code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- | Generated by Haskell protocol buffer compiler. DO NOT EDIT! module Echo where import qualified Prelude as Hs import qualified Proto3.Suite.Class as HsProtobuf import qualified Proto3.Suite.DotProto as HsProtobuf import qualified Proto3.Suite.JSONPB as HsJSONPB import Proto3.Suite.JSONPB ((.=), (.:)) import qualified Proto3.Suite.Types as HsProtobuf import qualified Proto3.Wire as HsProtobuf import qualified Control.Applicative as Hs import Control.Applicative ((<*>), (<|>), (<$>)) import qualified Control.DeepSeq as Hs import qualified Control.Monad as Hs import qualified Data.ByteString as Hs import qualified Data.Coerce as Hs import qualified Data.Int as Hs (Int16, Int32, Int64) import qualified Data.List.NonEmpty as Hs (NonEmpty(..)) import qualified Data.Map as Hs (Map, mapKeysMonotonic) import qualified Data.Proxy as Proxy import qualified Data.String as Hs (fromString) import qualified Data.Text.Lazy as Hs (Text) import qualified Data.Vector as Hs (Vector) import qualified Data.Word as Hs (Word16, Word32, Word64) import qualified GHC.Enum as Hs import qualified GHC.Generics as Hs import qualified Unsafe.Coerce as Hs import Network.GRPC.HighLevel.Generated as HsGRPC import Network.GRPC.HighLevel.Client as HsGRPC import Network.GRPC.HighLevel.Server as HsGRPC hiding (serverLoop) import Network.GRPC.HighLevel.Server.Unregistered as HsGRPC (serverLoop) data Echo request response = Echo{echoDoEcho :: request 'HsGRPC.Normal Echo.EchoRequest Echo.EchoResponse -> Hs.IO (response 'HsGRPC.Normal Echo.EchoResponse)} deriving Hs.Generic echoServer :: Echo HsGRPC.ServerRequest HsGRPC.ServerResponse -> HsGRPC.ServiceOptions -> Hs.IO () echoServer Echo{echoDoEcho = echoDoEcho} (ServiceOptions serverHost serverPort useCompression userAgentPrefix userAgentSuffix initialMetadata sslConfig logger serverMaxReceiveMessageLength) = (HsGRPC.serverLoop HsGRPC.defaultOptions{HsGRPC.optNormalHandlers = [(HsGRPC.UnaryHandler (HsGRPC.MethodName "/echo.Echo/DoEcho") (HsGRPC.convertGeneratedServerHandler echoDoEcho))], HsGRPC.optClientStreamHandlers = [], HsGRPC.optServerStreamHandlers = [], HsGRPC.optBiDiStreamHandlers = [], optServerHost = serverHost, optServerPort = serverPort, optUseCompression = useCompression, optUserAgentPrefix = userAgentPrefix, optUserAgentSuffix = userAgentSuffix, optInitialMetadata = initialMetadata, optSSLConfig = sslConfig, optLogger = logger, optMaxReceiveMessageLength = serverMaxReceiveMessageLength}) echoClient :: HsGRPC.Client -> Hs.IO (Echo HsGRPC.ClientRequest HsGRPC.ClientResult) echoClient client = (Hs.pure Echo) <*> ((Hs.pure (HsGRPC.clientRequest client)) <*> (HsGRPC.clientRegisterMethod client (HsGRPC.MethodName "/echo.Echo/DoEcho"))) newtype EchoRequest = EchoRequest{echoRequestMessage :: Hs.Text} deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named EchoRequest where nameOf _ = (Hs.fromString "EchoRequest") instance HsProtobuf.HasDefault EchoRequest instance HsProtobuf.Message EchoRequest where encodeMessage _ EchoRequest{echoRequestMessage = echoRequestMessage} = (Hs.mconcat [(HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 1) echoRequestMessage)]) decodeMessage _ = (Hs.pure EchoRequest) <*> (HsProtobuf.at HsProtobuf.decodeMessageField (HsProtobuf.FieldNumber 1)) dotProto _ = [(HsProtobuf.DotProtoField (HsProtobuf.FieldNumber 1) (HsProtobuf.Prim HsProtobuf.String) (HsProtobuf.Single "message") [] "")] instance HsJSONPB.ToJSONPB EchoRequest where toJSONPB (EchoRequest f1) = (HsJSONPB.object ["message" .= f1]) toEncodingPB (EchoRequest f1) = (HsJSONPB.pairs ["message" .= f1]) instance HsJSONPB.FromJSONPB EchoRequest where parseJSONPB = (HsJSONPB.withObject "EchoRequest" (\ obj -> (Hs.pure EchoRequest) <*> obj .: "message")) instance HsJSONPB.ToJSON EchoRequest where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON EchoRequest where parseJSON = HsJSONPB.parseJSONPB instance HsJSONPB.ToSchema EchoRequest where declareNamedSchema _ = do let declare_message = HsJSONPB.declareSchemaRef echoRequestMessage <- declare_message Proxy.Proxy let _ = Hs.pure EchoRequest <*> HsJSONPB.asProxy declare_message Hs.return (HsJSONPB.NamedSchema{HsJSONPB._namedSchemaName = Hs.Just "EchoRequest", HsJSONPB._namedSchemaSchema = Hs.mempty{HsJSONPB._schemaParamSchema = Hs.mempty{HsJSONPB._paramSchemaType = Hs.Just HsJSONPB.SwaggerObject}, HsJSONPB._schemaProperties = HsJSONPB.insOrdFromList [("message", echoRequestMessage)]}}) newtype EchoResponse = EchoResponse{echoResponseMessage :: Hs.Text} deriving (Hs.Show, Hs.Eq, Hs.Ord, Hs.Generic, Hs.NFData) instance HsProtobuf.Named EchoResponse where nameOf _ = (Hs.fromString "EchoResponse") instance HsProtobuf.HasDefault EchoResponse instance HsProtobuf.Message EchoResponse where encodeMessage _ EchoResponse{echoResponseMessage = echoResponseMessage} = (Hs.mconcat [(HsProtobuf.encodeMessageField (HsProtobuf.FieldNumber 1) echoResponseMessage)]) decodeMessage _ = (Hs.pure EchoResponse) <*> (HsProtobuf.at HsProtobuf.decodeMessageField (HsProtobuf.FieldNumber 1)) dotProto _ = [(HsProtobuf.DotProtoField (HsProtobuf.FieldNumber 1) (HsProtobuf.Prim HsProtobuf.String) (HsProtobuf.Single "message") [] "")] instance HsJSONPB.ToJSONPB EchoResponse where toJSONPB (EchoResponse f1) = (HsJSONPB.object ["message" .= f1]) toEncodingPB (EchoResponse f1) = (HsJSONPB.pairs ["message" .= f1]) instance HsJSONPB.FromJSONPB EchoResponse where parseJSONPB = (HsJSONPB.withObject "EchoResponse" (\ obj -> (Hs.pure EchoResponse) <*> obj .: "message")) instance HsJSONPB.ToJSON EchoResponse where toJSON = HsJSONPB.toAesonValue toEncoding = HsJSONPB.toAesonEncoding instance HsJSONPB.FromJSON EchoResponse where parseJSON = HsJSONPB.parseJSONPB instance HsJSONPB.ToSchema EchoResponse where declareNamedSchema _ = do let declare_message = HsJSONPB.declareSchemaRef echoResponseMessage <- declare_message Proxy.Proxy let _ = Hs.pure EchoResponse <*> HsJSONPB.asProxy declare_message Hs.return (HsJSONPB.NamedSchema{HsJSONPB._namedSchemaName = Hs.Just "EchoResponse", HsJSONPB._namedSchemaSchema = Hs.mempty{HsJSONPB._schemaParamSchema = Hs.mempty{HsJSONPB._paramSchemaType = Hs.Just HsJSONPB.SwaggerObject}, HsJSONPB._schemaProperties = HsJSONPB.insOrdFromList [("message", echoResponseMessage)]}})
awakenetworks/gRPC-haskell
examples/echo/echo-hs/Echo.hs
apache-2.0
8,770
0
17
2,780
1,786
1,008
778
167
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -- | -- XML Signature Syntax and Processing -- -- <http://www.w3.org/TR/xmldsig-core1/> (selected portions) module SAML2.XML.Signature.Types where import Control.Lens (Lens') import Crypto.Number.Serialize (i2osp, os2ip) import qualified Data.X509 as X509 import SAML2.XML import qualified SAML2.XML.Schema as XS import qualified Text.XML.HXT.Arrow.Pickle.Xml.Invertible as XP import qualified SAML2.XML.Canonical as C14N import SAML2.XML.ASN1 nsFrag :: String -> URI nsFrag = httpURI "www.w3.org" "/2000/09/xmldsig" "" . ('#':) nsFrag11 :: String -> URI nsFrag11 = httpURI "www.w3.org" "/2009/xmldsig11" "" . ('#':) ns :: Namespace ns = mkNamespace "ds" $ nsFrag "" ns11 :: Namespace ns11 = mkNamespace "dsig11" $ nsFrag11 "" xpElem :: String -> XP.PU a -> XP.PU a xpElem = xpTrimElemNS ns xpElem11 :: String -> XP.PU a -> XP.PU a xpElem11 = xpTrimElemNS ns11 -- |§4.1 type CryptoBinary = Integer -- as Base64Binary xpCryptoBinary :: XP.PU CryptoBinary xpCryptoBinary = XP.xpWrap (os2ip, i2osp) XS.xpBase64Binary -- |§4.2 data Signature = Signature { signatureId :: Maybe ID , signatureSignedInfo :: SignedInfo , signatureSignatureValue :: SignatureValue , signatureKeyInfo :: Maybe KeyInfo , signatureObject :: [Object] } deriving (Eq, Show) instance XP.XmlPickler Signature where xpickle = xpElem "Signature" $ [XP.biCase|((((i, s), v), k), o) <-> Signature i s v k o|] XP.>$< (XP.xpAttrImplied "Id" XS.xpID XP.>*< XP.xpickle XP.>*< XP.xpickle XP.>*< XP.xpOption XP.xpickle XP.>*< XP.xpList XP.xpickle) class Signable a where signature' :: Lens' a (Maybe Signature) signedID :: a -> XS.ID -- |§4.3 data SignatureValue = SignatureValue { signatureValueId :: Maybe ID , signatureValue :: XS.Base64Binary } deriving (Eq, Show) instance XP.XmlPickler SignatureValue where xpickle = xpElem "SignatureValue" $ [XP.biCase|(i, v) <-> SignatureValue i v|] XP.>$< (XP.xpAttrImplied "Id" XS.xpID XP.>*< XS.xpBase64Binary) -- |§4.4 data SignedInfo = SignedInfo { signedInfoId :: Maybe ID , signedInfoCanonicalizationMethod :: CanonicalizationMethod , signedInfoSignatureMethod :: SignatureMethod , signedInfoReference :: List1 Reference } deriving (Eq, Show) instance XP.XmlPickler SignedInfo where xpickle = xpElem "SignedInfo" $ [XP.biCase|(((i, c), s), r) <-> SignedInfo i c s r|] XP.>$< (XP.xpAttrImplied "Id" XS.xpID XP.>*< XP.xpickle XP.>*< XP.xpickle XP.>*< xpList1 XP.xpickle) -- |§4.4.1 data CanonicalizationMethod = CanonicalizationMethod { canonicalizationMethodAlgorithm :: IdentifiedURI C14N.CanonicalizationAlgorithm , canonicalizationMethodInclusiveNamespaces :: Maybe C14N.InclusiveNamespaces , canonicalizationMethod :: Nodes } deriving (Eq, Show) instance XP.XmlPickler CanonicalizationMethod where xpickle = xpElem "CanonicalizationMethod" $ [XP.biCase|((a, n), x) <-> CanonicalizationMethod a n x|] XP.>$< (XP.xpAttr "Algorithm" XP.xpickle XP.>*< XP.xpOption XP.xpickle XP.>*< XP.xpAnyCont) simpleCanonicalization :: C14N.CanonicalizationAlgorithm -> CanonicalizationMethod simpleCanonicalization a = CanonicalizationMethod (Identified a) Nothing [] -- |§4.4.2 data SignatureMethod = SignatureMethod { signatureMethodAlgorithm :: IdentifiedURI SignatureAlgorithm , signatureMethodHMACOutputLength :: Maybe Int , signatureMethod :: Nodes } deriving (Eq, Show) instance XP.XmlPickler SignatureMethod where xpickle = xpElem "SignatureMethod" $ [XP.biCase|((a, l), x) <-> SignatureMethod a l x|] XP.>$< (XP.xpAttr "Algorithm" XP.xpickle XP.>*< XP.xpOption (xpElem "HMACOutputLength" XP.xpickle) XP.>*< XP.xpAnyCont) -- |§4.4.3 data Reference = Reference { referenceId :: Maybe ID , referenceURI :: Maybe AnyURI , referenceType :: Maybe AnyURI -- xml object type , referenceTransforms :: Maybe Transforms , referenceDigestMethod :: DigestMethod , referenceDigestValue :: XS.Base64Binary -- ^§4.3.3.6 } deriving (Eq, Show) instance XP.XmlPickler Reference where xpickle = xpElem "Reference" $ [XP.biCase|(((((i, u), t), f), m), v) <-> Reference i u t f m v|] XP.>$< (XP.xpAttrImplied "Id" XS.xpID XP.>*< XP.xpAttrImplied "URI" XS.xpAnyURI XP.>*< XP.xpAttrImplied "Type" XS.xpAnyURI XP.>*< XP.xpOption XP.xpickle XP.>*< XP.xpickle XP.>*< xpElem "DigestValue" XS.xpBase64Binary) -- |§4.4.3.4 newtype Transforms = Transforms{ transforms :: List1 Transform } deriving (Eq, Show) instance XP.XmlPickler Transforms where xpickle = xpElem "Transforms" $ [XP.biCase|l <-> Transforms l|] XP.>$< xpList1 XP.xpickle data Transform = Transform { transformAlgorithm :: IdentifiedURI TransformAlgorithm , transformInclusiveNamespaces :: Maybe C14N.InclusiveNamespaces , transform :: [TransformElement] } deriving (Eq, Show) instance XP.XmlPickler Transform where xpickle = xpElem "Transform" $ [XP.biCase|((a, n), l) <-> Transform a n l|] XP.>$< (XP.xpAttr "Algorithm" XP.xpickle XP.>*< XP.xpOption XP.xpickle XP.>*< XP.xpList XP.xpickle) simpleTransform :: TransformAlgorithm -> Transform simpleTransform a = Transform (Identified a) Nothing [] data TransformElement = TransformElementXPath XString | TransformElement Node deriving (Eq, Show) instance XP.XmlPickler TransformElement where xpickle = [XP.biCase| Left s <-> TransformElementXPath s Right x <-> TransformElement x |] XP.>$< (xpElem "XPath" XS.xpString XP.>|< xpTrimAnyElem) -- |§4.4.3.5 data DigestMethod = DigestMethod { digestAlgorithm :: IdentifiedURI DigestAlgorithm , digest :: [Node] } deriving (Eq, Show) instance XP.XmlPickler DigestMethod where xpickle = xpElem "DigestMethod" $ [XP.biCase|(a, d) <-> DigestMethod a d|] XP.>$< (XP.xpAttr "Algorithm" XP.xpickle XP.>*< XP.xpAnyCont) simpleDigest :: DigestAlgorithm -> DigestMethod simpleDigest a = DigestMethod (Identified a) [] -- |§4.5 data KeyInfo = KeyInfo { keyInfoId :: Maybe ID , keyInfoElements :: List1 KeyInfoElement } deriving (Eq, Show) xpKeyInfoType :: XP.PU KeyInfo xpKeyInfoType = [XP.biCase|(i, l) <-> KeyInfo i l|] XP.>$< (XP.xpAttrImplied "Id" XS.xpID XP.>*< xpList1 XP.xpickle) instance XP.XmlPickler KeyInfo where xpickle = xpElem "KeyInfo" xpKeyInfoType data KeyInfoElement = KeyName XString -- ^§4.5.1 | KeyInfoKeyValue KeyValue -- ^§4.5.2 | RetrievalMethod { retrievalMethodURI :: URI , retrievalMethodType :: Maybe URI , retrievalMethodTransforms :: Maybe Transforms } -- ^§4.5.3 | X509Data { x509Data :: List1 X509Element } -- ^§4.5.4 | PGPData { pgpKeyID :: Maybe XS.Base64Binary , pgpKeyPacket :: Maybe XS.Base64Binary , pgpData :: Nodes } -- ^§4.5.5 | SPKIData { spkiData :: List1 SPKIElement } -- ^§4.5.6 | MgmtData XString -- ^§4.5.7 | KeyInfoElement Node deriving (Eq, Show) instance XP.XmlPickler KeyInfoElement where xpickle = [XP.biCase| Left (Left (Left (Left (Left (Left (Left n)))))) <-> KeyName n Left (Left (Left (Left (Left (Left (Right v)))))) <-> KeyInfoKeyValue v Left (Left (Left (Left (Left (Right ((u, t), f)))))) <-> RetrievalMethod u t f Left (Left (Left (Left (Right l)))) <-> X509Data l Left (Left (Left (Right ((i, p), x)))) <-> PGPData i p x Left (Left (Right l)) <-> SPKIData l Left (Right m) <-> MgmtData m Right x <-> KeyInfoElement x|] XP.>$< (xpElem "KeyName" XS.xpString XP.>|< XP.xpickle XP.>|< xpElem "RetrievalMethod" (XP.xpAttr "URI" XS.xpAnyURI XP.>*< XP.xpAttrImplied "Type" XS.xpAnyURI XP.>*< XP.xpOption XP.xpickle) XP.>|< xpElem "X509Data" (xpList1 XP.xpickle) XP.>|< xpElem "PGPData" (XP.xpOption (xpElem "PGPKeyID" XS.xpBase64Binary) XP.>*< XP.xpOption (xpElem "PGPKeyPacket" XS.xpBase64Binary) XP.>*< XP.xpList xpTrimAnyElem) XP.>|< xpElem "SPKIData" (xpList1 XP.xpickle) XP.>|< xpElem "MgmtData" XS.xpString XP.>|< XP.xpTree) -- |§4.5.2 data KeyValue = DSAKeyValue { dsaKeyValuePQ :: Maybe (CryptoBinary, CryptoBinary) , dsaKeyValueG :: Maybe CryptoBinary , dsaKeyValueY :: CryptoBinary , dsaKeyValueJ :: Maybe CryptoBinary , dsaKeyValueSeedPgenCounter :: Maybe (CryptoBinary, CryptoBinary) } -- ^§4.5.2.1 | RSAKeyValue { rsaKeyValueModulus , rsaKeyValueExponent :: CryptoBinary } -- ^§4.5.2.2 | ECKeyValue { ecKeyValueId :: Maybe XS.ID , ecKeyValue :: ECKeyValue , ecKeyValuePublicKey :: ECPoint } -- ^§4.5.2.3 | KeyValue Node deriving (Eq, Show) instance XP.XmlPickler KeyValue where xpickle = xpElem "KeyValue" $ [XP.biCase| Left (Left (Left ((((pq, g), y), j), sp))) <-> DSAKeyValue pq g y j sp Left (Left (Right (m, e))) <-> RSAKeyValue m e Left (Right ((i, v), p)) <-> ECKeyValue i v p Right x <-> KeyValue x|] XP.>$< (xpElem "DSAKeyValue" (XP.xpOption (xpElem "P" xpCryptoBinary XP.>*< xpElem "Q" xpCryptoBinary) XP.>*< XP.xpOption (xpElem "G" xpCryptoBinary) XP.>*< xpElem "Y" xpCryptoBinary XP.>*< XP.xpOption (xpElem "J" xpCryptoBinary) XP.>*< (XP.xpOption (xpElem "Seed" xpCryptoBinary XP.>*< xpElem "PgenCounter" xpCryptoBinary))) XP.>|< xpElem "RSAKeyValue" (xpElem "Modulus" xpCryptoBinary XP.>*< xpElem "Exponent" xpCryptoBinary) XP.>|< xpElem11 "ECKeyValue" (XP.xpAttrImplied "Id" XS.xpID XP.>*< XP.xpickle XP.>*< xpElem11 "PublicKey" xpCryptoBinary) XP.>|< XP.xpTree) data ECKeyValue = ECParameters { ecParametersFieldID :: ECFieldID , ecParametersCurve :: ECCurve , ecParametersBase :: ECPoint , ecParametersOrder :: CryptoBinary , ecParametersCoFactor :: Maybe Integer , ecParametersValidationData :: Maybe ECValidationData } -- ^§4.5.2.3.1 | ECNamedCurve { ecNamedCurveURI :: XS.AnyURI } deriving (Eq, Show) type ECPoint = CryptoBinary instance XP.XmlPickler ECKeyValue where xpickle = [XP.biCase| Left (((((f, c), b), o), cf), vd) <-> ECParameters f c b o cf vd Right u <-> ECNamedCurve u|] XP.>$< (xpElem11 "ECParameters" (XP.xpickle XP.>*< XP.xpickle XP.>*< xpElem11 "Base" xpCryptoBinary XP.>*< xpElem11 "Order" xpCryptoBinary XP.>*< XP.xpOption (xpElem11 "CoFactor" XS.xpInteger) XP.>*< XP.xpOption XP.xpickle) XP.>|< xpElem11 "NamedCurve" (XP.xpAttr "URI" XS.xpAnyURI)) data ECFieldID = ECPrime { ecP :: CryptoBinary } | ECTnB { ecM :: XS.PositiveInteger , ecK :: XS.PositiveInteger } | ECPnB { ecM :: XS.PositiveInteger , ecK1, ecK2, ecK3 :: XS.PositiveInteger } | ECGnB { ecM :: XS.PositiveInteger } | ECFieldID Node deriving (Eq, Show) instance XP.XmlPickler ECFieldID where xpickle = xpElem11 "FieldID" $ [XP.biCase| Left (Left (Left (Left p))) <-> ECPrime p Left (Left (Left (Right (m, k)))) <-> ECTnB m k Left (Left (Right (((m, k1), k2), k3))) <-> ECPnB m k1 k2 k3 Left (Right m) <-> ECGnB m Right x <-> ECFieldID x|] XP.>$< (xpElem11 "Prime" (xpElem11 "P" xpCryptoBinary) XP.>|< xpElem11 "TnB" (xpElem11 "M" XS.xpPositiveInteger XP.>*< xpElem11 "K" XS.xpPositiveInteger) XP.>|< xpElem11 "PnB" (xpElem11 "M" XS.xpPositiveInteger XP.>*< xpElem11 "K1" XS.xpPositiveInteger XP.>*< xpElem11 "K2" XS.xpPositiveInteger XP.>*< xpElem11 "K3" XS.xpPositiveInteger) XP.>|< xpElem11 "GnB" (xpElem11 "M" XS.xpPositiveInteger) XP.>|< xpTrimAnyElem) data ECCurve = ECCurve { ecCurveA, ecCurveB :: CryptoBinary } deriving (Eq, Show) instance XP.XmlPickler ECCurve where xpickle = xpElem11 "Curve" $ [XP.biCase| (a, b) <-> ECCurve a b|] XP.>$< (xpElem11 "A" xpCryptoBinary XP.>*< xpElem11 "B" xpCryptoBinary) data ECValidationData = ECValidationData { ecValidationDataHashAlgorithm :: AnyURI , ecValidationDataSeed :: CryptoBinary } deriving (Eq, Show) instance XP.XmlPickler ECValidationData where xpickle = xpElem11 "ValidationData" $ [XP.biCase| (a, s) <-> ECValidationData a s|] XP.>$< (XP.xpAttr "hashAlgorithm" XS.xpAnyURI XP.>*< xpElem11 "seed" xpCryptoBinary) -- |§4.5.4.1 type X509DistinguishedName = XString xpX509DistinguishedName :: XP.PU X509DistinguishedName xpX509DistinguishedName = XS.xpString data X509Element = X509IssuerSerial { x509IssuerName :: X509DistinguishedName , x509SerialNumber :: Int } | X509SKI XS.Base64Binary | X509SubjectName X509DistinguishedName | X509Certificate X509.SignedCertificate | X509CRL X509.SignedCRL | X509Digest { x509DigestAlgorithm :: IdentifiedURI DigestAlgorithm , x509Digest :: XS.Base64Binary } | X509Element Node deriving (Eq, Show) instance XP.XmlPickler X509Element where xpickle = [XP.biCase| Left (Left (Left (Left (Left (Left (n, i)))))) <-> X509IssuerSerial n i Left (Left (Left (Left (Left (Right n))))) <-> X509SubjectName n Left (Left (Left (Left (Right b)))) <-> X509SKI b Left (Left (Left (Right b))) <-> X509Certificate b Left (Left (Right b)) <-> X509CRL b Left (Right (a, d)) <-> X509Digest a d Right x <-> X509Element x|] XP.>$< (xpElem "X509IssuerSerial" (xpElem "X509IssuerName" xpX509DistinguishedName XP.>*< xpElem "X509SerialNumber" XP.xpickle) XP.>|< xpElem "X509SubjectName" xpX509DistinguishedName XP.>|< xpElem "X509SKI" XS.xpBase64Binary XP.>|< xpElem "X509Certificate" xpX509Signed XP.>|< xpElem "X509CRL" xpX509Signed XP.>|< xpElem11 "X509Digest" (XP.xpAttr "Algorithm" XP.xpickle XP.>*< XS.xpBase64Binary) XP.>|< xpTrimAnyElem) -- |§4.4.6 data SPKIElement = SPKISexp XS.Base64Binary | SPKIElement Node deriving (Eq, Show) instance XP.XmlPickler SPKIElement where xpickle = [XP.biCase| Left b <-> SPKISexp b Right x <-> SPKIElement x|] XP.>$< (xpElem "SPKISexp" XS.xpBase64Binary XP.>|< xpTrimAnyElem) -- |§4.5 data Object = Object { objectId :: Maybe ID , objectMimeType :: Maybe XString , objectEncoding :: Maybe (IdentifiedURI EncodingAlgorithm) , objectXML :: [ObjectElement] } deriving (Eq, Show) instance XP.XmlPickler Object where xpickle = xpElem "Object" $ [XP.biCase|(((i, m), e), x) <-> Object i m e x|] XP.>$< (XP.xpAttrImplied "Id" XS.xpID XP.>*< XP.xpAttrImplied "MimeType" XS.xpString XP.>*< XP.xpAttrImplied "Encoding" XP.xpickle XP.>*< XP.xpList XP.xpickle) data ObjectElement = ObjectSignature Signature | ObjectSignatureProperties SignatureProperties | ObjectManifest Manifest | ObjectElement Node deriving (Eq, Show) instance XP.XmlPickler ObjectElement where xpickle = [XP.biCase| Left (Left (Left s)) <-> ObjectSignature s Left (Left (Right p)) <-> ObjectSignatureProperties p Left (Right m) <-> ObjectManifest m Right x <-> ObjectElement x|] XP.>$< (XP.xpickle XP.>|< XP.xpickle XP.>|< XP.xpickle XP.>|< XP.xpTree) -- |§5.1 data Manifest = Manifest { manifestId :: Maybe ID , manifestReferences :: List1 Reference } deriving (Eq, Show) instance XP.XmlPickler Manifest where xpickle = xpElem "Manifest" $ [XP.biCase|(i, r) <-> Manifest i r|] XP.>$< (XP.xpAttrImplied "Id" XS.xpID XP.>*< xpList1 XP.xpickle) -- |§5.2 data SignatureProperties = SignatureProperties { signaturePropertiesId :: Maybe ID , signatureProperties :: List1 SignatureProperty } deriving (Eq, Show) instance XP.XmlPickler SignatureProperties where xpickle = xpElem "SignatureProperties" $ [XP.biCase|(i, p) <-> SignatureProperties i p|] XP.>$< (XP.xpAttrImplied "Id" XS.xpID XP.>*< xpList1 XP.xpickle) data SignatureProperty = SignatureProperty { signaturePropertyId :: Maybe ID , signaturePropertyTarget :: AnyURI , signatureProperty :: List1 Node } deriving (Eq, Show) instance XP.XmlPickler SignatureProperty where xpickle = xpElem "SignatureProperty" $ [XP.biCase|((i, t), x) <-> SignatureProperty i t x|] XP.>$< (XP.xpAttrImplied "Id" XS.xpID XP.>*< XP.xpAttr "Target" XS.xpAnyURI XP.>*< xpList1 XP.xpTree) -- |§6.1 data EncodingAlgorithm = EncodingBase64 deriving (Eq, Bounded, Enum, Show) instance Identifiable URI EncodingAlgorithm where identifier EncodingBase64 = nsFrag "base64" -- |§6.2 data DigestAlgorithm = DigestSHA1 -- ^§6.2.1 | DigestSHA224 -- ^§6.2.2 | DigestSHA256 -- ^§6.2.3 | DigestSHA384 -- ^§6.2.4 | DigestSHA512 -- ^§6.2.5 | DigestRIPEMD160 -- ^xmlenc §5.7.4 deriving (Eq, Bounded, Enum, Show) instance Identifiable URI DigestAlgorithm where identifier DigestSHA1 = nsFrag "sha1" identifier DigestSHA224 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#sha224" identifier DigestSHA256 = httpURI "www.w3.org" "/2001/04/xmlenc" "" "#sha256" identifier DigestSHA384 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#sha384" identifier DigestSHA512 = httpURI "www.w3.org" "/2001/04/xmlenc" "" "#sha512" identifier DigestRIPEMD160 = httpURI "www.w3.org" "/2001/04/xmlenc" "" "#ripemd160" -- |§6.3 data MACAlgorithm = MACHMAC_SHA1 -- ^§6.3.1 deriving (Eq, Bounded, Enum, Show) instance Identifiable URI MACAlgorithm where identifier MACHMAC_SHA1 = nsFrag "hmac-sha1" -- |§6.4 data SignatureAlgorithm = SignatureDSA_SHA1 | SignatureDSA_SHA256 | SignatureRSA_SHA1 | SignatureRSA_SHA224 | SignatureRSA_SHA256 | SignatureRSA_SHA384 | SignatureRSA_SHA512 | SignatureECDSA_SHA1 | SignatureECDSA_SHA224 | SignatureECDSA_SHA256 | SignatureECDSA_SHA384 | SignatureECDSA_SHA512 deriving (Eq, Bounded, Enum, Show) instance Identifiable URI SignatureAlgorithm where identifier SignatureDSA_SHA1 = nsFrag "dsa-sha1" identifier SignatureDSA_SHA256 = nsFrag11 "dsa-sha256" identifier SignatureRSA_SHA1 = nsFrag "rsa-sha1" identifier SignatureRSA_SHA224 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#rsa-sha224" identifier SignatureRSA_SHA256 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#rsa-sha256" identifier SignatureRSA_SHA384 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#rsa-sha384" identifier SignatureRSA_SHA512 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#rsa-sha512" identifier SignatureECDSA_SHA1 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#ecdsa-sha1" identifier SignatureECDSA_SHA224 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#ecdsa-sha224" identifier SignatureECDSA_SHA256 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#ecdsa-sha256" identifier SignatureECDSA_SHA384 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#ecdsa-sha384" identifier SignatureECDSA_SHA512 = httpURI "www.w3.org" "/2001/04/xmldsig-more" "" "#ecdsa-sha512" -- |§6.6 data TransformAlgorithm = TransformCanonicalization C14N.CanonicalizationAlgorithm -- ^§6.6.1 | TransformBase64 -- ^§6.6.2 | TransformXPath -- ^§6.6.3 | TransformEnvelopedSignature -- ^§6.6.4 | TransformXSLT -- ^§6.6.5 deriving (Eq, Show) instance Identifiable URI TransformAlgorithm where identifier (TransformCanonicalization c) = identifier c identifier TransformBase64 = nsFrag "base64" identifier TransformXPath = httpURI "www.w3.org" "/TR/1999/REC-xpath-19991116" "" "" identifier TransformEnvelopedSignature = nsFrag "enveloped-signature" identifier TransformXSLT = httpURI "www.w3.org" "/TR/1999/REC-xslt-19991116" "" "" identifiedValues = map TransformCanonicalization identifiedValues ++ [ TransformBase64 , TransformXSLT , TransformXPath , TransformEnvelopedSignature ]
dylex/hsaml2
SAML2/XML/Signature/Types.hs
apache-2.0
20,188
0
20
4,087
4,530
2,449
2,081
460
1
{-# LANGUAGE CPP, OverloadedStrings #-} module Sound.Freesound.Sound ( SoundId(..) , FileType(..) , GeoTag(..) , Sound(..) , Summary , Detail , url , description , geotag , created , sound_license , fileType , channels , filesize , bitrate , bitdepth , duration , samplerate , sound_username , pack , download , bookmark , previews , images , numDownloads , avgRating , numRatings , rate , comments , numComments , comment , similarSounds -- , analysis , analysisStats , analysisFrames , soundById , soundDetail ) where import qualified Data.Text as T import Sound.Freesound.API (Freesound, get, resourceURI) import Sound.Freesound.Sound.Type as Sound -- | Get a sound by id. soundById :: SoundId -> Freesound Detail soundById (SoundId i) = get $ resourceURI ["sounds", T.pack (show i)] [] -- | Get detailed sound information from its summary. soundDetail :: Summary -> Freesound Detail soundDetail = soundById . Sound.id
kaoskorobase/freesound
src/Sound/Freesound/Sound.hs
bsd-2-clause
1,021
0
10
242
248
157
91
45
1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS -Wall #-} ---------------------------------------------------------------------- -- | -- Module : Blaze.ByteString.Builder.ZoomCache.Internal -- Copyright : Conrad Parker -- License : BSD3-style (see LICENSE) -- -- Maintainer : Conrad Parker <[email protected]> -- Stability : unstable -- Portability : unknown -- -- Blaze-builder utility functions for writing ZoomCache files. ---------------------------------------------------------------------- module Blaze.ByteString.Builder.ZoomCache.Internal ( -- * Builders fromFlags , fromGlobal , fromSummarySO , fromTrackNo , fromCodec ) where import Blaze.ByteString.Builder import Data.Bits import qualified Data.ByteString as B import Data.Monoid import Data.Time import Blaze.ByteString.Builder.ZoomCache import Data.ZoomCache.Common import Data.ZoomCache.Format import Data.ZoomCache.Types ---------------------------------------------------------------------- -- Creating builders for ZoomCache types. fromFlags :: Bool -> Bool -> SampleRateType -> Builder fromFlags delta zlib drType = fromInt16be (zl .|. dl .|. dr) where zl | zlib = 4 | otherwise = 0 dl | delta = 2 | otherwise = 0 dr | drType == VariableSR = 1 | otherwise = 0 fromGlobal :: Global -> Builder fromGlobal Global{..} = mconcat [ fromByteString globalHeader , mconcat $ [ fromVersion version , fromIntegral32be noTracks , fromUTCBaseTime baseUTC ] ] fromUTCBaseTime :: Maybe UTCTime -> Builder fromUTCBaseTime Nothing = mconcat $ replicate 3 (fromIntegerVLC 0) fromUTCBaseTime (Just UTCTime{..}) = mconcat . map fromIntegerVLC $ [ toModifiedJulianDay utctDay , round . toRational . (pico *) $ utctDayTime , pico ] where pico :: forall a . Num a => a pico = 1000000000000 fromSummarySO :: ZoomWritable a => SummarySO a -> Builder fromSummarySO s@SummarySO{..} = mconcat [ fromSummarySOHeader s, l, d] where d = fromSummaryData summarySOData l = fromIntegral32be . B.length . toByteString $ d fromSummarySOHeader :: SummarySO a -> Builder fromSummarySOHeader s = mconcat [ fromByteString summaryHeader , fromIntegral32be . summarySOTrack $ s , fromIntegral32be . summarySOLevel $ s , fromSampleOffset . summarySOEntry $ s , fromSampleOffset . summarySOExit $ s ] fromTrackNo :: TrackNo -> Builder fromTrackNo = fromInt32be . fromIntegral fromCodec :: Codec -> Builder fromCodec (Codec a) = fromByteString $ trackIdentifier a fromVersion :: Version -> Builder fromVersion (Version vMaj vMin) = mconcat [ fromInt16be . fromIntegral $ vMaj , fromInt16be . fromIntegral $ vMin ]
kfish/zoom-cache
Blaze/ByteString/Builder/ZoomCache/Internal.hs
bsd-2-clause
2,881
0
10
659
633
344
289
60
1
{-# LANGUAGE OverloadedStrings #-} -- | Parse CSS with parseNestedBlocks and render it with renderNestedBlock module Text.CSS.Parse ( NestedBlock(..) , parseNestedBlocks , parseBlocks , parseBlock , attrParser , attrsParser , blockParser , blocksParser , parseAttr , parseAttrs ) where import Prelude hiding (takeWhile, take) import Data.Attoparsec.Text import Data.Text (Text, strip, append) import Control.Applicative ((<|>), many, (<$>), (<*), (*>)) import Data.Char (isSpace) import Control.Monad (mzero) type CssBlock = (Text, [(Text, Text)]) data NestedBlock = NestedBlock Text [NestedBlock] -- ^ for example a media query | LeafBlock CssBlock deriving (Eq, Show) -- | The preferred parser, will capture media queries parseNestedBlocks :: Text -> Either String [NestedBlock] parseNestedBlocks = parseOnly nestedBlocksParser -- | The original parser of basic CSS, but throws out media queries parseBlocks :: Text -> Either String [CssBlock] parseBlocks = parseOnly blocksParser parseBlock :: Text -> Either String CssBlock parseBlock = parseOnly blockParser parseAttrs :: Text -> Either String [(Text, Text)] parseAttrs = parseOnly attrsParser parseAttr :: Text -> Either String (Text, Text) parseAttr = parseOnly attrParser skipWS :: Parser () skipWS = (string "/*" >> endComment >> skipWS) <|> (skip isSpace >> skipWhile isSpace >> skipWS) <|> return () where endComment = do skipWhile (/= '*') (do _ <- char '*' (char '/' >> return ()) <|> endComment ) <|> fail "Missing end comment" attrParser :: Parser (Text, Text) attrParser = do skipWS key <- takeWhile1 (\c -> c /= ':' && c /= '{' && c /= '}') _ <- char ':' <|> fail "Missing colon in attribute" value <- valueParser _ <- option ';' (char ';') skipWS return (strip key, strip value) valueParser :: Parser Text valueParser = takeWhile (\c -> c /= ';' && c /= '}' && c /= '{') attrsParser :: Parser [(Text, Text)] attrsParser = many attrParser blockParser :: Parser (Text, [(Text, Text)]) blockParser = do sel <- takeWhile (/= '{') _ <- char '{' attrs <- attrsParser skipWS _ <- char '}' return (strip sel, attrs) mediaQueryParser :: Parser NestedBlock mediaQueryParser = do _ <- char '@' sel <- strip <$> takeWhile (\c -> c /= '{' && c /= '}') _ <- char '{' blocks <- nestedBlocksParser skipWS _ <- char '}' return $ NestedBlock ("@" `append` sel) $ blocks blocksParser :: Parser [(Text, [(Text, Text)])] blocksParser = skipWS *> blockParser `sepBy` skipWS <* skipWS nestedBlockParser :: Parser NestedBlock nestedBlockParser = do mc <- peekChar case mc of Just '}' -> mzero _ -> try mediaQueryParser <|> (LeafBlock <$> blockParser) nestedBlocksParser :: Parser [NestedBlock] nestedBlocksParser = skipWS *> nestedBlockParser `sepBy` skipWS <* skipWS
jgm/css-text
Text/CSS/Parse.hs
bsd-2-clause
2,989
0
17
700
955
509
446
82
2
module Import ( module Prelude , module Yesod , module Foundation , module Settings.StaticFiles , module Settings.Development , module Data.Monoid , module Control.Applicative , module Utils , Text #if __GLASGOW_HASKELL__ < 704 , (<>) #endif ) where import Prelude hiding (writeFile, readFile, head, tail, init, last) import Yesod hiding (Route(..)) import Foundation import Data.Monoid (Monoid (mappend, mempty, mconcat)) import Control.Applicative ((<$>), (<*>), pure) import Data.Text (Text) import Settings.StaticFiles import Settings.Development import Utils #if __GLASGOW_HASKELL__ < 704 infixr 5 <> (<>) :: Monoid m => m -> m -> m (<>) = mappend #endif
erochest/whatisdh
Import.hs
bsd-2-clause
708
0
7
141
193
130
63
23
1
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Properties (tests) where import Control.Applicative as A ((<$>)) import Criterion.Analysis import Prelude () import Prelude.Compat import Statistics.Types (Sample) import Test.Tasty (TestTree, testGroup) import Test.Tasty.QuickCheck (testProperty) import Test.QuickCheck import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed as U instance (Arbitrary a, U.Unbox a) => Arbitrary (U.Vector a) where arbitrary = U.fromList A.<$> arbitrary shrink = map U.fromList . shrink . U.toList outlier_bucketing :: Double -> Sample -> Bool outlier_bucketing y ys = countOutliers (classifyOutliers xs) <= fromIntegral (G.length xs) where xs = U.cons y ys outlier_bucketing_weighted :: Double -> Sample -> Bool outlier_bucketing_weighted x xs = outlier_bucketing x (xs <> G.replicate (G.length xs * 10) 0) tests :: TestTree tests = testGroup "Properties" [ testProperty "outlier_bucketing" outlier_bucketing , testProperty "outlier_bucketing_weighted" outlier_bucketing_weighted ]
bos/criterion
tests/Properties.hs
bsd-2-clause
1,082
0
12
157
310
173
137
27
1
{-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-| dependant is a simple dependency resolving library. To be able to use dependant, the items you want to sort have to be an instance of the 'Dependant' typeclass. You can then call 'resolve' with a list of items to perform a topological sort. Example: @ instance (Dependant String) (String, [String]) where identifier = fst dependencies = snd @ @ A <- B D ^ ^ \ / C @ Let's resolve a simple dependency graph: >>> resolve [("B", ["A"]), ("A", []), ("C", ["B", "A"]), ("D", [])] Right [("A",[]),("D",[]),("B",["A"]),("C",["B","A"])] @ _____ / \ | v A B D <- C ^ | \ / ----- @ Now let's try resolving a cyclic dependency: >>> resolve [("B", ["A"]), ("A", ["B"]), ("C", ["D"]), ("D", [])] Left [("B",["A"]),("A",["B"])] -} module Dependant ( resolve , Dependant ) where import Data.List (partition) import Control.Monad (forM, liftM) class Dependant id a | a -> id where identifier :: a -> id -- ^ Returns the unique identifier of an item dependencies :: a -> [id] -- ^ Returns the dependencies of an item -- | Try to topologically sort a list of Dependants. resolve :: (Dependant id a, Eq id) => [a] -- ^ The list of Dependants -> Either [a] [a] -- ^ Return Left with the Dependants that couldn't be -- resolved (cyclic dependency, missing dependency) resolve xs = go xs [] where go [] xs = Right xs go unresolved resolved = let (resolvables, unresolvables) = partition (resolvable resolved) unresolved in if not . null $ resolvables then go unresolvables (resolved ++ resolvables) else Left unresolvables resolvable :: (Dependant id a, Eq id) => [a] -> a -> Bool resolvable xs x = all (`elem` map identifier xs) (dependencies x)
firecoders/sachverhalt-server
src/Dependencies.hs
bsd-3-clause
2,055
0
13
559
292
162
130
-1
-1
module ETCS.DMI ( module ETCS.DMI.Windows.MenuWindows , mkWidget, widgetEvent ) where import ETCS.DMI.Windows.MenuWindows import Reactive.Banana.DOM
open-etcs/openetcs-dmi
src/ETCS/DMI.hs
bsd-3-clause
191
0
5
56
35
24
11
5
0
module Rules.Gmp ( gmpRules, gmpBuildPath, gmpObjectsDir, gmpLibraryH, gmpBuildInfoPath ) where import Base import Context import GHC import Oracles.Setting import Target import Utilities gmpBase :: FilePath gmpBase = pkgPath integerGmp -/- "gmp" gmpLibraryInTreeH :: FilePath gmpLibraryInTreeH = "include/gmp.h" gmpLibrary :: FilePath gmpLibrary = ".libs/libgmp.a" -- | GMP is considered a Stage1 package. This determines GMP build directory. gmpContext :: Context gmpContext = vanillaContext Stage1 integerGmp -- | Build directory for in-tree GMP library. gmpBuildPath :: Action FilePath gmpBuildPath = buildRoot <&> (-/- stageString (stage gmpContext) -/- "gmp") -- | GMP library header, relative to 'gmpBuildPath'. gmpLibraryH :: FilePath gmpLibraryH = "include/ghc-gmp.h" -- | Directory for GMP library object files, relative to 'gmpBuildPath'. gmpObjectsDir :: FilePath gmpObjectsDir = "objs" -- | Path to the GMP library buildinfo file. gmpBuildInfoPath :: FilePath gmpBuildInfoPath = pkgPath integerGmp -/- "integer-gmp.buildinfo" configureEnvironment :: Action [CmdOption] configureEnvironment = sequence [ builderEnvironment "CC" $ Cc CompileC Stage1 , builderEnvironment "AR" (Ar Unpack Stage1) , builderEnvironment "NM" Nm ] gmpRules :: Rules () gmpRules = do -- Copy appropriate GMP header and object files "//" ++ gmpLibraryH %> \header -> do windows <- windowsHost configMk <- readFile' $ gmpBase -/- "config.mk" if not windows && -- TODO: We don't use system GMP on Windows. Fix? any (`isInfixOf` configMk) [ "HaveFrameworkGMP = YES", "HaveLibGmp = YES" ] then do putBuild "| GMP library/framework detected and will be used" copyFile (gmpBase -/- "ghc-gmp.h") header else do putBuild "| No GMP library/framework detected; in tree GMP will be built" gmpPath <- gmpBuildPath need [gmpPath -/- gmpLibrary] createDirectory (gmpPath -/- gmpObjectsDir) top <- topDirectory build $ target gmpContext (Ar Unpack Stage1) [top -/- gmpPath -/- gmpLibrary] [gmpPath -/- gmpObjectsDir] copyFile (gmpPath -/- "gmp.h") header copyFile (gmpPath -/- "gmp.h") (gmpPath -/- gmpLibraryInTreeH) -- Build in-tree GMP library "//" ++ gmpLibrary %> \lib -> do gmpPath <- gmpBuildPath build $ target gmpContext (Make gmpPath) [gmpPath -/- "Makefile"] [lib] putSuccess "| Successfully built custom library 'gmp'" -- In-tree GMP header is built by the gmpLibraryH rule "//" ++ gmpLibraryInTreeH %> \_ -> do gmpPath <- gmpBuildPath need [gmpPath -/- gmpLibraryH] -- This causes integerGmp package to be configured, hence creating the files [gmpBase -/- "config.mk", gmpBuildInfoPath] &%> \_ -> do dataFile <- pkgDataFile gmpContext need [dataFile] -- Run GMP's configure script -- TODO: Get rid of hard-coded @gmp@. "//gmp/Makefile" %> \mk -> do env <- configureEnvironment gmpPath <- gmpBuildPath need [mk <.> "in"] buildWithCmdOptions env $ target gmpContext (Configure gmpPath) [mk <.> "in"] [mk] -- Extract in-tree GMP sources and apply patches "//gmp/Makefile.in" %> \_ -> do gmpPath <- gmpBuildPath removeDirectory gmpPath -- Note: We use a tarball like gmp-4.2.4-nodoc.tar.bz2, which is -- gmp-4.2.4.tar.bz2 repacked without the doc/ directory contents. -- That's because the doc/ directory contents are under the GFDL, -- which causes problems for Debian. tarball <- unifyPath . fromSingleton "Exactly one GMP tarball is expected" <$> getDirectoryFiles "" [gmpBase -/- "gmp-tarballs/gmp*.tar.bz2"] withTempDir $ \dir -> do let tmp = unifyPath dir need [tarball] build $ target gmpContext (Tar Extract) [tarball] [tmp] let patch = gmpBase -/- "gmpsrc.patch" patchName = takeFileName patch copyFile patch $ tmp -/- patchName applyPatch tmp patchName let name = dropExtension . dropExtension $ takeFileName tarball unpack = fromMaybe . error $ "gmpRules: expected suffix " ++ "-nodoc (found: " ++ name ++ ")." libName = unpack $ stripSuffix "-nodoc" name moveDirectory (tmp -/- libName) gmpPath
ezyang/ghc
hadrian/src/Rules/Gmp.hs
bsd-3-clause
4,575
0
22
1,243
920
466
454
82
2
{-# LANGUAGE MagicHash, CPP #-} {-| Module : Data.Number.MPFR.Instances.Zero Description : Instance declarations Copyright : (c) Aleš Bizjak License : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable This module defines instances 'Num', 'Real', 'Fractional', 'Floating' and 'RealFrac' of 'MPFR'. Operations are rounded with 'RoundMode' 'Zero' and computed with maximum precision of two operands or with the precision of the operand. -} {-# INCLUDE <mpfr.h> #-} {-# INCLUDE <chsmpfr.h> #-} module Data.Number.MPFR.Instances.Zero () where import qualified Data.Number.MPFR.Arithmetic as A import qualified Data.Number.MPFR.Special as S import Data.Number.MPFR.Misc import Data.Number.MPFR.Assignment import Data.Number.MPFR.Comparison import Data.Number.MPFR.Internal import Data.Number.MPFR.Conversion import Data.Number.MPFR.Integer import Data.Maybe import Data.Ratio #if (__GLASGOW_HASKELL__ >= 610) && (__GLASGOW_HASKELL__ < 612) import GHC.Integer.Internals #elif __GLASGOW_HASKELL__ >= 612 import GHC.Integer.GMP.Internals #endif import qualified GHC.Exts as E instance Num MPFR where d + d' = A.add Zero (maxPrec d d') d d' d - d' = A.sub Zero (maxPrec d d') d d' d * d' = A.mul Zero (maxPrec d d') d d' negate d = A.neg Zero (getPrec d) d abs d = A.absD Zero (getPrec d) d signum = fromInt Zero minPrec . fromMaybe (-1) . sgn fromInteger (S# i) = fromInt Zero minPrec (E.I# i) fromInteger i@(J# n _) = fromIntegerA Zero (fromIntegral . abs $ E.I# n * bitsPerIntegerLimb) i instance Real MPFR where toRational d = n % 2 ^ e where (n', e') = decompose d (n, e) = if e' >= 0 then ((n' * 2 ^ e'), 0) else (n', - e') instance Fractional MPFR where d / d' = A.div Zero (maxPrec d d') d d' fromRational r = fromInteger n / fromInteger d where n = numerator r d = denominator r recip d = one / d instance Floating MPFR where pi = S.pi Zero 53 exp d = S.exp Zero (getPrec d) d log d = S.log Zero (getPrec d) d sqrt d = A.sqrt Zero (getPrec d) d (**) d d' = A.pow Zero (maxPrec d d') d d' logBase d d' = Prelude.log d' / Prelude.log d sin d = S.sin Zero (getPrec d) d cos d = S.cos Zero (getPrec d) d tan d = S.tan Zero (getPrec d) d asin d = S.asin Zero (getPrec d) d acos d = S.acos Zero (getPrec d) d atan d = S.atan Zero (getPrec d) d sinh d = S.sinh Zero (getPrec d) d cosh d = S.cosh Zero (getPrec d) d tanh d = S.tanh Zero (getPrec d) d asinh d = S.asinh Zero (getPrec d) d acosh d = S.acosh Zero (getPrec d) d atanh d = S.atanh Zero (getPrec d) d instance RealFrac MPFR where properFraction d = (fromIntegral n, f) where r = toRational d m = numerator r e = denominator r n = quot m e f = frac Zero (getPrec d) d
ekmett/hmpfr
src/Data/Number/MPFR/Instances/Zero.hs
bsd-3-clause
3,154
0
12
961
1,025
529
496
59
0
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.APPLE.RowBytes -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.APPLE.RowBytes ( -- * Extension Support glGetAPPLERowBytes, gl_APPLE_row_bytes, -- * Enums pattern GL_PACK_ROW_BYTES_APPLE, pattern GL_UNPACK_ROW_BYTES_APPLE ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
haskell-opengl/OpenGLRaw
src/Graphics/GL/APPLE/RowBytes.hs
bsd-3-clause
679
0
5
95
52
39
13
8
0
module System.Unix.Files where import Control.Exception (catch) import Prelude hiding (catch) import System.Posix.Files (createSymbolicLink, removeLink) import System.IO.Error (isAlreadyExistsError) -- |calls 'createSymbolicLink' but will remove the target and retry if -- 'createSymbolicLink' raises EEXIST. forceSymbolicLink :: FilePath -> FilePath -> IO () forceSymbolicLink target linkName = createSymbolicLink target linkName `catch` (\e -> if isAlreadyExistsError e then do removeLink linkName createSymbolicLink target linkName else ioError e)
seereason/haskell-unixutils
System/Unix/Files.hs
bsd-3-clause
610
0
11
122
128
72
56
12
2
-- | Meta data for a presentation of a /movie fragment/. module Data.ByteString.IsoBaseFileFormat.Boxes.TrackFragmentHeader where import Data.ByteString.IsoBaseFileFormat.Box import Data.ByteString.IsoBaseFileFormat.Util.BoxContent import Data.ByteString.IsoBaseFileFormat.Util.BoxFields import Data.ByteString.IsoBaseFileFormat.Util.FullBox import Data.Default -- * @tfhd@ Box -- | Construct a 'TrackFragmentHeader' box. trackFragmentHeader :: -- TODO allow 64 bit variant TrackFragmentHeader -> Box (FullBox TrackFragmentHeader 0) trackFragmentHeader = fullBox 0x020000 -- TODO box is hard coded for file offset calculations in the 'trun' box -- | Track fragment meta data -- TODO box is hard coded for file offset calculations in the 'trun' box newtype TrackFragmentHeader where TrackFragmentHeader :: Template (U32 "track_ID") 1 -> TrackFragmentHeader -- TODO all optional fields currently omitted for offset calculations in the 'trun' box deriving (IsBoxContent, Default) instance IsBox TrackFragmentHeader type instance BoxTypeSymbol TrackFragmentHeader = "tfhd" -- | Return the static size of the empty box trackFragmentHeaderStaticSize :: Num a => a trackFragmentHeaderStaticSize = fromBoxSize 0 (boxSize (trackFragmentHeader def))
sheyll/isobmff-builder
src/Data/ByteString/IsoBaseFileFormat/Boxes/TrackFragmentHeader.hs
bsd-3-clause
1,265
0
9
171
168
101
67
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1998 \section[DataCon]{@DataCon@: Data Constructors} -} {-# LANGUAGE CPP, DeriveDataTypeable #-} module DataCon ( -- * Main data types DataCon, DataConRep(..), HsBang(..), StrictnessMark(..), ConTag, -- ** Type construction mkDataCon, fIRST_TAG, buildAlgTyCon, -- ** Type deconstruction dataConRepType, dataConSig, dataConFullSig, dataConName, dataConIdentity, dataConTag, dataConTyCon, dataConOrigTyCon, dataConUserType, dataConUnivTyVars, dataConExTyVars, dataConAllTyVars, dataConEqSpec, eqSpecPreds, dataConTheta, dataConStupidTheta, dataConInstArgTys, dataConOrigArgTys, dataConOrigResTy, dataConInstOrigArgTys, dataConRepArgTys, dataConFieldLabels, dataConFieldType, dataConStrictMarks, dataConSourceArity, dataConRepArity, dataConRepRepArity, dataConIsInfix, dataConWorkId, dataConWrapId, dataConWrapId_maybe, dataConImplicitIds, dataConRepStrictness, dataConRepBangs, dataConBoxer, splitDataProductType_maybe, -- ** Predicates on DataCons isNullarySrcDataCon, isNullaryRepDataCon, isTupleDataCon, isUnboxedTupleCon, isVanillaDataCon, classDataCon, dataConCannotMatch, isBanged, isMarkedStrict, eqHsBang, -- ** Promotion related functions promoteKind, promoteDataCon, promoteDataCon_maybe ) where #include "HsVersions.h" import {-# SOURCE #-} MkId( DataConBoxer ) import Type import TypeRep( Type(..) ) -- Used in promoteType import PrelNames( liftedTypeKindTyConKey ) import ForeignCall( CType ) import Coercion import Kind import Unify import TyCon import Class import Name import Var import Outputable import Unique import ListSetOps import Util import BasicTypes import FastString import Module import VarEnv import qualified Data.Data as Data import qualified Data.Typeable import Data.Maybe import Data.Char import Data.Word {- Data constructor representation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider the following Haskell data type declaration data T = T !Int ![Int] Using the strictness annotations, GHC will represent this as data T = T Int# [Int] That is, the Int has been unboxed. Furthermore, the Haskell source construction T e1 e2 is translated to case e1 of { I# x -> case e2 of { r -> T x r }} That is, the first argument is unboxed, and the second is evaluated. Finally, pattern matching is translated too: case e of { T a b -> ... } becomes case e of { T a' b -> let a = I# a' in ... } To keep ourselves sane, we name the different versions of the data constructor differently, as follows. Note [Data Constructor Naming] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Each data constructor C has two, and possibly up to four, Names associated with it: OccName Name space Name of Notes --------------------------------------------------------------------------- The "data con itself" C DataName DataCon In dom( GlobalRdrEnv ) The "worker data con" C VarName Id The worker The "wrapper data con" $WC VarName Id The wrapper The "newtype coercion" :CoT TcClsName TyCon EVERY data constructor (incl for newtypes) has the former two (the data con itself, and its worker. But only some data constructors have a wrapper (see Note [The need for a wrapper]). Each of these three has a distinct Unique. The "data con itself" name appears in the output of the renamer, and names the Haskell-source data constructor. The type checker translates it into either the wrapper Id (if it exists) or worker Id (otherwise). The data con has one or two Ids associated with it: The "worker Id", is the actual data constructor. * Every data constructor (newtype or data type) has a worker * The worker is very like a primop, in that it has no binding. * For a *data* type, the worker *is* the data constructor; it has no unfolding * For a *newtype*, the worker has a compulsory unfolding which does a cast, e.g. newtype T = MkT Int The worker for MkT has unfolding \\(x:Int). x `cast` sym CoT Here CoT is the type constructor, witnessing the FC axiom axiom CoT : T = Int The "wrapper Id", \$WC, goes as follows * Its type is exactly what it looks like in the source program. * It is an ordinary function, and it gets a top-level binding like any other function. * The wrapper Id isn't generated for a data type if there is nothing for the wrapper to do. That is, if its defn would be \$wC = C Note [The need for a wrapper] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Why might the wrapper have anything to do? Two reasons: * Unboxing strict fields (with -funbox-strict-fields) data T = MkT !(Int,Int) \$wMkT :: (Int,Int) -> T \$wMkT (x,y) = MkT x y Notice that the worker has two fields where the wapper has just one. That is, the worker has type MkT :: Int -> Int -> T * Equality constraints for GADTs data T a where { MkT :: a -> T [a] } The worker gets a type with explicit equality constraints, thus: MkT :: forall a b. (a=[b]) => b -> T a The wrapper has the programmer-specified type: \$wMkT :: a -> T [a] \$wMkT a x = MkT [a] a [a] x The third argument is a coerion [a] :: [a]~[a] INVARIANT: the dictionary constructor for a class never has a wrapper. A note about the stupid context ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Data types can have a context: data (Eq a, Ord b) => T a b = T1 a b | T2 a and that makes the constructors have a context too (notice that T2's context is "thinned"): T1 :: (Eq a, Ord b) => a -> b -> T a b T2 :: (Eq a) => a -> T a b Furthermore, this context pops up when pattern matching (though GHC hasn't implemented this, but it is in H98, and I've fixed GHC so that it now does): f (T2 x) = x gets inferred type f :: Eq a => T a b -> a I say the context is "stupid" because the dictionaries passed are immediately discarded -- they do nothing and have no benefit. It's a flaw in the language. Up to now [March 2002] I have put this stupid context into the type of the "wrapper" constructors functions, T1 and T2, but that turned out to be jolly inconvenient for generics, and record update, and other functions that build values of type T (because they don't have suitable dictionaries available). So now I've taken the stupid context out. I simply deal with it separately in the type checker on occurrences of a constructor, either in an expression or in a pattern. [May 2003: actually I think this decision could evasily be reversed now, and probably should be. Generics could be disabled for types with a stupid context; record updates now (H98) needs the context too; etc. It's an unforced change, so I'm leaving it for now --- but it does seem odd that the wrapper doesn't include the stupid context.] [July 04] With the advent of generalised data types, it's less obvious what the "stupid context" is. Consider C :: forall a. Ord a => a -> a -> T (Foo a) Does the C constructor in Core contain the Ord dictionary? Yes, it must: f :: T b -> Ordering f = /\b. \x:T b. case x of C a (d:Ord a) (p:a) (q:a) -> compare d p q Note that (Foo a) might not be an instance of Ord. ************************************************************************ * * \subsection{Data constructors} * * ************************************************************************ -} -- | A data constructor -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose','ApiAnnotation.AnnComma' data DataCon = MkData { dcName :: Name, -- This is the name of the *source data con* -- (see "Note [Data Constructor Naming]" above) dcUnique :: Unique, -- Cached from Name dcTag :: ConTag, -- ^ Tag, used for ordering 'DataCon's -- Running example: -- -- *** As declared by the user -- data T a where -- MkT :: forall x y. (x~y,Ord x) => x -> y -> T (x,y) -- *** As represented internally -- data T a where -- MkT :: forall a. forall x y. (a~(x,y),x~y,Ord x) => x -> y -> T a -- -- The next six fields express the type of the constructor, in pieces -- e.g. -- -- dcUnivTyVars = [a] -- dcExTyVars = [x,y] -- dcEqSpec = [a~(x,y)] -- dcOtherTheta = [x~y, Ord x] -- dcOrigArgTys = [x,y] -- dcRepTyCon = T dcVanilla :: Bool, -- True <=> This is a vanilla Haskell 98 data constructor -- Its type is of form -- forall a1..an . t1 -> ... tm -> T a1..an -- No existentials, no coercions, nothing. -- That is: dcExTyVars = dcEqSpec = dcOtherTheta = [] -- NB 1: newtypes always have a vanilla data con -- NB 2: a vanilla constructor can still be declared in GADT-style -- syntax, provided its type looks like the above. -- The declaration format is held in the TyCon (algTcGadtSyntax) dcUnivTyVars :: [TyVar], -- Universally-quantified type vars [a,b,c] -- INVARIANT: length matches arity of the dcRepTyCon --- result type of (rep) data con is exactly (T a b c) dcExTyVars :: [TyVar], -- Existentially-quantified type vars -- In general, the dcUnivTyVars are NOT NECESSARILY THE SAME AS THE TYVARS -- FOR THE PARENT TyCon. With GADTs the data con might not even have -- the same number of type variables. -- [This is a change (Oct05): previously, vanilla datacons guaranteed to -- have the same type variables as their parent TyCon, but that seems ugly.] -- INVARIANT: the UnivTyVars and ExTyVars all have distinct OccNames -- Reason: less confusing, and easier to generate IfaceSyn dcEqSpec :: [(TyVar,Type)], -- Equalities derived from the result type, -- _as written by the programmer_ -- This field allows us to move conveniently between the two ways -- of representing a GADT constructor's type: -- MkT :: forall a b. (a ~ [b]) => b -> T a -- MkT :: forall b. b -> T [b] -- Each equality is of the form (a ~ ty), where 'a' is one of -- the universally quantified type variables -- The next two fields give the type context of the data constructor -- (aside from the GADT constraints, -- which are given by the dcExpSpec) -- In GADT form, this is *exactly* what the programmer writes, even if -- the context constrains only universally quantified variables -- MkT :: forall a b. (a ~ b, Ord b) => a -> T a b dcOtherTheta :: ThetaType, -- The other constraints in the data con's type -- other than those in the dcEqSpec dcStupidTheta :: ThetaType, -- The context of the data type declaration -- data Eq a => T a = ... -- or, rather, a "thinned" version thereof -- "Thinned", because the Report says -- to eliminate any constraints that don't mention -- tyvars free in the arg types for this constructor -- -- INVARIANT: the free tyvars of dcStupidTheta are a subset of dcUnivTyVars -- Reason: dcStupidTeta is gotten by thinning the stupid theta from the tycon -- -- "Stupid", because the dictionaries aren't used for anything. -- Indeed, [as of March 02] they are no longer in the type of -- the wrapper Id, because that makes it harder to use the wrap-id -- to rebuild values after record selection or in generics. dcOrigArgTys :: [Type], -- Original argument types -- (before unboxing and flattening of strict fields) dcOrigResTy :: Type, -- Original result type, as seen by the user -- NB: for a data instance, the original user result type may -- differ from the DataCon's representation TyCon. Example -- data instance T [a] where MkT :: a -> T [a] -- The OrigResTy is T [a], but the dcRepTyCon might be :T123 -- Now the strictness annotations and field labels of the constructor -- See Note [Bangs on data constructor arguments] dcArgBangs :: [HsBang], -- Strictness annotations as decided by the compiler. -- Matches 1-1 with dcOrigArgTys -- Hence length = dataConSourceArity dataCon dcFields :: [FieldLabel], -- Field labels for this constructor, in the -- same order as the dcOrigArgTys; -- length = 0 (if not a record) or dataConSourceArity. -- The curried worker function that corresponds to the constructor: -- It doesn't have an unfolding; the code generator saturates these Ids -- and allocates a real constructor when it finds one. dcWorkId :: Id, -- Constructor representation dcRep :: DataConRep, -- Cached dcRepArity :: Arity, -- == length dataConRepArgTys dcSourceArity :: Arity, -- == length dcOrigArgTys -- Result type of constructor is T t1..tn dcRepTyCon :: TyCon, -- Result tycon, T dcRepType :: Type, -- Type of the constructor -- forall a x y. (a~(x,y), x~y, Ord x) => -- x -> y -> T a -- (this is *not* of the constructor wrapper Id: -- see Note [Data con representation] below) -- Notice that the existential type parameters come *second*. -- Reason: in a case expression we may find: -- case (e :: T t) of -- MkT x y co1 co2 (d:Ord x) (v:r) (w:F s) -> ... -- It's convenient to apply the rep-type of MkT to 't', to get -- forall x y. (t~(x,y), x~y, Ord x) => x -> y -> T t -- and use that to check the pattern. Mind you, this is really only -- used in CoreLint. dcInfix :: Bool, -- True <=> declared infix -- Used for Template Haskell and 'deriving' only -- The actual fixity is stored elsewhere dcPromoted :: Maybe TyCon -- The promoted TyCon if this DataCon is promotable -- See Note [Promoted data constructors] in TyCon } deriving Data.Typeable.Typeable data DataConRep = NoDataConRep -- No wrapper | DCR { dcr_wrap_id :: Id -- Takes src args, unboxes/flattens, -- and constructs the representation , dcr_boxer :: DataConBoxer , dcr_arg_tys :: [Type] -- Final, representation argument types, -- after unboxing and flattening, -- and *including* all evidence args , dcr_stricts :: [StrictnessMark] -- 1-1 with dcr_arg_tys -- See also Note [Data-con worker strictness] in MkId.lhs , dcr_bangs :: [HsBang] -- The actual decisions made (including failures) -- 1-1 with orig_arg_tys -- See Note [Bangs on data constructor arguments] } -- Algebraic data types always have a worker, and -- may or may not have a wrapper, depending on whether -- the wrapper does anything. -- -- Data types have a worker with no unfolding -- Newtypes just have a worker, which has a compulsory unfolding (just a cast) -- _Neither_ the worker _nor_ the wrapper take the dcStupidTheta dicts as arguments -- The wrapper (if it exists) takes dcOrigArgTys as its arguments -- The worker takes dataConRepArgTys as its arguments -- If the worker is absent, dataConRepArgTys is the same as dcOrigArgTys -- The 'NoDataConRep' case is important -- Not only is this efficient, -- but it also ensures that the wrapper is replaced -- by the worker (because it *is* the worker) -- even when there are no args. E.g. in -- f (:) x -- the (:) *is* the worker. -- This is really important in rule matching, -- (We could match on the wrappers, -- but that makes it less likely that rules will match -- when we bring bits of unfoldings together.) ------------------------- -- HsBang describes what the *programmer* wrote -- This info is retained in the DataCon.dcStrictMarks field data HsBang = HsUserBang -- The user's source-code request (Maybe Bool) -- Just True {-# UNPACK #-} -- Just False {-# NOUNPACK #-} -- Nothing no pragma Bool -- True <=> '!' specified | HsNoBang -- Lazy field -- HsUserBang Nothing False means the same as HsNoBang | HsUnpack -- Definite commitment: this field is strict and unboxed (Maybe Coercion) -- co :: arg-ty ~ product-ty | HsStrict -- Definite commitment: this field is strict but not unboxed deriving (Data.Data, Data.Typeable) ------------------------- -- StrictnessMark is internal only, used to indicate strictness -- of the DataCon *worker* fields data StrictnessMark = MarkedStrict | NotMarkedStrict {- Note [Data con representation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The dcRepType field contains the type of the representation of a contructor This may differ from the type of the contructor *Id* (built by MkId.mkDataConId) for two reasons: a) the constructor Id may be overloaded, but the dictionary isn't stored e.g. data Eq a => T a = MkT a a b) the constructor may store an unboxed version of a strict field. Here's an example illustrating both: data Ord a => T a = MkT Int! a Here T :: Ord a => Int -> a -> T a but the rep type is Trep :: Int# -> a -> T a Actually, the unboxed part isn't implemented yet! Note [Bangs on data constructor arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T = MkT !Int {-# UNPACK #-} !Int Bool Its dcArgBangs field records the *users* specifications, in this case [ HsUserBang Nothing True , HsUserBang (Just True) True , HsNoBang] See the declaration of HsBang in BasicTypes The dcr_bangs field of the dcRep field records the *actual, decided* representation of the data constructor. Without -O this might be [HsStrict, HsStrict, HsNoBang] With -O it might be [HsStrict, HsUnpack, HsNoBang] With -funbox-small-strict-fields it might be [HsUnpack, HsUnpack, HsNoBang] For imported data types, the dcArgBangs field is just the same as the dcr_bangs field; we don't know what the user originally said. ************************************************************************ * * \subsection{Instances} * * ************************************************************************ -} instance Eq DataCon where a == b = getUnique a == getUnique b a /= b = getUnique a /= getUnique b instance Ord DataCon where a <= b = getUnique a <= getUnique b a < b = getUnique a < getUnique b a >= b = getUnique a >= getUnique b a > b = getUnique a > getUnique b compare a b = getUnique a `compare` getUnique b instance Uniquable DataCon where getUnique = dcUnique instance NamedThing DataCon where getName = dcName instance Outputable DataCon where ppr con = ppr (dataConName con) instance OutputableBndr DataCon where pprInfixOcc con = pprInfixName (dataConName con) pprPrefixOcc con = pprPrefixName (dataConName con) instance Data.Data DataCon where -- don't traverse? toConstr _ = abstractConstr "DataCon" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "DataCon" instance Outputable HsBang where ppr HsNoBang = empty ppr (HsUserBang prag bang) = pp_unpk prag <+> ppWhen bang (char '!') ppr (HsUnpack Nothing) = ptext (sLit "Unpk") ppr (HsUnpack (Just co)) = ptext (sLit "Unpk") <> parens (ppr co) ppr HsStrict = ptext (sLit "SrictNotUnpacked") pp_unpk :: Maybe Bool -> SDoc pp_unpk Nothing = empty pp_unpk (Just True) = ptext (sLit "{-# UNPACK #-}") pp_unpk (Just False) = ptext (sLit "{-# NOUNPACK #-}") instance Outputable StrictnessMark where ppr MarkedStrict = ptext (sLit "!") ppr NotMarkedStrict = empty eqHsBang :: HsBang -> HsBang -> Bool eqHsBang HsNoBang HsNoBang = True eqHsBang HsStrict HsStrict = True eqHsBang (HsUserBang u1 b1) (HsUserBang u2 b2) = u1==u2 && b1==b2 eqHsBang (HsUnpack Nothing) (HsUnpack Nothing) = True eqHsBang (HsUnpack (Just c1)) (HsUnpack (Just c2)) = eqType (coercionType c1) (coercionType c2) eqHsBang _ _ = False isBanged :: HsBang -> Bool isBanged HsNoBang = False isBanged (HsUserBang Nothing bang) = bang isBanged _ = True isMarkedStrict :: StrictnessMark -> Bool isMarkedStrict NotMarkedStrict = False isMarkedStrict _ = True -- All others are strict {- ************************************************************************ * * \subsection{Construction} * * ************************************************************************ -} -- | Build a new data constructor mkDataCon :: Name -> Bool -- ^ Is the constructor declared infix? -> [HsBang] -- ^ Strictness annotations written in the source file -> [FieldLabel] -- ^ Field labels for the constructor, if it is a record, -- otherwise empty -> [TyVar] -- ^ Universally quantified type variables -> [TyVar] -- ^ Existentially quantified type variables -> [(TyVar,Type)] -- ^ GADT equalities -> ThetaType -- ^ Theta-type occuring before the arguments proper -> [Type] -- ^ Original argument types -> Type -- ^ Original result type -> TyCon -- ^ Representation type constructor -> ThetaType -- ^ The "stupid theta", context of the data declaration -- e.g. @data Eq a => T a ...@ -> Id -- ^ Worker Id -> DataConRep -- ^ Representation -> DataCon -- Can get the tag from the TyCon mkDataCon name declared_infix arg_stricts -- Must match orig_arg_tys 1-1 fields univ_tvs ex_tvs eq_spec theta orig_arg_tys orig_res_ty rep_tycon stupid_theta work_id rep -- Warning: mkDataCon is not a good place to check invariants. -- If the programmer writes the wrong result type in the decl, thus: -- data T a where { MkT :: S } -- then it's possible that the univ_tvs may hit an assertion failure -- if you pull on univ_tvs. This case is checked by checkValidDataCon, -- so the error is detected properly... it's just that asaertions here -- are a little dodgy. = con where is_vanilla = null ex_tvs && null eq_spec && null theta con = MkData {dcName = name, dcUnique = nameUnique name, dcVanilla = is_vanilla, dcInfix = declared_infix, dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, dcEqSpec = eq_spec, dcOtherTheta = theta, dcStupidTheta = stupid_theta, dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty, dcRepTyCon = rep_tycon, dcArgBangs = arg_stricts, dcFields = fields, dcTag = tag, dcRepType = rep_ty, dcWorkId = work_id, dcRep = rep, dcSourceArity = length orig_arg_tys, dcRepArity = length rep_arg_tys, dcPromoted = mb_promoted } -- The 'arg_stricts' passed to mkDataCon are simply those for the -- source-language arguments. We add extra ones for the -- dictionary arguments right here. tag = assoc "mkDataCon" (tyConDataCons rep_tycon `zip` [fIRST_TAG..]) con rep_arg_tys = dataConRepArgTys con rep_ty = mkForAllTys univ_tvs $ mkForAllTys ex_tvs $ mkFunTys rep_arg_tys $ mkTyConApp rep_tycon (mkTyVarTys univ_tvs) mb_promoted -- See Note [Promoted data constructors] in TyCon | isJust (promotableTyCon_maybe rep_tycon) -- The TyCon is promotable only if all its datacons -- are, so the promoteType for prom_kind should succeed = Just (mkPromotedDataCon con name (getUnique name) prom_kind roles) | otherwise = Nothing prom_kind = promoteType (dataConUserType con) roles = map (const Nominal) (univ_tvs ++ ex_tvs) ++ map (const Representational) orig_arg_tys eqSpecPreds :: [(TyVar,Type)] -> ThetaType eqSpecPreds spec = [ mkEqPred (mkTyVarTy tv) ty | (tv,ty) <- spec ] {- Note [Unpack equality predicates] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we have a GADT with a contructor C :: (a~[b]) => b -> T a we definitely want that equality predicate *unboxed* so that it takes no space at all. This is easily done: just give it an UNPACK pragma. The rest of the unpack/repack code does the heavy lifting. This one line makes every GADT take a word less space for each equality predicate, so it's pretty important! -} -- | The 'Name' of the 'DataCon', giving it a unique, rooted identification dataConName :: DataCon -> Name dataConName = dcName -- | The tag used for ordering 'DataCon's dataConTag :: DataCon -> ConTag dataConTag = dcTag -- | The type constructor that we are building via this data constructor dataConTyCon :: DataCon -> TyCon dataConTyCon = dcRepTyCon -- | The original type constructor used in the definition of this data -- constructor. In case of a data family instance, that will be the family -- type constructor. dataConOrigTyCon :: DataCon -> TyCon dataConOrigTyCon dc | Just (tc, _) <- tyConFamInst_maybe (dcRepTyCon dc) = tc | otherwise = dcRepTyCon dc -- | The representation type of the data constructor, i.e. the sort -- type that will represent values of this type at runtime dataConRepType :: DataCon -> Type dataConRepType = dcRepType -- | Should the 'DataCon' be presented infix? dataConIsInfix :: DataCon -> Bool dataConIsInfix = dcInfix -- | The universally-quantified type variables of the constructor dataConUnivTyVars :: DataCon -> [TyVar] dataConUnivTyVars = dcUnivTyVars -- | The existentially-quantified type variables of the constructor dataConExTyVars :: DataCon -> [TyVar] dataConExTyVars = dcExTyVars -- | Both the universal and existentiatial type variables of the constructor dataConAllTyVars :: DataCon -> [TyVar] dataConAllTyVars (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs }) = univ_tvs ++ ex_tvs -- | Equalities derived from the result type of the data constructor, as written -- by the programmer in any GADT declaration dataConEqSpec :: DataCon -> [(TyVar,Type)] dataConEqSpec = dcEqSpec -- | The *full* constraints on the constructor type dataConTheta :: DataCon -> ThetaType dataConTheta (MkData { dcEqSpec = eq_spec, dcOtherTheta = theta }) = eqSpecPreds eq_spec ++ theta -- | Get the Id of the 'DataCon' worker: a function that is the "actual" -- constructor and has no top level binding in the program. The type may -- be different from the obvious one written in the source program. Panics -- if there is no such 'Id' for this 'DataCon' dataConWorkId :: DataCon -> Id dataConWorkId dc = dcWorkId dc -- | Get the Id of the 'DataCon' wrapper: a function that wraps the "actual" -- constructor so it has the type visible in the source program: c.f. 'dataConWorkId'. -- Returns Nothing if there is no wrapper, which occurs for an algebraic data constructor -- and also for a newtype (whose constructor is inlined compulsorily) dataConWrapId_maybe :: DataCon -> Maybe Id dataConWrapId_maybe dc = case dcRep dc of NoDataConRep -> Nothing DCR { dcr_wrap_id = wrap_id } -> Just wrap_id -- | Returns an Id which looks like the Haskell-source constructor by using -- the wrapper if it exists (see 'dataConWrapId_maybe') and failing over to -- the worker (see 'dataConWorkId') dataConWrapId :: DataCon -> Id dataConWrapId dc = case dcRep dc of NoDataConRep-> dcWorkId dc -- worker=wrapper DCR { dcr_wrap_id = wrap_id } -> wrap_id -- | Find all the 'Id's implicitly brought into scope by the data constructor. Currently, -- the union of the 'dataConWorkId' and the 'dataConWrapId' dataConImplicitIds :: DataCon -> [Id] dataConImplicitIds (MkData { dcWorkId = work, dcRep = rep}) = case rep of NoDataConRep -> [work] DCR { dcr_wrap_id = wrap } -> [wrap,work] -- | The labels for the fields of this particular 'DataCon' dataConFieldLabels :: DataCon -> [FieldLabel] dataConFieldLabels = dcFields -- | Extract the type for any given labelled field of the 'DataCon' dataConFieldType :: DataCon -> FieldLabel -> Type dataConFieldType con label = case lookup label (dcFields con `zip` dcOrigArgTys con) of Just ty -> ty Nothing -> pprPanic "dataConFieldType" (ppr con <+> ppr label) -- | The strictness markings decided on by the compiler. Does not include those for -- existential dictionaries. The list is in one-to-one correspondence with the arity of the 'DataCon' dataConStrictMarks :: DataCon -> [HsBang] dataConStrictMarks = dcArgBangs -- | Source-level arity of the data constructor dataConSourceArity :: DataCon -> Arity dataConSourceArity (MkData { dcSourceArity = arity }) = arity -- | Gives the number of actual fields in the /representation/ of the -- data constructor. This may be more than appear in the source code; -- the extra ones are the existentially quantified dictionaries dataConRepArity :: DataCon -> Arity dataConRepArity (MkData { dcRepArity = arity }) = arity -- | The number of fields in the /representation/ of the constructor -- AFTER taking into account the unpacking of any unboxed tuple fields dataConRepRepArity :: DataCon -> RepArity dataConRepRepArity dc = typeRepArity (dataConRepArity dc) (dataConRepType dc) -- | Return whether there are any argument types for this 'DataCon's original source type isNullarySrcDataCon :: DataCon -> Bool isNullarySrcDataCon dc = null (dcOrigArgTys dc) -- | Return whether there are any argument types for this 'DataCon's runtime representation type isNullaryRepDataCon :: DataCon -> Bool isNullaryRepDataCon dc = dataConRepArity dc == 0 dataConRepStrictness :: DataCon -> [StrictnessMark] -- ^ Give the demands on the arguments of a -- Core constructor application (Con dc args) dataConRepStrictness dc = case dcRep dc of NoDataConRep -> [NotMarkedStrict | _ <- dataConRepArgTys dc] DCR { dcr_stricts = strs } -> strs dataConRepBangs :: DataCon -> [HsBang] dataConRepBangs dc = case dcRep dc of NoDataConRep -> dcArgBangs dc DCR { dcr_bangs = bangs } -> bangs dataConBoxer :: DataCon -> Maybe DataConBoxer dataConBoxer (MkData { dcRep = DCR { dcr_boxer = boxer } }) = Just boxer dataConBoxer _ = Nothing -- | The \"signature\" of the 'DataCon' returns, in order: -- -- 1) The result of 'dataConAllTyVars', -- -- 2) All the 'ThetaType's relating to the 'DataCon' (coercion, dictionary, implicit -- parameter - whatever) -- -- 3) The type arguments to the constructor -- -- 4) The /original/ result type of the 'DataCon' dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type) dataConSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, dcEqSpec = eq_spec, dcOtherTheta = theta, dcOrigArgTys = arg_tys, dcOrigResTy = res_ty}) = (univ_tvs ++ ex_tvs, eqSpecPreds eq_spec ++ theta, arg_tys, res_ty) -- | The \"full signature\" of the 'DataCon' returns, in order: -- -- 1) The result of 'dataConUnivTyVars' -- -- 2) The result of 'dataConExTyVars' -- -- 3) The result of 'dataConEqSpec' -- -- 4) The result of 'dataConDictTheta' -- -- 5) The original argument types to the 'DataCon' (i.e. before -- any change of the representation of the type) -- -- 6) The original result type of the 'DataCon' dataConFullSig :: DataCon -> ([TyVar], [TyVar], [(TyVar,Type)], ThetaType, [Type], Type) dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, dcEqSpec = eq_spec, dcOtherTheta = theta, dcOrigArgTys = arg_tys, dcOrigResTy = res_ty}) = (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, res_ty) dataConOrigResTy :: DataCon -> Type dataConOrigResTy dc = dcOrigResTy dc -- | The \"stupid theta\" of the 'DataCon', such as @data Eq a@ in: -- -- > data Eq a => T a = ... dataConStupidTheta :: DataCon -> ThetaType dataConStupidTheta dc = dcStupidTheta dc dataConUserType :: DataCon -> Type -- ^ The user-declared type of the data constructor -- in the nice-to-read form: -- -- > T :: forall a b. a -> b -> T [a] -- -- rather than: -- -- > T :: forall a c. forall b. (c~[a]) => a -> b -> T c -- -- NB: If the constructor is part of a data instance, the result type -- mentions the family tycon, not the internal one. dataConUserType (MkData { dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, dcEqSpec = eq_spec, dcOtherTheta = theta, dcOrigArgTys = arg_tys, dcOrigResTy = res_ty }) = mkForAllTys ((univ_tvs `minusList` map fst eq_spec) ++ ex_tvs) $ mkFunTys theta $ mkFunTys arg_tys $ res_ty -- | Finds the instantiated types of the arguments required to construct a 'DataCon' representation -- NB: these INCLUDE any dictionary args -- but EXCLUDE the data-declaration context, which is discarded -- It's all post-flattening etc; this is a representation type dataConInstArgTys :: DataCon -- ^ A datacon with no existentials or equality constraints -- However, it can have a dcTheta (notably it can be a -- class dictionary, with superclasses) -> [Type] -- ^ Instantiated at these types -> [Type] dataConInstArgTys dc@(MkData {dcUnivTyVars = univ_tvs, dcEqSpec = eq_spec, dcExTyVars = ex_tvs}) inst_tys = ASSERT2( length univ_tvs == length inst_tys , ptext (sLit "dataConInstArgTys") <+> ppr dc $$ ppr univ_tvs $$ ppr inst_tys) ASSERT2( null ex_tvs && null eq_spec, ppr dc ) map (substTyWith univ_tvs inst_tys) (dataConRepArgTys dc) -- | Returns just the instantiated /value/ argument types of a 'DataCon', -- (excluding dictionary args) dataConInstOrigArgTys :: DataCon -- Works for any DataCon -> [Type] -- Includes existential tyvar args, but NOT -- equality constraints or dicts -> [Type] -- For vanilla datacons, it's all quite straightforward -- But for the call in MatchCon, we really do want just the value args dataConInstOrigArgTys dc@(MkData {dcOrigArgTys = arg_tys, dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs}) inst_tys = ASSERT2( length tyvars == length inst_tys , ptext (sLit "dataConInstOrigArgTys") <+> ppr dc $$ ppr tyvars $$ ppr inst_tys ) map (substTyWith tyvars inst_tys) arg_tys where tyvars = univ_tvs ++ ex_tvs -- | Returns the argument types of the wrapper, excluding all dictionary arguments -- and without substituting for any type variables dataConOrigArgTys :: DataCon -> [Type] dataConOrigArgTys dc = dcOrigArgTys dc -- | Returns the arg types of the worker, including *all* evidence, after any -- flattening has been done and without substituting for any type variables dataConRepArgTys :: DataCon -> [Type] dataConRepArgTys (MkData { dcRep = rep , dcEqSpec = eq_spec , dcOtherTheta = theta , dcOrigArgTys = orig_arg_tys }) = case rep of NoDataConRep -> ASSERT( null eq_spec ) theta ++ orig_arg_tys DCR { dcr_arg_tys = arg_tys } -> arg_tys -- | The string @package:module.name@ identifying a constructor, which is attached -- to its info table and used by the GHCi debugger and the heap profiler dataConIdentity :: DataCon -> [Word8] -- We want this string to be UTF-8, so we get the bytes directly from the FastStrings. dataConIdentity dc = bytesFS (packageKeyFS (modulePackageKey mod)) ++ fromIntegral (ord ':') : bytesFS (moduleNameFS (moduleName mod)) ++ fromIntegral (ord '.') : bytesFS (occNameFS (nameOccName name)) where name = dataConName dc mod = ASSERT( isExternalName name ) nameModule name isTupleDataCon :: DataCon -> Bool isTupleDataCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc isUnboxedTupleCon :: DataCon -> Bool isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc -- | Vanilla 'DataCon's are those that are nice boring Haskell 98 constructors isVanillaDataCon :: DataCon -> Bool isVanillaDataCon dc = dcVanilla dc classDataCon :: Class -> DataCon classDataCon clas = case tyConDataCons (classTyCon clas) of (dict_constr:no_more) -> ASSERT( null no_more ) dict_constr [] -> panic "classDataCon" dataConCannotMatch :: [Type] -> DataCon -> Bool -- Returns True iff the data con *definitely cannot* match a -- scrutinee of type (T tys) -- where T is the dcRepTyCon for the data con -- NB: look at *all* equality constraints, not only those -- in dataConEqSpec; see Trac #5168 dataConCannotMatch tys con | null theta = False -- Common | all isTyVarTy tys = False -- Also common | otherwise = typesCantMatch [(Type.substTy subst ty1, Type.substTy subst ty2) | (ty1, ty2) <- concatMap predEqs theta ] where dc_tvs = dataConUnivTyVars con theta = dataConTheta con subst = ASSERT2( length dc_tvs == length tys, ppr con $$ ppr dc_tvs $$ ppr tys ) zipTopTvSubst dc_tvs tys -- TODO: could gather equalities from superclasses too predEqs pred = case classifyPredType pred of EqPred NomEq ty1 ty2 -> [(ty1, ty2)] TuplePred ts -> concatMap predEqs ts _ -> [] {- ************************************************************************ * * Building an algebraic data type * * ************************************************************************ buildAlgTyCon is here because it is called from TysWiredIn, which in turn depends on DataCon, but not on BuildTyCl. -} buildAlgTyCon :: Name -> [TyVar] -- ^ Kind variables and type variables -> [Role] -> Maybe CType -> ThetaType -- ^ Stupid theta -> AlgTyConRhs -> RecFlag -> Bool -- ^ True <=> this TyCon is promotable -> Bool -- ^ True <=> was declared in GADT syntax -> TyConParent -> TyCon buildAlgTyCon tc_name ktvs roles cType stupid_theta rhs is_rec is_promotable gadt_syn parent = tc where kind = mkPiKinds ktvs liftedTypeKind -- tc and mb_promoted_tc are mutually recursive tc = mkAlgTyCon tc_name kind ktvs roles cType stupid_theta rhs parent is_rec gadt_syn mb_promoted_tc mb_promoted_tc | is_promotable = Just (mkPromotedTyCon tc (promoteKind kind)) | otherwise = Nothing {- ************************************************************************ * * Promoting of data types to the kind level * * ************************************************************************ These two 'promoted..' functions are here because * They belong together * 'promoteDataCon' depends on DataCon stuff -} promoteDataCon :: DataCon -> TyCon promoteDataCon (MkData { dcPromoted = Just tc }) = tc promoteDataCon dc = pprPanic "promoteDataCon" (ppr dc) promoteDataCon_maybe :: DataCon -> Maybe TyCon promoteDataCon_maybe (MkData { dcPromoted = mb_tc }) = mb_tc {- Note [Promoting a Type to a Kind] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppsoe we have a data constructor D D :: forall (a:*). Maybe a -> T a We promote this to be a type constructor 'D: 'D :: forall (k:BOX). 'Maybe k -> 'T k The transformation from type to kind is done by promoteType * Convert forall (a:*) to forall (k:BOX), and substitute * Ensure all foralls are at the top (no higher rank stuff) * Ensure that all type constructors mentioned (Maybe and T in the example) are promotable; that is, they have kind * -> ... -> * -> * -} -- | Promotes a type to a kind. -- Assumes the argument satisfies 'isPromotableType' promoteType :: Type -> Kind promoteType ty = mkForAllTys kvs (go rho) where (tvs, rho) = splitForAllTys ty kvs = [ mkKindVar (tyVarName tv) superKind | tv <- tvs ] env = zipVarEnv tvs kvs go (TyConApp tc tys) | Just prom_tc <- promotableTyCon_maybe tc = mkTyConApp prom_tc (map go tys) go (FunTy arg res) = mkArrowKind (go arg) (go res) go (TyVarTy tv) | Just kv <- lookupVarEnv env tv = TyVarTy kv go _ = panic "promoteType" -- Argument did not satisfy isPromotableType promoteKind :: Kind -> SuperKind -- Promote the kind of a type constructor -- from (* -> * -> *) to (BOX -> BOX -> BOX) promoteKind (TyConApp tc []) | tc `hasKey` liftedTypeKindTyConKey = superKind promoteKind (FunTy arg res) = FunTy (promoteKind arg) (promoteKind res) promoteKind k = pprPanic "promoteKind" (ppr k) {- ************************************************************************ * * \subsection{Splitting products} * * ************************************************************************ -} -- | Extract the type constructor, type argument, data constructor and it's -- /representation/ argument types from a type if it is a product type. -- -- Precisely, we return @Just@ for any type that is all of: -- -- * Concrete (i.e. constructors visible) -- -- * Single-constructor -- -- * Not existentially quantified -- -- Whether the type is a @data@ type or a @newtype@ splitDataProductType_maybe :: Type -- ^ A product type, perhaps -> Maybe (TyCon, -- The type constructor [Type], -- Type args of the tycon DataCon, -- The data constructor [Type]) -- Its /representation/ arg types -- Rejecting existentials is conservative. Maybe some things -- could be made to work with them, but I'm not going to sweat -- it through till someone finds it's important. splitDataProductType_maybe ty | Just (tycon, ty_args) <- splitTyConApp_maybe ty , Just con <- isDataProductTyCon_maybe tycon = Just (tycon, ty_args, con, dataConInstArgTys con ty_args) | otherwise = Nothing
bitemyapp/ghc
compiler/basicTypes/DataCon.hs
bsd-3-clause
45,391
0
18
13,432
4,975
2,827
2,148
405
4
module Day9 where import qualified Text.Parsec as Parsec import Text.Parsec hiding (parse) import Text.Parsec.Char import Lib data Code = Raw String | Repeat Int String deriving (Show) type Parser = Parsec String () input = readFile "day9" marker :: Parser Code marker = do string "(" subseqCount <- read <$> many1 digit string "x" times <- read <$> many1 digit string ")" subseq <- count subseqCount anyChar pure $ Repeat times subseq raw :: Parser Code raw = Raw <$> (many1 $ noneOf "(") code :: Parser Code code = try marker <|> raw parse :: String -> [Code] parse s = either (error . show) id $ Parsec.parse (many code) "Codes" s solve :: [Code] -> String solve = concatMap runCode where runCode (Raw s) = s runCode (Repeat n s) = concat $ replicate n s solve2 :: [Code] -> Int solve2 = sum . map runCode where runCode (Raw s) = length s runCode (Repeat n s) = n * (solve2 $ parse s)
mbernat/aoc16-haskell
src/Day9.hs
bsd-3-clause
950
0
10
229
391
199
192
32
2
-- -- Ray.Algebra -- module Ray.Algebra where import Data.Maybe import Test.QuickCheck nearly0 = 0.00000001 :: Double class (Show a, Eq a) => BasicMatrix a where madd :: a -> a -> a msub :: a -> a -> a mscale :: Double -> a -> a mdiv :: a -> Double -> Maybe a mdiv a s | s == 0 = Nothing | otherwise = Just ((1 / s) `mscale` a) norm :: a -> Double nearlyEqual :: a -> a -> Bool class (BasicMatrix a) => Vector a where dot :: a -> a -> Double normalize :: a -> Maybe a normalize a = mdiv a (norm a) square :: a -> Double square v = v `dot` v data Vector3 = Vector3 Double Double Double instance Show Vector3 where show (Vector3 ax ay az) = "[" ++ (show ax) ++ "," ++ (show ay) ++ "," ++ (show az) ++ "]" instance Eq Vector3 where (==) (Vector3 ax ay az) (Vector3 bx by bz) = ax == bx && ay == by && az == bz instance Arbitrary Vector3 where arbitrary = do x <- arbitrary y <- arbitrary z <- arbitrary return $ Vector3 x y z instance BasicMatrix Vector3 where -- | -- vector addition -- -- >>> maddd (Vector3 1 2 3) (Vector3 4 5 6) -- [5.0,7.0,9.1] madd (Vector3 ax ay az) (Vector3 bx by bz) = Vector3 (ax + bx) (ay + by) (az + bz) msub (Vector3 ax ay az) (Vector3 bx by bz) = Vector3 (ax - bx) (ay - by) (az - bz) mscale s (Vector3 x y z) = Vector3 (s * x) (s * y) (s * z) norm a = sqrt $ square a -- | -- nearly equal Zero -- (.==.) nearlyEqual a b = norm (msub a b) < nearly0 -- | -- vector substract -- -- >>> msub (Vector3 1 2 3) (Vector3 4 5 6) -- [-3.0,-3.0,-3.0] -- -- | -- vector scaling -- -- >>> mscale 4.0 (Vector3 1.1 2.1 3.1) -- [4.4,8.4,12.4] -- -- | -- norm of vector -- instance Vector Vector3 where -- | -- dot vector -- dot (Vector3 ax ay az) (Vector3 bx by bz) = ax * bx + ay * by + az * bz -- | -- cross vector -- cross :: Vector3 -> Vector3 -> Vector3 cross (Vector3 ax ay az) (Vector3 bx by bz) = Vector3 (ay * bz - by * az) (az * bx - bz * ax) (ax * by - ay * bx) -- | -- initialize Vector -- initVec :: Double -> Double -> Double -> Vector3 initVec x y z = Vector3 x y z -- | -- element X axis of vector -- -- >>> elemX (Vector3 1 2 3) -- 1.0 -- >>> elemY (Vector3 1 2 3) -- 2.0 -- >>> elemZ (Vector3 1 2 3) -- 3.0 -- elemX :: Vector3 -> Double elemX (Vector3 ax _ _) = ax elemY :: Vector3 -> Double elemY (Vector3 _ ay _) = ay elemZ :: Vector3 -> Double elemZ (Vector3 _ _ az) = az -- | -- QuickCheck -- -- prop> \a b -> msub (madd a b) (b :: Vector3) `nearlyEqual` (a :: Vector3) -- prop> \a b -> madd (msub a b) (b :: Vector3) `nearlyEqual` (a :: Vector3) -- prop> \a s -> elemX (mscale s a) == s * elemX a -- prop> dot (Vector3 ax ay az) (Vector3 bx by bz) == ax * bx + ay * by + az * bz -- prop> dot a (a :: Vector3) == square a -- prop> elemX (cross (Vector3 ax ay az) (Vector3 bx by bz)) == ay * bz - az * by -- prop> elemY (cross (Vector3 ax ay az) (Vector3 bx by bz)) == az * bx - ax * bz -- prop> elemZ (cross (Vector3 ax ay az) (Vector3 bx by bz)) == ax * by - ay * bx
eijian/raytracer
src/Ray/Algebra-r1.hs
bsd-3-clause
3,483
4
13
1,248
982
532
450
-1
-1
{-| Module : Idris.REPL Description : Entry Point for the Idris REPL and CLI. License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor, PatternGuards, CPP #-} module Idris.REPL ( idemodeStart , startServer , runClient , process , replSettings , repl , proofs ) where import Idris.AbsSyntax import Idris.ASTUtils import Idris.Apropos (apropos, aproposModules) import Idris.REPL.Parser import Idris.Error import Idris.IBC import Idris.ErrReverse import Idris.Delaborate import Idris.Docstrings (overview, renderDocstring, renderDocTerm) import Idris.Help import Idris.IdrisDoc import Idris.Prover import Idris.Parser hiding (indent) import Idris.Coverage import Idris.Docs hiding (Doc) import Idris.Completion import qualified Idris.IdeMode as IdeMode import Idris.Colours hiding (colourise) import Idris.Inliner import Idris.Output import Idris.Interactive import Idris.WhoCalls import Idris.TypeSearch (searchByType) import Idris.REPL.Browse (namesInNS, namespacesInNS) import Idris.REPL.Commands import Idris.ElabDecls import Idris.Elab.Clause import Idris.Elab.Value import Idris.Elab.Term import Idris.ModeCommon import Idris.Info import Version_idris (gitHash) import Util.System import Util.DynamicLinker import Util.Net (listenOnLocalhost, listenOnLocalhostAnyPort) import Util.Pretty hiding ((</>)) import Idris.Core.Evaluate import Idris.Core.Execute (execute) import Idris.Core.TT import Idris.Core.Unify import Idris.Core.WHNF import Idris.Core.Constraints import IRTS.Compiler import Control.Category import qualified Control.Exception as X import Prelude hiding ((<$>), (.), id) import Data.List.Split (splitOn) import qualified Data.Text as T import Text.Trifecta.Result(Result(..), ErrInfo(..)) import System.Console.Haskeline as H import System.FilePath ( (</>) , (<.>) , splitExtension , addExtension , dropExtension , takeExtension , takeDirectory ) import System.Exit import System.Environment import System.Process import System.Directory import System.IO import Control.Monad import Control.Monad.Trans.Except (ExceptT, runExceptT) import Control.Monad.Trans.State.Strict ( StateT, execStateT, evalStateT, get, put ) import Control.Monad.Trans ( lift ) import Control.Concurrent.MVar import Network import Control.Concurrent import Data.Maybe import Data.List hiding (group) import Data.Char import qualified Data.Set as S import Data.Version import Data.Either (partitionEithers) import Control.DeepSeq import Control.Concurrent.Async (race) import System.FSNotify (withManager, watchDir) import System.FSNotify.Devel (allEvents, doAllEvents) -- | Run the REPL repl :: IState -- ^ The initial state -> [FilePath] -- ^ The loaded modules -> FilePath -- ^ The file to edit (with :e) -> InputT Idris () repl orig mods efile = -- H.catch do let quiet = opt_quiet (idris_options orig) i <- lift getIState let colour = idris_colourRepl i let theme = idris_colourTheme i let mvs = idris_metavars i let prompt = if quiet then "" else showMVs colour theme mvs ++ let str = mkPrompt mods ++ ">" in (if colour && not isWindows then colourisePrompt theme str else str) ++ " " x <- H.catch (H.withInterrupt $ getInputLine prompt) (ctrlC (return $ Just "")) case x of Nothing -> do lift $ when (not quiet) (iputStrLn "Bye bye") return () Just input -> -- H.catch do ms <- H.catch (H.withInterrupt $ lift $ processInput input orig mods efile) (ctrlC (return (Just mods))) case ms of Just mods -> let efile' = fromMaybe efile (listToMaybe mods) in repl orig mods efile' Nothing -> return () -- ctrlC) -- ctrlC where ctrlC :: InputT Idris a -> SomeException -> InputT Idris a ctrlC act e = do lift $ iputStrLn (show e) act -- repl orig mods showMVs c thm [] = "" showMVs c thm ms = "Holes: " ++ show' 4 c thm (map fst ms) ++ "\n" show' 0 c thm ms = let l = length ms in "... ( + " ++ show l ++ " other" ++ if l == 1 then ")" else "s)" show' n c thm [m] = showM c thm m show' n c thm (m : ms) = showM c thm m ++ ", " ++ show' (n - 1) c thm ms showM c thm n = if c then colouriseFun thm (show n) else show n -- | Run the REPL server startServer :: PortNumber -> IState -> [FilePath] -> Idris () startServer port orig fn_in = do tid <- runIO $ forkIO (serverLoop port) return () where serverLoop port = withSocketsDo $ do sock <- listenOnLocalhost port loop fn orig { idris_colourRepl = False } sock fn = fromMaybe "" (listToMaybe fn_in) loop fn ist sock = do (h,_,_) <- accept sock hSetEncoding h utf8 cmd <- hGetLine h let isth = case idris_outputmode ist of RawOutput _ -> ist {idris_outputmode = RawOutput h} IdeMode n _ -> ist {idris_outputmode = IdeMode n h} (ist', fn) <- processNetCmd orig isth h fn cmd hClose h loop fn ist' sock processNetCmd :: IState -> IState -> Handle -> FilePath -> String -> IO (IState, FilePath) processNetCmd orig i h fn cmd = do res <- case parseCmd i "(net)" cmd of Failure (ErrInfo err _) -> return (Left (Msg " invalid command")) Success (Right c) -> runExceptT $ evalStateT (processNet fn c) i Success (Left err) -> return (Left (Msg err)) case res of Right x -> return x Left err -> do hPutStrLn h (show err) return (i, fn) where processNet fn Reload = processNet fn (Load fn Nothing) processNet fn (Load f toline) = -- The $!! here prevents a space leak on reloading. -- This isn't a solution - but it's a temporary stopgap. -- See issue #2386 do putIState $!! orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i , idris_colourRepl = False } setErrContext True setOutH h setQuiet True setVerbose False mods <- loadInputs [f] toline ist <- getIState return (ist, f) processNet fn c = do process fn c ist <- getIState return (ist, fn) setOutH :: Handle -> Idris () setOutH h = do ist <- getIState putIState $ case idris_outputmode ist of RawOutput _ -> ist {idris_outputmode = RawOutput h} IdeMode n _ -> ist {idris_outputmode = IdeMode n h} -- | Run a command on the server on localhost runClient :: Maybe PortNumber -> String -> IO () runClient port str = withSocketsDo $ do let port' = fromMaybe defaultPort port res <- X.try (connectTo "localhost" $ PortNumber port') case res of Right h -> do hSetEncoding h utf8 hPutStrLn h str resp <- hGetResp "" h putStr resp hClose h Left err -> do connectionError err exitWith (ExitFailure 1) where hGetResp acc h = do eof <- hIsEOF h if eof then return acc else do l <- hGetLine h hGetResp (acc ++ l ++ "\n") h connectionError :: X.SomeException -> IO () connectionError _ = putStrLn "Unable to connect to a running Idris repl" initIdemodeSocket :: IO Handle initIdemodeSocket = do (sock, port) <- listenOnLocalhostAnyPort putStrLn $ show port (h, _, _) <- accept sock hSetEncoding h utf8 return h -- | Run the IdeMode idemodeStart :: Bool -> IState -> [FilePath] -> Idris () idemodeStart s orig mods = do h <- runIO $ if s then initIdemodeSocket else return stdout setIdeMode True h i <- getIState case idris_outputmode i of IdeMode n h -> do runIO $ hPutStrLn h $ IdeMode.convSExp "protocol-version" IdeMode.ideModeEpoch n case mods of a:_ -> runIdeModeCommand h n i "" [] (IdeMode.LoadFile a Nothing) _ -> return () idemode h orig mods idemode :: Handle -> IState -> [FilePath] -> Idris () idemode h orig mods = do idrisCatch (do let inh = if h == stdout then stdin else h len' <- runIO $ IdeMode.getLen inh len <- case len' of Left err -> ierror err Right n -> return n l <- runIO $ IdeMode.getNChar inh len "" (sexp, id) <- case IdeMode.parseMessage l of Left err -> ierror err Right (sexp, id) -> return (sexp, id) i <- getIState putIState $ i { idris_outputmode = (IdeMode id h) } idrisCatch -- to report correct id back! (do let fn = fromMaybe "" (listToMaybe mods) case IdeMode.sexpToCommand sexp of Just cmd -> runIdeModeCommand h id orig fn mods cmd Nothing -> iPrintError "did not understand" ) (\e -> do iPrintError $ show e)) (\e -> do iPrintError $ show e) idemode h orig mods -- | Run IDEMode commands runIdeModeCommand :: Handle -- ^^ The handle for communication -> Integer -- ^^ The continuation ID for the client -> IState -- ^^ The original IState -> FilePath -- ^^ The current open file -> [FilePath] -- ^^ The currently loaded modules -> IdeMode.IdeModeCommand -- ^^ The command to process -> Idris () runIdeModeCommand h id orig fn mods (IdeMode.Interpret cmd) = do c <- colourise i <- getIState case parseCmd i "(input)" cmd of Failure (ErrInfo err _) -> iPrintError $ show (fixColour False err) Success (Right (Prove mode n')) -> idrisCatch (do process fn (Prove mode n') isetPrompt (mkPrompt mods) case idris_outputmode i of IdeMode n h -> -- signal completion of proof to ide runIO . hPutStrLn h $ IdeMode.convSExp "return" (IdeMode.SymbolAtom "ok", "") n _ -> return ()) (\e -> do ist <- getIState isetPrompt (mkPrompt mods) case idris_outputmode i of IdeMode n h -> runIO . hPutStrLn h $ IdeMode.convSExp "abandon-proof" "Abandoned" n _ -> return () iRenderError $ pprintErr ist e) Success (Right cmd) -> idrisCatch (idemodeProcess fn cmd) (\e -> getIState >>= iRenderError . flip pprintErr e) Success (Left err) -> iPrintError err runIdeModeCommand h id orig fn mods (IdeMode.REPLCompletions str) = do (unused, compls) <- replCompletion (reverse str, "") let good = IdeMode.SexpList [IdeMode.SymbolAtom "ok", IdeMode.toSExp (map replacement compls, reverse unused)] runIO . hPutStrLn h $ IdeMode.convSExp "return" good id runIdeModeCommand h id orig fn mods (IdeMode.LoadFile filename toline) = -- The $!! here prevents a space leak on reloading. -- This isn't a solution - but it's a temporary stopgap. -- See issue #2386 do i <- getIState clearErr putIState $!! orig { idris_options = idris_options i, idris_outputmode = (IdeMode id h) } mods <- loadInputs [filename] toline isetPrompt (mkPrompt mods) -- Report either success or failure i <- getIState case (errSpan i) of Nothing -> let msg = maybe (IdeMode.SexpList [IdeMode.SymbolAtom "ok", IdeMode.SexpList []]) (\fc -> IdeMode.SexpList [IdeMode.SymbolAtom "ok", IdeMode.toSExp fc]) (idris_parsedSpan i) in runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id Just x -> iPrintError $ "didn't load " ++ filename idemode h orig mods runIdeModeCommand h id orig fn mods (IdeMode.TypeOf name) = case splitName name of Left err -> iPrintError err Right n -> process "(idemode)" (Check (PRef (FC "(idemode)" (0,0) (0,0)) [] n)) runIdeModeCommand h id orig fn mods (IdeMode.DocsFor name w) = case parseConst orig name of Success c -> process "(idemode)" (DocStr (Right c) (howMuch w)) Failure _ -> case splitName name of Left err -> iPrintError err Right n -> process "(idemode)" (DocStr (Left n) (howMuch w)) where howMuch IdeMode.Overview = OverviewDocs howMuch IdeMode.Full = FullDocs runIdeModeCommand h id orig fn mods (IdeMode.CaseSplit line name) = process fn (CaseSplitAt False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.AddClause line name) = process fn (AddClauseFrom False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.AddProofClause line name) = process fn (AddProofClauseFrom False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.AddMissing line name) = process fn (AddMissing False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.MakeWithBlock line name) = process fn (MakeWith False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.MakeCaseBlock line name) = process fn (MakeCase False line (sUN name)) runIdeModeCommand h id orig fn mods (IdeMode.ProofSearch r line name hints depth) = doProofSearch fn False r line (sUN name) (map sUN hints) depth runIdeModeCommand h id orig fn mods (IdeMode.MakeLemma line name) = case splitName name of Left err -> iPrintError err Right n -> process fn (MakeLemma False line n) runIdeModeCommand h id orig fn mods (IdeMode.Apropos a) = process fn (Apropos [] a) runIdeModeCommand h id orig fn mods (IdeMode.GetOpts) = do ist <- getIState let opts = idris_options ist let impshow = opt_showimp opts let errCtxt = opt_errContext opts let options = (IdeMode.SymbolAtom "ok", [(IdeMode.SymbolAtom "show-implicits", impshow), (IdeMode.SymbolAtom "error-context", errCtxt)]) runIO . hPutStrLn h $ IdeMode.convSExp "return" options id runIdeModeCommand h id orig fn mods (IdeMode.SetOpt IdeMode.ShowImpl b) = do setImpShow b let msg = (IdeMode.SymbolAtom "ok", b) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn mods (IdeMode.SetOpt IdeMode.ErrContext b) = do setErrContext b let msg = (IdeMode.SymbolAtom "ok", b) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn mods (IdeMode.Metavariables cols) = do ist <- getIState let mvs = reverse $ map fst (idris_metavars ist) \\ primDefs let ppo = ppOptionIst ist -- splitMvs is a list of pairs of names and their split types let splitMvs = mapSnd (splitPi ist) (mvTys ist mvs) -- mvOutput is the pretty-printed version ready for conversion to SExpr let mvOutput = map (\(n, (hs, c)) -> (n, hs, c)) $ mapPair show (\(hs, c, pc) -> let bnd = [ n | (n,_,_) <- hs ] in let bnds = inits bnd in (map (\(bnd, h) -> processPremise ist bnd h) (zip bnds hs), render ist bnd c pc)) splitMvs runIO . hPutStrLn h $ IdeMode.convSExp "return" (IdeMode.SymbolAtom "ok", mvOutput) id where mapPair f g xs = zip (map (f . fst) xs) (map (g . snd) xs) mapSnd f xs = zip (map fst xs) (map (f . snd) xs) -- | Split a function type into a pair of premises, conclusion. -- Each maintains both the original and delaborated versions. splitPi :: IState -> Type -> ([(Name, Type, PTerm)], Type, PTerm) splitPi ist (Bind n (Pi _ t _) rest) = let (hs, c, pc) = splitPi ist rest in ((n, t, delabTy' ist [] t False False True):hs, c, delabTy' ist [] c False False True) splitPi ist tm = ([], tm, delabTy' ist [] tm False False True) -- | Get the types of a list of metavariable names mvTys :: IState -> [Name] -> [(Name, Type)] mvTys ist = mapSnd vToP . mapMaybe (flip lookupTyNameExact (tt_ctxt ist)) -- | Show a type and its corresponding PTerm in a format suitable -- for the IDE - that is, pretty-printed and annotated. render :: IState -> [Name] -> Type -> PTerm -> (String, SpanList OutputAnnotation) render ist bnd t pt = let prettyT = pprintPTerm (ppOptionIst ist) (zip bnd (repeat False)) [] (idris_infixes ist) pt in displaySpans . renderPretty 0.9 cols . fmap (fancifyAnnots ist True) . annotate (AnnTerm (zip bnd (take (length bnd) (repeat False))) t) $ prettyT -- | Juggle the bits of a premise to prepare for output. processPremise :: IState -> [Name] -- ^ the names to highlight as bound -> (Name, Type, PTerm) -> (String, String, SpanList OutputAnnotation) processPremise ist bnd (n, t, pt) = let (out, spans) = render ist bnd t pt in (show n , out, spans) runIdeModeCommand h id orig fn mods (IdeMode.WhoCalls n) = case splitName n of Left err -> iPrintError err Right n -> do calls <- whoCalls n ist <- getIState let msg = (IdeMode.SymbolAtom "ok", map (\ (n,ns) -> (pn ist n, map (pn ist) ns)) calls) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id where pn ist = displaySpans . renderPretty 0.9 1000 . fmap (fancifyAnnots ist True) . prettyName True True [] runIdeModeCommand h id orig fn mods (IdeMode.CallsWho n) = case splitName n of Left err -> iPrintError err Right n -> do calls <- callsWho n ist <- getIState let msg = (IdeMode.SymbolAtom "ok", map (\ (n,ns) -> (pn ist n, map (pn ist) ns)) calls) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id where pn ist = displaySpans . renderPretty 0.9 1000 . fmap (fancifyAnnots ist True) . prettyName True True [] runIdeModeCommand h id orig fn modes (IdeMode.BrowseNS ns) = case splitOn "." ns of [] -> iPrintError "No namespace provided" ns -> do underNSs <- fmap (map $ concat . intersperse ".") $ namespacesInNS ns names <- namesInNS ns if null underNSs && null names then iPrintError "Invalid or empty namespace" else do ist <- getIState underNs <- mapM pn names let msg = (IdeMode.SymbolAtom "ok", (underNSs, underNs)) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id where pn n = do ctxt <- getContext ist <- getIState return $ displaySpans . renderPretty 0.9 1000 . fmap (fancifyAnnots ist True) $ prettyName True False [] n <> case lookupTyExact n ctxt of Just t -> space <> colon <> space <> align (group (pprintDelab ist t)) Nothing -> empty runIdeModeCommand h id orig fn modes (IdeMode.TermNormalise bnd tm) = do ctxt <- getContext ist <- getIState let tm' = normaliseAll ctxt [] tm ptm = annotate (AnnTerm bnd tm') (pprintPTerm (ppOptionIst ist) bnd [] (idris_infixes ist) (delab ist tm')) msg = (IdeMode.SymbolAtom "ok", displaySpans . renderPretty 0.9 80 . fmap (fancifyAnnots ist True) $ ptm) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn modes (IdeMode.TermShowImplicits bnd tm) = ideModeForceTermImplicits h id bnd True tm runIdeModeCommand h id orig fn modes (IdeMode.TermNoImplicits bnd tm) = ideModeForceTermImplicits h id bnd False tm runIdeModeCommand h id orig fn modes (IdeMode.TermElab bnd tm) = do ist <- getIState let ptm = annotate (AnnTerm bnd tm) (pprintTT (map fst bnd) tm) msg = (IdeMode.SymbolAtom "ok", displaySpans . renderPretty 0.9 70 . fmap (fancifyAnnots ist True) $ ptm) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn mods (IdeMode.PrintDef name) = case splitName name of Left err -> iPrintError err Right n -> process "(idemode)" (PrintDef n) runIdeModeCommand h id orig fn modes (IdeMode.ErrString e) = do ist <- getIState let out = displayS . renderPretty 1.0 60 $ pprintErr ist e msg = (IdeMode.SymbolAtom "ok", IdeMode.StringAtom $ out "") runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn modes (IdeMode.ErrPPrint e) = do ist <- getIState let (out, spans) = displaySpans . renderPretty 0.9 80 . fmap (fancifyAnnots ist True) $ pprintErr ist e msg = (IdeMode.SymbolAtom "ok", out, spans) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id runIdeModeCommand h id orig fn modes IdeMode.GetIdrisVersion = let idrisVersion = (versionBranch getIdrisVersionNoGit, if not (null gitHash) then [gitHash] else []) msg = (IdeMode.SymbolAtom "ok", idrisVersion) in runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id -- | Show a term for IDEMode with the specified implicitness ideModeForceTermImplicits :: Handle -> Integer -> [(Name, Bool)] -> Bool -> Term -> Idris () ideModeForceTermImplicits h id bnd impl tm = do ist <- getIState let expl = annotate (AnnTerm bnd tm) (pprintPTerm ((ppOptionIst ist) { ppopt_impl = impl }) bnd [] (idris_infixes ist) (delab ist tm)) msg = (IdeMode.SymbolAtom "ok", displaySpans . renderPretty 0.9 80 . fmap (fancifyAnnots ist True) $ expl) runIO . hPutStrLn h $ IdeMode.convSExp "return" msg id splitName :: String -> Either String Name splitName s = case reverse $ splitOn "." s of [] -> Left ("Didn't understand name '" ++ s ++ "'") [n] -> Right . sUN $ unparen n (n:ns) -> Right $ sNS (sUN (unparen n)) ns where unparen "" = "" unparen ('(':x:xs) | last xs == ')' = init (x:xs) unparen str = str idemodeProcess :: FilePath -> Command -> Idris () idemodeProcess fn Warranty = process fn Warranty idemodeProcess fn Help = process fn Help idemodeProcess fn (ChangeDirectory f) = do process fn (ChangeDirectory f) dir <- runIO $ getCurrentDirectory iPrintResult $ "changed directory to " ++ dir idemodeProcess fn (ModImport f) = process fn (ModImport f) idemodeProcess fn (Eval t) = process fn (Eval t) idemodeProcess fn (NewDefn decls) = do process fn (NewDefn decls) iPrintResult "defined" idemodeProcess fn (Undefine n) = process fn (Undefine n) idemodeProcess fn (ExecVal t) = process fn (ExecVal t) idemodeProcess fn (Check (PRef x hls n)) = process fn (Check (PRef x hls n)) idemodeProcess fn (Check t) = process fn (Check t) idemodeProcess fn (Core t) = process fn (Core t) idemodeProcess fn (DocStr n w) = process fn (DocStr n w) idemodeProcess fn Universes = process fn Universes idemodeProcess fn (Defn n) = do process fn (Defn n) iPrintResult "" idemodeProcess fn (TotCheck n) = process fn (TotCheck n) idemodeProcess fn (DebugInfo n) = do process fn (DebugInfo n) iPrintResult "" idemodeProcess fn (Search ps t) = process fn (Search ps t) idemodeProcess fn (Spec t) = process fn (Spec t) -- RmProof and AddProof not supported! idemodeProcess fn (ShowProof n') = process fn (ShowProof n') idemodeProcess fn (WHNF t) = process fn (WHNF t) --idemodeProcess fn TTShell = process fn TTShell -- need some prove mode! idemodeProcess fn (TestInline t) = process fn (TestInline t) idemodeProcess fn (Execute t) = do process fn (Execute t) iPrintResult "" idemodeProcess fn (Compile codegen f) = do process fn (Compile codegen f) iPrintResult "" idemodeProcess fn (LogLvl i) = do process fn (LogLvl i) iPrintResult "" idemodeProcess fn (Pattelab t) = process fn (Pattelab t) idemodeProcess fn (Missing n) = process fn (Missing n) idemodeProcess fn (DynamicLink l) = do process fn (DynamicLink l) iPrintResult "" idemodeProcess fn ListDynamic = do process fn ListDynamic iPrintResult "" idemodeProcess fn Metavars = process fn Metavars idemodeProcess fn (SetOpt ErrContext) = do process fn (SetOpt ErrContext) iPrintResult "" idemodeProcess fn (UnsetOpt ErrContext) = do process fn (UnsetOpt ErrContext) iPrintResult "" idemodeProcess fn (SetOpt ShowImpl) = do process fn (SetOpt ShowImpl) iPrintResult "" idemodeProcess fn (UnsetOpt ShowImpl) = do process fn (UnsetOpt ShowImpl) iPrintResult "" idemodeProcess fn (SetOpt ShowOrigErr) = do process fn (SetOpt ShowOrigErr) iPrintResult "" idemodeProcess fn (UnsetOpt ShowOrigErr) = do process fn (UnsetOpt ShowOrigErr) iPrintResult "" idemodeProcess fn (SetOpt x) = process fn (SetOpt x) idemodeProcess fn (UnsetOpt x) = process fn (UnsetOpt x) idemodeProcess fn (CaseSplitAt False pos str) = process fn (CaseSplitAt False pos str) idemodeProcess fn (AddProofClauseFrom False pos str) = process fn (AddProofClauseFrom False pos str) idemodeProcess fn (AddClauseFrom False pos str) = process fn (AddClauseFrom False pos str) idemodeProcess fn (AddMissing False pos str) = process fn (AddMissing False pos str) idemodeProcess fn (MakeWith False pos str) = process fn (MakeWith False pos str) idemodeProcess fn (MakeCase False pos str) = process fn (MakeCase False pos str) idemodeProcess fn (DoProofSearch False r pos str xs) = process fn (DoProofSearch False r pos str xs) idemodeProcess fn (SetConsoleWidth w) = do process fn (SetConsoleWidth w) iPrintResult "" idemodeProcess fn (SetPrinterDepth d) = do process fn (SetPrinterDepth d) iPrintResult "" idemodeProcess fn (Apropos pkg a) = do process fn (Apropos pkg a) iPrintResult "" idemodeProcess fn (WhoCalls n) = process fn (WhoCalls n) idemodeProcess fn (CallsWho n) = process fn (CallsWho n) idemodeProcess fn (PrintDef n) = process fn (PrintDef n) idemodeProcess fn (PPrint fmt n tm) = process fn (PPrint fmt n tm) idemodeProcess fn _ = iPrintError "command not recognized or not supported" -- | The prompt consists of the currently loaded modules, or "Idris" if there are none mkPrompt [] = "Idris" mkPrompt [x] = "*" ++ dropExtension x mkPrompt (x:xs) = "*" ++ dropExtension x ++ " " ++ mkPrompt xs -- | Determine whether a file uses literate syntax lit f = case splitExtension f of (_, ".lidr") -> True _ -> False reload :: IState -> [FilePath] -> Idris (Maybe [FilePath]) reload orig inputs = do i <- getIState -- The $!! here prevents a space leak on reloading. -- This isn't a solution - but it's a temporary stopgap. -- See issue #2386 putIState $!! orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i , imported = imported i } clearErr fmap Just $ loadInputs inputs Nothing watch :: IState -> [FilePath] -> Idris (Maybe [FilePath]) watch orig inputs = do resp <- runIO $ do let dirs = nub $ map takeDirectory inputs inputSet <- fmap S.fromList $ mapM canonicalizePath inputs signal <- newEmptyMVar withManager $ \mgr -> do forM_ dirs $ \dir -> watchDir mgr dir (allEvents $ flip S.member inputSet) (doAllEvents $ putMVar signal) race getLine (takeMVar signal) case resp of Left _ -> return (Just inputs) -- canceled, so nop Right _ -> reload orig inputs >> watch orig inputs processInput :: String -> IState -> [FilePath] -> FilePath -> Idris (Maybe [FilePath]) processInput cmd orig inputs efile = do i <- getIState let opts = idris_options i let quiet = opt_quiet opts let fn = fromMaybe "" (listToMaybe inputs) c <- colourise case parseCmd i "(input)" cmd of Failure (ErrInfo err _) -> do iputStrLn $ show (fixColour c err) return (Just inputs) Success (Right Reload) -> reload orig inputs Success (Right Watch) -> if null inputs then do iputStrLn "No loaded files to watch." return (Just inputs) else do iputStrLn efile iputStrLn $ "Watching for .idr changes in " ++ show inputs ++ ", press enter to cancel." watch orig inputs Success (Right (Load f toline)) -> -- The $!! here prevents a space leak on reloading. -- This isn't a solution - but it's a temporary stopgap. -- See issue #2386 do putIState $!! orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i } clearErr mod <- loadInputs [f] toline return (Just mod) Success (Right (ModImport f)) -> do clearErr fmod <- loadModule f (IBC_REPL True) return (Just (inputs ++ maybe [] (:[]) fmod)) Success (Right Edit) -> do -- takeMVar stvar edit efile orig return (Just inputs) Success (Right Proofs) -> do proofs orig return (Just inputs) Success (Right Quit) -> do when (not quiet) (iputStrLn "Bye bye") return Nothing Success (Right cmd ) -> do idrisCatch (process fn cmd) (\e -> do msg <- showErr e ; iputStrLn msg) return (Just inputs) Success (Left err) -> do runIO $ putStrLn err return (Just inputs) resolveProof :: Name -> Idris Name resolveProof n' = do i <- getIState ctxt <- getContext n <- case lookupNames n' ctxt of [x] -> return x [] -> return n' ns -> ierror (CantResolveAlts ns) return n removeProof :: Name -> Idris () removeProof n = do i <- getIState let proofs = proof_list i let ps = filter ((/= n) . fst) proofs putIState $ i { proof_list = ps } edit :: FilePath -> IState -> Idris () edit "" orig = iputStrLn "Nothing to edit" edit f orig = do i <- getIState env <- runIO getEnvironment let editor = getEditor env let line = case errSpan i of Just l -> '+' : show (fst (fc_start l)) Nothing -> "" let cmdLine = intercalate " " [editor, line, fixName f] runIO $ system cmdLine clearErr -- The $!! here prevents a space leak on reloading. -- This isn't a solution - but it's a temporary stopgap. -- See issue #2386 putIState $!! orig { idris_options = idris_options i , idris_colourTheme = idris_colourTheme i } loadInputs [f] Nothing -- clearOrigPats iucheck return () where getEditor env | Just ed <- lookup "EDITOR" env = ed | Just ed <- lookup "VISUAL" env = ed | otherwise = "vi" fixName file | map toLower (takeExtension file) `elem` [".lidr", ".idr"] = quote file | otherwise = quote $ addExtension file "idr" where quoteChar = if isWindows then '"' else '\'' quote s = [quoteChar] ++ s ++ [quoteChar] proofs :: IState -> Idris () proofs orig = do i <- getIState let ps = proof_list i case ps of [] -> iputStrLn "No proofs available" _ -> iputStrLn $ "Proofs:\n\t" ++ (show $ map fst ps) insertScript :: String -> [String] -> [String] insertScript prf [] = "\n---------- Proofs ----------" : "" : [prf] insertScript prf (p@"---------- Proofs ----------" : "" : xs) = p : "" : prf : xs insertScript prf (x : xs) = x : insertScript prf xs process :: FilePath -> Command -> Idris () process fn Help = iPrintResult displayHelp process fn Warranty = iPrintResult warranty process fn (ChangeDirectory f) = do runIO $ setCurrentDirectory f return () process fn (ModImport f) = do fmod <- loadModule f (IBC_REPL True) case fmod of Just pr -> isetPrompt pr Nothing -> iPrintError $ "Can't find import " ++ f process fn (Eval t) = withErrorReflection $ do logParser 5 $ show t getIState >>= flip warnDisamb t (tm, ty) <- elabREPL (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext let tm' = perhapsForce $ normaliseBlocking ctxt [] [sUN "foreign", sUN "prim_read", sUN "prim_write"] tm let ty' = perhapsForce $ normaliseAll ctxt [] ty -- Add value to context, call it "it" updateContext (addCtxtDef (sUN "it") (Function ty' tm')) ist <- getIState logParser 3 $ "Raw: " ++ show (tm', ty') logParser 10 $ "Debug: " ++ showEnvDbg [] tm' let tmDoc = pprintDelab ist tm' -- errReverse to make type more readable tyDoc = pprintDelab ist (errReverse ist ty') iPrintTermWithType tmDoc tyDoc where perhapsForce tm | termSmallerThan 100 tm = force tm | otherwise = tm process fn (NewDefn decls) = do logParser 3 ("Defining names using these decls: " ++ show (showDecls verbosePPOption decls)) mapM_ defineName namedGroups where namedGroups = groupBy (\d1 d2 -> getName d1 == getName d2) decls getName :: PDecl -> Maybe Name getName (PTy docs argdocs syn fc opts name _ ty) = Just name getName (PClauses fc opts name (clause:clauses)) = Just (getClauseName clause) getName (PData doc argdocs syn fc opts dataDecl) = Just (d_name dataDecl) getName (PInterface doc syn fc constraints name nfc parms parmdocs fds decls _ _) = Just name getName _ = Nothing -- getClauseName is partial and I am not sure it's used safely! -- trillioneyes getClauseName (PClause fc name whole with rhs whereBlock) = name getClauseName (PWith fc name whole with rhs pn whereBlock) = name defineName :: [PDecl] -> Idris () defineName (tyDecl@(PTy docs argdocs syn fc opts name _ ty) : decls) = do elabDecl EAll info tyDecl elabClauses info fc opts name (concatMap getClauses decls) setReplDefined (Just name) defineName [PClauses fc opts _ [clause]] = do let pterm = getRHS clause (tm,ty) <- elabVal info ERHS pterm ctxt <- getContext let tm' = force (normaliseAll ctxt [] tm) let ty' = force (normaliseAll ctxt [] ty) updateContext (addCtxtDef (getClauseName clause) (Function ty' tm')) setReplDefined (Just $ getClauseName clause) defineName (PClauses{} : _) = tclift $ tfail (Msg "Only one function body is allowed without a type declaration.") -- fixity and syntax declarations are ignored by elabDecls, so they'll have to be handled some other way defineName (PFix fc fixity strs : defns) = do fmodifyState idris_fixities (map (Fix fixity) strs ++) unless (null defns) $ defineName defns defineName (PSyntax _ syntax:_) = do i <- get put (addReplSyntax i syntax) defineName decls = do elabDecls (toplevelWith fn) (map fixClauses decls) setReplDefined (getName (head decls)) getClauses (PClauses fc opts name clauses) = clauses getClauses _ = [] getRHS :: PClause -> PTerm getRHS (PClause fc name whole with rhs whereBlock) = rhs getRHS (PWith fc name whole with rhs pn whereBlock) = rhs getRHS (PClauseR fc with rhs whereBlock) = rhs getRHS (PWithR fc with rhs pn whereBlock) = rhs setReplDefined :: Maybe Name -> Idris () setReplDefined Nothing = return () setReplDefined (Just n) = do oldState <- get fmodifyState repl_definitions (n:) -- the "name" field of PClauses seems to always be MN 2 "__", so we need to -- retrieve the actual name from deeper inside. -- This should really be a full recursive walk through the structure of PDecl, but -- I think it should work this way and I want to test sooner. Also lazy. fixClauses :: PDecl' t -> PDecl' t fixClauses (PClauses fc opts _ css@(clause:cs)) = PClauses fc opts (getClauseName clause) css fixClauses (PImplementation doc argDocs syn fc constraints pnames acc opts cls nfc parms pextra ty implName decls) = PImplementation doc argDocs syn fc constraints pnames acc opts cls nfc parms pextra ty implName (map fixClauses decls) fixClauses decl = decl info = recinfo (fileFC "toplevel") process fn (Undefine names) = undefine names where undefine :: [Name] -> Idris () undefine [] = do allDefined <- idris_repl_defs `fmap` get undefine' allDefined [] -- Keep track of which names you've removed so you can -- print them out to the user afterward undefine names = undefine' names [] undefine' [] list = do iRenderResult $ printUndefinedNames list return () undefine' (n:names) already = do allDefined <- idris_repl_defs `fmap` get if n `elem` allDefined then do undefinedJustNow <- undefClosure n undefine' names (undefinedJustNow ++ already) else do tclift $ tfail $ Msg ("Can't undefine " ++ show n ++ " because it wasn't defined at the repl") undefine' names already undefOne n = do fputState (ctxt_lookup n . known_terms) Nothing -- for now just assume it's an interface. Eventually we'll want some kind of -- smart detection of exactly what kind of name we're undefining. fputState (ctxt_lookup n . known_interfaces) Nothing fmodifyState repl_definitions (delete n) undefClosure n = do replDefs <- idris_repl_defs `fmap` get callGraph <- whoCalls n let users = case lookup n callGraph of Just ns -> nub ns Nothing -> fail ("Tried to undefine nonexistent name" ++ show n) undefinedJustNow <- concat `fmap` mapM undefClosure users undefOne n return (nub (n : undefinedJustNow)) process fn (ExecVal t) = do ctxt <- getContext ist <- getIState (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t -- let tm' = normaliseAll ctxt [] tm let ty' = normaliseAll ctxt [] ty res <- execute tm let (resOut, tyOut) = (prettyIst ist (delab ist res), prettyIst ist (delab ist ty')) iPrintTermWithType resOut tyOut process fn (Check (PRef _ _ n)) = do ctxt <- getContext ist <- getIState let ppo = ppOptionIst ist case lookupNames n ctxt of ts@(t:_) -> case lookup t (idris_metavars ist) of Just (_, i, _, _, _) -> iRenderResult . fmap (fancifyAnnots ist True) $ showMetavarInfo ppo ist n i Nothing -> iPrintFunTypes [] n (map (\n -> (n, pprintDelabTy ist n)) ts) [] -> iPrintError $ "No such variable " ++ show n where showMetavarInfo ppo ist n i = case lookupTy n (tt_ctxt ist) of (ty:_) -> let ty' = normaliseC (tt_ctxt ist) [] ty in putTy ppo ist i [] (delab ist (errReverse ist ty')) putTy :: PPOption -> IState -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation putTy ppo ist 0 bnd sc = putGoal ppo ist bnd sc putTy ppo ist i bnd (PPi _ n _ t sc) = let current = case n of MN _ _ -> text "" UN nm | ('_':'_':_) <- str nm -> text "" _ -> text " " <> bindingOf n False <+> colon <+> align (tPretty bnd ist t) <> line in current <> putTy ppo ist (i-1) ((n,False):bnd) sc putTy ppo ist _ bnd sc = putGoal ppo ist ((n,False):bnd) sc putGoal ppo ist bnd g = text "--------------------------------------" <$> annotate (AnnName n Nothing Nothing Nothing) (text $ show n) <+> colon <+> align (tPretty bnd ist g) tPretty bnd ist t = pprintPTerm (ppOptionIst ist) bnd [] (idris_infixes ist) t process fn (Check t) = do (tm, ty) <- elabREPL (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext ist <- getIState let ppo = ppOptionIst ist ty' = if opt_evaltypes (idris_options ist) then normaliseC ctxt [] ty else ty case tm of TType _ -> iPrintTermWithType (prettyIst ist (PType emptyFC)) type1Doc _ -> iPrintTermWithType (pprintDelab ist tm) (pprintDelab ist ty') process fn (Core t) = case t of PRef _ _ n -> do ist <- getIState case lookupDef n (tt_ctxt ist) of [CaseOp _ _ _ _ _ _] -> pprintDef True n >>= iRenderResult . vsep _ -> coreTerm t t -> coreTerm t where coreTerm t = do (tm, ty) <- elabREPL (recinfo (fileFC "toplevel")) ERHS t iPrintTermWithType (pprintTT [] tm) (pprintTT [] ty) process fn (DocStr (Left n) w) | UN ty <- n, ty == T.pack "Type" = getIState >>= iRenderResult . pprintTypeDoc | otherwise = do ist <- getIState let docs = lookupCtxtName n (idris_docstrings ist) ++ map (\(n,d)-> (n, (d, []))) (lookupCtxtName (modDocN n) (idris_moduledocs ist)) case docs of [] -> iPrintError $ "No documentation for " ++ show n ns -> do toShow <- mapM (showDoc ist) ns iRenderResult (vsep toShow) where showDoc ist (n, d) = do doc <- getDocs n w return $ pprintDocs ist doc modDocN (NS (UN n) ns) = NS modDocName (n:ns) modDocN (UN n) = NS modDocName [n] modDocN _ = sMN 1 "NotFoundForSure" process fn (DocStr (Right c) _) -- constants only have overviews = do ist <- getIState iRenderResult $ pprintConstDocs ist c (constDocs c) process fn Universes = do i <- getIState let cs = idris_constraints i let cslist = S.toAscList cs -- iputStrLn $ showSep "\n" (map show cs) iputStrLn $ showSep "\n" (map show cslist) let n = length cslist iputStrLn $ "(" ++ show n ++ " constraints)" case ucheck cs of Error e -> iPrintError $ pshow i e OK _ -> iPrintResult "Universes OK" process fn (Defn n) = do i <- getIState let head = text "Compiled patterns:" <$> text (show (lookupDef n (tt_ctxt i))) let defs = case lookupCtxt n (idris_patdefs i) of [] -> empty [(d, _)] -> text "Original definiton:" <$> vsep (map (printCase i) d) let tot = case lookupTotal n (tt_ctxt i) of [t] -> showTotal t i _ -> empty iRenderResult $ vsep [head, defs, tot] where printCase i (_, lhs, rhs) = let i' = i { idris_options = (idris_options i) { opt_showimp = True } } in text (showTm i' (delab i lhs)) <+> text "=" <+> text (showTm i' (delab i rhs)) process fn (TotCheck n) = do i <- getIState case lookupNameTotal n (tt_ctxt i) of [] -> iPrintError $ "Unknown operator " ++ show n ts -> do ist <- getIState c <- colourise let ppo = ppOptionIst ist let showN n = annotate (AnnName n Nothing Nothing Nothing) . text $ showName (Just ist) [] ppo False n iRenderResult . vsep . map (\(n, t) -> hang 4 $ showN n <+> text "is" <+> showTotal t i) $ ts process fn (DebugUnify l r) = do (ltm, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS l (rtm, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS r ctxt <- getContext case unify ctxt [] (ltm, Nothing) (rtm, Nothing) [] [] [] [] of OK ans -> iputStrLn (show ans) Error e -> iputStrLn (show e) process fn (DebugInfo n) = do i <- getIState let oi = lookupCtxtName n (idris_optimisation i) when (not (null oi)) $ iputStrLn (show oi) let si = lookupCtxt n (idris_statics i) when (not (null si)) $ iputStrLn (show si) let di = lookupCtxt n (idris_datatypes i) when (not (null di)) $ iputStrLn (show di) let imps = lookupCtxt n (idris_implicits i) when (not (null imps)) $ iputStrLn (show imps) let d = lookupDefAcc n False (tt_ctxt i) when (not (null d)) $ iputStrLn $ "Definition: " ++ (show (head d)) let cg = lookupCtxtName n (idris_callgraph i) i <- getIState let cg' = lookupCtxtName n (idris_callgraph i) sc <- checkSizeChange n iputStrLn $ "Size change: " ++ show sc let fn = lookupCtxtName n (idris_fninfo i) when (not (null cg')) $ do iputStrLn "Call graph:\n" iputStrLn (show cg') when (not (null fn)) $ iputStrLn (show fn) process fn (Search pkgs t) = searchByType pkgs t process fn (CaseSplitAt updatefile l n) = caseSplitAt fn updatefile l n process fn (AddClauseFrom updatefile l n) = addClauseFrom fn updatefile l n process fn (AddProofClauseFrom updatefile l n) = addProofClauseFrom fn updatefile l n process fn (AddMissing updatefile l n) = addMissing fn updatefile l n process fn (MakeWith updatefile l n) = makeWith fn updatefile l n process fn (MakeCase updatefile l n) = makeCase fn updatefile l n process fn (MakeLemma updatefile l n) = makeLemma fn updatefile l n process fn (DoProofSearch updatefile rec l n hints) = doProofSearch fn updatefile rec l n hints Nothing process fn (Spec t) = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext ist <- getIState let tm' = simplify ctxt [] {- (idris_statics ist) -} tm iPrintResult (show (delab ist tm')) process fn (RmProof n') = do i <- getIState n <- resolveProof n' let proofs = proof_list i case lookup n proofs of Nothing -> iputStrLn "No proof to remove" Just _ -> do removeProof n insertMetavar n iputStrLn $ "Removed proof " ++ show n where insertMetavar :: Name -> Idris () insertMetavar n = do i <- getIState let ms = idris_metavars i putIState $ i { idris_metavars = (n, (Nothing, 0, [], False, False)) : ms } process fn' (AddProof prf) = do fn <- do let fn'' = takeWhile (/= ' ') fn' ex <- runIO $ doesFileExist fn'' let fnExt = fn'' <.> "idr" exExt <- runIO $ doesFileExist fnExt if ex then return fn'' else if exExt then return fnExt else ifail $ "Neither \""++fn''++"\" nor \""++fnExt++"\" exist" let fb = fn ++ "~" runIO $ copyFile fn fb -- make a backup in case something goes wrong! prog <- runIO $ readSource fb i <- getIState let proofs = proof_list i n' <- case prf of Nothing -> case proofs of [] -> ifail "No proof to add" ((x, _) : _) -> return x Just nm -> return nm n <- resolveProof n' case lookup n proofs of Nothing -> iputStrLn "No proof to add" Just (mode, prf) -> do let script = if mode then showRunElab (lit fn) n prf else showProof (lit fn) n prf let prog' = insertScript script ls runIO $ writeSource fn (unlines prog') removeProof n iputStrLn $ "Added proof " ++ show n where ls = (lines prog) process fn (ShowProof n') = do i <- getIState n <- resolveProof n' let proofs = proof_list i case lookup n proofs of Nothing -> iPrintError "No proof to show" Just (m, p) -> iPrintResult $ if m then showRunElab False n p else showProof False n p process fn (Prove mode n') = do ctxt <- getContext ist <- getIState let ns = lookupNames n' ctxt let metavars = mapMaybe (\n -> do c <- lookup n (idris_metavars ist); return (n, c)) ns n <- case metavars of [] -> ierror (Msg $ "Cannot find metavariable " ++ show n') [(n, (_,_,_,False,_))] -> return n [(_, (_,_,_,_,False))] -> ierror (Msg "Can't prove this hole as it depends on other holes") [(_, (_,_,_,True,_))] -> ierror (Msg "Declarations not solvable using prover") ns -> ierror (CantResolveAlts (map fst ns)) prover (toplevelWith fn) mode (lit fn) n -- recheck totality i <- getIState totcheck (fileFC "(input)", n) mapM_ (\ (f,n) -> setTotality n Unchecked) (idris_totcheck i) mapM_ checkDeclTotality (idris_totcheck i) warnTotality process fn (WHNF t) = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext ist <- getIState let tm' = whnf ctxt tm iPrintResult (show (delab ist tm')) process fn (TestInline t) = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext ist <- getIState let tm' = inlineTerm ist tm c <- colourise iPrintResult (showTm ist (delab ist tm')) process fn (Execute tm) = idrisCatch (do ist <- getIState (m, _) <- elabVal (recinfo (fileFC "toplevel")) ERHS (elabExec fc tm) (tmpn, tmph) <- runIO $ tempfile "" runIO $ hClose tmph t <- codegen -- gcc adds .exe when it builds windows programs progName <- return $ if isWindows then tmpn ++ ".exe" else tmpn ir <- compile t tmpn (Just m) runIO $ generate t (fst (head (idris_imported ist))) ir case idris_outputmode ist of RawOutput h -> do runIO $ rawSystem progName [] return () IdeMode n h -> runIO . hPutStrLn h $ IdeMode.convSExp "run-program" tmpn n) (\e -> getIState >>= iRenderError . flip pprintErr e) where fc = fileFC "main" process fn (Compile codegen f) | map toLower (takeExtension f) `elem` [".idr", ".lidr", ".idc"] = iPrintError $ "Invalid filename for compiler output \"" ++ f ++"\"" | otherwise = do opts <- getCmdLine let iface = Interface `elem` opts let mainname = sNS (sUN "main") ["Main"] m <- if iface then return Nothing else do (m', _) <- elabVal (recinfo (fileFC "compiler")) ERHS (PApp fc (PRef fc [] (sUN "run__IO")) [pexp $ PRef fc [] mainname]) return (Just m') ir <- compile codegen f m i <- getIState runIO $ generate codegen (fst (head (idris_imported i))) ir where fc = fileFC "main" process fn (LogLvl i) = setLogLevel i process fn (LogCategory cs) = setLogCats cs -- Elaborate as if LHS of a pattern (debug command) process fn (Pattelab t) = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ELHS t iPrintResult $ show tm ++ "\n\n : " ++ show ty process fn (Missing n) = do i <- getIState ppOpts <- fmap ppOptionIst getIState case lookupCtxt n (idris_patdefs i) of [] -> iPrintError $ "Unknown name " ++ show n [(_, tms)] -> iRenderResult (vsep (map (pprintPTerm ppOpts {ppopt_impl = True} [] [] (idris_infixes i)) tms)) _ -> iPrintError "Ambiguous name" process fn (DynamicLink l) = do i <- getIState let importdirs = opt_importdirs (idris_options i) lib = trim l handle <- lift . lift $ tryLoadLib importdirs lib case handle of Nothing -> iPrintError $ "Could not load dynamic lib \"" ++ l ++ "\"" Just x -> do let libs = idris_dynamic_libs i if x `elem` libs then do logParser 1 ("Tried to load duplicate library " ++ lib_name x) return () else putIState $ i { idris_dynamic_libs = x:libs } where trim = reverse . dropWhile isSpace . reverse . dropWhile isSpace process fn ListDynamic = do i <- getIState iputStrLn "Dynamic libraries:" showLibs $ idris_dynamic_libs i where showLibs [] = return () showLibs ((Lib name _):ls) = do iputStrLn $ "\t" ++ name; showLibs ls process fn Metavars = do ist <- getIState let mvs = map fst (idris_metavars ist) \\ primDefs case mvs of [] -> iPrintError "No global holes to solve" _ -> iPrintResult $ "Global holes:\n\t" ++ show mvs process fn NOP = return () process fn (SetOpt ErrContext) = setErrContext True process fn (UnsetOpt ErrContext) = setErrContext False process fn (SetOpt ShowImpl) = setImpShow True process fn (UnsetOpt ShowImpl) = setImpShow False process fn (SetOpt ShowOrigErr) = setShowOrigErr True process fn (UnsetOpt ShowOrigErr) = setShowOrigErr False process fn (SetOpt AutoSolve) = setAutoSolve True process fn (UnsetOpt AutoSolve) = setAutoSolve False process fn (SetOpt NoBanner) = setNoBanner True process fn (UnsetOpt NoBanner) = setNoBanner False process fn (SetOpt WarnReach) = fmodifyState opts_idrisCmdline $ nub . (WarnReach:) process fn (UnsetOpt WarnReach) = fmodifyState opts_idrisCmdline $ delete WarnReach process fn (SetOpt EvalTypes) = setEvalTypes True process fn (UnsetOpt EvalTypes) = setEvalTypes False process fn (SetOpt DesugarNats) = setDesugarNats True process fn (UnsetOpt DesugarNats) = setDesugarNats False process fn (SetOpt _) = iPrintError "Not a valid option" process fn (UnsetOpt _) = iPrintError "Not a valid option" process fn (SetColour ty c) = setColour ty c process fn ColourOn = do ist <- getIState putIState $ ist { idris_colourRepl = True } process fn ColourOff = do ist <- getIState putIState $ ist { idris_colourRepl = False } process fn ListErrorHandlers = do ist <- getIState iPrintResult $ case idris_errorhandlers ist of [] -> "No registered error handlers" handlers -> "Registered error handlers: " ++ (concat . intersperse ", " . map show) handlers process fn (SetConsoleWidth w) = setWidth w process fn (SetPrinterDepth d) = setDepth d process fn (Apropos pkgs a) = do orig <- getIState when (not (null pkgs)) $ iputStrLn $ "Searching packages: " ++ showSep ", " pkgs mapM_ loadPkgIndex pkgs ist <- getIState let mods = aproposModules ist (T.pack a) let names = apropos ist (T.pack a) let aproposInfo = [ (n, delabTy ist n, fmap (overview . fst) (lookupCtxtExact n (idris_docstrings ist))) | n <- sort names, isUN n ] if (not (null mods)) || (not (null aproposInfo)) then iRenderResult $ vsep (map (\(m, d) -> text "Module" <+> text m <$> ppD ist d <> line) mods) <$> vsep (map (prettyDocumentedIst ist) aproposInfo) else iRenderError $ text "No results found" where isUN (UN _) = True isUN (NS n _) = isUN n isUN _ = False ppD ist = renderDocstring (renderDocTerm (pprintDelab ist) (normaliseAll (tt_ctxt ist) [])) process fn (WhoCalls n) = do calls <- whoCalls n ist <- getIState iRenderResult . vsep $ map (\(n, ns) -> text "Callers of" <+> prettyName True True [] n <$> indent 1 (vsep (map ((text "*" <+>) . align . prettyName True True []) ns))) calls process fn (CallsWho n) = do calls <- callsWho n ist <- getIState iRenderResult . vsep $ map (\(n, ns) -> prettyName True True [] n <+> text "calls:" <$> indent 1 (vsep (map ((text "*" <+>) . align . prettyName True True []) ns))) calls process fn (Browse ns) = do underNSs <- namespacesInNS ns names <- namesInNS ns if null underNSs && null names then iPrintError "Invalid or empty namespace" else do ist <- getIState iRenderResult $ text "Namespaces:" <$> indent 2 (vsep (map (text . showSep ".") underNSs)) <$> text "Names:" <$> indent 2 (vsep (map (\n -> prettyName True False [] n <+> colon <+> (group . align $ pprintDelabTy ist n)) names)) -- IdrisDoc process fn (MakeDoc s) = do istate <- getIState let names = words s parse n | Success x <- runparser (fmap fst name) istate fn n = Right x parse n = Left n (bad, nss) = partitionEithers $ map parse names cd <- runIO getCurrentDirectory let outputDir = cd </> "doc" result <- if null bad then runIO $ generateDocs istate nss outputDir else return . Left $ "Illegal name: " ++ head bad case result of Right _ -> iputStrLn "IdrisDoc generated" Left err -> iPrintError err process fn (PrintDef n) = do result <- pprintDef False n case result of [] -> iPrintError "Not found" outs -> iRenderResult . vsep $ outs -- Show relevant transformation rules for the name 'n' process fn (TransformInfo n) = do i <- getIState let ts = lookupCtxt n (idris_transforms i) let res = map (showTrans i) ts iRenderResult . vsep $ concat res where showTrans :: IState -> [(Term, Term)] -> [Doc OutputAnnotation] showTrans i [] = [] showTrans i ((lhs, rhs) : ts) = let ppTm tm = annotate (AnnTerm [] tm) . pprintPTerm (ppOptionIst i) [] [] [] . delab i $ tm ts' = showTrans i ts in ppTm lhs <+> text " ==> " <+> ppTm rhs : ts' -- iRenderOutput (pretty lhs) -- iputStrLn " ==> " -- iPrintTermWithType (pprintDelab i rhs) -- iputStrLn "---------------" -- showTrans i ts process fn (PPrint fmt width (PRef _ _ n)) = do outs <- pprintDef False n iPrintResult =<< renderExternal fmt width (vsep outs) process fn (PPrint fmt width t) = do (tm, ty) <- elabVal (recinfo (fileFC "toplevel")) ERHS t ctxt <- getContext ist <- getIState let ppo = ppOptionIst ist ty' = normaliseC ctxt [] ty iPrintResult =<< renderExternal fmt width (pprintDelab ist tm) showTotal :: Totality -> IState -> Doc OutputAnnotation showTotal t@(Partial (Other ns)) i = text "possibly not total due to:" <$> vsep (map (showTotalN i) ns) showTotal t@(Partial (Mutual ns)) i = text "possibly not total due to recursive path:" <$> align (group (vsep (punctuate comma (map (\n -> annotate (AnnName n Nothing Nothing Nothing) $ text (show n)) ns)))) showTotal t i = text (show t) showTotalN :: IState -> Name -> Doc OutputAnnotation showTotalN ist n = case lookupTotal n (tt_ctxt ist) of [t] -> showN n <> text ", which is" <+> showTotal t ist _ -> empty where ppo = ppOptionIst ist showN n = annotate (AnnName n Nothing Nothing Nothing) . text $ showName (Just ist) [] ppo False n displayHelp = let vstr = showVersion getIdrisVersionNoGit in "\nIdris version " ++ vstr ++ "\n" ++ "--------------" ++ map (\x -> '-') vstr ++ "\n\n" ++ concatMap cmdInfo helphead ++ concatMap cmdInfo help where cmdInfo (cmds, args, text) = " " ++ col 16 12 (showSep " " cmds) (show args) text col c1 c2 l m r = l ++ take (c1 - length l) (repeat ' ') ++ m ++ take (c2 - length m) (repeat ' ') ++ r ++ "\n" pprintDef :: Bool -> Name -> Idris [Doc OutputAnnotation] pprintDef asCore n = do ist <- getIState ctxt <- getContext let ambiguous = length (lookupNames n ctxt) > 1 patdefs = idris_patdefs ist tyinfo = idris_datatypes ist if asCore then return $ map (ppCoreDef ist) (lookupCtxtName n patdefs) else return $ map (ppDef ambiguous ist) (lookupCtxtName n patdefs) ++ map (ppTy ambiguous ist) (lookupCtxtName n tyinfo) ++ map (ppCon ambiguous ist) (filter (flip isDConName ctxt) (lookupNames n ctxt)) where ppCoreDef :: IState -> (Name, ([([(Name, Term)], Term, Term)], [PTerm])) -> Doc OutputAnnotation ppCoreDef ist (n, (clauses, missing)) = case lookupTy n (tt_ctxt ist) of [] -> error "Attempted pprintDef of TT of thing that doesn't exist" (ty:_) -> prettyName True True [] n <+> colon <+> align (annotate (AnnTerm [] ty) (pprintTT [] ty)) <$> vsep (map (\(vars, lhs, rhs) -> pprintTTClause vars lhs rhs) clauses) ppDef :: Bool -> IState -> (Name, ([([(Name, Term)], Term, Term)], [PTerm])) -> Doc OutputAnnotation ppDef amb ist (n, (clauses, missing)) = prettyName True amb [] n <+> colon <+> align (pprintDelabTy ist n) <$> ppClauses ist (map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) clauses) <> ppMissing missing ppClauses ist [] = text "No clauses." ppClauses ist cs = vsep (map pp cs) where pp (vars, lhs, rhs) = let ppTm t = annotate (AnnTerm (zip vars (repeat False)) t) . pprintPTerm (ppOptionIst ist) (zip vars (repeat False)) [] (idris_infixes ist) . delab ist $ t in group $ ppTm lhs <+> text "=" <$> (group . align . hang 2 $ ppTm rhs) ppMissing _ = empty ppTy :: Bool -> IState -> (Name, TypeInfo) -> Doc OutputAnnotation ppTy amb ist (n, TI constructors isCodata _ _ _) = kwd key <+> prettyName True amb [] n <+> colon <+> align (pprintDelabTy ist n) <+> kwd "where" <$> indent 2 (vsep (map (ppCon False ist) constructors)) where key | isCodata = "codata" | otherwise = "data" kwd = annotate AnnKeyword . text ppCon amb ist n = prettyName True amb [] n <+> colon <+> align (pprintDelabTy ist n) helphead = [ (["Command"], SpecialHeaderArg, "Purpose"), ([""], NoArg, "") ] replSettings :: Maybe FilePath -> Settings Idris replSettings hFile = setComplete replCompletion $ defaultSettings { historyFile = hFile }
enolan/Idris-dev
src/Idris/REPL.hs
bsd-3-clause
69,507
1
22
25,718
22,139
10,759
11,380
1,363
73
module Gen.Log where import System.Console.ANSI asStep, asSuccess, asInfo, asWarning, asError :: IO a -> IO a asStep = writeIn Blue asSuccess = writeIn Green asInfo = writeIn Cyan asWarning = writeIn Yellow asError = writeIn Red writeIn :: Color -> IO a -> IO a writeIn col x = do setSGR [SetColor Foreground Vivid col] _r <- x setSGR [Reset] return _r
rvion/ride
jetpack-gen/src/Gen/Log.hs
bsd-3-clause
374
0
9
83
142
73
69
14
1
{-# LANGUAGE ConstraintKinds #-} -- | This version explores the simple option of using type-classes to -- overload on the type of the tuning input parameters. This enables -- us to remain polymorphic in how many "dimensions" are being tuned. -- It enables some forms of composability, but requires that the -- dimensionality be known statically at type checking time. module ClassBasedTuning where import Test.QuickCheck -- | The assessment of how good a run is; bigger is better. type Score = Double type Tunable t = Arbitrary t -- Arbitrary is sufficient for tunable, but it could add more control as well... -- -- class Arbitrary t => Tunable t where -- | The tuner takes a tunable and returns the best tuning parameter -- for it after expending a (currently nonconfigurable) amount of -- effort. tune :: Tunable t => (a -> t -> (b,Score)) -> t tune = undefined -- | Online tuning returns a pure function onlineTune :: Tunable t => (a -> t -> (b,Score)) -> (a->b) onlineTune = undefined -------------------------------------------------- -- | Because we're overloaded in the type of the tunable, we can tune -- over arbitrary-dimensional tuning spaces by just example1 :: String -> (Int,Int) -> (String,Score) example1 inp (i,j) = (inp++ " done", fromIntegral (i*j)) -- TODO/TOFIX: Without using a ton of newtypes, this doesn't provide a -- way to bound the range of "Int" tuning parameters! -- The "refined" package on hackage shows one way to do this: -- https://hackage.haskell.org/package/refined test :: (Int, Int) test = tune example1
iu-parfunc/AutoObsidian
interface_brainstorming/03_QuickCheck_style/ClassBasedTuning.hs
bsd-3-clause
1,581
0
10
293
209
129
80
15
1
module Algebra.Enumerable ( Enumerable(..), universeBounded, Enumerated(..) ) where -- | Finitely enumerable things class Enumerable a where universe :: [a] universeBounded :: (Enum a, Bounded a) => [a] universeBounded = enumFromTo minBound maxBound -- | Wrapper used to mark where we expect to use the fact that something is Enumerable newtype Enumerated a = Enumerated { unEnumerated :: a } deriving (Eq, Ord) instance Enumerable a => Enumerable (Enumerated a) where universe = map Enumerated universe -- TODO: add to this rather sorry little set of instances. Can we exploit commonality with lazy-smallcheck? instance Enumerable Bool where universe = universeBounded instance Enumerable Int where universe = universeBounded instance Enumerable a => Enumerable (Maybe a) where universe = Nothing : map Just universe instance (Enumerable a, Enumerable b) => Enumerable (Either a b) where universe = map Left universe ++ map Right universe instance Enumerable () where universe = [()] instance (Enumerable a, Enumerable b) => Enumerable (a, b) where universe = [(a, b) | a <- universe, b <- universe]
batterseapower/lattices
Algebra/Enumerable.hs
bsd-3-clause
1,177
0
8
246
324
178
146
23
1
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses,FunctionalDependencies, TypeSynonymInstances, FlexibleContexts, UndecidableInstances #-} module EFA2.Display.DispVector (module EFA2.Display.DispVector) where import EFA2.Display.DispBase import EFA2.Signal.Base import qualified Data.Vector.Unboxed as UV -- | display a single value dispSingle :: Disp a => a -> String dispSingle x = sdisp x -- | display a single value dispRange :: Disp a => a -> a -> String dispRange x y = sdisp x ++ " - " ++ sdisp y -- | Data Container Display Class with Instances class DataDisplay dim s where ddisp :: DC dim s -> String instance Disp d => DataDisplay D0 (DVal d) where ddisp (DC (DVal x)) = "DVal :" ++ sdisp x instance (DRange D1 UVec d, Disp d,NeutralElement d, UV.Unbox d, Ord d, SFold UVec d (d, d)) => DataDisplay D1 (UVec d) where ddisp x = "UVec: " ++ sdisp min ++ "-" ++ sdisp max where (DC (DVal (min,max))) = getRange x instance (DRange D1 Vec d, Disp d,NeutralElement d, Ord d, SFold Vec d (d, d) ) => DataDisplay D1 (Vec d) where ddisp x = "Vec: " ++ sdisp min ++ "-" ++ sdisp max where (DC (DVal (min,max))) = getRange x instance (DRange D1 List d, Disp d,NeutralElement d, Ord d, SFold List d (d, d)) => DataDisplay D1 (List d) where ddisp x = "List: " ++ sdisp min ++ "-" ++ sdisp max where (DC (DVal (min,max))) = getRange x {- instance (DRange dim UVec Val) => DataDisplay dim (UVec Val) where ddisp x = "UVec: " ++ sdisp min ++ "-" ++ sdisp max where (DC (DVal (min,max))) = getRange x instance (DRange dim Vec Val ) => DataDisplay dim (Vec Val) where ddisp x = "Vec: " ++ sdisp min ++ "-" ++ sdisp max where (DC (DVal (min,max))) = getRange x instance (DRange dim Vec Sign) => DataDisplay dim (Vec Sign) where ddisp x = "Vec: " ++ sdisp min ++ "-" ++ sdisp max where (DC (DVal (min,max))) = getRange x instance (DRange dim List Val) => DataDisplay dim (List Val) where ddisp x = "List: " ++ sdisp min ++ "-" ++ sdisp max where (DC (DVal (min,max))) = getRange x -}
energyflowanalysis/efa-2.1
attic/src/EFA2/Display/DispData.hs
bsd-3-clause
2,070
0
12
453
550
285
265
22
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE ScopedTypeVariables #-} module CO4.Example.WCB_Matrix (result,ex0) where import Prelude hiding (sequence) import Control.Monad (void,forM) import Language.Haskell.TH (runIO) import qualified Data.Map as M import qualified Satchmo.Core.SAT.Minisat import qualified Satchmo.Core.Decode import CO4 import CO4.Prelude import CO4.Util (toBinary,fromBinary) import System.Environment (getArgs) import System.IO import CO4.Example.WCB_MatrixStandalone $( compileFile [ ImportPrelude -- , DumpAll "/tmp/WCB_Matrix" , InstantiationDepth 20 ] "test/CO4/Example/WCB_MatrixStandalone.hs" ) uBase = unions [knownA, knownC, knownG, knownU] uEnergy = unions [knownMinusInfinity, knownFinite $ uNat 8] uMatrix xs ys f = let row xs g = case xs of [] -> knownNil x:xs' -> knownCons (g x) (row xs' g) in row xs $ \ x -> row ys $ \ y -> f x y -- upper triag finite energy uTriagGap delta n = uMatrix [1 .. n] [1 .. n] $ \ i j -> if i + delta <= j then knownFinite (uNat 8) else knownMinusInfinity uTriag2Gap delta n = uMatrix [1 .. n] [1 .. n] $ \ i j -> if i + delta <= j then knownTuple2 (knownFinite $ uNat 8) uEnergy else knownTuple2 knownMinusInfinity knownMinusInfinity inforna cs = map ( \ c -> case c of '(' -> Open ; '.' -> Blank ; ')' -> Close ) cs ex1 = inforna "(((((...(((((......))))).)))))" ex0 = [ Open, Open , Blank, Close, Open , Close , Close, Blank ] result :: [Paren] -> IO (Maybe ([Base],Energy)) result sec = do let n = length sec out <- solveAndTestP sec ( knownTuple2 (kList n uBase) ( -- uTriag2Gap 1 (n+1) uTriagGap 1 (n+1) )) encConstraint constraint return $ case out of Nothing -> Nothing Just (p,m) -> Just (p, upright m)
apunktbau/co4
test/CO4/Example/WCB_Matrix.hs
gpl-3.0
2,198
0
14
660
642
354
288
56
3
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeApplications #-} module GrLang (initialize) where import Control.Arrow ((***)) import Control.Monad import Control.Monad.Except (ExceptT (..), runExceptT) import qualified Control.Monad.Except as ExceptT import Control.Monad.Reader import Control.Monad.Trans (lift) import Data.Array.IO import qualified Data.ByteString as BS import Data.IORef import Data.Map (Map) import qualified Data.Map as Map import Data.Monoid import Data.Proxy 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.Text.Prettyprint.Doc (Pretty (..)) import Foreign.Lua (FromLuaStack, Lua, ToHaskellFunction) import qualified Foreign.Lua as Lua import qualified Foreign.Lua.Util as Lua import Abstract.Category import Abstract.Category.Adhesive import Abstract.Category.FindMorphism import Abstract.Category.Finitary import Abstract.Category.Limit import Abstract.Rewriting.DPO import Base.Annotation (Annotated (..)) import qualified Data.Graphs as TypeGraph import Data.TypedGraph (Edge (..), EdgeId, Node (..), NodeId) import qualified Data.TypedGraph as TGraph import qualified Data.TypedGraph.Morphism as TGraph import qualified GrLang.Compiler as GrLang import GrLang.Monad (MonadGrLang) import qualified GrLang.Monad as GrLang import qualified GrLang.Parser as GrLang import GrLang.Value import qualified Image.Dot.TypedGraph as Dot import Util.Lua import XML.GGXReader as GGX import Paths_verigraph (getDataFileName) data MemSpace a = MemSpace { cells :: IOArray Int (Maybe a) , maxFreeValues :: Int , numFreeValues :: IORef Int , nextFreeIndex :: IORef (Maybe Int) } emptyMemSpace :: Int -> IO (MemSpace a) emptyMemSpace capacity = MemSpace <$> newArray (0, capacity - 1) Nothing <*> pure capacity <*> newIORef capacity <*> newIORef (Just 0) lookupMemSpace :: Lua.LuaInteger -> MemSpace a -> ExceptT GrLang.Error LuaGrLang a lookupMemSpace idx' memSpace = do let idx = fromEnum idx' result <- liftIO $ readArray (cells memSpace) idx case result of Nothing -> GrLang.throwError Nothing "Value has unallocated index" Just val -> return val isEmptyMemSpace :: MemSpace a -> ExceptT GrLang.Error LuaGrLang Bool isEmptyMemSpace memSpace = (maxFreeValues memSpace ==) <$> liftIO (readIORef $ numFreeValues memSpace) putMemSpace :: Lua.LuaInteger -> a -> MemSpace a -> ExceptT GrLang.Error LuaGrLang () putMemSpace idx' val memSpace = do let idx = fromEnum idx' liftIO $ writeArray (cells memSpace) idx (Just val) allocateMemSpace :: a -> MemSpace a -> ExceptT GrLang.Error LuaGrLang Lua.LuaInteger allocateMemSpace value memSpace = do idx <- getFreeIndex memSpace liftIO $ do writeArray (cells memSpace) idx (Just value) freeVals <- readIORef (numFreeValues memSpace) let freeVals' = freeVals - 1 writeIORef (numFreeValues memSpace) freeVals' writeIORef (nextFreeIndex memSpace) =<< if freeVals' < 1 then return Nothing else Just <$> findNextFreeIndex (idx+1) return (fromIntegral idx) where getFreeIndex memSpace = do freeIdx <- liftIO $ readIORef (nextFreeIndex memSpace) case freeIdx of Just idx -> return idx Nothing -> do liftLua $ Lua.gc Lua.GCCOLLECT 0 freeIdx <- liftIO $ readIORef (nextFreeIndex memSpace) case freeIdx of Just idx -> return idx Nothing -> GrLang.throwError Nothing "Out of GrLang memory" findNextFreeIndex idx = do val <- readArray (cells memSpace) idx case val of Nothing -> return idx Just _ -> findNextFreeIndex (idx+1) freeMemSpace :: Lua.LuaInteger -> MemSpace a -> ExceptT GrLang.Error LuaGrLang () freeMemSpace idx' memSpace = liftIO $ do let idx = fromEnum idx' writeArray (cells memSpace) idx Nothing modifyIORef (numFreeValues memSpace) (+1) modifyIORef (nextFreeIndex memSpace) $ Just . maybe idx (min idx) data GrLangState = GrLangState { typeGraph :: IORef TypeGraph , nodeTypes :: IORef (Map Text NodeId) , edgeTypes :: IORef (Map (Text, NodeId, NodeId) EdgeId) , importedModules :: IORef (Set FilePath) , visibleModules :: IORef (Set FilePath) , values :: MemSpace Value , iterLists :: MemSpace [[Value]] } type LuaGrLang = ReaderT GrLangState Lua get :: (MonadIO m, MonadReader GrLangState m) => (GrLangState -> IORef a) -> m a get f = liftIO . readIORef =<< asks f put :: (MonadIO m, MonadReader GrLangState m) => (GrLangState -> IORef a) -> a -> m () put f x = do ref <- asks f liftIO $ writeIORef ref x modify :: (MonadIO m, MonadReader GrLangState m) => (GrLangState -> IORef a) -> (a -> a) -> m () modify f x = do ref <- asks f liftIO $ modifyIORef ref x liftLua :: Lua a -> ExceptT GrLang.Error LuaGrLang a liftLua = lift . lift withMemSpace :: (GrLangState -> MemSpace a) -> (MemSpace a -> ExceptT GrLang.Error LuaGrLang b) -> ExceptT GrLang.Error LuaGrLang b withMemSpace space action = asks space >>= action instance MonadGrLang (ReaderT GrLangState Lua) where importIfNeeded path importAction = do prevImported <- get importedModules if Set.member path prevImported then do modify visibleModules (Set.insert path) return Nothing else do outerVisible <- get visibleModules put visibleModules (Set.singleton path) modify importedModules (Set.insert path) result <- importAction `ExceptT.catchError` \err -> do modify importedModules (Set.delete path) put visibleModules (Set.insert path outerVisible) ExceptT.throwError err put visibleModules (Set.insert path outerVisible) return (Just result) checkIfImported srcPath = Set.member srcPath <$> get importedModules checkIfVisible srcPath = Set.member srcPath <$> get visibleModules unsafeMakeVisible srcPath = modify visibleModules (Set.insert srcPath) getTypeGraph = get typeGraph getNodeType (A loc name) = GrLang.getOrError loc "node type" name (lookupNodeType name) nodeLocation getEdgeType (A loc name) srcType tgtType = GrLang.getOrError loc "edge type" (showEdgeType name srcType tgtType) (lookupEdgeType name srcType tgtType) edgeLocation addNodeType (A loc name) = do existingType <- lift $ lookupNodeType name GrLang.addNew loc "Node type" name (nodeLocation <$> existingType) $ do newId:_ <- TypeGraph.newNodes <$> get typeGraph let metadata = Metadata (Just name) loc modify typeGraph $ TypeGraph.insertNodeWithPayload newId (Just metadata) modify nodeTypes $ Map.insert name newId addEdgeType (A loc name) srcName tgtName = do srcType <- GrLang.getNodeType srcName tgtType <- GrLang.getNodeType tgtName existingType <- lift $ lookupEdgeType name srcType tgtType GrLang.addNew loc "Edge type" (showEdgeType name srcType tgtType) (edgeLocation <$> existingType) $ do newId:_ <- TypeGraph.newEdges <$> get typeGraph let metadata = Metadata (Just name) loc (Node srcId _, Node tgtId _) = (srcType, tgtType) modify typeGraph $ TypeGraph.insertEdgeWithPayload newId srcId tgtId (Just metadata) modify edgeTypes $ Map.insert (name, srcId, tgtId) newId getValue (A _ name) = do liftLua $ Lua.getglobal (Text.unpack name) hasTable <- liftLua $ Lua.istable Lua.stackTop if not hasTable then GrLang.throwError Nothing "Value is not a table" else do liftLua $ Lua.getfield Lua.stackTop indexKey result <- liftLua $ Lua.tointegerx Lua.stackTop liftLua $ Lua.pop 2 case result of Nothing -> GrLang.throwError Nothing "Value has no index" Just memIndex' -> lookupGrLangValue memIndex' putValue (A _ name) val = do memIdx <- allocateGrLang val liftLua $ do createTable [(indexKey, Lua.pushinteger memIdx)] tblIdx <- Lua.gettop Lua.getglobal (metatableFor val) Lua.setmetatable tblIdx Lua.setglobal (Text.unpack name) where metatableFor (VGraph _) = "Graph" metatableFor (VRule _) = "Rule" metatableFor (VMorph _) = "Morphism" indexKey :: String indexKey = "index" :: String showEdgeType :: Text -> GrNode -> GrNode -> Text showEdgeType e src tgt = formatEdgeType e (nodeName src) (nodeName tgt) memSpacesAreEmpty :: ExceptT GrLang.Error LuaGrLang Bool memSpacesAreEmpty = do areEmpty' <- (&&) <$> withMemSpace values isEmptyMemSpace <*> withMemSpace iterLists isEmptyMemSpace if areEmpty' then return True else do liftLua $ Lua.gc Lua.GCCOLLECT 0 (&&) <$> withMemSpace values isEmptyMemSpace <*> withMemSpace iterLists isEmptyMemSpace lookupGrLangValue :: Lua.LuaInteger -> ExceptT GrLang.Error LuaGrLang Value lookupGrLangValue = withMemSpace values . lookupMemSpace lookupNodeType :: Text -> LuaGrLang (Maybe NodeType) lookupNodeType name = do tgraph <- get typeGraph ntypes <- get nodeTypes return $ (`TypeGraph.lookupNode` tgraph) =<< Map.lookup name ntypes lookupEdgeType :: Text -> NodeType -> NodeType -> LuaGrLang (Maybe EdgeType) lookupEdgeType name srcType tgtType = do tgraph <- get typeGraph etypes <- get edgeTypes return $ (`TypeGraph.lookupEdge` tgraph) =<< Map.lookup (name, nodeId srcType, nodeId tgtType) etypes initState :: Int -> Int -> IO GrLangState initState maxValues maxLists = GrLangState <$> newIORef TypeGraph.empty <*> newIORef Map.empty <*> newIORef Map.empty <*> newIORef (Set.singleton "<repl>") <*> newIORef (Set.singleton "<repl>") <*> emptyMemSpace maxValues <*> emptyMemSpace maxLists allocateGrLang :: Value -> ExceptT GrLang.Error LuaGrLang Lua.LuaInteger allocateGrLang = withMemSpace values . allocateMemSpace . normalizeValue freeGrLang :: Lua.LuaInteger -> ExceptT GrLang.Error LuaGrLang () freeGrLang = withMemSpace values . freeMemSpace runGrLang' :: ToHaskellFunction (Lua a) => GrLangState -> ExceptT GrLang.Error LuaGrLang a -> Lua Lua.NumResults runGrLang' globalState action = do result <- runReaderT (runExceptT action) globalState case result of Left errs -> luaError (show $ GrLang.prettyError errs) Right val -> Lua.toHaskellFunction (return @Lua val) morphConf :: MorphismsConfig GrMorphism morphConf = MorphismsConfig monic initialize :: Lua () initialize = do globalState <- liftIO (initState 256 64) execLuaFile =<< liftIO (getDataFileName "src/repl/lua/help.lua") execLuaFile =<< liftIO (getDataFileName "src/repl/lua/grlang.lua") initGrLang globalState return () grLangNamingContext :: Dot.NamingContext Metadata Metadata ann grLangNamingContext = Dot.Ctx { Dot.getNodeTypeName = \(n, _) -> pretty $ nodeTypeName n , Dot.getEdgeTypeName = \((s,_), e, (t,_)) -> pretty $ showEdgeType (edgeName e) s t , Dot.getNodeName = \_ (node, _, _) -> pretty (nodeName node) , Dot.getNodeLabel = \_ (node, ntype, _) -> Just $ pretty (nodeName node) <> ":" <> pretty (nodeTypeName ntype) , Dot.getEdgeLabel = \_ (_, edge, etype, _) -> Just $ case edgeExactName edge of Nothing -> pretty $ edgeName etype Just name -> pretty name <> ":" <> pretty (edgeName etype) } initGrLang :: GrLangState -> Lua () initGrLang globalState = do setNative "GrLang" [ ("getNodeTypes", haskellFn0 globalState $ do types <- get nodeTypes return . map Text.unpack $ Map.keys types ) , ("getEdgeTypes", haskellFn0 globalState $ do types <- Map.keys <$> get edgeTypes forM types $ \(name, srcId, tgtId) -> do tgraph <- get typeGraph let Just srcType = TypeGraph.lookupNode srcId tgraph Just tgtType = TypeGraph.lookupNode tgtId tgraph return . Text.unpack $ formatEdgeType name (nodeName srcType) (nodeName tgtType) ) , ("addNodeType", haskellFn1 globalState $ \name -> GrLang.addNodeType (A Nothing name) ) , ("addEdgeType", haskellFn3 globalState $ \name srcName tgtName -> GrLang.addEdgeType (A Nothing name) (A Nothing srcName) (A Nothing tgtName) ) , ("resetTypes", haskellFn0 globalState $ do areEmpty <- memSpacesAreEmpty unless areEmpty . GrLang.throwError Nothing $ "Cannot reset types, some GrLang values still refer to the type graph." put typeGraph TypeGraph.empty put nodeTypes Map.empty put edgeTypes Map.empty ) , ("toString", haskellFn1 globalState $ \idx -> show . pretty <$> lookupGrLangValue idx ) , ("equals", haskellFn2 globalState $ \idxA idxB -> do valA <- lookupGrLangValue idxA valB <- lookupGrLangValue idxB return (valA == valB) ) , ("deallocate", haskellFn1 globalState $ \idx -> freeGrLang idx ) , ("toDot", haskellFn2 globalState $ \idx name -> do VGraph graph <- lookupGrLangValue idx return . show $ Dot.typedGraph grLangNamingContext (pretty $ Text.decodeUtf8 name) graph ) , ("compileFile", haskellFn1 globalState $ \path -> GrLang.compileFile path ) , ("readGGX", haskellFn1 globalState $ \fileName -> do (grammar, _, _) <- liftIO $ GGX.readGrammar fileName False morphConf let makeValidIdentifier = Text.pack . GrLang.makeIdentifier . takeWhile (/='%') names <- liftIO $ Map.fromList . map (id *** makeValidIdentifier) <$> GGX.readNames fileName -- Construct a type graph with proper names and update the current type graph let tgraph = useGgxNamesOnTypeGraph (fmap correctTypeName names) $ TGraph.typeGraph (start grammar) where correctTypeName = Text.takeWhile (/='%') put typeGraph tgraph put nodeTypes $ Map.fromList [(nodeName n, nodeId n) | n <- TypeGraph.nodes tgraph ] put edgeTypes $ Map.fromList [((edgeName e, sourceId e, targetId e), edgeId e) | e <- TypeGraph.edges tgraph ] -- Return a table of productions indexed by name prods <- forM (productions grammar) $ \(name, prod) -> do idx <- allocateGrLang . addNamesFromTypes . useGgxNames names . updateTypeGraph tgraph $ VRule prod return (name, idx) return (Map.fromList prods) ) ] setNative "HsListIterator" [ ("deallocate", haskellFn1 globalState $ \idx -> withMemSpace iterLists $ freeMemSpace idx ) , ("hasNextItem", haskellFn1 globalState $ \idx -> not . null <$> withMemSpace iterLists (lookupMemSpace idx) ) , ("getNextItem", haskellFn1 globalState $ \listIdx -> do list <- withMemSpace iterLists $ lookupMemSpace listIdx case list of [] -> return (0 :: Lua.NumResults) (vals : rest) -> do withMemSpace iterLists $ putMemSpace listIdx rest returnVals vals ) ] setNative "Graph" [ ("parse", haskellFn1 globalState $ \string -> do graph <- GrLang.compileGraph =<< GrLang.parseGraph "<repl>" (string :: String) allocateGrLang (VGraph graph) ) , ("identity", haskellFn1 globalState $ \idx -> do VGraph graph <- lookupGrLangValue idx allocateGrLang (VMorph $ identity graph) ) , ("isInitial", haskellFn1 globalState $ \idx -> do VGraph graph <- lookupGrLangValue idx return (isInitial (Proxy @GrMorphism) graph) ) , ("calculateCoproduct", haskellFn2 globalState $ \idG idH -> do VGraph g <- lookupGrLangValue idG VGraph h <- lookupGrLangValue idH let (jG, jH) = calculateCoproduct g h returnVals [VGraph (codomain jG), VMorph jG, VMorph jH] ) , ("calculateProduct", haskellFn2 globalState $ \idG idH -> do VGraph g <- lookupGrLangValue idG VGraph h <- lookupGrLangValue idH let (pG, pH) = calculateProduct g h returnVals [VGraph (domain pG), VMorph pG, VMorph pH] ) , ("findMorphisms", haskellFn3 globalState $ \kindStr idG idH -> do VGraph g <- lookupGrLangValue idG VGraph h <- lookupGrLangValue idH cls <- morphClassFromString kindStr withMemSpace iterLists . allocateMemSpace . map (\f -> [VMorph f]) $ findMorphisms cls g h ) , ("findAllSubobjectsOf", haskellFn1 globalState $ \idx -> do VGraph g <- lookupGrLangValue idx withMemSpace iterLists . allocateMemSpace . map (\f -> [VGraph (domain f), VMorph f]) $ findAllSubobjectsOf g ) , ("findAllQuotientsOf", haskellFn1 globalState $ \idx -> do VGraph g <- lookupGrLangValue idx withMemSpace iterLists . allocateMemSpace . map (\f -> [VGraph (codomain f), VMorph f]) $ findAllQuotientsOf g ) , ("findJointSurjections", haskellFn4 globalState $ \idG kindStrG idH kindStrH -> do VGraph g <- lookupGrLangValue idG VGraph h <- lookupGrLangValue idH clsG <- morphClassFromString kindStrG clsH <- morphClassFromString kindStrH withMemSpace iterLists . allocateMemSpace . map (\(jg, jh) -> [VGraph (codomain jg), VMorph jg, VMorph jh]) $ findJointSurjections (clsG, g) (clsH, h) ) ] setNative "Morphism" [ ("parse", haskellFn3 globalState $ \domIdx codIdx string -> do VGraph dom <- lookupGrLangValue domIdx VGraph cod <- lookupGrLangValue codIdx morphism <- GrLang.compileMorphism Nothing dom cod =<< GrLang.parseMorphism "<repl>" (string :: String) allocateGrLang (VMorph morphism) ) , ("compose", haskellFn2 globalState $ \idF idG -> do VMorph f <- lookupGrLangValue idF VMorph g <- lookupGrLangValue idG allocateGrLang (VMorph $ f <&> g) ) , ("isMonic", haskellFn1 globalState $ \idx -> do VMorph f <- lookupGrLangValue idx return (isMonic f) ) , ("isEpic", haskellFn1 globalState $ \idx -> do VMorph f <- lookupGrLangValue idx return (isEpic f) ) , ("isIsomorphism", haskellFn1 globalState $ \idx -> do VMorph f <- lookupGrLangValue idx return (isIsomorphism f) ) , ("calculatePullback", haskellFn2 globalState $ \idF idG -> do VMorph f <- lookupGrLangValue idF VMorph g <- lookupGrLangValue idG let (f', g') = calculatePullback f g returnVals [VGraph (domain f'), VMorph f', VMorph g'] ) , ("calculatePushout", haskellFn2 globalState $ \idF idG -> do VMorph f <- lookupGrLangValue idF VMorph g <- lookupGrLangValue idG let (f', g') = calculatePushout f g returnVals [VGraph (codomain f'), VMorph f', VMorph g'] ) , ("calculateEqualizer", haskellFn2 globalState $ \idF idG -> do VMorph f <- lookupGrLangValue idF VMorph g <- lookupGrLangValue idG let e = calculateEqualizer f g returnVals [VGraph (domain e), VMorph e] ) , ("calculateCoequalizer", haskellFn2 globalState $ \idF idG -> do VMorph f <- lookupGrLangValue idF VMorph g <- lookupGrLangValue idG let e = calculateCoequalizer f g returnVals [VGraph (codomain e), VMorph e] ) , ("hasPushoutComplementAlongM", haskellFn2 globalState $ \idF idG -> do VMorph f <- lookupGrLangValue idF VMorph g <- lookupGrLangValue idG return (hasPushoutComplementAlongM f g) ) , ("calculatePushoutComplementAlongM", haskellFn2 globalState $ \idF idG -> do VMorph f <- lookupGrLangValue idF VMorph g <- lookupGrLangValue idG let (g', f') = calculatePushoutComplementAlongM f g returnVals [VGraph (codomain g'), VMorph g', VMorph f'] ) , ("calculateInitialPushout", haskellFn1 globalState $ \idx -> do VMorph f <- lookupGrLangValue idx let (b, f', c) = calculateMInitialPushout f returnVals [VGraph (domain b), VGraph (domain c), VMorph b, VMorph f', VMorph c] ) , ("subobjectIntersection", haskellFn2 globalState $ \idA idB -> do VMorph a <- lookupGrLangValue idA VMorph b <- lookupGrLangValue idB let c = subobjectIntersection a b returnVals [VGraph (domain c), VMorph c] ) , ("subobjectUnion", haskellFn2 globalState $ \idA idB -> do VMorph a <- lookupGrLangValue idA VMorph b <- lookupGrLangValue idB let c = subobjectUnion a b returnVals [VGraph (domain c), VMorph c] ) , ("findJointSurjectionSquares", haskellFn4 globalState $ \kindStrF idF kindStrG idG -> do VMorph f <- lookupGrLangValue idF VMorph g <- lookupGrLangValue idG clsF <- morphClassFromString kindStrF clsG <- morphClassFromString kindStrG withMemSpace iterLists . allocateMemSpace . map (\(f', g') -> [VGraph (codomain f'), VMorph f', VMorph g']) $ findJointSurjectionSquares (clsF, f) (clsG, g) ) ] setNative "Cospan" [ ("findCospanCommuters", haskellFn3 globalState $ \kindStr idF idG -> do VMorph f <- lookupGrLangValue idF VMorph g <- lookupGrLangValue idG cls <- morphClassFromString kindStr withMemSpace iterLists . allocateMemSpace . map (\h -> [VMorph h]) $ findCospanCommuters cls f g ) ] setNative "Rule" [ ("parse", haskellFn1 globalState $ \string -> do rule <- GrLang.compileRule =<< GrLang.parseRule "<repl>" (string :: String) allocateGrLang (VRule rule) ) , ("getLeftObject", haskellFn1 globalState $ \idRule -> do VRule rule <- lookupGrLangValue idRule allocateGrLang (VGraph $ leftObject rule) ) , ("getRightObject", haskellFn1 globalState $ \idRule -> do VRule rule <- lookupGrLangValue idRule allocateGrLang (VGraph $ rightObject rule) ) , ("getInterface", haskellFn1 globalState $ \idRule -> do VRule rule <- lookupGrLangValue idRule allocateGrLang (VGraph $ interfaceObject rule) ) , ("getLeftMorphism", haskellFn1 globalState $ \idRule -> do VRule rule <- lookupGrLangValue idRule allocateGrLang (VMorph $ leftMorphism rule) ) , ("getRightMorphism", haskellFn1 globalState $ \idRule -> do VRule rule <- lookupGrLangValue idRule allocateGrLang (VMorph $ rightMorphism rule) ) ] where setNative className entries = do Lua.getglobal className tableIdx <- Lua.gettop createTable entries Lua.setfield tableIdx "native" Lua.pop 1 returnVals :: [Value] -> ExceptT GrLang.Error LuaGrLang Lua.NumResults returnVals vals = do mapM_ (liftLua . Lua.push <=< allocateGrLang) vals return . fromIntegral $ length vals morphClassFromString :: Lua.OrNil BS.ByteString -> ExceptT GrLang.Error LuaGrLang (MorphismClass GrMorphism) morphClassFromString strOrNil = case Lua.toMaybe strOrNil of Nothing -> return anyMorphism Just "all" -> return anyMorphism Just "monic" -> return monic Just "epic" -> return epic Just "'iso" -> return iso Just kind -> GrLang.throwError Nothing $ "Invalid kind of morphism '" <> pretty (show kind) <> "'" haskellFn0 :: ToHaskellFunction (Lua a) => GrLangState -> ExceptT GrLang.Error LuaGrLang a -> Lua () haskellFn0 globalState f = pushFunction (runGrLang' globalState f) haskellFn1 :: (FromLuaStack a, ToHaskellFunction (Lua b)) => GrLangState -> (a -> ExceptT GrLang.Error LuaGrLang b) -> Lua () haskellFn1 globalState f = pushFunction (runGrLang' globalState . f) haskellFn2 :: (FromLuaStack a, FromLuaStack b, ToHaskellFunction (Lua c)) => GrLangState -> (a -> b -> ExceptT GrLang.Error LuaGrLang c) -> Lua () haskellFn2 globalState f = pushFunction (\x y -> runGrLang' globalState (f x y)) haskellFn3 :: (FromLuaStack a, FromLuaStack b, FromLuaStack c, ToHaskellFunction (Lua d)) => GrLangState -> (a -> b -> c -> ExceptT GrLang.Error LuaGrLang d) -> Lua () haskellFn3 globalState f = pushFunction (\x y z -> runGrLang' globalState (f x y z)) haskellFn4 :: (FromLuaStack a, FromLuaStack b, FromLuaStack c, FromLuaStack d, ToHaskellFunction (Lua e)) => GrLangState -> (a -> b -> c -> d -> ExceptT GrLang.Error LuaGrLang e) -> Lua () haskellFn4 globalState f = pushFunction (\w x y z -> runGrLang' globalState (f w x y z)) createTable :: Foldable t => t (String, Lua ()) -> Lua () createTable contents = do Lua.createtable 0 (length contents) tableIdx <- Lua.gettop forM_ contents $ \(key, pushVal) -> do pushVal Lua.setfield tableIdx key useGgxNamesOnTypeGraph :: Map String Text -> TypeGraph -> TypeGraph useGgxNamesOnTypeGraph names graph = TypeGraph.fromNodesAndEdges [ Node n (makeInfo n) | Node n _ <- TypeGraph.nodes graph ] [ Edge e s t (makeInfo e) | Edge e s t _ <- TypeGraph.edges graph ] where makeInfo id = Just $ Metadata (Map.lookup ("I" ++ show id) names) Nothing useGgxNames :: Map String Text -> Value -> Value useGgxNames names (VGraph g) = VGraph . useGgxNamesOnGraph names $ g useGgxNames names (VMorph f) = VMorph . useGgxNamesOnMorphism names $ f useGgxNames names (VRule (Production l r ns)) = VRule $ Production (useGgxNamesOnMorphism names l) (useGgxNamesOnMorphism names r) (map (useGgxNamesOnMorphism names) ns) useGgxNamesOnGraph :: Map String Text -> GrGraph -> GrGraph useGgxNamesOnGraph names graph = TGraph.fromNodesAndEdges (TGraph.typeGraph graph) [ (Node n (makeInfo n), nodeId ntype) | (Node n _, ntype, _) <- TGraph.nodesInContext graph ] [ (Edge e s t (makeInfo e), edgeId etype) | (_, Edge e s t _, etype, _) <- TGraph.edgesInContext graph ] where makeInfo elemId = Just $ Metadata (Map.lookup ("I" ++ show elemId) names) Nothing useGgxNamesOnMorphism :: Map String Text -> GrMorphism -> GrMorphism useGgxNamesOnMorphism names (TGraph.TypedGraphMorphism dom cod morph) = TGraph.TypedGraphMorphism (useGgxNamesOnGraph names dom) (useGgxNamesOnGraph names cod) morph
rodrigo-machado/verigraph
src/repl/GrLang.hs
gpl-3.0
26,993
0
23
6,952
8,715
4,272
4,443
-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.OpsWorks.AssociateElasticIp -- 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. -- | Associates one of the stack's registered Elastic IP addresses with a -- specified instance. The address must first be registered with the stack by -- calling 'RegisterElasticIp'. For more information, see <http://docs.aws.amazon.com/opsworks/latest/userguide/resources.html Resource Management>. -- -- Required Permissions: To use this action, an IAM user must have a Manage -- permissions level for the stack, or an attached policy that explicitly grants -- permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing UserPermissions>. -- -- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_AssociateElasticIp.html> module Network.AWS.OpsWorks.AssociateElasticIp ( -- * Request AssociateElasticIp -- ** Request constructor , associateElasticIp -- ** Request lenses , aeiElasticIp , aeiInstanceId -- * Response , AssociateElasticIpResponse -- ** Response constructor , associateElasticIpResponse ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.OpsWorks.Types import qualified GHC.Exts data AssociateElasticIp = AssociateElasticIp { _aeiElasticIp :: Text , _aeiInstanceId :: Maybe Text } deriving (Eq, Ord, Read, Show) -- | 'AssociateElasticIp' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'aeiElasticIp' @::@ 'Text' -- -- * 'aeiInstanceId' @::@ 'Maybe' 'Text' -- associateElasticIp :: Text -- ^ 'aeiElasticIp' -> AssociateElasticIp associateElasticIp p1 = AssociateElasticIp { _aeiElasticIp = p1 , _aeiInstanceId = Nothing } -- | The Elastic IP address. aeiElasticIp :: Lens' AssociateElasticIp Text aeiElasticIp = lens _aeiElasticIp (\s a -> s { _aeiElasticIp = a }) -- | The instance ID. aeiInstanceId :: Lens' AssociateElasticIp (Maybe Text) aeiInstanceId = lens _aeiInstanceId (\s a -> s { _aeiInstanceId = a }) data AssociateElasticIpResponse = AssociateElasticIpResponse deriving (Eq, Ord, Read, Show, Generic) -- | 'AssociateElasticIpResponse' constructor. associateElasticIpResponse :: AssociateElasticIpResponse associateElasticIpResponse = AssociateElasticIpResponse instance ToPath AssociateElasticIp where toPath = const "/" instance ToQuery AssociateElasticIp where toQuery = const mempty instance ToHeaders AssociateElasticIp instance ToJSON AssociateElasticIp where toJSON AssociateElasticIp{..} = object [ "ElasticIp" .= _aeiElasticIp , "InstanceId" .= _aeiInstanceId ] instance AWSRequest AssociateElasticIp where type Sv AssociateElasticIp = OpsWorks type Rs AssociateElasticIp = AssociateElasticIpResponse request = post "AssociateElasticIp" response = nullResponse AssociateElasticIpResponse
romanb/amazonka
amazonka-opsworks/gen/Network/AWS/OpsWorks/AssociateElasticIp.hs
mpl-2.0
3,940
0
9
775
428
261
167
54
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} {-# LANGUAGE DeriveDataTypeable #-} module Graphics.UI.Threepenny.Internal.FFI ( -- * Synopsis -- | Combinators for creating JavaScript code and marhsalling. -- * Documentation ffi, FFI(..), ToJS(..), JSFunction, showJSON, toCode, marshalResult, ) where import Data.Aeson as JSON import qualified Data.Aeson.Types as JSON import qualified Data.Aeson.Encode import Data.ByteString (ByteString) import Data.Data import Data.Functor import Data.Maybe import Data.String (fromString) import qualified Data.Text.Lazy import qualified Data.Text.Lazy.Builder import Safe (atMay) import Graphics.UI.Threepenny.Internal.Types {----------------------------------------------------------------------------- Easy, if stupid conversion between String and JSON TODO: Use more efficient string types like ByteString, Text, etc. ------------------------------------------------------------------------------} showJSON :: ToJSON a => a -> String showJSON = Data.Text.Lazy.unpack . Data.Text.Lazy.Builder.toLazyText . Data.Aeson.Encode.fromValue . JSON.toJSON {----------------------------------------------------------------------------- JavaScript Code and Foreign Function Interface ------------------------------------------------------------------------------} -- | JavaScript code snippet. newtype JSCode = JSCode { unJSCode :: String } deriving (Eq, Ord, Show, Data, Typeable) -- | Helper class for rendering Haskell values as JavaScript expressions. class ToJS a where render :: a -> JSCode instance ToJS String where render = render . JSON.String . fromString instance ToJS Int where render = JSCode . show instance ToJS Bool where render b = JSCode $ if b then "false" else "true" instance ToJS JSON.Value where render = JSCode . showJSON -- TODO: ByteString instance may be wrong. Only needed for ElementId right now. instance ToJS ByteString where render = JSCode . show instance ToJS ElementId where render (ElementId x) = apply "elidToElement(%1)" [render x] instance ToJS Element where render = render . unprotectedGetElementId -- | A JavaScript function with a given output type @a@. data JSFunction a = JSFunction { code :: JSCode -- ^ code snippet , marshal :: Window -> JSON.Value -> JSON.Parser a -- ^ conversion to Haskell value } -- | Render function to a textual representation using JavaScript syntax. toCode :: JSFunction a -> String toCode = unJSCode . code -- | Convert function result to a Haskell value. marshalResult :: JSFunction a -- ^ Function that has been executed -> Window -- ^ Browser context -> JSON.Value -- ^ JSON representation of the return value -> JSON.Result a -- ^ Function result as parsed Haskell value marshalResult fun w = JSON.parse (marshal fun w) instance Functor JSFunction where fmap f = fmapWindow (const f) fmapWindow :: (Window -> a -> b) -> JSFunction a -> JSFunction b fmapWindow f (JSFunction c m) = JSFunction c (\w v -> f w <$> m w v) fromJSCode :: JSCode -> JSFunction () fromJSCode c = JSFunction { code = c, marshal = \_ _ -> return () } -- | Helper class for making 'ffi' a variable argument function. class FFI a where fancy :: ([JSCode] -> JSCode) -> a instance (ToJS a, FFI b) => FFI (a -> b) where fancy f a = fancy $ f . (render a:) instance FFI (JSFunction ()) where fancy f = fromJSCode $ f [] instance FFI (JSFunction String) where fancy = mkResult "%1.toString()" instance FFI (JSFunction JSON.Value) where fancy = mkResult "%1" instance FFI (JSFunction [ElementId]) where fancy = mkResult "elementsToElids(%1)" -- FIXME: We need access to IO in order to turn a Coupon into an Element. {- instance FFI (JSFunction Element) where fancy = fmapWindow (\w elid -> Element elid w) . fancy -} mkResult :: FromJSON a => String -> ([JSCode] -> JSCode) -> JSFunction a mkResult client f = JSFunction { code = apply client [f []] , marshal = \w -> parseJSON } -- | Simple JavaScript FFI with string substitution. -- -- Inspired by the Fay language. <http://fay-lang.org/> -- -- > example :: String -> Int -> JSFunction String -- > example = ffi "$(%1).prop('checked',%2)" -- -- The 'ffi' function takes a string argument representing the JavaScript -- code to be executed on the client. -- Occurrences of the substrings @%1@ to @%9@ will be replaced by -- subequent arguments. -- -- Note: Always specify a type signature! The types automate -- how values are marshalled between Haskell and JavaScript. -- The class instances for the 'FFI' class show which conversions are supported. -- ffi :: FFI a => String -> a ffi macro = fancy (apply macro) testFFI :: String -> Int -> JSFunction String testFFI = ffi "$(%1).prop('checked',%2)" -- | String substitution. -- Substitute occurences of %1, %2 up to %9 with the argument strings. -- The types ensure that the % character has no meaning in the generated output. -- -- > apply "%1 and %2" [x,y] = x ++ " and " ++ y apply :: String -> [JSCode] -> JSCode apply code args = JSCode $ go code where at xs i = maybe (error err) id $ atMay xs i err = "Graphics.UI.Threepenny.FFI: Too few arguments in FFI call!" argument i = unJSCode (args `at` i) go [] = [] go ('%':c:cs) = argument index ++ go cs where index = fromEnum c - fromEnum '1' go (c:cs) = c : go cs
yuvallanger/threepenny-gui
src/Graphics/UI/Threepenny/Internal/FFI.hs
bsd-3-clause
5,641
0
12
1,250
1,174
650
524
79
3
{-# LANGUAGE CPP #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} -- | The Config type. module Stack.Types.Config ( -- * Main configuration types and classes -- ** HasPlatform & HasStackRoot HasPlatform(..) ,HasStackRoot(..) ,PlatformVariant(..) -- ** Config & HasConfig ,Config(..) ,HasConfig(..) ,askConfig ,askLatestSnapshotUrl ,explicitSetupDeps ,getMinimalEnvOverride -- ** BuildConfig & HasBuildConfig ,BuildConfig(..) ,bcRoot ,bcWorkDir ,HasBuildConfig(..) -- ** GHCVariant & HasGHCVariant ,GHCVariant(..) ,ghcVariantName ,ghcVariantSuffix ,parseGHCVariant ,HasGHCVariant(..) ,snapshotsDir -- ** EnvConfig & HasEnvConfig ,EnvConfig(..) ,HasEnvConfig(..) ,getWhichCompiler -- * Details -- ** ApplyGhcOptions ,ApplyGhcOptions(..) -- ** ConfigException ,ConfigException(..) -- ** ConfigMonoid ,ConfigMonoid(..) -- ** EnvSettings ,EnvSettings(..) ,minimalEnvSettings -- ** GlobalOpts & GlobalOptsMonoid ,GlobalOpts(..) ,GlobalOptsMonoid(..) ,defaultLogLevel -- ** LoadConfig ,LoadConfig(..) -- ** PackageEntry & PackageLocation ,PackageEntry(..) ,peExtraDep ,PackageLocation(..) ,RemotePackageType(..) -- ** PackageIndex, IndexName & IndexLocation ,PackageIndex(..) ,IndexName(..) ,configPackageIndex ,configPackageIndexCache ,configPackageIndexGz ,configPackageIndexRoot ,configPackageTarball ,indexNameText ,IndexLocation(..) -- ** Project & ProjectAndConfigMonoid ,Project(..) ,ProjectAndConfigMonoid(..) -- ** PvpBounds ,PvpBounds(..) ,parsePvpBounds -- ** Resolver & AbstractResolver ,Resolver(..) ,parseResolverText ,resolverName ,AbstractResolver(..) -- ** SCM ,SCM(..) -- * Paths ,bindirSuffix ,configInstalledCache ,configMiniBuildPlanCache ,configProjectWorkDir ,docDirSuffix ,flagCacheLocal ,extraBinDirs ,hpcReportDir ,installationRootDeps ,installationRootLocal ,packageDatabaseDeps ,packageDatabaseExtra ,packageDatabaseLocal ,platformOnlyRelDir ,platformGhcRelDir ,useShaPathOnWindows ,getWorkDir -- * Command-specific types -- ** Eval ,EvalOpts(..) -- ** Exec ,ExecOpts(..) ,SpecialExecCmd(..) ,ExecOptsExtra(..) -- ** Setup ,DownloadInfo(..) ,VersionedDownloadInfo(..) ,SetupInfo(..) ,SetupInfoLocation(..) -- ** Docker entrypoint ,DockerEntrypoint(..) ) where import Control.Applicative import Control.Arrow ((&&&)) import Control.Exception import Control.Monad (liftM, mzero, forM) import Control.Monad.Catch (MonadThrow, throwM) import Control.Monad.Logger (LogLevel(..)) import Control.Monad.Reader (MonadReader, ask, asks, MonadIO, liftIO) import Data.Aeson.Extended (ToJSON, toJSON, FromJSON, parseJSON, withText, object, (.=), (..:), (..:?), (..!=), Value(String, Object), withObjectWarnings, WarningParser, Object, jsonSubWarnings, JSONWarning, jsonSubWarningsT, jsonSubWarningsTT) import Data.Attoparsec.Args import Data.Binary (Binary) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Either (partitionEithers) import Data.List (stripPrefix) import Data.Hashable (Hashable) import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Map.Strict as M import Data.Maybe import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8, decodeUtf8) import Data.Typeable import Data.Yaml (ParseException) import Distribution.System (Platform) import qualified Distribution.Text import Distribution.Version (anyVersion) import Network.HTTP.Client (parseUrl) import Path import qualified Paths_stack as Meta import Stack.Types.BuildPlan (SnapName, renderSnapName, parseSnapName) import Stack.Types.Compiler import Stack.Types.Docker import Stack.Types.Nix import Stack.Types.FlagName import Stack.Types.Image import Stack.Types.PackageIdentifier import Stack.Types.PackageIndex import Stack.Types.PackageName import Stack.Types.Version import System.PosixCompat.Types (UserID, GroupID) import System.Process.Read (EnvOverride) #ifdef mingw32_HOST_OS import qualified Crypto.Hash.SHA1 as SHA1 import qualified Data.ByteString.Base16 as B16 #endif -- | The top-level Stackage configuration. data Config = Config {configStackRoot :: !(Path Abs Dir) -- ^ ~/.stack more often than not ,configWorkDir :: !(Path Rel Dir) -- ^ this allows to override .stack-work directory ,configUserConfigPath :: !(Path Abs File) -- ^ Path to user configuration file (usually ~/.stack/config.yaml) ,configDocker :: !DockerOpts -- ^ Docker configuration ,configNix :: !NixOpts -- ^ Execution environment (e.g nix-shell) configuration ,configEnvOverride :: !(EnvSettings -> IO EnvOverride) -- ^ Environment variables to be passed to external tools ,configLocalProgramsBase :: !(Path Abs Dir) -- ^ Non-platform-specific path containing local installations ,configLocalPrograms :: !(Path Abs Dir) -- ^ Path containing local installations (mainly GHC) ,configConnectionCount :: !Int -- ^ How many concurrent connections are allowed when downloading ,configHideTHLoading :: !Bool -- ^ Hide the Template Haskell "Loading package ..." messages from the -- console ,configPlatform :: !Platform -- ^ The platform we're building for, used in many directory names ,configPlatformVariant :: !PlatformVariant -- ^ Variant of the platform, also used in directory names ,configGHCVariant0 :: !(Maybe GHCVariant) -- ^ The variant of GHC requested by the user. -- In most cases, use 'BuildConfig' or 'MiniConfig's version instead, -- which will have an auto-detected default. ,configLatestSnapshotUrl :: !Text -- ^ URL for a JSON file containing information on the latest -- snapshots available. ,configPackageIndices :: ![PackageIndex] -- ^ Information on package indices. This is left biased, meaning that -- packages in an earlier index will shadow those in a later index. -- -- Warning: if you override packages in an index vs what's available -- upstream, you may correct your compiled snapshots, as different -- projects may have different definitions of what pkg-ver means! This -- feature is primarily intended for adding local packages, not -- overriding. Overriding is better accomplished by adding to your -- list of packages. -- -- Note that indices specified in a later config file will override -- previous indices, /not/ extend them. -- -- Using an assoc list instead of a Map to keep track of priority ,configSystemGHC :: !Bool -- ^ Should we use the system-installed GHC (on the PATH) if -- available? Can be overridden by command line options. ,configInstallGHC :: !Bool -- ^ Should we automatically install GHC if missing or the wrong -- version is available? Can be overridden by command line options. ,configSkipGHCCheck :: !Bool -- ^ Don't bother checking the GHC version or architecture. ,configSkipMsys :: !Bool -- ^ On Windows: don't use a locally installed MSYS ,configCompilerCheck :: !VersionCheck -- ^ Specifies which versions of the compiler are acceptable. ,configLocalBin :: !(Path Abs Dir) -- ^ Directory we should install executables into ,configRequireStackVersion :: !VersionRange -- ^ Require a version of stack within this range. ,configJobs :: !Int -- ^ How many concurrent jobs to run, defaults to number of capabilities ,configExtraIncludeDirs :: !(Set Text) -- ^ --extra-include-dirs arguments ,configExtraLibDirs :: !(Set Text) -- ^ --extra-lib-dirs arguments ,configConfigMonoid :: !ConfigMonoid -- ^ @ConfigMonoid@ used to generate this ,configConcurrentTests :: !Bool -- ^ Run test suites concurrently ,configImage :: !ImageOpts ,configTemplateParams :: !(Map Text Text) -- ^ Parameters for templates. ,configScmInit :: !(Maybe SCM) -- ^ Initialize SCM (e.g. git) when creating new projects. ,configGhcOptions :: !(Map (Maybe PackageName) [Text]) -- ^ Additional GHC options to apply to either all packages (Nothing) -- or a specific package (Just). ,configSetupInfoLocations :: ![SetupInfoLocation] -- ^ Additional SetupInfo (inline or remote) to use to find tools. ,configPvpBounds :: !PvpBounds -- ^ How PVP upper bounds should be added to packages ,configModifyCodePage :: !Bool -- ^ Force the code page to UTF-8 on Windows ,configExplicitSetupDeps :: !(Map (Maybe PackageName) Bool) -- ^ See 'explicitSetupDeps'. 'Nothing' provides the default value. ,configRebuildGhcOptions :: !Bool -- ^ Rebuild on GHC options changes ,configApplyGhcOptions :: !ApplyGhcOptions -- ^ Which packages to ghc-options on the command line apply to? ,configAllowNewer :: !Bool -- ^ Ignore version ranges in .cabal files. Funny naming chosen to -- match cabal. } -- | Which packages to ghc-options on the command line apply to? data ApplyGhcOptions = AGOTargets -- ^ all local targets | AGOLocals -- ^ all local packages, even non-targets | AGOEverything -- ^ every package deriving (Show, Read, Eq, Ord, Enum, Bounded) instance FromJSON ApplyGhcOptions where parseJSON = withText "ApplyGhcOptions" $ \t -> case t of "targets" -> return AGOTargets "locals" -> return AGOLocals "everything" -> return AGOEverything _ -> fail $ "Invalid ApplyGhcOptions: " ++ show t -- | Information on a single package index data PackageIndex = PackageIndex { indexName :: !IndexName , indexLocation :: !IndexLocation , indexDownloadPrefix :: !Text -- ^ URL prefix for downloading packages , indexGpgVerify :: !Bool -- ^ GPG-verify the package index during download. Only applies to Git -- repositories for now. , indexRequireHashes :: !Bool -- ^ Require that hashes and package size information be available for packages in this index } deriving Show instance FromJSON (PackageIndex, [JSONWarning]) where parseJSON = withObjectWarnings "PackageIndex" $ \o -> do name <- o ..: "name" prefix <- o ..: "download-prefix" mgit <- o ..:? "git" mhttp <- o ..:? "http" loc <- case (mgit, mhttp) of (Nothing, Nothing) -> fail $ "Must provide either Git or HTTP URL for " ++ T.unpack (indexNameText name) (Just git, Nothing) -> return $ ILGit git (Nothing, Just http) -> return $ ILHttp http (Just git, Just http) -> return $ ILGitHttp git http gpgVerify <- o ..:? "gpg-verify" ..!= False reqHashes <- o ..:? "require-hashes" ..!= False return PackageIndex { indexName = name , indexLocation = loc , indexDownloadPrefix = prefix , indexGpgVerify = gpgVerify , indexRequireHashes = reqHashes } -- | Unique name for a package index newtype IndexName = IndexName { unIndexName :: ByteString } deriving (Show, Eq, Ord, Hashable, Binary) indexNameText :: IndexName -> Text indexNameText = decodeUtf8 . unIndexName instance ToJSON IndexName where toJSON = toJSON . indexNameText instance FromJSON IndexName where parseJSON = withText "IndexName" $ \t -> case parseRelDir (T.unpack t) of Left e -> fail $ "Invalid index name: " ++ show e Right _ -> return $ IndexName $ encodeUtf8 t -- | Location of the package index. This ensures that at least one of Git or -- HTTP is available. data IndexLocation = ILGit !Text | ILHttp !Text | ILGitHttp !Text !Text deriving (Show, Eq, Ord) -- | Controls which version of the environment is used data EnvSettings = EnvSettings { esIncludeLocals :: !Bool -- ^ include local project bin directory, GHC_PACKAGE_PATH, etc , esIncludeGhcPackagePath :: !Bool -- ^ include the GHC_PACKAGE_PATH variable , esStackExe :: !Bool -- ^ set the STACK_EXE variable to the current executable name , esLocaleUtf8 :: !Bool -- ^ set the locale to C.UTF-8 } deriving (Show, Eq, Ord) data ExecOpts = ExecOpts { eoCmd :: !SpecialExecCmd , eoArgs :: ![String] , eoExtra :: !ExecOptsExtra } deriving (Show) data SpecialExecCmd = ExecCmd String | ExecGhc | ExecRunGhc deriving (Show, Eq) data ExecOptsExtra = ExecOptsPlain | ExecOptsEmbellished { eoEnvSettings :: !EnvSettings , eoPackages :: ![String] } deriving (Show) data EvalOpts = EvalOpts { evalArg :: !String , evalExtra :: !ExecOptsExtra } deriving (Show) -- | Parsed global command-line options. data GlobalOpts = GlobalOpts { globalReExecVersion :: !(Maybe String) -- ^ Expected re-exec in container version , globalDockerEntrypoint :: !(Maybe DockerEntrypoint) -- ^ Data used when stack is acting as a Docker entrypoint (internal use only) , globalLogLevel :: !LogLevel -- ^ Log level , globalConfigMonoid :: !ConfigMonoid -- ^ Config monoid, for passing into 'loadConfig' , globalResolver :: !(Maybe AbstractResolver) -- ^ Resolver override , globalCompiler :: !(Maybe CompilerVersion) -- ^ Compiler override , globalTerminal :: !Bool -- ^ We're in a terminal? , globalStackYaml :: !(Maybe FilePath) -- ^ Override project stack.yaml } deriving (Show) -- | Parsed global command-line options monoid. data GlobalOptsMonoid = GlobalOptsMonoid { globalMonoidReExecVersion :: !(Maybe String) -- ^ Expected re-exec in container version , globalMonoidDockerEntrypoint :: !(Maybe DockerEntrypoint) -- ^ Data used when stack is acting as a Docker entrypoint (internal use only) , globalMonoidLogLevel :: !(Maybe LogLevel) -- ^ Log level , globalMonoidConfigMonoid :: !ConfigMonoid -- ^ Config monoid, for passing into 'loadConfig' , globalMonoidResolver :: !(Maybe AbstractResolver) -- ^ Resolver override , globalMonoidCompiler :: !(Maybe CompilerVersion) -- ^ Compiler override , globalMonoidTerminal :: !(Maybe Bool) -- ^ We're in a terminal? , globalMonoidStackYaml :: !(Maybe FilePath) -- ^ Override project stack.yaml } deriving (Show) instance Monoid GlobalOptsMonoid where mempty = GlobalOptsMonoid Nothing Nothing Nothing mempty Nothing Nothing Nothing Nothing mappend l r = GlobalOptsMonoid { globalMonoidReExecVersion = globalMonoidReExecVersion l <|> globalMonoidReExecVersion r , globalMonoidDockerEntrypoint = globalMonoidDockerEntrypoint l <|> globalMonoidDockerEntrypoint r , globalMonoidLogLevel = globalMonoidLogLevel l <|> globalMonoidLogLevel r , globalMonoidConfigMonoid = globalMonoidConfigMonoid l <> globalMonoidConfigMonoid r , globalMonoidResolver = globalMonoidResolver l <|> globalMonoidResolver r , globalMonoidCompiler = globalMonoidCompiler l <|> globalMonoidCompiler r , globalMonoidTerminal = globalMonoidTerminal l <|> globalMonoidTerminal r , globalMonoidStackYaml = globalMonoidStackYaml l <|> globalMonoidStackYaml r } -- | Either an actual resolver value, or an abstract description of one (e.g., -- latest nightly). data AbstractResolver = ARLatestNightly | ARLatestLTS | ARLatestLTSMajor !Int | ARResolver !Resolver | ARGlobal deriving Show -- | Default logging level should be something useful but not crazy. defaultLogLevel :: LogLevel defaultLogLevel = LevelInfo -- | A superset of 'Config' adding information on how to build code. The reason -- for this breakdown is because we will need some of the information from -- 'Config' in order to determine the values here. data BuildConfig = BuildConfig { bcConfig :: !Config , bcResolver :: !Resolver -- ^ How we resolve which dependencies to install given a set of -- packages. , bcWantedCompiler :: !CompilerVersion -- ^ Compiler version wanted for this build , bcPackageEntries :: ![PackageEntry] -- ^ Local packages identified by a path, Bool indicates whether it is -- a non-dependency (the opposite of 'peExtraDep') , bcExtraDeps :: !(Map PackageName Version) -- ^ Extra dependencies specified in configuration. -- -- These dependencies will not be installed to a shared location, and -- will override packages provided by the resolver. , bcExtraPackageDBs :: ![Path Abs Dir] -- ^ Extra package databases , bcStackYaml :: !(Path Abs File) -- ^ Location of the stack.yaml file. -- -- Note: if the STACK_YAML environment variable is used, this may be -- different from bcRoot </> "stack.yaml" , bcFlags :: !(Map PackageName (Map FlagName Bool)) -- ^ Per-package flag overrides , bcImplicitGlobal :: !Bool -- ^ Are we loading from the implicit global stack.yaml? This is useful -- for providing better error messages. , bcGHCVariant :: !GHCVariant -- ^ The variant of GHC used to select a GHC bindist. , bcPackageCaches :: !(Map PackageIdentifier (PackageIndex, PackageCache)) -- ^ Shared package cache map } -- | Directory containing the project's stack.yaml file bcRoot :: BuildConfig -> Path Abs Dir bcRoot = parent . bcStackYaml -- | @"'bcRoot'/.stack-work"@ bcWorkDir :: (MonadReader env m, HasConfig env) => BuildConfig -> m (Path Abs Dir) bcWorkDir bconfig = do workDir <- getWorkDir return (bcRoot bconfig </> workDir) -- | Configuration after the environment has been setup. data EnvConfig = EnvConfig {envConfigBuildConfig :: !BuildConfig ,envConfigCabalVersion :: !Version ,envConfigCompilerVersion :: !CompilerVersion ,envConfigPackages :: !(Map (Path Abs Dir) Bool)} instance HasBuildConfig EnvConfig where getBuildConfig = envConfigBuildConfig instance HasConfig EnvConfig instance HasPlatform EnvConfig instance HasGHCVariant EnvConfig instance HasStackRoot EnvConfig class (HasBuildConfig r, HasGHCVariant r) => HasEnvConfig r where getEnvConfig :: r -> EnvConfig instance HasEnvConfig EnvConfig where getEnvConfig = id -- | Value returned by 'Stack.Config.loadConfig'. data LoadConfig m = LoadConfig { lcConfig :: !Config -- ^ Top-level Stack configuration. , lcLoadBuildConfig :: !(Maybe CompilerVersion -> m BuildConfig) -- ^ Action to load the remaining 'BuildConfig'. , lcProjectRoot :: !(Maybe (Path Abs Dir)) -- ^ The project root directory, if in a project. } data PackageEntry = PackageEntry { peExtraDepMaybe :: !(Maybe Bool) -- ^ Is this package a dependency? This means the local package will be -- treated just like an extra-deps: it will only be built as a dependency -- for others, and its test suite/benchmarks will not be run. -- -- Useful modifying an upstream package, see: -- https://github.com/commercialhaskell/stack/issues/219 -- https://github.com/commercialhaskell/stack/issues/386 , peValidWanted :: !(Maybe Bool) -- ^ Deprecated name meaning the opposite of peExtraDep. Only present to -- provide deprecation warnings to users. , peLocation :: !PackageLocation , peSubdirs :: ![FilePath] } deriving Show -- | Once peValidWanted is removed, this should just become the field name in PackageEntry. peExtraDep :: PackageEntry -> Bool peExtraDep pe = case peExtraDepMaybe pe of Just x -> x Nothing -> case peValidWanted pe of Just x -> not x Nothing -> False instance ToJSON PackageEntry where toJSON pe | not (peExtraDep pe) && null (peSubdirs pe) = toJSON $ peLocation pe toJSON pe = object [ "extra-dep" .= peExtraDep pe , "location" .= peLocation pe , "subdirs" .= peSubdirs pe ] instance FromJSON (PackageEntry, [JSONWarning]) where parseJSON (String t) = do (loc, _::[JSONWarning]) <- parseJSON $ String t return (PackageEntry { peExtraDepMaybe = Nothing , peValidWanted = Nothing , peLocation = loc , peSubdirs = [] }, []) parseJSON v = withObjectWarnings "PackageEntry" (\o -> PackageEntry <$> o ..:? "extra-dep" <*> o ..:? "valid-wanted" <*> jsonSubWarnings (o ..: "location") <*> o ..:? "subdirs" ..!= []) v data PackageLocation = PLFilePath FilePath -- ^ Note that we use @FilePath@ and not @Path@s. The goal is: first parse -- the value raw, and then use @canonicalizePath@ and @parseAbsDir@. | PLRemote Text RemotePackageType -- ^ URL and further details deriving Show data RemotePackageType = RPTHttpTarball | RPTGit Text -- ^ Commit | RPTHg Text -- ^ Commit deriving Show instance ToJSON PackageLocation where toJSON (PLFilePath fp) = toJSON fp toJSON (PLRemote t RPTHttpTarball) = toJSON t toJSON (PLRemote x (RPTGit y)) = toJSON $ T.unwords ["git", x, y] toJSON (PLRemote x (RPTHg y)) = toJSON $ T.unwords ["hg", x, y] instance FromJSON (PackageLocation, [JSONWarning]) where parseJSON v = ((,[]) <$> withText "PackageLocation" (\t -> http t <|> file t) v) <|> git v <|> hg v where file t = pure $ PLFilePath $ T.unpack t http t = case parseUrl $ T.unpack t of Left _ -> mzero Right _ -> return $ PLRemote t RPTHttpTarball git = withObjectWarnings "PackageGitLocation" $ \o -> PLRemote <$> o ..: "git" <*> (RPTGit <$> o ..: "commit") hg = withObjectWarnings "PackageHgLocation" $ \o -> PLRemote <$> o ..: "hg" <*> (RPTHg <$> o ..: "commit") -- | A project is a collection of packages. We can have multiple stack.yaml -- files, but only one of them may contain project information. data Project = Project { projectPackages :: ![PackageEntry] -- ^ Components of the package list , projectExtraDeps :: !(Map PackageName Version) -- ^ Components of the package list referring to package/version combos, -- see: https://github.com/fpco/stack/issues/41 , projectFlags :: !(Map PackageName (Map FlagName Bool)) -- ^ Per-package flag overrides , projectResolver :: !Resolver -- ^ How we resolve which dependencies to use , projectCompiler :: !(Maybe CompilerVersion) -- ^ When specified, overrides which compiler to use , projectExtraPackageDBs :: ![FilePath] } deriving Show instance ToJSON Project where toJSON p = object $ (maybe id (\cv -> (("compiler" .= cv) :)) (projectCompiler p)) [ "packages" .= projectPackages p , "extra-deps" .= map fromTuple (Map.toList $ projectExtraDeps p) , "flags" .= projectFlags p , "resolver" .= projectResolver p , "extra-package-dbs" .= projectExtraPackageDBs p ] -- | How we resolve which dependencies to install given a set of packages. data Resolver = ResolverSnapshot SnapName -- ^ Use an official snapshot from the Stackage project, either an LTS -- Haskell or Stackage Nightly | ResolverCompiler !CompilerVersion -- ^ Require a specific compiler version, but otherwise provide no build plan. -- Intended for use cases where end user wishes to specify all upstream -- dependencies manually, such as using a dependency solver. | ResolverCustom !Text !Text -- ^ A custom resolver based on the given name and URL. This file is assumed -- to be completely immutable. deriving (Show) instance ToJSON Resolver where toJSON (ResolverCustom name location) = object [ "name" .= name , "location" .= location ] toJSON x = toJSON $ resolverName x instance FromJSON (Resolver,[JSONWarning]) where -- Strange structuring is to give consistent error messages parseJSON v@(Object _) = withObjectWarnings "Resolver" (\o -> ResolverCustom <$> o ..: "name" <*> o ..: "location") v parseJSON (String t) = either (fail . show) return ((,[]) <$> parseResolverText t) parseJSON _ = fail $ "Invalid Resolver, must be Object or String" -- | Convert a Resolver into its @Text@ representation, as will be used by -- directory names resolverName :: Resolver -> Text resolverName (ResolverSnapshot name) = renderSnapName name resolverName (ResolverCompiler v) = compilerVersionText v resolverName (ResolverCustom name _) = "custom-" <> name -- | Try to parse a @Resolver@ from a @Text@. Won't work for complex resolvers (like custom). parseResolverText :: MonadThrow m => Text -> m Resolver parseResolverText t | Right x <- parseSnapName t = return $ ResolverSnapshot x | Just v <- parseCompilerVersion t = return $ ResolverCompiler v | otherwise = throwM $ ParseResolverException t -- | Class for environment values which have access to the stack root class HasStackRoot env where getStackRoot :: env -> Path Abs Dir default getStackRoot :: HasConfig env => env -> Path Abs Dir getStackRoot = configStackRoot . getConfig {-# INLINE getStackRoot #-} -- | Class for environment values which have a Platform class HasPlatform env where getPlatform :: env -> Platform default getPlatform :: HasConfig env => env -> Platform getPlatform = configPlatform . getConfig {-# INLINE getPlatform #-} getPlatformVariant :: env -> PlatformVariant default getPlatformVariant :: HasConfig env => env -> PlatformVariant getPlatformVariant = configPlatformVariant . getConfig {-# INLINE getPlatformVariant #-} instance HasPlatform (Platform,PlatformVariant) where getPlatform (p,_) = p getPlatformVariant (_,v) = v -- | Class for environment values which have a GHCVariant class HasGHCVariant env where getGHCVariant :: env -> GHCVariant default getGHCVariant :: HasBuildConfig env => env -> GHCVariant getGHCVariant = bcGHCVariant . getBuildConfig {-# INLINE getGHCVariant #-} instance HasGHCVariant GHCVariant where getGHCVariant = id -- | Class for environment values that can provide a 'Config'. class (HasStackRoot env, HasPlatform env) => HasConfig env where getConfig :: env -> Config default getConfig :: HasBuildConfig env => env -> Config getConfig = bcConfig . getBuildConfig {-# INLINE getConfig #-} instance HasStackRoot Config instance HasPlatform Config instance HasConfig Config where getConfig = id {-# INLINE getConfig #-} -- | Class for environment values that can provide a 'BuildConfig'. class HasConfig env => HasBuildConfig env where getBuildConfig :: env -> BuildConfig instance HasStackRoot BuildConfig instance HasPlatform BuildConfig instance HasGHCVariant BuildConfig instance HasConfig BuildConfig instance HasBuildConfig BuildConfig where getBuildConfig = id {-# INLINE getBuildConfig #-} -- An uninterpreted representation of configuration options. -- Configurations may be "cascaded" using mappend (left-biased). data ConfigMonoid = ConfigMonoid { configMonoidWorkDir :: !(Maybe FilePath) -- ^ See: 'configWorkDir'. , configMonoidDockerOpts :: !DockerOptsMonoid -- ^ Docker options. , configMonoidNixOpts :: !NixOptsMonoid -- ^ Options for the execution environment (nix-shell or container) , configMonoidConnectionCount :: !(Maybe Int) -- ^ See: 'configConnectionCount' , configMonoidHideTHLoading :: !(Maybe Bool) -- ^ See: 'configHideTHLoading' , configMonoidLatestSnapshotUrl :: !(Maybe Text) -- ^ See: 'configLatestSnapshotUrl' , configMonoidPackageIndices :: !(Maybe [PackageIndex]) -- ^ See: 'configPackageIndices' , configMonoidSystemGHC :: !(Maybe Bool) -- ^ See: 'configSystemGHC' ,configMonoidInstallGHC :: !(Maybe Bool) -- ^ See: 'configInstallGHC' ,configMonoidSkipGHCCheck :: !(Maybe Bool) -- ^ See: 'configSkipGHCCheck' ,configMonoidSkipMsys :: !(Maybe Bool) -- ^ See: 'configSkipMsys' ,configMonoidCompilerCheck :: !(Maybe VersionCheck) -- ^ See: 'configCompilerCheck' ,configMonoidRequireStackVersion :: !VersionRange -- ^ See: 'configRequireStackVersion' ,configMonoidOS :: !(Maybe String) -- ^ Used for overriding the platform ,configMonoidArch :: !(Maybe String) -- ^ Used for overriding the platform ,configMonoidGHCVariant :: !(Maybe GHCVariant) -- ^ Used for overriding the GHC variant ,configMonoidJobs :: !(Maybe Int) -- ^ See: 'configJobs' ,configMonoidExtraIncludeDirs :: !(Set Text) -- ^ See: 'configExtraIncludeDirs' ,configMonoidExtraLibDirs :: !(Set Text) -- ^ See: 'configExtraLibDirs' ,configMonoidConcurrentTests :: !(Maybe Bool) -- ^ See: 'configConcurrentTests' ,configMonoidLocalBinPath :: !(Maybe FilePath) -- ^ Used to override the binary installation dir ,configMonoidImageOpts :: !ImageOptsMonoid -- ^ Image creation options. ,configMonoidTemplateParameters :: !(Map Text Text) -- ^ Template parameters. ,configMonoidScmInit :: !(Maybe SCM) -- ^ Initialize SCM (e.g. git init) when making new projects? ,configMonoidGhcOptions :: !(Map (Maybe PackageName) [Text]) -- ^ See 'configGhcOptions' ,configMonoidExtraPath :: ![Path Abs Dir] -- ^ Additional paths to search for executables in ,configMonoidSetupInfoLocations :: ![SetupInfoLocation] -- ^ Additional setup info (inline or remote) to use for installing tools ,configMonoidPvpBounds :: !(Maybe PvpBounds) -- ^ See 'configPvpBounds' ,configMonoidModifyCodePage :: !(Maybe Bool) -- ^ See 'configModifyCodePage' ,configMonoidExplicitSetupDeps :: !(Map (Maybe PackageName) Bool) -- ^ See 'configExplicitSetupDeps' ,configMonoidRebuildGhcOptions :: !(Maybe Bool) -- ^ See 'configMonoidRebuildGhcOptions' ,configMonoidApplyGhcOptions :: !(Maybe ApplyGhcOptions) -- ^ See 'configApplyGhcOptions' ,configMonoidAllowNewer :: !(Maybe Bool) -- ^ See 'configMonoidAllowNewer' } deriving Show instance Monoid ConfigMonoid where mempty = ConfigMonoid { configMonoidWorkDir = Nothing , configMonoidDockerOpts = mempty , configMonoidNixOpts = mempty , configMonoidConnectionCount = Nothing , configMonoidHideTHLoading = Nothing , configMonoidLatestSnapshotUrl = Nothing , configMonoidPackageIndices = Nothing , configMonoidSystemGHC = Nothing , configMonoidInstallGHC = Nothing , configMonoidSkipGHCCheck = Nothing , configMonoidSkipMsys = Nothing , configMonoidRequireStackVersion = anyVersion , configMonoidOS = Nothing , configMonoidArch = Nothing , configMonoidGHCVariant = Nothing , configMonoidJobs = Nothing , configMonoidExtraIncludeDirs = Set.empty , configMonoidExtraLibDirs = Set.empty , configMonoidConcurrentTests = Nothing , configMonoidLocalBinPath = Nothing , configMonoidImageOpts = mempty , configMonoidTemplateParameters = mempty , configMonoidScmInit = Nothing , configMonoidCompilerCheck = Nothing , configMonoidGhcOptions = mempty , configMonoidExtraPath = [] , configMonoidSetupInfoLocations = mempty , configMonoidPvpBounds = Nothing , configMonoidModifyCodePage = Nothing , configMonoidExplicitSetupDeps = mempty , configMonoidRebuildGhcOptions = Nothing , configMonoidApplyGhcOptions = Nothing , configMonoidAllowNewer = Nothing } mappend l r = ConfigMonoid { configMonoidWorkDir = configMonoidWorkDir l <|> configMonoidWorkDir r , configMonoidDockerOpts = configMonoidDockerOpts l <> configMonoidDockerOpts r , configMonoidNixOpts = configMonoidNixOpts l <> configMonoidNixOpts r , configMonoidConnectionCount = configMonoidConnectionCount l <|> configMonoidConnectionCount r , configMonoidHideTHLoading = configMonoidHideTHLoading l <|> configMonoidHideTHLoading r , configMonoidLatestSnapshotUrl = configMonoidLatestSnapshotUrl l <|> configMonoidLatestSnapshotUrl r , configMonoidPackageIndices = configMonoidPackageIndices l <|> configMonoidPackageIndices r , configMonoidSystemGHC = configMonoidSystemGHC l <|> configMonoidSystemGHC r , configMonoidInstallGHC = configMonoidInstallGHC l <|> configMonoidInstallGHC r , configMonoidSkipGHCCheck = configMonoidSkipGHCCheck l <|> configMonoidSkipGHCCheck r , configMonoidSkipMsys = configMonoidSkipMsys l <|> configMonoidSkipMsys r , configMonoidRequireStackVersion = intersectVersionRanges (configMonoidRequireStackVersion l) (configMonoidRequireStackVersion r) , configMonoidOS = configMonoidOS l <|> configMonoidOS r , configMonoidArch = configMonoidArch l <|> configMonoidArch r , configMonoidGHCVariant = configMonoidGHCVariant l <|> configMonoidGHCVariant r , configMonoidJobs = configMonoidJobs l <|> configMonoidJobs r , configMonoidExtraIncludeDirs = Set.union (configMonoidExtraIncludeDirs l) (configMonoidExtraIncludeDirs r) , configMonoidExtraLibDirs = Set.union (configMonoidExtraLibDirs l) (configMonoidExtraLibDirs r) , configMonoidConcurrentTests = configMonoidConcurrentTests l <|> configMonoidConcurrentTests r , configMonoidLocalBinPath = configMonoidLocalBinPath l <|> configMonoidLocalBinPath r , configMonoidImageOpts = configMonoidImageOpts l <> configMonoidImageOpts r , configMonoidTemplateParameters = configMonoidTemplateParameters l <> configMonoidTemplateParameters r , configMonoidScmInit = configMonoidScmInit l <|> configMonoidScmInit r , configMonoidCompilerCheck = configMonoidCompilerCheck l <|> configMonoidCompilerCheck r , configMonoidGhcOptions = Map.unionWith (++) (configMonoidGhcOptions l) (configMonoidGhcOptions r) , configMonoidExtraPath = configMonoidExtraPath l ++ configMonoidExtraPath r , configMonoidSetupInfoLocations = configMonoidSetupInfoLocations l ++ configMonoidSetupInfoLocations r , configMonoidPvpBounds = configMonoidPvpBounds l <|> configMonoidPvpBounds r , configMonoidModifyCodePage = configMonoidModifyCodePage l <|> configMonoidModifyCodePage r , configMonoidExplicitSetupDeps = configMonoidExplicitSetupDeps l <> configMonoidExplicitSetupDeps r , configMonoidRebuildGhcOptions = configMonoidRebuildGhcOptions l <|> configMonoidRebuildGhcOptions r , configMonoidApplyGhcOptions = configMonoidApplyGhcOptions l <|> configMonoidApplyGhcOptions r , configMonoidAllowNewer = configMonoidAllowNewer l <|> configMonoidAllowNewer r } instance FromJSON (ConfigMonoid, [JSONWarning]) where parseJSON = withObjectWarnings "ConfigMonoid" parseConfigMonoidJSON -- | Parse a partial configuration. Used both to parse both a standalone config -- file and a project file, so that a sub-parser is not required, which would interfere with -- warnings for missing fields. parseConfigMonoidJSON :: Object -> WarningParser ConfigMonoid parseConfigMonoidJSON obj = do configMonoidWorkDir <- obj ..:? configMonoidWorkDirName configMonoidDockerOpts <- jsonSubWarnings (obj ..:? configMonoidDockerOptsName ..!= mempty) configMonoidNixOpts <- jsonSubWarnings (obj ..:? configMonoidNixOptsName ..!= mempty) configMonoidConnectionCount <- obj ..:? configMonoidConnectionCountName configMonoidHideTHLoading <- obj ..:? configMonoidHideTHLoadingName configMonoidLatestSnapshotUrl <- obj ..:? configMonoidLatestSnapshotUrlName configMonoidPackageIndices <- jsonSubWarningsTT (obj ..:? configMonoidPackageIndicesName) configMonoidSystemGHC <- obj ..:? configMonoidSystemGHCName configMonoidInstallGHC <- obj ..:? configMonoidInstallGHCName configMonoidSkipGHCCheck <- obj ..:? configMonoidSkipGHCCheckName configMonoidSkipMsys <- obj ..:? configMonoidSkipMsysName configMonoidRequireStackVersion <- unVersionRangeJSON <$> obj ..:? configMonoidRequireStackVersionName ..!= VersionRangeJSON anyVersion configMonoidOS <- obj ..:? configMonoidOSName configMonoidArch <- obj ..:? configMonoidArchName configMonoidGHCVariant <- obj ..:? configMonoidGHCVariantName configMonoidJobs <- obj ..:? configMonoidJobsName configMonoidExtraIncludeDirs <- obj ..:? configMonoidExtraIncludeDirsName ..!= Set.empty configMonoidExtraLibDirs <- obj ..:? configMonoidExtraLibDirsName ..!= Set.empty configMonoidConcurrentTests <- obj ..:? configMonoidConcurrentTestsName configMonoidLocalBinPath <- obj ..:? configMonoidLocalBinPathName configMonoidImageOpts <- jsonSubWarnings (obj ..:? configMonoidImageOptsName ..!= mempty) templates <- obj ..:? "templates" (configMonoidScmInit,configMonoidTemplateParameters) <- case templates of Nothing -> return (Nothing,M.empty) Just tobj -> do scmInit <- tobj ..:? configMonoidScmInitName params <- tobj ..:? configMonoidTemplateParametersName return (scmInit,fromMaybe M.empty params) configMonoidCompilerCheck <- obj ..:? configMonoidCompilerCheckName mghcoptions <- obj ..:? configMonoidGhcOptionsName configMonoidGhcOptions <- case mghcoptions of Nothing -> return mempty Just m -> fmap Map.fromList $ mapM handleGhcOptions $ Map.toList m extraPath <- obj ..:? configMonoidExtraPathName ..!= [] configMonoidExtraPath <- forM extraPath $ either (fail . show) return . parseAbsDir . T.unpack configMonoidSetupInfoLocations <- maybeToList <$> jsonSubWarningsT (obj ..:? configMonoidSetupInfoLocationsName) configMonoidPvpBounds <- obj ..:? configMonoidPvpBoundsName configMonoidModifyCodePage <- obj ..:? configMonoidModifyCodePageName configMonoidExplicitSetupDeps <- (obj ..:? configMonoidExplicitSetupDepsName ..!= mempty) >>= fmap Map.fromList . mapM handleExplicitSetupDep . Map.toList configMonoidRebuildGhcOptions <- obj ..:? configMonoidRebuildGhcOptionsName configMonoidApplyGhcOptions <- obj ..:? configMonoidApplyGhcOptionsName configMonoidAllowNewer <- obj ..:? configMonoidAllowNewerName return ConfigMonoid {..} where handleGhcOptions :: Monad m => (Text, Text) -> m (Maybe PackageName, [Text]) handleGhcOptions (name', vals') = do name <- if name' == "*" then return Nothing else case parsePackageNameFromString $ T.unpack name' of Left e -> fail $ show e Right x -> return $ Just x case parseArgs Escaping vals' of Left e -> fail e Right vals -> return (name, map T.pack vals) handleExplicitSetupDep :: Monad m => (Text, Bool) -> m (Maybe PackageName, Bool) handleExplicitSetupDep (name', b) = do name <- if name' == "*" then return Nothing else case parsePackageNameFromString $ T.unpack name' of Left e -> fail $ show e Right x -> return $ Just x return (name, b) configMonoidWorkDirName :: Text configMonoidWorkDirName = "work-dir" configMonoidDockerOptsName :: Text configMonoidDockerOptsName = "docker" configMonoidNixOptsName :: Text configMonoidNixOptsName = "nix" configMonoidConnectionCountName :: Text configMonoidConnectionCountName = "connection-count" configMonoidHideTHLoadingName :: Text configMonoidHideTHLoadingName = "hide-th-loading" configMonoidLatestSnapshotUrlName :: Text configMonoidLatestSnapshotUrlName = "latest-snapshot-url" configMonoidPackageIndicesName :: Text configMonoidPackageIndicesName = "package-indices" configMonoidSystemGHCName :: Text configMonoidSystemGHCName = "system-ghc" configMonoidInstallGHCName :: Text configMonoidInstallGHCName = "install-ghc" configMonoidSkipGHCCheckName :: Text configMonoidSkipGHCCheckName = "skip-ghc-check" configMonoidSkipMsysName :: Text configMonoidSkipMsysName = "skip-msys" configMonoidRequireStackVersionName :: Text configMonoidRequireStackVersionName = "require-stack-version" configMonoidOSName :: Text configMonoidOSName = "os" configMonoidArchName :: Text configMonoidArchName = "arch" configMonoidGHCVariantName :: Text configMonoidGHCVariantName = "ghc-variant" configMonoidJobsName :: Text configMonoidJobsName = "jobs" configMonoidExtraIncludeDirsName :: Text configMonoidExtraIncludeDirsName = "extra-include-dirs" configMonoidExtraLibDirsName :: Text configMonoidExtraLibDirsName = "extra-lib-dirs" configMonoidConcurrentTestsName :: Text configMonoidConcurrentTestsName = "concurrent-tests" configMonoidLocalBinPathName :: Text configMonoidLocalBinPathName = "local-bin-path" configMonoidImageOptsName :: Text configMonoidImageOptsName = "image" configMonoidScmInitName :: Text configMonoidScmInitName = "scm-init" configMonoidTemplateParametersName :: Text configMonoidTemplateParametersName = "params" configMonoidCompilerCheckName :: Text configMonoidCompilerCheckName = "compiler-check" configMonoidGhcOptionsName :: Text configMonoidGhcOptionsName = "ghc-options" configMonoidExtraPathName :: Text configMonoidExtraPathName = "extra-path" configMonoidSetupInfoLocationsName :: Text configMonoidSetupInfoLocationsName = "setup-info" configMonoidPvpBoundsName :: Text configMonoidPvpBoundsName = "pvp-bounds" configMonoidModifyCodePageName :: Text configMonoidModifyCodePageName = "modify-code-page" configMonoidExplicitSetupDepsName :: Text configMonoidExplicitSetupDepsName = "explicit-setup-deps" configMonoidRebuildGhcOptionsName :: Text configMonoidRebuildGhcOptionsName = "rebuild-ghc-options" configMonoidApplyGhcOptionsName :: Text configMonoidApplyGhcOptionsName = "apply-ghc-options" configMonoidAllowNewerName :: Text configMonoidAllowNewerName = "allow-newer" data ConfigException = ParseConfigFileException (Path Abs File) ParseException | ParseResolverException Text | NoProjectConfigFound (Path Abs Dir) (Maybe Text) | UnexpectedTarballContents [Path Abs Dir] [Path Abs File] | BadStackVersionException VersionRange | NoMatchingSnapshot [SnapName] | NoSuchDirectory FilePath | ParseGHCVariantException String deriving Typeable instance Show ConfigException where show (ParseConfigFileException configFile exception) = concat [ "Could not parse '" , toFilePath configFile , "':\n" , show exception , "\nSee https://github.com/commercialhaskell/stack/blob/release/doc/yaml_configuration.md." ] show (ParseResolverException t) = concat [ "Invalid resolver value: " , T.unpack t , ". Possible valid values include lts-2.12, nightly-YYYY-MM-DD, ghc-7.10.2, and ghcjs-0.1.0_ghc-7.10.2. " , "See https://www.stackage.org/snapshots for a complete list." ] show (NoProjectConfigFound dir mcmd) = concat [ "Unable to find a stack.yaml file in the current directory (" , toFilePath dir , ") or its ancestors" , case mcmd of Nothing -> "" Just cmd -> "\nRecommended action: stack " ++ T.unpack cmd ] show (UnexpectedTarballContents dirs files) = concat [ "When unpacking a tarball specified in your stack.yaml file, " , "did not find expected contents. Expected: a single directory. Found: " , show ( map (toFilePath . dirname) dirs , map (toFilePath . filename) files ) ] show (BadStackVersionException requiredRange) = concat [ "The version of stack you are using (" , show (fromCabalVersion Meta.version) , ") is outside the required\n" ,"version range specified in stack.yaml (" , T.unpack (versionRangeText requiredRange) , ")." ] show (NoMatchingSnapshot names) = concat [ "There was no snapshot found that matched the package " , "bounds in your .cabal files.\n" , "Please choose one of the following commands to get started.\n\n" , unlines $ map (\name -> " stack init --resolver " ++ T.unpack (renderSnapName name)) names , "\nYou'll then need to add some extra-deps. See:\n\n" , " https://github.com/commercialhaskell/stack/blob/release/doc/yaml_configuration.md#extra-deps" , "\n\nYou can also try falling back to a dependency solver with:\n\n" , " stack init --solver" ] show (NoSuchDirectory dir) = concat ["No directory could be located matching the supplied path: " ,dir ] show (ParseGHCVariantException v) = concat [ "Invalid ghc-variant value: " , v ] instance Exception ConfigException -- | Helper function to ask the environment and apply getConfig askConfig :: (MonadReader env m, HasConfig env) => m Config askConfig = liftM getConfig ask -- | Get the URL to request the information on the latest snapshots askLatestSnapshotUrl :: (MonadReader env m, HasConfig env) => m Text askLatestSnapshotUrl = asks (configLatestSnapshotUrl . getConfig) -- | Root for a specific package index configPackageIndexRoot :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs Dir) configPackageIndexRoot (IndexName name) = do config <- asks getConfig dir <- parseRelDir $ S8.unpack name return (configStackRoot config </> $(mkRelDir "indices") </> dir) -- | Location of the 00-index.cache file configPackageIndexCache :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs File) configPackageIndexCache = liftM (</> $(mkRelFile "00-index.cache")) . configPackageIndexRoot -- | Location of the 00-index.tar file configPackageIndex :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs File) configPackageIndex = liftM (</> $(mkRelFile "00-index.tar")) . configPackageIndexRoot -- | Location of the 00-index.tar.gz file configPackageIndexGz :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> m (Path Abs File) configPackageIndexGz = liftM (</> $(mkRelFile "00-index.tar.gz")) . configPackageIndexRoot -- | Location of a package tarball configPackageTarball :: (MonadReader env m, HasConfig env, MonadThrow m) => IndexName -> PackageIdentifier -> m (Path Abs File) configPackageTarball iname ident = do root <- configPackageIndexRoot iname name <- parseRelDir $ packageNameString $ packageIdentifierName ident ver <- parseRelDir $ versionString $ packageIdentifierVersion ident base <- parseRelFile $ packageIdentifierString ident ++ ".tar.gz" return (root </> $(mkRelDir "packages") </> name </> ver </> base) -- | @".stack-work"@ getWorkDir :: (MonadReader env m, HasConfig env) => m (Path Rel Dir) getWorkDir = configWorkDir `liftM` asks getConfig -- | Per-project work dir configProjectWorkDir :: (HasBuildConfig env, MonadReader env m) => m (Path Abs Dir) configProjectWorkDir = do bc <- asks getBuildConfig workDir <- getWorkDir return (bcRoot bc </> workDir) -- | File containing the installed cache, see "Stack.PackageDump" configInstalledCache :: (HasBuildConfig env, MonadReader env m) => m (Path Abs File) configInstalledCache = liftM (</> $(mkRelFile "installed-cache.bin")) configProjectWorkDir -- | Relative directory for the platform identifier platformOnlyRelDir :: (MonadReader env m, HasPlatform env, MonadThrow m) => m (Path Rel Dir) platformOnlyRelDir = do platform <- asks getPlatform platformVariant <- asks getPlatformVariant parseRelDir (Distribution.Text.display platform ++ platformVariantSuffix platformVariant) -- | Directory containing snapshots snapshotsDir :: (MonadReader env m, HasConfig env, HasGHCVariant env, MonadThrow m) => m (Path Abs Dir) snapshotsDir = do config <- asks getConfig platform <- platformGhcRelDir return $ configStackRoot config </> $(mkRelDir "snapshots") </> platform -- | Installation root for dependencies installationRootDeps :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) installationRootDeps = do config <- asks getConfig -- TODO: also useShaPathOnWindows here, once #1173 is resolved. psc <- platformSnapAndCompilerRel return $ configStackRoot config </> $(mkRelDir "snapshots") </> psc -- | Installation root for locals installationRootLocal :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) installationRootLocal = do bc <- asks getBuildConfig psc <- useShaPathOnWindows =<< platformSnapAndCompilerRel return $ configProjectWorkDir bc </> $(mkRelDir "install") </> psc -- | Path for platform followed by snapshot name followed by compiler -- name. platformSnapAndCompilerRel :: (MonadReader env m, HasPlatform env, HasEnvConfig env, MonadThrow m) => m (Path Rel Dir) platformSnapAndCompilerRel = do bc <- asks getBuildConfig platform <- platformGhcRelDir name <- parseRelDir $ T.unpack $ resolverName $ bcResolver bc ghc <- compilerVersionDir useShaPathOnWindows (platform </> name </> ghc) -- | Relative directory for the platform identifier platformGhcRelDir :: (MonadReader env m, HasPlatform env, HasGHCVariant env, MonadThrow m) => m (Path Rel Dir) platformGhcRelDir = do platform <- asks getPlatform platformVariant <- asks getPlatformVariant ghcVariant <- asks getGHCVariant parseRelDir (mconcat [ Distribution.Text.display platform , platformVariantSuffix platformVariant , ghcVariantSuffix ghcVariant ]) -- | This is an attempt to shorten stack paths on Windows to decrease our -- chances of hitting 260 symbol path limit. The idea is to calculate -- SHA1 hash of the path used on other architectures, encode with base -- 16 and take first 8 symbols of it. useShaPathOnWindows :: MonadThrow m => Path Rel Dir -> m (Path Rel Dir) useShaPathOnWindows = #ifdef mingw32_HOST_OS parseRelDir . S8.unpack . S8.take 8 . B16.encode . SHA1.hash . encodeUtf8 . T.pack . toFilePath #else return #endif compilerVersionDir :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Rel Dir) compilerVersionDir = do compilerVersion <- asks (envConfigCompilerVersion . getEnvConfig) parseRelDir $ case compilerVersion of GhcVersion version -> versionString version GhcjsVersion {} -> compilerVersionString compilerVersion -- | Package database for installing dependencies into packageDatabaseDeps :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) packageDatabaseDeps = do root <- installationRootDeps return $ root </> $(mkRelDir "pkgdb") -- | Package database for installing local packages into packageDatabaseLocal :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) packageDatabaseLocal = do root <- installationRootLocal return $ root </> $(mkRelDir "pkgdb") -- | Extra package databases packageDatabaseExtra :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m [Path Abs Dir] packageDatabaseExtra = do bc <- asks getBuildConfig return $ bcExtraPackageDBs bc -- | Directory for holding flag cache information flagCacheLocal :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) flagCacheLocal = do root <- installationRootLocal return $ root </> $(mkRelDir "flag-cache") -- | Where to store mini build plan caches configMiniBuildPlanCache :: (MonadThrow m, MonadReader env m, HasConfig env, HasGHCVariant env) => SnapName -> m (Path Abs File) configMiniBuildPlanCache name = do root <- asks getStackRoot platform <- platformGhcRelDir file <- parseRelFile $ T.unpack (renderSnapName name) ++ ".cache" -- Yes, cached plans differ based on platform return (root </> $(mkRelDir "build-plan-cache") </> platform </> file) -- | Suffix applied to an installation root to get the bin dir bindirSuffix :: Path Rel Dir bindirSuffix = $(mkRelDir "bin") -- | Suffix applied to an installation root to get the doc dir docDirSuffix :: Path Rel Dir docDirSuffix = $(mkRelDir "doc") -- | Where HPC reports and tix files get stored. hpcReportDir :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Path Abs Dir) hpcReportDir = do root <- installationRootLocal return $ root </> $(mkRelDir "hpc") -- | Get the extra bin directories (for the PATH). Puts more local first -- -- Bool indicates whether or not to include the locals extraBinDirs :: (MonadThrow m, MonadReader env m, HasEnvConfig env) => m (Bool -> [Path Abs Dir]) extraBinDirs = do deps <- installationRootDeps local <- installationRootLocal return $ \locals -> if locals then [local </> bindirSuffix, deps </> bindirSuffix] else [deps </> bindirSuffix] -- | Get the minimal environment override, useful for just calling external -- processes like git or ghc getMinimalEnvOverride :: (MonadReader env m, HasConfig env, MonadIO m) => m EnvOverride getMinimalEnvOverride = do config <- asks getConfig liftIO $ configEnvOverride config minimalEnvSettings minimalEnvSettings :: EnvSettings minimalEnvSettings = EnvSettings { esIncludeLocals = False , esIncludeGhcPackagePath = False , esStackExe = False , esLocaleUtf8 = False } getWhichCompiler :: (MonadReader env m, HasEnvConfig env) => m WhichCompiler getWhichCompiler = asks (whichCompiler . envConfigCompilerVersion . getEnvConfig) data ProjectAndConfigMonoid = ProjectAndConfigMonoid !Project !ConfigMonoid instance (warnings ~ [JSONWarning]) => FromJSON (ProjectAndConfigMonoid, warnings) where parseJSON = withObjectWarnings "ProjectAndConfigMonoid" $ \o -> do dirs <- jsonSubWarningsTT (o ..:? "packages") ..!= [packageEntryCurrDir] extraDeps' <- o ..:? "extra-deps" ..!= [] extraDeps <- case partitionEithers $ goDeps extraDeps' of ([], x) -> return $ Map.fromList x (errs, _) -> fail $ unlines errs flags <- o ..:? "flags" ..!= mempty resolver <- jsonSubWarnings (o ..: "resolver") compiler <- o ..:? "compiler" config <- parseConfigMonoidJSON o extraPackageDBs <- o ..:? "extra-package-dbs" ..!= [] let project = Project { projectPackages = dirs , projectExtraDeps = extraDeps , projectFlags = flags , projectResolver = resolver , projectCompiler = compiler , projectExtraPackageDBs = extraPackageDBs } return $ ProjectAndConfigMonoid project config where goDeps = map toSingle . Map.toList . Map.unionsWith Set.union . map toMap where toMap i = Map.singleton (packageIdentifierName i) (Set.singleton (packageIdentifierVersion i)) toSingle (k, s) = case Set.toList s of [x] -> Right (k, x) xs -> Left $ concat [ "Multiple versions for package " , packageNameString k , ": " , unwords $ map versionString xs ] -- | A PackageEntry for the current directory, used as a default packageEntryCurrDir :: PackageEntry packageEntryCurrDir = PackageEntry { peValidWanted = Nothing , peExtraDepMaybe = Nothing , peLocation = PLFilePath "." , peSubdirs = [] } -- | A software control system. data SCM = Git deriving (Show) instance FromJSON SCM where parseJSON v = do s <- parseJSON v case s of "git" -> return Git _ -> fail ("Unknown or unsupported SCM: " <> s) instance ToJSON SCM where toJSON Git = toJSON ("git" :: Text) -- | A variant of the platform, used to differentiate Docker builds from host data PlatformVariant = PlatformVariantNone | PlatformVariant String -- | Render a platform variant to a String suffix. platformVariantSuffix :: PlatformVariant -> String platformVariantSuffix PlatformVariantNone = "" platformVariantSuffix (PlatformVariant v) = "-" ++ v -- | Specialized bariant of GHC (e.g. libgmp4 or integer-simple) data GHCVariant = GHCStandard -- ^ Standard bindist | GHCGMP4 -- ^ Bindist that supports libgmp4 (centos66) | GHCArch -- ^ Bindist built on Arch Linux (bleeding-edge) | GHCIntegerSimple -- ^ Bindist that uses integer-simple | GHCCustom String -- ^ Other bindists deriving (Show) instance FromJSON GHCVariant where -- Strange structuring is to give consistent error messages parseJSON = withText "GHCVariant" (either (fail . show) return . parseGHCVariant . T.unpack) -- | Render a GHC variant to a String. ghcVariantName :: GHCVariant -> String ghcVariantName GHCStandard = "standard" ghcVariantName GHCGMP4 = "gmp4" ghcVariantName GHCArch = "arch" ghcVariantName GHCIntegerSimple = "integersimple" ghcVariantName (GHCCustom name) = "custom-" ++ name -- | Render a GHC variant to a String suffix. ghcVariantSuffix :: GHCVariant -> String ghcVariantSuffix GHCStandard = "" ghcVariantSuffix v = "-" ++ ghcVariantName v -- | Parse GHC variant from a String. parseGHCVariant :: (MonadThrow m) => String -> m GHCVariant parseGHCVariant s = case stripPrefix "custom-" s of Just name -> return (GHCCustom name) Nothing | s == "" -> return GHCStandard | s == "standard" -> return GHCStandard | s == "gmp4" -> return GHCGMP4 | s == "arch" -> return GHCArch | s == "integersimple" -> return GHCIntegerSimple | otherwise -> return (GHCCustom s) -- | Information for a file to download. data DownloadInfo = DownloadInfo { downloadInfoUrl :: Text , downloadInfoContentLength :: Maybe Int , downloadInfoSha1 :: Maybe ByteString } deriving (Show) instance FromJSON (DownloadInfo, [JSONWarning]) where parseJSON = withObjectWarnings "DownloadInfo" parseDownloadInfoFromObject -- | Parse JSON in existing object for 'DownloadInfo' parseDownloadInfoFromObject :: Object -> WarningParser DownloadInfo parseDownloadInfoFromObject o = do url <- o ..: "url" contentLength <- o ..:? "content-length" sha1TextMay <- o ..:? "sha1" return DownloadInfo { downloadInfoUrl = url , downloadInfoContentLength = contentLength , downloadInfoSha1 = fmap encodeUtf8 sha1TextMay } data VersionedDownloadInfo = VersionedDownloadInfo { vdiVersion :: Version , vdiDownloadInfo :: DownloadInfo } deriving Show instance FromJSON (VersionedDownloadInfo, [JSONWarning]) where parseJSON = withObjectWarnings "VersionedDownloadInfo" $ \o -> do version <- o ..: "version" downloadInfo <- parseDownloadInfoFromObject o return VersionedDownloadInfo { vdiVersion = version , vdiDownloadInfo = downloadInfo } data SetupInfo = SetupInfo { siSevenzExe :: Maybe DownloadInfo , siSevenzDll :: Maybe DownloadInfo , siMsys2 :: Map Text VersionedDownloadInfo , siGHCs :: Map Text (Map Version DownloadInfo) , siGHCJSs :: Map Text (Map CompilerVersion DownloadInfo) , siStack :: Map Text (Map Version DownloadInfo) } deriving Show instance FromJSON (SetupInfo, [JSONWarning]) where parseJSON = withObjectWarnings "SetupInfo" $ \o -> do siSevenzExe <- jsonSubWarningsT (o ..:? "sevenzexe-info") siSevenzDll <- jsonSubWarningsT (o ..:? "sevenzdll-info") siMsys2 <- jsonSubWarningsT (o ..:? "msys2" ..!= mempty) siGHCs <- jsonSubWarningsTT (o ..:? "ghc" ..!= mempty) siGHCJSs <- jsonSubWarningsTT (o ..:? "ghcjs" ..!= mempty) siStack <- jsonSubWarningsTT (o ..:? "stack" ..!= mempty) return SetupInfo {..} -- | For @siGHCs@ and @siGHCJSs@ fields maps are deeply merged. -- For all fields the values from the last @SetupInfo@ win. instance Monoid SetupInfo where mempty = SetupInfo { siSevenzExe = Nothing , siSevenzDll = Nothing , siMsys2 = Map.empty , siGHCs = Map.empty , siGHCJSs = Map.empty , siStack = Map.empty } mappend l r = SetupInfo { siSevenzExe = siSevenzExe r <|> siSevenzExe l , siSevenzDll = siSevenzDll r <|> siSevenzDll l , siMsys2 = siMsys2 r <> siMsys2 l , siGHCs = Map.unionWith (<>) (siGHCs r) (siGHCs l) , siGHCJSs = Map.unionWith (<>) (siGHCJSs r) (siGHCJSs l) , siStack = Map.unionWith (<>) (siStack l) (siStack r) } -- | Remote or inline 'SetupInfo' data SetupInfoLocation = SetupInfoFileOrURL String | SetupInfoInline SetupInfo deriving (Show) instance FromJSON (SetupInfoLocation, [JSONWarning]) where parseJSON v = ((, []) <$> withText "SetupInfoFileOrURL" (pure . SetupInfoFileOrURL . T.unpack) v) <|> inline where inline = do (si,w) <- parseJSON v return (SetupInfoInline si, w) -- | How PVP bounds should be added to .cabal files data PvpBounds = PvpBoundsNone | PvpBoundsUpper | PvpBoundsLower | PvpBoundsBoth deriving (Show, Read, Eq, Typeable, Ord, Enum, Bounded) pvpBoundsText :: PvpBounds -> Text pvpBoundsText PvpBoundsNone = "none" pvpBoundsText PvpBoundsUpper = "upper" pvpBoundsText PvpBoundsLower = "lower" pvpBoundsText PvpBoundsBoth = "both" parsePvpBounds :: Text -> Either String PvpBounds parsePvpBounds t = case Map.lookup t m of Nothing -> Left $ "Invalid PVP bounds: " ++ T.unpack t Just x -> Right x where m = Map.fromList $ map (pvpBoundsText &&& id) [minBound..maxBound] instance ToJSON PvpBounds where toJSON = toJSON . pvpBoundsText instance FromJSON PvpBounds where parseJSON = withText "PvpBounds" (either fail return . parsePvpBounds) -- | Provide an explicit list of package dependencies when running a custom Setup.hs explicitSetupDeps :: (MonadReader env m, HasConfig env) => PackageName -> m Bool explicitSetupDeps name = do m <- asks $ configExplicitSetupDeps . getConfig return $ -- Yes there are far cleverer ways to write this. I honestly consider -- the explicit pattern matching much easier to parse at a glance. case Map.lookup (Just name) m of Just b -> b Nothing -> case Map.lookup Nothing m of Just b -> b Nothing -> False -- default value -- | Data passed into Docker container for the Docker entrypoint's use data DockerEntrypoint = DockerEntrypoint { deUidGid :: !(Maybe (UserID, GroupID)) -- ^ UID/GID of host user, if we wish to perform UID/GID switch in container } deriving (Read,Show)
keent/stack
src/Stack/Types/Config.hs
bsd-3-clause
64,972
0
17
15,156
12,416
6,711
5,705
1,411
8
{-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, UndecidableInstances, TypeOperators, ScopedTypeVariables, TypeSynonymInstances, ConstraintKinds #-} module Functions.Comp.Eval where import DataTypes.Comp import Functions.Comp.Desugar import Data.Comp import Data.Comp.Thunk hiding (eval, eval2) import Data.Comp.Derive import Control.Monad -- evaluation with thunks class (Monad m, Traversable v) => EvalT e v m where evalTAlg :: AlgT m e v evalT :: (EvalT e v m, Functor e) => Term e -> m (Term v) evalT = nf . cata evalTAlg $(derive [liftSum] [''EvalT]) instance (Monad m, Traversable v, Value :<: m :+: v) => EvalT Value v m where evalTAlg = inject instance (Value :<: (m :+: v), Value :<: v, Traversable v, EqF v, Monad m) => EvalT Op v m where evalTAlg (Plus x y) = thunk $ do VInt i <- whnfPr x VInt j <- whnfPr y return $ iVInt (i+j) evalTAlg (Mult x y) = thunk $ do VInt i <- whnfPr x VInt j <- whnfPr y return $ iVInt (i*j) evalTAlg (If x y z) = thunk $ do VBool b <- whnfPr x return $ if b then y else z evalTAlg (Eq x y) = thunk $ liftM iVBool $ eqT x y evalTAlg (Lt x y) = thunk $ do VInt i <- whnfPr x VInt j <- whnfPr y return $ iVBool (i < j) evalTAlg (And x y) = thunk $ do VBool b1 <- whnfPr x if b1 then do VBool b2 <- whnfPr y return $ iVBool b2 else return $ iVBool False evalTAlg (Not x) = thunk $ do VBool b <- whnfPr x return $ iVBool (not b) evalTAlg (Proj p x) = thunk $ do VPair a b <- whnfPr x return $ select a b where select x y = case p of ProjLeft -> x ProjRight -> y instance (Value :<: (m :+: v), Value :<: v, Traversable v, Monad m) => EvalT Sugar v m where evalTAlg (Neg x) = thunk $ do VInt i <- whnfPr x return $ iVInt (-i) evalTAlg (Minus x y) = thunk $ do VInt i <- whnfPr x VInt j <- whnfPr y return $ iVInt (i-j) evalTAlg (Gt x y) = thunk $ do VInt i <- whnfPr x VInt j <- whnfPr y return $ iVBool (i > j) evalTAlg (Or x y) = thunk $ do VBool b1 <- whnfPr x if b1 then return $ iVBool True else do VBool b2 <- whnfPr y return $ iVBool b2 evalTAlg (Impl x y) = thunk $ do VBool b1 <- whnfPr x if b1 then do VBool b2 <- whnfPr y return $ iVBool b2 else return $ iVBool True -- evaluation class Monad m => Eval e v m where evalAlg :: e (Term v) -> m (Term v) eval :: (Traversable e, Eval e v m) => Term e -> m (Term v) eval = cataM evalAlg $(derive [liftSum] [''Eval]) instance (Value :<: v, Monad m) => Eval Value v m where evalAlg = return . inject coerceInt :: (Value :<: v, Monad m) => Term v -> m Int coerceInt t = case project t of Just (VInt i) -> return i _ -> fail "" coerceBool :: (Value :<: v, Monad m) => Term v -> m Bool coerceBool t = case project t of Just (VBool b) -> return b _ -> fail "" coercePair :: (Value :<: v, Monad m) => Term v -> m (Term v, Term v) coercePair t = case project t of Just (VPair x y) -> return (x,y) _ -> fail "" instance (Value :<: v, EqF v, Monad m) => Eval Op v m where evalAlg (Plus x y) = liftM2 (\ i j -> iVInt (i + j)) (coerceInt x) (coerceInt y) evalAlg (Mult x y) = liftM2 (\ i j -> iVInt (i * j)) (coerceInt x) (coerceInt y) evalAlg (If b x y) = liftM select (coerceBool b) where select b' = if b' then x else y evalAlg (Eq x y) = return $ iVBool (x == y) evalAlg (Lt x y) = liftM2 (\ i j -> iVBool (i < j)) (coerceInt x) (coerceInt y) evalAlg (And x y) = liftM2 (\ b c -> iVBool (b && c)) (coerceBool x) (coerceBool y) evalAlg (Not x) = liftM (iVBool . not) (coerceBool x) evalAlg (Proj p x) = liftM select (coercePair x) where select (x,y) = case p of ProjLeft -> x ProjRight -> y instance (Value :<: v, Monad m) => Eval Sugar v m where evalAlg (Neg x) = liftM (iVInt . negate) (coerceInt x) evalAlg (Minus x y) = liftM2 (\ i j -> iVInt (i - j)) (coerceInt x) (coerceInt y) evalAlg (Gt x y) = liftM2 (\ i j -> iVBool (i > j)) (coerceInt x) (coerceInt y) evalAlg (Or x y) = liftM2 (\ b c -> iVBool (b || c)) (coerceBool x) (coerceBool y) evalAlg (Impl x y) = liftM2 (\ b c -> iVBool (not b || c)) (coerceBool x) (coerceBool y) -- direct evaluation class Monad m => EvalDir e m where evalDir :: (Traversable f, EvalDir f m) => e (Term f) -> m ValueExpr evalDirect :: (Traversable e, EvalDir e m) => Term e -> m ValueExpr evalDirect = evalDir . unTerm evalDirectE :: SugarExpr -> Err ValueExpr evalDirectE = evalDirect $(derive [liftSum] [''EvalDir]) instance (Monad m) => EvalDir Value m where evalDir (VInt i) = return $ iVInt i evalDir (VBool i) = return $ iVBool i evalDir (VPair x y) = liftM2 iVPair (evalDirect x) (evalDirect y) evalInt :: (Traversable e, EvalDir e m) => Term e -> m Int evalInt t = do t' <- evalDirect t case project t' of Just (VInt i) -> return i _ -> fail "" evalBool :: (Traversable e, EvalDir e m) => Term e -> m Bool evalBool t = do t' <- evalDirect t case project t' of Just (VBool b) -> return b _ -> fail "" evalPair :: (Traversable e, EvalDir e m) => Term e -> m (ValueExpr, ValueExpr) evalPair t = do t' <- evalDirect t case project t' of Just (VPair x y) -> return (x,y) _ -> fail "" instance (Monad m) => EvalDir Op m where evalDir (Plus x y) = liftM2 (\ i j -> iVInt (i + j)) (evalInt x) (evalInt y) evalDir (Mult x y) = liftM2 (\ i j -> iVInt (i * j)) (evalInt x) (evalInt y) evalDir (If b x y) = do b' <- evalBool b if b' then evalDirect x else evalDirect y evalDir (Eq x y) = liftM iVBool $ liftM2 (==) (evalDirect x) (evalDirect y) evalDir (Lt x y) = liftM2 (\ i j -> iVBool (i < j)) (evalInt x) (evalInt y) evalDir (And x y) = liftM2 (\ b c -> iVBool (b && c)) (evalBool x) (evalBool y) evalDir (Not x) = liftM (iVBool . not) (evalBool x) evalDir (Proj p x) = liftM select (evalPair x) where select (x,y) = case p of ProjLeft -> x ProjRight -> y instance (Monad m) => EvalDir Sugar m where evalDir (Neg x) = liftM (iVInt . negate) (evalInt x) evalDir (Minus x y) = liftM2 (\ i j -> iVInt (i - j)) (evalInt x) (evalInt y) evalDir (Gt x y) = liftM2 (\ i j -> iVBool (i > j)) (evalInt x) (evalInt y) evalDir (Or x y) = liftM2 (\ b c -> iVBool (b || c)) (evalBool x) (evalBool y) evalDir (Impl x y) = liftM2 (\ b c -> iVBool (not b || c)) (evalBool x) (evalBool y) -- evaluation2 class Functor e => Eval2 e v where eval2Alg :: e (Term v) -> Term v eval2 :: (Functor e, Eval2 e v) => Term e -> Term v eval2 = cata eval2Alg $(derive [liftSum] [''Eval2]) instance (Value :<: v) => Eval2 Value v where eval2Alg = inject coerceInt2 :: (Value :<: v) => Term v -> Int coerceInt2 t = case project t of Just (VInt i) -> i _ -> undefined coerceBool2 :: (Value :<: v) => Term v -> Bool coerceBool2 t = case project t of Just (VBool b) -> b _ -> undefined coercePair2 :: (Value :<: v) => Term v -> (Term v, Term v) coercePair2 t = case project t of Just (VPair x y) -> (x,y) _ -> undefined instance (Value :<: v, EqF v) => Eval2 Op v where eval2Alg (Plus x y) = (\ i j -> iVInt (i + j)) (coerceInt2 x) (coerceInt2 y) eval2Alg (Mult x y) = (\ i j -> iVInt (i * j)) (coerceInt2 x) (coerceInt2 y) eval2Alg (If b x y) = select (coerceBool2 b) where select b' = if b' then x else y eval2Alg (Eq x y) = iVBool (x == y) eval2Alg (Lt x y) = (\ i j -> iVBool (i < j)) (coerceInt2 x) (coerceInt2 y) eval2Alg (And x y) = (\ b c -> iVBool (b && c)) (coerceBool2 x) (coerceBool2 y) eval2Alg (Not x) = (iVBool . not) (coerceBool2 x) eval2Alg (Proj p x) = select (coercePair2 x) where select (x,y) = case p of ProjLeft -> x ProjRight -> y instance (Value :<: v) => Eval2 Sugar v where eval2Alg (Neg x) = (iVInt . negate) (coerceInt2 x) eval2Alg (Minus x y) = (\ i j -> iVInt (i - j)) (coerceInt2 x) (coerceInt2 y) eval2Alg (Gt x y) = (\ i j -> iVBool (i > j)) (coerceInt2 x) (coerceInt2 y) eval2Alg (Or x y) = (\ b c -> iVBool (b || c)) (coerceBool2 x) (coerceBool2 y) eval2Alg (Impl x y) = (\ b c -> iVBool (not b || c)) (coerceBool2 x) (coerceBool2 y) -- direct evaluation 2 class EvalDir2 e where evalDir2 :: (EvalDir2 f) => e (Term f) -> ValueExpr evalDirect2 :: (EvalDir2 e) => Term e -> ValueExpr evalDirect2 = evalDir2 . unTerm evalDirectE2 :: SugarExpr -> ValueExpr evalDirectE2 = evalDirect2 $(derive [liftSum] [''EvalDir2]) instance EvalDir2 Value where evalDir2 (VInt i) = iVInt i evalDir2 (VBool i) = iVBool i evalDir2 (VPair x y) = iVPair (evalDirect2 x) (evalDirect2 y) evalInt2 :: (EvalDir2 e) => Term e -> Int evalInt2 t = case project (evalDirect2 t) of Just (VInt i) -> i _ -> error "" evalBool2 :: (EvalDir2 e) => Term e -> Bool evalBool2 t = case project (evalDirect2 t) of Just (VBool b) -> b _ -> error "" evalPair2 :: (EvalDir2 e) => Term e -> (ValueExpr, ValueExpr) evalPair2 t = case project (evalDirect2 t) of Just (VPair x y) -> (x,y) _ -> error "" instance EvalDir2 Op where evalDir2 (Plus x y) = (\ i j -> iVInt (i + j)) (evalInt2 x) (evalInt2 y) evalDir2 (Mult x y) = (\ i j -> iVInt (i * j)) (evalInt2 x) (evalInt2 y) evalDir2 (If b x y) = if evalBool2 b then evalDirect2 x else evalDirect2 y evalDir2 (Eq x y) = iVBool $ (==) (evalDirect2 x) (evalDirect2 y) evalDir2 (Lt x y) = (\ i j -> iVBool (i < j)) (evalInt2 x) (evalInt2 y) evalDir2 (And x y) = (\ b c -> iVBool (b && c)) (evalBool2 x) (evalBool2 y) evalDir2 (Not x) = (iVBool . not) (evalBool2 x) evalDir2 (Proj p x) = select (evalPair2 x) where select (x,y) = case p of ProjLeft -> x ProjRight -> y instance EvalDir2 Sugar where evalDir2 (Neg x) = (iVInt . negate) (evalInt2 x) evalDir2 (Minus x y) = (\ i j -> iVInt (i - j)) (evalInt2 x) (evalInt2 y) evalDir2 (Gt x y) = (\ i j -> iVBool (i > j)) (evalInt2 x) (evalInt2 y) evalDir2 (Or x y) = (\ b c -> iVBool (b || c)) (evalBool2 x) (evalBool2 y) evalDir2 (Impl x y) = (\ b c -> iVBool (not b || c)) (evalBool2 x) (evalBool2 y) -- desugar desugEval :: SugarExpr -> Err ValueExpr desugEval = eval . (desug :: SugarExpr -> Expr) desugEvalT :: SugarExpr -> Err ValueExpr desugEvalT = evalT . (desug :: SugarExpr -> Expr) evalSugar :: SugarExpr -> Err ValueExpr evalSugar = eval evalSugarT :: SugarExpr -> Err ValueExpr evalSugarT = evalT desugEvalAlg :: AlgM Err SugarSig ValueExpr desugEvalAlg = evalAlg `compAlgM'` (desugAlg :: Hom SugarSig ExprSig) desugEval' :: SugarExpr -> Err ValueExpr desugEval' = cataM desugEvalAlg desugEvalAlgT :: AlgT Err SugarSig Value desugEvalAlgT = evalTAlg `compAlg` (desugAlg :: Hom SugarSig ExprSig) desugEvalT' :: SugarExpr -> Err ValueExpr desugEvalT' = nf . cata desugEvalAlgT desugEval2 :: SugarExpr -> ValueExpr desugEval2 = eval2 . (desug :: SugarExpr -> Expr) evalSugar2 :: SugarExpr -> ValueExpr evalSugar2 = eval2 desugEval2Alg :: Alg SugarSig ValueExpr desugEval2Alg = eval2Alg `compAlg` (desugAlg :: Hom SugarSig ExprSig) desugEval2' :: SugarExpr -> ValueExpr desugEval2' = cata desugEval2Alg
spacekitteh/compdata
benchmark/Functions/Comp/Eval.hs
bsd-3-clause
12,730
0
13
4,341
5,710
2,846
2,864
270
2
module FunctionUsagesInMultipleFiles00001 where import FunctionUsagesInSingleFile00001 thisFile :: () thisFile = <caret>boring name :: String name = "Testsuite"
KasperJanssens/intellij-haskforce
tests/gold/codeInsight/FunctionUsagesInMultipleFiles00001.hs
apache-2.0
164
2
5
20
35
21
14
-1
-1
import KMeansCore import Data.Random.Normal import System.Random import System.IO import Data.Array import System.Environment import Control.Monad import Data.List import Data.Binary minX, maxX, minY, maxY, minSD, maxSD :: Double minX = -10 maxX = 10 minY = -10 maxY = 10 minSD = 1.5 maxSD = 2.0 main = do n: minp: maxp: rest <- fmap (fmap read) getArgs case rest of [seed] -> setStdGen (mkStdGen seed) _ -> return () nps <- replicateM n (randomRIO (minp, maxp)) xs <- replicateM n (randomRIO (minX, maxY)) ys <- replicateM n (randomRIO (minX, maxY)) sds <- replicateM n (randomRIO (minSD, maxSD)) let params = zip5 nps xs ys sds sds -- first generate a set of points for each set of sample parameters ss <- mapM (\(a,b,c,d,e) -> generate2DSamples a b c d e) params let points = concat ss -- dump all the points into the file "points" hsamp <- openFile "points" WriteMode mapM_ (printPoint hsamp) points hClose hsamp encodeFile "points.bin" points -- generate the initial clusters by assigning each point to random -- cluster. gen <- newStdGen let rand_clusters = randomRs (0,n-1) gen :: [Int] arr = accumArray (flip (:)) [] (0,n-1) $ zip rand_clusters points clusters = map (uncurry makeCluster) (assocs arr) writeFile "clusters" (show clusters) -- so we can tell what the answer should be: writeFile "params" (show params) printPoint :: Handle -> Point -> IO () printPoint h (Point x y) = do hPutStr h (show x) hPutChar h ' ' hPutStr h (show y) hPutChar h '\n' generate2DSamples :: Int -- number of samples to generate -> Double -> Double -- X and Y of the mean -> Double -> Double -- X and Y standard deviations -> IO [Point] generate2DSamples n mx my sdx sdy = do gen <- newStdGen let (genx, geny) = split gen xsamples = normals' (mx,sdx) genx ysamples = normals' (my,sdy) geny return (zipWith Point (take n xsamples) ysamples)
prt2121/haskell-practice
parconc/kmeans/GenSamples.hs
apache-2.0
2,094
2
13
577
728
370
358
56
2
import PPfeMain(mainPFE) import PPfeInstances import PfeInteractive(pfeiAllCmds) import PPfeCmds(ppfeCmds) --import TraceIO(traceIO) --main = traceIO main' main = mainPFE (pfeiAllCmds ppfeCmds)
forste/haReFork
tools/property/ppfe.hs
bsd-3-clause
197
0
7
22
44
26
18
5
1
{-# LANGUAGE GADTs #-} module T14978 where data Equal a b where Refl :: Equal a a data Goof a where Goof :: {-# UNPACK #-} !(Equal a Int) -> Goof a foo :: Goof Int foo = Goof Refl
sdiehl/ghc
testsuite/tests/simplCore/should_compile/T14978.hs
bsd-3-clause
189
0
9
49
64
37
27
8
1
-- Who likes it? -- http://www.codewars.com/kata/5266876b8f4bf2da9b000362/ module Likes where likes :: [String] -> String likes [] = "no one likes this" likes [x] = x ++ " likes this" likes (x:x':[]) = x ++ " and " ++ x' ++ " like this" likes (x:x':x'':[]) = x ++ ", " ++ x' ++ " and " ++ x'' ++ " like this" likes (x:x':xs) = x ++ ", " ++ x' ++ " and " ++ (show . length $ xs) ++ " others like this"
gafiatulin/codewars
src/6 kyu/Likes.hs
mit
403
0
10
88
171
91
80
7
1
{-# LANGUAGE RecordWildCards #-} module Actor.Conductor ( ) where import Control.Distributed.Process hiding (call) import Control.Distributed.Process.Platform.ManagedProcess import Data.Binary (Binary) import Data.Data import Data.Typeable import GHC.Generics import Actor.Types
neight-allen/lonelycyberwolf
src/Actor/Conductor.hs
mit
494
0
5
241
60
39
21
11
0
module Cook.Recipe.FsTree ( FsTree (..) , Content (..) , defAttrs , createFsTree ) where import Data.Aeson import Data.ByteString (ByteString) import Data.Default.Class import Data.Foldable import Data.Text (Text) import System.Directory import System.FilePath import System.Posix.Files import System.Posix.Types import System.Posix.User import qualified Data.Text.IO as T import Cook.Recipe.Template type Attrs = (Maybe FileMode, Maybe (String, String)) data Content where Copy :: FilePath -> Content Template :: ToJSON a => String -> ByteString -> a -> Content Content :: Text -> Content data FsTree = File FilePath Content Attrs | Mode FilePath Attrs | Dir FilePath Attrs [FsTree] | DirEmpty FilePath Attrs defAttrs :: Attrs defAttrs = def createFsTree :: FilePath -> FsTree -> IO () createFsTree base fstree = do createFile base fstree applyAttrs base fstree createFile :: FilePath -> FsTree -> IO () createFile base (File name (Content txt) _) = T.writeFile (base </> name) txt createFile base (File name (Copy src) _) = copyFile src (base </> name) createFile base (File name (Template tname tmpl conf) attrs) = do result <- useTemplateWith tname tmpl conf createFile base (File name (Content result) attrs) createFile _ (Mode _ _) = return () createFile base (DirEmpty name _) = mkdir (base </> name) createFile base (Dir name _ subtree) = do mkdir (base </> name) mapM_ (createFile $ base </> name) subtree applyAttrs :: FilePath -> FsTree -> IO () applyAttrs base (File name _ attrs) = useAttrs (base </> name) attrs applyAttrs base (Mode name attrs) = useAttrs (base </> name) attrs applyAttrs base (DirEmpty name attrs) = useAttrs (base </> name) attrs applyAttrs base (Dir name attrs subtree) = do useAttrs (base </> name) attrs mapM_ (applyAttrs $ base </> name) subtree useAttrs :: FilePath -> Attrs -> IO () useAttrs path (mode, perm) = do forM_ mode (chmod path) forM_ perm (uncurry $ chown path) mkdir :: FilePath -> IO () mkdir = createDirectoryIfMissing True chmod :: FilePath -> FileMode -> IO () chmod path mode | mode > 0o7777 = error "FsTree.chmod: invalid mode" | otherwise = setFileMode path mode chown :: FilePath -> String -> String -> IO () chown path user group = do uentry <- getUserEntryForName user gentry <- getGroupEntryForName group setOwnerAndGroup path (userID uentry) (groupID gentry)
jimenezrick/cook.hs
src/Cook/Recipe/FsTree.hs
mit
2,615
0
11
660
921
472
449
-1
-1
module Server where import Control.Concurrent.Async import Control.Exception (bracket, handleJust) import Control.Monad (guard, void, when) import Control.Monad.IfElse (whenM) import Control.Monad.Loops (iterateWhile) import Control.Proxy import Control.Proxy.Concurrent (atomically, recvS, send, sendD) import Control.Proxy.Trans.Maybe import Data.Maybe import GHC.IO.Exception (IOErrorType (ResourceVanished)) import qualified Network as N import qualified Network.Socket as N hiding (accept) import System.Directory (doesFileExist, removeFile) import System.Exit (ExitCode (ExitSuccess)) import System.IO import System.IO.Error (ioeGetErrorType) import CommandLoop import Types import Util withSocket :: FilePath -> (N.Socket -> IO a) -> IO a withSocket sock = bracket (createListenSocket sock) (cleanupSocket sock) cleanupSocket :: FilePath -> N.Socket -> IO () cleanupSocket sockFile sock = do N.close sock whenM (doesFileExist sockFile) $ removeFile sockFile createListenSocket :: FilePath -> IO N.Socket createListenSocket socketPath = N.listenOn (N.UnixSocket socketPath) acceptOne :: N.Socket -> (Handle -> IO a) -> IO a acceptOne sock action = do (clientHandle,_,_) <- N.accept sock action clientHandle ignoreEPipe :: a -> IO a -> IO a ignoreEPipe d = handleJust (guard . isEPipe) (const $ return d) where isEPipe e = ioeGetErrorType e == ResourceVanished processRequest :: (Proxy p) => () -> Pipe (MaybeP p) String (Either ClientDirective CommandObj) IO () processRequest () = forever $ do let logmsg = respond . Left . ClientLog "processRequest" logmsg "Waiting for requests" line <- request () logmsg "Received request" case readMaybe line of Just (SrvCommand cmd ghcOpts) -> respond $ Right (cmd, ghcOpts) Just SrvStatus -> do respond $ Left $ ClientStdout "Server is running" respond $ Left $ ClientExit ExitSuccess Just SrvExit -> do respond $ Left $ ClientLog "processRequest" "Shutting server down" respond $ Left $ ClientExit ExitSuccess nothing Nothing -> respond $ Left $ ClientUnexpectedError $ "The client sent an invalid message to the server: " ++ line isClientExit :: ClientDirective -> Bool isClientExit (ClientExit _) = True isClientExit _ = False takeWhileInclusiveD :: (Proxy p, Monad m) => (a -> Bool) -> a' -> p a' a a' a m () takeWhileInclusiveD p = runIdentityK go where go a' = do a <- request a' a'2 <- respond a when (p a) $ go a'2 startServer :: Maybe FilePath -> N.Socket -> IO () startServer cabal sock = do (inp,outp,rawi) <- setupCommandLoop cabal [] void $ iterateWhile id $ acceptOne sock $ \clientHandle -> ignoreEPipe True $ do void $ atomically $ send rawi $ ClientLog "startServer" "New client connection" a <- async $ runProxy $ recvS outp >-> takeWhileInclusiveD (not . isClientExit) >-> mapD show >-> hPutStrLnD clientHandle r <- runProxy $ runMaybeK $ hGetLineS clientHandle >-> processRequest >-> leftD (sendD rawi) >-> rightD (sendD inp) do void $ atomically $ send rawi $ ClientLog "startServer" "Waiting for end of send process" wait a return (isJust r)
bennofs/hdevtools
src/Server.hs
mit
3,425
0
18
859
1,098
549
549
72
4
{-# OPTIONS_GHC -fno-warn-unused-imports #-} {-| Use @threads-supervisor@ if you want the "poor-man's Erlang supervisors". @threads-supervisor@ is an IO-based library with minimal dependencies which does only one thing: It provides you a 'Supervisor' entity you can use to monitor your forked computations. If one of the managed threads dies, you can decide if and how to restart it. This gives you: * Protection against silent exceptions which might terminate your workers. * A simple but powerful way of structure your program into a supervision tree, where the leaves are the worker threads, and the nodes can be other supervisors being monitored. * A disaster recovery mechanism. You can install the @threads-supervisor@ library by running: > $ cabal install threads-supervisor -} module Control.Concurrent.Supervisor.Tutorial ( -- * Introduction -- $introduction -- * Different type of jobs -- $jobs -- * Creating a Supervisor -- $createSupervisor -- * Bounded vs Unbounded -- $boundedVsUnbounded -- * Supervising and choosing a 'RestartStrategy' -- $supervising -- * Wrapping up -- $conclusions ) where -- $introduction -- Who worked with Haskell's concurrency primitives would be surely familiar -- with the `forkIO` function, which allow us to fork an IO computation in a separate -- green thread. `forkIO` is great, but is also very low level, and has a -- couple of subtleties, as you can read from this passage of the documentation: -- -- The newly created thread has an exception handler that discards the exceptions -- `BlockedIndefinitelyOnMVar`,`BlockedIndefinitelyOnSTM`, and `ThreadKilled`, -- and passes all other exceptions to the uncaught exception handler. -- -- To mitigate this, we have a couple of libraries available, for example -- <http://hackage.haskell.org/package/async> and <http://hackage.haskell.org/package/slave-thread>. -- -- But what about if I do not want to take explicit action, but instead specifying upfront -- how to react to disaster, and leave the library work out the details? -- This is what this library aims to do. -- $jobs -- In this example, let's create four different threads: -- -- > job1 :: IO () -- > job1 = do -- > threadDelay 5000000 -- > fail "Dead" -- This job will die after five seconds. -- -- > job2 :: ThreadId -> IO () -- > job2 tid = do -- > threadDelay 3000000 -- > killThread tid -- -- This other job instead, we have waited three seconds, and then kill a target thread, -- generating an asynchronous exception. -- -- > job3 :: IO () -- > job3 = do -- > threadDelay 5000000 -- > error "Oh boy, I'm good as dead" -- -- This guy is very similar to the first one, except for the fact `error` is used instead of `fail`. -- -- > job4 :: IO () -- > job4 = threadDelay 7000000 -- @job4@ is what we wish for all our passing cross computation: smooth sailing. -- -- These jobs represent a significant pool of our everyday computations in the IO monad -- $createSupervisor -- Creating a 'Supervisor' is as simple as calling `newSupervisor`, specifying the `RestartStrategy` -- you want to use as well as the size of the `EventStream` (this depends whether you are using a Bounded -- supervisor or not). -- Immediately after doing so, a new thread will be started, monitoring any subsequent IO actions -- submitted to it. -- $boundedVsUnbounded -- By default, it's programmer responsibility to read the `SupervisionEvent` the library writes -- into its internal queue. If you do not do so, your program might leak. To mitigate this, and -- to offer a more granular control, two different modules are provided: a `Bounded` and an -- `Unbounded` one, which use, respectively, a `TBQueue` or a `TQueue` underneath. You can decide -- to go with the bounded version, with a queue size enforced by the library author, or pass in -- your own size. -- $supervising -- Let's wrap everything together into a full blown example: -- -- > main :: IO () -- > main = bracketOnError (do -- > -- > sup1 <- newSupervisor OneForOne -- > sup2 <- newSupervisor OneForOne -- > -- > monitorWith fibonacciRetryPolicy sup1 sup2 -- > -- > _ <- forkSupervised sup2 fibonacciRetryPolicy job3 -- > -- > j1 <- forkSupervised sup1 fibonacciRetryPolicy job1 -- > _ <- forkSupervised sup1 fibonacciRetryPolicy (job2 j1) -- > _ <- forkSupervised sup1 fibonacciRetryPolicy job4 -- > _ <- forkIO (go (eventStream sup1)) -- > return sup1) shutdownSupervisor (\_ -> threadDelay 10000000000) -- > where -- > go eS = do -- > newE <- atomically $ readTBQueue eS -- > print newE -- > go eS -- -- What we have done here, was to spawn two supervisors and we have used -- our swiss knife `forkSupervised` to spawn four supervised -- IO computations. As you can see, if we partially apply `forkSupervised`, -- its type resemble `forkIO` one; this is by design, as we want to keep -- this API as IO-friendly as possible. -- Note also how we can ask the first supervisor to monitor the second one. -- -- `fibonacciRetryPolicy` is a constructor for the `RetryPolicy`, which creates -- under the hood a `RetryPolicy` from the "retry" package which is using -- the `fibonacciBackoff`. The clear advantage is that you are not obliged to use -- it if you don't like this sensible default; -- `RetryPolicy` is an monoid, so you can compose retry policies as you wish. -- -- The `RetryPolicy` will also be responsible for determining whether a thread can be -- restarted or not; in the latter case you will find a `ChildRestartedLimitReached` -- in your event log. -- -- If you run this program, hopefully you should see on stdout -- something like this: -- -- > ChildBorn ThreadId 62 2015-02-13 11:51:15.293882 UTC -- > ChildBorn ThreadId 63 2015-02-13 11:51:15.293897 UTC -- > ChildBorn ThreadId 64 2015-02-13 11:51:15.293904 UTC -- > ChildDied ThreadId 61 (MonitoredSupervision ThreadId 61) 2015-02-13 11:51:15.293941 UTC -- > ChildBorn ThreadId 65 2015-02-13 11:51:15.294014 UTC -- > ChildFinished ThreadId 64 2015-02-13 11:51:18.294797 UTC -- > ChildDied ThreadId 63 thread killed 2015-02-13 11:51:18.294909 UTC -- > ChildDied ThreadId 62 Oh boy, I'm good as dead 2015-02-13 11:51:20.294861 UTC -- > ChildRestarted ThreadId 62 ThreadId 68 OneForOne 2015-02-13 11:51:20.294861 UTC -- > ChildFinished ThreadId 65 2015-02-13 11:51:22.296089 UTC -- > ChildDied ThreadId 68 Oh boy, I'm good as dead 2015-02-13 11:51:25.296189 UTC -- > ChildRestarted ThreadId 68 ThreadId 69 OneForOne 2015-02-13 11:51:25.296189 UTC -- > ChildDied ThreadId 69 Oh boy, I'm good as dead 2015-02-13 11:51:30.297464 UTC -- > ChildRestarted ThreadId 69 ThreadId 70 OneForOne 2015-02-13 11:51:30.297464 UTC -- > ChildDied ThreadId 70 Oh boy, I'm good as dead 2015-02-13 11:51:35.298123 UTC -- > ChildRestarted ThreadId 70 ThreadId 71 OneForOne 2015-02-13 11:51:35.298123 UTC -- $conclusions -- I hope that you are now convinced that this library can be of some use to you!
adinapoli/threads-supervisor
src/Control/Concurrent/Supervisor/Tutorial.hs
mit
7,018
0
3
1,301
145
142
3
3
0
module Foundation where import Prelude import Yesod import Yesod.Static import Yesod.Auth import Yesod.Auth.BrowserId import Yesod.Default.Config import Yesod.Default.Util (addStaticContentExternal) import Network.HTTP.Client.Conduit (Manager, HasHttpManager (getHttpManager)) import qualified Settings import Settings.Development (development) import qualified Database.Persist import Database.Persist.Sql (SqlPersistT) import Settings.StaticFiles import Settings (widgetFile, Extra (..)) import Model import Text.Hamlet (hamletFile) import Yesod.Fay import Yesod.Core.Types (Logger) import Data.Text -- | The site argument for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { settings :: AppConfig DefaultEnv Extra , getStatic :: Static -- ^ Settings for static file serving. , connPool :: Database.Persist.PersistConfigPool Settings.PersistConf -- ^ Database connection pool. , httpManager :: Manager , persistConfig :: Settings.PersistConf , fayCommandHandler :: CommandHandler App , appLogger :: Logger } instance HasHttpManager App where getHttpManager = httpManager -- Set up i18n messages. See the message folder. mkMessage "App" "messages" "en" -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/routing-and-handlers -- -- Note that this is really half the story; in Application.hs, mkYesodDispatch -- generates the rest of the code. Please see the linked documentation for an -- explanation for this split. mkYesodData "App" $(parseRoutesFile "config/routes") type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where approot = ApprootMaster $ appRoot . settings -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend _ = fmap Just $ defaultClientSessionBackend 120 -- timeout in minutes "config/client_session_key.aes" defaultLayout widget = do master <- getYesod mmsg <- getMessage -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. pc <- widgetToPageContent $ do $(combineStylesheets 'StaticR [ css_normalize_css , css_bootstrap_css ]) $(widgetFile "default-layout") giveUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") -- This is done to provide an optimization for serving static files from -- a separate domain. Please see the staticRoot setting in Settings.hs urlRenderOverride y (StaticR s) = Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s urlRenderOverride _ _ = Nothing -- The page to be redirected to when authentication is required. authRoute _ = Just $ AuthR LoginR -- Routes not requiring authenitcation. isAuthorized (AuthR _) _ = return Authorized isAuthorized FaviconR _ = return Authorized isAuthorized RobotsR _ = return Authorized -- Default to Authorized for now. isAuthorized _ _ = return Authorized -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent = addStaticContentExternal Right genFileName Settings.staticDir (StaticR . flip StaticRoute []) where -- Generate a unique filename based on the content itself genFileName lbs | development = "autogen-" ++ base64md5 lbs | otherwise = base64md5 lbs -- Place Javascript at bottom of the body tag so the rest of the page loads first jsLoader _ = BottomOfBody -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLog _ _source level = development || level == LevelWarn || level == LevelError makeLogger = return . appLogger instance YesodJquery App instance YesodFay App where fayRoute = FaySiteR yesodFayCommand render command = do master <- getYesod fayCommandHandler master render command -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlPersistT runDB = defaultRunDB persistConfig connPool instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner connPool instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest _ = HomeR -- Where to send a user after logout logoutDest _ = HomeR getAuthId creds = runDB $ do x <- getBy $ UniqueUser $ credsIdent creds case x of Just (Entity uid _) -> return $ Just uid Nothing -> do fmap Just $ insert User { userIdent = credsIdent creds , userPassword = Nothing } -- You can add other plugins like BrowserID, email or OAuth here authPlugins _ = [authBrowserId def] authHttpManager = httpManager -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage -- | Get the 'Extra' value, used to hold data from the settings.yml file. getExtra :: Handler Extra getExtra = fmap (appExtra . settings) getYesod -- Note: previous versions of the scaffolding included a deliver function to -- send emails. Unfortunately, there are too many different options for us to -- give a reasonable default. Instead, the information is available on the -- wiki: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email
tagami-keisuke/yesod-blog
Foundation.hs
mit
6,544
0
18
1,481
980
531
449
-1
-1
module Var0 where import Control.Monad.Identity type M a = Identity a showM :: Show a => M a -> String showM = show.runIdentity type Name = String data Term = Var Name | Con Integer | Term :+: Term | Lam Name Term | App Term Term deriving (Show) term0 :: Term term0 = App (Lam "x" (Var "x" :+: Var "x")) (Con 10 :+: Con 11) term21 :: Term term21 = App (Lam "x" (Var "x" :+: Var "y")) (Con 10 :+: Con 11) term22 :: Term term22 = App (Con 7) (Con 2) term23 :: Term term23 = Lam "x" (Var "x" :+: Var "x") :+: Con 11 {- for Variation three term31 :: Term term31 = (Con 1 :+: Con 2) :+: Count -} pgm :: Term pgm = App (Lam "y" (App (App (Lam "f" (Lam "y" (App (Var "f") (Var "y")) ) ) (Lam "x" (Var "x" :+: Var "y") ) ) (Con 3) ) ) (Con 4) data Value = Num Integer | Fun (Value -> M Value) | Wrong instance Show Value where show (Num x) = show x show (Fun _) = "<function>" show Wrong = "<wrong>" type Environment = [(Name, Value)] interp :: Term -> Environment -> M Value interp (Var x) env = lookupM x env interp (Con i) _ = return (Num i) interp (t1 :+: t2) env = do v1 <- interp t1 env v2 <- interp t2 env add v1 v2 interp (Lam x e) env = return $ Fun $ \ v -> interp e ((x,v):env) interp (App t1 t2) env = do f <- interp t1 env v <- interp t2 env apply f v lookupM :: Name -> Environment -> M Value lookupM x env = case lookup x env of Just v -> return v Nothing -> return Wrong add :: Value -> Value -> M Value add (Num i) (Num j) = return (Num (i + j)) add _ _ = return Wrong apply :: Value -> Value -> M Value apply (Fun k) v = k v apply _ _ = return Wrong test :: Term -> String test t = showM $ interp t []
PavelClaudiuStefan/FMI
An_3_Semestru_1/ProgramareDeclarativa/Extra/Laborator/Laborator 10/var0.hs
cc0-1.0
1,850
0
19
603
861
432
429
64
2
module Dimensions where import Data.Semigroup import Data.List.NonEmpty type XPos = Double type YPos = Double type Height = Double type Width = Double -- Top, Right, Bottom, Left type TaggedDimensions = (String, Double, Double, Double, Double) data Dimensions = D { top :: Double, right :: Double, bottom :: Double, left :: Double } deriving (Show, Eq) instance Semigroup Dimensions where (<>) = dimUnion rect :: Double -> Double -> Dimensions rect h v = D 0 h v 0 sq :: Double -> Dimensions sq s = rect s s tag :: String -> Dimensions -> TaggedDimensions tag name (D t r b l) = (name, t, r, b, l) move :: XPos -> YPos -> Dimensions -> Dimensions move x y (D t r b l) = D (t+y) (r+x) (b+y) (l+x) moveDown :: YPos -> Dimensions -> Dimensions moveDown = move 0 moveRight :: YPos -> Dimensions -> Dimensions moveRight x = move x 0 setWidth :: Width -> Dimensions -> Dimensions setWidth w d = d { right = left d + w } setHeight :: Height -> Dimensions -> Dimensions setHeight h d = d { bottom = top d + h } boxHeight :: Dimensions -> Height boxHeight d = bottom d - top d zero :: Dimensions zero = D 0 0 0 0 boundingBoxAll :: [Dimensions] -> Dimensions boundingBoxAll xs = sconcat $ fromList xs dimUnion :: Dimensions -> Dimensions -> Dimensions dimUnion (D t r b l) (D t' r' b' l') = D (min t t') (max r r') (max b b') (min l l')
pbevin/toycss
src/Dimensions.hs
gpl-2.0
1,345
0
8
283
586
318
268
35
1
{-# LANGUAGE CPP, TypeFamilies, DeriveDataTypeable #-} module PGIP.GraphQL.Result.NativeDocument where import PGIP.GraphQL.Result.DocumentLink import PGIP.GraphQL.Result.OMSSimple import Data.Data data NativeDocument = NativeDocument { __typename :: String , displayName :: String , locId :: String , name :: String , version :: Maybe String , documentLinksSource :: [DocumentLink] , documentLinksTarget :: [DocumentLink] , oms :: OMSSimple } deriving (Show, Typeable, Data)
spechub/Hets
PGIP/GraphQL/Result/NativeDocument.hs
gpl-2.0
775
0
9
357
109
70
39
14
0
module Frontend where import Data.Map(Map) import qualified Data.Map as M import Control.Monad import Data.Monoid import Control.Monad.Trans import Control.Monad.Identity import Control.Monad.Trans.State import Control.Monad.Trans.Writer import Text.Printf -- [1] http://comonad.com/reader/2012/mirrored-lenses/ data Culling = CCW | CW deriving Show data RasterizerState = RasterizerState { culling :: Culling -- ... } deriving Show data BufferView = BufferView deriving Show type Semantic = String data Input = Input { bufferBinding :: Map Int BufferView, shaderParameters :: Map Semantic BufferView } deriving Show emptyInput = Input M.empty M.empty -- Graphics state is a product type of all pipeline states data GS = GS { input :: Input, rasterizerState :: RasterizerState } deriving Show emptyGS = GS emptyInput $ RasterizerState { culling = CW } data Framebuffer = Framebuffer -- persistent view onto possible mutable memory -- Rendering is the process of taking a initial framebuffer and a thing -- and produce a new framebuffer with a rendered into it. type Rendering a = a -> Framebuffer -> Framebuffer -- Rendering takes place in an appropriate overloaded structure: State -- monad. of course this thing now can also track all operations and build -- dependency graphs et al. type RenderM = StateT GS Identity -- now renderM could also produce Renderings type RenderingM a = Rendering (RenderM a) -- PART I: public api which can be used to do low level hackery (much like -- opengl) -- we now define some actions which can be used for rendering -- note that this setter stuff can be modelelled using lenses [for example -- [1] which gives first class references. -- however, for simplicity we won't do this now. -- takes a cull mode and procues a action in RenderM which has no result -- but an effect on the pi undefined setCullMode :: Culling -> RenderM () setCullMode cullMode = modify setCull where setCull (GS input r) = GS input $ r { culling = cullMode } -- nicer with lenses type Index = Int -- Buffers are indexed by ints. setBuffer :: BufferView -> Index -> RenderM () setBuffer buffer index = modify set where set s = let binding = input s -- very ugly here. but can be fixed ;) in s { input = binding { bufferBinding = setBuffer' binding } } setBuffer' = M.insert index buffer . bufferBinding -- Render lives in RenderM render :: RenderM () render = return () renderCube :: RenderM () renderCube = do setBuffer BufferView 0 render -- example: quasi opengl interface myRendering :: RenderM () myRendering = do setCullMode CCW setBuffer BufferView 0 render -- higher order programming on functions with rendering effects resetBuffers :: RenderM () resetBuffers = mapM_ (setBuffer BufferView) [1..16] -- resets all 16 buffer slots -- PART II: imperative stuff should by reflective - we need to extract -- dependency graphs. data Log = LogSeq [Log] -- computation structure tree | Log String deriving Show instance Monoid Log where mempty = LogSeq [] (LogSeq a) `mappend` (LogSeq b) = LogSeq (a++b) l@(Log _) `mappend` (LogSeq b) = LogSeq $ l:b (LogSeq a) `mappend` l@(Log _) = LogSeq $ a ++ [l] Log s `mappend` Log b = LogSeq [Log s, Log b] data Cube = Cube type Scene = WriterT Log RenderM tellLog :: Monad m => String -> WriterT Log m () tellLog = tell . Log cube :: Cube -> Scene () cube c = lift renderCube >> tellLog "renderCube\n" data Transform = Transform transform :: Transform -> Scene () transform _ = tellLog "transform\n" transformScene :: Transform -> Scene () -> Scene () transformScene t g = transform t >> g scene :: Scene () scene = transformScene Transform $ replicateM_ 10 (transformScene Transform unitCube) where unitCube = cube Cube runStructurue s = runIdentity $ (runStateT $ runWriterT s) startState where startState = emptyGS test :: WriterT Log Identity () test = tell (Log "abc") >> tell (Log "cdef")
haraldsteinlechner/lambdaWolf
src/Frontend.hs
gpl-3.0
4,090
0
13
889
998
539
459
76
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeOperators #-} {- | A functional, type-safe interface to slicing up audio files with SoX. -} module Sound.Scissors ( Audio , Rawdio(..) , Side(..) , Time(..) , toRawdio , fromRawdio , fromRawdio' , unsafeFromRawdio -- * Basic audio primitives , silence , resample , file , file' , unsafeFile -- * Combining multiple audio files , concatenate , merge , mix , concatenate' , merge' , mix' -- * Editing a single audio file , pad , trim , cutoff , vol -- * Querying sample rate and channel count , sampleRate , channels , getSampleRate , getChannels -- * Writing audio to a file , runAudio , runRawdio , runRawdioIn ) where import Control.Arrow (second) import Control.Monad (forM) import Data.Char (toLower) import Data.Proxy (Proxy (..)) import qualified Data.Traversable as T import GHC.TypeLits (KnownNat, Nat, natVal, (+)()) import System.Directory (copyFile) import System.FilePath (takeExtension) import System.IO (hClose) import System.IO.Temp (openTempFile, withSystemTempDirectory) import System.Process (callProcess, readProcess) -- | An audio expression, typed by sample rate and number of channels. newtype Audio (r :: Nat) (c :: Nat) = Audio { toRawdio :: Rawdio -- ^ Removes the extra type information, leaving a raw audio expression. } deriving (Eq, Ord, Show, Read) -- | A raw audio expression. data Rawdio = Silence Integer Integer -- ^ Sample rate & channel count. | File FilePath | Pad Side Time Rawdio | Trim Side Time Rawdio | Cutoff Side Time Rawdio | Concatenate [(Double, Rawdio)] | Merge [(Double, Rawdio)] | Mix [(Double, Rawdio)] | Resample Rawdio Integer deriving (Eq, Ord, Show, Read) -- | Which end of the audio to apply certain operations to. data Side = Front | Back deriving (Eq, Ord, Show, Read, Enum, Bounded) -- | A length of time to cut or add. data Time = Seconds Double | Samples Double deriving (Eq, Ord, Show, Read) -- | Assigns an already-known sample rate and channel count to an expression. unsafeFromRawdio :: Rawdio -> Audio r c unsafeFromRawdio = Audio -- | Glues audio files together sequentially. Can also adjust volumes. concatenate' :: (KnownNat r, KnownNat c) => [(Double, Audio r c)] -> Audio r c concatenate' [] = silence concatenate' vauds = Audio $ Concatenate $ map (second toRawdio) vauds -- | Glues audio files together sequentially. concatenate :: (KnownNat r, KnownNat c) => [Audio r c] -> Audio r c concatenate = concatenate' . map (1,) -- | Stacks the channels of two audio files together. Can also adjust volumes. merge' :: (Double, Audio r c1) -> (Double, Audio r c2) -> Audio r (c1 + c2) merge' (a, Audio x) (b, Audio y) = Audio $ Merge [(a, x), (b, y)] -- | Stacks the channels of two audio files together. merge :: Audio r c1 -> Audio r c2 -> Audio r (c1 + c2) merge x y = merge' (1, x) (1, y) -- | Mixes audio files together channel-wise. Can also adjust volumes. mix' :: (KnownNat r, KnownNat c) => [(Double, Audio r c)] -> Audio r c mix' [] = silence mix' vauds = Audio $ Mix $ map (second toRawdio) vauds -- | Mixes audio files together channel-wise. mix :: (KnownNat r, KnownNat c) => [Audio r c] -> Audio r c mix = mix' . map (1,) -- | Multiplies the volume of the audio by a scalar. vol :: Double -> Audio r c -> Audio r c vol v (Audio x) = Audio $ Concatenate [(v, x)] -- | An empty audio file, of zero length. silence :: (KnownNat r, KnownNat c) => Audio r c silence = let res = Audio $ Silence (sampleRate res) (channels res) in res -- | Assigns an already-known sample rate and channel count to an existing file. unsafeFile :: FilePath -> Audio r c unsafeFile = Audio . File -- | Resamples an audio file from one rate to another. resample :: (KnownNat r2) => Audio r1 c -> Audio r2 c resample (Audio x) = let res = Audio $ Resample x $ sampleRate res in res -- | Pads one end of the audio with silence. pad :: Side -> Time -> Audio r c -> Audio r c pad side len = Audio . Pad side len . toRawdio -- | Trims a chunk of time off one end of the audio. trim :: Side -> Time -> Audio r c -> Audio r c trim side len = Audio . Trim side len . toRawdio -- | Cuts off everything after a length of time (counted from either end). cutoff :: Side -> Time -> Audio r c -> Audio r c cutoff side len = Audio . Cutoff side len . toRawdio -- | Gets the sample rate stored in the audio expression's type. sampleRate :: (KnownNat r) => Audio r c -> Integer sampleRate = natVal . (undefined :: Audio r c -> Proxy r) -- | Gets the number of channels stored in the audio expression's type. channels :: (KnownNat c) => Audio r c -> Integer channels = natVal . (undefined :: Audio r c -> Proxy c) -- | Runs SoX with the given list of arguments. An exception will be raised -- if SoX returns a non-zero error code. sox :: [String] -> IO () sox = callProcess "sox" -- | Calculates the sample rate of a raw audio expression. -- Any files referenced will be queried with @soxi@. getSampleRate :: Rawdio -> IO Integer getSampleRate raw = case raw of Silence r _ -> return r File f -> fmap read $ readProcess "soxi" ["-r", f] "" Pad _ _ raw' -> getSampleRate raw' Trim _ _ raw' -> getSampleRate raw' Cutoff _ _ raw' -> getSampleRate raw' Concatenate pairs -> getSampleRate $ snd $ head pairs Merge pairs -> getSampleRate $ snd $ head pairs Mix pairs -> getSampleRate $ snd $ head pairs Resample _ r -> return r -- | Calculates the channel count of a raw audio expression. -- Any files referenced will be queried with @soxi@. getChannels :: Rawdio -> IO Integer getChannels raw = case raw of Silence _ c -> return c File f -> fmap read $ readProcess "soxi" ["-c", f] "" Pad _ _ raw' -> getChannels raw' Trim _ _ raw' -> getChannels raw' Cutoff _ _ raw' -> getChannels raw' Concatenate pairs -> getChannels $ snd $ head pairs Merge pairs -> fmap sum $ mapM (getChannels . snd) pairs Mix pairs -> getChannels $ snd $ head pairs Resample _ r -> return r -- | Checks that the sample rate and channel count of the expression -- match the type it is being cast to. If not, returns 'Nothing'. fromRawdio :: (KnownNat r, KnownNat c) => Rawdio -> IO (Either String (Audio r c)) fromRawdio raw = do r <- getSampleRate raw c <- getChannels raw let res = if r == sampleRate aud && c == channels aud then Right $ unsafeFromRawdio raw else Left $ unwords [ "Expected sample rate" , show $ sampleRate aud , "and channel count" , show $ channels aud , "but got" , show r , "and" , show c ] aud = (undefined :: Either a b -> b) res return res -- | Checks that the sample rate and channel count of the file -- match the type it is being cast to. If not, returns 'Nothing'. file :: (KnownNat r, KnownNat c) => FilePath -> IO (Either String (Audio r c)) file = fromRawdio . File -- | Like 'fromRawdio', but raises an error if the rate or count do not match. fromRawdio' :: (KnownNat r, KnownNat c) => Rawdio -> IO (Audio r c) fromRawdio' raw = fromRawdio raw >>= either (\e -> error $ "fromRawdio': " ++ e) return -- | Like 'file', but raises an error if the rate or count do not match. file' :: (KnownNat r, KnownNat c) => FilePath -> IO (Audio r c) file' = fromRawdio' . File -- | Writes a typed audio expression to a file. runAudio :: Audio r c -- ^ Audio expression to evaluate. -> FilePath -- ^ Output WAV file to generate. -> IO () runAudio = runRawdio . toRawdio -- | Writes a raw audio expression to a file. runRawdio :: Rawdio -- ^ Audio expression to evaluate. -> FilePath -- ^ Output WAV file to generate. -> IO () runRawdio raw out = withSystemTempDirectory "scissors" $ \tempdir -> do f <- runRawdioIn tempdir raw copyFile f out -- | Writes a raw audio expression to a new file in a temporary directory. runRawdioIn :: FilePath -- ^ A directory for temporary files. -> Rawdio -- ^ Audio expression to evaluate. -> IO FilePath -- ^ The output file, which will be in the temporary directory. runRawdioIn tempdir = go where new :: IO FilePath new = do (fp, h) <- openTempFile tempdir "scissors.wav" hClose h return fp go x = case x of Silence rate chans -> do output <- new sox [ "-n" , output , "trim", "0", "0" , "rate", show rate , "channels", show chans ] return output File input -> do output <- new case map toLower $ takeExtension input of ".mp3" -> callProcess "lame" ["--decode", input, output] _ -> sox [input, output] return output Concatenate auds -> combine "concatenate" auds Merge auds -> combine "merge" auds Mix auds -> combine "mix" auds Resample aud rate -> do input <- go aud output <- new sox [input, output, "rate", show rate] return output Pad Front len aud -> transform aud ["pad", showTime len] Pad Back len aud -> transform aud ["pad", "0", showTime len] Trim Front len aud -> transform aud ["trim", showTime len] Trim Back len aud -> transform aud ["trim", "0", '-' : showTime len] Cutoff Front len aud -> transform aud ["trim", "0", showTime len] Cutoff Back len aud -> transform aud ["trim", '-' : showTime len] showTime :: Time -> String showTime (Seconds d) = show d showTime (Samples d) = show d ++ "s" transform :: Rawdio -> [String] -> IO FilePath transform aud args = do input <- go aud output <- new sox $ input : output : args return output combine :: String -> [(Double, Rawdio)] -> IO FilePath combine _ [] = error "runAudio: can't combine 0 audio files" combine _ [(v, aud)] = do input <- go aud output <- new sox ["-v", show v, input, output] return output combine method vauds = do inputs <- forM vauds $ T.mapM go output <- new sox $ ["--combine", method] ++ (inputs >>= \(v, f) -> ["-v", show v, f]) ++ [output] return output
mtolly/sound-scissors
src/Sound/Scissors.hs
gpl-3.0
10,326
0
16
2,591
3,099
1,613
1,486
-1
-1
module Zombies.Model ( ZombiesMsg (..), Role (..), ZombiesAgentState (..), ZombiesEnvironment, ZombiesNetwork, ZombiesPatch, ZombiesPatches, ZombiesAgentDef, ZombiesAgentBehaviour, ZombiesAgentIn, ZombiesAgentOut, ZombiesAgentObservable, humanCount, zombieCount, zombieSpeed, humanSpeed, humanInitEnergyRange, gridDimensions, sortPatchesByZombies, sortPatchesByHumans, humansOnPatch, addHuman, removeHuman, incZombie, decZombie, isHuman, isZombie ) where import FRP.FrABS import Data.List ------------------------------------------------------------------------------------------------------------------------ -- DOMAIN-SPECIFIC AGENT-DEFINITIONS ------------------------------------------------------------------------------------------------------------------------ data ZombiesMsg = Infect deriving (Eq, Show) data Role = Human | Zombie deriving (Eq, Show) data ZombiesAgentState = ZombiesState { zAgentRole :: Role, zAgentCoord :: Continuous2dCoord } | HumanState { zAgentRole :: Role, zAgentCoord :: Continuous2dCoord, zHumanEnergyLevel :: Int, zHumanEnergyInit :: Int } deriving (Show) type ZombiesPatch = ([AgentId], Int) -- fst: agentids of human on this patch, snd number of zombies on this patch type ZombiesNetwork = Network () type ZombiesPatches = Discrete2d ZombiesPatch type ZombiesEnvironment = (Continuous2dEmpty, ZombiesPatches, ZombiesNetwork) type ZombiesAgentDef = AgentDef ZombiesAgentState ZombiesMsg ZombiesEnvironment type ZombiesAgentBehaviour = AgentBehaviour ZombiesAgentState ZombiesMsg ZombiesEnvironment type ZombiesAgentIn = AgentIn ZombiesAgentState ZombiesMsg ZombiesEnvironment type ZombiesAgentOut = AgentOut ZombiesAgentState ZombiesMsg ZombiesEnvironment type ZombiesAgentObservable = AgentObservable ZombiesAgentState ------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------ -- MODEL-PARAMETERS ------------------------------------------------------------------------------------------------------------------------ humanCount :: Int humanCount = 200 zombieCount :: Int zombieCount = 5 humanInitEnergyRange :: (Int, Int) humanInitEnergyRange = (4, 10) gridDimensions :: Discrete2dDimension gridDimensions = (50, 50) zombieSpeed :: Double zombieSpeed = 1.0 humanSpeed :: Double humanSpeed = 2.0 ------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------ -- UTILITIES ------------------------------------------------------------------------------------------------------------------------ sortPatchesByZombies :: Discrete2dCell ZombiesPatch -> Discrete2dCell ZombiesPatch -> Ordering sortPatchesByZombies (_, (_, z1)) (_, (_, z2)) = compare z1 z2 sortPatchesByHumans :: Discrete2dCell ZombiesPatch -> Discrete2dCell ZombiesPatch -> Ordering sortPatchesByHumans (_, p1) (_, p2) = compare (humansOnPatch p1) (humansOnPatch p2) humansOnPatch :: ZombiesPatch -> Int humansOnPatch = length . fst addHuman :: AgentId -> ZombiesPatch -> ZombiesPatch addHuman aid (hs, z) = (aid : hs, z) removeHuman :: AgentId -> ZombiesPatch -> ZombiesPatch removeHuman aid (hs, z) = (delete aid hs, z) incZombie :: ZombiesPatch -> ZombiesPatch incZombie (h, z) = (h, z+1) decZombie :: ZombiesPatch -> ZombiesPatch decZombie (h, z) = (h, z-1) isHuman :: ZombiesAgentState -> Bool isHuman s = zAgentRole s == Human isZombie :: ZombiesAgentState -> Bool isZombie s = zAgentRole s == Zombie ------------------------------------------------------------------------------------------------------------------------
thalerjonathan/phd
coding/libraries/chimera/examples/ABS/Zombies/Model.hs
gpl-3.0
3,984
0
8
530
736
435
301
81
1
module DrawGraph where -- Data structures import Data.List as List import Data.Set as Set import Data.Foldable as Fold import qualified Data.Map.Strict as Map import OpenGraph as OG import GraphPresentation import TypeHierarchy import SemanticScheme import Utilities -- GUI / Rendering stuff import Graphics.UI.Gtk.Gdk.DrawWindow import Graphics.Rendering.Cairo import Control.Concurrent.MVar import Graphics.UI.Gtk.Gdk.EventM import Graphics.UI.Gtk.Abstract.Widget -- Current state of the pointer data DrawingState = DSelect | DMoving OId | DNode | DEdge | DDrawing OPath Double Double | DDelete deriving (Eq) -- Current state of the object selection data ElemSelection = SelectNode OId | SelectEdge OPath | NoSelection -- Global state of the graph editor data GraphState = GraphState { totalGraph :: OGraph, presentation :: GraphPresentation, selection :: ElemSelection, nodeBB :: (Map.Map OId BoundingBox), gateBB :: (Map.Map OPath BoundingBox), lastMouse :: Maybe (Double,Double), originalTypeSkeleton :: LambekSkel } -- Draw a node onscreen drawNode :: Double -> Double -> Int -> Int -> Render () drawNode posX posY 0 0 = do setSourceRGB 0 0 0 setLineWidth 1 moveTo posX posY relMoveTo 0 (-nodeSemiHeight) relLineTo nodeSemiHeight nodeSemiHeight relLineTo (-nodeSemiHeight) nodeSemiHeight relLineTo (-nodeSemiHeight) (-nodeSemiHeight) relLineTo (2*nodeSemiHeight) 0 relMoveTo (-2*nodeSemiHeight) 0 relLineTo nodeSemiHeight (-nodeSemiHeight) stroke drawNode posX posY nInputs nOutputs = do setSourceRGB 0 0 0 setLineWidth 1 let height = (nodeSemiHeight*2) let topWidth = if nInputs > 0 then ((fromIntegral nInputs+1)*nodeGateSpacing) else 0 let bottomWidth = if nOutputs > 0 then ((fromIntegral nOutputs+1)*nodeGateSpacing) else 0 moveTo posX posY relMoveTo (topWidth/2) (-nodeSemiHeight) relLineTo (bottomWidth/2 - topWidth/2) height relLineTo (-bottomWidth) 0 relLineTo ((bottomWidth - topWidth) /2) (-height) relLineTo topWidth 0 -- closePath stroke doList (\ x -> do arc (posX-(bottomWidth/2)+x) (posY+nodeSemiHeight) gateRadius 0 (2*pi) fill) . List.map (* nodeGateSpacing) . (List.map fromIntegral) $ (seqInt nOutputs []) doList (\ x -> do arc (posX-(topWidth/2)+x) (posY-nodeSemiHeight) gateRadius 0 (2*pi) fill) . List.map (* nodeGateSpacing) . (List.map fromIntegral) $ (seqInt nInputs []) -- Draw an outer gate drawGate :: Double -> Double -> Render () drawGate posX posY = do setSourceRGB 1 0 0 arc posX posY gateRadius 0 (2*pi) fill -- Add indexes to elements of a list indexList :: Num b => [a] -> [(a,b)] indexList = indexList_accu 0 where indexList_accu curId [] = [] indexList_accu curId (h:t) = (h,curId):(indexList_accu (curId+1) t) -- Draw an edge drawEdge :: OGraph -> GraphPresentation -> OEdge -> Render () drawEdge graph pres (OEdge from to) = do let (fromX,fromY) = getGatePos graph pres from let (toX,toY) = getGatePos graph pres to setSourceRGB 0 0 0 setLineWidth 1 moveTo fromX fromY lineTo toX toY stroke -- Draw a graph given its presentation drawGraph g@(OGraph gates nodes edges) presentation = do setSourceRGB 1 1 1 paint drawGates gates doList (\ (id,ONode s gates) -> let Just (posX,posY) = Map.lookup id presentation in drawNode posX posY (fromIntegral . length $ (consumers gates)) (fromIntegral . length $ (producers gates))) nodes doSet (drawEdge g presentation) edges where drawGates = doList (\ ((OGate s prod),id) -> let y = if prod then topOuterGates else bottomOuterGates in let x = outerGateOffset + outerGateSpacing*id in do setSourceRGB 0.8 0.8 0.8 setLineWidth 1 moveTo x 0 lineTo x gateLineEnd stroke drawGate x y) . indexList -- Draw the current selection drawSelection _ NoSelection = return () drawSelection bounds (SelectNode id) = case (Map.lookup id bounds) of Nothing -> return () Just (BBox startx starty width height) -> do setSourceRGB 0.5 0.5 0.5 moveTo startx starty relLineTo width 0 relLineTo 0 height relLineTo (-width) 0 closePath stroke drawSelection _ _ = return () -- Draw the whole scene (graph and selection if any) drawScene drawStateM gsM = do gs <- liftIO (readMVar gsM) drawState <- liftIO (readMVar drawStateM) drawGraph (totalGraph gs) (presentation gs) drawTypeSkeleton (originalTypeSkeleton gs) drawSelection (nodeBB gs) (selection gs) for_ (lastMouse gs) $ \(x,y) -> case drawState of DDrawing _ origX origY -> do setSourceRGB 0 0 0 setLineWidth 1 moveTo origX origY lineTo x y stroke DNode -> do drawNode x y 0 0 _ -> return () updateScene drawStateM (readGS,setGS) drawWidget = do (x,y) <- eventCoordinates gs <- liftIO $ readGS liftIO $ setGS $ gs { lastMouse = Just (x,y) } drawState <- liftIO $ readMVar drawStateM liftIO $ case drawState of DDrawing _ _ _ -> widgetQueueDraw drawWidget DNode -> widgetQueueDraw drawWidget DMoving id -> do setGS $ gs { presentation = Map.insert id (x,y) $ presentation gs } widgetQueueDraw drawWidget _ -> return () return True -- Create a new graph state based on an input graph and a presentation createGraphState g@(OGraph gates nodes edges) pres skel = GraphState g pres NoSelection nodeBB gateBB Nothing skel where nodeBB = List.foldl (\ m n -> Map.insert (fst n) (boundingBoxFromNode pres n) m) Map.empty nodes addGates boundMap nodeId gates = List.foldl (\ bm (OGate n _) -> Map.insert (OPath nodeId n) (boundingBoxFromGate g pres (OPath nodeId n)) bm) boundMap gates gateBB = List.foldl (\ m (id,ONode _ gates) -> addGates m id gates) outerGatesBB nodes outerGatesBB = addGates Map.empty boundaryId gates -- Same function, different type createGraphStateFromEntry :: SkelEntry -> GraphState createGraphStateFromEntry entry = createGraphState (skelGraph entry) (skelPres entry) (skeleton entry) -- Make an edge out of two gates, if there is one -- (one has to be producer, the other consumer) -- and no edge is currently bound to the consumer makeEdge graph path1 path2 = case (getGate path1 graph, getGate path2 graph) of (Just True, Just False) -> if checkAddEdge graph (OEdge path1 path2) then Just $ OEdge path1 path2 else Nothing (Just False, Just True) -> if checkAddEdge graph (OEdge path2 path1) then Just $ OEdge path2 path1 else Nothing _ -> Nothing ifNothing Nothing b = b ifNothing a _ = a addMaybeGate (Just (OPath oid gateName)) (Just producer) g@(OGraph _ nodes _) = Just (g { nodesList = List.map changeNodes nodes }) where changeNodes n@(id,ONode name gates) = if id /= oid then n else (id,ONode name ((OGate gateName producer):gates)) addMaybeGate _ _ _ = Nothing getOrCreateGate gs x y = case searchResult of Nothing -> createGateAt gs x y Just g -> (graph,Just g) where graph = totalGraph gs searchResult = findBoundingBox x y (gateBB gs) createGateAt gs x y = (newGraph,matchingNodeGate) where matchingNode = findBoundingBox x y (nodeBB gs) isClickProducer oid = (Map.lookup oid (nodeBB gs) >>= return . inLowerPartOfBBox x y) == Just True matchingNodeGate = (matchingNode >>= (\ oid -> let Just fresh = freshGateName graph oid in -- this is safe return $ OPath oid fresh)) maybeProducer = matchingNode >>= return . isClickProducer maybeGraph = addMaybeGate matchingNodeGate maybeProducer graph newGraph = (case maybeGraph of Just g -> g Nothing -> graph) updateBoundingBoxes (readGS,setGS) = do gs <- readGS setGS . rebuildGraphState $ gs rebuildGraphState gs = createGraphState (totalGraph gs) (presentation gs) (originalTypeSkeleton gs) -- Handle a click based on the current state --handleClick :: MVar DrawingState -> (IO GraphState,GraphState -> IO ()) -> DrawWindow -> IO () handleClick drawStateM (readGS,setGS) drawWidget = do coords <- eventCoordinates let (x,y) = coords st <- liftIO (readMVar drawStateM) gs <- liftIO readGS let gotoState newState = modifyMVar_ drawStateM (\_ -> return newState) liftIO $ case st of DNode -> do let (OGraph gates nodes edges) = totalGraph gs let pres = presentation gs let newId = maxOId nodes + 1 let newGraph = OGraph gates ((newId,(ONode "" [])):nodes) edges let newPres = Map.insert newId coords pres let newNodeBB = Map.insert newId (makeNodeBoundingBox 0 0 x y) (nodeBB gs) setGS (gs { totalGraph = newGraph, presentation = newPres, nodeBB = newNodeBB }) gotoState DSelect widgetQueueDraw drawWidget DSelect -> do putStrLn ("Click handled at position " ++ (show coords)) let searchResult = findBoundingBox x y (nodeBB gs) newSelection <- case searchResult of Nothing -> return NoSelection Just id -> do gotoState (DMoving id) return $ SelectNode id setGS (gs { selection = newSelection }) widgetQueueDraw drawWidget DEdge -> do let (newGraph,searchResult) = getOrCreateGate gs x y setGS (gs { totalGraph = newGraph }) case searchResult of Nothing -> gotoState DEdge Just path -> do let (origX,origY) = getGatePos newGraph (presentation gs) path gotoState $ DDrawing path origX origY DDrawing gate _ _ -> do let (newGraph,maybeGate) = getOrCreateGate gs x y case maybeGate >>= (makeEdge newGraph gate) of Nothing -> gotoState DEdge Just edge -> do setGS (gs { totalGraph = newGraph { edgesList=Set.insert edge (edgesList newGraph) } }) gotoState DEdge widgetQueueDraw drawWidget DDelete -> do tryActions (x,y) [deleteNearestGate, deleteNearestNode, deleteNearestEdge] updateBoundingBoxes (readGS,setGS) widgetQueueDraw drawWidget _ -> return () liftIO $ updateBoundingBoxes (readGS,setGS) return True where tryActions :: a -> [a -> IO Bool] -> IO () tryActions pos [] = return () tryActions pos (filter:others) = do successful <- filter pos if successful then return () else tryActions pos others deleteNearestGate (x,y) = do gs <- readGS let searchResult = findBoundingBox x y (gateBB gs) case searchResult of Nothing -> return False Just gate -> do gs <- readGS setGS $ gs { totalGraph = deleteGate (totalGraph gs) gate } return True deleteNearestEdge (x,y) = do gs <- liftIO readGS deleteEdge gs where deleteEdge gs = case bestCandidate of Nothing -> return False Just (edge,distance) -> do let newEdges = Set.delete (OEdge (fst edge) (snd edge)) (edgesList graph) setGS $ gs { totalGraph = graph { edgesList = newEdges } } return True where graph = totalGraph gs edges = List.map (\ (OEdge a b) -> (a,b)) . elems . edgesList $ graph distances = List.map (getDistance gs) edges zipped = List.zip edges distances bestCandidate = do best <- findMin zipped if (snd best) < maxDistEdgeDeletion then return best else Nothing getDistance gs (from,to) = let fromPos = getPos from in let toPos = getPos to in let uv = diff2 toPos fromPos in let n = l2norm uv in if n == 0 then gateBBhalfSize*4.0 else let ua = diff2 (x,y) fromPos in abs . cross ua $ (toUnitary uv) where getPos = getGatePos (totalGraph gs) (presentation gs) findMin :: Ord b => [(a,b)] -> Maybe (a,b) findMin [] = Nothing findMin lst = Just $ List.minimumBy (\(_,a) (_,b) -> compare a b) lst deleteNearestNode (x,y) = do gs <- liftIO readGS let searchResult = findBoundingBox x y (nodeBB gs) case searchResult of Nothing -> return False Just node -> do -- Delete all the gates in this node let oldGraph = totalGraph gs let newGraph = List.foldl deleteGate oldGraph . getGatesList oldGraph $ node -- Delete the node itself let newNodeList = List.filter (\ (id,_) -> id /= node) (nodesList newGraph) -- TODO: update bounding boxes gs <- readGS setGS $ gs { totalGraph = newGraph { nodesList = newNodeList }} return True where getGatesList :: OGraph -> OId -> [OPath] getGatesList graph nodeId = List.map (\ (OGate name _) -> OPath nodeId name) . getMaybeGates $ nodeId where getMaybeGates nodeId = let lst = List.find (\ (i,_) -> i == nodeId) (nodesList graph) in case lst of Nothing -> [] Just (_,ONode _ gates) -> gates deleteGate :: OGraph -> OPath -> OGraph deleteGate oldGraph gate = -- Delete any edge involving this gate let edges = edgesList oldGraph in let newEdges = Set.filter (\ (OEdge p1 p2) -> p1 /= gate && p2 /= gate) edges in -- Delete the gate itself let (OPath nodeId gateId) = gate in let node = List.find (\ (id,_) -> id == nodeId) $ nodesList oldGraph in let newNode = node >>= (\ (_,ONode nodeName gatesList) -> return $ ONode nodeName $ List.filter (\ (OGate g _) -> g /= gateId) gatesList) in case newNode of Nothing -> oldGraph Just newNode -> let newNodesList = replaceItem nodeId newNode $ nodesList oldGraph in oldGraph { nodesList = newNodesList, edgesList = newEdges } where replaceItem :: Eq a => a -> b -> [(a,b)] -> [(a,b)] replaceItem k v [] = [] replaceItem k v ((k1,_):t) | (k1 == k) = (k,v):t replaceItem k v (h:t) = h:(replaceItem k v t) handleRelease drawStateM (readGS,setGS) drawWidget = do st <- liftIO (readMVar drawStateM) let gotoState newState = modifyMVar_ drawStateM (\_ -> return newState) (x,y) <- eventCoordinates liftIO $ case st of DMoving _ -> do gs <- readGS setGS ((rebuildGraphState gs) { selection = (selection gs)}) gotoState DSelect widgetQueueDraw drawWidget _ -> return () return True changeDrawingState gsM drawStateM cursors drawArea newState = do modifyMVar_ drawStateM (\oldState -> do case (oldState,newState) of (DSelect,DNode) -> resetSelection (DSelect,DEdge) -> resetSelection _ -> return () window <- widgetGetParentWindow drawArea case newState of DEdge -> drawWindowSetCursor window (Just $ cursors !! 1) _ -> drawWindowSetCursor window Nothing return newState) where resetSelection = modifyMVar_ gsM (\gs -> return $ gs { selection = NoSelection }) drawHorizontallyCenteredText x y text left right = do (TextExtents xb _ w _ _ _) <- textExtents text moveTo (x - (w/2.0)) (y) textPath text fillPreserve setSourceRGB 0 0 0 setLineWidth 0.7 stroke (TextExtents xbl _ wl _ _ _) <- textExtents left moveTo (x - (w/2.0)-xbl-wl) y textPath left fillPreserve stroke (TextExtents xbr _ wr _ _ _) <- textExtents right moveTo (x + (w/2.0)+xbr) y textPath right fillPreserve stroke -- Draw a type skeleton with the types above the gates drawTypeSkeleton :: LambekSkel -> Render () drawTypeSkeleton skel = do _ <- drawSubSkeleton 1 NoParen "" "" skel return () where drawHorizText x text l r = drawHorizontallyCenteredText x typeSkeletonPosition text l r drawSubSkeleton :: Double -> ParenthesisNeeded -> String -> String -> LambekSkel -> Render Double drawSubSkeleton offset _ l r t@(LSAtom s) = do drawHorizText (offset*outerGateSpacing) (renderLS t) l r return (offset + 1) drawSubSkeleton offset _ l r t@(LSVar n) = do drawHorizText (offset*outerGateSpacing) (show n) l r return (offset + 1) drawSubSkeleton offset NoParen l r (LSLeft body arg) = do offset2 <- drawSubSkeleton offset AlwaysParen l "" arg drawHorizText ((offset2-0.5)*outerGateSpacing) "\\" "" "" drawSubSkeleton offset2 ParenRight "" r body drawSubSkeleton offset ParenRight l r skel@(LSLeft _ _) = drawSubSkeleton offset NoParen l r skel drawSubSkeleton offset _ l r skel@(LSLeft _ _) = do drawSubSkeleton offset NoParen (l++"(") (")"++r) skel drawSubSkeleton offset NoParen l r (LSRight body arg) = do offset2 <- drawSubSkeleton offset ParenLeft l "" body drawHorizText ((offset2-0.5)*outerGateSpacing) "/" "" "" drawSubSkeleton offset2 AlwaysParen "" r arg drawSubSkeleton offset ParenLeft l r skel@(LSRight _ _) = drawSubSkeleton offset NoParen l r skel drawSubSkeleton offset _ l r skel@(LSRight _ _) = do drawSubSkeleton offset NoParen (l++"(") (")"++r) skel
wetneb/yanker
src/DrawGraph.hs
gpl-3.0
18,475
296
19
5,778
5,059
2,782
2,277
425
21
import System.Environment import System.Directory import Text.StringTemplate main :: IO () main = do args <- getArgs cdir <- getCurrentDirectory tmpl <- (directoryGroup cdir :: IO (STGroup String)) let mneutstr = args !! 0 Just cntrtmpl = getStringTemplate "contour.gpl" tmpl Just cmbdtmpl = getStringTemplate "combined.gpl" tmpl simplstr = (toString . flip setManyAttrib cntrtmpl) [ ("mass", mneutstr) , ("xmin", "600") , ("xmax", "3000") , ("ymin", "600") , ("ymax", "3000") , ("modelname", "simplifiedsusy") ] {- xuddstr = (toString . flip setManyAttrib cntrtmpl) [ ("mass", mneutstr) , ("xmin", "600") , ("xmax", "3000") , ("ymin", "600") , ("ymax", "3000") , ("modelname", "xudd_neutLOSP") ] -} xqldstr = (toString . flip setManyAttrib cntrtmpl) [ ("mass", mneutstr) , ("xmin", "600") , ("xmax", "3000") , ("ymin", "600") , ("ymax", "3000") , ("modelname", "xqld_neutLOSP") ] cmbdstr = (toString . flip setManyAttrib cmbdtmpl) [ ("mass", mneutstr) , ("xmin", "600") , ("xmax", "3000") , ("ymin", "600") , ("ymax", "3000") , ("modelname", "xqld_neutLOSP") , ("modelalias", "Xqld") ] writeFile "contour_simplifiedsusy.gpl" simplstr writeFile "contour_xqld.gpl" xqldstr -- writeFile "contour_xudd.gpl" xuddstr writeFile "combined.gpl" cmbdstr
wavewave/lhc-analysis-collection
pic/drawfigure.hs
gpl-3.0
1,897
0
13
819
368
208
160
36
1
{-# LANGUAGE OverloadedStrings #-} -- Handlers for working with user authentication. Login, Logout etc. module Reffit.Handlers.HandleAuthentication ( handleLogin ,handleLoginSubmit ,handleLogout ) where import Application import Snap.Core import Data.Map.Syntax import Snap.Snaplet import Snap.Snaplet.Auth import Snap.Snaplet.Heist import Heist import qualified Heist.Interpreted as I import qualified Data.Text as T -- | Render login form handleLogin :: Maybe T.Text -> Handler App (AuthManager App) () handleLogin authError = heistLocal (I.bindSplices errs) $ render "login" where errs = maybe mempty splice authError splice err = "loginError" ## I.textSplice err -- | Handle login submit handleLoginSubmit :: Handler App (AuthManager App) () handleLoginSubmit = loginUser "login" "password" (Just "remember") (\_ -> handleLogin err) (redirect "/") where err = Just "Unknown user or password" -- | Logs out and redirects the user to the site index. handleLogout :: Handler App (AuthManager App) () handleLogout = logout >> redirect "/"
imalsogreg/reffit
src/Reffit/Handlers/HandleAuthentication.hs
gpl-3.0
1,153
0
9
256
260
143
117
25
1
module SmellsAnalyzerSpec(spec) where import Language.Mulang.Analyzer hiding (result, spec) import Language.Mulang.Ast import Test.Hspec result smells = emptyCompletedAnalysisResult { smells = smells } runExcept language content smells = analyse (smellsAnalysis (CodeSample language content) (allSmellsBut smells)) runOnly language content smells = analyse (smellsAnalysis (CodeSample language content) (noSmellsBut smells)) runWithTypos language content expectations = do let spec = emptyAnalysisSpec { smellsSet = (allSmellsBut []), expectations = Just expectations } result <- analyse (Analysis (CodeSample language content) spec) return $ smells result spec = describe "SmellsAnalyzer" $ do describe "Using language specific smells" $ do it "works with JavaScript smells" $ do (runOnly JavaScript "function f() { var x = 1 }" ["JavaScript#UsesVarInsteadOfLet"]) `shouldReturn` (result [Expectation "f" "JavaScript#UsesVarInsteadOfLet"]) (runOnly JavaScript "function f() { let x = 1 }" ["JavaScript#UsesVarInsteadOfLet"]) `shouldReturn` (result []) describe "using usage typos" $ do it "works when there are missing usages and typos" $ do runWithTypos JavaScript "baz()" [Expectation "*" "Uses:bar"] `shouldReturn` [Expectation "baz" "HasUsageTypos:bar"] it "works when there are missing usages and multiple potential typos" $ do let typos = [ Expectation "baz" "HasUsageTypos:bar", Expectation "Bar" "HasUsageTypos:bar" ] runWithTypos JavaScript "baz()\nBar() {}" [Expectation "*" "Uses:bar"] `shouldReturn` typos it "works when there are missing usages but no typos" $ do runWithTypos JavaScript "goo()" [Expectation "*" "Uses:bar"] `shouldReturn` [] it "works when there are no missing usages and potential typos" $ do runWithTypos JavaScript "bar()\nbaz()\n" [Expectation "*" "Uses:bar"] `shouldReturn` [] describe "using declaration typos" $ do it "works when there are missing declarations and typos" $ do runWithTypos JavaScript "function baz() {}" [Expectation "*" "Declares:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] runWithTypos JavaScript "function baz() {}" [Expectation "*" "DeclaresComputation:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] runWithTypos JavaScript "function baz() {}" [Expectation "*" "DeclaresComputationWithArity0:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] runWithTypos JavaScript "function baz() {}" [Expectation "*" "DeclaresComputationWithArity1:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] runWithTypos JavaScript "function baz() {}" [Expectation "*" "DeclaresProcedure:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] runWithTypos JavaScript "function baz() {}" [Expectation "*" "DeclaresFunction:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] runWithTypos JavaScript "function baz() {}" [Expectation "*" "Delegates:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] runWithTypos JavaScript "function baz() {}" [Expectation "*" "SubordinatesDeclarationsTo:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] it "works when there are duplicated expectations" $ do runWithTypos JavaScript "function baz() {}" [Expectation "*" "Declares:bar", Expectation "*" "Declares:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] it "works when there are duplicated expectation results" $ do runWithTypos Java "class Foo { void baz() {} }" [Expectation "*" "Declares:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] it "works when there are similar declares expectations results" $ do runWithTypos Java "class Foo { void baz() {} }" [Expectation "*" "Declares:bar", Expectation "*" "DeclaresComputationWithArity0:bar"] `shouldReturn` [Expectation "baz" "HasDeclarationTypos:bar"] it "works when there are missing declarations and multiple potential typos" $ do let typos = [ Expectation "Bar" "HasDeclarationTypos:bar", Expectation "baz" "HasDeclarationTypos:bar" ] runWithTypos JavaScript "function baz() {}\nfunction Bar() {}" [Expectation "*" "Declares:bar"] `shouldReturn` typos it "works when there are missing declarations but no typos" $ do runWithTypos JavaScript "function goo() {}" [Expectation "*" "Declares:bar"] `shouldReturn` [] it "works when there are no missing declarations and potential typos" $ do runWithTypos JavaScript "function bar() {}\nfunction baz() {}\n" [Expectation "*" "Declares:bar"] `shouldReturn` [] it "works when there are no missing declarations but original expectations fail" $ do runWithTypos JavaScript "function bar() {}" [Expectation "*" "DeclaresClass:bar"] `shouldReturn` [] runWithTypos JavaScript "function bar() {}" [Expectation "*" "DeclaresComputationWithArity1:bar"] `shouldReturn` [] runWithTypos JavaScript "function bar() {}" [Expectation "*" "Delegates:bar"] `shouldReturn` [] runWithTypos JavaScript "function bar() {}\nfunction other(){}" [Expectation "*" "SubordinatesDeclarationsTo:bar"] `shouldReturn` [] it "Using domain language and nested structures" $ do let runRuby sample = analyse (domainLanguageAnalysis (MulangSample (Just sample)) (DomainLanguage Nothing (Just RubyCase) (Just 3) Nothing)) (runRuby (Sequence [ (Object "Foo_Bar" (Sequence [ (SimpleMethod "y" [] None), (SimpleMethod "aB" [] None), (SimpleMethod "fooBar" [] None)])), (Object "Foo" None)])) `shouldReturn` (result [ Expectation "y" "HasTooShortIdentifiers", Expectation "aB" "HasTooShortIdentifiers", Expectation "Foo_Bar" "HasWrongCaseIdentifiers", Expectation "aB" "HasWrongCaseIdentifiers", Expectation "fooBar" "HasWrongCaseIdentifiers"]) it "works inferring domain language" $ do let runPython sample = runExcept Python3 sample [] runPython "def fooBar():\n\tpass\n\ndef foo_baz():\n\tpass\n\n" `shouldReturn` (result [Expectation "fooBar" "HasWrongCaseIdentifiers"]) it "works inferring caseStyle" $ do let runPython sample = analyse (domainLanguageAnalysis (CodeSample Python3 sample) (DomainLanguage Nothing Nothing (Just 3) Nothing)) runPython "def fooBar():\n\tpass\n\ndef foo_baz():\n\tpass\n\n" `shouldReturn` (result [Expectation "fooBar" "HasWrongCaseIdentifiers"]) describe "Using exclusion" $ do it "works with empty set, in java" $ do (runExcept Java "class Foo { static { System.out.println(\"foo\"); } }" []) `shouldReturn` (result [Expectation "Foo" "DoesConsolePrint"]) it "works with empty set, in haskell" $ do (runExcept Haskell "fun x = if x then True else False" []) `shouldReturn` (result [Expectation "fun" "HasRedundantIf"]) describe "detect domain language violations" $ do it "detects identifier length violations" $ do (runExcept Haskell "f x = x" []) `shouldReturn` (result [Expectation "f" "HasTooShortIdentifiers"]) it "detects case violations" $ do (runExcept Haskell "fixme_now x = x" []) `shouldReturn` (result [Expectation "fixme_now" "HasWrongCaseIdentifiers"]) describe "works with non-empty set" $ do it "dont reports smell when excluded" $ do (runExcept JavaScript "function f() { let x = 1; return x }" ["HasRedundantLocalVariableReturn", "HasTooShortIdentifiers"]) `shouldReturn` (result []) it "reports smell when not excluded and present" $ do (runExcept JavaScript "function foo() { let aVariable = 1; return aVariable }" []) `shouldReturn` (result [Expectation "foo" "HasRedundantLocalVariableReturn"]) it "dont reports smell when not excluded and not present" $ do (runExcept JavaScript "function foo() { return 1; }" ["HasRedundantLocalVariableReturn"]) `shouldReturn` (result []) describe "works with top level detections" $ do it "works with empty set, in Python" $ do (runExcept Python "print(4)" []) `shouldReturn` (result [Expectation "*" "DoesConsolePrint"]) it "works with empty set, in JavaScript" $ do (runExcept JavaScript "console.log(4)" []) `shouldReturn` (result [Expectation "*" "DoesConsolePrint"]) describe "Using inclusion" $ do it "works with empty set, in haskell" $ do (runOnly Haskell "f x = if x then True else False" []) `shouldReturn` (result []) it "works with empty set, in python" $ do (runExcept Python "def funcion():\n if True:\n pass\n else:\n return 1" []) `shouldReturn` (result [Expectation "funcion" "ShouldInvertIfCondition"])
mumuki/mulang
spec/SmellsAnalyzerSpec.hs
gpl-3.0
9,059
0
24
1,846
2,034
993
1,041
107
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.Compute.RegionNetworkEndpointGroups.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 the list of regional network endpoint groups available to the -- specified project in the given region. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionNetworkEndpointGroups.list@. module Network.Google.Resource.Compute.RegionNetworkEndpointGroups.List ( -- * REST Resource RegionNetworkEndpointGroupsListResource -- * Creating a Request , regionNetworkEndpointGroupsList , RegionNetworkEndpointGroupsList -- * Request Lenses , rneglReturnPartialSuccess , rneglOrderBy , rneglProject , rneglFilter , rneglRegion , rneglPageToken , rneglMaxResults ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionNetworkEndpointGroups.list@ method which the -- 'RegionNetworkEndpointGroupsList' request conforms to. type RegionNetworkEndpointGroupsListResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "networkEndpointGroups" :> QueryParam "returnPartialSuccess" Bool :> QueryParam "orderBy" Text :> QueryParam "filter" Text :> QueryParam "pageToken" Text :> QueryParam "maxResults" (Textual Word32) :> QueryParam "alt" AltJSON :> Get '[JSON] NetworkEndpointGroupList -- | Retrieves the list of regional network endpoint groups available to the -- specified project in the given region. -- -- /See:/ 'regionNetworkEndpointGroupsList' smart constructor. data RegionNetworkEndpointGroupsList = RegionNetworkEndpointGroupsList' { _rneglReturnPartialSuccess :: !(Maybe Bool) , _rneglOrderBy :: !(Maybe Text) , _rneglProject :: !Text , _rneglFilter :: !(Maybe Text) , _rneglRegion :: !Text , _rneglPageToken :: !(Maybe Text) , _rneglMaxResults :: !(Textual Word32) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegionNetworkEndpointGroupsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rneglReturnPartialSuccess' -- -- * 'rneglOrderBy' -- -- * 'rneglProject' -- -- * 'rneglFilter' -- -- * 'rneglRegion' -- -- * 'rneglPageToken' -- -- * 'rneglMaxResults' regionNetworkEndpointGroupsList :: Text -- ^ 'rneglProject' -> Text -- ^ 'rneglRegion' -> RegionNetworkEndpointGroupsList regionNetworkEndpointGroupsList pRneglProject_ pRneglRegion_ = RegionNetworkEndpointGroupsList' { _rneglReturnPartialSuccess = Nothing , _rneglOrderBy = Nothing , _rneglProject = pRneglProject_ , _rneglFilter = Nothing , _rneglRegion = pRneglRegion_ , _rneglPageToken = Nothing , _rneglMaxResults = 500 } -- | Opt-in for partial success behavior which provides partial results in -- case of failure. The default value is false. rneglReturnPartialSuccess :: Lens' RegionNetworkEndpointGroupsList (Maybe Bool) rneglReturnPartialSuccess = lens _rneglReturnPartialSuccess (\ s a -> s{_rneglReturnPartialSuccess = a}) -- | Sorts list results by a certain order. By default, results are returned -- in alphanumerical order based on the resource name. You can also sort -- results in descending order based on the creation timestamp using -- \`orderBy=\"creationTimestamp desc\"\`. This sorts results based on the -- \`creationTimestamp\` field in reverse chronological order (newest -- result first). Use this to sort resources like operations so that the -- newest operation is returned first. Currently, only sorting by \`name\` -- or \`creationTimestamp desc\` is supported. rneglOrderBy :: Lens' RegionNetworkEndpointGroupsList (Maybe Text) rneglOrderBy = lens _rneglOrderBy (\ s a -> s{_rneglOrderBy = a}) -- | Project ID for this request. rneglProject :: Lens' RegionNetworkEndpointGroupsList Text rneglProject = lens _rneglProject (\ s a -> s{_rneglProject = a}) -- | A filter expression that filters resources listed in the response. The -- expression must specify the field name, a comparison operator, and the -- value that you want to use for filtering. The value must be a string, a -- number, or a boolean. The comparison operator must be either \`=\`, -- \`!=\`, \`>\`, or \`\<\`. For example, if you are filtering Compute -- Engine instances, you can exclude instances named \`example-instance\` -- by specifying \`name != example-instance\`. You can also filter nested -- fields. For example, you could specify \`scheduling.automaticRestart = -- false\` to include instances only if they are not scheduled for -- automatic restarts. You can use filtering on nested fields to filter -- based on resource labels. To filter on multiple expressions, provide -- each separate expression within parentheses. For example: \`\`\` -- (scheduling.automaticRestart = true) (cpuPlatform = \"Intel Skylake\") -- \`\`\` By default, each expression is an \`AND\` expression. However, -- you can include \`AND\` and \`OR\` expressions explicitly. For example: -- \`\`\` (cpuPlatform = \"Intel Skylake\") OR (cpuPlatform = \"Intel -- Broadwell\") AND (scheduling.automaticRestart = true) \`\`\` rneglFilter :: Lens' RegionNetworkEndpointGroupsList (Maybe Text) rneglFilter = lens _rneglFilter (\ s a -> s{_rneglFilter = a}) -- | The name of the region where the network endpoint group is located. It -- should comply with RFC1035. rneglRegion :: Lens' RegionNetworkEndpointGroupsList Text rneglRegion = lens _rneglRegion (\ s a -> s{_rneglRegion = a}) -- | Specifies a page token to use. Set \`pageToken\` to the -- \`nextPageToken\` returned by a previous list request to get the next -- page of results. rneglPageToken :: Lens' RegionNetworkEndpointGroupsList (Maybe Text) rneglPageToken = lens _rneglPageToken (\ s a -> s{_rneglPageToken = a}) -- | The maximum number of results per page that should be returned. If the -- number of available results is larger than \`maxResults\`, Compute -- Engine returns a \`nextPageToken\` that can be used to get the next page -- of results in subsequent list requests. Acceptable values are \`0\` to -- \`500\`, inclusive. (Default: \`500\`) rneglMaxResults :: Lens' RegionNetworkEndpointGroupsList Word32 rneglMaxResults = lens _rneglMaxResults (\ s a -> s{_rneglMaxResults = a}) . _Coerce instance GoogleRequest RegionNetworkEndpointGroupsList where type Rs RegionNetworkEndpointGroupsList = NetworkEndpointGroupList type Scopes RegionNetworkEndpointGroupsList = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient RegionNetworkEndpointGroupsList'{..} = go _rneglProject _rneglRegion _rneglReturnPartialSuccess _rneglOrderBy _rneglFilter _rneglPageToken (Just _rneglMaxResults) (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy RegionNetworkEndpointGroupsListResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionNetworkEndpointGroups/List.hs
mpl-2.0
8,270
0
20
1,765
834
498
336
125
1
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. module Main where import Test.Tasty import qualified Test.Network.Wai.Route as Route main :: IO () main = defaultMain Route.tests
romanb/wai-route
test/Main.hs
mpl-2.0
335
0
6
58
42
27
15
5
1
-- GSoC 2015 - Haskell bindings for OpenCog. {-# LANGUAGE GADTs #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE StandaloneDeriving #-} -- | This Module defines the main data types for Haskell bindings. module OpenCog.AtomSpace.Types ( TruthVal (..) , AtomName (..) , Atom (..) , AtomGen (..) , Gen (..) , appGen , getType ) where import OpenCog.AtomSpace.Inheritance (type (<~)) import OpenCog.AtomSpace.AtomType (AtomType(..)) import Data.Typeable (Typeable,typeRep) import Control.Monad (Functor,Monad) -- | Atom name type. type AtomName = String -- | 'TruthVal' represent the different types of TruthValues. data TruthVal = SimpleTV { tvMean :: Double , tvConfidence :: Double } | CountTV { tvMean :: Double , tvCount :: Double , tvConfidence :: Double } | IndefTV { tvMean :: Double , tvL :: Double , tvU :: Double , tvConfLevel :: Double , tvDiff :: Double } | FuzzyTV { tvMean :: Double , tvConfidence :: Double } | ProbTV { tvMean :: Double , tvCount :: Double , tvConfidence :: Double } deriving (Show,Eq) type TVal = Maybe TruthVal -- | 'Gen' groups all the atoms that are children of the atom type a. data Gen a where Gen :: (Typeable a,b <~ a) => Atom b -> Gen a deriving instance Show (Gen a) -- | 'appGen' evaluates a given function with the atom type instance -- wrapped inside the 'Gen' type. appGen :: (forall b. (Typeable a,b <~ a) => Atom b -> c) -> Gen a -> c appGen f (Gen at) = f at -- | 'AtomGen' is a general atom type hiding the type variables. -- (necessary when working with many instances of different atoms, -- for example, for lists of general atoms) type AtomGen = Gen AtomT -- | 'Atom' is the main data type to represent the different types of atoms. -- -- Here we impose type constraints in how atoms relate between them. -- -- The @<~@ type operator means that the type on the left "inherits" from the -- type on the right. -- -- __DEFINING NEW ATOM TYPES:__ -- -- * If it is a node: -- -- We add a new data constructor such as: -- -- @ NewAtomTypeNode :: AtomName -> TVal -> Atom NewAtomTypeT @ -- -- where NewAtomTypeT is a phantom type (automatically generated by temp. hask.). -- -- * If it is a link: -- -- * If it is of a fixed arity: -- -- We impose the type constraints on each of the members of its outgoing set. -- -- @ NewAtomTypeLink :: (a <~ t1,b <~ t2,c <~ t3) => -- TVal -> Atom a -> Atom b -> Atom c -> AtomNewAtomTypeT @ -- -- * If it is of unlimited arity: -- -- We define it as a data constructor that takes a list of atoms as first argument. -- All the members of its outgoing set will satisfy the same constraints. -- -- For example suppose NewAtomTypeLink accepts nodes that are concepts: -- -- @ NewAtomTypeLink :: TVal -> [Gen ConceptT] -> Atom NewAtomTypeT @ -- -- Also, you have to modify the module Internal. Adding proper case clauses for -- this new atom type to the functions "toRaw" and "fromRaw". -- data Atom (a :: AtomType) where PredicateNode :: AtomName -> TVal -> Atom PredicateT AndLink :: TVal -> [AtomGen] -> Atom AndT OrLink :: TVal -> [AtomGen] -> Atom OrT ImplicationLink :: (a <~ AtomT,b <~ AtomT) => TVal -> Atom a -> Atom b -> Atom ImplicationT EquivalenceLink :: (a <~ AtomT,b <~ AtomT) => TVal -> Atom a -> Atom b -> Atom EquivalenceT EvaluationLink :: (p <~ PredicateT,l <~ ListT) => TVal -> Atom p -> Atom l -> Atom EvaluationT ConceptNode :: AtomName -> TVal -> Atom ConceptT InheritanceLink :: (c1 <~ ConceptT,c2 <~ ConceptT) => TVal -> Atom c1 -> Atom c2 -> Atom InheritanceT SimilarityLink :: (c1 <~ ConceptT,c2 <~ ConceptT) => TVal -> Atom c1 -> Atom c2 -> Atom SimilarityT MemberLink :: (c1 <~ NodeT,c2 <~ NodeT) => TVal -> Atom c1 -> Atom c2 -> Atom MemberT SatisfyingSetLink :: (p <~ PredicateT) => Atom p -> Atom SatisfyingSetT NumberNode :: Double -> Atom NumberT ListLink :: [AtomGen] -> Atom ListT SetLink :: [AtomGen] -> Atom SetT SchemaNode :: AtomName -> Atom SchemaT GroundedSchemaNode :: AtomName -> Atom GroundedSchemaT ExecutionLink :: (s <~ SchemaT,l <~ ListT,a <~ AtomT) => Atom s -> Atom l -> Atom a -> Atom ExecutionT VariableNode :: AtomName -> Atom VariableT VariableList :: [Gen VariableT] -> Atom VariableT SatisfactionLink :: (v <~ VariableT,l <~ LinkT) => Atom v -> Atom l -> Atom SatisfactionT ForAllLink :: (v <~ ListT,i <~ ImplicationT) => TVal -> Atom v -> Atom i -> Atom ForAllT AverageLink :: (v <~ VariableT,a <~ AtomT) => TVal -> Atom v -> Atom a -> Atom AverageT QuoteLink :: (a <~ AtomT) => Atom a -> Atom a BindLink :: (v <~ VariableT,p <~ AtomT,q <~ AtomT) => Atom v -> Atom p -> Atom q -> Atom BindT deriving instance Show (Atom a) deriving instance Typeable Atom -- TODO: improve this code, defining an instance of Data for Atom GADT -- and use the Data type class interface to get the constructor. getType :: (Typeable a) => Atom a -> String getType = head . words . show
virneo/atomspace
opencog/haskell/OpenCog/AtomSpace/Types.hs
agpl-3.0
6,401
0
10
2,316
1,235
686
549
-1
-1
-- Author: Giedrius Jonikas -- [email protected] {-# LANGUAGE BangPatterns #-} module Msm (simulateVolatility, simulateReturns) where import Control.Monad.State import System.Random import System.IO.Unsafe rand :: Float -> Float -> Float rand min max = unsafePerformIO $ do gen <- newStdGen let (prob, _) = randomR (min,max) gen :: (Float, StdGen) return prob simulateReturns :: Float -> Int -> Float -> Float -> Float -> IO [Float] simulateReturns sigma kbar gamma_kbar b m0 = do volatility <- simulateVolatility sigma kbar gamma_kbar b m0 gen <- newStdGen let rand = (randomRs (-1,1) gen) :: [Float] let ret = zipWith (*) rand volatility return ret simulateVolatility :: Float -> Int -> Float -> Float -> Float -> IO [Float] simulateVolatility sigma kbar gamma_kbar b m0 = do gen <- newStdGen let ns = take 1 $ randoms gen :: [Int] markovStateVector <- generateMarkovStateVector m0 kbar -- forM monad will keep the state of current markov state vector. -- Each iteration will return one point from time series simulation -- and update markov state vector. let sim = flip evalState markovStateVector $ do forM [0..] $ \_ -> do -- Get Markov state vector from state stateVector <- get -- updateMarkovStateVector already uses unsafe IO, so we might as -- well abuse it a bit more. let nextStateVector = unsafePerformIO $ updateMarkovStateVector stateVector gamma_v m0 kbar -- Save updated state vector for next step put nextStateVector -- Calculate next step in the simulation let result = sigma * (sqrt (product stateVector)) return result return sim where gamma_v = gammaVector gamma_kbar kbar b -- Computes gamma vector from gamma_kbar by inverting the ralationship -- defined on page 54 of Calvet-Fisher. gammaVector :: Float -> Int -> Float -> [Float] gammaVector gamma_kbar kbar b = [gamma1] ++ [gamma_n x | x <- [2..kbar]] where gamma1 = 1 - (1 - gamma_kbar) ** (b ** (1 - fromIntegral kbar)) gamma_n n = 1 - (1 - gamma1) ** (b ** (fromIntegral n-1)) -- Creates new random markov state vector of size kbar generateMarkovStateVector :: Float -> Int -> IO [Float] generateMarkovStateVector m0 kbar = do gen <- newStdGen let rand = take kbar $ randoms gen :: [Int] return [r (rand !! x) | x <- [0..kbar-1]] where m1 = 2 - m0 r :: Int -> Float r n | n `mod` 2 == 0 = m0 | otherwise = m1 -- Takes MarkovStateVector, GammaVector, m0 and kbar. -- Returns updated MakovStateVector. updateMarkovStateVector :: [Float] -> [Float] -> Float -> Int -> IO [Float] updateMarkovStateVector stateVector gammaVector m0 kbar = do gen <- newStdGen let rand = take kbar (randomRs (0,1) gen) :: [Float] gen2 <- newStdGen let ns = take 1 $ randoms gen2 :: [Bool] let result = [update x (rand !! x) | x <- [0..kbar-1]] return result where update n r | r < (gammaVector !! n) = -- For the sake of simplicity, unsafe IO will be perfomed. -- If this fails, something terribly wrong must have happened. if unsafePerformIO (do gen2 <- newStdGen let (x,y) = random gen2 :: (Bool, StdGen) return x) == True then m1 else m0 | otherwise = stateVector !! n newRandomM ns | ns = m1 | otherwise = m0 m1 = 2 - m0
Giedriusj1/Markov_switching_multifractal_simulation
Msm.hs
unlicense
3,787
0
24
1,240
1,050
535
515
68
2
-- | Read a file line-by-line using handles, and perform a fold over the lines. -- The fold is used here to calculate the number of lines in the file. -- -- Tested in this benchmark: -- -- * Buffered, line-based IO -- {-# LANGUAGE BangPatterns #-} module Benchmarks.FoldLines ( benchmark ) where import Test.Tasty.Bench (Benchmark, bgroup, bench, whnfIO) import System.IO import qualified Data.Text as T import qualified Data.Text.IO as T benchmark :: FilePath -> Benchmark benchmark fp = bgroup "ReadLines" [ bench "Text" $ withHandle $ foldLinesT (\n _ -> n + 1) (0 :: Int) ] where withHandle f = whnfIO $ do h <- openFile fp ReadMode hSetBuffering h (BlockBuffering (Just 16384)) x <- f h hClose h return x -- | Text line fold -- foldLinesT :: (a -> T.Text -> a) -> a -> Handle -> IO a foldLinesT f z0 h = go z0 where go !z = do eof <- hIsEOF h if eof then return z else do l <- T.hGetLine h let z' = f z l in go z' {-# INLINE foldLinesT #-}
bos/text
benchmarks/haskell/Benchmarks/FoldLines.hs
bsd-2-clause
1,094
0
16
332
310
162
148
26
2
-- 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.Numeral.GA.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Numeral.GA.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "GA Tests" [ makeCorpusTest [Seal Numeral] corpus ]
facebookincubator/duckling
tests/Duckling/Numeral/GA/Tests.hs
bsd-3-clause
504
0
9
78
79
50
29
11
1
module Chat.Bot.Run.Guess where import Chat.Data import Chat.Bot.Guess import Chat.Bot.Misc.Guess import Control.Concurrent import Control.Monad import Data.List import System.Random guessBot :: IO Bot guessBot = do secretVar <- newMVar 0 nextGuess secretVar return $ \m -> case stripPrefix "/guess " m of Nothing -> return Nothing Just number -> do secret <- readMVar secretVar let guessResult = guess secret (read number) case guessResult of GuessCorrect -> -- Reset the guess when it's correct nextGuess secretVar _ -> return () return (Just (guessRender guessResult)) nextGuess :: MVar Int -> IO () nextGuess secretVar = modifyMVar_ secretVar $ \_ -> getStdRandom $ randomR (1, 100)
charleso/haskell-in-haste
src/Chat/Bot/Run/Guess.hs
bsd-3-clause
858
0
19
272
240
120
120
28
3
module Main where import RDSTests.DBInstanceTests import RDSTests.DBParameterGroupTests import RDSTests.DBSecurityGroupTests import RDSTests.DBSnapshotTests import RDSTests.DBSubnetGroupTests import RDSTests.EventTests import RDSTests.EventSubscriptionTests import RDSTests.OptionGroupTests import RDSTests.TagTests main :: IO () main = do runDBSnapshotTests runDBInstanceTests runDBParameterGroupTests runDBSecurityGroupTests runDBSubnetGroupTests runEventTests runEventSubscriptionTests runOptionGroupTests runRDSTagTests
worksap-ate/aws-sdk
test/RDSTests.hs
bsd-3-clause
562
0
6
75
91
47
44
21
1
{-| Module : IRTS.Bytecode Description : Bytecode for a stack based VM (e.g. for generating C code with an accurate hand written GC) Copyright : License : BSD3 Maintainer : The Idris Community. BASE: Current stack frame's base TOP: Top of stack OLDBASE: Passed in to each function, the previous stack frame's base L i refers to the stack item at BASE + i T i refers to the stack item at TOP + i RVal is a register in which computed values (essentially, what a function returns) are stored. -} module IRTS.Bytecode where import Idris.Core.TT import IRTS.Defunctionalise import IRTS.Simplified import Data.Maybe data Reg = RVal | L Int | T Int | Tmp deriving (Show, Eq) data BC = -- | reg1 = reg2 ASSIGN Reg Reg -- | reg = const | ASSIGNCONST Reg Const -- | reg1 = reg2 (same as assign, it seems) | UPDATE Reg Reg -- | reg = constructor, where constructor consists of a tag and -- values from registers, e.g. (cons tag args) -- the 'Maybe Reg', if set, is a register which can be overwritten -- (i.e. safe for mutable update), though this can be ignored | MKCON Reg (Maybe Reg) Int [Reg] -- | Matching on value of reg: usually (but not always) there are -- constructors, hence "Int" for patterns (that's a tag on which -- we should match), and the following [BC] is just a list of -- instructions for the corresponding case. The last argument is -- for default case. When it's not necessary a constructor in the -- reg, the Bool should be False, indicating that it's not safe to -- work with that as with a constructor, so a check should be -- added. If it's not a constructor, default case should be used. | CASE Bool Reg [(Int, [BC])] (Maybe [BC]) -- | get a value from register, which should be a constructor, and -- put its arguments into the stack, starting from (base + int1) -- and onwards; second Int provides arity | PROJECT Reg Int Int -- | probably not used | PROJECTINTO Reg Reg Int -- project argument from one reg into another -- | same as CASE, but there's an exact value (not constructor) in reg | CONSTCASE Reg [(Const, [BC])] (Maybe [BC]) -- | just call a function, passing MYOLDBASE (see below) to it | CALL Name -- | same, perhaps exists just for TCO | TAILCALL Name -- | set reg to (apply string args), | FOREIGNCALL Reg FDesc FDesc [(FDesc, Reg)] -- | move this number of elements from TOP to BASE | SLIDE Int -- | set BASE = OLDBASE | REBASE -- | reserve n more stack items (i.e. check there's space, grow if -- necessary) | RESERVE Int -- | move the top of stack up | ADDTOP Int -- | set TOP = BASE + n | TOPBASE Int -- | set BASE = TOP + n | BASETOP Int -- | set MYOLDBASE = BASE, where MYOLDBASE is a function-local -- variable, set to OLDBASE by default, and passed on function -- call to called functions as their OLDBASE | STOREOLD -- | reg = apply primitive_function args | OP Reg PrimFn [Reg] -- | clear reg | NULL Reg -- | throw an error | ERROR String deriving Show toBC :: (Name, SDecl) -> (Name, [BC]) toBC (n, SFun n' args locs exp) = (n, reserve locs ++ bc RVal exp True) where reserve 0 = [] reserve n = [RESERVE n, ADDTOP n] clean True = [TOPBASE 0, REBASE] clean False = [] bc :: Reg -> SExp -> Bool -> -- returning [BC] bc reg (SV (Glob n)) r = bc reg (SApp False n []) r bc reg (SV (Loc i)) r = assign reg (L i) ++ clean r bc reg (SApp False f vs) r = if argCount == 0 then moveReg 0 vs ++ [STOREOLD, BASETOP 0, CALL f] ++ ret else RESERVE argCount : moveReg 0 vs ++ [STOREOLD, BASETOP 0, ADDTOP argCount, CALL f] ++ ret where ret = assign reg RVal ++ clean r argCount = length vs bc reg (SApp True f vs) r = RESERVE (length vs) : moveReg 0 vs ++ [SLIDE (length vs), TOPBASE (length vs), TAILCALL f] bc reg (SForeign t fname args) r = FOREIGNCALL reg t fname (map farg args) : clean r where farg (ty, Loc i) = (ty, L i) bc reg (SLet (Loc i) e sc) r = bc (L i) e False ++ bc reg sc r bc reg (SUpdate (Loc i) sc) r = bc reg sc False ++ [ASSIGN (L i) reg] ++ clean r -- bc reg (SUpdate x sc) r = bc reg sc r -- can't update, just do it bc reg (SCon atloc i _ vs) r = MKCON reg (getAllocLoc atloc) i (map getL vs) : clean r where getL (Loc x) = L x getAllocLoc (Just (Loc x)) = Just (L x) getAllocLoc _ = Nothing bc reg (SProj (Loc l) i) r = PROJECTINTO reg (L l) i : clean r bc reg (SConst i) r = ASSIGNCONST reg i : clean r bc reg (SOp p vs) r = OP reg p (map getL vs) : clean r where getL (Loc x) = L x bc reg (SError str) r = [ERROR str] bc reg SNothing r = NULL reg : clean r bc reg (SCase up (Loc l) alts) r | isConst alts = constCase reg (L l) alts r | otherwise = conCase True reg (L l) alts r bc reg (SChkCase (Loc l) alts) r = conCase False reg (L l) alts r bc reg t r = error $ "Can't compile " ++ show t isConst [] = False isConst (SConstCase _ _ : xs) = True isConst (SConCase _ _ _ _ _ : xs) = False isConst (_ : xs) = False moveReg off [] = [] moveReg off (Loc x : xs) = assign (T off) (L x) ++ moveReg (off + 1) xs assign r1 r2 | r1 == r2 = [] | otherwise = [ASSIGN r1 r2] conCase safe reg l xs r = [CASE safe l (mapMaybe (caseAlt l reg r) xs) (defaultAlt reg xs r)] constCase reg l xs r = [CONSTCASE l (mapMaybe (constAlt l reg r) xs) (defaultAlt reg xs r)] caseAlt l reg r (SConCase lvar tag _ args e) = Just (tag, PROJECT l lvar (length args) : bc reg e r) caseAlt l reg r _ = Nothing constAlt l reg r (SConstCase c e) = Just (c, bc reg e r) constAlt l reg r _ = Nothing defaultAlt reg [] r = Nothing defaultAlt reg (SDefaultCase e : _) r = Just (bc reg e r) defaultAlt reg (_ : xs) r = defaultAlt reg xs r
uuhan/Idris-dev
src/IRTS/Bytecode.hs
bsd-3-clause
5,962
0
11
1,654
1,852
958
894
96
3
-- 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. module Duckling.Numeral.UK.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Numeral.UK.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "UK Tests" [ makeCorpusTest [This Numeral] corpus ]
rfranek/duckling
tests/Duckling/Numeral/UK/Tests.hs
bsd-3-clause
600
0
9
96
80
51
29
11
1
module Command.Helper where import qualified Server as S import qualified User as U import qualified Reply as R import qualified Message as M import System.IO import Control.Concurrent.MVar sendNeedMoreParams :: MVar U.User -> S.Server -> String -> IO () sendNeedMoreParams userVar serv cmd = do use <- takeMVar userVar let pref = M.ServerName (S.hostname serv) let rep = R.Reply pref 401 [U.nickname use, cmd] "Not enough parameters" R.sendReply (U.handle use) rep putMVar userVar use sendNoSuchNick :: MVar U.User -> S.Server -> String -> IO () sendNoSuchNick userVar serv cmd = do use <- takeMVar userVar let pref = M.ServerName (S.hostname serv) let rep = R.Reply pref 461 [U.nickname use, cmd] "No such nick/channel" R.sendReply (U.handle use) rep putMVar userVar use
allonsy/chirp
src/Command/Helper.hs
bsd-3-clause
797
0
13
143
301
151
150
21
1
----------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL -- Copyright : (c) Sven Panne 2002-2005 -- License : BSD-style (see the file libraries/OpenGL/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- A Haskell binding for OpenGL, the industry\'s most widely used and -- supported 2D and 3D graphics API. -- ----------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL ( -- * OpenGL Operation module Graphics.Rendering.OpenGL.GL.BasicTypes, module Graphics.Rendering.OpenGL.GL.BeginEnd, module Graphics.Rendering.OpenGL.GL.VertexSpec, module Graphics.Rendering.OpenGL.GL.VertexArrays, module Graphics.Rendering.OpenGL.GL.BufferObjects, module Graphics.Rendering.OpenGL.GL.Rectangles, module Graphics.Rendering.OpenGL.GL.CoordTrans, module Graphics.Rendering.OpenGL.GL.Clipping, module Graphics.Rendering.OpenGL.GL.RasterPos, module Graphics.Rendering.OpenGL.GL.Colors, -- * Rasterization module Graphics.Rendering.OpenGL.GL.Antialiasing, module Graphics.Rendering.OpenGL.GL.Points, module Graphics.Rendering.OpenGL.GL.LineSegments, module Graphics.Rendering.OpenGL.GL.Polygons, module Graphics.Rendering.OpenGL.GL.PixelRectangles, module Graphics.Rendering.OpenGL.GL.Bitmaps, module Graphics.Rendering.OpenGL.GL.Texturing, module Graphics.Rendering.OpenGL.GL.ColorSum, module Graphics.Rendering.OpenGL.GL.Fog, -- * Per-Fragment Operations and the Framebuffer module Graphics.Rendering.OpenGL.GL.PerFragment, module Graphics.Rendering.OpenGL.GL.Framebuffer, module Graphics.Rendering.OpenGL.GL.ReadCopyPixels, -- * Special Functions module Graphics.Rendering.OpenGL.GL.Evaluators, module Graphics.Rendering.OpenGL.GL.Selection, module Graphics.Rendering.OpenGL.GL.Feedback, module Graphics.Rendering.OpenGL.GL.DisplayLists, module Graphics.Rendering.OpenGL.GL.FlushFinish, module Graphics.Rendering.OpenGL.GL.Hints, -- * State and State Requests module Graphics.Rendering.OpenGL.GL.StateVar, module Graphics.Rendering.OpenGL.GL.StringQueries, module Graphics.Rendering.OpenGL.GL.SavingState ) where import Graphics.Rendering.OpenGL.GL.BasicTypes import Graphics.Rendering.OpenGL.GL.BeginEnd import Graphics.Rendering.OpenGL.GL.VertexSpec import Graphics.Rendering.OpenGL.GL.VertexArrays import Graphics.Rendering.OpenGL.GL.BufferObjects import Graphics.Rendering.OpenGL.GL.Rectangles import Graphics.Rendering.OpenGL.GL.CoordTrans import Graphics.Rendering.OpenGL.GL.Clipping import Graphics.Rendering.OpenGL.GL.RasterPos import Graphics.Rendering.OpenGL.GL.Colors import Graphics.Rendering.OpenGL.GL.Antialiasing import Graphics.Rendering.OpenGL.GL.Points import Graphics.Rendering.OpenGL.GL.LineSegments import Graphics.Rendering.OpenGL.GL.Polygons import Graphics.Rendering.OpenGL.GL.PixelRectangles import Graphics.Rendering.OpenGL.GL.Bitmaps import Graphics.Rendering.OpenGL.GL.Texturing import Graphics.Rendering.OpenGL.GL.ColorSum import Graphics.Rendering.OpenGL.GL.Fog import Graphics.Rendering.OpenGL.GL.PerFragment import Graphics.Rendering.OpenGL.GL.Framebuffer import Graphics.Rendering.OpenGL.GL.ReadCopyPixels import Graphics.Rendering.OpenGL.GL.Evaluators import Graphics.Rendering.OpenGL.GL.Selection import Graphics.Rendering.OpenGL.GL.Feedback import Graphics.Rendering.OpenGL.GL.DisplayLists import Graphics.Rendering.OpenGL.GL.FlushFinish import Graphics.Rendering.OpenGL.GL.Hints import Graphics.Rendering.OpenGL.GL.StateVar import Graphics.Rendering.OpenGL.GL.StringQueries import Graphics.Rendering.OpenGL.GL.SavingState
FranklinChen/hugs98-plus-Sep2006
packages/OpenGL/Graphics/Rendering/OpenGL/GL.hs
bsd-3-clause
3,761
0
5
349
556
429
127
63
0
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Bead.View.BeadContextInit ( beadContextInit , beadConfigFileName , InitTasks , Daemons(..) , usersJson ) where import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Data.Char (toUpper) import qualified Data.Map as Map import qualified Data.Set as Set import Snap hiding (Config(..)) import Snap.Snaplet.Auth import Snap.Snaplet.Auth.Backends.SafeJsonFile import Snap.Snaplet.Fay import Snap.Snaplet.Session.Backends.CookieSession import System.FilePath ((</>)) import System.Directory import Bead.Config import Bead.Controller.ServiceContext as S hiding (serviceContext) #ifdef EmailEnabled import Bead.Daemon.Email #endif #ifdef SSO import Bead.Daemon.LDAP #endif import Bead.Daemon.Logout import Bead.Domain.Entities (UserRegInfo, Username(..)) import Bead.Domain.TimeZone import Bead.View.BeadContext hiding (ldapDaemon) import Bead.View.DataDir import Bead.View.Dictionary (Language(..)) import Bead.View.DictionaryLoader (loadDictionaries) import Bead.View.Registration (createAdminUser) import Bead.View.Routing beadConfigFileName :: String beadConfigFileName = "bead.config" iconFileName :: String iconFileName = "icon.ico" usersJson :: String usersJson = "users.json" -- During the initialization what other tasks need to be done. -- Just userRegInfo means that a new admin user should be craeted -- Nothing means there is no additional init task to be done. type InitTasks = Maybe UserRegInfo -- The collection of the daemons that are neccesary to create the -- application data Daemons = Daemons { logoutDaemon :: LogoutDaemon #ifdef EmailEnabled , emailDaemon :: EmailDaemon #endif #ifdef SSO , ldapDaemon :: LDAPDaemon #endif } beadContextInit :: Config -> ServiceContext -> Daemons -> FilePath -> SnapletInit BeadContext BeadContext beadContextInit config s daemons tempDir = makeSnaplet "bead" description dataDir $ do copyDataContext sm <- nestSnaplet "session" sessionManager $ initCookieSessionManager "cookie" "session" (Just (sessionTimeout config)) as <- nestSnaplet "auth" auth $ initSafeJsonFileAuthManager defAuthSettings sessionManager usersJson ss <- nestSnaplet "context" serviceContext $ contextSnaplet s (logoutDaemon daemons) let dictionaryDir = "lang" dExist <- liftIO $ doesDirectoryExist dictionaryDir dictResult <- case dExist of True -> liftIO $ loadDictionaries dictionaryDir False -> return $ Right $ Map.empty liftIO $ putStrLn "Searching for dictionaries..." ds <- case dictResult of Left err -> error $ "ERROR: Conflicts while processing dictionaries:\n\n" ++ err Right dictionaries -> do -- TODO: Use a start logger liftIO $ putStrLn $ "Found dictionaries: " ++ (show $ Map.keys dictionaries) nestSnaplet "dictionary" dictionaryContext $ dictionarySnaplet dictionaries (Language $ defaultLoginLanguage config) #ifdef EmailEnabled se <- nestSnaplet "sendemail" sendEmailContext (emailSenderSnaplet config (emailDaemon daemons)) #endif rp <- nestSnaplet "randompassword" randomPasswordContext passwordGeneratorSnaplet fs <- nestSnaplet "fay" fayContext $ initFay ts <- nestSnaplet "tempdir" tempDirContext $ tempDirectorySnaplet tempDir cs <- nestSnaplet "config" configContext $ configurationServiceContext config #ifndef SSO un <- nestSnaplet "usernamechecker" checkUsernameContext $ regexpUsernameChecker config #endif timeZoneConverter <- liftIO $ createTimeZoneConverter (timeZoneInfoDirectory config) tz <- nestSnaplet "timezoneconveter" timeZoneContext $ createTimeZoneContext timeZoneConverter dl <- nestSnaplet "debuglogger" debugLoggerContext $ createDebugLogger #ifdef SSO ldap <- do nestSnaplet "ldap-config" ldapContext $ createLDAPContext (LDAP $ ldapDaemon daemons) #endif addRoutes (routes config) wrapSite (<|> pages) return $ #ifdef SSO #ifdef EmailEnabled BeadContext sm as ss ds se rp fs ts cs tz dl ldap #else BeadContext sm as ss ds rp fs ts cs tz dl ldap #endif #else #ifdef EmailEnabled BeadContext sm as ss ds se rp fs ts cs un tz dl #else BeadContext sm as ss ds rp fs ts cs un tz dl #endif #endif where description = "The BEAD website" dataDir = Just referenceDataDir -- | Creating data context in the current directory, -- copying reference files. copyDataContext :: Initializer b v () copyDataContext = do reference <- liftIO referenceDataDir dataDir <- getSnapletFilePath let skips = [beadConfigFileName, iconFileName] liftIO $ copyFiles skips reference dataDir return () -- | Copy and update files if missing or outdated, skip the ones -- from the outdate check that names are the same as in the skipped list copyFiles :: [FilePath] -> FilePath -> FilePath -> IO () copyFiles skips src dst = do dstExist <- doesDirectoryExist dst unless dstExist $ createDirectory dst contents <- getDirectoryContents src let xs = filter (`notElem` [".", ".."]) contents forM_ xs $ \name -> do let srcPath = src </> name dstPath = dst </> name isDirectory <- doesDirectoryExist srcPath if isDirectory then copyFiles skips srcPath dstPath else do dstFileExist <- doesFileExist dstPath when (not dstFileExist || name `notElem` skips) $ do doCopy <- if dstFileExist then do srcDate <- getModificationTime srcPath dstDate <- getModificationTime dstPath return $ dstDate < srcDate else return True when doCopy $ copyFile srcPath dstPath
pgj/bead
src/Bead/View/BeadContextInit.hs
bsd-3-clause
5,912
0
22
1,289
1,259
660
599
105
3
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- -- Pretty-printing assembly language -- -- (c) The University of Glasgow 1993-2005 -- ----------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-orphans #-} module X86.Ppr ( pprNatCmmDecl, pprData, pprInstr, pprFormat, pprImm, pprDataItem, ) where #include "HsVersions.h" import GhcPrelude import X86.Regs import X86.Instr import X86.Cond import Instruction import Format import Reg import PprBase import GHC.Cmm.Dataflow.Collections import GHC.Cmm.Dataflow.Label import BasicTypes (Alignment, mkAlignment, alignmentBytes) import DynFlags import GHC.Cmm hiding (topInfoTable) import GHC.Cmm.BlockId import GHC.Cmm.CLabel import Unique ( pprUniqueAlways ) import GHC.Platform import FastString import Outputable import Data.Word import Data.Bits -- ----------------------------------------------------------------------------- -- Printing this stuff out -- -- -- Note [Subsections Via Symbols] -- -- If we are using the .subsections_via_symbols directive -- (available on recent versions of Darwin), -- we have to make sure that there is some kind of reference -- from the entry code to a label on the _top_ of of the info table, -- so that the linker will not think it is unreferenced and dead-strip -- it. That's why the label is called a DeadStripPreventer (_dsp). -- -- The LLVM code gen already creates `iTableSuf` symbols, where -- the X86 would generate the DeadStripPreventer (_dsp) symbol. -- Therefore all that is left for llvm code gen, is to ensure -- that all the `iTableSuf` symbols are marked as used. -- As of this writing the documentation regarding the -- .subsections_via_symbols and -dead_strip can be found at -- <https://developer.apple.com/library/mac/documentation/DeveloperTools/Reference/Assembler/040-Assembler_Directives/asm_directives.html#//apple_ref/doc/uid/TP30000823-TPXREF101> pprProcAlignment :: SDoc pprProcAlignment = sdocWithDynFlags $ \dflags -> (maybe empty (pprAlign . mkAlignment) (cmmProcAlignment dflags)) pprNatCmmDecl :: NatCmmDecl (Alignment, RawCmmStatics) Instr -> SDoc pprNatCmmDecl (CmmData section dats) = pprSectionAlign section $$ pprDatas dats pprNatCmmDecl proc@(CmmProc top_info lbl _ (ListGraph blocks)) = sdocWithDynFlags $ \dflags -> pprProcAlignment $$ case topInfoTable proc of Nothing -> -- special case for code without info table: pprSectionAlign (Section Text lbl) $$ pprProcAlignment $$ pprLabel lbl $$ -- blocks guaranteed not null, so label needed vcat (map (pprBasicBlock top_info) blocks) $$ (if debugLevel dflags > 0 then ppr (mkAsmTempEndLabel lbl) <> char ':' else empty) $$ pprSizeDecl lbl Just (RawCmmStatics info_lbl _) -> sdocWithPlatform $ \platform -> pprSectionAlign (Section Text info_lbl) $$ pprProcAlignment $$ (if platformHasSubsectionsViaSymbols platform then ppr (mkDeadStripPreventer info_lbl) <> char ':' else empty) $$ vcat (map (pprBasicBlock top_info) blocks) $$ -- above: Even the first block gets a label, because with branch-chain -- elimination, it might be the target of a goto. (if platformHasSubsectionsViaSymbols platform then -- See Note [Subsections Via Symbols] text "\t.long " <+> ppr info_lbl <+> char '-' <+> ppr (mkDeadStripPreventer info_lbl) else empty) $$ pprSizeDecl info_lbl -- | Output the ELF .size directive. pprSizeDecl :: CLabel -> SDoc pprSizeDecl lbl = sdocWithPlatform $ \platform -> if osElfTarget (platformOS platform) then text "\t.size" <+> ppr lbl <> ptext (sLit ", .-") <> ppr lbl else empty pprBasicBlock :: LabelMap RawCmmStatics -> NatBasicBlock Instr -> SDoc pprBasicBlock info_env (BasicBlock blockid instrs) = sdocWithDynFlags $ \dflags -> maybe_infotable dflags $ pprLabel asmLbl $$ vcat (map pprInstr instrs) $$ (if debugLevel dflags > 0 then ppr (mkAsmTempEndLabel asmLbl) <> char ':' else empty) where asmLbl = blockLbl blockid maybe_infotable dflags c = case mapLookup blockid info_env of Nothing -> c Just (RawCmmStatics infoLbl info) -> pprAlignForSection Text $$ infoTableLoc $$ vcat (map pprData info) $$ pprLabel infoLbl $$ c $$ (if debugLevel dflags > 0 then ppr (mkAsmTempEndLabel infoLbl) <> char ':' else empty) -- Make sure the info table has the right .loc for the block -- coming right after it. See [Note: Info Offset] infoTableLoc = case instrs of (l@LOCATION{} : _) -> pprInstr l _other -> empty pprDatas :: (Alignment, RawCmmStatics) -> SDoc -- See note [emit-time elimination of static indirections] in CLabel. pprDatas (_, RawCmmStatics alias [CmmStaticLit (CmmLabel lbl), CmmStaticLit ind, _, _]) | lbl == mkIndStaticInfoLabel , let labelInd (CmmLabelOff l _) = Just l labelInd (CmmLabel l) = Just l labelInd _ = Nothing , Just ind' <- labelInd ind , alias `mayRedirectTo` ind' = pprGloblDecl alias $$ text ".equiv" <+> ppr alias <> comma <> ppr (CmmLabel ind') pprDatas (align, (RawCmmStatics lbl dats)) = vcat (pprAlign align : pprLabel lbl : map pprData dats) pprData :: CmmStatic -> SDoc pprData (CmmString str) = pprBytes str pprData (CmmUninitialised bytes) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then text ".space " <> int bytes else text ".skip " <> int bytes pprData (CmmStaticLit lit) = pprDataItem lit pprGloblDecl :: CLabel -> SDoc pprGloblDecl lbl | not (externallyVisibleCLabel lbl) = empty | otherwise = text ".globl " <> ppr lbl pprLabelType' :: DynFlags -> CLabel -> SDoc pprLabelType' dflags lbl = if isCFunctionLabel lbl || functionOkInfoTable then text "@function" else text "@object" where {- NOTE: This is a bit hacky. With the `tablesNextToCode` info tables look like this: ``` <info table data> label_info: <info table code> ``` So actually info table label points exactly to the code and we can mark the label as @function. (This is required to make perf and potentially other tools to work on Haskell binaries). This usually works well but it can cause issues with a linker. A linker uses different algorithms for the relocation depending on the symbol type.For some reason, a linker will generate JUMP_SLOT relocation when constructor info table is referenced from a data section. This only happens with static constructor call so we mark _con_info symbols as `@object` to avoid the issue with relocations. @SimonMarlow hack explanation: "The reasoning goes like this: * The danger when we mark a symbol as `@function` is that the linker will redirect it to point to the PLT and use a `JUMP_SLOT` relocation when the symbol refers to something outside the current shared object. A PLT / JUMP_SLOT reference only works for symbols that we jump to, not for symbols representing data,, nor for info table symbol references which we expect to point directly to the info table. * GHC generates code that might refer to any info table symbol from the text segment, but that's OK, because those will be explicit GOT references generated by the code generator. * When we refer to info tables from the data segment, it's either * a FUN_STATIC/THUNK_STATIC local to this module * a `con_info` that could be from anywhere So, the only info table symbols that we might refer to from the data segment of another shared object are `con_info` symbols, so those are the ones we need to exclude from getting the @function treatment. " A good place to check for more https://gitlab.haskell.org/ghc/ghc/wikis/commentary/position-independent-code Another possible hack is to create an extra local function symbol for every code-like thing to give the needed information for to the tools but mess up with the relocation. https://phabricator.haskell.org/D4730 -} functionOkInfoTable = tablesNextToCode dflags && isInfoTableLabel lbl && not (isConInfoTableLabel lbl) pprTypeDecl :: CLabel -> SDoc pprTypeDecl lbl = sdocWithPlatform $ \platform -> if osElfTarget (platformOS platform) && externallyVisibleCLabel lbl then sdocWithDynFlags $ \df -> text ".type " <> ppr lbl <> ptext (sLit ", ") <> pprLabelType' df lbl else empty pprLabel :: CLabel -> SDoc pprLabel lbl = pprGloblDecl lbl $$ pprTypeDecl lbl $$ (ppr lbl <> char ':') pprAlign :: Alignment -> SDoc pprAlign alignment = sdocWithPlatform $ \platform -> text ".align " <> int (alignmentOn platform) where bytes = alignmentBytes alignment alignmentOn platform = if platformOS platform == OSDarwin then log2 bytes else bytes log2 :: Int -> Int -- cache the common ones log2 1 = 0 log2 2 = 1 log2 4 = 2 log2 8 = 3 log2 n = 1 + log2 (n `quot` 2) -- ----------------------------------------------------------------------------- -- pprInstr: print an 'Instr' instance Outputable Instr where ppr instr = pprInstr instr pprReg :: Format -> Reg -> SDoc pprReg f r = case r of RegReal (RealRegSingle i) -> sdocWithPlatform $ \platform -> if target32Bit platform then ppr32_reg_no f i else ppr64_reg_no f i RegReal (RealRegPair _ _) -> panic "X86.Ppr: no reg pairs on this arch" RegVirtual (VirtualRegI u) -> text "%vI_" <> pprUniqueAlways u RegVirtual (VirtualRegHi u) -> text "%vHi_" <> pprUniqueAlways u RegVirtual (VirtualRegF u) -> text "%vF_" <> pprUniqueAlways u RegVirtual (VirtualRegD u) -> text "%vD_" <> pprUniqueAlways u where ppr32_reg_no :: Format -> Int -> SDoc ppr32_reg_no II8 = ppr32_reg_byte ppr32_reg_no II16 = ppr32_reg_word ppr32_reg_no _ = ppr32_reg_long ppr32_reg_byte i = ptext (case i of { 0 -> sLit "%al"; 1 -> sLit "%bl"; 2 -> sLit "%cl"; 3 -> sLit "%dl"; _ -> sLit $ "very naughty I386 byte register: " ++ show i }) ppr32_reg_word i = ptext (case i of { 0 -> sLit "%ax"; 1 -> sLit "%bx"; 2 -> sLit "%cx"; 3 -> sLit "%dx"; 4 -> sLit "%si"; 5 -> sLit "%di"; 6 -> sLit "%bp"; 7 -> sLit "%sp"; _ -> sLit "very naughty I386 word register" }) ppr32_reg_long i = ptext (case i of { 0 -> sLit "%eax"; 1 -> sLit "%ebx"; 2 -> sLit "%ecx"; 3 -> sLit "%edx"; 4 -> sLit "%esi"; 5 -> sLit "%edi"; 6 -> sLit "%ebp"; 7 -> sLit "%esp"; _ -> ppr_reg_float i }) ppr64_reg_no :: Format -> Int -> SDoc ppr64_reg_no II8 = ppr64_reg_byte ppr64_reg_no II16 = ppr64_reg_word ppr64_reg_no II32 = ppr64_reg_long ppr64_reg_no _ = ppr64_reg_quad ppr64_reg_byte i = ptext (case i of { 0 -> sLit "%al"; 1 -> sLit "%bl"; 2 -> sLit "%cl"; 3 -> sLit "%dl"; 4 -> sLit "%sil"; 5 -> sLit "%dil"; -- new 8-bit regs! 6 -> sLit "%bpl"; 7 -> sLit "%spl"; 8 -> sLit "%r8b"; 9 -> sLit "%r9b"; 10 -> sLit "%r10b"; 11 -> sLit "%r11b"; 12 -> sLit "%r12b"; 13 -> sLit "%r13b"; 14 -> sLit "%r14b"; 15 -> sLit "%r15b"; _ -> sLit $ "very naughty x86_64 byte register: " ++ show i }) ppr64_reg_word i = ptext (case i of { 0 -> sLit "%ax"; 1 -> sLit "%bx"; 2 -> sLit "%cx"; 3 -> sLit "%dx"; 4 -> sLit "%si"; 5 -> sLit "%di"; 6 -> sLit "%bp"; 7 -> sLit "%sp"; 8 -> sLit "%r8w"; 9 -> sLit "%r9w"; 10 -> sLit "%r10w"; 11 -> sLit "%r11w"; 12 -> sLit "%r12w"; 13 -> sLit "%r13w"; 14 -> sLit "%r14w"; 15 -> sLit "%r15w"; _ -> sLit "very naughty x86_64 word register" }) ppr64_reg_long i = ptext (case i of { 0 -> sLit "%eax"; 1 -> sLit "%ebx"; 2 -> sLit "%ecx"; 3 -> sLit "%edx"; 4 -> sLit "%esi"; 5 -> sLit "%edi"; 6 -> sLit "%ebp"; 7 -> sLit "%esp"; 8 -> sLit "%r8d"; 9 -> sLit "%r9d"; 10 -> sLit "%r10d"; 11 -> sLit "%r11d"; 12 -> sLit "%r12d"; 13 -> sLit "%r13d"; 14 -> sLit "%r14d"; 15 -> sLit "%r15d"; _ -> sLit "very naughty x86_64 register" }) ppr64_reg_quad i = ptext (case i of { 0 -> sLit "%rax"; 1 -> sLit "%rbx"; 2 -> sLit "%rcx"; 3 -> sLit "%rdx"; 4 -> sLit "%rsi"; 5 -> sLit "%rdi"; 6 -> sLit "%rbp"; 7 -> sLit "%rsp"; 8 -> sLit "%r8"; 9 -> sLit "%r9"; 10 -> sLit "%r10"; 11 -> sLit "%r11"; 12 -> sLit "%r12"; 13 -> sLit "%r13"; 14 -> sLit "%r14"; 15 -> sLit "%r15"; _ -> ppr_reg_float i }) ppr_reg_float :: Int -> PtrString ppr_reg_float i = case i of 16 -> sLit "%xmm0" ; 17 -> sLit "%xmm1" 18 -> sLit "%xmm2" ; 19 -> sLit "%xmm3" 20 -> sLit "%xmm4" ; 21 -> sLit "%xmm5" 22 -> sLit "%xmm6" ; 23 -> sLit "%xmm7" 24 -> sLit "%xmm8" ; 25 -> sLit "%xmm9" 26 -> sLit "%xmm10"; 27 -> sLit "%xmm11" 28 -> sLit "%xmm12"; 29 -> sLit "%xmm13" 30 -> sLit "%xmm14"; 31 -> sLit "%xmm15" _ -> sLit "very naughty x86 register" pprFormat :: Format -> SDoc pprFormat x = ptext (case x of II8 -> sLit "b" II16 -> sLit "w" II32 -> sLit "l" II64 -> sLit "q" FF32 -> sLit "ss" -- "scalar single-precision float" (SSE2) FF64 -> sLit "sd" -- "scalar double-precision float" (SSE2) ) pprFormat_x87 :: Format -> SDoc pprFormat_x87 x = ptext $ case x of FF32 -> sLit "s" FF64 -> sLit "l" _ -> panic "X86.Ppr.pprFormat_x87" pprCond :: Cond -> SDoc pprCond c = ptext (case c of { GEU -> sLit "ae"; LU -> sLit "b"; EQQ -> sLit "e"; GTT -> sLit "g"; GE -> sLit "ge"; GU -> sLit "a"; LTT -> sLit "l"; LE -> sLit "le"; LEU -> sLit "be"; NE -> sLit "ne"; NEG -> sLit "s"; POS -> sLit "ns"; CARRY -> sLit "c"; OFLO -> sLit "o"; PARITY -> sLit "p"; NOTPARITY -> sLit "np"; ALWAYS -> sLit "mp"}) pprImm :: Imm -> SDoc pprImm (ImmInt i) = int i pprImm (ImmInteger i) = integer i pprImm (ImmCLbl l) = ppr l pprImm (ImmIndex l i) = ppr l <> char '+' <> int i pprImm (ImmLit s) = s pprImm (ImmFloat _) = text "naughty float immediate" pprImm (ImmDouble _) = text "naughty double immediate" pprImm (ImmConstantSum a b) = pprImm a <> char '+' <> pprImm b pprImm (ImmConstantDiff a b) = pprImm a <> char '-' <> lparen <> pprImm b <> rparen pprAddr :: AddrMode -> SDoc pprAddr (ImmAddr imm off) = let pp_imm = pprImm imm in if (off == 0) then pp_imm else if (off < 0) then pp_imm <> int off else pp_imm <> char '+' <> int off pprAddr (AddrBaseIndex base index displacement) = sdocWithPlatform $ \platform -> let pp_disp = ppr_disp displacement pp_off p = pp_disp <> char '(' <> p <> char ')' pp_reg r = pprReg (archWordFormat (target32Bit platform)) r in case (base, index) of (EABaseNone, EAIndexNone) -> pp_disp (EABaseReg b, EAIndexNone) -> pp_off (pp_reg b) (EABaseRip, EAIndexNone) -> pp_off (text "%rip") (EABaseNone, EAIndex r i) -> pp_off (comma <> pp_reg r <> comma <> int i) (EABaseReg b, EAIndex r i) -> pp_off (pp_reg b <> comma <> pp_reg r <> comma <> int i) _ -> panic "X86.Ppr.pprAddr: no match" where ppr_disp (ImmInt 0) = empty ppr_disp imm = pprImm imm -- | Print section header and appropriate alignment for that section. pprSectionAlign :: Section -> SDoc pprSectionAlign (Section (OtherSection _) _) = panic "X86.Ppr.pprSectionAlign: unknown section" pprSectionAlign sec@(Section seg _) = sdocWithPlatform $ \platform -> pprSectionHeader platform sec $$ pprAlignForSection seg -- | Print appropriate alignment for the given section type. pprAlignForSection :: SectionType -> SDoc pprAlignForSection seg = sdocWithPlatform $ \platform -> text ".align " <> case platformOS platform of -- Darwin: alignments are given as shifts. OSDarwin | target32Bit platform -> case seg of ReadOnlyData16 -> int 4 CString -> int 1 _ -> int 2 | otherwise -> case seg of ReadOnlyData16 -> int 4 CString -> int 1 _ -> int 3 -- Other: alignments are given as bytes. _ | target32Bit platform -> case seg of Text -> text "4,0x90" ReadOnlyData16 -> int 16 CString -> int 1 _ -> int 4 | otherwise -> case seg of ReadOnlyData16 -> int 16 CString -> int 1 _ -> int 8 pprDataItem :: CmmLit -> SDoc pprDataItem lit = sdocWithDynFlags $ \dflags -> pprDataItem' dflags lit pprDataItem' :: DynFlags -> CmmLit -> SDoc pprDataItem' dflags lit = vcat (ppr_item (cmmTypeFormat $ cmmLitType dflags lit) lit) where platform = targetPlatform dflags imm = litToImm lit -- These seem to be common: ppr_item II8 _ = [text "\t.byte\t" <> pprImm imm] ppr_item II16 _ = [text "\t.word\t" <> pprImm imm] ppr_item II32 _ = [text "\t.long\t" <> pprImm imm] ppr_item FF32 (CmmFloat r _) = let bs = floatToBytes (fromRational r) in map (\b -> text "\t.byte\t" <> pprImm (ImmInt b)) bs ppr_item FF64 (CmmFloat r _) = let bs = doubleToBytes (fromRational r) in map (\b -> text "\t.byte\t" <> pprImm (ImmInt b)) bs ppr_item II64 _ = case platformOS platform of OSDarwin | target32Bit platform -> case lit of CmmInt x _ -> [text "\t.long\t" <> int (fromIntegral (fromIntegral x :: Word32)), text "\t.long\t" <> int (fromIntegral (fromIntegral (x `shiftR` 32) :: Word32))] _ -> panic "X86.Ppr.ppr_item: no match for II64" | otherwise -> [text "\t.quad\t" <> pprImm imm] _ | target32Bit platform -> [text "\t.quad\t" <> pprImm imm] | otherwise -> -- x86_64: binutils can't handle the R_X86_64_PC64 -- relocation type, which means we can't do -- pc-relative 64-bit addresses. Fortunately we're -- assuming the small memory model, in which all such -- offsets will fit into 32 bits, so we have to stick -- to 32-bit offset fields and modify the RTS -- appropriately -- -- See Note [x86-64-relative] in includes/rts/storage/InfoTables.h -- case lit of -- A relative relocation: CmmLabelDiffOff _ _ _ _ -> [text "\t.long\t" <> pprImm imm, text "\t.long\t0"] _ -> [text "\t.quad\t" <> pprImm imm] ppr_item _ _ = panic "X86.Ppr.ppr_item: no match" asmComment :: SDoc -> SDoc asmComment c = whenPprDebug $ text "# " <> c pprInstr :: Instr -> SDoc pprInstr (COMMENT s) = asmComment (ftext s) pprInstr (LOCATION file line col _name) = text "\t.loc " <> ppr file <+> ppr line <+> ppr col pprInstr (DELTA d) = asmComment $ text ("\tdelta = " ++ show d) pprInstr (NEWBLOCK _) = panic "PprMach.pprInstr: NEWBLOCK" pprInstr (UNWIND lbl d) = asmComment (text "\tunwind = " <> ppr d) $$ ppr lbl <> colon pprInstr (LDATA _ _) = panic "PprMach.pprInstr: LDATA" {- pprInstr (SPILL reg slot) = hcat [ text "\tSPILL", char ' ', pprUserReg reg, comma, text "SLOT" <> parens (int slot)] pprInstr (RELOAD slot reg) = hcat [ text "\tRELOAD", char ' ', text "SLOT" <> parens (int slot), comma, pprUserReg reg] -} -- Replace 'mov $0x0,%reg' by 'xor %reg,%reg', which is smaller and cheaper. -- The code generator catches most of these already, but not all. pprInstr (MOV format (OpImm (ImmInt 0)) dst@(OpReg _)) = pprInstr (XOR format' dst dst) where format' = case format of II64 -> II32 -- 32-bit version is equivalent, and smaller _ -> format pprInstr (MOV format src dst) = pprFormatOpOp (sLit "mov") format src dst pprInstr (CMOV cc format src dst) = pprCondOpReg (sLit "cmov") format cc src dst pprInstr (MOVZxL II32 src dst) = pprFormatOpOp (sLit "mov") II32 src dst -- 32-to-64 bit zero extension on x86_64 is accomplished by a simple -- movl. But we represent it as a MOVZxL instruction, because -- the reg alloc would tend to throw away a plain reg-to-reg -- move, and we still want it to do that. pprInstr (MOVZxL formats src dst) = pprFormatOpOpCoerce (sLit "movz") formats II32 src dst -- zero-extension only needs to extend to 32 bits: on x86_64, -- the remaining zero-extension to 64 bits is automatic, and the 32-bit -- instruction is shorter. pprInstr (MOVSxL formats src dst) = sdocWithPlatform $ \platform -> pprFormatOpOpCoerce (sLit "movs") formats (archWordFormat (target32Bit platform)) src dst -- here we do some patching, since the physical registers are only set late -- in the code generation. pprInstr (LEA format (OpAddr (AddrBaseIndex (EABaseReg reg1) (EAIndex reg2 1) (ImmInt 0))) dst@(OpReg reg3)) | reg1 == reg3 = pprFormatOpOp (sLit "add") format (OpReg reg2) dst pprInstr (LEA format (OpAddr (AddrBaseIndex (EABaseReg reg1) (EAIndex reg2 1) (ImmInt 0))) dst@(OpReg reg3)) | reg2 == reg3 = pprFormatOpOp (sLit "add") format (OpReg reg1) dst pprInstr (LEA format (OpAddr (AddrBaseIndex (EABaseReg reg1) EAIndexNone displ)) dst@(OpReg reg3)) | reg1 == reg3 = pprInstr (ADD format (OpImm displ) dst) pprInstr (LEA format src dst) = pprFormatOpOp (sLit "lea") format src dst pprInstr (ADD format (OpImm (ImmInt (-1))) dst) = pprFormatOp (sLit "dec") format dst pprInstr (ADD format (OpImm (ImmInt 1)) dst) = pprFormatOp (sLit "inc") format dst pprInstr (ADD format src dst) = pprFormatOpOp (sLit "add") format src dst pprInstr (ADC format src dst) = pprFormatOpOp (sLit "adc") format src dst pprInstr (SUB format src dst) = pprFormatOpOp (sLit "sub") format src dst pprInstr (SBB format src dst) = pprFormatOpOp (sLit "sbb") format src dst pprInstr (IMUL format op1 op2) = pprFormatOpOp (sLit "imul") format op1 op2 pprInstr (ADD_CC format src dst) = pprFormatOpOp (sLit "add") format src dst pprInstr (SUB_CC format src dst) = pprFormatOpOp (sLit "sub") format src dst {- A hack. The Intel documentation says that "The two and three operand forms [of IMUL] may also be used with unsigned operands because the lower half of the product is the same regardless if (sic) the operands are signed or unsigned. The CF and OF flags, however, cannot be used to determine if the upper half of the result is non-zero." So there. -} -- Use a 32-bit instruction when possible as it saves a byte. -- Notably, extracting the tag bits of a pointer has this form. -- TODO: we could save a byte in a subsequent CMP instruction too, -- but need something like a peephole pass for this pprInstr (AND II64 src@(OpImm (ImmInteger mask)) dst) | 0 <= mask && mask < 0xffffffff = pprInstr (AND II32 src dst) pprInstr (AND FF32 src dst) = pprOpOp (sLit "andps") FF32 src dst pprInstr (AND FF64 src dst) = pprOpOp (sLit "andpd") FF64 src dst pprInstr (AND format src dst) = pprFormatOpOp (sLit "and") format src dst pprInstr (OR format src dst) = pprFormatOpOp (sLit "or") format src dst pprInstr (XOR FF32 src dst) = pprOpOp (sLit "xorps") FF32 src dst pprInstr (XOR FF64 src dst) = pprOpOp (sLit "xorpd") FF64 src dst pprInstr (XOR format src dst) = pprFormatOpOp (sLit "xor") format src dst pprInstr (POPCNT format src dst) = pprOpOp (sLit "popcnt") format src (OpReg dst) pprInstr (LZCNT format src dst) = pprOpOp (sLit "lzcnt") format src (OpReg dst) pprInstr (TZCNT format src dst) = pprOpOp (sLit "tzcnt") format src (OpReg dst) pprInstr (BSF format src dst) = pprOpOp (sLit "bsf") format src (OpReg dst) pprInstr (BSR format src dst) = pprOpOp (sLit "bsr") format src (OpReg dst) pprInstr (PDEP format src mask dst) = pprFormatOpOpReg (sLit "pdep") format src mask dst pprInstr (PEXT format src mask dst) = pprFormatOpOpReg (sLit "pext") format src mask dst pprInstr (PREFETCH NTA format src ) = pprFormatOp_ (sLit "prefetchnta") format src pprInstr (PREFETCH Lvl0 format src) = pprFormatOp_ (sLit "prefetcht0") format src pprInstr (PREFETCH Lvl1 format src) = pprFormatOp_ (sLit "prefetcht1") format src pprInstr (PREFETCH Lvl2 format src) = pprFormatOp_ (sLit "prefetcht2") format src pprInstr (NOT format op) = pprFormatOp (sLit "not") format op pprInstr (BSWAP format op) = pprFormatOp (sLit "bswap") format (OpReg op) pprInstr (NEGI format op) = pprFormatOp (sLit "neg") format op pprInstr (SHL format src dst) = pprShift (sLit "shl") format src dst pprInstr (SAR format src dst) = pprShift (sLit "sar") format src dst pprInstr (SHR format src dst) = pprShift (sLit "shr") format src dst pprInstr (BT format imm src) = pprFormatImmOp (sLit "bt") format imm src pprInstr (CMP format src dst) | isFloatFormat format = pprFormatOpOp (sLit "ucomi") format src dst -- SSE2 | otherwise = pprFormatOpOp (sLit "cmp") format src dst pprInstr (TEST format src dst) = sdocWithPlatform $ \platform -> let format' = case (src,dst) of -- Match instructions like 'test $0x3,%esi' or 'test $0x7,%rbx'. -- We can replace them by equivalent, but smaller instructions -- by reducing the size of the immediate operand as far as possible. -- (We could handle masks larger than a single byte too, -- but it would complicate the code considerably -- and tag checks are by far the most common case.) -- The mask must have the high bit clear for this smaller encoding -- to be completely equivalent to the original; in particular so -- that the signed comparison condition bits are the same as they -- would be if doing a full word comparison. See #13425. (OpImm (ImmInteger mask), OpReg dstReg) | 0 <= mask && mask < 128 -> minSizeOfReg platform dstReg _ -> format in pprFormatOpOp (sLit "test") format' src dst where minSizeOfReg platform (RegReal (RealRegSingle i)) | target32Bit platform && i <= 3 = II8 -- al, bl, cl, dl | target32Bit platform && i <= 7 = II16 -- si, di, bp, sp | not (target32Bit platform) && i <= 15 = II8 -- al .. r15b minSizeOfReg _ _ = format -- other pprInstr (PUSH format op) = pprFormatOp (sLit "push") format op pprInstr (POP format op) = pprFormatOp (sLit "pop") format op -- both unused (SDM): -- pprInstr PUSHA = text "\tpushal" -- pprInstr POPA = text "\tpopal" pprInstr NOP = text "\tnop" pprInstr (CLTD II8) = text "\tcbtw" pprInstr (CLTD II16) = text "\tcwtd" pprInstr (CLTD II32) = text "\tcltd" pprInstr (CLTD II64) = text "\tcqto" pprInstr (CLTD x) = panic $ "pprInstr: " ++ show x pprInstr (SETCC cond op) = pprCondInstr (sLit "set") cond (pprOperand II8 op) pprInstr (JXX cond blockid) = pprCondInstr (sLit "j") cond (ppr lab) where lab = blockLbl blockid pprInstr (JXX_GBL cond imm) = pprCondInstr (sLit "j") cond (pprImm imm) pprInstr (JMP (OpImm imm) _) = text "\tjmp " <> pprImm imm pprInstr (JMP op _) = sdocWithPlatform $ \platform -> text "\tjmp *" <> pprOperand (archWordFormat (target32Bit platform)) op pprInstr (JMP_TBL op _ _ _) = pprInstr (JMP op []) pprInstr (CALL (Left imm) _) = text "\tcall " <> pprImm imm pprInstr (CALL (Right reg) _) = sdocWithPlatform $ \platform -> text "\tcall *" <> pprReg (archWordFormat (target32Bit platform)) reg pprInstr (IDIV fmt op) = pprFormatOp (sLit "idiv") fmt op pprInstr (DIV fmt op) = pprFormatOp (sLit "div") fmt op pprInstr (IMUL2 fmt op) = pprFormatOp (sLit "imul") fmt op -- x86_64 only pprInstr (MUL format op1 op2) = pprFormatOpOp (sLit "mul") format op1 op2 pprInstr (MUL2 format op) = pprFormatOp (sLit "mul") format op pprInstr (FDIV format op1 op2) = pprFormatOpOp (sLit "div") format op1 op2 pprInstr (SQRT format op1 op2) = pprFormatOpReg (sLit "sqrt") format op1 op2 pprInstr (CVTSS2SD from to) = pprRegReg (sLit "cvtss2sd") from to pprInstr (CVTSD2SS from to) = pprRegReg (sLit "cvtsd2ss") from to pprInstr (CVTTSS2SIQ fmt from to) = pprFormatFormatOpReg (sLit "cvttss2si") FF32 fmt from to pprInstr (CVTTSD2SIQ fmt from to) = pprFormatFormatOpReg (sLit "cvttsd2si") FF64 fmt from to pprInstr (CVTSI2SS fmt from to) = pprFormatOpReg (sLit "cvtsi2ss") fmt from to pprInstr (CVTSI2SD fmt from to) = pprFormatOpReg (sLit "cvtsi2sd") fmt from to -- FETCHGOT for PIC on ELF platforms pprInstr (FETCHGOT reg) = vcat [ text "\tcall 1f", hcat [ text "1:\tpopl\t", pprReg II32 reg ], hcat [ text "\taddl\t$_GLOBAL_OFFSET_TABLE_+(.-1b), ", pprReg II32 reg ] ] -- FETCHPC for PIC on Darwin/x86 -- get the instruction pointer into a register -- (Terminology note: the IP is called Program Counter on PPC, -- and it's a good thing to use the same name on both platforms) pprInstr (FETCHPC reg) = vcat [ text "\tcall 1f", hcat [ text "1:\tpopl\t", pprReg II32 reg ] ] -- the -- GST fmt src addr ==> FLD dst ; FSTPsz addr pprInstr g@(X87Store fmt addr) = pprX87 g (hcat [gtab, text "fstp", pprFormat_x87 fmt, gsp, pprAddr addr]) -- Atomics pprInstr (LOCK i) = text "\tlock" $$ pprInstr i pprInstr MFENCE = text "\tmfence" pprInstr (XADD format src dst) = pprFormatOpOp (sLit "xadd") format src dst pprInstr (CMPXCHG format src dst) = pprFormatOpOp (sLit "cmpxchg") format src dst -------------------------- -- some left over gtab :: SDoc gtab = char '\t' gsp :: SDoc gsp = char ' ' pprX87 :: Instr -> SDoc -> SDoc pprX87 fake actual = (char '#' <> pprX87Instr fake) $$ actual pprX87Instr :: Instr -> SDoc pprX87Instr (X87Store fmt dst) = pprFormatAddr (sLit "gst") fmt dst pprX87Instr _ = panic "X86.Ppr.pprX87Instr: no match" pprDollImm :: Imm -> SDoc pprDollImm i = text "$" <> pprImm i pprOperand :: Format -> Operand -> SDoc pprOperand f (OpReg r) = pprReg f r pprOperand _ (OpImm i) = pprDollImm i pprOperand _ (OpAddr ea) = pprAddr ea pprMnemonic_ :: PtrString -> SDoc pprMnemonic_ name = char '\t' <> ptext name <> space pprMnemonic :: PtrString -> Format -> SDoc pprMnemonic name format = char '\t' <> ptext name <> pprFormat format <> space pprFormatImmOp :: PtrString -> Format -> Imm -> Operand -> SDoc pprFormatImmOp name format imm op1 = hcat [ pprMnemonic name format, char '$', pprImm imm, comma, pprOperand format op1 ] pprFormatOp_ :: PtrString -> Format -> Operand -> SDoc pprFormatOp_ name format op1 = hcat [ pprMnemonic_ name , pprOperand format op1 ] pprFormatOp :: PtrString -> Format -> Operand -> SDoc pprFormatOp name format op1 = hcat [ pprMnemonic name format, pprOperand format op1 ] pprFormatOpOp :: PtrString -> Format -> Operand -> Operand -> SDoc pprFormatOpOp name format op1 op2 = hcat [ pprMnemonic name format, pprOperand format op1, comma, pprOperand format op2 ] pprOpOp :: PtrString -> Format -> Operand -> Operand -> SDoc pprOpOp name format op1 op2 = hcat [ pprMnemonic_ name, pprOperand format op1, comma, pprOperand format op2 ] pprRegReg :: PtrString -> Reg -> Reg -> SDoc pprRegReg name reg1 reg2 = sdocWithPlatform $ \platform -> hcat [ pprMnemonic_ name, pprReg (archWordFormat (target32Bit platform)) reg1, comma, pprReg (archWordFormat (target32Bit platform)) reg2 ] pprFormatOpReg :: PtrString -> Format -> Operand -> Reg -> SDoc pprFormatOpReg name format op1 reg2 = sdocWithPlatform $ \platform -> hcat [ pprMnemonic name format, pprOperand format op1, comma, pprReg (archWordFormat (target32Bit platform)) reg2 ] pprCondOpReg :: PtrString -> Format -> Cond -> Operand -> Reg -> SDoc pprCondOpReg name format cond op1 reg2 = hcat [ char '\t', ptext name, pprCond cond, space, pprOperand format op1, comma, pprReg format reg2 ] pprFormatFormatOpReg :: PtrString -> Format -> Format -> Operand -> Reg -> SDoc pprFormatFormatOpReg name format1 format2 op1 reg2 = hcat [ pprMnemonic name format2, pprOperand format1 op1, comma, pprReg format2 reg2 ] pprFormatOpOpReg :: PtrString -> Format -> Operand -> Operand -> Reg -> SDoc pprFormatOpOpReg name format op1 op2 reg3 = hcat [ pprMnemonic name format, pprOperand format op1, comma, pprOperand format op2, comma, pprReg format reg3 ] pprFormatAddr :: PtrString -> Format -> AddrMode -> SDoc pprFormatAddr name format op = hcat [ pprMnemonic name format, comma, pprAddr op ] pprShift :: PtrString -> Format -> Operand -> Operand -> SDoc pprShift name format src dest = hcat [ pprMnemonic name format, pprOperand II8 src, -- src is 8-bit sized comma, pprOperand format dest ] pprFormatOpOpCoerce :: PtrString -> Format -> Format -> Operand -> Operand -> SDoc pprFormatOpOpCoerce name format1 format2 op1 op2 = hcat [ char '\t', ptext name, pprFormat format1, pprFormat format2, space, pprOperand format1 op1, comma, pprOperand format2 op2 ] pprCondInstr :: PtrString -> Cond -> SDoc -> SDoc pprCondInstr name cond arg = hcat [ char '\t', ptext name, pprCond cond, space, arg]
sdiehl/ghc
compiler/nativeGen/X86/Ppr.hs
bsd-3-clause
35,651
0
22
10,286
9,702
4,829
4,873
647
96
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, DeriveDataTypeable, PatternGuards #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.Mosaic -- Copyright : (c) 2009 Adam Vogt, 2007 James Webb -- License : BSD-style (see xmonad/LICENSE) -- -- Maintainer : vogt.adam<at>gmail.com -- Stability : unstable -- Portability : unportable -- -- Based on MosaicAlt, but aspect ratio messages always change the aspect -- ratios, and rearranging the window stack changes the window sizes. -- ----------------------------------------------------------------------------- module XMonad.Layout.Mosaic ( -- * Usage -- $usage Aspect(..) ,mosaic ,changeMaster ,changeFocused ) where import Prelude hiding (sum) import XMonad(Typeable, LayoutClass(doLayout, handleMessage, pureMessage, description), Message, X, fromMessage, withWindowSet, Resize(..), splitHorizontallyBy, splitVerticallyBy, sendMessage, Rectangle) import qualified XMonad.StackSet as W import Control.Arrow(second, first) import Control.Monad(mplus) import Data.Foldable(Foldable,foldMap, sum) import Data.Function(on) import Data.List(sortBy) import Data.Monoid(Monoid,mempty, mappend) -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.Mosaic -- -- Then edit your @layoutHook@ by adding the Mosaic layout: -- -- > myLayout = mosaic 2 [3,2] ||| Full ||| etc.. -- > main = xmonad $ defaultConfig { layoutHook = myLayout } -- -- Unfortunately, infinite lists break serialization, so don't use them. And if -- the list is too short, it is extended with @++ repeat 1@, which covers the -- main use case. -- -- To change the choice in aspect ratio and the relative sizes of windows, add -- to your keybindings: -- -- > , ((modm, xK_a), sendMessage Taller) -- > , ((modm, xK_z), sendMessage Wider) -- -- > , ((modm, xK_r), sendMessage Reset) -- -- For more detailed instructions on editing the layoutHook see: -- -- "XMonad.Doc.Extending#Editing_the_layout_hook" data Aspect = Taller | Wider | Reset | SlopeMod ([Rational] -> [Rational]) deriving (Typeable) instance Message Aspect -- | The relative magnitudes (the sign is ignored) of the rational numbers in -- the second argument determine the relative areas that the windows receive. -- The first number represents the size of the master window, the second is for -- the next window in the stack, and so on. -- -- The list is extended with @++ repeat 1@, so @mosaic 1.5 []@ is like a -- resizable grid. -- -- The first parameter is the multiplicative factor to use when responding to -- the 'Expand' message. mosaic :: Rational -> [Rational] -> Mosaic a mosaic = Mosaic Nothing data Mosaic a = -- | True to override the aspect, current index, maximum index Mosaic (Maybe(Bool,Rational,Int)) Rational [Rational] deriving (Read,Show) instance LayoutClass Mosaic a where description = const "Mosaic" pureMessage (Mosaic Nothing _ _) _ = Nothing pureMessage (Mosaic (Just(_,ix,mix)) delta ss) ms = fromMessage ms >>= ixMod where ixMod Taller | round ix >= mix = Nothing | otherwise = Just $ Mosaic (Just(False,succ ix,mix)) delta ss ixMod Wider | round ix <= (0::Integer) = Nothing | otherwise = Just $ Mosaic (Just(False,pred ix,mix)) delta ss ixMod Reset = Just $ Mosaic Nothing delta ss ixMod (SlopeMod f) = Just $ Mosaic (Just(False,ix,mix)) delta (f ss) handleMessage l@(Mosaic _ delta _) ms | Just Expand <- fromMessage ms = changeFocused (*delta) >> return Nothing | Just Shrink <- fromMessage ms = changeFocused (/delta) >> return Nothing | otherwise = return $ pureMessage l ms doLayout (Mosaic state delta ss) r st = let ssExt = zipWith const (ss ++ repeat 1) $ W.integrate st rects = splits r ssExt nls = length rects fi = fromIntegral nextIx (ov,ix,mix) | mix <= 0 || ov = fromIntegral $ nls `div` 2 | otherwise = max 0 $ (*fi (pred nls)) $ min 1 $ ix / fi mix rect = rects !! maybe (nls `div` 2) round (nextIx `fmap` state) state' = fmap (\x@(ov,_,_) -> (ov,nextIx x,pred nls)) state `mplus` Just (True,fromIntegral nls / 2,pred nls) ss' = maybe ss (const ss `either` const ssExt) $ zipRemain ss ssExt in return (zip (W.integrate st) rect, Just $ Mosaic state' delta ss') zipRemain :: [a] -> [b] -> Maybe (Either [a] [b]) zipRemain (_:xs) (_:ys) = zipRemain xs ys zipRemain [] [] = Nothing zipRemain [] y = Just (Right y) zipRemain x [] = Just (Left x) -- | These sample functions are meant to be applied to the list of window sizes -- through the 'SlopeMod' message. changeMaster :: (Rational -> Rational) -> X () changeMaster = sendMessage . SlopeMod . onHead -- | Apply a function to the Rational that represents the currently focused -- window. -- -- 'Expand' and 'Shrink' messages are responded to with @changeFocused -- (*delta)@ or @changeFocused (delta/)@ where @delta@ is the first argument to -- 'mosaic'. -- -- This is exported because other functions (ex. @const 1@, @(+1)@) may be -- useful to apply to the current area. changeFocused :: (Rational -> Rational) -> X () changeFocused f = withWindowSet $ sendMessage . SlopeMod . maybe id (mulIx . length . W.up) . W.stack . W.workspace . W.current where mulIx i = uncurry (++) . second (onHead f) . splitAt i onHead :: (a -> a) -> [a] -> [a] onHead f = uncurry (++) . first (fmap f) . splitAt 1 splits :: Rectangle -> [Rational] -> [[Rectangle]] splits rect = map (reverse . map snd . sortBy (compare `on` fst)) . splitsL rect . makeTree snd . zip [1..] . normalize . reverse . map abs splitsL :: Rectangle -> Tree (Int,Rational) -> [[(Int,Rectangle)]] splitsL _rect Empty = [] splitsL rect (Leaf (x,_)) = [[(x,rect)]] splitsL rect (Branch l r) = do let mkSplit f = f ((sumSnd l /) $ sumSnd l + sumSnd r) rect sumSnd = sum . fmap snd (rl,rr) <- map mkSplit [splitVerticallyBy,splitHorizontallyBy] splitsL rl l `interleave` splitsL rr r -- like zipWith (++), but when one list is shorter, its elements are duplicated -- so that they match interleave :: [[a]] -> [[a]] -> [[a]] interleave xs ys | lx > ly = zc xs (extend lx ys) | otherwise = zc (extend ly xs) ys where lx = length xs ly = length ys zc = zipWith (++) extend :: Int -> [a] -> [a] extend n pat = do (p,e) <- zip pat $ replicate m True ++ repeat False [p | e] ++ replicate d p where (d,m) = n `divMod` length pat normalize :: Fractional a => [a] -> [a] normalize x = let s = sum x in map (/s) x data Tree a = Branch (Tree a) (Tree a) | Leaf a | Empty instance Foldable Tree where foldMap _f Empty = mempty foldMap f (Leaf x) = f x foldMap f (Branch l r) = foldMap f l `mappend` foldMap f r instance Functor Tree where fmap f (Leaf x) = Leaf $ f x fmap f (Branch l r) = Branch (fmap f l) (fmap f r) fmap _ Empty = Empty instance Monoid (Tree a) where mempty = Empty mappend Empty x = x mappend x Empty = x mappend x y = Branch x y makeTree :: (Num a1, Ord a1) => (a -> a1) -> [a] -> Tree a makeTree _ [] = Empty makeTree _ [x] = Leaf x makeTree f xs = Branch (makeTree f a) (makeTree f b) where ((a,b),_) = foldr go (([],[]),(0,0)) xs go n ((ls,rs),(l,r)) | l > r = ((ls,n:rs),(l,f n+r)) | otherwise = ((n:ls,rs),(f n+l,r))
MasseR/xmonadcontrib
XMonad/Layout/Mosaic.hs
bsd-3-clause
7,801
0
18
1,928
2,446
1,319
1,127
117
1
{-# LANGUAGE TypeFamilies #-} module Data.Hot.Generic ( prefix , suffix , merge ) where import Data.Hot.Base import GHC.TypeLits {-# INLINABLE prefix #-} prefix :: (HotClass n, HotClass m, m <= n) => Hot n a -> Hot m a prefix x = runSub $ unfold buildSub $ Sub 0 (elementAt x) {-# INLINABLE suffix #-} suffix :: forall n m a. (HotClass n, HotClass m, m <= n) => Hot n a -> Hot m a suffix x = runSub $ unfold buildSub $ Sub from (elementAt x) where from = length x - length (undefined :: Hot m a) data Sub a b = Sub !Int (Int -> a) b buildSub :: Sub a (a -> r) -> Sub a r buildSub (Sub i f k) = Sub (i + 1) f (k (f i)) runSub :: Sub a r -> r runSub (Sub _ _ x) = x {-# INLINABLE merge #-} merge :: (HotClass n, HotClass m, HotClass (n + m), Ord a) => Hot n a -> Hot m a -> Hot (n + m) a merge x y = runMerge $ unfold (buildMerge (length x) (length y)) (Merge 0 0 (elementAt x) (elementAt y)) data Merge a b = Merge !Int !Int (Int -> a) (Int -> a) b buildMerge :: (Ord a) => Int -> Int -> Merge a (a -> r) -> Merge a r buildMerge n m = \case (Merge i j f g k) | i == n -> take2 | j == m -> take1 | f i < g j -> take1 | otherwise -> take2 where take1 = Merge (i + 1) j f g (k (f i)) take2 = Merge i (j + 1) f g (k (g j)) runMerge :: Merge a r -> r runMerge (Merge _ _ _ _ x) = x
tserduke/hot
lib/indexed/Data/Hot/Generic.hs
bsd-3-clause
1,340
0
14
372
738
376
362
-1
-1
import Control.Monad import Haste import Haste.DOM import PropositionalLogic main = do withElem "analyzeButton" $ \el -> setCallback el OnClick analyzeFormula withElem "formulaInput" $ \el -> setCallback el OnKeyPress analyzeOnEnter analyzeOnEnter keyCode = when (keyCode == 13) (analyzeFormula 0) analyzeFormula _ = do formulaStr <- withElem "formulaInput" $ \el -> getProp el "value" case formula formulaStr of Left (pos, msg) -> alert $ "error at character " ++ show pos ++ ": " ++ msg Right x -> let normal = mkNormal x nnf = mkNNF normal cnf = mkCNF nnf scnf = simplifyCNF cnf dnf = mkDNF nnf sdnf = simplifyDNF dnf simplified = simplify x in do withElem "cnfCode" $ \el -> setProp el "innerHTML" $ prettyFormulaString cnf withElem "scnfCode" $ \el -> setProp el "innerHTML" $ prettyFormulaString scnf withElem "dnfCode" $ \el -> setProp el "innerHTML" $ prettyFormulaString dnf withElem "sdnfCode" $ \el -> setProp el "innerHTML" $ prettyFormulaString sdnf withElem "nnfCode" $ \el -> setProp el "innerHTML" $ prettyFormulaString nnf withElem "simplifiedCode" $ \el -> setProp el "innerHTML" $ prettyFormulaString simplified
tilltheis/propositional-logic
src/App.hs
bsd-3-clause
1,453
0
17
496
401
188
213
26
2
import Control.Monad(forM_) import Control.Concurrent(threadDelay) import System.PIO.Linux.GPIO(getValue) {-- Connection for Intel Edison $ sh/setup_in.sh 78 [J20-11] [J19- 2] --} test = do forM_ [0..999] $ \_ -> do print =<< getValue 78 threadDelay $ 100 * 1000
mitsuji/huckleberry
demo/GpioIn.hs
bsd-3-clause
286
0
12
59
80
43
37
7
1
{-# OPTIONS_GHC -Wall #-} -- |Here we parse the shell AST and delegate all the builtins, -- piping, command-running, etc. module System.Console.ShSh.Command ( runCommands, source, eval ) where import System.Console.ShSh.Builtins ( builtin, showAlias ) import System.Console.ShSh.Foreign.Pwd ( getHomeDir ) import System.Console.ShSh.IO ( ePutStrLn, oPutStrLn, oFlush, eFlush, iHandle, oHandle, eHandle ) import System.Console.ShSh.Internal.IO ( newPipe, rGetContents ) import System.Console.ShSh.Internal.Process ( WriteStream(..), PipeState(..) ) import System.Console.ShSh.Path ( findExecutable ) import System.Console.ShSh.ShellError ( failWith ) import System.Console.ShSh.Shell ( Shell, ShellProcess(..), withShellProcess, withChangeCodeHandler, withMaybeHandler, maybeCloseOut, withRedirects, subShell, makeLocal, finally, unsetEnv, runShellProcess, setEnv, getAllEnv, setFunction, getFunction, setExitCode, setExport, getExports, getPositionals, pipeShells, runInShell, getExitCode, withEnvironment, withExitHandler, getFlag, getAliases, withPositionals, withErrorsPrefixed, withPipes -- DEBUG! , envVars ) import Language.Sh.Glob ( expandGlob, matchPattern ) import Language.Sh.Parser ( parse, hereDocsComplete ) import Language.Sh.Pretty ( pretty ) import Language.Sh.Syntax ( Command(..), AndOrList(..), Pipeline(..), Statement(..), CompoundStatement(..), Word, Redir, Assignment(..) ) import qualified Language.Sh.Expansion as E import Control.Monad.Trans ( liftIO ) import Control.Monad ( when, unless, forM, forM_, mplus ) import Data.Maybe ( catMaybes ) import Data.Monoid ( mempty ) import System.Exit ( ExitCode(..), exitWith ) -- |What to do on failure? data OnErr = IgnoreE | CheckE -- |Simply run a 'Command'. runCommand :: OnErr -> Command -> Shell ExitCode runCommand _ (Asynchronous list) = do runAsync $ withExitHandler $ runList IgnoreE list return ExitSuccess runCommand b (Synchronous list) = withExitHandler $ runList b list runAsync :: Shell a -> Shell ExitCode runAsync _ = fail "Asyncronous commands not yet supported" >> return ExitSuccess -- i.e. (false &) && echo 1 -- |Run an 'AndOrList'. runList :: OnErr -> AndOrList -> Shell ExitCode runList b (Singleton p) = runShellProcess =<< pipeline b p runList b (l :&&: p) = do ec <- runList IgnoreE l if ec == ExitSuccess then runShellProcess =<< pipeline b p else return ec runList b (l :||: p) = do ec <- runList IgnoreE l if ec /= ExitSuccess then runShellProcess =<< pipeline b p else return ec -- |Modifies a Shell ShellProcess to set the exit code. sec :: Shell ShellProcess -> Shell ShellProcess sec = fmap $ withShellProcess $ \job -> job >>= setExitCode -- |Run a 'Pipeline'. (or rather, return something that will) pipeline :: OnErr -> Pipeline -> Shell ShellProcess pipeline b (Pipeline [s]) = sec $ runStatement b s pipeline b (Pipeline (s:ss)) = do s' <- runStatement IgnoreE s ss' <- pipeline b $ Pipeline ss return $ pipeShells s' ss' pipeline _ (Pipeline []) = error "impossible" pipeline _ (BangPipeline [s]) = sec $ notProcess `fmap` runStatement IgnoreE s pipeline _ (BangPipeline (s:ss)) = do s' <- runStatement IgnoreE s ss' <- pipeline IgnoreE $ BangPipeline ss return $ pipeShells s' ss' pipeline _ (BangPipeline []) = error "impossible" notProcess :: ShellProcess -> ShellProcess notProcess = withShellProcess $ \sp -> do ec <- sp case ec of ExitSuccess -> return $ ExitFailure 1 ExitFailure _ -> return $ ExitSuccess checkE :: OnErr -> ShellProcess -> ShellProcess checkE CheckE = withShellProcess $ \sp -> do ec <- sp am_e <- getFlag 'e' when (am_e && ec/=ExitSuccess) $ liftIO $ exitWith ec return ec checkE IgnoreE = id withEnv ::[Redir] -> [Assignment] -> Shell ExitCode -> Shell ExitCode withEnv = withEnvironment expandWord withRedirs ::[Redir] -> Shell ExitCode -> Shell ExitCode withRedirs = withRedirects expandWord -- |Run a 'Statement'. runStatement :: OnErr -> Statement -> Shell ShellProcess runStatement b (Compound c rs) = return $ BuiltinProcess $ withEnv rs [] $ runCompound b c runStatement _ (FunctionDefinition s c rs) = return $ BuiltinProcess $ do setFunction s c rs return ExitSuccess runStatement _ (OrderedStatement ts) = fail $ "OrderedStatement got through: " ++ show ts runStatement b (Statement ws rs as) = checkE b `fmap` do ws' <- expandWords ws case ws' of [] -> return $ BuiltinProcess $ withRedirs rs $ setVars as ("unset":xs) -> return $ BuiltinProcess $ do forM_ xs unsetEnv return ExitSuccess ("local":xs) -> return $ BuiltinProcess $ setLocals xs ["export"] -> return $ BuiltinProcess $ withEnv rs as $ setExports [] ("export":xs) -> return $ BuiltinProcess $ setExports xs -- NOTE: can't be in a withEnv (name:args) -> do func <- getFunction name case func of -- order of redirs matches dash Just (f,rs') -> return $ BuiltinProcess $ withEnv (rs++rs') as $ withPositionals args $ runCompound b f Nothing -> do job <- runBuiltinOrExe name args return $ withShellProcess `flip` job $ \j -> withEnv rs as j runCompound :: OnErr -> CompoundStatement -> Shell ExitCode runCompound b (For var list cs) = do ws <- expandWords list ecs <- forM ws $ \w -> do setEnv var w runCommands' b cs return $ if null ecs then ExitSuccess else head $ reverse $ ecs runCompound b (If cond thn els) = do ec <- runCommands' IgnoreE cond case ec of ExitSuccess -> runCommands' b thn _ -> runCommands' b els runCompound b (Case expr cases) = do e <- expandWord expr run e cases where run _ [] = return ExitSuccess run s ((ps,cs):xs) = do match <- check s ps if match then runCommands' b cs else run s xs check _ [] = return False check s (p:ps) = do p' <- expandPattern p if matchPattern p' s then return True else check s ps runCompound b (While cond code) = do ec <- runCommands' IgnoreE cond case ec of ExitSuccess -> do runCommands' b code runCompound b $ While cond code _ -> return ExitSuccess runCompound b (Until cond code) = do ec <- runCommands' IgnoreE cond case ec of ExitSuccess -> return ExitSuccess _ -> do runCommands' b code runCompound b $ Until cond code runCompound b (BraceGroup cs) = runCommands' b cs -- what to do here...? `finally` maybeCloseOut -- ????? runCompound b (Subshell cs) = runCompound b (BraceGroup cs) -- FOR NOW!!! --runCompound _ c = fail $ "Control structure "++show c++" not yet supported." openHandles :: Shell () -- this is weird -> these shouldn't have side effects openHandles = iHandle >> oHandle >> eHandle >> return () runBuiltinOrExe :: String -> [String] -> Shell ShellProcess runBuiltinOrExe = run' where -- now this is just for layout... run' "env#" _ = return $ BuiltinProcess $ do -- debug builtin (e,l,p) <- envVars oPutStrLn $ "environment\n" ++ unlines (map show e) oPutStrLn $ "locals\n" ++ unlines (map show l) oPutStrLn $ "positionals: " ++ show p return ExitSuccess run' "." args = run' "source" args run' "source" (f:args) | null args = return $ BuiltinProcess $ source f | otherwise = return $ BuiltinProcess $ withPositionals args $ source f run' "source" [] = return $ BuiltinProcess $ fail "filename argument required" run' "command" args = return $ BuiltinProcess $ commandBuiltin args run' "type" args = return $ BuiltinProcess $ typeBuiltin args run' command args = do b <- builtin command return $ case b of Just b' -> BuiltinProcess $ withExitHandler $ withErrorsPrefixed command $ do openHandles ec <- b' args -- after builtins are run. oFlush `mplus` return () -- to behave like external eFlush `mplus` return () -- commands, need to flush return ec Nothing -> ExternalProcess $ withExitHandler $ runWithArgs command args runWithArgs :: String -> [String] -> Shell ExitCode runWithArgs cmd args = do exe <- withChangeCodeHandler 127 $ findExecutable cmd runInShell exe args setVars :: [Assignment] -> Shell ExitCode setVars [] = return ExitSuccess setVars ((name:=word):as) = (setEnv name =<< expandWord word) >> setVars as -- |These should really be in 'Builtins', but we want them outside the -- 'withEnvironment'... we could process in multiple stages... setLocals :: [String] -> Shell ExitCode setLocals [] = return ExitSuccess setLocals (x:xs) = do let (name,val) = break (=='=') x makeLocal name unless (null val) $ setEnv name $ drop 1 val setLocals xs -- poor man's mapM_ >> return ExitSuccess setExports :: [String] -> Shell ExitCode setExports [] = getExports >>= mapM (oPutStrLn . (\(s,v) -> "export "++s++"="++v)) >> return ExitSuccess setExports xs = mapM_ se xs >> return ExitSuccess where se x = do let (name,val) = break (=='=') x setExport name True unless (null val) $ setEnv name $ drop 1 val -- |We need to be able to do this in a sort of "half -v" mode in which -- shell errors (bad substitution, parse, etc) cause it to quite, but -- bad exitcodes are OK. runCommands :: [Command] -> Shell ExitCode runCommands = runCommands' CheckE runCommands' :: OnErr -> [Command] -> Shell ExitCode runCommands' b xs = mapM_ (runCommand b) xs >> getExitCode -- |We want to set up a @Chan@ to read from a process. captureOutput :: Shell a -> Shell String captureOutput job = do (r,w) <- liftIO $ newPipe withPipes (mempty { p_out = WUseHandle w }) $ job >> maybeCloseOut liftIO $ rGetContents r eval :: String -> Shell ExitCode eval c = eval' "" $ lines c where eval' :: String -> [String] -> Shell ExitCode eval' i rest = do if null rest then getExitCode else do let ([s],rest') = splitAt 1 rest am_v <- getFlag 'v' when am_v $ ePutStrLn s as <- getAliases case parse as (i++s) of Left (err,False) -> do when (null rest') $ fail err eval' (i++s++"\n") rest' Left (err,True) -> do ePutStrLn err -- refail at eof? eval' "" rest' Right cs -> if hereDocsComplete cs then runCommands cs >> eval' "" rest' else if null rest' then runCommands cs else eval' (i++s++"\n") rest' source :: FilePath -> Shell ExitCode source f = liftIO (readFile f) >>= eval -- |Functions to pass to the actual @Expansion@ module. ef :: E.ExpansionFunctions Shell ef = E.ExpansionFunctions { E.getAllEnv = getAllEnv, E.setEnv = setEnv, E.homeDir = liftIO . getHomeDir, E.expandGlob = expandGlob, E.commandSub = captureOutput . subShell . runCommands, E.positionals = getPositionals } -- |Expand a single word into a single string; no field splitting expandWord :: Word -> Shell String expandWord = E.expandWord ef -- |Expand a single word into a single string; no field splitting expandPattern :: Word -> Shell Word expandPattern = E.expandPattern ef -- |Expand a list of words into a list of strings; fields will be split. expandWords :: [Word] -> Shell [String] expandWords = E.expand ef ------------------------------------------------------------------------ -- I don't particularly like having this here, but where else can it go? data Resolved = Executable FilePath | Builtin ([String] -> Shell ExitCode) | Function CompoundStatement [Redir] | Alias String | Keyword resolveCommand :: String -> Shell [Resolved] resolveCommand s = catMaybes `fmap` sequence -- special path? [(fmap Alias . lookup s) `fmap` getAliases ,return $ if s `elem` keywords then Just Keyword else Nothing ,fmap (uncurry Function) `fmap` getFunction s ,fmap Builtin `fmap` builtin s ,fmap Executable `fmap` withMaybeHandler (findExecutable s)] keywords :: [String] keywords = ["for", "in", "do", "done", "while", "until", "if", "then", "elif", "fi", "case", "{", "}", "[[", "]]"] -- case lookup s as of -- Just a -> return $ Alias a -- Nothing -> do -- func <- getFunction s -- case func of -- Just (f,rs) -> return $ Function f rs -- Nothing -> do -- b <- builtin command -- case b of -- Just b' -> return $ Builtin -- Nothing -> do -- exe <- withMaybeHandler $ findExecutable cmd -- case exe of -- Just fp -> return Executable fp -- Nothing -> return NotFound -- |This is a complicated builtin that we need to put here, since -- it needs to call functions in this module... We might later work -- out a distinction between POSIX builtins and standard utils, as well -- as the @-p@ path, but for now, we don't do much. -- Additionally, bash's command -V tells whether something is hashed... data CommandMode = Path | Verb | Basic | Empty commandBuiltin :: [String] -> Shell ExitCode commandBuiltin = run `flip` Empty where run [] _ = return ExitSuccess run (('-':a:[]):as) m = run as $ mode m a run (('-':a:a'):as) m = run (('-':a'):as) $ mode m a run (s:args) Empty = do rs <- resolveCommand s case take 1 rs of [Executable fp] -> runInShell fp args [Builtin b] -> b args _ -> failWith 127 $ s++": command not found" run (s:args) Path = run (s:args) Empty -- for now...? run ss Basic = anyM ss $ \s -> short s =<< resolveCommand s run ss Verb = anyM ss $ \s -> doType "command" s =<< resolveCommand s mode m c = case c of { 'p'->Path; 'v'->Basic; 'V'->Verb; _->m } anyM ss f = do res <- forM ss f if any id res then return ExitSuccess else return $ ExitFailure 1 short s (x:_:_) = short s [x] short _ [Executable fp] = oPutStrLn fp >> return True short s [Builtin _] = oPutStrLn s >> return True short s [Keyword] = oPutStrLn s >> return True short s [Function _ _] = oPutStrLn s >> return True short s [Alias s'] = showAlias s s' >> return True short _ [] = return False typeBuiltin :: [String] -> Shell ExitCode typeBuiltin ss = anyM $ \s -> doType "type" s =<< resolveCommand s where anyM f = do res <- forM ss f -- could probably use a clever fold if any id res then return ExitSuccess else return $ ExitFailure 1 doType :: String -> String -> [Resolved] -> Shell Bool doType c s (x:_:_) = doType c s [x] doType _ s [Executable fp] = oPutStrLn (s++" is "++fp) >> return True doType _ s [Builtin _] = oPutStrLn (s++" is a shell builtin") >> return True doType _ s [Keyword] = oPutStrLn (s++" is a shell keyword") >> return True doType _ s [Function f rs] = do oPutStrLn $ s++" is a function" oPutStrLn $ pretty $ FunctionDefinition s f rs return True doType _ s [Alias s'] = do oPutStrLn $ s++" is aliased to `"++s'++"'" return True doType cmd s [] = do ePutStrLn $ "shsh: "++cmd++": "++s++": not found" return False ----- -- We have extra builtins that we have to have here for silly reasons... -- (although we could put the pertinent things in a class to separate) -- -> these are hardcoded into runStatement and runBuiltinOrExe -> ... -- Currently these don't work properly with command/type. -- specialBuiltins :: [(String,[String] -> ShellProcess)]
shicks/shsh
System/Console/ShSh/Command.hs
bsd-3-clause
19,493
0
21
7,659
4,930
2,513
2,417
303
19
-- | Simplified interface for go. Defines the standard black/white player, -- and re-exports versions of common functions which take 2D co-ordinates -- for the board position rather than a Repa co-ordinate. This allows you -- to use the Go package for standard 2D, 2-player games without having to -- pull in the Repa dependency. module Game.Go.Simple ( StandardPlayer (..) , Board , Game , Rules -- * Board , empty , allPoints , set , at , relative , neighbours , within , surrounding , matchingNeighbours , chain , liberties , territory , territories , pressuredGroups , placeStone -- * Game , initGame , initGameWithBoard , setPlayer , playMove , playPass , isLegal -- * Go game DSL , go , black , white , setBlack , setWhite ) where import qualified Data.Array.Repa as R import Data.Array.Repa (Z (..), (:.) (..)) import Game.Go.Monad import qualified Game.Go.Board as B import Game.Go.Board (Player, Territory(..)) import qualified Game.Go.Game as G import Game.Go.Game (Illegal(..)) import Control.Arrow -- | Standard go player. Black or White; Black plays first. data StandardPlayer = Black | White deriving (Eq, Enum, Bounded, Ord) instance B.Player StandardPlayer -- | 2-dimensional game board. type Board p = B.Board R.DIM2 p -- | Simplified 'Game.Go.Game' type for 2-dimensional games. type Game p = G.Game R.DIM2 p -- | Simplified 'Game.Go.Rules' type for 2-dimensional rulesets. type Rules p = G.Rules R.DIM2 p -- | Create an empty `Board` with size w, h -- The player is parameterized in the return type; to create an empty -- board at the ghci prompt, for example, you must do something like the -- following: -- -- > empty 19 19 :: Board StandardPlayer empty :: Player p => Int -> Int -> Board p empty w h = B.empty $ tupleToRepaCoords (w, h) -- | Get a list of all valid co-ordinates on the given `Board`. allPoints :: Board p -> [(Int, Int)] allPoints = map repaCoordsToTuple . B.allPoints -- | Set the value of a list of co-ordinates. set :: Board p -> [(Int, Int)] -> Maybe p -> Board p set b coords = B.set b (map tupleToRepaCoords coords) -- | Get the value at a certain co-ordinate. at :: Board p -> (Int, Int) -> Maybe p at b = B.at b . tupleToRepaCoords -- | Return a list of co-ordinates offset by @Offset@. relative :: [(Int, Int)] -- ^ Initial co-ordinates -> (Int, Int) -- ^ Offset -> [(Int, Int)] -- ^ Result relative coords = map repaCoordsToTuple . B.relative (map tupleToRepaCoords coords) . tupleToRepaCoords -- | Return a list of co-ordinates surrounding the given co-ordinate. neighbours :: (Int, Int) -> [(Int, Int)] neighbours = map repaCoordsToTuple . B.neighbours . tupleToRepaCoords -- | Filters the supplied co-ordinates, returning only those which lie -- within the supplied `Board`. within :: Board p -> [(Int, Int)] -> [(Int, Int)] within b = map repaCoordsToTuple . B.within b . map tupleToRepaCoords -- | Return a list of co-ordinates surrounding the supplied co-ordinates. -- Co-ordinates that lie outside the boundaries of the passed `Board` are -- filtered out. surrounding :: Board p -> [(Int, Int)] -> [(Int, Int)] surrounding b = map repaCoordsToTuple . B.surrounding b . map tupleToRepaCoords -- | Query the Board to find which of the stones surrounding a list of coords -- match the value of point. matchingNeighbours :: Player p => Board p -> Maybe p -> [(Int, Int)] -> [(Int, Int)] matchingNeighbours b v = map repaCoordsToTuple . B.matchingNeighbours b v . map tupleToRepaCoords -- | Return the co-ordinates of all points in the chain of which the -- supplied point is a member. A point is a member of a chain if there -- is a direct line, horizontally or vertically, leading to another point -- of the same colour. -- Requesting the chain for an Empty point returns the contiguous range -- of empty points. chain :: Player p => Board p -> (Int, Int) -> [(Int, Int)] chain b = map repaCoordsToTuple . B.chain b . tupleToRepaCoords -- | Calculate the liberties from a chain of points. liberties :: Player p => Board p -> [(Int, Int)] -> [(Int, Int)] liberties b = map repaCoordsToTuple . B.liberties b . map tupleToRepaCoords -- | Return the territorial status of the passed position, alongside the -- chain of which it is a member. territory :: Player p => Board p -> (Int, Int) -> (Territory p, [(Int, Int)]) territory b = second (map repaCoordsToTuple) . B.territory b . tupleToRepaCoords -- | Return a list of all chains and empty areas as returned by `territory`. territories :: Player p => Board p -> [(Territory p, [[(Int, Int)]])] territories = map (second $ map (map repaCoordsToTuple)) . B.territories -- | Returns a list of groups of stones adjacent to a point @x@ whose colour -- differs from that of player @p@. pressuredGroups :: Player p => Board p -- ^ The current state of the board -> p -- ^ The player @p@ making the threat -> (Int, Int) -- ^ The position @x@ where @p@ will play -> [[(Int, Int)]] -- ^ List of pressured groups pressuredGroups b p = map (map repaCoordsToTuple) . B.pressuredGroups b p . tupleToRepaCoords -- | Returns the state of the board after placing a stone of colour @p@ in -- position @x@, along with a list of stones taken as a result. Does not -- check the legality of the move. placeStone :: Player p => Board p -- ^ The current state of the board -> p -- ^ The player, @p@ -> (Int, Int) -- ^ The position, @x@ -> ([(p, (Int, Int))], Board p) -- ^ List of taken stones and the -- resulting board position placeStone b p = first (map $ second repaCoordsToTuple) . B.placeStone b p . tupleToRepaCoords -- | Initialises a new game with the given board dimensions. initGame :: Player p => Rules p -> (Int, Int) -> Game p initGame r = G.initGame r . tupleToRepaCoords -- | Initialises a new game with a starting board (useful for handicap games). initGameWithBoard :: Player p => Rules p -> Board p -> Game p initGameWithBoard = G.initGameWithBoard -- | Set the current player manually. setPlayer :: Player p => Game p -> p -> Game p setPlayer = G.setPlayer -- | Play a move. Checks the legality of the move, and if it is legal, -- returns the game state following the move. playMove :: Player p => Game p -> p -> (Int, Int) -> Either Illegal (Game p) playMove g p = G.playMove g p . tupleToRepaCoords -- | Play a pass. The number of passes will be incremented. The game is -- over when all players have passed sequentially, and then the first -- player to pass passes again. playPass :: Player p => Game p -> p -> Either Illegal (Game p) playPass = G.playPass -- | Check the legality of a move. isLegal :: Player p => Game p -> p -> (Int, Int) -> Bool isLegal g p = G.isLegal g p . tupleToRepaCoords -- | Run the given 'Go' monad on a standard 19x19 board. go :: (Player p) => Rules p -> Go R.DIM2 p a -> (a, Game p) go r = goWithSize r (Z :. 19 :. 19) -- | Set the supplied co-ordinates to Black. setBlack :: [(Int, Int)] -> Go R.DIM2 StandardPlayer () setBlack = flip setM (Just Black) . map tupleToRepaCoords -- | Set the supplied co-ordinates to White. setWhite :: [(Int, Int)] -> Go R.DIM2 StandardPlayer () setWhite = flip setM (Just White) . map tupleToRepaCoords -- | Play a move as Black. black :: Int -> Int -> Go R.DIM2 StandardPlayer (Either Illegal ()) black x y = playMoveM Black (Z :. x :. y) -- | Play a move as White. white :: Int -> Int -> Go R.DIM2 StandardPlayer (Either Illegal ()) white x y = playMoveM White (Z :. x :. y) -- Conversion helpers tupleToRepaCoords :: (Int, Int) -> R.DIM2 tupleToRepaCoords (x, y) = Z :. x :. y repaCoordsToTuple :: R.DIM2 -> (Int, Int) repaCoordsToTuple (Z :. x :. y) = (x, y)
dpwright/igo
src/Game/Go/Simple.hs
bsd-3-clause
8,047
0
12
1,885
1,953
1,080
873
116
1
{-# LANGUAGE ScopedTypeVariables #-} import Control.Monad import Control.Monad.Base import Control.Monad.Trans.Class import Control.Monad.Trans.Loop main :: IO () main = do foreach [1..10] $ \(i :: Int) -> do foreach [1..10] $ \(j :: Int) -> do when (j > i) $ lift continue when (i == 2 && j == 2) $ exit when (i == 9 && j == 9) $ lift exit liftBase $ print (i, j) liftBase $ putStrLn "Inner loop finished" putStrLn "Outer loop finished"
joeyadams/haskell-control-monad-loop
test/lift-continue.hs
bsd-3-clause
559
0
20
199
206
103
103
18
1
{-# LANGUAGE CPP, NondecreasingIndentation, ScopedTypeVariables #-} -- ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow, 2005-2012 -- -- The GHC API -- -- ----------------------------------------------------------------------------- module GHC ( -- * Initialisation defaultErrorHandler, defaultCleanupHandler, prettyPrintGhcErrors, -- * GHC Monad Ghc, GhcT, GhcMonad(..), HscEnv, runGhc, runGhcT, initGhcMonad, gcatch, gbracket, gfinally, printException, handleSourceError, needsTemplateHaskell, -- * Flags and settings DynFlags(..), GeneralFlag(..), Severity(..), HscTarget(..), gopt, GhcMode(..), GhcLink(..), defaultObjectTarget, parseDynamicFlags, getSessionDynFlags, setSessionDynFlags, getProgramDynFlags, setProgramDynFlags, getInteractiveDynFlags, setInteractiveDynFlags, parseStaticFlags, -- * Targets Target(..), TargetId(..), Phase, setTargets, getTargets, addTarget, removeTarget, guessTarget, -- * Loading\/compiling the program depanal, load, LoadHowMuch(..), InteractiveImport(..), SuccessFlag(..), succeeded, failed, defaultWarnErrLogger, WarnErrLogger, workingDirectoryChanged, parseModule, typecheckModule, desugarModule, loadModule, ParsedModule(..), TypecheckedModule(..), DesugaredModule(..), TypecheckedSource, ParsedSource, RenamedSource, -- ditto TypecheckedMod, ParsedMod, moduleInfo, renamedSource, typecheckedSource, parsedSource, coreModule, -- ** Compiling to Core CoreModule(..), compileToCoreModule, compileToCoreSimplified, -- * Inspecting the module structure of the program ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..), getModSummary, getModuleGraph, isLoaded, topSortModuleGraph, -- * Inspecting modules ModuleInfo, getModuleInfo, modInfoTyThings, modInfoTopLevelScope, modInfoExports, modInfoInstances, modInfoIsExportedName, modInfoLookupName, modInfoIface, modInfoSafe, lookupGlobalName, findGlobalAnns, mkPrintUnqualifiedForModule, ModIface(..), SafeHaskellMode(..), -- * Querying the environment -- packageDbModules, -- * Printing PrintUnqualified, alwaysQualify, -- * Interactive evaluation getBindings, getInsts, getPrintUnqual, findModule, lookupModule, #ifdef GHCI isModuleTrusted, moduleTrustReqs, setContext, getContext, getNamesInScope, getRdrNamesInScope, getGRE, moduleIsInterpreted, getInfo, exprType, typeKind, parseName, RunResult(..), runStmt, runStmtWithLocation, runDecls, runDeclsWithLocation, runTcInteractive, -- Desired by some clients (Trac #8878) parseImportDecl, SingleStep(..), resume, Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan, resumeHistory, resumeHistoryIx), History(historyBreakInfo, historyEnclosingDecls), GHC.getHistorySpan, getHistoryModule, getResumeContext, abandon, abandonAll, InteractiveEval.back, InteractiveEval.forward, showModule, isModuleInterpreted, InteractiveEval.compileExpr, HValue, dynCompileExpr, GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType, modInfoModBreaks, ModBreaks(..), BreakIndex, BreakInfo(breakInfo_number, breakInfo_module), BreakArray, setBreakOn, setBreakOff, getBreak, #endif lookupName, #ifdef GHCI -- ** EXPERIMENTAL setGHCiMonad, #endif -- * Abstract syntax elements -- ** Packages PackageKey, -- ** Modules Module, mkModule, pprModule, moduleName, modulePackageKey, ModuleName, mkModuleName, moduleNameString, -- ** Names Name, isExternalName, nameModule, pprParenSymName, nameSrcSpan, NamedThing(..), RdrName(Qual,Unqual), -- ** Identifiers Id, idType, isImplicitId, isDeadBinder, isExportedId, isLocalId, isGlobalId, isRecordSelector, isPrimOpId, isFCallId, isClassOpId_maybe, isDataConWorkId, idDataCon, isBottomingId, isDictonaryId, recordSelectorFieldLabel, -- ** Type constructors TyCon, tyConTyVars, tyConDataCons, tyConArity, isClassTyCon, isTypeSynonymTyCon, isTypeFamilyTyCon, isNewTyCon, isPrimTyCon, isFunTyCon, isFamilyTyCon, isOpenFamilyTyCon, isOpenTypeFamilyTyCon, tyConClass_maybe, synTyConRhs_maybe, synTyConDefn_maybe, synTyConResKind, -- ** Type variables TyVar, alphaTyVars, -- ** Data constructors DataCon, dataConSig, dataConType, dataConTyCon, dataConFieldLabels, dataConIsInfix, isVanillaDataCon, dataConUserType, dataConStrictMarks, StrictnessMark(..), isMarkedStrict, -- ** Classes Class, classMethods, classSCTheta, classTvsFds, classATs, pprFundeps, -- ** Instances ClsInst, instanceDFunId, pprInstance, pprInstanceHdr, pprFamInst, FamInst, -- ** Types and Kinds Type, splitForAllTys, funResultTy, pprParendType, pprTypeApp, Kind, PredType, ThetaType, pprForAll, pprThetaArrowTy, -- ** Entities TyThing(..), -- ** Syntax module HsSyn, -- ToDo: remove extraneous bits -- ** Fixities FixityDirection(..), defaultFixity, maxPrecedence, negateFixity, compareFixity, -- ** Source locations SrcLoc(..), RealSrcLoc, mkSrcLoc, noSrcLoc, srcLocFile, srcLocLine, srcLocCol, SrcSpan(..), RealSrcSpan, mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan, srcSpanStart, srcSpanEnd, srcSpanFile, srcSpanStartLine, srcSpanEndLine, srcSpanStartCol, srcSpanEndCol, -- ** Located GenLocated(..), Located, -- *** Constructing Located noLoc, mkGeneralLocated, -- *** Deconstructing Located getLoc, unLoc, -- *** Combining and comparing Located values eqLocated, cmpLocated, combineLocs, addCLoc, leftmost_smallest, leftmost_largest, rightmost, spans, isSubspanOf, -- * Exceptions GhcException(..), showGhcException, -- * Token stream manipulations Token, getTokenStream, getRichTokenStream, showRichTokenStream, addSourceToTokens, -- * Pure interface to the parser parser, -- * API Annotations ApiAnns,AnnKeywordId(..),AnnotationComment(..), getAnnotation, getAnnotationComments, -- * Miscellaneous --sessionHscEnv, cyclicModuleErr, ) where {- ToDo: * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt. * what StaticFlags should we expose, if any? -} #include "HsVersions.h" #ifdef GHCI import ByteCodeInstr import BreakArray import InteractiveEval import TcRnDriver ( runTcInteractive ) #endif import PprTyThing ( pprFamInst ) import HscMain import GhcMake import DriverPipeline ( compileOne' ) import GhcMonad import TcRnMonad ( finalSafeMode ) import TcRnTypes import Packages import NameSet import RdrName import qualified HsSyn -- hack as we want to reexport the whole module import HsSyn import Type hiding( typeKind ) import Kind ( synTyConResKind ) import TcType hiding( typeKind ) import Id import TysPrim ( alphaTyVars ) import TyCon import Class import DataCon import Name hiding ( varName ) import Avail import InstEnv import FamInstEnv ( FamInst ) import SrcLoc import CoreSyn import TidyPgm import DriverPhases ( Phase(..), isHaskellSrcFilename ) import Finder import HscTypes import DynFlags import StaticFlags import SysTools import Annotations import Module import UniqFM import Panic import Platform import Bag ( unitBag ) import ErrUtils import MonadUtils import Util import StringBuffer import Outputable import BasicTypes import Maybes ( expectJust ) import FastString import qualified Parser import Lexer import ApiAnnotation import System.Directory ( doesFileExist ) import Data.Maybe import Data.List ( find ) import Data.Time import Data.Typeable ( Typeable ) import Data.Word ( Word8 ) import Control.Monad import System.Exit ( exitWith, ExitCode(..) ) import Exception import Data.IORef import System.FilePath import System.IO import Prelude hiding (init) -- %************************************************************************ -- %* * -- Initialisation: exception handlers -- %* * -- %************************************************************************ -- | Install some default exception handlers and run the inner computation. -- Unless you want to handle exceptions yourself, you should wrap this around -- the top level of your program. The default handlers output the error -- message(s) to stderr and exit cleanly. defaultErrorHandler :: (ExceptionMonad m, MonadIO m) => FatalMessager -> FlushOut -> m a -> m a defaultErrorHandler fm (FlushOut flushOut) inner = -- top-level exception handler: any unrecognised exception is a compiler bug. ghandle (\exception -> liftIO $ do flushOut case fromException exception of -- an IO exception probably isn't our fault, so don't panic Just (ioe :: IOException) -> fatalErrorMsg'' fm (show ioe) _ -> case fromException exception of Just UserInterrupt -> -- Important to let this one propagate out so our -- calling process knows we were interrupted by ^C liftIO $ throwIO UserInterrupt Just StackOverflow -> fatalErrorMsg'' fm "stack overflow: use +RTS -K<size> to increase it" _ -> case fromException exception of Just (ex :: ExitCode) -> liftIO $ throwIO ex _ -> fatalErrorMsg'' fm (show (Panic (show exception))) exitWith (ExitFailure 1) ) $ -- error messages propagated as exceptions handleGhcException (\ge -> liftIO $ do flushOut case ge of PhaseFailed _ code -> exitWith code Signal _ -> exitWith (ExitFailure 1) _ -> do fatalErrorMsg'' fm (show ge) exitWith (ExitFailure 1) ) $ inner -- | Install a default cleanup handler to remove temporary files deposited by -- a GHC run. This is separate from 'defaultErrorHandler', because you might -- want to override the error handling, but still get the ordinary cleanup -- behaviour. defaultCleanupHandler :: (ExceptionMonad m, MonadIO m) => DynFlags -> m a -> m a defaultCleanupHandler dflags inner = -- make sure we clean up after ourselves inner `gfinally` (liftIO $ do cleanTempFiles dflags cleanTempDirs dflags ) -- exceptions will be blocked while we clean the temporary files, -- so there shouldn't be any difficulty if we receive further -- signals. -- %************************************************************************ -- %* * -- The Ghc Monad -- %* * -- %************************************************************************ -- | Run function for the 'Ghc' monad. -- -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call -- to this function will create a new session which should not be shared among -- several threads. -- -- Any errors not handled inside the 'Ghc' action are propagated as IO -- exceptions. runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'. -> Ghc a -- ^ The action to perform. -> IO a runGhc mb_top_dir ghc = do ref <- newIORef (panic "empty session") let session = Session ref flip unGhc session $ do initGhcMonad mb_top_dir ghc -- XXX: unregister interrupt handlers here? -- | Run function for 'GhcT' monad transformer. -- -- It initialises the GHC session and warnings via 'initGhcMonad'. Each call -- to this function will create a new session which should not be shared among -- several threads. runGhcT :: (ExceptionMonad m, Functor m, MonadIO m) => Maybe FilePath -- ^ See argument to 'initGhcMonad'. -> GhcT m a -- ^ The action to perform. -> m a runGhcT mb_top_dir ghct = do ref <- liftIO $ newIORef (panic "empty session") let session = Session ref flip unGhcT session $ do initGhcMonad mb_top_dir ghct -- | Initialise a GHC session. -- -- If you implement a custom 'GhcMonad' you must call this function in the -- monad run function. It will initialise the session variable and clear all -- warnings. -- -- The first argument should point to the directory where GHC's library files -- reside. More precisely, this should be the output of @ghc --print-libdir@ -- of the version of GHC the module using this API is compiled with. For -- portability, you should use the @ghc-paths@ package, available at -- <http://hackage.haskell.org/package/ghc-paths>. initGhcMonad :: GhcMonad m => Maybe FilePath -> m () initGhcMonad mb_top_dir = do { env <- liftIO $ do { installSignalHandlers -- catch ^C ; initStaticOpts ; mySettings <- initSysTools mb_top_dir ; dflags <- initDynFlags (defaultDynFlags mySettings) ; checkBrokenTablesNextToCode dflags ; setUnsafeGlobalDynFlags dflags -- c.f. DynFlags.parseDynamicFlagsFull, which -- creates DynFlags and sets the UnsafeGlobalDynFlags ; newHscEnv dflags } ; setSession env } -- | The binutils linker on ARM emits unnecessary R_ARM_COPY relocations which -- breaks tables-next-to-code in dynamically linked modules. This -- check should be more selective but there is currently no released -- version where this bug is fixed. -- See https://sourceware.org/bugzilla/show_bug.cgi?id=16177 and -- https://ghc.haskell.org/trac/ghc/ticket/4210#comment:29 checkBrokenTablesNextToCode :: MonadIO m => DynFlags -> m () checkBrokenTablesNextToCode dflags = do { broken <- checkBrokenTablesNextToCode' dflags ; when broken $ do { _ <- liftIO $ throwIO $ mkApiErr dflags invalidLdErr ; fail "unsupported linker" } } where invalidLdErr = text "Tables-next-to-code not supported on ARM" <+> text "when using binutils ld (please see:" <+> text "https://sourceware.org/bugzilla/show_bug.cgi?id=16177)" checkBrokenTablesNextToCode' :: MonadIO m => DynFlags -> m Bool checkBrokenTablesNextToCode' dflags | not (isARM arch) = return False | WayDyn `notElem` ways dflags = return False | not (tablesNextToCode dflags) = return False | otherwise = do linkerInfo <- liftIO $ getLinkerInfo dflags case linkerInfo of GnuLD _ -> return True _ -> return False where platform = targetPlatform dflags arch = platformArch platform -- %************************************************************************ -- %* * -- Flags & settings -- %* * -- %************************************************************************ -- $DynFlags -- -- The GHC session maintains two sets of 'DynFlags': -- -- * The "interactive" @DynFlags@, which are used for everything -- related to interactive evaluation, including 'runStmt', -- 'runDecls', 'exprType', 'lookupName' and so on (everything -- under \"Interactive evaluation\" in this module). -- -- * The "program" @DynFlags@, which are used when loading -- whole modules with 'load' -- -- 'setInteractiveDynFlags', 'getInteractiveDynFlags' work with the -- interactive @DynFlags@. -- -- 'setProgramDynFlags', 'getProgramDynFlags' work with the -- program @DynFlags@. -- -- 'setSessionDynFlags' sets both @DynFlags@, and 'getSessionDynFlags' -- retrieves the program @DynFlags@ (for backwards compatibility). -- | Updates both the interactive and program DynFlags in a Session. -- This also reads the package database (unless it has already been -- read), and prepares the compilers knowledge about packages. It can -- be called again to load new packages: just add new package flags to -- (packageFlags dflags). -- -- Returns a list of new packages that may need to be linked in using -- the dynamic linker (see 'linkPackages') as a result of new package -- flags. If you are not doing linking or doing static linking, you -- can ignore the list of packages returned. -- setSessionDynFlags :: GhcMonad m => DynFlags -> m [PackageKey] setSessionDynFlags dflags = do (dflags', preload) <- liftIO $ initPackages dflags modifySession $ \h -> h{ hsc_dflags = dflags' , hsc_IC = (hsc_IC h){ ic_dflags = dflags' } } invalidateModSummaryCache return preload -- | Sets the program 'DynFlags'. setProgramDynFlags :: GhcMonad m => DynFlags -> m [PackageKey] setProgramDynFlags dflags = do (dflags', preload) <- liftIO $ initPackages dflags modifySession $ \h -> h{ hsc_dflags = dflags' } invalidateModSummaryCache return preload -- When changing the DynFlags, we want the changes to apply to future -- loads, but without completely discarding the program. But the -- DynFlags are cached in each ModSummary in the hsc_mod_graph, so -- after a change to DynFlags, the changes would apply to new modules -- but not existing modules; this seems undesirable. -- -- Furthermore, the GHC API client might expect that changing -- log_action would affect future compilation messages, but for those -- modules we have cached ModSummaries for, we'll continue to use the -- old log_action. This is definitely wrong (#7478). -- -- Hence, we invalidate the ModSummary cache after changing the -- DynFlags. We do this by tweaking the date on each ModSummary, so -- that the next downsweep will think that all the files have changed -- and preprocess them again. This won't necessarily cause everything -- to be recompiled, because by the time we check whether we need to -- recopmile a module, we'll have re-summarised the module and have a -- correct ModSummary. -- invalidateModSummaryCache :: GhcMonad m => m () invalidateModSummaryCache = modifySession $ \h -> h { hsc_mod_graph = map inval (hsc_mod_graph h) } where inval ms = ms { ms_hs_date = addUTCTime (-1) (ms_hs_date ms) } -- | Returns the program 'DynFlags'. getProgramDynFlags :: GhcMonad m => m DynFlags getProgramDynFlags = getSessionDynFlags -- | Set the 'DynFlags' used to evaluate interactive expressions. -- Note: this cannot be used for changes to packages. Use -- 'setSessionDynFlags', or 'setProgramDynFlags' and then copy the -- 'pkgState' into the interactive @DynFlags@. setInteractiveDynFlags :: GhcMonad m => DynFlags -> m () setInteractiveDynFlags dflags = do modifySession $ \h -> h{ hsc_IC = (hsc_IC h) { ic_dflags = dflags }} -- | Get the 'DynFlags' used to evaluate interactive expressions. getInteractiveDynFlags :: GhcMonad m => m DynFlags getInteractiveDynFlags = withSession $ \h -> return (ic_dflags (hsc_IC h)) parseDynamicFlags :: MonadIO m => DynFlags -> [Located String] -> m (DynFlags, [Located String], [Located String]) parseDynamicFlags = parseDynamicFlagsCmdLine -- %************************************************************************ -- %* * -- Setting, getting, and modifying the targets -- %* * -- %************************************************************************ -- ToDo: think about relative vs. absolute file paths. And what -- happens when the current directory changes. -- | Sets the targets for this session. Each target may be a module name -- or a filename. The targets correspond to the set of root modules for -- the program\/library. Unloading the current program is achieved by -- setting the current set of targets to be empty, followed by 'load'. setTargets :: GhcMonad m => [Target] -> m () setTargets targets = modifySession (\h -> h{ hsc_targets = targets }) -- | Returns the current set of targets getTargets :: GhcMonad m => m [Target] getTargets = withSession (return . hsc_targets) -- | Add another target. addTarget :: GhcMonad m => Target -> m () addTarget target = modifySession (\h -> h{ hsc_targets = target : hsc_targets h }) -- | Remove a target removeTarget :: GhcMonad m => TargetId -> m () removeTarget target_id = modifySession (\h -> h{ hsc_targets = filter (hsc_targets h) }) where filter targets = [ t | t@(Target id _ _) <- targets, id /= target_id ] -- | Attempts to guess what Target a string refers to. This function -- implements the @--make@/GHCi command-line syntax for filenames: -- -- - if the string looks like a Haskell source filename, then interpret it -- as such -- -- - if adding a .hs or .lhs suffix yields the name of an existing file, -- then use that -- -- - otherwise interpret the string as a module name -- guessTarget :: GhcMonad m => String -> Maybe Phase -> m Target guessTarget str (Just phase) = return (Target (TargetFile str (Just phase)) True Nothing) guessTarget str Nothing | isHaskellSrcFilename file = return (target (TargetFile file Nothing)) | otherwise = do exists <- liftIO $ doesFileExist hs_file if exists then return (target (TargetFile hs_file Nothing)) else do exists <- liftIO $ doesFileExist lhs_file if exists then return (target (TargetFile lhs_file Nothing)) else do if looksLikeModuleName file then return (target (TargetModule (mkModuleName file))) else do dflags <- getDynFlags liftIO $ throwGhcExceptionIO (ProgramError (showSDoc dflags $ text "target" <+> quotes (text file) <+> text "is not a module name or a source file")) where (file,obj_allowed) | '*':rest <- str = (rest, False) | otherwise = (str, True) hs_file = file <.> "hs" lhs_file = file <.> "lhs" target tid = Target tid obj_allowed Nothing -- | Inform GHC that the working directory has changed. GHC will flush -- its cache of module locations, since it may no longer be valid. -- -- Note: Before changing the working directory make sure all threads running -- in the same session have stopped. If you change the working directory, -- you should also unload the current program (set targets to empty, -- followed by load). workingDirectoryChanged :: GhcMonad m => m () workingDirectoryChanged = withSession $ (liftIO . flushFinderCaches) -- %************************************************************************ -- %* * -- Running phases one at a time -- %* * -- %************************************************************************ class ParsedMod m where modSummary :: m -> ModSummary parsedSource :: m -> ParsedSource class ParsedMod m => TypecheckedMod m where renamedSource :: m -> Maybe RenamedSource typecheckedSource :: m -> TypecheckedSource moduleInfo :: m -> ModuleInfo tm_internals :: m -> (TcGblEnv, ModDetails) -- ToDo: improvements that could be made here: -- if the module succeeded renaming but not typechecking, -- we can still get back the GlobalRdrEnv and exports, so -- perhaps the ModuleInfo should be split up into separate -- fields. class TypecheckedMod m => DesugaredMod m where coreModule :: m -> ModGuts -- | The result of successful parsing. data ParsedModule = ParsedModule { pm_mod_summary :: ModSummary , pm_parsed_source :: ParsedSource , pm_extra_src_files :: [FilePath] , pm_annotations :: ApiAnns } -- See Note [Api annotations] in ApiAnnotation.hs instance ParsedMod ParsedModule where modSummary m = pm_mod_summary m parsedSource m = pm_parsed_source m -- | The result of successful typechecking. It also contains the parser -- result. data TypecheckedModule = TypecheckedModule { tm_parsed_module :: ParsedModule , tm_renamed_source :: Maybe RenamedSource , tm_typechecked_source :: TypecheckedSource , tm_checked_module_info :: ModuleInfo , tm_internals_ :: (TcGblEnv, ModDetails) } instance ParsedMod TypecheckedModule where modSummary m = modSummary (tm_parsed_module m) parsedSource m = parsedSource (tm_parsed_module m) instance TypecheckedMod TypecheckedModule where renamedSource m = tm_renamed_source m typecheckedSource m = tm_typechecked_source m moduleInfo m = tm_checked_module_info m tm_internals m = tm_internals_ m -- | The result of successful desugaring (i.e., translation to core). Also -- contains all the information of a typechecked module. data DesugaredModule = DesugaredModule { dm_typechecked_module :: TypecheckedModule , dm_core_module :: ModGuts } instance ParsedMod DesugaredModule where modSummary m = modSummary (dm_typechecked_module m) parsedSource m = parsedSource (dm_typechecked_module m) instance TypecheckedMod DesugaredModule where renamedSource m = renamedSource (dm_typechecked_module m) typecheckedSource m = typecheckedSource (dm_typechecked_module m) moduleInfo m = moduleInfo (dm_typechecked_module m) tm_internals m = tm_internals_ (dm_typechecked_module m) instance DesugaredMod DesugaredModule where coreModule m = dm_core_module m type ParsedSource = Located (HsModule RdrName) type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name], Maybe LHsDocString) type TypecheckedSource = LHsBinds Id -- NOTE: -- - things that aren't in the output of the typechecker right now: -- - the export list -- - the imports -- - type signatures -- - type/data/newtype declarations -- - class declarations -- - instances -- - extra things in the typechecker's output: -- - default methods are turned into top-level decls. -- - dictionary bindings -- | Return the 'ModSummary' of a module with the given name. -- -- The module must be part of the module graph (see 'hsc_mod_graph' and -- 'ModuleGraph'). If this is not the case, this function will throw a -- 'GhcApiError'. -- -- This function ignores boot modules and requires that there is only one -- non-boot module with the given name. getModSummary :: GhcMonad m => ModuleName -> m ModSummary getModSummary mod = do mg <- liftM hsc_mod_graph getSession case [ ms | ms <- mg, ms_mod_name ms == mod, not (isBootSummary ms) ] of [] -> do dflags <- getDynFlags liftIO $ throwIO $ mkApiErr dflags (text "Module not part of module graph") [ms] -> return ms multiple -> do dflags <- getDynFlags liftIO $ throwIO $ mkApiErr dflags (text "getModSummary is ambiguous: " <+> ppr multiple) -- | Parse a module. -- -- Throws a 'SourceError' on parse error. parseModule :: GhcMonad m => ModSummary -> m ParsedModule parseModule ms = do hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms } hpm <- liftIO $ hscParse hsc_env_tmp ms return (ParsedModule ms (hpm_module hpm) (hpm_src_files hpm) (hpm_annotations hpm)) -- See Note [Api annotations] in ApiAnnotation.hs -- | Typecheck and rename a parsed module. -- -- Throws a 'SourceError' if either fails. typecheckModule :: GhcMonad m => ParsedModule -> m TypecheckedModule typecheckModule pmod = do let ms = modSummary pmod hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms } (tc_gbl_env, rn_info) <- liftIO $ hscTypecheckRename hsc_env_tmp ms $ HsParsedModule { hpm_module = parsedSource pmod, hpm_src_files = pm_extra_src_files pmod, hpm_annotations = pm_annotations pmod } details <- liftIO $ makeSimpleDetails hsc_env_tmp tc_gbl_env safe <- liftIO $ finalSafeMode (ms_hspp_opts ms) tc_gbl_env return $ TypecheckedModule { tm_internals_ = (tc_gbl_env, details), tm_parsed_module = pmod, tm_renamed_source = rn_info, tm_typechecked_source = tcg_binds tc_gbl_env, tm_checked_module_info = ModuleInfo { minf_type_env = md_types details, minf_exports = availsToNameSet $ md_exports details, minf_rdr_env = Just (tcg_rdr_env tc_gbl_env), minf_instances = md_insts details, minf_iface = Nothing, minf_safe = safe #ifdef GHCI ,minf_modBreaks = emptyModBreaks #endif }} -- | Desugar a typechecked module. desugarModule :: GhcMonad m => TypecheckedModule -> m DesugaredModule desugarModule tcm = do let ms = modSummary tcm let (tcg, _) = tm_internals tcm hsc_env <- getSession let hsc_env_tmp = hsc_env { hsc_dflags = ms_hspp_opts ms } guts <- liftIO $ hscDesugar hsc_env_tmp ms tcg return $ DesugaredModule { dm_typechecked_module = tcm, dm_core_module = guts } -- | Load a module. Input doesn't need to be desugared. -- -- A module must be loaded before dependent modules can be typechecked. This -- always includes generating a 'ModIface' and, depending on the -- 'DynFlags.hscTarget', may also include code generation. -- -- This function will always cause recompilation and will always overwrite -- previous compilation results (potentially files on disk). -- loadModule :: (TypecheckedMod mod, GhcMonad m) => mod -> m mod loadModule tcm = do let ms = modSummary tcm let mod = ms_mod_name ms let loc = ms_location ms let (tcg, _details) = tm_internals tcm mb_linkable <- case ms_obj_date ms of Just t | t > ms_hs_date ms -> do l <- liftIO $ findObjectLinkable (ms_mod ms) (ml_obj_file loc) t return (Just l) _otherwise -> return Nothing let source_modified | isNothing mb_linkable = SourceModified | otherwise = SourceUnmodified -- we can't determine stability here -- compile doesn't change the session hsc_env <- getSession mod_info <- liftIO $ compileOne' (Just tcg) Nothing hsc_env ms 1 1 Nothing mb_linkable source_modified modifySession $ \e -> e{ hsc_HPT = addToUFM (hsc_HPT e) mod mod_info } return tcm -- %************************************************************************ -- %* * -- Dealing with Core -- %* * -- %************************************************************************ -- | A CoreModule consists of just the fields of a 'ModGuts' that are needed for -- the 'GHC.compileToCoreModule' interface. data CoreModule = CoreModule { -- | Module name cm_module :: !Module, -- | Type environment for types declared in this module cm_types :: !TypeEnv, -- | Declarations cm_binds :: CoreProgram, -- | Safe Haskell mode cm_safe :: SafeHaskellMode } instance Outputable CoreModule where ppr (CoreModule {cm_module = mn, cm_types = te, cm_binds = cb, cm_safe = sf}) = text "%module" <+> ppr mn <+> parens (ppr sf) <+> ppr te $$ vcat (map ppr cb) -- | This is the way to get access to the Core bindings corresponding -- to a module. 'compileToCore' parses, typechecks, and -- desugars the module, then returns the resulting Core module (consisting of -- the module name, type declarations, and function declarations) if -- successful. compileToCoreModule :: GhcMonad m => FilePath -> m CoreModule compileToCoreModule = compileCore False -- | Like compileToCoreModule, but invokes the simplifier, so -- as to return simplified and tidied Core. compileToCoreSimplified :: GhcMonad m => FilePath -> m CoreModule compileToCoreSimplified = compileCore True compileCore :: GhcMonad m => Bool -> FilePath -> m CoreModule compileCore simplify fn = do -- First, set the target to the desired filename target <- guessTarget fn Nothing addTarget target _ <- load LoadAllTargets -- Then find dependencies modGraph <- depanal [] True case find ((== fn) . msHsFilePath) modGraph of Just modSummary -> do -- Now we have the module name; -- parse, typecheck and desugar the module mod_guts <- coreModule `fmap` -- TODO: space leaky: call hsc* directly? (desugarModule =<< typecheckModule =<< parseModule modSummary) liftM (gutsToCoreModule (mg_safe_haskell mod_guts)) $ if simplify then do -- If simplify is true: simplify (hscSimplify), then tidy -- (tidyProgram). hsc_env <- getSession simpl_guts <- liftIO $ hscSimplify hsc_env mod_guts tidy_guts <- liftIO $ tidyProgram hsc_env simpl_guts return $ Left tidy_guts else return $ Right mod_guts Nothing -> panic "compileToCoreModule: target FilePath not found in\ module dependency graph" where -- two versions, based on whether we simplify (thus run tidyProgram, -- which returns a (CgGuts, ModDetails) pair, or not (in which case -- we just have a ModGuts. gutsToCoreModule :: SafeHaskellMode -> Either (CgGuts, ModDetails) ModGuts -> CoreModule gutsToCoreModule safe_mode (Left (cg, md)) = CoreModule { cm_module = cg_module cg, cm_types = md_types md, cm_binds = cg_binds cg, cm_safe = safe_mode } gutsToCoreModule safe_mode (Right mg) = CoreModule { cm_module = mg_module mg, cm_types = typeEnvFromEntities (bindersOfBinds (mg_binds mg)) (mg_tcs mg) (mg_fam_insts mg), cm_binds = mg_binds mg, cm_safe = safe_mode } -- %************************************************************************ -- %* * -- Inspecting the session -- %* * -- %************************************************************************ -- | Get the module dependency graph. getModuleGraph :: GhcMonad m => m ModuleGraph -- ToDo: DiGraph ModSummary getModuleGraph = liftM hsc_mod_graph getSession -- | Determines whether a set of modules requires Template Haskell. -- -- Note that if the session's 'DynFlags' enabled Template Haskell when -- 'depanal' was called, then each module in the returned module graph will -- have Template Haskell enabled whether it is actually needed or not. needsTemplateHaskell :: ModuleGraph -> Bool needsTemplateHaskell ms = any (xopt Opt_TemplateHaskell . ms_hspp_opts) ms -- | Return @True@ <==> module is loaded. isLoaded :: GhcMonad m => ModuleName -> m Bool isLoaded m = withSession $ \hsc_env -> return $! isJust (lookupUFM (hsc_HPT hsc_env) m) -- | Return the bindings for the current interactive session. getBindings :: GhcMonad m => m [TyThing] getBindings = withSession $ \hsc_env -> return $ icInScopeTTs $ hsc_IC hsc_env -- | Return the instances for the current interactive session. getInsts :: GhcMonad m => m ([ClsInst], [FamInst]) getInsts = withSession $ \hsc_env -> return $ ic_instances (hsc_IC hsc_env) getPrintUnqual :: GhcMonad m => m PrintUnqualified getPrintUnqual = withSession $ \hsc_env -> return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env)) -- | Container for information about a 'Module'. data ModuleInfo = ModuleInfo { minf_type_env :: TypeEnv, minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails? minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod minf_instances :: [ClsInst], minf_iface :: Maybe ModIface, minf_safe :: SafeHaskellMode #ifdef GHCI ,minf_modBreaks :: ModBreaks #endif } -- We don't want HomeModInfo here, because a ModuleInfo applies -- to package modules too. -- | Request information about a loaded 'Module' getModuleInfo :: GhcMonad m => Module -> m (Maybe ModuleInfo) -- XXX: Maybe X getModuleInfo mdl = withSession $ \hsc_env -> do let mg = hsc_mod_graph hsc_env if mdl `elem` map ms_mod mg then liftIO $ getHomeModuleInfo hsc_env mdl else do {- if isHomeModule (hsc_dflags hsc_env) mdl then return Nothing else -} liftIO $ getPackageModuleInfo hsc_env mdl -- ToDo: we don't understand what the following comment means. -- (SDM, 19/7/2011) -- getPackageModuleInfo will attempt to find the interface, so -- we don't want to call it for a home module, just in case there -- was a problem loading the module and the interface doesn't -- exist... hence the isHomeModule test here. (ToDo: reinstate) getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo) #ifdef GHCI getPackageModuleInfo hsc_env mdl = do eps <- hscEPS hsc_env iface <- hscGetModuleInterface hsc_env mdl let avails = mi_exports iface names = availsToNameSet avails pte = eps_PTE eps tys = [ ty | name <- concatMap availNames avails, Just ty <- [lookupTypeEnv pte name] ] -- return (Just (ModuleInfo { minf_type_env = mkTypeEnv tys, minf_exports = names, minf_rdr_env = Just $! availsToGlobalRdrEnv (moduleName mdl) avails, minf_instances = error "getModuleInfo: instances for package module unimplemented", minf_iface = Just iface, minf_safe = getSafeMode $ mi_trust iface, minf_modBreaks = emptyModBreaks })) #else -- bogusly different for non-GHCI (ToDo) getPackageModuleInfo _hsc_env _mdl = do return Nothing #endif getHomeModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo) getHomeModuleInfo hsc_env mdl = case lookupUFM (hsc_HPT hsc_env) (moduleName mdl) of Nothing -> return Nothing Just hmi -> do let details = hm_details hmi iface = hm_iface hmi return (Just (ModuleInfo { minf_type_env = md_types details, minf_exports = availsToNameSet (md_exports details), minf_rdr_env = mi_globals $! hm_iface hmi, minf_instances = md_insts details, minf_iface = Just iface, minf_safe = getSafeMode $ mi_trust iface #ifdef GHCI ,minf_modBreaks = getModBreaks hmi #endif })) -- | The list of top-level entities defined in a module modInfoTyThings :: ModuleInfo -> [TyThing] modInfoTyThings minf = typeEnvElts (minf_type_env minf) modInfoTopLevelScope :: ModuleInfo -> Maybe [Name] modInfoTopLevelScope minf = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf) modInfoExports :: ModuleInfo -> [Name] modInfoExports minf = nameSetElems $! minf_exports minf -- | Returns the instances defined by the specified module. -- Warning: currently unimplemented for package modules. modInfoInstances :: ModuleInfo -> [ClsInst] modInfoInstances = minf_instances modInfoIsExportedName :: ModuleInfo -> Name -> Bool modInfoIsExportedName minf name = elemNameSet name (minf_exports minf) mkPrintUnqualifiedForModule :: GhcMonad m => ModuleInfo -> m (Maybe PrintUnqualified) -- XXX: returns a Maybe X mkPrintUnqualifiedForModule minf = withSession $ \hsc_env -> do return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf)) modInfoLookupName :: GhcMonad m => ModuleInfo -> Name -> m (Maybe TyThing) -- XXX: returns a Maybe X modInfoLookupName minf name = withSession $ \hsc_env -> do case lookupTypeEnv (minf_type_env minf) name of Just tyThing -> return (Just tyThing) Nothing -> do eps <- liftIO $ readIORef (hsc_EPS hsc_env) return $! lookupType (hsc_dflags hsc_env) (hsc_HPT hsc_env) (eps_PTE eps) name modInfoIface :: ModuleInfo -> Maybe ModIface modInfoIface = minf_iface -- | Retrieve module safe haskell mode modInfoSafe :: ModuleInfo -> SafeHaskellMode modInfoSafe = minf_safe #ifdef GHCI modInfoModBreaks :: ModuleInfo -> ModBreaks modInfoModBreaks = minf_modBreaks #endif isDictonaryId :: Id -> Bool isDictonaryId id = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau } -- | Looks up a global name: that is, any top-level name in any -- visible module. Unlike 'lookupName', lookupGlobalName does not use -- the interactive context, and therefore does not require a preceding -- 'setContext'. lookupGlobalName :: GhcMonad m => Name -> m (Maybe TyThing) lookupGlobalName name = withSession $ \hsc_env -> do liftIO $ lookupTypeHscEnv hsc_env name findGlobalAnns :: (GhcMonad m, Typeable a) => ([Word8] -> a) -> AnnTarget Name -> m [a] findGlobalAnns deserialize target = withSession $ \hsc_env -> do ann_env <- liftIO $ prepareAnnotations hsc_env Nothing return (findAnns deserialize ann_env target) #ifdef GHCI -- | get the GlobalRdrEnv for a session getGRE :: GhcMonad m => m GlobalRdrEnv getGRE = withSession $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env) #endif -- ----------------------------------------------------------------------------- {- ToDo: Move the primary logic here to compiler/main/Packages.lhs -- | Return all /external/ modules available in the package database. -- Modules from the current session (i.e., from the 'HomePackageTable') are -- not included. This includes module names which are reexported by packages. packageDbModules :: GhcMonad m => Bool -- ^ Only consider exposed packages. -> m [Module] packageDbModules only_exposed = do dflags <- getSessionDynFlags let pkgs = eltsUFM (pkgIdMap (pkgState dflags)) return $ [ mkModule pid modname | p <- pkgs , not only_exposed || exposed p , let pid = packageConfigId p , modname <- exposedModules p ++ map exportName (reexportedModules p) ] -} -- ----------------------------------------------------------------------------- -- Misc exported utils dataConType :: DataCon -> Type dataConType dc = idType (dataConWrapId dc) -- | print a 'NamedThing', adding parentheses if the name is an operator. pprParenSymName :: NamedThing a => a -> SDoc pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a)) -- ---------------------------------------------------------------------------- #if 0 -- ToDo: -- - Data and Typeable instances for HsSyn. -- ToDo: check for small transformations that happen to the syntax in -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral) -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way -- to get from TyCons, Ids etc. to TH syntax (reify). -- :browse will use either lm_toplev or inspect lm_interface, depending -- on whether the module is interpreted or not. #endif -- Extract the filename, stringbuffer content and dynflags associed to a module -- -- XXX: Explain pre-conditions getModuleSourceAndFlags :: GhcMonad m => Module -> m (String, StringBuffer, DynFlags) getModuleSourceAndFlags mod = do m <- getModSummary (moduleName mod) case ml_hs_file $ ms_location m of Nothing -> do dflags <- getDynFlags liftIO $ throwIO $ mkApiErr dflags (text "No source available for module " <+> ppr mod) Just sourceFile -> do source <- liftIO $ hGetStringBuffer sourceFile return (sourceFile, source, ms_hspp_opts m) -- | Return module source as token stream, including comments. -- -- The module must be in the module graph and its source must be available. -- Throws a 'HscTypes.SourceError' on parse error. getTokenStream :: GhcMonad m => Module -> m [Located Token] getTokenStream mod = do (sourceFile, source, flags) <- getModuleSourceAndFlags mod let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1 case lexTokenStream source startLoc flags of POk _ ts -> return ts PFailed span err -> do dflags <- getDynFlags liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err) -- | Give even more information on the source than 'getTokenStream' -- This function allows reconstructing the source completely with -- 'showRichTokenStream'. getRichTokenStream :: GhcMonad m => Module -> m [(Located Token, String)] getRichTokenStream mod = do (sourceFile, source, flags) <- getModuleSourceAndFlags mod let startLoc = mkRealSrcLoc (mkFastString sourceFile) 1 1 case lexTokenStream source startLoc flags of POk _ ts -> return $ addSourceToTokens startLoc source ts PFailed span err -> do dflags <- getDynFlags liftIO $ throwIO $ mkSrcErr (unitBag $ mkPlainErrMsg dflags span err) -- | Given a source location and a StringBuffer corresponding to this -- location, return a rich token stream with the source associated to the -- tokens. addSourceToTokens :: RealSrcLoc -> StringBuffer -> [Located Token] -> [(Located Token, String)] addSourceToTokens _ _ [] = [] addSourceToTokens loc buf (t@(L span _) : ts) = case span of UnhelpfulSpan _ -> (t,"") : addSourceToTokens loc buf ts RealSrcSpan s -> (t,str) : addSourceToTokens newLoc newBuf ts where (newLoc, newBuf, str) = go "" loc buf start = realSrcSpanStart s end = realSrcSpanEnd s go acc loc buf | loc < start = go acc nLoc nBuf | start <= loc && loc < end = go (ch:acc) nLoc nBuf | otherwise = (loc, buf, reverse acc) where (ch, nBuf) = nextChar buf nLoc = advanceSrcLoc loc ch -- | Take a rich token stream such as produced from 'getRichTokenStream' and -- return source code almost identical to the original code (except for -- insignificant whitespace.) showRichTokenStream :: [(Located Token, String)] -> String showRichTokenStream ts = go startLoc ts "" where sourceFile = getFile $ map (getLoc . fst) ts getFile [] = panic "showRichTokenStream: No source file found" getFile (UnhelpfulSpan _ : xs) = getFile xs getFile (RealSrcSpan s : _) = srcSpanFile s startLoc = mkRealSrcLoc sourceFile 1 1 go _ [] = id go loc ((L span _, str):ts) = case span of UnhelpfulSpan _ -> go loc ts RealSrcSpan s | locLine == tokLine -> ((replicate (tokCol - locCol) ' ') ++) . (str ++) . go tokEnd ts | otherwise -> ((replicate (tokLine - locLine) '\n') ++) . ((replicate (tokCol - 1) ' ') ++) . (str ++) . go tokEnd ts where (locLine, locCol) = (srcLocLine loc, srcLocCol loc) (tokLine, tokCol) = (srcSpanStartLine s, srcSpanStartCol s) tokEnd = realSrcSpanEnd s -- ----------------------------------------------------------------------------- -- Interactive evaluation -- | Takes a 'ModuleName' and possibly a 'PackageKey', and consults the -- filesystem and package database to find the corresponding 'Module', -- using the algorithm that is used for an @import@ declaration. findModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module findModule mod_name maybe_pkg = withSession $ \hsc_env -> do let dflags = hsc_dflags hsc_env this_pkg = thisPackage dflags -- case maybe_pkg of Just pkg | fsToPackageKey pkg /= this_pkg && pkg /= fsLit "this" -> liftIO $ do res <- findImportedModule hsc_env mod_name maybe_pkg case res of Found _ m -> return m err -> throwOneError $ noModError dflags noSrcSpan mod_name err _otherwise -> do home <- lookupLoadedHomeModule mod_name case home of Just m -> return m Nothing -> liftIO $ do res <- findImportedModule hsc_env mod_name maybe_pkg case res of Found loc m | modulePackageKey m /= this_pkg -> return m | otherwise -> modNotLoadedError dflags m loc err -> throwOneError $ noModError dflags noSrcSpan mod_name err modNotLoadedError :: DynFlags -> Module -> ModLocation -> IO a modNotLoadedError dflags m loc = throwGhcExceptionIO $ CmdLineError $ showSDoc dflags $ text "module is not loaded:" <+> quotes (ppr (moduleName m)) <+> parens (text (expectJust "modNotLoadedError" (ml_hs_file loc))) -- | Like 'findModule', but differs slightly when the module refers to -- a source file, and the file has not been loaded via 'load'. In -- this case, 'findModule' will throw an error (module not loaded), -- but 'lookupModule' will check to see whether the module can also be -- found in a package, and if so, that package 'Module' will be -- returned. If not, the usual module-not-found error will be thrown. -- lookupModule :: GhcMonad m => ModuleName -> Maybe FastString -> m Module lookupModule mod_name (Just pkg) = findModule mod_name (Just pkg) lookupModule mod_name Nothing = withSession $ \hsc_env -> do home <- lookupLoadedHomeModule mod_name case home of Just m -> return m Nothing -> liftIO $ do res <- findExposedPackageModule hsc_env mod_name Nothing case res of Found _ m -> return m err -> throwOneError $ noModError (hsc_dflags hsc_env) noSrcSpan mod_name err lookupLoadedHomeModule :: GhcMonad m => ModuleName -> m (Maybe Module) lookupLoadedHomeModule mod_name = withSession $ \hsc_env -> case lookupUFM (hsc_HPT hsc_env) mod_name of Just mod_info -> return (Just (mi_module (hm_iface mod_info))) _not_a_home_module -> return Nothing #ifdef GHCI -- | Check that a module is safe to import (according to Safe Haskell). -- -- We return True to indicate the import is safe and False otherwise -- although in the False case an error may be thrown first. isModuleTrusted :: GhcMonad m => Module -> m Bool isModuleTrusted m = withSession $ \hsc_env -> liftIO $ hscCheckSafe hsc_env m noSrcSpan -- | Return if a module is trusted and the pkgs it depends on to be trusted. moduleTrustReqs :: GhcMonad m => Module -> m (Bool, [PackageKey]) moduleTrustReqs m = withSession $ \hsc_env -> liftIO $ hscGetSafe hsc_env m noSrcSpan -- | EXPERIMENTAL: DO NOT USE. -- -- Set the monad GHCi lifts user statements into. -- -- Checks that a type (in string form) is an instance of the -- @GHC.GHCi.GHCiSandboxIO@ type class. Sets it to be the GHCi monad if it is, -- throws an error otherwise. {-# WARNING setGHCiMonad "This is experimental! Don't use." #-} setGHCiMonad :: GhcMonad m => String -> m () setGHCiMonad name = withSession $ \hsc_env -> do ty <- liftIO $ hscIsGHCiMonad hsc_env name modifySession $ \s -> let ic = (hsc_IC s) { ic_monad = ty } in s { hsc_IC = ic } getHistorySpan :: GhcMonad m => History -> m SrcSpan getHistorySpan h = withSession $ \hsc_env -> return $ InteractiveEval.getHistorySpan hsc_env h obtainTermFromVal :: GhcMonad m => Int -> Bool -> Type -> a -> m Term obtainTermFromVal bound force ty a = withSession $ \hsc_env -> liftIO $ InteractiveEval.obtainTermFromVal hsc_env bound force ty a obtainTermFromId :: GhcMonad m => Int -> Bool -> Id -> m Term obtainTermFromId bound force id = withSession $ \hsc_env -> liftIO $ InteractiveEval.obtainTermFromId hsc_env bound force id #endif -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any -- entity known to GHC, including 'Name's defined using 'runStmt'. lookupName :: GhcMonad m => Name -> m (Maybe TyThing) lookupName name = withSession $ \hsc_env -> liftIO $ hscTcRcLookupName hsc_env name -- ----------------------------------------------------------------------------- -- Pure API -- | A pure interface to the module parser. -- parser :: String -- ^ Haskell module source text (full Unicode is supported) -> DynFlags -- ^ the flags -> FilePath -- ^ the filename (for source locations) -> Either ErrorMessages (WarningMessages, Located (HsModule RdrName)) parser str dflags filename = let loc = mkRealSrcLoc (mkFastString filename) 1 1 buf = stringToStringBuffer str in case unP Parser.parseModule (mkPState dflags buf loc) of PFailed span err -> Left (unitBag (mkPlainErrMsg dflags span err)) POk pst rdr_module -> let (warns,_) = getMessages pst in Right (warns, rdr_module)
bitemyapp/ghc
compiler/main/GHC.hs
bsd-3-clause
55,483
4
28
15,226
9,854
5,316
4,538
-1
-1
import Text.XML.YJSVG main = do putStrLn $ showSVG 600 550 $ [ Text 10 50 25 (ColorName "green") "KochiGothic" "今日は", Text 10 90 25 (ColorName "green") "KochiMincho" "今日は" ]
YoshikuniJujo/yjsvg_haskell
tests/font.hs
bsd-3-clause
195
7
11
38
81
39
42
5
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} module Main where import qualified Brick.AttrMap as A import Brick.BChan import qualified Brick.Main as M import Brick.Types (BrickEvent (..), CursorLocation, EventM, Next, Widget (..), attrL, emptyResult, handleEventLensed) import Brick.Util (on) import qualified Brick.Widgets.Center as C import Brick.Widgets.Core (hLimit, str, vLimit, (<+>), (<=>)) import qualified Graphics.Vty as V import Lens.Micro import Lens.Micro.TH import qualified EditRope as E import qualified Yi.Rope as Y import ErrUtils (mkPlainErrMsg) import FastString (mkFastString) import GHC import GHC.Paths (libdir) import Lexer import qualified MonadUtils as GMU import SrcLoc import StringBuffer import Control.Concurrent import Control.Monad import Control.Monad.IO.Class import qualified Control.FoldDebounce as Fdeb import System.IO data EditorName = Edit1 | Edit2 deriving (Ord, Show, Eq) newtype St = St { _edit1 :: E.Editor EditorName } makeLenses ''St drawUI :: St -> [Widget EditorName] drawUI st = [ui] where e1 = E.renderEditor True (st^.edit1) ui = C.center $ hLimit 30 (vLimit 5 e1) appEvent :: St -> BrickEvent EditorName (E.TokenizedEvent [GHC.Located GHC.Token]) -> EventM EditorName (Next St) appEvent st e = case e of VtyEvent (V.EvKey V.KEsc []) -> M.halt st appEvt@(AppEvent (E.Tokens _)) -> handleInEditor st appEvt vtyEv@(VtyEvent (V.EvKey _ _)) -> handleInEditor st vtyEv _ -> M.continue st handleInEditor :: St -> BrickEvent EditorName (E.TokenizedEvent [GHC.Located GHC.Token]) -> EventM EditorName (Next St) handleInEditor st e = M.continue =<< handleEventLensed st edit1 E.handleEditorEvent e initialState :: (String -> IO ()) -> St initialState sendSource = St (E.editor Edit1 "edit1" sendSource) theMap :: A.AttrMap theMap = A.attrMap V.defAttr [ (E.editAttr, V.white `on` V.black) ,(A.attrName "ITinteger", V.withStyle (V.green `on` V.black) V.bold) ,(A.attrName "ITvarid", V.withStyle (V.blue `on` V.black) V.bold) ] theApp :: M.App St (E.TokenizedEvent [GHC.Located GHC.Token]) EditorName theApp = M.App { M.appDraw = drawUI , M.appChooseCursor = M.showFirstCursor , M.appHandleEvent = appEvent , M.appStartEvent = return -- TODO: initial tokenization ! , M.appAttrMap = const theMap } main :: IO () main = do eventChannel <- newBChan 1 lexerChannel <- liftIO newEmptyMVar liftIO $ startGhc eventChannel lexerChannel let callback = putMVar lexerChannel -- TODO: this debounces input events -- trigger <- Fdeb.new Fdeb.Args { Fdeb.cb = callback, Fdeb.fold = \_ i -> i, Fdeb.init = "" } -- Fdeb.def { Fdeb.delay = 100000 } -- let sendSource = Fdeb.send trigger -- let initSt = initialState sendSource let initSt = initialState callback st <- M.customMain (V.mkVty V.defaultConfig) (Just eventChannel) theApp initSt putStrLn "In input 1 you entered:\n" putStrLn $ Y.toString $ E.getEditContents $ st^.edit1 startGhc :: BChan (E.TokenizedEvent [Located Token]) -> MVar String -> IO () startGhc eventChannel lexerChannel = do _ <- forkIO $ runGhc (Just libdir) $ do flags <- getSessionDynFlags let lexLoc = mkRealSrcLoc (mkFastString "<interactive>") 1 1 GMU.liftIO $ forever $ do src <- takeMVar lexerChannel let sb = stringToStringBuffer src let pResult = lexTokenStream sb lexLoc flags case pResult of POk _ toks -> GMU.liftIO $ do hPutStrLn stderr $ "TOKENS\n" ++ concatMap showToken toks writeBChan eventChannel $ E.Tokens toks PFailed srcspan msg -> do GMU.liftIO $ print $ show srcspan GMU.liftIO $ do putStrLn "Lexer Error:" print $ mkPlainErrMsg flags srcspan msg return () showToken :: GenLocated SrcSpan Token -> String showToken t = "\nsrcLoc: " ++ srcloc ++ "\ntok: " ++ tok ++ "\n" where srcloc = show $ getLoc t tok = show $ unLoc t showTokenWithSource :: (Located Token, String) -> String showTokenWithSource (loctok, src) = "Located Token: " ++ tok ++ "\n" ++ "Source: " ++ src ++ "\n" ++ "Location: " ++ srcloc ++ "\n\n" where tok = show $ unLoc loctok srcloc = show $ getLoc loctok
clojj/hsedit
app/Main.hs
bsd-3-clause
4,831
19
21
1,421
1,347
723
624
105
4
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE CPP #-} module WeiXin.PublicPlatform.Utils ( module WeiXin.PublicPlatform.Utils , epochIntToUtcTime , utcTimeToEpochInt ) where import ClassyPrelude #if MIN_VERSION_base(4, 13, 0) import Control.Monad (MonadFail(..)) #else #endif import qualified Control.Exception.Safe as ExcSafe import qualified Codec.QRCode.JuicyPixels as QRJP -- haskell-qrencode import qualified Codec.QRCode as QRC import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString as B import qualified Codec.Picture as P -- from `JuicyPixel' package import qualified Codec.Picture.Saving as P -- from `JuicyPixel' package import qualified Data.Text as T import qualified Data.Serialize as S import qualified Data.StateVar as SV import qualified Data.Aeson as A import qualified Data.Yaml as Y import qualified Data.HashMap.Strict as HM import System.FilePath (hasExtension) import System.Directory (doesFileExist) import Network.Mime (MimeType, defaultMimeType) import Network.Wreq (Response, responseBody, responseHeader) import Control.Lens ((^.), (^?)) import Control.Monad.Trans.Maybe import Data.Aeson.Types (Parser) import Data.Aeson import Data.Yaml (ParseException, prettyPrintParseException) import qualified Data.Yaml as Yaml import Data.List.NonEmpty as LNE hiding (length, (!!), filter) import Numeric (readDec, readFloat) import Crypto.Hash.TX.Utils (MD5Hash(..), md5HashBS) import Yesod.Helpers.Utils (epochIntToUtcTime, utcTimeToEpochInt) data YamlFileParseException = YamlFileParseException String -- file path ParseException -- the real exception deriving (Typeable) instance Show YamlFileParseException where show (YamlFileParseException fp exc) = fp ++ ": " ++ prettyPrintParseException exc instance Exception YamlFileParseException -- | 在实现允许在解释一个 YAML 时,引用另一个 YAML这样的功能时 -- 在第一次解释时,结果不再是一个简单的值,而是一个 IO 函数。 -- 以下类型就是表达这种延期加载的函数 -- ReaderT 的 r 参数是相对路径相对的目录 type DelayedYamlLoader a = ReaderT (NonEmpty FilePath) -- 运行时要知道一个或更多的消息文件的基础目录 IO (Either YamlFileParseException a) -- | Cache read result from file system type CachedYamlInfo = HashMap FilePath -- full file path (MD5Hash, Value) -- file content md5 and its Yaml parsing result type CachedYamlLoader s a = ReaderT s IO a -- | intend to obsolete DelayedYamlLoader type DelayedCachedYamlLoader s a = NonEmpty FilePath -> CachedYamlLoader s a type CachedYamlInfoState s = ( SV.HasUpdate s CachedYamlInfo CachedYamlInfo , SV.HasGetter s CachedYamlInfo ) setExtIfNotExist :: String -> FilePath -> FilePath setExtIfNotExist def_ext fp = if hasExtension fp then fp else fp <.> def_ext -- | 从一个字典对象中解释出某种值 -- 这个字典里约定两个字段 -- 一个是直接可以解释出所需的值的字段,即值直接内嵌在当前字典中 -- 另一个是指示出一个文件路径的字段,此路径用于真正延迟加载的情况 -- 如果不指定第一个字段,那么就认为当前的字典可以解释出所需的值 parseDelayedYamlLoader :: FromJSON a => Maybe Text -> Text -> Object -> Parser (DelayedYamlLoader a) parseDelayedYamlLoader m_direct_field indirect_field obj = case m_direct_field of Nothing -> -- 在没有指定直接字段时,优先试一次间接字段 parse_indirect <|> (return . Right <$> parseJSON (toJSON obj)) Just direct_field -> (return . Right <$> obj .: direct_field) <|> parse_indirect where parse_indirect = mkDelayedYamlLoader . setExtIfNotExist "yml" . T.unpack <$> obj .: indirect_field mkDelayedYamlLoader :: forall a. FromJSON a => FilePath -> DelayedYamlLoader a mkDelayedYamlLoader fp = do base_dir_list <- ask liftIO $ do -- 运行时,如果全部都有 IOError,抛出第一个非 DoesNotExistError let try_dir :: FilePath -> IO (Either (Either IOError YamlFileParseException) a) try_dir bp = do let full_path = bp </> fp ioerr_or_v <- tryIOError $ do -- we need to catch IOError, so don't use decodeFileEither -- decodeFileEither full_path (liftM Yaml.decodeEither' $ B.readFile full_path) return $ case ioerr_or_v of Left ioe -> Left $ Left ioe Right (Left perr) -> Left $ Right $ YamlFileParseException full_path perr Right (Right x) -> Right x first_try <- try_dir $ LNE.head base_dir_list case first_try of Right v -> return $ Right v Left first_err -> do let is_does_not_exist_err (Left ioe) = isDoesNotExistError ioe is_does_not_exist_err (Right _) = False let go [] last_err = either (liftIO . throwIO) (return . Left) last_err go (x:xs) last_err = do try_dir x >>= either (\e -> go xs $ if is_does_not_exist_err last_err then e else last_err) (return . Right) go (LNE.tail base_dir_list) first_err -- | May throw IOError runDelayedYamlLoaderL_IOE :: (MonadIO m) => NonEmpty FilePath -- ^ 消息文件存放目录 -> DelayedYamlLoader a -> m (Either YamlFileParseException a) runDelayedYamlLoaderL_IOE base_dirs f = liftIO $ runReaderT f base_dirs runDelayedYamlLoaderL :: (MonadIO m) => NonEmpty FilePath -- ^ 消息文件存放目录 -> DelayedYamlLoader a -> m (Either String a) runDelayedYamlLoaderL base_dir_list get_ext = liftIO $ do err_or_x <- tryIOError $ runReaderT get_ext base_dir_list case err_or_x of Left err -> return $ Left $ "failed to load from file: " ++ show err Right x -> return $ parseMsgErrorToString x runDelayedYamlLoader :: (MonadIO m) => FilePath -- ^ 消息文件存放目录 -> DelayedYamlLoader a -> m (Either String a) runDelayedYamlLoader base_dir = runDelayedYamlLoaderL (base_dir :| []) -- | 这是会抛异常的版本 runDelayedYamlLoaderExcL :: (MonadIO m) => NonEmpty FilePath -- ^ 消息文件存放目录 -> DelayedYamlLoader a -> m a runDelayedYamlLoaderExcL base_dir_list get_ext = liftIO $ runReaderT get_ext base_dir_list >>= either (liftIO . throwIO) return runDelayedYamlLoaderExc :: (MonadIO m) => FilePath -- ^ 消息文件存放目录 -> DelayedYamlLoader a -> m a runDelayedYamlLoaderExc base_dir = runDelayedYamlLoaderExcL (base_dir :| []) findFirstMatchedFile :: (Functor t, Foldable t) => t FilePath -- ^ base dirs to try -> FilePath -- ^ sub-path -> IO (Maybe FilePath) -- ^ get the first fullpath that exists findFirstMatchedFile base_dir_list fp = do runMaybeT $ asum $ fmap (MaybeT . try_dir) $ base_dir_list where try_dir bp = do let full_path = bp </> fp exists <- doesFileExist full_path return $ if exists then Just full_path else Nothing mkDelayedCachedYamlLoader :: ( FromJSON a, CachedYamlInfoState s) => FilePath -> DelayedCachedYamlLoader s a mkDelayedCachedYamlLoader fp base_dir_list = do full_path <- liftIO (findFirstMatchedFile base_dir_list fp) >>= maybe (liftIO $ throwIO $ mkIOError doesNotExistErrorType "mkDelayedCachedYamlLoader" Nothing (Just fp)) return bs <- liftIO $ B.readFile full_path let md5sum = md5HashBS bs st <- ask cache_map <- SV.get st jv <- case HM.lookup full_path cache_map of Just (md5sum2, jv) | md5sum == md5sum2 -> do return jv _ -> do new_jv <- either (liftIO . throwIO . YamlFileParseException full_path) return $ Y.decodeEither' bs st SV.$~! (HM.insert full_path (md5sum, new_jv)) return new_jv case A.fromJSON jv of A.Error err -> liftIO $ throwIO $ YamlFileParseException full_path (Y.AesonException err) A.Success x -> return x -- | May throw IOError runDelayedCachedYamlLoaderL_IOE :: ( MonadIO m) => s -> NonEmpty FilePath -- ^ 消息文件存放目录 -> DelayedCachedYamlLoader s a -> m (Either YamlFileParseException a) runDelayedCachedYamlLoaderL_IOE st base_dirs f = liftIO $ try $ runReaderT (f base_dirs) st -- | Don't throw IOError runDelayedCachedYamlLoaderL :: ( MonadIO m ) => s -> NonEmpty FilePath -- ^ 消息文件存放目录 -> DelayedCachedYamlLoader s a -> m (Either String a) runDelayedCachedYamlLoaderL st base_dirs f = liftIO $ do err_or_x <- tryIOError $ try $ runReaderT (f base_dirs) st case err_or_x of Left err -> return $ Left $ "failed to load from file: " ++ show err Right x -> return $ parseMsgErrorToString x parseMsgErrorToString :: Either YamlFileParseException a -> Either String a parseMsgErrorToString (Left err) = Left $ "failed to parse from file: " ++ show err parseMsgErrorToString (Right x) = Right x unifyExcHandler :: (Show e, Monad m) => ExcSafe.Handler m (Either e a) -> ExcSafe.Handler m (Either String a) unifyExcHandler = #if MIN_VERSION_classy_prelude(1, 0, 0) \ (ExcSafe.Handler f) -> ExcSafe.Handler $ fmap (either (Left . show) Right) . f #else fmap $ either (Left . show) Right #endif encodeStringQRCodeImage :: (QRC.ToText a) => Int -> a -> (P.Image P.Pixel8) encodeStringQRCodeImage pixelPerCell input = QRJP.toImage 4 pixelPerCell $ fromMaybe (error "QRC.encodeTExt failed") $ QRC.encodeText (QRC.defaultQRCodeOptions QRC.M) QRC.Utf8WithoutECI input encodeStringQRCodeJpeg :: (QRC.ToText a) => Int -> a -> LB.ByteString encodeStringQRCodeJpeg pixelPerCell input = P.imageToJpg 100 . P.ImageY8 $ encodeStringQRCodeImage pixelPerCell input encodeStringQRCodePng :: (QRC.ToText a) => Int -> a -> LB.ByteString encodeStringQRCodePng pixelPerCell input = P.imageToPng . P.ImageY8 $ encodeStringQRCodeImage pixelPerCell input -- | 经常需要保存微信的文件内容及mime到本地 -- 这个类型及下面的工具函数为此而设 type FileContentAndMime = (LB.ByteString, MimeType) saveWreqResponseContentAndMime :: (MonadIO m) => Handle -> Response LB.ByteString -> m FileContentAndMime saveWreqResponseContentAndMime h r = liftIO $ do LB.hPut h $ S.encodeLazy dat return dat where dat = (body, mime) body = r ^. responseBody mime = fromMaybe defaultMimeType $ r ^? responseHeader "Content-Type" loadWreqResponseContentAndMime :: (MonadIO m) => Handle -- ^ 因为使用了 hGetContents ,Handle 会关闭 -> m FileContentAndMime loadWreqResponseContentAndMime h = liftIO $ do lbs <- LB.hGetContents h either (const $ throwIO $ userError "cannot decode file as FileContentAndMime") return $ S.decodeLazy lbs simpleParseDec :: (Eq a, Num a) => String -> Maybe a simpleParseDec = fmap fst . listToMaybe . filter (null . snd) . readDec simpleParseDecT :: (Eq a, Num a) => Text -> Maybe a simpleParseDecT = simpleParseDec . T.unpack simpleParseFloat :: (RealFrac a) => String -> Maybe a simpleParseFloat = fmap fst . listToMaybe . filter ((== "") . snd) . readFloat simpleParseFloatT :: (RealFrac a) => Text -> Maybe a simpleParseFloatT = simpleParseFloat . T.unpack nonEmptyJsonText :: String -- ^ error message -> Text -- ^ parsed text, returned unchanged if non-empty -> Parser Text nonEmptyJsonText msg t = do if null t then fail msg else return t boolToInt :: Bool -> Int boolToInt False = 0 boolToInt True = 1
yoo-e/weixin-mp-sdk
WeiXin/PublicPlatform/Utils.hs
mit
13,317
0
26
4,029
2,931
1,524
1,407
230
7
{-# 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.StorageGateway.ListVolumeRecoveryPoints -- 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. -- | This operation lists the recovery points for a specified gateway. This -- operation is supported only for the gateway-cached volume architecture. -- -- Each gateway-cached volume has one recovery point. A volume recovery point -- is a point in time at which all data of the volume is consistent and from -- which you can create a snapshot. To create a snapshot from a volume recovery -- point use the 'CreateSnapshotFromVolumeRecoveryPoint' operation. -- -- <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_ListVolumeRecoveryPoints.html> module Network.AWS.StorageGateway.ListVolumeRecoveryPoints ( -- * Request ListVolumeRecoveryPoints -- ** Request constructor , listVolumeRecoveryPoints -- ** Request lenses , lvrpGatewayARN -- * Response , ListVolumeRecoveryPointsResponse -- ** Response constructor , listVolumeRecoveryPointsResponse -- ** Response lenses , lvrprGatewayARN , lvrprVolumeRecoveryPointInfos ) where import Network.AWS.Data (Object) import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.StorageGateway.Types import qualified GHC.Exts newtype ListVolumeRecoveryPoints = ListVolumeRecoveryPoints { _lvrpGatewayARN :: Text } deriving (Eq, Ord, Read, Show, Monoid, IsString) -- | 'ListVolumeRecoveryPoints' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lvrpGatewayARN' @::@ 'Text' -- listVolumeRecoveryPoints :: Text -- ^ 'lvrpGatewayARN' -> ListVolumeRecoveryPoints listVolumeRecoveryPoints p1 = ListVolumeRecoveryPoints { _lvrpGatewayARN = p1 } lvrpGatewayARN :: Lens' ListVolumeRecoveryPoints Text lvrpGatewayARN = lens _lvrpGatewayARN (\s a -> s { _lvrpGatewayARN = a }) data ListVolumeRecoveryPointsResponse = ListVolumeRecoveryPointsResponse { _lvrprGatewayARN :: Maybe Text , _lvrprVolumeRecoveryPointInfos :: List "VolumeRecoveryPointInfos" VolumeRecoveryPointInfo } deriving (Eq, Read, Show) -- | 'ListVolumeRecoveryPointsResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'lvrprGatewayARN' @::@ 'Maybe' 'Text' -- -- * 'lvrprVolumeRecoveryPointInfos' @::@ ['VolumeRecoveryPointInfo'] -- listVolumeRecoveryPointsResponse :: ListVolumeRecoveryPointsResponse listVolumeRecoveryPointsResponse = ListVolumeRecoveryPointsResponse { _lvrprGatewayARN = Nothing , _lvrprVolumeRecoveryPointInfos = mempty } lvrprGatewayARN :: Lens' ListVolumeRecoveryPointsResponse (Maybe Text) lvrprGatewayARN = lens _lvrprGatewayARN (\s a -> s { _lvrprGatewayARN = a }) lvrprVolumeRecoveryPointInfos :: Lens' ListVolumeRecoveryPointsResponse [VolumeRecoveryPointInfo] lvrprVolumeRecoveryPointInfos = lens _lvrprVolumeRecoveryPointInfos (\s a -> s { _lvrprVolumeRecoveryPointInfos = a }) . _List instance ToPath ListVolumeRecoveryPoints where toPath = const "/" instance ToQuery ListVolumeRecoveryPoints where toQuery = const mempty instance ToHeaders ListVolumeRecoveryPoints instance ToJSON ListVolumeRecoveryPoints where toJSON ListVolumeRecoveryPoints{..} = object [ "GatewayARN" .= _lvrpGatewayARN ] instance AWSRequest ListVolumeRecoveryPoints where type Sv ListVolumeRecoveryPoints = StorageGateway type Rs ListVolumeRecoveryPoints = ListVolumeRecoveryPointsResponse request = post "ListVolumeRecoveryPoints" response = jsonResponse instance FromJSON ListVolumeRecoveryPointsResponse where parseJSON = withObject "ListVolumeRecoveryPointsResponse" $ \o -> ListVolumeRecoveryPointsResponse <$> o .:? "GatewayARN" <*> o .:? "VolumeRecoveryPointInfos" .!= mempty
kim/amazonka
amazonka-storagegateway/gen/Network/AWS/StorageGateway/ListVolumeRecoveryPoints.hs
mpl-2.0
4,804
0
12
922
534
322
212
65
1
module Bug548 (WrappedArrow(..)) where import Control.Applicative
Fuuzetsu/haddock
html-test/src/Bug548.hs
bsd-2-clause
67
0
5
7
18
12
6
2
0
{-# LANGUAGE TypeFamilies, GADTs, ConstraintKinds, RankNTypes #-} module T5655 where import GHC.Exts (Constraint) class Show a => Twice a where twice :: a -> a instance Twice Int where twice = (*2) data ETwice where ETwice :: Twice a => a -> ETwice class E e where type C e :: * -> Constraint ap :: (forall a. C e a => a -> r) -> e -> r instance E ETwice where type C ETwice = Twice ap f (ETwice a) = f a f :: (E e, C e ~ Twice) => e -> ETwice f = ap (ETwice . twice) foo :: ETwice foo = ETwice (5 :: Int) bar :: IO () bar = ap print (f foo)
rahulmutt/ghcvm
tests/suite/typecheck/compile/T5655.hs
bsd-3-clause
567
0
11
147
256
137
119
18
1
-- Copyright (c) 2013 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS -- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. {-# OPTIONS_GHC -Wall -Werror -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances, FlexibleContexts, UndecidableInstances, MultiParamTypeClasses #-} -- | Some useful instances for 'Scope's in the bound library. This -- provides 'Format', 'FormatM', and 'XmlPickler' instances for any -- 'Scope'. module Bound.Scope.ExtraInstances where import Bound.Scope import Bound.Var import Text.Format import Text.XML.Expat.Pickle import Text.XML.Expat.Tree(NodeG) instance (Monad t, Format (t (Var b s))) => Format (Scope b t s) where format s = format (fromScope s) instance (Monad m, Monad t, FormatM m (t (Var b s))) => FormatM m (Scope b t s) where formatM s = formatM (fromScope s) instance (GenericXMLString tag, Show tag, GenericXMLString text, Show text, Monad func, XmlPickler [NodeG [] tag text] (func (Var bound free))) => XmlPickler [NodeG [] tag text] (Scope bound func free) where xpickle = xpWrap (toScope, fromScope) xpickle
emc2/compiler-misc
src/Bound/Scope/ExtraInstances.hs
bsd-3-clause
2,541
0
10
452
328
189
139
18
0
{-# 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.CloudFront.GetInvalidation -- 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. -- | Get the information about an invalidation. -- -- <http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/GetInvalidation.html> module Network.AWS.CloudFront.GetInvalidation ( -- * Request GetInvalidation -- ** Request constructor , getInvalidation -- ** Request lenses , giDistributionId , giId -- * Response , GetInvalidationResponse -- ** Response constructor , getInvalidationResponse -- ** Response lenses , girInvalidation ) where import Network.AWS.Prelude import Network.AWS.Request.RestXML import Network.AWS.CloudFront.Types import qualified GHC.Exts data GetInvalidation = GetInvalidation { _giDistributionId :: Text , _giId :: Text } deriving (Eq, Ord, Read, Show) -- | 'GetInvalidation' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'giDistributionId' @::@ 'Text' -- -- * 'giId' @::@ 'Text' -- getInvalidation :: Text -- ^ 'giDistributionId' -> Text -- ^ 'giId' -> GetInvalidation getInvalidation p1 p2 = GetInvalidation { _giDistributionId = p1 , _giId = p2 } -- | The distribution's id. giDistributionId :: Lens' GetInvalidation Text giDistributionId = lens _giDistributionId (\s a -> s { _giDistributionId = a }) -- | The invalidation's id. giId :: Lens' GetInvalidation Text giId = lens _giId (\s a -> s { _giId = a }) newtype GetInvalidationResponse = GetInvalidationResponse { _girInvalidation :: Maybe Invalidation } deriving (Eq, Read, Show) -- | 'GetInvalidationResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'girInvalidation' @::@ 'Maybe' 'Invalidation' -- getInvalidationResponse :: GetInvalidationResponse getInvalidationResponse = GetInvalidationResponse { _girInvalidation = Nothing } -- | The invalidation's information. girInvalidation :: Lens' GetInvalidationResponse (Maybe Invalidation) girInvalidation = lens _girInvalidation (\s a -> s { _girInvalidation = a }) instance ToPath GetInvalidation where toPath GetInvalidation{..} = mconcat [ "/2014-11-06/distribution/" , toText _giDistributionId , "/invalidation/" , toText _giId ] instance ToQuery GetInvalidation where toQuery = const mempty instance ToHeaders GetInvalidation instance ToXMLRoot GetInvalidation where toXMLRoot = const (namespaced ns "GetInvalidation" []) instance ToXML GetInvalidation instance AWSRequest GetInvalidation where type Sv GetInvalidation = CloudFront type Rs GetInvalidation = GetInvalidationResponse request = get response = xmlResponse instance FromXML GetInvalidationResponse where parseXML x = GetInvalidationResponse <$> x .@? "Invalidation"
kim/amazonka
amazonka-cloudfront/gen/Network/AWS/CloudFront/GetInvalidation.hs
mpl-2.0
3,854
0
9
865
513
309
204
65
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} module Web.Twitter.Conduit.Stream ( -- * StreamingAPI Userstream , userstream , StatusesFilter , statusesFilterByFollow , statusesFilterByTrack -- , statusesFilterByLocation -- , statusesSample -- , statusesFirehose -- , sitestream -- , sitestream' , stream , stream' ) where import Web.Twitter.Conduit.Types import Web.Twitter.Conduit.Base import Web.Twitter.Types import Web.Twitter.Conduit.Parameters import Web.Twitter.Conduit.Parameters.TH import Web.Twitter.Conduit.Request import Web.Twitter.Conduit.Response import qualified Data.Conduit as C import qualified Data.Conduit.List as CL import qualified Data.Conduit.Internal as CI import qualified Data.Text as T import Control.Monad.IO.Class import Data.Aeson import Control.Monad.Trans.Resource (MonadResource) import qualified Network.HTTP.Conduit as HTTP #if MIN_VERSION_conduit(1,0,16) ($=+) :: MonadIO m => CI.ResumableSource m a -> CI.Conduit a m o -> m (CI.ResumableSource m o) ($=+) = (return .) . (C.$=+) #else rsrc $=+ cndt = do (src, finalizer) <- C.unwrapResumable rsrc return $ CI.ResumableSource (src C.$= cndt) finalizer #endif stream :: (MonadResource m, FromJSON responseType) => TWInfo -> HTTP.Manager -> APIRequest apiName responseType -> m (C.ResumableSource m responseType) stream = stream' stream' :: (MonadResource m, FromJSON value) => TWInfo -> HTTP.Manager -> APIRequest apiName responseType -> m (C.ResumableSource m value) stream' info mgr req = do rsrc <- getResponse info mgr =<< liftIO (makeRequest req) responseBody rsrc $=+ CL.sequence sinkFromJSON data Userstream userstream :: APIRequest Userstream StreamingAPI userstream = APIRequestGet "https://userstream.twitter.com/1.1/user.json" [] deriveHasParamInstances ''Userstream [ "language" , "filter_level" , "stall_warnings" , "replies" ] statusesFilterEndpoint :: String statusesFilterEndpoint = "https://stream.twitter.com/1.1/statuses/filter.json" data StatusesFilter statusesFilterByFollow :: [UserId] -> APIRequest StatusesFilter StreamingAPI statusesFilterByFollow userIds = APIRequestPost statusesFilterEndpoint [("follow", PVIntegerArray userIds)] statusesFilterByTrack :: T.Text -- ^ keyword -> APIRequest StatusesFilter StreamingAPI statusesFilterByTrack keyword = APIRequestPost statusesFilterEndpoint [("track", PVString keyword)] deriveHasParamInstances ''StatusesFilter [ "language" , "filter_level" , "stall_warnings" ]
johan--/twitter-conduit
Web/Twitter/Conduit/Stream.hs
bsd-2-clause
2,839
0
12
558
556
323
233
-1
-1
{- | Module : $Id$ Description : from a list of words create haskell constants Copyright : (c) Christian Maeder, DFKI Bremen 2008 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : experimental Portability : portable from a list of words (one each line) create haskell constants -} module Main where import Data.Char import qualified Data.Map as Map camelCase :: Bool -> String -> String camelCase up s = case s of "" -> "" c : r -> if elem c "_-" then camelCase True r else [(if up then toUpper else toLower) c | isAlphaNum c] ++ camelCase False r main :: IO () main = getContents >>= mapM_ (\ (k, v) -> putStrLn "" >> putStrLn (k ++ " :: String") >> putStrLn (k ++ " = \"" ++ v ++ "\"")) . Map.toList . Map.fromList . map (\ s -> (camelCase False s ++ "S", s)) . filter (not . null) . map (takeWhile $ \ c -> isAlpha c || elem c "-_?") . lines
keithodulaigh/Hets
utils/createKeywordDecls.hs
gpl-2.0
964
0
20
249
278
146
132
21
4
----------------------------------------------------------------------------- -- | -- Module : Control.Lens.Internal.CTypes -- Copyright : (C) 2012-2016 Edward Kmett, (C) 2017 Ryan Scott -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable -- -- In "Control.Lens.Wrapped", we need to muck around with the internals of the -- newtypes in "Foreign.C.Types". Unfortunately, the exact types used varies -- wildly from platform to platform, so trying to manage the imports necessary -- to bring these types in scope can be unwieldy. -- -- To make things easier, we use this module as a way to import everything -- carte blanche that might be used internally in "Foreign.C.Types". For -- now, this consists of all the exports from the "Data.Int" and "Data.Word" -- modules, as well as the 'Ptr' type. ---------------------------------------------------------------------------- module Control.Lens.Internal.CTypes ( module Data.Int , Ptr , module Data.Word ) where import Data.Int import Data.Word import Foreign.Ptr (Ptr)
ddssff/lens
src/Control/Lens/Internal/CTypes.hs
bsd-3-clause
1,145
0
5
184
64
48
16
7
0
-- | -- Module : $Header$ -- Copyright : (c) 2013-2015 Galois, Inc. -- License : BSD3 -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable module Cryptol.ModuleSystem ( -- * Module System ModuleEnv(..), initialModuleEnv , DynamicEnv(..) , ModuleError(..), ModuleWarning(..) , ModuleCmd, ModuleRes , findModule , loadModuleByPath , loadModule , checkExpr , evalExpr , checkDecls , evalDecls , noPat , focusedEnv -- * Interfaces , Iface(..), IfaceDecls(..), genIface , IfaceTySyn, IfaceDecl(..) ) where import qualified Cryptol.Eval.Value as E import Cryptol.ModuleSystem.Env import Cryptol.ModuleSystem.Interface import Cryptol.ModuleSystem.Monad import Cryptol.ModuleSystem.Renamer (Rename) import qualified Cryptol.ModuleSystem.Base as Base import qualified Cryptol.Parser.AST as P import Cryptol.Parser.NoPat (RemovePatterns) import Cryptol.Parser.Position (HasLoc) import qualified Cryptol.TypeCheck.AST as T import qualified Cryptol.TypeCheck.Depends as T -- Public Interface ------------------------------------------------------------ type ModuleCmd a = ModuleEnv -> IO (ModuleRes a) type ModuleRes a = (Either ModuleError (a,ModuleEnv), [ModuleWarning]) -- | Find the file associated with a module name in the module search path. findModule :: P.ModName -> ModuleCmd FilePath findModule n env = runModuleM env (Base.findModule n) -- | Load the module contained in the given file. loadModuleByPath :: FilePath -> ModuleCmd T.Module loadModuleByPath path env = runModuleM (resetModuleEnv env) $ do -- unload the module if it already exists unloadModule path m <- Base.loadModuleByPath path setFocusedModule (T.mName m) return m -- | Load the given parsed module. loadModule :: FilePath -> P.Module -> ModuleCmd T.Module loadModule path m env = runModuleM env $ do -- unload the module if it already exists unloadModule path let n = P.thing (P.mName m) m' <- loadingModule n (Base.loadModule path m) setFocusedModule (T.mName m') return m' -- Extended Environments ------------------------------------------------------- -- These functions are particularly useful for interactive modes, as -- they allow for expressions to be evaluated in an environment that -- can extend dynamically outside of the context of a module. -- | Check the type of an expression. Give back the renamed expression, the -- core expression, and its type schema. checkExpr :: P.Expr -> ModuleCmd (P.Expr,T.Expr,T.Schema) checkExpr e env = runModuleM env (interactive (Base.checkExpr e)) -- | Evaluate an expression. evalExpr :: T.Expr -> ModuleCmd E.Value evalExpr e env = runModuleM env (interactive (Base.evalExpr e)) -- | Typecheck declarations. checkDecls :: (HasLoc d, Rename d, T.FromDecl d) => [d] -> ModuleCmd [T.DeclGroup] checkDecls ds env = runModuleM env (interactive (Base.checkDecls ds)) -- | Evaluate declarations and add them to the extended environment. evalDecls :: [T.DeclGroup] -> ModuleCmd () evalDecls dgs env = runModuleM env (interactive (Base.evalDecls dgs)) noPat :: RemovePatterns a => a -> ModuleCmd a noPat a env = runModuleM env (interactive (Base.noPat a))
ntc2/cryptol
src/Cryptol/ModuleSystem.hs
bsd-3-clause
3,284
0
14
607
758
424
334
54
1
{- (c) The GRASP Project, Glasgow University, 1994-1998 \section[TysWiredIn]{Wired-in knowledge about {\em non-primitive} types} -} {-# LANGUAGE CPP #-} -- | This module is about types that can be defined in Haskell, but which -- must be wired into the compiler nonetheless. C.f module TysPrim module TysWiredIn ( -- * All wired in things wiredInTyCons, isBuiltInOcc_maybe, -- * Bool boolTy, boolTyCon, boolTyCon_RDR, boolTyConName, trueDataCon, trueDataConId, true_RDR, falseDataCon, falseDataConId, false_RDR, promotedBoolTyCon, promotedFalseDataCon, promotedTrueDataCon, -- * Ordering ltDataCon, ltDataConId, eqDataCon, eqDataConId, gtDataCon, gtDataConId, promotedOrderingTyCon, promotedLTDataCon, promotedEQDataCon, promotedGTDataCon, -- * Char charTyCon, charDataCon, charTyCon_RDR, charTy, stringTy, charTyConName, -- * Double doubleTyCon, doubleDataCon, doubleTy, doubleTyConName, -- * Float floatTyCon, floatDataCon, floatTy, floatTyConName, -- * Int intTyCon, intDataCon, intTyCon_RDR, intDataCon_RDR, intTyConName, intTy, -- * Word wordTyCon, wordDataCon, wordTyConName, wordTy, -- * Word8 word8TyCon, word8DataCon, word8TyConName, word8Ty, -- * List listTyCon, listTyCon_RDR, listTyConName, listTyConKey, nilDataCon, nilDataConName, nilDataConKey, consDataCon_RDR, consDataCon, consDataConName, mkListTy, mkPromotedListTy, -- * Maybe maybeTyCon, maybeTyConName, nothingDataCon, nothingDataConName, justDataCon, justDataConName, -- * Tuples mkTupleTy, mkBoxedTupleTy, tupleTyCon, tupleDataCon, tupleTyConName, promotedTupleTyCon, promotedTupleDataCon, unitTyCon, unitDataCon, unitDataConId, unitTy, unitTyConKey, pairTyCon, unboxedUnitTyCon, unboxedUnitDataCon, unboxedSingletonTyCon, unboxedSingletonDataCon, unboxedPairTyCon, unboxedPairDataCon, cTupleTyConName, cTupleTyConNames, isCTupleTyConName, -- * Kinds typeNatKindCon, typeNatKind, typeSymbolKindCon, typeSymbolKind, -- * Parallel arrays mkPArrTy, parrTyCon, parrFakeCon, isPArrTyCon, isPArrFakeCon, parrTyCon_RDR, parrTyConName, -- * Equality predicates eqTyCon_RDR, eqTyCon, eqTyConName, eqBoxDataCon, coercibleTyCon, coercibleDataCon, coercibleClass, -- * Implicit Parameters ipTyCon, ipDataCon, ipClass, callStackTyCon, mkWiredInTyConName -- This is used in TcTypeNats to define the -- built-in functions for evaluation. ) where #include "HsVersions.h" import {-# SOURCE #-} MkId( mkDataConWorkId ) -- friends: import PrelNames import TysPrim -- others: import CoAxiom import Coercion import Id import Constants ( mAX_TUPLE_SIZE, mAX_CTUPLE_SIZE ) import Module ( Module ) import Type ( mkTyConApp ) import DataCon import {-# SOURCE #-} ConLike import Var import TyCon import Class ( Class, mkClass ) import TypeRep import RdrName import Name import NameSet ( NameSet, mkNameSet, elemNameSet ) import BasicTypes ( Arity, RecFlag(..), Boxity(..), TupleSort(..) ) import ForeignCall import SrcLoc ( noSrcSpan ) import Unique import Data.Array import FastString import Outputable import Util import BooleanFormula ( mkAnd ) alpha_tyvar :: [TyVar] alpha_tyvar = [alphaTyVar] alpha_ty :: [Type] alpha_ty = [alphaTy] {- ************************************************************************ * * \subsection{Wired in type constructors} * * ************************************************************************ If you change which things are wired in, make sure you change their names in PrelNames, so they use wTcQual, wDataQual, etc -} -- This list is used only to define PrelInfo.wiredInThings. That in turn -- is used to initialise the name environment carried around by the renamer. -- This means that if we look up the name of a TyCon (or its implicit binders) -- that occurs in this list that name will be assigned the wired-in key we -- define here. -- -- Because of their infinite nature, this list excludes tuples, Any and implicit -- parameter TyCons. Instead, we have a hack in lookupOrigNameCache to deal with -- these names. -- -- See also Note [Known-key names] wiredInTyCons :: [TyCon] wiredInTyCons = [ unitTyCon -- Not treated like other tuples, because -- it's defined in GHC.Base, and there's only -- one of it. We put it in wiredInTyCons so -- that it'll pre-populate the name cache, so -- the special case in lookupOrigNameCache -- doesn't need to look out for it , boolTyCon , charTyCon , doubleTyCon , floatTyCon , intTyCon , wordTyCon , word8TyCon , listTyCon , maybeTyCon , parrTyCon , eqTyCon , coercibleTyCon , typeNatKindCon , typeSymbolKindCon , ipTyCon ] mkWiredInTyConName :: BuiltInSyntax -> Module -> FastString -> Unique -> TyCon -> Name mkWiredInTyConName built_in modu fs unique tycon = mkWiredInName modu (mkTcOccFS fs) unique (ATyCon tycon) -- Relevant TyCon built_in mkWiredInDataConName :: BuiltInSyntax -> Module -> FastString -> Unique -> DataCon -> Name mkWiredInDataConName built_in modu fs unique datacon = mkWiredInName modu (mkDataOccFS fs) unique (AConLike (RealDataCon datacon)) -- Relevant DataCon built_in mkWiredInCoAxiomName :: BuiltInSyntax -> Module -> FastString -> Unique -> CoAxiom Branched -> Name mkWiredInCoAxiomName built_in modu fs unique ax = mkWiredInName modu (mkTcOccFS fs) unique (ACoAxiom ax) -- Relevant CoAxiom built_in -- See Note [Kind-changing of (~) and Coercible] eqTyConName, eqBoxDataConName :: Name eqTyConName = mkWiredInTyConName BuiltInSyntax gHC_TYPES (fsLit "~") eqTyConKey eqTyCon eqBoxDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "Eq#") eqBoxDataConKey eqBoxDataCon -- See Note [Kind-changing of (~) and Coercible] coercibleTyConName, coercibleDataConName :: Name coercibleTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Coercible") coercibleTyConKey coercibleTyCon coercibleDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "MkCoercible") coercibleDataConKey coercibleDataCon charTyConName, charDataConName, intTyConName, intDataConName :: Name charTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Char") charTyConKey charTyCon charDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "C#") charDataConKey charDataCon intTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Int") intTyConKey intTyCon intDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "I#") intDataConKey intDataCon boolTyConName, falseDataConName, trueDataConName :: Name boolTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Bool") boolTyConKey boolTyCon falseDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "False") falseDataConKey falseDataCon trueDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "True") trueDataConKey trueDataCon listTyConName, nilDataConName, consDataConName :: Name listTyConName = mkWiredInTyConName BuiltInSyntax gHC_TYPES (fsLit "[]") listTyConKey listTyCon nilDataConName = mkWiredInDataConName BuiltInSyntax gHC_TYPES (fsLit "[]") nilDataConKey nilDataCon consDataConName = mkWiredInDataConName BuiltInSyntax gHC_TYPES (fsLit ":") consDataConKey consDataCon maybeTyConName, nothingDataConName, justDataConName :: Name maybeTyConName = mkWiredInTyConName UserSyntax gHC_BASE (fsLit "Maybe") maybeTyConKey maybeTyCon nothingDataConName = mkWiredInDataConName UserSyntax gHC_BASE (fsLit "Nothing") nothingDataConKey nothingDataCon justDataConName = mkWiredInDataConName UserSyntax gHC_BASE (fsLit "Just") justDataConKey justDataCon wordTyConName, wordDataConName, word8TyConName, word8DataConName :: Name wordTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Word") wordTyConKey wordTyCon wordDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "W#") wordDataConKey wordDataCon word8TyConName = mkWiredInTyConName UserSyntax gHC_WORD (fsLit "Word8") word8TyConKey word8TyCon word8DataConName = mkWiredInDataConName UserSyntax gHC_WORD (fsLit "W8#") word8DataConKey word8DataCon floatTyConName, floatDataConName, doubleTyConName, doubleDataConName :: Name floatTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Float") floatTyConKey floatTyCon floatDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "F#") floatDataConKey floatDataCon doubleTyConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Double") doubleTyConKey doubleTyCon doubleDataConName = mkWiredInDataConName UserSyntax gHC_TYPES (fsLit "D#") doubleDataConKey doubleDataCon -- Kinds typeNatKindConName, typeSymbolKindConName :: Name typeNatKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Nat") typeNatKindConNameKey typeNatKindCon typeSymbolKindConName = mkWiredInTyConName UserSyntax gHC_TYPES (fsLit "Symbol") typeSymbolKindConNameKey typeSymbolKindCon parrTyConName, parrDataConName :: Name parrTyConName = mkWiredInTyConName BuiltInSyntax gHC_PARR' (fsLit "[::]") parrTyConKey parrTyCon parrDataConName = mkWiredInDataConName UserSyntax gHC_PARR' (fsLit "PArr") parrDataConKey parrDataCon boolTyCon_RDR, false_RDR, true_RDR, intTyCon_RDR, charTyCon_RDR, intDataCon_RDR, listTyCon_RDR, consDataCon_RDR, parrTyCon_RDR, eqTyCon_RDR :: RdrName boolTyCon_RDR = nameRdrName boolTyConName false_RDR = nameRdrName falseDataConName true_RDR = nameRdrName trueDataConName intTyCon_RDR = nameRdrName intTyConName charTyCon_RDR = nameRdrName charTyConName intDataCon_RDR = nameRdrName intDataConName listTyCon_RDR = nameRdrName listTyConName consDataCon_RDR = nameRdrName consDataConName parrTyCon_RDR = nameRdrName parrTyConName eqTyCon_RDR = nameRdrName eqTyConName {- ************************************************************************ * * \subsection{mkWiredInTyCon} * * ************************************************************************ -} pcNonRecDataTyCon :: Name -> Maybe CType -> [TyVar] -> [DataCon] -> TyCon -- Not an enumeration, not promotable pcNonRecDataTyCon = pcTyCon False NonRecursive False -- This function assumes that the types it creates have all parameters at -- Representational role! pcTyCon :: Bool -> RecFlag -> Bool -> Name -> Maybe CType -> [TyVar] -> [DataCon] -> TyCon pcTyCon is_enum is_rec is_prom name cType tyvars cons = buildAlgTyCon name tyvars (map (const Representational) tyvars) cType [] -- No stupid theta (DataTyCon cons is_enum) is_rec is_prom False -- Not in GADT syntax (VanillaAlgTyCon (mkPrelTyConRepName name)) pcDataCon :: Name -> [TyVar] -> [Type] -> TyCon -> DataCon pcDataCon = pcDataConWithFixity False pcDataConWithFixity :: Bool -> Name -> [TyVar] -> [Type] -> TyCon -> DataCon pcDataConWithFixity infx n = pcDataConWithFixity' infx n (incrUnique (nameUnique n)) -- The Name's unique is the first of two free uniques; -- the first is used for the datacon itself, -- the second is used for the "worker name" -- -- To support this the mkPreludeDataConUnique function "allocates" -- one DataCon unique per pair of Ints. pcDataConWithFixity' :: Bool -> Name -> Unique -> [TyVar] -> [Type] -> TyCon -> DataCon -- The Name should be in the DataName name space; it's the name -- of the DataCon itself. pcDataConWithFixity' declared_infix dc_name wrk_key tyvars arg_tys tycon = data_con where data_con = mkDataCon dc_name declared_infix prom_info (map (const no_bang) arg_tys) [] -- No labelled fields tyvars [] -- No existential type variables [] -- No equality spec [] -- No theta arg_tys (mkTyConApp tycon (mkTyVarTys tyvars)) tycon [] -- No stupid theta (mkDataConWorkId wrk_name data_con) NoDataConRep -- Wired-in types are too simple to need wrappers no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict modu = ASSERT( isExternalName dc_name ) nameModule dc_name dc_occ = nameOccName dc_name wrk_occ = mkDataConWorkerOcc dc_occ wrk_name = mkWiredInName modu wrk_occ wrk_key (AnId (dataConWorkId data_con)) UserSyntax prom_info | Promoted {} <- promotableTyCon_maybe tycon -- Knot-tied = Promoted (mkPrelTyConRepName dc_name) | otherwise = NotPromoted {- ************************************************************************ * * Kinds * * ************************************************************************ -} typeNatKindCon, typeSymbolKindCon :: TyCon -- data Nat -- data Symbol typeNatKindCon = pcTyCon False NonRecursive True typeNatKindConName Nothing [] [] typeSymbolKindCon = pcTyCon False NonRecursive True typeSymbolKindConName Nothing [] [] typeNatKind, typeSymbolKind :: Kind typeNatKind = TyConApp (promoteTyCon typeNatKindCon) [] typeSymbolKind = TyConApp (promoteTyCon typeSymbolKindCon) [] {- ************************************************************************ * * Stuff for dealing with tuples * * ************************************************************************ Note [How tuples work] See also Note [Known-key names] in PrelNames ~~~~~~~~~~~~~~~~~~~~~~ * There are three families of tuple TyCons and corresponding DataCons, expressed by the type BasicTypes.TupleSort: data TupleSort = BoxedTuple | UnboxedTuple | ConstraintTuple * All three families are AlgTyCons, whose AlgTyConRhs is TupleTyCon * BoxedTuples - A wired-in type - Data type declarations in GHC.Tuple - The data constructors really have an info table * UnboxedTuples - A wired-in type - Have a pretend DataCon, defined in GHC.Prim, but no actual declaration and no info table * ConstraintTuples - Are known-key rather than wired-in. Reason: it's awkward to have all the superclass selectors wired-in. - Declared as classes in GHC.Classes, e.g. class (c1,c2) => (c1,c2) - Given constraints: the superclasses automatically become available - Wanted constraints: there is a built-in instance instance (c1,c2) => (c1,c2) - Currently just go up to 16; beyond that you have to use manual nesting - Their OccNames look like (%,,,%), so they can easily be distinguished from term tuples. But (following Haskell) we pretty-print saturated constraint tuples with round parens; see BasicTypes.tupleParens. * In quite a lot of places things are restrcted just to BoxedTuple/UnboxedTuple, and then we used BasicTypes.Boxity to distinguish E.g. tupleTyCon has a Boxity argument * When looking up an OccName in the original-name cache (IfaceEnv.lookupOrigNameCache), we spot the tuple OccName to make sure we get the right wired-in name. This guy can't tell the difference betweeen BoxedTuple and ConstraintTuple (same OccName!), so tuples are not serialised into interface files using OccNames at all. -} isBuiltInOcc_maybe :: OccName -> Maybe Name -- Built in syntax isn't "in scope" so these OccNames -- map to wired-in Names with BuiltInSyntax isBuiltInOcc_maybe occ = case occNameString occ of "[]" -> choose_ns listTyConName nilDataConName ":" -> Just consDataConName "[::]" -> Just parrTyConName "()" -> tup_name Boxed 0 "(##)" -> tup_name Unboxed 0 '(':',':rest -> parse_tuple Boxed 2 rest '(':'#':',':rest -> parse_tuple Unboxed 2 rest _other -> Nothing where ns = occNameSpace occ parse_tuple sort n rest | (',' : rest2) <- rest = parse_tuple sort (n+1) rest2 | tail_matches sort rest = tup_name sort n | otherwise = Nothing tail_matches Boxed ")" = True tail_matches Unboxed "#)" = True tail_matches _ _ = False tup_name boxity arity = choose_ns (getName (tupleTyCon boxity arity)) (getName (tupleDataCon boxity arity)) choose_ns tc dc | isTcClsNameSpace ns = Just tc | isDataConNameSpace ns = Just dc | otherwise = pprPanic "tup_name" (ppr occ) mkTupleOcc :: NameSpace -> Boxity -> Arity -> OccName mkTupleOcc ns sort ar = mkOccName ns str where -- No need to cache these, the caching is done in mk_tuple str = case sort of Unboxed -> '(' : '#' : commas ++ "#)" Boxed -> '(' : commas ++ ")" commas = take (ar-1) (repeat ',') mkCTupleOcc :: NameSpace -> Arity -> OccName mkCTupleOcc ns ar = mkOccName ns str where str = "(%" ++ commas ++ "%)" commas = take (ar-1) (repeat ',') cTupleTyConName :: Arity -> Name cTupleTyConName arity = mkExternalName (mkCTupleTyConUnique arity) gHC_CLASSES (mkCTupleOcc tcName arity) noSrcSpan -- The corresponding DataCon does not have a known-key name cTupleTyConNames :: [Name] cTupleTyConNames = map cTupleTyConName (0 : [2..mAX_CTUPLE_SIZE]) cTupleTyConNameSet :: NameSet cTupleTyConNameSet = mkNameSet cTupleTyConNames isCTupleTyConName :: Name -> Bool isCTupleTyConName n = ASSERT2( isExternalName n, ppr n ) nameModule n == gHC_CLASSES && n `elemNameSet` cTupleTyConNameSet tupleTyCon :: Boxity -> Arity -> TyCon tupleTyCon sort i | i > mAX_TUPLE_SIZE = fst (mk_tuple sort i) -- Build one specially tupleTyCon Boxed i = fst (boxedTupleArr ! i) tupleTyCon Unboxed i = fst (unboxedTupleArr ! i) tupleTyConName :: TupleSort -> Arity -> Name tupleTyConName ConstraintTuple a = cTupleTyConName a tupleTyConName BoxedTuple a = tyConName (tupleTyCon Boxed a) tupleTyConName UnboxedTuple a = tyConName (tupleTyCon Unboxed a) promotedTupleTyCon :: Boxity -> Arity -> TyCon promotedTupleTyCon boxity i = promoteTyCon (tupleTyCon boxity i) promotedTupleDataCon :: Boxity -> Arity -> TyCon promotedTupleDataCon boxity i = promoteDataCon (tupleDataCon boxity i) tupleDataCon :: Boxity -> Arity -> DataCon tupleDataCon sort i | i > mAX_TUPLE_SIZE = snd (mk_tuple sort i) -- Build one specially tupleDataCon Boxed i = snd (boxedTupleArr ! i) tupleDataCon Unboxed i = snd (unboxedTupleArr ! i) boxedTupleArr, unboxedTupleArr :: Array Int (TyCon,DataCon) boxedTupleArr = listArray (0,mAX_TUPLE_SIZE) [mk_tuple Boxed i | i <- [0..mAX_TUPLE_SIZE]] unboxedTupleArr = listArray (0,mAX_TUPLE_SIZE) [mk_tuple Unboxed i | i <- [0..mAX_TUPLE_SIZE]] mk_tuple :: Boxity -> Int -> (TyCon,DataCon) mk_tuple boxity arity = (tycon, tuple_con) where tycon = mkTupleTyCon tc_name tc_kind arity tyvars tuple_con tup_sort prom_tc flavour flavour = case boxity of Boxed -> VanillaAlgTyCon (mkPrelTyConRepName tc_name) Unboxed -> UnboxedAlgTyCon tup_sort = case boxity of Boxed -> BoxedTuple Unboxed -> UnboxedTuple prom_tc = case boxity of Boxed -> Promoted (mkPromotedTyCon tycon (promoteKind tc_kind)) Unboxed -> NotPromoted modu = case boxity of Boxed -> gHC_TUPLE Unboxed -> gHC_PRIM tc_name = mkWiredInName modu (mkTupleOcc tcName boxity arity) tc_uniq (ATyCon tycon) BuiltInSyntax tc_kind = mkArrowKinds (map tyVarKind tyvars) res_kind res_kind = case boxity of Boxed -> liftedTypeKind Unboxed -> unliftedTypeKind tyvars = take arity $ case boxity of Boxed -> alphaTyVars Unboxed -> openAlphaTyVars tuple_con = pcDataCon dc_name tyvars tyvar_tys tycon tyvar_tys = mkTyVarTys tyvars dc_name = mkWiredInName modu (mkTupleOcc dataName boxity arity) dc_uniq (AConLike (RealDataCon tuple_con)) BuiltInSyntax tc_uniq = mkTupleTyConUnique boxity arity dc_uniq = mkTupleDataConUnique boxity arity unitTyCon :: TyCon unitTyCon = tupleTyCon Boxed 0 unitTyConKey :: Unique unitTyConKey = getUnique unitTyCon unitDataCon :: DataCon unitDataCon = head (tyConDataCons unitTyCon) unitDataConId :: Id unitDataConId = dataConWorkId unitDataCon pairTyCon :: TyCon pairTyCon = tupleTyCon Boxed 2 unboxedUnitTyCon :: TyCon unboxedUnitTyCon = tupleTyCon Unboxed 0 unboxedUnitDataCon :: DataCon unboxedUnitDataCon = tupleDataCon Unboxed 0 unboxedSingletonTyCon :: TyCon unboxedSingletonTyCon = tupleTyCon Unboxed 1 unboxedSingletonDataCon :: DataCon unboxedSingletonDataCon = tupleDataCon Unboxed 1 unboxedPairTyCon :: TyCon unboxedPairTyCon = tupleTyCon Unboxed 2 unboxedPairDataCon :: DataCon unboxedPairDataCon = tupleDataCon Unboxed 2 {- ************************************************************************ * * The ``boxed primitive'' types (@Char@, @Int@, etc) * * ************************************************************************ -} charTy :: Type charTy = mkTyConTy charTyCon charTyCon :: TyCon charTyCon = pcNonRecDataTyCon charTyConName (Just (CType "" Nothing ("HsChar",fsLit "HsChar"))) [] [charDataCon] charDataCon :: DataCon charDataCon = pcDataCon charDataConName [] [charPrimTy] charTyCon stringTy :: Type stringTy = mkListTy charTy -- convenience only intTy :: Type intTy = mkTyConTy intTyCon intTyCon :: TyCon intTyCon = pcNonRecDataTyCon intTyConName (Just (CType "" Nothing ("HsInt",fsLit "HsInt"))) [] [intDataCon] intDataCon :: DataCon intDataCon = pcDataCon intDataConName [] [intPrimTy] intTyCon wordTy :: Type wordTy = mkTyConTy wordTyCon wordTyCon :: TyCon wordTyCon = pcNonRecDataTyCon wordTyConName (Just (CType "" Nothing ("HsWord", fsLit "HsWord"))) [] [wordDataCon] wordDataCon :: DataCon wordDataCon = pcDataCon wordDataConName [] [wordPrimTy] wordTyCon word8Ty :: Type word8Ty = mkTyConTy word8TyCon word8TyCon :: TyCon word8TyCon = pcNonRecDataTyCon word8TyConName (Just (CType "" Nothing ("HsWord8", fsLit "HsWord8"))) [] [word8DataCon] word8DataCon :: DataCon word8DataCon = pcDataCon word8DataConName [] [wordPrimTy] word8TyCon floatTy :: Type floatTy = mkTyConTy floatTyCon floatTyCon :: TyCon floatTyCon = pcNonRecDataTyCon floatTyConName (Just (CType "" Nothing ("HsFloat", fsLit "HsFloat"))) [] [floatDataCon] floatDataCon :: DataCon floatDataCon = pcDataCon floatDataConName [] [floatPrimTy] floatTyCon doubleTy :: Type doubleTy = mkTyConTy doubleTyCon doubleTyCon :: TyCon doubleTyCon = pcNonRecDataTyCon doubleTyConName (Just (CType "" Nothing ("HsDouble",fsLit "HsDouble"))) [] [doubleDataCon] doubleDataCon :: DataCon doubleDataCon = pcDataCon doubleDataConName [] [doublePrimTy] doubleTyCon {- ************************************************************************ * * The Bool type * * ************************************************************************ An ordinary enumeration type, but deeply wired in. There are no magical operations on @Bool@ (just the regular Prelude code). {\em BEGIN IDLE SPECULATION BY SIMON} This is not the only way to encode @Bool@. A more obvious coding makes @Bool@ just a boxed up version of @Bool#@, like this: \begin{verbatim} type Bool# = Int# data Bool = MkBool Bool# \end{verbatim} Unfortunately, this doesn't correspond to what the Report says @Bool@ looks like! Furthermore, we get slightly less efficient code (I think) with this coding. @gtInt@ would look like this: \begin{verbatim} gtInt :: Int -> Int -> Bool gtInt x y = case x of I# x# -> case y of I# y# -> case (gtIntPrim x# y#) of b# -> MkBool b# \end{verbatim} Notice that the result of the @gtIntPrim@ comparison has to be turned into an integer (here called @b#@), and returned in a @MkBool@ box. The @if@ expression would compile to this: \begin{verbatim} case (gtInt x y) of MkBool b# -> case b# of { 1# -> e1; 0# -> e2 } \end{verbatim} I think this code is a little less efficient than the previous code, but I'm not certain. At all events, corresponding with the Report is important. The interesting thing is that the language is expressive enough to describe more than one alternative; and that a type doesn't necessarily need to be a straightforwardly boxed version of its primitive counterpart. {\em END IDLE SPECULATION BY SIMON} -} boolTy :: Type boolTy = mkTyConTy boolTyCon boolTyCon :: TyCon boolTyCon = pcTyCon True NonRecursive True boolTyConName (Just (CType "" Nothing ("HsBool", fsLit "HsBool"))) [] [falseDataCon, trueDataCon] falseDataCon, trueDataCon :: DataCon falseDataCon = pcDataCon falseDataConName [] [] boolTyCon trueDataCon = pcDataCon trueDataConName [] [] boolTyCon falseDataConId, trueDataConId :: Id falseDataConId = dataConWorkId falseDataCon trueDataConId = dataConWorkId trueDataCon orderingTyCon :: TyCon orderingTyCon = pcTyCon True NonRecursive True orderingTyConName Nothing [] [ltDataCon, eqDataCon, gtDataCon] ltDataCon, eqDataCon, gtDataCon :: DataCon ltDataCon = pcDataCon ltDataConName [] [] orderingTyCon eqDataCon = pcDataCon eqDataConName [] [] orderingTyCon gtDataCon = pcDataCon gtDataConName [] [] orderingTyCon ltDataConId, eqDataConId, gtDataConId :: Id ltDataConId = dataConWorkId ltDataCon eqDataConId = dataConWorkId eqDataCon gtDataConId = dataConWorkId gtDataCon {- ************************************************************************ * * The List type Special syntax, deeply wired in, but otherwise an ordinary algebraic data type * * ************************************************************************ data [] a = [] | a : (List a) -} mkListTy :: Type -> Type mkListTy ty = mkTyConApp listTyCon [ty] listTyCon :: TyCon listTyCon = buildAlgTyCon listTyConName alpha_tyvar [Representational] Nothing [] (DataTyCon [nilDataCon, consDataCon] False ) Recursive True False (VanillaAlgTyCon (mkSpecialTyConRepName (fsLit "tcList") listTyConName)) mkPromotedListTy :: Type -> Type mkPromotedListTy ty = mkTyConApp promotedListTyCon [ty] promotedListTyCon :: TyCon promotedListTyCon = promoteTyCon listTyCon nilDataCon :: DataCon nilDataCon = pcDataCon nilDataConName alpha_tyvar [] listTyCon consDataCon :: DataCon consDataCon = pcDataConWithFixity True {- Declared infix -} consDataConName alpha_tyvar [alphaTy, mkTyConApp listTyCon alpha_ty] listTyCon -- Interesting: polymorphic recursion would help here. -- We can't use (mkListTy alphaTy) in the defn of consDataCon, else mkListTy -- gets the over-specific type (Type -> Type) -- Wired-in type Maybe maybeTyCon :: TyCon maybeTyCon = pcTyCon True NonRecursive True maybeTyConName Nothing alpha_tyvar [nothingDataCon, justDataCon] nothingDataCon :: DataCon nothingDataCon = pcDataCon nothingDataConName alpha_tyvar [] maybeTyCon justDataCon :: DataCon justDataCon = pcDataCon justDataConName alpha_tyvar [alphaTy] maybeTyCon {- ** ********************************************************************* * * The tuple types * * ************************************************************************ The tuple types are definitely magic, because they form an infinite family. \begin{itemize} \item They have a special family of type constructors, of type @TyCon@ These contain the tycon arity, but don't require a Unique. \item They have a special family of constructors, of type @Id@. Again these contain their arity but don't need a Unique. \item There should be a magic way of generating the info tables and entry code for all tuples. But at the moment we just compile a Haskell source file\srcloc{lib/prelude/...} containing declarations like: \begin{verbatim} data Tuple0 = Tup0 data Tuple2 a b = Tup2 a b data Tuple3 a b c = Tup3 a b c data Tuple4 a b c d = Tup4 a b c d ... \end{verbatim} The print-names associated with the magic @Id@s for tuple constructors ``just happen'' to be the same as those generated by these declarations. \item The instance environment should have a magic way to know that each tuple type is an instances of classes @Eq@, @Ix@, @Ord@ and so on. \ToDo{Not implemented yet.} \item There should also be a way to generate the appropriate code for each of these instances, but (like the info tables and entry code) it is done by enumeration\srcloc{lib/prelude/InTup?.hs}. \end{itemize} -} mkTupleTy :: Boxity -> [Type] -> Type -- Special case for *boxed* 1-tuples, which are represented by the type itself mkTupleTy Boxed [ty] = ty mkTupleTy boxity tys = mkTyConApp (tupleTyCon boxity (length tys)) tys -- | Build the type of a small tuple that holds the specified type of thing mkBoxedTupleTy :: [Type] -> Type mkBoxedTupleTy tys = mkTupleTy Boxed tys unitTy :: Type unitTy = mkTupleTy Boxed [] {- ********************************************************************* * * The parallel-array type, [::] * * ************************************************************************ Special syntax for parallel arrays needs some wired in definitions. -} -- | Construct a type representing the application of the parallel array constructor mkPArrTy :: Type -> Type mkPArrTy ty = mkTyConApp parrTyCon [ty] -- | Represents the type constructor of parallel arrays -- -- * This must match the definition in @PrelPArr@ -- -- NB: Although the constructor is given here, it will not be accessible in -- user code as it is not in the environment of any compiled module except -- @PrelPArr@. -- parrTyCon :: TyCon parrTyCon = pcNonRecDataTyCon parrTyConName Nothing alpha_tyvar [parrDataCon] parrDataCon :: DataCon parrDataCon = pcDataCon parrDataConName alpha_tyvar -- forall'ed type variables [intTy, -- 1st argument: Int mkTyConApp -- 2nd argument: Array# a arrayPrimTyCon alpha_ty] parrTyCon -- | Check whether a type constructor is the constructor for parallel arrays isPArrTyCon :: TyCon -> Bool isPArrTyCon tc = tyConName tc == parrTyConName -- | Fake array constructors -- -- * These constructors are never really used to represent array values; -- however, they are very convenient during desugaring (and, in particular, -- in the pattern matching compiler) to treat array pattern just like -- yet another constructor pattern -- parrFakeCon :: Arity -> DataCon parrFakeCon i | i > mAX_TUPLE_SIZE = mkPArrFakeCon i -- build one specially parrFakeCon i = parrFakeConArr!i -- pre-defined set of constructors -- parrFakeConArr :: Array Int DataCon parrFakeConArr = array (0, mAX_TUPLE_SIZE) [(i, mkPArrFakeCon i) | i <- [0..mAX_TUPLE_SIZE]] -- build a fake parallel array constructor for the given arity -- mkPArrFakeCon :: Int -> DataCon mkPArrFakeCon arity = data_con where data_con = pcDataCon name [tyvar] tyvarTys parrTyCon tyvar = head alphaTyVars tyvarTys = replicate arity $ mkTyVarTy tyvar nameStr = mkFastString ("MkPArr" ++ show arity) name = mkWiredInName gHC_PARR' (mkDataOccFS nameStr) unique (AConLike (RealDataCon data_con)) UserSyntax unique = mkPArrDataConUnique arity -- | Checks whether a data constructor is a fake constructor for parallel arrays isPArrFakeCon :: DataCon -> Bool isPArrFakeCon dcon = dcon == parrFakeCon (dataConSourceArity dcon) -- Promoted Booleans promotedBoolTyCon, promotedFalseDataCon, promotedTrueDataCon :: TyCon promotedBoolTyCon = promoteTyCon boolTyCon promotedTrueDataCon = promoteDataCon trueDataCon promotedFalseDataCon = promoteDataCon falseDataCon -- Promoted Ordering promotedOrderingTyCon , promotedLTDataCon , promotedEQDataCon , promotedGTDataCon :: TyCon promotedOrderingTyCon = promoteTyCon orderingTyCon promotedLTDataCon = promoteDataCon ltDataCon promotedEQDataCon = promoteDataCon eqDataCon promotedGTDataCon = promoteDataCon gtDataCon {- ********************************************************************* * * Type equalities * * ********************************************************************* -} eqTyCon :: TyCon eqTyCon = mkAlgTyCon eqTyConName (ForAllTy kv $ mkArrowKinds [k, k] constraintKind) [kv, a, b] [Nominal, Nominal, Nominal] Nothing [] -- No stupid theta (DataTyCon [eqBoxDataCon] False) (VanillaAlgTyCon (mkSpecialTyConRepName (fsLit "tcEq") eqTyConName)) NonRecursive False NotPromoted where kv = kKiVar k = mkTyVarTy kv [a,b] = mkTemplateTyVars [k,k] eqBoxDataCon :: DataCon eqBoxDataCon = pcDataCon eqBoxDataConName args [TyConApp eqPrimTyCon (map mkTyVarTy args)] eqTyCon where kv = kKiVar k = mkTyVarTy kv [a,b] = mkTemplateTyVars [k,k] args = [kv, a, b] coercibleTyCon :: TyCon coercibleTyCon = mkClassTyCon coercibleTyConName kind tvs [Nominal, Representational, Representational] rhs coercibleClass NonRecursive (mkPrelTyConRepName coercibleTyConName) where kind = (ForAllTy kv $ mkArrowKinds [k, k] constraintKind) kv = kKiVar k = mkTyVarTy kv [a,b] = mkTemplateTyVars [k,k] tvs = [kv, a, b] rhs = DataTyCon [coercibleDataCon] False coercibleDataCon :: DataCon coercibleDataCon = pcDataCon coercibleDataConName args [TyConApp eqReprPrimTyCon (map mkTyVarTy args)] coercibleTyCon where kv = kKiVar k = mkTyVarTy kv [a,b] = mkTemplateTyVars [k,k] args = [kv, a, b] coercibleClass :: Class coercibleClass = mkClass (tyConTyVars coercibleTyCon) [] [] [] [] [] (mkAnd []) coercibleTyCon {- Note [The Implicit Parameter class] Implicit parameters `?x :: a` are desugared into dictionaries for the class `IP "x" a`, which is defined (in GHC.Classes) as class IP (x :: Symbol) a | x -> a This class is wired-in so that `error` and `undefined`, which have wired-in types, can use the implicit-call-stack feature to provide a call-stack alongside the error message. -} ipDataConName, ipTyConName, ipCoName :: Name ipDataConName = mkWiredInDataConName UserSyntax gHC_CLASSES (fsLit "IP") ipDataConKey ipDataCon ipTyConName = mkWiredInTyConName UserSyntax gHC_CLASSES (fsLit "IP") ipTyConKey ipTyCon ipCoName = mkWiredInCoAxiomName BuiltInSyntax gHC_CLASSES (fsLit "NTCo:IP") ipCoNameKey (toBranchedAxiom ipCoAxiom) -- See Note [The Implicit Parameter class] ipTyCon :: TyCon ipTyCon = mkClassTyCon ipTyConName kind [ip,a] [] rhs ipClass NonRecursive (mkPrelTyConRepName ipTyConName) where kind = mkArrowKinds [typeSymbolKind, liftedTypeKind] constraintKind [ip,a] = mkTemplateTyVars [typeSymbolKind, liftedTypeKind] rhs = NewTyCon ipDataCon (mkTyVarTy a) ([], mkTyVarTy a) ipCoAxiom ipCoAxiom :: CoAxiom Unbranched ipCoAxiom = mkNewTypeCo ipCoName ipTyCon [ip,a] [Nominal, Nominal] (mkTyVarTy a) where [ip,a] = mkTemplateTyVars [typeSymbolKind, liftedTypeKind] ipDataCon :: DataCon ipDataCon = pcDataCon ipDataConName [ip,a] ts ipTyCon where [ip,a] = mkTemplateTyVars [typeSymbolKind, liftedTypeKind] ts = [mkTyVarTy a] ipClass :: Class ipClass = mkClass (tyConTyVars ipTyCon) [([ip], [a])] [] [] [] [] (mkAnd []) ipTyCon where [ip, a] = tyConTyVars ipTyCon -- this is a fake version of the CallStack TyCon so we can refer to it -- in MkCore.errorTy callStackTyCon :: TyCon callStackTyCon = pcNonRecDataTyCon callStackTyConName Nothing [] []
AlexanderPankiv/ghc
compiler/prelude/TysWiredIn.hs
bsd-3-clause
39,069
0
14
10,358
6,411
3,505
2,906
553
10
<?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="hr-HR"> <title>TreeTools</title> <maps> <homeID>treetools</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>
kingthorin/zap-extensions
addOns/treetools/src/main/javahelp/help_hr_HR/helpset_hr_HR.hs
apache-2.0
960
77
66
155
404
205
199
-1
-1
module RmOneParameter.D1 where {-remove parameter 'ys' from function 'sumSquares'. This refactoring affects module 'D1', and 'A1'-} sumSquares (x:xs) = sq x + sumSquares xs sumSquares [] = 0 sq x = x ^ pow pow =2
RefactoringTools/HaRe
test/testdata/RmOneParameter/D1.expected.hs
bsd-3-clause
221
0
7
44
59
31
28
5
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module DefinedNames(module DefinedNames,module TypedIds) where import TypedIds import HsIdent --import Maybe(mapMaybe) import Recursive {-+ This modules defines a class for extensible extraction of names defined by declaration(s). Since the abstract syntax uses the same type for top level declarations and the body of class definitions, we need a separate function to extract the methods of a class. -} type TypedIdent i = (HsIdentI i,IdTy i) class DefinedNames i def | def->i where definedNames :: def -> [TypedIdent i] class ClassMethods i def | def->i where classMethods :: i -> Int -> def -> [TypedIdent i] class ContextSize c where contextSize :: c -> Int {-+ Some declarations have no explicit name in the concrete syntax, but can be assigned an automatically generated name. -} class AddName i d | d->i where addName :: d -> d; addName=id {-+ Default methods are part of class declarations in the Haskell syntax, but after type checking we treat them as separate top-level entities with their own names, so we need to be able to change their names... -} class MapDefinedNames i def | def->i where mapDefinedNames :: (i->i) -> def->def {-+ Instances for collecting defined names from lists and pairs of things: -} instance DefinedNames i d => DefinedNames i [d] where definedNames = concatMap definedNames instance ClassMethods i d => ClassMethods i [d] where classMethods c cnt = concatMap (classMethods c cnt) instance AddName i d => AddName i [d] where addName = map addName instance MapDefinedNames i d => MapDefinedNames i [d] where mapDefinedNames = map . mapDefinedNames instance (DefinedNames i a, DefinedNames i b) => DefinedNames i (a,b) where definedNames (x,y) = definedNames x ++ definedNames y -- classMethods c (x,y) = classMethods c x ++ classMethods c y {-+ Auxiliary functions for extracting particular kinds of names: -} definedVars ds = filter isHsVar . definedValues $ ds -- hmm definedValues' ds = filter (isValue.snd) . definedNames $ ds definedValues ds = map fst . definedValues' $ ds definedType tp = c where [(HsCon c,_)] = definedNames tp {-+ Auxiliary functions to simplify the definition of instances of #DefinedNames#: -} definedNamesRec x = definedNames (struct x) classMethodsRec i cnt = classMethods i cnt . struct mapDefinedNamesRec f = mapRec (mapDefinedNames f) addNameRec x = mapRec addName x value qn = (HsVar qn,Value) -- con t defty cs n = (HsCon n,ConstrOf t defty cs) con t defty n = (HsCon n,ConstrOf t defty) field t tyinfo n = (HsVar n,FieldOf t tyinfo) method c cnt ms n = (HsVar n,MethodOf c cnt ms) -- tcon n defty cs fs = (HsCon n,Type defty cs fs) tcon n tyinfo = (HsCon n, Type tyinfo) classname c cnt methods = (HsCon c, Class cnt methods)
kmate/HaRe
old/tools/base/defs/DefinedNames.hs
bsd-3-clause
2,903
0
11
520
715
376
339
41
1
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.Named -- Copyright : (c) David Roundy <[email protected]> -- License : BSD3-style (see LICENSE) -- -- Maintainer : none -- Stability : unstable -- Portability : unportable -- -- A module for assigning a name to a given layout. Deprecated, use -- "XMonad.Layout.Renamed" instead. -- ----------------------------------------------------------------------------- module XMonad.Layout.Named ( -- * Usage -- $usage named, nameTail ) where import XMonad.Layout.LayoutModifier import XMonad.Layout.Renamed -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.Named -- -- Then edit your @layoutHook@ by adding the Named layout modifier -- to some layout: -- -- > myLayout = named "real big" Full ||| (nameTail $ named "real big" $ Full) ||| etc.. -- > main = xmonad defaultConfig { layoutHook = myLayout } -- -- For more detailed instructions on editing the layoutHook see: -- -- "XMonad.Doc.Extending#Editing_the_layout_hook" -- -- Note that this module has been deprecated and may be removed in a future -- release, please use "XMonad.Layout.Renamed" instead. -- | (Deprecated) Rename a layout. named :: String -> l a -> ModifiedLayout Rename l a named s = renamed [Replace s] -- | (Deprecated) Remove the first word of the name. nameTail :: l a -> ModifiedLayout Rename l a nameTail = renamed [CutWordsLeft 1]
markus1189/xmonad-contrib-710
XMonad/Layout/Named.hs
bsd-3-clause
1,607
0
7
274
136
89
47
11
1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor, PatternGuards #-} module Idris.ElabDecls where import Idris.AbsSyntax import Idris.ASTUtils import Idris.DSL import Idris.Error import Idris.Delaborate import Idris.Directives import Idris.Imports import Idris.Elab.Term import Idris.Coverage import Idris.DataOpts import Idris.Providers import Idris.Primitives import Idris.Inliner import Idris.PartialEval import Idris.DeepSeq import Idris.Output (iputStrLn, pshow, iWarn, sendHighlighting) import IRTS.Lang import Idris.Elab.Utils import Idris.Elab.Type import Idris.Elab.Clause import Idris.Elab.Data import Idris.Elab.Record import Idris.Elab.Class import Idris.Elab.Instance import Idris.Elab.Provider import Idris.Elab.RunElab import Idris.Elab.Transform import Idris.Elab.Value import Idris.Core.TT import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.Execute import Idris.Core.Typecheck import Idris.Core.CaseTree import Idris.Docstrings hiding (Unchecked) import Prelude hiding (id, (.)) import Control.Category import Control.Applicative hiding (Const) import Control.DeepSeq import Control.Monad import Control.Monad.State.Strict as State import Data.List import Data.Maybe import Debug.Trace import qualified Data.Map as Map import qualified Data.Set as S import qualified Data.Text as T import Data.Char(isLetter, toLower) import Data.List.Split (splitOn) import Util.Pretty(pretty, text) -- Top level elaborator info, supporting recursive elaboration recinfo :: ElabInfo recinfo = EInfo [] emptyContext id Nothing Nothing elabDecl' -- | Return the elaborated term which calls 'main' elabMain :: Idris Term elabMain = do (m, _) <- elabVal recinfo ERHS (PApp fc (PRef fc [] (sUN "run__IO")) [pexp $ PRef fc [] (sNS (sUN "main") ["Main"])]) return m where fc = fileFC "toplevel" -- | Elaborate primitives elabPrims :: Idris () elabPrims = do mapM_ (elabDecl' EAll recinfo) (map (\(opt, decl, docs, argdocs) -> PData docs argdocs defaultSyntax (fileFC "builtin") opt decl) (zip4 [inferOpts, eqOpts] [inferDecl, eqDecl] [emptyDocstring, eqDoc] [[], eqParamDoc])) addNameHint eqTy (sUN "prf") mapM_ elabPrim primitives -- Special case prim__believe_me because it doesn't work on just constants elabBelieveMe -- Finally, syntactic equality elabSynEq where elabPrim :: Prim -> Idris () elabPrim (Prim n ty i def sc tot) = do updateContext (addOperator n ty i (valuePrim def)) setTotality n tot i <- getIState putIState i { idris_scprims = (n, sc) : idris_scprims i } valuePrim :: ([Const] -> Maybe Const) -> [Value] -> Maybe Value valuePrim prim vals = fmap VConstant (mapM getConst vals >>= prim) getConst (VConstant c) = Just c getConst _ = Nothing p_believeMe [_,_,x] = Just x p_believeMe _ = Nothing believeTy = Bind (sUN "a") (Pi Nothing (TType (UVar (-2))) (TType (UVar (-1)))) (Bind (sUN "b") (Pi Nothing (TType (UVar (-2))) (TType (UVar (-1)))) (Bind (sUN "x") (Pi Nothing (V 1) (TType (UVar (-1)))) (V 1))) elabBelieveMe = do let prim__believe_me = sUN "prim__believe_me" updateContext (addOperator prim__believe_me believeTy 3 p_believeMe) setTotality prim__believe_me (Partial NotCovering) i <- getIState putIState i { idris_scprims = (prim__believe_me, (3, LNoOp)) : idris_scprims i } p_synEq [t,_,x,y] | x == y = Just (VApp (VApp vnJust VErased) (VApp (VApp vnRefl t) x)) | otherwise = Just (VApp vnNothing VErased) p_synEq args = Nothing nMaybe = P (TCon 0 2) (sNS (sUN "Maybe") ["Maybe", "Prelude"]) Erased vnJust = VP (DCon 1 2 False) (sNS (sUN "Just") ["Maybe", "Prelude"]) VErased vnNothing = VP (DCon 0 1 False) (sNS (sUN "Nothing") ["Maybe", "Prelude"]) VErased vnRefl = VP (DCon 0 2 False) eqCon VErased synEqTy = Bind (sUN "a") (Pi Nothing (TType (UVar (-3))) (TType (UVar (-2)))) (Bind (sUN "b") (Pi Nothing (TType (UVar (-3))) (TType (UVar (-2)))) (Bind (sUN "x") (Pi Nothing (V 1) (TType (UVar (-2)))) (Bind (sUN "y") (Pi Nothing (V 1) (TType (UVar (-2)))) (mkApp nMaybe [mkApp (P (TCon 0 4) eqTy Erased) [V 3, V 2, V 1, V 0]])))) elabSynEq = do let synEq = sUN "prim__syntactic_eq" updateContext (addOperator synEq synEqTy 4 p_synEq) setTotality synEq (Total []) i <- getIState putIState i { idris_scprims = (synEq, (4, LNoOp)) : idris_scprims i } elabDecls :: ElabInfo -> [PDecl] -> Idris () elabDecls info ds = do mapM_ (elabDecl EAll info) ds elabDecl :: ElabWhat -> ElabInfo -> PDecl -> Idris () elabDecl what info d = let info' = info { rec_elabDecl = elabDecl' } in idrisCatch (withErrorReflection $ elabDecl' what info' d) (setAndReport) elabDecl' _ info (PFix _ _ _) = return () -- nothing to elaborate elabDecl' _ info (PSyntax _ p) = return () -- nothing to elaborate elabDecl' what info (PTy doc argdocs s f o n nfc ty) | what /= EDefns = do logLvl 1 $ "Elaborating type decl " ++ show n ++ show o elabType info s doc argdocs f o n nfc ty return () elabDecl' what info (PPostulate b doc s f nfc o n ty) | what /= EDefns = do logLvl 1 $ "Elaborating postulate " ++ show n ++ show o if b then elabExtern info s doc f nfc o n ty else elabPostulate info s doc f nfc o n ty elabDecl' what info (PData doc argDocs s f co d) | what /= ETypes = do logLvl 1 $ "Elaborating " ++ show (d_name d) elabData info s doc argDocs f co d | otherwise = do logLvl 1 $ "Elaborating [type of] " ++ show (d_name d) elabData info s doc argDocs f co (PLaterdecl (d_name d) (d_name_fc d) (d_tcon d)) elabDecl' what info d@(PClauses f o n ps) | what /= ETypes = do logLvl 1 $ "Elaborating clause " ++ show n i <- getIState -- get the type options too let o' = case lookupCtxt n (idris_flags i) of [fs] -> fs [] -> [] elabClauses info f (o ++ o') n ps elabDecl' what info (PMutual f ps) = do case ps of [p] -> elabDecl what info p _ -> do mapM_ (elabDecl ETypes info) ps mapM_ (elabDecl EDefns info) ps -- record mutually defined data definitions let datans = concatMap declared (filter isDataDecl ps) mapM_ (setMutData datans) datans logLvl 1 $ "Rechecking for positivity " ++ show datans mapM_ (\x -> do setTotality x Unchecked) datans -- Do totality checking after entire mutual block i <- get mapM_ (\n -> do logLvl 5 $ "Simplifying " ++ show n ctxt' <- do ctxt <- getContext tclift $ simplifyCasedef n (getErasureInfo i) ctxt setContext ctxt') (map snd (idris_totcheck i)) mapM_ buildSCG (idris_totcheck i) mapM_ checkDeclTotality (idris_totcheck i) clear_totcheck where isDataDecl (PData _ _ _ _ _ _) = True isDataDecl _ = False setMutData ns n = do i <- getIState case lookupCtxt n (idris_datatypes i) of [x] -> do let x' = x { mutual_types = ns } putIState $ i { idris_datatypes = addDef n x' (idris_datatypes i) } _ -> return () elabDecl' what info (PParams f ns ps) = do i <- getIState logLvl 1 $ "Expanding params block with " ++ show ns ++ " decls " ++ show (concatMap tldeclared ps) let nblock = pblock i mapM_ (elabDecl' what info) nblock where pinfo = let ds = concatMap tldeclared ps newps = params info ++ ns dsParams = map (\n -> (n, map fst newps)) ds newb = addAlist dsParams (inblock info) in info { params = newps, inblock = newb } pblock i = map (expandParamsD False i id ns (concatMap tldeclared ps)) ps elabDecl' what info (PNamespace n nfc ps) = do mapM_ (elabDecl' what ninfo) ps let ns = reverse (map T.pack newNS) sendHighlighting [(nfc, AnnNamespace ns Nothing)] where newNS = maybe [n] (n:) (namespace info) ninfo = info { namespace = Just newNS } elabDecl' what info (PClass doc s f cs n nfc ps pdocs fds ds cn cd) | what /= EDefns = do logLvl 1 $ "Elaborating class " ++ show n elabClass info (s { syn_params = [] }) doc f cs n nfc ps pdocs fds ds cn cd elabDecl' what info (PInstance doc argDocs s f cs n nfc ps t expn ds) = do logLvl 1 $ "Elaborating instance " ++ show n elabInstance info s doc argDocs what f cs n nfc ps t expn ds elabDecl' what info (PRecord doc rsyn fc opts name nfc ps pdocs fs cname cdoc csyn) = do logLvl 1 $ "Elaborating record " ++ show name elabRecord info what doc rsyn fc opts name nfc ps pdocs fs cname cdoc csyn {- | otherwise = do logLvl 1 $ "Elaborating [type of] " ++ show tyn elabData info s doc [] f [] (PLaterdecl tyn ty) -} elabDecl' _ info (PDSL n dsl) = do i <- getIState putIState (i { idris_dsls = addDef n dsl (idris_dsls i) }) addIBC (IBCDSL n) elabDecl' what info (PDirective i) | what /= EDefns = directiveAction i elabDecl' what info (PProvider doc syn fc nfc provWhat n) | what /= EDefns = do logLvl 1 $ "Elaborating type provider " ++ show n elabProvider doc info syn fc nfc provWhat n elabDecl' what info (PTransform fc safety old new) = do elabTransform info fc safety old new return () elabDecl' what info (PRunElabDecl fc script ns) = do elabRunElab info fc script ns return () elabDecl' _ _ _ = return () -- skipped this time
osa1/Idris-dev
src/Idris/ElabDecls.hs
bsd-3-clause
10,739
0
21
3,510
3,725
1,875
1,850
227
6
module Idris.Help (CmdArg(..), extraHelp) where data CmdArg = ExprArg -- ^ The command takes an expression | NameArg -- ^ The command takes a name | FileArg -- ^ The command takes a file | ModuleArg -- ^ The command takes a module name | PkgArgs -- ^ The command takes a list of package names | NumberArg -- ^ The command takes a number | NamespaceArg -- ^ The command takes a namespace name | OptionArg -- ^ The command takes an option | MetaVarArg -- ^ The command takes a metavariable | ColourArg -- ^ The command is the colour-setting command | NoArg -- ^ No completion (yet!?) | SpecialHeaderArg -- ^ do not use | ConsoleWidthArg -- ^ The width of the console | DeclArg -- ^ An Idris declaration, as might be contained in a file | ManyArgs CmdArg -- ^ Zero or more of one kind of argument | OptionalArg CmdArg -- ^ Zero or one of one kind of argument | SeqArgs CmdArg CmdArg -- ^ One kind of argument followed by another instance Show CmdArg where show ExprArg = "<expr>" show NameArg = "<name>" show FileArg = "<filename>" show ModuleArg = "<module>" show PkgArgs = "<package list>" show NumberArg = "<number>" show NamespaceArg = "<namespace>" show OptionArg = "<option>" show MetaVarArg = "<hole>" show ColourArg = "<option>" show NoArg = "" show SpecialHeaderArg = "Arguments" show ConsoleWidthArg = "auto|infinite|<number>" show DeclArg = "<top-level declaration>" show (ManyArgs a) = "(" ++ show a ++ ")..." show (OptionalArg a) = "[" ++ show a ++ "]" show (SeqArgs a b) = show a ++ " " ++ show b -- | Use these for completion, but don't show them in :help extraHelp ::[([String], CmdArg, String)] extraHelp = [ ([":casesplit!", ":cs!"], NoArg, ":cs! <line> <name> destructively splits the pattern variable on the line") , ([":addclause!", ":ac!"], NoArg, ":ac! <line> <name> destructively adds a clause for the definition of the name on the line") , ([":addmissing!", ":am!"], NoArg, ":am! <line> <name> destructively adds all missing pattern matches for the name on the line") , ([":makewith!", ":mw!"], NoArg, ":mw! <line> <name> destructively adds a with clause for the definition of the name on the line") , ([":proofsearch!", ":ps!"], NoArg, ":ps! <line> <name> <names> destructively does proof search for name on line, with names as hints") , ([":addproofclause!", ":apc!"], NoArg, ":apc! <line> <name> destructively adds a pattern-matching proof clause to name on line") , ([":refine!", ":ref!"], NoArg, ":ref! <line> <name> <name'> destructively attempts to partially solve name on line, with name' as hint, introducing holes for arguments that aren't inferrable") ]
adnelson/Idris-dev
src/Idris/Help.hs
bsd-3-clause
2,969
0
8
814
450
268
182
45
1
{-# LANGUAGE MagicHash #-} -- Should be compiled with -O0 import Control.Concurrent import GHC.Conc import GHC.Prim import GHC.Exts main = do t <- forkIO (f 0 `seq` return ()) threadDelay 10 killThread t putStrLn "Done" -- Non-allocating let-no-escape infinite loop in fail {-# NOINLINE f #-} f :: Int -> Bool f i@(I# j) = let fail :: Int# -> Bool fail i = fail (i +# 1#) in if (case i of 0 -> True _ -> False) then fail j else False
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/concurrent/should_run/T367_letnoescape.hs
bsd-3-clause
501
0
12
151
164
84
80
17
3
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} -- | Helper information for the main optimisation passes. module Futhark.Optimise.MemoryBlockMerging.AuxiliaryInfo where import qualified Data.Map.Strict as M import Control.Monad import Futhark.Representation.AST import Futhark.Representation.ExplicitMemory (ExplicitMemory) import Futhark.Optimise.MemoryBlockMerging.Types import Futhark.Optimise.MemoryBlockMerging.Miscellaneous import Futhark.Optimise.MemoryBlockMerging.VariableMemory import Futhark.Optimise.MemoryBlockMerging.MemoryAliases import Futhark.Optimise.MemoryBlockMerging.VariableAliases import Futhark.Optimise.MemoryBlockMerging.Liveness.FirstUse import Futhark.Optimise.MemoryBlockMerging.Liveness.LastUse import Futhark.Optimise.MemoryBlockMerging.Liveness.Interference import Futhark.Optimise.MemoryBlockMerging.ActualVariables import Futhark.Optimise.MemoryBlockMerging.Existentials getAuxiliaryInfo :: FunDef ExplicitMemory -> AuxiliaryInfo getAuxiliaryInfo fundef = let name = funDefName fundef var_to_mem = findVarMemMappings fundef mem_aliases = findMemAliases fundef var_to_mem var_aliases = findVarAliases fundef first_uses = findFirstUses var_to_mem mem_aliases fundef last_uses = findLastUses var_to_mem mem_aliases first_uses existentials fundef (interferences, potential_kernel_interferences) = findInterferences var_to_mem mem_aliases first_uses last_uses existentials fundef actual_variables = findActualVariables var_to_mem first_uses fundef existentials = findExistentials fundef in AuxiliaryInfo { auxName = name , auxVarMemMappings = var_to_mem , auxMemAliases = mem_aliases , auxVarAliases = var_aliases , auxFirstUses = first_uses , auxLastUses = last_uses , auxInterferences = interferences , auxPotentialKernelDataRaceInterferences = potential_kernel_interferences , auxActualVariables = actual_variables , auxExistentials = existentials } debugAuxiliaryInfo :: AuxiliaryInfo -> String -> IO () debugAuxiliaryInfo aux desc = aux `seq` auxVarMemMappings aux `seq` auxMemAliases aux `seq` auxVarAliases aux `seq` auxFirstUses aux `seq` auxLastUses aux `seq` auxInterferences aux `seq` auxPotentialKernelDataRaceInterferences `seq` auxActualVariables aux `seq` auxExistentials aux `seq` do putStrLn $ replicate 70 '=' putStrLn (desc ++ ": Helper info in " ++ pretty (auxName aux) ++ ":") putStrLn $ replicate 70 '-' putStrLn "Variable-to-memory mappings:" forM_ (M.assocs $ auxVarMemMappings aux) $ \(var, memloc) -> putStrLn ("For " ++ pretty var ++ ": " ++ pretty (memSrcName memloc) ++ ", " ++ show (memSrcIxFun memloc)) putStrLn $ replicate 70 '-' putStrLn "Memory aliases:" forM_ (M.assocs $ auxMemAliases aux) $ \(mem, aliases) -> putStrLn ("For " ++ pretty mem ++ ": " ++ prettySet aliases) putStrLn $ replicate 70 '-' putStrLn "Variables aliases:" forM_ (M.assocs $ auxVarAliases aux) $ \(var, aliases) -> putStrLn ("For " ++ pretty var ++ ": " ++ prettySet aliases) putStrLn $ replicate 70 '-' putStrLn "First uses of memory:" forM_ (M.assocs $ auxFirstUses aux) $ \(stmt_var, mems) -> putStrLn ("In " ++ pretty stmt_var ++ ": " ++ prettySet mems) putStrLn $ replicate 70 '-' putStrLn "Last uses of memory:" forM_ (M.assocs $ auxLastUses aux) $ \(var, mems) -> do let pret = case var of FromStm stmt_var -> "stm@" ++ pretty stmt_var FromRes res_var -> "res@" ++ pretty res_var putStrLn ("In " ++ pret ++ ": " ++ prettySet mems) putStrLn $ replicate 70 '-' putStrLn "Interferences of memory blocks:" forM_ (M.assocs $ auxInterferences aux) $ \(mem, mems) -> putStrLn ("In " ++ pretty mem ++ ": " ++ prettySet mems) putStrLn $ replicate 70 '-' putStrLn "Potential kernel data race interferences of memory blocks:" forM_ (auxPotentialKernelDataRaceInterferences aux) $ mapM_ print putStrLn $ replicate 70 '-' putStrLn "Actual variables:" forM_ (M.assocs $ auxActualVariables aux) $ \(var, vars) -> putStrLn ("For " ++ pretty var ++ ": " ++ prettySet vars) putStrLn $ replicate 70 '-' putStrLn "Existentials:" putStrLn $ prettySet $ auxExistentials aux putStrLn $ replicate 70 '=' putStrLn ""
ihc/futhark
src/Futhark/Optimise/MemoryBlockMerging/AuxiliaryInfo.hs
isc
4,337
0
19
777
1,144
582
562
90
2
{-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# LANGUAGE RecordWildCards #-} import Data.Foldable (for_) import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import WordProblem (answer) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "answer" $ for_ cases test where test Case{..} = it description assertion where assertion = answer input `shouldBe` fromIntegral <$> expected data Case = Case { description :: String , input :: String , expected :: Maybe Integer } cases :: [Case] cases = [ Case { description = "just a number" , input = "What is 5?" , expected = Just 5 } , Case { description = "addition" , input = "What is 1 plus 1?" , expected = Just 2 } , Case { description = "more addition" , input = "What is 53 plus 2?" , expected = Just 55 } , Case { description = "addition with negative numbers" , input = "What is -1 plus -10?" , expected = Just (-11) } , Case { description = "large addition" , input = "What is 123 plus 45678?" , expected = Just 45801 } , Case { description = "subtraction" , input = "What is 4 minus -12?" , expected = Just 16 } , Case { description = "multiplication" , input = "What is -3 multiplied by 25?" , expected = Just (-75) } , Case { description = "division" , input = "What is 33 divided by -3?" , expected = Just (-11) } , Case { description = "multiple additions" , input = "What is 1 plus 1 plus 1?" , expected = Just 3 } , Case { description = "addition and subtraction" , input = "What is 1 plus 5 minus -2?" , expected = Just 8 } , Case { description = "multiple subtraction" , input = "What is 20 minus 4 minus 13?" , expected = Just 3 } , Case { description = "subtraction then addition" , input = "What is 17 minus 6 plus 3?" , expected = Just 14 } , Case { description = "multiple multiplication" , input = "What is 2 multiplied by -2 multiplied by 3?" , expected = Just (-12) } , Case { description = "addition and multiplication" , input = "What is -3 plus 7 multiplied by -2?" , expected = Just (-8) } , Case { description = "multiple division" , input = "What is -12 divided by 2 divided by -3?" , expected = Just 2 } , Case { description = "unknown operation" , input = "What is 52 cubed?" , expected = Nothing } , Case { description = "Non math question" , input = "Who is the President of the United States?" , expected = Nothing } , Case { description = "reject problem missing an operand" , input = "What is 1 plus?" , expected = Nothing } , Case { description = "reject problem with no operands or operators" , input = "What is?" , expected = Nothing } , Case { description = "reject two operations in a row" , input = "What is 1 plus plus 2?" , expected = Nothing } , Case { description = "reject two numbers in a row" , input = "What is 1 plus 2 1?" , expected = Nothing } , Case { description = "reject postfix notation" , input = "What is 1 2 plus?" , expected = Nothing } , Case { description = "reject prefix notation" , input = "What is plus 1 2?" , expected = Nothing } ] -- 67cc2d6b240854e7d997a92c0f1819c2fe72a1e0
exercism/xhaskell
exercises/practice/wordy/test/Tests.hs
mit
4,638
0
11
2,132
791
485
306
85
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.HTMLTableCellElement ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.HTMLTableCellElement #else module Graphics.UI.Gtk.WebKit.DOM.HTMLTableCellElement #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.HTMLTableCellElement #else import Graphics.UI.Gtk.WebKit.DOM.HTMLTableCellElement #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/HTMLTableCellElement.hs
mit
485
0
5
39
33
26
7
4
0
-- | Faun.Fuzzy is a fun functional set of functions for fuzzy logic module Faun.Parser.NamedFuzzy ( parseNamedFuzzy ) where import qualified Data.Text as T import Text.Parsec import Text.Parsec.String (Parser) import Faun.Parser.Core import Faun.Parser.FuzzySet import Faun.NamedFuzzy -- | Parse a fuzzy set. parseNamedFuzzy :: String -> Either ParseError NamedFuzzy parseNamedFuzzy = parse (contents getNamedFuzzy) "<stdin>" getNamedFuzzy :: Parser NamedFuzzy getNamedFuzzy = do n <- identifier reservedOp "=" reservedOp "{" fs <- getFuzzy reservedOp "}" return $ NamedFuzzy (T.pack n) fs
PhDP/Sphinx-AI
Faun/Parser/NamedFuzzy.hs
mit
606
0
11
94
150
80
70
18
1
{-# LANGUAGE OverloadedStrings #-} module Data.FlexibleTime ( (.+) , (.-) , getYear , getMonth , getDay , getDate , getHour , getMin , getSec ) where import qualified Data.ByteString.Char8 as BS import Data.UnixTime (Format, UnixTime, addUnixDiffTime, diffUnixTime, formatUnixTime, secondsToUnixDiffTime, udtSeconds) import Foreign.C.Types (CTime (..)) import System.IO.Unsafe ---------------------------------------------------------------------- -- Add seconds to UnixTime (.+) :: (Integral a) => UnixTime -> a -> UnixTime u .+ d = addUnixDiffTime u (secondsToUnixDiffTime d) -- Substract seconds from UnixTime (.-) :: (Integral a) => UnixTime -> UnixTime -> a l .- r = ctimeToIntegral $ udtSeconds $ diffUnixTime l r getYear :: (Integral a) => UnixTime -> a getYear = get "%Y" getMonth :: (Integral a) => UnixTime -> a getMonth = get "%m" getDay :: (Integral a) => UnixTime -> a getDay = get "%d" getDate :: (Integral a) => UnixTime -> a getDate = get "%w" getHour :: (Integral a) => UnixTime -> a getHour = get "%H" getMin :: (Integral a) => UnixTime -> a getMin = get "%M" getSec :: (Integral a) => UnixTime -> a getSec = get "%S" ---------------------------------------------------------------------- ctimeToIntegral :: (Integral a) => CTime -> a ctimeToIntegral (CTime n) = fromIntegral n get :: (Integral a) => Format -> UnixTime -> a get f = readBsNum . unsafePerformIO . formatUnixTime f readBsNum :: (Integral a) => BS.ByteString -> a readBsNum bs = go (reverse . map readChar . BS.unpack $ bs) 0 1 where go [] num _ = num go (x:xs) num cnt = go xs (num + (x * cnt)) (cnt*10) readChar :: (Integral a) => Char -> a readChar '0' = 0 readChar '1' = 1 readChar '2' = 2 readChar '3' = 3 readChar '4' = 4 readChar '5' = 5 readChar '6' = 6 readChar '7' = 7 readChar '8' = 8 readChar '9' = 9 readChar _ = error "parse error"
tattsun/flexible-time
src/Data/FlexibleTime.hs
mit
2,047
0
11
529
681
373
308
55
2
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeFamilyDependencies #-} {-# LANGUAGE TypeOperators #-} module Text.Html.Nice.Writer ( -- * The markup monad Markup -- * Basic node types , text , lazyText , builder , string , doctype_ -- ** Variants that don't escape their input , textRaw , lazyTextRaw , builderRaw , stringRaw -- * Combinators , AddAttr , (!) , dynamic , dynamicRaw , using , sub , mapP -- ** Streaming , stream -- ** Noting specific elements , Note (..) , note -- * Compilation , compile , runMarkup -- * Internals , makeElement , makeVoidElement ) where import Data.Foldable (toList) import Data.String (IsString (..)) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Builder as TLB import qualified Data.Vector as V import Text.Html.Nice.Internal type Children p = [Markup' p] -> [Markup' p] data MarkupStep p a = MarkupStep { msGlobalId :: {-# UNPACK #-} !Int , msChildren :: Children p , msResult :: a } deriving (Functor, Foldable, Traversable) -- | A Writer-like monad newtype Markup p a = Markup (Int -> [Attr p] -> MarkupStep p a) instance Functor (Markup p) where fmap f (Markup m) = Markup (\i attr -> fmap f (m i attr)) instance Applicative (Markup p) where pure a = Markup (\i _ -> MarkupStep i id a) Markup f <*> Markup x = Markup $ \i attr -> case f i attr of MarkupStep j fnodes f' -> case x j [] of MarkupStep k xnodes x' -> MarkupStep k (fnodes . xnodes) (f' x') instance Monad (Markup p) where Markup mx >>= f = Markup $ \i attr -> case mx i attr of MarkupStep j dx a -> case f a of Markup f' -> case f' j attr of MarkupStep k dy b -> MarkupStep k (dx . dy) b -- | Compile a 'Markup'. Don't run this multiple times! compile :: Markup t a -> FastMarkup t compile m = case runM 0 m of (m', _, _) -> compile_ m' -- | Compile a 'Markup'. Don't run this multiple times! -- -- Same as 'compile' but lets you use the result. runMarkup :: Markup t a -> (a, FastMarkup t) runMarkup m = case runM 0 m of (m', _, a) -> (a, compile_ m') -------------------------------------------------------------------------------- -- Internals runM :: Int -> Markup t a -> (Markup' t, Int, a) runM i (Markup m) = (List (x []), j, a) where MarkupStep j x a = m i [] {-# INLINE makeElement #-} makeElement :: Text -> Markup p a -> Markup p a makeElement name m = Markup $ \i attr -> case runM i m of (cs, j, a) -> MarkupStep { msGlobalId = j , msChildren = (:) (Node name (V.fromList attr) cs) , msResult = a } {-# INLINE makeVoidElement #-} makeVoidElement :: Text -> Markup p () makeVoidElement name = Markup $ \i attr -> MarkupStep { msGlobalId = i , msChildren = (:) (VoidNode name (V.fromList attr)) , msResult = () } {-# INLINE lift #-} lift :: Markup' t -> Markup t () lift m' = Markup $ \i _ -> MarkupStep { msGlobalId = i , msChildren = (m':) , msResult = () } doctype_ :: Markup p () doctype_ = lift Doctype -------------------------------------------------------------------------------- -- Node types {-# INLINE using #-} using :: ToFastMarkup b => (a -> b) -> Markup (a -> FastMarkup r) () using f = dynamic (toFastMarkup . f) {-# INLINE dynamic #-} dynamic :: p -> Markup p () dynamic = lift . Hole DoEscape {-# INLINE dynamicRaw #-} dynamicRaw :: p -> Markup p () dynamicRaw = lift . Hole Don'tEscape -- | Map over the holes in a 'Markup'. This necessarily discards any attributes -- currently being added that are not static. mapP :: (a -> b) -> Markup a r -> Markup b r mapP f (Markup m) = Markup $ \i attr -> case m i (foldr addA [] attr) of ms -> ms { msChildren = \cs -> map (fmap f) (msChildren ms []) ++ cs } where addA ((:=) a b) xs = (a := b) : xs addA _ xs = xs instance a ~ () => IsString (Markup t a) where fromString = text . fromString -------------------------------------------------------------------------------- -- Combinators type MarkupLike a = a class AddAttr a t | a -> t where addAttr :: a -> Attr t -> a instance AddAttr (Markup t a -> Markup t b) t where addAttr f a x = Markup $ \i attrs -> case f x of Markup m -> m i (a:attrs) instance AddAttr (Markup t a) t where addAttr f a = Markup $ \i attrs -> case f of Markup m -> m i (a:attrs) (!) :: AddAttr a t => MarkupLike a -> Attr t -> MarkupLike a (!) = addAttr infixl 8 ! {-# INLINE stream #-} stream :: Foldable f => Markup (a -> n) r -> Markup (f a -> FastMarkup n) r stream m = result <$ dynamicRaw (\fa -> FStream (ListS (toList fa) fm)) where (result, !fm) = runMarkup m -- | Sub-template sub :: Markup n a -> Markup (FastMarkup n) a sub m = case runMarkup m of (a, fm) -> a <$ lift (Hole Don'tEscape fm) -------------------------------------------------------------------------------- -- 'Note' system data Note a = Note { noteId :: {-# UNPACK #-} !Int , noted :: FastMarkup a } deriving (Eq, Show, Functor) -- | Give a node a unique id -- -- Might be handy to build server-side react-esque systems note :: (Markup t a -> Markup t b) -> Markup t a -> Markup t (Note t, b) note f x = withNote where withNote = do (i, a) <- markup case runM i markup of (m', _, _) -> return (Note { noteId = i , noted = compile_ m' }, a) markup = Markup $ \i attrs -> case f x of Markup m -> case m (i + 1) ("id" := niceId i:attrs) of ms -> ms { msResult = (i, msResult ms) } -- | HTML 'id' attribute given to 'note'd elements. niceId :: Int -> Text niceId i = T.pack ("nice-" ++ show i) -------------------------------------------------------------------------------- -- Useful string functions -- | Insert text and escape it text :: Text -> Markup t () text = lift . Text DoEscape . StrictT -- | Insert text and escape it lazyText :: TL.Text -> Markup n () lazyText = lift . Text DoEscape . LazyT -- | Insert text and escape it builder :: TLB.Builder -> Markup n () builder = lift . Text DoEscape . BuilderT -- | Insert text and escape it string :: String -> Markup n () string = lift . Text DoEscape . BuilderT . TLB.fromString -- | Insert text and don't escape it textRaw :: Text -> Markup t () textRaw = lift . Text Don'tEscape . StrictT -- | Insert text and don't escape it lazyTextRaw :: TL.Text -> Markup n () lazyTextRaw = lift . Text Don'tEscape . LazyT -- | Insert text and don't escape it builderRaw :: TLB.Builder -> Markup n () builderRaw = lift . Text Don'tEscape . BuilderT -- | Insert text and don't escape it stringRaw :: String -> Markup n () stringRaw = lift . Text Don'tEscape . BuilderT . TLB.fromString
TransportEngineering/nice-html
src/Text/Html/Nice/Writer.hs
mit
7,413
0
19
1,903
2,390
1,284
1,106
174
2
{-# LANGUAGE OverloadedStrings #-} module System.Directory.Watchman.Subscribe ( SubscriptionName(..) , SubscribeParams , SubscriptionNotification(..) , SubscriptionFiles(..) , SubscriptionStateEnter(..) , SubscriptionStateLeave(..) , renderSubscribe , parseSubscriptionNotification , since , deferVcs , defer , System.Directory.Watchman.Subscribe.drop ) where import Data.Foldable (foldl') import Control.Monad (unless) import Data.ByteString (ByteString) import Data.Sequence (Seq) import qualified Data.Sequence as Seq import qualified Data.Map.Strict as M import Data.Map.Strict (Map) import qualified Data.ByteString.Char8 as BC8 import System.Directory.Watchman.WFilePath import System.Directory.Watchman.Fields import System.Directory.Watchman.Expression (Expression, renderExpression) import System.Directory.Watchman.BSER import System.Directory.Watchman.BSER.Parser import System.Directory.Watchman.Clockspec import System.Directory.Watchman.State data SubscribeParams = SubscribeParams { _SubscribeParams_Since :: !(Maybe Clockspec) , _SubscribeParams_DeferVcs :: !Bool , _SubscribeParams_Defer :: ![StateName] , _SubscribeParams_Drop :: ![StateName] } deriving (Show, Eq) defaultSubscribeParams :: SubscribeParams defaultSubscribeParams = SubscribeParams { _SubscribeParams_Since = Nothing , _SubscribeParams_DeferVcs = True , _SubscribeParams_Defer = [] , _SubscribeParams_Drop = [] } newtype SubscriptionName = SubscriptionName ByteString deriving (Show, Eq, Ord) -- | The subscribe command object allows the client to specify a since parameter; if present in the command, -- the initial set of subscription results will only include files that changed since the specified clockspec, -- equivalent to using the @query@ command with the @since@ generator. -- -- <https://facebook.github.io/watchman/docs/cmd/subscribe.html> since :: Clockspec -> (SubscribeParams -> SubscribeParams) since s x = x { _SubscribeParams_Since = Just s } -- | Starting in watchman version 3.2, after the notification stream is complete, if the root appears to -- be a version control directory, subscription notifications will be held until an outstanding version -- control operation is complete (at the time of writing, this is based on the presence of either -- @.hg/wlock@ or @.git/index.lock@). This behavior matches triggers and helps to avoid performing transient -- work in response to files changing, for example, during a rebase operation. -- -- In some circumstances it is desirable for a client to observe the creation of the control files at the start -- of a version control operation. You may specify that you want this behavior by using 'deferVcs False' deferVcs :: Bool -> (SubscribeParams -> SubscribeParams) deferVcs s x = x { _SubscribeParams_DeferVcs = s } defer :: [StateName] -> (SubscribeParams -> SubscribeParams) defer [] _ = error "defer: List of StateNames must not be empty" defer s x = x { _SubscribeParams_Defer = s } drop :: [StateName] -> (SubscribeParams -> SubscribeParams) drop [] _ = error "drop: List of StateNames must not be empty" drop s x = x { _SubscribeParams_Drop = s } renderSubscribe :: WFilePath -> SubscriptionName -> Expression -> [SubscribeParams -> SubscribeParams] -> [FileFieldLabel] -> BSERValue renderSubscribe rootPath (SubscriptionName subscriptionName) expr params fileFieldLabels = BSERArray $ Seq.fromList [ BSERString "subscribe" , BSERString (toByteString rootPath) , BSERString subscriptionName , BSERObject $ M.unions [ renderFieldLabels fileFieldLabels , M.singleton "expression" (renderExpression expr) , renderSubscribeParams params' ] ] where params' = foldl' (\x f -> f x) defaultSubscribeParams params renderSubscribeParams :: SubscribeParams -> Map ByteString BSERValue renderSubscribeParams params = M.unions [ case _SubscribeParams_Since params of Nothing -> M.empty Just c -> M.singleton "since" (renderClockspec c) , case _SubscribeParams_DeferVcs params of True -> M.empty -- When not specified, default behaviour of watchman is True False -> M.singleton "defer_vcs" (BSERBool False) , case _SubscribeParams_Defer params of [] -> M.empty xs -> M.singleton "defer" (BSERArray (Seq.fromList (map (\(StateName s) -> BSERString s) xs))) , case _SubscribeParams_Drop params of [] -> M.empty xs -> M.singleton "drop" (BSERArray (Seq.fromList (map (\(StateName s) -> BSERString s) xs))) ] data SubscriptionFiles = SubscriptionFiles { _SubscriptionFiles_Clock :: !ClockId , _SubscriptionFiles_Root :: !WFilePath , _SubscriptionFiles_Subscription :: !SubscriptionName , _SubscriptionFiles_Files :: !(Seq [FileField]) , _SubscriptionFiles_IsFreshInstance :: !Bool } deriving (Show, Eq, Ord) data SubscriptionStateEnter = SubscriptionStateEnter { _SubscriptionStateEnter_Clock :: !ClockId , _SubscriptionStateEnter_Root :: !WFilePath , _SubscriptionStateEnter_Subscription :: !SubscriptionName , _SubscriptionStateEnter_State :: !StateName , _SubscriptionStateEnter_Metadata :: !(Maybe BSERValue) } deriving (Show, Eq, Ord) data SubscriptionStateLeave = SubscriptionStateLeave { _SubscriptionStateLeave_Clock :: !ClockId , _SubscriptionStateLeave_Root :: !WFilePath , _SubscriptionStateLeave_Subscription :: !SubscriptionName , _SubscriptionStateLeave_State :: !StateName , _SubscriptionStateLeave_Metadata :: !(Maybe BSERValue) , _SubscriptionStateLeave_Abandoned :: !Bool } deriving (Show, Eq, Ord) data SubscriptionNotification = Subscription_Files !SubscriptionFiles | Subscription_StateEnter SubscriptionStateEnter | Subscription_StateLeave SubscriptionStateLeave deriving (Show, Eq, Ord) parseSubscriptionNotification :: [FileFieldLabel] -> BSERValue -> Parser SubscriptionNotification parseSubscriptionNotification fileFieldLabels v@(BSERObject o) = do case M.lookup "files" o of Just _ -> do f <- parseSubscriptionFiles fileFieldLabels v pure $ Subscription_Files f Nothing -> case M.lookup "state-enter" o of Just _ -> do s <- parseSubscriptionStateEnter v pure $ Subscription_StateEnter s Nothing -> case M.lookup "state-leave" o of Just _ -> do s <- parseSubscriptionStateLeave v pure $ Subscription_StateLeave s Nothing -> fail "Unrecognized subscription notification" parseSubscriptionNotification _ _ = fail "Not an Object" parseSubscriptionFiles :: [FileFieldLabel] -> BSERValue -> Parser SubscriptionFiles parseSubscriptionFiles fileFieldLabels (BSERObject o) = do clockId <- parseClockId o root <- o .: "root" subscription <- o .: "subscription" files <- o .: "files" files' <- mapM (parseFileFields fileFieldLabels) files isFreshInstance <- o .: "is_fresh_instance" pure SubscriptionFiles { _SubscriptionFiles_Clock = clockId , _SubscriptionFiles_Root = root , _SubscriptionFiles_Subscription = SubscriptionName subscription , _SubscriptionFiles_Files = files' , _SubscriptionFiles_IsFreshInstance = isFreshInstance } parseSubscriptionFiles _ _ = fail "Not an Object" parseSubscriptionStateEnter :: BSERValue -> Parser SubscriptionStateEnter parseSubscriptionStateEnter (BSERObject o) = do clockId <- parseClockId o root <- o .: "root" subscription <- o .: "subscription" state <- o .: "state-enter" let metadata = case M.lookup "metadata" o of Nothing -> Nothing Just v -> Just v pure SubscriptionStateEnter { _SubscriptionStateEnter_Clock = clockId , _SubscriptionStateEnter_Root = root , _SubscriptionStateEnter_Subscription = SubscriptionName subscription , _SubscriptionStateEnter_State = StateName state , _SubscriptionStateEnter_Metadata = metadata } parseSubscriptionStateEnter _ = fail "Not an Object" parseSubscriptionStateLeave :: BSERValue -> Parser SubscriptionStateLeave parseSubscriptionStateLeave (BSERObject o) = do clockId <- parseClockId o root <- o .: "root" subscription <- o .: "subscription" state <- o .: "state-leave" let metadata = case M.lookup "metadata" o of Nothing -> Nothing Just v -> Just v let abandoned = case M.lookup "abandoned" o of Just (BSERBool True) -> True _ -> False pure SubscriptionStateLeave { _SubscriptionStateLeave_Clock = clockId , _SubscriptionStateLeave_Root = root , _SubscriptionStateLeave_Subscription = SubscriptionName subscription , _SubscriptionStateLeave_State = StateName state , _SubscriptionStateLeave_Metadata = metadata , _SubscriptionStateLeave_Abandoned = abandoned } parseSubscriptionStateLeave _ = fail "Not an Object" parseClockId :: BSERObject -> Parser ClockId parseClockId o = do clockId <- o .: "clock" unless ("c:" `BC8.isPrefixOf` clockId) $ fail $ "Invalid clock id: " ++ BC8.unpack clockId pure (ClockId clockId)
bitc/hs-watchman
src/System/Directory/Watchman/Subscribe.hs
mit
9,455
0
20
2,021
1,970
1,046
924
223
5
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} import GHC.Generics import Web.Scotty import Data.Aeson (ToJSON) data PadOutput = PadOutput { str :: String } deriving (Generic) instance ToJSON PadOutput -- Snippet originally from https://hackage.haskell.org/package/acme-left-pad leftPad :: String -> Int -> String -> String leftPad s l "" = leftPad' s l ' ' leftPad s l (c:[]) = leftPad' s l c leftPad' s 0 c = s leftPad' s n c = if length s < n then [c] ++ leftPad' s (n - 1) c else leftPad' s (n - 1) c main :: IO () main = scotty 3000 $ do get "/" $ do stringToPad <- param "str" padding <- param "ch" padLength <- param "len" let out = PadOutput { str = leftPad stringToPad padLength padding} json out
melonmanchan/left-pad-services
haskell/leftpad/Main.hs
mit
758
0
16
166
283
142
141
20
2
{-# LANGUAGE OverloadedStrings #-} module DarkSky.Response where import DarkSky.Response.Alert import DarkSky.Response.DataBlock import DarkSky.Response.DataPoint import DarkSky.Response.Flags import DarkSky.Types import Data.Aeson import Data.Maybe (fromMaybe) import Data.Text (Text) data Response = Response { coordinate :: Coordinate , timezone :: Text , currently :: Maybe DataPoint , minutely :: Maybe DataBlock , hourly :: Maybe DataBlock , daily :: Maybe DataBlock , alerts :: [Alert] , flags :: Maybe Flags } deriving (Eq, Show) instance FromJSON Response where parseJSON = withObject "response" $ \o -> do latitude' <- o .: "latitude" longitude' <- o .: "longitude" let coordinate' = Coordinate latitude' longitude' timezone' <- o .: "timezone" currently' <- o .:? "currently" minutely' <- o .:? "minutely" hourly' <- o .:? "hourly" daily' <- o .:? "daily" alerts' <- fromMaybe [] <$> o .:? "alerts" flags' <- o .:? "flags" return Response { coordinate = coordinate' , timezone = timezone' , currently = currently' , minutely = minutely' , hourly = hourly' , daily = daily' , alerts = alerts' , flags = flags' }
peterstuart/dark-sky
src/DarkSky/Response.hs
mit
1,300
0
14
349
350
192
158
44
0
module Zeno.Unification ( Unifiable (..), Unification (..), applyUnification, mergeUnifiers, allUnifiers, ) where import Prelude () import Zeno.Prelude import Zeno.Utils import Zeno.Traversing import qualified Data.Map as Map -- |The result of trying to unify two values where -- 'NoUnifier' indicates that unification was impossible, -- This is essentially 'Maybe (Substitution n a)'. data Unification n a = Unifier !(Substitution n a) | NoUnifier -- |Values which can be unified class Unifiable a where type Names a unify :: a -> a -> Unification (Names a) a -- |Appending two unifiers will create a unifier that will -- perform both unifications, if such a unifier is still valid. instance (Ord a, Eq b) => Monoid (Unification a b) where mempty = Unifier mempty mappend NoUnifier _ = NoUnifier mappend _ NoUnifier = NoUnifier mappend (Unifier left) (Unifier right) | and (Map.elems inter) = Unifier (Map.union left right) | otherwise = NoUnifier where inter = Map.intersectionWith (==) left right -- |This is like 'catMaybes' mergeUnifiers :: [Unification a b] -> [Substitution a b] mergeUnifiers = foldl' addUni [] where addUni subs NoUnifier = subs addUni subs (Unifier sub) = sub : subs applyUnification :: (WithinTraversable a f, Eq a) => Unification a a -> f -> f applyUnification NoUnifier = id applyUnification (Unifier sub) = substitute sub allUnifiers :: (Unifiable a, WithinTraversable a f, Eq a) => a -> f -> [Substitution (Names a) a] allUnifiers from = mergeUnifiers . execWriter . (mapWithinM unifiers) where unifiers to = tell [unify from to] >> return to
trenta3/zeno-0.2.0.1
src/Zeno/Unification.hs
mit
1,650
0
12
328
495
263
232
-1
-1