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
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.AmountOfMoney.EN.IE.Rules ( rules ) where import Data.HashMap.Strict (HashMap) import Data.String import Data.Text (Text) import Prelude import Duckling.AmountOfMoney.Helpers import Duckling.AmountOfMoney.Types (Currency(..)) import Duckling.Numeral.Helpers (isPositive) import Duckling.Regex.Types import Duckling.Types import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Text import qualified Duckling.AmountOfMoney.Helpers as Helpers import qualified Duckling.Numeral.Types as TNumeral ruleAGrand :: Rule ruleAGrand = Rule { name = "a grand" , pattern = [ regex "a grand" ] , prod = \_ -> Just . Token AmountOfMoney . withValue 1000 $ currencyOnly Dollar } ruleGrand :: Rule ruleGrand = Rule { name = "<amount> grand" , pattern = [ Predicate isPositive , regex "grand" ] , prod = \case (Token Numeral TNumeral.NumeralData{TNumeral.value = v}:_) -> Just . Token AmountOfMoney . withValue (1000 * v) $ currencyOnly Dollar _ -> Nothing } ruleDollarCoin :: Rule ruleDollarCoin = Rule { name = "dollar coin" , pattern = [ regex "(nickel|dime|quarter)s?" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> do c <- HashMap.lookup (Text.toLower match) Helpers.dollarCoins Just . Token AmountOfMoney . withValue c $ currencyOnly Dollar _ -> Nothing } rules :: [Rule] rules = [ ruleAGrand , ruleGrand , ruleDollarCoin ]
facebookincubator/duckling
Duckling/AmountOfMoney/EN/IE/Rules.hs
bsd-3-clause
1,829
0
17
391
452
264
188
51
2
module Renkon.Command.List ( run ) where import ClassyPrelude import Control.Lens.Operators import Formatting import Renkon.Config import Renkon.Util import System.Directory (doesDirectoryExist) import System.FilePath (getSearchPath) import System.FilePath.Find as FilePath run :: Config -> Bool -> IO () run config detail = do let root' = config ^. path . renkonRoot bin' = config ^. path . renkonBin onDirAbsence root' $ do withColor Red $ do fprint ("renkon root does not exist." % ln) withColor White $ do fprint (" " % string % ln) root' guard False fprint ("Available generators:" % ln) path' <- getSearchPath gens' <- sequence $ findRenconGenerator config <$> path' let displayItem = bool displayItemSimple displayItemDetail detail traverse_ (displayList (displayItem config)) gens' displayList :: (FilePath -> IO ()) -> [FilePath] -> IO () displayList displayItem xs = traverse_ displayItem xs displayItemSimple :: Config -> FilePath -> IO () displayItemSimple config exe = do withColor Green $ do fprint (indent 2 % string % ln) . (takeGeneratorName config) $ exe displayItemDetail :: Config -> FilePath -> IO () displayItemDetail config exe = do withColor Green $ do fprint (indent 2 % string % ln) . (takeGeneratorName config) $ exe withColor Yellow $ do fprint (indent 2 % string % ln) exe withColor White $ do traverse_ (fprint (indent 4 % stext % ln)) . lines =<< execute' exe ["--help"] fprint ln isRenconBinDir :: Config -> FindClause Bool isRenconBinDir config = isPrefixOf pre' <$> filePath where pre' = config ^. path . renkonBin isRenconGenerator :: Config -> FindClause Bool isRenconGenerator config = isPrefixOf pre' <$> fileName where pre' = unpack $ config ^. path . renkonPrefix findRenconGenerator :: Config -> FilePath -> IO [FilePath] findRenconGenerator config dir = do exists <- doesDirectoryExist dir if exists then FilePath.find (filePath ==? dir) (isRenconGenerator config) dir else return [] onDirAbsence :: (MonadIO m) => FilePath -> m () -> m () onDirAbsence dir action = do exists <- liftIO $ doesDirectoryExist dir when (not exists) $ do action
kayhide/renkon
src/Renkon/Command/List.hs
bsd-3-clause
2,202
0
18
442
784
380
404
-1
-1
{-# LANGUAGE CPP, DefaultSignatures, EmptyDataDecls, FlexibleInstances, FunctionalDependencies, KindSignatures, ScopedTypeVariables, TypeOperators, UndecidableInstances, ViewPatterns, NamedFieldPuns, FlexibleContexts, PatternGuards, RecordWildCards, DataKinds, NoImplicitPrelude #-} {-# OPTIONS_GHC -fno-warn-orphans #-} #include "overlapping-compat.h" -- TODO: is it true or not that Generic instances might go into infinite -- loops when the type refers to itself in some field? If yes, we have to -- warn (and if not, we can mention that it's alright). Same for Template -- Haskell and mkParseJson, I guess. module Json.Internal.Generic () where import BasePrelude import Json.Internal.Instances import Json.Internal.Types import Json.Internal.Classes import Json.Internal.ValueParser import qualified Json.Internal.Encode.ByteString as E import Data.ByteString.Builder as B import Data.DList (DList) import qualified Data.Text as T import Data.Text (Text) import GHC.Generics import qualified Data.HashMap.Strict as H import qualified Data.Vector as V import qualified Data.Vector.Mutable as VM -------------------------------------------------------------------------------- -- Generic toJson and toEncoding instance OVERLAPPABLE_ (GToJson a) => GToJson (M1 i c a) where -- Meta-information, which is not handled elsewhere, is ignored: gToJson opts = gToJson opts . unM1 gToEncoding opts = gToEncoding opts . unM1 instance (ToJson a) => GToJson (K1 i a) where -- Constant values are encoded using their ToJson instance: gToJson _opts = toJson . unK1 gToEncoding _opts = toEncoding . unK1 instance GToJson U1 where -- Empty constructors are encoded to an empty array: gToJson _opts _ = Array mempty gToEncoding _opts _ = emptyArrayE instance (ConsToJson a) => GToJson (C1 c a) where -- Constructors need to be encoded differently depending on whether they're -- a record or not. This distinction is made by 'consToJson': gToJson opts = consToJson opts . unM1 gToEncoding opts = Encoding . consToEncoding opts . unM1 instance ( WriteProduct a, WriteProduct b , EncodeProduct a, EncodeProduct b , ProductSize a, ProductSize b ) => GToJson (a :*: b) where -- Products are encoded to an array. Here we allocate a mutable vector of -- the same size as the product and write the product's elements to it -- using 'writeProduct': gToJson opts p = Array $ V.create $ do mv <- VM.unsafeNew lenProduct writeProduct opts mv 0 lenProduct p return mv where lenProduct = (unTagged2 :: Tagged2 (a :*: b) Int -> Int) productSize gToEncoding opts p = Encoding $ B.char7 '[' <> encodeProduct opts p <> B.char7 ']' instance ( AllNullary (a :+: b) allNullary , SumToJson (a :+: b) allNullary ) => GToJson (a :+: b) where -- If all constructors of a sum datatype are nullary and the -- 'allNullaryToStringTag' option is set they are encoded to -- strings. This distinction is made by 'sumToJson': gToJson opts = (unTagged :: Tagged allNullary Json -> Json) . sumToJson opts gToEncoding opts = Encoding . (unTagged :: Tagged allNullary B.Builder -> B.Builder) . sumToEncoding opts -------------------------------------------------------------------------------- class SumToJson f allNullary where sumToJson :: Options -> f a -> Tagged allNullary Json sumToEncoding :: Options -> f a -> Tagged allNullary B.Builder -- TODO: rename TwoElemArrayObj, etc to not mention Obj instance ( GetConName f , TaggedObjectPairs f , ObjectWithSingleFieldObj f , TwoElemArrayObj f ) => SumToJson f True where sumToJson opts | allNullaryToStringTag opts = Tagged . String . T.pack . constructorTagModifier opts . getConName | otherwise = Tagged . nonAllNullarySumToJson opts sumToEncoding opts | allNullaryToStringTag opts = Tagged . builder . constructorTagModifier opts . getConName | otherwise = Tagged . nonAllNullarySumToEncoding opts instance ( TwoElemArrayObj f , TaggedObjectPairs f , ObjectWithSingleFieldObj f ) => SumToJson f False where sumToJson opts = Tagged . nonAllNullarySumToJson opts sumToEncoding opts = Tagged . nonAllNullarySumToEncoding opts nonAllNullarySumToJson :: ( TwoElemArrayObj f , TaggedObjectPairs f , ObjectWithSingleFieldObj f ) => Options -> f a -> Json nonAllNullarySumToJson opts = case sumEncoding opts of TaggedObject{..} -> object . taggedObjectPairs opts tagFieldName contentsFieldName ObjectWithSingleField -> Object . objectWithSingleFieldObj opts TwoElemArray -> Array . twoElemArrayObj opts nonAllNullarySumToEncoding :: ( TwoElemArrayObj f , TaggedObjectPairs f , ObjectWithSingleFieldObj f ) => Options -> f a -> B.Builder nonAllNullarySumToEncoding opts = case sumEncoding opts of TaggedObject{..} -> taggedObjectEnc opts tagFieldName contentsFieldName ObjectWithSingleField -> objectWithSingleFieldEnc opts TwoElemArray -> twoElemArrayEnc opts -------------------------------------------------------------------------------- class TaggedObjectPairs f where taggedObjectPairs :: Options -> String -> String -> f a -> [Pair] taggedObjectEnc :: Options -> String -> String -> f a -> B.Builder instance ( TaggedObjectPairs a , TaggedObjectPairs b ) => TaggedObjectPairs (a :+: b) where taggedObjectPairs opts tagFieldName contentsFieldName (L1 x) = taggedObjectPairs opts tagFieldName contentsFieldName x taggedObjectPairs opts tagFieldName contentsFieldName (R1 x) = taggedObjectPairs opts tagFieldName contentsFieldName x taggedObjectEnc opts tagFieldName contentsFieldName (L1 x) = taggedObjectEnc opts tagFieldName contentsFieldName x taggedObjectEnc opts tagFieldName contentsFieldName (R1 x) = taggedObjectEnc opts tagFieldName contentsFieldName x instance ( IsRecord a isRecord , TaggedObjectPairs' a isRecord , Constructor c ) => TaggedObjectPairs (C1 c a) where taggedObjectPairs opts tagFieldName contentsFieldName = (T.pack tagFieldName .= constructorTagModifier opts (conName (undefined :: t c a p)) :) . (unTagged :: Tagged isRecord [Pair] -> [Pair]) . taggedObjectPairs' opts contentsFieldName . unM1 taggedObjectEnc opts tagFieldName contentsFieldName v = B.char7 '{' <> (builder tagFieldName <> B.char7 ':' <> builder (constructorTagModifier opts (conName (undefined :: t c a p)))) <> B.char7 ',' <> ((unTagged :: Tagged isRecord B.Builder -> B.Builder) . taggedObjectEnc' opts contentsFieldName . unM1 $ v) <> B.char7 '}' class TaggedObjectPairs' f isRecord where taggedObjectPairs' :: Options -> String -> f a -> Tagged isRecord [Pair] taggedObjectEnc' :: Options -> String -> f a -> Tagged isRecord B.Builder instance (RecordToPairs f) => TaggedObjectPairs' f True where taggedObjectPairs' opts _ = Tagged . toList . recordToPairs opts taggedObjectEnc' opts _ = Tagged . fst . recordToEncoding opts instance (GToJson f) => TaggedObjectPairs' f False where taggedObjectPairs' opts contentsFieldName = Tagged . (:[]) . (T.pack contentsFieldName .=) . gToJson opts taggedObjectEnc' opts contentsFieldName = Tagged . (\z -> builder contentsFieldName <> B.char7 ':' <> z) . gbuilder opts -------------------------------------------------------------------------------- -- | Get the name of the constructor of a sum datatype. class GetConName f where getConName :: f a -> String instance (GetConName a, GetConName b) => GetConName (a :+: b) where getConName (L1 x) = getConName x getConName (R1 x) = getConName x instance (Constructor c) => GetConName (C1 c a) where getConName = conName -------------------------------------------------------------------------------- class TwoElemArrayObj f where twoElemArrayObj :: Options -> f a -> V.Vector Json twoElemArrayEnc :: Options -> f a -> B.Builder instance (TwoElemArrayObj a, TwoElemArrayObj b) => TwoElemArrayObj (a :+: b) where twoElemArrayObj opts (L1 x) = twoElemArrayObj opts x twoElemArrayObj opts (R1 x) = twoElemArrayObj opts x twoElemArrayEnc opts (L1 x) = twoElemArrayEnc opts x twoElemArrayEnc opts (R1 x) = twoElemArrayEnc opts x instance ( GToJson a, ConsToJson a , Constructor c ) => TwoElemArrayObj (C1 c a) where twoElemArrayObj opts x = V.create $ do mv <- VM.unsafeNew 2 VM.unsafeWrite mv 0 $ String $ T.pack $ constructorTagModifier opts $ conName (undefined :: t c a p) VM.unsafeWrite mv 1 $ gToJson opts x return mv twoElemArrayEnc opts x = E.brackets $ builder (constructorTagModifier opts (conName (undefined :: t c a p))) <> B.char7 ',' <> gbuilder opts x -------------------------------------------------------------------------------- class ConsToJson f where consToJson :: Options -> f a -> Json consToEncoding :: Options -> f a -> B.Builder class ConsToJson' f isRecord where consToJson' :: Options -> Bool -- ^ Are we a record with one field? -> f a -> Tagged isRecord Json consToEncoding' :: Options -> Bool -- ^ Are we a record with one field? -> f a -> Tagged isRecord B.Builder instance ( IsRecord f isRecord , ConsToJson' f isRecord ) => ConsToJson f where consToJson opts = (unTagged :: Tagged isRecord Json -> Json) . consToJson' opts (isUnary (undefined :: f a)) consToEncoding opts = (unTagged :: Tagged isRecord B.Builder -> B.Builder) . consToEncoding' opts (isUnary (undefined :: f a)) instance (RecordToPairs f) => ConsToJson' f True where consToJson' opts isUn f = do let vals = toList $ recordToPairs opts f -- Note that checking that vals has only 1 element is needed because it's -- possible that it would have 0 elements – for instance, when -- omitNothingFields is enabled and it's a Nothing field. Checking for -- 'isUn' is not enough. case (unwrapUnaryRecords opts, isUn, vals) of (True, True, [(_,val)]) -> Tagged val _ -> Tagged $ object vals consToEncoding' opts isUn x = do let (enc, mbVal) = recordToEncoding opts x case (unwrapUnaryRecords opts, isUn, mbVal) of (True, True, Just val) -> Tagged val _ -> Tagged $ B.char7 '{' <> enc <> B.char7 '}' instance GToJson f => ConsToJson' f False where consToJson' opts _ = Tagged . gToJson opts consToEncoding' opts _ = Tagged . gbuilder opts -------------------------------------------------------------------------------- class RecordToPairs f where recordToPairs :: Options -> f a -> DList Pair -- 1st element: whole thing -- 2nd element: in case the record has only 1 field, just the value -- of the field (without the key); 'Nothing' otherwise recordToEncoding :: Options -> f a -> (B.Builder, Maybe B.Builder) instance (RecordToPairs a, RecordToPairs b) => RecordToPairs (a :*: b) where recordToPairs opts (a :*: b) = recordToPairs opts a <> recordToPairs opts b recordToEncoding opts (a :*: b) = (fst (recordToEncoding opts a) <> B.char7 ',' <> fst (recordToEncoding opts b), Nothing) instance (Selector s, GToJson a) => RecordToPairs (S1 s a) where recordToPairs = fieldToPair recordToEncoding = fieldToEncoding instance OVERLAPPING_ (Selector s, ToJson a) => RecordToPairs (S1 s (K1 i (Maybe a))) where recordToPairs opts (M1 k1) | omitNothingFields opts , K1 Nothing <- k1 = empty recordToPairs opts m1 = fieldToPair opts m1 recordToEncoding opts (M1 k1) | omitNothingFields opts , K1 Nothing <- k1 = (mempty, Nothing) recordToEncoding opts m1 = fieldToEncoding opts m1 fieldToPair :: (Selector s, GToJson a) => Options -> S1 s a p -> DList Pair fieldToPair opts m1 = pure (T.pack $ fieldLabelModifier opts $ selName m1, gToJson opts (unM1 m1)) fieldToEncoding :: (Selector s, GToJson a) => Options -> S1 s a p -> (B.Builder, Maybe B.Builder) fieldToEncoding opts m1 = do let keyBuilder = builder (fieldLabelModifier opts $ selName m1) valueBuilder = gbuilder opts (unM1 m1) (keyBuilder <> B.char7 ':' <> valueBuilder, Just valueBuilder) -------------------------------------------------------------------------------- class WriteProduct f where writeProduct :: Options -> VM.MVector s Json -> Int -- ^ index -> Int -- ^ length -> f a -> ST s () instance ( WriteProduct a , WriteProduct b ) => WriteProduct (a :*: b) where writeProduct opts mv ix len (a :*: b) = do writeProduct opts mv ix lenL a writeProduct opts mv ixR lenR b where lenL = len `unsafeShiftR` 1 lenR = len - lenL ixR = ix + lenL instance OVERLAPPABLE_ (GToJson a) => WriteProduct a where writeProduct opts mv ix _ = VM.unsafeWrite mv ix . gToJson opts -------------------------------------------------------------------------------- class EncodeProduct f where encodeProduct :: Options -> f a -> B.Builder instance ( EncodeProduct a , EncodeProduct b ) => EncodeProduct (a :*: b) where encodeProduct opts (a :*: b) = encodeProduct opts a <> B.char7 ',' <> encodeProduct opts b instance OVERLAPPABLE_ (GToJson a) => EncodeProduct a where encodeProduct opts = gbuilder opts -------------------------------------------------------------------------------- class ObjectWithSingleFieldObj f where objectWithSingleFieldObj :: Options -> f a -> Object objectWithSingleFieldEnc :: Options -> f a -> B.Builder instance ( ObjectWithSingleFieldObj a , ObjectWithSingleFieldObj b ) => ObjectWithSingleFieldObj (a :+: b) where objectWithSingleFieldObj opts (L1 x) = objectWithSingleFieldObj opts x objectWithSingleFieldObj opts (R1 x) = objectWithSingleFieldObj opts x objectWithSingleFieldEnc opts (L1 x) = objectWithSingleFieldEnc opts x objectWithSingleFieldEnc opts (R1 x) = objectWithSingleFieldEnc opts x instance ( GToJson a, ConsToJson a , Constructor c ) => ObjectWithSingleFieldObj (C1 c a) where objectWithSingleFieldObj opts = H.singleton typ . gToJson opts where typ = T.pack $ constructorTagModifier opts $ conName (undefined :: t c a p) objectWithSingleFieldEnc opts v = B.char7 '{' <> builder (constructorTagModifier opts (conName (undefined :: t c a p))) <> B.char7 ':' <> gbuilder opts v <> B.char7 '}' gbuilder :: GToJson f => Options -> f a -> Builder gbuilder opts = fromEncoding . gToEncoding opts -------------------------------------------------------------------------------- -- Generic parseJson instance OVERLAPPABLE_ (GFromJson a) => GFromJson (M1 i c a) where -- Meta-information, which is not handled elsewhere, is just added to the -- parsed value: gParseJson opts = M1 <$> gParseJson opts instance (FromJson a) => GFromJson (K1 i a) where -- Constant values are decoded using their FromJson instance: gParseJson _opts = K1 <$> parseJson instance GFromJson U1 where -- Empty constructors are expected to be encoded as an empty array: gParseJson _opts = withArray "unit constructor (U1)" $ do checkLength 0 return U1 instance (ConsFromJson a) => GFromJson (C1 c a) where -- Constructors need to be decoded differently depending on whether they're -- a record or not. This distinction is made by consParseJson: gParseJson opts = M1 <$> consParseJson opts instance ( FromProduct a, FromProduct b , ProductSize a, ProductSize b ) => GFromJson (a :*: b) where -- Products are expected to be encoded to an array. Here we check whether we -- got an array of the same size as the product, then parse each of the -- product's elements using parseProduct: gParseJson opts = withArray "product (:*:)" $ do let lenProduct = (unTagged2 :: Tagged2 (a :*: b) Int -> Int) productSize checkLength lenProduct parseProduct opts 0 lenProduct instance (AllNullary (a :+: b) allNullary, ParseSum (a :+: b) allNullary) => GFromJson (a :+: b) where -- If all constructors of a sum datatype are nullary and the -- 'allNullaryToStringTag' option is set they are expected to be -- encoded as strings. This distinction is made by 'parseSum': gParseJson opts = unT (parseSum opts) where unT :: Tagged allNullary (Parser Json ((a :+: b) d)) -> Parser Json ((a :+: b) d) unT = unTagged -------------------------------------------------------------------------------- class ParseSum f allNullary where parseSum :: Options -> Tagged allNullary (Parser Json (f a)) instance ( SumFromString (a :+: b) , FromPair (a :+: b) , FromTaggedObject (a :+: b) ) => ParseSum (a :+: b) True where parseSum opts | allNullaryToStringTag opts = Tagged (parseAllNullarySum opts) | otherwise = Tagged (parseNonAllNullarySum opts) instance ( FromPair (a :+: b) , FromTaggedObject (a :+: b) ) => ParseSum (a :+: b) False where parseSum opts = Tagged (parseNonAllNullarySum opts) -------------------------------------------------------------------------------- parseAllNullarySum :: SumFromString f => Options -> Parser Json (f a) parseAllNullarySum opts = do key <- getString "" maybe (notFound $ T.unpack key) return $ parseSumFromString opts key class SumFromString f where parseSumFromString :: Options -> Text -> Maybe (f a) instance (SumFromString a, SumFromString b) => SumFromString (a :+: b) where parseSumFromString opts key = (L1 <$> parseSumFromString opts key) <|> (R1 <$> parseSumFromString opts key) instance (Constructor c) => SumFromString (C1 c U1) where parseSumFromString opts key | key == name = Just $ M1 U1 | otherwise = Nothing where name = T.pack $ constructorTagModifier opts $ conName (undefined :: t c U1 p) -------------------------------------------------------------------------------- parseNonAllNullarySum :: (FromPair (a :+: b), FromTaggedObject (a :+: b)) => Options -> Parser Json ((a :+: b) c) parseNonAllNullarySum opts = case sumEncoding opts of TaggedObject{..} -> withObject "" $ do tag <- field (T.pack tagFieldName) fromMaybe (notFound $ T.unpack tag) $ parseFromTaggedObject opts contentsFieldName tag ObjectWithSingleField -> -- TODO: rename “withSingleton” to “inSingleton” or something? since it's -- different from withArray or withObject withSingleton "" $ \tagKey -> do fromMaybe (notFound $ T.unpack tagKey) $ parsePair opts tagKey TwoElemArray -> withArray "" $ do checkLength 2 -- TODO: rename “with” to “inside”? or something that doesn't clash -- with lens tag <- with (unsafeElementAt 0) $ getString "" with (unsafeElementAt 1) $ fromMaybe (notFound $ T.unpack tag) $ parsePair opts tag -------------------------------------------------------------------------------- class FromTaggedObject f where parseFromTaggedObject :: Options -> String -> Text -> Maybe (Parser Object (f a)) instance (FromTaggedObject a, FromTaggedObject b) => FromTaggedObject (a :+: b) where parseFromTaggedObject opts contentsFieldName tag = (fmap L1 <$> parseFromTaggedObject opts contentsFieldName tag) <|> (fmap R1 <$> parseFromTaggedObject opts contentsFieldName tag) instance ( FromTaggedObject' f , Constructor c ) => FromTaggedObject (C1 c f) where parseFromTaggedObject opts contentsFieldName tag | tag == name = Just $ M1 <$> parseFromTaggedObject' opts contentsFieldName | otherwise = Nothing where name = T.pack $ constructorTagModifier opts $ conName (undefined :: t c f p) -------------------------------------------------------------------------------- class FromTaggedObject' f where parseFromTaggedObject' :: Options -> String -> Parser Object (f a) class FromTaggedObject'' f isRecord where parseFromTaggedObject'' :: Options -> String -> Tagged isRecord (Parser Object (f a)) instance ( IsRecord f isRecord , FromTaggedObject'' f isRecord ) => FromTaggedObject' f where parseFromTaggedObject' opts contentsFieldName = unT (parseFromTaggedObject'' opts contentsFieldName) where unT :: Tagged isRecord (Parser Object (f a)) -> Parser Object (f a) unT = unTagged instance (FromRecord f) => FromTaggedObject'' f True where parseFromTaggedObject'' opts _ = Tagged (parseRecord opts Nothing) instance (GFromJson f) => FromTaggedObject'' f False where parseFromTaggedObject'' opts contentsFieldName = Tagged (with (field (T.pack contentsFieldName)) (gParseJson opts)) -------------------------------------------------------------------------------- class ConsFromJson f where consParseJson :: Options -> Parser Json (f a) class ConsFromJson' f isRecord where consParseJson' :: Options -> Maybe Text -- ^ A dummy label ('Nothing' to use proper label) -> Tagged isRecord (Parser Json (f a)) instance (IsRecord f isRecord, ConsFromJson' f isRecord) => ConsFromJson f where consParseJson opts = do v <- getInput let useDummy = unwrapUnaryRecords opts && isUnary (undefined :: f a) dummyObject = object [(T.pack "dummy", v)] dummyLabel = Just (T.pack "dummy") if useDummy then unT $ (`apply` dummyObject) <$> consParseJson' opts dummyLabel else unT $ (`apply` v) <$> consParseJson' opts Nothing where unT :: Tagged isRecord (Parser Json (f a)) -> Parser Json (f a) unT = unTagged instance (FromRecord f) => ConsFromJson' f True where consParseJson' opts mlab = Tagged (withObject "record (:*:)" $ parseRecord opts mlab) instance (GFromJson f) => ConsFromJson' f False where consParseJson' opts _ = Tagged (gParseJson opts) -------------------------------------------------------------------------------- class FromRecord f where parseRecord :: Options -> Maybe Text -- ^ A dummy label ('Nothing' to use proper label) -> Parser Object (f a) instance (FromRecord a, FromRecord b) => FromRecord (a :*: b) where parseRecord opts _ = (:*:) <$> parseRecord opts Nothing <*> parseRecord opts Nothing instance (Selector s, GFromJson a) => FromRecord (S1 s a) where parseRecord opts mbLab = with (field lab) (gParseJson opts) where selLabel = fieldLabelModifier opts $ selName (undefined :: t s a p) lab = fromMaybe (T.pack selLabel) mbLab instance OVERLAPPING_ (Selector s, FromJson a) => FromRecord (S1 s (K1 i (Maybe a))) where parseRecord opts mbLab = (M1 . K1) <$> optionalField lab where selLabel = fieldLabelModifier opts $ selName (undefined :: t s (K1 i (Maybe a)) p) lab = fromMaybe (T.pack selLabel) mbLab -------------------------------------------------------------------------------- class ProductSize f where productSize :: Tagged2 f Int instance (ProductSize a, ProductSize b) => ProductSize (a :*: b) where productSize = Tagged2 $ unTagged2 (productSize :: Tagged2 a Int) + unTagged2 (productSize :: Tagged2 b Int) instance ProductSize (S1 s a) where productSize = Tagged2 1 -------------------------------------------------------------------------------- class FromProduct f where parseProduct :: Options -> Int -> Int -> Parser Array (f a) instance (FromProduct a, FromProduct b) => FromProduct (a :*: b) where parseProduct opts ix len = (:*:) <$> parseProduct opts ix lenL <*> parseProduct opts ixR lenR where lenL = len `unsafeShiftR` 1 ixR = ix + lenL lenR = len - lenL instance (GFromJson a) => FromProduct (S1 s a) where parseProduct opts ix _ = with (unsafeElementAt ix) $ gParseJson opts -------------------------------------------------------------------------------- class FromPair f where parsePair :: Options -> Text -> Maybe (Parser Json (f a)) instance (FromPair a, FromPair b) => FromPair (a :+: b) where parsePair opts tag = (fmap L1 <$> parsePair opts tag) <|> (fmap R1 <$> parsePair opts tag) instance (Constructor c, GFromJson a, ConsFromJson a) => FromPair (C1 c a) where parsePair opts tag | tag == tag' = Just (gParseJson opts) | otherwise = Nothing where tag' = T.pack $ constructorTagModifier opts $ conName (undefined :: t c a p) -------------------------------------------------------------------------------- class IsRecord (f :: * -> *) isRecord | f -> isRecord where isUnary :: f a -> Bool isUnary = const True instance (IsRecord f isRecord) => IsRecord (f :*: g) isRecord where isUnary = const False #if MIN_VERSION_base(4,9,0) instance OVERLAPPING_ IsRecord (M1 S ('MetaSel 'Nothing u ss ds) f) False #else instance OVERLAPPING_ IsRecord (M1 S NoSelector f) False #endif instance (IsRecord f isRecord) => IsRecord (M1 S c f) isRecord instance IsRecord (K1 i c) True instance IsRecord U1 False where isUnary = const False -------------------------------------------------------------------------------- class AllNullary (f :: * -> *) allNullary | f -> allNullary instance ( AllNullary a allNullaryL , AllNullary b allNullaryR , And allNullaryL allNullaryR allNullary ) => AllNullary (a :+: b) allNullary instance AllNullary a allNullary => AllNullary (M1 i c a) allNullary instance AllNullary (a :*: b) False instance AllNullary (K1 i c) False instance AllNullary U1 True -------------------------------------------------------------------------------- data True data False class And bool1 bool2 bool3 | bool1 bool2 -> bool3 instance And True True True instance And False False False instance And False True False instance And True False False -------------------------------------------------------------------------------- newtype Tagged s b = Tagged {unTagged :: b} instance Functor (Tagged s) where fmap f (Tagged x) = Tagged (f x) {-# INLINE fmap #-} newtype Tagged2 (s :: * -> *) b = Tagged2 {unTagged2 :: b} -------------------------------------------------------------------------------- notFound :: String -> Parser x a notFound key = fail $ "The key \"" ++ key ++ "\" was not found" {-# INLINE notFound #-} builder :: ToJson a => a -> Builder builder = fromEncoding . toEncoding
aelve/json-x
lib/Json/Internal/Generic.hs
bsd-3-clause
27,487
0
18
6,522
7,479
3,765
3,714
-1
-1
{-# LANGUAGE TemplateHaskell #-} module Quid2Pkg (Quid2Pkg(..)) where -- import Types import Test.Data import qualified Types as T import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L ( ByteString ,unpack,pack) import Quid2.HRT.Class.Serialize as Class.Serialize -- import Class.Serialize import Quid2.HRT.Data.Serialize import Quid2.HRT.Prelude data Quid2Pkg a = Quid2Pkg a deriving (Eq,Show) instance Serialize a => T.Serialize (Quid2Pkg a) where serialize (Quid2Pkg a) = L.pack . B.unpack . encode $ a deserialize = either (Left . error) (Right . Quid2Pkg) . decode . B.pack . L.unpack t = T.ser $ Quid2Pkg tree1 deriveSerialize ''Bool deriveSerialize ''Tree deriveSerialize ''Car deriveSerialize ''Acceleration deriveSerialize ''Consumption deriveSerialize ''Model deriveSerialize ''OptionalExtra deriveSerialize ''Engine
tittoassini/flat
benchmarks/PkgHRT.hs
bsd-3-clause
871
0
11
123
271
147
124
22
1
module Problem61 where -- -- Problem 61: Cyclical figurate numbers -- -- Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers -- are all figurate (polygonal) numbers and are generated by the following formulae: -- -- Triangle P3,n=n(n+1)/2 1, 3, 6, 10, 15, ... -- Square P4,n=n^2 1, 4, 9, 16, 25, ... -- Pentagonal P5,n=n(3n−1)/2 1, 5, 12, 22, 35, ... -- Hexagonal P6,n=n(2n−1) 1, 6, 15, 28, 45, ... -- Heptagonal P7,n=n(5n−3)/2 1, 7, 18, 34, 55, ... -- Octagonal P8,n=n(3n−2) 1, 8, 21, 40, 65, ... -- -- The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three -- interesting properties. -- -- 1. The set is cyclic, in that the last two digits of each number is the first -- two digits of the next number (including the last number with the first). -- 2. Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and -- pentagonal (P5,44=2882), is represented by a different number in the set. -- 3. This is the only set of 4-digit numbers with this property. -- -- Find the sum of the only ordered set of six cyclic 4-digit numbers for which -- each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, -- and octagonal, is represented by a different number in the set. problem61 :: Int problem61 = sum $ head $ cycleOptions initialCandidates [] pFn :: [Int -> Int] pFn = [ \n -> n*(n+1) `div` 2 , \n -> n*n , \n -> n*(3*n-1) `div` 2 , \n -> n*(2*n-1) , \n -> n*(5*n-3) `div` 2 , \n -> n*(3*n-2) ] initialCandidates = fourDigits . flip map [1..] <$> pFn splits xs = flip splitAt xs <$> [0..length xs-1] bottom x = x `mod` 100 top x = x `div` 100 cycleOptions :: [[Int]] -> [Int] -> [[Int]] cycleOptions [] path -- Link first and last of path | bottom (head path) == top (last path) = [reverse path] | otherwise = [] -- Start considering all numbers, in all columns of candidates cycleOptions ps [] = concatMap go $ splits ps where go (h, p:t) = concatMap (cycleOptions (h ++ t) . (:[])) p -- Given the head of the path (x), match numbers from all columns, -- whose top matches the bottom of x. cycleOptions ps path@(x:_) = concatMap go $ splits ps where hasPrefix y = top y == bottom x go (h, p:t) = concatMap (cycleOptions (h ++ t) . (:path)) $ filter hasPrefix p -- Assumes xs is a sorted (possibly infinite) list. fourDigits :: [Int] -> [Int] fourDigits = takeWhile (< 10^4) . dropWhile (< 10^3)
c0deaddict/project-euler
src/Part2/Problem61.hs
bsd-3-clause
2,434
0
13
498
597
335
262
26
1
module CardDeck ( Deck, createOrderedDeck, getCard, getCards ) where import Card import qualified Data.Vector as V type CardVector = V.Vector Card data Deck = Deck CardVector deriving Show getCard :: Deck -> Int -> Card getCard (Deck xs) n = xs V.! n getCards :: Deck -> [Card] getCards (Deck v) = V.toList v createOrderedDeck :: Deck createOrderedDeck = Deck $ V.fromList createListOfCards createListOfCards :: [Card] createListOfCards = [mkCard r s | r <- [Two .. Ace], s <- [Heart .. Spade]]
fffej/HS-Poker
CardDeck.hs
bsd-3-clause
525
0
8
112
186
105
81
17
1
module HudsonTest where import Text.ParserCombinators.Parsec import HudsonParser import Test.HUnit import HudsonPreproc (parseResult) param a b c = Just Param {ref = a, paramName = b, paramType = c} func a b c = Just FuncDecl {funcName = a, funcParams = b, funcCode = c} testParamSimple = "Simple param" ~: param False "param" Nothing ~=? parseResult parseParam "param" testParamRef = "Param with a ref" ~: param True "param_3A" Nothing ~=? parseResult parseParam "ref param_3A" testParamType = "Param with a ref and type" ~: param True "param_3A" (Just "Type") ~=? parseResult parseParam "ref param_3A : Type" testParamNewline = "Param with a bad newline" ~: Nothing ~=? parseResult parseParam "\nref" paramTests = TestLabel "param Tests" $ TestList [testParamSimple, testParamRef, testParamType, testParamNewline] testFuncSimple = "Simple Func" ~: func "simple" [] [BlockStmt $ Return $ Just $ LiteralInt 2] ~=? parseResult parseFuncDecl "function simple () is\n return 2" funcTests = TestLabel "func Tests" $ TestList [testFuncSimple] allTests = TestList [paramTests, funcTests] main = runTestTT allTests
jschaf/hudson-dev
src/Language/Hudson/HudsonTest.hs
bsd-3-clause
1,314
0
11
366
307
163
144
27
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Numeral.ES.Rules ( rules ) where import qualified Data.HashMap.Strict as HashMap import Data.Maybe import qualified Data.Text as Text import Prelude import Data.String import Duckling.Dimensions.Types import Duckling.Numeral.Helpers import Duckling.Numeral.Types (NumeralData (..)) import qualified Duckling.Numeral.Types as TNumeral import Duckling.Regex.Types import Duckling.Types ruleNumeralsPrefixWithNegativeOrMinus :: Rule ruleNumeralsPrefixWithNegativeOrMinus = Rule { name = "numbers prefix with -, negative or minus" , pattern = [ regex "-|menos" , dimension Numeral ] , prod = \tokens -> case tokens of (_:Token Numeral (NumeralData {TNumeral.value = v}):_) -> double $ v * (- 1) _ -> Nothing } ruleIntegerNumeric :: Rule ruleIntegerNumeric = Rule { name = "integer (numeric)" , pattern = [ regex "(\\d{1,18})" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> do v <- parseInt match integer $ toInteger v _ -> Nothing } ruleDecimalWithThousandsSeparator :: Rule ruleDecimalWithThousandsSeparator = Rule { name = "decimal with thousands separator" , pattern = [ regex "(\\d+(\\.\\d\\d\\d)+,\\d+)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> let dot = Text.singleton '.' comma = Text.singleton ',' fmt = Text.replace comma dot $ Text.replace dot Text.empty match in parseDouble fmt >>= double _ -> Nothing } ruleDecimalNumeral :: Rule ruleDecimalNumeral = Rule { name = "decimal number" , pattern = [ regex "(\\d*,\\d+)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> parseDecimal False match _ -> Nothing } byTensMap :: HashMap.HashMap Text.Text Integer byTensMap = HashMap.fromList [ ( "veinte" , 20 ) , ( "treinta" , 30 ) , ( "cuarenta" , 40 ) , ( "cincuenta" , 50 ) , ( "sesenta" , 60 ) , ( "setenta" , 70 ) , ( "ochenta" , 80 ) , ( "noventa" , 90 ) ] ruleNumeral2 :: Rule ruleNumeral2 = Rule { name = "number (20..90)" , pattern = [ regex "(veinte|treinta|cuarenta|cincuenta|sesenta|setenta|ochenta|noventa)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) byTensMap >>= integer _ -> Nothing } zeroToFifteenMap :: HashMap.HashMap Text.Text Integer zeroToFifteenMap = HashMap.fromList [ ( "zero" , 0 ) , ( "cero" , 0 ) , ( "un" , 1 ) , ( "una" , 1 ) , ( "uno" , 1 ) , ( "dos" , 2 ) , ( "tr\x00e9s" , 3 ) , ( "tres" , 3 ) , ( "cuatro" , 4 ) , ( "cinco" , 5 ) , ( "seis" , 6 ) , ( "s\x00e9is" , 6 ) , ( "siete" , 7 ) , ( "ocho" , 8 ) , ( "nueve" , 9 ) , ( "diez" , 10 ) , ( "dies" , 10 ) , ( "once" , 11 ) , ( "doce" , 12 ) , ( "trece" , 13 ) , ( "catorce" , 14 ) , ( "quince" , 15 ) ] ruleNumeral :: Rule ruleNumeral = Rule { name = "number (0..15)" , pattern = [ regex "((c|z)ero|un(o|a)?|dos|tr(\x00e9|e)s|cuatro|cinco|s(e|\x00e9)is|siete|ocho|nueve|die(z|s)|once|doce|trece|catorce|quince)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) zeroToFifteenMap >>= integer _ -> Nothing } sixteenToTwentyNineMap :: HashMap.HashMap Text.Text Integer sixteenToTwentyNineMap = HashMap.fromList [ ( "dieciseis" , 16 ) , ( "diesis\x00e9is" , 16 ) , ( "diesiseis" , 16 ) , ( "diecis\x00e9is" , 16 ) , ( "diecisiete" , 17 ) , ( "dieciocho" , 18 ) , ( "diecinueve" , 19 ) , ( "veintiuno" , 21 ) , ( "veintiuna" , 21 ) , ( "veintidos" , 22 ) , ( "veintitr\x00e9s" , 23 ) , ( "veintitres" , 23 ) , ( "veinticuatro" , 24 ) , ( "veinticinco" , 25 ) , ( "veintis\x00e9is" , 26 ) , ( "veintiseis" , 26 ) , ( "veintisiete" , 27 ) , ( "veintiocho" , 28 ) , ( "veintinueve" , 29 ) ] ruleNumeral5 :: Rule ruleNumeral5 = Rule { name = "number (16..19 21..29)" , pattern = [ regex "(die(c|s)is(\x00e9|e)is|diecisiete|dieciocho|diecinueve|veintiun(o|a)|veintidos|veintitr(\x00e9|e)s|veinticuatro|veinticinco|veintis(\x00e9|e)is|veintisiete|veintiocho|veintinueve)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) sixteenToTwentyNineMap >>= integer _ -> Nothing } ruleNumeral3 :: Rule ruleNumeral3 = Rule { name = "number (16..19)" , pattern = [ numberWith TNumeral.value (== 10) , regex "y" , numberBetween 6 10 ] , prod = \tokens -> case tokens of (_:_:Token Numeral (NumeralData {TNumeral.value = v}):_) -> double $ 10 + v _ -> Nothing } ruleNumeralsSuffixesKMG :: Rule ruleNumeralsSuffixesKMG = Rule { name = "numbers suffixes (K, M, G)" , pattern = [ dimension Numeral , regex "([kmg])(?=[\\W\\$\x20ac]|$)" ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v}): Token RegexMatch (GroupMatch (match:_)): _) -> case Text.toLower match of "k" -> double $ v * 1e3 "m" -> double $ v * 1e6 "g" -> double $ v * 1e9 _ -> Nothing _ -> Nothing } oneHundredToThousandMap :: HashMap.HashMap Text.Text Integer oneHundredToThousandMap = HashMap.fromList [ ( "cien" , 100 ) , ( "cientos" , 100 ) , ( "ciento" , 100 ) , ( "doscientos" , 200 ) , ( "trescientos" , 300 ) , ( "cuatrocientos" , 400 ) , ( "quinientos" , 500 ) , ( "seiscientos" , 600 ) , ( "setecientos" , 700 ) , ( "ochocientos" , 800 ) , ( "novecientos" , 900 ) , ( "mil" , 1000 ) ] ruleNumeral6 :: Rule ruleNumeral6 = Rule { name = "number 100..1000 " , pattern = [ regex "(cien(to)?s?|doscientos|trescientos|cuatrocientos|quinientos|seiscientos|setecientos|ochocientos|novecientos|mil)" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> HashMap.lookup (Text.toLower match) oneHundredToThousandMap >>= integer _ -> Nothing } ruleNumeral4 :: Rule ruleNumeral4 = Rule { name = "number (21..29 31..39 41..49 51..59 61..69 71..79 81..89 91..99)" , pattern = [ oneOf [70, 20, 60, 50, 40, 90, 30, 80] , regex "y" , numberBetween 1 10 ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v1}): _: Token Numeral (NumeralData {TNumeral.value = v2}): _) -> double $ v1 + v2 _ -> Nothing } ruleNumerals :: Rule ruleNumerals = Rule { name = "numbers 200..999" , pattern = [ numberBetween 2 10 , numberWith TNumeral.value (== 100) , numberBetween 0 100 ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v1}): _: Token Numeral (NumeralData {TNumeral.value = v2}): _) -> double $ 100 * v1 + v2 _ -> Nothing } ruleNumeralDotNumeral :: Rule ruleNumeralDotNumeral = Rule { name = "number dot number" , pattern = [ dimension Numeral , regex "punto" , numberWith TNumeral.grain isNothing ] , prod = \tokens -> case tokens of (Token Numeral (NumeralData {TNumeral.value = v1}): _: Token Numeral (NumeralData {TNumeral.value = v2}): _) -> double $ v1 + decimalsToDouble v2 _ -> Nothing } ruleIntegerWithThousandsSeparator :: Rule ruleIntegerWithThousandsSeparator = Rule { name = "integer with thousands separator ." , pattern = [ regex "(\\d{1,3}(\\.\\d\\d\\d){1,5})" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> parseDouble (Text.replace (Text.singleton '.') Text.empty match) >>= double _ -> Nothing } rules :: [Rule] rules = [ ruleDecimalNumeral , ruleDecimalWithThousandsSeparator , ruleIntegerNumeric , ruleIntegerWithThousandsSeparator , ruleNumeral , ruleNumeral2 , ruleNumeral3 , ruleNumeral4 , ruleNumeral5 , ruleNumeral6 , ruleNumeralDotNumeral , ruleNumerals , ruleNumeralsPrefixWithNegativeOrMinus , ruleNumeralsSuffixesKMG ]
rfranek/duckling
Duckling/Numeral/ES/Rules.hs
bsd-3-clause
8,586
0
19
2,117
2,478
1,433
1,045
251
5
{-# OPTIONS_GHC -fno-warn-orphans #-} module Ed25519 ( benchmarks -- :: IO [Benchmark] ) where import Criterion.Main import Crypto.Key import Crypto.Sign.Ed25519 import Control.DeepSeq import qualified Data.ByteString as B import Util () instance NFData (SecretKey t) instance NFData (PublicKey t) benchmarks :: IO [Benchmark] benchmarks = do keys@(pk,sk) <- createKeypair let dummy = B.replicate 512 3 msg = sign sk dummy return [ bench "keypair" $ nfIO createKeypair , bench "sign" $ nf (sign sk) dummy , bench "verify" $ nf (verify pk) msg , bench "roundtrip" $ nf (signBench keys) dummy ] signBench :: (PublicKey Ed25519, SecretKey Ed25519) -> B.ByteString -> Bool signBench (pk, sk) xs = verify pk (sign sk xs)
thoughtpolice/hs-nacl
benchmarks/Ed25519.hs
bsd-3-clause
874
0
12
269
268
140
128
22
1
{-# LANGUAGE ScopedTypeVariables, QuasiQuotes, TemplateHaskell, MultiParamTypeClasses, FlexibleInstances #-} module NestedPatMatch where import Data.Maybe import Language.XHaskell [xh| data Foo = Foo (Star Bar) deriving Show data Bar = Bar deriving Show f :: Foo -> Choice Foo () f (Foo (x :: Bar)) = Foo x f (Foo (x :: (Star Bar))) = () mapStar :: (a -> b) -> Star a -> Star b mapStar (f :: a -> b) = \x -> case x of { (x :: ()) -> x ; (x :: a, xs :: Star a) -> (f x, mapStar f xs) } g :: Star Foo -> Star Foo g (xs :: (Star Foo)) = (mapStar f xs) mapStar' :: (Foo -> Choice Foo ()) -> Star Foo -> Star (Choice Foo ()) mapStar' (f :: Foo -> Choice Foo ()) = \x -> case x of { (x :: ()) -> x ; (x :: Foo, xs :: Star Foo) -> (f x, mapStar' f xs) } |] {- *NestedPatMatch> f (Foo [Bar]) Left (Foo [Bar]) *NestedPatMatch> f (Foo []) Right () -}
luzhuomi/xhaskell
test/NestedPatMatch.hs
bsd-3-clause
898
0
4
236
23
16
7
5
0
import Graphics.Efl.Simple import Control.Monad (when) import Paths_graphics_efl main :: IO () main = do initWindowingSystem engines <- getEngines putStrLn (show engines) let engine = if "opengl_x11" `elem` engines then Just "opengl_x11" else Nothing withDefaultWindow engine $ \ win canvas -> do engineName <- getEngineName win putStrLn $ "Using engine " ++ engineName setWindowTitle "Simple Haskell-EFL Example" win bgfile <- getDataFileName "examples/data/Red_Giant_Earth_warm.jpg" inTxt <- addText canvas |> setText "Your text: " |> resize 200 10 |> move 25 200 |> setTextStyle (TextStylePlain,TextStyleShadowDirectionBottomRight) |> setTextFont ("DejaVu",14) |> setObjectColor (255,255,255,255) |> enableEventPassing |> uncover -- bg <- addFilledImage canvas bg <- addRectangle canvas |> setImageFile bgfile Nothing |> setObjectColor (0,0,0,255) |> setLayer (-1) |> uncover |> setFocus True |> onKeyDown (\ _ ev -> do name <- keyDownKeyName ev old <- getText inTxt new <- case name of "Escape" -> quitMainLoop >> return old "BackSpace" -> return $ if null old then old else init old _ -> (old ++) <$> keyDownString ev setText new inTxt ) onWindowResize win $ do (_,_,w,h) <- getWindowGeometry win resize w h bg let clickHandler obj ev = do name <- getName obj btn <- mouseDownButton ev putStrLn $ "You clicked on " ++ name ++ " with button " ++ show btn r <- addRectangle canvas |> setName "First rectangle" |> resize 100 40 |> move 20 40 |> setObjectColor (255,0,0,255) |> uncover |> onMouseDown clickHandler |> onMouseMove (\_ _ -> putStrLn "Move!") r2 <- addRectangle canvas |> setName "Second rectangle" |> resize 100 40 |> move 100 100 |> setObjectColor (128,128,0,128) |> uncover |> onMouseIn (\_ ev -> do wxy <- mouseInWorldXY ev cxy <- mouseInCanvasXY ev t <- mouseInTimestamp ev putStrLn (show wxy ++ ";" ++ show cxy ++ ";" ++ show t)) |> onMouseDown clickHandler |> onMouseOut (\ _ _-> putStrLn "Out!") |> onMouseUp (\ _ _-> putStrLn "Up!") |> onMouseWheel (\ _ _-> putStrLn "Wheel!") let poly :: Int -> Double -> [(Coord,Coord)] poly n w = [(round $ x*w, round $ y*w) | (x,y) <- (map cos angles `zip` map sin angles)] where angles :: [Double] angles = map ((*c) . fromIntegral) [0..(n-1)] c = 2.0 * pi / fromIntegral n po <- addPolygon canvas |> addPolygonPoints (poly 8 10) |> setObjectColor (128,128,128,255) |> move 200 200 |> uncover style <- createTextBlockStyle |> configureTextBlockStyle "DEFAULT='font=DejaVuSans-Bold font_size=26 align=center color=#000000 wrap=word style=soft_outline outline_color=#3779cb' NewLine= '+\n'" _ <- addTextBlock canvas |> setTextBlockStyle style |> setTextBlockTextMarkup "Welcome to the <b>Haskell-EFL</b> demo!!!" |> resize 500 400 |> move 300 10 |> setObjectColor (255,255,255,255) |> enableEventPassing |> uncover let lipsum = "In this demo, you can:<br/>\ \ - click on objects (with any button)<br/>\ \ - scroll this text with the mouse wheel<br/>\ \ - enter some text<br/>\ \<br/><br/>\ \Press \"Escape\" to quit\ \" style2 <- createTextBlockStyle |> configureTextBlockStyle "DEFAULT='font=DejaVuSans-Bold font_size=20 align=left color=#000000 wrap=word style=soft_shadow shadow_color=#CCCCCC' NewLine= '+\n'" lipsumTxt <- addTextBlock canvas |> setTextBlockStyle style2 |> setTextBlockTextMarkup lipsum |> resize 500 400 |> move 20 400 |> enableEventPassing |> uncover flip onMouseWheel bg $ \ _ ev -> do dir <- mouseWheelDirection ev off <- mouseWheelOffset ev (x,y,_,_) <- getGeometry lipsumTxt when (dir == 0) $ move x (y + fromIntegral (-10 * off)) lipsumTxt when (dir == 1) $ move (x + fromIntegral (10 * off)) y lipsumTxt let center o = do (x,y,w,h) <- getGeometry o return (w `div` 2 + x, h `div` 2 + y) --setAnimatorFrameRate 4 (cx,cy) <- center r addAnimationLinear' 1.0 Nothing $ \step -> do m <- createMap 4 |> populateMapPointsFromObject r |> rotateMap (360.0 * step) (fromIntegral cx) (fromIntegral cy) setMap m r enableMap r anim <- addAnimationLinear 4.0 Nothing $ \step -> do (cx',cy') <- center r2 m <- createMap 4 |> populateMapPointsFromObject r2 |> rotateMap (360.0 * step) (fromIntegral cx') (fromIntegral cy') setMap m r2 enableMap r2 flip onMouseDown r2 $ \ _ _ -> freezeAnimator anim flip onMouseUp r2 $ \ _ _ -> thawAnimator anim addAnimationLinear' 3.0 (Just 1) $ \step -> do let x' = (100+(floor $ step * 200)) move x' 100 r2 addAnimationBounce' 4 Nothing $ \step -> do let x' = (100+(floor $ step * 400)) (_,y,_,_) <- getGeometry po move x' y po addAnimationSinusoidal' 6 8.0 Nothing $ \step -> do let y' = (200+(floor $ step * 100)) (x,_,_,_) <- getGeometry po move x y' po return ()
hsyl20/graphics-efl
examples/Simple.hs
bsd-3-clause
6,156
0
28
2,299
1,824
882
942
137
5
------------------------------------------------------------------------ -- | -- Module : ALife.Creatur.Wain.AudioID.Experiment -- Copyright : (c) Amy de Buitléir 2012-2016 -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- A data mining agent, designed for the Créatúr framework. -- ------------------------------------------------------------------------ {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE Rank2Types #-} module ALife.Creatur.Wain.AudioID.Experiment ( PatternWain, randomPatternWain, PatternTweaker(..), run, finishRound, schemaQuality, printStats, versionInfo, idealPopControlDeltaE -- exported for testing only ) where import ALife.Creatur (agentId, isAlive, programVersion) import ALife.Creatur.Task (checkPopSize) import qualified ALife.Creatur.Wain as W import qualified ALife.Creatur.Wain.Audio.Wain as AW import ALife.Creatur.Wain.AudioID.Action (Action(..), correct, correctActions) import ALife.Creatur.Wain.Audio.Pattern (Pattern, mkAudio) import ALife.Creatur.Wain.Audio.PatternDB (PatternDB, anyPattern) import ALife.Creatur.Wain.Audio.Tweaker (PatternTweaker(..)) import qualified ALife.Creatur.Wain.AudioID.Universe as U import ALife.Creatur.Wain.Brain (makeBrain, predictor, scenarioReport, responseReport, decisionReport) import ALife.Creatur.Wain.Checkpoint (enforceAll) import qualified ALife.Creatur.Wain.Classifier as Cl import ALife.Creatur.Wain.Muser (makeMuser) import qualified ALife.Creatur.Wain.Predictor as P import ALife.Creatur.Wain.GeneticSOM (RandomLearningParams(..), randomLearningFunction, schemaQuality, modelMap) import qualified ALife.Creatur.Wain.Audio.Object as O import ALife.Creatur.Wain.Pretty (pretty) import ALife.Creatur.Wain.Raw (raw) import ALife.Creatur.Wain.Response (Response, _action, _outcomes) import ALife.Creatur.Wain.SimpleResponseTweaker (ResponseTweaker(..)) import ALife.Creatur.Wain.UnitInterval (uiToDouble) import qualified ALife.Creatur.Wain.Statistics as Stats import ALife.Creatur.Persistent (putPS, getPS) import ALife.Creatur.Wain.PersistentStatistics (updateStats, readStats, clearStats) import ALife.Creatur.Wain.Statistics (summarise) import ALife.Creatur.Wain.Weights (makeWeights) import Control.Conditional (whenM) import Control.Lens hiding (universe) import Control.Monad (when, unless) import Control.Monad.IO.Class (liftIO) import Control.Monad.Random (Rand, RandomGen, getRandomR, getRandomRs, getRandom, evalRandIO, fromList) import Control.Monad.State.Lazy (StateT, execStateT, evalStateT, get, put) import Data.List (intercalate, sortBy) import Data.Map (toList) import Data.Ord (comparing) import Data.Version (showVersion) import Data.Word (Word64) import Paths_exp_audio_id_wains (version) import System.Directory (createDirectoryIfMissing) import System.FilePath (dropFileName) versionInfo :: String versionInfo = "exp-audio-id-wains-" ++ showVersion version ++ ", compiled with " ++ AW.packageVersion ++ ", " ++ W.packageVersion ++ ", " ++ ALife.Creatur.programVersion type PatternWain = W.Wain Pattern PatternTweaker (ResponseTweaker Action) Action randomPatternWain :: RandomGen r => String -> U.Universe PatternWain -> Word64 -> Word64 -> Rand r PatternWain randomPatternWain wName u classifierSize predictorSize = do let fcp = RandomLearningParams { _r0Range = view U.uClassifierR0Range u, _rfRange = view U.uClassifierRfRange u, _tfRange = view U.uClassifierTfRange u } fc <- randomLearningFunction fcp classifierThreshold <- getRandomR (view U.uClassifierThresholdRange u) let c = Cl.buildClassifier fc classifierSize classifierThreshold PatternTweaker let fdp = RandomLearningParams { _r0Range = view U.uPredictorR0Range u, _rfRange = view U.uPredictorRfRange u, _tfRange = view U.uPredictorTfRange u } fd <- randomLearningFunction fdp predictorThreshold <- getRandomR (view U.uPredictorThresholdRange u) let p = P.buildPredictor fd predictorSize predictorThreshold ResponseTweaker -- TODO: Allow a range of random weights -- hw <- (makeWeights . take 3) <$> getRandomRs unitInterval let hw = makeWeights [0.7, 0.3, 0, 0.1] t <- getRandom s <- getRandomR (view U.uStrictnessRange u) dp <- getRandomR $ view U.uDepthRange u dos <- take 4 <$> getRandomRs (view U.uDefaultOutcomeRange u) let (Right mr) = makeMuser dos dp ios <- take 4 <$> getRandomRs (view U.uImprintOutcomeRange u) rds <- take 4 <$> getRandomRs (view U.uReinforcementDeltasRange u) let (Right wBrain) = makeBrain c mr p hw t s ios rds wDevotion <- getRandomR . view U.uDevotionRange $ u wAgeOfMaturity <- getRandomR . view U.uMaturityRange $ u wPassionDelta <- getRandomR . view U.uPassionDeltaRange $ u let wBoredomDelta = 0 let n = (view U.uNumVectors u)*(view U.uVectorLength u) let wAppearance = mkAudio $ replicate n 0 return $ W.buildWainAndGenerateGenome wName wAppearance wBrain wDevotion wAgeOfMaturity wPassionDelta wBoredomDelta data Summary = Summary { _rPopSize :: Int, _rMetabolismDeltaE :: Double, _rPopControlDeltaE :: Double, _rCatDeltaE :: Double, _rFlirtingDeltaE :: Double, _rMatingDeltaE :: Double, _rOldAgeDeltaE :: Double, _rOtherMatingDeltaE :: Double, _rNetDeltaE :: Double, _rChildNetDeltaE :: Double, _rDeltaEToReflectOn :: Double, _rDeltaPToReflectOn :: Double, _rDeltaHToReflectOn :: Double, _rErr :: Double, _rBirthCount :: Int, _rWeanCount :: Int, _rCatCount :: Int, _rFlirtCount :: Int, _rMateCount :: Int, _rDeathCount :: Int, _rMistakeCount :: Int } makeLenses ''Summary initSummary :: Int -> Summary initSummary p = Summary { _rPopSize = p, _rMetabolismDeltaE = 0, _rPopControlDeltaE = 0, _rCatDeltaE = 0, _rFlirtingDeltaE = 0, _rMatingDeltaE = 0, _rOldAgeDeltaE = 0, _rOtherMatingDeltaE = 0, _rNetDeltaE = 0, _rChildNetDeltaE = 0, _rDeltaEToReflectOn = 0, _rDeltaPToReflectOn = 0, _rDeltaHToReflectOn = 0, _rErr = 0, _rBirthCount = 0, _rWeanCount = 0, _rCatCount = 0, _rFlirtCount = 0, _rMateCount = 0, _rDeathCount = 0, _rMistakeCount = 0 } summaryStats :: Summary -> [Stats.Statistic] summaryStats r = [ Stats.dStat "pop. size" (view rPopSize r), Stats.dStat "adult metabolism Δe" (view rMetabolismDeltaE r), Stats.dStat "adult pop. control Δe" (view rPopControlDeltaE r), Stats.dStat "cat Δe" (view rCatDeltaE r), Stats.dStat "flirting Δe" (view rFlirtingDeltaE r), Stats.dStat "adult mating Δe" (view rMatingDeltaE r), Stats.dStat "adult old age Δe" (view rOldAgeDeltaE r), Stats.dStat "other adult mating Δe" (view rOtherMatingDeltaE r), Stats.dStat "adult net Δe" (view rNetDeltaE r), Stats.dStat "child net Δe" (view rChildNetDeltaE r), Stats.dStat "Δe to reflect on" (view rDeltaEToReflectOn r), Stats.dStat "Δp to reflect on" (view rDeltaPToReflectOn r), Stats.dStat "Δh to reflect on" (view rDeltaHToReflectOn r), Stats.dStat "err" (view rErr r), Stats.iStat "bore" (view rBirthCount r), Stats.iStat "weaned" (view rWeanCount r), Stats.iStat "classified" (view rCatCount r), Stats.iStat "flirted" (view rFlirtCount r), Stats.iStat "mated" (view rMateCount r), Stats.iStat "died" (view rDeathCount r), Stats.iStat "mistakes" (view rMistakeCount r) ] data Experiment = Experiment { _subject :: PatternWain, _other :: O.Object Action (ResponseTweaker Action), _weanlings :: [PatternWain], _universe :: U.Universe PatternWain, _summary :: Summary } makeLenses ''Experiment finishRound :: FilePath -> StateT (U.Universe PatternWain) IO () finishRound f = do xss <- readStats f let yss = summarise xss printStats yss let zs = concat yss adjustPopControlDeltaE zs cs <- use U.uCheckpoints enforceAll zs cs clearStats f (a, b) <- use U.uAllowedPopulationRange checkPopSize (a, b) report :: String -> StateT Experiment IO () report = zoom universe . U.writeToLog run :: [PatternWain] -> StateT (U.Universe PatternWain) IO [PatternWain] run (me:otherWain:xs) = do when (null xs) $ U.writeToLog "WARNING: Last two wains standing!" p <- U.popSize u <- get x <- liftIO $ chooseObject (view U.uFrequencies u) otherWain (view U.uPatternDB u) let e = Experiment { _subject = me, _other = x, _weanlings = [], _universe = u, _summary = initSummary p} e' <- liftIO $ execStateT run' e put (view universe e') let modifiedAgents = O.addIfWain (view other e') $ view subject e' : view weanlings e' U.writeToLog $ "Modified agents: " ++ show (map agentId modifiedAgents) reportAnyDeaths modifiedAgents return modifiedAgents run _ = error "too few wains" run' :: StateT Experiment IO () run' = do t <- zoom universe U.currentTime if (t < 100) then imprintCorrectAction else runNormal runNormal :: StateT Experiment IO () runNormal = do (e0, ec0) <- totalEnergy a <- use subject report $ "---------- " ++ agentId a ++ "'s turn ----------" report $ "At beginning of turn, " ++ agentId a ++ "'s summary: " ++ pretty (Stats.stats a) runMetabolism autoPopControl <- use (universe . U.uPopControl) when autoPopControl applyPopControl r <- chooseSubjectAction wainBeforeAction <- use subject runAction (_action r) letSubjectReflect wainBeforeAction r subject %= W.autoAdjustPassion subject %= W.incAge a' <- use subject -- assign (summary.rNetDeltaE) (energy a' - energy a) unless (isAlive a') $ assign (summary.rDeathCount) 1 summary %= fillInSummary (ef, ecf) <- totalEnergy balanceEnergyEquation e0 ec0 ef ecf updateChildren killIfTooOld agentStats <- ((Stats.stats a' ++) . summaryStats) <$> use summary report $ "At end of turn, " ++ agentId a ++ "'s summary: " ++ pretty agentStats rsf <- use (universe . U.uRawStatsFile) zoom universe $ writeRawStats (agentId a) rsf agentStats sf <- use (universe . U.uStatsFile) zoom universe $ updateStats agentStats sf fillInSummary :: Summary -> Summary fillInSummary s = s { _rNetDeltaE = _rMetabolismDeltaE s + _rPopControlDeltaE s + _rCatDeltaE s + _rFlirtingDeltaE s + _rMatingDeltaE s + _rOldAgeDeltaE s + _rOtherMatingDeltaE s, _rChildNetDeltaE = 0 -- include energy given to wains when they are born - _rMatingDeltaE s - _rOtherMatingDeltaE s } balanceEnergyEquation :: Double -> Double -> Double -> Double -> StateT Experiment IO () balanceEnergyEquation e0 ec0 ef ecf = do netDeltaE1 <- use (summary . rNetDeltaE) let netDeltaE2 = ef - e0 let err = abs (netDeltaE1 - netDeltaE2) when (err > 0.000001) $ do report $ "WARNING: Adult energy equation doesn't balance" report $ "e0=" ++ show e0 ++ ", ef=" ++ show ef ++ ", netDeltaE2=" ++ show netDeltaE2 ++ ", netDeltaE1=" ++ show netDeltaE1 ++ ", err=" ++ show err childNetDeltaE1 <- use (summary . rChildNetDeltaE) let childNetDeltaE2 = ecf - ec0 let childErr = abs (childNetDeltaE1 - childNetDeltaE2) when (childErr > 0.000001) $ do report $ "WARNING: Child energy equation doesn't balance" report $ "ec0=" ++ show ec0 ++ ", ecf=" ++ show ecf ++ ", childNetDeltaE2=" ++ show childNetDeltaE2 ++ ", childNetDeltaE1=" ++ show childNetDeltaE1 ++ ", childErr=" ++ show childErr runMetabolism :: StateT Experiment IO () runMetabolism = do a <- use subject bmc <- use (universe . U.uBaseMetabolismDeltaE) cpcm <- use (universe . U.uEnergyCostPerClassifierModel) ccf <- use (universe . U.uChildCostFactor) let deltaE = AW.metabCost bmc cpcm 1 a + sum (map (AW.metabCost bmc cpcm ccf) (view W.litter a)) AW.adjustEnergy subject deltaE rMetabolismDeltaE "metab." summary report chooseSubjectAction :: StateT Experiment IO (Response Action) chooseSubjectAction = do a <- use subject obj <- use other (r, a') <- zoom universe $ chooseAction3 a obj assign subject a' return r chooseAction3 :: PatternWain -> O.Object Action (ResponseTweaker Action) -> StateT (U.Universe PatternWain) IO (Response Action, PatternWain) chooseAction3 w obj = do whenM (use U.uShowPredictorModels) $ do U.writeToLog "begin predictor models" describeModels w U.writeToLog "end predictor models" let (ldss, sps, rplos, aohs, r, w') = W.chooseAction [O.objectAppearance obj] w whenM (use U.uGenFmris) --writeFmri w (mapM_ U.writeToLog . AW.describeClassifierModels $ w) whenM (use U.uShowScenarioReport) $ do U.writeToLog "begin scenario report" mapM_ U.writeToLog $ scenarioReport sps U.writeToLog "end scenario report" whenM (use U.uShowResponseReport) $ do U.writeToLog "begin response report" mapM_ U.writeToLog $ responseReport rplos U.writeToLog "end response report" whenM (use U.uShowDecisionReport) $ do U.writeToLog "begin decision report" mapM_ U.writeToLog $ decisionReport aohs U.writeToLog "end decision report" let bmuInfo = formatBMUs . map fst . sortBy (comparing snd) . head $ ldss U.writeToLog $ agentId w ++ " sees " ++ O.objectId obj ++ ", classifies it as " ++ bmuInfo ++ " and chooses to " ++ show (_action r) ++ " predicting the outcomes " ++ show (_outcomes r) return (r, w') describeModels :: PatternWain -> StateT (U.Universe PatternWain) IO () describeModels w = mapM_ (U.writeToLog . f) ms where ms = toList . modelMap . view (W.brain . predictor) $ w f (l, r) = view W.name w ++ "'s predictor model " ++ show l ++ "=" ++ pretty r formatBMUs :: [Cl.Label] -> String formatBMUs (cBMU:cBMU2:_) = show cBMU ++ " (alt. " ++ show cBMU2 ++ ")" formatBMUs (cBMU:_) = show cBMU formatBMUs _ = error "no BMUs" chooseObject :: [Rational] -> PatternWain -> PatternDB -> IO (O.Object Action (ResponseTweaker Action)) chooseObject freqs w db = do (img1, audioId1) <- evalStateT anyPattern db fromList $ zip [O.PObject img1 audioId1, O.AObject w] freqs runAction :: Action -> StateT Experiment IO () -- -- Flirt -- runAction Flirt = do applyFlirtationEffects obj <- use other unless (O.isPattern obj) flirt (summary.rFlirtCount) += 1 -- -- Categorise -- runAction a = do obj <- use other let n = O.objectNum obj deltaE <- if correct a n then use (universe . U.uCorrectDeltaE) else use (universe . U.uIncorrectDeltaE) AW.adjustEnergy subject deltaE rCatDeltaE "audio ID" summary report (summary.rCatCount) += 1 -- -- Utility functions -- applyPopControl :: StateT Experiment IO () applyPopControl = do deltaE <- zoom (universe . U.uPopControlDeltaE) getPS AW.adjustEnergy subject deltaE rPopControlDeltaE "pop. control" summary report flirt :: StateT Experiment IO () flirt = do a <- use subject (O.AObject b) <- use other babyName <- zoom universe U.genName (a':b':_, msgs, aMatingDeltaE, bMatingDeltaE) <- liftIO . evalRandIO $ W.mate a b babyName if null msgs then do report $ agentId a ++ " and " ++ agentId b ++ " mated" report $ "Contribution to child: " ++ agentId a ++ "'s share is " ++ show aMatingDeltaE ++ " " ++ agentId b ++ "'s share is " ++ show bMatingDeltaE assign subject a' assign other (O.AObject b') recordBirths (summary . rMatingDeltaE) += aMatingDeltaE (summary . rOtherMatingDeltaE) += bMatingDeltaE (summary . rMateCount) += 1 else mapM_ report msgs recordBirths :: StateT Experiment IO () recordBirths = do a <- use subject (summary.rBirthCount) += length (view W.litter a) applyFlirtationEffects :: StateT Experiment IO () applyFlirtationEffects = do deltaE <- use (universe . U.uFlirtingDeltaE) report $ "Applying flirtation energy adjustment" AW.adjustEnergy subject deltaE rFlirtingDeltaE "flirting" summary report (summary.rFlirtCount) += 1 updateChildren :: StateT Experiment IO () updateChildren = do (a:matureChildren) <- W.weanMatureChildren <$> use subject assign subject a (a':deadChildren) <- W.pruneDeadChildren <$> use subject assign subject a' assign weanlings (matureChildren ++ deadChildren) (summary.rWeanCount) += length matureChildren killIfTooOld :: StateT Experiment IO () killIfTooOld = do a <- view W.age <$> use subject maxAge <- use (universe . U.uMaxAge) when (fromIntegral a > maxAge) $ AW.adjustEnergy subject (-100) rOldAgeDeltaE "old age" summary report adjustPopControlDeltaE :: [Stats.Statistic] -> StateT (U.Universe PatternWain) IO () adjustPopControlDeltaE xs = unless (null xs) $ do let (Just average) = Stats.lookup "avg. energy" xs let (Just total) = Stats.lookup "total energy" xs budget <- use U.uEnergyBudget pop <- U.popSize let c = idealPopControlDeltaE average total budget pop U.writeToLog $ "Current avg. energy = " ++ show average U.writeToLog $ "Current total energy = " ++ show total U.writeToLog $ "energy budget = " ++ show budget U.writeToLog $ "Adjusted pop. control Δe = " ++ show c zoom U.uPopControlDeltaE $ putPS c -- TODO: Make the 0.8 configurable idealPopControlDeltaE :: Double -> Double -> Double -> Int -> Double idealPopControlDeltaE average total budget pop | average < 0.8 = (budget - total) / (fromIntegral pop) | otherwise = 0.8 - average totalEnergy :: StateT Experiment IO (Double, Double) totalEnergy = do a <- fmap uiToDouble $ view W.energy <$> use subject b <- fmap uiToDouble $ O.objectEnergy <$> use other d <- W.childEnergy <$> use subject e <- O.objectChildEnergy <$> use other return (a + b, d + e) printStats :: [[Stats.Statistic]] -> StateT (U.Universe PatternWain) IO () printStats = mapM_ f where f xs = U.writeToLog $ "Summary - " ++ intercalate "," (map pretty xs) letSubjectReflect :: PatternWain -> Response Action -> StateT Experiment IO () letSubjectReflect wBefore r = do w <- use subject obj <- use other let p = O.objectAppearance obj let energyBefore = view W.energy wBefore let passionBefore = view W.passion wBefore let happinessBefore = W.happiness wBefore energyAfter <- use (subject . W.energy) passionAfter <- use (subject . W.passion) happinessAfter <- W.happiness <$> use subject let deltaH = uiToDouble happinessAfter - uiToDouble happinessBefore assign (summary . rDeltaEToReflectOn) (uiToDouble energyAfter - uiToDouble energyBefore) assign (summary . rDeltaPToReflectOn) (uiToDouble passionAfter - uiToDouble passionBefore) assign (summary . rDeltaHToReflectOn) deltaH let (w', err) = W.reflect [p] r wBefore w assign subject w' assign (summary . rErr) err if (correct (_action r) (O.objectNum obj)) then report $ agentId w ++ "'s choice to " ++ show (_action r) ++ " (with) " ++ O.objectId obj ++ " was correct" else do report $ agentId w ++ "'s choice to " ++ show (_action r) ++ " (with) " ++ O.objectId obj ++ " was wrong" (summary . rMistakeCount) += 1 imprintCorrectAction :: StateT Experiment IO () imprintCorrectAction = do w <- use subject obj <- use other let p = O.objectAppearance obj let a = correctActions !! (O.objectNum obj) report $ "Teaching " ++ agentId w ++ " that correct action for " ++ O.objectId obj ++ " is " ++ show a let (_, _, _, _, w') = W.imprint [p] a w assign subject w' writeRawStats :: String -> FilePath -> [Stats.Statistic] -> StateT (U.Universe PatternWain) IO () writeRawStats n f xs = do liftIO $ createDirectoryIfMissing True (dropFileName f) t <- U.currentTime liftIO . appendFile f $ "time=" ++ show t ++ ",agent=" ++ n ++ ',':raw xs ++ "\n" reportAnyDeaths :: [PatternWain] -> StateT (U.Universe PatternWain) IO () reportAnyDeaths ws = mapM_ f ws where f w = when (not . isAlive $ w) $ U.writeToLog (agentId w ++ " dead at age " ++ show (view W.age w))
mhwombat/exp-audio-id-wains
src/ALife/Creatur/Wain/AudioID/Experiment.hs
bsd-3-clause
20,431
0
19
4,291
6,469
3,245
3,224
502
2
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} module System.HFind.Expr.Eval ( Eval , EvalContext , UninitializedVariableException(..) , RuntimeVar(..) , ctxGetVarValues, ctxGetActiveMatch, ctxGetBacktrace, ctxGetBakerContext , newContext , runEvalT , wrapEvalT , readonly , getVarValue , setVarValue , getCaptureValue , setCaptures , evalWithin ) where import Control.Exception (Exception, throw) import Control.Monad.Trans.Except (throwE) import Control.Monad.Catch (MonadThrow, MonadCatch, catchAll) import Control.Monad.Except import Control.Monad.Reader import Control.Monad.Morph import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.ICU as ICU import Data.Vector.Mutable (IOVector) import qualified Data.Vector as V import qualified Data.Vector.Mutable as MV import Data.Void (Void) import Unsafe.Coerce (unsafeCoerce) import System.HFind.Expr.Types (Name, TypedName(..), ErasedValue(..), Value, eraseType, RxCaptureMode(..)) import System.HFind.Expr.Baker (VarId) import qualified System.HFind.Expr.Baker as Baker import qualified System.HFind.Expr.Error as Err data EvalContext = EvalContext { ctxValues :: !(IOVector (Value Void)) -- reversed , ctxActiveMatch :: !(IORef (Maybe ICU.Match)) , ctxBacktrace :: !(IORef Err.Backtrace) , ctxBakerContext :: !Baker.BakingContext } instance Show EvalContext where show _ = "<ctx>" data UninitializedVariableException = UninitializedVariableException deriving (Eq, Show) instance Exception UninitializedVariableException newContext :: Baker.BakingContext -> IO EvalContext newContext ctx = do vals <- MV.replicate (Baker.ctxGetNumVars ctx) (throw UninitializedVariableException) activeMatch <- newIORef Nothing backtrace <- newIORef Err.emptyBacktrace return (EvalContext vals activeMatch backtrace ctx) data RuntimeVar where RuntimeVar :: !Name -> !(Value t) -> RuntimeVar ctxGetVarValues :: EvalContext -> IO [RuntimeVar] ctxGetVarValues ctx = do let vars = Baker.ctxGetVars (ctxBakerContext ctx) values <- V.freeze (ctxValues ctx) return (zipWith runtimeVar vars (V.toList values)) where runtimeVar :: TypedName -> Value Void -> RuntimeVar runtimeVar (TypedName ty name) val = case eraseType ty (unsafeCoerce val) of ErasedValue val' -> RuntimeVar name val' ctxGetActiveMatch :: EvalContext -> IO (Maybe ICU.Match) ctxGetActiveMatch = readIORef . ctxActiveMatch ctxGetBacktrace :: EvalContext -> IO Err.Backtrace ctxGetBacktrace = readIORef . ctxBacktrace ctxGetBakerContext :: EvalContext -> Baker.BakingContext ctxGetBakerContext = ctxBakerContext type Eval = EvalT IO type instance Baker.EvalMonad Baker.BakerT = Eval newtype EvalT m a = EvalT (ExceptT Err.RuntimeError (ReaderT EvalContext m) a) deriving (Functor, Applicative, Monad, MonadIO, MonadError Err.RuntimeError, MonadThrow, MonadCatch) instance MonadTrans EvalT where lift = EvalT . lift . lift instance MFunctor EvalT where hoist f (EvalT m) = EvalT $ hoist (hoist f) m -- Eval primitives -------------------------------------------------- runEvalT :: MonadIO m => EvalContext -> EvalT m a -> ExceptT (EvalContext, Err.RuntimeError) m a runEvalT ctx (EvalT m) = do res <- lift $ runReaderT (runExceptT m) ctx case res of Left err -> throwE (ctx, err) Right a -> return a wrapEvalT :: Monad m => ExceptT (EvalContext, Err.RuntimeError) m a -> EvalT m a wrapEvalT m = EvalT $ ExceptT $ ReaderT $ \_ -> do r <- runExceptT m case r of Left (_, e) -> return (Left e) Right a -> return (Right a) readonly :: MonadIO m => EvalT m a -> EvalT m a readonly (EvalT m) = EvalT $ do -- variables may change in the action, but the current language does not -- allow it in predicates and this is just used in Eval.hs, so we're -- safe for now ctx <- ask match <- liftIO $ readIORef (ctxActiveMatch ctx) bt <- liftIO $ readIORef (ctxBacktrace ctx) a <- m liftIO $ writeIORef (ctxActiveMatch ctx) match liftIO $ writeIORef (ctxBacktrace ctx) bt return a -- evil unsafeCoerceValue :: VarId a -> Value Void -> Value a unsafeCoerceValue _ = unsafeCoerce unsafeVoidValue :: VarId a -> Value a -> Value Void unsafeVoidValue _ = unsafeCoerce getVarValue :: (MonadIO m, MonadCatch m) => VarId a -> EvalT m (Value a) getVarValue i = do vals <- EvalT $ asks ctxValues val <- liftIO (MV.read vals (Baker.varIdNum i)) `catchAll` (throwError . Err.NativeError) return (unsafeCoerceValue i val) setVarValue :: (MonadIO m, MonadCatch m) => VarId a -> Value a -> EvalT m () setVarValue i val = do vals <- EvalT $ asks ctxValues liftIO (MV.write vals (Baker.varIdNum i) (unsafeVoidValue i val)) `catchAll` (throwError . Err.NativeError) getCaptureValue :: MonadIO m => Int -> EvalT m Text getCaptureValue i = EvalT $ do Just match <- liftIO . readIORef =<< asks ctxActiveMatch case ICU.group i match of Just text -> return text Nothing -> error $ "getCaptureValue: could not find $" ++ show i ++ " of " ++ T.unpack (ICU.pattern match) setCaptures :: MonadIO m => RxCaptureMode -> ICU.Match -> EvalT m () setCaptures NoCapture _ = return () setCaptures Capture match = EvalT $ do activeMatch <- asks ctxActiveMatch liftIO $ writeIORef activeMatch $! Just $! match evalWithin :: MonadIO m => Err.Backtrace -> EvalT m a -> EvalT m a evalWithin bt (EvalT ma) = EvalT $ do btRef <- asks ctxBacktrace prev <- liftIO $ readIORef btRef liftIO $ writeIORef btRef bt a <- ma liftIO $ writeIORef btRef prev return a
xcv-/pipes-find
src/System/HFind/Expr/Eval.hs
mit
6,295
0
15
1,505
1,886
974
912
166
2
{-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-orphans #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Test.AWS.Gen.DeviceFarm -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Test.AWS.Gen.DeviceFarm where import Data.Proxy import Test.AWS.Fixture import Test.AWS.Prelude import Test.Tasty import Network.AWS.DeviceFarm import Test.AWS.DeviceFarm.Internal -- Auto-generated: the actual test selection needs to be manually placed into -- the top-level so that real test data can be incrementally added. -- -- This commented snippet is what the entire set should look like: -- fixtures :: TestTree -- fixtures = -- [ testGroup "request" -- [ testListProjects $ -- listProjects -- -- , testGetDevicePoolCompatibility $ -- getDevicePoolCompatibility -- -- , testListTests $ -- listTests -- -- , testListArtifacts $ -- listArtifacts -- -- , testCreateUpload $ -- createUpload -- -- , testGetDevicePool $ -- getDevicePool -- -- , testListDevicePools $ -- listDevicePools -- -- , testGetUpload $ -- getUpload -- -- , testCreateDevicePool $ -- createDevicePool -- -- , testListRuns $ -- listRuns -- -- , testGetTest $ -- getTest -- -- , testGetDevice $ -- getDevice -- -- , testListJobs $ -- listJobs -- -- , testGetJob $ -- getJob -- -- , testScheduleRun $ -- scheduleRun -- -- , testGetRun $ -- getRun -- -- , testListSamples $ -- listSamples -- -- , testListSuites $ -- listSuites -- -- , testGetAccountSettings $ -- getAccountSettings -- -- , testListUploads $ -- listUploads -- -- , testGetSuite $ -- getSuite -- -- , testGetProject $ -- getProject -- -- , testListUniqueProblems $ -- listUniqueProblems -- -- , testListDevices $ -- listDevices -- -- , testCreateProject $ -- createProject -- -- ] -- , testGroup "response" -- [ testListProjectsResponse $ -- listProjectsResponse -- -- , testGetDevicePoolCompatibilityResponse $ -- getDevicePoolCompatibilityResponse -- -- , testListTestsResponse $ -- listTestsResponse -- -- , testListArtifactsResponse $ -- listArtifactsResponse -- -- , testCreateUploadResponse $ -- createUploadResponse -- -- , testGetDevicePoolResponse $ -- getDevicePoolResponse -- -- , testListDevicePoolsResponse $ -- listDevicePoolsResponse -- -- , testGetUploadResponse $ -- getUploadResponse -- -- , testCreateDevicePoolResponse $ -- createDevicePoolResponse -- -- , testListRunsResponse $ -- listRunsResponse -- -- , testGetTestResponse $ -- getTestResponse -- -- , testGetDeviceResponse $ -- getDeviceResponse -- -- , testListJobsResponse $ -- listJobsResponse -- -- , testGetJobResponse $ -- getJobResponse -- -- , testScheduleRunResponse $ -- scheduleRunResponse -- -- , testGetRunResponse $ -- getRunResponse -- -- , testListSamplesResponse $ -- listSamplesResponse -- -- , testListSuitesResponse $ -- listSuitesResponse -- -- , testGetAccountSettingsResponse $ -- getAccountSettingsResponse -- -- , testListUploadsResponse $ -- listUploadsResponse -- -- , testGetSuiteResponse $ -- getSuiteResponse -- -- , testGetProjectResponse $ -- getProjectResponse -- -- , testListUniqueProblemsResponse $ -- listUniqueProblemsResponse -- -- , testListDevicesResponse $ -- listDevicesResponse -- -- , testCreateProjectResponse $ -- createProjectResponse -- -- ] -- ] -- Requests testListProjects :: ListProjects -> TestTree testListProjects = req "ListProjects" "fixture/ListProjects.yaml" testGetDevicePoolCompatibility :: GetDevicePoolCompatibility -> TestTree testGetDevicePoolCompatibility = req "GetDevicePoolCompatibility" "fixture/GetDevicePoolCompatibility.yaml" testListTests :: ListTests -> TestTree testListTests = req "ListTests" "fixture/ListTests.yaml" testListArtifacts :: ListArtifacts -> TestTree testListArtifacts = req "ListArtifacts" "fixture/ListArtifacts.yaml" testCreateUpload :: CreateUpload -> TestTree testCreateUpload = req "CreateUpload" "fixture/CreateUpload.yaml" testGetDevicePool :: GetDevicePool -> TestTree testGetDevicePool = req "GetDevicePool" "fixture/GetDevicePool.yaml" testListDevicePools :: ListDevicePools -> TestTree testListDevicePools = req "ListDevicePools" "fixture/ListDevicePools.yaml" testGetUpload :: GetUpload -> TestTree testGetUpload = req "GetUpload" "fixture/GetUpload.yaml" testCreateDevicePool :: CreateDevicePool -> TestTree testCreateDevicePool = req "CreateDevicePool" "fixture/CreateDevicePool.yaml" testListRuns :: ListRuns -> TestTree testListRuns = req "ListRuns" "fixture/ListRuns.yaml" testGetTest :: GetTest -> TestTree testGetTest = req "GetTest" "fixture/GetTest.yaml" testGetDevice :: GetDevice -> TestTree testGetDevice = req "GetDevice" "fixture/GetDevice.yaml" testListJobs :: ListJobs -> TestTree testListJobs = req "ListJobs" "fixture/ListJobs.yaml" testGetJob :: GetJob -> TestTree testGetJob = req "GetJob" "fixture/GetJob.yaml" testScheduleRun :: ScheduleRun -> TestTree testScheduleRun = req "ScheduleRun" "fixture/ScheduleRun.yaml" testGetRun :: GetRun -> TestTree testGetRun = req "GetRun" "fixture/GetRun.yaml" testListSamples :: ListSamples -> TestTree testListSamples = req "ListSamples" "fixture/ListSamples.yaml" testListSuites :: ListSuites -> TestTree testListSuites = req "ListSuites" "fixture/ListSuites.yaml" testGetAccountSettings :: GetAccountSettings -> TestTree testGetAccountSettings = req "GetAccountSettings" "fixture/GetAccountSettings.yaml" testListUploads :: ListUploads -> TestTree testListUploads = req "ListUploads" "fixture/ListUploads.yaml" testGetSuite :: GetSuite -> TestTree testGetSuite = req "GetSuite" "fixture/GetSuite.yaml" testGetProject :: GetProject -> TestTree testGetProject = req "GetProject" "fixture/GetProject.yaml" testListUniqueProblems :: ListUniqueProblems -> TestTree testListUniqueProblems = req "ListUniqueProblems" "fixture/ListUniqueProblems.yaml" testListDevices :: ListDevices -> TestTree testListDevices = req "ListDevices" "fixture/ListDevices.yaml" testCreateProject :: CreateProject -> TestTree testCreateProject = req "CreateProject" "fixture/CreateProject.yaml" -- Responses testListProjectsResponse :: ListProjectsResponse -> TestTree testListProjectsResponse = res "ListProjectsResponse" "fixture/ListProjectsResponse.proto" deviceFarm (Proxy :: Proxy ListProjects) testGetDevicePoolCompatibilityResponse :: GetDevicePoolCompatibilityResponse -> TestTree testGetDevicePoolCompatibilityResponse = res "GetDevicePoolCompatibilityResponse" "fixture/GetDevicePoolCompatibilityResponse.proto" deviceFarm (Proxy :: Proxy GetDevicePoolCompatibility) testListTestsResponse :: ListTestsResponse -> TestTree testListTestsResponse = res "ListTestsResponse" "fixture/ListTestsResponse.proto" deviceFarm (Proxy :: Proxy ListTests) testListArtifactsResponse :: ListArtifactsResponse -> TestTree testListArtifactsResponse = res "ListArtifactsResponse" "fixture/ListArtifactsResponse.proto" deviceFarm (Proxy :: Proxy ListArtifacts) testCreateUploadResponse :: CreateUploadResponse -> TestTree testCreateUploadResponse = res "CreateUploadResponse" "fixture/CreateUploadResponse.proto" deviceFarm (Proxy :: Proxy CreateUpload) testGetDevicePoolResponse :: GetDevicePoolResponse -> TestTree testGetDevicePoolResponse = res "GetDevicePoolResponse" "fixture/GetDevicePoolResponse.proto" deviceFarm (Proxy :: Proxy GetDevicePool) testListDevicePoolsResponse :: ListDevicePoolsResponse -> TestTree testListDevicePoolsResponse = res "ListDevicePoolsResponse" "fixture/ListDevicePoolsResponse.proto" deviceFarm (Proxy :: Proxy ListDevicePools) testGetUploadResponse :: GetUploadResponse -> TestTree testGetUploadResponse = res "GetUploadResponse" "fixture/GetUploadResponse.proto" deviceFarm (Proxy :: Proxy GetUpload) testCreateDevicePoolResponse :: CreateDevicePoolResponse -> TestTree testCreateDevicePoolResponse = res "CreateDevicePoolResponse" "fixture/CreateDevicePoolResponse.proto" deviceFarm (Proxy :: Proxy CreateDevicePool) testListRunsResponse :: ListRunsResponse -> TestTree testListRunsResponse = res "ListRunsResponse" "fixture/ListRunsResponse.proto" deviceFarm (Proxy :: Proxy ListRuns) testGetTestResponse :: GetTestResponse -> TestTree testGetTestResponse = res "GetTestResponse" "fixture/GetTestResponse.proto" deviceFarm (Proxy :: Proxy GetTest) testGetDeviceResponse :: GetDeviceResponse -> TestTree testGetDeviceResponse = res "GetDeviceResponse" "fixture/GetDeviceResponse.proto" deviceFarm (Proxy :: Proxy GetDevice) testListJobsResponse :: ListJobsResponse -> TestTree testListJobsResponse = res "ListJobsResponse" "fixture/ListJobsResponse.proto" deviceFarm (Proxy :: Proxy ListJobs) testGetJobResponse :: GetJobResponse -> TestTree testGetJobResponse = res "GetJobResponse" "fixture/GetJobResponse.proto" deviceFarm (Proxy :: Proxy GetJob) testScheduleRunResponse :: ScheduleRunResponse -> TestTree testScheduleRunResponse = res "ScheduleRunResponse" "fixture/ScheduleRunResponse.proto" deviceFarm (Proxy :: Proxy ScheduleRun) testGetRunResponse :: GetRunResponse -> TestTree testGetRunResponse = res "GetRunResponse" "fixture/GetRunResponse.proto" deviceFarm (Proxy :: Proxy GetRun) testListSamplesResponse :: ListSamplesResponse -> TestTree testListSamplesResponse = res "ListSamplesResponse" "fixture/ListSamplesResponse.proto" deviceFarm (Proxy :: Proxy ListSamples) testListSuitesResponse :: ListSuitesResponse -> TestTree testListSuitesResponse = res "ListSuitesResponse" "fixture/ListSuitesResponse.proto" deviceFarm (Proxy :: Proxy ListSuites) testGetAccountSettingsResponse :: GetAccountSettingsResponse -> TestTree testGetAccountSettingsResponse = res "GetAccountSettingsResponse" "fixture/GetAccountSettingsResponse.proto" deviceFarm (Proxy :: Proxy GetAccountSettings) testListUploadsResponse :: ListUploadsResponse -> TestTree testListUploadsResponse = res "ListUploadsResponse" "fixture/ListUploadsResponse.proto" deviceFarm (Proxy :: Proxy ListUploads) testGetSuiteResponse :: GetSuiteResponse -> TestTree testGetSuiteResponse = res "GetSuiteResponse" "fixture/GetSuiteResponse.proto" deviceFarm (Proxy :: Proxy GetSuite) testGetProjectResponse :: GetProjectResponse -> TestTree testGetProjectResponse = res "GetProjectResponse" "fixture/GetProjectResponse.proto" deviceFarm (Proxy :: Proxy GetProject) testListUniqueProblemsResponse :: ListUniqueProblemsResponse -> TestTree testListUniqueProblemsResponse = res "ListUniqueProblemsResponse" "fixture/ListUniqueProblemsResponse.proto" deviceFarm (Proxy :: Proxy ListUniqueProblems) testListDevicesResponse :: ListDevicesResponse -> TestTree testListDevicesResponse = res "ListDevicesResponse" "fixture/ListDevicesResponse.proto" deviceFarm (Proxy :: Proxy ListDevices) testCreateProjectResponse :: CreateProjectResponse -> TestTree testCreateProjectResponse = res "CreateProjectResponse" "fixture/CreateProjectResponse.proto" deviceFarm (Proxy :: Proxy CreateProject)
fmapfmapfmap/amazonka
amazonka-devicefarm/test/Test/AWS/Gen/DeviceFarm.hs
mpl-2.0
12,656
0
7
2,819
1,492
878
614
259
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} -- Module : Gen.Tree -- Copyright : (c) 2013-2015 Brendan Hay -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : provisional -- Portability : non-portable (GHC extensions) module Gen.Tree ( root , fold , populate ) where import Control.Error import Control.Lens (each, (^.), (^..)) import Control.Monad import Control.Monad.Except import Data.Aeson hiding (json) import Data.Bifunctor import Data.Functor.Identity import qualified Data.HashMap.Strict as Map import Data.Monoid import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Lazy as LText import Filesystem.Path.CurrentOS hiding (FilePath, root) import Gen.Formatting (failure, shown) import Gen.Import import qualified Gen.JSON as JS import Gen.Types import Prelude hiding (mod) import System.Directory.Tree hiding (file) import Text.EDE hiding (failure, render) root :: AnchoredDirTree a -> Path root (p :/ d) = decodeString p </> decodeString (name d) fold :: MonadError Error m => (Path -> m ()) -- ^ Directories -> (Path -> a -> m b) -- ^ Files -> AnchoredDirTree a -> m (AnchoredDirTree b) fold g f (p :/ t) = (p :/) <$> go (decodeString p) t where go x = \case Failed n e -> failure shown e >> return (Failed n e) File n a -> File n <$> f (x </> decodeString n) a Dir n cs -> g d >> Dir n <$> mapM (go d) cs where d = x </> decodeString n -- If Nothing, then touch the file, otherwise write the Just contents. type Touch = Maybe Rendered populate :: Path -> Templates -> Library -> Either Error (AnchoredDirTree Touch) populate d Templates{..} l = (encodeString d :/) . dir lib <$> layout where layout :: Either Error [DirTree Touch] layout = traverse sequenceA [ dir "src" -- Supress cabal warnings about directories listed that don't exist. [ touch ".gitkeep" ] , dir "gen" [ dir "Network" [ dir "AWS" [ dir svc $ [ dir "Types" [ mod (l ^. sumNS) (sumImports l) sumTemplate , mod (l ^. productNS) (productImports l) productTemplate ] , mod (l ^. typesNS) (typeImports l) typesTemplate , mod (l ^. waitersNS) (waiterImports l) waitersTemplate ] ++ map op (l ^.. operations . each) , mod (l ^. libraryNS) mempty tocTemplate ] ] ] , dir "test" [ mod "Main" (testImports l) testsTemplate , dir "Test" [ dir "AWS" [ touch (l ^. serviceAbbrev <> ".hs") , dir svc [ touch "Internal.hs" ] , dir "Gen" [ mod (l ^. fixturesNS) (fixtureImports l) fixturesTemplate ] ] ] ] , dir "fixture" $ concatMap fixture (l ^.. operations . each) , file (lib <.> "cabal") cabalTemplate , file "README.md" readmeTemplate ] svc, lib :: Path svc = fromText (l ^. serviceAbbrev) lib = fromText (l ^. libraryName) op :: Operation Identity SData a -> DirTree (Either Error Touch) op = write . operation' l operationTemplate fixture :: Operation Identity SData a -> [DirTree (Either Error Touch)] fixture o = [ touch (n <> ".yaml") , touch (n <> "Response.proto") ] where n = typeId (_opName o) mod :: NS -> [NS] -> Template -> DirTree (Either Error Touch) mod n is t = write . module' n is t . pure $ toJSON l file :: Path -> Template -> DirTree (Either Error Touch) file p t = write $ file' p t (pure env) env :: Value env = toJSON l operation' :: Library -> Template -> Operation Identity SData a -> DirTree (Either Error Rendered) operation' l t o = module' n is t $ do x <- JS.objectErr (show n) o y <- JS.objectErr "metadata" (toJSON m) return $! Map.insert "operationUrl" (toJSON u) (y <> x) where n = operationNS (l ^. libraryNS) (o ^. opName) m = l ^. metadata u = l ^. operationUrl is = operationImports l o module' :: ToJSON a => NS -> [NS] -> Template -> Either Error a -> DirTree (Either Error Rendered) module' ns is t f = file' (filename $ nsToPath ns) t $ do x <- f >>= JS.objectErr (show ns) return $! x <> fromPairs [ "moduleName" .= ns , "moduleImports" .= is ] file' :: ToJSON a => Path -> Template -> Either Error a -> DirTree (Either Error Rendered) file' (encodeString -> p) t f = File p $ f >>= JS.objectErr p >>= fmapL LText.pack . eitherRender t dir :: Path -> [DirTree a] -> DirTree a dir p = Dir (encodeString p) write :: DirTree (Either e a) -> DirTree (Either e (Maybe a)) write = fmap (second Just) touch :: Text -> DirTree (Either e (Maybe a)) touch f = File (Text.unpack f) (Right Nothing)
fmapfmapfmap/amazonka
gen/src/Gen/Tree.hs
mpl-2.0
6,199
0
22
2,326
1,759
917
842
-1
-1
{-# LANGUAGE PatternGuards #-} module CPS.FromGHC where import CPS.Syntax hiding (Subst, renameIdBinder) import qualified GHC.Data as G import qualified GHC.Var as G import qualified GHC.Syntax as G import qualified GHC.Type as G import qualified GHC.Kind as G import GHC.Primitives import Name import Utilities -- FIXME: it might be easier to just permit unboxed tuples everywhere, including inside other unboxed tuples and on the left-hand-side of function arrows. -- The only wrinkle is that fromId may have to manufacture some fresh names. -- FIXME: we can even permit unboxed tuples as e.g. arguments to (,)! Of course, you can't use such types as arguments to polymorphic functions (ill-kinded type application). -- In GHC we would also have to be careful about what info tables such things get -- we can't reuse the polymorphic one (closure layout will change). -- NB: the input type must be of a TypeKind kind -- NB: the type returned is the *unlifted* version of the type -- NB: may return multiple types for unboxed tuples -- NB: do not look through newtypes here or we may produce an infinite type fromType :: G.Type -> [Type] fromType (G.ForAllTy _ ty) = fromType ty fromType ty = case G.splitTyConAppTy_maybe ty of Just (tc, [_, _]) | tc == G.funTyCon -> [PtrTy] | Just _ <- G.isEqHashTyCon tc -> [] | tc == G.pairTyCon -> [PtrTy] Just (tc, []) | tc == G.boolTyCon -> [PtrTy] | tc == G.intTyCon -> [PtrTy] | tc == G.intHashTyCon -> [IntHashTy] Just (tc, tys) | Just n <- G.isUnboxedTupleTyCon_maybe tc , n == length tys -> concatMap fromTypeThunky tys -- NB: this does not actualy permit nested unboxed tuples, the list is needed if some components are void Just _ -> error "fromType: unrecognised explicit TyCon" Nothing -> case G.typeKind ty of G.LiftedTypeKind -> [PtrTy] _ -> error "fromType: non-TyCon non-lifted type" -- GHC currently has a bug where you can lambda-abstract over type variables of non-lifted kind. -- This is a serious problem because there is no way to reliably determine the representation of -- that type variable. This becomes explicit in our translation. -- -- FIXME: we should allow such types in *result* positions (e.g. for error :: forall (a :: OPEN). a). -- In this case, we can return [] on the understanding that such functions can never return. -- NB: the input type must be lifted fromLiftedType :: G.Type -> Type fromLiftedType ty = case fromType ty of [ty] -> ty _ -> error "fromLiftedType: non-unary input type - must be an unboxed tuple or void unlifted type" -- NB: the input type must be lifted fromLiftedTypeThunky :: G.Type -> Type fromLiftedTypeThunky ty = case fromTypeThunky ty of [ty] -> ty _ -> error "fromLiftedTypeThunky: non-unary input type - must be an unboxed tuple or void unlifted type" fromTypeThunky :: G.Type -> [Type] fromTypeThunky ty | G.typeKind ty /= G.LiftedTypeKind = fromType ty | otherwise = [PtrTy] -- We don't have to worry about occurrences of unboxed tuple Ids, but void Ids may occur fromId :: G.Id -> [Id] fromId x = case fromTypeThunky (G.idType x) of [] -> [] [ty] -> [Id { idName = G.idName x, idType = ty }] _ -> error "fromId: unboxed tuple Ids are not present in the input" -- NB: the type of the input Id must be lifted fromLiftedId :: G.Id -> Id fromLiftedId x = case fromId x of [x] -> x _ -> error "fromLiftedId: void input Id" type Context = (UniqueSupply, InScopeSet) type Subst = UniqueMap (Maybe Trivial) type In a = (Subst, a) instance Uniqueable G.Id where getUnique = getUnique . G.idName rename :: Subst -> G.Id -> Maybe Trivial rename subst x = findUniqueWithDefault (error "rename: out of scope") x subst renameLifted :: Subst -> G.Id -> Trivial renameLifted subst x = case rename subst x of Just t -> t Nothing -> error "renameLifted: binding not lifted" renameIdBinder :: Context -> Subst -> G.Id -> (Context, Subst, Maybe Id) renameIdBinder ids subst x = (ids', insertUniqueMap x (fmap IdOcc mb_x') subst, mb_x') where (ids', mb_x') = renameIdBinder' ids x renameIdBinder' :: Context -> G.Id -> (Context, Maybe Id) renameIdBinder' (ids, iss) x = case fromTypeThunky (G.idType x) of [] -> ((ids, iss), Nothing) [ty] -> ((ids, iss'), Just x') where n = G.idName x (iss', n') = uniqAwayName iss n x' = Id { idName = n', idType = ty } -- NB: don't need to rename types _ -> error "renameIdBinder': unboxed tuple binders are always dead" --renameBinders :: Context -> Subst -> [G.Id] -> (Context, Subst, [Maybe Id]) --renameBinders ids subst = third3 catMaybes . mapAccumL (\(ids, subst) x -> case renameBinder ids subst x of (ids, subst, mb_x') -> ((ids, subst, mb_x'))) (ids, subst) freshId :: Context -> String -> Type -> (Context, Id) freshId (ids, iss) s ty = ((ids', iss'), Id { idName = n', idType = ty }) where (ids', n) = freshName ids s (iss', n') = uniqAwayName iss n freshCoId :: Context -> String -> CoType -> (Context, CoId) freshCoId (ids, iss) s nty = ((ids', iss'), CoId { coIdName = n', coIdType = nty }) where (ids', n) = freshName ids s (iss', n') = uniqAwayName iss n freshs :: (Context -> String -> a -> (Context, b)) -> Context -> String -> [a] -> (Context, [b]) freshs fresh ids s tys = mapAccumL (\ids ty -> fresh ids s ty) ids tys -- fromTerm ids (subst, e) u -- -- NB: -- fromType (termType e) `allR subType` coIdType u -- FVs are available in the environment of the output with their *thunky* types data Kont = Unknown CoId | Known [Type] (Context -> [Trivial] -> Term) returnToKont :: Kont -> Context -> [Trivial] -> Term returnToKont (Unknown u) _ ts = Term [] [] (Return u ts) returnToKont (Known _ f) ids ts = f ids ts bindKont :: Kont -> Context -> (Context -> CoId -> Term) -> Term bindKont (Unknown u) ids nested = nested ids u bindKont (Known tys f) ids0 nested = addContinuation u k (nested ids2 u) -- FIXME: should tys come from bindCont caller? (Casts) where k = Continuation xs (f ids2 (map IdOcc xs)) (ids1, u) = freshCoId ids0 "u" (continuationCoType k) (ids2, xs) = freshs freshId ids1 "x" tys fromTerm :: Context -> In G.Term -> Kont -> Term fromTerm ids (subst, G.Var x) u | G.typeKind (G.idType x) /= G.LiftedTypeKind = returnToKont u ids (maybeToList (rename subst x)) | otherwise = bindKont u ids $ \_ u -> Term [] [] (Call (renameLifted subst x) (Enter []) [u]) fromTerm ids0 (subst, G.Value v) u = case v of G.Coercion _ -> returnToKont u ids0 [] G.Lambda (G.ATyVar _) e -> fromTerm ids0 (subst, e) u G.Lambda (G.AnId x) e -> addFunction y f (returnToKont u ids1 [IdOcc y]) where (ids1, y) = freshId ids0 "fun" PtrTy (ids2, subst', mb_x') = renameIdBinder ids1 subst x (ids3, w) = freshCoId ids2 "w" (fromType (G.termType e)) f = Function (maybeToList mb_x') [w] (fromTerm ids3 (subst', e) (Unknown w)) G.Data dc _ _ xs | Just _ <- G.isUnboxedTupleTyCon_maybe (G.dataConTyCon dc) -> returnToKont u ids0 (mapMaybe (rename subst) xs) | otherwise -> addFunction y f (returnToKont u ids1 [IdOcc y]) where dcs = G.dataConFamily dc ListPoint tys_lefts _tys_here tys_rights = fmap (concatMap fromTypeThunky . G.dataConFields) $ locateListPoint (==dc) dcs f = Box tys_lefts (mapMaybe (rename subst) xs) tys_rights (ids1, y) = freshId ids0 "data" PtrTy G.Literal l -> returnToKont u ids0 [Literal l] fromTerm ids (subst, G.App e x) u = fromTerm ids (subst, e) $ Known (fromType (G.termType e)) $ \ids [t] -> bindKont u ids $ \_ u -> Term [] [] (Call t (Enter (maybeToList (rename subst x))) [u]) fromTerm ids (subst, G.TyApp e _) u = fromTerm ids (subst, e) u fromTerm ids (subst, G.PrimOp pop es) u = foldr (\e known ids ts -> fromTerm ids (subst, e) $ Known (fromType (G.termType e)) $ \ids extra_ts -> known ids (ts ++ extra_ts)) (\ids ts -> bindKont u ids $ \_ u -> Term [] [] (Call (PrimOp pop) (Enter ts) [u])) es ids [] fromTerm ids0 (subst, G.Case e _ x alts) u | [(G.DataAlt dc _ xs, e_alt)] <- alts , Just _ <- G.isUnboxedTupleTyCon_maybe (G.dataConTyCon dc) , let combine [] [] = [] combine (x:xs) ts = case fromTypeThunky (G.idType x) of [] -> (x, Nothing) : combine xs ts [_] | (t:ts) <- ts -> (x, Just t) : combine xs ts _ -> error "combine: binder, but no matching trivials" combine [] (_:_) = error "combine: not enough trivials" = fromTerm ids0 (subst, e) $ Known (fromType (G.idType x)) $ \ids0 ts -> fromTerm ids0 (foldr (uncurry insertUniqueMap) subst (combine xs ts), e_alt) u | otherwise = fromTerm ids0 (subst, e) $ Known (fromType (G.idType x)) $ \ids0 ts -> let subst' = insertUniqueMap x (if G.typeKind (G.idType x) /= G.LiftedTypeKind then listToMaybe ts else Just (case ts of [t] -> t)) subst in case alts of [(G.DefaultAlt, e)] -> fromTerm ids0 (subst', e) u ((G.DefaultAlt, e_def):(G.DataAlt dc _ xs, e):alts) | [t] <- ts -> fromAlts (selectData t) ids0 subst' (Just e_def) ((dc, (xs, e)):[(dc, (xs, e)) | (G.DataAlt dc _ xs, e) <- alts]) u ((G.DataAlt dc _ xs, e):alts) | [t] <- ts -> fromAlts (selectData t) ids0 subst' Nothing ((dc, (xs, e)):[(dc, (xs, e)) | (G.DataAlt dc _ xs, e) <- alts]) u ((G.DefaultAlt, e_def):(G.LiteralAlt l, e):alts) | [t] <- ts -> fromAlts (selectLiteral t) ids0 subst' (Just e_def) ((l, ([], e)):[(l, ([], e)) | (G.LiteralAlt l, e) <- alts]) u ((G.LiteralAlt l, e):alts) | [t] <- ts -> fromAlts (selectLiteral t) ids0 subst' Nothing ((l, ([], e)):[(l, ([], e)) | (G.LiteralAlt l, e) <- alts]) u fromTerm ids0 (subst0, G.LetRec xes e) u = e' where (ids3, subst2, e') = foldr (\(x, e) (ids1, subst0, e') -> let (ids2, subst1, Just x') = renameIdBinder ids1 subst0 x ty = fromLiftedType (G.termType e) (ids3, w) = freshCoId ids2 "w" [ty] in (ids2, subst1, addFunction x' (Function [] [w] (fromTerm ids3 (subst2, e) (Known [ty] $ \_ [t] -> Term [] [] (Call (Update [] (coIdType w) []) (Enter [IdOcc x', t]) [w])))) e')) (ids0, subst0, fromTerm ids3 (subst2, e) u) xes fromTerm ids (subst, G.Cast e _) u = fromTerm ids (subst, e) u -- FIXME: I'm a bit worried about the type-precision consequences of this -- dropping casts may kill typeability of the output! -- -- Consider: -- \(y :: Int) -> let x :: F Int = (\(x :: Int) -> x) |> (co :: (Int -> Int) ~ F Int) -- in x |> (sym co) y -- -- Which would naively translate to: -- let x :: * = \(x :: *) -> x -- in x y -- -- Which is ill typed. -- -- How about in CPS-core? (NB: I'm using * to stand for the evaluated form of the lifted type Int) -- let x :: <> -> * = \<> (k :: *) -> let xv :: (<> -> *) -> * = \x k -> x <> k -- in k xv -- l :: (<> -> *) -> * = \(xv :: (<> -> *) -> *) -> xv y halt -- in x l -- -- This is STILL ill typed -- look at the (x l) application, where l demands more than the x can supply. -- -- Even worse, since x is hidden by a lambda: -- \(y :: Int) -> let x :: F Int = (\(x :: Int) -> x) |> (co :: (Int -> Int) ~ F Int) -- in (\(x :: F Int) -> x |> (sym co) y) x -- -- One other thing we have to be careful about is recursive types: -- f :: Rec = (\(x :: Int) -> f) |> (nt_ax :: (Int -> Rec) ~ Rec) -- -- Translating to: -- f :: * = (\(x :: *) -> f) :: * -> * -- -- From this, it is clear that we could -- but *should not* -- update let-binder types from the type of -- their RHSs, since we can iterate this forever and build infinite arbitrarily large types. selectData :: Trivial -> CoId -> [(G.DataCon, CoId)] -> Term selectData t u_def dcs_us = Term [] [] (Call t Unbox [lookup dc dcs_us `orElse` u_def | dc <- dc_family]) where dc_family = G.dataConFamily (fst (head dcs_us)) selectLiteral :: Trivial -> CoId -> [(Literal, CoId)] -> Term selectLiteral t = error "FIXME: selectLiteral (perhaps via a primitive Id we can call)" t typeFromVar :: G.Var -> [Type] typeFromVar (G.AnId x) = fromTypeThunky (G.idType x) typeFromVar (G.ATyVar _) = [] fromVar :: G.Var -> [Id] fromVar (G.AnId x) = fromId x fromVar (G.ATyVar _) = [] fromAlts :: (CoId -> [(a, CoId)] -> Term) -> Context -> Subst -> Maybe G.Term -> [(a, ([G.Id], G.Term))] -> Kont -> Term fromAlts select ids0 subst mb_def selectors_alts u = bindKont u ids0 fromAlts' where fromAlts' ids0 u = e2 where e0 = select (mb_def_u `orElse` error "FIXME: add an unreachable fallback") selector_us ((ids1, mb_def_u), e1) = case mb_def of Nothing -> ((ids0, Nothing), e0) Just e -> ((ids1, Just w), addContinuation w (Continuation [] (fromTerm ids2 (subst, e) (Unknown u))) e0) where (ids1, w) = freshCoId ids0 "w" [] ((ids2, e2), selector_us) = mapAccumL (\(ids1, e1) (selector, (xs, e)) -> let k = Continuation (catMaybes mb_ys) (fromTerm ids2 (subst', e) (Unknown u)) (ids2a, w) = freshCoId ids1 "w" (continuationCoType k) (ids2b, subst', mb_ys) = renameBinders renameIdBinder ids2a subst xs in ((ids2b, addContinuation w k e1), (selector, w))) (ids1, e1) selectors_alts
beni55/cps-core
CPS/FromGHC.hs
bsd-3-clause
14,206
0
27
3,983
4,612
2,451
2,161
169
14
import Diagrams.Prelude hiding (doRender) import Diagrams.Backend.OpenGL import Diagrams.Backend.OpenGL.CmdLine main :: IO () main = do defaultMain d v1 :: R2 v1 = r2 (0,1) v2 :: R2 v2 = r2 (0.5,-0.5) p :: Path R2 p = pathFromTrail . closeTrail $ fromOffsets [v1,v2] p2_ :: Path R2 p2_ = pathFromTrail . closeTrail $ fromOffsets [v2, v1] d :: Diagram OpenGL R2 d = stroke p # fc green <> (stroke p2_ # lc blue # fc cyan # translate (r2 (0,0.5)))
mbernat/diagrams-opengl
examples/polygons.hs
bsd-3-clause
459
0
11
94
214
114
100
17
1
-- Copyright (c) 2014-present, Facebook, Inc. -- All rights reserved. -- -- This source code is distributed under the terms of a BSD license, -- found in the LICENSE file. {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} module SleepDataSource ( sleep, ) where import Haxl.Prelude import Prelude () import Haxl.Core import Haxl.DataSource.ConcurrentIO import Control.Concurrent import Data.Hashable import Data.Typeable sleep :: Int -> GenHaxl u Int sleep n = dataFetch (Sleep n) data Sleep deriving Typeable instance ConcurrentIO Sleep where data ConcurrentIOReq Sleep a where Sleep :: Int -> ConcurrentIOReq Sleep Int performIO (Sleep n) = threadDelay (n*1000) >> return n deriving instance Eq (ConcurrentIOReq Sleep a) deriving instance Show (ConcurrentIOReq Sleep a) instance ShowP (ConcurrentIOReq Sleep) where showp = show instance Hashable (ConcurrentIOReq Sleep a) where hashWithSalt s (Sleep n) = hashWithSalt s n
simonmar/Haxl
tests/SleepDataSource.hs
bsd-3-clause
1,179
0
9
186
248
137
111
-1
-1
{-# LANGUAGE CPP #-} module TcSimplify( simplifyInfer, pickQuantifiablePreds, growThetaTyVars, simplifyAmbiguityCheck, simplifyDefault, simplifyTop, simplifyInteractive, solveWantedsTcM, -- For Rules we need these twoo solveWanteds, runTcS ) where #include "HsVersions.h" import Bag import Class ( classKey ) import Class ( Class ) import DynFlags ( ExtensionFlag( Opt_AllowAmbiguousTypes , Opt_FlexibleContexts ) ) import ErrUtils ( emptyMessages ) import FastString import Id ( idType ) import Inst import Kind ( isKind, defaultKind_maybe ) import ListSetOps import Maybes ( isNothing ) import Name import Outputable import PrelInfo import PrelNames import TcErrors import TcEvidence import TcInteract import TcMType as TcM import TcRnMonad as TcRn import TcSMonad as TcS import TcType import TrieMap () -- DV: for now import TyCon ( isTypeFamilyTyCon ) import Type ( classifyPredType, isIPClass, PredTree(..) , getClassPredTys_maybe, EqRel(..) ) import Unify ( tcMatchTy ) import Util import Var import VarSet import Control.Monad ( unless ) import Data.List ( partition ) {- ********************************************************************************* * * * External interface * * * ********************************************************************************* -} simplifyTop :: WantedConstraints -> TcM (Bag EvBind) -- Simplify top-level constraints -- Usually these will be implications, -- but when there is nothing to quantify we don't wrap -- in a degenerate implication, so we do that here instead simplifyTop wanteds = do { traceTc "simplifyTop {" $ text "wanted = " <+> ppr wanteds ; ((final_wc, unsafe_ol), binds1) <- runTcS $ simpl_top wanteds ; traceTc "End simplifyTop }" empty ; traceTc "reportUnsolved {" empty ; binds2 <- reportUnsolved final_wc ; traceTc "reportUnsolved }" empty ; traceTc "reportUnsolved (unsafe overlapping) {" empty ; unless (isEmptyCts unsafe_ol) $ do { -- grab current error messages and clear, warnAllUnsolved will -- update error messages which we'll grab and then restore saved -- messges. ; errs_var <- getErrsVar ; saved_msg <- TcRn.readTcRef errs_var ; TcRn.writeTcRef errs_var emptyMessages ; warnAllUnsolved $ WC { wc_simple = unsafe_ol , wc_insol = emptyCts , wc_impl = emptyBag } ; whyUnsafe <- fst <$> TcRn.readTcRef errs_var ; TcRn.writeTcRef errs_var saved_msg ; recordUnsafeInfer whyUnsafe } ; traceTc "reportUnsolved (unsafe overlapping) }" empty ; return (binds1 `unionBags` binds2) } type SafeOverlapFailures = Cts -- ^ See Note [Safe Haskell Overlapping Instances Implementation] type FinalConstraints = (WantedConstraints, SafeOverlapFailures) simpl_top :: WantedConstraints -> TcS FinalConstraints -- See Note [Top-level Defaulting Plan] simpl_top wanteds = do { wc_first_go <- nestTcS (solveWantedsAndDrop wanteds) -- This is where the main work happens ; wc_final <- try_tyvar_defaulting wc_first_go ; unsafe_ol <- getSafeOverlapFailures ; return (wc_final, unsafe_ol) } where try_tyvar_defaulting :: WantedConstraints -> TcS WantedConstraints try_tyvar_defaulting wc | isEmptyWC wc = return wc | otherwise = do { free_tvs <- TcS.zonkTyVarsAndFV (tyVarsOfWC wc) ; let meta_tvs = varSetElems (filterVarSet isMetaTyVar free_tvs) -- zonkTyVarsAndFV: the wc_first_go is not yet zonked -- filter isMetaTyVar: we might have runtime-skolems in GHCi, -- and we definitely don't want to try to assign to those! ; meta_tvs' <- mapM defaultTyVar meta_tvs -- Has unification side effects ; if meta_tvs' == meta_tvs -- No defaulting took place; -- (defaulting returns fresh vars) then try_class_defaulting wc else do { wc_residual <- nestTcS (solveWantedsAndDrop wc) -- See Note [Must simplify after defaulting] ; try_class_defaulting wc_residual } } try_class_defaulting :: WantedConstraints -> TcS WantedConstraints try_class_defaulting wc | isEmptyWC wc = return wc | otherwise -- See Note [When to do type-class defaulting] = do { something_happened <- applyDefaultingRules wc -- See Note [Top-level Defaulting Plan] ; if something_happened then do { wc_residual <- nestTcS (solveWantedsAndDrop wc) ; try_class_defaulting wc_residual } else return wc } {- Note [When to do type-class defaulting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In GHC 7.6 and 7.8.2, we did type-class defaulting only if insolubleWC was false, on the grounds that defaulting can't help solve insoluble constraints. But if we *don't* do defaulting we may report a whole lot of errors that would be solved by defaulting; these errors are quite spurious because fixing the single insoluble error means that defaulting happens again, which makes all the other errors go away. This is jolly confusing: Trac #9033. So it seems better to always do type-class defaulting. However, always doing defaulting does mean that we'll do it in situations like this (Trac #5934): run :: (forall s. GenST s) -> Int run = fromInteger 0 We don't unify the return type of fromInteger with the given function type, because the latter involves foralls. So we're left with (Num alpha, alpha ~ (forall s. GenST s) -> Int) Now we do defaulting, get alpha := Integer, and report that we can't match Integer with (forall s. GenST s) -> Int. That's not totally stupid, but perhaps a little strange. Another potential alternative would be to suppress *all* non-insoluble errors if there are *any* insoluble errors, anywhere, but that seems too drastic. Note [Must simplify after defaulting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We may have a deeply buried constraint (t:*) ~ (a:Open) which we couldn't solve because of the kind incompatibility, and 'a' is free. Then when we default 'a' we can solve the constraint. And we want to do that before starting in on type classes. We MUST do it before reporting errors, because it isn't an error! Trac #7967 was due to this. Note [Top-level Defaulting Plan] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We have considered two design choices for where/when to apply defaulting. (i) Do it in SimplCheck mode only /whenever/ you try to solve some simple constraints, maybe deep inside the context of implications. This used to be the case in GHC 7.4.1. (ii) Do it in a tight loop at simplifyTop, once all other constraint has finished. This is the current story. Option (i) had many disadvantages: a) First it was deep inside the actual solver, b) Second it was dependent on the context (Infer a type signature, or Check a type signature, or Interactive) since we did not want to always start defaulting when inferring (though there is an exception to this see Note [Default while Inferring]) c) It plainly did not work. Consider typecheck/should_compile/DfltProb2.hs: f :: Int -> Bool f x = const True (\y -> let w :: a -> a w a = const a (y+1) in w y) We will get an implication constraint (for beta the type of y): [untch=beta] forall a. 0 => Num beta which we really cannot default /while solving/ the implication, since beta is untouchable. Instead our new defaulting story is to pull defaulting out of the solver loop and go with option (i), implemented at SimplifyTop. Namely: - First have a go at solving the residual constraint of the whole program - Try to approximate it with a simple constraint - Figure out derived defaulting equations for that simple constraint - Go round the loop again if you did manage to get some equations Now, that has to do with class defaulting. However there exists type variable /kind/ defaulting. Again this is done at the top-level and the plan is: - At the top-level, once you had a go at solving the constraint, do figure out /all/ the touchable unification variables of the wanted constraints. - Apply defaulting to their kinds More details in Note [DefaultTyVar]. Note [Safe Haskell Overlapping Instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In Safe Haskell, we apply an extra restriction to overlapping instances. The motive is to prevent untrusted code provided by a third-party, changing the behavior of trusted code through type-classes. This is due to the global and implicit nature of type-classes that can hide the source of the dictionary. Another way to state this is: if a module M compiles without importing another module N, changing M to import N shouldn't change the behavior of M. Overlapping instances with type-classes can violate this principle. However, overlapping instances aren't always unsafe. They are just unsafe when the most selected dictionary comes from untrusted code (code compiled with -XSafe) and overlaps instances provided by other modules. In particular, in Safe Haskell at a call site with overlapping instances, we apply the following rule to determine if it is a 'unsafe' overlap: 1) Most specific instance, I1, defined in an `-XSafe` compiled module. 2) I1 is an orphan instance or a MPTC. 3) At least one overlapped instance, Ix, is both: A) from a different module than I1 B) Ix is not marked `OVERLAPPABLE` This is a slightly involved heuristic, but captures the situation of an imported module N changing the behavior of existing code. For example, if condition (2) isn't violated, then the module author M must depend either on a type-class or type defined in N. Secondly, when should these heuristics be enforced? We enforced them when the type-class method call site is in a module marked `-XSafe` or `-XTrustworthy`. This allows `-XUnsafe` modules to operate without restriction, and for Safe Haskell inferrence to infer modules with unsafe overlaps as unsafe. One alternative design would be to also consider if an instance was imported as a `safe` import or not and only apply the restriction to instances imported safely. However, since instances are global and can be imported through more than one path, this alternative doesn't work. Note [Safe Haskell Overlapping Instances Implementation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ How is this implemented? It's compilcated! So we'll step through it all: 1) `InstEnv.lookupInstEnv` -- Performs instance resolution, so this is where we check if a particular type-class method call is safe or unsafe. We do this through the return type, `ClsInstLookupResult`, where the last parameter is a list of instances that are unsafe to overlap. When the method call is safe, the list is null. 2) `TcInteract.matchClassInst` -- This module drives the instance resolution / dictionary generation. The return type is `LookupInstResult`, which either says no instance matched, or one found and if it was a safe or unsafe overlap. 3) `TcInteract.doTopReactDict` -- Takes a dictionary / class constraint and tries to resolve it by calling (in part) `matchClassInst`. The resolving mechanism has a work list (of constraints) that it process one at a time. If the constraint can't be resolved, it's added to an inert set. When compiling an `-XSafe` or `-XTrustworthy` module we follow this approach as we know compilation should fail. These are handled as normal constraint resolution failures from here-on (see step 6). Otherwise, we may be inferring safety (or using `-fwarn-unsafe`) and compilation should succeed, but print warnings and/or mark the compiled module as `-XUnsafe`. In this case, we call `insertSafeOverlapFailureTcS` which adds the unsafe (but resolved!) constraint to the `inert_safehask` field of `InertCans`. 4) `TcSimplify.simpl_top` -- Top-level function for driving the simplifier for constraint resolution. Once finished, we call `getSafeOverlapFailures` to retrieve the list of overlapping instances that were successfully resolved, but unsafe. Remember, this is only applicable for generating warnings (`-fwarn-unsafe`) or inferring a module unsafe. `-XSafe` and `-XTrustworthy` cause compilation failure by not resolving the unsafe constraint at all. `simpl_top` returns a list of unresolved constraints (all types), and resolved (but unsafe) resolved dictionary constraints. 5) `TcSimplify.simplifyTop` -- Is the caller of `simpl_top`. For unresolved constraints, it calls `TcErrors.reportUnsolved`, while for unsafe overlapping instance constraints, it calls `TcErrors.warnAllUnsolved`. Both functions convert constraints into a warning message for the user. 6) `TcErrors.*Unsolved` -- Generates error messages for conastraints by actually calling `InstEnv.lookupInstEnv` again! Yes, confusing, but all we know is the constraint that is unresolved or unsafe. For dictionary, this is know we need a dictionary of type C, but not what instances are available and how they overlap. So we once again call `lookupInstEnv` to figure that out so we can generate a helpful error message. 7) `TcSimplify.simplifyTop` -- In the case of `warnAllUnsolved` for resolved, but unsafe dictionary constraints, we collect the generated warning message (pop it) and call `TcRnMonad.recordUnsafeInfer` to mark the module we are compiling as unsafe, passing the warning message along as the reason. 8) `TcRnMonad.recordUnsafeInfer` -- Save the unsafe result and reason in an IORef called `tcg_safeInfer`. 9) `HscMain.tcRnModule'` -- Reads `tcg_safeInfer` after type-checking, calling `HscMain.markUnsafeInfer` (passing the reason along) when safe-inferrence failed. -} ------------------ simplifyAmbiguityCheck :: Type -> WantedConstraints -> TcM () simplifyAmbiguityCheck ty wanteds = do { traceTc "simplifyAmbiguityCheck {" (text "type = " <+> ppr ty $$ text "wanted = " <+> ppr wanteds) ; ((final_wc, _), _binds) <- runTcS $ simpl_top wanteds ; traceTc "End simplifyAmbiguityCheck }" empty -- Normally report all errors; but with -XAllowAmbiguousTypes -- report only insoluble ones, since they represent genuinely -- inaccessible code ; allow_ambiguous <- xoptM Opt_AllowAmbiguousTypes ; traceTc "reportUnsolved(ambig) {" empty ; unless (allow_ambiguous && not (insolubleWC final_wc)) (discardResult (reportUnsolved final_wc)) ; traceTc "reportUnsolved(ambig) }" empty ; return () } ------------------ simplifyInteractive :: WantedConstraints -> TcM (Bag EvBind) simplifyInteractive wanteds = traceTc "simplifyInteractive" empty >> simplifyTop wanteds ------------------ simplifyDefault :: ThetaType -- Wanted; has no type variables in it -> TcM () -- Succeeds iff the constraint is soluble simplifyDefault theta = do { traceTc "simplifyInteractive" empty ; wanted <- newWanteds DefaultOrigin theta ; unsolved <- solveWantedsTcM wanted ; traceTc "reportUnsolved {" empty -- See Note [Deferring coercion errors to runtime] ; reportAllUnsolved unsolved ; traceTc "reportUnsolved }" empty ; return () } {- ********************************************************************************* * * * Inference * * *********************************************************************************** Note [Inferring the type of a let-bound variable] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f x = rhs To infer f's type we do the following: * Gather the constraints for the RHS with ambient level *one more than* the current one. This is done by the call pushLevelAndCaptureConstraints (tcMonoBinds...) in TcBinds.tcPolyInfer * Call simplifyInfer to simplify the constraints and decide what to quantify over. We pass in the level used for the RHS constraints, here called rhs_tclvl. This ensures that the implication constraint we generate, if any, has a strictly-increased level compared to the ambient level outside the let binding. -} simplifyInfer :: TcLevel -- Used when generating the constraints -> Bool -- Apply monomorphism restriction -> [(Name, TcTauType)] -- Variables to be generalised, -- and their tau-types -> WantedConstraints -> TcM ([TcTyVar], -- Quantify over these type variables [EvVar], -- ... and these constraints (fully zonked) Bool, -- The monomorphism restriction did something -- so the results type is not as general as -- it could be TcEvBinds) -- ... binding these evidence variables simplifyInfer rhs_tclvl apply_mr name_taus wanteds | isEmptyWC wanteds = do { gbl_tvs <- tcGetGlobalTyVars ; qtkvs <- quantifyTyVars gbl_tvs (tyVarsOfTypes (map snd name_taus)) ; traceTc "simplifyInfer: empty WC" (ppr name_taus $$ ppr qtkvs) ; return (qtkvs, [], False, emptyTcEvBinds) } | otherwise = do { traceTc "simplifyInfer {" $ vcat [ ptext (sLit "binds =") <+> ppr name_taus , ptext (sLit "rhs_tclvl =") <+> ppr rhs_tclvl , ptext (sLit "apply_mr =") <+> ppr apply_mr , ptext (sLit "(unzonked) wanted =") <+> ppr wanteds ] -- Historical note: Before step 2 we used to have a -- HORRIBLE HACK described in Note [Avoid unecessary -- constraint simplification] but, as described in Trac -- #4361, we have taken in out now. That's why we start -- with step 2! -- Step 2) First try full-blown solving -- NB: we must gather up all the bindings from doing -- this solving; hence (runTcSWithEvBinds ev_binds_var). -- And note that since there are nested implications, -- calling solveWanteds will side-effect their evidence -- bindings, so we can't just revert to the input -- constraint. ; ev_binds_var <- TcM.newTcEvBinds ; wanted_transformed_incl_derivs <- setTcLevel rhs_tclvl $ runTcSWithEvBinds ev_binds_var (solveWanteds wanteds) ; wanted_transformed_incl_derivs <- TcM.zonkWC wanted_transformed_incl_derivs -- Step 4) Candidates for quantification are an approximation of wanted_transformed -- NB: Already the fixpoint of any unifications that may have happened -- NB: We do not do any defaulting when inferring a type, this can lead -- to less polymorphic types, see Note [Default while Inferring] ; tc_lcl_env <- TcRn.getLclEnv ; null_ev_binds_var <- TcM.newTcEvBinds ; let wanted_transformed = dropDerivedWC wanted_transformed_incl_derivs ; quant_pred_candidates -- Fully zonked <- if insolubleWC wanted_transformed_incl_derivs then return [] -- See Note [Quantification with errors] -- NB: must include derived errors in this test, -- hence "incl_derivs" else do { let quant_cand = approximateWC wanted_transformed meta_tvs = filter isMetaTyVar (varSetElems (tyVarsOfCts quant_cand)) ; gbl_tvs <- tcGetGlobalTyVars -- Miminise quant_cand. We are not interested in any evidence -- produced, because we are going to simplify wanted_transformed -- again later. All we want here is the predicates over which to -- quantify. -- -- If any meta-tyvar unifications take place (unlikely), we'll -- pick that up later. ; WC { wc_simple = simples } <- setTcLevel rhs_tclvl $ runTcSWithEvBinds null_ev_binds_var $ do { mapM_ (promoteAndDefaultTyVar rhs_tclvl gbl_tvs) meta_tvs -- See Note [Promote _and_ default when inferring] ; solveSimpleWanteds quant_cand } ; return [ ctEvPred ev | ct <- bagToList simples , let ev = ctEvidence ct , isWanted ev ] } -- NB: quant_pred_candidates is already fully zonked -- Decide what type variables and constraints to quantify ; zonked_taus <- mapM (TcM.zonkTcType . snd) name_taus ; let zonked_tau_tvs = tyVarsOfTypes zonked_taus ; (qtvs, bound_theta, mr_bites) <- decideQuantification apply_mr quant_pred_candidates zonked_tau_tvs -- Emit an implication constraint for the -- remaining constraints from the RHS ; bound_ev_vars <- mapM TcM.newEvVar bound_theta ; let skol_info = InferSkol [ (name, mkSigmaTy [] bound_theta ty) | (name, ty) <- name_taus ] -- Don't add the quantified variables here, because -- they are also bound in ic_skols and we want them -- to be tidied uniformly implic = Implic { ic_tclvl = rhs_tclvl , ic_skols = qtvs , ic_no_eqs = False , ic_given = bound_ev_vars , ic_wanted = wanted_transformed , ic_status = IC_Unsolved , ic_binds = ev_binds_var , ic_info = skol_info , ic_env = tc_lcl_env } ; emitImplication implic -- Promote any type variables that are free in the inferred type -- of the function: -- f :: forall qtvs. bound_theta => zonked_tau -- These variables now become free in the envt, and hence will show -- up whenever 'f' is called. They may currently at rhs_tclvl, but -- they had better be unifiable at the outer_tclvl! -- Example: envt mentions alpha[1] -- tau_ty = beta[2] -> beta[2] -- consraints = alpha ~ [beta] -- we don't quantify over beta (since it is fixed by envt) -- so we must promote it! The inferred type is just -- f :: beta -> beta ; outer_tclvl <- TcRn.getTcLevel ; zonked_tau_tvs <- TcM.zonkTyVarsAndFV zonked_tau_tvs -- decideQuantification turned some meta tyvars into -- quantified skolems, so we have to zonk again ; let phi_tvs = tyVarsOfTypes bound_theta `unionVarSet` zonked_tau_tvs promote_tvs = varSetElems (closeOverKinds phi_tvs `delVarSetList` qtvs) ; runTcSWithEvBinds null_ev_binds_var $ -- runTcS just to get the types right :-( mapM_ (promoteTyVar outer_tclvl) promote_tvs -- All done! ; traceTc "} simplifyInfer/produced residual implication for quantification" $ vcat [ ptext (sLit "quant_pred_candidates =") <+> ppr quant_pred_candidates , ptext (sLit "zonked_taus") <+> ppr zonked_taus , ptext (sLit "zonked_tau_tvs=") <+> ppr zonked_tau_tvs , ptext (sLit "promote_tvs=") <+> ppr promote_tvs , ptext (sLit "bound_theta =") <+> vcat [ ppr v <+> dcolon <+> ppr (idType v) | v <- bound_ev_vars] , ptext (sLit "mr_bites =") <+> ppr mr_bites , ptext (sLit "qtvs =") <+> ppr qtvs , ptext (sLit "implic =") <+> ppr implic ] ; return ( qtvs, bound_ev_vars, mr_bites, TcEvBinds ev_binds_var) } {- ************************************************************************ * * Quantification * * ************************************************************************ Note [Deciding quantification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the monomorphism restriction does not apply, then we quantify as follows: * Take the global tyvars, and "grow" them using the equality constraints E.g. if x:alpha is in the environment, and alpha ~ [beta] (which can happen because alpha is untouchable here) then do not quantify over beta, because alpha fixes beta, and beta is effectively free in the environment too These are the mono_tvs * Take the free vars of the tau-type (zonked_tau_tvs) and "grow" them using all the constraints. These are tau_tvs_plus * Use quantifyTyVars to quantify over (tau_tvs_plus - mono_tvs), being careful to close over kinds, and to skolemise the quantified tyvars. (This actually unifies each quantifies meta-tyvar with a fresh skolem.) Result is qtvs. * Filter the constraints using pickQuantifyablePreds and the qtvs. We have to zonk the constraints first, so they "see" the freshly created skolems. If the MR does apply, mono_tvs includes all the constrained tyvars, and the quantified constraints are empty. -} decideQuantification :: Bool -- Apply monomorphism restriction -> [PredType] -> TcTyVarSet -- Constraints and type variables from RHS -> TcM ( [TcTyVar] -- Quantify over these tyvars (skolems) , [PredType] -- and this context (fully zonked) , Bool ) -- Did the MR bite? -- See Note [Deciding quantification] decideQuantification apply_mr constraints zonked_tau_tvs | apply_mr -- Apply the Monomorphism restriction = do { gbl_tvs <- tcGetGlobalTyVars ; let constrained_tvs = tyVarsOfTypes constraints mono_tvs = gbl_tvs `unionVarSet` constrained_tvs mr_bites = constrained_tvs `intersectsVarSet` zonked_tau_tvs ; qtvs <- quantifyTyVars mono_tvs zonked_tau_tvs ; traceTc "decideQuantification 1" (vcat [ppr constraints, ppr gbl_tvs, ppr mono_tvs, ppr qtvs]) ; return (qtvs, [], mr_bites) } | otherwise = do { gbl_tvs <- tcGetGlobalTyVars ; let mono_tvs = growThetaTyVars (filter isEqPred constraints) gbl_tvs tau_tvs_plus = growThetaTyVars constraints zonked_tau_tvs ; qtvs <- quantifyTyVars mono_tvs tau_tvs_plus ; constraints <- zonkTcThetaType constraints -- quantifyTyVars turned some meta tyvars into -- quantified skolems, so we have to zonk again ; theta <- pickQuantifiablePreds (mkVarSet qtvs) constraints ; let min_theta = mkMinimalBySCs theta -- See Note [Minimize by Superclasses] ; traceTc "decideQuantification 2" (vcat [ppr constraints, ppr gbl_tvs, ppr mono_tvs , ppr tau_tvs_plus, ppr qtvs, ppr min_theta]) ; return (qtvs, min_theta, False) } ------------------ pickQuantifiablePreds :: TyVarSet -- Quantifying over these -> TcThetaType -- Proposed constraints to quantify -> TcM TcThetaType -- A subset that we can actually quantify -- This function decides whether a particular constraint shoudl be -- quantified over, given the type variables that are being quantified pickQuantifiablePreds qtvs theta = do { flex_ctxt <- xoptM Opt_FlexibleContexts ; return (filter (pick_me flex_ctxt) theta) } where pick_me flex_ctxt pred = case classifyPredType pred of ClassPred cls tys | isIPClass cls -> True -- See note [Inheriting implicit parameters] | otherwise -> pick_cls_pred flex_ctxt tys EqPred ReprEq ty1 ty2 -> pick_cls_pred flex_ctxt [ty1, ty2] -- Representational equality is like a class constraint EqPred NomEq ty1 ty2 -> quant_fun ty1 || quant_fun ty2 IrredPred ty -> tyVarsOfType ty `intersectsVarSet` qtvs pick_cls_pred flex_ctxt tys = tyVarsOfTypes tys `intersectsVarSet` qtvs && (checkValidClsArgs flex_ctxt tys) -- Only quantify over predicates that checkValidType -- will pass! See Trac #10351. -- See Note [Quantifying over equality constraints] quant_fun ty = case tcSplitTyConApp_maybe ty of Just (tc, tys) | isTypeFamilyTyCon tc -> tyVarsOfTypes tys `intersectsVarSet` qtvs _ -> False ------------------ growThetaTyVars :: ThetaType -> TyVarSet -> TyVarSet -- See Note [Growing the tau-tvs using constraints] growThetaTyVars theta tvs | null theta = tvs | otherwise = transCloVarSet mk_next seed_tvs where seed_tvs = tvs `unionVarSet` tyVarsOfTypes ips (ips, non_ips) = partition isIPPred theta -- See note [Inheriting implicit parameters] mk_next :: VarSet -> VarSet -- Maps current set to newly-grown ones mk_next so_far = foldr (grow_one so_far) emptyVarSet non_ips grow_one so_far pred tvs | pred_tvs `intersectsVarSet` so_far = tvs `unionVarSet` pred_tvs | otherwise = tvs where pred_tvs = tyVarsOfType pred {- Note [Quantifying over equality constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Should we quantify over an equality constraint (s ~ t)? In general, we don't. Doing so may simply postpone a type error from the function definition site to its call site. (At worst, imagine (Int ~ Bool)). However, consider this forall a. (F [a] ~ Int) => blah Should we quantify over the (F [a] ~ Int). Perhaps yes, because at the call site we will know 'a', and perhaps we have instance F [Bool] = Int. So we *do* quantify over a type-family equality where the arguments mention the quantified variables. Note [Growing the tau-tvs using constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (growThetaTyVars insts tvs) is the result of extending the set of tyvars tvs using all conceivable links from pred E.g. tvs = {a}, preds = {H [a] b, K (b,Int) c, Eq e} Then growThetaTyVars preds tvs = {a,b,c} Notice that growThetaTyVars is conservative if v might be fixed by vs => v `elem` grow(vs,C) Note [Inheriting implicit parameters] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: f x = (x::Int) + ?y where f is *not* a top-level binding. From the RHS of f we'll get the constraint (?y::Int). There are two types we might infer for f: f :: Int -> Int (so we get ?y from the context of f's definition), or f :: (?y::Int) => Int -> Int At first you might think the first was better, because then ?y behaves like a free variable of the definition, rather than having to be passed at each call site. But of course, the WHOLE IDEA is that ?y should be passed at each call site (that's what dynamic binding means) so we'd better infer the second. BOTTOM LINE: when *inferring types* you must quantify over implicit parameters, *even if* they don't mention the bound type variables. Reason: because implicit parameters, uniquely, have local instance declarations. See the pickQuantifiablePreds. Note [Quantification with errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we find that the RHS of the definition has some absolutely-insoluble constraints, we abandon all attempts to find a context to quantify over, and instead make the function fully-polymorphic in whatever type we have found. For two reasons a) Minimise downstream errors b) Avoid spurious errors from this function But NB that we must include *derived* errors in the check. Example: (a::*) ~ Int# We get an insoluble derived error *~#, and we don't want to discard it before doing the isInsolubleWC test! (Trac #8262) Note [Default while Inferring] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Our current plan is that defaulting only happens at simplifyTop and not simplifyInfer. This may lead to some insoluble deferred constraints Example: instance D g => C g Int b constraint inferred = (forall b. 0 => C gamma alpha b) /\ Num alpha type inferred = gamma -> gamma Now, if we try to default (alpha := Int) we will be able to refine the implication to (forall b. 0 => C gamma Int b) which can then be simplified further to (forall b. 0 => D gamma) Finally we /can/ approximate this implication with (D gamma) and infer the quantified type: forall g. D g => g -> g Instead what will currently happen is that we will get a quantified type (forall g. g -> g) and an implication: forall g. 0 => (forall b. 0 => C g alpha b) /\ Num alpha which, even if the simplifyTop defaults (alpha := Int) we will still be left with an unsolvable implication: forall g. 0 => (forall b. 0 => D g) The concrete example would be: h :: C g a s => g -> a -> ST s a f (x::gamma) = (\_ -> x) (runST (h x (undefined::alpha)) + 1) But it is quite tedious to do defaulting and resolve the implication constraints and we have not observed code breaking because of the lack of defaulting in inference so we don't do it for now. Note [Minimize by Superclasses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we quantify over a constraint, in simplifyInfer we need to quantify over a constraint that is minimal in some sense: For instance, if the final wanted constraint is (Eq alpha, Ord alpha), we'd like to quantify over Ord alpha, because we can just get Eq alpha from superclass selection from Ord alpha. This minimization is what mkMinimalBySCs does. Then, simplifyInfer uses the minimal constraint to check the original wanted. Note [Avoid unecessary constraint simplification] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -------- NB NB NB (Jun 12) ------------- This note not longer applies; see the notes with Trac #4361. But I'm leaving it in here so we remember the issue.) ---------------------------------------- When inferring the type of a let-binding, with simplifyInfer, try to avoid unnecessarily simplifying class constraints. Doing so aids sharing, but it also helps with delicate situations like instance C t => C [t] where .. f :: C [t] => .... f x = let g y = ...(constraint C [t])... in ... When inferring a type for 'g', we don't want to apply the instance decl, because then we can't satisfy (C t). So we just notice that g isn't quantified over 't' and partition the constraints before simplifying. This only half-works, but then let-generalisation only half-works. ********************************************************************************* * * * Main Simplifier * * * *********************************************************************************** Note [Deferring coercion errors to runtime] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ While developing, sometimes it is desirable to allow compilation to succeed even if there are type errors in the code. Consider the following case: module Main where a :: Int a = 'a' main = print "b" Even though `a` is ill-typed, it is not used in the end, so if all that we're interested in is `main` it is handy to be able to ignore the problems in `a`. Since we treat type equalities as evidence, this is relatively simple. Whenever we run into a type mismatch in TcUnify, we normally just emit an error. But it is always safe to defer the mismatch to the main constraint solver. If we do that, `a` will get transformed into co :: Int ~ Char co = ... a :: Int a = 'a' `cast` co The constraint solver would realize that `co` is an insoluble constraint, and emit an error with `reportUnsolved`. But we can also replace the right-hand side of `co` with `error "Deferred type error: Int ~ Char"`. This allows the program to compile, and it will run fine unless we evaluate `a`. This is what `deferErrorsToRuntime` does. It does this by keeping track of which errors correspond to which coercion in TcErrors (with ErrEnv). TcErrors.reportTidyWanteds does not print the errors and does not fail if -fdefer-type-errors is on, so that we can continue compilation. The errors are turned into warnings in `reportUnsolved`. -} solveWantedsTcM :: [CtEvidence] -> TcM WantedConstraints -- Simplify the input constraints -- Discard the evidence binds -- Discards all Derived stuff in result -- Result is /not/ guaranteed zonked solveWantedsTcM wanted = do { (wanted1, _binds) <- runTcS (solveWantedsAndDrop (mkSimpleWC wanted)) ; return wanted1 } solveWantedsAndDrop :: WantedConstraints -> TcS WantedConstraints -- Since solveWanteds returns the residual WantedConstraints, -- it should always be called within a runTcS or something similar, -- Result is not zonked solveWantedsAndDrop wanted = do { wc <- solveWanteds wanted ; return (dropDerivedWC wc) } solveWanteds :: WantedConstraints -> TcS WantedConstraints -- so that the inert set doesn't mindlessly propagate. -- NB: wc_simples may be wanted /or/ derived now solveWanteds wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics }) = do { traceTcS "solveWanteds {" (ppr wc) -- Try the simple bit, including insolubles. Solving insolubles a -- second time round is a bit of a waste; but the code is simple -- and the program is wrong anyway, and we don't run the danger -- of adding Derived insolubles twice; see -- TcSMonad Note [Do not add duplicate derived insolubles] ; wc1 <- solveSimpleWanteds simples ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1 ; (floated_eqs, implics2) <- solveNestedImplications (implics `unionBags` implics1) ; final_wc <- simpl_loop 0 floated_eqs (WC { wc_simple = simples1, wc_impl = implics2 , wc_insol = insols `unionBags` insols1 }) ; bb <- getTcEvBindsMap ; traceTcS "solveWanteds }" $ vcat [ text "final wc =" <+> ppr final_wc , text "current evbinds =" <+> ppr (evBindMapBinds bb) ] ; return final_wc } simpl_loop :: Int -> Cts -> WantedConstraints -> TcS WantedConstraints simpl_loop n floated_eqs wc@(WC { wc_simple = simples, wc_insol = insols, wc_impl = implics }) | n > 10 = do { traceTcS "solveWanteds: loop!" (ppr wc); return wc } | no_floated_eqs = return wc -- Done! | otherwise = do { traceTcS "simpl_loop, iteration" (int n) -- solveSimples may make progress if either float_eqs hold ; (unifs_happened1, wc1) <- if no_floated_eqs then return (False, emptyWC) else reportUnifications $ solveSimpleWanteds (floated_eqs `unionBags` simples) -- Put floated_eqs first so they get solved first -- NB: the floated_eqs may include /derived/ equalities -- arising from fundeps inside an implication ; let WC { wc_simple = simples1, wc_insol = insols1, wc_impl = implics1 } = wc1 -- solveImplications may make progress only if unifs2 holds ; (floated_eqs2, implics2) <- if not unifs_happened1 && isEmptyBag implics1 then return (emptyBag, implics) else solveNestedImplications (implics `unionBags` implics1) ; simpl_loop (n+1) floated_eqs2 (WC { wc_simple = simples1, wc_impl = implics2 , wc_insol = insols `unionBags` insols1 }) } where no_floated_eqs = isEmptyBag floated_eqs solveNestedImplications :: Bag Implication -> TcS (Cts, Bag Implication) -- Precondition: the TcS inerts may contain unsolved simples which have -- to be converted to givens before we go inside a nested implication. solveNestedImplications implics | isEmptyBag implics = return (emptyBag, emptyBag) | otherwise = do { traceTcS "solveNestedImplications starting {" empty ; (floated_eqs_s, unsolved_implics) <- mapAndUnzipBagM solveImplication implics ; let floated_eqs = concatBag floated_eqs_s -- ... and we are back in the original TcS inerts -- Notice that the original includes the _insoluble_simples so it was safe to ignore -- them in the beginning of this function. ; traceTcS "solveNestedImplications end }" $ vcat [ text "all floated_eqs =" <+> ppr floated_eqs , text "unsolved_implics =" <+> ppr unsolved_implics ] ; return (floated_eqs, catBagMaybes unsolved_implics) } solveImplication :: Implication -- Wanted -> TcS (Cts, -- All wanted or derived floated equalities: var = type Maybe Implication) -- Simplified implication (empty or singleton) -- Precondition: The TcS monad contains an empty worklist and given-only inerts -- which after trying to solve this implication we must restore to their original value solveImplication imp@(Implic { ic_tclvl = tclvl , ic_binds = ev_binds , ic_skols = skols , ic_given = givens , ic_wanted = wanteds , ic_info = info , ic_status = status , ic_env = env }) | IC_Solved {} <- status = return (emptyCts, Just imp) -- Do nothing | otherwise -- Even for IC_Insoluble it is worth doing more work -- The insoluble stuff might be in one sub-implication -- and other unsolved goals in another; and we want to -- solve the latter as much as possible = do { inerts <- getTcSInerts ; traceTcS "solveImplication {" (ppr imp $$ text "Inerts" <+> ppr inerts) -- Solve the nested constraints ; (no_given_eqs, given_insols, residual_wanted) <- nestImplicTcS ev_binds tclvl $ do { given_insols <- solveSimpleGivens (mkGivenLoc tclvl info env) givens ; no_eqs <- getNoGivenEqs tclvl skols ; residual_wanted <- solveWanteds wanteds -- solveWanteds, *not* solveWantedsAndDrop, because -- we want to retain derived equalities so we can float -- them out in floatEqualities ; return (no_eqs, given_insols, residual_wanted) } ; (floated_eqs, residual_wanted) <- floatEqualities skols no_given_eqs residual_wanted ; let final_wanted = residual_wanted `addInsols` given_insols ; res_implic <- setImplicationStatus (imp { ic_no_eqs = no_given_eqs , ic_wanted = final_wanted }) ; evbinds <- getTcEvBindsMap ; traceTcS "solveImplication end }" $ vcat [ text "no_given_eqs =" <+> ppr no_given_eqs , text "floated_eqs =" <+> ppr floated_eqs , text "res_implic =" <+> ppr res_implic , text "implication evbinds = " <+> ppr (evBindMapBinds evbinds) ] ; return (floated_eqs, res_implic) } ---------------------- setImplicationStatus :: Implication -> TcS (Maybe Implication) -- Finalise the implication returned from solveImplication: -- * Set the ic_status field -- * Trim the ic_wanted field to remove Derived constraints -- Return Nothing if we can discard the implication altogether setImplicationStatus implic@(Implic { ic_binds = EvBindsVar ev_binds_var _ , ic_info = info , ic_wanted = wc , ic_given = givens }) | some_insoluble = return $ Just $ implic { ic_status = IC_Insoluble , ic_wanted = wc { wc_simple = pruned_simples , wc_insol = pruned_insols } } | some_unsolved = return $ Just $ implic { ic_status = IC_Unsolved , ic_wanted = wc { wc_simple = pruned_simples , wc_insol = pruned_insols } } | otherwise -- Everything is solved; look at the implications -- See Note [Tracking redundant constraints] = do { ev_binds <- TcS.readTcRef ev_binds_var ; let all_needs = neededEvVars ev_binds implic_needs dead_givens | warnRedundantGivens info = filterOut (`elemVarSet` all_needs) givens | otherwise = [] -- None to report final_needs = all_needs `delVarSetList` givens discard_entire_implication -- Can we discard the entire implication? = null dead_givens -- No warning from this implication && isEmptyBag pruned_implics -- No live children && isEmptyVarSet final_needs -- No needed vars to pass up to parent final_status = IC_Solved { ics_need = final_needs , ics_dead = dead_givens } final_implic = implic { ic_status = final_status , ic_wanted = wc { wc_simple = pruned_simples , wc_insol = pruned_insols , wc_impl = pruned_implics } } -- We can only prune the child implications (pruned_implics) -- in the IC_Solved status case, because only then we can -- accumulate their needed evidence variales into the -- IC_Solved final_status field of the parent implication. ; return $ if discard_entire_implication then Nothing else Just final_implic } where WC { wc_simple = simples, wc_impl = implics, wc_insol = insols } = wc some_insoluble = insolubleWC wc some_unsolved = not (isEmptyBag simples && isEmptyBag insols) || isNothing mb_implic_needs pruned_simples = dropDerivedSimples simples pruned_insols = dropDerivedInsols insols pruned_implics = filterBag need_to_keep_implic implics mb_implic_needs :: Maybe VarSet -- Just vs => all implics are IC_Solved, with 'vs' needed -- Nothing => at least one implic is not IC_Solved mb_implic_needs = foldrBag add_implic (Just emptyVarSet) implics Just implic_needs = mb_implic_needs add_implic implic acc | Just vs_acc <- acc , IC_Solved { ics_need = vs } <- ic_status implic = Just (vs `unionVarSet` vs_acc) | otherwise = Nothing need_to_keep_implic ic | IC_Solved { ics_dead = [] } <- ic_status ic -- Fully solved, and no redundant givens to report , isEmptyBag (wc_impl (ic_wanted ic)) -- And no children that might have things to report = False | otherwise = True warnRedundantGivens :: SkolemInfo -> Bool warnRedundantGivens (SigSkol ctxt _) = case ctxt of FunSigCtxt _ warn_redundant -> warn_redundant ExprSigCtxt -> True _ -> False warnRedundantGivens InstSkol = True warnRedundantGivens _ = False neededEvVars :: EvBindMap -> VarSet -> VarSet -- Find all the evidence variables that are "needed", -- and then delete all those bound by the evidence bindings -- A variable is "needed" if -- a) it is free in the RHS of a Wanted EvBind (add_wanted) -- b) it is free in the RHS of an EvBind whose LHS is needed (transClo) -- c) it is in the ic_need_evs of a nested implication (initial_seeds) -- (after removing the givens) neededEvVars ev_binds initial_seeds = needed `minusVarSet` bndrs where seeds = foldEvBindMap add_wanted initial_seeds ev_binds needed = transCloVarSet also_needs seeds bndrs = foldEvBindMap add_bndr emptyVarSet ev_binds add_wanted :: EvBind -> VarSet -> VarSet add_wanted (EvBind { eb_is_given = is_given, eb_rhs = rhs }) needs | is_given = needs -- Add the rhs vars of the Wanted bindings only | otherwise = evVarsOfTerm rhs `unionVarSet` needs also_needs :: VarSet -> VarSet also_needs needs = foldVarSet add emptyVarSet needs where add v needs | Just ev_bind <- lookupEvBind ev_binds v , EvBind { eb_is_given = is_given, eb_rhs = rhs } <- ev_bind , is_given = evVarsOfTerm rhs `unionVarSet` needs | otherwise = needs add_bndr :: EvBind -> VarSet -> VarSet add_bndr (EvBind { eb_lhs = v }) vs = extendVarSet vs v {- Note [Tracking redundant constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With Opt_WarnRedundantConstraints, GHC can report which constraints of a type signature (or instance declaration) are redundant, and can be omitted. Here is an overview of how it works: ----- What is a redudant constraint? * The things that can be redundant are precisely the Given constraints of an implication. * A constraint can be redundant in two different ways: a) It is implied by other givens. E.g. f :: (Eq a, Ord a) => blah -- Eq a unnecessary g :: (Eq a, a~b, Eq b) => blah -- Either Eq a or Eq b unnecessary b) It is not needed by the Wanted constraints covered by the implication E.g. f :: Eq a => a -> Bool f x = True -- Equality not uesd * To find (a), when we have two Given constraints, we must be careful to drop the one that is a naked variable (if poss). So if we have f :: (Eq a, Ord a) => blah then we may find [G] sc_sel (d1::Ord a) :: Eq a [G] d2 :: Eq a We want to discard d2 in favour of the superclass selection from the Ord dictionary. This is done by TcInteract.solveOneFromTheOther See Note [Replacement vs keeping]. * To find (b) we need to know which evidence bindings are 'wanted'; hence the eb_is_given field on an EvBind. ----- How tracking works * When the constraint solver finishes solving all the wanteds in an implication, it sets its status to IC_Solved - The ics_dead field of IC_Solved records the subset of the ic_given of this implication that are redundant (not needed). - The ics_need field of IC_Solved then records all the in-scope (given) evidence variables, bound by the context, that were needed to solve this implication, including all its nested implications. (We remove the ic_given of this implication from the set, of course.) * We compute which evidence variables are needed by an implication in setImplicationStatus. A variable is needed if a) it is free in the RHS of a Wanted EvBind b) it is free in the RHS of an EvBind whose LHS is needed c) it is in the ics_need of a nested implication * We need to be careful not to discard an implication prematurely, even one that is fully solved, because we might thereby forget which variables it needs, and hence wrongly report a constraint as redundant. But we can discard it once its free vars have been incorporated into its parent; or if it simply has no free vars. This careful discarding is also handled in setImplicationStatus ----- Reporting redundant constraints * TcErrors does the actual warning, in warnRedundantConstraints. * We don't report redundant givens for *every* implication; only for those which reply True to TcSimplify.warnRedundantGivens: - For example, in a class declaration, the default method *can* use the class constraint, but it certainly doesn't *have* to, and we don't want to report an error there. - More subtly, in a function definition f :: (Ord a, Ord a, Ix a) => a -> a f x = rhs we do an ambiguity check on the type (which would find that one of the Ord a constraints was redundant), and then we check that the definition has that type (which might find that both are redundant). We don't want to report the same error twice, so we disable it for the ambiguity check. Hence the flag in TcType.FunSigCtxt. This decision is taken in setImplicationStatus, rather than TcErrors so that we can discard implication constraints that we don't need. So ics_dead consists only of the *reportable* redundant givens. ----- Shortcomings Consider (see Trac #9939) f2 :: (Eq a, Ord a) => a -> a -> Bool -- Ord a redundant, but Eq a is reported f2 x y = (x == y) We report (Eq a) as redundant, whereas actually (Ord a) is. But it's really not easy to detect that! Note [Cutting off simpl_loop] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is very important not to iterate in simpl_loop unless there is a chance of progress. Trac #8474 is a classic example: * There's a deeply-nested chain of implication constraints. ?x:alpha => ?y1:beta1 => ... ?yn:betan => [W] ?x:Int * From the innermost one we get a [D] alpha ~ Int, but alpha is untouchable until we get out to the outermost one * We float [D] alpha~Int out (it is in floated_eqs), but since alpha is untouchable, the solveInteract in simpl_loop makes no progress * So there is no point in attempting to re-solve ?yn:betan => [W] ?x:Int because we'll just get the same [D] again * If we *do* re-solve, we'll get an ininite loop. It is cut off by the fixed bound of 10, but solving the next takes 10*10*...*10 (ie exponentially many) iterations! Conclusion: we should iterate simpl_loop iff we will get more 'givens' in the inert set when solving the nested implications. That is the result of prepareInertsForImplications is larger. How can we tell this? Consider floated_eqs (all wanted or derived): (a) [W/D] CTyEqCan (a ~ ty). This can give rise to a new given only by causing a unification. So we count those unifications. (b) [W] CFunEqCan (F tys ~ xi). Even though these are wanted, they are pushed in as givens by prepareInertsForImplications. See Note [Preparing inert set for implications] in TcSMonad. But because of that very fact, we won't generate another copy if we iterate simpl_loop. So we iterate if there any of these -} promoteTyVar :: TcLevel -> TcTyVar -> TcS TcTyVar -- When we float a constraint out of an implication we must restore -- invariant (MetaTvInv) in Note [TcLevel and untouchable type variables] in TcType -- See Note [Promoting unification variables] promoteTyVar tclvl tv | isFloatedTouchableMetaTyVar tclvl tv = do { cloned_tv <- TcS.cloneMetaTyVar tv ; let rhs_tv = setMetaTyVarTcLevel cloned_tv tclvl ; unifyTyVar tv (mkTyVarTy rhs_tv) ; return rhs_tv } | otherwise = return tv promoteAndDefaultTyVar :: TcLevel -> TcTyVarSet -> TcTyVar -> TcS TcTyVar -- See Note [Promote _and_ default when inferring] promoteAndDefaultTyVar tclvl gbl_tvs tv = do { tv1 <- if tv `elemVarSet` gbl_tvs then return tv else defaultTyVar tv ; promoteTyVar tclvl tv1 } defaultTyVar :: TcTyVar -> TcS TcTyVar -- Precondition: MetaTyVars only -- See Note [DefaultTyVar] defaultTyVar the_tv | Just default_k <- defaultKind_maybe (tyVarKind the_tv) = do { tv' <- TcS.cloneMetaTyVar the_tv ; let new_tv = setTyVarKind tv' default_k ; traceTcS "defaultTyVar" (ppr the_tv <+> ppr new_tv) ; unifyTyVar the_tv (mkTyVarTy new_tv) ; return new_tv } -- Why not directly derived_pred = mkTcEqPred k default_k? -- See Note [DefaultTyVar] -- We keep the same TcLevel on tv' | otherwise = return the_tv -- The common case approximateWC :: WantedConstraints -> Cts -- Postcondition: Wanted or Derived Cts -- See Note [ApproximateWC] approximateWC wc = float_wc emptyVarSet wc where float_wc :: TcTyVarSet -> WantedConstraints -> Cts float_wc trapping_tvs (WC { wc_simple = simples, wc_impl = implics }) = filterBag is_floatable simples `unionBags` do_bag (float_implic new_trapping_tvs) implics where is_floatable ct = tyVarsOfCt ct `disjointVarSet` new_trapping_tvs new_trapping_tvs = transCloVarSet grow trapping_tvs grow :: VarSet -> VarSet -- Maps current trapped tyvars to newly-trapped ones grow so_far = foldrBag (grow_one so_far) emptyVarSet simples grow_one so_far ct tvs | ct_tvs `intersectsVarSet` so_far = tvs `unionVarSet` ct_tvs | otherwise = tvs where ct_tvs = tyVarsOfCt ct float_implic :: TcTyVarSet -> Implication -> Cts float_implic trapping_tvs imp | ic_no_eqs imp -- No equalities, so float = float_wc new_trapping_tvs (ic_wanted imp) | otherwise -- Don't float out of equalities = emptyCts -- See Note [ApproximateWC] where new_trapping_tvs = trapping_tvs `extendVarSetList` ic_skols imp do_bag :: (a -> Bag c) -> Bag a -> Bag c do_bag f = foldrBag (unionBags.f) emptyBag {- Note [ApproximateWC] ~~~~~~~~~~~~~~~~~~~~ approximateWC takes a constraint, typically arising from the RHS of a let-binding whose type we are *inferring*, and extracts from it some *simple* constraints that we might plausibly abstract over. Of course the top-level simple constraints are plausible, but we also float constraints out from inside, if they are not captured by skolems. The same function is used when doing type-class defaulting (see the call to applyDefaultingRules) to extract constraints that that might be defaulted. There are two caveats: 1. We do *not* float anything out if the implication binds equality constraints, because that defeats the OutsideIn story. Consider data T a where TInt :: T Int MkT :: T a f TInt = 3::Int We get the implication (a ~ Int => res ~ Int), where so far we've decided f :: T a -> res We don't want to float (res~Int) out because then we'll infer f :: T a -> Int which is only on of the possible types. (GHC 7.6 accidentally *did* float out of such implications, which meant it would happily infer non-principal types.) 2. We do not float out an inner constraint that shares a type variable (transitively) with one that is trapped by a skolem. Eg forall a. F a ~ beta, Integral beta We don't want to float out (Integral beta). Doing so would be bad when defaulting, because then we'll default beta:=Integer, and that makes the error message much worse; we'd get Can't solve F a ~ Integer rather than Can't solve Integral (F a) Moreover, floating out these "contaminated" constraints doesn't help when generalising either. If we generalise over (Integral b), we still can't solve the retained implication (forall a. F a ~ b). Indeed, arguably that too would be a harder error to understand. Note [DefaultTyVar] ~~~~~~~~~~~~~~~~~~~ defaultTyVar is used on any un-instantiated meta type variables to default the kind of OpenKind and ArgKind etc to *. This is important to ensure that instance declarations match. For example consider instance Show (a->b) foo x = show (\_ -> True) Then we'll get a constraint (Show (p ->q)) where p has kind ArgKind, and that won't match the typeKind (*) in the instance decl. See tests tc217 and tc175. We look only at touchable type variables. No further constraints are going to affect these type variables, so it's time to do it by hand. However we aren't ready to default them fully to () or whatever, because the type-class defaulting rules have yet to run. An important point is that if the type variable tv has kind k and the default is default_k we do not simply generate [D] (k ~ default_k) because: (1) k may be ArgKind and default_k may be * so we will fail (2) We need to rewrite all occurrences of the tv to be a type variable with the right kind and we choose to do this by rewriting the type variable /itself/ by a new variable which does have the right kind. Note [Promote _and_ default when inferring] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we are inferring a type, we simplify the constraint, and then use approximateWC to produce a list of candidate constraints. Then we MUST a) Promote any meta-tyvars that have been floated out by approximateWC, to restore invariant (MetaTvInv) described in Note [TcLevel and untouchable type variables] in TcType. b) Default the kind of any meta-tyyvars that are not mentioned in in the environment. To see (b), suppose the constraint is (C ((a :: OpenKind) -> Int)), and we have an instance (C ((x:*) -> Int)). The instance doesn't match -- but it should! If we don't solve the constraint, we'll stupidly quantify over (C (a->Int)) and, worse, in doing so zonkQuantifiedTyVar will quantify over (b:*) instead of (a:OpenKind), which can lead to disaster; see Trac #7332. Trac #7641 is a simpler example. Note [Promoting unification variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we float an equality out of an implication we must "promote" free unification variables of the equality, in order to maintain Invariant (MetaTvInv) from Note [TcLevel and untouchable type variables] in TcType. for the leftover implication. This is absolutely necessary. Consider the following example. We start with two implications and a class with a functional dependency. class C x y | x -> y instance C [a] [a] (I1) [untch=beta]forall b. 0 => F Int ~ [beta] (I2) [untch=beta]forall c. 0 => F Int ~ [[alpha]] /\ C beta [c] We float (F Int ~ [beta]) out of I1, and we float (F Int ~ [[alpha]]) out of I2. They may react to yield that (beta := [alpha]) which can then be pushed inwards the leftover of I2 to get (C [alpha] [a]) which, using the FunDep, will mean that (alpha := a). In the end we will have the skolem 'b' escaping in the untouchable beta! Concrete example is in indexed_types/should_fail/ExtraTcsUntch.hs: class C x y | x -> y where op :: x -> y -> () instance C [a] [a] type family F a :: * h :: F Int -> () h = undefined data TEx where TEx :: a -> TEx f (x::beta) = let g1 :: forall b. b -> () g1 _ = h [x] g2 z = case z of TEx y -> (h [[undefined]], op x [y]) in (g1 '3', g2 undefined) Note [Solving Family Equations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After we are done with simplification we may be left with constraints of the form: [Wanted] F xis ~ beta If 'beta' is a touchable unification variable not already bound in the TyBinds then we'd like to create a binding for it, effectively "defaulting" it to be 'F xis'. When is it ok to do so? 1) 'beta' must not already be defaulted to something. Example: [Wanted] F Int ~ beta <~ Will default [beta := F Int] [Wanted] F Char ~ beta <~ Already defaulted, can't default again. We have to report this as unsolved. 2) However, we must still do an occurs check when defaulting (F xis ~ beta), to set [beta := F xis] only if beta is not among the free variables of xis. 3) Notice that 'beta' can't be bound in ty binds already because we rewrite RHS of type family equations. See Inert Set invariants in TcInteract. This solving is now happening during zonking, see Note [Unflattening while zonking] in TcMType. ********************************************************************************* * * * Floating equalities * * * ********************************************************************************* Note [Float Equalities out of Implications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For ordinary pattern matches (including existentials) we float equalities out of implications, for instance: data T where MkT :: Eq a => a -> T f x y = case x of MkT _ -> (y::Int) We get the implication constraint (x::T) (y::alpha): forall a. [untouchable=alpha] Eq a => alpha ~ Int We want to float out the equality into a scope where alpha is no longer untouchable, to solve the implication! But we cannot float equalities out of implications whose givens may yield or contain equalities: data T a where T1 :: T Int T2 :: T Bool T3 :: T a h :: T a -> a -> Int f x y = case x of T1 -> y::Int T2 -> y::Bool T3 -> h x y We generate constraint, for (x::T alpha) and (y :: beta): [untouchables = beta] (alpha ~ Int => beta ~ Int) -- From 1st branch [untouchables = beta] (alpha ~ Bool => beta ~ Bool) -- From 2nd branch (alpha ~ beta) -- From 3rd branch If we float the equality (beta ~ Int) outside of the first implication and the equality (beta ~ Bool) out of the second we get an insoluble constraint. But if we just leave them inside the implications we unify alpha := beta and solve everything. Principle: We do not want to float equalities out which may need the given *evidence* to become soluble. Consequence: classes with functional dependencies don't matter (since there is no evidence for a fundep equality), but equality superclasses do matter (since they carry evidence). -} floatEqualities :: [TcTyVar] -> Bool -> WantedConstraints -> TcS (Cts, WantedConstraints) -- Main idea: see Note [Float Equalities out of Implications] -- -- Precondition: the wc_simple of the incoming WantedConstraints are -- fully zonked, so that we can see their free variables -- -- Postcondition: The returned floated constraints (Cts) are only -- Wanted or Derived and come from the input wanted -- ev vars or deriveds -- -- Also performs some unifications (via promoteTyVar), adding to -- monadically-carried ty_binds. These will be used when processing -- floated_eqs later -- -- Subtleties: Note [Float equalities from under a skolem binding] -- Note [Skolem escape] floatEqualities skols no_given_eqs wanteds@(WC { wc_simple = simples }) | not no_given_eqs -- There are some given equalities, so don't float = return (emptyBag, wanteds) -- Note [Float Equalities out of Implications] | otherwise = do { outer_tclvl <- TcS.getTcLevel ; mapM_ (promoteTyVar outer_tclvl) (varSetElems (tyVarsOfCts float_eqs)) -- See Note [Promoting unification variables] ; traceTcS "floatEqualities" (vcat [ text "Skols =" <+> ppr skols , text "Simples =" <+> ppr simples , text "Floated eqs =" <+> ppr float_eqs ]) ; return (float_eqs, wanteds { wc_simple = remaining_simples }) } where skol_set = mkVarSet skols (float_eqs, remaining_simples) = partitionBag (usefulToFloat is_useful) simples is_useful pred = tyVarsOfType pred `disjointVarSet` skol_set {- Note [Float equalities from under a skolem binding] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Which of the simple equalities can we float out? Obviously, only ones that don't mention the skolem-bound variables. But that is over-eager. Consider [2] forall a. F a beta[1] ~ gamma[2], G beta[1] gamma[2] ~ Int The second constraint doesn't mention 'a'. But if we float it we'll promote gamma[2] to gamma'[1]. Now suppose that we learn that beta := Bool, and F a Bool = a, and G Bool _ = Int. Then we'll we left with the constraint [2] forall a. a ~ gamma'[1] which is insoluble because gamma became untouchable. Solution: float only constraints that stand a jolly good chance of being soluble simply by being floated, namely ones of form a ~ ty where 'a' is a currently-untouchable unification variable, but may become touchable by being floated (perhaps by more than one level). We had a very complicated rule previously, but this is nice and simple. (To see the notes, look at this Note in a version of TcSimplify prior to Oct 2014). Note [Skolem escape] ~~~~~~~~~~~~~~~~~~~~ You might worry about skolem escape with all this floating. For example, consider [2] forall a. (a ~ F beta[2] delta, Maybe beta[2] ~ gamma[1]) The (Maybe beta ~ gamma) doesn't mention 'a', so we float it, and solve with gamma := beta. But what if later delta:=Int, and F b Int = b. Then we'd get a ~ beta[2], and solve to get beta:=a, and now the skolem has escaped! But it's ok: when we float (Maybe beta[2] ~ gamma[1]), we promote beta[2] to beta[1], and that means the (a ~ beta[1]) will be stuck, as it should be. ********************************************************************************* * * * Defaulting and disamgiguation * * * ********************************************************************************* -} applyDefaultingRules :: WantedConstraints -> TcS Bool -- True <=> I did some defaulting, by unifying a meta-tyvar -- Imput WantedConstraints are not necessarily zonked applyDefaultingRules wanteds | isEmptyWC wanteds = return False | otherwise = do { info@(default_tys, _) <- getDefaultInfo ; wanteds <- TcS.zonkWC wanteds ; let groups = findDefaultableGroups info wanteds ; traceTcS "applyDefaultingRules {" $ vcat [ text "wanteds =" <+> ppr wanteds , text "groups =" <+> ppr groups , text "info =" <+> ppr info ] ; something_happeneds <- mapM (disambigGroup default_tys) groups ; traceTcS "applyDefaultingRules }" (ppr something_happeneds) ; return (or something_happeneds) } findDefaultableGroups :: ( [Type] , (Bool,Bool) ) -- (Overloaded strings, extended default rules) -> WantedConstraints -- Unsolved (wanted or derived) -> [(TyVar, [Ct])] findDefaultableGroups (default_tys, (ovl_strings, extended_defaults)) wanteds | null default_tys = [] | otherwise = [ (tv, map fstOf3 group) | group@((_,_,tv):_) <- unary_groups , defaultable_tyvar tv , defaultable_classes (map sndOf3 group) ] where simples = approximateWC wanteds (unaries, non_unaries) = partitionWith find_unary (bagToList simples) unary_groups = equivClasses cmp_tv unaries unary_groups :: [[(Ct, Class, TcTyVar)]] -- (C tv) constraints unaries :: [(Ct, Class, TcTyVar)] -- (C tv) constraints non_unaries :: [Ct] -- and *other* constraints -- Finds unary type-class constraints -- But take account of polykinded classes like Typeable, -- which may look like (Typeable * (a:*)) (Trac #8931) find_unary cc | Just (cls,tys) <- getClassPredTys_maybe (ctPred cc) , Just (kinds, ty) <- snocView tys -- Ignore kind arguments , all isKind kinds -- for this purpose , Just tv <- tcGetTyVar_maybe ty , isMetaTyVar tv -- We might have runtime-skolems in GHCi, and -- we definitely don't want to try to assign to those! = Left (cc, cls, tv) find_unary cc = Right cc -- Non unary or non dictionary bad_tvs :: TcTyVarSet -- TyVars mentioned by non-unaries bad_tvs = mapUnionVarSet tyVarsOfCt non_unaries cmp_tv (_,_,tv1) (_,_,tv2) = tv1 `compare` tv2 defaultable_tyvar tv = let b1 = isTyConableTyVar tv -- Note [Avoiding spurious errors] b2 = not (tv `elemVarSet` bad_tvs) in b1 && b2 defaultable_classes clss | extended_defaults = any isInteractiveClass clss | otherwise = all is_std_class clss && (any is_num_class clss) -- In interactive mode, or with -XExtendedDefaultRules, -- we default Show a to Show () to avoid graututious errors on "show []" isInteractiveClass cls = is_num_class cls || (classKey cls `elem` [showClassKey, eqClassKey, ordClassKey]) is_num_class cls = isNumericClass cls || (ovl_strings && (cls `hasKey` isStringClassKey)) -- is_num_class adds IsString to the standard numeric classes, -- when -foverloaded-strings is enabled is_std_class cls = isStandardClass cls || (ovl_strings && (cls `hasKey` isStringClassKey)) -- Similarly is_std_class ------------------------------ disambigGroup :: [Type] -- The default types -> (TcTyVar, [Ct]) -- All classes of the form (C a) -- sharing same type variable -> TcS Bool -- True <=> something happened, reflected in ty_binds disambigGroup [] _ = return False disambigGroup (default_ty:default_tys) group@(the_tv, wanteds) = do { traceTcS "disambigGroup {" (vcat [ ppr default_ty, ppr the_tv, ppr wanteds ]) ; fake_ev_binds_var <- TcS.newTcEvBinds ; tclvl <- TcS.getTcLevel ; success <- nestImplicTcS fake_ev_binds_var (pushTcLevel tclvl) try_group ; if success then -- Success: record the type variable binding, and return do { unifyTyVar the_tv default_ty ; wrapWarnTcS $ warnDefaulting wanteds default_ty ; traceTcS "disambigGroup succeeded }" (ppr default_ty) ; return True } else -- Failure: try with the next type do { traceTcS "disambigGroup failed, will try other default types }" (ppr default_ty) ; disambigGroup default_tys group } } where try_group | Just subst <- mb_subst = do { wanted_evs <- mapM (newWantedEvVarNC loc . substTy subst . ctPred) wanteds ; residual_wanted <- solveSimpleWanteds $ listToBag $ map mkNonCanonical wanted_evs ; return (isEmptyWC residual_wanted) } | otherwise = return False tmpl_tvs = extendVarSet (tyVarsOfType (tyVarKind the_tv)) the_tv mb_subst = tcMatchTy tmpl_tvs (mkTyVarTy the_tv) default_ty -- Make sure the kinds match too; hence this call to tcMatchTy -- E.g. suppose the only constraint was (Typeable k (a::k)) loc = CtLoc { ctl_origin = GivenOrigin UnkSkol , ctl_env = panic "disambigGroup:env" , ctl_depth = initialSubGoalDepth } {- Note [Avoiding spurious errors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When doing the unification for defaulting, we check for skolem type variables, and simply don't default them. For example: f = (*) -- Monomorphic g :: Num a => a -> a g x = f x x Here, we get a complaint when checking the type signature for g, that g isn't polymorphic enough; but then we get another one when dealing with the (Num a) context arising from f's definition; we try to unify a with Int (to default it), but find that it's already been unified with the rigid variable from g's type sig -}
fmthoma/ghc
compiler/typecheck/TcSimplify.hs
bsd-3-clause
77,037
1
19
21,347
7,292
3,858
3,434
584
5
{- This module handles generation of position independent code and dynamic-linking related issues for the native code generator. This depends both the architecture and OS, so we define it here instead of in one of the architecture specific modules. Things outside this module which are related to this: + module CLabel - PIC base label (pretty printed as local label 1) - DynamicLinkerLabels - several kinds: CodeStub, SymbolPtr, GotSymbolPtr, GotSymbolOffset - labelDynamic predicate + module Cmm - The GlobalReg datatype has a PicBaseReg constructor - The CmmLit datatype has a CmmLabelDiffOff constructor + codeGen & RTS - When tablesNextToCode, no absolute addresses are stored in info tables any more. Instead, offsets from the info label are used. - For Win32 only, SRTs might contain addresses of __imp_ symbol pointers because Win32 doesn't support external references in data sections. TODO: make sure this still works, it might be bitrotted + NCG - The cmmToCmm pass in AsmCodeGen calls cmmMakeDynamicReference for all labels. - nativeCodeGen calls pprImportedSymbol and pprGotDeclaration to output all the necessary stuff for imported symbols. - The NCG monad keeps track of a list of imported symbols. - MachCodeGen invokes initializePicBase to generate code to initialize the PIC base register when needed. - MachCodeGen calls cmmMakeDynamicReference whenever it uses a CLabel that wasn't in the original Cmm code (e.g. floating point literals). -} module PIC ( cmmMakeDynamicReference, CmmMakeDynamicReferenceM(..), ReferenceKind(..), needImportedSymbols, pprImportedSymbol, pprGotDeclaration, initializePicBase_ppc, initializePicBase_x86 ) where import qualified PPC.Instr as PPC import qualified PPC.Regs as PPC import qualified X86.Instr as X86 import Platform import Instruction import Reg import NCGMonad import Hoopl import Cmm import CLabel ( CLabel, ForeignLabelSource(..), pprCLabel, mkDynamicLinkerLabel, DynamicLinkerLabelInfo(..), dynamicLinkerLabelInfo, mkPicBaseLabel, labelDynamic, externallyVisibleCLabel ) import CLabel ( mkForeignLabel ) import BasicTypes import Module import Outputable import DynFlags import FastString -------------------------------------------------------------------------------- -- It gets called by the cmmToCmm pass for every CmmLabel in the Cmm -- code. It does The Right Thing(tm) to convert the CmmLabel into a -- position-independent, dynamic-linking-aware reference to the thing -- in question. -- Note that this also has to be called from MachCodeGen in order to -- access static data like floating point literals (labels that were -- created after the cmmToCmm pass). -- The function must run in a monad that can keep track of imported symbols -- A function for recording an imported symbol must be passed in: -- - addImportCmmOpt for the CmmOptM monad -- - addImportNat for the NatM monad. data ReferenceKind = DataReference | CallReference | JumpReference deriving(Eq) class Monad m => CmmMakeDynamicReferenceM m where addImport :: CLabel -> m () getThisModule :: m Module instance CmmMakeDynamicReferenceM NatM where addImport = addImportNat getThisModule = getThisModuleNat cmmMakeDynamicReference :: CmmMakeDynamicReferenceM m => DynFlags -> ReferenceKind -- whether this is the target of a jump -> CLabel -- the label -> m CmmExpr cmmMakeDynamicReference dflags referenceKind lbl | Just _ <- dynamicLinkerLabelInfo lbl = return $ CmmLit $ CmmLabel lbl -- already processed it, pass through | otherwise = do this_mod <- getThisModule case howToAccessLabel dflags (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) this_mod referenceKind lbl of AccessViaStub -> do let stub = mkDynamicLinkerLabel CodeStub lbl addImport stub return $ CmmLit $ CmmLabel stub AccessViaSymbolPtr -> do let symbolPtr = mkDynamicLinkerLabel SymbolPtr lbl addImport symbolPtr return $ CmmLoad (cmmMakePicReference dflags symbolPtr) (bWord dflags) AccessDirectly -> case referenceKind of -- for data, we might have to make some calculations: DataReference -> return $ cmmMakePicReference dflags lbl -- all currently supported processors support -- PC-relative branch and call instructions, -- so just jump there if it's a call or a jump _ -> return $ CmmLit $ CmmLabel lbl -- ----------------------------------------------------------------------------- -- Create a position independent reference to a label. -- (but do not bother with dynamic linking). -- We calculate the label's address by adding some (platform-dependent) -- offset to our base register; this offset is calculated by -- the function picRelative in the platform-dependent part below. cmmMakePicReference :: DynFlags -> CLabel -> CmmExpr cmmMakePicReference dflags lbl -- Windows doesn't need PIC, -- everything gets relocated at runtime | OSMinGW32 <- platformOS $ targetPlatform dflags = CmmLit $ CmmLabel lbl | OSAIX <- platformOS $ targetPlatform dflags = CmmMachOp (MO_Add W32) [ CmmReg (CmmGlobal PicBaseReg) , CmmLit $ picRelative (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) lbl ] -- both ABI versions default to medium code model | ArchPPC_64 _ <- platformArch $ targetPlatform dflags = CmmMachOp (MO_Add W32) -- code model medium [ CmmReg (CmmGlobal PicBaseReg) , CmmLit $ picRelative (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) lbl ] | (gopt Opt_PIC dflags || WayDyn `elem` ways dflags) && absoluteLabel lbl = CmmMachOp (MO_Add (wordWidth dflags)) [ CmmReg (CmmGlobal PicBaseReg) , CmmLit $ picRelative (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) lbl ] | otherwise = CmmLit $ CmmLabel lbl absoluteLabel :: CLabel -> Bool absoluteLabel lbl = case dynamicLinkerLabelInfo lbl of Just (GotSymbolPtr, _) -> False Just (GotSymbolOffset, _) -> False _ -> True -------------------------------------------------------------------------------- -- Knowledge about how special dynamic linker labels like symbol -- pointers, code stubs and GOT offsets look like is located in the -- module CLabel. -- We have to decide which labels need to be accessed -- indirectly or via a piece of stub code. data LabelAccessStyle = AccessViaStub | AccessViaSymbolPtr | AccessDirectly howToAccessLabel :: DynFlags -> Arch -> OS -> Module -> ReferenceKind -> CLabel -> LabelAccessStyle -- Windows -- In Windows speak, a "module" is a set of objects linked into the -- same Portable Exectuable (PE) file. (both .exe and .dll files are PEs). -- -- If we're compiling a multi-module program then symbols from other modules -- are accessed by a symbol pointer named __imp_SYMBOL. At runtime we have the -- following. -- -- (in the local module) -- __imp_SYMBOL: addr of SYMBOL -- -- (in the other module) -- SYMBOL: the real function / data. -- -- To access the function at SYMBOL from our local module, we just need to -- dereference the local __imp_SYMBOL. -- -- If not compiling with -dynamic we assume that all our code will be linked -- into the same .exe file. In this case we always access symbols directly, -- and never use __imp_SYMBOL. -- howToAccessLabel dflags _ OSMinGW32 this_mod _ lbl -- Assume all symbols will be in the same PE, so just access them directly. | WayDyn `notElem` ways dflags = AccessDirectly -- If the target symbol is in another PE we need to access it via the -- appropriate __imp_SYMBOL pointer. | labelDynamic dflags this_mod lbl = AccessViaSymbolPtr -- Target symbol is in the same PE as the caller, so just access it directly. | otherwise = AccessDirectly -- Mach-O (Darwin, Mac OS X) -- -- Indirect access is required in the following cases: -- * things imported from a dynamic library -- * (not on x86_64) data from a different module, if we're generating PIC code -- It is always possible to access something indirectly, -- even when it's not necessary. -- howToAccessLabel dflags arch OSDarwin this_mod DataReference lbl -- data access to a dynamic library goes via a symbol pointer | labelDynamic dflags this_mod lbl = AccessViaSymbolPtr -- when generating PIC code, all cross-module data references must -- must go via a symbol pointer, too, because the assembler -- cannot generate code for a label difference where one -- label is undefined. Doesn't apply t x86_64. -- Unfortunately, we don't know whether it's cross-module, -- so we do it for all externally visible labels. -- This is a slight waste of time and space, but otherwise -- we'd need to pass the current Module all the way in to -- this function. | arch /= ArchX86_64 , gopt Opt_PIC dflags && externallyVisibleCLabel lbl = AccessViaSymbolPtr | otherwise = AccessDirectly howToAccessLabel dflags arch OSDarwin this_mod JumpReference lbl -- dyld code stubs don't work for tailcalls because the -- stack alignment is only right for regular calls. -- Therefore, we have to go via a symbol pointer: | arch == ArchX86 || arch == ArchX86_64 , labelDynamic dflags this_mod lbl = AccessViaSymbolPtr howToAccessLabel dflags arch OSDarwin this_mod _ lbl -- Code stubs are the usual method of choice for imported code; -- not needed on x86_64 because Apple's new linker, ld64, generates -- them automatically. | arch /= ArchX86_64 , labelDynamic dflags this_mod lbl = AccessViaStub | otherwise = AccessDirectly ---------------------------------------------------------------------------- -- AIX -- quite simple (for now) howToAccessLabel _dflags _arch OSAIX _this_mod kind _lbl = case kind of DataReference -> AccessViaSymbolPtr CallReference -> AccessDirectly JumpReference -> AccessDirectly -- ELF (Linux) -- -- ELF tries to pretend to the main application code that dynamic linking does -- not exist. While this may sound convenient, it tends to mess things up in -- very bad ways, so we have to be careful when we generate code for the main -- program (-dynamic but no -fPIC). -- -- Indirect access is required for references to imported symbols -- from position independent code. It is also required from the main program -- when dynamic libraries containing Haskell code are used. howToAccessLabel _ (ArchPPC_64 _) os _ kind _ | osElfTarget os = case kind of -- ELF PPC64 (powerpc64-linux), AIX, MacOS 9, BeOS/PPC DataReference -> AccessViaSymbolPtr -- RTLD does not generate stubs for function descriptors -- in tail calls. Create a symbol pointer and generate -- the code to load the function descriptor at the call site. JumpReference -> AccessViaSymbolPtr -- regular calls are handled by the runtime linker _ -> AccessDirectly howToAccessLabel dflags _ os _ _ _ -- no PIC -> the dynamic linker does everything for us; -- if we don't dynamically link to Haskell code, -- it actually manages to do so without messing things up. | osElfTarget os , not (gopt Opt_PIC dflags) && WayDyn `notElem` ways dflags = AccessDirectly howToAccessLabel dflags arch os this_mod DataReference lbl | osElfTarget os = case () of -- A dynamic label needs to be accessed via a symbol pointer. _ | labelDynamic dflags this_mod lbl -> AccessViaSymbolPtr -- For PowerPC32 -fPIC, we have to access even static data -- via a symbol pointer (see below for an explanation why -- PowerPC32 Linux is especially broken). | arch == ArchPPC , gopt Opt_PIC dflags -> AccessViaSymbolPtr | otherwise -> AccessDirectly -- In most cases, we have to avoid symbol stubs on ELF, for the following reasons: -- on i386, the position-independent symbol stubs in the Procedure Linkage Table -- require the address of the GOT to be loaded into register %ebx on entry. -- The linker will take any reference to the symbol stub as a hint that -- the label in question is a code label. When linking executables, this -- will cause the linker to replace even data references to the label with -- references to the symbol stub. -- This leaves calling a (foreign) function from non-PIC code -- (AccessDirectly, because we get an implicit symbol stub) -- and calling functions from PIC code on non-i386 platforms (via a symbol stub) howToAccessLabel dflags arch os this_mod CallReference lbl | osElfTarget os , labelDynamic dflags this_mod lbl && not (gopt Opt_PIC dflags) = AccessDirectly | osElfTarget os , arch /= ArchX86 , labelDynamic dflags this_mod lbl && gopt Opt_PIC dflags = AccessViaStub howToAccessLabel dflags _ os this_mod _ lbl | osElfTarget os = if labelDynamic dflags this_mod lbl then AccessViaSymbolPtr else AccessDirectly -- all other platforms howToAccessLabel dflags _ _ _ _ _ | not (gopt Opt_PIC dflags) = AccessDirectly | otherwise = panic "howToAccessLabel: PIC not defined for this platform" -- ------------------------------------------------------------------- -- | Says what we we have to add to our 'PIC base register' in order to -- get the address of a label. picRelative :: Arch -> OS -> CLabel -> CmmLit -- Darwin, but not x86_64: -- The PIC base register points to the PIC base label at the beginning -- of the current CmmDecl. We just have to use a label difference to -- get the offset. -- We have already made sure that all labels that are not from the current -- module are accessed indirectly ('as' can't calculate differences between -- undefined labels). picRelative arch OSDarwin lbl | arch /= ArchX86_64 = CmmLabelDiffOff lbl mkPicBaseLabel 0 -- On AIX we use an indirect local TOC anchored by 'gotLabel'. -- This way we use up only one global TOC entry per compilation-unit -- (this is quite similiar to GCC's @-mminimal-toc@ compilation mode) picRelative _ OSAIX lbl = CmmLabelDiffOff lbl gotLabel 0 -- PowerPC Linux: -- The PIC base register points to our fake GOT. Use a label difference -- to get the offset. -- We have made sure that *everything* is accessed indirectly, so this -- is only used for offsets from the GOT to symbol pointers inside the -- GOT. picRelative ArchPPC os lbl | osElfTarget os = CmmLabelDiffOff lbl gotLabel 0 -- Most Linux versions: -- The PIC base register points to the GOT. Use foo@got for symbol -- pointers, and foo@gotoff for everything else. -- Linux and Darwin on x86_64: -- The PIC base register is %rip, we use foo@gotpcrel for symbol pointers, -- and a GotSymbolOffset label for other things. -- For reasons of tradition, the symbol offset label is written as a plain label. picRelative arch os lbl | osElfTarget os || (os == OSDarwin && arch == ArchX86_64) = let result | Just (SymbolPtr, lbl') <- dynamicLinkerLabelInfo lbl = CmmLabel $ mkDynamicLinkerLabel GotSymbolPtr lbl' | otherwise = CmmLabel $ mkDynamicLinkerLabel GotSymbolOffset lbl in result picRelative _ _ _ = panic "PositionIndependentCode.picRelative undefined for this platform" -------------------------------------------------------------------------------- needImportedSymbols :: DynFlags -> Arch -> OS -> Bool needImportedSymbols dflags arch os | os == OSDarwin , arch /= ArchX86_64 = True | os == OSAIX = True -- PowerPC Linux: -fPIC or -dynamic | osElfTarget os , arch == ArchPPC = gopt Opt_PIC dflags || WayDyn `elem` ways dflags -- PowerPC 64 Linux: always | osElfTarget os , arch == ArchPPC_64 ELF_V1 || arch == ArchPPC_64 ELF_V2 = True -- i386 (and others?): -dynamic but not -fPIC | osElfTarget os , arch /= ArchPPC_64 ELF_V1 && arch /= ArchPPC_64 ELF_V2 = WayDyn `elem` ways dflags && not (gopt Opt_PIC dflags) | otherwise = False -- gotLabel -- The label used to refer to our "fake GOT" from -- position-independent code. gotLabel :: CLabel gotLabel -- HACK: this label isn't really foreign = mkForeignLabel (fsLit ".LCTOC1") Nothing ForeignLabelInThisPackage IsData -------------------------------------------------------------------------------- -- We don't need to declare any offset tables. -- However, for PIC on x86, we need a small helper function. pprGotDeclaration :: DynFlags -> Arch -> OS -> SDoc pprGotDeclaration dflags ArchX86 OSDarwin | gopt Opt_PIC dflags = vcat [ text ".section __TEXT,__textcoal_nt,coalesced,no_toc", text ".weak_definition ___i686.get_pc_thunk.ax", text ".private_extern ___i686.get_pc_thunk.ax", text "___i686.get_pc_thunk.ax:", text "\tmovl (%esp), %eax", text "\tret" ] pprGotDeclaration _ _ OSDarwin = empty -- Emit XCOFF TOC section pprGotDeclaration _ _ OSAIX = vcat $ [ text ".toc" , text ".tc ghc_toc_table[TC],.LCTOC1" , text ".csect ghc_toc_table[RW]" -- See Note [.LCTOC1 in PPC PIC code] , text ".set .LCTOC1,$+0x8000" ] -- PPC 64 ELF v1needs a Table Of Contents (TOC) on Linux pprGotDeclaration _ (ArchPPC_64 ELF_V1) OSLinux = text ".section \".toc\",\"aw\"" -- In ELF v2 we also need to tell the assembler that we want ABI -- version 2. This would normally be done at the top of the file -- right after a file directive, but I could not figure out how -- to do that. pprGotDeclaration _ (ArchPPC_64 ELF_V2) OSLinux = vcat [ text ".abiversion 2", text ".section \".toc\",\"aw\"" ] pprGotDeclaration _ (ArchPPC_64 _) _ = panic "pprGotDeclaration: ArchPPC_64 only Linux supported" -- Emit GOT declaration -- Output whatever needs to be output once per .s file. pprGotDeclaration dflags arch os | osElfTarget os , arch /= ArchPPC_64 ELF_V1 && arch /= ArchPPC_64 ELF_V2 , not (gopt Opt_PIC dflags) = empty | osElfTarget os , arch /= ArchPPC_64 ELF_V1 && arch /= ArchPPC_64 ELF_V2 = vcat [ -- See Note [.LCTOC1 in PPC PIC code] text ".section \".got2\",\"aw\"", text ".LCTOC1 = .+32768" ] pprGotDeclaration _ _ _ = panic "pprGotDeclaration: no match" -------------------------------------------------------------------------------- -- On Darwin, we have to generate our own stub code for lazy binding.. -- For each processor architecture, there are two versions, one for PIC -- and one for non-PIC. -- -- Whenever you change something in this assembler output, make sure -- the splitter in driver/split/ghc-split.pl recognizes the new output pprImportedSymbol :: DynFlags -> Platform -> CLabel -> SDoc pprImportedSymbol dflags platform@(Platform { platformArch = ArchPPC, platformOS = OSDarwin }) importedLbl | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl = case gopt Opt_PIC dflags of False -> vcat [ text ".symbol_stub", text "L" <> pprCLabel platform lbl <> ptext (sLit "$stub:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\tlis r11,ha16(L" <> pprCLabel platform lbl <> text "$lazy_ptr)", text "\tlwz r12,lo16(L" <> pprCLabel platform lbl <> text "$lazy_ptr)(r11)", text "\tmtctr r12", text "\taddi r11,r11,lo16(L" <> pprCLabel platform lbl <> text "$lazy_ptr)", text "\tbctr" ] True -> vcat [ text ".section __TEXT,__picsymbolstub1," <> text "symbol_stubs,pure_instructions,32", text "\t.align 2", text "L" <> pprCLabel platform lbl <> ptext (sLit "$stub:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\tmflr r0", text "\tbcl 20,31,L0$" <> pprCLabel platform lbl, text "L0$" <> pprCLabel platform lbl <> char ':', text "\tmflr r11", text "\taddis r11,r11,ha16(L" <> pprCLabel platform lbl <> text "$lazy_ptr-L0$" <> pprCLabel platform lbl <> char ')', text "\tmtlr r0", text "\tlwzu r12,lo16(L" <> pprCLabel platform lbl <> text "$lazy_ptr-L0$" <> pprCLabel platform lbl <> text ")(r11)", text "\tmtctr r12", text "\tbctr" ] $+$ vcat [ text ".lazy_symbol_pointer", text "L" <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\t.long dyld_stub_binding_helper"] | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl = vcat [ text ".non_lazy_symbol_pointer", char 'L' <> pprCLabel platform lbl <> text "$non_lazy_ptr:", text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\t.long\t0"] | otherwise = empty pprImportedSymbol dflags platform@(Platform { platformArch = ArchX86, platformOS = OSDarwin }) importedLbl | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl = case gopt Opt_PIC dflags of False -> vcat [ text ".symbol_stub", text "L" <> pprCLabel platform lbl <> ptext (sLit "$stub:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\tjmp *L" <> pprCLabel platform lbl <> text "$lazy_ptr", text "L" <> pprCLabel platform lbl <> text "$stub_binder:", text "\tpushl $L" <> pprCLabel platform lbl <> text "$lazy_ptr", text "\tjmp dyld_stub_binding_helper" ] True -> vcat [ text ".section __TEXT,__picsymbolstub2," <> text "symbol_stubs,pure_instructions,25", text "L" <> pprCLabel platform lbl <> ptext (sLit "$stub:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\tcall ___i686.get_pc_thunk.ax", text "1:", text "\tmovl L" <> pprCLabel platform lbl <> text "$lazy_ptr-1b(%eax),%edx", text "\tjmp *%edx", text "L" <> pprCLabel platform lbl <> text "$stub_binder:", text "\tlea L" <> pprCLabel platform lbl <> text "$lazy_ptr-1b(%eax),%eax", text "\tpushl %eax", text "\tjmp dyld_stub_binding_helper" ] $+$ vcat [ text ".section __DATA, __la_sym_ptr" <> (if gopt Opt_PIC dflags then int 2 else int 3) <> text ",lazy_symbol_pointers", text "L" <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr:"), text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\t.long L" <> pprCLabel platform lbl <> text "$stub_binder"] | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl = vcat [ text ".non_lazy_symbol_pointer", char 'L' <> pprCLabel platform lbl <> text "$non_lazy_ptr:", text "\t.indirect_symbol" <+> pprCLabel platform lbl, text "\t.long\t0"] | otherwise = empty pprImportedSymbol _ (Platform { platformOS = OSDarwin }) _ = empty -- XCOFF / AIX -- -- Similiar to PPC64 ELF v1, there's dedicated TOC register (r2). To -- workaround the limitation of a global TOC we use an indirect TOC -- with the label `ghc_toc_table`. -- -- See also GCC's `-mminimal-toc` compilation mode or -- http://www.ibm.com/developerworks/rational/library/overview-toc-aix/ -- -- NB: No DSO-support yet pprImportedSymbol _ platform@(Platform { platformOS = OSAIX }) importedLbl = case dynamicLinkerLabelInfo importedLbl of Just (SymbolPtr, lbl) -> vcat [ text "LC.." <> pprCLabel platform lbl <> char ':', text "\t.long" <+> pprCLabel platform lbl ] _ -> empty -- ELF / Linux -- -- In theory, we don't need to generate any stubs or symbol pointers -- by hand for Linux. -- -- Reality differs from this in two areas. -- -- 1) If we just use a dynamically imported symbol directly in a read-only -- section of the main executable (as GCC does), ld generates R_*_COPY -- relocations, which are fundamentally incompatible with reversed info -- tables. Therefore, we need a table of imported addresses in a writable -- section. -- The "official" GOT mechanism (label@got) isn't intended to be used -- in position dependent code, so we have to create our own "fake GOT" -- when not Opt_PIC && WayDyn `elem` ways dflags. -- -- 2) PowerPC Linux is just plain broken. -- While it's theoretically possible to use GOT offsets larger -- than 16 bit, the standard crt*.o files don't, which leads to -- linker errors as soon as the GOT size exceeds 16 bit. -- Also, the assembler doesn't support @gotoff labels. -- In order to be able to use a larger GOT, we have to circumvent the -- entire GOT mechanism and do it ourselves (this is also what GCC does). -- When needImportedSymbols is defined, -- the NCG will keep track of all DynamicLinkerLabels it uses -- and output each of them using pprImportedSymbol. pprImportedSymbol _ platform@(Platform { platformArch = ArchPPC_64 _ }) importedLbl | osElfTarget (platformOS platform) = case dynamicLinkerLabelInfo importedLbl of Just (SymbolPtr, lbl) -> vcat [ text ".section \".toc\", \"aw\"", text ".LC_" <> pprCLabel platform lbl <> char ':', text "\t.quad" <+> pprCLabel platform lbl ] _ -> empty pprImportedSymbol dflags platform importedLbl | osElfTarget (platformOS platform) = case dynamicLinkerLabelInfo importedLbl of Just (SymbolPtr, lbl) -> let symbolSize = case wordWidth dflags of W32 -> sLit "\t.long" W64 -> sLit "\t.quad" _ -> panic "Unknown wordRep in pprImportedSymbol" in vcat [ text ".section \".got2\", \"aw\"", text ".LC_" <> pprCLabel platform lbl <> char ':', ptext symbolSize <+> pprCLabel platform lbl ] -- PLT code stubs are generated automatically by the dynamic linker. _ -> empty pprImportedSymbol _ _ _ = panic "PIC.pprImportedSymbol: no match" -------------------------------------------------------------------------------- -- Generate code to calculate the address that should be put in the -- PIC base register. -- This is called by MachCodeGen for every CmmProc that accessed the -- PIC base register. It adds the appropriate instructions to the -- top of the CmmProc. -- It is assumed that the first NatCmmDecl in the input list is a Proc -- and the rest are CmmDatas. -- Darwin is simple: just fetch the address of a local label. -- The FETCHPC pseudo-instruction is expanded to multiple instructions -- during pretty-printing so that we don't have to deal with the -- local label: -- PowerPC version: -- bcl 20,31,1f. -- 1: mflr picReg -- i386 version: -- call 1f -- 1: popl %picReg -- Get a pointer to our own fake GOT, which is defined on a per-module basis. -- This is exactly how GCC does it in linux. initializePicBase_ppc :: Arch -> OS -> Reg -> [NatCmmDecl CmmStatics PPC.Instr] -> NatM [NatCmmDecl CmmStatics PPC.Instr] initializePicBase_ppc ArchPPC os picReg (CmmProc info lab live (ListGraph blocks) : statics) | osElfTarget os = do let gotOffset = PPC.ImmConstantDiff (PPC.ImmCLbl gotLabel) (PPC.ImmCLbl mkPicBaseLabel) blocks' = case blocks of [] -> [] (b:bs) -> fetchPC b : map maybeFetchPC bs maybeFetchPC b@(BasicBlock bID _) | bID `mapMember` info = fetchPC b | otherwise = b -- GCC does PIC prologs thusly: -- bcl 20,31,.L1 -- .L1: -- mflr 30 -- addis 30,30,.LCTOC1-.L1@ha -- addi 30,30,.LCTOC1-.L1@l -- TODO: below we use it over temporary register, -- it can and should be optimised by picking -- correct PIC reg. fetchPC (BasicBlock bID insns) = BasicBlock bID (PPC.FETCHPC picReg : PPC.ADDIS picReg picReg (PPC.HA gotOffset) : PPC.ADDI picReg picReg (PPC.LO gotOffset) : PPC.MR PPC.r30 picReg : insns) return (CmmProc info lab live (ListGraph blocks') : statics) initializePicBase_ppc ArchPPC OSDarwin picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) -- just one entry because of splitting = return (CmmProc info lab live (ListGraph (b':blocks)) : statics) where BasicBlock bID insns = entry b' = BasicBlock bID (PPC.FETCHPC picReg : insns) ------------------------------------------------------------------------- -- Load TOC into register 2 -- PowerPC 64-bit ELF ABI 2.0 requires the address of the callee -- in register 12. -- We pass the label to FETCHTOC and create a .localentry too. -- TODO: Explain this better and refer to ABI spec! {- We would like to do approximately this, but spill slot allocation might be added before the first BasicBlock. That violates the ABI. For now we will emit the prologue code in the pretty printer, which is also what we do for ELF v1. initializePicBase_ppc (ArchPPC_64 ELF_V2) OSLinux picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) = do bID <-getUniqueM return (CmmProc info lab live (ListGraph (b':entry:blocks)) : statics) where BasicBlock entryID _ = entry b' = BasicBlock bID [PPC.FETCHTOC picReg lab, PPC.BCC PPC.ALWAYS entryID] -} initializePicBase_ppc _ _ _ _ = panic "initializePicBase_ppc: not needed" -- We cheat a bit here by defining a pseudo-instruction named FETCHGOT -- which pretty-prints as: -- call 1f -- 1: popl %picReg -- addl __GLOBAL_OFFSET_TABLE__+.-1b, %picReg -- (See PprMach.hs) initializePicBase_x86 :: Arch -> OS -> Reg -> [NatCmmDecl (Alignment, CmmStatics) X86.Instr] -> NatM [NatCmmDecl (Alignment, CmmStatics) X86.Instr] initializePicBase_x86 ArchX86 os picReg (CmmProc info lab live (ListGraph blocks) : statics) | osElfTarget os = return (CmmProc info lab live (ListGraph blocks') : statics) where blocks' = case blocks of [] -> [] (b:bs) -> fetchGOT b : map maybeFetchGOT bs -- we want to add a FETCHGOT instruction to the beginning of -- every block that is an entry point, which corresponds to -- the blocks that have entries in the info-table mapping. maybeFetchGOT b@(BasicBlock bID _) | bID `mapMember` info = fetchGOT b | otherwise = b fetchGOT (BasicBlock bID insns) = BasicBlock bID (X86.FETCHGOT picReg : insns) initializePicBase_x86 ArchX86 OSDarwin picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) = return (CmmProc info lab live (ListGraph (block':blocks)) : statics) where BasicBlock bID insns = entry block' = BasicBlock bID (X86.FETCHPC picReg : insns) initializePicBase_x86 _ _ _ _ = panic "initializePicBase_x86: not needed"
olsner/ghc
compiler/nativeGen/PIC.hs
bsd-3-clause
34,518
0
20
10,544
4,908
2,499
2,409
437
9
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sr-SP"> <title>GraalVM JavaScript</title> <maps> <homeID>graaljs</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/graaljs/src/main/javahelp/help_sr_SP/helpset_sr_SP.hs
apache-2.0
967
77
66
156
407
206
201
-1
-1
module OrphanInstancesClass (AClass(..)) where class AClass a where aClass :: a -> Int
niteria/haddock
html-test/src/OrphanInstancesClass.hs
bsd-2-clause
90
0
7
16
31
18
13
3
0
{-# LANGUAGE OverloadedStrings #-} -- | BigTable benchmark implemented using Hamlet. -- {-# LANGUAGE QuasiQuotes #-} module Main where import Criterion.Main import Text.Hamlet import Numeric (showInt) import qualified Data.ByteString.Lazy as L import qualified Text.Blaze.Html.Renderer.Utf8 as Utf8 import Data.Monoid (mconcat) import Text.Blaze.Html5 (table, tr, td) import Text.Blaze.Html (toHtml) import Yesod.Core.Widget import Control.Monad.Trans.Writer import Control.Monad.Trans.RWS import Data.Functor.Identity import Yesod.Core.Types import Data.Monoid import Data.IORef main = defaultMain [ bench "bigTable html" $ nf bigTableHtml bigTableData , bench "bigTable hamlet" $ nf bigTableHamlet bigTableData , bench "bigTable widget" $ nfIO (bigTableWidget bigTableData) , bench "bigTable blaze" $ nf bigTableBlaze bigTableData ] where rows :: Int rows = 1000 bigTableData :: [[Int]] bigTableData = replicate rows [1..10] {-# NOINLINE bigTableData #-} bigTableHtml rows = L.length $ Utf8.renderHtml $ ($ id) [hamlet| <table> $forall row <- rows <tr> $forall cell <- row <td>#{show cell} |] bigTableHamlet rows = L.length $ Utf8.renderHtml $ ($ id) [hamlet| <table> $forall row <- rows <tr> $forall cell <- row <td>#{show cell} |] bigTableWidget rows = fmap (L.length . Utf8.renderHtml . ($ render)) (run [whamlet| <table> $forall row <- rows <tr> $forall cell <- row <td>#{show cell} |]) where render _ _ = "foo" run (WidgetT w) = do (_, GWData { gwdBody = Body x }) <- w undefined return x bigTableBlaze t = L.length $ Utf8.renderHtml $ table $ mconcat $ map row t where row r = tr $ mconcat $ map (td . toHtml . show) r
ygale/yesod
yesod-core/bench/widget.hs
mit
1,816
0
14
429
468
265
203
37
1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Util.Dzen -- Copyright : (c) [email protected] -- License : BSD -- -- Maintainer : [email protected] -- Stability : stable -- Portability : unportable -- -- Handy wrapper for dzen. Requires dzen >= 0.2.4. -- ----------------------------------------------------------------------------- module XMonad.Util.Dzen ( -- * Flexible interface dzenConfig, DzenConfig, timeout, font, xScreen, vCenter, hCenter, center, onCurr, x, y, addArgs, -- * Legacy interface dzen, dzenScreen, dzenWithArgs, -- * Miscellaneous seconds, chomp, (>=>), ) where import Control.Monad import XMonad import XMonad.StackSet import XMonad.Util.Run (runProcessWithInputAndWait, seconds) type DzenConfig = (Int, [String]) -> X (Int, [String]) -- | @dzenConfig config s@ will display the string @s@ according to the -- configuration @config@. For example, to display the string @\"foobar\"@ with -- all the default settings, you can simply call -- -- > dzenConfig return "foobar" -- -- Or, to set a longer timeout, you could use -- -- > dzenConfig (timeout 10) "foobar" -- -- You can combine configurations with the (>=>) operator. To display -- @\"foobar\"@ for 10 seconds on the first screen, you could use -- -- > dzenConfig (timeout 10 >=> xScreen 0) "foobar" -- -- As a final example, you could adapt the above to display @\"foobar\"@ for -- 10 seconds on the current screen with -- -- > dzenConfig (timeout 10 >=> onCurr xScreen) "foobar" dzenConfig :: DzenConfig -> String -> X () dzenConfig conf s = do (t, args) <- conf (seconds 3, []) runProcessWithInputAndWait "dzen2" args (chomp s) t -- | dzen wants exactly one newline at the end of its input, so this can be -- used for your own invocations of dzen. However, all functions in this -- module will call this for you. chomp :: String -> String chomp = (++"\n") . reverse . dropWhile ('\n' ==) . reverse -- | Set the timeout, in seconds. This defaults to 3 seconds if not -- specified. timeout :: Rational -> DzenConfig timeout = timeoutMicro . seconds -- | Set the timeout, in microseconds. Mostly here for the legacy -- interface. timeoutMicro :: Int -> DzenConfig timeoutMicro n (_, ss) = return (n, ss) -- | Add raw command-line arguments to the configuration. These will be -- passed on verbatim to dzen2. The default includes no arguments. addArgs :: [String] -> DzenConfig addArgs ss (n, ss') = return (n, ss ++ ss') -- | Start dzen2 on a particular screen. Only works with versions of dzen -- that support the "-xs" argument. xScreen :: ScreenId -> DzenConfig xScreen sc = addArgs ["-xs", show (fromIntegral sc + 1 :: Int)] -- | Take a screen-specific configuration and supply it with the screen ID -- of the currently focused screen, according to xmonad. For example, show -- a 100-pixel wide bar centered within the current screen, you could use -- -- > dzenConfig (onCurr (hCenter 100)) "foobar" -- -- Of course, you can still combine these with (>=>); for example, to center -- the string @\"foobar\"@ both horizontally and vertically in a 100x14 box -- using the lovely Terminus font, you could use -- -- > terminus = "-*-terminus-*-*-*-*-12-*-*-*-*-*-*-*" -- > dzenConfig (onCurr (center 100 14) >=> font terminus) "foobar" onCurr :: (ScreenId -> DzenConfig) -> DzenConfig onCurr f conf = gets (screen . current . windowset) >>= flip f conf -- | Put the top of the dzen bar at a particular pixel. x :: Int -> DzenConfig x n = addArgs ["-x", show n] -- | Put the left of the dzen bar at a particular pixel. y :: Int -> DzenConfig y n = addArgs ["-y", show n] -- | Specify the font. Check out xfontsel to get the format of the String -- right; if your dzen supports xft, then you can supply that here, too. font :: String -> DzenConfig font fn = addArgs ["-fn", fn] -- | @vCenter height sc@ sets the configuration to have the dzen bar appear -- on screen @sc@ with height @height@, vertically centered with respect to -- the actual size of that screen. vCenter :: Int -> ScreenId -> DzenConfig vCenter = center' rect_height "-h" "-y" -- | @hCenter width sc@ sets the configuration to have the dzen bar appear -- on screen @sc@ with width @width@, horizontally centered with respect to -- the actual size of that screen. hCenter :: Int -> ScreenId -> DzenConfig hCenter = center' rect_width "-w" "-x" -- | @center width height sc@ sets the configuration to have the dzen bar -- appear on screen @sc@ with width @width@ and height @height@, centered -- both horizontally and vertically with respect to the actual size of that -- screen. center :: Int -> Int -> ScreenId -> DzenConfig center width height sc = hCenter width sc >=> vCenter height sc -- Center things along a single dimension on a particular screen. center' :: (Rectangle -> Dimension) -> String -> String -> Int -> ScreenId -> DzenConfig center' selector extentName positionName extent sc conf = do rect <- gets (detailFromScreenId sc . windowset) case rect of Nothing -> return conf Just r -> addArgs [extentName , show extent, positionName, show ((fromIntegral (selector r) - extent) `div` 2), "-xs" , show (fromIntegral sc + 1 :: Int) ] conf -- Get the rectangle outlining a particular screen. detailFromScreenId :: ScreenId -> WindowSet -> Maybe Rectangle detailFromScreenId sc ws = fmap screenRect maybeSD where c = current ws v = visible ws mapping = map (\s -> (screen s, screenDetail s)) (c:v) maybeSD = lookup sc mapping -- | @dzen str timeout@ pipes @str@ to dzen2 for @timeout@ microseconds. -- Example usage: -- -- > dzen "Hi, mom!" (5 `seconds`) dzen :: String -> Int -> X () dzen = flip (dzenConfig . timeoutMicro) -- | @dzen str args timeout@ pipes @str@ to dzen2 for @timeout@ seconds, passing @args@ to dzen. -- Example usage: -- -- > dzenWithArgs "Hi, dons!" ["-ta", "r"] (5 `seconds`) dzenWithArgs :: String -> [String] -> Int -> X () dzenWithArgs str args t = dzenConfig (timeoutMicro t >=> addArgs args) str -- | @dzenScreen sc str timeout@ pipes @str@ to dzen2 for @timeout@ microseconds, and on screen @sc@. -- Requires dzen to be compiled with Xinerama support. dzenScreen :: ScreenId -> String -> Int -> X () dzenScreen sc str t = dzenConfig (timeoutMicro t >=> xScreen sc) str
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Util/Dzen.hs
bsd-2-clause
6,457
0
19
1,303
1,080
614
466
73
2
import Test.Hspec import qualified YesodCoreTest main :: IO () main = hspec YesodCoreTest.specs
psibi/yesod
yesod-core/test/test.hs
mit
97
0
6
14
30
16
14
4
1
{-# LANGUAGE GADTs #-} module Main where import Data.IORef data T a where Li:: Int -> T Int Lb:: Bool -> T Bool La:: a -> T a writeInt:: T a -> IORef a -> IO () writeInt v ref = case v of ~(Li x) -> writeIORef ref (1::Int) readBool:: T a -> IORef a -> IO () readBool v ref = case v of ~(Lb x) -> readIORef ref >>= (print . not) tt::T a -> IO () tt v = case v of ~(Li x) -> print "OK" main = do tt (La undefined) ref <- newIORef undefined writeInt (La undefined) ref readBool (La undefined) ref
ezyang/ghc
testsuite/tests/gadt/rw.hs
bsd-3-clause
610
0
10
225
278
135
143
22
1
-- | Register available actions and how they will be called module Shaker.PluginConfig where import qualified Data.Map as M (fromList) import Shaker.Type import Shaker.Action.Test import Shaker.Action.Compile import Shaker.Action.Standard -- | The default plugin map contains mapping for compile, help and exit action defaultPluginMap :: PluginMap defaultPluginMap = M.fromList $ map (\(a,b) -> (a, runStartAction >> b >> runEndAction)) list where list = [ (Compile,runCompile ), (FullCompile,runFullCompile ), (Help,runHelp), (InvalidAction,runInvalidAction), (TestFramework , runTestFramework), (ModuleTestFramework , runModuleTestFramework), (Empty,runEmpty), (Clean,runClean), (Quit,runExit) ] defaultCommandMap :: CommandMap defaultCommandMap = M.fromList list where list = [ ("compile",Compile), ("fullcompile",FullCompile), ("help", Help), ("test", TestFramework ), ("test-module", ModuleTestFramework), ("clean",Clean), ("quit",Quit) ]
bonnefoa/Shaker
src/Shaker/PluginConfig.hs
isc
1,207
0
11
365
266
170
96
28
1
import Common main = print $ foldl (\acc x -> 10*acc + x) 0 $take 10 $ toDigits $ sum numbers numbers = [ 37107287533902102798797998220837590246510135740250, 46376937677490009712648124896970078050417018260538, 74324986199524741059474233309513058123726617309629, 91942213363574161572522430563301811072406154908250, 23067588207539346171171980310421047513778063246676, 89261670696623633820136378418383684178734361726757, 28112879812849979408065481931592621691275889832738, 44274228917432520321923589422876796487670272189318, 47451445736001306439091167216856844588711603153276, 70386486105843025439939619828917593665686757934951, 62176457141856560629502157223196586755079324193331, 64906352462741904929101432445813822663347944758178, 92575867718337217661963751590579239728245598838407, 58203565325359399008402633568948830189458628227828, 80181199384826282014278194139940567587151170094390, 35398664372827112653829987240784473053190104293586, 86515506006295864861532075273371959191420517255829, 71693888707715466499115593487603532921714970056938, 54370070576826684624621495650076471787294438377604, 53282654108756828443191190634694037855217779295145, 36123272525000296071075082563815656710885258350721, 45876576172410976447339110607218265236877223636045, 17423706905851860660448207621209813287860733969412, 81142660418086830619328460811191061556940512689692, 51934325451728388641918047049293215058642563049483, 62467221648435076201727918039944693004732956340691, 15732444386908125794514089057706229429197107928209, 55037687525678773091862540744969844508330393682126, 18336384825330154686196124348767681297534375946515, 80386287592878490201521685554828717201219257766954, 78182833757993103614740356856449095527097864797581, 16726320100436897842553539920931837441497806860984, 48403098129077791799088218795327364475675590848030, 87086987551392711854517078544161852424320693150332, 59959406895756536782107074926966537676326235447210, 69793950679652694742597709739166693763042633987085, 41052684708299085211399427365734116182760315001271, 65378607361501080857009149939512557028198746004375, 35829035317434717326932123578154982629742552737307, 94953759765105305946966067683156574377167401875275, 88902802571733229619176668713819931811048770190271, 25267680276078003013678680992525463401061632866526, 36270218540497705585629946580636237993140746255962, 24074486908231174977792365466257246923322810917141, 91430288197103288597806669760892938638285025333403, 34413065578016127815921815005561868836468420090470, 23053081172816430487623791969842487255036638784583, 11487696932154902810424020138335124462181441773470, 63783299490636259666498587618221225225512486764533, 67720186971698544312419572409913959008952310058822, 95548255300263520781532296796249481641953868218774, 76085327132285723110424803456124867697064507995236, 37774242535411291684276865538926205024910326572967, 23701913275725675285653248258265463092207058596522, 29798860272258331913126375147341994889534765745501, 18495701454879288984856827726077713721403798879715, 38298203783031473527721580348144513491373226651381, 34829543829199918180278916522431027392251122869539, 40957953066405232632538044100059654939159879593635, 29746152185502371307642255121183693803580388584903, 41698116222072977186158236678424689157993532961922, 62467957194401269043877107275048102390895523597457, 23189706772547915061505504953922979530901129967519, 86188088225875314529584099251203829009407770775672, 11306739708304724483816533873502340845647058077308, 82959174767140363198008187129011875491310547126581, 97623331044818386269515456334926366572897563400500, 42846280183517070527831839425882145521227251250327, 55121603546981200581762165212827652751691296897789, 32238195734329339946437501907836945765883352399886, 75506164965184775180738168837861091527357929701337, 62177842752192623401942399639168044983993173312731, 32924185707147349566916674687634660915035914677504, 99518671430235219628894890102423325116913619626622, 73267460800591547471830798392868535206946944540724, 76841822524674417161514036427982273348055556214818, 97142617910342598647204516893989422179826088076852, 87783646182799346313767754307809363333018982642090, 10848802521674670883215120185883543223812876952786, 71329612474782464538636993009049310363619763878039, 62184073572399794223406235393808339651327408011116, 66627891981488087797941876876144230030984490851411, 60661826293682836764744779239180335110989069790714, 85786944089552990653640447425576083659976645795096, 66024396409905389607120198219976047599490197230297, 64913982680032973156037120041377903785566085089252, 16730939319872750275468906903707539413042652315011, 94809377245048795150954100921645863754710598436791, 78639167021187492431995700641917969777599028300699, 15368713711936614952811305876380278410754449733078, 40789923115535562561142322423255033685442488917353, 44889911501440648020369068063960672322193204149535, 41503128880339536053299340368006977710650566631954, 81234880673210146739058568557934581403627822703280, 82616570773948327592232845941706525094512325230608, 22918802058777319719839450180888072429661980811197, 77158542502016545090413245809786882778948721859617, 72107838435069186155435662884062257473692284509516, 20849603980134001723930671666823555245252804609722, 53503534226472524250874054075591789781264330331690]
lekto/haskell
Project-Euler-Solutions/problem0013.hs
mit
5,409
0
12
227
357
229
128
103
1
module U.Codebase.Sqlite.Patch.Format where import Data.Vector (Vector) import U.Codebase.Sqlite.DbId (HashId, ObjectId, PatchObjectId, TextId) import U.Codebase.Sqlite.Patch.Diff (LocalPatchDiff) import U.Codebase.Sqlite.Patch.Full (LocalPatch) import Data.ByteString (ByteString) data PatchFormat = Full PatchLocalIds LocalPatch | Diff PatchObjectId PatchLocalIds LocalPatchDiff data PatchLocalIds = LocalIds { patchTextLookup :: Vector TextId, patchHashLookup :: Vector HashId, patchDefnLookup :: Vector ObjectId } data SyncPatchFormat = SyncFull PatchLocalIds ByteString | SyncDiff PatchObjectId PatchLocalIds ByteString
unisonweb/platform
codebase2/codebase-sqlite/U/Codebase/Sqlite/Patch/Format.hs
mit
648
0
9
84
152
93
59
16
0
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, TypeFamilies #-} module Main where import Data.Bits import Data.Monoid import Control.Monad import Control.Exception import System.Socket import System.Socket.Family.Inet as Inet import System.Exit main :: IO () main = do t0001 t0002 t0003 t0001 :: IO () t0001 = do ais <- getAddressInfo (Just "127.0.0.1") (Just "http") aiNumericHost `onException` p 0 :: IO [AddressInfo Inet Stream TCP] when (length ais /= 1) (e 1) let [ai] = ais when (canonicalName ai /= Nothing) (e 2) let sa = socketAddress ai when (port sa /= 80) (e 3) when (address sa /= Inet.loopback) (e 4) where p i = print ("t0001." ++ show i) e i = error ("t0001." ++ show i) t0002 :: IO () t0002 = do let x = getAddressInfo Nothing Nothing mempty :: IO [AddressInfo Inet Stream TCP] eui <- tryJust (\ex@(AddressInfoException _)-> if ex == eaiNoName then Just () else Nothing) (x `onException` p 0) when (eui /= Left ()) (e 1) where p i = print ("t0002." ++ show i) e i = error ("t0002." ++ show i) -- | This tests the correct funtionality of the flags -- AI_V4MAPPEND and AI_ALL. Asking for localhost should -- yield an additional v4-mappend IPV6-Address in the second case, -- but not in the first one. t0003 :: IO () t0003 = do x <- getAddressInfo (Just "localhost") Nothing mempty `onException` p 0:: IO [AddressInfo Inet6 Stream TCP] y <- getAddressInfo (Just "localhost") Nothing (aiAll `mappend` aiV4Mapped) `onException` p 1 :: IO [AddressInfo Inet6 Stream TCP] when (length x == length y) (e 2) where p i = print ("t0003." ++ show i) e i = error ("t0003." ++ show i)
nh2/haskell-socket
tests/AddrInfo.hs
mit
1,838
0
13
520
665
332
333
55
2
module Twelve where import Data.Char (toUpper) import Data.List (intersperse, unfoldr) notThe :: String -> Maybe String notThe w | w == "the" || w == "The" = Nothing | otherwise = Just w removeThe :: Maybe String -> String removeThe (Just x) = x removeThe Nothing = "a" replaceThe :: String -> String replaceThe s = concat $ intersperse " " $ fmap (removeThe . notThe) w where w = words s isVowel :: Char -> Bool isVowel letter = elem (toUpper letter) "AEIOU" counter :: (Bool, Integer) -> String -> (Bool, Integer) counter (_, cnt) "the" = (True, cnt) counter (True, cnt) (w:ws) = if isVowel w then (False, cnt+1) else (False, cnt) counter (False, cnt) _ = (False, cnt) countTheBeforeVowel :: String -> Integer countTheBeforeVowel s = (\(_, cnt) -> cnt) $ foldl counter (False, 0) w where w = words s countVowels :: String -> Integer countVowels s = (toInteger . length) $ filter isVowel s newtype Word' = Word' String deriving (Eq, Show) mkWord :: String -> Maybe Word' mkWord s = go s (0, 0) where go [] (consonants, vowels) = if vowels > consonants then Nothing else Just (Word' s) go (x:xs) (consonants, vowels) | isVowel x = go xs (consonants, vowels + 1) | otherwise = go xs (consonants + 1, vowels) data Nat = Zero | Succ Nat deriving (Eq, Show) natToInteger :: Nat -> Integer natToInteger Zero = 0 natToInteger (Succ nat) = 1 + (natToInteger nat) integerToNat :: Integer -> Maybe Nat integerToNat i | i < 0 = Nothing | otherwise = Just (go i) where go int | int == 0 = Zero | otherwise = (Succ (go (int - 1))) isJust :: Maybe a -> Bool isJust Nothing = False isJust (Just _) = True isNothing :: Maybe a -> Bool isNothing Nothing = True isNothing (Just _) = False mayybee :: b -> (a -> b) -> Maybe a -> b mayybee b _ Nothing = b mayybee _ f (Just a) = f a fromMaybe :: a -> Maybe a -> a fromMaybe a m = mayybee a id m listToMaybe :: [a] -> Maybe a listToMaybe [] = Nothing listToMaybe (x:_) = Just x maybeToList :: Maybe a -> [a] maybeToList (Just a) = [a] maybeToList Nothing = [] catMaybes :: [Maybe a] -> [a] catMaybes ms = foldr f [] ms where f (Just a) b = [a] ++ b f Nothing b = b flipMaybe :: [Maybe a] -> Maybe [a] flipMaybe = foldr f (Just []) where f _ Nothing = Nothing f Nothing _ = Nothing f (Just a) (Just b) = Just ([a] ++ b) lefts' :: [Either a b] -> [a] lefts' = foldr f [] where f (Left a) acc = [a] ++ acc f (Right _) acc = acc rights' :: [Either a b] -> [b] rights' = foldr f [] where f (Left _) acc = acc f (Right b) acc = [b] ++ acc partitionEithers' :: [Either a b] -> ([a], [b]) partitionEithers' = foldr f ([], []) where f (Left a) (lefts, rights) = ([a] ++ lefts, rights) f (Right b) (lefts, rights) = (lefts, [b] ++ rights) eitherMaybe' :: (b -> c) -> Either a b -> Maybe c eitherMaybe' _ (Left _) = Nothing eitherMaybe' f (Right b) = Just (f b) either' :: (a -> c) -> (b -> c) -> Either a b -> c either' f _ (Left a) = f a either' _ g (Right b) = g b eitherMaybe'' :: (b -> c) -> Either a b -> Maybe c eitherMaybe'' _ (Left _) = Nothing eitherMaybe'' g r@(Right b) = Just (either' (\_ -> g b) g r) myIterate :: (a -> a) -> a -> [a] myIterate f a = [a] ++ (myIterate f (f a)) unf :: (Ord b, Num b) => b -> Maybe (b, b) unf n | n > 10 = Nothing | otherwise = Just (n, n + 1) myUnfoldr :: (b -> Maybe (a, b)) -> b -> [a] myUnfoldr f b = go $ f b where go Nothing = [] go (Just (a, nextB)) = [a] ++ (go $ f nextB) betterIterate :: (a -> a) -> a -> [a] betterIterate f x = myUnfoldr (\x -> Just (x, f x)) x
mudphone/HaskellBook
src/Twelve.hs
mit
3,627
0
13
915
1,917
999
918
106
3
-- A tutorial on the universality and expressiveness of fold -- TODO: https://jeremykun.com/tag/foldr/ -- foldr -- f x acc fold :: (a -> b -> b) -> b -> [a] -> b fold f v [] = v fold f v (x:xs) = f x (fold f v xs) -- foldl f v (x:xs) = f (fold f v xs) x -- f acc n product = fold (*) 0 and = fold (&) True or = fold (|) False (++) :: [a] -> [a] -> [a] (++ ys) = fold (:) ys length = fold (\x n -> n + 1) 0 reverse = fold (\x xs -> xs ++ [x]) 0 map f = fold (\x xs -> f x : xs) [] filter p = fold (\x xs -> if p x then x : xs else xs) [] -- recursion theory -- universal property (definition) -- g [] = v -- g (x:xs) = f x (g xs) <=> g = fold f v -- (+1) . sum = fold (+) 1 -- (+1) . sum [] = 1 -- (+1) . sum (x : xs) = (+) x (((+1) . sum) xs) -- fusion property -- h w = v -- h (g x y) = f x (h y) <=> h . fold g w = fold f v -- (+1) . sum = fold (+) 1 -- (+1) . fold (+) 0 = fold (+) 1 -- (+1) 0 = 1 -- (+1) ((+) x y) = (+) x ((+1) y) -- infix n op -- (op a) . fold (op) b = fold (op) (b op a) -- map f = fold (\x xs -> f x : xs) [] -- map f [] = [] -- map f (g x : y) = (f . g) x : map f y -- generate tuples -- sum and length sumLength :: [Int] -> (Int, Int) -- sumLength xs = (sum xs, length xs) sumLength = fold (\n (x, y) -> (n + x, 1 + y)) (0, 0) -- cannot be implemented as fold because xs is stateless dropWhile :: (a -> Bool) -> [a] -> [a] -- using tupling techniques we can redefine it dropWhile' :: (a -> Bool) -> ([a] -> ([a], [a])) dropWhile' p = fold f v where f x (ys, xs) = (if p x then ys else x : xs, x : xs) v = ([], []) -- primitive recursion -- h y [] = f y -- h y (x:xs) = g y x (h y xs) -- h y = fold (g y) (f y) -- primitive recursion -- h y [] = f y -- h y (x:xs) = g y x xs (h y xs) -- k y [] = (f y, []) -- k y xs = (h y xs, xs) -- k y [] = j -- k y (x:xs) = i x (k y xs) -- k y = fold i j where -- i x (z, xs) = (g y x xs, x : xs) -- j = (f y, []) -- h y = fst . k y -- generate functions compose :: [a -> a] -> a -> a compose = fold (.) id -- right to left sum :: [Int] -> Int sum = fold (+) 0 suml :: [Int] -> Int suml xs = suml' xs 0 where suml' [] n = n suml' (x:xs) n = suml' xs (n + x) -- suml' :: [Int] -> Int -> Int -- suml' = fold (\x g -> (\n -> g (n + x))) id -- suml xs = fold (\x g -> (\n -> g (n + x))) id xs 0 foldl f v xs = fold (\x g -> (\a -> g (f a x))) id xs v ack :: [Int] -> [Int] -> [Int] ack [] ys = 1 : ys ack (x:xs) [] = ack xs [1] ack (x:xs) (y:ys) = ack xs (ack (x:xs) ys) -- ack = fold (\x g -> fold (\y -> g) ( g [1] )) (1 :) -- Other works -- fold for regular datatypes (not just lists) -- fold for nested datatypes -- fold for functional datatypes -- Monadic fold -- Relational fold -- other reursion operators -- automatic program transformation -- polytypic programming -- programming languages
Airtnp/Freshman_Simple_Haskell_Lib
Theoritical/Universal-fold.hs
mit
2,945
2
12
920
826
479
347
-1
-1
module Countdown where data Op = Add | Sub | Mul | Div instance Show Op where show Add = "+" show Sub = "-" show Mul = "*" show Div = "/" valid :: Op -> Int -> Int -> Bool valid Add _ _ = True valid Sub x y = x > y valid Mul _ _ = True valid Div x y = x `mod` y == 0 apply :: Op -> Int -> Int -> Int apply Add x y = x + y apply Sub x y = x - y apply Mul x y = x * y apply Div x y = x `div` y data Expr = Val Int | App Op Expr Expr instance Show Expr where show (Val n) = show n show (App o l r) = brak l ++ show o ++ brak r where brak (Val n) = show n brak e = "(" ++ show e ++ ")" values :: Expr -> [Int] values (Val n) = [n] values (App _ l r) = values l ++ values r eval :: Expr -> [Int] eval (Val n) = [n | n > 0] eval (App o l r) = [apply o x y | x <- eval l, y <- eval r, valid o x y] computer :: Expr -> Int computer = head . eval
brodyberg/LearnHaskell
CaesarCypher.hsproj/Countdown.hs
mit
1,051
0
10
444
511
261
250
33
1
{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, StandaloneDeriving #-} module Eval where import Prelude hiding (id, exp) import qualified Prelude import Control.Lens hiding (reuses) import Data.Either (partitionEithers) import Data.Map (Map) import qualified Data.Map as Map import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Text as T import Data.Functor.Foldable.Extended import qualified Id import qualified Lam import Lam (BindingWithId, ExpWithId) import qualified Primitives flattenBinding :: BindingWithId i -> Maybe (i, i, Lam.Name, ExpWithId i) flattenBinding binding = flip fmap (Lam.bindingExp binding) $ \exp -> (binding ^. Id.id, Lam.expTopId exp, Lam.bindingName binding, exp) data EvalError i = UndefinedVar i T.Text | UndefinedMember i (Frame i) T.Text | TypeError i (Val i) T.Text deriving (Eq, Ord, Show) type ThunkWithId i = Id.WithId i Identity (Thunk i) data Suspension i = Suspension i (Map i (Val i)) [Suspension i] deriving (Eq, Ord, Show) data Val i = Primitive Primitives.Prim | Thunk [[i]] (Set i) (Env i) (ThunkWithId i) | ValSuspension (Suspension i) | ValFrame (Frame i) | ValList [Val i] deriving (Show, Ord, Eq) type Env i = Map i (Val i) newtype GlobalEnv i = GlobalEnv { unGlobalEnv :: Env i } type Trail i = Set (Frame i, Val i) data Trailing i a = Trailing (Trail i) a data Thunk i = ThunkFn (Env i -> GlobalEnv i -> Either [EvalError i] (Val i)) | ThunkResolvedFn (Frame i -> Env i -> GlobalEnv i -> Lam.Resolved i -> Either [EvalError i] (Trailing i (Val i))) | ThunkEvalFn (Env i -> GlobalEnv i -> (Val i -> Either [EvalError i] (Trailing i (Val i))) -> Either [EvalError i] (Trailing i (Val i))) | ThunkTrailFn (Trail i -> Env i -> GlobalEnv i -> Either [EvalError i] (Val i)) | ThunkExp (ExpWithId i) | ThunkRecord instance Show i => Show (Thunk i) where show (ThunkFn _) = "thunkfn" show (ThunkResolvedFn _) = "thunkresolvedfn" show (ThunkTrailFn _) = "thunktrailfn" show (ThunkEvalFn _) = "thunkevalfn" show (ThunkExp _) = "thunkexp" show (ThunkRecord) = "thunkrecord" pprintVal :: Show i => Val i -> String pprintVal = unlines . go 0 where put indent s = [replicate indent ' ' ++ s] go indent (Primitive p) = put indent ("Primitive " ++ show p) go indent (Thunk ss needed env t) = concat $ [ put indent $ "Thunk " ++ (show $ t ^. Id.id) ++ " " ++ show ss ++ " " ++ (show $ t ^. Id.value) , concat neededArgsRows , put (indent + 2) "has" , concat [ put (indent + 4) (show k) ++ concat [ go (indent + 6) v ] | (k, v) <- Map.assocs env ] ] where neededArgsRows | Set.null needed = [ put (indent + 2) "satisfied" ] | otherwise = [ put (indent + 2) "needs" , concat $ (put (indent + 4) . show) <$> Set.toList needed ] go indent (ValSuspension _) = put indent ("Suspension") go indent (ValFrame frame) = concat [ put indent $ "ValFrame " ++ show (_frameCodeDbId frame) ++ " " ++ show (_frameParent frame) , put (indent + 2) "ValFrameEnv" , concat [ concat [ put (indent + 4) "ValFrameEnvElem" , put (indent + 6) (show k) , go (indent + 8) v ] | (k, v) <- Map.assocs (_frameEnv frame) ] ] go indent (ValList elems) = concat [ put indent "ValList" , concat $ go (indent + 2) <$> elems ] data Frame i = Frame { _frameParent :: Maybe (Frame i) , _frameCodeDbId :: i , _frameEnv :: Env i } deriving (Ord, Eq, Show) makeLenses ''Frame instance (Ord i, Show i, Monoid a) => Monoid (Trailing i a) where mempty = Trailing Set.empty mempty mappend (Trailing t1 v1) (Trailing t2 v2) = Trailing (mappend t1 t2) (mappend v1 v2) instance (Eq a, Eq i) => Eq (Trailing i a) where Trailing t1 v1 == Trailing t2 v2 = (t1 == t2) && (v1 == v2) instance (Show a) => Show (Trailing i a) where show (Trailing _ v1) = show v1 instance Functor (Trailing i) where fmap f (Trailing t v) = Trailing t (f v) instance (Ord i, Show i) => Applicative (Trailing i) where pure v = noTrail v Trailing t1 f <*> Trailing t2 v = Trailing (mappend t1 t2) (f v) noTrail :: Ord i => a -> Trailing i a noTrail v = Trailing mempty v dropTrail :: Trailing t t1 -> t1 dropTrail (Trailing _ v) = v withTrail :: (Trail t -> Trail i) -> Trailing t a -> Trailing i a withTrail f (Trailing t v) = Trailing (f t) v expandTrail :: (Ord i, Show i) => [[i]] -> (Frame i, Val i) -> Trailing i v -> Trailing i v expandTrail [] _ = Prelude.id expandTrail _ frameWithResult = withTrail (Set.insert frameWithResult) withEitherTrail :: (Ord i, Show i) => (v1 -> Either e (Trailing i v2)) -> Either e (Trailing i v1) -> Either e (Trailing i v2) withEitherTrail f e = do Trailing t1 v1 <- e Trailing t2 v2 <- f v1 pure $ Trailing (t1 `mappend` t2) v2 invertTrailingEither :: Trailing i (Either e v) -> Either e (Trailing i v) invertTrailingEither (Trailing t v) = Trailing t <$> v eval :: (Ord i, Show i) => Lam.Resolved i -> GlobalEnv i -> Frame i -> Map i (Val i) -> Trail i -> ExpWithId i -> Either [EvalError i] (Trailing i (Val i)) eval resolved globalEnv parentFrames env trail (Fix (Lam.ExpW (Id.WithId id (Identity v)))) = withEitherTrail (evalVal resolved globalEnv parentFrames env trail) $ case v of Lam.LamF susable args exp -> let argIds = map (^. Id.id) args in noTrail <$> (Thunk <$> flattenSusable resolved id susable <*> pure (Set.fromList argIds) <*> pure env <*> pure (Id.withId id (ThunkExp exp))) Lam.AppF exp args -> flip withEitherTrail (evalArgs resolved globalEnv parentFrames env trail args) $ \argValues -> eval resolved globalEnv parentFrames (Map.union argValues env) trail exp Lam.LamArgIdF var -> case lookupVarId id resolved of Nothing -> Left [UndefinedVar id var] Just varId -> Right $ noTrail $ ValSuspension (Suspension varId Map.empty []) Lam.VarF var -> case lookupVar id resolved env globalEnv of Nothing -> Left [UndefinedVar id var] Just val -> Right $ noTrail val Lam.SuspendF suspendSpec -> let evalSuspension (Lam.SuspendSpec (Id.WithId suspensionId (Identity name)) args parents) = do case Map.lookup suspensionId resolved of Nothing -> Left [UndefinedVar id name] Just resolvedId -> do argsEnv <- evalArgs resolved globalEnv parentFrames env trail args parentSuspensions <- eitherList $ (evalSuspension <$> parents) pure $ Suspension resolvedId (dropTrail argsEnv) parentSuspensions -- noTrail . dropTrail is pretty weird! But since we're evaluating things to specify a suspension, we're kind of not in the real world maybe? Perhaps these shouldn't be expressions in their own right, but references to expressions in the tree that are fully legit? That way there wouldn't be this weird case where expressions don't leave a trail. We don't have a good 'syntax' for referring to expressions like that though. in noTrail . ValSuspension <$> evalSuspension suspendSpec Lam.LitF (Lam.Number n) -> pure $ noTrail $ Primitive $ Primitives.Number n Lam.LitF (Lam.Text n) -> pure $ noTrail $ Primitive $ Primitives.Text n evalArgs :: (Ord i, Show i) => Lam.Resolved i -> GlobalEnv i -> Frame i -> Map i (Val i) -> Trail i -> [(Id.WithId i Identity Lam.Name, ExpWithId i)] -> Either [EvalError i] (Trailing i (Map i (Val i))) evalArgs resolved globalEnv parentFrame env trail args = let evalArg (Id.WithId argId (Identity argName), exp) = case Map.lookup argId resolved of Just resolvedArgId -> fmap (resolvedArgId,) <$> eval resolved globalEnv parentFrame env trail exp Nothing -> Left [UndefinedVar argId argName] in fmap (fmap Map.fromList . sequenceA) . eitherList $ evalArg <$> args eitherList :: Monoid e => [Either e r] -> Either e [r] eitherList es = case partitionEithers es of ([], successesList) -> Right successesList (failuresList, _) -> Left (mconcat failuresList) evalVal :: (Ord i, Show i) => Lam.Resolved i -> GlobalEnv i -> Frame i -> Map i (Val i) -> Trail i -> Val i -> Either [EvalError i] (Trailing i (Val i)) evalVal resolved globalEnv parentFrames env trail (Thunk thunkSusable thunkArgs thunkEnv thunk) = let argsInEnv = Set.intersection thunkArgs (Map.keysSet env) argsEnv = Map.filterWithKey (\k _ -> k `Set.member` argsInEnv) env thunkEnv' = Map.unions [env, argsEnv, thunkEnv] in if Set.size argsInEnv == Set.size thunkArgs then fmap (fmap (reSus thunkSusable)) . evalThunk resolved globalEnv parentFrames trail thunkSusable thunkEnv' argsEnv $ thunk else Right $ noTrail $ Thunk thunkSusable thunkArgs thunkEnv' thunk evalVal _ _ _ _ _ v = Right $ noTrail v evalThunk :: (Show i, Ord i) => Lam.Resolved i -> GlobalEnv i -> Frame i -> Trail i -> [[i]] -> Env i -> Env i -> Id.WithId i Identity (Thunk i) -> Either [EvalError i] (Trailing i (Val i)) evalThunk resolved globalEnv parentFrame trail susable thunkEnv argsEnv thunk = let newFrame = Frame (Just parentFrame) (thunk ^. Id.id) argsEnv in do result <- withEitherTrail (evalVal resolved globalEnv newFrame thunkEnv trail . reSus susable) $ case Id.unId thunk of ThunkFn fn -> fmap noTrail $ fn thunkEnv globalEnv ThunkTrailFn fn -> fmap noTrail $ fn trail thunkEnv globalEnv ThunkResolvedFn fn -> fn newFrame thunkEnv globalEnv resolved ThunkEvalFn fn -> fn thunkEnv globalEnv (evalVal resolved globalEnv newFrame thunkEnv trail) ThunkExp exp -> eval resolved globalEnv newFrame thunkEnv trail exp ThunkRecord -> pure . pure . ValFrame $ newFrame let finalSusable = case result of Trailing _ (Thunk s _ _ _) -> s ++ susable _ -> susable pure $ expandTrail finalSusable (newFrame, dropTrail result) result reSus :: [[i]] -> Val i -> Val i reSus susable (Thunk susable' a e t) = Thunk (susable' ++ susable) a e t reSus _ v = v lookupVar :: (Ord i, Show i) => i -> Lam.Resolved i -> Map i (Val i) -> GlobalEnv i -> Maybe (Val i) lookupVar id resolved env globalEnv = maybe Nothing (lookupVarByResolvedId env globalEnv) $ lookupVarId id resolved lookupVarByResolvedId :: Ord i => Map i (Val i) -> GlobalEnv i -> i -> Maybe (Val i) lookupVarByResolvedId env globalEnv k = case Map.lookup k env of Just x -> Just x Nothing -> Map.lookup k . unGlobalEnv $ globalEnv lookupVarId :: Ord k => k -> Map k a -> Maybe a lookupVarId id resolved = Map.lookup id resolved flattenSusable :: (Show i, Ord i) => Lam.Resolved i -> i -> Lam.Susable (Id.WithId i Identity) -> Either [EvalError i] [[i]] flattenSusable resolved errId (Lam.Susable ss) = eitherList ((\s -> eitherList (go <$> s)) <$> ss) where go (Id.WithId id (Identity name)) = maybe (Left [UndefinedVar errId name]) Right (Map.lookup id resolved)
imccoy/utopia
src/Eval.hs
mit
12,800
0
23
4,348
4,523
2,253
2,270
-1
-1
import Data.Tuple import Data.Maybe import Data.List.Extra import Data.Map (Map) import qualified Data.Map as M test1_map :: OrbitMap test1_map = mkMap [ "COM)B", "B)C", "C)D", "D)E", "E)F", "B)G", "G)H", "D)I", "E)J", "J)K", "K)L"] test2_map :: OrbitMap test2_map = mkMap [ "COM)B", "B)C", "C)D", "D)E", "E)F", "B)G", "G)H", "D)I", "E)J", "J)K", "K)L", "K)YOU", "I)SAN"] type Pair = (String,String) toPair :: String -> Pair toPair xs = (a,b) where [a,b] = splitOn ")" xs type OrbitMap = Map String String mkMap :: [String] -> OrbitMap mkMap = M.fromList . map (swap . toPair) get :: String -> OrbitMap -> [String] get s m = takeWhile (/= "COM") $ iterate look s where look s' = let fnd = M.lookup s' m in fromMaybe "COM" fnd -- 278744 part_1 :: OrbitMap -> Int part_1 m = sum $ length . flip get m <$> ks where ks = M.keys m -- 475 part_2 :: OrbitMap -> Int part_2 m = yn + sn where you = reverse $ get "YOU" m san = reverse $ get "SAN" m zz = takeWhile (uncurry (==)) $ zip you san lz = length zz you' = drop lz you san' = drop lz san yn = pred $ length you' sn = pred $ length san' main :: IO () main = do print $ part_1 test1_map print $ part_2 test2_map mps <- mkMap . lines <$> getContents print $ part_1 mps print $ part_2 mps
wizzup/advent_of_code
2019/haskell/exe/Day06.hs
mit
1,355
0
12
360
552
297
255
63
1
-- (220、284)、(1,184、1,210)、(2,620、2,924)、(5,020、5,564)、(6,232、6,368)、 -- import System.Environment amicable :: Int -> Int -> Bool amicable n m | sum(propDivis n) /= m = False | otherwise = sum(propDivis m) == n amicables :: Int -> [[Int]] amicables n = [[i,j]|i<-[4..n],j<-[i..min n (i*16`div`10)],amicable i j] propDivis :: Int -> [Int] propDivis n = [i | i<-[1..(n-1)], n `mod` i == 0] answer' n = concat [ps | ps<-amicables n] answer n = concat [if p/=q then p:q:[] else [] | (p:q:[])<-amicables n] main = do args <- getArgs let n = read (head args) print $ answer' n print $ sum $ answer' n print $ answer n print $ sum $ answer n
yuto-matsum/contest-util-hs
src/Euler/021.hs
mit
689
0
12
145
379
192
187
18
2
{- Copyright (c) 2008-2015 the Urho3D project. 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. -} module Mover where import Data.IORef import Foreign import Control.Lens hiding (Context, element) import Graphics.Urho3D import Sample -- | Custom logic component for moving the animated model and rotating at area edges. type Mover = CustomLogicComponent -- | Internal state of component data MoverState = MoverState { moverSpeed :: Float -- ^ Forward movement speed. , moverRotateSpeed :: Float -- ^ Rotation speed. , moverBounds :: BoundingBox -- ^ Movement boundaries. } -- | Custom logic component setup that holds state and callbacks. type MoverSetup = CustomLogicComponentSetup MoverState -- | Type hash of our mover component type MoverType = StringHash -- | Register mover within Urho engine, resulting type is used for creation of -- the component instances. registerMover :: MonadIO m => Ptr Context -> m MoverType registerMover cntx = registerCustomComponent cntx "Mover" moverState moverDef where moverState = MoverState { moverSpeed = 0 , moverRotateSpeed = 0 , moverBounds = 0 } -- | Update internal state of mover. Set motion parameters: forward movement speed, rotation speed, and movement boundaries. setMoverParameters :: MonadIO m => Ptr Mover -> Float -> Float -> BoundingBox -> m () setMoverParameters ptr moveSpeed rotateSpeed bounds = liftIO $ do ref <- getCustomComponentState ptr writeIORef ref $ MoverState { moverSpeed = moveSpeed , moverRotateSpeed = rotateSpeed , moverBounds = bounds } -- | Return forward movement speed. moverGetMoveSpeed :: MonadIO m => Ptr Mover -> m Float moverGetMoveSpeed ptr = liftIO $ do ref <- getCustomComponentState ptr moverSpeed <$> readIORef ref -- | Return rotation speed. moverGetRotationSpeed :: MonadIO m => Ptr Mover -> m Float moverGetRotationSpeed ptr = liftIO $ do ref <- getCustomComponentState ptr moverRotateSpeed <$> readIORef ref -- | Return movement boundaries. moverGetBounds :: MonadIO m => Ptr Mover -> m BoundingBox moverGetBounds ptr = liftIO $ do ref <- getCustomComponentState ptr moverBounds <$> readIORef ref -- | Custom logic component for rotating a scene node. moverDef :: MoverSetup moverDef = defaultCustomLogicComponent { componentUpdate = Just $ \ref compNode t -> do -- Component state is passed via reference MoverState {..} <- readIORef ref nodeTranslate compNode (vec3Forward * vec3 (moverSpeed * t)) TSLocal -- If in risk of going outside the plane, rotate the model right pos <- nodeGetPosition compNode when ((pos ^. x < moverBounds ^. minVector ^. x) || (pos ^. x > moverBounds ^. maxVector ^. x) || (pos ^. z < moverBounds ^. minVector ^. z) || (pos ^. z > moverBounds ^. maxVector ^. z)) $ nodeYaw compNode (moverRotateSpeed * t) TSLocal -- Get the model's first (only) animation state and advance its time. Note the convenience accessor to other components -- in the same scene node (model :: Ptr AnimatedModel) <- fromJustTrace "AnimatedModel mover" <$> nodeGetComponent compNode False whenM ((> 0) <$> animatedModelGetNumAnimationStates model) $ do states <- animatedModelGetAnimationStates model animationStateAddTime (head states) t }
Teaspot-Studio/Urho3D-Haskell
app/sample06/Mover.hs
mit
4,305
0
21
832
699
361
338
-1
-1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import qualified Map import Control.Applicative import Control.Concurrent.Async import Control.Concurrent.MSem import Control.Concurrent.Timeout import Control.Monad.Catch import Control.Monad import Data.Time.Clock.POSIX import Data.Timeout import System.Environment import System.IO import Text.Printf import Language.Haskell.Liquid.Types (GhcSpec) import Test.Target import Test.Target.Monad instance Show (a -> b) where show _ = "<function>" main :: IO () main = do [t] <- getArgs withFile ("_results/Map-" ++ t ++ ".tsv") WriteMode $ \h -> do hPutStrLn h "Function\tDepth\tTime(s)\tResult" mapPool 12 (checkMany h (read t # Minute)) funs putStrLn "done" putStrLn "" mapPool max f xs = do sem <- new max mapConcurrently (with sem . f) xs checkMany :: Handle -> Timeout -> (Test, String) -> IO [(Int, Double, Outcome)] checkMany h time (f,sp) = putStrNow (printf "Testing %s..\n" sp) >> go 2 where go 21 = return [] go n = checkAt f sp n time >>= \case (d,Nothing) -> do let s = printf "%s\t%d\t%.2f\t%s" sp n d (show TimeOut) putStrLn s >> hFlush stdout hPutStrLn h s >> hFlush h return [(n,d,TimeOut)] --NOTE: timeout is a bit unreliable.. (d,_) | round d >= time #> Second -> do let s = printf "%s\t%d\t%.2f\t%s" sp n d (show TimeOut) putStrLn s >> hFlush stdout hPutStrLn h s >> hFlush h putStrLn "WARNING: timeout seems to have been ignored..." return [(n,d,TimeOut)] --NOTE: sometimes the timeout causes an error instead of a timeout exn (d,Just (Errored s)) -> return [(n,d,Complete (Errored s))] --NOTE: ignore counter-examples for the sake of exploring coverage --(d,Just (Failed s)) -> return [(n,d,Complete (Failed s))] (d,Just r) -> do let s = printf "%s\t%d\t%.2f\t%s" sp n d (show (Complete r)) putStrLn s >> hFlush stdout hPutStrLn h s >> hFlush h ((n,d,Complete r):) <$> go (n+1) checkAt :: Test -> String -> Int -> Timeout -> IO (Double, Maybe Result) checkAt (T f) sp n time = timed $ do r <- try $ timeout time $ targetResultWithStr f sp "bench/Map.hs" (defaultOpts {logging=False, keepGoing = True, depth = n}) case r of Left (e :: SomeException) -> return $ Just $ Errored $ show e Right r -> return r -- time = 5 # Minute getTime :: IO Double getTime = realToFrac `fmap` getPOSIXTime timed x = do start <- getTime v <- x end <- getTime return (end-start, v) putStrNow s = putStr s >> hFlush stdout data Outcome = Complete Result | TimeOut deriving (Show) funs :: [(Test,String)] funs = [(T ((Map.!) :: Map.Map Map.Char () -> Map.Char -> ()), "Map.!") ,(T ((Map.\\) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.\\\\") ,(T ((Map.null) :: Map.Map Map.Char () -> Map.Bool), "Map.null") ,(T ((Map.lookup) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe ()), "Map.lookup") ,(T ((Map.member) :: Map.Char -> Map.Map Map.Char () -> Map.Bool), "Map.member") ,(T ((Map.notMember) :: Map.Char -> Map.Map Map.Char () -> Map.Bool), "Map.notMember") ,(T ((Map.findWithDefault) :: () -> Map.Char -> Map.Map Map.Char () -> ()), "Map.findWithDefault") ,(T ((Map.lookupLT) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe (Map.Char, ())), "Map.lookupLT") ,(T ((Map.lookupGT) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe (Map.Char, ())), "Map.lookupGT") ,(T ((Map.lookupLE) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe (Map.Char, ())), "Map.lookupLE") ,(T ((Map.lookupGE) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe (Map.Char, ())), "Map.lookupGE") ,(T ((Map.singleton) :: Map.Char -> () -> Map.Map Map.Char ()), "Map.singleton") ,(T ((Map.insert) :: Map.Char -> () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.insert") ,(T ((Map.insertWith) :: (() -> () -> ())-> Map.Char -> () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.insertWith") ,(T ((Map.insertWithKey) :: (Map.Char -> () -> () -> ())-> Map.Char -> () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.insertWithKey") ,(T ((Map.insertLookupWithKey) :: (Map.Char -> () -> () -> ())-> Map.Char-> ()-> Map.Map Map.Char ()-> (Map.Maybe (), Map.Map Map.Char ())), "Map.insertLookupWithKey") ,(T ((Map.delete) :: Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.delete") ,(T ((Map.adjust) :: (() -> ())-> Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.adjust") ,(T ((Map.adjustWithKey) :: (Map.Char -> () -> ())-> Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.adjustWithKey") ,(T ((Map.update) :: (() -> Map.Maybe ())-> Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.update") ,(T ((Map.updateWithKey) :: (Map.Char -> () -> Map.Maybe ())-> Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateWithKey") ,(T ((Map.updateLookupWithKey) :: (Map.Char -> () -> Map.Maybe ())-> Map.Char-> Map.Map Map.Char ()-> (Map.Maybe (), Map.Map Map.Char ())), "Map.updateLookupWithKey") ,(T ((Map.alter) :: (Map.Maybe () -> Map.Maybe ())-> Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.alter") ,(T ((Map.findIndex) :: Map.Char -> Map.Map Map.Char () -> Map.Int), "Map.findIndex") ,(T ((Map.lookupIndex) :: Map.Char -> Map.Map Map.Char () -> Map.Maybe Map.Int), "Map.lookupIndex") ,(T ((Map.elemAt) :: Map.Int -> Map.Map Map.Char () -> (Map.Char, ())), "Map.elemAt") ,(T ((Map.updateAt) :: (Map.Char -> () -> Map.Maybe ())-> Map.Int -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateAt") ,(T ((Map.deleteAt) :: Map.Int -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.deleteAt") ,(T ((Map.findMin) :: Map.Map Map.Char () -> (Map.Char, ())), "Map.findMin") ,(T ((Map.findMax) :: Map.Map Map.Char () -> (Map.Char, ())), "Map.findMax") ,(T ((Map.deleteMin) :: Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.deleteMin") ,(T ((Map.deleteMax) :: Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.deleteMax") ,(T ((Map.updateMin) :: (() -> Map.Maybe ()) -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateMin") ,(T ((Map.updateMax) :: (() -> Map.Maybe ()) -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateMax") ,(T ((Map.updateMinWithKey) :: (Map.Char -> () -> Map.Maybe ())-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateMinWithKey") ,(T ((Map.updateMaxWithKey) :: (Map.Char -> () -> Map.Maybe ())-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.updateMaxWithKey") ,(T ((Map.minViewWithKey) :: Map.Map Map.Char ()-> Map.Maybe (Map.Char, (), Map.Map Map.Char ())), "Map.minViewWithKey") ,(T ((Map.maxViewWithKey) :: Map.Map Map.Char ()-> Map.Maybe (Map.Char, (), Map.Map Map.Char ())), "Map.maxViewWithKey") ,(T ((Map.minView) :: Map.Map Map.Char () -> Map.Maybe ((), Map.Map Map.Char ())), "Map.minView") ,(T ((Map.maxView) :: Map.Map Map.Char () -> Map.Maybe ((), Map.Map Map.Char ())), "Map.maxView") ,(T ((Map.unions) :: [Map.Map Map.Char ()] -> Map.Map Map.Char ()), "Map.unions") ,(T ((Map.unionsWith) :: (() -> () -> ()) -> [Map.Map Map.Char ()] -> Map.Map Map.Char ()), "Map.unionsWith") ,(T ((Map.union) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.union") ,(T ((Map.unionWith) :: (() -> () -> ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.unionWith") ,(T ((Map.unionWithKey) :: (Map.Char -> () -> () -> ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.unionWithKey") ,(T ((Map.difference) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.difference") ,(T ((Map.differenceWith) :: (() -> () -> Map.Maybe ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.differenceWith") ,(T ((Map.differenceWithKey) :: (Map.Char -> () -> () -> Map.Maybe ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.differenceWithKey") ,(T ((Map.intersection) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.intersection") ,(T ((Map.intersectionWith) :: (() -> () -> ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.intersectionWith") ,(T ((Map.intersectionWithKey) :: (Map.Char -> () -> () -> ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.intersectionWithKey") ,(T ((Map.mergeWithKey) :: (Map.Char -> () -> () -> Map.Maybe ())-> (Map.MaybeS Map.Char -> Map.MaybeS Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ())-> (Map.MaybeS Map.Char -> Map.MaybeS Map.Char -> Map.Map Map.Char () -> Map.Map Map.Char ())-> Map.Map Map.Char ()-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.mergeWithKey") ,(T ((Map.isSubmapOf) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Bool), "Map.isSubmapOf") ,(T ((Map.isSubmapOfBy) :: (() -> () -> Map.Bool)-> Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Bool), "Map.isSubmapOfBy") ,(T ((Map.isProperSubmapOf) :: Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Bool), "Map.isProperSubmapOf") ,(T ((Map.isProperSubmapOfBy) :: (() -> () -> Map.Bool)-> Map.Map Map.Char () -> Map.Map Map.Char () -> Map.Bool), "Map.isProperSubmapOfBy") ,(T ((Map.filter) :: (() -> Map.Bool) -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.filter") ,(T ((Map.filterWithKey) :: (Map.Char -> () -> Map.Bool)-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.filterWithKey") ,(T ((Map.partition) :: (() -> Map.Bool)-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Map Map.Char ())), "Map.partition") ,(T ((Map.partitionWithKey) :: (Map.Char -> () -> Map.Bool)-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Map Map.Char ())), "Map.partitionWithKey") ,(T ((Map.mapMaybe) :: (() -> Map.Maybe ()) -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.mapMaybe") ,(T ((Map.mapMaybeWithKey) :: (Map.Char -> () -> Map.Maybe ())-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.mapMaybeWithKey") ,(T ((Map.mapEither) :: (() -> Map.Either () ())-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Map Map.Char ())), "Map.mapEither") ,(T ((Map.mapEitherWithKey) :: (Map.Char -> () -> Map.Either () ())-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Map Map.Char ())), "Map.mapEitherWithKey") ,(T ((Map.map) :: (() -> ()) -> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.map") ,(T ((Map.mapWithKey) :: (Map.Char -> () -> ())-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.mapWithKey") ,(T ((Map.mapAccum) :: (() -> () -> ((), ()))-> () -> Map.Map Map.Char () -> ((), Map.Map Map.Char ())), "Map.mapAccum") ,(T ((Map.mapAccumWithKey) :: (() -> Map.Char -> () -> ((), ()))-> () -> Map.Map Map.Char () -> ((), Map.Map Map.Char ())), "Map.mapAccumWithKey") ,(T ((Map.mapAccumRWithKey) :: (() -> Map.Char -> () -> ((), ()))-> () -> Map.Map Map.Char () -> ((), Map.Map Map.Char ())), "Map.mapAccumRWithKey") ,(T ((Map.mapKeys) :: (Map.Char -> Map.Char)-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.mapKeys") ,(T ((Map.mapKeysWith) :: (() -> () -> ())-> (Map.Char -> Map.Char)-> Map.Map Map.Char ()-> Map.Map Map.Char ()), "Map.mapKeysWith") ,(T ((Map.mapKeysMonotonic) :: (Map.Char -> Map.Char)-> Map.Map Map.Char () -> Map.Map Map.Char ()), "Map.mapKeysMonotonic") ,(T ((Map.foldr) :: (() -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldr") ,(T ((Map.foldr') :: (() -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldr'") ,(T ((Map.foldl) :: (() -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldl") ,(T ((Map.foldl') :: (() -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldl'") ,(T ((Map.foldrWithKey) :: (Map.Char -> () -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldrWithKey") ,(T ((Map.foldrWithKey') :: (Map.Char -> () -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldrWithKey'") ,(T ((Map.foldlWithKey) :: (() -> Map.Char -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldlWithKey") ,(T ((Map.foldlWithKey') :: (() -> Map.Char -> () -> ()) -> () -> Map.Map Map.Char () -> ()), "Map.foldlWithKey'") ,(T ((Map.elems) :: Map.Map Map.Char () -> [()]), "Map.elems") ,(T ((Map.keys) :: Map.Map Map.Char () -> [Map.Char]), "Map.keys") ,(T ((Map.assocs) :: Map.Map Map.Char () -> [(Map.Char, ())]), "Map.assocs") ,(T ((Map.fromList) :: [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromList") ,(T ((Map.fromListWith) :: (() -> () -> ()) -> [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromListWith") ,(T ((Map.fromListWithKey) :: (Map.Char -> () -> () -> ())-> [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromListWithKey") ,(T ((Map.toList) :: Map.Map Map.Char () -> [(Map.Char, ())]), "Map.toList") ,(T ((Map.toAscList) :: Map.Map Map.Char () -> [(Map.Char, ())]), "Map.toAscList") ,(T ((Map.toDescList) :: Map.Map Map.Char () -> [(Map.Char, ())]), "Map.toDescList") ,(T ((Map.fromAscList) :: [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromAscList") ,(T ((Map.fromAscListWith) :: (() -> () -> ()) -> [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromAscListWith") ,(T ((Map.fromAscListWithKey) :: (Map.Char -> () -> () -> ())-> [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromAscListWithKey") ,(T ((Map.fromDistinctAscList) :: [(Map.Char, ())] -> Map.Map Map.Char ()), "Map.fromDistinctAscList") ,(T ((Map.split) :: Map.Char-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Map Map.Char ())), "Map.split") ,(T ((Map.splitLookup) :: Map.Char-> Map.Map Map.Char ()-> (Map.Map Map.Char (), Map.Maybe (), Map.Map Map.Char ())), "Map.splitLookup") --,(T ((Map.deleteFindMin) :: Map.Map Map.Char () -> (Map.Char, (), Map.Map Map.Char ())), "Map.deleteFindMin") --,(T ((Map.deleteFindMax) :: Map.Map Map.Char () -> (Map.Char, (), Map.Map Map.Char ())), "Map.deleteFindMax") ]
gridaphobe/target
bench/MapCoverage.hs
mit
14,904
0
20
3,362
7,560
3,999
3,561
162
5
-- Number-Star ladder -- https://www.codewars.com/kata/5631213916d70a0979000066 module Codewars.Kata.NumberStar where import Data.List(intercalate) pattern :: Int -> String pattern n = intercalate "\n" . ("1" :) . map (\i -> "1" ++ replicate (pred i) '*' ++ show i) $ [2..n]
gafiatulin/codewars
src/7 kyu/NumberStar.hs
mit
278
4
12
41
91
52
39
4
1
{- This module was generated from data in the Kate syntax highlighting file actionscript.xml, version 1.0, by Aaron Miller ([email protected]) -} module Text.Highlighting.Kate.Syntax.Actionscript (highlight, parseExpression, syntaxName, syntaxExtensions) where import Text.Highlighting.Kate.Types import Text.Highlighting.Kate.Common import qualified Text.Highlighting.Kate.Syntax.Javadoc import Text.ParserCombinators.Parsec hiding (State) import Control.Monad.State import Data.Char (isSpace) import qualified Data.Set as Set -- | Full name of language. syntaxName :: String syntaxName = "ActionScript 2.0" -- | Filename extensions for this language. syntaxExtensions :: String syntaxExtensions = "*.as" -- | Highlight source code using this syntax definition. highlight :: String -> [SourceLine] highlight input = evalState (mapM parseSourceLine $ lines input) startingState parseSourceLine :: String -> State SyntaxState SourceLine parseSourceLine = mkParseSourceLine (parseExpression Nothing) -- | Parse an expression using appropriate local context. parseExpression :: Maybe (String,String) -> KateParser Token parseExpression mbcontext = do (lang,cont) <- maybe currentContext return mbcontext result <- parseRules (lang,cont) optional $ do eof updateState $ \st -> st{ synStPrevChar = '\n' } pEndLine return result startingState = SyntaxState {synStContexts = [("ActionScript 2.0","Normal")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = True, synStCaptures = []} pEndLine = do updateState $ \st -> st{ synStPrevNonspace = False } context <- currentContext contexts <- synStContexts `fmap` getState st <- getState if length contexts >= 2 then case context of _ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False } ("ActionScript 2.0","Normal") -> return () ("ActionScript 2.0","String") -> (popContext) >> pEndLine ("ActionScript 2.0","Member") -> (popContext) >> pEndLine ("ActionScript 2.0","StaticImports") -> (popContext) >> pEndLine ("ActionScript 2.0","Imports") -> (popContext) >> pEndLine ("ActionScript 2.0","Commentar 1") -> (popContext) >> pEndLine ("ActionScript 2.0","Commentar 2") -> return () _ -> return () else return () withAttribute attr txt = do when (null txt) $ fail "Parser matched no text" updateState $ \st -> st { synStPrevChar = last txt , synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) } return (attr, txt) list_properties = Set.fromList $ words $ "_accProps _focusrect _global _highquality _level _parent _quality _root _soundbuftime maxscroll scroll this" list_global'5ffunctions = Set.fromList $ words $ "asfunction call chr clearInterval duplicateMovieClip escape eval fscommand getProperty getTimer getURL getVersion gotoAndPlay gotoAndStop ifFrameLoaded int isFinite isNaN length loadMovie loadMovieNum loadVariables loadVariablesNum mbchr mblength mbord mbsubstring nextFrame nextScene on onClipEvent ord parseFloat parseInt play prevFrame prevScene print printAsBitmap printAsBitmapNum printNum random removeMovieClip setInterval setProperty showRedrawRegions startDrag stop stopAllSounds stopDrag substring targetPath tellTarget toggleHighQuality trace typeof unescape unloadMovie unloadMovieNum updateAfterEvent" list_classes = Set.fromList $ words $ "Accessibility Accordion Alert Binding Button Camera CellRenderer CheckBox Collection Color ComboBox ComponentMixins ContextMenu ContextMenuItem CustomActions CustomFormatter CustomValidator DataGrid DataHolder DataProvider DataSet DataType Date DateChooser DateField Delta DeltaItem DeltaPacket DepthManager EndPoint Error FaultEvent FocusManager Form Function Iterator Key Label List LoadVars Loader LocalConnection Log Math Media Menu MenuBar Microphone Mouse MovieClip MovieClipLoader NetConnection NetStream Number NumericStepper PendingCall PopUpManager PrintJob ProgressBar RDBMSResolver RadioButton RelayResponder SOAPCall Screen ScrollPane Selection SharedObject Slide Sound Stage StyleManager System TextArea TextField TextFormat TextInput TextSnapshot TransferObject Tree TreeDataProvider TypedValue UIComponent UIEventDispatcher UIObject Video WebService WebServiceConnector Window XML XMLConnector XUpdateResolver" list_keywords = Set.fromList $ words $ "add and break case catch class continue default delete do dynamic else eq extends finally for function ge get gt if implements import in instanceof interface intrinsic le lt ne new not or private public return set static switch throw try var void while with" list_const = Set.fromList $ words $ "false Infinity -Infinity NaN newline null true undefined" list_types = Set.fromList $ words $ "Array Boolean Number Object String Void" regex_'2f'2f'5cs'2aBEGIN'2e'2a'24 = compileRegex True "//\\s*BEGIN.*$" regex_'2f'2f'5cs'2aEND'2e'2a'24 = compileRegex True "//\\s*END.*$" regex_'5c'2e'7b3'2c3'7d'5cs'2b = compileRegex True "\\.{3,3}\\s+" regex_'5cb'28import'5cs'2bstatic'29'5cb = compileRegex True "\\b(import\\s+static)\\b" regex_'5cb'28package'7cimport'29'5cb = compileRegex True "\\b(package|import)\\b" regex_'5cb'5b'5f'5cw'5d'5b'5f'5cw'5cd'5d'2a'28'3f'3d'5b'5cs'5d'2a'28'2f'5c'2a'5cs'2a'5cd'2b'5cs'2a'5c'2a'2f'5cs'2a'29'3f'5b'28'5d'29 = compileRegex True "\\b[_\\w][_\\w\\d]*(?=[\\s]*(/\\*\\s*\\d+\\s*\\*/\\s*)?[(])" regex_'5b'2e'5d'7b1'2c1'7d = compileRegex True "[.]{1,1}" regex_'5cb'5b'5fa'2dzA'2dZ'5d'5cw'2a'28'3f'3d'5b'5cs'5d'2a'29 = compileRegex True "\\b[_a-zA-Z]\\w*(?=[\\s]*)" regex_'5cs'2a'2e'2a'24 = compileRegex True "\\s*.*$" parseRules ("ActionScript 2.0","Normal") = (((Text.Highlighting.Kate.Syntax.Javadoc.parseExpression (Just ("Javadoc","")))) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_properties >>= withAttribute NormalTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_global'5ffunctions >>= withAttribute NormalTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_classes >>= withAttribute NormalTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywords >>= withAttribute KeywordTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_const >>= withAttribute NormalTok)) <|> ((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_types >>= withAttribute DataTypeTok)) <|> (withChildren (pFloat >>= withAttribute FloatTok) ((pAnyChar "fF" >>= withAttribute FloatTok))) <|> ((pHlCOct >>= withAttribute BaseNTok)) <|> ((pHlCHex >>= withAttribute BaseNTok)) <|> (withChildren (pInt >>= withAttribute DecValTok) (((pString False "ULL" >>= withAttribute DecValTok)) <|> ((pString False "LUL" >>= withAttribute DecValTok)) <|> ((pString False "LLU" >>= withAttribute DecValTok)) <|> ((pString False "UL" >>= withAttribute DecValTok)) <|> ((pString False "LU" >>= withAttribute DecValTok)) <|> ((pString False "LL" >>= withAttribute DecValTok)) <|> ((pString False "U" >>= withAttribute DecValTok)) <|> ((pString False "L" >>= withAttribute DecValTok)))) <|> ((pHlCChar >>= withAttribute CharTok)) <|> ((pRegExpr regex_'2f'2f'5cs'2aBEGIN'2e'2a'24 >>= withAttribute DecValTok)) <|> ((pRegExpr regex_'2f'2f'5cs'2aEND'2e'2a'24 >>= withAttribute DecValTok)) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("ActionScript 2.0","String")) <|> ((pDetect2Chars False '/' '/' >>= withAttribute CommentTok) >>~ pushContext ("ActionScript 2.0","Commentar 1")) <|> ((pDetect2Chars False '/' '*' >>= withAttribute CommentTok) >>~ pushContext ("ActionScript 2.0","Commentar 2")) <|> ((pDetectChar False '{' >>= withAttribute NormalTok)) <|> ((pDetectChar False '}' >>= withAttribute NormalTok)) <|> ((pRegExpr regex_'5c'2e'7b3'2c3'7d'5cs'2b >>= withAttribute KeywordTok)) <|> ((pRegExpr regex_'5cb'28import'5cs'2bstatic'29'5cb >>= withAttribute KeywordTok) >>~ pushContext ("ActionScript 2.0","StaticImports")) <|> ((pRegExpr regex_'5cb'28package'7cimport'29'5cb >>= withAttribute KeywordTok) >>~ pushContext ("ActionScript 2.0","Imports")) <|> ((pRegExpr regex_'5cb'5b'5f'5cw'5d'5b'5f'5cw'5cd'5d'2a'28'3f'3d'5b'5cs'5d'2a'28'2f'5c'2a'5cs'2a'5cd'2b'5cs'2a'5c'2a'2f'5cs'2a'29'3f'5b'28'5d'29 >>= withAttribute FunctionTok)) <|> ((pRegExpr regex_'5b'2e'5d'7b1'2c1'7d >>= withAttribute NormalTok) >>~ pushContext ("ActionScript 2.0","Member")) <|> ((pAnyChar ":!%&()+,-/.*<=>?[]|~^;" >>= withAttribute NormalTok)) <|> (currentContext >>= \x -> guard (x == ("ActionScript 2.0","Normal")) >> pDefault >>= withAttribute NormalTok)) parseRules ("ActionScript 2.0","String") = (((pLineContinue >>= withAttribute StringTok)) <|> ((pHlCStringChar >>= withAttribute CharTok)) <|> ((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("ActionScript 2.0","String")) >> pDefault >>= withAttribute StringTok)) parseRules ("ActionScript 2.0","Member") = (((pRegExpr regex_'5cb'5b'5fa'2dzA'2dZ'5d'5cw'2a'28'3f'3d'5b'5cs'5d'2a'29 >>= withAttribute FunctionTok) >>~ (popContext)) <|> ((popContext) >> currentContext >>= parseRules)) parseRules ("ActionScript 2.0","StaticImports") = (((pRegExpr regex_'5cs'2a'2e'2a'24 >>= withAttribute KeywordTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("ActionScript 2.0","StaticImports")) >> pDefault >>= withAttribute NormalTok)) parseRules ("ActionScript 2.0","Imports") = (((pRegExpr regex_'5cs'2a'2e'2a'24 >>= withAttribute KeywordTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("ActionScript 2.0","Imports")) >> pDefault >>= withAttribute NormalTok)) parseRules ("ActionScript 2.0","Commentar 1") = (currentContext >>= \x -> guard (x == ("ActionScript 2.0","Commentar 1")) >> pDefault >>= withAttribute CommentTok) parseRules ("ActionScript 2.0","Commentar 2") = (((pDetect2Chars False '*' '/' >>= withAttribute CommentTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("ActionScript 2.0","Commentar 2")) >> pDefault >>= withAttribute CommentTok)) parseRules ("Javadoc", _) = Text.Highlighting.Kate.Syntax.Javadoc.parseExpression Nothing parseRules x = parseRules ("ActionScript 2.0","Normal") <|> fail ("Unknown context" ++ show x)
ambiata/highlighting-kate
Text/Highlighting/Kate/Syntax/Actionscript.hs
gpl-2.0
11,196
0
36
2,205
2,259
1,204
1,055
158
10
module Std where import Expressions import Eval import qualified Data.Map as Map import Control.Monad.State import Control.Monad.Error true = "t" false = "nil" nothing = "nil" -- Helper functions getSymbol sym = eval $ LispSymbol sym getSymbols syms = mapM getSymbol syms -- Primitives lispQuote = getSymbol "thing" >>= return lispAtom = do arg <- getSymbol "object" return $ LispSymbol (if isAtom arg then true else false) isAtom :: LispExpr -> Bool isAtom (LispList _) = False isAtom _ = True lispEqArgs = ["expr1","expr2"] lispEq = do [expr1,expr2] <- getSymbols lispEqArgs return $ isEqual expr1 expr2 isEqual :: LispExpr -> LispExpr -> LispExpr isEqual a b | a == b = LispSymbol true | otherwise = LispSymbol false lispCar = do list <- getSymbol "list" action list where action arg | arg == (LispList []) = return $ (LispSymbol nothing) | isAtom $ arg = throwError "Argument is not of type list" | otherwise = return $ car arg lispCdr = do list <- getSymbol "list" action list where action arg | arg == (LispList []) = return $ arg | isAtom arg = throwError "Argument is not of type list" | otherwise = return $ cdr arg car :: LispExpr -> LispExpr car (LispList list) = head list car _ = (LispSymbol nothing) cdr :: LispExpr -> LispExpr cdr (LispList list) = (LispList (tail list)) cdr _ = (LispSymbol nothing) notNothing :: LispExpr -> Bool notNothing = (/= (LispSymbol nothing)) lispConsArgs = ["expr1","expr2"] lispCons = do [expr1,expr2] <- getSymbols lispConsArgs action expr1 expr2 where action expr1 expr2 | (isAtom $ expr2) && (notNothing $ expr2) = throwError "Cannot construct list" | otherwise = return $ splice expr1 expr2 splice :: LispExpr -> LispExpr -> LispExpr splice elem (LispSymbol nothing) = (LispList [elem]) splice elem (LispList list) = (LispList (elem:list)) splice _ _ = (LispSymbol false) lispCond = do (LispList args) <- getSymbol "clauses" cond args where cond args | null args = return $ (LispSymbol nothing) | isAtom $ head args = throwError "cond clause is not a list" | notTwoElementList $ head args = throwError "clause has not two arguments" | otherwise = do eval_expr <- eval $ car $ head args if (not $ isBool $ eval_expr) then throwError $ "first form in a clause does not evaluate to " ++ true ++ " or " ++ false else if (eval_expr == (LispSymbol true)) then eval $ car $ cdr $ head args else cond $ tail args isBool :: LispExpr -> Bool isBool (LispSymbol sym) = if(sym == true || sym == false) then True else False isBool _ = False notTwoElementList :: LispExpr -> Bool notTwoElementList (LispList list) = length list /= 2 notTwoElementList _ = False -- function creation lispLambdaArgs = ["args", "&rest", "body"] lispLambda = do [(LispList args), (LispList body)] <- getSymbols ["args", "body"] let newFn = do evalBody <- mapM eval body return $ last evalBody return $ LispLambda newFn (map show args) lispFunArgs = ["name", "args", "&rest", "body"] lispFun = do [(LispSymbol name), (LispList args), (LispList body)] <- getSymbols ["name", "args", "body"] let newFn = do evalBody <- mapM eval body return $ last evalBody lambda = LispFunc newFn name (map show args) updateSymbolInParent name lambda return lambda -- Special form setq lispSetArgs = ["symbol", "value"] lispSet = do [(LispSymbol s), e] <- getSymbols lispSetArgs eval_e <- eval e updateSymbolInParent s eval_e return eval_e -- If Conditional, cond can easily replace it lispIfArgs = ["condition", "expr1", "expr2"] lispIf = do [condExpr, expr1, expr2] <- getSymbols lispIfArgs eval_cond <- eval condExpr if (notNil eval_cond) then eval expr1 else eval expr2 where notNil (LispSymbol val) = false /= val lispArithmetic f = do (LispList args) <- getSymbol "args" lispBinary f args lispBinary :: (Integer->Integer->Integer) -> [LispExpr] -> LispResult lispBinary op args = do return $ foldl1 (lispBinaryAux op) args where lispBinaryAux op (LispInt i) (LispInt j) = LispInt (i `op` j) -- Symbol table initialCtx = Ctx (Map.fromList [ (true, LispSymbol true), (false, LispSymbol false), ("()", LispSymbol "()"), ("quote", LispSpecial lispQuote ["thing"]), ("atom", LispFunc lispAtom "atom" ["object"]), ("eq", LispFunc lispEq "eq" lispEqArgs), ("car", LispFunc lispCar "car" ["list"]), ("cdr", LispFunc lispCdr "cdr" ["list"]), ("cons", LispFunc lispCons "cons" ["expr1", "expr2"]), ("cond", LispSpecial lispCond ["&rest", "clauses"]), ("lambda", LispSpecial lispLambda lispLambdaArgs), ("defun", LispSpecial lispFun lispFunArgs), ("setq", LispSpecial lispSet lispSetArgs), ("+", LispFunc (lispArithmetic (+)) "+" ["&rest", "args"]), ("-", LispFunc (lispArithmetic (-)) "-" ["&rest", "args"]), ("*", LispFunc (lispArithmetic (*)) "*" ["&rest", "args"]), ("/", LispFunc (lispArithmetic div) "/" ["&rest", "args"]), ("if", LispSpecial lispIf lispIfArgs) --redundant ]) Nothing
aksiazek/yali
src/Std.hs
gpl-2.0
6,200
24
15
2,165
1,915
986
929
123
3
module GlobRegex ( globToRegex, matchesGlob ) where import Text.Regex.Posix((=~)) type GlobError = String globToRegex :: String -> Either GlobError String globToRegex cs = case globToRegex' cs of Right result -> Right ('^' : result ++ "$") Left error -> Left error globToRegex' :: String -> Either GlobError String globToRegex' "" = Right "" globToRegex' ('*':cs) = case globToRegex' cs of Right result -> Right (".*" ++ result) Left error -> Left error globToRegex' ('?':cs) = case globToRegex' cs of Right result -> Right ('.' : result) Left error -> Left error globToRegex' ('[':'!':c:cs) = case charClass cs of Right result -> Right ("[^" ++ c : result) Left error -> Left error globToRegex' ('[':c:cs) = case charClass cs of Right res -> Right ('[' : c : res) Left err -> Left err globToRegex' ('[':_) = Left "unterminated character class" globToRegex' (c:cs) = case globToRegex' cs of Right res -> Right (escape c ++ res) Left err -> Left err escape :: Char -> String escape c | elem c regex = '\\' : [c] | otherwise = [c] where regex = "\\+()^$.{}]|" charClass :: String -> Either GlobError String charClass (']':cs) = case globToRegex' cs of Right result -> Right (']' : result) Left error -> Left error charClass (c:cs) = case charClass cs of Right res -> Right (c : res) Left err -> Left err charClass [] = Left "unterminated character class" matchesGlob :: FilePath -> String -> Bool name `matchesGlob` pat = case globToRegex pat of Right res -> (name =~ res) Left err -> False
Tr1p0d/realWorldHaskell
rwh8/GlobRegex.hs
gpl-2.0
1,658
58
11
429
729
356
373
44
6
import System.Environment (getArgs) import System.IO (readLn, getLine) main :: IO() main = do -- args <- getArgs args <- getLine let xs = map read $ words args let x = head xs let y = head $ tail xs let z = last xs putStrLn . show $ mod_fib x y (z-1) mod_fib :: Integer -> Integer -> Integer -> Integer mod_fib x y 0 = x mod_fib x y 1 = y mod_fib x y z = mod_fib x y (z-2) + (mod_fib x y (z-1)) ^ 2 toInt :: String -> Int toInt x = read x
woodsjc/hackerrank-challenges
hackerrank_fib_modified.hs
gpl-3.0
456
0
11
117
243
120
123
16
1
module BackendState where import System.ZMQ data NetworkState = NetworkState { zmqContext :: Context , replySock :: Socket Rep , requestSock :: Socket Req , broadcastSock :: Socket Pub } data AcqState = AcqState { acquiring :: Bool , disking :: Maybe Handle , broadcasting :: Bool } data BackendState = BackendState { net :: NetworkState , acq :: MVar AcqState } -- FIXME initSimple :: IO BackendState initSimple = do context <- zmqContext 1 repSock <- zmqSocket Rep reqSock <- zmqSocket Req brdSock <- zmqSocket Pub let acqState = AcqState False Nothing False netState <- newMVar $ NetworkState context repSock reqSock brdSock BackendState { net = netState, acq = acqState } -- FIXME initFile :: Filepath -> ErrorT (IO BackendState) initFile fn = do
imalsogreg/arte-ephys
arte-backend/src/System/Arte/Backend/BackendState.hs
gpl-3.0
1,121
1
11
494
238
126
112
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Text.BlogLiterately.Highlight -- Copyright : (c) 2008-2010 Robert Greayer, 2012 Brent Yorgey -- License : GPL (see LICENSE) -- Maintainer : Brent Yorgey <[email protected]> -- -- Syntax highlighting. -- ----------------------------------------------------------------------------- module Text.BlogLiterately.Highlight ( HsHighlight(..) , colourIt , litify , StylePrefs , defaultStylePrefs , getStylePrefs , bakeStyles , replaceBreaks , colouriseCodeBlock , colourisePandoc ) where import Control.Monad ( liftM ) import Data.Maybe ( isNothing ) import qualified System.IO.UTF8 as U ( readFile ) import Text.Pandoc ( Pandoc(..) , Block (CodeBlock, RawBlock) ) import Text.Pandoc.Highlighting ( highlight, formatHtmlBlock ) import Language.Haskell.HsColour ( hscolour, Output(..) ) import Language.Haskell.HsColour.Colourise ( defaultColourPrefs ) import System.Console.CmdArgs ( Data, Typeable ) import Text.XML.HaXml import Text.XML.HaXml.Posn ( noPos ) import Text.Blaze.Html.Renderer.String ( renderHtml ) import Text.BlogLiterately.Block ( unTag ) -- | Four modes for highlighting Haskell. data HsHighlight = HsColourInline StylePrefs -- ^ Use hscolour and inline the styles. | HsColourCSS -- ^ Use hscolour in conjunction with -- an external CSS style sheet. | HsKate -- ^ Use highlighting-kate. | HsNoHighlight -- ^ Do not highlight Haskell. deriving (Data,Typeable,Show,Eq) {- The literate Haskell that Pandoc finds in a file ends up in various `CodeBlock` elements of the `Pandoc` document. Other code can also wind up in `CodeBlock` elements -- normal markdown formatted code. The `Attr` component has metadata about what's in the code block: [haskell] type Attr = ( String, -- code block identifier , [String] -- list of code classes , [(String, String)] -- name/value pairs ) Thanks to some feedback from the Pandoc author, John MacFarlane, I learned that the CodeBlock *may* contain markers about the kind of code contained within the block. LHS (bird-style or LaTex style) will always have an `Attr` of the form `("",["sourceCode","haskell"],[])`, and other `CodeBlock` elements are the markdown code blocks *may* have an identifier, classes, or key/value pairs. Pandoc captures this info when the file contains code blocks in the delimited (rather than indented) format, which allows an optional meta-data specification, e.g. ~~~~~~~~~~~ ~~~~~~~ { .bash } x=$1 echo $x ~~~~~~~ ~~~~~~~~~~~ Although Pandoc supports the above format for marking code blocks (and annotating the kind of code within the block) I'll also keep my notation as another option for use with indented blocks, i.e. if you write: <pre><code> [haskell] foo :: String -> String </code></pre> it is a Haskell block. You can also use other annotations, *e.g.* <pre><code> [cpp] cout << "Hello World!"; </code></pre> If highlighting-kate is specified for highlighting Haskell blocks, the distinction between the literate blocks and the delimited blocks is lost (this is simply how the Pandoc highlighting module currently works). I'll adopt the rule that if you specify a class or classes using Pandoc's delimited code block syntax, I'll assume that there is no additional tag within the block in Blog Literately syntax. I still need my `unTag` function to parse the code block. To highlight the syntax using hscolour (which produces HTML), I'm going to need to transform the `String` from a `CodeBlock` element to a `String` suitable for the `RawHtml` element (because the hscolour library transforms Haskell text to HTML). Pandoc strips off the prepended &gt; characters from the literate Haskell, so I need to put them back, and also tell hscolour whether the source it is colouring is literate or not. The hscolour function looks like: [haskell] hscolour :: Output -- ^ Output format. -> ColourPrefs -- ^ Colour preferences... -> Bool -- ^ Whether to include anchors. -> Bool -- ^ Whether output document is partial or complete. -> String -- ^ Title for output. -> Bool -- ^ Whether input document is literate haskell -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. Since I still don't like the `ICSS` output from hscolour, I'm going to provide two options for hscolouring to users: one that simply uses hscolour's `CSS` format, so the user can provide definitions in their blog's stylesheet to control the rendering, and a post-processing option to transform the `CSS` class-based rendering into a inline style based rendering (for people who can't update their stylesheet). `colourIt` performs the initial transformation: -} -- | Use hscolour to syntax highlight some Haskell code. The first -- argument indicates whether the code is literate Haskell. colourIt :: Bool -> String -> String colourIt literate srcTxt = hscolour CSS defaultColourPrefs False True "" literate srcTxt' where srcTxt' | literate = litify srcTxt | otherwise = srcTxt -- | Prepend literate Haskell markers to some source code. litify :: String -> String litify = unlines . map ("> " ++) . lines {- Hscolour uses HTML `span` elements and CSS classes like 'hs-keyword' or `hs-keyglyph` to markup Haskell code. What I want to do is take each marked `span` element and replace the `class` attribute with an inline `style` element that has the markup I want for that kind of source. Style preferences are specified as a list of name/value pairs: -} -- | Style preferences are specified as a list of mappings from class -- attributes to CSS style attributes. type StylePrefs = [(String,String)] -- | A default style that produces something that looks like the -- source listings on Hackage. defaultStylePrefs :: StylePrefs defaultStylePrefs = [ ("hs-keyword","color: blue; font-weight: bold;") , ("hs-keyglyph","color: red;") , ("hs-layout","color: red;") , ("hs-comment","color: green;") , ("hs-conid", "") , ("hs-varid", "") , ("hs-conop", "") , ("hs-varop", "") , ("hs-str", "color: teal;") , ("hs-chr", "color: teal;") , ("hs-number", "") , ("hs-cpp", "") , ("hs-selection", "") , ("hs-variantselection", "") , ("hs-definition", "") ] -- | Read style preferences in from a file using the @Read@ instance -- for @StylePrefs@, or return the default style if the file name is -- empty. getStylePrefs :: FilePath -> IO StylePrefs getStylePrefs "" = return defaultStylePrefs getStylePrefs fname = liftM read (U.readFile fname) -- | Take a @String@ of HTML produced by hscolour, and \"bake\" styles -- into it by replacing class attributes with appropriate style -- attributes. bakeStyles :: StylePrefs -> String -> String bakeStyles prefs s = verbatim $ filtDoc (xmlParse "bake-input" s) where -- filter the document (an Hscoloured fragment of Haskell source) filtDoc (Document p s e m) = c where [c] = filts (CElem e noPos) -- the filter is a fold of individual filters for each CSS class filts = mkElem "pre" [(foldXml $ foldl o keep $ map filt prefs) `o` replaceTag "code"] -- an individual filter replaces the attributes of a tag with -- a style attribute when it has a specific 'class' attribute. filt (cls,style) = replaceAttrs [("style",style)] `when` (attrval $ (N "class", AttValue [Left cls])) {- Highlighting-Kate uses @\<br/>@ in code blocks to indicate newlines. WordPress (and possibly others) chooses to strip them away when found in @\<pre>@ sections of uploaded HTML. So we need to turn them back to newlines. -} -- | Replace @\<br/>@ tags with newlines. replaceBreaks :: String -> String replaceBreaks s = verbatim $ filtDoc (xmlParse "input" s) where -- filter the document (a highlighting-kate highlighted fragment of -- haskell source) filtDoc (Document p s e m) = c where [c] = filts (CElem e noPos) filts = foldXml (literal "\n" `when` tag "br") {- Note/todo: the above is a function that could be made better in a few ways and then factored out into a library. A way to handle the above would be to allow the preferences to be specified as an actual CSS style sheet, which then would be baked into the HTML. Such a function could be separately useful, and could be used to 'bake' in the highlighting-kate styles. -} -- | Transform a @CodeBlock@ into a @RawHtml@ block, where -- the content contains marked up Haskell (possibly with literate -- markers), or marked up non-Haskell, if highlighting of non-Haskell has -- been selected. colouriseCodeBlock :: HsHighlight -> Bool -> Block -> Block colouriseCodeBlock hsHighlight otherHighlight b@(CodeBlock attr@(_,classes,_) s) | tag == Just "haskell" || haskell = case hsHighlight of HsColourInline style -> RawBlock "html" $ bakeStyles style $ colourIt lit src HsColourCSS -> RawBlock "html" $ colourIt lit src HsNoHighlight -> RawBlock "html" $ simpleHTML hsrc HsKate -> case tag of Nothing -> myHighlightK attr hsrc Just t -> myHighlightK ("", t:classes,[]) hsrc | otherHighlight = case tag of Nothing -> myHighlightK attr src Just t -> myHighlightK ("",[t],[]) src | otherwise = RawBlock "html" $ simpleHTML src where (tag,src) | null classes = unTag s | otherwise = (Nothing, s) hsrc | lit = litify src | otherwise = src lit = "sourceCode" `elem` classes haskell = "haskell" `elem` classes simpleHTML s = "<pre><code>" ++ s ++ "</code></pre>" myHighlightK attr s = case highlight formatHtmlBlock attr s of Nothing -> RawBlock "html" $ simpleHTML s Just html -> RawBlock "html" $ replaceBreaks $ renderHtml html colouriseCodeBlock _ _ b = b -- | Perform syntax highlighting on an entire Pandoc document. colourisePandoc :: HsHighlight -> Bool -> Pandoc -> Pandoc colourisePandoc hsHighlight otherHighlight (Pandoc m blocks) = Pandoc m $ map (colouriseCodeBlock hsHighlight otherHighlight) blocks
jwiegley/BlogLiterately
src/Text/BlogLiterately/Highlight.hs
gpl-3.0
10,848
0
16
2,663
1,350
755
595
105
7
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} import Chorale.Common import qualified Codec.Compression.GZip as GZip import Control.Monad import Data.Aeson hiding (Result) import qualified Data.ByteString as BB import qualified Data.ByteString.Char8 as CC import qualified Data.ByteString.Lazy as B import qualified Data.ByteString.Lazy.Char8 as C import Data.List import Data.Maybe import Data.Time import GHC.Generics import Network.Curl.Download import Network.Curl.Download.Lazy import Safe import Text.XML.Hexml urlState :: String urlState = "https://planet.openstreetmap.org/replication/day/state.txt" urlFile :: Int -> String urlFile n = "https://planet.openstreetmap.org/replication/day/" ++ (justifyRight 3 '0' . show) (div n 1000000) ++ "/" ++ (justifyRight 3 '0' . show) (mod (div n 1000) 1000) ++ "/" ++ (justifyRight 3 '0' . show) (mod n 1000) ++ ".osc.gz" outputFile :: String outputFile = "../../data/osm-node-changes-per-area.json" dataDescription' :: String dataDescription' = "Statistics on node changes of OpenStreetMap data" dataSource' :: String dataSource' = "OpenStreetMap project, <a href=\"http://opendatacommons.org/licenses/odbl/\" target=\"_blank\">ODbL</a>" -- --== MAIN main :: IO () main = do (latestTimestamp', url', nodeChanges') <- downloadAndParseXml let nodeChangesStatistics = aggregateNodeChanges . map roundNodeChange $ nodeChanges' C.writeFile outputFile . encode $ Result latestTimestamp' dataDescription' dataSource' url' nodeChangesStatistics -- --== RESULT data Result = Result {dataTimestamp :: String, dataDescription :: String, dataSource :: String, dataUrl :: String, nodeChanges :: [NodeChangeStatistics]} deriving Generic instance ToJSON Result where toEncoding = genericToEncoding defaultOptions -- --== DOWNLOAD FILES downloadAndParseXml :: IO (String, String, [NodeChangeUTCTime]) downloadAndParseXml = do info <- lines . either (error . ("[ERROR]" ++)) id <$> openURIString urlState let latestSequenceNumber = nothingToError "[ERROR] Could not read sequence number" . join . mapJust readMay . headMay . mapMaybe (stripPrefix "sequenceNumber=") $ info let latestTimestamp = nothingToError "[ERROR] Could not read timestamp" . mapJust (replaceElementInList '\\' "") . headMay . mapMaybe (stripPrefix "timestamp=") $ info nodeChanges' <- parseChangesXml . GZip.decompress . leftToError "[ERROR] Could not read file" <$> (openLazyURI . urlFile) latestSequenceNumber return (latestTimestamp, urlFile latestSequenceNumber, nodeChanges') -- --== NODECHANGE data NodeChangeUTCTime = NodeChangeUTCTime UTCTime Double Double deriving Show data NodeChange = NodeChange String Double Double deriving (Show, Eq, Ord) data NodeChangeStatistics = NodeChangeStatistics {timestamp :: String, lat :: Double, lon :: Double, count :: Int} deriving (Generic, Show) instance ToJSON NodeChangeStatistics where toEncoding = genericToEncoding defaultOptions -- --== PARSE XML parseChangesXml :: B.ByteString -> [NodeChangeUTCTime] parseChangesXml = mapMaybe parseChangeXml . flip childrenByDeep "node" . leftToError "[ERROR] Could not parse file" . parse . C.toStrict childrenByDeep :: Node -> BB.ByteString -> [Node] childrenByDeep node s = childrenBy node s ++ concatMap (`childrenByDeep` s) (children node) parseChangeXml :: Node -> Maybe NodeChangeUTCTime parseChangeXml node = if isJust timestamp' && all isJust [lat', lon'] then Just $ NodeChangeUTCTime (fromJust timestamp') (fromJust lat') (fromJust lon') else Nothing where timestamp' = parseTimeM True defaultTimeLocale "%Y-%m-%dT%H:%M:%S%Z" . CC.unpack . attributeValue =<< attributeBy node "timestamp" lat' = readMay . CC.unpack. attributeValue =<< attributeBy node "lat" lon' = readMay . CC.unpack. attributeValue =<< attributeBy node "lon" -- --== AGGREGATE NODECHANGES roundNodeChange :: NodeChangeUTCTime -> NodeChange roundNodeChange (NodeChangeUTCTime timestamp' lat' lon') = NodeChange ((\(h, m) -> h ++ ":" ++ m) . map12 (justifyRight 2 '0' . show) . map21 (todHour, (* 10) . flip div 10 . todMin) . timeToTimeOfDay . utctDayTime $ timestamp') (fromIntegral . (round :: Double -> Int) $ lat') (fromIntegral . (round :: Double -> Int) $ lon') aggregateNodeChanges :: [NodeChange] -> [NodeChangeStatistics] aggregateNodeChanges = map ((\(NodeChange timestamp' lat' lon', n) -> NodeChangeStatistics timestamp' lat' lon' n) . map21 (head, length)) . sortAndGroup -- --== HELPERS nothingToError :: String -> Maybe a -> a nothingToError msg = \case Just a -> a Nothing -> error msg leftToError :: String -> Either a b -> b leftToError msg = leftToError' (const msg) leftToError' :: (a -> String) -> Either a b -> b leftToError' msg = \case Left a -> error . msg $ a Right b -> b
mocnik-science/osm-vis
data-mining/osm-node-changes-per-area/tool.hs
gpl-3.0
4,869
81
15
734
1,319
714
605
75
2
module Inkvizitor.Geocode ( Coords(..) , Query(..) , Location(..) , geocode ) where import Codec.Binary.UTF8.String import Control.Applicative import Control.Monad import Network.HTTP import Network.URI import Text.JSON ( decode , fromJSObject , fromJSString , resultToEither , JSValue(..) ) data Coords = Coords { getLatitude :: Double , getLongitude :: Double } deriving (Eq, Show) -- | Query saved in input.txt (to be geocoded) data Query = Query { getAddress :: String -- | Address (e.g. "Silicon Valley") , getQueryId :: String -- | An identifier (e.g. "my work") } deriving (Eq, Show) -- | Result of geocoding (exact location) data Location = Location { getCoords :: Coords , getLocId :: String , getFullAddress :: String } deriving (Eq, Show) -- | Returns an IO action that returns either error message or list of found -- locations. geocode :: Query -> IO (Either String [Location]) geocode query = do let uri = "http://maps.googleapis.com/maps/api/geocode/json?" ++ params params = "address=" ++ escape (getAddress query) ++ "&sensor=false" escape = escapeURIString isAllowedInURI . encodeString -- get HTTP result result <- simpleHTTP (getRequest uri) case result of Left err -> return $ Left ("HTTP error: " ++ show err) Right response -> do -- parse JSON let body = rspBody response jsResult = Text.JSON.decode body return (resultToEither jsResult >>= processJSON query) -- helpers fjo = fromJSObject fjs = fromJSString -- | Processes parsed JSON response processJSON :: Query -> JSValue -> Either String [Location] processJSON query (JSObject topObj) = case fjs status of "OK" -> Right $ map (processResult query) results "ZERO_RESULTS" -> Right [] err -> Left $ "Geocoding API returned error: " ++ err where toplevel = fjo topObj -- fields of toplevel JSON object Just (JSString status) = lookup "status" toplevel Just (JSArray results) = lookup "results" toplevel -- | Processes one result processResult :: Query -> JSValue -> Location processResult query (JSObject result) = Location { getCoords = coords , getLocId = getQueryId query , getFullAddress = decodeString . fjs $ fullAddr } where coords = Coords (fromRational lat) (fromRational lng) Just (JSRational _ lat) = lookup "lat" (fjo location) Just (JSRational _ lng) = lookup "lng" (fjo location) Just (JSObject location) = lookup "location" (fjo geometry) Just (JSObject geometry) = lookup "geometry" (fjo result) Just (JSString fullAddr) = lookup "formatted_address" (fjo result)
honzasp/inkvizitor
Inkvizitor/Geocode.hs
gpl-3.0
2,670
0
16
593
745
393
352
64
3
{-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} module Hadolint.Formatter.TTY ( printResults, formatCheck, formatError, ) where import Colourista import qualified Control.Foldl as Foldl import qualified Data.Text as Text import Hadolint.Formatter.Format import Hadolint.Rule (CheckFailure (..), DLSeverity (..), RuleCode (..)) import Language.Docker.Syntax import Text.Megaparsec (TraversableStream) import Text.Megaparsec.Error import Text.Megaparsec.Stream (VisualStream) formatError :: (VisualStream s, TraversableStream s, ShowErrorComponent e) => ParseErrorBundle s e -> String formatError err = stripNewlines (errorMessageLine err) formatCheck :: Bool -> Text.Text -> CheckFailure -> Text.Text formatCheck nocolor source CheckFailure {code, severity, line, message} = formatPos source line <> unRuleCode code <> " " <> ( if nocolor then severityText severity else colorizedSeverity severity ) <> ": " <> message formatPos :: Filename -> Linenumber -> Text.Text formatPos source line = source <> ":" <> Text.pack (show line) <> " " printResults :: (VisualStream s, TraversableStream s, ShowErrorComponent e, Foldl.Foldable f) => f (Result s e) -> Bool -> IO () printResults results color = mapM_ printResult results where printResult Result {fileName, errors, checks} = printErrors errors >> printChecks fileName checks printErrors errors = mapM_ (putStrLn . formatError) errors printChecks fileName checks = mapM_ (putStrLn . Text.unpack . formatCheck color fileName) checks colorizedSeverity :: DLSeverity -> Text.Text colorizedSeverity s = case s of DLErrorC -> formatWith [bold, red] $ severityText s DLWarningC -> formatWith [bold, yellow] $ severityText s DLInfoC -> formatWith [green] $ severityText s DLStyleC -> formatWith [cyan] $ severityText s _ -> severityText s
lukasmartinelli/hadolint
src/Hadolint/Formatter/TTY.hs
gpl-3.0
1,914
0
11
352
574
306
268
46
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.DFAReporting.DirectorySites.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) -- -- Retrieves a list of directory sites, possibly filtered. This method -- supports paging. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ Campaign Manager 360 API Reference> for @dfareporting.directorySites.list@. module Network.Google.Resource.DFAReporting.DirectorySites.List ( -- * REST Resource DirectorySitesListResource -- * Creating a Request , directorySitesList , DirectorySitesList -- * Request Lenses , dslXgafv , dslUploadProtocol , dslAccessToken , dslSearchString , dslAcceptsInterstitialPlacements , dslAcceptsPublisherPaidPlacements , dslUploadType , dslIds , dslProFileId , dslSortOrder , dslActive , dslPageToken , dslSortField , dslAcceptsInStreamVideoPlacements , dslMaxResults , dslDfpNetworkCode , dslCallback ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.directorySites.list@ method which the -- 'DirectorySitesList' request conforms to. type DirectorySitesListResource = "dfareporting" :> "v3.5" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "directorySites" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "searchString" Text :> QueryParam "acceptsInterstitialPlacements" Bool :> QueryParam "acceptsPublisherPaidPlacements" Bool :> QueryParam "uploadType" Text :> QueryParams "ids" (Textual Int64) :> QueryParam "sortOrder" DirectorySitesListSortOrder :> QueryParam "active" Bool :> QueryParam "pageToken" Text :> QueryParam "sortField" DirectorySitesListSortField :> QueryParam "acceptsInStreamVideoPlacements" Bool :> QueryParam "maxResults" (Textual Int32) :> QueryParam "dfpNetworkCode" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] DirectorySitesListResponse -- | Retrieves a list of directory sites, possibly filtered. This method -- supports paging. -- -- /See:/ 'directorySitesList' smart constructor. data DirectorySitesList = DirectorySitesList' { _dslXgafv :: !(Maybe Xgafv) , _dslUploadProtocol :: !(Maybe Text) , _dslAccessToken :: !(Maybe Text) , _dslSearchString :: !(Maybe Text) , _dslAcceptsInterstitialPlacements :: !(Maybe Bool) , _dslAcceptsPublisherPaidPlacements :: !(Maybe Bool) , _dslUploadType :: !(Maybe Text) , _dslIds :: !(Maybe [Textual Int64]) , _dslProFileId :: !(Textual Int64) , _dslSortOrder :: !DirectorySitesListSortOrder , _dslActive :: !(Maybe Bool) , _dslPageToken :: !(Maybe Text) , _dslSortField :: !DirectorySitesListSortField , _dslAcceptsInStreamVideoPlacements :: !(Maybe Bool) , _dslMaxResults :: !(Textual Int32) , _dslDfpNetworkCode :: !(Maybe Text) , _dslCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'DirectorySitesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dslXgafv' -- -- * 'dslUploadProtocol' -- -- * 'dslAccessToken' -- -- * 'dslSearchString' -- -- * 'dslAcceptsInterstitialPlacements' -- -- * 'dslAcceptsPublisherPaidPlacements' -- -- * 'dslUploadType' -- -- * 'dslIds' -- -- * 'dslProFileId' -- -- * 'dslSortOrder' -- -- * 'dslActive' -- -- * 'dslPageToken' -- -- * 'dslSortField' -- -- * 'dslAcceptsInStreamVideoPlacements' -- -- * 'dslMaxResults' -- -- * 'dslDfpNetworkCode' -- -- * 'dslCallback' directorySitesList :: Int64 -- ^ 'dslProFileId' -> DirectorySitesList directorySitesList pDslProFileId_ = DirectorySitesList' { _dslXgafv = Nothing , _dslUploadProtocol = Nothing , _dslAccessToken = Nothing , _dslSearchString = Nothing , _dslAcceptsInterstitialPlacements = Nothing , _dslAcceptsPublisherPaidPlacements = Nothing , _dslUploadType = Nothing , _dslIds = Nothing , _dslProFileId = _Coerce # pDslProFileId_ , _dslSortOrder = DSLSOAscending , _dslActive = Nothing , _dslPageToken = Nothing , _dslSortField = DSLSFID , _dslAcceptsInStreamVideoPlacements = Nothing , _dslMaxResults = 1000 , _dslDfpNetworkCode = Nothing , _dslCallback = Nothing } -- | V1 error format. dslXgafv :: Lens' DirectorySitesList (Maybe Xgafv) dslXgafv = lens _dslXgafv (\ s a -> s{_dslXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). dslUploadProtocol :: Lens' DirectorySitesList (Maybe Text) dslUploadProtocol = lens _dslUploadProtocol (\ s a -> s{_dslUploadProtocol = a}) -- | OAuth access token. dslAccessToken :: Lens' DirectorySitesList (Maybe Text) dslAccessToken = lens _dslAccessToken (\ s a -> s{_dslAccessToken = a}) -- | Allows searching for objects by name, ID or URL. Wildcards (*) are -- allowed. For example, \"directory site*2015\" will return objects with -- names like \"directory site June 2015\", \"directory site April 2015\", -- or simply \"directory site 2015\". Most of the searches also add -- wildcards implicitly at the start and the end of the search string. For -- example, a search string of \"directory site\" will match objects with -- name \"my directory site\", \"directory site 2015\" or simply, -- \"directory site\". dslSearchString :: Lens' DirectorySitesList (Maybe Text) dslSearchString = lens _dslSearchString (\ s a -> s{_dslSearchString = a}) -- | This search filter is no longer supported and will have no effect on the -- results returned. dslAcceptsInterstitialPlacements :: Lens' DirectorySitesList (Maybe Bool) dslAcceptsInterstitialPlacements = lens _dslAcceptsInterstitialPlacements (\ s a -> s{_dslAcceptsInterstitialPlacements = a}) -- | Select only directory sites that accept publisher paid placements. This -- field can be left blank. dslAcceptsPublisherPaidPlacements :: Lens' DirectorySitesList (Maybe Bool) dslAcceptsPublisherPaidPlacements = lens _dslAcceptsPublisherPaidPlacements (\ s a -> s{_dslAcceptsPublisherPaidPlacements = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). dslUploadType :: Lens' DirectorySitesList (Maybe Text) dslUploadType = lens _dslUploadType (\ s a -> s{_dslUploadType = a}) -- | Select only directory sites with these IDs. dslIds :: Lens' DirectorySitesList [Int64] dslIds = lens _dslIds (\ s a -> s{_dslIds = a}) . _Default . _Coerce -- | User profile ID associated with this request. dslProFileId :: Lens' DirectorySitesList Int64 dslProFileId = lens _dslProFileId (\ s a -> s{_dslProFileId = a}) . _Coerce -- | Order of sorted results. dslSortOrder :: Lens' DirectorySitesList DirectorySitesListSortOrder dslSortOrder = lens _dslSortOrder (\ s a -> s{_dslSortOrder = a}) -- | Select only active directory sites. Leave blank to retrieve both active -- and inactive directory sites. dslActive :: Lens' DirectorySitesList (Maybe Bool) dslActive = lens _dslActive (\ s a -> s{_dslActive = a}) -- | Value of the nextPageToken from the previous result page. dslPageToken :: Lens' DirectorySitesList (Maybe Text) dslPageToken = lens _dslPageToken (\ s a -> s{_dslPageToken = a}) -- | Field by which to sort the list. dslSortField :: Lens' DirectorySitesList DirectorySitesListSortField dslSortField = lens _dslSortField (\ s a -> s{_dslSortField = a}) -- | This search filter is no longer supported and will have no effect on the -- results returned. dslAcceptsInStreamVideoPlacements :: Lens' DirectorySitesList (Maybe Bool) dslAcceptsInStreamVideoPlacements = lens _dslAcceptsInStreamVideoPlacements (\ s a -> s{_dslAcceptsInStreamVideoPlacements = a}) -- | Maximum number of results to return. dslMaxResults :: Lens' DirectorySitesList Int32 dslMaxResults = lens _dslMaxResults (\ s a -> s{_dslMaxResults = a}) . _Coerce -- | Select only directory sites with this Ad Manager network code. dslDfpNetworkCode :: Lens' DirectorySitesList (Maybe Text) dslDfpNetworkCode = lens _dslDfpNetworkCode (\ s a -> s{_dslDfpNetworkCode = a}) -- | JSONP dslCallback :: Lens' DirectorySitesList (Maybe Text) dslCallback = lens _dslCallback (\ s a -> s{_dslCallback = a}) instance GoogleRequest DirectorySitesList where type Rs DirectorySitesList = DirectorySitesListResponse type Scopes DirectorySitesList = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient DirectorySitesList'{..} = go _dslProFileId _dslXgafv _dslUploadProtocol _dslAccessToken _dslSearchString _dslAcceptsInterstitialPlacements _dslAcceptsPublisherPaidPlacements _dslUploadType (_dslIds ^. _Default) (Just _dslSortOrder) _dslActive _dslPageToken (Just _dslSortField) _dslAcceptsInStreamVideoPlacements (Just _dslMaxResults) _dslDfpNetworkCode _dslCallback (Just AltJSON) dFAReportingService where go = buildClient (Proxy :: Proxy DirectorySitesListResource) mempty
brendanhay/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/DirectorySites/List.hs
mpl-2.0
11,002
5
30
2,956
1,639
941
698
234
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.PageSpeed.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.PageSpeed.Types.Product where import Network.Google.PageSpeed.Types.Sum import Network.Google.Prelude -- -- /See:/ 'resultFormattedResultsRuleResultsAdditionalURLBlocksItem' smart constructor. data ResultFormattedResultsRuleResultsAdditionalURLBlocksItem = ResultFormattedResultsRuleResultsAdditionalURLBlocksItem' { _rfrrraubiURLs :: !(Maybe [ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem]) , _rfrrraubiHeader :: !(Maybe PagespeedAPIFormatStringV2) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ResultFormattedResultsRuleResultsAdditionalURLBlocksItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rfrrraubiURLs' -- -- * 'rfrrraubiHeader' resultFormattedResultsRuleResultsAdditionalURLBlocksItem :: ResultFormattedResultsRuleResultsAdditionalURLBlocksItem resultFormattedResultsRuleResultsAdditionalURLBlocksItem = ResultFormattedResultsRuleResultsAdditionalURLBlocksItem' { _rfrrraubiURLs = Nothing , _rfrrraubiHeader = Nothing } -- | List of entries that provide information about URLs in the url block. -- Optional. rfrrraubiURLs :: Lens' ResultFormattedResultsRuleResultsAdditionalURLBlocksItem [ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem] rfrrraubiURLs = lens _rfrrraubiURLs (\ s a -> s{_rfrrraubiURLs = a}) . _Default . _Coerce -- | Heading to be displayed with the list of URLs. rfrrraubiHeader :: Lens' ResultFormattedResultsRuleResultsAdditionalURLBlocksItem (Maybe PagespeedAPIFormatStringV2) rfrrraubiHeader = lens _rfrrraubiHeader (\ s a -> s{_rfrrraubiHeader = a}) instance FromJSON ResultFormattedResultsRuleResultsAdditionalURLBlocksItem where parseJSON = withObject "ResultFormattedResultsRuleResultsAdditionalURLBlocksItem" (\ o -> ResultFormattedResultsRuleResultsAdditionalURLBlocksItem' <$> (o .:? "urls" .!= mempty) <*> (o .:? "header")) instance ToJSON ResultFormattedResultsRuleResultsAdditionalURLBlocksItem where toJSON ResultFormattedResultsRuleResultsAdditionalURLBlocksItem'{..} = object (catMaybes [("urls" .=) <$> _rfrrraubiURLs, ("header" .=) <$> _rfrrraubiHeader]) -- -- /See:/ 'pagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem' smart constructor. data PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem = PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem' { _pafsvaisiHeight :: !(Maybe (Textual Int32)) , _pafsvaisiLeft :: !(Maybe (Textual Int32)) , _pafsvaisiWidth :: !(Maybe (Textual Int32)) , _pafsvaisiTop :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pafsvaisiHeight' -- -- * 'pafsvaisiLeft' -- -- * 'pafsvaisiWidth' -- -- * 'pafsvaisiTop' pagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem :: PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem pagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem = PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem' { _pafsvaisiHeight = Nothing , _pafsvaisiLeft = Nothing , _pafsvaisiWidth = Nothing , _pafsvaisiTop = Nothing } -- | The height of the rect. pafsvaisiHeight :: Lens' PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem (Maybe Int32) pafsvaisiHeight = lens _pafsvaisiHeight (\ s a -> s{_pafsvaisiHeight = a}) . mapping _Coerce -- | The left coordinate of the rect, in page coordinates. pafsvaisiLeft :: Lens' PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem (Maybe Int32) pafsvaisiLeft = lens _pafsvaisiLeft (\ s a -> s{_pafsvaisiLeft = a}) . mapping _Coerce -- | The width of the rect. pafsvaisiWidth :: Lens' PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem (Maybe Int32) pafsvaisiWidth = lens _pafsvaisiWidth (\ s a -> s{_pafsvaisiWidth = a}) . mapping _Coerce -- | The top coordinate of the rect, in page coordinates. pafsvaisiTop :: Lens' PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem (Maybe Int32) pafsvaisiTop = lens _pafsvaisiTop (\ s a -> s{_pafsvaisiTop = a}) . mapping _Coerce instance FromJSON PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem where parseJSON = withObject "PagespeedAPIFormatStringV2ArgsItemSecondaryRectsItem" (\ o -> PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem' <$> (o .:? "height") <*> (o .:? "left") <*> (o .:? "width") <*> (o .:? "top")) instance ToJSON PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem where toJSON PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem'{..} = object (catMaybes [("height" .=) <$> _pafsvaisiHeight, ("left" .=) <$> _pafsvaisiLeft, ("width" .=) <$> _pafsvaisiWidth, ("top" .=) <$> _pafsvaisiTop]) -- -- /See:/ 'pagespeedAPIImageV2' smart constructor. data PagespeedAPIImageV2 = PagespeedAPIImageV2' { _paivHeight :: !(Maybe (Textual Int32)) , _paivData :: !(Maybe Bytes) , _paivMimeType :: !(Maybe Text) , _paivWidth :: !(Maybe (Textual Int32)) , _paivPageRect :: !(Maybe PagespeedAPIImageV2Page_rect) , _paivKey :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PagespeedAPIImageV2' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'paivHeight' -- -- * 'paivData' -- -- * 'paivMimeType' -- -- * 'paivWidth' -- -- * 'paivPageRect' -- -- * 'paivKey' pagespeedAPIImageV2 :: PagespeedAPIImageV2 pagespeedAPIImageV2 = PagespeedAPIImageV2' { _paivHeight = Nothing , _paivData = Nothing , _paivMimeType = Nothing , _paivWidth = Nothing , _paivPageRect = Nothing , _paivKey = Nothing } -- | Height of screenshot in pixels. paivHeight :: Lens' PagespeedAPIImageV2 (Maybe Int32) paivHeight = lens _paivHeight (\ s a -> s{_paivHeight = a}) . mapping _Coerce -- | Image data base64 encoded. paivData :: Lens' PagespeedAPIImageV2 (Maybe ByteString) paivData = lens _paivData (\ s a -> s{_paivData = a}) . mapping _Bytes -- | Mime type of image data (e.g. \"image\/jpeg\"). paivMimeType :: Lens' PagespeedAPIImageV2 (Maybe Text) paivMimeType = lens _paivMimeType (\ s a -> s{_paivMimeType = a}) -- | Width of screenshot in pixels. paivWidth :: Lens' PagespeedAPIImageV2 (Maybe Int32) paivWidth = lens _paivWidth (\ s a -> s{_paivWidth = a}) . mapping _Coerce -- | The region of the page that is captured by this image, with dimensions -- measured in CSS pixels. paivPageRect :: Lens' PagespeedAPIImageV2 (Maybe PagespeedAPIImageV2Page_rect) paivPageRect = lens _paivPageRect (\ s a -> s{_paivPageRect = a}) -- | Unique string key, if any, identifying this image. paivKey :: Lens' PagespeedAPIImageV2 (Maybe Text) paivKey = lens _paivKey (\ s a -> s{_paivKey = a}) instance FromJSON PagespeedAPIImageV2 where parseJSON = withObject "PagespeedAPIImageV2" (\ o -> PagespeedAPIImageV2' <$> (o .:? "height") <*> (o .:? "data") <*> (o .:? "mime_type") <*> (o .:? "width") <*> (o .:? "page_rect") <*> (o .:? "key")) instance ToJSON PagespeedAPIImageV2 where toJSON PagespeedAPIImageV2'{..} = object (catMaybes [("height" .=) <$> _paivHeight, ("data" .=) <$> _paivData, ("mime_type" .=) <$> _paivMimeType, ("width" .=) <$> _paivWidth, ("page_rect" .=) <$> _paivPageRect, ("key" .=) <$> _paivKey]) -- -- /See:/ 'pagespeedAPIFormatStringV2ArgsItemRectsItem' smart constructor. data PagespeedAPIFormatStringV2ArgsItemRectsItem = PagespeedAPIFormatStringV2ArgsItemRectsItem' { _pafsvairiHeight :: !(Maybe (Textual Int32)) , _pafsvairiLeft :: !(Maybe (Textual Int32)) , _pafsvairiWidth :: !(Maybe (Textual Int32)) , _pafsvairiTop :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PagespeedAPIFormatStringV2ArgsItemRectsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pafsvairiHeight' -- -- * 'pafsvairiLeft' -- -- * 'pafsvairiWidth' -- -- * 'pafsvairiTop' pagespeedAPIFormatStringV2ArgsItemRectsItem :: PagespeedAPIFormatStringV2ArgsItemRectsItem pagespeedAPIFormatStringV2ArgsItemRectsItem = PagespeedAPIFormatStringV2ArgsItemRectsItem' { _pafsvairiHeight = Nothing , _pafsvairiLeft = Nothing , _pafsvairiWidth = Nothing , _pafsvairiTop = Nothing } -- | The height of the rect. pafsvairiHeight :: Lens' PagespeedAPIFormatStringV2ArgsItemRectsItem (Maybe Int32) pafsvairiHeight = lens _pafsvairiHeight (\ s a -> s{_pafsvairiHeight = a}) . mapping _Coerce -- | The left coordinate of the rect, in page coordinates. pafsvairiLeft :: Lens' PagespeedAPIFormatStringV2ArgsItemRectsItem (Maybe Int32) pafsvairiLeft = lens _pafsvairiLeft (\ s a -> s{_pafsvairiLeft = a}) . mapping _Coerce -- | The width of the rect. pafsvairiWidth :: Lens' PagespeedAPIFormatStringV2ArgsItemRectsItem (Maybe Int32) pafsvairiWidth = lens _pafsvairiWidth (\ s a -> s{_pafsvairiWidth = a}) . mapping _Coerce -- | The top coordinate of the rect, in page coordinates. pafsvairiTop :: Lens' PagespeedAPIFormatStringV2ArgsItemRectsItem (Maybe Int32) pafsvairiTop = lens _pafsvairiTop (\ s a -> s{_pafsvairiTop = a}) . mapping _Coerce instance FromJSON PagespeedAPIFormatStringV2ArgsItemRectsItem where parseJSON = withObject "PagespeedAPIFormatStringV2ArgsItemRectsItem" (\ o -> PagespeedAPIFormatStringV2ArgsItemRectsItem' <$> (o .:? "height") <*> (o .:? "left") <*> (o .:? "width") <*> (o .:? "top")) instance ToJSON PagespeedAPIFormatStringV2ArgsItemRectsItem where toJSON PagespeedAPIFormatStringV2ArgsItemRectsItem'{..} = object (catMaybes [("height" .=) <$> _pafsvairiHeight, ("left" .=) <$> _pafsvairiLeft, ("width" .=) <$> _pafsvairiWidth, ("top" .=) <$> _pafsvairiTop]) -- | The version of PageSpeed used to generate these results. -- -- /See:/ 'resultVersion' smart constructor. data ResultVersion = ResultVersion' { _rvMinor :: !(Maybe (Textual Int32)) , _rvMajor :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ResultVersion' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rvMinor' -- -- * 'rvMajor' resultVersion :: ResultVersion resultVersion = ResultVersion' { _rvMinor = Nothing , _rvMajor = Nothing } -- | The minor version number of PageSpeed used to generate these results. rvMinor :: Lens' ResultVersion (Maybe Int32) rvMinor = lens _rvMinor (\ s a -> s{_rvMinor = a}) . mapping _Coerce -- | The major version number of PageSpeed used to generate these results. rvMajor :: Lens' ResultVersion (Maybe Int32) rvMajor = lens _rvMajor (\ s a -> s{_rvMajor = a}) . mapping _Coerce instance FromJSON ResultVersion where parseJSON = withObject "ResultVersion" (\ o -> ResultVersion' <$> (o .:? "minor") <*> (o .:? "major")) instance ToJSON ResultVersion where toJSON ResultVersion'{..} = object (catMaybes [("minor" .=) <$> _rvMinor, ("major" .=) <$> _rvMajor]) -- | Summary statistics for the page, such as number of JavaScript bytes, -- number of HTML bytes, etc. -- -- /See:/ 'resultPageStats' smart constructor. data ResultPageStats = ResultPageStats' { _rpsHTMLResponseBytes :: !(Maybe (Textual Int64)) , _rpsTotalRequestBytes :: !(Maybe (Textual Int64)) , _rpsNumberResources :: !(Maybe (Textual Int32)) , _rpsNumberStaticResources :: !(Maybe (Textual Int32)) , _rpsNumberHosts :: !(Maybe (Textual Int32)) , _rpsNumberJsResources :: !(Maybe (Textual Int32)) , _rpsNumberCssResources :: !(Maybe (Textual Int32)) , _rpsTextResponseBytes :: !(Maybe (Textual Int64)) , _rpsFlashResponseBytes :: !(Maybe (Textual Int64)) , _rpsImageResponseBytes :: !(Maybe (Textual Int64)) , _rpsOtherResponseBytes :: !(Maybe (Textual Int64)) , _rpsJavascriptResponseBytes :: !(Maybe (Textual Int64)) , _rpsCssResponseBytes :: !(Maybe (Textual Int64)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ResultPageStats' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rpsHTMLResponseBytes' -- -- * 'rpsTotalRequestBytes' -- -- * 'rpsNumberResources' -- -- * 'rpsNumberStaticResources' -- -- * 'rpsNumberHosts' -- -- * 'rpsNumberJsResources' -- -- * 'rpsNumberCssResources' -- -- * 'rpsTextResponseBytes' -- -- * 'rpsFlashResponseBytes' -- -- * 'rpsImageResponseBytes' -- -- * 'rpsOtherResponseBytes' -- -- * 'rpsJavascriptResponseBytes' -- -- * 'rpsCssResponseBytes' resultPageStats :: ResultPageStats resultPageStats = ResultPageStats' { _rpsHTMLResponseBytes = Nothing , _rpsTotalRequestBytes = Nothing , _rpsNumberResources = Nothing , _rpsNumberStaticResources = Nothing , _rpsNumberHosts = Nothing , _rpsNumberJsResources = Nothing , _rpsNumberCssResources = Nothing , _rpsTextResponseBytes = Nothing , _rpsFlashResponseBytes = Nothing , _rpsImageResponseBytes = Nothing , _rpsOtherResponseBytes = Nothing , _rpsJavascriptResponseBytes = Nothing , _rpsCssResponseBytes = Nothing } -- | Number of uncompressed response bytes for the main HTML document and all -- iframes on the page. rpsHTMLResponseBytes :: Lens' ResultPageStats (Maybe Int64) rpsHTMLResponseBytes = lens _rpsHTMLResponseBytes (\ s a -> s{_rpsHTMLResponseBytes = a}) . mapping _Coerce -- | Total size of all request bytes sent by the page. rpsTotalRequestBytes :: Lens' ResultPageStats (Maybe Int64) rpsTotalRequestBytes = lens _rpsTotalRequestBytes (\ s a -> s{_rpsTotalRequestBytes = a}) . mapping _Coerce -- | Number of HTTP resources loaded by the page. rpsNumberResources :: Lens' ResultPageStats (Maybe Int32) rpsNumberResources = lens _rpsNumberResources (\ s a -> s{_rpsNumberResources = a}) . mapping _Coerce -- | Number of static (i.e. cacheable) resources on the page. rpsNumberStaticResources :: Lens' ResultPageStats (Maybe Int32) rpsNumberStaticResources = lens _rpsNumberStaticResources (\ s a -> s{_rpsNumberStaticResources = a}) . mapping _Coerce -- | Number of unique hosts referenced by the page. rpsNumberHosts :: Lens' ResultPageStats (Maybe Int32) rpsNumberHosts = lens _rpsNumberHosts (\ s a -> s{_rpsNumberHosts = a}) . mapping _Coerce -- | Number of JavaScript resources referenced by the page. rpsNumberJsResources :: Lens' ResultPageStats (Maybe Int32) rpsNumberJsResources = lens _rpsNumberJsResources (\ s a -> s{_rpsNumberJsResources = a}) . mapping _Coerce -- | Number of CSS resources referenced by the page. rpsNumberCssResources :: Lens' ResultPageStats (Maybe Int32) rpsNumberCssResources = lens _rpsNumberCssResources (\ s a -> s{_rpsNumberCssResources = a}) . mapping _Coerce -- | Number of uncompressed response bytes for text resources not covered by -- other statistics (i.e non-HTML, non-script, non-CSS resources) on the -- page. rpsTextResponseBytes :: Lens' ResultPageStats (Maybe Int64) rpsTextResponseBytes = lens _rpsTextResponseBytes (\ s a -> s{_rpsTextResponseBytes = a}) . mapping _Coerce -- | Number of response bytes for flash resources on the page. rpsFlashResponseBytes :: Lens' ResultPageStats (Maybe Int64) rpsFlashResponseBytes = lens _rpsFlashResponseBytes (\ s a -> s{_rpsFlashResponseBytes = a}) . mapping _Coerce -- | Number of response bytes for image resources on the page. rpsImageResponseBytes :: Lens' ResultPageStats (Maybe Int64) rpsImageResponseBytes = lens _rpsImageResponseBytes (\ s a -> s{_rpsImageResponseBytes = a}) . mapping _Coerce -- | Number of response bytes for other resources on the page. rpsOtherResponseBytes :: Lens' ResultPageStats (Maybe Int64) rpsOtherResponseBytes = lens _rpsOtherResponseBytes (\ s a -> s{_rpsOtherResponseBytes = a}) . mapping _Coerce -- | Number of uncompressed response bytes for JS resources on the page. rpsJavascriptResponseBytes :: Lens' ResultPageStats (Maybe Int64) rpsJavascriptResponseBytes = lens _rpsJavascriptResponseBytes (\ s a -> s{_rpsJavascriptResponseBytes = a}) . mapping _Coerce -- | Number of uncompressed response bytes for CSS resources on the page. rpsCssResponseBytes :: Lens' ResultPageStats (Maybe Int64) rpsCssResponseBytes = lens _rpsCssResponseBytes (\ s a -> s{_rpsCssResponseBytes = a}) . mapping _Coerce instance FromJSON ResultPageStats where parseJSON = withObject "ResultPageStats" (\ o -> ResultPageStats' <$> (o .:? "htmlResponseBytes") <*> (o .:? "totalRequestBytes") <*> (o .:? "numberResources") <*> (o .:? "numberStaticResources") <*> (o .:? "numberHosts") <*> (o .:? "numberJsResources") <*> (o .:? "numberCssResources") <*> (o .:? "textResponseBytes") <*> (o .:? "flashResponseBytes") <*> (o .:? "imageResponseBytes") <*> (o .:? "otherResponseBytes") <*> (o .:? "javascriptResponseBytes") <*> (o .:? "cssResponseBytes")) instance ToJSON ResultPageStats where toJSON ResultPageStats'{..} = object (catMaybes [("htmlResponseBytes" .=) <$> _rpsHTMLResponseBytes, ("totalRequestBytes" .=) <$> _rpsTotalRequestBytes, ("numberResources" .=) <$> _rpsNumberResources, ("numberStaticResources" .=) <$> _rpsNumberStaticResources, ("numberHosts" .=) <$> _rpsNumberHosts, ("numberJsResources" .=) <$> _rpsNumberJsResources, ("numberCssResources" .=) <$> _rpsNumberCssResources, ("textResponseBytes" .=) <$> _rpsTextResponseBytes, ("flashResponseBytes" .=) <$> _rpsFlashResponseBytes, ("imageResponseBytes" .=) <$> _rpsImageResponseBytes, ("otherResponseBytes" .=) <$> _rpsOtherResponseBytes, ("javascriptResponseBytes" .=) <$> _rpsJavascriptResponseBytes, ("cssResponseBytes" .=) <$> _rpsCssResponseBytes]) -- | The region of the page that is captured by this image, with dimensions -- measured in CSS pixels. -- -- /See:/ 'pagespeedAPIImageV2Page_rect' smart constructor. data PagespeedAPIImageV2Page_rect = PagespeedAPIImageV2Page_rect' { _paivpHeight :: !(Maybe (Textual Int32)) , _paivpLeft :: !(Maybe (Textual Int32)) , _paivpWidth :: !(Maybe (Textual Int32)) , _paivpTop :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PagespeedAPIImageV2Page_rect' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'paivpHeight' -- -- * 'paivpLeft' -- -- * 'paivpWidth' -- -- * 'paivpTop' pagespeedAPIImageV2Page_rect :: PagespeedAPIImageV2Page_rect pagespeedAPIImageV2Page_rect = PagespeedAPIImageV2Page_rect' { _paivpHeight = Nothing , _paivpLeft = Nothing , _paivpWidth = Nothing , _paivpTop = Nothing } -- | The height of the rect. paivpHeight :: Lens' PagespeedAPIImageV2Page_rect (Maybe Int32) paivpHeight = lens _paivpHeight (\ s a -> s{_paivpHeight = a}) . mapping _Coerce -- | The left coordinate of the rect, in page coordinates. paivpLeft :: Lens' PagespeedAPIImageV2Page_rect (Maybe Int32) paivpLeft = lens _paivpLeft (\ s a -> s{_paivpLeft = a}) . mapping _Coerce -- | The width of the rect. paivpWidth :: Lens' PagespeedAPIImageV2Page_rect (Maybe Int32) paivpWidth = lens _paivpWidth (\ s a -> s{_paivpWidth = a}) . mapping _Coerce -- | The top coordinate of the rect, in page coordinates. paivpTop :: Lens' PagespeedAPIImageV2Page_rect (Maybe Int32) paivpTop = lens _paivpTop (\ s a -> s{_paivpTop = a}) . mapping _Coerce instance FromJSON PagespeedAPIImageV2Page_rect where parseJSON = withObject "PagespeedAPIImageV2PageRect" (\ o -> PagespeedAPIImageV2Page_rect' <$> (o .:? "height") <*> (o .:? "left") <*> (o .:? "width") <*> (o .:? "top")) instance ToJSON PagespeedAPIImageV2Page_rect where toJSON PagespeedAPIImageV2Page_rect'{..} = object (catMaybes [("height" .=) <$> _paivpHeight, ("left" .=) <$> _paivpLeft, ("width" .=) <$> _paivpWidth, ("top" .=) <$> _paivpTop]) -- -- /See:/ 'result' smart constructor. data Result = Result' { _rScreenshot :: !(Maybe PagespeedAPIImageV2) , _rKind :: !Text , _rResponseCode :: !(Maybe (Textual Int32)) , _rInvalidRules :: !(Maybe [Text]) , _rFormattedResults :: !(Maybe ResultFormattedResults) , _rVersion :: !(Maybe ResultVersion) , _rRuleGroups :: !(Maybe ResultRuleGroups) , _rPageStats :: !(Maybe ResultPageStats) , _rId :: !(Maybe Text) , _rTitle :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'Result' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rScreenshot' -- -- * 'rKind' -- -- * 'rResponseCode' -- -- * 'rInvalidRules' -- -- * 'rFormattedResults' -- -- * 'rVersion' -- -- * 'rRuleGroups' -- -- * 'rPageStats' -- -- * 'rId' -- -- * 'rTitle' result :: Result result = Result' { _rScreenshot = Nothing , _rKind = "pagespeedonline#result" , _rResponseCode = Nothing , _rInvalidRules = Nothing , _rFormattedResults = Nothing , _rVersion = Nothing , _rRuleGroups = Nothing , _rPageStats = Nothing , _rId = Nothing , _rTitle = Nothing } -- | Base64-encoded screenshot of the page that was analyzed. rScreenshot :: Lens' Result (Maybe PagespeedAPIImageV2) rScreenshot = lens _rScreenshot (\ s a -> s{_rScreenshot = a}) -- | Kind of result. rKind :: Lens' Result Text rKind = lens _rKind (\ s a -> s{_rKind = a}) -- | Response code for the document. 200 indicates a normal page load. -- 4xx\/5xx indicates an error. rResponseCode :: Lens' Result (Maybe Int32) rResponseCode = lens _rResponseCode (\ s a -> s{_rResponseCode = a}) . mapping _Coerce -- | List of rules that were specified in the request, but which the server -- did not know how to instantiate. rInvalidRules :: Lens' Result [Text] rInvalidRules = lens _rInvalidRules (\ s a -> s{_rInvalidRules = a}) . _Default . _Coerce -- | Localized PageSpeed results. Contains a ruleResults entry for each -- PageSpeed rule instantiated and run by the server. rFormattedResults :: Lens' Result (Maybe ResultFormattedResults) rFormattedResults = lens _rFormattedResults (\ s a -> s{_rFormattedResults = a}) -- | The version of PageSpeed used to generate these results. rVersion :: Lens' Result (Maybe ResultVersion) rVersion = lens _rVersion (\ s a -> s{_rVersion = a}) -- | A map with one entry for each rule group in these results. rRuleGroups :: Lens' Result (Maybe ResultRuleGroups) rRuleGroups = lens _rRuleGroups (\ s a -> s{_rRuleGroups = a}) -- | Summary statistics for the page, such as number of JavaScript bytes, -- number of HTML bytes, etc. rPageStats :: Lens' Result (Maybe ResultPageStats) rPageStats = lens _rPageStats (\ s a -> s{_rPageStats = a}) -- | Canonicalized and final URL for the document, after following page -- redirects (if any). rId :: Lens' Result (Maybe Text) rId = lens _rId (\ s a -> s{_rId = a}) -- | Title of the page, as displayed in the browser\'s title bar. rTitle :: Lens' Result (Maybe Text) rTitle = lens _rTitle (\ s a -> s{_rTitle = a}) instance FromJSON Result where parseJSON = withObject "Result" (\ o -> Result' <$> (o .:? "screenshot") <*> (o .:? "kind" .!= "pagespeedonline#result") <*> (o .:? "responseCode") <*> (o .:? "invalidRules" .!= mempty) <*> (o .:? "formattedResults") <*> (o .:? "version") <*> (o .:? "ruleGroups") <*> (o .:? "pageStats") <*> (o .:? "id") <*> (o .:? "title")) instance ToJSON Result where toJSON Result'{..} = object (catMaybes [("screenshot" .=) <$> _rScreenshot, Just ("kind" .= _rKind), ("responseCode" .=) <$> _rResponseCode, ("invalidRules" .=) <$> _rInvalidRules, ("formattedResults" .=) <$> _rFormattedResults, ("version" .=) <$> _rVersion, ("ruleGroups" .=) <$> _rRuleGroups, ("pageStats" .=) <$> _rPageStats, ("id" .=) <$> _rId, ("title" .=) <$> _rTitle]) -- -- /See:/ 'pagespeedAPIFormatStringV2ArgsItem' smart constructor. data PagespeedAPIFormatStringV2ArgsItem = PagespeedAPIFormatStringV2ArgsItem' { _pafsvaiValue :: !(Maybe Text) , _pafsvaiRects :: !(Maybe [PagespeedAPIFormatStringV2ArgsItemRectsItem]) , _pafsvaiKey :: !(Maybe Text) , _pafsvaiType :: !(Maybe Text) , _pafsvaiSecondaryRects :: !(Maybe [PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PagespeedAPIFormatStringV2ArgsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pafsvaiValue' -- -- * 'pafsvaiRects' -- -- * 'pafsvaiKey' -- -- * 'pafsvaiType' -- -- * 'pafsvaiSecondaryRects' pagespeedAPIFormatStringV2ArgsItem :: PagespeedAPIFormatStringV2ArgsItem pagespeedAPIFormatStringV2ArgsItem = PagespeedAPIFormatStringV2ArgsItem' { _pafsvaiValue = Nothing , _pafsvaiRects = Nothing , _pafsvaiKey = Nothing , _pafsvaiType = Nothing , _pafsvaiSecondaryRects = Nothing } -- | Argument value, as a localized string. pafsvaiValue :: Lens' PagespeedAPIFormatStringV2ArgsItem (Maybe Text) pafsvaiValue = lens _pafsvaiValue (\ s a -> s{_pafsvaiValue = a}) -- | The screen rectangles being referred to, with dimensions measured in CSS -- pixels. This is only ever used for SNAPSHOT_RECT arguments. If this is -- absent for a SNAPSHOT_RECT argument, it means that that argument refers -- to the entire snapshot. pafsvaiRects :: Lens' PagespeedAPIFormatStringV2ArgsItem [PagespeedAPIFormatStringV2ArgsItemRectsItem] pafsvaiRects = lens _pafsvaiRects (\ s a -> s{_pafsvaiRects = a}) . _Default . _Coerce -- | The placeholder key for this arg, as a string. pafsvaiKey :: Lens' PagespeedAPIFormatStringV2ArgsItem (Maybe Text) pafsvaiKey = lens _pafsvaiKey (\ s a -> s{_pafsvaiKey = a}) -- | Type of argument. One of URL, STRING_LITERAL, INT_LITERAL, BYTES, -- DURATION, VERBATIM_STRING, PERCENTAGE, HYPERLINK, or SNAPSHOT_RECT. pafsvaiType :: Lens' PagespeedAPIFormatStringV2ArgsItem (Maybe Text) pafsvaiType = lens _pafsvaiType (\ s a -> s{_pafsvaiType = a}) -- | Secondary screen rectangles being referred to, with dimensions measured -- in CSS pixels. This is only ever used for SNAPSHOT_RECT arguments. pafsvaiSecondaryRects :: Lens' PagespeedAPIFormatStringV2ArgsItem [PagespeedAPIFormatStringV2ArgsItemSecondary_rectsItem] pafsvaiSecondaryRects = lens _pafsvaiSecondaryRects (\ s a -> s{_pafsvaiSecondaryRects = a}) . _Default . _Coerce instance FromJSON PagespeedAPIFormatStringV2ArgsItem where parseJSON = withObject "PagespeedAPIFormatStringV2ArgsItem" (\ o -> PagespeedAPIFormatStringV2ArgsItem' <$> (o .:? "value") <*> (o .:? "rects" .!= mempty) <*> (o .:? "key") <*> (o .:? "type") <*> (o .:? "secondary_rects" .!= mempty)) instance ToJSON PagespeedAPIFormatStringV2ArgsItem where toJSON PagespeedAPIFormatStringV2ArgsItem'{..} = object (catMaybes [("value" .=) <$> _pafsvaiValue, ("rects" .=) <$> _pafsvaiRects, ("key" .=) <$> _pafsvaiKey, ("type" .=) <$> _pafsvaiType, ("secondary_rects" .=) <$> _pafsvaiSecondaryRects]) -- | The name of this rule group: one of \"SPEED\" or \"USABILITY\". -- -- /See:/ 'resultRuleGroupsAdditional' smart constructor. newtype ResultRuleGroupsAdditional = ResultRuleGroupsAdditional' { _rrgaScore :: Maybe (Textual Int32) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ResultRuleGroupsAdditional' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rrgaScore' resultRuleGroupsAdditional :: ResultRuleGroupsAdditional resultRuleGroupsAdditional = ResultRuleGroupsAdditional' { _rrgaScore = Nothing } -- | The score (0-100) for this rule group, which indicates how much better a -- page could be in that category (e.g. how much faster, or how much more -- usable). A high score indicates little room for improvement, while a -- lower score indicates more room for improvement. rrgaScore :: Lens' ResultRuleGroupsAdditional (Maybe Int32) rrgaScore = lens _rrgaScore (\ s a -> s{_rrgaScore = a}) . mapping _Coerce instance FromJSON ResultRuleGroupsAdditional where parseJSON = withObject "ResultRuleGroupsAdditional" (\ o -> ResultRuleGroupsAdditional' <$> (o .:? "score")) instance ToJSON ResultRuleGroupsAdditional where toJSON ResultRuleGroupsAdditional'{..} = object (catMaybes [("score" .=) <$> _rrgaScore]) -- | Localized PageSpeed results. Contains a ruleResults entry for each -- PageSpeed rule instantiated and run by the server. -- -- /See:/ 'resultFormattedResults' smart constructor. data ResultFormattedResults = ResultFormattedResults' { _rfrLocale :: !(Maybe Text) , _rfrRuleResults :: !(Maybe ResultFormattedResultsRuleResults) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ResultFormattedResults' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rfrLocale' -- -- * 'rfrRuleResults' resultFormattedResults :: ResultFormattedResults resultFormattedResults = ResultFormattedResults' { _rfrLocale = Nothing , _rfrRuleResults = Nothing } -- | The locale of the formattedResults, e.g. \"en_US\". rfrLocale :: Lens' ResultFormattedResults (Maybe Text) rfrLocale = lens _rfrLocale (\ s a -> s{_rfrLocale = a}) -- | Dictionary of formatted rule results, with one entry for each PageSpeed -- rule instantiated and run by the server. rfrRuleResults :: Lens' ResultFormattedResults (Maybe ResultFormattedResultsRuleResults) rfrRuleResults = lens _rfrRuleResults (\ s a -> s{_rfrRuleResults = a}) instance FromJSON ResultFormattedResults where parseJSON = withObject "ResultFormattedResults" (\ o -> ResultFormattedResults' <$> (o .:? "locale") <*> (o .:? "ruleResults")) instance ToJSON ResultFormattedResults where toJSON ResultFormattedResults'{..} = object (catMaybes [("locale" .=) <$> _rfrLocale, ("ruleResults" .=) <$> _rfrRuleResults]) -- | The enum-like identifier for this rule. For instance \"EnableKeepAlive\" -- or \"AvoidCssImport\". Not localized. -- -- /See:/ 'resultFormattedResultsRuleResultsAdditional' smart constructor. data ResultFormattedResultsRuleResultsAdditional = ResultFormattedResultsRuleResultsAdditional' { _rfrrraSummary :: !(Maybe PagespeedAPIFormatStringV2) , _rfrrraRuleImpact :: !(Maybe (Textual Double)) , _rfrrraGroups :: !(Maybe [Text]) , _rfrrraLocalizedRuleName :: !(Maybe Text) , _rfrrraURLBlocks :: !(Maybe [ResultFormattedResultsRuleResultsAdditionalURLBlocksItem]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ResultFormattedResultsRuleResultsAdditional' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rfrrraSummary' -- -- * 'rfrrraRuleImpact' -- -- * 'rfrrraGroups' -- -- * 'rfrrraLocalizedRuleName' -- -- * 'rfrrraURLBlocks' resultFormattedResultsRuleResultsAdditional :: ResultFormattedResultsRuleResultsAdditional resultFormattedResultsRuleResultsAdditional = ResultFormattedResultsRuleResultsAdditional' { _rfrrraSummary = Nothing , _rfrrraRuleImpact = Nothing , _rfrrraGroups = Nothing , _rfrrraLocalizedRuleName = Nothing , _rfrrraURLBlocks = Nothing } -- | A brief summary description for the rule, indicating at a high level -- what should be done to follow the rule and what benefit can be gained by -- doing so. rfrrraSummary :: Lens' ResultFormattedResultsRuleResultsAdditional (Maybe PagespeedAPIFormatStringV2) rfrrraSummary = lens _rfrrraSummary (\ s a -> s{_rfrrraSummary = a}) -- | The impact (unbounded floating point value) that implementing the -- suggestions for this rule would have on making the page faster. Impact -- is comparable between rules to determine which rule\'s suggestions would -- have a higher or lower impact on making a page faster. For instance, if -- enabling compression would save 1MB, while optimizing images would save -- 500kB, the enable compression rule would have 2x the impact of the image -- optimization rule, all other things being equal. rfrrraRuleImpact :: Lens' ResultFormattedResultsRuleResultsAdditional (Maybe Double) rfrrraRuleImpact = lens _rfrrraRuleImpact (\ s a -> s{_rfrrraRuleImpact = a}) . mapping _Coerce -- | List of rule groups that this rule belongs to. Each entry in the list is -- one of \"SPEED\" or \"USABILITY\". rfrrraGroups :: Lens' ResultFormattedResultsRuleResultsAdditional [Text] rfrrraGroups = lens _rfrrraGroups (\ s a -> s{_rfrrraGroups = a}) . _Default . _Coerce -- | Localized name of the rule, intended for presentation to a user. rfrrraLocalizedRuleName :: Lens' ResultFormattedResultsRuleResultsAdditional (Maybe Text) rfrrraLocalizedRuleName = lens _rfrrraLocalizedRuleName (\ s a -> s{_rfrrraLocalizedRuleName = a}) -- | List of blocks of URLs. Each block may contain a heading and a list of -- URLs. Each URL may optionally include additional details. rfrrraURLBlocks :: Lens' ResultFormattedResultsRuleResultsAdditional [ResultFormattedResultsRuleResultsAdditionalURLBlocksItem] rfrrraURLBlocks = lens _rfrrraURLBlocks (\ s a -> s{_rfrrraURLBlocks = a}) . _Default . _Coerce instance FromJSON ResultFormattedResultsRuleResultsAdditional where parseJSON = withObject "ResultFormattedResultsRuleResultsAdditional" (\ o -> ResultFormattedResultsRuleResultsAdditional' <$> (o .:? "summary") <*> (o .:? "ruleImpact") <*> (o .:? "groups" .!= mempty) <*> (o .:? "localizedRuleName") <*> (o .:? "urlBlocks" .!= mempty)) instance ToJSON ResultFormattedResultsRuleResultsAdditional where toJSON ResultFormattedResultsRuleResultsAdditional'{..} = object (catMaybes [("summary" .=) <$> _rfrrraSummary, ("ruleImpact" .=) <$> _rfrrraRuleImpact, ("groups" .=) <$> _rfrrraGroups, ("localizedRuleName" .=) <$> _rfrrraLocalizedRuleName, ("urlBlocks" .=) <$> _rfrrraURLBlocks]) -- | A map with one entry for each rule group in these results. -- -- /See:/ 'resultRuleGroups' smart constructor. newtype ResultRuleGroups = ResultRuleGroups' { _rrgAddtional :: HashMap Text ResultRuleGroupsAdditional } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ResultRuleGroups' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rrgAddtional' resultRuleGroups :: HashMap Text ResultRuleGroupsAdditional -- ^ 'rrgAddtional' -> ResultRuleGroups resultRuleGroups pRrgAddtional_ = ResultRuleGroups' { _rrgAddtional = _Coerce # pRrgAddtional_ } -- | The name of this rule group: one of \"SPEED\" or \"USABILITY\". rrgAddtional :: Lens' ResultRuleGroups (HashMap Text ResultRuleGroupsAdditional) rrgAddtional = lens _rrgAddtional (\ s a -> s{_rrgAddtional = a}) . _Coerce instance FromJSON ResultRuleGroups where parseJSON = withObject "ResultRuleGroups" (\ o -> ResultRuleGroups' <$> (parseJSONObject o)) instance ToJSON ResultRuleGroups where toJSON = toJSON . _rrgAddtional -- -- /See:/ 'pagespeedAPIFormatStringV2' smart constructor. data PagespeedAPIFormatStringV2 = PagespeedAPIFormatStringV2' { _pafsvArgs :: !(Maybe [PagespeedAPIFormatStringV2ArgsItem]) , _pafsvFormat :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PagespeedAPIFormatStringV2' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pafsvArgs' -- -- * 'pafsvFormat' pagespeedAPIFormatStringV2 :: PagespeedAPIFormatStringV2 pagespeedAPIFormatStringV2 = PagespeedAPIFormatStringV2' { _pafsvArgs = Nothing , _pafsvFormat = Nothing } -- | List of arguments for the format string. pafsvArgs :: Lens' PagespeedAPIFormatStringV2 [PagespeedAPIFormatStringV2ArgsItem] pafsvArgs = lens _pafsvArgs (\ s a -> s{_pafsvArgs = a}) . _Default . _Coerce -- | A localized format string with {{FOO}} placeholders, where \'FOO\' is -- the key of the argument whose value should be substituted. For HYPERLINK -- arguments, the format string will instead contain {{BEGIN_FOO}} and -- {{END_FOO}} for the argument with key \'FOO\'. pafsvFormat :: Lens' PagespeedAPIFormatStringV2 (Maybe Text) pafsvFormat = lens _pafsvFormat (\ s a -> s{_pafsvFormat = a}) instance FromJSON PagespeedAPIFormatStringV2 where parseJSON = withObject "PagespeedAPIFormatStringV2" (\ o -> PagespeedAPIFormatStringV2' <$> (o .:? "args" .!= mempty) <*> (o .:? "format")) instance ToJSON PagespeedAPIFormatStringV2 where toJSON PagespeedAPIFormatStringV2'{..} = object (catMaybes [("args" .=) <$> _pafsvArgs, ("format" .=) <$> _pafsvFormat]) -- | Dictionary of formatted rule results, with one entry for each PageSpeed -- rule instantiated and run by the server. -- -- /See:/ 'resultFormattedResultsRuleResults' smart constructor. newtype ResultFormattedResultsRuleResults = ResultFormattedResultsRuleResults' { _rfrrrAddtional :: HashMap Text ResultFormattedResultsRuleResultsAdditional } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ResultFormattedResultsRuleResults' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rfrrrAddtional' resultFormattedResultsRuleResults :: HashMap Text ResultFormattedResultsRuleResultsAdditional -- ^ 'rfrrrAddtional' -> ResultFormattedResultsRuleResults resultFormattedResultsRuleResults pRfrrrAddtional_ = ResultFormattedResultsRuleResults' { _rfrrrAddtional = _Coerce # pRfrrrAddtional_ } -- | The enum-like identifier for this rule. For instance \"EnableKeepAlive\" -- or \"AvoidCssImport\". Not localized. rfrrrAddtional :: Lens' ResultFormattedResultsRuleResults (HashMap Text ResultFormattedResultsRuleResultsAdditional) rfrrrAddtional = lens _rfrrrAddtional (\ s a -> s{_rfrrrAddtional = a}) . _Coerce instance FromJSON ResultFormattedResultsRuleResults where parseJSON = withObject "ResultFormattedResultsRuleResults" (\ o -> ResultFormattedResultsRuleResults' <$> (parseJSONObject o)) instance ToJSON ResultFormattedResultsRuleResults where toJSON = toJSON . _rfrrrAddtional -- -- /See:/ 'resultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem' smart constructor. data ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem = ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem' { _rfrrraubiuiResult :: !(Maybe PagespeedAPIFormatStringV2) , _rfrrraubiuiDetails :: !(Maybe [PagespeedAPIFormatStringV2]) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rfrrraubiuiResult' -- -- * 'rfrrraubiuiDetails' resultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem :: ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem resultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem = ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem' { _rfrrraubiuiResult = Nothing , _rfrrraubiuiDetails = Nothing } -- | A format string that gives information about the URL, and a list of -- arguments for that format string. rfrrraubiuiResult :: Lens' ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem (Maybe PagespeedAPIFormatStringV2) rfrrraubiuiResult = lens _rfrrraubiuiResult (\ s a -> s{_rfrrraubiuiResult = a}) -- | List of entries that provide additional details about a single URL. -- Optional. rfrrraubiuiDetails :: Lens' ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem [PagespeedAPIFormatStringV2] rfrrraubiuiDetails = lens _rfrrraubiuiDetails (\ s a -> s{_rfrrraubiuiDetails = a}) . _Default . _Coerce instance FromJSON ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem where parseJSON = withObject "ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem" (\ o -> ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem' <$> (o .:? "result") <*> (o .:? "details" .!= mempty)) instance ToJSON ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem where toJSON ResultFormattedResultsRuleResultsAdditionalURLBlocksItemURLsItem'{..} = object (catMaybes [("result" .=) <$> _rfrrraubiuiResult, ("details" .=) <$> _rfrrraubiuiDetails])
rueshyna/gogol
gogol-pagespeed/gen/Network/Google/PageSpeed/Types/Product.hs
mpl-2.0
45,491
0
23
10,542
7,915
4,509
3,406
903
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.DFAReporting.CreativeFieldValues.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) -- -- Retrieves a list of creative field values, possibly filtered. This -- method supports paging. -- -- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.creativeFieldValues.list@. module Network.Google.Resource.DFAReporting.CreativeFieldValues.List ( -- * REST Resource CreativeFieldValuesListResource -- * Creating a Request , creativeFieldValuesList , CreativeFieldValuesList -- * Request Lenses , cfvlCreativeFieldId , cfvlSearchString , cfvlIds , cfvlProFileId , cfvlSortOrder , cfvlPageToken , cfvlSortField , cfvlMaxResults ) where import Network.Google.DFAReporting.Types import Network.Google.Prelude -- | A resource alias for @dfareporting.creativeFieldValues.list@ method which the -- 'CreativeFieldValuesList' request conforms to. type CreativeFieldValuesListResource = "dfareporting" :> "v2.7" :> "userprofiles" :> Capture "profileId" (Textual Int64) :> "creativeFields" :> Capture "creativeFieldId" (Textual Int64) :> "creativeFieldValues" :> QueryParam "searchString" Text :> QueryParams "ids" (Textual Int64) :> QueryParam "sortOrder" CreativeFieldValuesListSortOrder :> QueryParam "pageToken" Text :> QueryParam "sortField" CreativeFieldValuesListSortField :> QueryParam "maxResults" (Textual Int32) :> QueryParam "alt" AltJSON :> Get '[JSON] CreativeFieldValuesListResponse -- | Retrieves a list of creative field values, possibly filtered. This -- method supports paging. -- -- /See:/ 'creativeFieldValuesList' smart constructor. data CreativeFieldValuesList = CreativeFieldValuesList' { _cfvlCreativeFieldId :: !(Textual Int64) , _cfvlSearchString :: !(Maybe Text) , _cfvlIds :: !(Maybe [Textual Int64]) , _cfvlProFileId :: !(Textual Int64) , _cfvlSortOrder :: !(Maybe CreativeFieldValuesListSortOrder) , _cfvlPageToken :: !(Maybe Text) , _cfvlSortField :: !(Maybe CreativeFieldValuesListSortField) , _cfvlMaxResults :: !(Maybe (Textual Int32)) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'CreativeFieldValuesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'cfvlCreativeFieldId' -- -- * 'cfvlSearchString' -- -- * 'cfvlIds' -- -- * 'cfvlProFileId' -- -- * 'cfvlSortOrder' -- -- * 'cfvlPageToken' -- -- * 'cfvlSortField' -- -- * 'cfvlMaxResults' creativeFieldValuesList :: Int64 -- ^ 'cfvlCreativeFieldId' -> Int64 -- ^ 'cfvlProFileId' -> CreativeFieldValuesList creativeFieldValuesList pCfvlCreativeFieldId_ pCfvlProFileId_ = CreativeFieldValuesList' { _cfvlCreativeFieldId = _Coerce # pCfvlCreativeFieldId_ , _cfvlSearchString = Nothing , _cfvlIds = Nothing , _cfvlProFileId = _Coerce # pCfvlProFileId_ , _cfvlSortOrder = Nothing , _cfvlPageToken = Nothing , _cfvlSortField = Nothing , _cfvlMaxResults = Nothing } -- | Creative field ID for this creative field value. cfvlCreativeFieldId :: Lens' CreativeFieldValuesList Int64 cfvlCreativeFieldId = lens _cfvlCreativeFieldId (\ s a -> s{_cfvlCreativeFieldId = a}) . _Coerce -- | Allows searching for creative field values by their values. Wildcards -- (e.g. *) are not allowed. cfvlSearchString :: Lens' CreativeFieldValuesList (Maybe Text) cfvlSearchString = lens _cfvlSearchString (\ s a -> s{_cfvlSearchString = a}) -- | Select only creative field values with these IDs. cfvlIds :: Lens' CreativeFieldValuesList [Int64] cfvlIds = lens _cfvlIds (\ s a -> s{_cfvlIds = a}) . _Default . _Coerce -- | User profile ID associated with this request. cfvlProFileId :: Lens' CreativeFieldValuesList Int64 cfvlProFileId = lens _cfvlProFileId (\ s a -> s{_cfvlProFileId = a}) . _Coerce -- | Order of sorted results, default is ASCENDING. cfvlSortOrder :: Lens' CreativeFieldValuesList (Maybe CreativeFieldValuesListSortOrder) cfvlSortOrder = lens _cfvlSortOrder (\ s a -> s{_cfvlSortOrder = a}) -- | Value of the nextPageToken from the previous result page. cfvlPageToken :: Lens' CreativeFieldValuesList (Maybe Text) cfvlPageToken = lens _cfvlPageToken (\ s a -> s{_cfvlPageToken = a}) -- | Field by which to sort the list. cfvlSortField :: Lens' CreativeFieldValuesList (Maybe CreativeFieldValuesListSortField) cfvlSortField = lens _cfvlSortField (\ s a -> s{_cfvlSortField = a}) -- | Maximum number of results to return. cfvlMaxResults :: Lens' CreativeFieldValuesList (Maybe Int32) cfvlMaxResults = lens _cfvlMaxResults (\ s a -> s{_cfvlMaxResults = a}) . mapping _Coerce instance GoogleRequest CreativeFieldValuesList where type Rs CreativeFieldValuesList = CreativeFieldValuesListResponse type Scopes CreativeFieldValuesList = '["https://www.googleapis.com/auth/dfatrafficking"] requestClient CreativeFieldValuesList'{..} = go _cfvlProFileId _cfvlCreativeFieldId _cfvlSearchString (_cfvlIds ^. _Default) _cfvlSortOrder _cfvlPageToken _cfvlSortField _cfvlMaxResults (Just AltJSON) dFAReportingService where go = buildClient (Proxy :: Proxy CreativeFieldValuesListResource) mempty
rueshyna/gogol
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/CreativeFieldValues/List.hs
mpl-2.0
6,676
0
21
1,690
951
546
405
141
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE ViewPatterns #-} module Xmpp where import Control.Applicative import Control.Concurrent import Control.Concurrent.STM import Control.Concurrent.Thread.Delay import qualified Control.Exception as Ex import Control.Lens import Control.Monad import Control.Monad.Except import Control.Monad.Reader import Control.Monad.Trans.Maybe import Control.Monad.Writer import qualified Crypto.Hash.SHA256 as SHA256 import DBus import DBus.Signal import DBus.Types hiding (logDebug, logError) import Data.ByteString (ByteString) import Data.Data import Data.Either import Data.Function import qualified Data.List as List import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import Data.UUID (UUID) import qualified Network.TLS as TLS import qualified Network.Xmpp as Xmpp import qualified Network.Xmpp.E2E as E2E import qualified Network.Xmpp.IM as Xmpp import Network.Xmpp.Lens hiding (view) import Persist import System.Random import Basic import Gpg import Signals import State import Types data XmppConnectionUpdate = NowConnected | ConnectionLost | ConnectionError Text | AuthenticationError deriving (Show, Eq, Typeable) instance Ex.Exception XmppConnectionUpdate tShow :: Show a => a -> Text tShow = Text.pack . show showJid :: Xmpp.Jid -> String showJid = Text.unpack . Xmpp.jidToText runHandler :: (MonadWriter [ThreadId] m, MonadIO m) => IO () -> m () runHandler m = do tid <- liftIO . forkIO $ m tell [tid] -- | TODO: implement. This function is called when the connection state changed -- (i.e. the connection has been established, was closed, could not be -- established due to error etc.) signalConnectionState :: XmppConnectionUpdate -> PSM IO () signalConnectionState _newState = return () xmppError :: MonadIO m => Text -> m a xmppError = liftIO . Ex.throwIO . ConnectionError makeE2ECallbacks :: (MonadReader PSState m, MonadIO m) => ByteString -> m E2E.E2ECallbacks makeE2ECallbacks kid = do st <- ask con <- liftIO . atomically . readTMVar =<< view psDBusConnection return E2E.E2EC { E2E.onStateChange = \p os ns -> handleStateChange st con p os ns , E2E.onSmpChallenge = \p ssid vinfo q -> do -- TODO: Select Session ID runPSM st $ addChallenge p ssid (toKeyID $ E2E.keyID vinfo) False q let q' = maybe "" id q emitSignal receivedChallengeSignal (p, q') con , E2E.onSmpAuthChange = \p s -> do runPSM st $ setChallengeCompleted p s emitSignal peerTrustStatusChangedSignal (p, s) con , E2E.cSign = signGPG kid , E2E.cVerify = \p pk sig txt -> fmap E2E.VerifyInfo <$> verifySignature st p (E2E.pubKeyData pk) sig txt } handleStateChange :: PSState -> DBusConnection -> Xmpp.Jid -> E2E.MsgState -> E2E.MsgState -> IO () handleStateChange st con j oldState newState = void . forkIO $ case (oldState, newState) of (E2E.MsgStatePlaintext, E2E.MsgStateEncrypted vi sid) -> setOnline st con j sid $ toKeyID (E2E.keyID vi) (E2E.MsgStateFinished, E2E.MsgStateEncrypted vi sid) -> setOnline st con j sid $ toKeyID (E2E.keyID vi) (E2E.MsgStateEncrypted vi sid, E2E.MsgStatePlaintext) -> setOffline st con j sid $ toKeyID (E2E.keyID vi) (E2E.MsgStateEncrypted vi sid, E2E.MsgStateFinished) -> setOffline st con j sid $ toKeyID (E2E.keyID vi) _ -> return () ourJid :: PSState -> IO (Maybe Xmpp.Jid) ourJid st = runMaybeT $ do (xmppCon, _ctx) <- (liftIO . atomically . readTVar $ view psXmppCon st) >>= \case XmppConnected c ctx _ -> return (c, ctx) _ -> do logError "Xmpp connection not established" mzero liftIO (Xmpp.getJid xmppCon) >>= \case Just w -> return w Nothing -> do logError "No local JID set" mzero setOnline :: MonadIO m => PSState -> DBusConnection -> Xmpp.Jid -> SSID -> KeyID -> m () setOnline st con p sid kid = runPSM st $ do mbWe <- liftIO $ ourJid st case mbWe of Nothing -> return () Just we -> addSession sid (Just kid) we p mbContact <- getIdentityContact kid case mbContact of Nothing -> do liftIO $ emitSignal unlinkedIdentityAvailabilitySignal (kid, p, Available) con Just c -> do liftIO $ emitSignal identityAvailabilitySignal (kid, p, contactUniqueID c, Available) con (cs, _) <- liftIO $ availableContacts st -- | Check that the contact wasn't already online (i.e. with other -- peers) case Map.lookup c cs of Just ps | Map.null (p `Map.delete` ps ) -> do liftIO $ emitSignal contactStatusChangedSignal ( contactUniqueID c , contactName c , Available) con _ -> do return () -- Was already set online setOffline :: MonadIO m => PSState -> DBusConnection -> Xmpp.Jid -> SSID -> KeyID -> m () setOffline st con p sid kid = runPSM st $ do concludeSession sid mbContact <- getIdentityContact kid case mbContact of Nothing -> liftIO $ do emitSignal unlinkedIdentityAvailabilitySignal (kid, p, Unavailable) con Just c -> do liftIO $ emitSignal identityAvailabilitySignal (kid, p, contactUniqueID c, Unavailable) con (cs, _) <- liftIO $ availableContacts st -- | Check that the contact wasn't already online (i.e. with other -- peers) case Map.lookup c cs of Just ps | not (Map.null (p `Map.delete` ps )) -> do return () -- Was already set offline or there are contacts -- remaining _ -> do liftIO $ emitSignal contactStatusChangedSignal ( contactUniqueID c , contactName c , Unavailable) con moveIdentity :: PSState -> KeyID -> Maybe UUID -> IO () moveIdentity st kid mbNewContact = runPSM st $ do con <- liftIO . atomically . readTMVar $ view psDBusConnection st mbContact <- fmap contactUniqueID <$> getIdentityContact kid unless (mbContact == mbNewContact) $ case mbNewContact of Just c -> do ps <- Map.keys <$> liftIO (sessionsByIdentity st kid) _ <- setContactIdentity c kid liftIO $ emitSignal identityContactMovedSignal (kid, c) con Nothing -> do ps <- Map.keys <$> liftIO (sessionsByIdentity st kid) _ <- removeContactIdentity kid liftIO $ emitSignal identityUnlinkedSignal kid con -- | Make a single attempt to connect to the xmpp server -- -- N.B.: Certain conditions may lead to a change of the current state. The -- change of state automatically sends an updating dbus signal and may block the -- following connection attempts tryConnect :: MonadIO m => ByteString -> PSState -> m (Xmpp.Session, E2E.E2EContext) tryConnect key st = runPSM st $ do mbCredentials <- getCredentials case mbCredentials of Just cred -> do let hostname = Text.unpack $ hostCredentialsHostname cred username = hostCredentialsUsername cred password = hostCredentialsPassword cred logDebug $ "Trying to connect to " ++ show hostname ++ " as " ++ show username mbKid <- getSigningKey kid <- case mbKid of Nothing -> xmppError "No signing key set" Just pid -> if | isJust (privIdentRevoked pid) -> xmppError "signing key is revoked" | privIdentKeyBackend pid /= "gpg" -> xmppError $ "unknown key backend: " <> privIdentKeyBackend pid | otherwise -> return $ privIdentKeyID pid cbs <- makeE2ECallbacks (fromKeyID kid) (e2ectx, e2eplugin) <- liftIO $ E2E.e2eInit (E2E.E2EG E2E.e2eDefaultParameters (E2E.PubKey "gpg" key)) policy cbs mbSess <- liftIO $ Xmpp.session hostname (Xmpp.simpleAuth username password) (def & Xmpp.tlsUseNameIndicationL .~ True & osc .~ (\_ _ _ _ -> return []) & Xmpp.pluginsL .~ [e2eplugin] & Xmpp.onPresenceChangeL .~ Just opc ) case mbSess of Left e -> do case e of (Xmpp.XmppAuthFailure _) -> do setState AuthenticationDenied liftIO $ Ex.throwIO AuthenticationError _ -> liftIO . Ex.throwIO $ ConnectionError (tShow e) Right r -> do _ <- liftIO $ Xmpp.sendPresence Xmpp.presenceOnline r setState Authenticated return (r, e2ectx) Nothing -> do setState CredentialsUnset liftIO . Ex.throwIO $ ConnectionError "Connection credentials are unset." where opc peer old new = do case (old, new) of -- peers going offline should be noticed by e2e and the appropriate -- callback called (Xmpp.PeerAvailable{}, Xmpp.PeerUnavailable) -> return () (Xmpp.PeerUnavailable, Xmpp.PeerAvailable{}) -> ake st peer _ -> return () clientHooksL = lens TLS.clientHooks (\cp ch -> cp{TLS.clientHooks = ch}) onServerCertificateL = lens TLS.onServerCertificate (\ch osc-> ch {TLS.onServerCertificate = osc}) osc = Xmpp.streamConfigurationL . Xmpp.tlsParamsL . clientHooksL . onServerCertificateL policy _peer = return $ Just True -- TODO: cross-check with DB ake :: PSState -> Xmpp.Jid -> IO () ake st them = liftM (maybe () id) . runMaybeT $ do (xmppCon, ctx) <- (liftIO . atomically . readTVar $ view psXmppCon st) >>= \case XmppConnected c ctx _ -> return (c, ctx) _ -> do logError "Xmpp connection not established" mzero we <- liftIO (Xmpp.getJid xmppCon) >>= \case Just w -> return w Nothing -> do logError "No local JID set" mzero let doStartAke = we /= them && jidHash we them <= jidHash them we liftIO $ when doStartAke (go 3 ctx) where jidHash j1 j2 = SHA256.hash $ (mappend `on` Text.encodeUtf8 . Xmpp.jidToText) j1 j2 go n ctx = do mbAke <- E2E.startE2E them ctx case mbAke of Right () -> return () Left (E2E.AKESendError e) -> do logError $ "AKE with " ++ Text.unpack (Xmpp.jidToText them) ++ " could not be established because " ++ show e return () Left (E2E.AKEIQError iqe) -> case iqe ^. errCond of Xmpp.Conflict -> unless (n <= (0 :: Integer)) $ do -- Wait for 5 to 20 seconds and try again (but at most 3 -- times) wait <- randomRIO (5, 20) delay (wait * 1000000) go (n-1) ctx -- Entity doesn't support AKE: Xmpp.ServiceUnavailable -> return () Xmpp.FeatureNotImplemented -> return () -- Something went wrong Xmpp.BadRequest -> do logError $ "AKE with " ++ showJid them ++ " failed: " ++ show (Xmpp.stanzaErrorText $ iqe ^. Xmpp.stanzaError) _ -> logError $ "AKE failed: " ++ show iqe Left (E2E.AKEError e) -> do logError $ "Error during AKE: " ++ show e return () errCond = Xmpp.stanzaError . Xmpp.stanzaErrorConditionL -- | Try to establish a connection to the server. If the connection fails -- another attempt is made after a (exponentially increasing) grace period. This -- function blocks until pre-conditions are met connector :: Integer -> PSState -> IO (Xmpp.Session, E2E.E2EContext, [ThreadId]) connector d st = do let pst = st ^. psState as = st ^. psAccountState -- The following operation will only finish when all the preconditions -- are met _simultaneously_ con <- liftIO . atomically $ do ps <- readTVar pst a <- readTVar as -- Check that we (should) have the necessary information before trying -- to connect case ps of Disabled -> return () Authenticating -> return () Authenticated -> return () _ -> retry -- Check that the account is enabled before trying to connect case a of AccountDisabled -> retry AccountEnabled -> readTMVar $ st ^. psDBusConnection mbKey <- liftIO $ exportSigningGpgKey st case mbKey of Nothing -> (runPSM st $ setState IdentityNotFound) >> connector d st Just key -> do runPSM st $ setState Authenticating mbSess <- liftIO . Ex.try $ tryConnect key st case mbSess of Left e -> do -- e :: XmppConnectionUpdate logDebug $ "Connection failed. Waiting for " ++ show d ++ " seconds" runPSM st $ signalConnectionState e liftIO $ delay (d * 1000000) -- avoid hammering the server, delay for a certain -- amount of seconds connector (nextDelay d) st Right (sess, e2eCtx) -> do sess' <- Xmpp.dupSession sess (_, threads) <- runWriterT $ do runHandler $ do pr <- Xmpp.waitForPresence ((== Xmpp.Subscribe ) . Xmpp.presenceType ) sess' runPSM st $ handleSubscriptionRequest sess' con pr return (sess, e2eCtx, threads) where -- Exponential back-off, we double the retry delay each time up to a total -- of 5 minutes and ensure that it's not below 5 seconds nextDelay d = max 5 (min (2*d) (5*60)) -- | Handle a subscription request. -- -- Checks the roster for a matching entry, if it exists and we are subscribed to -- it or a subscription is pending, it automatically approves the -- request. Otherwise emits a SubscriptionRequestSignal handleSubscriptionRequest :: MonadIO m => Xmpp.Session -> DBusConnection -> Xmpp.Presence -> PSM m () handleSubscriptionRequest sess con st | Just fr <- Xmpp.presenceFrom st = do roster <- liftIO $ Xmpp.getRoster sess -- Automatically approve the request if we have a (pending) -- subscription to it let autoApprove = case roster ^. itemsL . at fr of Nothing -> False Just item -> or [ item ^. riSubscriptionL `elem` [Xmpp.To, Xmpp.Both] , item ^. riAskL ] case autoApprove of True -> do res <- liftIO $ Xmpp.sendPresence (Xmpp.presenceSubscribed fr) sess case res of Left error -> logError $ "Failed to accept subscription request from " ++ show fr ++ "; error = " ++ show error Right _ -> return () False -> do addSubscriptionRequest fr liftIO $ emitSignal subscriptionRequestSignal fr con | otherwise = logError "Presence subscription without from field" enableXmpp :: (MonadReader PSState m, MonadIO m, Functor m) => m () enableXmpp = do st <- ask xc <- view psXmppCon c <- liftIO . atomically $ readTVar xc case c of XmppConnecting _ -> return () XmppConnected{} -> return () XmppNoConnection -> void . liftIO . forkIO $ do tid <- myThreadId -- | To avoid a race condition where multiple connection threads are -- started we try to write our own ThreadId into the ref. If the ref -- already contains something else we lost the race and abort run <- atomically $ do x <- readTVar xc case x of XmppNoConnection -> do writeTVar xc (XmppConnecting tid) return True _ -> return False case run of False -> return () True -> do runPSM st . (st ^. psCallbacks . onStateChange) $ XmppConnecting tid (sess, e2eCtx, threads) <- connector 0 st let state2 = XmppConnected sess e2eCtx threads runPSM st . (st ^. psCallbacks . onStateChange) $ state2 atomically . writeTVar xc $ state2 enableAccount :: (Functor m, MonadIO m) => PSM (MethodHandlerT m) () enableAccount = do as <- view psAccountState liftIO . atomically $ writeTVar as AccountEnabled enableXmpp disconnect :: Xmpp.Session -> IO () disconnect con = do _ <- Xmpp.sendPresence Xmpp.presenceOffline con Xmpp.endSession con disableAccount :: (MonadReader PSState m, MonadIO m) => m () disableAccount = do as <- view psAccountState xmppRef <- view psXmppCon mbXmppSess <- liftIO . atomically $ do writeTVar as AccountDisabled readTVar xmppRef case mbXmppSess of XmppConnecting tid -> liftIO $ killThread tid XmppConnected con _ threads -> do liftIO $ disconnect con liftIO . forM_ threads $ killThread XmppNoConnection -> return () liftIO . atomically $ writeTVar xmppRef XmppNoConnection st <- ask liftIO $ runPSM st updateState getSession :: (Monad m, MonadIO m, MonadMethodError m) => PSM m Xmpp.Session getSession = do xc <- view psXmppCon c <- liftIO $ readTVarIO xc case c of XmppConnected sess _ _ -> return sess _ -> lift $ throwMethodError $ MsgError "org.pontarius.Error.Xmpp" (Just $ "Not connected") [] checkSession :: (MonadIO m, MonadReader PSState m) => m (Maybe Xmpp.Session) checkSession = do xc <- view psXmppCon c <- liftIO $ readTVarIO xc case c of XmppConnected sess _ _ -> return $ Just sess _ -> return Nothing connected :: (MonadIO m, MonadReader PSState m) => m Bool connected = do s <- checkSession return $ isJust s getE2EContext :: PSM (MethodHandlerT IO) E2E.E2EContext getE2EContext = do xc <- view psXmppCon c <- liftIO $ readTVarIO xc case c of XmppConnected _ ctx _ -> return ctx _ -> lift $ methodError $ MsgError "org.pontarius.Error.Xmpp" (Just $ "Not connected") [] getE2EContextSTM :: PSState -> STM E2E.E2EContext getE2EContextSTM st = do c <- readTVar (view psXmppCon st) case c of XmppConnected _ ctx _ -> return ctx _ -> retry getSessionSTM :: PSState -> STM Xmpp.Session getSessionSTM st = do c <- readTVar (st ^. psXmppCon) case c of XmppConnected sess _ _ -> return sess _ -> retry getXmppRoster :: PSM (MethodHandlerT IO) (Map Xmpp.Jid Xmpp.Item) getXmppRoster = do sess <- getSession Xmpp.items <$> liftIO (Xmpp.getRoster sess) getPeersSTM :: PSState -> STM [(Xmpp.Jid, Bool)] getPeersSTM st = do sess <- getSessionSTM st peers <- map Xmpp.riJid . filter ((== Xmpp.Both) . Xmpp.riSubscription) . Map.elems . Xmpp.items <$> Xmpp.getRosterSTM sess forM peers $ \peer -> do av <- Xmpp.isPeerAvailable peer sess return (peer, av) <|> return [] subscribe :: Xmpp.Jid -> PSM (MethodHandlerT IO) (Either Xmpp.XmppFailure ()) subscribe peer = do sess <- getSession liftIO $ Xmpp.sendPresence (Xmpp.presenceSubscribe peer) sess acceptSubscription :: (MonadIO m, MonadMethodError m) => Xmpp.Jid -> PSM m () acceptSubscription peer = do sess <- getSession res <- liftIO $ Xmpp.sendPresence (Xmpp.presenceSubscribed peer) sess case res of Right () -> removeSubscriptionRequest peer Left e -> xmppError $ "Could not accept subscription: " <> showText e where showText = Text.pack . show addPeer :: (MonadIO m, MonadMethodError m) => Xmpp.Jid -> PSM m (Maybe ()) addPeer peer = do -- TODO: be more precise here. We have to check that the server supports -- pre-approval mbSess <- checkSession case mbSess of Nothing -> return Nothing Just sess -> Just <$> do _ <- liftIO $ Xmpp.sendPresence (Xmpp.presenceSubscribe peer) sess features <- liftIO $ Xmpp.getFeatures sess case Xmpp.streamFeaturesPreApproval features of True -> do _ <- acceptSubscription peer return () False -> do srs <- getSubscriptionRequests case peer `Set.member` srs of False -> return () True -> acceptSubscription peer removeSubscriptionRequest peer removePeer :: (MonadIO m, MonadMethodError m) => Xmpp.Jid -> PSM m () removePeer peer = do sess <- getSession e1 <- liftIO $ Xmpp.sendPresence (Xmpp.presenceUnsubscribed peer) sess case e1 of Left e -> lift . throwMethodError $ MsgError { errorName = "org.pontarius.Error.Xmpp.RemovePeer" , errorText = Just . Text.pack . show $ e , errorBody = [] } Right _ -> return () e2 <- liftIO $ Xmpp.sendPresence (Xmpp.presenceUnsubscribe peer) sess case e2 of Left e -> lift . throwMethodError $ MsgError { errorName = "org.pontarius.Error.Xmpp.RemovePeer" , errorText = Just . Text.pack . show $ e , errorBody = [] } Right _ -> return () return () getAvailableXmppPeers :: PSM (MethodHandlerT IO) [Xmpp.Jid] getAvailableXmppPeers = do sess <- getSession liftIO . atomically $ do ps <- Xmpp.getAvailablePeers sess fmap concat . forM ps $ \p -> Map.keys <$> Xmpp.getPeerEntities p sess getAvailableXmppPeersSTM :: PSState -> STM [Xmpp.Jid] getAvailableXmppPeersSTM st = do sess <- getSessionSTM st Xmpp.getAvailablePeers sess startAKE :: Xmpp.Jid -> PSM (MethodHandlerT IO) (Either E2E.AKEError ()) startAKE peer = do e2eCtx <- getE2EContext liftIO $ E2E.startE2E peer e2eCtx verifyChannel :: Xmpp.Jid -> Text -> Text -> PSM (MethodHandlerT IO) () verifyChannel peer question secret = do ctx <- getE2EContext let mbQuestion = if Text.null question then Nothing else Just question res <- liftIO $ E2E.startSmp peer mbQuestion secret ctx case res of Left e -> lift . methodError $ MsgError "pontarius.Xmpp.SMP" (Just $ tShow e) [] Right (ssid, vinfo) -> addChallenge peer ssid (toKeyID $ E2E.keyID vinfo) True mbQuestion respondChallenge :: Xmpp.Jid -> Text -> PSM (MethodHandlerT IO) () respondChallenge peer secret = do ctx <- getE2EContext res <- E2E.answerChallenge peer secret ctx case res of Left e -> lift . methodError $ MsgError "pontarius.Xmpp.SMP" (Just $ tShow e) [] Right r -> return r getSessions :: PSState -> IO (Map Xmpp.Jid E2E.SessionState) getSessions st = atomically $ do c <- readTVar (view psXmppCon st) case c of XmppConnected _ ctx _ -> E2E.getSessions ctx _ -> return Map.empty sessionsByIdentity :: PSState -> KeyID -> IO (Map Xmpp.Jid E2E.SessionState) sessionsByIdentity st kid = do sess <- getSessions st return $ Map.filter hasKid sess where hasKid E2E.Authenticated{E2E.sessionVerifyInfo = vinfo} = toKeyID (E2E.keyID vinfo) == kid hasKid _ = False getContactIdentities :: UUID -> PSM IO (Map KeyID (Set Xmpp.Jid)) getContactIdentities c = do ids <- getContactIds c st <- ask ids' <- forM ids $ \id -> (\ss -> (id, Map.keysSet ss)) <$> liftIO (sessionsByIdentity st id) return $ Map.fromList ids' sessionsByJid :: PSState -> Xmpp.Jid -> IO (Map Xmpp.Jid KeyID) sessionsByJid st p = do sess <- getSessions st return $ Map.mapMaybeWithKey (\k v -> case (Xmpp.toBare k == p, v) of (True, E2E.Authenticated{E2E.sessionVerifyInfo = vinfo}) -> Just $ toKeyID (E2E.keyID vinfo) _ -> Nothing) sess getContactPeers :: UUID -> PSM IO (Map Xmpp.Jid (Map Xmpp.Jid KeyID)) getContactPeers c = do ids <- Persist.getContactPeers c st <- ask ids' <- forM ids $ \id -> (\ss -> (id, ss)) <$> liftIO (sessionsByJid st id) return $ Map.fromList ids' availableContacts :: PSState -> IO ( Map Contact (Map Xmpp.Jid KeyID) , Map Xmpp.Jid KeyID) availableContacts st = do logDebug "getting session" sessions <- getSessions st logDebug "got session" -- "online" (i.e. authenticated) peers let ops = mapMaybe isAuthenticated $ Map.toList sessions (cs, noCs) <- fmap (partitionEithers . catMaybes) . forM ops $ \(p, pkId) -> do logDebug $ show p mbC <- runPSM st $ getIdentityContact (toKeyID pkId) case mbC of Nothing -> do pi <- runPSM st $ peerIgnored p case pi of True -> return Nothing False -> return . Just $ Right (p, toKeyID pkId) Just c -> return . Just . Left $ Map.singleton c (Map.singleton p $ toKeyID pkId) return (List.foldl' (Map.unionWith Map.union) Map.empty cs, Map.fromList noCs) where isAuthenticated (p, E2E.Authenticated{E2E.sessionVerifyInfo = vi}) = Just (p, E2E.keyID vi) isAuthenticated _ = Nothing getContactsM :: PSM IO [(Contact, Bool)] getContactsM = do cs <- getContacts forM cs $ \c -> do ps <- Xmpp.getContactPeers (contactUniqueID c) return (c, mapAll Map.null ps) where mapAll p m = Map.null $ Map.filter p m
pontarius/pontarius-service
source/Xmpp.hs
agpl-3.0
29,070
0
30
10,872
7,751
3,781
3,970
-1
-1
module Evaluate where {- const 1 undefined = \a -> \b -> a \1 -> \_ -> 1 1 const undefined 1 = \a -> \b -> a \undefined -> \_ -> undefined undefined flip const undefined 1 = (\a -> \b -> c) -> \b -> \a -> c let b = undefined, a = 1 in (\a -> \_ -> a) \1 -> \_ -> 1 1 flip const 1 undefined = (\a -> \b -> c) -> \b -> \a -> c let b = 1, a = undefined in (\a -> \_ -> a) \undefined -> \_ -> undefined undefined const undefined undefined = \a -> \b -> a \undefined -> \undefined -> undefined undefined foldr const 'z' ['a'..'e'] = (a -> b -> b) -> b -> t a -> b (\a -> \_ -> a) -> \'z' -> ['a'..'e'] -> b let b = 'z', a = ['a'..'e'] in (\a -> \_ -> a) let b = 'z', a = 'a' in (\'a' -> \_ -> 'a' 'a' foldr (flip const) 'z' ['a'..'e'] = (a -> b -> b) -> b -> t a -> b (let b = 'z', a = ['a'..'e'] in (\b -> \a -> \b) -> \b -> \a -> b) 'z' -}
thewoolleyman/haskellbook
27/04/maor/Evaluate.hs
unlicense
1,000
0
2
376
5
4
1
1
0
module Main where import Test.HUnit import Test.Framework import Test.Framework.Providers.HUnit import Solutions.Problem001 as P1 tests = TestList [ TestCase (assertEqual "Test 1a" 23 (P1.solution 10)), TestCase (assertEqual "Test 1b" 233168 (P1.solution 1000)) ] main = defaultMain $ hUnitTestToTests tests
jhnesk/project-euler
test/UnitTests.hs
unlicense
324
0
12
54
96
53
43
9
1
module Terminology.CommonAbbrev (quizByAbbrev, quizByMeaning) where import Colors terms = [("ADD","attention deficit disorder") ,("ADR","adverse drug reaction") ,("AIDS","acquired immunodeficiency syndrome") ,("AV","atrial-ventricular") ,("AMI","acute myocardial infarction") ,("ANS","autonomic nervous system") ,("ASAP","as soon as possible") ,("BM","bowel movement") ,("BP","blood pressure") ,("BPH","benign prostatic hyperplasia") ,("BS","blood sugar") ,("BSA","body surface area") ,("CA","cancer") ,("CAD","coronary artery disease") ,("CF","cardiac failure") ,("CHF","congestive heart failure") ,("CMV","cytomegalovirus") ,("CNS","central nervous system") ,("COPD","chronic obstructive pulmonary disease") ,("CVA","cerebrovascular accident (stroke)") ,("DAW","dispense as written") ,("D/C","discontinue") ,("DM","diabetes melitus") ,("DOB","date of birth") ,("DUR","drug utilization review") ,("Dx","diagnosis") ,("EC","enteric coated") ,("ECG, EKG","electrocardiogram") ,("ENT","ears, nose, throat") ,("ER","emergency room") ,("FH","family history") ,("GERD","gastroesophageal reflux disease") ,("GI","gastrointestinal") ,("Gtt","drop") ,("HA","headache") ,("HBP","high blood pressure") ,("HDL","high density lipoprotein") ,("HIV","human immunodeficiency virus") ,("HR","heart rate") ,("IO, I/O","fluid intake and output") ,("IOP","intraocular pressure") ,("IV","intravenous") ,("KVO","keep veins open") ,("LBW","low birth weight") ,("LDL","low density lipoprotein") ,("LOC","loss of consciousness") ,("MI","myocardial infarction") ,("MICU","medical intensive care unit") ,("MRI","magnetic resonance imaging") ,("NKA","no known allergies") ,("NPO","nothing by mouth") ,("NS","normal saline") ,("NVD","nausea, vomiting, diarrhea") ,("OR","operating room") ,("PMH","past medical history") ,("PUD","peptic ulcer disease") ,("PVD","peripheral vascular disease") ,("RA","rheumatoid arthritis") ,("RBC","red blood count or red blood cell") ,("SBP","systolic blood pressure") ,("SOB","shortness of breath") ,("STD","sexually transmitted disease") ,("T","temperature") ,("T&C","type and cross-match (blood)") ,("TB","tuberculosis") ,("TEDS","thrombo-embolic disease stockings") ,("TPN","total parenteral nutrition") ,("Tx","treatment") ,("U","units") ,("U/A","urinalysis") ,("UCHD","usual childhood disease") ,("URD","upper respiratory disease") ,("UTI","urinary tract infection") ,("VD","veneral disease") ,("VS","vital signs") ,("WBC","white blood count or white blood cell") ,("WT","weight") ] quizByAbbrev = [("What is the abbreviation for " ++ white q ++ "?", a) | (a, q) <- terms] quizByMeaning = [("What is the meaning for " ++ white q ++ "?", a) | (q, a) <- terms]
kohabi/rxquiz
src/Terminology/CommonAbbrev.hs
unlicense
3,289
0
9
865
793
520
273
81
1
module Language.Drasil.Format where -- | Possible formats for output data Format = TeX | Plain | HTML
JacquesCarette/literate-scientific-software
code/drasil-printers/Language/Drasil/Format.hs
bsd-2-clause
104
0
5
19
21
14
7
2
0
module Text.Tokenize.Util.String ( unHyphen ) where unHyphen :: String -> String unHyphen ('‑':'\n':xs) = unHyphen xs unHyphen (x:xs) = x : unHyphen xs unHyphen [] = []
kawu/tokenize
Text/Tokenize/Util/String.hs
bsd-2-clause
172
0
8
28
78
42
36
6
1
-- Collztz sequences chain :: (Integral a) => a -> [a] chain 1 = [1] chain n | even n = n:chain (n `div` 2) | odd n = n:chain (n * 3 + 1) numLongChains :: Int numLongChains = length (filter (\xs -> length xs > 15) (map chain [1..100])) addThree :: (Num a) => a -> a -> a -> a addThree = \x -> \y -> \z -> x + y + z flip' :: (a -> b -> c) -> b -> a -> c flip' f = \x y -> f y x
sharkspeed/dororis
languages/haskell/LYHGG/6-higher-order-functions/2-lambda.hs
bsd-2-clause
388
0
11
109
248
130
118
11
1
{-# LANGUAGE PackageImports #-} -- {-# LANGUAGE PackageImports, FlexibleContexts, FlexibleInstances, UndecidableInstances, RankNTypes #-} -- , OverlappingInstances {- | Radix sort of lists, based on binary representation of * floats * Int<N> * Word<N> The lsd prefix is for Least significant digit radix sort, while msd is for the parallelized Most significant digit one. Here we partition numbers by sign and sort both lists in parallel (you should link with -threaded) The digit size is set to 8 bits. Digit value queues ('Seq' a) are appended as difference lists ('DList' from package dlist, O(1) on append) Instances of RadixRep for 'Int' and 'Word' are not supported. The instance for 'Int' (machine word size) is not portable because it may have reserved bits for compiler use. The type Word may be restricted to the same number of bits as Int. Check The word size story at <http://www.haskell.org/ghc/docs/7.2.2/html/libraries/ghc-prim-0.2.0.0/GHC-Prim.html#g:1> A quickcheck test-suite has been added. -} -- @author: Gabriel Riba Faura -- Internally uses (.$) = flip ($) module Data.List.RadixSort.Base ( msdSort, lsdSort, msdSortBy, lsdSortBy, RadixRep(..) ) where import Data.List.RadixSort.Internal.Types import Data.List.RadixSort.Internal.MSD (msdRadixSort) import Data.List.RadixSort.Internal.LSD (lsdRadixSort) import Data.List.RadixSort.Internal.Counters (countAndPartBySign) import Data.List.RadixSort.Internal.RadixRep (getSortInfo) import qualified Data.List as L -- import "dlist" Data.DList (DList) import qualified "dlist" Data.DList as D import "parallel" Control.Parallel.Strategies (using, rpar, rseq) import GHC.ST (runST) -- | A first pass to build digit counters is used to split lists by sign, then they are sorted in parallel. -- -- Each split group is sparked to compute in parallel -- -- Worst case O((k+1) n + length negatives (append)) where k= #digits. msdSort :: (RadixRep a) => [a] -> [a] msdSort = msdSortBy id msdSortBy :: (RadixRep b) => (a -> b) -> [a] -> [a] msdSortBy _indexMap [] = [] msdSortBy _indexMap [x] = [x] msdSortBy indexMap list@(x:_) = case repType rep of RT_Float -> msdSortFloats sortInfo indexMap list RT_IntN -> msdSortInts sortInfo indexMap list RT_WordN -> msdSortNats sortInfo indexMap list where sortInfo = getSortInfo ST_MSD rep rep = indexMap x -- | A first pass to build digit counters is used to split lists by sign, then they are sorted in parallel -- -- Worst case O((k+1) n + length negatives (append)) where k= #digits. lsdSort :: (RadixRep a) => [a] -> [a] lsdSort = lsdSortBy id lsdSortBy :: (RadixRep b) => (a -> b) -> [a] -> [a] lsdSortBy _indexMap [] = [] lsdSortBy _indexMap [x] = [x] lsdSortBy indexMap list@(x:_) = case repType rep of RT_Float -> lsdSortFloats sortInfo indexMap list RT_IntN -> lsdSortInts sortInfo indexMap list RT_WordN -> lsdSortNats sortInfo indexMap list where sortInfo = getSortInfo ST_LSD rep rep = indexMap x ---------------------------------- msdSortFloats :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] msdSortFloats sortInfo indexMap list = (sortedPoss `using` rpar) `prependReversing` (sortedNegs `using` rseq) where (poss, digitsConstPos, negs, digitsConstNeg) = runST $ countAndPartBySign indexMap sortInfo list sortedPoss = D.toList $ msdRadixSort indexMap sortInfo digitsConstPos poss sortedNegs = D.toList $ msdRadixSort indexMap sortInfo {siIsOrderReverse = True} digitsConstNeg negs prependReversing :: [a] -> [a] -> [a] prependReversing = L.foldl' (flip (:)) {-# INLINABLE prependReversing #-} lsdSortFloats :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] lsdSortFloats sortInfo indexMap list = (sortedPoss `using` rpar) `prependReversing` (sortedNegs `using` rseq) where (poss, digitsConstPos, negs, digitsConstNeg) = runST $ countAndPartBySign indexMap sortInfo list sortedPoss = D.toList $ lsdRadixSort indexMap sortInfo digitsConstPos poss sortedNegs = D.toList $ msdRadixSort indexMap sortInfo {siIsOrderReverse = True} digitsConstNeg negs ---------------------------------- msdSortInts :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] msdSortInts sortInfo indexMap list = D.toList $ D.concat [(sortedNegs `using` rpar), (sortedPoss `using` rseq)] where (poss, digitsConstPos, negs, digitsConstNeg) = runST $ countAndPartBySign indexMap sortInfo list sortedPoss = msdRadixSort indexMap sortInfo digitsConstPos poss sortedNegs = msdRadixSort indexMap sortInfo digitsConstNeg negs lsdSortInts :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] lsdSortInts sortInfo indexMap list = D.toList $ D.concat [(sortedNegs `using` rpar), (sortedPoss `using` rseq)] where (poss, digitsConstPos, negs, digitsConstNeg) = runST $ countAndPartBySign indexMap sortInfo list sortedPoss = lsdRadixSort indexMap sortInfo digitsConstPos poss sortedNegs = lsdRadixSort indexMap sortInfo digitsConstNeg negs ---------------------------------- msdSortNats :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] msdSortNats sortInfo indexMap list = D.toList $ msdRadixSort indexMap sortInfo digitsConstPos poss where (poss, digitsConstPos, _, _) = runST $ countAndPartBySign indexMap sortInfo list lsdSortNats :: (RadixRep b) => SortInfo -> (a -> b) -> [a] -> [a] lsdSortNats sortInfo indexMap list = D.toList $ lsdRadixSort indexMap sortInfo digitsConstPos poss where (poss, digitsConstPos, _, _) = runST $ countAndPartBySign indexMap sortInfo list
griba2001/haskell-binaryrep-radix-sort
Data/List/RadixSort/Base.hs
bsd-2-clause
5,805
0
10
1,194
1,350
762
588
66
3
module Database.SqlServer.Create.PartitionFunction ( PartitionFunction ) where import Prelude hiding (Left, Right) import Database.SqlServer.Create.Identifier hiding (unwrap) import Database.SqlServer.Create.DataType import Database.SqlServer.Create.Value import Database.SqlServer.Create.Entity import Data.List (nub) import Text.PrettyPrint hiding (render) import Test.QuickCheck import Data.Maybe (fromJust) {- All data types are valid for use as partitioning columns, except text, ntext, image, xml, timestamp, varchar(max), nvarchar(max), varbinary(max), alias data types, or CLR user-defined data types. -} newtype InputParameterType = InputParameterType { unwrap :: Type } instance Arbitrary InputParameterType where arbitrary = do x <- arbitrary `suchThat` isSupportedTypeForPartitionFunction return (InputParameterType x) data Range = Left | Right instance Arbitrary Range where arbitrary = elements [Left, Right] renderRange :: Range -> Doc renderRange Left = text "LEFT" renderRange Right = text "RIGHT" -- TODO boundaryValues need to all be the same type.... data PartitionFunction = PartitionFunction { partitionFunctionName :: RegularIdentifier , inputType :: InputParameterType , range :: Range , boundaryValues :: [SQLValue] } renderValues :: [SQLValue] -> Doc renderValues xs = parens (vcat (punctuate comma $ map renderValue xs)) instance Arbitrary PartitionFunction where arbitrary = do n <- arbitrary t <- arbitrary r <- arbitrary let b = fromJust $ value (unwrap t) -- otherwise an error in my code bv <- listOf b return $ PartitionFunction n t r (nub bv) instance Entity PartitionFunction where name = partitionFunctionName render a = text "CREATE PARTITION FUNCTION" <+> renderName a <+> parens (renderDataType (unwrap $ inputType a)) $+$ text "AS RANGE" <+> renderRange (range a) <+> text "FOR VALUES" <+> renderValues (boundaryValues a) $+$ text "GO\n" instance Show PartitionFunction where show = show . render
fffej/sql-server-gen
src/Database/SqlServer/Create/PartitionFunction.hs
bsd-2-clause
2,086
0
17
407
498
268
230
47
1
module Main where import Prelude hiding (lookup) import Control.Concurrent import Control.DeepSeq import Control.Monad import Data.Binary.Put import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import Data.IORef import System.Mem import Data.Disk.Swapper import Data.Disk.Swapper.Cache import Data.Disk.Swapper.Snapshot instance NFData BS.ByteString where rnf x = x `seq` () main :: IO () main = do x <- newIORef =<< mkSwapper "data" [] setCacheRef x =<< mkClockCache 5 forM_ [1..7] $ \_ -> do d <- BS.readFile "in" x' <- readIORef x writeIORef x $! adding (:) d x' performGC forM_ [3..4] $ \i -> do BS.writeFile "out" . getting (!!i) =<< readIORef x performGC forM_ [8..10] $ \_ -> do d <- BS.readFile "in" x' <- readIORef x writeIORef x $! adding (:) d x' performGC forM_ [2..6] $ \i -> do x' <- return . getting (!!i) =<< readIORef x BS.writeFile "out" x' performGC forM_ [2..6] $ \_ -> do modifyIORef x $ changing tail performGC forM_ [8..10] $ \_ -> do d <- BS.readFile "in" x' <- readIORef x writeIORef x $! adding (:) d x' performGC BSL.writeFile "snapshot0" . runPut =<< putToSnapshot =<< readIORef x forM_ [1..7] $ \_ -> do d <- BS.readFile "in" x' <- readIORef x writeIORef x $! adding (:) d x' performGC wait1 <- newEmptyMVar wait2 <- newEmptyMVar forkIO $ do BSL.writeFile "snapshot1" . runPut =<< putToSnapshot =<< readIORef x putMVar wait1 () forkIO $ do BSL.writeFile "snapshot2" . runPut =<< putToSnapshot =<< readIORef x putMVar wait2 () takeMVar wait1 takeMVar wait2 print . BS.length . getting last =<< readIORef x
roman-smrz/swapper
test/test.hs
bsd-2-clause
2,151
0
15
841
704
336
368
61
1
{-# LANGUAGE NoImplicitPrelude #-} module Bamboo.Plugin.Photo.View where import Bamboo.Plugin.Photo.Model import MPSUTF8 import Prelude hiding ((.), (>), (^), (/), id, div) import Text.XHtml.Strict hiding (select, sub, meta) id :: String -> HtmlAttr id = identifier div_id :: String -> Html -> Html div_id s = thediv ! [id s] div_class :: String -> Html -> Html div_class s = thediv ! [theclass s] div_class_id :: String -> String -> Html -> Html div_class_id x y = thediv ! [theclass x, id y] span :: Html -> Html div :: Html -> Html d :: Html -> Html ul :: Html -> Html span = thespan div = thediv d = div ul = ulist klass :: String -> HtmlAttr klass = theclass c :: String -> Html -> Html c x = d ! [klass x] -- i x = d ! [id x] ic, ci:: String -> String -> Html -> Html ic x y = d ! [id x, klass y] ci x y = ic y x link :: String -> Html -> HotLink link = hotlink img :: Html space_html :: Html img = image space_html = primHtml "&#160;" render :: Album -> Html render = show_album empty_html :: Html empty_html = toHtml "" show_album :: Album -> Html show_album x = case x.album_type of Fade -> show_fade x Galleria -> show_galleria x SlideViewer -> show_slide_viewer x Popeye -> show_popeye x show_popeye :: Album -> Html show_popeye x = c "popeye" << ul << x.data_list.map picture_li where picture_li (l, t, i) = li << link l << img ! [src i, alt t] show_slide_viewer :: Album -> Html show_slide_viewer x = ul ! [id "slide-viewer", klass "svw"] << x.data_list.map picture_li where picture_li (_, t, i) = li << img ! [src i, alt t] show_galleria :: Album -> Html show_galleria x = ul ! [klass "gallery"] << x.data_list.map picture_li where picture_li (_, t, i) = li << img ! [src i, alt t] show_fade :: Album -> Html show_fade x = ul ! [klass "fade-album"] << x.data_list.map picture_li where picture_li (l, t, i) = li << [ toHtml $ link l << img ! [src i, alt t] , if x.show_description then p << t else empty_html ]
nfjinjing/bamboo-plugin-photo
src/Bamboo/Plugin/Photo/View.hs
bsd-3-clause
2,106
0
12
553
826
447
379
-1
-1
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- This module corresponds to a part of section 3.6.1 (Pixel Storage Modes) of -- the OpenGL 1.5 specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.PixelRectangles.Convolution ( ConvolutionTarget(..), convolution, convolutionFilter1D, getConvolutionFilter1D, convolutionFilter2D, getConvolutionFilter2D, separableFilter2D, getSeparableFilter2D, copyConvolutionFilter1D, copyConvolutionFilter2D, convolutionWidth, convolutionHeight, maxConvolutionWidth, maxConvolutionHeight, ConvolutionBorderMode(..), convolutionBorderMode, convolutionFilterScale, convolutionFilterBias, ) where import Foreign.Marshal.Alloc ( alloca ) import Foreign.Marshal.Utils ( with ) import Foreign.Ptr ( Ptr, nullPtr ) import Foreign.Storable ( Storable(..) ) import Graphics.Rendering.OpenGL.GL.Capability ( EnableCap(CapConvolution1D, CapConvolution2D,CapSeparable2D), makeCapability ) import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum, GLint, GLsizei, GLfloat, Capability ) import Graphics.Rendering.OpenGL.GL.CoordTrans ( Position(..), Size(..) ) import Graphics.Rendering.OpenGL.GL.Extensions ( FunPtr, unsafePerformIO, Invoker, getProcAddress ) import Graphics.Rendering.OpenGL.GL.PeekPoke ( peek1 ) import Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable ( PixelInternalFormat ) import Graphics.Rendering.OpenGL.GL.PixelRectangles.Rasterization ( PixelData(..) ) import Graphics.Rendering.OpenGL.GL.PixelData ( withPixelData ) import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat ( marshalPixelInternalFormat' ) import Graphics.Rendering.OpenGL.GL.StateVar ( GettableStateVar, makeGettableStateVar, StateVar, makeStateVar ) import Graphics.Rendering.OpenGL.GL.VertexSpec ( Color4(..) ) import Graphics.Rendering.OpenGL.GLU.ErrorsInternal ( recordInvalidValue ) -------------------------------------------------------------------------------- #include "HsOpenGLExt.h" -------------------------------------------------------------------------------- data ConvolutionTarget = Convolution1D | Convolution2D | Separable2D deriving ( Eq, Ord, Show ) marshalConvolutionTarget :: ConvolutionTarget -> GLenum marshalConvolutionTarget x = case x of Convolution1D -> 0x8010 Convolution2D -> 0x8011 Separable2D -> 0x8012 convolutionTargetToEnableCap :: ConvolutionTarget -> EnableCap convolutionTargetToEnableCap x = case x of Convolution1D -> CapConvolution1D Convolution2D -> CapConvolution2D Separable2D -> CapSeparable2D -------------------------------------------------------------------------------- convolution :: ConvolutionTarget -> StateVar Capability convolution = makeCapability . convolutionTargetToEnableCap -------------------------------------------------------------------------------- convolutionFilter1D :: PixelInternalFormat -> GLsizei -> PixelData a -> IO () convolutionFilter1D int w pd = withPixelData pd $ glConvolutionFilter1D (marshalConvolutionTarget Convolution1D) (marshalPixelInternalFormat' int) w EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionFilter1D,GLenum -> GLenum -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) -------------------------------------------------------------------------------- getConvolutionFilter1D :: PixelData a -> IO () getConvolutionFilter1D = getConvolutionFilter Convolution1D getConvolutionFilter :: ConvolutionTarget -> PixelData a -> IO () getConvolutionFilter t pd = withPixelData pd $ glGetConvolutionFilter (marshalConvolutionTarget t) EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionFilter,GLenum -> GLenum -> GLenum -> Ptr a -> IO ()) -------------------------------------------------------------------------------- convolutionFilter2D :: PixelInternalFormat -> Size -> PixelData a -> IO () convolutionFilter2D int (Size w h) pd = withPixelData pd $ glConvolutionFilter2D (marshalConvolutionTarget Convolution2D) (marshalPixelInternalFormat' int) w h EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionFilter2D,GLenum -> GLenum -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> IO ()) -------------------------------------------------------------------------------- getConvolutionFilter2D :: PixelData a -> IO () getConvolutionFilter2D = getConvolutionFilter Convolution2D -------------------------------------------------------------------------------- separableFilter2D :: PixelInternalFormat -> Size -> PixelData a -> PixelData a -> IO () separableFilter2D int (Size w h) pdRow pdCol = withPixelData pdRow $ \f1 d1 p1 -> withPixelData pdCol $ \f2 d2 p2 -> if f1 == f2 && d1 == d2 then glSeparableFilter2D (marshalConvolutionTarget Separable2D) (marshalPixelInternalFormat' int) w h f1 d1 p1 p2 else recordInvalidValue EXTENSION_ENTRY("GL_ARB_imaging",glSeparableFilter2D,GLenum -> GLenum -> GLsizei -> GLsizei -> GLenum -> GLenum -> Ptr a -> Ptr a -> IO ()) -------------------------------------------------------------------------------- getSeparableFilter2D :: PixelData a -> PixelData a -> IO () getSeparableFilter2D pdRow pdCol = withPixelData pdRow $ \f1 d1 p1 -> withPixelData pdCol $ \f2 d2 p2 -> if f1 == f2 && d1 == d2 then glGetSeparableFilter (marshalConvolutionTarget Separable2D) f1 d1 p1 p2 nullPtr else recordInvalidValue EXTENSION_ENTRY("GL_ARB_imaging",glGetSeparableFilter,GLenum -> GLenum -> GLenum -> Ptr a -> Ptr a -> Ptr a -> IO ()) -------------------------------------------------------------------------------- copyConvolutionFilter1D :: PixelInternalFormat -> Position -> GLsizei -> IO () copyConvolutionFilter1D int (Position x y) = glCopyConvolutionFilter1D (marshalConvolutionTarget Convolution1D) (marshalPixelInternalFormat' int) x y EXTENSION_ENTRY("GL_ARB_imaging",glCopyConvolutionFilter1D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> IO ()) -------------------------------------------------------------------------------- copyConvolutionFilter2D :: PixelInternalFormat -> Position -> Size -> IO () copyConvolutionFilter2D int (Position x y) (Size w h) = glCopyConvolutionFilter2D (marshalConvolutionTarget Convolution2D) (marshalPixelInternalFormat' int) x y w h EXTENSION_ENTRY("GL_ARB_imaging",glCopyConvolutionFilter2D,GLenum -> GLenum -> GLint -> GLint -> GLsizei -> GLsizei -> IO ()) -------------------------------------------------------------------------------- data ConvolutionParameter = ConvolutionBorderColor | ConvolutionBorderMode | ConvolutionFilterScale | ConvolutionFilterBias | ConvolutionFormat | ConvolutionWidth | ConvolutionHeight | MaxConvolutionWidth | MaxConvolutionHeight deriving ( Eq, Ord, Show ) marshalConvolutionParameter :: ConvolutionParameter -> GLenum marshalConvolutionParameter x = case x of ConvolutionBorderColor -> 0x8154 ConvolutionBorderMode -> 0x8013 ConvolutionFilterScale -> 0x8014 ConvolutionFilterBias -> 0x8015 ConvolutionFormat -> 0x8017 ConvolutionWidth -> 0x8018 ConvolutionHeight -> 0x8019 MaxConvolutionWidth -> 0x801a MaxConvolutionHeight -> 0x801b -------------------------------------------------------------------------------- convolutionWidth :: ConvolutionTarget -> GettableStateVar GLsizei convolutionWidth t = convolutionParameteri t ConvolutionWidth convolutionHeight :: ConvolutionTarget -> GettableStateVar GLsizei convolutionHeight t = convolutionParameteri t ConvolutionHeight maxConvolutionWidth :: ConvolutionTarget -> GettableStateVar GLsizei maxConvolutionWidth t = convolutionParameteri t MaxConvolutionWidth maxConvolutionHeight :: ConvolutionTarget -> GettableStateVar GLsizei maxConvolutionHeight t = convolutionParameteri t MaxConvolutionHeight convolutionParameteri :: ConvolutionTarget -> ConvolutionParameter -> GettableStateVar GLsizei convolutionParameteri t p = makeGettableStateVar (getConvolutionParameteri fromIntegral t p) getConvolutionParameteri :: (GLint -> a) -> ConvolutionTarget -> ConvolutionParameter -> IO a getConvolutionParameteri f t p = alloca $ \buf -> do glGetConvolutionParameteriv (marshalConvolutionTarget t) (marshalConvolutionParameter p) buf peek1 f buf EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionParameteriv,GLenum -> GLenum -> Ptr GLint -> IO ()) -------------------------------------------------------------------------------- data ConvolutionBorderMode' = Reduce' | ConstantBorder' | ReplicateBorder' marshalConvolutionBorderMode' :: ConvolutionBorderMode' -> GLint marshalConvolutionBorderMode' x = case x of Reduce' -> 0x8016 ConstantBorder' -> 0x8151 ReplicateBorder' -> 0x8153 unmarshalConvolutionBorderMode' :: GLint -> ConvolutionBorderMode' unmarshalConvolutionBorderMode' x | x == 0x8016 = Reduce' | x == 0x8151 = ConstantBorder' | x == 0x8153 = ReplicateBorder' | otherwise = error ("unmarshalConvolutionBorderMode': illegal value " ++ show x) -------------------------------------------------------------------------------- data ConvolutionBorderMode = Reduce | ConstantBorder (Color4 GLfloat) | ReplicateBorder deriving ( Eq, Ord, Show ) -------------------------------------------------------------------------------- convolutionBorderMode :: ConvolutionTarget -> StateVar ConvolutionBorderMode convolutionBorderMode t = makeStateVar (getConvolutionBorderMode t) (setConvolutionBorderMode t) getConvolutionBorderMode :: ConvolutionTarget -> IO ConvolutionBorderMode getConvolutionBorderMode t = do mode <- getConvolutionParameteri unmarshalConvolutionBorderMode' t ConvolutionBorderMode case mode of Reduce' -> return Reduce ConstantBorder' -> do c <- getConvolutionParameterC4f t ConvolutionBorderColor return $ ConstantBorder c ReplicateBorder' -> return ReplicateBorder setConvolutionBorderMode :: ConvolutionTarget -> ConvolutionBorderMode -> IO () setConvolutionBorderMode t mode = do let setBM = setConvolutionParameteri marshalConvolutionBorderMode' t ConvolutionBorderMode case mode of Reduce -> setBM Reduce' ConstantBorder c -> do setBM ConstantBorder' convolutionParameterC4f t ConvolutionBorderColor c ReplicateBorder -> setBM ReplicateBorder' setConvolutionParameteri :: (a -> GLint) -> ConvolutionTarget -> ConvolutionParameter -> a -> IO () setConvolutionParameteri f t p x = glConvolutionParameteri (marshalConvolutionTarget t) (marshalConvolutionParameter p) (f x) EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionParameteri,GLenum -> GLenum -> GLint -> IO ()) -------------------------------------------------------------------------------- convolutionFilterScale :: ConvolutionTarget -> StateVar (Color4 GLfloat) convolutionFilterScale = convolutionC4f ConvolutionFilterScale convolutionFilterBias :: ConvolutionTarget -> StateVar (Color4 GLfloat) convolutionFilterBias = convolutionC4f ConvolutionFilterBias convolutionC4f :: ConvolutionParameter -> ConvolutionTarget -> StateVar (Color4 GLfloat) convolutionC4f p t = makeStateVar (getConvolutionParameterC4f t p) (convolutionParameterC4f t p) getConvolutionParameterC4f :: ConvolutionTarget -> ConvolutionParameter -> IO (Color4 GLfloat) getConvolutionParameterC4f t p = alloca $ \buf -> do glGetConvolutionParameterfv (marshalConvolutionTarget t) (marshalConvolutionParameter p) buf peek buf EXTENSION_ENTRY("GL_ARB_imaging",glGetConvolutionParameterfv,GLenum -> GLenum -> Ptr (Color4 GLfloat) -> IO ()) convolutionParameterC4f :: ConvolutionTarget -> ConvolutionParameter -> Color4 GLfloat -> IO () convolutionParameterC4f t p c = with c $ glConvolutionParameterfv (marshalConvolutionTarget t) (marshalConvolutionParameter p) EXTENSION_ENTRY("GL_ARB_imaging",glConvolutionParameterfv,GLenum -> GLenum -> Ptr (Color4 GLfloat) -> IO ())
FranklinChen/hugs98-plus-Sep2006
packages/OpenGL/Graphics/Rendering/OpenGL/GL/PixelRectangles/Convolution.hs
bsd-3-clause
12,502
4
19
1,834
2,584
1,354
1,230
-1
-1
{-# Language PatternGuards #-} module Blub ( blub , foo , bar ) where #include "Foo.h" #ifdef FOO import Control.Applicative #endif import Control.BiFunctor import Control.Monad f :: Int -> Int -- ^ Some Haddock doc -- One line more f = (+ 3) g :: Int -> Int g = where
dan-t/hsimport
tests/goldenFiles/ModuleTest37.hs
bsd-3-clause
289
0
5
71
68
44
24
-1
-1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE StandaloneDeriving #-} module Mitsuba.Utils where import Mitsuba.Types import Mitsuba.Element hiding (Visibility (Hidden)) import qualified Mitsuba.Element as E import Control.Lens hiding ((#), (.>)) import Control.Lens.Fold import Data.Word import Data.Text.Format import Data.Double.Conversion.Text import Control.Applicative import Data.Monoid import Data.Data import GHC.Generics import qualified Data.Text as T import qualified Data.Text.Lazy as TL import Data.Text (Text) import Text.Blaze import Data.List import qualified Data.HashMap.Strict as H import Data.HashMap.Strict (HashMap) import Control.Arrow hiding (left) import qualified Data.Foldable as F import Data.Maybe import Mitsuba.Types.Primitives import Mitsuba.Types.Transform import Mitsuba.LensTH import Data.Default.Generics import Data.Map (Map) import qualified Data.Map as M import Language.Haskell.TH.Module.Magic class HasToWorld a where toWorld :: Traversal' a Transform class HasBSDF a where bsdf :: Traversal' a BSDF instance HasToWorld ShapeLeaf where toWorld = shapeLeafToWorldL instance HasBSDF (Child BSDF) where bsdf f = \case CRef x -> CRef <$> pure x CNested x -> CNested <$> f x instance HasBSDF ShapeLeaf where bsdf = shapeLeafLeafL.bsdf instance HasBSDF SimpleShapeLeaf where bsdf = simpleShapeLeafMaterialL . bsdf instance (HasBSDF a, HasBSDF b) => HasBSDF (Either a b) where bsdf f = \case Left x -> Left <$> bsdf f x Right x -> Right <$> bsdf f x instance HasBSDF OBJLeaf where bsdf f OBJLeaf {..} = OBJLeaf objLeafObj <$> case objLeafMaterial of Left x -> Left <$> bsdf f x Right x -> Right <$> pure x twosided :: NonTransmission -> BSDF twosided = BSDFTwosided . Twosided . CNested diffuse :: BSDF diffuse = BSDFDiffuse $ Diffuse $ CSpectrum $ SUniform 1.0 class DielectricI a where dielectric :: a -> a -> BSDF instance DielectricI RefractiveValue where dielectric x y = BSDFDielectric $ Dielectric { dielectricIntIOR = IOR x , dielectricExtIOR = IOR y , dielectricSpecularReflectance = def , dielectricSpecularTransmittance = def } instance DielectricI KnownMaterial where dielectric x y = BSDFDielectric $ Dielectric { dielectricIntIOR = RKM x , dielectricExtIOR = RKM y , dielectricSpecularReflectance = def , dielectricSpecularTransmittance = def } instance HasToWorld Shape where toWorld = _SShapeLeaf . toWorld instance HasBSDF Shape where bsdf f = \case SShapeGroup xs -> SShapeGroup <$> traverse (bsdf f) xs SShapeLeaf x -> SShapeLeaf <$> bsdf f x objMaterialMap :: Traversal' Shape (Map Text (Child BSDF)) objMaterialMap = _SShapeLeaf . shapeLeafLeafL . _Right . objLeafMaterialL . _Right shapeLeaf :: ShapeType -> Shape shapeLeaf st = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf st (CNested diffuse) ) mempty Nothing Nothing cube :: Shape cube = shapeLeaf $ STCube $ Cube False sphere :: PositiveDouble -> Shape sphere radius = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf (STSphere $ Sphere zeroPoint radius True) (CNested diffuse) ) mempty Nothing Nothing cylinder :: PositiveDouble -> Shape cylinder radius = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf (STCylinder $ Cylinder zeroPoint (Point 0 1 0) radius True) (CNested diffuse) ) mempty Nothing Nothing -- TODO make the rectangle command square :: Shape square = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf (STRectangle $ Rectangle True) (CNested diffuse) ) mempty Nothing Nothing --rectangle :: Double -> Double -> Shape --rectangle width height -- = Shape (STRectangle ) disk :: Shape disk = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf (STDisk $ Disk True) (CNested diffuse) ) mempty Nothing Nothing obj :: FilePath -> Shape obj filePath = SShapeLeaf $ ShapeLeaf ( Right $ OBJLeaf ( OBJ filePath False 0.0 False False ) (Left $ CNested diffuse) ) mempty Nothing Nothing ply :: FilePath -> Shape ply filePath = SShapeLeaf $ ShapeLeaf ( Left $ SimpleShapeLeaf (STPLY $ PLY filePath True 0.0 False False) (CNested diffuse) ) mempty Nothing Nothing objMultiMaterial :: FilePath -> Shape objMultiMaterial filePath = SShapeLeaf $ ShapeLeaf ( Right $ OBJLeaf ( OBJ filePath False 0.0 False False ) (Right mempty) ) mempty Nothing Nothing serialized :: FilePath -> Shape serialized filepath = shapeLeaf $ STSerialized $ Serialized { serializedFilename = filepath , serializedShapeIndex = 0 , serializedFaceNormals = True , serializedMaxSmoothAngle = 0.0 , serializedFlipNormals = False } instanceShape :: Ref Shape -> Shape instanceShape = shapeLeaf . STInstance . Instance hair :: FilePath -> Shape hair filePath = shapeLeaf $ STHair $ Hair { hairFilename = filePath , hairRadius = 1.0 , hairAngleThreshold = 0.0 , hairReduction = 0.0 , hairWidth = 1 , hairHeight = 1 , hairTexture = TCheckerboard $ def } heightField :: FilePath -> Shape heightField filePath = shapeLeaf $ STHeightField $ HeightField { heightFieldShadingNormals = True , heightFieldFlipNormals = False , heightFieldWidth = 1 , heightFieldHeight = 1 , heightFieldScale = 1 , heightFieldFilename = filePath , heightFieldTexture = TCheckerboard $ def }
jfischoff/hs-mitsuba
src/Mitsuba/Utils.hs
bsd-3-clause
6,458
0
14
1,863
1,555
848
707
217
1
module Goblin.Workshop.Scheduler where import Control.Concurrent import Control.Concurrent.STM import Control.Monad import Goblin.Workshop.Types import Goblin.Workshop.Util import System.Log.Logger import Text.Printf newSchedulerBus :: STM (SchedulerBus m) newSchedulerBus = newTChan talk :: TaskId -> SchedulerBus IO -> TaskMessage -> IO () talk tid sbus msg = atomically $ writeTChan sbus $ STaskTalk tid $ case msg of TProgress progress -> STaskTalkProgress progress TOutput s -> STaskTalkOutput s translateTalkMessage :: STaskTalk -> WTaskTalk translateTalkMessage (STaskTalkProgress progress) = WTaskTalkProgress progress translateTalkMessage (STaskTalkOutput s) = WTaskTalkOutput s defaultScheduler :: Scheduler IO defaultScheduler = Scheduler $ \sbus dbus wbus -> do infoM "gw.s" "Scheduler launched" listen sbus dbus wbus where listen sbus dbus wbus = do msg <- atomically $ readTChan sbus case msg of SSpawnTask tid task -> do debugM "gw.s" $ printf "Spawning task: %d" tid forkIO $ do result <- case task of Task action -> action TalkativeTask action -> action (talk tid sbus) debugM "gw.t" $ printf "Task %d is done. Informing scheduler" tid atomically $ writeTChan sbus $ STaskDone tid result listen sbus dbus wbus STaskDone tid result -> do debugM "gw.s" $ printf "Task %d is done. Informing dispatcher" tid atomically $ writeTChan dbus $ DTaskDone tid result listen sbus dbus wbus STaskTalk tid stt -> do atomically $ writeMaybeTChan wbus $ WTaskTalk tid $ translateTalkMessage stt listen sbus dbus wbus SFin -> do infoM "gw.s" "Bye" _ -> error "Not implemented yet"
y-usuzumi/goblin-workshop
src/Goblin/Workshop/Scheduler.hs
bsd-3-clause
1,894
0
23
543
510
238
272
43
6
module SecondFront.Config ( module SecondFront.Config.Defaults, module SecondFront.Config.Types )where import SecondFront.Config.Defaults import SecondFront.Config.Types
alcidesv/second-front
hs-src/SecondFront/Config.hs
bsd-3-clause
190
0
5
32
34
23
11
5
0
{-# LANGUAGE PatternGuards, TypeSynonymInstances, CPP #-} module IRTS.Compiler(compile, generate) where import IRTS.Lang import IRTS.LangOpts import IRTS.Defunctionalise import IRTS.Simplified import IRTS.CodegenCommon import IRTS.CodegenC import IRTS.DumpBC import IRTS.CodegenJavaScript import IRTS.Inliner import IRTS.Exports import Idris.AbsSyntax import Idris.AbsSyntaxTree import Idris.ASTUtils import Idris.Erasure import Idris.Error import Debug.Trace import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.CaseTree import Control.Category import Prelude hiding (id, (.)) import Control.Applicative import Control.Monad.State import Data.Maybe import Data.List import Data.Ord import Data.IntSet (IntSet) import qualified Data.IntSet as IS import qualified Data.Map as M import qualified Data.Set as S import System.Process import System.IO import System.Exit import System.Directory import System.Environment import System.FilePath ((</>), addTrailingPathSeparator) -- | Given a 'main' term to compiler, return the IRs which can be used to -- generate code. compile :: Codegen -> FilePath -> Maybe Term -> Idris CodegenInfo compile codegen f mtm = do checkMVs -- check for undefined metavariables checkTotality -- refuse to compile if there are totality problems exports <- findExports let rootNames = case mtm of Nothing -> [] Just t -> freeNames t reachableNames <- performUsageAnalysis (rootNames ++ getExpNames exports) maindef <- case mtm of Nothing -> return [] Just tm -> do md <- irMain tm logLvl 1 $ "MAIN: " ++ show md return [(sMN 0 "runMain", md)] objs <- getObjectFiles codegen libs <- getLibs codegen flags <- getFlags codegen hdrs <- getHdrs codegen impdirs <- allImportDirs defsIn <- mkDecls reachableNames -- if no 'main term' given, generate interface files let iface = case mtm of Nothing -> True Just _ -> False let defs = defsIn ++ maindef -- iputStrLn $ showSep "\n" (map show defs) -- Inlined top level LDecl made here let defsInlined = inlineAll defs let defsUniq = map (allocUnique (addAlist defsInlined emptyContext)) defsInlined let (nexttag, tagged) = addTags 65536 (liftAll defsUniq) let ctxtIn = addAlist tagged emptyContext logLvl 1 "Defunctionalising" let defuns_in = defunctionalise nexttag ctxtIn logLvl 5 $ show defuns_in logLvl 1 "Inlining" let defuns = inline defuns_in logLvl 5 $ show defuns logLvl 1 "Resolving variables for CG" -- iputStrLn $ showSep "\n" (map show (toAlist defuns)) let checked = simplifyDefs defuns (toAlist defuns) outty <- outputTy dumpCases <- getDumpCases dumpDefun <- getDumpDefun case dumpCases of Nothing -> return () Just f -> runIO $ writeFile f (showCaseTrees defs) case dumpDefun of Nothing -> return () Just f -> runIO $ writeFile f (dumpDefuns defuns) triple <- Idris.AbsSyntax.targetTriple cpu <- Idris.AbsSyntax.targetCPU logLvl 1 "Building output" case checked of OK c -> do return $ CodegenInfo f outty triple cpu hdrs impdirs objs libs flags NONE c (toAlist defuns) tagged iface exports -- runIO $ case codegen of -- ViaC -> codegenC cginfo -- ViaJava -> codegenJava cginfo -- ViaJavaScript -> codegenJavaScript cginfo -- ViaNode -> codegenNode cginfo -- ViaLLVM -> codegenLLVM cginfo -- Bytecode -> dumpBC c f Error e -> ierror e where checkMVs = do i <- getIState case map fst (idris_metavars i) \\ primDefs of [] -> return () ms -> ifail $ "There are undefined holes: " ++ show ms checkTotality = do i <- getIState case idris_totcheckfail i of [] -> return () ((fc, msg):fs) -> ierror . At fc . Msg $ "Cannot compile:\n " ++ msg inDir d h = do let f = d </> h ex <- doesFileExist f if ex then return f else return h generate :: Codegen -> FilePath -> CodegenInfo -> IO () generate codegen mainmod ir = case codegen of -- Built-in code generators (FIXME: lift these out!) Via "c" -> codegenC ir -- Any external code generator Via cg -> do let cmd = "idris-codegen-" ++ cg args = ["--yes-really", mainmod, "-o", outputFile ir] ++ compilerFlags ir exit <- rawSystem cmd args when (exit /= ExitSuccess) $ putStrLn ("FAILURE: " ++ show cmd ++ " " ++ show args) Bytecode -> dumpBC (simpleDecls ir) (outputFile ir) irMain :: TT Name -> Idris LDecl irMain tm = do i <- irTerm M.empty [] tm return $ LFun [] (sMN 0 "runMain") [] (LForce i) mkDecls :: [Name] -> Idris [(Name, LDecl)] mkDecls used = do i <- getIState let ds = filter (\(n, d) -> n `elem` used || isCon d) $ ctxtAlist (tt_ctxt i) decls <- mapM build ds return decls showCaseTrees :: [(Name, LDecl)] -> String showCaseTrees = showSep "\n\n" . map showCT . sortBy (comparing defnRank) where showCT (n, LFun _ f args lexp) = show n ++ " " ++ showSep " " (map show args) ++ " =\n\t" ++ show lexp showCT (n, LConstructor c t a) = "data " ++ show n ++ " " ++ show a defnRank :: (Name, LDecl) -> String defnRank (n, LFun _ _ _ _) = "1" ++ nameRank n defnRank (n, LConstructor _ _ _) = "2" ++ nameRank n nameRank :: Name -> String nameRank (UN s) = "1" ++ show s nameRank (MN i s) = "2" ++ show s ++ show i nameRank (NS n ns) = "3" ++ concatMap show (reverse ns) ++ nameRank n nameRank (SN sn) = "4" ++ snRank sn nameRank n = "5" ++ show n snRank :: SpecialName -> String snRank (WhereN i n n') = "1" ++ nameRank n' ++ nameRank n ++ show i snRank (InstanceN n args) = "2" ++ nameRank n ++ concatMap show args snRank (ParentN n s) = "3" ++ nameRank n ++ show s snRank (MethodN n) = "4" ++ nameRank n snRank (CaseN n) = "5" ++ nameRank n snRank (ElimN n) = "6" ++ nameRank n snRank (InstanceCtorN n) = "7" ++ nameRank n snRank (WithN i n) = "8" ++ nameRank n ++ show i isCon (TyDecl _ _) = True isCon _ = False build :: (Name, Def) -> Idris (Name, LDecl) build (n, d) = do i <- getIState case getPrim n i of Just (ar, op) -> let args = map (\x -> sMN x "op") [0..] in return (n, (LFun [] n (take ar args) (LOp op (map (LV . Glob) (take ar args))))) _ -> do def <- mkLDecl n d logLvl 3 $ "Compiled " ++ show n ++ " =\n\t" ++ show def return (n, def) where getPrim n i | Just (ar, op) <- lookup n (idris_scprims i) = Just (ar, op) | Just ar <- lookup n (S.toList (idris_externs i)) = Just (ar, LExternal n) getPrim n i = Nothing declArgs args inl n (LLam xs x) = declArgs (args ++ xs) inl n x declArgs args inl n x = LFun (if inl then [Inline] else []) n args x mkLDecl n (Function tm _) = declArgs [] True n <$> irTerm M.empty [] tm mkLDecl n (CaseOp ci _ _ _ pats cd) = declArgs [] (case_inlinable ci || caseName n) n <$> irTree args sc where (args, sc) = cases_runtime cd -- Always attempt to inline functions arising from 'case' expressions caseName (SN (CaseN _)) = True caseName (SN (WithN _ _)) = True caseName (NS n _) = caseName n caseName _ = False mkLDecl n (TyDecl (DCon tag arity _) _) = LConstructor n tag . length <$> fgetState (cg_usedpos . ist_callgraph n) mkLDecl n (TyDecl (TCon t a) _) = return $ LConstructor n (-1) a mkLDecl n _ = return $ (declArgs [] True n LNothing) -- postulate, never run data VarInfo = VI { viMethod :: Maybe Name } deriving Show type Vars = M.Map Name VarInfo irTerm :: Vars -> [Name] -> Term -> Idris LExp irTerm vs env tm@(App _ f a) = do ist <- getIState case unApply tm of (P _ (UN m) _, args) | m == txt "mkForeignPrim" -> doForeign vs env (reverse (drop 4 args)) -- drop implicits (P _ (UN u) _, [_, arg]) | u == txt "unsafePerformPrimIO" -> irTerm vs env arg -- TMP HACK - until we get inlining. (P _ (UN r) _, [_, _, _, _, _, arg]) | r == txt "replace" -> irTerm vs env arg -- Laziness, the old way (P _ (UN l) _, [_, arg]) | l == txt "lazy" -> error "lazy has crept in somehow" (P _ (UN l) _, [_, arg]) | l == txt "force" -> LForce <$> irTerm vs env arg -- Laziness, the new way (P _ (UN l) _, [_, _, arg]) | l == txt "Delay" -> LLazyExp <$> irTerm vs env arg (P _ (UN l) _, [_, _, arg]) | l == txt "Force" -> LForce <$> irTerm vs env arg (P _ (UN a) _, [_, _, _, arg]) | a == txt "assert_smaller" -> irTerm vs env arg (P _ (UN a) _, [_, arg]) | a == txt "assert_total" -> irTerm vs env arg (P _ (UN p) _, [_, arg]) | p == txt "par" -> do arg' <- irTerm vs env arg return $ LOp LPar [LLazyExp arg'] (P _ (UN pf) _, [arg]) | pf == txt "prim_fork" -> do arg' <- irTerm vs env arg return $ LOp LFork [LLazyExp arg'] (P _ (UN m) _, [_,size,t]) | m == txt "malloc" -> irTerm vs env t (P _ (UN tm) _, [_,t]) | tm == txt "trace_malloc" -> irTerm vs env t -- TODO -- This case is here until we get more general inlining. It's just -- a really common case, and the laziness hurts... (P _ (NS (UN be) [b,p]) _, [_,x,(App _ (App _ (App _ (P _ (UN d) _) _) _) t), (App _ (App _ (App _ (P _ (UN d') _) _) _) e)]) | be == txt "ifThenElse" , d == txt "Delay" , d' == txt "Delay" , b == txt "Bool" , p == txt "Prelude" -> do x' <- irTerm vs env x t' <- irTerm vs env t e' <- irTerm vs env e return (LCase Shared x' [LConCase 0 (sNS (sUN "False") ["Bool","Prelude"]) [] e' ,LConCase 1 (sNS (sUN "True" ) ["Bool","Prelude"]) [] t' ]) -- data constructor (P (DCon t arity _) n _, args) -> do detag <- fgetState (opt_detaggable . ist_optimisation n) used <- map fst <$> fgetState (cg_usedpos . ist_callgraph n) let isNewtype = length used == 1 && detag let argsPruned = [a | (i,a) <- zip [0..] args, i `elem` used] -- The following code removes fields from data constructors -- and performs the newtype optimisation. -- -- The general rule here is: -- Everything we get as input is not touched by erasure, -- so it conforms to the official arities and types -- and we can reason about it like it's plain TT. -- -- It's only the data that leaves this point that's erased -- and possibly no longer typed as the original TT version. -- -- Especially, underapplied constructors must yield functions -- even if all the remaining arguments are erased -- (the resulting function *will* be applied, to NULLs). -- -- This will probably need rethinking when we get erasure from functions. -- "padLams" will wrap our term in LLam-bdas and give us -- the "list of future unerased args" coming from these lambdas. -- -- We can do whatever we like with the list of unerased args, -- hence it takes a lambda: \unerased_argname_list -> resulting_LExp. let padLams = padLambdas used (length args) arity case compare (length args) arity of -- overapplied GT -> ifail ("overapplied data constructor: " ++ show tm) -- exactly saturated EQ | isNewtype -> irTerm vs env (head argsPruned) | otherwise -- not newtype, plain data ctor -> buildApp (LV $ Glob n) argsPruned -- not saturated, underapplied LT | isNewtype -- newtype , length argsPruned == 1 -- and we already have the value -> padLams . (\tm [] -> tm) -- the [] asserts there are no unerased args <$> irTerm vs env (head argsPruned) | isNewtype -- newtype but the value is not among args yet -> return . padLams $ \[vn] -> LApp False (LV $ Glob n) [LV $ Glob vn] -- not a newtype, just apply to a constructor | otherwise -> padLams . applyToNames <$> buildApp (LV $ Glob n) argsPruned -- type constructor (P (TCon t a) n _, args) -> return LNothing -- an external name applied to arguments (P _ n _, args) | S.member (n, length args) (idris_externs ist) -> do LOp (LExternal n) <$> mapM (irTerm vs env) args -- a name applied to arguments (P _ n _, args) -> do case lookup n (idris_scprims ist) of -- if it's a primitive that is already saturated, -- compile to the corresponding op here already to save work Just (arity, op) | length args == arity -> LOp op <$> mapM (irTerm vs env) args -- otherwise, just apply the name _ -> applyName n ist args -- turn de bruijn vars into regular named references and try again (V i, args) -> irTerm vs env $ mkApp (P Bound (env !! i) Erased) args (f, args) -> LApp False <$> irTerm vs env f <*> mapM (irTerm vs env) args where buildApp :: LExp -> [Term] -> Idris LExp buildApp e [] = return e buildApp e xs = LApp False e <$> mapM (irTerm vs env) xs applyToNames :: LExp -> [Name] -> LExp applyToNames tm [] = tm applyToNames tm ns = LApp False tm $ map (LV . Glob) ns padLambdas :: [Int] -> Int -> Int -> ([Name] -> LExp) -> LExp padLambdas used startIdx endSIdx mkTerm = LLam allNames $ mkTerm nonerasedNames where allNames = [sMN i "sat" | i <- [startIdx .. endSIdx-1]] nonerasedNames = [sMN i "sat" | i <- [startIdx .. endSIdx-1], i `elem` used] applyName :: Name -> IState -> [Term] -> Idris LExp applyName n ist args = LApp False (LV $ Glob n) <$> mapM (irTerm vs env . erase) (zip [0..] args) where erase (i, x) | i >= arity || i `elem` used = x | otherwise = Erased arity = case fst4 <$> lookupCtxtExact n (definitions . tt_ctxt $ ist) of Just (CaseOp ci ty tys def tot cdefs) -> length tys Just (TyDecl (DCon tag ar _) _) -> ar Just (TyDecl Ref ty) -> length $ getArgTys ty Just (Operator ty ar op) -> ar Just def -> error $ "unknown arity: " ++ show (n, def) Nothing -> 0 -- no definition, probably local name => can't erase anything -- name for purposes of usage info lookup uName | Just n' <- viMethod =<< M.lookup n vs = n' | otherwise = n used = maybe [] (map fst . usedpos) $ lookupCtxtExact uName (idris_callgraph ist) fst4 (x,_,_,_) = x irTerm vs env (P _ n _) = return $ LV (Glob n) irTerm vs env (V i) | i >= 0 && i < length env = return $ LV (Glob (env!!i)) | otherwise = ifail $ "bad de bruijn index: " ++ show i irTerm vs env (Bind n (Lam _) sc) = LLam [n'] <$> irTerm vs (n':env) sc where n' = uniqueName n env irTerm vs env (Bind n (Let _ v) sc) = LLet n <$> irTerm vs env v <*> irTerm vs (n : env) sc irTerm vs env (Bind _ _ _) = return $ LNothing irTerm vs env (Proj t (-1)) = do t' <- irTerm vs env t return $ LOp (LMinus (ATInt ITBig)) [t', LConst (BI 1)] irTerm vs env (Proj t i) = LProj <$> irTerm vs env t <*> pure i irTerm vs env (Constant TheWorld) = return $ LNothing irTerm vs env (Constant c) = return $ LConst c irTerm vs env (TType _) = return $ LNothing irTerm vs env Erased = return $ LNothing irTerm vs env Impossible = return $ LNothing doForeign :: Vars -> [Name] -> [Term] -> Idris LExp doForeign vs env (ret : fname : world : args) = do args' <- mapM splitArg args let fname' = toFDesc fname let ret' = toFDesc ret return $ LForeign ret' fname' args' where splitArg tm | (_, [_,_,l,r]) <- unApply tm -- pair, two implicits = do let l' = toFDesc l r' <- irTerm vs env r return (l', r') splitArg _ = ifail "Badly formed foreign function call" toFDesc (Constant (Str str)) = FStr str toFDesc tm | (P _ n _, []) <- unApply tm = FCon (deNS n) | (P _ n _, as) <- unApply tm = FApp (deNS n) (map toFDesc as) toFDesc _ = FUnknown deNS (NS n _) = n deNS n = n doForeign vs env xs = ifail "Badly formed foreign function call" {- - | (_, (Constant (Str fgnName) : fgnArgTys : ret : [])) <- unApply fgn = case getFTypes fgnArgTys of Nothing -> ifail $ "Foreign type specification is not a constant list: " ++ show (fgn:args) Just tys -> do args' <- mapM (irTerm vs env) (init args) return $ LForeign LANG_C (mkIty' ret) fgnName (zip tys args') | otherwise = ifail "Badly formed foreign function call" where getFTypes :: TT Name -> Maybe [FType] getFTypes tm = case unApply tm of -- nil : {a : Type} -> List a (nil, [_]) -> Just [] -- cons : {a : Type} -> a -> List a -> List a (cons, [_, ty, xs]) -> (mkIty' ty :) <$> getFTypes xs _ -> Nothing mkIty' (P _ (UN ty) _) = mkIty (str ty) mkIty' (App (P _ (UN fi) _) (P _ (UN intTy) _)) | fi == txt "FIntT" = mkIntIty (str intTy) mkIty' (App (App (P _ (UN ff) _) _) (App (P _ (UN fa) _) (App (P _ (UN io) _) _))) | ff == txt "FFunction" , fa == txt "FAny" , io == txt "IO" = FFunctionIO mkIty' (App (App (P _ (UN ff) _) _) _) | ff == txt "FFunction" = FFunction mkIty' _ = FAny -- would be better if these FInt types were evaluated at compile time -- TODO: add %eval directive for such things -- Issue #1742 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1742 mkIty "FFloat" = FArith ATFloat mkIty "FInt" = mkIntIty "ITNative" mkIty "FChar" = mkIntIty "ITChar" mkIty "FByte" = mkIntIty "IT8" mkIty "FShort" = mkIntIty "IT16" mkIty "FLong" = mkIntIty "IT64" mkIty "FBits8" = mkIntIty "IT8" mkIty "FBits16" = mkIntIty "IT16" mkIty "FBits32" = mkIntIty "IT32" mkIty "FBits64" = mkIntIty "IT64" mkIty "FString" = FString mkIty "FPtr" = FPtr mkIty "FManagedPtr" = FManagedPtr mkIty "FUnit" = FUnit mkIty "FFunction" = FFunction mkIty "FFunctionIO" = FFunctionIO mkIty "FBits8x16" = FArith (ATInt (ITVec IT8 16)) mkIty "FBits16x8" = FArith (ATInt (ITVec IT16 8)) mkIty "FBits32x4" = FArith (ATInt (ITVec IT32 4)) mkIty "FBits64x2" = FArith (ATInt (ITVec IT64 2)) mkIty x = error $ "Unknown type " ++ x mkIntIty "ITNative" = FArith (ATInt ITNative) mkIntIty "ITChar" = FArith (ATInt ITChar) mkIntIty "IT8" = FArith (ATInt (ITFixed IT8)) mkIntIty "IT16" = FArith (ATInt (ITFixed IT16)) mkIntIty "IT32" = FArith (ATInt (ITFixed IT32)) mkIntIty "IT64" = FArith (ATInt (ITFixed IT64)) -} irTree :: [Name] -> SC -> Idris LExp irTree args tree = do logLvl 3 $ "Compiling " ++ show args ++ "\n" ++ show tree LLam args <$> irSC M.empty tree irSC :: Vars -> SC -> Idris LExp irSC vs (STerm t) = irTerm vs [] t irSC vs (UnmatchedCase str) = return $ LError str irSC vs (ProjCase tm alts) = do tm' <- irTerm vs [] tm alts' <- mapM (irAlt vs tm') alts return $ LCase Shared tm' alts' -- Transform matching on Delay to applications of Force. irSC vs (Case up n [ConCase (UN delay) i [_, _, n'] sc]) | delay == txt "Delay" = do sc' <- irSC vs $ mkForce n' n sc return $ LLet n' (LForce (LV (Glob n))) sc' -- There are two transformations in this case: -- -- 1. Newtype-case elimination: -- case {e0} of -- wrap({e1}) -> P({e1}) ==> P({e0}) -- -- This is important because newtyped constructors are compiled away entirely -- and we need to do that everywhere. -- -- 2. Unused-case elimination (only valid for singleton branches): -- case {e0} of ==> P -- C(x,y) -> P[... x,y not used ...] -- -- This is important for runtime because sometimes we case on irrelevant data: -- -- In the example above, {e0} will most probably have been erased -- so this vain projection would make the resulting program segfault -- because the code generator still emits a PROJECT(...) G-machine instruction. -- -- Hence, we check whether the variables are used at all -- and erase the casesplit if they are not. -- irSC vs (Case up n [alt]) = do replacement <- case alt of ConCase cn a ns sc -> do detag <- fgetState (opt_detaggable . ist_optimisation cn) used <- map fst <$> fgetState (cg_usedpos . ist_callgraph cn) if detag && length used == 1 then return . Just $ substSC (ns !! head used) n sc else return Nothing _ -> return Nothing case replacement of Just sc -> irSC vs sc _ -> do alt' <- irAlt vs (LV (Glob n)) alt return $ case namesBoundIn alt' `usedIn` subexpr alt' of [] -> subexpr alt' -- strip the unused top-most case _ -> LCase up (LV (Glob n)) [alt'] where namesBoundIn :: LAlt -> [Name] namesBoundIn (LConCase cn i ns sc) = ns namesBoundIn (LConstCase c sc) = [] namesBoundIn (LDefaultCase sc) = [] subexpr :: LAlt -> LExp subexpr (LConCase _ _ _ e) = e subexpr (LConstCase _ e) = e subexpr (LDefaultCase e) = e -- FIXME: When we have a non-singleton case-tree of the form -- -- case {e0} of -- C(x) => ... -- ... => ... -- -- and C is detaggable (the only constructor of the family), we can be sure -- that the first branch will be always taken -- so we add special handling -- to remove the dead default branch. -- -- If we don't do so and C is newtype-optimisable, we will miss this newtype -- transformation and the resulting code will probably segfault. -- -- This work-around is not entirely optimal; the best approach would be -- to ensure that such case trees don't arise in the first place. -- irSC vs (Case up n alts@[ConCase cn a ns sc, DefaultCase sc']) = do detag <- fgetState (opt_detaggable . ist_optimisation cn) if detag then irSC vs (Case up n [ConCase cn a ns sc]) else LCase up (LV (Glob n)) <$> mapM (irAlt vs (LV (Glob n))) alts irSC vs sc@(Case up n alts) = do -- check that neither alternative needs the newtype optimisation, -- see comment above goneWrong <- or <$> mapM isDetaggable alts when goneWrong $ ifail ("irSC: non-trivial case-match on detaggable data: " ++ show sc) -- everything okay LCase up (LV (Glob n)) <$> mapM (irAlt vs (LV (Glob n))) alts where isDetaggable (ConCase cn _ _ _) = fgetState $ opt_detaggable . ist_optimisation cn isDetaggable _ = return False irSC vs ImpossibleCase = return LNothing irAlt :: Vars -> LExp -> CaseAlt -> Idris LAlt -- this leaves out all unused arguments of the constructor irAlt vs _ (ConCase n t args sc) = do used <- map fst <$> fgetState (cg_usedpos . ist_callgraph n) let usedArgs = [a | (i,a) <- zip [0..] args, i `elem` used] LConCase (-1) n usedArgs <$> irSC (methodVars `M.union` vs) sc where methodVars = case n of SN (InstanceCtorN className) -> M.fromList [(v, VI { viMethod = Just $ mkFieldName n i }) | (v,i) <- zip args [0..]] _ -> M.empty -- not an instance constructor irAlt vs _ (ConstCase x rhs) | matchable x = LConstCase x <$> irSC vs rhs | matchableTy x = LDefaultCase <$> irSC vs rhs where matchable (I _) = True matchable (BI _) = True matchable (Ch _) = True matchable (Str _) = True matchable (B8 _) = True matchable (B16 _) = True matchable (B32 _) = True matchable (B64 _) = True matchable _ = False matchableTy (AType (ATInt ITNative)) = True matchableTy (AType (ATInt ITBig)) = True matchableTy (AType (ATInt ITChar)) = True matchableTy StrType = True matchableTy (AType (ATInt (ITFixed IT8))) = True matchableTy (AType (ATInt (ITFixed IT16))) = True matchableTy (AType (ATInt (ITFixed IT32))) = True matchableTy (AType (ATInt (ITFixed IT64))) = True matchableTy _ = False irAlt vs tm (SucCase n rhs) = do rhs' <- irSC vs rhs return $ LDefaultCase (LLet n (LOp (LMinus (ATInt ITBig)) [tm, LConst (BI 1)]) rhs') irAlt vs _ (ConstCase c rhs) = ifail $ "Can't match on (" ++ show c ++ ")" irAlt vs _ (DefaultCase rhs) = LDefaultCase <$> irSC vs rhs
rpglover64/Idris-dev
src/IRTS/Compiler.hs
bsd-3-clause
26,376
0
21
8,816
7,987
3,965
4,022
440
30
module Main(main) where import PolyPaver.Invocation import Data.Ratio ((%)) main = defaultMain Problem { box = [(0,(409018325532672 % 579004697502343,9015995347763200 % 6369051672525773)),(1,(1 % 2,2 % 1))] ,theorem = thm } thm = Implies (Geq (Var 0) (Over (Over (Lit (1023 % 1)) (Lit (1024 % 1))) (Sqrt (Var 1)))) (Implies (Leq (Var 0) (Over (Over (Lit (1025 % 1)) (Lit (1024 % 1))) (Sqrt (Var 1)))) (Implies (Geq (Var 1) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Implies (Geq (Var 1) (Over (Lit (1 % 1)) (Lit (2 % 1)))) (Implies (Leq (Var 1) (Lit (2 % 1))) (Implies (Geq (Var 0) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Implies (Leq (Var 0) (Lit (340282000000000000000000000000000000000 % 1))) (And (Geq (FTimes (Over (Lit (1 % 1)) (Lit (2 % 1))) (Var 0)) (Neg (Lit (340282000000000000000000000000000000000 % 1)))) (Leq (FTimes (Over (Lit (1 % 1)) (Lit (2 % 1))) (Var 0)) (Lit (340282000000000000000000000000000000000 % 1))))))))))
michalkonecny/polypaver
examples/old/their_sqrt/their_sqrt_11.hs
bsd-3-clause
1,018
0
29
194
608
323
285
9
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# OPTIONS -Wall #-} -- | -- Module : GHC.TypeLits.SigNat -- License : BSD3 -- Maintainer : [email protected] -- Stability : Experimental -- Portability : GHC 7.8.* on Unix -- -- This module provides support for signed type-level naturals. module GHC.TypeLits.SigNat ( -- ** Signed Type-Level Naturals SigNat(..) , KnownSigNat(..) , SomeSigNat(..) , someSigNatVal , promoteSigNat ) where import Data.Maybe (fromJust) import Data.Proxy (Proxy(..)) import GHC.TypeLits -- | -- This is the kind of a signed type-level natural. data SigNat where Plus :: Nat -> SigNat Minus :: Nat -> SigNat -- | -- This class gives the integer associated with a signed type-level natural. class KnownSigNat (signat :: SigNat) where sigNatVal :: Proxy signat -> Integer instance KnownNat nat => KnownSigNat (Plus nat) where sigNatVal _ = natVal (Proxy :: Proxy nat) instance KnownNat nat => KnownSigNat (Minus nat) where sigNatVal _ = negate $ natVal (Proxy :: Proxy nat) -- | -- This type represents an unknown signed type-level natural. data SomeSigNat = forall signat . KnownSigNat signat => SomeSigNat (Proxy signat) instance Eq SomeSigNat where SomeSigNat proxy1 == SomeSigNat proxy2 = sigNatVal proxy1 == sigNatVal proxy2 deriving instance Show SomeSigNat -- | -- Convert an integer into an unknown signed type-level natural. someSigNatVal :: Integer -> SomeSigNat someSigNatVal x = case fromJust . someNatVal $ abs x of SomeNat (_ :: Proxy nat) -> if x >= 0 then SomeSigNat (Proxy :: Proxy (Plus nat)) else SomeSigNat (Proxy :: Proxy (Minus nat)) -- | -- Promote a signed type-level natural. promoteSigNat :: forall proxy signat a . KnownSigNat signat => proxy signat -> (Proxy signat -> a) -> a promoteSigNat _ f = f Proxy
time-cube/time-cube
src/GHC/TypeLits/SigNat.hs
bsd-3-clause
2,116
0
13
500
448
248
200
38
2
{- BlendEqn.hs (adapted from blendeqn.c which is (c) Silicon Graphics, Inc.) Copyright (c) Sven Panne 2002-2005 <[email protected]> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE Demonstrate the different blending functions available with the OpenGL imaging subset. This program demonstrates use of blendEquation. The following keys change the selected blend equation function: 'a' -> FuncAdd 's' -> FuncSubtract 'r' -> FuncReverseSubtract 'm' -> Min 'x' -> Max -} import Data.Char ( toLower ) import System.Exit ( exitWith, ExitCode(ExitSuccess) ) import Graphics.UI.GLUT myInit :: IO () myInit = do clearColor $= Color4 1 1 0 0 blendFunc $= (One, One) blend $= Enabled display :: DisplayCallback display = do clear [ ColorBuffer ] color (Color3 0 0 (1 :: GLfloat)) rect (Vertex2 (-0.5) (-0.5)) (Vertex2 0.5 (0.5 :: GLfloat)) flush reshape :: ReshapeCallback reshape size@(Size w h) = do let aspect = fromIntegral w / fromIntegral h viewport $= (Position 0 0, size) matrixMode $= Projection loadIdentity if aspect < 1 then let aspect' = recip aspect in ortho (-aspect') aspect' (-1) 1 (-1) 1 else ortho (-1) 1 (-aspect) aspect (-1) 1 matrixMode $= Modelview 0 keyboard :: KeyboardMouseCallback keyboard (Char c) Down _ _ = case toLower c of -- Colors are added as: (0, 0, 1) + (1, 1, 0) = (1, 1, 1) -- which will produce a white square on a yellow background. 'a' -> setBlendEquation FuncAdd -- Colors are subtracted as: (0, 0, 1) - (1, 1, 0) = (-1, -1, 1) -- which is clamped to (0, 0, 1), producing a blue square on a -- yellow background 's' -> setBlendEquation FuncSubtract -- Colors are subtracted as: (1, 1, 0) - (0, 0, 1) = (1, 1, -1) -- which is clamed to (1, 1, 0). This produces yellow for both -- the square and the background. 'r' -> setBlendEquation FuncReverseSubtract -- The minimum of each component is computed, as -- [min(0, 1), min(0, 1), min(1, 0)] which equates to (0, 0, 0). -- This will produce a black square on the yellow background. 'm' -> setBlendEquation Min -- The minimum of each component is computed, as -- [max(0, 1), max(0, 1), max(1, 0)] which equates to (1, 1, 1) -- This will produce a white square on the yellow background. 'x' -> setBlendEquation Max '\27' -> exitWith ExitSuccess _ -> return () where setBlendEquation e = do blendEquation $= e postRedisplay Nothing keyboard _ _ _ _ = return () main :: IO () main = do (progName, _args) <- getArgsAndInitialize initialDisplayMode $= [ SingleBuffered, RGBMode ] initialWindowSize $= Size 512 512 initialWindowPosition $= Position 100 100 createWindow progName myInit reshapeCallback $= Just reshape keyboardMouseCallback $= Just keyboard displayCallback $= display mainLoop
FranklinChen/hugs98-plus-Sep2006
packages/GLUT/examples/RedBook/BlendEqn.hs
bsd-3-clause
3,007
0
12
736
593
297
296
50
7
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving #-} import System.IO import System.Linux.Input.Event import Control.Concurrent.STM import Control.Concurrent import Control.Lens import Control.Applicative import Data.Int import Data.Functor.Rep import Linear import Control.Monad (forever) import Control.Monad.State.Strict import Data.Traversable as T import Data.Foldable as F import Data.Monoid import Options.Applicative hiding ((&)) import qualified MercuryController as MM import qualified ZMotor as Z data Config = Config { xyDevice :: FilePath , zDevice :: FilePath , inputDevice :: FilePath , driveCurrent :: Int , holdCurrent :: Int } axisNames :: V3 String axisNames = V3 "x" "y" "z" config = Config <$> strOption ( long "xy" <> metavar "DEVICE" <> value "/dev/ttyUSB.stage" <> help "XY stepper device path") <*> strOption ( long "z" <> metavar "DEVICE" <> value "/dev/ttyUSB.zstage" <> help "Z stepper device path") <*> strOption ( long "input" <> metavar "DEVICE" <> value "/dev/input/event4" <> help "Joystick input device") <*> option auto ( long "drive-current" <> metavar "MA" <> value 350 <> help "Motor drive current") <*> option auto ( long "hold-current" <> metavar "MA" <> value 350 <> help "Motor drive current") newtype Position = Pos Int deriving (Show, Eq, Ord, Num, Integral, Real, Enum) data NavAxis = NavAxis { _position :: Position , _velocity :: Double -- | Position units per second } deriving (Show, Eq) makeLenses ''NavAxis type Mover = Position -> IO () newNavAxis :: Int -> Mover -> Position -> IO (MVar NavAxis) newNavAxis updateRate move initial = do ref <- newMVar $ NavAxis initial 0 forkIO $ forever $ update ref initial return ref where dt = 1 / realToFrac updateRate update ref lastPos = do threadDelay $ round (1e6 * dt) na' <- modifyMVar ref $ \na->do let dx = round $ dt * na ^. velocity na' = na & position %~ (+dx) pos = na' ^. position when (lastPos /= pos) $ move pos return (na', na') update ref (na' ^. position) newMotorQueue :: FilePath -> IO (TQueue (MM.Bus -> IO ())) newMotorQueue device = do bus <- MM.open device queue <- newTQueueIO forkIO $ forever $ atomically (readTQueue queue) >>= ($ bus) return queue data JoystickState = JSS { _jssPosition :: V3 Int32 , _jssEnabled :: V3 Bool , _jssCurrentAxis :: [E V3] } makeLenses ''JoystickState listenEvDev :: Handle -> V3 (MVar NavAxis) -> IO () listenEvDev h navAxes = void $ flip evalStateT s0 $ forever $ lift (hReadEvent h) >>= maybe (return ()) handleEvent where s0 = JSS { _jssPosition = pure 0 , _jssEnabled = pure True , _jssCurrentAxis = cycle [ex, ey, ez] } handleEvent :: Event -> StateT JoystickState IO () handleEvent (KeyEvent {evKeyCode=key, evKeyEventType=Released}) | key == btn_0 = do curAxis:_ <- use jssCurrentAxis jssEnabled . el curAxis %= not en <- use jssEnabled when (not $ en ^. el curAxis) $ do jssPosition . el curAxis .= 0 lift $ putStrLn $ "Enabled axes: "++show en | key == btn_1 = do jssCurrentAxis %= tail axis:_ <- use jssCurrentAxis lift $ putStrLn $ "Selected axis: "++(axisNames ^. el axis) handleEvent event@(RelEvent {}) = do case relAxisToLens (evRelAxis event) of Just l -> do enabled <- use $ jssEnabled . el l when enabled $ do jssPosition . el l .= evValue event update Nothing -> return () handleEvent _ = return () tabulateV3 = tabulate :: (E V3 -> a) -> V3 a update :: StateT JoystickState IO () update = void $ T.sequence $ tabulateV3 $ \(E l)->do v <- uses (jssPosition . l) realToFrac lift $ modifyMVar_ (navAxes ^. l) $ return . (velocity .~ v) relAxisToLens :: RelAxis -> Maybe (E V3) relAxisToLens ax | ax == rel_x = Just ex | ax == rel_y = Just ey | ax == rel_z = Just ez | otherwise = Nothing valueToVelocity :: V3 Int32 -> V3 Double valueToVelocity v | norm v' < thresh = 0 | otherwise = gain * (norm v' - thresh)**1.4 *^ vhat where thresh = 30 gain = 1 v' = fmap realToFrac v vhat = normalize v' updateRate = 30 axes = V2 (MM.Axis 0) (MM.Axis 1) main :: IO () main = do args <- execParser $ info (helper <*> config) mempty putStrLn "Opening XY stage" queue <- newMotorQueue (xyDevice args) let enqueue :: (MM.Bus -> IO ()) -> IO () enqueue = atomically . writeTQueue queue initialVar <- newEmptyMVar enqueue $ \bus->do initialPos <- T.forM axes $ \axis->do MM.select bus axis --MM.getError bus >>= print MM.setBrake bus False MM.setDriveCurrent bus (driveCurrent args) MM.setHoldCurrent bus (holdCurrent args) MM.setMotorPower bus True either (error "Error fetching initial position") fromIntegral <$> MM.getPosition bus putMVar initialVar initialPos initial <- takeMVar initialVar let moveStage :: MM.Axis -> Mover moveStage axis (Pos n) = enqueue $ \bus->do MM.select bus axis MM.moveAbs bus (MM.Pos $ fromIntegral n) putStrLn $ "Move "++show axis++" to "++show n putStrLn "Opening Z stage" zMotor <- Z.open (zDevice args) let moveZStage (Pos n) = do Z.move zMotor n putStrLn $ "Move Z to "++show n --forkIO $ forever $ threadDelay 1000000 >> enqueue reportPositions navAxes <- T.sequence $ V3 (newNavAxis updateRate (moveStage (axes ^. _x)) (initial ^. _x)) (newNavAxis updateRate (moveStage (axes ^. _y)) (initial ^. _y)) (newNavAxis updateRate moveZStage 0) putStrLn "Opening joystick" joystick <- openFile (inputDevice args) ReadMode listenEvDev joystick navAxes reportPositions :: MM.Bus -> IO () reportPositions bus = F.forM_ axes $ \axis->do MM.select bus axis p <- MM.getPosition bus putStrLn $ show axis++" is "++show p
bgamari/navigate
Navigate.hs
bsd-3-clause
6,750
0
19
2,242
2,203
1,075
1,128
-1
-1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Time.IT.Tests ( tests ) where import Data.String import Prelude import Test.Tasty import Duckling.Dimensions.Types import Duckling.Testing.Asserts import Duckling.Time.IT.Corpus tests :: TestTree tests = testGroup "IT Tests" [ makeCorpusTest [Seal Time] corpus , makeNegativeCorpusTest [Seal Time] negativeCorpus ]
facebookincubator/duckling
tests/Duckling/Time/IT/Tests.hs
bsd-3-clause
549
0
9
85
93
57
36
12
1
{-# LANGUAGE RecordWildCards #-} module Tronkell.Server.Server where import Tronkell.Server.Types as Server import Tronkell.Game.Types as Game import Tronkell.Types() import Tronkell.Game.Engine as Engine import qualified Tronkell.Utils as SUtils import qualified Tronkell.Network.Websockets as W import qualified Tronkell.Network.TcpSockets as Tcp import Control.Concurrent import Control.Concurrent.STM import qualified Data.Text as T import Data.Maybe (fromJust) import Control.Monad (void, foldM, forever, when) import Control.Monad.Fix (fix) import qualified Data.Map as M import qualified Data.List as L (foldl') startServer :: Game.GameConfig -> IO () startServer gConfig = do firstUId <- newMVar $ UserID 0 playersVar <- newMVar M.empty networkInChan <- newChan clientSpecificOutChan <- newChan serverChan <- atomically newTChan clientsChan <- newChan internalChan <- newChan let networkChans = (networkInChan, clientSpecificOutChan) server = Server gConfig playersVar networkChans serverChan clientsChan internalChan -- start game server : one game at a time. gameThread <- forkIO $ forever $ do moveAllPlayersToWaiting (serverUsers server) gameEngineThread server Nothing -- start network wsThread <- forkIO $ W.start firstUId networkChans clientsChan tcpThread <- forkIO $ Tcp.start firstUId networkChans clientsChan -- to avoid space msg leak.. -- fixme : move to broadcast tchan forkIO . forever . readChan $ clientSpecificOutChan forkIO . forever . readChan $ clientsChan forkIO . forever . readChan $ internalChan clientsLoop server M.empty killThread gameThread killThread wsThread killThread tcpThread where moveAllPlayersToWaiting serverUsers = modifyMVar_ serverUsers (return . M.map (\u -> u { userState = Waiting })) clientsLoop :: Server -> M.Map UserID (TChan InMessage) -> IO () clientsLoop server@Server{..} userChans = do let (networkInChan, _) = networkChans msg <- readChan networkInChan case msg of PlayerJoined uId -> do userChan <- atomically newTChan let userChans' = M.insert uId userChan userChans -- check if uId already not there void $ forkIO $ runClient uId userChan server -- remove useChan after runClient returns. clientsLoop server userChans' _ -> do let uId = SUtils.getUserId msg userChan = M.lookup uId userChans maybe (return ()) (\c -> atomically $ writeTChan c msg) userChan clientsLoop server userChans runClient :: UserID -> TChan InMessage -> Server -> IO () runClient uId clientChan server@Server{..} = do let (_, clientSpecificOutChan) = networkChans writeChan clientSpecificOutChan $ (uId, ServerMsg "Take a nick name : ") msg <- atomically $ readTChan clientChan let nick = case msg of PlayerName _ name -> Just name _ -> Nothing case nick of Nothing -> runClient uId clientChan server Just _ -> do let user = User uId nick Waiting failedToAdd <- modifyMVar serverUsers $ \users -> -- for player we still have name as id ; so keep it unique. if isNickTaken users nick then return (users, True) else return (M.insert uId user users, False) if failedToAdd then runClient uId clientChan server else do atomically $ writeTChan serverChan $ PlayerJoined uId waitForPlayerReady clientSpecificOutChan nick where isNickTaken users nick = any (\u -> nick == userNick u) users waitForPlayerReady clientSpecificOutChan nick = fix $ \ loop -> do writeChan clientSpecificOutChan $ (uId, ServerMsg $ "Hi.. " ++ T.unpack (fromJust nick) ++ ".. send \"ready\" when you are ready to play..") m <- atomically $ readTChan clientChan case m of PlayerReady _ -> do playClient uId clientChan server exists <- userExistsNow serverUsers when exists $ loop UserExit _ -> onUserExit uId serverUsers _ -> loop userExistsNow users = do currentUsers <- readMVar users return (M.member uId currentUsers) playClient :: UserID -> TChan InMessage -> Server -> IO () playClient clientId inChan Server{..} = do let (_, clientSpecificOutChan) = networkChans clientInternalChan <- dupChan internalChan writeChan clientSpecificOutChan (clientId, ServerMsg "Waiting for other players to start the game...!!!") writeChan clientSpecificOutChan (clientId, PlayerRegisterId clientId) atomically $ writeTChan serverChan $ PlayerReady clientId -- block on ready-signal from server-thread to start the game. signal <- readChan clientInternalChan case signal of GameReadySignal _ _ -> return () writeList2Chan clientSpecificOutChan [ (clientId, ServerMsg "Here.. you go!!!") , (clientId, ServerMsg "Movements: type L for left , R for right, Q for quit... enjoy.") ] -- flush all accumulated messages till now before allowing to play the game. _ <- SUtils.readMsgs inChan fix $ \loop -> do msg <- atomically $ readTChan inChan case msg of PlayerExit _ -> void $ writeChan clientSpecificOutChan (clientId, ServerMsg "Sayonara !!!") UserExit _ -> atomically $ writeTChan serverChan msg _ -> atomically (writeTChan serverChan msg) >> loop atomically $ writeTChan serverChan (PlayerExit clientId) -- Adds user to user list and returns whether all users are ready updateUserReady :: UserID -> M.Map UserID User -> IO (M.Map UserID User, Bool) updateUserReady clientId users = let newUsers = M.adjust (\u -> u { userState = Ready }) clientId users -- We have at least 2 users, and all users are ready ready = length users > 1 && all ((Ready ==) . userState) newUsers in return (newUsers, ready) oneSecond :: Int oneSecond = 1000000 onUserExit :: UserID -> MVar (M.Map UserID User) -> IO () onUserExit clientId serverUsers = modifyMVar_ serverUsers (return . M.delete clientId) processMessages :: Server -> Maybe Game -> [InMessage] -> IO (Maybe Game) processMessages server@Server{..} game inMsgs = do game' <- foldM threadGameOverEvent game inMsgs moveAllDeadPlayersToWaiting game' return game' where threadGameOverEvent g' inMsg = case inMsg of PlayerJoined _ -> return game PlayerReady clientId -> processPlayerReady clientId PlayerTurnLeft clientId -> processEvent' g' TurnLeft clientId PlayerTurnRight clientId -> processEvent' g' TurnRight clientId UserExit clientId -> do onUserExit clientId serverUsers processEvent' g' PlayerQuit clientId PlayerExit clientId -> do processEvent' g' PlayerQuit clientId PlayerName _ _ -> return game processPlayerReady clientId = case game of -- do not disturb already running game. Just game' -> return $ Just game' -- start a new game. Nothing -> do ready <- modifyMVar serverUsers $ updateUserReady clientId -- if all users are ready, start the game. if ready then do users <- readMVar serverUsers players <- SUtils.playersFromUsers serverGameConfig users writeChan internalChan $ GameReadySignal serverGameConfig (M.elems players) writeChan clientsChan $ GameReady serverGameConfig (M.elems players) return $ Just $ Game Nothing players InProgress serverGameConfig else return Nothing processEvent' game' evCons clientId = do let event = evCons . PlayerId . getUserID $ clientId processEvent server game' event moveAllDeadPlayersToWaiting maybeGame = case maybeGame of -- try maybe Nothing -> return () Just g' -> let deadUserIds = map SUtils.playerIdToUserId $ Engine.deadPlayers g' in modifyMVar_ serverUsers $ \users -> return $ L.foldl' (\newUsers deadUId -> M.adjust (\u -> u { userState = Waiting }) deadUId newUsers) users deadUserIds processEvent :: Server -> Maybe Game -> InputEvent -> IO (Maybe Game) processEvent Server{..} g event = do users <- readMVar serverUsers let (outEvs, game') = runGame g event outMsgs = SUtils.outEventToOutMessage users <$> outEvs writeList2Chan clientsChan outMsgs return game' gameEngineThread :: Server -> Maybe Game -> IO Game gameEngineThread server@Server{..} game = do threadDelay . quot oneSecond . gameTicksPerSecond $ serverGameConfig inMsgs <- SUtils.readMsgs serverChan game' <- processMessages server game inMsgs game'' <- processEvent server game' Tick if isGameFinished game'' then return . fromJust $ game'' else gameEngineThread server game'' where isGameFinished g = case g of Nothing -> False Just g' -> Finished == gameStatus g' runGame :: Maybe Game -> InputEvent -> ([OutEvent], Maybe Game) runGame game event = case game of Nothing -> ([], Nothing) Just g -> Just <$> Engine.runEngine Engine.gameEngine g [event]
nilenso/tronkell
src/Tronkell/Server/Server.hs
bsd-3-clause
9,308
0
22
2,356
2,552
1,237
1,315
187
10
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} -- | Resolving a build plan for a set of packages in a given Stackage -- snapshot. module Stack.BuildPlan ( BuildPlanException (..) , MiniBuildPlan(..) , MiniPackageInfo(..) , Snapshots (..) , getSnapshots , loadMiniBuildPlan , resolveBuildPlan , findBuildPlan , ToolMap , getToolMap , shadowMiniBuildPlan , parseCustomMiniBuildPlan ) where import Control.Applicative import Control.Exception (assert) import Control.Monad (liftM, forM) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (asks) import Control.Monad.State.Strict (State, execState, get, modify, put) import Control.Monad.Trans.Control (MonadBaseControl) import qualified Crypto.Hash.SHA256 as SHA256 import Data.Aeson.Extended (FromJSON (..), withObject, withText, (.:), (.:?), (.!=)) import Data.Binary.VersionTagged (taggedDecodeOrLoad) import Data.ByteString (ByteString) import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import Data.Either (partitionEithers) import qualified Data.Foldable as F import qualified Data.HashMap.Strict as HM import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.List (intercalate) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe, mapMaybe) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time (Day) import qualified Data.Traversable as Tr import Data.Typeable (Typeable) import Data.Yaml (decodeEither', decodeFileEither) import Distribution.PackageDescription (GenericPackageDescription, flagDefault, flagManual, flagName, genPackageFlags, executables, exeName, library, libBuildInfo, buildable) import qualified Distribution.Package as C import qualified Distribution.PackageDescription as C import qualified Distribution.Version as C import Distribution.Text (display) import Network.HTTP.Download import Network.HTTP.Types (Status(..)) import Network.HTTP.Client (checkStatus) import Path import Path.IO import Prelude -- Fix AMP warning import Stack.Constants import Stack.Fetch import Stack.GhcPkg import Stack.Package import Stack.PackageIndex import Stack.Types import Stack.Types.StackT import System.Directory (canonicalizePath) import qualified System.FilePath as FP data BuildPlanException = UnknownPackages (Path Abs File) -- stack.yaml file (Map PackageName (Maybe Version, (Set PackageName))) -- truly unknown (Map PackageName (Set PackageIdentifier)) -- shadowed | SnapshotNotFound SnapName deriving (Typeable) instance Exception BuildPlanException instance Show BuildPlanException where show (SnapshotNotFound snapName) = unlines [ "SnapshotNotFound " ++ snapName' , "Non existing resolver: " ++ snapName' ++ "." , "For a complete list of available snapshots see https://www.stackage.org/snapshots" ] where snapName' = show $ renderSnapName snapName show (UnknownPackages stackYaml unknown shadowed) = unlines $ unknown' ++ shadowed' where unknown' :: [String] unknown' | Map.null unknown = [] | otherwise = concat [ ["The following packages do not exist in the build plan:"] , map go (Map.toList unknown) , case mapMaybe goRecommend $ Map.toList unknown of [] -> [] rec -> ("Recommended action: modify the extra-deps field of " ++ toFilePath stackYaml ++ " to include the following:") : (rec ++ ["Note: further dependencies may need to be added"]) , case mapMaybe getNoKnown $ Map.toList unknown of [] -> [] noKnown -> [ "There are no known versions of the following packages:" , intercalate ", " $ map packageNameString noKnown ] ] where go (dep, (_, users)) | Set.null users = packageNameString dep go (dep, (_, users)) = concat [ packageNameString dep , " (used by " , intercalate ", " $ map packageNameString $ Set.toList users , ")" ] goRecommend (name, (Just version, _)) = Just $ "- " ++ packageIdentifierString (PackageIdentifier name version) goRecommend (_, (Nothing, _)) = Nothing getNoKnown (name, (Nothing, _)) = Just name getNoKnown (_, (Just _, _)) = Nothing shadowed' :: [String] shadowed' | Map.null shadowed = [] | otherwise = concat [ ["The following packages are shadowed by local packages:"] , map go (Map.toList shadowed) , ["Recommended action: modify the extra-deps field of " ++ toFilePath stackYaml ++ " to include the following:"] , extraDeps , ["Note: further dependencies may need to be added"] ] where go (dep, users) | Set.null users = concat [ packageNameString dep , " (internal stack error: this should never be null)" ] go (dep, users) = concat [ packageNameString dep , " (used by " , intercalate ", " $ map (packageNameString . packageIdentifierName) $ Set.toList users , ")" ] extraDeps = map (\ident -> "- " ++ packageIdentifierString ident) $ Set.toList $ Set.unions $ Map.elems shadowed -- | Determine the necessary packages to install to have the given set of -- packages available. -- -- This function will not provide test suite and benchmark dependencies. -- -- This may fail if a target package is not present in the @BuildPlan@. resolveBuildPlan :: (MonadThrow m, MonadIO m, MonadReader env m, HasBuildConfig env, MonadLogger m, HasHttpManager env, MonadBaseControl IO m,MonadCatch m) => EnvOverride -> MiniBuildPlan -> (PackageName -> Bool) -- ^ is it shadowed by a local package? -> Map PackageName (Set PackageName) -- ^ required packages, and users of it -> m ( Map PackageName (Version, Map FlagName Bool) , Map PackageName (Set PackageName) ) resolveBuildPlan menv mbp isShadowed packages | Map.null (rsUnknown rs) && Map.null (rsShadowed rs) = return (rsToInstall rs, rsUsedBy rs) | otherwise = do cache <- getPackageCaches menv let maxVer = Map.fromListWith max $ map toTuple $ Map.keys cache unknown = flip Map.mapWithKey (rsUnknown rs) $ \ident x -> (Map.lookup ident maxVer, x) bconfig <- asks getBuildConfig throwM $ UnknownPackages (bcStackYaml bconfig) unknown (rsShadowed rs) where rs = getDeps mbp isShadowed packages data ResolveState = ResolveState { rsVisited :: Map PackageName (Set PackageName) -- ^ set of shadowed dependencies , rsUnknown :: Map PackageName (Set PackageName) , rsShadowed :: Map PackageName (Set PackageIdentifier) , rsToInstall :: Map PackageName (Version, Map FlagName Bool) , rsUsedBy :: Map PackageName (Set PackageName) } toMiniBuildPlan :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m) => Version -- ^ GHC version -> Map PackageName Version -- ^ cores -> Map PackageName (Version, Map FlagName Bool) -- ^ non-core packages -> m MiniBuildPlan toMiniBuildPlan ghcVersion corePackages packages = do $logInfo "Caching build plan" -- Determine the dependencies of all of the packages in the build plan. We -- handle core packages specially, because some of them will not be in the -- package index. For those, we allow missing packages to exist, and then -- remove those from the list of dependencies, since there's no way we'll -- ever reinstall them anyway. (cores, missingCores) <- addDeps True ghcVersion $ fmap (, Map.empty) corePackages (extras, missing) <- addDeps False ghcVersion packages assert (Set.null missing) $ return MiniBuildPlan { mbpGhcVersion = ghcVersion , mbpPackages = Map.unions [ fmap (removeMissingDeps (Map.keysSet cores)) cores , extras , Map.fromList $ map goCore $ Set.toList missingCores ] } where goCore (PackageIdentifier name version) = (name, MiniPackageInfo { mpiVersion = version , mpiFlags = Map.empty , mpiPackageDeps = Set.empty , mpiToolDeps = Set.empty , mpiExes = Set.empty , mpiHasLibrary = True }) removeMissingDeps cores mpi = mpi { mpiPackageDeps = Set.intersection cores (mpiPackageDeps mpi) } -- | Add in the resolved dependencies from the package index addDeps :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m) => Bool -- ^ allow missing -> Version -- ^ GHC version -> Map PackageName (Version, Map FlagName Bool) -> m (Map PackageName MiniPackageInfo, Set PackageIdentifier) addDeps allowMissing ghcVersion toCalc = do menv <- getMinimalEnvOverride platform <- asks $ configPlatform . getConfig (resolvedMap, missingIdents) <- if allowMissing then do (missingNames, missingIdents, m) <- resolvePackagesAllowMissing menv (Map.keysSet idents0) Set.empty assert (Set.null missingNames) $ return (m, missingIdents) else do m <- resolvePackages menv (Map.keysSet idents0) Set.empty return (m, Set.empty) let byIndex = Map.fromListWith (++) $ flip map (Map.toList resolvedMap) $ \(ident, rp) -> (indexName $ rpIndex rp, [( ident , rpCache rp , maybe Map.empty snd $ Map.lookup (packageIdentifierName ident) toCalc )]) res <- forM (Map.toList byIndex) $ \(indexName', pkgs) -> withCabalFiles indexName' pkgs $ \ident flags cabalBS -> do gpd <- readPackageUnresolvedBS Nothing cabalBS let packageConfig = PackageConfig { packageConfigEnableTests = False , packageConfigEnableBenchmarks = False , packageConfigFlags = flags , packageConfigGhcVersion = ghcVersion , packageConfigPlatform = platform } name = packageIdentifierName ident pd = resolvePackageDescription packageConfig gpd exes = Set.fromList $ map (ExeName . S8.pack . exeName) $ executables pd notMe = Set.filter (/= name) . Map.keysSet return (name, MiniPackageInfo { mpiVersion = packageIdentifierVersion ident , mpiFlags = flags , mpiPackageDeps = notMe $ packageDependencies pd , mpiToolDeps = Map.keysSet $ packageToolDependencies pd , mpiExes = exes , mpiHasLibrary = maybe False (buildable . libBuildInfo) (library pd) }) return (Map.fromList $ concat res, missingIdents) where idents0 = Map.fromList $ map (\(n, (v, f)) -> (PackageIdentifier n v, Left f)) $ Map.toList toCalc -- | Resolve all packages necessary to install for getDeps :: MiniBuildPlan -> (PackageName -> Bool) -- ^ is it shadowed by a local package? -> Map PackageName (Set PackageName) -> ResolveState getDeps mbp isShadowed packages = execState (mapM_ (uncurry goName) $ Map.toList packages) ResolveState { rsVisited = Map.empty , rsUnknown = Map.empty , rsShadowed = Map.empty , rsToInstall = Map.empty , rsUsedBy = Map.empty } where toolMap = getToolMap mbp -- | Returns a set of shadowed packages we depend on. goName :: PackageName -> Set PackageName -> State ResolveState (Set PackageName) goName name users = do -- Even though we could check rsVisited first and short-circuit things -- earlier, lookup in mbpPackages first so that we can produce more -- usable error information on missing dependencies rs <- get put rs { rsUsedBy = Map.insertWith Set.union name users $ rsUsedBy rs } case Map.lookup name $ mbpPackages mbp of Nothing -> do modify $ \rs' -> rs' { rsUnknown = Map.insertWith Set.union name users $ rsUnknown rs' } return Set.empty Just mpi -> case Map.lookup name (rsVisited rs) of Just shadowed -> return shadowed Nothing -> do put rs { rsVisited = Map.insert name Set.empty $ rsVisited rs } let depsForTools = Set.unions $ mapMaybe (flip Map.lookup toolMap) (Set.toList $ mpiToolDeps mpi) let deps = Set.filter (/= name) (mpiPackageDeps mpi <> depsForTools) shadowed <- fmap F.fold $ Tr.forM (Set.toList deps) $ \dep -> if isShadowed dep then do modify $ \rs' -> rs' { rsShadowed = Map.insertWith Set.union dep (Set.singleton $ PackageIdentifier name (mpiVersion mpi)) (rsShadowed rs') } return $ Set.singleton dep else do shadowed <- goName dep (Set.singleton name) let m = Map.fromSet (\_ -> Set.singleton $ PackageIdentifier name (mpiVersion mpi)) shadowed modify $ \rs' -> rs' { rsShadowed = Map.unionWith Set.union m $ rsShadowed rs' } return shadowed modify $ \rs' -> rs' { rsToInstall = Map.insert name (mpiVersion mpi, mpiFlags mpi) $ rsToInstall rs' , rsVisited = Map.insert name shadowed $ rsVisited rs' } return shadowed -- | Look up with packages provide which tools. type ToolMap = Map ByteString (Set PackageName) -- | Map from tool name to package providing it getToolMap :: MiniBuildPlan -> Map ByteString (Set PackageName) getToolMap mbp = Map.unionsWith Set.union {- We no longer do this, following discussion at: https://github.com/commercialhaskell/stack/issues/308#issuecomment-112076704 -- First grab all of the package names, for times where a build tool is -- identified by package name $ Map.fromList (map (packageNameByteString &&& Set.singleton) (Map.keys ps)) -} -- And then get all of the explicit executable names $ concatMap goPair (Map.toList ps) where ps = mbpPackages mbp goPair (pname, mpi) = map (flip Map.singleton (Set.singleton pname) . unExeName) $ Set.toList $ mpiExes mpi -- | Download the 'Snapshots' value from stackage.org. getSnapshots :: (MonadThrow m, MonadIO m, MonadReader env m, HasHttpManager env, HasStackRoot env, HasConfig env) => m Snapshots getSnapshots = askLatestSnapshotUrl >>= parseUrl . T.unpack >>= downloadJSON -- | Most recent Nightly and newest LTS version per major release. data Snapshots = Snapshots { snapshotsNightly :: !Day , snapshotsLts :: !(IntMap Int) } deriving Show instance FromJSON Snapshots where parseJSON = withObject "Snapshots" $ \o -> Snapshots <$> (o .: "nightly" >>= parseNightly) <*> (fmap IntMap.unions $ mapM parseLTS $ map snd $ filter (isLTS . fst) $ HM.toList o) where parseNightly t = case parseSnapName t of Left e -> fail $ show e Right (LTS _ _) -> fail "Unexpected LTS value" Right (Nightly d) -> return d isLTS = ("lts-" `T.isPrefixOf`) parseLTS = withText "LTS" $ \t -> case parseSnapName t of Left e -> fail $ show e Right (LTS x y) -> return $ IntMap.singleton x y Right (Nightly _) -> fail "Unexpected nightly value" -- | Load up a 'MiniBuildPlan', preferably from cache loadMiniBuildPlan :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m, MonadCatch m) => SnapName -> m MiniBuildPlan loadMiniBuildPlan name = do path <- configMiniBuildPlanCache name let fp = toFilePath path taggedDecodeOrLoad fp $ liftM buildPlanFixes $ do bp <- loadBuildPlan name toMiniBuildPlan (siGhcVersion $ bpSystemInfo bp) (siCorePackages $ bpSystemInfo bp) (fmap goPP $ bpPackages bp) where goPP pp = ( ppVersion pp , pcFlagOverrides $ ppConstraints pp ) -- | Some hard-coded fixes for build plans, hopefully to be irrelevant over -- time. buildPlanFixes :: MiniBuildPlan -> MiniBuildPlan buildPlanFixes mbp = mbp { mbpPackages = Map.fromList $ map go $ Map.toList $ mbpPackages mbp } where go (name, mpi) = (name, mpi { mpiFlags = goF (packageNameString name) (mpiFlags mpi) }) goF "persistent-sqlite" = Map.insert $(mkFlagName "systemlib") False goF "yaml" = Map.insert $(mkFlagName "system-libyaml") False goF _ = id -- | Load the 'BuildPlan' for the given snapshot. Will load from a local copy -- if available, otherwise downloading from Github. loadBuildPlan :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasStackRoot env) => SnapName -> m BuildPlan loadBuildPlan name = do env <- ask let stackage = getStackRoot env file' <- parseRelFile $ T.unpack file let fp = stackage </> $(mkRelDir "build-plan") </> file' $logDebug $ "Decoding build plan from: " <> T.pack (toFilePath fp) eres <- liftIO $ decodeFileEither $ toFilePath fp case eres of Right bp -> return bp Left e -> do $logDebug $ "Decoding build plan from file failed: " <> T.pack (show e) createTree (parent fp) req <- parseUrl $ T.unpack url $logSticky $ "Downloading " <> renderSnapName name <> " build plan ..." $logDebug $ "Downloading build plan from: " <> url _ <- download req { checkStatus = handle404 } fp $logStickyDone $ "Downloaded " <> renderSnapName name <> " build plan." liftIO (decodeFileEither $ toFilePath fp) >>= either throwM return where file = renderSnapName name <> ".yaml" reponame = case name of LTS _ _ -> "lts-haskell" Nightly _ -> "stackage-nightly" url = rawGithubUrl "fpco" reponame "master" file handle404 (Status 404 _) _ _ = Just $ SomeException $ SnapshotNotFound name handle404 _ _ _ = Nothing -- | Find the set of @FlagName@s necessary to get the given -- @GenericPackageDescription@ to compile against the given @BuildPlan@. Will -- only modify non-manual flags, and will prefer default values for flags. -- Returns @Nothing@ if no combination exists. checkBuildPlan :: (MonadLogger m, MonadThrow m, MonadIO m, MonadReader env m, HasConfig env, MonadCatch m) => Map PackageName Version -- ^ locally available packages -> MiniBuildPlan -> GenericPackageDescription -> m (Either DepErrors (Map PackageName (Map FlagName Bool))) checkBuildPlan locals mbp gpd = do platform <- asks (configPlatform . getConfig) return $ loop platform flagOptions where packages = Map.union locals $ fmap mpiVersion $ mbpPackages mbp loop _ [] = assert False $ Left Map.empty loop platform (flags:rest) | Map.null errs = Right $ if Map.null flags then Map.empty else Map.singleton (packageName pkg) flags | null rest = Left errs | otherwise = loop platform rest where errs = checkDeps (packageName pkg) (packageDeps pkg) packages pkg = resolvePackage pkgConfig gpd pkgConfig = PackageConfig { packageConfigEnableTests = True , packageConfigEnableBenchmarks = True , packageConfigFlags = flags , packageConfigGhcVersion = ghcVersion , packageConfigPlatform = platform } ghcVersion = mbpGhcVersion mbp flagName' = fromCabalFlagName . flagName -- Avoid exponential complexity in flag combinations making us sad pandas. -- See: https://github.com/commercialhaskell/stack/issues/543 maxFlagOptions = 128 flagOptions = take maxFlagOptions $ map Map.fromList $ mapM getOptions $ genPackageFlags gpd getOptions f | flagManual f = [(flagName' f, flagDefault f)] | flagDefault f = [ (flagName' f, True) , (flagName' f, False) ] | otherwise = [ (flagName' f, False) , (flagName' f, True) ] -- | Checks if the given package dependencies can be satisfied by the given set -- of packages. Will fail if a package is either missing or has a version -- outside of the version range. checkDeps :: PackageName -- ^ package using dependencies, for constructing DepErrors -> Map PackageName VersionRange -> Map PackageName Version -> DepErrors checkDeps myName deps packages = Map.unionsWith mappend $ map go $ Map.toList deps where go :: (PackageName, VersionRange) -> DepErrors go (name, range) = case Map.lookup name packages of Nothing -> Map.singleton name DepError { deVersion = Nothing , deNeededBy = Map.singleton myName range } Just v | withinRange v range -> Map.empty | otherwise -> Map.singleton name DepError { deVersion = Just v , deNeededBy = Map.singleton myName range } type DepErrors = Map PackageName DepError data DepError = DepError { deVersion :: !(Maybe Version) , deNeededBy :: !(Map PackageName VersionRange) } instance Monoid DepError where mempty = DepError Nothing Map.empty mappend (DepError a x) (DepError b y) = DepError (maybe a Just b) (Map.unionWith C.intersectVersionRanges x y) -- | Find a snapshot and set of flags that is compatible with the given -- 'GenericPackageDescription'. Returns 'Nothing' if no such snapshot is found. findBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m) => [GenericPackageDescription] -> [SnapName] -> m (Maybe (SnapName, Map PackageName (Map FlagName Bool))) findBuildPlan gpds0 = loop where loop [] = return Nothing loop (name:names') = do mbp <- loadMiniBuildPlan name $logInfo $ "Checking against build plan " <> renderSnapName name res <- mapM (checkBuildPlan localNames mbp) gpds0 case partitionEithers res of ([], flags) -> return $ Just (name, Map.unions flags) (errs, _) -> do $logInfo "" $logInfo "* Build plan did not match your requirements:" displayDepErrors $ Map.unionsWith mappend errs $logInfo "" loop names' localNames = Map.fromList $ map (fromCabalIdent . C.package . C.packageDescription) gpds0 fromCabalIdent (C.PackageIdentifier name version) = (fromCabalPackageName name, fromCabalVersion version) displayDepErrors :: MonadLogger m => DepErrors -> m () displayDepErrors errs = F.forM_ (Map.toList errs) $ \(depName, DepError mversion neededBy) -> do $logInfo $ T.concat [ " " , T.pack $ packageNameString depName , case mversion of Nothing -> " not found" Just version -> T.concat [ " version " , T.pack $ versionString version , " found" ] ] F.forM_ (Map.toList neededBy) $ \(user, range) -> $logInfo $ T.concat [ " - " , T.pack $ packageNameString user , " requires " , T.pack $ display range ] $logInfo "" shadowMiniBuildPlan :: MiniBuildPlan -> Set PackageName -> (MiniBuildPlan, Map PackageName MiniPackageInfo) shadowMiniBuildPlan (MiniBuildPlan ghc pkgs0) shadowed = (MiniBuildPlan ghc $ Map.fromList met, Map.fromList unmet) where pkgs1 = Map.difference pkgs0 $ Map.fromSet (\_ -> ()) shadowed depsMet = flip execState Map.empty $ mapM_ (check Set.empty) (Map.keys pkgs1) check visited name | name `Set.member` visited = error $ "shadowMiniBuildPlan: cycle detected, your MiniBuildPlan is broken: " ++ show (visited, name) | otherwise = do m <- get case Map.lookup name m of Just x -> return x Nothing -> case Map.lookup name pkgs1 of Nothing | name `Set.member` shadowed -> return False -- In this case, we have to assume that we're -- constructing a build plan on a different OS or -- architecture, and therefore different packages -- are being chosen. The common example of this is -- the Win32 package. | otherwise -> return True Just mpi -> do let visited' = Set.insert name visited ress <- mapM (check visited') (Set.toList $ mpiPackageDeps mpi) let res = and ress modify $ \m' -> Map.insert name res m' return res (met, unmet) = partitionEithers $ map toEither $ Map.toList pkgs1 toEither pair@(name, _) = wrapper pair where wrapper = case Map.lookup name depsMet of Just True -> Left Just False -> Right Nothing -> assert False Right parseCustomMiniBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m) => Path Abs File -- ^ stack.yaml file location -> T.Text -> m MiniBuildPlan parseCustomMiniBuildPlan stackYamlFP url0 = do yamlFP <- getYamlFP url0 yamlBS <- liftIO $ S.readFile $ toFilePath yamlFP let yamlHash = S8.unpack $ B16.encode $ SHA256.hash yamlBS binaryFilename <- parseRelFile $ yamlHash ++ ".bin" customPlanDir <- getCustomPlanDir let binaryFP = customPlanDir </> $(mkRelDir "bin") </> binaryFilename taggedDecodeOrLoad (toFilePath binaryFP) $ do cs <- either throwM return $ decodeEither' yamlBS let addFlags :: PackageIdentifier -> (PackageName, (Version, Map FlagName Bool)) addFlags (PackageIdentifier name ver) = (name, (ver, fromMaybe Map.empty $ Map.lookup name $ csFlags cs)) toMiniBuildPlan (csGhcVersion cs) Map.empty (Map.fromList $ map addFlags $ Set.toList $ csPackages cs) where getCustomPlanDir = do root <- asks $ configStackRoot . getConfig return $ root </> $(mkRelDir "custom-plan") -- Get the path to the YAML file getYamlFP url = case parseUrl $ T.unpack url of Just req -> getYamlFPFromReq url req Nothing -> getYamlFPFromFile url getYamlFPFromReq url req = do let hashStr = S8.unpack $ B16.encode $ SHA256.hash $ encodeUtf8 url hashFP <- parseRelFile $ hashStr ++ ".yaml" customPlanDir <- getCustomPlanDir let cacheFP = customPlanDir </> $(mkRelDir "yaml") </> hashFP _ <- download req cacheFP return cacheFP getYamlFPFromFile url = do fp <- liftIO $ canonicalizePath $ toFilePath (parent stackYamlFP) FP.</> T.unpack (fromMaybe url $ T.stripPrefix "file://" url <|> T.stripPrefix "file:" url) parseAbsFile fp data CustomSnapshot = CustomSnapshot { csGhcVersion :: !Version , csPackages :: !(Set PackageIdentifier) , csFlags :: !(Map PackageName (Map FlagName Bool)) } instance FromJSON CustomSnapshot where parseJSON = withObject "CustomSnapshot" $ \o -> CustomSnapshot <$> ((o .: "compiler") >>= (\t -> maybe (fail $ "Invalid compiler: " ++ T.unpack t) return $ do cv <- parseCompilerVersion t case cv of GhcVersion v -> return v)) <*> o .: "packages" <*> o .:? "flags" .!= Map.empty
joozek78/stack
src/Stack/BuildPlan.hs
bsd-3-clause
31,150
388
23
10,565
6,800
3,700
3,100
588
5
module Main where import System.Environment import System.Directory import Data.List import Lib main :: IO () main = getArgs >>= parseArgs parseArgs :: [String] -> IO () parseArgs [] = runDefault parseArgs [path] = processDirectory path parseArgs args = photoProcess args runDefault :: IO () runDefault = do putStrLn "No file specified. Running on directory." currentDirectory <- getCurrentDirectory imagePaths <- getFilesFromDirectory currentDirectory photoProcess imagePaths getFilesFromDirectory :: FilePath -> IO [FilePath] getFilesFromDirectory directory = do filesAndDirectories <- listDirectory directory return (filter fileIsMedia filesAndDirectories) processDirectory :: String -> IO () processDirectory path = do isDirectory <- doesDirectoryExist path if (isDirectory) then do putStrLn "You asked me to work on a directory." files <- getFilesFromDirectory path let relativePaths = map ((path ++ "/") ++) files absolutePaths <- mapM makeAbsolute relativePaths photoProcess absolutePaths else do photoProcess [path]
dominikmayer/photo-process
app/Main.hs
bsd-3-clause
1,091
0
16
199
298
144
154
33
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Y.Buffer where import Control.Lens import Control.Lens.TH import Data.Default import Data.Group import Data.Monoid import qualified Data.Vector as V import qualified Y.String as S data Buffer = Buffer { _text :: S.YiString , _cursorPosition :: S.Position } deriving (Eq, Show) makeLenses ''Buffer instance Default Buffer where def = Buffer "" 0 data BufferUpdate = Composite (V.Vector BufferUpdate) | Insert S.YiString | Delete S.YiString | CursorFromTo S.Position S.Position | Nop deriving (Show, Eq) cursorUp :: Buffer -> BufferUpdate cursorUp (Buffer string cursor) = if y > 0 then CursorFromTo cursor (S.positionForCoords (pred y, 0) string) else Nop where (y, x) = S.coordsOfPosition cursor string instance Monoid BufferUpdate where mempty = Nop mappend x Nop = x mappend Nop x = x mappend (Insert s) (Insert t) = Insert (mappend s t) mappend (Composite xs) (Composite ys) = Composite (mappend xs ys) mappend x y = Composite (V.fromList [x, y]) instance Group BufferUpdate where invert Nop = Nop invert (Insert s) = Delete s invert (Delete s) = Insert s invert (CursorFromTo x y) = CursorFromTo y x invert (Composite xs) = Composite (V.reverse (fmap invert xs)) cursorDown :: Buffer -> BufferUpdate cursorDown (Buffer string cursor) = if y < lineCount then CursorFromTo cursor (S.positionForCoords (succ y, 0) string) else Nop where (y, x) = S.coordsOfPosition cursor string lineCount = S.countNewLines string cursorLeft :: Buffer -> BufferUpdate cursorLeft b | atSof b = Nop cursorLeft (Buffer _ cursor) = CursorFromTo cursor (pred cursor) cursorRight :: Buffer -> BufferUpdate cursorRight b | atEof b = Nop cursorRight (Buffer _ cursor) = CursorFromTo cursor (succ cursor) atSof :: Buffer -> Bool atSof (Buffer _ 0) = True atSof _ = False atEof :: Buffer -> Bool atEof (Buffer string cursor) = cursor == S.fromSize (S.length string)
ethercrow/y
src/Y/Buffer.hs
bsd-3-clause
2,078
0
10
462
753
390
363
61
2
module Parse.Helpers where import Prelude hiding (until) import Control.Applicative ((<$>),(<*>),(<*)) import Control.Monad (guard, join) import Control.Monad.State (State) import Data.Char (isUpper) import qualified Data.Map as Map import qualified Language.GLSL.Parser as GLP import qualified Language.GLSL.Syntax as GLS import Text.Parsec hiding (newline, spaces, State) import Text.Parsec.Indent (indented, runIndent) import qualified Text.Parsec.Token as T import qualified AST.Declaration as Decl import qualified AST.Expression.General as E import qualified AST.Expression.Source as Source import qualified AST.Helpers as Help import qualified AST.Literal as L import qualified AST.Variable as Variable import qualified Reporting.Annotation as A import qualified Reporting.Error.Syntax as Syntax import qualified Reporting.Region as R reserveds :: [String] reserveds = [ "if", "then", "else" , "case", "of" , "let", "in" , "type" , "module", "where" , "import", "as", "hiding", "exposing" , "port", "export", "foreign" , "perform" , "deriving" ] -- ERROR HELP expecting = flip (<?>) -- SETUP type OpTable = Map.Map String (Int, Decl.Assoc) type SourceM = State SourcePos type IParser a = ParsecT String OpTable SourceM a iParse :: IParser a -> String -> Either ParseError a iParse parser source = iParseWithTable "" Map.empty parser source iParseWithTable :: SourceName -> OpTable -> IParser a -> String -> Either ParseError a iParseWithTable sourceName table aParser input = runIndent sourceName $ runParserT aParser table sourceName input -- VARIABLES var :: IParser String var = makeVar (letter <|> char '_') <?> "a name" lowVar :: IParser String lowVar = makeVar lower <?> "a lower case name" capVar :: IParser String capVar = makeVar upper <?> "an upper case name" qualifiedVar :: IParser String qualifiedVar = do vars <- many ((++) <$> capVar <*> string ".") (++) (concat vars) <$> lowVar rLabel :: IParser String rLabel = lowVar innerVarChar :: IParser Char innerVarChar = alphaNum <|> char '_' <|> char '\'' <?> "more letters in this name" makeVar :: IParser Char -> IParser String makeVar firstChar = do variable <- (:) <$> firstChar <*> many innerVarChar if variable `elem` reserveds then fail (Syntax.keyword variable) else return variable reserved :: String -> IParser String reserved word = expecting ("reserved word `" ++ word ++ "`") $ do string word notFollowedBy innerVarChar return word -- INFIX OPERATORS anyOp :: IParser String anyOp = betwixt '`' '`' qualifiedVar <|> symOp <?> "an infix operator like (+)" symOp :: IParser String symOp = do op <- many1 (satisfy Help.isSymbol) guard (op `notElem` [ "=", "..", "->", "--", "|", "\8594", ":" ]) case op of "." -> notFollowedBy lower >> return op _ -> return op -- COMMON SYMBOLS equals :: IParser String equals = string "=" <?> "=" rightArrow :: IParser String rightArrow = string "->" <|> string "\8594" <?> "->" leftArrow :: IParser String leftArrow = string "<-" <?> "<- for a record update" hasType :: IParser String hasType = string ":" <?> "the \"has type\" symbol ':'" commitIf check p = commit <|> try p where commit = try (lookAhead check) >> p -- SEPARATORS spaceySepBy1 :: IParser b -> IParser a -> IParser [a] spaceySepBy1 sep parser = do value <- parser (value:) <$> spaceyPrefixBy sep parser spaceyPrefixBy :: IParser sep -> IParser a -> IParser [a] spaceyPrefixBy sep parser = many (commitIf (whitespace >> sep) (padded sep >> parser)) comma :: IParser Char comma = char ',' <?> "a comma ','" commaSep1 :: IParser a -> IParser [a] commaSep1 = spaceySepBy1 comma commaSep :: IParser a -> IParser [a] commaSep = option [] . commaSep1 semiSep1 :: IParser a -> IParser [a] semiSep1 = spaceySepBy1 (char ';' <?> "a semicolon ';'") pipeSep1 :: IParser a -> IParser [a] pipeSep1 = spaceySepBy1 (char '|' <?> "a vertical bar '|'") consSep1 :: IParser a -> IParser [a] consSep1 = spaceySepBy1 (string "::" <?> "a cons operator '::'") dotSep1 :: IParser a -> IParser [a] dotSep1 p = (:) <$> p <*> many (try (char '.') >> p) spaceSep1 :: IParser a -> IParser [a] spaceSep1 p = (:) <$> p <*> spacePrefix p spacePrefix p = constrainedSpacePrefix p (\_ -> return ()) constrainedSpacePrefix parser constraint = many $ choice [ try (spacing >> lookAhead (oneOf "[({")) >> parser , try (spacing >> parser) ] where spacing = do n <- whitespace constraint n <?> Syntax.whitespace indented -- SURROUNDED BY followedBy a b = do x <- a b return x betwixt :: Char -> Char -> IParser a -> IParser a betwixt a b c = do char a out <- c char b <?> "a closing '" ++ [b] ++ "'" return out surround :: Char -> Char -> String -> IParser a -> IParser a surround a z name p = do char a v <- padded p char z <?> unwords ["a closing", name, show z] return v braces :: IParser a -> IParser a braces = surround '[' ']' "brace" parens :: IParser a -> IParser a parens = surround '(' ')' "paren" brackets :: IParser a -> IParser a brackets = surround '{' '}' "bracket" -- HELPERS FOR EXPRESSIONS getMyPosition :: IParser R.Position getMyPosition = R.fromSourcePos <$> getPosition addLocation :: IParser a -> IParser (A.Located a) addLocation expr = do (start, e, end) <- located expr return (A.at start end e) located :: IParser a -> IParser (R.Position, a, R.Position) located parser = do start <- getMyPosition value <- parser end <- getMyPosition return (start, value, end) accessible :: IParser Source.Expr -> IParser Source.Expr accessible exprParser = do start <- getMyPosition annotatedRootExpr@(A.A _ rootExpr) <- exprParser access <- optionMaybe (try dot <?> "a field access like .name") case access of Nothing -> return annotatedRootExpr Just _ -> accessible $ do v <- var end <- getMyPosition return . A.at start end $ case rootExpr of E.Var (Variable.Raw name@(c:_)) | isUpper c -> E.rawVar (name ++ '.' : v) _ -> E.Access annotatedRootExpr v dot :: IParser () dot = do char '.' notFollowedBy (char '.') -- WHITESPACE padded :: IParser a -> IParser a padded p = do whitespace out <- p whitespace return out spaces :: IParser String spaces = let space = string " " <|> multiComment <?> Syntax.whitespace in concat <$> many1 space forcedWS :: IParser String forcedWS = choice [ (++) <$> spaces <*> (concat <$> many nl_space) , concat <$> many1 nl_space ] where nl_space = try ((++) <$> (concat <$> many1 newline) <*> spaces) -- Just eats whitespace until the next meaningful character. dumbWhitespace :: IParser String dumbWhitespace = concat <$> many (spaces <|> newline) whitespace :: IParser String whitespace = option "" forcedWS freshLine :: IParser [[String]] freshLine = try (many1 newline >> many space_nl) <|> try (many1 space_nl) <?> Syntax.freshLine where space_nl = try $ spaces >> many1 newline newline :: IParser String newline = simpleNewline <|> lineComment <?> Syntax.newline simpleNewline :: IParser String simpleNewline = try (string "\r\n") <|> string "\n" lineComment :: IParser String lineComment = do try (string "--") comment <- anyUntil $ simpleNewline <|> (eof >> return "\n") return ("--" ++ comment) docComment :: IParser String docComment = do try (string "{-|") contents <- closeComment return (init (init contents)) multiComment :: IParser String multiComment = (++) <$> try (string "{-" <* notFollowedBy (string "|")) <*> closeComment closeComment :: IParser String closeComment = anyUntil $ choice $ [ try (string "-}") <?> "the end of a comment -}" , concat <$> sequence [ try (string "{-"), closeComment, closeComment ] ] -- ODD COMBINATORS failure msg = do inp <- getInput setInput ('x':inp) anyToken fail msg until :: IParser a -> IParser b -> IParser b until p end = go where go = end <|> (p >> go) anyUntil :: IParser String -> IParser String anyUntil end = go where go = end <|> (:) <$> anyChar <*> go ignoreUntil :: IParser a -> IParser (Maybe a) ignoreUntil end = go where ignore p = const () <$> p filler = choice [ try (ignore chr) <|> ignore str , ignore multiComment , ignore docComment , ignore anyChar ] go = choice [ Just <$> end , filler `until` choice [ const Nothing <$> eof, newline >> go ] ] onFreshLines :: (a -> b -> b) -> b -> IParser a -> IParser b onFreshLines insert init thing = go init where go values = do optionValue <- ignoreUntil thing case optionValue of Nothing -> return values Just v -> go (insert v values) withSource :: IParser a -> IParser (String, a) withSource p = do start <- getParserState result <- p endPos <- getPosition setParserState start raw <- anyUntilPos endPos return (raw, result) anyUntilPos :: SourcePos -> IParser String anyUntilPos pos = do currentPos <- getPosition if currentPos == pos then return [] else (:) <$> anyChar <*> anyUntilPos pos -- BASIC LANGUAGE LITERALS shader :: IParser (String, L.GLShaderTipe) shader = do try (string "[glsl|") rawSrc <- closeShader id case glSource rawSrc of Left err -> parserFail . show $ err Right tipe -> return (rawSrc, tipe) closeShader :: (String -> a) -> IParser a closeShader builder = choice [ do try (string "|]") return (builder "") , do c <- anyChar closeShader (builder . (c:)) ] glSource :: String -> Either ParseError L.GLShaderTipe glSource src = case GLP.parse src of Left e -> Left e Right (GLS.TranslationUnit decls) -> map extractGLinputs decls |> join |> foldr addGLinput emptyDecls |> Right where (|>) = flip ($) emptyDecls = L.GLShaderTipe Map.empty Map.empty Map.empty addGLinput (qual,tipe,name) glDecls = case qual of GLS.Attribute -> glDecls { L.attribute = Map.insert name tipe $ L.attribute glDecls } GLS.Uniform -> glDecls { L.uniform = Map.insert name tipe $ L.uniform glDecls } GLS.Varying -> glDecls { L.varying = Map.insert name tipe $ L.varying glDecls } _ -> error "Should never happen due to below filter" extractGLinputs decl = case decl of GLS.Declaration (GLS.InitDeclaration (GLS.TypeDeclarator (GLS.FullType (Just (GLS.TypeQualSto qual)) (GLS.TypeSpec _prec (GLS.TypeSpecNoPrecision tipe _mexpr1)))) [GLS.InitDecl name _mexpr2 _mexpr3] ) -> case elem qual [GLS.Attribute, GLS.Varying, GLS.Uniform] of False -> [] True -> case tipe of GLS.Int -> return (qual, L.Int,name) GLS.Float -> return (qual, L.Float,name) GLS.Vec2 -> return (qual, L.V2,name) GLS.Vec3 -> return (qual, L.V3,name) GLS.Vec4 -> return (qual, L.V4,name) GLS.Mat4 -> return (qual, L.M4,name) GLS.Sampler2D -> return (qual, L.Texture,name) _ -> [] _ -> [] str :: IParser String str = expecting "a string" $ do s <- choice [ multiStr, singleStr ] processAs T.stringLiteral . sandwich '\"' $ concat s where rawString quote insides = quote >> manyTill insides quote multiStr = rawString (try (string "\"\"\"")) multilineStringChar singleStr = rawString (char '"') stringChar stringChar :: IParser String stringChar = choice [ newlineChar, escaped '\"', (:[]) <$> satisfy (/= '\"') ] multilineStringChar :: IParser String multilineStringChar = do noEnd choice [ newlineChar, escaped '\"', expandQuote <$> anyChar ] where noEnd = notFollowedBy (string "\"\"\"") expandQuote c = if c == '\"' then "\\\"" else [c] newlineChar :: IParser String newlineChar = choice [ char '\n' >> return "\\n" , char '\r' >> return "\\r" ] sandwich :: Char -> String -> String sandwich delim s = delim : s ++ [delim] escaped :: Char -> IParser String escaped delim = try $ do char '\\' c <- char '\\' <|> char delim return ['\\', c] chr :: IParser Char chr = betwixt '\'' '\'' character <?> "a character" where nonQuote = satisfy (/='\'') character = do c <- choice [ escaped '\'' , (:) <$> char '\\' <*> many1 nonQuote , (:[]) <$> nonQuote ] processAs T.charLiteral $ sandwich '\'' c processAs :: (T.GenTokenParser String u SourceM -> IParser a) -> String -> IParser a processAs processor s = calloutParser s (processor lexer) where calloutParser :: String -> IParser a -> IParser a calloutParser inp p = either (fail . show) return (iParse p inp) lexer :: T.GenTokenParser String u SourceM lexer = T.makeTokenParser elmDef -- I don't know how many of these are necessary for charLiteral/stringLiteral elmDef :: T.GenLanguageDef String u SourceM elmDef = T.LanguageDef { T.commentStart = "{-" , T.commentEnd = "-}" , T.commentLine = "--" , T.nestedComments = True , T.identStart = undefined , T.identLetter = undefined , T.opStart = undefined , T.opLetter = undefined , T.reservedNames = reserveds , T.reservedOpNames = [":", "->", "<-", "|"] , T.caseSensitive = True }
johnpmayer/elm-compiler
src/Parse/Helpers.hs
bsd-3-clause
14,360
0
22
4,121
4,728
2,411
2,317
424
14
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -Wall #-} module Dhall.Import.Types where import Control.Exception (Exception) import Control.Monad.Trans.State.Strict (StateT) import Data.ByteString (ByteString) import Data.CaseInsensitive (CI) import Data.Dynamic import Data.HashMap.Strict (HashMap) import Data.List.NonEmpty (NonEmpty) import Data.Void (Void) import Dhall.Context (Context) import Dhall.Core ( Expr , Import (..) , ReifiedNormalizer (..) , URL ) import Dhall.Map (Map) import Dhall.Parser (Src) import Lens.Family (LensLike') import Prettyprinter (Pretty (..)) #ifdef WITH_HTTP import qualified Dhall.Import.Manager #endif import qualified Data.Text import qualified Dhall.Context import qualified Dhall.Map as Map import qualified Dhall.Substitution -- | A fully \"chained\" import, i.e. if it contains a relative path that path -- is relative to the current directory. If it is a remote import with headers -- those are well-typed (either of type `List { header : Text, value Text}` or -- `List { mapKey : Text, mapValue Text})` and in normal form. These -- invariants are preserved by the API exposed by @Dhall.Import@. newtype Chained = Chained { chainedImport :: Import -- ^ The underlying import } deriving (Eq, Ord) instance Pretty Chained where pretty (Chained import_) = pretty import_ -- | An import that has been fully interpeted newtype ImportSemantics = ImportSemantics { importSemantics :: Expr Void Void -- ^ The fully resolved import, typechecked and beta-normal. } -- | `parent` imports (i.e. depends on) `child` data Depends = Depends { parent :: Chained, child :: Chained } {-| This enables or disables the semantic cache for imports protected by integrity checks -} data SemanticCacheMode = IgnoreSemanticCache | UseSemanticCache deriving (Eq) -- | Shared state for HTTP requests type Manager = #ifdef WITH_HTTP Dhall.Import.Manager.Manager #else () #endif -- | The default HTTP 'Manager' defaultNewManager :: IO Manager defaultNewManager = #ifdef WITH_HTTP Dhall.Import.Manager.defaultNewManager #else pure () #endif -- | HTTP headers type HTTPHeader = (CI ByteString, ByteString) -- | A map of site origin -> HTTP headers type OriginHeaders = HashMap Data.Text.Text [HTTPHeader] {-| Used internally to track whether or not we've already warned the user about caching issues -} data CacheWarning = CacheNotWarned | CacheWarned -- | State threaded throughout the import process data Status = Status { _stack :: NonEmpty Chained -- ^ Stack of `Import`s that we've imported along the way to get to the -- current point , _graph :: [Depends] -- ^ Graph of all the imports visited so far, represented by a list of -- import dependencies. , _cache :: Map Chained ImportSemantics -- ^ Cache of imported expressions with their node id in order to avoid -- importing the same expression twice with different values , _newManager :: IO Manager , _manager :: Maybe Manager -- ^ Used to cache the `Dhall.Import.Manager.Manager` when making multiple -- requests , _loadOriginHeaders :: StateT Status IO OriginHeaders -- ^ Load the origin headers from environment or configuration file. -- After loading once, further evaluations return the cached version. , _remote :: URL -> StateT Status IO Data.Text.Text -- ^ The remote resolver, fetches the content at the given URL. , _substitutions :: Dhall.Substitution.Substitutions Src Void , _normalizer :: Maybe (ReifiedNormalizer Void) , _startingContext :: Context (Expr Src Void) , _semanticCacheMode :: SemanticCacheMode , _cacheWarning :: CacheWarning -- ^ Records whether or not we already warned the user about issues with -- cache directory } -- | Initial `Status`, parameterised over the HTTP 'Manager', -- the origin headers and the remote resolver, -- importing relative to the given root import. emptyStatusWith :: IO Manager -> StateT Status IO OriginHeaders -> (URL -> StateT Status IO Data.Text.Text) -> Import -> Status emptyStatusWith _newManager _loadOriginHeaders _remote rootImport = Status {..} where _stack = pure (Chained rootImport) _graph = [] _cache = Map.empty _manager = Nothing _substitutions = Dhall.Substitution.empty _normalizer = Nothing _startingContext = Dhall.Context.empty _semanticCacheMode = UseSemanticCache _cacheWarning = CacheNotWarned -- | Lens from a `Status` to its `_stack` field stack :: Functor f => LensLike' f Status (NonEmpty Chained) stack k s = fmap (\x -> s { _stack = x }) (k (_stack s)) -- | Lens from a `Status` to its `_graph` field graph :: Functor f => LensLike' f Status [Depends] graph k s = fmap (\x -> s { _graph = x }) (k (_graph s)) -- | Lens from a `Status` to its `_cache` field cache :: Functor f => LensLike' f Status (Map Chained ImportSemantics) cache k s = fmap (\x -> s { _cache = x }) (k (_cache s)) -- | Lens from a `Status` to its `_remote` field remote :: Functor f => LensLike' f Status (URL -> StateT Status IO Data.Text.Text) remote k s = fmap (\x -> s { _remote = x }) (k (_remote s)) -- | Lens from a `Status` to its `_substitutions` field substitutions :: Functor f => LensLike' f Status (Dhall.Substitution.Substitutions Src Void) substitutions k s = fmap (\x -> s { _substitutions = x }) (k (_substitutions s)) -- | Lens from a `Status` to its `_normalizer` field normalizer :: Functor f => LensLike' f Status (Maybe (ReifiedNormalizer Void)) normalizer k s = fmap (\x -> s {_normalizer = x}) (k (_normalizer s)) -- | Lens from a `Status` to its `_startingContext` field startingContext :: Functor f => LensLike' f Status (Context (Expr Src Void)) startingContext k s = fmap (\x -> s { _startingContext = x }) (k (_startingContext s)) -- | Lens from a `Status` to its `_cacheWarning` field cacheWarning :: Functor f => LensLike' f Status CacheWarning cacheWarning k s = fmap (\x -> s { _cacheWarning = x }) (k (_cacheWarning s)) {-| This exception indicates that there was an internal error in Dhall's import-related logic This exception indicates that an invalid `Dhall.Syntax.Type` was provided to the `Dhall.input` function -} data InternalError = InternalError deriving (Typeable) instance Show InternalError where show InternalError = unlines [ _ERROR <> ": Compiler bug " , " " , "Explanation: This error message means that there is a bug in the Dhall compiler." , "You didn't do anything wrong, but if you would like to see this problem fixed " , "then you should report the bug at: " , " " , "https://github.com/dhall-lang/dhall-haskell/issues " , " " , "Please include the following text in your bug report: " , " " , "``` " , "Header extraction failed even though the header type-checked " , "``` " ] where _ERROR :: String _ERROR = "\ESC[1;31mError\ESC[0m" instance Exception InternalError -- | Wrapper around `Network.HTTP.Client.HttpException`s with a prettier `Show` -- instance -- -- In order to keep the library API constant even when the @with-http@ Cabal -- flag is disabled the pretty error message is pre-rendered and the real -- 'Network.HTTP.Client.HttpException' is stored in a 'Dynamic' data PrettyHttpException = PrettyHttpException String Dynamic deriving (Typeable) instance Exception PrettyHttpException instance Show PrettyHttpException where show (PrettyHttpException msg _) = msg
Gabriel439/Haskell-Dhall-Library
dhall/src/Dhall/Import/Types.hs
bsd-3-clause
8,562
0
11
2,464
1,423
818
605
115
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 TcInstDecls: Typechecking instance declarations -} {-# LANGUAGE CPP #-} module TcInstDcls ( tcInstDecls1, tcInstDecls2 ) where #include "HsVersions.h" import HsSyn import TcBinds import TcTyClsDecls import TcClassDcl( tcClassDecl2, HsSigFun, lookupHsSig, mkHsSigFun, findMethodBind, instantiateMethod ) import TcPat ( TcIdSigInfo, addInlinePrags, completeIdSigPolyId, lookupPragEnv, emptyPragEnv ) import TcRnMonad import TcValidity import TcMType import TcType import BuildTyCl import Inst import InstEnv import FamInst import FamInstEnv import TcDeriv import TcEnv import TcHsType import TcUnify import Coercion ( pprCoAxiom {- , isReflCo, mkSymCo, mkSubCo -} ) import MkCore ( nO_METHOD_BINDING_ERROR_ID ) import Type import TcEvidence import TyCon import CoAxiom import DataCon import Class import Var import VarEnv import VarSet import PrelNames ( typeableClassName, genericClassNames ) -- , knownNatClassName, knownSymbolClassName ) import Bag import BasicTypes import DynFlags import ErrUtils import FastString import HscTypes ( isHsBoot ) import Id import MkId import Name import NameSet import Outputable import SrcLoc import Util import BooleanFormula ( isUnsatisfied, pprBooleanFormulaNice ) import Control.Monad import Maybes import Data.List ( mapAccumL, partition ) {- Typechecking instance declarations is done in two passes. The first pass, made by @tcInstDecls1@, collects information to be used in the second pass. This pre-processed info includes the as-yet-unprocessed bindings inside the instance declaration. These are type-checked in the second pass, when the class-instance envs and GVE contain all the info from all the instance and value decls. Indeed that's the reason we need two passes over the instance decls. Note [How instance declarations are translated] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is how we translate instance declarations into Core Running example: class C a where op1, op2 :: Ix b => a -> b -> b op2 = <dm-rhs> instance C a => C [a] {-# INLINE [2] op1 #-} op1 = <rhs> ===> -- Method selectors op1,op2 :: forall a. C a => forall b. Ix b => a -> b -> b op1 = ... op2 = ... -- Default methods get the 'self' dictionary as argument -- so they can call other methods at the same type -- Default methods get the same type as their method selector $dmop2 :: forall a. C a => forall b. Ix b => a -> b -> b $dmop2 = /\a. \(d:C a). /\b. \(d2: Ix b). <dm-rhs> -- NB: type variables 'a' and 'b' are *both* in scope in <dm-rhs> -- Note [Tricky type variable scoping] -- A top-level definition for each instance method -- Here op1_i, op2_i are the "instance method Ids" -- The INLINE pragma comes from the user pragma {-# INLINE [2] op1_i #-} -- From the instance decl bindings op1_i, op2_i :: forall a. C a => forall b. Ix b => [a] -> b -> b op1_i = /\a. \(d:C a). let this :: C [a] this = df_i a d -- Note [Subtle interaction of recursion and overlap] local_op1 :: forall b. Ix b => [a] -> b -> b local_op1 = <rhs> -- Source code; run the type checker on this -- NB: Type variable 'a' (but not 'b') is in scope in <rhs> -- Note [Tricky type variable scoping] in local_op1 a d op2_i = /\a \d:C a. $dmop2 [a] (df_i a d) -- The dictionary function itself {-# NOINLINE CONLIKE df_i #-} -- Never inline dictionary functions df_i :: forall a. C a -> C [a] df_i = /\a. \d:C a. MkC (op1_i a d) (op2_i a d) -- But see Note [Default methods in instances] -- We can't apply the type checker to the default-method call -- Use a RULE to short-circuit applications of the class ops {-# RULE "op1@C[a]" forall a, d:C a. op1 [a] (df_i d) = op1_i a d #-} Note [Instances and loop breakers] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Note that df_i may be mutually recursive with both op1_i and op2_i. It's crucial that df_i is not chosen as the loop breaker, even though op1_i has a (user-specified) INLINE pragma. * Instead the idea is to inline df_i into op1_i, which may then select methods from the MkC record, and thereby break the recursion with df_i, leaving a *self*-recurisve op1_i. (If op1_i doesn't call op at the same type, it won't mention df_i, so there won't be recursion in the first place.) * If op1_i is marked INLINE by the user there's a danger that we won't inline df_i in it, and that in turn means that (since it'll be a loop-breaker because df_i isn't), op1_i will ironically never be inlined. But this is OK: the recursion breaking happens by way of a RULE (the magic ClassOp rule above), and RULES work inside InlineRule unfoldings. See Note [RULEs enabled in SimplGently] in SimplUtils Note [ClassOp/DFun selection] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ One thing we see a lot is stuff like op2 (df d1 d2) where 'op2' is a ClassOp and 'df' is DFun. Now, we could inline *both* 'op2' and 'df' to get case (MkD ($cop1 d1 d2) ($cop2 d1 d2) ... of MkD _ op2 _ _ _ -> op2 And that will reduce to ($cop2 d1 d2) which is what we wanted. But it's tricky to make this work in practice, because it requires us to inline both 'op2' and 'df'. But neither is keen to inline without having seen the other's result; and it's very easy to get code bloat (from the big intermediate) if you inline a bit too much. Instead we use a cunning trick. * We arrange that 'df' and 'op2' NEVER inline. * We arrange that 'df' is ALWAYS defined in the sylised form df d1 d2 = MkD ($cop1 d1 d2) ($cop2 d1 d2) ... * We give 'df' a magical unfolding (DFunUnfolding [$cop1, $cop2, ..]) that lists its methods. * We make CoreUnfold.exprIsConApp_maybe spot a DFunUnfolding and return a suitable constructor application -- inlining df "on the fly" as it were. * ClassOp rules: We give the ClassOp 'op2' a BuiltinRule that extracts the right piece iff its argument satisfies exprIsConApp_maybe. This is done in MkId mkDictSelId * We make 'df' CONLIKE, so that shared uses still match; eg let d = df d1 d2 in ...(op2 d)...(op1 d)... Note [Single-method classes] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If the class has just one method (or, more accurately, just one element of {superclasses + methods}), then we use a different strategy. class C a where op :: a -> a instance C a => C [a] where op = <blah> We translate the class decl into a newtype, which just gives a top-level axiom. The "constructor" MkC expands to a cast, as does the class-op selector. axiom Co:C a :: C a ~ (a->a) op :: forall a. C a -> (a -> a) op a d = d |> (Co:C a) MkC :: forall a. (a->a) -> C a MkC = /\a.\op. op |> (sym Co:C a) The clever RULE stuff doesn't work now, because ($df a d) isn't a constructor application, so exprIsConApp_maybe won't return Just <blah>. Instead, we simply rely on the fact that casts are cheap: $df :: forall a. C a => C [a] {-# INLINE df #-} -- NB: INLINE this $df = /\a. \d. MkC [a] ($cop_list a d) = $cop_list |> forall a. C a -> (sym (Co:C [a])) $cop_list :: forall a. C a => [a] -> [a] $cop_list = <blah> So if we see (op ($df a d)) we'll inline 'op' and '$df', since both are simply casts, and good things happen. Why do we use this different strategy? Because otherwise we end up with non-inlined dictionaries that look like $df = $cop |> blah which adds an extra indirection to every use, which seems stupid. See Trac #4138 for an example (although the regression reported there wasn't due to the indirection). There is an awkward wrinkle though: we want to be very careful when we have instance C a => C [a] where {-# INLINE op #-} op = ... then we'll get an INLINE pragma on $cop_list but it's important that $cop_list only inlines when it's applied to *two* arguments (the dictionary and the list argument). So we must not eta-expand $df above. We ensure that this doesn't happen by putting an INLINE pragma on the dfun itself; after all, it ends up being just a cast. There is one more dark corner to the INLINE story, even more deeply buried. Consider this (Trac #3772): class DeepSeq a => C a where gen :: Int -> a instance C a => C [a] where gen n = ... class DeepSeq a where deepSeq :: a -> b -> b instance DeepSeq a => DeepSeq [a] where {-# INLINE deepSeq #-} deepSeq xs b = foldr deepSeq b xs That gives rise to these defns: $cdeepSeq :: DeepSeq a -> [a] -> b -> b -- User INLINE( 3 args )! $cdeepSeq a (d:DS a) b (x:[a]) (y:b) = ... $fDeepSeq[] :: DeepSeq a -> DeepSeq [a] -- DFun (with auto INLINE pragma) $fDeepSeq[] a d = $cdeepSeq a d |> blah $cp1 a d :: C a => DeepSep [a] -- We don't want to eta-expand this, lest -- $cdeepSeq gets inlined in it! $cp1 a d = $fDeepSep[] a (scsel a d) $fC[] :: C a => C [a] -- Ordinary DFun $fC[] a d = MkC ($cp1 a d) ($cgen a d) Here $cp1 is the code that generates the superclass for C [a]. The issue is this: we must not eta-expand $cp1 either, or else $fDeepSeq[] and then $cdeepSeq will inline there, which is definitely wrong. Like on the dfun, we solve this by adding an INLINE pragma to $cp1. Note [Subtle interaction of recursion and overlap] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this class C a where { op1,op2 :: a -> a } instance C a => C [a] where op1 x = op2 x ++ op2 x op2 x = ... instance C [Int] where ... When type-checking the C [a] instance, we need a C [a] dictionary (for the call of op2). If we look up in the instance environment, we find an overlap. And in *general* the right thing is to complain (see Note [Overlapping instances] in InstEnv). But in *this* case it's wrong to complain, because we just want to delegate to the op2 of this same instance. Why is this justified? Because we generate a (C [a]) constraint in a context in which 'a' cannot be instantiated to anything that matches other overlapping instances, or else we would not be executing this version of op1 in the first place. It might even be a bit disguised: nullFail :: C [a] => [a] -> [a] nullFail x = op2 x ++ op2 x instance C a => C [a] where op1 x = nullFail x Precisely this is used in package 'regex-base', module Context.hs. See the overlapping instances for RegexContext, and the fact that they call 'nullFail' just like the example above. The DoCon package also does the same thing; it shows up in module Fraction.hs. Conclusion: when typechecking the methods in a C [a] instance, we want to treat the 'a' as an *existential* type variable, in the sense described by Note [Binding when looking up instances]. That is why isOverlappableTyVar responds True to an InstSkol, which is the kind of skolem we use in tcInstDecl2. Note [Tricky type variable scoping] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In our example class C a where op1, op2 :: Ix b => a -> b -> b op2 = <dm-rhs> instance C a => C [a] {-# INLINE [2] op1 #-} op1 = <rhs> note that 'a' and 'b' are *both* in scope in <dm-rhs>, but only 'a' is in scope in <rhs>. In particular, we must make sure that 'b' is in scope when typechecking <dm-rhs>. This is achieved by subFunTys, which brings appropriate tyvars into scope. This happens for both <dm-rhs> and for <rhs>, but that doesn't matter: the *renamer* will have complained if 'b' is mentioned in <rhs>. ************************************************************************ * * \subsection{Extracting instance decls} * * ************************************************************************ Gather up the instance declarations from their various sources -} tcInstDecls1 -- Deal with both source-code and imported instance decls :: [TyClGroup Name] -- For deriving stuff -> [LInstDecl Name] -- Source code instance decls -> [LDerivDecl Name] -- Source code stand-alone deriving decls -> TcM (TcGblEnv, -- The full inst env [InstInfo Name], -- Source-code instance decls to process; -- contains all dfuns for this module HsValBinds Name) -- Supporting bindings for derived instances tcInstDecls1 tycl_decls inst_decls deriv_decls = checkNoErrs $ do { -- Stop if addInstInfos etc discovers any errors -- (they recover, so that we get more than one error each -- round) -- Do class and family instance declarations ; stuff <- mapAndRecoverM tcLocalInstDecl inst_decls ; let (local_infos_s, fam_insts_s, datafam_deriv_infos) = unzip3 stuff fam_insts = concat fam_insts_s local_infos' = concat local_infos_s -- Handwritten instances of the poly-kinded Typeable class are -- forbidden, so we handle those separately (typeable_instances, local_infos) = partition bad_typeable_instance local_infos' ; addClsInsts local_infos $ addFamInsts fam_insts $ do { -- Compute instances from "deriving" clauses; -- This stuff computes a context for the derived instance -- decl, so it needs to know about all the instances possible -- NB: class instance declarations can contain derivings as -- part of associated data type declarations failIfErrsM -- If the addInsts stuff gave any errors, don't -- try the deriving stuff, because that may give -- more errors still ; traceTc "tcDeriving" Outputable.empty ; th_stage <- getStage -- See Note [Deriving inside TH brackets ] ; (gbl_env, deriv_inst_info, deriv_binds) <- if isBrackStage th_stage then do { gbl_env <- getGblEnv ; return (gbl_env, emptyBag, emptyValBindsOut) } else do { data_deriv_infos <- mkDerivInfos tycl_decls ; let deriv_infos = concat datafam_deriv_infos ++ data_deriv_infos ; tcDeriving deriv_infos deriv_decls } -- Fail if there are any handwritten instance of poly-kinded Typeable ; mapM_ typeable_err typeable_instances -- Check that if the module is compiled with -XSafe, there are no -- hand written instances of old Typeable as then unsafe casts could be -- performed. Derived instances are OK. ; dflags <- getDynFlags ; when (safeLanguageOn dflags) $ forM_ local_infos $ \x -> case x of _ | genInstCheck x -> addErrAt (getSrcSpan $ iSpec x) (genInstErr x) _ -> return () -- As above but for Safe Inference mode. ; when (safeInferOn dflags) $ forM_ local_infos $ \x -> case x of _ | genInstCheck x -> recordUnsafeInfer emptyBag _ -> return () ; return ( gbl_env , bagToList deriv_inst_info ++ local_infos , deriv_binds ) }} where -- Separate the Typeable instances from the rest bad_typeable_instance i = typeableClassName == is_cls_nm (iSpec i) -- Check for hand-written Generic instances (disallowed in Safe Haskell) genInstCheck ty = is_cls_nm (iSpec ty) `elem` genericClassNames genInstErr i = hang (ptext (sLit $ "Generic instances can only be " ++ "derived in Safe Haskell.") $+$ ptext (sLit "Replace the following instance:")) 2 (pprInstanceHdr (iSpec i)) -- Report an error or a warning for a `Typeable` instances. -- If we are working on an .hs-boot file, we just report a warning, -- and ignore the instance. We do this, to give users a chance to fix -- their code. typeable_err i = setSrcSpan (getSrcSpan (iSpec i)) $ do env <- getGblEnv if isHsBoot (tcg_src env) then do warn <- woptM Opt_WarnDerivingTypeable when warn $ addWarnTc $ vcat [ ptext (sLit "`Typeable` instances in .hs-boot files are ignored.") , ptext (sLit "This warning will become an error in future versions of the compiler.") ] else addErrTc $ ptext (sLit "Class `Typeable` does not support user-specified instances.") addClsInsts :: [InstInfo Name] -> TcM a -> TcM a addClsInsts infos thing_inside = tcExtendLocalInstEnv (map iSpec infos) thing_inside addFamInsts :: [FamInst] -> TcM a -> TcM a -- Extend (a) the family instance envt -- (b) the type envt with stuff from data type decls addFamInsts fam_insts thing_inside = tcExtendLocalFamInstEnv fam_insts $ tcExtendGlobalEnv things $ do { traceTc "addFamInsts" (pprFamInsts fam_insts) ; tcg_env <- tcAddImplicits things ; setGblEnv tcg_env thing_inside } where axioms = map (toBranchedAxiom . famInstAxiom) fam_insts tycons = famInstsRepTyCons fam_insts things = map ATyCon tycons ++ map ACoAxiom axioms {- Note [Deriving inside TH brackets] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Given a declaration bracket [d| data T = A | B deriving( Show ) |] there is really no point in generating the derived code for deriving( Show) and then type-checking it. This will happen at the call site anyway, and the type check should never fail! Moreover (Trac #6005) the scoping of the generated code inside the bracket does not seem to work out. The easy solution is simply not to generate the derived instances at all. (A less brutal solution would be to generate them with no bindings.) This will become moot when we shift to the new TH plan, so the brutal solution will do. -} tcLocalInstDecl :: LInstDecl Name -> TcM ([InstInfo Name], [FamInst], [DerivInfo]) -- A source-file instance declaration -- Type-check all the stuff before the "where" -- -- We check for respectable instance type, and context tcLocalInstDecl (L loc (TyFamInstD { tfid_inst = decl })) = do { fam_inst <- tcTyFamInstDecl Nothing (L loc decl) ; return ([], [fam_inst], []) } tcLocalInstDecl (L loc (DataFamInstD { dfid_inst = decl })) = do { (fam_inst, m_deriv_info) <- tcDataFamInstDecl Nothing (L loc decl) ; return ([], [fam_inst], maybeToList m_deriv_info) } tcLocalInstDecl (L loc (ClsInstD { cid_inst = decl })) = do { (insts, fam_insts, deriv_infos) <- tcClsInstDecl (L loc decl) ; return (insts, fam_insts, deriv_infos) } tcClsInstDecl :: LClsInstDecl Name -> TcM ([InstInfo Name], [FamInst], [DerivInfo]) -- the returned DerivInfos are for any associated data families tcClsInstDecl (L loc (ClsInstDecl { cid_poly_ty = poly_ty, cid_binds = binds , cid_sigs = uprags, cid_tyfam_insts = ats , cid_overlap_mode = overlap_mode , cid_datafam_insts = adts })) = setSrcSpan loc $ addErrCtxt (instDeclCtxt1 poly_ty) $ do { is_boot <- tcIsHsBootOrSig ; checkTc (not is_boot || (isEmptyLHsBinds binds && null uprags)) badBootDeclErr ; (tyvars, theta, clas, inst_tys) <- tcHsInstHead InstDeclCtxt poly_ty ; let mini_env = mkVarEnv (classTyVars clas `zip` inst_tys) mini_subst = mkTvSubst (mkInScopeSet (mkVarSet tyvars)) mini_env mb_info = Just (clas, mini_env) -- Next, process any associated types. ; traceTc "tcLocalInstDecl" (ppr poly_ty) ; tyfam_insts0 <- tcExtendTyVarEnv tyvars $ mapAndRecoverM (tcTyFamInstDecl mb_info) ats ; datafam_stuff <- tcExtendTyVarEnv tyvars $ mapAndRecoverM (tcDataFamInstDecl mb_info) adts ; let (datafam_insts, m_deriv_infos) = unzip datafam_stuff deriv_infos = catMaybes m_deriv_infos -- Check for missing associated types and build them -- from their defaults (if available) ; let defined_ats = mkNameSet (map (tyFamInstDeclName . unLoc) ats) `unionNameSet` mkNameSet (map (unLoc . dfid_tycon . unLoc) adts) ; tyfam_insts1 <- mapM (tcATDefault loc mini_subst defined_ats) (classATItems clas) -- Finally, construct the Core representation of the instance. -- (This no longer includes the associated types.) ; dfun_name <- newDFunName clas inst_tys (getLoc poly_ty) -- Dfun location is that of instance *header* ; ispec <- newClsInst (fmap unLoc overlap_mode) dfun_name tyvars theta clas inst_tys ; let inst_info = InstInfo { iSpec = ispec , iBinds = InstBindings { ib_binds = binds , ib_tyvars = map Var.varName tyvars -- Scope over bindings , ib_pragmas = uprags , ib_extensions = [] , ib_derived = False } } ; return ( [inst_info], tyfam_insts0 ++ concat tyfam_insts1 ++ datafam_insts , deriv_infos ) } tcATDefault :: SrcSpan -> TvSubst -> NameSet -> ClassATItem -> TcM [FamInst] -- ^ Construct default instances for any associated types that -- aren't given a user definition -- Returns [] or singleton tcATDefault loc inst_subst defined_ats (ATI fam_tc defs) -- User supplied instances ==> everything is OK | tyConName fam_tc `elemNameSet` defined_ats = return [] -- No user instance, have defaults ==> instatiate them -- Example: class C a where { type F a b :: *; type F a b = () } -- instance C [x] -- Then we want to generate the decl: type F [x] b = () | Just (rhs_ty, _loc) <- defs = do { let (subst', pat_tys') = mapAccumL subst_tv inst_subst (tyConTyVars fam_tc) rhs' = substTy subst' rhs_ty tv_set' = tyVarsOfTypes pat_tys' tvs' = varSetElemsKvsFirst tv_set' ; rep_tc_name <- newFamInstTyConName (L loc (tyConName fam_tc)) pat_tys' ; let axiom = mkSingleCoAxiom Nominal rep_tc_name tvs' fam_tc pat_tys' rhs' -- NB: no validity check. We check validity of default instances -- in the class definition. Because type instance arguments cannot -- be type family applications and cannot be polytypes, the -- validity check is redundant. ; traceTc "mk_deflt_at_instance" (vcat [ ppr fam_tc, ppr rhs_ty , pprCoAxiom axiom ]) ; fam_inst <- ASSERT( tyVarsOfType rhs' `subVarSet` tv_set' ) newFamInst SynFamilyInst axiom ; return [fam_inst] } -- No defaults ==> generate a warning | otherwise -- defs = Nothing = do { warnMissingMethodOrAT "associated type" (tyConName fam_tc) ; return [] } where subst_tv subst tc_tv | Just ty <- lookupVarEnv (getTvSubstEnv subst) tc_tv = (subst, ty) | otherwise = (extendTvSubst subst tc_tv ty', ty') where ty' = mkTyVarTy (updateTyVarKind (substTy subst) tc_tv) {- ************************************************************************ * * Type checking family instances * * ************************************************************************ Family instances are somewhat of a hybrid. They are processed together with class instance heads, but can contain data constructors and hence they share a lot of kinding and type checking code with ordinary algebraic data types (and GADTs). -} tcFamInstDeclCombined :: Maybe ClsInfo -> Located Name -> TcM TyCon tcFamInstDeclCombined mb_clsinfo fam_tc_lname = do { -- Type family instances require -XTypeFamilies -- and can't (currently) be in an hs-boot file ; traceTc "tcFamInstDecl" (ppr fam_tc_lname) ; type_families <- xoptM Opt_TypeFamilies ; is_boot <- tcIsHsBootOrSig -- Are we compiling an hs-boot file? ; checkTc type_families $ badFamInstDecl fam_tc_lname ; checkTc (not is_boot) $ badBootFamInstDeclErr -- Look up the family TyCon and check for validity including -- check that toplevel type instances are not for associated types. ; fam_tc <- tcLookupLocatedTyCon fam_tc_lname ; when (isNothing mb_clsinfo && -- Not in a class decl isTyConAssoc fam_tc) -- but an associated type (addErr $ assocInClassErr fam_tc_lname) ; return fam_tc } tcTyFamInstDecl :: Maybe ClsInfo -> LTyFamInstDecl Name -> TcM FamInst -- "type instance" tcTyFamInstDecl mb_clsinfo (L loc decl@(TyFamInstDecl { tfid_eqn = eqn })) = setSrcSpan loc $ tcAddTyFamInstCtxt decl $ do { let fam_lname = tfe_tycon (unLoc eqn) ; fam_tc <- tcFamInstDeclCombined mb_clsinfo fam_lname -- (0) Check it's an open type family ; checkTc (isFamilyTyCon fam_tc) (notFamily fam_tc) ; checkTc (isTypeFamilyTyCon fam_tc) (wrongKindOfFamily fam_tc) ; checkTc (isOpenTypeFamilyTyCon fam_tc) (notOpenFamily fam_tc) -- (1) do the work of verifying the synonym group ; co_ax_branch <- tcTyFamInstEqn (famTyConShape fam_tc) mb_clsinfo eqn -- (2) check for validity ; checkValidCoAxBranch mb_clsinfo fam_tc co_ax_branch -- (3) construct coercion axiom ; rep_tc_name <- newFamInstAxiomName loc (unLoc fam_lname) [co_ax_branch] ; let axiom = mkUnbranchedCoAxiom rep_tc_name fam_tc co_ax_branch ; newFamInst SynFamilyInst axiom } tcDataFamInstDecl :: Maybe ClsInfo -> LDataFamInstDecl Name -> TcM (FamInst, Maybe DerivInfo) -- "newtype instance" and "data instance" tcDataFamInstDecl mb_clsinfo (L loc decl@(DataFamInstDecl { dfid_pats = pats , dfid_tycon = fam_tc_name , dfid_defn = defn@HsDataDefn { dd_ND = new_or_data, dd_cType = cType , dd_ctxt = ctxt, dd_cons = cons , dd_derivs = derivs } })) = setSrcSpan loc $ tcAddDataFamInstCtxt decl $ do { fam_tc <- tcFamInstDeclCombined mb_clsinfo fam_tc_name -- Check that the family declaration is for the right kind ; checkTc (isFamilyTyCon fam_tc) (notFamily fam_tc) ; checkTc (isAlgTyCon fam_tc) (wrongKindOfFamily fam_tc) -- Kind check type patterns ; tcFamTyPats (famTyConShape fam_tc) mb_clsinfo pats (kcDataDefn defn) $ \tvs' pats' res_kind -> do { -- Check that left-hand side contains no type family applications -- (vanilla synonyms are fine, though, and we checked for -- foralls earlier) checkValidFamPats fam_tc tvs' pats' -- Check that type patterns match class instance head, if any ; checkConsistentFamInst mb_clsinfo fam_tc tvs' pats' -- Result kind must be '*' (otherwise, we have too few patterns) ; checkTc (isLiftedTypeKind res_kind) $ tooFewParmsErr (tyConArity fam_tc) ; stupid_theta <- tcHsContext ctxt ; gadt_syntax <- dataDeclChecks (tyConName fam_tc) new_or_data stupid_theta cons -- Construct representation tycon ; rep_tc_name <- newFamInstTyConName fam_tc_name pats' ; axiom_name <- newImplicitBinder rep_tc_name mkInstTyCoOcc ; let orig_res_ty = mkTyConApp fam_tc pats' ; (rep_tc, fam_inst) <- fixM $ \ ~(rec_rep_tc, _) -> do { data_cons <- tcConDecls new_or_data rec_rep_tc (tvs', orig_res_ty) cons ; tc_rhs <- case new_or_data of DataType -> return (mkDataTyConRhs data_cons) NewType -> ASSERT( not (null data_cons) ) mkNewTyConRhs rep_tc_name rec_rep_tc (head data_cons) -- freshen tyvars ; let (eta_tvs, eta_pats) = eta_reduce tvs' pats' axiom = mkSingleCoAxiom Representational axiom_name eta_tvs fam_tc eta_pats (mkTyConApp rep_tc (mkTyVarTys eta_tvs)) parent = FamInstTyCon axiom fam_tc pats' roles = map (const Nominal) tvs' -- NB: Use the tvs' from the pats. See bullet toward -- the end of Note [Data type families] in TyCon rep_tc = buildAlgTyCon rep_tc_name tvs' roles (fmap unLoc cType) stupid_theta tc_rhs Recursive False -- No promotable to the kind level gadt_syntax parent -- We always assume that indexed types are recursive. Why? -- (1) Due to their open nature, we can never be sure that a -- further instance might not introduce a new recursive -- dependency. (2) They are always valid loop breakers as -- they involve a coercion. ; fam_inst <- newFamInst (DataFamilyInst rep_tc) axiom ; return (rep_tc, fam_inst) } -- Remember to check validity; no recursion to worry about here ; checkValidTyCon rep_tc ; let m_deriv_info = case derivs of Nothing -> Nothing Just (L _ preds) -> Just $ DerivInfo { di_rep_tc = rep_tc , di_preds = preds , di_ctxt = tcMkDataFamInstCtxt decl } ; return (fam_inst, m_deriv_info) } } where -- See Note [Eta reduction for data family axioms] -- [a,b,c,d].T [a] c Int c d ==> [a,b,c]. T [a] c Int c eta_reduce tvs pats = go (reverse tvs) (reverse pats) go (tv:tvs) (pat:pats) | Just tv' <- getTyVar_maybe pat , tv == tv' , not (tv `elemVarSet` tyVarsOfTypes pats) = go tvs pats go tvs pats = (reverse tvs, reverse pats) {- Note [Eta reduction for data family axioms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this data family T a b :: * newtype instance T Int a = MkT (IO a) deriving( Monad ) We'd like this to work. From the 'newtype instance' you might think we'd get: newtype TInt a = MkT (IO a) axiom ax1 a :: T Int a ~ TInt a -- The type-instance part axiom ax2 a :: TInt a ~ IO a -- The newtype part But now what can we do? We have this problem Given: d :: Monad IO Wanted: d' :: Monad (T Int) = d |> ???? What coercion can we use for the ??? Solution: eta-reduce both axioms, thus: axiom ax1 :: T Int ~ TInt axiom ax2 :: TInt ~ IO Now d' = d |> Monad (sym (ax2 ; ax1)) This eta reduction happens both for data instances and newtype instances. See Note [Newtype eta] in TyCon. ************************************************************************ * * Type-checking instance declarations, pass 2 * * ************************************************************************ -} tcInstDecls2 :: [LTyClDecl Name] -> [InstInfo Name] -> TcM (LHsBinds Id) -- (a) From each class declaration, -- generate any default-method bindings -- (b) From each instance decl -- generate the dfun binding tcInstDecls2 tycl_decls inst_decls = do { -- (a) Default methods from class decls let class_decls = filter (isClassDecl . unLoc) tycl_decls ; dm_binds_s <- mapM tcClassDecl2 class_decls ; let dm_binds = unionManyBags dm_binds_s -- (b) instance declarations ; let dm_ids = collectHsBindsBinders dm_binds -- Add the default method Ids (again) -- See Note [Default methods and instances] ; inst_binds_s <- tcExtendLetEnv TopLevel dm_ids $ mapM tcInstDecl2 inst_decls -- Done ; return (dm_binds `unionBags` unionManyBags inst_binds_s) } {- See Note [Default methods and instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The default method Ids are already in the type environment (see Note [Default method Ids and Template Haskell] in TcTyClsDcls), BUT they don't have their InlinePragmas yet. Usually that would not matter, because the simplifier propagates information from binding site to use. But, unusually, when compiling instance decls we *copy* the INLINE pragma from the default method to the method for that particular operation (see Note [INLINE and default methods] below). So right here in tcInstDecls2 we must re-extend the type envt with the default method Ids replete with their INLINE pragmas. Urk. -} tcInstDecl2 :: InstInfo Name -> TcM (LHsBinds Id) -- Returns a binding for the dfun tcInstDecl2 (InstInfo { iSpec = ispec, iBinds = ibinds }) = recoverM (return emptyLHsBinds) $ setSrcSpan loc $ addErrCtxt (instDeclCtxt2 (idType dfun_id)) $ do { -- Instantiate the instance decl with skolem constants ; (inst_tyvars, dfun_theta, inst_head) <- tcSkolDFunType (idType dfun_id) ; dfun_ev_vars <- newEvVars dfun_theta -- We instantiate the dfun_id with superSkolems. -- See Note [Subtle interaction of recursion and overlap] -- and Note [Binding when looking up instances] ; let (clas, inst_tys) = tcSplitDFunHead inst_head (class_tyvars, sc_theta, _, op_items) = classBigSig clas sc_theta' = substTheta (zipOpenTvSubst class_tyvars inst_tys) sc_theta ; traceTc "tcInstDecl2" (vcat [ppr inst_tyvars, ppr inst_tys, ppr dfun_theta, ppr sc_theta']) -- Deal with 'SPECIALISE instance' pragmas -- See Note [SPECIALISE instance pragmas] ; spec_inst_info@(spec_inst_prags,_) <- tcSpecInstPrags dfun_id ibinds -- Typecheck superclasses and methods -- See Note [Typechecking plan for instance declarations] ; dfun_ev_binds_var <- newTcEvBinds ; let dfun_ev_binds = TcEvBinds dfun_ev_binds_var ; ((sc_meth_ids, sc_meth_binds, sc_meth_implics), tclvl) <- pushTcLevelM $ do { fam_envs <- tcGetFamInstEnvs ; (sc_ids, sc_binds, sc_implics) <- tcSuperClasses dfun_id clas inst_tyvars dfun_ev_vars inst_tys dfun_ev_binds fam_envs sc_theta' -- Typecheck the methods ; (meth_ids, meth_binds, meth_implics) <- tcMethods dfun_id clas inst_tyvars dfun_ev_vars inst_tys dfun_ev_binds spec_inst_info op_items ibinds ; return ( sc_ids ++ meth_ids , sc_binds `unionBags` meth_binds , sc_implics `unionBags` meth_implics ) } ; env <- getLclEnv ; emitImplication $ Implic { ic_tclvl = tclvl , ic_skols = inst_tyvars , ic_no_eqs = False , ic_given = dfun_ev_vars , ic_wanted = addImplics emptyWC sc_meth_implics , ic_status = IC_Unsolved , ic_binds = dfun_ev_binds_var , ic_env = env , ic_info = InstSkol } -- Create the result bindings ; self_dict <- newDict clas inst_tys ; let class_tc = classTyCon clas [dict_constr] = tyConDataCons class_tc dict_bind = mkVarBind self_dict (L loc con_app_args) -- We don't produce a binding for the dict_constr; instead we -- rely on the simplifier to unfold this saturated application -- We do this rather than generate an HsCon directly, because -- it means that the special cases (e.g. dictionary with only one -- member) are dealt with by the common MkId.mkDataConWrapId -- code rather than needing to be repeated here. -- con_app_tys = MkD ty1 ty2 -- con_app_scs = MkD ty1 ty2 sc1 sc2 -- con_app_args = MkD ty1 ty2 sc1 sc2 op1 op2 con_app_tys = wrapId (mkWpTyApps inst_tys) (dataConWrapId dict_constr) con_app_args = foldl app_to_meth con_app_tys sc_meth_ids app_to_meth :: HsExpr Id -> Id -> HsExpr Id app_to_meth fun meth_id = L loc fun `HsApp` L loc (wrapId arg_wrapper meth_id) inst_tv_tys = mkTyVarTys inst_tyvars arg_wrapper = mkWpEvVarApps dfun_ev_vars <.> mkWpTyApps inst_tv_tys -- Do not inline the dfun; instead give it a magic DFunFunfolding dfun_spec_prags | isNewTyCon class_tc = SpecPrags [] -- Newtype dfuns just inline unconditionally, -- so don't attempt to specialise them | otherwise = SpecPrags spec_inst_prags export = ABE { abe_wrap = idHsWrapper, abe_poly = dfun_id , abe_mono = self_dict, abe_prags = dfun_spec_prags } -- NB: see Note [SPECIALISE instance pragmas] main_bind = AbsBinds { abs_tvs = inst_tyvars , abs_ev_vars = dfun_ev_vars , abs_exports = [export] , abs_ev_binds = [] , abs_binds = unitBag dict_bind } ; return (unitBag (L loc main_bind) `unionBags` sc_meth_binds) } where dfun_id = instanceDFunId ispec loc = getSrcSpan dfun_id wrapId :: HsWrapper -> id -> HsExpr id wrapId wrapper id = mkHsWrap wrapper (HsVar id) {- Note [Typechecking plan for instance declarations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For intance declarations we generate the following bindings and implication constraints. Example: instance Ord a => Ord [a] where compare = <compare-rhs> generates this: Bindings: -- Method bindings $ccompare :: forall a. Ord a => a -> a -> Ordering $ccompare = /\a \(d:Ord a). let <meth-ev-binds> in ... -- Superclass bindings $cp1Ord :: forall a. Ord a => Eq [a] $cp1Ord = /\a \(d:Ord a). let <sc-ev-binds> in dfEqList (dw :: Eq a) Constraints: forall a. Ord a => -- Method constraint (forall. (empty) => <constraints from compare-rhs>) -- Superclass constraint /\ (forall. (empty) => dw :: Eq a) Notice that * Per-meth/sc implication. There is one inner implication per superclass or method, with no skolem variables or givens. The only reason for this one is to gather the evidence bindings privately for this superclass or method. This implication is generated by checkInstConstraints. * Overall instance implication. There is an overall enclosing implication for the whole instance declaratation, with the expected skolems and givens. We need this to get the correct "redundant constraint" warnings, gathering all the uses from all the methods and superclasses. See TcSimplify Note [Tracking redundant constraints] * The given constraints in the outer implication may generate evidence, notably by superclass selection. Since the method and superclass bindings are top-level, we want that evidence copied into *every* method or superclass definition. (Some of it will be usused in some, but dead-code elimination will drop it.) We achieve this by putting the the evidence variable for the overall instance implicaiton into the AbsBinds for each method/superclass. Hence the 'dfun_ev_binds' passed into tcMethods and tcSuperClasses. (And that in turn is why the abs_ev_binds field of AbBinds is a [TcEvBinds] rather than simply TcEvBinds. This is a bit of a hack, but works very nicely in practice. * Note that if a method has a locally-polymorphic binding, there will be yet another implication for that, generated by tcPolyCheck in tcMethodBody. E.g. class C a where foo :: forall b. Ord b => blah ************************************************************************ * * Type-checking superclases * * ************************************************************************ -} tcSuperClasses :: DFunId -> Class -> [TcTyVar] -> [EvVar] -> [TcType] -> TcEvBinds -> FamInstEnvs -> TcThetaType -> TcM ([EvVar], LHsBinds Id, Bag Implication) -- Make a new top-level function binding for each superclass, -- something like -- $Ordp1 :: forall a. Ord a => Eq [a] -- $Ordp1 = /\a \(d:Ord a). dfunEqList a (sc_sel d) -- -- See Note [Recursive superclasses] for why this is so hard! -- In effect, be build a special-purpose solver for the first step -- of solving each superclass constraint tcSuperClasses dfun_id cls tyvars dfun_evs inst_tys dfun_ev_binds _fam_envs sc_theta = do { (ids, binds, implics) <- mapAndUnzip3M tc_super (zip sc_theta [fIRST_TAG..]) ; return (ids, listToBag binds, listToBag implics) } where loc = getSrcSpan dfun_id size = sizeTypes inst_tys tc_super (sc_pred, n) = do { (sc_implic, sc_ev_id) <- checkInstConstraints $ \_ -> emitWanted (ScOrigin size) sc_pred ; sc_top_name <- newName (mkSuperDictAuxOcc n (getOccName cls)) ; let sc_top_ty = mkForAllTys tyvars (mkPiTypes dfun_evs sc_pred) sc_top_id = mkLocalId sc_top_name sc_top_ty export = ABE { abe_wrap = idHsWrapper, abe_poly = sc_top_id , abe_mono = sc_ev_id , abe_prags = SpecPrags [] } local_ev_binds = TcEvBinds (ic_binds sc_implic) bind = AbsBinds { abs_tvs = tyvars , abs_ev_vars = dfun_evs , abs_exports = [export] , abs_ev_binds = [dfun_ev_binds, local_ev_binds] , abs_binds = emptyBag } ; return (sc_top_id, L loc bind, sc_implic) } ------------------- checkInstConstraints :: (EvBindsVar -> TcM result) -> TcM (Implication, result) -- See Note [Typechecking plan for instance declarations] -- The thing_inside is also passed the EvBindsVar, -- so that emit_sc_pred can add evidence for the superclass -- (not used for methods) checkInstConstraints thing_inside = do { ev_binds_var <- newTcEvBinds ; env <- getLclEnv ; (result, tclvl, wanted) <- pushLevelAndCaptureConstraints $ thing_inside ev_binds_var ; let implic = Implic { ic_tclvl = tclvl , ic_skols = [] , ic_no_eqs = False , ic_given = [] , ic_wanted = wanted , ic_status = IC_Unsolved , ic_binds = ev_binds_var , ic_env = env , ic_info = InstSkol } ; return (implic, result) } {- Note [Recursive superclasses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See Trac #3731, #4809, #5751, #5913, #6117, #6161, which all describe somewhat more complicated situations, but ones encountered in practice. See also tests tcrun020, tcrun021, tcrun033 ----- THE PROBLEM -------- The problem is that it is all too easy to create a class whose superclass is bottom when it should not be. Consider the following (extreme) situation: class C a => D a where ... instance D [a] => D [a] where ... (dfunD) instance C [a] => C [a] where ... (dfunC) Although this looks wrong (assume D [a] to prove D [a]), it is only a more extreme case of what happens with recursive dictionaries, and it can, just about, make sense because the methods do some work before recursing. To implement the dfunD we must generate code for the superclass C [a], which we had better not get by superclass selection from the supplied argument: dfunD :: forall a. D [a] -> D [a] dfunD = \d::D [a] -> MkD (scsel d) .. Otherwise if we later encounter a situation where we have a [Wanted] dw::D [a] we might solve it thus: dw := dfunD dw Which is all fine except that now ** the superclass C is bottom **! The instance we want is: dfunD :: forall a. D [a] -> D [a] dfunD = \d::D [a] -> MkD (dfunC (scsel d)) ... ----- THE SOLUTION -------- The basic solution is simple: be very careful about using superclass selection to generate a superclass witness in a dictionary function definition. More precisely: Superclass Invariant: in every class dictionary, every superclass dictionary field is non-bottom To achieve the Superclass Invariant, in a dfun definition we can generate a guaranteed-non-bottom superclass witness from: (sc1) one of the dictionary arguments itself (all non-bottom) (sc2) an immediate superclass of a smaller dictionary (sc3) a call of a dfun (always returns a dictionary constructor) The tricky case is (sc2). We proceed by induction on the size of the (type of) the dictionary, defined by TcValidity.sizeTypes. Let's suppose we are building a dictionary of size 3, and suppose the Superclass Invariant holds of smaller dictionaries. Then if we have a smaller dictionary, its immediate superclasses will be non-bottom by induction. What does "we have a smaller dictionary" mean? It might be one of the arguments of the instance, or one of its superclasses. Here is an example, taken from CmmExpr: class Ord r => UserOfRegs r a where ... (i1) instance UserOfRegs r a => UserOfRegs r (Maybe a) where (i2) instance (Ord r, UserOfRegs r CmmReg) => UserOfRegs r CmmExpr where For (i1) we can get the (Ord r) superclass by selection from (UserOfRegs r a), since it is smaller than the thing we are building (UserOfRegs r (Maybe a). But for (i2) that isn't the case, so we must add an explicit, and perhaps surprising, (Ord r) argument to the instance declaration. Here's another example from Trac #6161: class Super a => Duper a where ... class Duper (Fam a) => Foo a where ... (i3) instance Foo a => Duper (Fam a) where ... (i4) instance Foo Float where ... It would be horribly wrong to define dfDuperFam :: Foo a -> Duper (Fam a) -- from (i3) dfDuperFam d = MkDuper (sc_sel1 (sc_sel2 d)) ... dfFooFloat :: Foo Float -- from (i4) dfFooFloat = MkFoo (dfDuperFam dfFooFloat) ... Now the Super superclass of Duper is definitely bottom! This won't happen because when processing (i3) we can use the superclasses of (Foo a), which is smaller, namely Duper (Fam a). But that is *not* smaller than the target so we can't take *its* superclasses. As a result the program is rightly rejected, unless you add (Super (Fam a)) to the context of (i3). Note [Solving superclass constraints] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ How do we ensure that every superclass witness is generated by one of (sc1) (sc2) or (sc3) in Note [Recursive superclases]. Answer: * Superclass "wanted" constraints have CtOrigin of (ScOrigin size) where 'size' is the size of the instance declaration. e.g. class C a => D a where... instance blah => D [a] where ... The wanted superclass constraint for C [a] has origin ScOrigin size, where size = size( D [a] ). * (sc1) When we rewrite such a wanted constraint, it retains its origin. But if we apply an instance declaration, we can set the origin to (ScOrigin infinity), thus lifting any restrictions by making prohibitedSuperClassSolve return False. * (sc2) ScOrigin wanted constraints can't be solved from a superclass selection, except at a smaller type. This test is implemented by TcInteract.prohibitedSuperClassSolve * The "given" constraints of an instance decl have CtOrigin GivenOrigin InstSkol. * When we make a superclass selection from InstSkol we use a SkolemInfo of (InstSC size), where 'size' is the size of the constraint whose superclass we are taking. An similarly when taking the superclass of an InstSC. This is implemented in TcCanonical.newSCWorkFromFlavored Note [Silent superclass arguments] (historical interest only) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ NB1: this note describes our *old* solution to the recursive-superclass problem. I'm keeping the Note for now, just as institutional memory. However, the code for silent superclass arguments was removed in late Dec 2014 NB2: the silent-superclass solution introduced new problems of its own, in the form of instance overlap. Tests SilentParametersOverlapping, T5051, and T7862 are examples NB3: the silent-superclass solution also generated tons of extra dictionaries. For example, in monad-transformer code, when constructing a Monad dictionary you had to pass an Applicative dictionary; and to construct that you neede a Functor dictionary. Yet these extra dictionaries were often never used. Test T3064 compiled *far* faster after silent superclasses were eliminated. Our solution to this problem "silent superclass arguments". We pass to each dfun some ``silent superclass arguments’’, which are the immediate superclasses of the dictionary we are trying to construct. In our example: dfun :: forall a. C [a] -> D [a] -> D [a] dfun = \(dc::C [a]) (dd::D [a]) -> DOrd dc ... Notice the extra (dc :: C [a]) argument compared to the previous version. This gives us: ----------------------------------------------------------- DFun Superclass Invariant ~~~~~~~~~~~~~~~~~~~~~~~~ In the body of a DFun, every superclass argument to the returned dictionary is either * one of the arguments of the DFun, or * constant, bound at top level ----------------------------------------------------------- This net effect is that it is safe to treat a dfun application as wrapping a dictionary constructor around its arguments (in particular, a dfun never picks superclasses from the arguments under the dictionary constructor). No superclass is hidden inside a dfun application. The extra arguments required to satisfy the DFun Superclass Invariant always come first, and are called the "silent" arguments. You can find out how many silent arguments there are using Id.dfunNSilent; and then you can just drop that number of arguments to see the ones that were in the original instance declaration. DFun types are built (only) by MkId.mkDictFunId, so that is where we decide what silent arguments are to be added. -} {- ************************************************************************ * * Type-checking an instance method * * ************************************************************************ tcMethod - Make the method bindings, as a [(NonRec, HsBinds)], one per method - Remembering to use fresh Name (the instance method Name) as the binder - Bring the instance method Ids into scope, for the benefit of tcInstSig - Use sig_fn mapping instance method Name -> instance tyvars - Ditto prag_fn - Use tcValBinds to do the checking -} tcMethods :: DFunId -> Class -> [TcTyVar] -> [EvVar] -> [TcType] -> TcEvBinds -> ([Located TcSpecPrag], TcPragEnv) -> [(Id, DefMeth)] -> InstBindings Name -> TcM ([Id], LHsBinds Id, Bag Implication) -- The returned inst_meth_ids all have types starting -- forall tvs. theta => ... tcMethods dfun_id clas tyvars dfun_ev_vars inst_tys dfun_ev_binds prags@(spec_inst_prags,_) op_items (InstBindings { ib_binds = binds , ib_tyvars = lexical_tvs , ib_pragmas = sigs , ib_extensions = exts , ib_derived = is_derived }) = tcExtendTyVarEnv2 (lexical_tvs `zip` tyvars) $ -- The lexical_tvs scope over the 'where' part do { traceTc "tcInstMeth" (ppr sigs $$ ppr binds) ; checkMinimalDefinition ; (ids, binds, mb_implics) <- set_exts exts $ mapAndUnzip3M tc_item op_items ; return (ids, listToBag binds, listToBag (catMaybes mb_implics)) } where set_exts :: [ExtensionFlag] -> TcM a -> TcM a set_exts es thing = foldr setXOptM thing es hs_sig_fn = mkHsSigFun sigs inst_loc = getSrcSpan dfun_id ---------------------- tc_item :: (Id, DefMeth) -> TcM (Id, LHsBind Id, Maybe Implication) tc_item (sel_id, dm_info) | Just (user_bind, bndr_loc) <- findMethodBind (idName sel_id) binds = tcMethodBody clas tyvars dfun_ev_vars inst_tys dfun_ev_binds is_derived hs_sig_fn prags sel_id user_bind bndr_loc | otherwise = do { traceTc "tc_def" (ppr sel_id) ; tc_default sel_id dm_info } ---------------------- tc_default :: Id -> DefMeth -> TcM (TcId, LHsBind Id, Maybe Implication) tc_default sel_id (GenDefMeth dm_name) = do { meth_bind <- mkGenericDefMethBind clas inst_tys sel_id dm_name ; tcMethodBody clas tyvars dfun_ev_vars inst_tys dfun_ev_binds is_derived hs_sig_fn prags sel_id meth_bind inst_loc } tc_default sel_id NoDefMeth -- No default method at all = do { traceTc "tc_def: warn" (ppr sel_id) ; (meth_id, _, _) <- mkMethIds hs_sig_fn clas tyvars dfun_ev_vars inst_tys sel_id ; dflags <- getDynFlags ; let meth_bind = mkVarBind meth_id $ mkLHsWrap lam_wrapper (error_rhs dflags) ; return (meth_id, meth_bind, Nothing) } where error_rhs dflags = L inst_loc $ HsApp error_fun (error_msg dflags) error_fun = L inst_loc $ wrapId (WpTyApp meth_tau) nO_METHOD_BINDING_ERROR_ID error_msg dflags = L inst_loc (HsLit (HsStringPrim "" (unsafeMkByteString (error_string dflags)))) meth_tau = funResultTy (applyTys (idType sel_id) inst_tys) error_string dflags = showSDoc dflags (hcat [ppr inst_loc, text "|", ppr sel_id ]) lam_wrapper = mkWpTyLams tyvars <.> mkWpLams dfun_ev_vars tc_default sel_id (DefMeth dm_name) -- A polymorphic default method = do { -- Build the typechecked version directly, -- without calling typecheck_method; -- see Note [Default methods in instances] -- Generate /\as.\ds. let self = df as ds -- in $dm inst_tys self -- The 'let' is necessary only because HsSyn doesn't allow -- you to apply a function to a dictionary *expression*. ; self_dict <- newDict clas inst_tys ; let self_ev_bind = mkWantedEvBind self_dict (EvDFunApp dfun_id (mkTyVarTys tyvars) dfun_ev_vars) ; (meth_id, local_meth_sig, hs_wrap) <- mkMethIds hs_sig_fn clas tyvars dfun_ev_vars inst_tys sel_id ; dm_id <- tcLookupId dm_name ; let dm_inline_prag = idInlinePragma dm_id rhs = HsWrap (mkWpEvVarApps [self_dict] <.> mkWpTyApps inst_tys) $ HsVar dm_id -- A method always has a complete type signature, -- hence it is safe to call completeIdSigPolyId local_meth_id = completeIdSigPolyId local_meth_sig meth_bind = mkVarBind local_meth_id (L inst_loc rhs) meth_id1 = meth_id `setInlinePragma` dm_inline_prag -- Copy the inline pragma (if any) from the default -- method to this version. Note [INLINE and default methods] export = ABE { abe_wrap = hs_wrap, abe_poly = meth_id1 , abe_mono = local_meth_id , abe_prags = mk_meth_spec_prags meth_id1 spec_inst_prags [] } bind = AbsBinds { abs_tvs = tyvars, abs_ev_vars = dfun_ev_vars , abs_exports = [export] , abs_ev_binds = [EvBinds (unitBag self_ev_bind)] , abs_binds = unitBag meth_bind } -- Default methods in an instance declaration can't have their own -- INLINE or SPECIALISE pragmas. It'd be possible to allow them, but -- currently they are rejected with -- "INLINE pragma lacks an accompanying binding" ; return (meth_id1, L inst_loc bind, Nothing) } ---------------------- -- Check if one of the minimal complete definitions is satisfied checkMinimalDefinition = whenIsJust (isUnsatisfied methodExists (classMinimalDef clas)) $ warnUnsatisfiedMinimalDefinition where methodExists meth = isJust (findMethodBind meth binds) ------------------------ tcMethodBody :: Class -> [TcTyVar] -> [EvVar] -> [TcType] -> TcEvBinds -> Bool -> HsSigFun -> ([LTcSpecPrag], TcPragEnv) -> Id -> LHsBind Name -> SrcSpan -> TcM (TcId, LHsBind Id, Maybe Implication) tcMethodBody clas tyvars dfun_ev_vars inst_tys dfun_ev_binds is_derived sig_fn (spec_inst_prags, prag_fn) sel_id (L bind_loc meth_bind) bndr_loc = add_meth_ctxt $ do { traceTc "tcMethodBody" (ppr sel_id <+> ppr (idType sel_id)) ; (global_meth_id, local_meth_sig, hs_wrap) <- setSrcSpan bndr_loc $ mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id ; let prags = lookupPragEnv prag_fn (idName sel_id) -- A method always has a complete type signature, -- so it is safe to call cmpleteIdSigPolyId local_meth_id = completeIdSigPolyId local_meth_sig lm_bind = meth_bind { fun_id = L bndr_loc (idName local_meth_id) } -- Substitute the local_meth_name for the binder -- NB: the binding is always a FunBind ; global_meth_id <- addInlinePrags global_meth_id prags ; spec_prags <- tcSpecPrags global_meth_id prags ; (meth_implic, (tc_bind, _)) <- checkInstConstraints $ \ _ev_binds -> tcPolyCheck NonRecursive no_prag_fn local_meth_sig (L bind_loc lm_bind) ; let specs = mk_meth_spec_prags global_meth_id spec_inst_prags spec_prags export = ABE { abe_poly = global_meth_id , abe_mono = local_meth_id , abe_wrap = hs_wrap , abe_prags = specs } local_ev_binds = TcEvBinds (ic_binds meth_implic) full_bind = AbsBinds { abs_tvs = tyvars , abs_ev_vars = dfun_ev_vars , abs_exports = [export] , abs_ev_binds = [dfun_ev_binds, local_ev_binds] , abs_binds = tc_bind } ; return (global_meth_id, L bind_loc full_bind, Just meth_implic) } where -- For instance decls that come from deriving clauses -- we want to print out the full source code if there's an error -- because otherwise the user won't see the code at all add_meth_ctxt thing | is_derived = addLandmarkErrCtxt (derivBindCtxt sel_id clas inst_tys) thing | otherwise = thing no_prag_fn = emptyPragEnv -- No pragmas for local_meth_id; -- they are all for meth_id ------------------------ mkMethIds :: HsSigFun -> Class -> [TcTyVar] -> [EvVar] -> [TcType] -> Id -> TcM (TcId, TcIdSigInfo, HsWrapper) mkMethIds sig_fn clas tyvars dfun_ev_vars inst_tys sel_id = do { poly_meth_name <- newName (mkClassOpAuxOcc sel_occ) ; local_meth_name <- newName sel_occ -- Base the local_meth_name on the selector name, because -- type errors from tcMethodBody come from here ; let poly_meth_id = mkLocalId poly_meth_name poly_meth_ty local_meth_id = mkLocalId local_meth_name local_meth_ty ; case lookupHsSig sig_fn sel_name of Just lhs_ty -- There is a signature in the instance declaration -- See Note [Instance method signatures] -> setSrcSpan (getLoc lhs_ty) $ do { inst_sigs <- xoptM Opt_InstanceSigs ; checkTc inst_sigs (misplacedInstSig sel_name lhs_ty) ; sig_ty <- tcHsSigType (FunSigCtxt sel_name False) lhs_ty ; let poly_sig_ty = mkSigmaTy tyvars theta sig_ty ctxt = FunSigCtxt sel_name True ; tc_sig <- instTcTySig ctxt lhs_ty sig_ty Nothing [] local_meth_name ; hs_wrap <- addErrCtxtM (methSigCtxt sel_name poly_sig_ty poly_meth_ty) $ tcSubType ctxt poly_sig_ty poly_meth_ty ; return (poly_meth_id, tc_sig, hs_wrap) } Nothing -- No type signature -> do { tc_sig <- instTcTySigFromId local_meth_id ; return (poly_meth_id, tc_sig, idHsWrapper) } } -- Absent a type sig, there are no new scoped type variables here -- Only the ones from the instance decl itself, which are already -- in scope. Example: -- class C a where { op :: forall b. Eq b => ... } -- instance C [c] where { op = <rhs> } -- In <rhs>, 'c' is scope but 'b' is not! where sel_name = idName sel_id sel_occ = nameOccName sel_name local_meth_ty = instantiateMethod clas sel_id inst_tys poly_meth_ty = mkSigmaTy tyvars theta local_meth_ty theta = map idType dfun_ev_vars methSigCtxt :: Name -> TcType -> TcType -> TidyEnv -> TcM (TidyEnv, MsgDoc) methSigCtxt sel_name sig_ty meth_ty env0 = do { (env1, sig_ty) <- zonkTidyTcType env0 sig_ty ; (env2, meth_ty) <- zonkTidyTcType env1 meth_ty ; let msg = hang (ptext (sLit "When checking that instance signature for") <+> quotes (ppr sel_name)) 2 (vcat [ ptext (sLit "is more general than its signature in the class") , ptext (sLit "Instance sig:") <+> ppr sig_ty , ptext (sLit " Class sig:") <+> ppr meth_ty ]) ; return (env2, msg) } misplacedInstSig :: Name -> LHsType Name -> SDoc misplacedInstSig name hs_ty = vcat [ hang (ptext (sLit "Illegal type signature in instance declaration:")) 2 (hang (pprPrefixName name) 2 (dcolon <+> ppr hs_ty)) , ptext (sLit "(Use InstanceSigs to allow this)") ] {- Note [Instance method signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ With -XInstanceSigs we allow the user to supply a signature for the method in an instance declaration. Here is an artificial example: data Age = MkAge Int instance Ord Age where compare :: a -> a -> Bool compare = error "You can't compare Ages" The instance signature can be *more* polymorphic than the instantiated class method (in this case: Age -> Age -> Bool), but it cannot be less polymorphic. Moreover, if a signature is given, the implementation code should match the signature, and type variables bound in the singature should scope over the method body. We achieve this by building a TcSigInfo for the method, whether or not there is an instance method signature, and using that to typecheck the declaration (in tcMethodBody). That means, conveniently, that the type variables bound in the signature will scope over the body. What about the check that the instance method signature is more polymorphic than the instantiated class method type? We just do a tcSubType call in mkMethIds, and use the HsWrapper thus generated in the method AbsBind. It's very like the tcSubType impedance-matching call in mkExport. We have to pass the HsWrapper into tcMethodBody. -} ---------------------- mk_meth_spec_prags :: Id -> [LTcSpecPrag] -> [LTcSpecPrag] -> TcSpecPrags -- Adapt the 'SPECIALISE instance' pragmas to work for this method Id -- There are two sources: -- * spec_prags_for_me: {-# SPECIALISE op :: <blah> #-} -- * spec_prags_from_inst: derived from {-# SPECIALISE instance :: <blah> #-} -- These ones have the dfun inside, but [perhaps surprisingly] -- the correct wrapper. -- See Note [Handling SPECIALISE pragmas] in TcBinds mk_meth_spec_prags meth_id spec_inst_prags spec_prags_for_me = SpecPrags (spec_prags_for_me ++ spec_prags_from_inst) where spec_prags_from_inst | isInlinePragma (idInlinePragma meth_id) = [] -- Do not inherit SPECIALISE from the instance if the -- method is marked INLINE, because then it'll be inlined -- and the specialisation would do nothing. (Indeed it'll provoke -- a warning from the desugarer | otherwise = [ L inst_loc (SpecPrag meth_id wrap inl) | L inst_loc (SpecPrag _ wrap inl) <- spec_inst_prags] mkGenericDefMethBind :: Class -> [Type] -> Id -> Name -> TcM (LHsBind Name) mkGenericDefMethBind clas inst_tys sel_id dm_name = -- A generic default method -- If the method is defined generically, we only have to call the -- dm_name. do { dflags <- getDynFlags ; liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Filling in method body" (vcat [ppr clas <+> ppr inst_tys, nest 2 (ppr sel_id <+> equals <+> ppr rhs)])) ; return (noLoc $ mkTopFunBind Generated (noLoc (idName sel_id)) [mkSimpleMatch [] rhs]) } where rhs = nlHsVar dm_name ---------------------- derivBindCtxt :: Id -> Class -> [Type ] -> SDoc derivBindCtxt sel_id clas tys = vcat [ ptext (sLit "When typechecking the code for") <+> quotes (ppr sel_id) , nest 2 (ptext (sLit "in a derived instance for") <+> quotes (pprClassPred clas tys) <> colon) , nest 2 $ ptext (sLit "To see the code I am typechecking, use -ddump-deriv") ] warnMissingMethodOrAT :: String -> Name -> TcM () warnMissingMethodOrAT what name = do { warn <- woptM Opt_WarnMissingMethods ; traceTc "warn" (ppr name <+> ppr warn <+> ppr (not (startsWithUnderscore (getOccName name)))) ; warnTc (warn -- Warn only if -fwarn-missing-methods && not (startsWithUnderscore (getOccName name))) -- Don't warn about _foo methods (ptext (sLit "No explicit") <+> text what <+> ptext (sLit "or default declaration for") <+> quotes (ppr name)) } warnUnsatisfiedMinimalDefinition :: ClassMinimalDef -> TcM () warnUnsatisfiedMinimalDefinition mindef = do { warn <- woptM Opt_WarnMissingMethods ; warnTc warn message } where message = vcat [ptext (sLit "No explicit implementation for") ,nest 2 $ pprBooleanFormulaNice mindef ] {- Note [Export helper functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We arrange to export the "helper functions" of an instance declaration, so that they are not subject to preInlineUnconditionally, even if their RHS is trivial. Reason: they are mentioned in the DFunUnfolding of the dict fun as Ids, not as CoreExprs, so we can't substitute a non-variable for them. We could change this by making DFunUnfoldings have CoreExprs, but it seems a bit simpler this way. Note [Default methods in instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this class Baz v x where foo :: x -> x foo y = <blah> instance Baz Int Int From the class decl we get $dmfoo :: forall v x. Baz v x => x -> x $dmfoo y = <blah> Notice that the type is ambiguous. That's fine, though. The instance decl generates $dBazIntInt = MkBaz fooIntInt fooIntInt = $dmfoo Int Int $dBazIntInt BUT this does mean we must generate the dictionary translation of fooIntInt directly, rather than generating source-code and type-checking it. That was the bug in Trac #1061. In any case it's less work to generate the translated version! Note [INLINE and default methods] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Default methods need special case. They are supposed to behave rather like macros. For exmample class Foo a where op1, op2 :: Bool -> a -> a {-# INLINE op1 #-} op1 b x = op2 (not b) x instance Foo Int where -- op1 via default method op2 b x = <blah> The instance declaration should behave just as if 'op1' had been defined with the code, and INLINE pragma, from its original definition. That is, just as if you'd written instance Foo Int where op2 b x = <blah> {-# INLINE op1 #-} op1 b x = op2 (not b) x So for the above example we generate: {-# INLINE $dmop1 #-} -- $dmop1 has an InlineCompulsory unfolding $dmop1 d b x = op2 d (not b) x $fFooInt = MkD $cop1 $cop2 {-# INLINE $cop1 #-} $cop1 = $dmop1 $fFooInt $cop2 = <blah> Note carefully: * We *copy* any INLINE pragma from the default method $dmop1 to the instance $cop1. Otherwise we'll just inline the former in the latter and stop, which isn't what the user expected * Regardless of its pragma, we give the default method an unfolding with an InlineCompulsory source. That means that it'll be inlined at every use site, notably in each instance declaration, such as $cop1. This inlining must happen even though a) $dmop1 is not saturated in $cop1 b) $cop1 itself has an INLINE pragma It's vital that $dmop1 *is* inlined in this way, to allow the mutual recursion between $fooInt and $cop1 to be broken * To communicate the need for an InlineCompulsory to the desugarer (which makes the Unfoldings), we use the IsDefaultMethod constructor in TcSpecPrags. ************************************************************************ * * Specialise instance pragmas * * ************************************************************************ Note [SPECIALISE instance pragmas] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider instance (Ix a, Ix b) => Ix (a,b) where {-# SPECIALISE instance Ix (Int,Int) #-} range (x,y) = ... We make a specialised version of the dictionary function, AND specialised versions of each *method*. Thus we should generate something like this: $dfIxPair :: (Ix a, Ix b) => Ix (a,b) {-# DFUN [$crangePair, ...] #-} {-# SPECIALISE $dfIxPair :: Ix (Int,Int) #-} $dfIxPair da db = Ix ($crangePair da db) (...other methods...) $crange :: (Ix a, Ix b) -> ((a,b),(a,b)) -> [(a,b)] {-# SPECIALISE $crange :: ((Int,Int),(Int,Int)) -> [(Int,Int)] #-} $crange da db = <blah> The SPECIALISE pragmas are acted upon by the desugarer, which generate dii :: Ix Int dii = ... $s$dfIxPair :: Ix ((Int,Int),(Int,Int)) {-# DFUN [$crangePair di di, ...] #-} $s$dfIxPair = Ix ($crangePair di di) (...) {-# RULE forall (d1,d2:Ix Int). $dfIxPair Int Int d1 d2 = $s$dfIxPair #-} $s$crangePair :: ((Int,Int),(Int,Int)) -> [(Int,Int)] $c$crangePair = ...specialised RHS of $crangePair... {-# RULE forall (d1,d2:Ix Int). $crangePair Int Int d1 d2 = $s$crangePair #-} Note that * The specialised dictionary $s$dfIxPair is very much needed, in case we call a function that takes a dictionary, but in a context where the specialised dictionary can be used. See Trac #7797. * The ClassOp rule for 'range' works equally well on $s$dfIxPair, because it still has a DFunUnfolding. See Note [ClassOp/DFun selection] * A call (range ($dfIxPair Int Int d1 d2)) might simplify two ways: --> {ClassOp rule for range} $crangePair Int Int d1 d2 --> {SPEC rule for $crangePair} $s$crangePair or thus: --> {SPEC rule for $dfIxPair} range $s$dfIxPair --> {ClassOpRule for range} $s$crangePair It doesn't matter which way. * We want to specialise the RHS of both $dfIxPair and $crangePair, but the SAME HsWrapper will do for both! We can call tcSpecPrag just once, and pass the result (in spec_inst_info) to tcMethods. -} tcSpecInstPrags :: DFunId -> InstBindings Name -> TcM ([Located TcSpecPrag], TcPragEnv) tcSpecInstPrags dfun_id (InstBindings { ib_binds = binds, ib_pragmas = uprags }) = do { spec_inst_prags <- mapM (wrapLocM (tcSpecInst dfun_id)) $ filter isSpecInstLSig uprags -- The filter removes the pragmas for methods ; return (spec_inst_prags, mkPragEnv uprags binds) } ------------------------------ tcSpecInst :: Id -> Sig Name -> TcM TcSpecPrag tcSpecInst dfun_id prag@(SpecInstSig _ hs_ty) = addErrCtxt (spec_ctxt prag) $ do { (tyvars, theta, clas, tys) <- tcHsInstHead SpecInstCtxt hs_ty ; let spec_dfun_ty = mkDictFunTy tyvars theta clas tys ; co_fn <- tcSpecWrapper SpecInstCtxt (idType dfun_id) spec_dfun_ty ; return (SpecPrag dfun_id co_fn defaultInlinePragma) } where spec_ctxt prag = hang (ptext (sLit "In the SPECIALISE pragma")) 2 (ppr prag) tcSpecInst _ _ = panic "tcSpecInst" {- ************************************************************************ * * \subsection{Error messages} * * ************************************************************************ -} instDeclCtxt1 :: LHsType Name -> SDoc instDeclCtxt1 hs_inst_ty = inst_decl_ctxt (case unLoc hs_inst_ty of HsForAllTy _ _ _ _ (L _ ty') -> ppr ty' _ -> ppr hs_inst_ty) -- Don't expect this instDeclCtxt2 :: Type -> SDoc instDeclCtxt2 dfun_ty = inst_decl_ctxt (ppr (mkClassPred cls tys)) where (_,_,cls,tys) = tcSplitDFunTy dfun_ty inst_decl_ctxt :: SDoc -> SDoc inst_decl_ctxt doc = hang (ptext (sLit "In the instance declaration for")) 2 (quotes doc) badBootFamInstDeclErr :: SDoc badBootFamInstDeclErr = ptext (sLit "Illegal family instance in hs-boot file") notFamily :: TyCon -> SDoc notFamily tycon = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tycon) , nest 2 $ parens (ppr tycon <+> ptext (sLit "is not an indexed type family"))] tooFewParmsErr :: Arity -> SDoc tooFewParmsErr arity = ptext (sLit "Family instance has too few parameters; expected") <+> ppr arity assocInClassErr :: Located Name -> SDoc assocInClassErr name = ptext (sLit "Associated type") <+> quotes (ppr name) <+> ptext (sLit "must be inside a class instance") badFamInstDecl :: Located Name -> SDoc badFamInstDecl tc_name = vcat [ ptext (sLit "Illegal family instance for") <+> quotes (ppr tc_name) , nest 2 (parens $ ptext (sLit "Use TypeFamilies to allow indexed type families")) ] notOpenFamily :: TyCon -> SDoc notOpenFamily tc = ptext (sLit "Illegal instance for closed family") <+> quotes (ppr tc)
ghc-android/ghc
compiler/typecheck/TcInstDcls.hs
bsd-3-clause
78,248
5
26
23,611
9,001
4,732
4,269
660
5
{-# LANGUAGE FunctionalDependencies #-} module Rachel.Types ( -- * Pretty printing Pretty (..) -- * Rachel values -- ** Primitive values , PrimitiveType (..) , RReal (..), RInteger (..) , RBool (..), RSound (..) -- ** All values , Value (..) -- * Expressions , Id , Exp (..) -- * Type of a expression , Type (..) , typeVars , mapTypeVars , prefixType, sufixType , hasHash, removeHash -- * Context , Context, Environment , OpAssoc (..) , Fixity (..), defaultFixity , Entity (..) , insertEntity , contextFromEnv -- * Declarations , Dec (..) ) where import Data.Sound -- Data structures import Data.Map (Map,insert) import Data.Set (Set) import qualified Data.Set as Set import Data.Fixed (Micro, showFixed) -- Other imports import Data.String import Data.Char (isLetter) import qualified Data.Foldable as F -- Pretty printing -- | Human readable representation. class Pretty a where pretty :: a -> String parens :: Bool -> String -> String parens True str = '(' : (str ++ ")") parens _ str = str -- Rachel types -- | Real numbers represented as floating point numbers (double precision). newtype RReal = RReal Double deriving (Show,Eq) instance Pretty RReal where pretty (RReal r) = showFixed True ((fromRational . toRational) r :: Micro) -- | Integer numbers. newtype RInteger = RInteger Integer deriving (Show,Eq) instance Pretty RInteger where pretty (RInteger i) = show i -- | Booleans. newtype RBool = RBool Bool instance Pretty RBool where pretty (RBool True) = "true" pretty (RBool False) = "false" -- | A sound. See 'Sound'. newtype RSound = RSound Sound instance Pretty RSound where pretty (RSound _) = "#sound#" -------------------------- class PrimitiveType p h | h -> p , p -> h where toPrimitive :: h -> p fromPrimitive :: p -> h toValue :: p -> Value fromValue :: Value -> Maybe p toType :: p -> Type instance PrimitiveType RInteger Integer where toPrimitive = RInteger fromPrimitive (RInteger i) = i toValue = VInteger fromValue (VInteger i) = Just i fromValue _ = Nothing toType _ = TInteger instance PrimitiveType RReal Double where toPrimitive = RReal fromPrimitive (RReal i) = i toValue = VReal fromValue (VReal i) = Just i fromValue _ = Nothing toType _ = TReal instance PrimitiveType RBool Bool where toPrimitive = RBool fromPrimitive (RBool i) = i toValue = VBool fromValue (VBool i) = Just i fromValue _ = Nothing toType _ = TBool instance PrimitiveType RSound Sound where toPrimitive = RSound fromPrimitive (RSound i) = i toValue = VSound fromValue (VSound i) = Just i fromValue _ = Nothing toType _ = TSound -- instance (PrimitiveType p h, PrimitiveType p' h') -- => PrimitiveType (p -> p') (h -> h') where -- toPrimitive f = toPrimitive . f . fromPrimitive -------------------------- -- | Any identifier contains a value of this type. data Value = -- | Real numbers. VReal RReal -- | Integer numbers. | VInteger RInteger -- | Booleans. | VBool RBool -- | Sounds. | VSound RSound -- | Product. | VProd Value Value -- | Left value of a sum. | VSumL Value -- | Right value of a sum. | VSumR Value -- | Functions. | VFun (Value -> Value) -- | Bottom. | VBottom String instance Pretty Value where pretty (VReal r) = pretty r pretty (VInteger i) = pretty i pretty (VBool b) = pretty b pretty (VSound s) = pretty s pretty (VProd x y) = "(" ++ pretty x ++ "," ++ pretty y ++ ")" pretty (VSumL x) = "L (" ++ pretty x ++ ")" pretty (VSumR x) = "R (" ++ pretty x ++ ")" pretty (VFun _) = "#function#" pretty (VBottom str) = "_|_: " ++ str -- Expressions and types -- | Identifiers are stored as 'String's. type Id = String -- | An expression in the Rachel language. data Exp = EReal RReal -- ^ @1.0@ | EInteger RInteger -- ^ @1@ | EVar Id -- ^ @x@ | EProd Exp Exp -- ^ @(e1,e2)@ | ESumL -- ^ @L@ | ESumR -- ^ @R@ | EApp Exp Exp -- ^ @e1 e2@ | ELambda Id Exp -- ^ @\\x.e@ | ELet Id Exp Exp -- ^ @let x = e1 in e2@ deriving (Show,Eq) instance IsString Exp where fromString = EVar isEOp :: Exp -> Bool isEOp (EProd _ _) = True isEOp (EApp _ _) = True isEOp _ = False instance Pretty Exp where pretty (EReal r) = pretty r pretty (EInteger i) = pretty i pretty (EVar str) = case str of [] -> error "Variable with empty name!" (x:_) -> if isLetter x || x == '_' then str else "(" ++ str ++ ")" pretty (EProd x y) = let pretty' e = parens (isEOp e) (pretty e) in "(" ++ pretty' x ++ "," ++ pretty' y ++ ")" pretty ESumL = "L" pretty ESumR = "R" pretty (EApp f x) = let pretty' e = parens (isEOp e) (pretty e) in pretty' f ++ " " ++ pretty' x pretty (ELambda x e) = "\\" ++ x ++ "." ++ pretty e pretty (ELet x e1 e2) = "let " ++ x ++ " = " ++ pretty e1 ++ " in " ++ pretty e2 -- | The type of Rachel types. data Type = -- Primitive types TReal | TInteger | TBool | TSound -- Arity two types | TFun Type Type | TProd Type Type | TSum Type Type -- Type variables | TVar Id deriving (Show,Eq) isTOp :: Type -> Bool isTOp (TFun _ _) = True isTOp (TProd _ _) = True isTOp (TSum _ _) = True isTOp _ = False isTFun :: Type -> Bool isTFun (TFun _ _) = True isTFun _ = False hasHash :: Type -> Bool hasHash = F.any (elem '#') . typeVars -- | Remove all the characters after a hash (including the hash) -- in every type variable. removeHash :: Type -> Type removeHash = mapTypeVars $ takeWhile (/='#') instance Pretty Type where pretty TReal = "Real" pretty TInteger = "Integer" pretty TBool = "Bool" pretty TSound = "Sound" pretty (TFun f x) = let pretty' e = parens (isTFun e) (pretty e) in pretty' f ++ " -> " ++ pretty x pretty (TProd x y) = let pretty' e = parens (isTOp e) (pretty e) in pretty' x ++ "*" ++ pretty' y pretty (TSum x y) = let pretty' e = parens (isTOp e) (pretty e) in pretty' x ++ "+" ++ pretty' y pretty (TVar str) = str -- | Map a function over all variable names in a type. mapTypeVars :: (String -> String) -> Type -> Type mapTypeVars f = go where go (TVar v) = TVar $ f v go (TFun x y) = TFun (go x) (go y) go (TProd x y) = TProd (go x) (go y) go (TSum x y) = TSum (go x) (go y) go t = t -- | Add a prefix to all the variables in a type. -- This has the property that, given any two types @t1@ and @t2@, -- if the strings @str1@ and @str2@ are /different/, then the -- set of variables of @prefixType str1 t1@ and @prefixType str2 t2@ -- are disjoint. prefixType :: String -> Type -> Type prefixType str = mapTypeVars (str++) -- | Add a sufix to all the variables in a type. sufixType :: String -> Type -> Type sufixType str = mapTypeVars (++str) -- | Type variables in a type. typeVars :: Type -> Set Id typeVars = typeVarsAux Set.empty typeVarsAux :: Set Id -> Type -> Set Id typeVarsAux xs (TVar x) = Set.insert x xs typeVarsAux xs (TFun f x) = let ys = typeVarsAux xs f in typeVarsAux ys x typeVarsAux xs (TProd x y) = let ys = typeVarsAux xs x in typeVarsAux ys y typeVarsAux xs (TSum x y) = let ys = typeVarsAux xs x in typeVarsAux ys y typeVarsAux xs _ = xs data OpAssoc = LeftA | RightA deriving Eq -- | A fixity value of an 'Entity'. -- The first parameter indicates the associativity as operator. -- The second parameter indicates the priority. data Fixity = Fixity OpAssoc Int deriving Eq instance Pretty Fixity where pretty (Fixity a p) = let str = if a == LeftA then "l" else "r" in "infix" ++ str ++ " " ++ show p defaultFixity :: Fixity defaultFixity = Fixity LeftA 10 -- | A complete 'Entity' with identity, type, fixity and value. data Entity = Entity Id Type Fixity Value -- | A context is a map from each defined identity to its 'Type'. type Context = Map Id Type -- | An environment is a map from each defined identity to its full definition, -- i.e. its type, its fixity and its value. type Environment = Map Id (Type,Fixity,Value) -- | Insert an 'Entity' in an environment, replacing the type and value of an -- already defined identity. insertEntity :: Entity -> Environment -> Environment insertEntity (Entity i t f v) = insert i (t,f,v) -- | Discard the values of every identity to get a 'Context' from an 'Environment'. contextFromEnv :: Environment -> Context contextFromEnv = fmap $ \(t,_,_) -> t -- Declarations -- | Rachel top level declarations. data Dec = TypeDec Id Type | FunDec Id Exp | InfixDec Id Fixity | PatDec Id Int [[Id]] -- ^ Pattern declaration. The 'Int' value specifies the number of columns.
Daniel-Diaz/rachel
Rachel/Types.hs
bsd-3-clause
8,847
0
12
2,268
2,695
1,442
1,253
-1
-1
-- -- HTTP client for use with pipes -- -- Copyright © 2012-2013 Operational Dynamics Consulting, Pty Ltd -- -- The code in this file, and the program it is a part of, is made -- available to you by its authors as open source software: you can -- redistribute it and/or modify it under a BSD licence. -- {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS -fno-warn-unused-imports #-} module Main where import Control.Exception (bracket) import Network.Http.Client -- -- Otherwise redundent imports, but useful for testing in GHCi. -- import Blaze.ByteString.Builder (Builder) import qualified Blaze.ByteString.Builder as Builder import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S import Debug.Trace main :: IO () main = do c <- openConnection "kernel.operationaldynamics.com" 58080 q <- buildRequest $ do http GET "/time" setAccept "text/plain" putStr $ show q -- Requests [headers] are terminated by a double newline -- already. We need a better way of emitting debug -- information mid-stream from this library. sendRequest c q emptyBody receiveResponse c debugHandler closeConnection c
afcowie/pipes-http
tests/ActualSnippet.hs
bsd-3-clause
1,203
0
11
253
167
96
71
20
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE CPP #-} module Main where import Common import Data.Aeson import Data.Proxy import Data.Text (Text) import qualified Data.Text as T import GHC.Generics import qualified Lucid as L import Lucid.Base import Network.HTTP.Types hiding (Header) import Network.Wai import Network.Wai.Handler.Warp import Network.Wai.Middleware.Gzip import Network.Wai.Application.Static import Network.Wai.Middleware.RequestLogger import Servant import Servant.Server.Internal import qualified System.IO as IO import Miso import Miso.String main :: IO () main = do IO.hPutStrLn IO.stderr "Running on port 3002..." run 3002 $ logStdout (compress app) where compress = gzip def { gzipFiles = GzipCompress } app :: Application #if MIN_VERSION_servant(0,11,0) app = serve (Proxy @ API) (static :<|> serverHandlers :<|> pure misoManifest :<|> Tagged handle404) #else app = serve (Proxy @ API) (static :<|> serverHandlers :<|> pure misoManifest :<|> handle404) #endif where static = serveDirectoryWith (defaultWebAppSettings "static") -- | Wrapper for setting HTML doctype and header newtype Wrapper a = Wrapper a deriving (Show, Eq) -- | Convert client side routes into server-side web handlers type ServerRoutes = ToServerRoutes ClientRoutes Wrapper Action -- | API type type API = ("static" :> Raw) :<|> ServerRoutes :<|> ("manifest.json" :> Get '[JSON] Manifest) :<|> Raw data Manifest = Manifest { name :: Text , short_name :: Text , start_url :: Text , display :: Text , theme_color :: Text , description :: Text } deriving (Show, Eq, Generic) instance ToJSON Manifest misoManifest :: Manifest misoManifest = Manifest { name = "Haskell Miso" , short_name = "Miso" , start_url = "." , display = "standalone" , theme_color = "#00d1b2" , description = "A tasty Haskell front-end framework" } handle404 :: Application handle404 _ respond = respond $ responseLBS status404 [("Content-Type", "text/html")] $ renderBS $ toHtml $ Wrapper $ the404 Model { uri = goHome, navMenuOpen = False } instance L.ToHtml a => L.ToHtml (Wrapper a) where toHtmlRaw = L.toHtml toHtml (Wrapper x) = do L.doctype_ L.html_ [ L.lang_ "en" ] $ do L.head_ $ do L.title_ "Miso: A tasty Haskell front-end framework" L.link_ [ L.rel_ "stylesheet" , L.href_ "https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.2/gh-fork-ribbon.min.css" ] L.link_ [ L.rel_ "manifest" , L.href_ "/manifest.json" ] L.meta_ [ L.charset_ "utf-8" ] L.meta_ [ L.name_ "theme-color", L.content_ "#00d1b2" ] L.meta_ [ L.httpEquiv_ "X-UA-Compatible" , L.content_ "IE=edge" ] L.meta_ [ L.name_ "viewport" , L.content_ "width=device-width, initial-scale=1" ] L.meta_ [ L.name_ "description" , L.content_ "Miso is a small isomorphic Haskell front-end framework featuring a virtual-dom, diffing / patching algorithm, event delegation, event batching, SVG, Server-sent events, Websockets, type-safe servant-style routing and an extensible Subscription-based subsystem. Inspired by Elm, Redux and Bobril. Miso is pure by default, but side effects (like XHR) can be introduced into the system via the Effect data type. Miso makes heavy use of the GHCJS FFI and therefore has minimal dependencies." ] L.style_ ".github-fork-ribbon:before { background-color: \"#e59751\" !important; } " cssRef animateRef cssRef bulmaRef cssRef fontAwesomeRef jsRef "https://buttons.github.io/buttons.js" L.script_ analytics jsRef "static/all.js" L.body_ (L.toHtml x) where jsRef href = L.with (L.script_ mempty) [ makeAttribute "src" href , makeAttribute "async" mempty , makeAttribute "defer" mempty ] cssRef href = L.with (L.link_ mempty) [ L.rel_ "stylesheet" , L.type_ "text/css" , L.href_ href ] fontAwesomeRef :: MisoString fontAwesomeRef = "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" animateRef :: MisoString animateRef = "https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" bulmaRef :: MisoString bulmaRef = "https://cdnjs.cloudflare.com/ajax/libs/bulma/0.4.3/css/bulma.min.css" analytics :: MisoString analytics = -- Multiline strings don’t work well with CPP mconcat [ "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" , "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," , "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" , "})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');" , "ga('create', 'UA-102668481-1', 'auto');" , "ga('send', 'pageview');" ] serverHandlers :: Handler (Wrapper (View Action)) :<|> Handler (Wrapper (View Action)) :<|> Handler (Wrapper (View Action)) :<|> Handler (Wrapper (View Action)) serverHandlers = examplesHandler :<|> docsHandler :<|> communityHandler :<|> homeHandler where send f u = pure $ Wrapper $ f Model {uri = u, navMenuOpen = False} homeHandler = send home goHome examplesHandler = send examples goExamples docsHandler = send docs goDocs communityHandler = send community goCommunity
dmjio/miso
examples/haskell-miso.org/server/Main.hs
bsd-3-clause
6,330
0
17
1,808
1,154
614
540
132
1
#!/usr/bin/env stack -- stack runghc --verbosity info --package hledger-lib -- Run this script from inside the hledger source tree, so that it -- will use the corresponding source version of hledger, which is the -- version it is tested with. -- -- You can compile these scripts by running compile.sh in this directory. -- The compiled executables can be run from anywhere, so you could add -- this directory to your $PATH and see them in hledger's command list. -- -- You could make this a standalone script that runs from anywhere and -- recompiles itself when changed, by replacing "runghc" above with -- "script --compile --resolver lts-16" (eg). However this uses the -- hledger version from that stackage resolver, so in this case you -- should check out the corresponding release-tagged version of this -- script for compatibility (eg: git checkout 1.18.1). -- -- This setup is adapted for some current limitations of stack's -- ghc/runghc/script commands. Unfortunately it requires repeating -- package dependencies, to the extent they are required, in multiple -- places. -- Keep synced: compile.sh, scripts*.test, hledger-*.hs ... {- ``` Usage: hledger-check-fancyassertions [-f|--file FILE] [--alias OLD=NEW] [--ignore-assertions] [-b|--begin DATE] [-e|--end DATE] [-C|--cleared] [--pending] [-U|--unmarked] [-R|--real] [--sunday] [-D|--daily ASSERT] [-W|--weekly ASSERT] [-M|--monthly ASSERT] [-Q|--quarterly ASSERT] [-Y|--yearly ASSERT] [ASSERT] Complex account balance assertions for hledger journals. Available options: -h,--help Show this help text -f,--file FILE use a different input file. For stdin, use - --alias OLD=NEW display accounts named OLD as NEW --ignore-assertions ignore any balance assertions in the journal -b,--begin DATE include postings/txns on or after this date -e,--end DATE include postings/txns before this date -U,--unmarked include only unmarked postings/txns -P,--pending include only pending postings/txns -C,--cleared include only cleared postings/txns -R,--real include only non-virtual postings --sunday weeks start on Sunday -D,--daily ASSERT assertions that must hold at the end of the day -W,--weekly ASSERT assertions that must hold at the end of the week -M,--monthly ASSERT assertions that must hold at the end of the month -Q,--quarterly ASSERT assertions that must hold at the end of the quarter -Y,--yearly ASSERT assertions that must hold at the end of the year ASSERT assertions that must hold after every transaction ``` Comparison: `<value OR account name> cmp <value OR account name>` ------------------------------------------------------------------- In the simplest form, an assertion is just a comparison between values. A value is either an amount or an account name (both as defined by hledger). The comparison operators are `<`, `<=`, `==`, `>=`, `>`, and `!=` (with the obvious meanings). Normally, the name of an account refers to the balance of that account only, without including subaccounts. The syntax `* AccountName` refers to the sum of the values in both that account and its subaccounts. **Example:** ``` hledger-check-fancyassertions -D "budget:books >= £0" ``` "At the end of every day, the books budget is greater than or equal to £0", implying that if I overspend, I need to take the money out of some other account. Note the double space after `budget:books`, this is because account names can contain single spaces. Combination: `<assertion> op <assertion>` ------------------------------------------- Assertions can be combined with logical connectives. The connectives are `&&`, `||`, `==>`, and `<==>` (with the obvious meanings). Assertions can also be wrapped inside parentheses. **Example:** ``` hledger-check-fancyassertions "(assets:overdraft < £2000) ==> (*assets:checking == £0)" ``` "If I have taken money from my overdraft, then I must have no money in my checking account (including subaccounts)." -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} module Main where import Control.Arrow (first) import Control.Monad (mplus, mzero, unless, void) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.State.Strict (runStateT) import Data.String (fromString) import Data.Function (on) import Data.Functor (($>)) import Data.Functor.Identity (Identity(..)) import Data.List (foldl', groupBy, intercalate, nub, sortOn) import Data.List.NonEmpty (NonEmpty(..), nonEmpty, toList) import Data.Maybe (fromMaybe, mapMaybe) import Data.Time.Calendar (toGregorian) import Data.Time.Calendar.OrdinalDate (mondayStartWeek, sundayStartWeek, toOrdinalDate) import Data.Text (Text, isPrefixOf, pack, unpack) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Hledger.Data as H import qualified Hledger.Query as H import qualified Hledger.Read as H import qualified Hledger.Utils.Parse as H import Lens.Micro (set) import Options.Applicative import System.Exit (exitFailure) import System.FilePath (FilePath) import qualified Text.Megaparsec as P import qualified Text.Megaparsec.Char as P -- Don't know how to preserve newlines yet. helptxt = unlines [ "ASSERTIONS can be:" ,"" ,"1. <VALUE_OR_ACCT> CMP <VALUE_OR_ACCT> -" ,"" ,"In the simplest form, an assertion is just a comparison between" ,"values. A value is either an amount or an account name (both as" ,"defined by hledger). The comparison operators are <, <=, ==," ,">=, >, and != (with the obvious meanings)." ,"" ,"Normally, the name of an account refers to the balance of that account" ,"only, without including subaccounts. The syntax `* ACCT` refers" ,"to the sum of the values in both that account and its subaccounts." ,"" ,"Example:" ,"" ,"hledger-check-fancyassertions -D 'budget:books >= £0'" ,"" ,"" ,"\"At the end of every day, the books budget is greater than or equal to" ,"£0\", implying that if I overspend, I need to take the money out of" ,"some other account. Note the double space after budget:books, this is" ,"because account names can contain single spaces." ,"" ,"2. <ASSERTION> OP <ASSERTION> -" ,"" ,"Assertions can be combined with logical connectives. The connectives" ,"are &&, ||, ==>, and <==> (with the obvious meanings)." ,"Assertions can also be wrapped inside parentheses." ,"" ,"Example:" ,"" ,"hledger-check-fancyassertions '(assets:overdraft < £2000) ==> (*assets:checking == £0)'" ,"" ,"" ,"\"If I have taken money from my overdraft, then I must have no money in" ,"my checking account (including subaccounts).\"" ] main :: IO () main = do opts <- execParser args journalFile <- maybe H.defaultJournalPath pure (file opts) ejournal <- H.readJournalFile (set H.ignore_assertions (ignoreAssertions opts) H.definputopts) journalFile case ejournal of Right j -> do (journal, starting) <- fixupJournal opts j let postings = H.journalPostings journal b1 <- checkAssertions starting (assertionsAlways opts) (groupByNE ((==) `on` H.ptransaction) postings) b2 <- checkAssertions starting (assertionsDaily opts) (groupByNE sameDay postings) b3 <- checkAssertions starting (assertionsWeekly opts) (groupByNE (sameWeek (sunday opts)) postings) b4 <- checkAssertions starting (assertionsMonthly opts) (groupByNE sameMonth postings) b5 <- checkAssertions starting (assertionsQuarterly opts) (groupByNE sameQuarter postings) b6 <- checkAssertions starting (assertionsYearly opts) (groupByNE sameYear postings) unless (b1 && b2 && b3 && b4 && b5 && b6) exitFailure Left err -> putStrLn err >> exitFailure ------------------------------------------------------------------------------- -- Assertions -- | Check assertions against a collection of grouped postings: -- assertions must hold when all postings in the group have been -- applied. Print out errors as they are found. checkAssertions :: [(H.AccountName, H.MixedAmount)] -> [(Text, Predicate)] -> [NonEmpty H.Posting] -> IO Bool checkAssertions balances0 asserts0 postingss | null failed = pure True | otherwise = T.putStrLn (T.intercalate "\n\n" failed) >> pure False where (_, _, failed) = foldl' applyAndCheck (balances0, asserts0, []) postingss -- Apply a collection of postings and check the assertions. applyAndCheck :: ([(H.AccountName, H.MixedAmount)], [(Text, Predicate)], [Text]) -> NonEmpty H.Posting -> ([(H.AccountName, H.MixedAmount)], [(Text, Predicate)], [Text]) applyAndCheck (starting, asserts, errs) ps = let ps' = toList ps closing = starting `addAccounts` closingBalances' ps' checked = map (\a -> (a, check (last ps') closing a)) asserts asserts' = [a | (a, Nothing) <- checked] errs' = [e | (_, Just e) <- checked] in (closing, asserts', errs ++ errs') -- Check an assertion against a collection of account balances, -- and return an error on failure. check :: H.Posting -> [(H.AccountName, H.MixedAmount)] -> (Text, Predicate) -> Maybe Text check lastp balances (pstr, p) | checkAssertion balances p = Nothing | otherwise = Just . T.unlines $ let after = case H.ptransaction lastp of Just t -> "after transaction:\n" <> H.showTransaction t <> "(after posting: " <> T.pack (init $ H.showPosting lastp) <> ")\n\n" Nothing -> "after posting:\n" <> T.pack (H.showPosting lastp) -- Restrict to accounts mentioned in the predicate, and pretty-print balances balances' = filter (flip inAssertion p . fst) balances maxalen = maximum $ map (T.length . fst) balances' accounts = [ a <> padding <> T.pack (show m) | (a,m) <- balances' , let padding = T.replicate (2 + maxalen - T.length a) " " ] in [ "assertion '" <> pstr <> "' violated", after <> "relevant balances:"] ++ map (" "<>) accounts -- | Check an assertion holds for a collection of account balances. checkAssertion :: [(H.AccountName, H.MixedAmount)] -> Predicate -> Bool checkAssertion accounts = checkAssertion' where checkAssertion' (Not p) = not (checkAssertion' p) checkAssertion' (Connect p1 c p2) = let p1' = checkAssertion' p1 p2' = checkAssertion' p2 in case c of AND -> p1' && p2' OR -> p1' || p2' IMPLIES -> not p1' || p2' IFF -> p1' == p2' checkAssertion' (Compare v1 c v2) = let v1e = evaluate v1 v2e = evaluate v2 v1' = fixup v1e v2e v2' = fixup v2e v1e in case c of LLT -> v1' < v2' EEQ -> v1' == v2' GGT -> v1' > v2' LTE -> v1' <= v2' NEQ -> v1' /= v2' GTE -> v1' >= v2' evaluate (Account account) = fromMaybe H.nullmixedamt $ lookup account accounts evaluate (AccountNested account) = H.maSum [m | (a,m) <- accounts, account == a || (a <> pack ":") `isPrefixOf` account] evaluate (Amount amount) = H.mixed [amount] -- Add missing amounts (with 0 value), normalise, throw away style -- information, and sort by commodity name. fixup m1 m2 = let m = H.mixed $ H.amounts m1 ++ [m_ { H.aquantity = 0 } | m_ <- H.amounts m2] as = H.amounts m in H.mixed $ sortOn H.acommodity . map (\a -> a { H.astyle = H.amountstyle }) $ as -- | Check if an account name is mentioned in an assertion. inAssertion :: H.AccountName -> Predicate -> Bool inAssertion account = inAssertion' where inAssertion' (Not p) = not (inAssertion' p) inAssertion' (Connect p1 _ p2) = inAssertion' p1 || inAssertion' p2 inAssertion' (Compare v1 _ v2) = inValue v1 || inValue v2 inValue (Account a) = account == a inValue (AccountNested a) = account == a || (a <> pack ":") `isPrefixOf` account inValue (Amount _) = False ------------------------------------------------------------------------------- -- Journals -- | Apply account aliases and restrict to the date range, return the -- starting balance of every account. fixupJournal :: Opts -> H.Journal -> IO (H.Journal, [(H.AccountName, H.MixedAmount)]) fixupJournal opts j = do today <- H.getCurrentDay let j' = (if cleared opts then H.filterJournalTransactions (H.StatusQ H.Cleared) else id) . (if pending opts then H.filterJournalTransactions (H.StatusQ H.Pending) else id) . (if unmarked opts then H.filterJournalTransactions (H.StatusQ H.Unmarked) else id) . (if real opts then H.filterJournalTransactions (H.Real True) else id) $ j let starting = case begin opts of Just _ -> let dateSpan = H.DateSpan Nothing (fixDay today begin) in closingBalances (H.filterJournalPostings (H.Date dateSpan) j') Nothing -> [] let dateSpan = H.DateSpan (fixDay today begin) (fixDay today end) pure (H.filterJournalTransactions (H.Date dateSpan) j', starting) where fixDay today dayf = H.fixSmartDate today <$> dayf opts -- | Get the closing balances of every account in the journal. closingBalances :: H.Journal -> [(H.AccountName, H.MixedAmount)] closingBalances = closingBalances' . H.journalPostings -- | Get the closing balances of every account referenced by a group -- of postings. closingBalances' :: [H.Posting] -> [(H.AccountName, H.MixedAmount)] closingBalances' postings = let postingsByAccount = groupBy ((==) `on` H.paccount) . sortOn H.paccount $ postings in map (\ps@(p:_) -> (H.paccount p, H.sumPostings ps)) postingsByAccount -- | Add balances in matching accounts. addAccounts :: [(H.AccountName, H.MixedAmount)] -> [(H.AccountName, H.MixedAmount)] -> [(H.AccountName, H.MixedAmount)] addAccounts as1 as2 = [ (a, a1 `H.maPlus` a2) | a <- nub (map fst as1 ++ map fst as2) , let a1 = fromMaybe H.nullmixedamt $ lookup a as1 , let a2 = fromMaybe H.nullmixedamt $ lookup a as2 ] ------------------------------------------------------------------------------- -- Dates -- | Check if two postings are in the same day. sameDay :: H.Posting -> H.Posting -> Bool sameDay = sameish id -- | Check if two postings are in the same week. sameWeek :: Bool -> H.Posting -> H.Posting -> Bool sameWeek startSunday p1 p2 = let startWeek = if startSunday then sundayStartWeek else mondayStartWeek d1 = H.postingDate p1 d2 = H.postingDate p2 y1 = fst (toOrdinalDate d1) y2 = fst (toOrdinalDate d2) w1 = fst (startWeek d1) w2 = fst (startWeek d2) sameYearSameWeek = y1 == y2 && w1 == w2 week0Week52 = y1 == y2+1 && w1 == 0 && w2 == 52 week52Week0 = 1+y1 == y2 && w1 == 52 && w2 == 0 in sameYearSameWeek || week0Week52 || week52Week0 -- | Check if two postings are in the same month. sameMonth :: H.Posting -> H.Posting -> Bool sameMonth = sameish (\(y,m,_) -> (y,m)) -- | Check if two postings are in the same quarter. sameQuarter :: H.Posting -> H.Posting -> Bool sameQuarter = sameish (\(y,m,_) -> (y, m `div` 4)) -- | Check if two postings are in the same year. sameYear :: H.Posting -> H.Posting -> Bool sameYear = sameish (\(y,_,_) -> y) ------------------------------------------------------------------------------- -- Command-line Arguments -- | Parsed command-line arguments. data Opts = Opts { file :: Maybe FilePath -- ^ Path to journal file. , aliases :: [H.AccountAlias] -- ^ Account name aliases: (OLD, NEW). , ignoreAssertions :: Bool -- ^ Ignore balance assertions while reading the journal file (but -- still apply any given to this tool. , begin :: Maybe H.SmartDate -- ^ Exclude postings/txns before this date. , end :: Maybe H.SmartDate -- ^ Exclude postings/txns on or after this date. , cleared :: Bool -- ^ Include only cleared postings/txns. , pending :: Bool -- ^ Include only pending postings/txns. , unmarked :: Bool -- ^ Include only unmarked postings/txns. , real :: Bool -- ^ Include only non-virtual postings. , sunday :: Bool -- ^ Week starts on Sunday. , assertionsDaily :: [(Text, Predicate)] -- ^ Account assertions that must hold at the end of each day. , assertionsWeekly :: [(Text, Predicate)] -- ^ Account assertions that must hold at the end of each week. , assertionsMonthly :: [(Text, Predicate)] -- ^ Account assertions that must hold at the end of each month. , assertionsQuarterly :: [(Text, Predicate)] -- ^ Account assertions that must hold at the end of each quarter. , assertionsYearly :: [(Text, Predicate)] -- ^ Account assertions that must hold at the end of each year. , assertionsAlways :: [(Text, Predicate)] -- ^ Account assertions that must hold after each txn. } deriving (Show) -- | Command-line arguments. args :: ParserInfo Opts args = info (helper <*> parser) $ mconcat [ fullDesc , progDesc "Complex account balance assertions for hledger journals." , footer helptxt ] where parser = Opts <$> (optional . strOption) (arg 'f' "file" "use a different input file. For stdin, use -" <> metavar "FILE") <*> (many . fmap snd . popt (lift H.accountaliasp)) (arg' "alias" "display accounts named OLD as NEW" <> metavar "OLD=NEW") <*> switch (arg' "ignore-assertions" "ignore any balance assertions in the journal") <*> (optional . fmap snd . popt' H.smartdate) (arg 'b' "begin" "include postings/txns on or after this date" <> metavar "DATE") <*> (optional . fmap snd . popt' H.smartdate) (arg 'e' "end" "include postings/txns before this date" <> metavar "DATE") <*> switch (arg 'C' "cleared" "include only cleared postings/txns") <*> switch (arg' "pending" "include only pending postings/txns") <*> switch (arg 'U' "unmarked" "include only unmarked postings/txns") <*> switch (arg 'R' "real" "include only non-virtual postings") <*> switch (arg' "sunday" "weeks start on Sunday") <*> (many . popt predicatep) (arg 'D' "daily" "assertions that must hold at the end of the day" <> metavar "ASSERT") <*> (many . popt predicatep) (arg 'W' "weekly" "assertions that must hold at the end of the week" <> metavar "ASSERT") <*> (many . popt predicatep) (arg 'M' "monthly" "assertions that must hold at the end of the month" <> metavar "ASSERT") <*> (many . popt predicatep) (arg 'Q' "quarterly" "assertions that must hold at the end of the quarter" <> metavar "ASSERT") <*> (many . popt predicatep) (arg 'Y' "yearly" "assertions that must hold at the end of the year" <> metavar "ASSERT") <*> (many . parg predicatep) (help "assertions that must hold after every transaction" <> metavar "ASSERT") -- Shorthand for options arg s l h = arg' l h <> short s arg' l h = long l <> help h -- Arguments and options from a Megaparsec parser. parg = argument . readParsec popt = option . readParsec popt' = option . readParsec' -- Turn a Parsec parser into a ReadM parser that also returns the -- input. readParsec :: H.JournalParser ReadM a -> ReadM (Text, a) readParsec p = do s <- str parsed <- P.runParserT (runStateT p H.nulljournal) "" s case parsed of Right (a, _) -> pure (s, a) Left err -> fail ("failed to parse input '" ++ unpack s ++ "': " ++ P.errorBundlePretty err) readParsec' :: H.SimpleTextParser a -> ReadM (String, a) readParsec' p = do s <- str let parsed = runIdentity $ P.runParserT p "" (pack s) case parsed of Right a -> pure (s, a) Left err -> fail ("failed to parse input '" ++ s ++ "': " ++ P.errorBundlePretty err) ------------------------------------------------------------------------------- -- Predicates & Parsers data Predicate = Compare Value Compare Value | Connect Predicate Connect Predicate | Not Predicate deriving (Eq, Ord, Show) -- | Parse a 'Predicate'. predicatep :: Monad m => H.JournalParser m Predicate predicatep = wrap predparensp <|> wrap predcomparep <|> wrap prednotp where predparensp = P.char '(' *> spaces *> predicatep <* spaces <* P.char ')' predcomparep = Compare <$> valuep <*> (spaces *> lift comparep <* spaces) <*> valuep prednotp = void (P.char '!') *> (Not <$> predicatep) spaces = void . many $ P.char ' ' wrap p = do a <- P.try p spaces P.try (wrap $ do c <- lift connectp; spaces; Connect a c <$> p) <|> pure a data Value = Account H.AccountName | AccountNested H.AccountName | Amount H.Amount deriving (Eq, Ord, Show) -- | Parse a 'Value'. valuep :: Monad m => H.JournalParser m Value -- Account name parser has to come last because they eat everything. valuep = P.try valueamountp <|> P.try valueaccountnestedp <|> valueaccountp where valueamountp = Amount <$> H.amountp valueaccountp = Account <$> lift H.accountnamep valueaccountnestedp = AccountNested <$> (P.char '*' *> spaces *> lift H.accountnamep) spaces = void . many $ P.char ' ' data Compare = LLT | EEQ | GGT | LTE | NEQ | GTE deriving (Eq, Ord, Read, Show, Bounded, Enum) -- | Parse a 'Compare'. comparep :: Monad m => H.TextParser m Compare comparep = gostringsp [("<=", LTE), ("<", LLT), ("==", EEQ), (">=", GTE), (">", GGT), ("!=", NEQ)] data Connect = AND | OR | IMPLIES | IFF deriving (Eq, Ord, Read, Show, Bounded, Enum) -- | Parse a 'Connect'. connectp :: Monad m => H.TextParser m Connect connectp = gostringsp [("&&", AND), ("||", OR), ("==>", IMPLIES), ("<==>", IFF)] ------------------------------------------------------------------------------- -- Utilities -- | Group values in a list into nonempty subsequences. groupByNE :: (a -> a -> Bool) -> [a] -> [NonEmpty a] groupByNE f = mapMaybe nonEmpty . groupBy f -- | Check if two postings are on the sameish date, given a function -- to convert the posting date (in (Y,M,D) format) to some comparable -- value. sameish :: Eq a => ((Integer, Int, Int) -> a) -> H.Posting -> H.Posting -> Bool sameish f = (==) `on` f . toGregorian . H.postingDate -- | Helper for 'Compare' and 'Connect' parsers. gostringsp :: Monad m => [(String, a)] -> H.TextParser m a gostringsp ((s,a):rest) = P.try (P.string (fromString s) $> a) `mplus` gostringsp rest gostringsp [] = mzero
adept/hledger
bin/hledger-check-fancyassertions.hs
gpl-3.0
23,623
94
23
5,969
5,015
2,721
2,294
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.SES.SetIdentityNotificationTopic -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | Given an identity (email address or domain), sets the Amazon Simple -- Notification Service (Amazon SNS) topic to which Amazon SES will publish -- bounce, complaint, and/or delivery notifications for emails sent with that -- identity as the 'Source'. -- -- This action is throttled at one request per second. -- -- For more information about feedback notification, see the <http://docs.aws.amazon.com/ses/latest/DeveloperGuide/notifications.html Amazon SESDeveloper Guide>. -- -- <http://docs.aws.amazon.com/ses/latest/APIReference/API_SetIdentityNotificationTopic.html> module Network.AWS.SES.SetIdentityNotificationTopic ( -- * Request SetIdentityNotificationTopic -- ** Request constructor , setIdentityNotificationTopic -- ** Request lenses , sintIdentity , sintNotificationType , sintSnsTopic -- * Response , SetIdentityNotificationTopicResponse -- ** Response constructor , setIdentityNotificationTopicResponse ) where import Network.AWS.Prelude import Network.AWS.Request.Query import Network.AWS.SES.Types import qualified GHC.Exts data SetIdentityNotificationTopic = SetIdentityNotificationTopic { _sintIdentity :: Text , _sintNotificationType :: NotificationType , _sintSnsTopic :: Maybe Text } deriving (Eq, Read, Show) -- | 'SetIdentityNotificationTopic' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'sintIdentity' @::@ 'Text' -- -- * 'sintNotificationType' @::@ 'NotificationType' -- -- * 'sintSnsTopic' @::@ 'Maybe' 'Text' -- setIdentityNotificationTopic :: Text -- ^ 'sintIdentity' -> NotificationType -- ^ 'sintNotificationType' -> SetIdentityNotificationTopic setIdentityNotificationTopic p1 p2 = SetIdentityNotificationTopic { _sintIdentity = p1 , _sintNotificationType = p2 , _sintSnsTopic = Nothing } -- | The identity for which the Amazon SNS topic will be set. Examples: '[email protected]', 'example.com'. sintIdentity :: Lens' SetIdentityNotificationTopic Text sintIdentity = lens _sintIdentity (\s a -> s { _sintIdentity = a }) -- | The type of notifications that will be published to the specified Amazon SNS -- topic. sintNotificationType :: Lens' SetIdentityNotificationTopic NotificationType sintNotificationType = lens _sintNotificationType (\s a -> s { _sintNotificationType = a }) -- | The Amazon Resource Name (ARN) of the Amazon SNS topic. If the parameter is -- omitted from the request or a null value is passed, 'SnsTopic' is cleared and -- publishing is disabled. sintSnsTopic :: Lens' SetIdentityNotificationTopic (Maybe Text) sintSnsTopic = lens _sintSnsTopic (\s a -> s { _sintSnsTopic = a }) data SetIdentityNotificationTopicResponse = SetIdentityNotificationTopicResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'SetIdentityNotificationTopicResponse' constructor. setIdentityNotificationTopicResponse :: SetIdentityNotificationTopicResponse setIdentityNotificationTopicResponse = SetIdentityNotificationTopicResponse instance ToPath SetIdentityNotificationTopic where toPath = const "/" instance ToQuery SetIdentityNotificationTopic where toQuery SetIdentityNotificationTopic{..} = mconcat [ "Identity" =? _sintIdentity , "NotificationType" =? _sintNotificationType , "SnsTopic" =? _sintSnsTopic ] instance ToHeaders SetIdentityNotificationTopic instance AWSRequest SetIdentityNotificationTopic where type Sv SetIdentityNotificationTopic = SES type Rs SetIdentityNotificationTopic = SetIdentityNotificationTopicResponse request = post "SetIdentityNotificationTopic" response = nullResponse SetIdentityNotificationTopicResponse
kim/amazonka
amazonka-ses/gen/Network/AWS/SES/SetIdentityNotificationTopic.hs
mpl-2.0
4,837
0
9
958
471
290
181
59
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="zh-CN"> <title>Replacer | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/replacer/src/main/javahelp/org/zaproxy/zap/extension/replacer/resources/help_zh_CN/helpset_zh_CN.hs
apache-2.0
970
85
52
159
396
209
187
-1
-1
module Haskus.Tests.Common ( isBijective , isEquivalent , ArbitraryByteString (..) , ArbitraryByteStringNoNul (..) , ArbitraryBuffer (..) , ArbitraryBufferNoNul (..) ) where import Test.Tasty.QuickCheck as QC import qualified Data.ByteString as BS import Haskus.Format.Binary.Buffer -- | Ensure a function is bijective isBijective :: Eq a => (a -> a) -> a -> Bool isBijective f w = w == (f (f w)) -- | Ensure that two functions return the same thing for the same input isEquivalent :: Eq b => (a -> b) -> (a -> b) -> a -> Bool isEquivalent f g x = (f x) == (g x) -- | Arbitrary ByteString (50 chars long max) newtype ArbitraryByteString = ArbitraryByteString BS.ByteString deriving (Show) instance Arbitrary ArbitraryByteString where arbitrary = ArbitraryByteString . BS.pack <$> resize 50 (listOf arbitrary) shrink (ArbitraryByteString bs) | BS.null bs = [] | otherwise = [ArbitraryByteString $ BS.take (BS.length bs `div` 2) bs] -- | Arbitrary ByteString (50 chars long max, no Nul) newtype ArbitraryByteStringNoNul = ArbitraryByteStringNoNul BS.ByteString deriving (Show) instance Arbitrary ArbitraryByteStringNoNul where arbitrary = ArbitraryByteStringNoNul . BS.pack <$> resize 50 (listOf (choose (1,255))) -- we exclude 0 shrink (ArbitraryByteStringNoNul bs) | BS.null bs = [] | otherwise = [ArbitraryByteStringNoNul $ BS.take (BS.length bs `div` 2) bs] -- | Arbitrary Buffer (50 chars long max) newtype ArbitraryBuffer = ArbitraryBuffer Buffer deriving (Show) instance Arbitrary ArbitraryBuffer where arbitrary = do ArbitraryByteString bs <- arbitrary return (ArbitraryBuffer (Buffer bs)) shrink (ArbitraryBuffer bs) | isBufferEmpty bs = [] | otherwise = [ArbitraryBuffer $ bufferTake (bufferSize bs `div` 2) bs] -- | Arbitrary Buffer (50 chars long max, no Nul) newtype ArbitraryBufferNoNul = ArbitraryBufferNoNul Buffer deriving (Show) instance Arbitrary ArbitraryBufferNoNul where arbitrary = do ArbitraryByteStringNoNul bs <- arbitrary return (ArbitraryBufferNoNul (Buffer bs)) shrink (ArbitraryBufferNoNul bs) | isBufferEmpty bs = [] | otherwise = [ArbitraryBufferNoNul $ bufferTake (bufferSize bs `div` 2) bs]
hsyl20/ViperVM
haskus-system/src/tests/Haskus/Tests/Common.hs
bsd-3-clause
2,345
0
13
524
662
350
312
50
1
{-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.SourceCandy -- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GNU-GPL -- -- Maintainer : <maintainer at leksah.org> -- Stability : provisional -- Portability : portable -- -- -- | -- --------------------------------------------------------------------------------- module IDE.SourceCandy ( parseCandy -- :: FilePath -> IO alpha , transformToCandy -- :: TextBuffer -> IO () , transformFromCandy -- :: TextBuffer -> IO () , keystrokeCandy -- :: Maybe Char -> TextBuffer -> IO () , getCandylessText -- :: TextBuffer -> IO Text , getCandylessPart -- :: CandyTable -> TextBuffer -> TextIter -> TextIter -> IO Text , stringToCandy -- :: CandyTable -> Text -> IO Text , positionToCandy -- :: CandyTable -> TextBuffer -> (Int,Int) -> IO (Int,Int) , positionFromCandy -- :: CandyTable -> TextBuffer -> (Int,Int) -> IO (Int,Int) ) where import Control.Applicative import Prelude hiding(getChar, getLine) import Data.Char(chr) import Data.List (elemIndices, isInfixOf, isSuffixOf) import Text.ParserCombinators.Parsec as P import qualified Text.ParserCombinators.Parsec.Token as P import Text.ParserCombinators.Parsec.Language(emptyDef) import qualified Data.Set as Set import IDE.Core.State import IDE.TextEditor import Control.Monad (when, unless) import Data.Text (Text) import qualified Data.Text as T (pack, singleton, replicate, head, takeWhile, isSuffixOf, length, index) import Data.Monoid ((<>)) import Control.Monad.IO.Class (MonadIO(..)) import Graphics.UI.Gtk.SourceView (sourceBufferNew) import Graphics.UI.Gtk.Multiline.TextBuffer (textBufferGetIterAtMark, textBufferCreateMark, textBufferSetText) --------------------------------------------------------------------------------- -- * Implementation notBeforeId = Set.fromList $['a'..'z'] ++ ['A'..'Z'] ++ "_" notAfterId = Set.fromList $['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ "_" notBeforeOp = Set.fromList "!#$%&*+./<=>?@\\^|-~'\"" notAfterOp = notBeforeOp keystrokeCandy :: TextEditor editor => CandyTable -> Maybe Char -> EditorBuffer editor -> (Text -> Bool) -> IDEM () keystrokeCandy (CT(transformTable,_)) mbc ebuf editInCommentOrString = do cursorMark <- getInsertMark ebuf endIter <- getIterAtMark ebuf cursorMark lineNr <- getLine endIter columnNr <- getLineOffset endIter offset <- getOffset endIter startIter <- backwardToLineStartC endIter slice <- getSlice ebuf startIter endIter True mbc2 <- case mbc of Just c -> return (Just c) Nothing -> getChar endIter let block = editInCommentOrString slice unless block $ replace mbc2 cursorMark slice offset transformTable where -- replace :: Maybe Char -> m -> Text -> Int -> [(Bool,Text,Text)] -> IDEM () replace mbAfterChar cursorMark match offset = replace' where replace' [] = return () replace' ((isOp,from,to):rest) = let beforeChar = T.index match (max 0 (T.length match - (T.length from + 1))) beforeOk = not $ if isOp then Set.member beforeChar notBeforeOp else Set.member beforeChar notBeforeId afterOk = case mbAfterChar of Nothing -> True Just afterChar -> not $ if isOp then Set.member afterChar notAfterOp else Set.member afterChar notAfterId in if T.isSuffixOf from match && beforeOk && afterOk then do beginNotUndoableAction ebuf start <- getIterAtOffset ebuf (offset - T.length from) end <- getIterAtOffset ebuf offset delete ebuf start end ins <- getIterAtMark ebuf cursorMark insert ebuf ins to endNotUndoableAction ebuf else replace mbAfterChar cursorMark match offset rest transformToCandy :: TextEditor editor => CandyTable -> EditorBuffer editor -> (Text -> Bool) -> IDEM () transformToCandy (CT(transformTable,_)) ebuf editInCommentOrString = do beginUserAction ebuf modified <- getModified ebuf mapM_ (\tbl -> replaceTo ebuf tbl 0 editInCommentOrString) transformTable setModified ebuf modified endUserAction ebuf replaceTo :: TextEditor editor => EditorBuffer editor -> (Bool,Text,Text) -> Int -> (Text -> Bool) -> IDEM () replaceTo buf (isOp,from,to) offset editInCommentOrString = replaceTo' offset where replaceTo' offset = do iter <- getIterAtOffset buf offset mbStartEnd <- forwardSearch iter from [] Nothing case mbStartEnd of Nothing -> return () Just (st,end) -> do stOff <- getOffset st lineNr <- getLine end columnNr <- getLineOffset end startIter <- backwardToLineStartC end slice <- getSlice buf startIter end True let block = editInCommentOrString slice unless block $ do beforeOk <- if stOff == 0 then return True else do iter <- getIterAtOffset buf (stOff - 1) mbChar <- getChar iter case mbChar of Nothing -> return True Just char -> return (not $ if isOp then Set.member char notBeforeOp else Set.member char notBeforeId) when beforeOk $ do afterOk <- do endOff <- getOffset end iter <- getIterAtOffset buf endOff mbChar <- getChar iter case mbChar of Nothing -> return True Just char -> return (not $ if isOp then Set.member char notAfterOp else Set.member char notAfterId) when afterOk $ do delete buf st end insert buf st to return () replaceTo' (stOff + 1) transformFromCandy :: TextEditor editor => CandyTable -> EditorBuffer editor -> IDEM () transformFromCandy (CT(_,transformTableBack)) ebuf = do beginUserAction ebuf modified <- getModified ebuf mapM_ (\tbl -> replaceFrom ebuf tbl 0) transformTableBack endUserAction ebuf setModified ebuf modified simpleGtkBuffer :: Text -> IDEM (EditorBuffer GtkSourceView) simpleGtkBuffer contents = liftIO $ GtkBuffer <$> do buffer <- sourceBufferNew Nothing textBufferSetText buffer contents return buffer getCandylessText :: TextEditor editor => CandyTable -> EditorBuffer editor -> IDEM Text getCandylessText (CT(_,transformTableBack)) ebuf = do i1 <- getStartIter ebuf i2 <- getEndIter ebuf text1 <- getText ebuf i1 i2 True workBuffer <- simpleGtkBuffer text1 mapM_ (\tbl -> replaceFrom workBuffer tbl 0) transformTableBack i1 <- getStartIter workBuffer i2 <- getEndIter workBuffer getText workBuffer i1 i2 True getCandylessPart :: TextEditor editor => CandyTable -> EditorBuffer editor -> EditorIter editor -> EditorIter editor -> IDEM Text getCandylessPart (CT(_,transformTableBack)) ebuf i1 i2 = do text1 <- getText ebuf i1 i2 True workBuffer <- simpleGtkBuffer text1 mapM_ (\tbl -> replaceFrom workBuffer tbl 0) transformTableBack i1 <- getStartIter workBuffer i2 <- getEndIter workBuffer getText workBuffer i1 i2 True stringToCandy :: CandyTable -> Text -> IDEM Text stringToCandy candyTable text = do workBuffer <- simpleGtkBuffer text transformToCandy candyTable workBuffer (const False) i1 <- getStartIter workBuffer i2 <- getEndIter workBuffer getText workBuffer i1 i2 True -- We only need a TextMark here not a SourceMark createTextMark (GtkBuffer sb) (GtkIter i) leftGravity = liftIO $ textBufferCreateMark sb Nothing i leftGravity getIterAtTextMark (GtkBuffer sb) m = liftIO $ GtkIter <$> textBufferGetIterAtMark sb m positionFromCandy :: TextEditor editor => CandyTable -> EditorBuffer editor -> (Int,Int) -> IDEM (Int,Int) positionFromCandy candyTable ebuf (line,column) = do i1 <- getIterAtLine ebuf (max 0 (line - 1)) i2 <- forwardToLineEndC i1 text <- getText ebuf i1 i2 True workBuffer <- simpleGtkBuffer text i3 <- getIterAtOffset workBuffer column mark <- createTextMark workBuffer i3 True transformFromCandy candyTable workBuffer i4 <- getIterAtTextMark workBuffer mark columnNew <- getLineOffset i4 return (line,columnNew) positionToCandy :: TextEditor editor => CandyTable -> EditorBuffer editor -> (Int,Int) -> IDEM (Int,Int) positionToCandy candyTable ebuf (line,column) = do i1 <- getIterAtLine ebuf (max 0 (line - 1)) i2 <- forwardToLineEndC i1 text <- getText ebuf i1 i2 True workBuffer <- simpleGtkBuffer text transformFromCandy candyTable workBuffer i3 <- getIterAtOffset workBuffer column mark <- createTextMark workBuffer i3 True transformToCandy candyTable workBuffer (const False) i4 <- getIterAtTextMark workBuffer mark columnNew <- getLineOffset i4 return (line,columnNew) replaceFrom :: TextEditor editor => EditorBuffer editor -> (Text,Text,Int) -> Int -> IDEM () replaceFrom buf (to,from,spaces) = replaceFrom' where replaceFrom' offset = do iter <- getIterAtOffset buf offset mbStartEnd <- forwardSearch iter from [] Nothing case mbStartEnd of Nothing -> return () Just (st,end) -> do offset <- getOffset st delete buf st end when (spaces > 0) $ do iter2 <- getIterAtOffset buf offset iter3 <- getIterAtOffset buf (offset + spaces + 1) slice <- getSlice buf iter2 iter3 True let l = T.length (T.takeWhile (== ' ') slice) when (l > 1) $ do iter4 <- atOffset iter3 (offset + l - 1) delete buf iter2 iter4 iter <- getIterAtOffset buf offset insert buf iter to replaceFrom' offset type CandyTableI = [(Text,Char,Bool)] forthFromTable :: CandyTableI -> CandyTableForth forthFromTable = map forthFrom where forthFrom (str,chr,noTrimming) = let isOp = not (Set.member (T.head str) notBeforeId) from = str trailingBlanks = T.replicate (if noTrimming then 0 else T.length str - 1) (T.singleton ' ') to = T.singleton chr <> trailingBlanks in (isOp,from,to) backFromTable :: CandyTableI -> CandyTableBack backFromTable = map backFrom where backFrom (str,chr,noTrimming) = let numTrailingBlanks = if noTrimming then 0 else T.length str - 1 in (str,T.singleton chr,numTrailingBlanks) ---Candy Parser candyStyle :: P.LanguageDef st candyStyle = emptyDef { P.commentStart = "{-" , P.commentEnd = "-}" , P.commentLine = "--" } lexer = P.makeTokenParser candyStyle lexeme = P.lexeme lexer whiteSpace = P.whiteSpace lexer hexadecimal = P.hexadecimal lexer symbol = P.symbol lexer parseCandy :: FilePath -> IO CandyTable parseCandy fn = do res <- parseFromFile candyParser fn case res of Left pe -> throwIDE $ "Error reading candy file " <> T.pack (show fn) <> " " <> T.pack (show pe) Right r -> return (CT(forthFromTable r, backFromTable r)) candyParser :: CharParser () CandyTableI candyParser = do whiteSpace ls <- P.many oneCandyParser eof return ls oneCandyParser :: CharParser () (Text,Char,Bool) oneCandyParser = do toReplace <- toReplaceParser replaceWith <- replaceWithParser nt <- option True (try $do symbol "Trimming" return False) return (toReplace,replaceWith,nt) toReplaceParser :: CharParser () Text toReplaceParser = lexeme (do str <- between (char '"') (char '"' <?> "end of string") (P.many $noneOf "\"") return $ T.pack str) <?> "to replace string" replaceWithParser :: CharParser () Char replaceWithParser = do char '0' hd <- lexeme hexadecimal return (chr (fromIntegral hd))
cocreature/leksah
src/IDE/SourceCandy.hs
gpl-2.0
13,617
0
34
4,590
3,518
1,724
1,794
262
7
-- | A parser for the Xtract command-language. (The string input is -- tokenised internally by the lexer 'lexXtract'.) -- See <http://www.haskell.org/HaXml/Xtract.html> for the grammar that -- is accepted. -- Because the original Xtract grammar was left-recursive, we have -- transformed it into a non-left-recursive form. module Text.XML.HaXml.Xtract.Parse (parseXtract,xtract) where import Text.ParserCombinators.Poly hiding (bracket) import Text.XML.HaXml.Xtract.Lex import Text.XML.HaXml.Xtract.Combinators as D import Text.XML.HaXml.Combinators as C import Text.XML.HaXml.Types (Content) import Data.List(isPrefixOf) import Text.XML.HaXml.Escape (xmlUnEscapeContent,stdXmlEscaper) -- output transformer - to ensure that text/references are glued together unescape :: [Content i] -> [Content i] unescape = xmlUnEscapeContent stdXmlEscaper -- | To convert an Xtract query into an ordinary HaXml combinator expression. -- First arg is a tag-transformation function (e.g. map toLower) applied --- before matching. Second arg is the query string. xtract :: (String->String) -> String -> CFilter i xtract f query | interiorRef lexedQ = dfilter (parseXtract lexedQ) | otherwise = cfilter (parseXtract lexedQ) where lexedQ = lexXtract f query -- test whether query has interior reference to doc root interiorRef (Right (_,Symbol s): Right (_,Symbol "//"): _) | s `elem` predicateIntro = True interiorRef (Right (_,Symbol s): Right (_,Symbol "/"): _) | s `elem` predicateIntro = True interiorRef (_ : rest) = interiorRef rest interiorRef [] = False predicateIntro = [ "[", "(" , "&", "|", "~" , "=", "!=", "<", "<=", ">", ">=" , ".=.",".!=.",".<.",".<=.",".>.",".>=." ] -- | The cool thing is that the Xtract command parser directly builds -- a higher-order 'DFilter' (see "Text.XML.HaXml.Xtract.Combinators") -- which can be applied to an XML document without further ado. -- (@parseXtract@ halts the program if a parse error is found.) parseXtract :: [Token] -> DFilter i parseXtract = either error id . parseXtract' -- | @parseXtract'@ returns error messages through the Either type. parseXtract' :: [Token] -> Either String (DFilter i) parseXtract' = fst . runParser (aquery liftLocal) ---- Auxiliary Parsing Functions ---- type XParser a = Parser (Either String (Posn,TokenT)) a string :: XParser String string = P (\inp -> case inp of (Left err: _) -> Failure inp err (Right (_,TokString n):ts) -> Success ts n ts -> Failure ts "expected a string" ) number :: XParser Integer number = P (\inp -> case inp of (Left err: _) -> Failure inp err (Right (_,TokNum n):ts) -> Success ts n ts -> Failure ts "expected a number" ) symbol :: String -> XParser () symbol s = P (\inp -> case inp of (Left err: _) -> Failure inp err (Right (_, Symbol n):ts) | n==s -> Success ts () ts -> Failure ts ("expected symbol "++s) ) quote :: XParser () quote = oneOf [ symbol "'", symbol "\"" ] pam :: [a->b] -> a -> [b] pam fs x = [ f x | f <- fs ] {--- original Xtract grammar ---- query = string tagname | string * tagname prefix | * string tagname suffix | * any element | - chardata | ( query ) | query / query parent/child relationship | query // query deep inside | query + query union of queries | query [predicate] | query [positions] predicate = quattr has attribute | quattr op ' string ' attribute has value | quattr op " string " attribute has value | quattr op quattr attribute value comparison (lexical) | quattr nop integer attribute has value (numerical) | quattr nop quattr attribute value comparison (numerical) | ( predicate ) bracketting | predicate & predicate logical and | predicate | predicate logical or | ~ predicate logical not attribute = @ string has attribute | query / @ string child has attribute | - has textual content | query / - child has textual content quattr = query | attribute op = = equal to | != not equal to | < less than | <= less than or equal to | > greater than | >= greater than or equal to nop = .=. equal to | .!=. not equal to | .<. less than | .<=. less than or equal to | .>. greater than | .>=. greater than or equal to positions = position {, positions} multiple positions | position - position ranges position = integer numbering is from 0 upwards | $ last ---- transformed grammar (removing left recursion) aquery = ./ tquery -- current context | tquery -- also current context | / tquery -- root context | // tquery -- deep context from root tquery = ( tquery ) xquery | tag xquery | - -- fixes original grammar ("-/*" is incorrect) tag = string * | string | * string | * xquery = / tquery | // tquery | / @ string -- new: print attribute value | + tquery | [ tpredicate ] xquery | [ positions ] xquery | lambda tpredicate = vpredicate upredicate upredicate = & tpredicate | | tpredicate | lambda vpredicate = ( tpredicate ) | ~ tpredicate | tattribute tattribute = aquery uattribute | @ string vattribute uattribute = / @ string vattribute | vattribute vattribute = op wattribute | op ' string ' | nop wattribute | nop integer | lambda wattribute = @ string | aquery / @ string | aquery positions = simplepos commapos simplepos = integer range | $ range = - integer | - $ | lambda commapos = , simplepos commapos | lambda op = = | != | < | <= | > | >= nop = .=. | .!=. | .<. | .<=. | .>. | .>=. -} bracket :: XParser a -> XParser a bracket p = do symbol "(" x <- p symbol ")" return x ---- Xtract parsers ---- -- aquery chooses to search from the root, or only in local context aquery :: ((CFilter i->CFilter i) -> (DFilter i->DFilter i)) -> XParser (DFilter i) aquery lift = oneOf [ do symbol "//" tquery [lift C.multi] , do symbol "/" tquery [lift id] , do symbol "./" tquery [(local C.keep D./>)] , do tquery [(local C.keep D./>)] ] tquery :: [DFilter i->DFilter i] -> XParser (DFilter i) tquery [] = tquery [id] tquery (qf:cxt) = oneOf [ do q <- bracket (tquery (qf:qf:cxt)) xquery cxt q , do q <- xtag xquery cxt (qf ((unescape .).q)) -- glue inners texts together , do symbol "-" return (qf (local C.txt)) ] xtag :: XParser (DFilter i) xtag = oneOf [ do s <- string symbol "*" return (local (C.tagWith (s `isPrefixOf`))) , do s <- string return (local (C.tag s)) , do symbol "*" s <- string return (local (C.tagWith (((reverse s) `isPrefixOf`) . reverse))) , do symbol "*" return (local C.elm) ] xquery :: [DFilter i->DFilter i] -> DFilter i -> XParser (DFilter i) xquery cxt q1 = oneOf [ do symbol "/" ( do symbol "@" attr <- string return (D.iffind attr (\s->local (C.literal s)) D.none `D.o` q1) `onFail` tquery ((q1 D./>):cxt) ) , do symbol "//" tquery ((\q2-> (liftLocal C.multi) q2 `D.o` local C.children `D.o` q1):cxt) , do symbol "+" q2 <- tquery cxt return (D.cat [q1,q2]) , do symbol "[" is <- iindex -- now extended to multiple indexes symbol "]" xquery cxt (\xml-> concat . pam is . q1 xml) , do symbol "[" p <- tpredicate symbol "]" xquery cxt (q1 `D.with` p) , return q1 ] tpredicate :: XParser (DFilter i) tpredicate = do p <- vpredicate f <- upredicate return (f p) upredicate :: XParser (DFilter i->DFilter i) upredicate = oneOf [ do symbol "&" p2 <- tpredicate return (`D.o` p2) , do symbol "|" p2 <- tpredicate return (D.|>| p2) , return id ] vpredicate :: XParser (DFilter i) vpredicate = oneOf [ do bracket tpredicate , do symbol "~" p <- tpredicate return (local C.keep `D.without` p) , do tattribute ] tattribute :: XParser (DFilter i) tattribute = oneOf [ do q <- aquery liftGlobal uattribute q , do symbol "@" s <- string vattribute (local C.keep, local (C.attr s), D.iffind s) ] uattribute :: DFilter i -> XParser (DFilter i) uattribute q = oneOf [ do symbol "/" symbol "@" s <- string vattribute (q, local (C.attr s), D.iffind s) , do vattribute (q, local C.keep, D.ifTxt) ] vattribute :: (DFilter i, DFilter i, (String->DFilter i)->DFilter i->DFilter i) -> XParser (DFilter i) vattribute (q,a,iffn) = oneOf [ do cmp <- op quote s2 <- string quote return ((iffn (\s1->if cmp s1 s2 then D.keep else D.none) D.none) `D.o` q) , do cmp <- op (q2,iffn2) <- wattribute -- q2 unused? is this a mistake? return ((iffn (\s1-> iffn2 (\s2-> if cmp s1 s2 then D.keep else D.none) D.none) D.none) `D.o` q) , do cmp <- nop n <- number return ((iffn (\s->if cmp (read s) n then D.keep else D.none) D.none) `D.o` q) , do cmp <- nop (q2,iffn2) <- wattribute -- q2 unused? is this a mistake? return ((iffn (\s1-> iffn2 (\s2-> if cmp (read s1) (read s2) then D.keep else D.none) D.none) D.none) `D.o` q) , do return ((a `D.o` q)) ] wattribute :: XParser (DFilter i, (String->DFilter i)->DFilter i->DFilter i) wattribute = oneOf [ do symbol "@" s <- string return (D.keep, D.iffind s) , do q <- aquery liftGlobal symbol "/" symbol "@" s <- string return (q, D.iffind s) , do q <- aquery liftGlobal return (q, D.ifTxt) ] iindex :: XParser [[a]->[a]] iindex = do i <- simpleindex is <- idxcomma return (i:is) simpleindex :: XParser ([a]->[a]) simpleindex = oneOf [ do n <- number r <- rrange n return r , do symbol "$" return (C.keep . last) ] rrange, numberdollar :: Integer -> XParser ([a]->[a]) rrange n1 = oneOf [ do symbol "-" numberdollar n1 , return (take 1 . drop (fromInteger n1)) ] numberdollar n1 = oneOf [ do n2 <- number return (take (fromInteger (1+n2-n1)) . drop (fromInteger n1)) , do symbol "$" return (drop (fromInteger n1)) ] idxcomma :: XParser [[a]->[a]] idxcomma = oneOf [ do symbol "," r <- simpleindex rs <- idxcomma return (r:rs) , return [] ] op :: XParser (String->String->Bool) op = oneOf [ do symbol "="; return (==) , do symbol "!="; return (/=) , do symbol "<"; return (<) , do symbol "<="; return (<=) , do symbol ">"; return (>) , do symbol ">="; return (>=) ] nop :: XParser (Integer->Integer->Bool) nop = oneOf [ do symbol ".=."; return (==) , do symbol ".!=."; return (/=) , do symbol ".<."; return (<) , do symbol ".<=."; return (<=) , do symbol ".>."; return (>) , do symbol ".>=."; return (>=) ]
Ian-Stewart-Binks/courseography
dependencies/HaXml-1.25.3/src/Text/XML/HaXml/Xtract/Parse.hs
gpl-3.0
12,878
0
22
4,841
3,444
1,735
1,709
226
5
-- | -- Module : Crypto.PubKey.Ed25519 -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : unknown -- -- Ed25519 support -- {-# LANGUAGE BangPatterns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Crypto.PubKey.Ed25519 ( SecretKey , PublicKey , Signature -- * Size constants , publicKeySize , secretKeySize , signatureSize -- * Smart constructors , signature , publicKey , secretKey -- * Methods , toPublic , sign , verify , generateSecretKey ) where import Data.Word import Foreign.C.Types import Foreign.Ptr import Crypto.Error import Crypto.Internal.ByteArray (ByteArrayAccess, Bytes, ScrubbedBytes, withByteArray) import qualified Crypto.Internal.ByteArray as B import Crypto.Internal.Compat import Crypto.Internal.Imports import Crypto.Random -- | An Ed25519 Secret key newtype SecretKey = SecretKey ScrubbedBytes deriving (Show,Eq,ByteArrayAccess,NFData) -- | An Ed25519 public key newtype PublicKey = PublicKey Bytes deriving (Show,Eq,ByteArrayAccess,NFData) -- | An Ed25519 signature newtype Signature = Signature Bytes deriving (Show,Eq,ByteArrayAccess,NFData) -- | Try to build a public key from a bytearray publicKey :: ByteArrayAccess ba => ba -> CryptoFailable PublicKey publicKey bs | B.length bs == publicKeySize = CryptoPassed $ PublicKey $ B.copyAndFreeze bs (\_ -> return ()) | otherwise = CryptoFailed $ CryptoError_PublicKeySizeInvalid -- | Try to build a secret key from a bytearray secretKey :: ByteArrayAccess ba => ba -> CryptoFailable SecretKey secretKey bs | B.length bs == secretKeySize = unsafeDoIO $ withByteArray bs initialize | otherwise = CryptoFailed CryptoError_SecretKeyStructureInvalid where initialize inp = do valid <- isValidPtr inp if valid then (CryptoPassed . SecretKey) <$> B.copy bs (\_ -> return ()) else return $ CryptoFailed CryptoError_SecretKeyStructureInvalid isValidPtr _ = return True {-# NOINLINE secretKey #-} -- | Try to build a signature from a bytearray signature :: ByteArrayAccess ba => ba -> CryptoFailable Signature signature bs | B.length bs == signatureSize = CryptoPassed $ Signature $ B.copyAndFreeze bs (\_ -> return ()) | otherwise = CryptoFailed CryptoError_SecretKeyStructureInvalid -- | Create a public key from a secret key toPublic :: SecretKey -> PublicKey toPublic (SecretKey sec) = PublicKey <$> B.allocAndFreeze publicKeySize $ \result -> withByteArray sec $ \psec -> ccryptonite_ed25519_publickey psec result {-# NOINLINE toPublic #-} -- | Sign a message using the key pair sign :: ByteArrayAccess ba => SecretKey -> PublicKey -> ba -> Signature sign secret public message = Signature $ B.allocAndFreeze signatureSize $ \sig -> withByteArray secret $ \sec -> withByteArray public $ \pub -> withByteArray message $ \msg -> ccryptonite_ed25519_sign msg (fromIntegral msgLen) sec pub sig where !msgLen = B.length message -- | Verify a message verify :: ByteArrayAccess ba => PublicKey -> ba -> Signature -> Bool verify public message signatureVal = unsafeDoIO $ withByteArray signatureVal $ \sig -> withByteArray public $ \pub -> withByteArray message $ \msg -> do r <- ccryptonite_ed25519_sign_open msg (fromIntegral msgLen) pub sig return (r == 0) where !msgLen = B.length message -- | Generate a secret key generateSecretKey :: MonadRandom m => m SecretKey generateSecretKey = SecretKey <$> getRandomBytes secretKeySize -- | A public key is 32 bytes publicKeySize :: Int publicKeySize = 32 -- | A secret key is 32 bytes secretKeySize :: Int secretKeySize = 32 -- | A signature is 64 bytes signatureSize :: Int signatureSize = 64 foreign import ccall "cryptonite_ed25519_publickey" ccryptonite_ed25519_publickey :: Ptr SecretKey -- secret key -> Ptr PublicKey -- public key -> IO () foreign import ccall "cryptonite_ed25519_sign_open" ccryptonite_ed25519_sign_open :: Ptr Word8 -- message -> CSize -- message len -> Ptr PublicKey -- public -> Ptr Signature -- signature -> IO CInt foreign import ccall "cryptonite_ed25519_sign" ccryptonite_ed25519_sign :: Ptr Word8 -- message -> CSize -- message len -> Ptr SecretKey -- secret -> Ptr PublicKey -- public -> Ptr Signature -- signature -> IO ()
tekul/cryptonite
Crypto/PubKey/Ed25519.hs
bsd-3-clause
5,061
0
16
1,512
1,025
541
484
103
2
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} module Quoter (quote, quoteFile, quoteFileReload) where import Language.Haskell.TH.Syntax import Language.Haskell.TH.Quote (QuasiQuoter (..)) #ifdef TEST_COFFEE import Text.Coffee import Text.Coffee (coffeeSettings) import Text.Shakespeare (shakespeare) #else # ifdef TEST_ROY import Text.Roy # else import Text.Julius # endif #endif quote :: QuasiQuoter quoteFile :: FilePath -> Q Exp quoteFileReload :: FilePath -> Q Exp #ifdef TEST_COFFEE translate ('#':'{':rest) = translate $ '%':'{':translate rest translate (c:other) = c:translate other translate [] = [] quote = QuasiQuoter { quoteExp = \s -> do rs <- coffeeSettings quoteExp (shakespeare rs) (translate s) } quoteFile = coffeeFile quoteFileReload = coffeeFileReload #else # ifdef TEST_ROY quote = roy quoteFile = royFile quoteFileReload = royFileReload # else quote = julius quoteFile = juliusFile quoteFileReload = juliusFileReload # endif #endif
fgaray/shakespeare
test/Quoter.hs
mit
996
3
13
150
221
125
96
12
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- Determine which packages are already installed module Stack.Build.Installed ( InstalledMap , Installed (..) , GetInstalledOpts (..) , getInstalled ) where import Control.Applicative import Control.Monad import Control.Monad.Catch (MonadMask) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Resource import Data.Conduit import qualified Data.Conduit.List as CL import Data.Function import qualified Data.Foldable as F import qualified Data.HashSet as HashSet import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import qualified Data.Map.Strict as Map import Data.Maybe import Data.Maybe.Extra (mapMaybeM) import Data.Monoid import qualified Data.Text as T import Network.HTTP.Client.Conduit (HasHttpManager) import Path import Prelude hiding (FilePath, writeFile) import Stack.Build.Cache import Stack.Types.Build import Stack.Types.Version import Stack.Constants import Stack.GhcPkg import Stack.PackageDump import Stack.Types import Stack.Types.Internal type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasEnvConfig env,MonadLogger m,MonadBaseControl IO m,MonadMask m,HasLogLevel env) -- | Options for 'getInstalled'. data GetInstalledOpts = GetInstalledOpts { getInstalledProfiling :: !Bool -- ^ Require profiling libraries? , getInstalledHaddock :: !Bool -- ^ Require haddocks? } -- | Returns the new InstalledMap and all of the locally registered packages. getInstalled :: (M env m, PackageInstallInfo pii) => EnvOverride -> GetInstalledOpts -> Map PackageName pii -- ^ does not contain any installed information -> m ( InstalledMap , [DumpPackage () ()] -- globally installed , [DumpPackage () ()] -- snapshot installed , [DumpPackage () ()] -- locally installed ) getInstalled menv opts sourceMap = do snapDBPath <- packageDatabaseDeps localDBPath <- packageDatabaseLocal extraDBPaths <- packageDatabaseExtra bconfig <- asks getBuildConfig mcache <- if getInstalledProfiling opts || getInstalledHaddock opts then liftM Just $ loadInstalledCache $ configInstalledCache bconfig else return Nothing let loadDatabase' = loadDatabase menv opts mcache sourceMap (installedLibs0, globalDumpPkgs) <- loadDatabase' Nothing [] (installedLibs1, _extraInstalled) <- (foldM (\lhs' pkgdb -> loadDatabase' (Just (ExtraGlobal, pkgdb)) (fst lhs') ) (installedLibs0, globalDumpPkgs) extraDBPaths) (installedLibs2, snapshotDumpPkgs) <- loadDatabase' (Just (InstalledTo Snap, snapDBPath)) installedLibs1 (installedLibs3, localDumpPkgs) <- loadDatabase' (Just (InstalledTo Local, localDBPath)) installedLibs2 let installedLibs = M.fromList $ map lhPair installedLibs3 F.forM_ mcache (saveInstalledCache (configInstalledCache bconfig)) -- Add in the executables that are installed, making sure to only trust a -- listed installation under the right circumstances (see below) let exesToSM loc = Map.unions . map (exeToSM loc) exeToSM loc (PackageIdentifier name version) = case Map.lookup name sourceMap of -- Doesn't conflict with anything, so that's OK Nothing -> m Just pii -- Not the version we want, ignore it | version /= piiVersion pii || loc /= piiLocation pii -> Map.empty | otherwise -> m where m = Map.singleton name (loc, Executable $ PackageIdentifier name version) exesSnap <- getInstalledExes Snap exesLocal <- getInstalledExes Local let installedMap = Map.unions [ exesToSM Local exesLocal , exesToSM Snap exesSnap , installedLibs ] return ( installedMap , globalDumpPkgs , snapshotDumpPkgs , localDumpPkgs ) -- | Outputs both the modified InstalledMap and the Set of all installed packages in this database -- -- The goal is to ascertain that the dependencies for a package are present, -- that it has profiling if necessary, and that it matches the version and -- location needed by the SourceMap loadDatabase :: (M env m, PackageInstallInfo pii) => EnvOverride -> GetInstalledOpts -> Maybe InstalledCache -- ^ if Just, profiling or haddock is required -> Map PackageName pii -- ^ to determine which installed things we should include -> Maybe (InstalledPackageLocation, Path Abs Dir) -- ^ package database, Nothing for global -> [LoadHelper] -- ^ from parent databases -> m ([LoadHelper], [DumpPackage () ()]) loadDatabase menv opts mcache sourceMap mdb lhs0 = do wc <- getWhichCompiler (lhs1', dps) <- ghcPkgDump menv wc (fmap snd (maybeToList mdb)) $ conduitDumpPackage =$ sink let ghcjsHack = wc == Ghcjs && isNothing mdb lhs1 <- mapMaybeM (processLoadResult mdb ghcjsHack) lhs1' let lhs = pruneDeps id lhId lhDeps const (lhs0 ++ lhs1) return (map (\lh -> lh { lhDeps = [] }) $ Map.elems lhs, dps) where conduitProfilingCache = case mcache of Just cache | getInstalledProfiling opts -> addProfiling cache -- Just an optimization to avoid calculating the profiling -- values when they aren't necessary _ -> CL.map (\dp -> dp { dpProfiling = False }) conduitHaddockCache = case mcache of Just cache | getInstalledHaddock opts -> addHaddock cache -- Just an optimization to avoid calculating the haddock -- values when they aren't necessary _ -> CL.map (\dp -> dp { dpHaddock = False }) mloc = fmap fst mdb sinkDP = conduitProfilingCache =$ conduitHaddockCache =$ CL.map (\dp -> (isAllowed opts mcache sourceMap mloc dp, toLoadHelper mloc dp)) =$ CL.consume sink = getZipSink $ (,) <$> ZipSink sinkDP <*> ZipSink CL.consume processLoadResult :: MonadLogger m => Maybe (InstalledPackageLocation, Path Abs Dir) -> Bool -> (Allowed, LoadHelper) -> m (Maybe LoadHelper) processLoadResult _ _ (Allowed, lh) = return (Just lh) processLoadResult _ True (WrongVersion actual wanted, lh) -- Allow some packages in the ghcjs global DB to have the wrong -- versions. Treat them as wired-ins by setting deps to []. | fst (lhPair lh) `HashSet.member` ghcjsBootPackages = do $logWarn $ T.concat [ "Ignoring that the GHCJS boot package \"" , packageNameText (fst (lhPair lh)) , "\" has a different version, " , versionText actual , ", than the resolver's wanted version, " , versionText wanted ] return (Just lh) processLoadResult mdb _ (reason, lh) = do $logDebug $ T.concat $ [ "Ignoring package " , packageNameText (fst (lhPair lh)) ] ++ maybe [] (\db -> [", from ", T.pack (show db), ","]) mdb ++ [ " due to" , case reason of Allowed -> " the impossible?!?!" NeedsProfiling -> " it needing profiling." NeedsHaddock -> " it needing haddocks." UnknownPkg -> " it being unknown to the resolver / extra-deps." WrongLocation mloc loc -> " wrong location: " <> T.pack (show (mloc, loc)) WrongVersion actual wanted -> T.concat [ " wanting version " , versionText wanted , " instead of " , versionText actual ] ] return Nothing data Allowed = Allowed | NeedsProfiling | NeedsHaddock | UnknownPkg | WrongLocation (Maybe InstalledPackageLocation) InstallLocation | WrongVersion Version Version deriving (Eq, Show) -- | Check if a can be included in the set of installed packages or not, based -- on the package selections made by the user. This does not perform any -- dirtiness or flag change checks. isAllowed :: PackageInstallInfo pii => GetInstalledOpts -> Maybe InstalledCache -> Map PackageName pii -> Maybe InstalledPackageLocation -> DumpPackage Bool Bool -> Allowed isAllowed opts mcache sourceMap mloc dp -- Check that it can do profiling if necessary | getInstalledProfiling opts && isJust mcache && not (dpProfiling dp) = NeedsProfiling -- Check that it has haddocks if necessary | getInstalledHaddock opts && isJust mcache && not (dpHaddock dp) = NeedsHaddock | otherwise = case Map.lookup name sourceMap of Nothing -> case mloc of -- The sourceMap has nothing to say about this global -- package, so we can use it Nothing -> Allowed Just ExtraGlobal -> Allowed -- For non-global packages, don't include unknown packages. -- See: -- https://github.com/commercialhaskell/stack/issues/292 Just _ -> UnknownPkg Just pii | not (checkLocation (piiLocation pii)) -> WrongLocation mloc (piiLocation pii) | version /= piiVersion pii -> WrongVersion version (piiVersion pii) | otherwise -> Allowed where PackageIdentifier name version = dpPackageIdent dp -- Ensure that the installed location matches where the sourceMap says it -- should be installed checkLocation Snap = mloc /= Just (InstalledTo Local) -- we can allow either global or snap checkLocation Local = mloc == Just (InstalledTo Local) || mloc == Just ExtraGlobal -- 'locally' installed snapshot packages can come from extra dbs data LoadHelper = LoadHelper { lhId :: !GhcPkgId , lhDeps :: ![GhcPkgId] , lhPair :: !(PackageName, (InstallLocation, Installed)) } deriving Show toLoadHelper :: Maybe InstalledPackageLocation -> DumpPackage Bool Bool -> LoadHelper toLoadHelper mloc dp = LoadHelper { lhId = gid , lhDeps = -- We always want to consider the wired in packages as having all -- of their dependencies installed, since we have no ability to -- reinstall them. This is especially important for using different -- minor versions of GHC, where the dependencies of wired-in -- packages may change slightly and therefore not match the -- snapshot. if name `HashSet.member` wiredInPackages then [] else dpDepends dp , lhPair = (name, (toPackageLocation mloc, Library ident gid)) } where gid = dpGhcPkgId dp ident@(PackageIdentifier name _) = dpPackageIdent dp toPackageLocation :: Maybe InstalledPackageLocation -> InstallLocation toPackageLocation Nothing = Snap toPackageLocation (Just ExtraGlobal) = Snap toPackageLocation (Just (InstalledTo loc)) = loc
phadej/stack
src/Stack/Build/Installed.hs
bsd-3-clause
11,896
0
19
3,673
2,447
1,289
1,158
225
6
----------------------------------------------------------------------------- -- -- GHCi's :ctags and :etags commands -- -- (c) The GHC Team 2005-2007 -- ----------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-name-shadowing #-} module GHCi.UI.Tags ( createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd, createETagsFileCmd ) where import Exception import GHC import GHCi.UI.Monad import Outputable -- ToDo: figure out whether we need these, and put something appropriate -- into the GHC API instead import Name (nameOccName) import OccName (pprOccName) import ConLike import MonadUtils import Control.Monad import Data.Function import Data.List import Data.Maybe import Data.Ord import DriverPhases import Panic import Prelude import System.Directory import System.IO import System.IO.Error ----------------------------------------------------------------------------- -- create tags file for currently loaded modules. createCTagsWithLineNumbersCmd, createCTagsWithRegExesCmd, createETagsFileCmd :: String -> GHCi () createCTagsWithLineNumbersCmd "" = ghciCreateTagsFile CTagsWithLineNumbers "tags" createCTagsWithLineNumbersCmd file = ghciCreateTagsFile CTagsWithLineNumbers file createCTagsWithRegExesCmd "" = ghciCreateTagsFile CTagsWithRegExes "tags" createCTagsWithRegExesCmd file = ghciCreateTagsFile CTagsWithRegExes file createETagsFileCmd "" = ghciCreateTagsFile ETags "TAGS" createETagsFileCmd file = ghciCreateTagsFile ETags file data TagsKind = ETags | CTagsWithLineNumbers | CTagsWithRegExes ghciCreateTagsFile :: TagsKind -> FilePath -> GHCi () ghciCreateTagsFile kind file = do createTagsFile kind file -- ToDo: -- - remove restriction that all modules must be interpreted -- (problem: we don't know source locations for entities unless -- we compiled the module. -- -- - extract createTagsFile so it can be used from the command-line -- (probably need to fix first problem before this is useful). -- createTagsFile :: TagsKind -> FilePath -> GHCi () createTagsFile tagskind tagsFile = do graph <- GHC.getModuleGraph mtags <- mapM listModuleTags (map GHC.ms_mod $ GHC.mgModSummaries graph) either_res <- liftIO $ collateAndWriteTags tagskind tagsFile $ concat mtags case either_res of Left e -> liftIO $ hPutStrLn stderr $ ioeGetErrorString e Right _ -> return () listModuleTags :: GHC.Module -> GHCi [TagInfo] listModuleTags m = do is_interpreted <- GHC.moduleIsInterpreted m -- should we just skip these? when (not is_interpreted) $ let mName = GHC.moduleNameString (GHC.moduleName m) in throwGhcException (CmdLineError ("module '" ++ mName ++ "' is not interpreted")) mbModInfo <- GHC.getModuleInfo m case mbModInfo of Nothing -> return [] Just mInfo -> do dflags <- getDynFlags mb_print_unqual <- GHC.mkPrintUnqualifiedForModule mInfo let unqual = fromMaybe GHC.alwaysQualify mb_print_unqual let names = fromMaybe [] $GHC.modInfoTopLevelScope mInfo let localNames = filter ((m==) . nameModule) names mbTyThings <- mapM GHC.lookupName localNames return $! [ tagInfo dflags unqual exported kind name realLoc | tyThing <- catMaybes mbTyThings , let name = getName tyThing , let exported = GHC.modInfoIsExportedName mInfo name , let kind = tyThing2TagKind tyThing , let loc = srcSpanStart (nameSrcSpan name) , RealSrcLoc realLoc <- [loc] ] where tyThing2TagKind (AnId _) = 'v' tyThing2TagKind (AConLike RealDataCon{}) = 'd' tyThing2TagKind (AConLike PatSynCon{}) = 'p' tyThing2TagKind (ATyCon _) = 't' tyThing2TagKind (ACoAxiom _) = 'x' data TagInfo = TagInfo { tagExported :: Bool -- is tag exported , tagKind :: Char -- tag kind , tagName :: String -- tag name , tagFile :: String -- file name , tagLine :: Int -- line number , tagCol :: Int -- column number , tagSrcInfo :: Maybe (String,Integer) -- source code line and char offset } -- get tag info, for later translation into Vim or Emacs style tagInfo :: DynFlags -> PrintUnqualified -> Bool -> Char -> Name -> RealSrcLoc -> TagInfo tagInfo dflags unqual exported kind name loc = TagInfo exported kind (showSDocForUser dflags unqual $ pprOccName (nameOccName name)) (showSDocForUser dflags unqual $ ftext (srcLocFile loc)) (srcLocLine loc) (srcLocCol loc) Nothing -- throw an exception when someone tries to overwrite existing source file (fix for #10989) writeTagsSafely :: FilePath -> String -> IO () writeTagsSafely file str = do dfe <- doesFileExist file if dfe && isSourceFilename file then throwGhcException (CmdLineError (file ++ " is existing source file. " ++ "Please specify another file name to store tags data")) else writeFile file str collateAndWriteTags :: TagsKind -> FilePath -> [TagInfo] -> IO (Either IOError ()) -- ctags style with the Ex expression being just the line number, Vim et al collateAndWriteTags CTagsWithLineNumbers file tagInfos = do let tags = unlines $ sort $ map showCTag tagInfos tryIO (writeTagsSafely file tags) -- ctags style with the Ex expression being a regex searching the line, Vim et al collateAndWriteTags CTagsWithRegExes file tagInfos = do -- ctags style, Vim et al tagInfoGroups <- makeTagGroupsWithSrcInfo tagInfos let tags = unlines $ sort $ map showCTag $concat tagInfoGroups tryIO (writeTagsSafely file tags) collateAndWriteTags ETags file tagInfos = do -- etags style, Emacs/XEmacs tagInfoGroups <- makeTagGroupsWithSrcInfo $filter tagExported tagInfos let tagGroups = map processGroup tagInfoGroups tryIO (writeTagsSafely file $ concat tagGroups) where processGroup [] = throwGhcException (CmdLineError "empty tag file group??") processGroup group@(tagInfo:_) = let tags = unlines $ map showETag group in "\x0c\n" ++ tagFile tagInfo ++ "," ++ show (length tags) ++ "\n" ++ tags makeTagGroupsWithSrcInfo :: [TagInfo] -> IO [[TagInfo]] makeTagGroupsWithSrcInfo tagInfos = do let groups = groupBy ((==) `on` tagFile) $ sortBy (comparing tagFile) tagInfos mapM addTagSrcInfo groups where addTagSrcInfo [] = throwGhcException (CmdLineError "empty tag file group??") addTagSrcInfo group@(tagInfo:_) = do file <- readFile $tagFile tagInfo let sortedGroup = sortBy (comparing tagLine) group return $ perFile sortedGroup 1 0 $ lines file perFile allTags@(tag:tags) cnt pos allLs@(l:ls) | tagLine tag > cnt = perFile allTags (cnt+1) (pos+fromIntegral(length l)) ls | tagLine tag == cnt = tag{ tagSrcInfo = Just(l,pos) } : perFile tags cnt pos allLs perFile _ _ _ _ = [] -- ctags format, for Vim et al showCTag :: TagInfo -> String showCTag ti = tagName ti ++ "\t" ++ tagFile ti ++ "\t" ++ tagCmd ++ ";\"\t" ++ tagKind ti : ( if tagExported ti then "" else "\tfile:" ) where tagCmd = case tagSrcInfo ti of Nothing -> show $tagLine ti Just (srcLine,_) -> "/^"++ foldr escapeSlashes [] srcLine ++"$/" where escapeSlashes '/' r = '\\' : '/' : r escapeSlashes '\\' r = '\\' : '\\' : r escapeSlashes c r = c : r -- etags format, for Emacs/XEmacs showETag :: TagInfo -> String showETag TagInfo{ tagName = tag, tagLine = lineNo, tagCol = colNo, tagSrcInfo = Just (srcLine,charPos) } = take (colNo - 1) srcLine ++ tag ++ "\x7f" ++ tag ++ "\x01" ++ show lineNo ++ "," ++ show charPos showETag _ = throwGhcException (CmdLineError "missing source file info in showETag")
sdiehl/ghc
ghc/GHCi/UI/Tags.hs
bsd-3-clause
7,831
115
15
1,717
1,887
993
894
148
6
import Test.Cabal.Prelude main = setupTest $ do -- No cabal test because per-component is broken with it skipUnless =<< ghcVersionIs (>= mkVersion [8,1]) withPackageDb $ do let setup_install' args = setup_install_with_docs (["--cabal-file", "Includes2.cabal"] ++ args) setup_install' ["mylib", "--cid", "mylib-0.1.0.0"] setup_install' ["mysql", "--cid", "mysql-0.1.0.0"] setup_install' ["postgresql", "--cid", "postgresql-0.1.0.0"] setup_install' ["mylib", "--cid", "mylib-0.1.0.0", "--instantiate-with", "Database=mysql-0.1.0.0:Database.MySQL"] setup_install' ["mylib", "--cid", "mylib-0.1.0.0", "--instantiate-with", "Database=postgresql-0.1.0.0:Database.PostgreSQL"] setup_install' ["Includes2"] setup_install' ["exe"] runExe' "exe" [] >>= assertOutputContains "minemysql minepostgresql"
mydaum/cabal
cabal-testsuite/PackageTests/Backpack/Includes2/setup-per-component.test.hs
bsd-3-clause
899
0
17
178
197
102
95
15
1
{- Copyright (C) 2015 John MacFarlane <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Readers.CommonMark Copyright : Copyright (C) 2015 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Conversion of CommonMark-formatted plain text to 'Pandoc' document. CommonMark is a strongly specified variant of Markdown: http://commonmark.org. -} module Text.Pandoc.Readers.CommonMark (readCommonMark) where import CMark import Data.Text (unpack, pack) import Data.List (groupBy) import Text.Pandoc.Definition import Text.Pandoc.Options import Text.Pandoc.Error -- | Parse a CommonMark formatted string into a 'Pandoc' structure. readCommonMark :: ReaderOptions -> String -> Either PandocError Pandoc readCommonMark opts = Right . nodeToPandoc . commonmarkToNode opts' . pack where opts' = if readerSmart opts then [optNormalize, optSmart] else [optNormalize] nodeToPandoc :: Node -> Pandoc nodeToPandoc (Node _ DOCUMENT nodes) = Pandoc nullMeta $ foldr addBlock [] nodes nodeToPandoc n = -- shouldn't happen Pandoc nullMeta $ foldr addBlock [] [n] addBlocks :: [Node] -> [Block] addBlocks = foldr addBlock [] addBlock :: Node -> [Block] -> [Block] addBlock (Node _ PARAGRAPH nodes) = (Para (addInlines nodes) :) addBlock (Node _ HRULE _) = (HorizontalRule :) addBlock (Node _ BLOCK_QUOTE nodes) = (BlockQuote (addBlocks nodes) :) addBlock (Node _ (HTML t) _) = (RawBlock (Format "html") (unpack t) :) addBlock (Node _ (CODE_BLOCK info t) _) = (CodeBlock ("", take 1 (words (unpack info)), []) (unpack t) :) addBlock (Node _ (HEADER lev) nodes) = (Header lev ("",[],[]) (addInlines nodes) :) addBlock (Node _ (LIST listAttrs) nodes) = (constructor (map (setTightness . addBlocks . children) nodes) :) where constructor = case listType listAttrs of BULLET_LIST -> BulletList ORDERED_LIST -> OrderedList (start, DefaultStyle, delim) start = listStart listAttrs setTightness = if listTight listAttrs then map paraToPlain else id paraToPlain (Para xs) = Plain (xs) paraToPlain x = x delim = case listDelim listAttrs of PERIOD_DELIM -> Period PAREN_DELIM -> OneParen addBlock (Node _ ITEM _) = id -- handled in LIST addBlock _ = id children :: Node -> [Node] children (Node _ _ ns) = ns addInlines :: [Node] -> [Inline] addInlines = foldr addInline [] addInline :: Node -> [Inline] -> [Inline] addInline (Node _ (TEXT t) _) = (map toinl clumps ++) where raw = unpack t clumps = groupBy samekind raw samekind ' ' ' ' = True samekind ' ' _ = False samekind _ ' ' = False samekind _ _ = True toinl (' ':_) = Space toinl xs = Str xs addInline (Node _ LINEBREAK _) = (LineBreak :) addInline (Node _ SOFTBREAK _) = (Space :) addInline (Node _ (INLINE_HTML t) _) = (RawInline (Format "html") (unpack t) :) addInline (Node _ (CODE t) _) = (Code ("",[],[]) (unpack t) :) addInline (Node _ EMPH nodes) = (Emph (addInlines nodes) :) addInline (Node _ STRONG nodes) = (Strong (addInlines nodes) :) addInline (Node _ (LINK url title) nodes) = (Link (addInlines nodes) (unpack url, unpack title) :) addInline (Node _ (IMAGE url title) nodes) = (Image (addInlines nodes) (unpack url, unpack title) :) addInline _ = id
gbataille/pandoc
src/Text/Pandoc/Readers/CommonMark.hs
gpl-2.0
4,286
0
12
1,051
1,203
636
567
78
5
----------------------------------------------------------------------------- -- -- Module : Main -- Copyright : (c) Phil Freeman 2013 -- License : MIT -- -- Maintainer : Phil Freeman <[email protected]> -- Stability : experimental -- Portability : -- -- | -- ----------------------------------------------------------------------------- {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Main where import Control.Applicative import Control.Monad.Error import Data.Version (showVersion) import System.Console.CmdTheLine import System.Directory (doesFileExist, getModificationTime, createDirectoryIfMissing) import System.FilePath (takeDirectory) import System.Exit (exitSuccess, exitFailure) import System.IO.Error (tryIOError) import Text.Parsec (ParseError) import qualified Language.PureScript as P import qualified Paths_purescript as Paths import qualified System.IO.UTF8 as U preludeFilename :: IO FilePath preludeFilename = Paths.getDataFileName "prelude/prelude.purs" readInput :: [FilePath] -> IO (Either ParseError [(FilePath, P.Module)]) readInput input = fmap collect $ forM input $ \inputFile -> do text <- U.readFile inputFile return $ (inputFile, P.runIndentParser inputFile P.parseModules text) where collect :: [(FilePath, Either ParseError [P.Module])] -> Either ParseError [(FilePath, P.Module)] collect = fmap concat . sequence . map (\(fp, e) -> fmap (map ((,) fp)) e) newtype Make a = Make { unMake :: ErrorT String IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadError String) runMake :: Make a -> IO (Either String a) runMake = runErrorT . unMake makeIO :: IO a -> Make a makeIO = Make . ErrorT . fmap (either (Left . show) Right) . tryIOError instance P.MonadMake Make where getTimestamp path = makeIO $ do exists <- doesFileExist path case exists of True -> Just <$> getModificationTime path False -> return Nothing readTextFile path = makeIO $ do U.putStrLn $ "Reading " ++ path U.readFile path writeTextFile path text = makeIO $ do mkdirp path U.putStrLn $ "Writing " ++ path U.writeFile path text liftError = either throwError return progress = makeIO . U.putStrLn compile :: FilePath -> P.Options -> [FilePath] -> IO () compile outputDir opts input = do modules <- readInput input case modules of Left err -> do U.print err exitFailure Right ms -> do e <- runMake $ P.make outputDir opts ms case e of Left err -> do U.putStrLn err exitFailure Right _ -> do exitSuccess mkdirp :: FilePath -> IO () mkdirp = createDirectoryIfMissing True . takeDirectory inputFiles :: Term [FilePath] inputFiles = value $ posAny [] $ posInfo { posDoc = "The input .ps files" } outputDirectory :: Term FilePath outputDirectory = value $ opt "output" $ (optInfo [ "o", "output" ]) { optDoc = "The output directory" } noTco :: Term Bool noTco = value $ flag $ (optInfo [ "no-tco" ]) { optDoc = "Disable tail call optimizations" } performRuntimeTypeChecks :: Term Bool performRuntimeTypeChecks = value $ flag $ (optInfo [ "runtime-type-checks" ]) { optDoc = "Generate runtime type checks" } noPrelude :: Term Bool noPrelude = value $ flag $ (optInfo [ "no-prelude" ]) { optDoc = "Omit the Prelude" } noMagicDo :: Term Bool noMagicDo = value $ flag $ (optInfo [ "no-magic-do" ]) { optDoc = "Disable the optimization that overloads the do keyword to generate efficient code specifically for the Eff monad." } noOpts :: Term Bool noOpts = value $ flag $ (optInfo [ "no-opts" ]) { optDoc = "Skip the optimization phase." } verboseErrors :: Term Bool verboseErrors = value $ flag $ (optInfo [ "v", "verbose-errors" ]) { optDoc = "Display verbose error messages" } options :: Term P.Options options = P.Options <$> noPrelude <*> noTco <*> performRuntimeTypeChecks <*> noMagicDo <*> pure Nothing <*> noOpts <*> pure Nothing <*> pure [] <*> pure [] <*> verboseErrors inputFilesAndPrelude :: FilePath -> Term [FilePath] inputFilesAndPrelude prelude = combine <$> (not <$> noPrelude) <*> inputFiles where combine True input = prelude : input combine False input = input term :: FilePath -> Term (IO ()) term prelude = compile <$> outputDirectory <*> options <*> inputFilesAndPrelude prelude termInfo :: TermInfo termInfo = defTI { termName = "psc-make" , version = showVersion Paths.version , termDoc = "Compiles PureScript to Javascript" } main :: IO () main = do prelude <- preludeFilename run (term prelude, termInfo)
bergmark/purescript
psc-make/Main.hs
mit
4,586
0
18
905
1,362
718
644
101
3
module Graphics.CG.Algorithms.PointInTriangle(pointInTriangle) where import Graphics.CG.Algorithms.Rotate import Graphics.CG.Primitives.Triangle import Graphics.Gloss.Data.Point pointInTriangle :: Point -> Triangle -> Bool pointInTriangle p (p1, p2, p3) = (c1 >= 0 && c2 >= 0 && c3 >= 0) || (c1 <= 0 && c2 <= 0 && c3 <= 0) where c1 = fromEnum $ orientation p p1 p2 c2 = fromEnum $ orientation p p2 p3 c3 = fromEnum $ orientation p p3 p1
jagajaga/CG-Haskell
Graphics/CG/Algorithms/PointInTriangle.hs
mit
497
0
11
130
166
93
73
9
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds, PolyKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE RankNTypes, ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TemplateHaskell #-} module List where import Data.Vinyl import Data.Type.Equality import Nats import Data.Singletons.Prelude import Data.Singletons.TH {- data SList l where SNil' :: SList '[] SCons' :: Sing a -> SList l -> SList (a ': l) slist :: forall l. SingI l => SList l slist = case sing :: Sing l of SNil -> SNil' SCons -> SCons' sing slist -} --class Offset -- an index n into l such that l[n] = a data Index (l :: [k]) a where ZIndex :: Index (t ': l) t SIndex :: Index l t -> Index (a ': l) t index :: Index l a -> Rec f l -> f a index ZIndex (a :& _) = a index (SIndex i) (_ :& l) = index i l instance TestEquality (Index l) where testEquality ZIndex ZIndex = Just Refl testEquality (SIndex i) (SIndex j) = do Refl <- testEquality i j return Refl testEquality _ _ = Nothing indices :: SList l -> Rec (Index l) l indices SNil = RNil indices (SCons _ l) = ZIndex :& rmap SIndex (indices l) class Find l a where find :: Index l a instance {-# OVERLAPS #-} Find (a ': l) a where find = ZIndex instance Find l a => Find (b ': l) a where find = SIndex find $(singletons [d| len :: [a] -> Nat len [] = Z len (x:xs) = S (len xs) |])
vladfi1/hs-misc
List.hs
mit
1,470
0
9
326
409
217
192
39
1
import Base.Scene import Base.Camera import Base.Image import SphereScene main = do save 500 500 5
burz/Rayzer
Rayzer.hs
mit
106
0
7
22
34
18
16
6
1
module Main where import Parser import Environment import Eval import PrettyPrint import System.Environment import Text.PrettyPrint.ANSI.Leijen import System.Exit import System.Directory main :: IO () main = do args <- getArgs if null args then do putDoc $ red (text "Error") <> text ": you did not enter a filename\n" exitFailure else do let file = head args found <- doesFileExist file if found then do process file exitSuccess else do putDoc $ red (text "Error") <> text ": file " <> dullgreen (text file) <> text " does not exist\n" exitFailure process :: FilePath -> IO () process path = do contents <- readFile path let res = parseProgram contents (lines contents) case res of Left err -> print err Right r' -> mapM_ (\(x, y) -> putDoc $ display x <> red (text " ⇒ ") <> display (eval' y) <> hardline) (zip (lines contents) r') where eval' = typeAndEval emptyEnv
kellino/TypeSystems
fullSimple/Main.hs
mit
1,099
2
24
379
350
168
182
34
3