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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Hakyll.Web.Template.Blaze
( Template
, applyTemplate
, applyTemplateList
, applyTemplateListWith
, string
, preEscapedString
-- For API compatibility with first release
, toHtml
, safeToHtml
) where
import Hakyll (Context(..), Item, Compiler,
itemSetBody, missingField, itemBody)
import Data.Monoid (mappend)
import Data.List (intercalate)
import Text.Blaze.Html (Html)
import Text.Blaze.Internal (string, preEscapedString)
import qualified Text.Blaze.Html as H
import Text.Blaze.Html.Renderer.String (renderHtml)
type Template m a = (String -> m String) -> Item a -> m Html
applyTemplate :: Template Compiler String -- ^ Blaze template
-> Context String -- ^ Hakyll context
-> Item String -- ^ The item
-> Compiler (Item String) -- ^ Resulting HTML
applyTemplate tpl ctx item =
tpl ctx' item
>>= return . renderHtml
>>= \body -> return $ itemSetBody body item
where
ctx' :: String -> Compiler String
ctx' key = unContext (ctx `mappend` missingField) key item
applyTemplateListWith :: String -- ^ String to join template with
-> Template Compiler String -- ^ Blaze template
-> Context String -- ^ Hakyll context
-> [Item String] -- ^ List of items
-> Compiler String -- ^ Resulting HTML
applyTemplateListWith delimiter tpl ctx items =
mapM (applyTemplate tpl ctx) items
>>= return . intercalate delimiter . map itemBody
applyTemplateList = applyTemplateListWith ""
toHtml, safeToHtml :: String -> Html
-- | toHtml specialised to String.
toHtml = string
-- | preEscapedToHtml specialised to String
-- Also safeToHtml sounds better than preEscapedToHtml
safeToHtml = preEscapedString
| nagisa/hakyll-blaze-templates | src/Hakyll/Web/Template/Blaze.hs | bsd-3-clause | 2,005 | 0 | 10 | 648 | 403 | 229 | 174 | 40 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.CSL.Output.Plain
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Andrea Rossato <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- The plain ascii output formatter for CSL
--
-----------------------------------------------------------------------------
module Text.CSL.Output.Plain
( renderPlain
) where
import Prelude
import Text.CSL.Compat.Pandoc (writePlain)
import Text.CSL.Style
import Text.Pandoc (Block (Plain), Pandoc (..), nullMeta)
-- | Render the 'Formatted' into a plain text string.
renderPlain :: Formatted -> String
renderPlain (Formatted ils) = writePlain $ Pandoc nullMeta [Plain ils]
| adunning/pandoc-citeproc | src/Text/CSL/Output/Plain.hs | bsd-3-clause | 886 | 0 | 8 | 168 | 111 | 73 | 38 | 9 | 1 |
{- | This module provides a pure implementation of Reflex, which is intended to serve as a reference for the semantics of the Reflex class. All implementations of Reflex should produce the same results as this implementation, although performance and laziness/strictness may differ.
-}
{-# LANGUAGE TypeFamilies, MultiParamTypeClasses #-}
{-# LANGUAGE EmptyDataDecls #-}
module Reflex.Pure where
import Reflex.Class
import Data.Functor.Misc
import Control.Monad
import Data.MemoTrie
import qualified Data.Dependent.Map as DMap
data Pure t
-- | The Enum instance of t must be dense: for all x :: t, there must not exist any y :: t such that pred x < y < x
-- The HasTrie instance will be used exclusively to memoize functions of t, not for any of its other capabilities
instance (Enum t, HasTrie t, Ord t) => Reflex (Pure t) where
newtype Behavior (Pure t) a = Behavior { unBehavior :: t -> a }
newtype Event (Pure t) a = Event { unEvent :: t -> Maybe a }
type PushM (Pure t) = (->) t
type PullM (Pure t) = (->) t
never = Event $ \_ -> Nothing
constant x = Behavior $ \_ -> x
push f e = Event $ memo $ \t -> unEvent e t >>= \o -> f o t
pull = Behavior . memo
merge events = Event $ memo $ \t ->
let currentOccurrences = unwrapDMapMaybe (($ t) . unEvent) events
in if DMap.null currentOccurrences
then Nothing
else Just currentOccurrences
fan e = EventSelector $ \k -> Event $ \t -> unEvent e t >>= DMap.lookup k
switch b = Event $ memo $ \t -> unEvent (unBehavior b t) t
coincidence e = Event $ memo $ \t -> unEvent e t >>= \o -> unEvent o t
instance Ord t => MonadSample (Pure t) ((->) t) where
sample = unBehavior
instance (Enum t, HasTrie t, Ord t) => MonadHold (Pure t) ((->) t) where
hold initialValue e initialTime = Behavior f
where f = memo $ \sampleTime ->
if sampleTime <= initialTime -- Really, the sampleTime should never be prior to the initialTime, because that would mean the Behavior is being sampled before being created
then initialValue
else let lastTime = pred sampleTime
in case unEvent e lastTime of
Nothing -> f lastTime
Just x -> x
| zudov/reflex-marbles | src/Reflex/Pure.hs | bsd-3-clause | 2,209 | 0 | 16 | 537 | 611 | 323 | 288 | -1 | -1 |
module Data.Exif.Types where
import Data.Ratio (Ratio)
import Data.Word (Word8, Word16, Word32)
data Endianness = LittleEndian | BigEndian deriving (Show)
data TIFFHeader = TIFFHeader {
thOffset :: Word32
, thByteOrder :: Endianness
, thIFDOffset :: Word32
} deriving (Show)
-- IFD (Image File Directory) Field
data RawIFDField = RawIFDField {
rifTag :: Word16
, rifType :: Type
, rifCount :: Int
, rifOffset :: Word32
} deriving Show
data IFDField = IFDField {
ifType :: Type
, ifCount :: Int
, ifValue :: ExifAttribute
} deriving Show
toIFDField :: RawIFDField -> ExifAttribute -> IFDField
toIFDField rawField = IFDField (rifType rawField) (rifCount rawField)
type RatioW32 = Ratio Word32
data Tag
-- Tags relating to image data structure
= TImageWidth
| TImageLength
| TBitsPerSample
| TCompression
| TPhotometricInterpretation
| TOrientation
| TSamplesPerPixel
| TPlanarConfiguration
| TYCbCrSubSampling
| TYCbCrPositioning
| TXResolution
| TYResolution
| TResolutionUnit
-- Tags relating to recording offset
| TStripOffsets
| TRowsPerStrip
| TStripByteCount
| TJPEGInterchangeFormat
| TJPEGInterchangeFormatLength
-- Tags relating to image data characteristics
| TTransferFunction
| TWhitePoint
| TPrimaryChromaticities
| TYCbCrCoefficients
| TReferenceBlackWhite
-- Other tags
| TDateTime
| TImageDescription
| TMake
| TModel
| TSoftware
| TArtist
| TCopyright
-- Tags relating to Exif
| TExifIFDPointer
| TGPS
| TInteroperability
-- Private and unknow tags
| TUnknownPrivateTag Word16
| TUnknownTag Word16
deriving (Show)
word2Tag :: Word16 -> Tag
word2Tag rawWord =
case rawWord of
-- Tags relating to image data structure
0x0100 -> TImageWidth
0x0101 -> TImageLength
0x0102 -> TBitsPerSample
0x0103 -> TCompression
0x0106 -> TPhotometricInterpretation
0x0112 -> TOrientation
0x0115 -> TSamplesPerPixel
0x011C -> TPlanarConfiguration
0x0212 -> TYCbCrSubSampling
0x0213 -> TYCbCrPositioning
0x011A -> TXResolution
0x011B -> TYResolution
0x0128 -> TResolutionUnit
-- Tags relating to recording offset
0x0111 -> TStripOffsets
0x0116 -> TRowsPerStrip
0x0117 -> TStripByteCount
0x0201 -> TJPEGInterchangeFormat
0x0202 -> TJPEGInterchangeFormatLength
-- Tags relating to image data characteristics
0x012D -> TTransferFunction
0x013E -> TWhitePoint
0x013F -> TPrimaryChromaticities
0x0211 -> TYCbCrCoefficients
0x0214 -> TReferenceBlackWhite
-- Other tags
0x0132 -> TDateTime
0x010E -> TImageDescription
0x010F -> TMake
0x0110 -> TModel
0x0131 -> TSoftware
0x013B -> TArtist
0x8298 -> TCopyright
-- Tags relating to Exif
0x8769 -> TExifIFDPointer
0x8825 -> TGPS
0xA005 -> TInteroperability
-- Handle unknow and private tags
_ ->
if rawWord >= 32768
then TUnknownPrivateTag rawWord
else TUnknownTag rawWord
data ExifAttribute
{-
- TIFF Attributes used in Exif
-}
-- Image data structure
= ImageWidth Integer
| ImageLength Integer
| BitsPerSample Int Int Int
| Compression Int
| PhotometricInterpretation Int
| Orientation Int
| SamplesPerPixel Int
| PlanarConfiguration Int
| YCbCrSubSampling Int Int
| YCbCrPositioning Int
| XResolution Rational
| YResolution Rational
| ResolutionUnit ResolutionUnit
-- Recording offset
| StripOffsets Integer
| RowsPerStrip Integer
| StripByteCount [Integer]
| JPEGInterchangeFormat Integer
| JPEGInterchangeFormatLength Integer
-- Image data characteristics
| TransferFunction [Int]
| WhitePoint Rational Rational Rational
| PrimaryChromaticities [Rational]
| YCbCrCoefficients Rational Rational Rational
| ReferenceBlackWhite [Rational]
-- Other tags
| DateTime String
| ImageDescription String
| Make String
| Model String
| Software String
| Artist String
| Copyright String
{-
- Exif Attributes
-}
-- Version
| ExifVersion Word32
| FlashPixVersion Word32
-- Image data characteristics
| ColorSpace Int
| ComponentsConfiguration Word32
| CompressedBitsPerPixel Rational
| PixelXDimension Integer
| PixelYDimension Integer
-- User information
| MakerNote String
| UserComment String
-- Related file information
| RelatedSoundFile String
-- Date and time
| DateTimeOriginal String
| DateTimeDigitized String
| SubSecTime String
| SubSecTimeOriginal String
| SubSecTimeDigitized String
-- Picture-taking conditions
| ExposureTime Rational
| FNumber Rational
| ExposureProgram Int
| SpectralSensitivity String
| ISOSpeedRatings Int
| OECF Word32
| ShutterSpeedValue Rational
| ApertureValue Rational
| BrightnessValue Rational
| ExposureBiasValue Rational
| MaxApertureValue Rational
| SubjectDistance Rational
| MeteringMode Int
| LightSource Int
| Flash Int
| FocalLength Rational
| SubjectArea [Int]
| FlashEnergy Rational
| SpatialFrequencyResponse [Word8]
| FocalPlaneXResolution Rational
| FocalPlaneYResolution Rational
| FocalPlaneResolutionUnit Int
| SubjectLocation Int Int
| ExposureIndex Rational
| SensingMethod Int
| FileSource Word32
| SceneType Word32
| CFAPattern [Word8]
| CustomRenderer Int
| ExposureMode Int
| WhiteBalance Int
| DigitalZoomRatio Rational
| FocalLengthIn35mmFilm Int
| SceneCaptureType Int
| GainControl Rational
| Contrast Int
| Saturation Int
| Sharpness Int
| DeviceSettingsDescription [Word8]
| SubjectDistanceRange Int
-- Other
| ImageUniqueID String
deriving (Show)
data ResolutionUnit = Centimeters
| Inches
deriving Show
-- data TIFFTag =
-- -- Tags relating to image data structure
-- ImageWidth Word32
-- | ImageLength Word32
-- | BitsPerSample Word16 Word16 Word16
-- | Compression Word16
-- | PhotometricInterpretation Word16
-- | Orientation Word16
-- | SamplesPerPixel Word16
-- | PlanarConfiguration Word16
-- | YCbCrSubSampling Word16 Word16
-- | YCbCrPositioning Word16
-- | XResolution Rational
-- | YResolution Rational
-- | ResolutionUnit Word16
-- -- Tags relating to recording offset
-- | StripOffsets [Word32]
-- | RowsPerStrip Word32
-- | StripByteCount [Word32]
-- | JPEGInterchangeFormat Word32
-- | JPEGInterchangeFormatLength Word32
-- -- Tags relating to image data characteristics
-- | TransferFunction [Word16]
-- | WhitePoint RatioW32 RatioW32
-- | PrimaryChromaticities [RatioW32]
-- | YCbCrCoefficients RatioW32 RatioW32 RatioW32
-- | ReferenceBlackWhite [RatioW32]
-- -- Other tags
-- | DateTime String
-- | ImageDescription String
-- | Make String
-- | Model String
-- | Software String
-- | Artist String
-- | Copyright String
-- deriving (Show)
data Type
= Byte
| Ascii
| Short
| Long
| ExifRational
| Undefined
| SLong
| SRational
deriving (Show)
word2ExifType :: Word16 -> Maybe Type
word2ExifType rawWord =
case rawWord of
1 -> Just Byte
2 -> Just Ascii
3 -> Just Short
4 -> Just Long
5 -> Just ExifRational
7 -> Just Undefined
9 -> Just SLong
10 -> Just SRational
_ -> Nothing
typeSize :: Type -> Int
typeSize etype =
case etype of
Byte -> 1
Ascii -> 1
Short -> 2
Long -> 4
ExifRational -> 8
Undefined -> 1
SLong -> 4
SRational -> 8
| duboisf/ymrefiler | src/Data/Exif/Types.hs | bsd-3-clause | 7,926 | 0 | 9 | 2,137 | 1,322 | 780 | 542 | 224 | 35 |
{-# LANGUAGE OverloadedStrings #-}
module Netsuite.Connect (
retrieveNS,
fetchSublistNS,
rawSearchNS,
searchNS,
createNS,
attachNS,
detachNS,
updateNS,
updateSublistNS,
deleteNS,
invoicePdfNS,
transformNS,
NsFilters,
NsFilter (..),
NsSearchOp (..),
RestletError (..),
IsNsType,
IsNsSubtype,
IsNsId,
IsNsDataId,
IsNsFilter,
IsNsData,
IsNsSublistData,
IsNsRestletConfig,
toNsFilter
) where
import Data.Aeson
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Text.IO as TextIO
import Paths_netsuite (getDataFileName)
import Netsuite.Helpers
import Netsuite.Restlet
import Netsuite.Restlet.Configuration
import Netsuite.Restlet.Response
import Netsuite.Types.Compile
import Netsuite.Types.Data
-- | Retrieves an object from Netsuite.
retrieveNS
:: (IsNsRestletConfig cfg, IsNsType t, IsNsDataId a)
=> cfg -- ^ Restlet configuration
-> t -- ^ NetSuite entity type
-> a -- ^ Entity ID
-> IO (Either RestletError Value)
retrieveNS cfg t i =
doNS (toNsRestletConfig cfg) $
NsActRetrieve (toNsType t)
(toNsDataId i)
(typeFields (toNsRestletConfig cfg) $ toNsType t)
-- | Retrieves an object's sublists from Netsuite.
fetchSublistNS
:: (IsNsRestletConfig cfg, IsNsSubtype st, IsNsId a)
=> cfg -- ^ Restlet configuration
-> st -- ^ NetSuite entity subtype
-> a -- ^ Entity ID
-> IO (Either RestletError Value)
fetchSublistNS cfg st i =
doNS (toNsRestletConfig cfg) $
NsActFetchSublist (toNsSubtype st)
(toNsId i)
(typeFields (toNsRestletConfig cfg) $ toNsSubtype st)
-- | Does a raw search in Netsuite.
rawSearchNS
:: (IsNsRestletConfig cfg, IsNsType t, IsNsSearchCol c)
=> cfg -- ^ Restlet configuration
-> t -- ^ NetSuite entity type
-> NsFilters -- ^ Search filters
-> [c] -- ^ Columns to return
-> IO (Either RestletError Value)
rawSearchNS cfg t fil col =
doNS (toNsRestletConfig cfg) $
NsActRawSearch (toNsType t) fil (map toNsSearchCol col)
-- | Does an object search in Netsuite.
searchNS
:: (IsNsRestletConfig cfg, IsNsType t)
=> cfg -- ^ Restlet configuration
-> t -- ^ NetSuite entity type
-> NsFilters -- ^ Search filters
-> IO (Either RestletError Value)
searchNS cfg t fil =
doChunkableNS (toNsRestletConfig cfg) $
NsActSearch (toNsType t)
fil
(typeFields (toNsRestletConfig cfg) $ toNsType t)
-- | Creates an object in Netsuite.
createNS
:: (IsNsRestletConfig cfg, IsNsType t, IsNsData d, IsNsSublistData sd)
=> cfg -- ^ Restlet configuration
-> t -- ^ NetSuite entity type
-> d -- ^ Data to assign to new entity
-> sd -- ^ Sublist data to assign to new entity
-> IO (Either RestletError Value)
createNS cfg t d sd =
doNS (toNsRestletConfig cfg) $
NsActCreate (toNsType t)
(toNsData d)
(toNsSublistData sd)
(typeFields (toNsRestletConfig cfg) $ toNsType t)
-- | Attaches an object to another in Netsuite.
attachNS
:: (IsNsRestletConfig cfg, IsNsType t, IsNsId a, IsNsData d)
=> cfg -- ^ Restlet configuration
-> t -- ^ Type of entities to attach to
-> [a] -- ^ Target entity IDs to attach to
-> t -- ^ Type of entity to attach
-> a -- ^ Entity ID to attach
-> d -- ^ Data to assign to attachment
-> IO (Either RestletError Value)
attachNS cfg targetType targetIDs attType attID attrs =
doNS (toNsRestletConfig cfg) $
NsActAttach (toNsType targetType)
(map toNsId targetIDs)
(toNsType attType)
(toNsId attID)
(toNsData attrs)
-- | Detaches an object from another in Netsuite.
detachNS
:: (IsNsRestletConfig cfg, IsNsType t, IsNsId a)
=> cfg -- ^ Restlet configuration
-> t -- ^ Type of entities to detach from
-> [a] -- ^ Target entity IDs to detach from
-> t -- ^ Type of entity to detach
-> a -- ^ Entity ID to detach
-> IO (Either RestletError Value)
detachNS cfg targetType targetIDs detType detID =
doNS (toNsRestletConfig cfg) $
NsActDetach (toNsType targetType)
(map toNsId targetIDs)
(toNsType detType)
(toNsId detID)
-- | Updates an object in Netsuite.
updateNS
:: (IsNsRestletConfig cfg, IsNsType t, IsNsData d)
=> cfg -- ^ Restlet configuration
-> t -- ^ NetSuite entity type
-> d -- ^ Data to update entity with (must include ID)
-> IO (Either RestletError Value)
updateNS cfg t d =
if testNsDataForId $ toNsData d
then doNS (toNsRestletConfig cfg) $
NsActUpdate (toNsType t)
(toNsData d)
(typeFields (toNsRestletConfig cfg) $ toNsType t)
else error "Update data does not contain ID."
-- | Updates an object's sublist in Netsuite.
updateSublistNS
:: (IsNsRestletConfig cfg, IsNsSubtype st, IsNsId a, IsNsData d)
=> cfg -- ^ Restlet configuration
-> st -- ^ NetSuite entity subtype
-> a -- ^ Entity ID
-> [d] -- ^ List of sublist items to update sublist with
-> IO (Either RestletError Value)
updateSublistNS cfg st i d =
doNS (toNsRestletConfig cfg) $
NsActUpdateSublist (toNsSubtype st) (toNsId i) (map toNsData d)
-- | Deletes an object from Netsuite.
deleteNS
:: (IsNsRestletConfig cfg, IsNsType t, IsNsDataId a)
=> cfg -- ^ Restlet configuration
-> t -- ^ NetSuite entity type
-> a -- ^ Entity ID to delete
-> IO (Either RestletError Value)
deleteNS cfg t i =
doNS (toNsRestletConfig cfg) $
NsActDelete (toNsType t) (toNsDataId i)
-- | Fetches an Invoice PDF by ID.
invoicePdfNS
:: (IsNsRestletConfig cfg, IsNsId a)
=> cfg -- ^ Restlet configuration
-> a -- ^ Invoice entity ID
-> IO (Either RestletError Value)
invoicePdfNS cfg i =
doNS (toNsRestletConfig cfg) $
NsActInvoicePDF (toNsId i)
-- | Transforms a Netsuite record to another type.
transformNS
:: (IsNsRestletConfig cfg, IsNsType t, IsNsId a, IsNsData d)
=> cfg -- ^ Restlet configuration
-> t -- ^ NetSuite entity source type (what you're transforming from)
-> a -- ^ Entity ID
-> t -- ^ NetSuite entity target type (what you're transforming into)
-> d -- ^ Data to be used in this transformation
-> IO (Either RestletError Value)
transformNS cfg st sid tt d =
doNS (toNsRestletConfig cfg) $
NsActTransform (toNsType st)
(toNsId sid)
(toNsType tt)
(toNsData d)
(typeFields (toNsRestletConfig cfg) $ toNsType tt)
-- | Performs a Netsuite restlet action with the normal runner.
doNS
:: NsRestletConfig -- ^ Restlet configuration
-> (NsRestletCode -> NsAction)
-> IO (Either RestletError Value)
doNS = runAction restletExecute
-- | Performs a Netsuite restlet action with the chunkable runner.
doChunkableNS
:: NsRestletConfig -- ^ Restlet configuration
-> (NsRestletCode -> NsAction) -- ^ Partial action that requires
-- restlet code
-> IO (Either RestletError Value)
doChunkableNS = runAction chunkableRestletExecute
-- | Runs a generic action
runAction
:: (String -> NsRestletConfig -> IO RestletResponse) -- Restlet runner
-> NsRestletConfig -- ^ Restlet configuration
-> (NsRestletCode -> NsAction) -- ^ Partial action that requires
-- restlet code
-> IO (Either RestletError Value)
runAction runner cfg act = do
code <- restletCode
let actJSON = reqJSON . act . NsRestletCode $ code
result <- runner actJSON cfg
return $ case result of
RestletErrorResp{} -> Left $ interpretError result
_ -> Right $ responseToAeson result
where
reqJSON = bytesToString . BSL.unpack . encode
restletCode = getDataFileName "Support/Restlet.js" >>= TextIO.readFile
| anchor/haskell-netsuite | lib/Netsuite/Connect.hs | bsd-3-clause | 8,133 | 0 | 14 | 2,269 | 1,862 | 985 | 877 | 202 | 2 |
{-# LANGUAGE FlexibleInstances, TemplateHaskell, TypeFamilies #-}
module GHC.Generics.Instances.TH where
import GHC.Generics
import Language.Haskell.TH
import Language.Haskell.TH.Lift
-- | Build a set of Generic instances for opaque types
buildOpaque :: Name -> DecsQ
buildOpaque n = do
let name = nameBase n
dshadow = mkName $ "D_" ++ name
cshadow = mkName $ "C_" ++ name
mname <- case nameModule n of
(Just m) -> return m
Nothing -> report False "No Module in Name..." >> return ""
instDecls <- [d|
instance Datatype $(conT dshadow) where
datatypeName _ = $(lift name)
moduleName _ = $(lift mname)
instance Constructor $(conT cshadow) where
conName _ = "" -- JPM: I'm not sure this is the right implementation...
|]
repType <- [t| D1 $(conT dshadow) (C1 $(conT cshadow) (S1 NoSelector (Rec0 $(conT n)))) |]
[(FunD _ fromClauses), (FunD _ toClauses)] <- [d|
from x = M1 (M1 (M1 (K1 x)))
to (M1 (M1 (M1 (K1 x)))) = x
|]
return $
[ DataD [] dshadow [] [] []
, DataD [] cshadow [] [] []
-- This really should be quote-able, but TH is kinda stupid about type families.
, InstanceD [] (AppT (ConT ''Generic) (ConT n))
[ TySynInstD (''Rep) [ConT n] repType
, FunD 'from fromClauses
, FunD 'to toClauses
]
] ++ instDecls | mgsloan/generic-orphans | src/GHC/Generics/Instances/TH.hs | bsd-3-clause | 1,338 | 0 | 15 | 333 | 314 | 168 | 146 | 31 | 2 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, ScopedTypeVariables, UndecidableInstances, CPP #-}
-----------------------------------------------------------------------------
{- |
Module : Control.Parallel.MPI.Fast
Copyright : (c) 2010 Bernie Pope, Dmitry Astapov
License : BSD-style
Maintainer : [email protected]
Stability : experimental
Portability : ghc
This module provides the ability to transfer via MPI any Haskell value that could be
represented by some MPI type without expensive conversion or serialization.
Most of the \"primitive\" Haskell types could be treated this way, along with Storable and IO Arrays. Full range of point-to-point and collective operation is supported, including for reduce and similar operations.
Typeclass 'SendFrom' incapsulates the act of representing Haskell value as a flat memory region that could be used as a \"send buffer\" in MPI calls.
Likewise, 'RecvInto' captures the rules for using Haskell value as a \"receive buffer\" in MPI calls.
Correspondence between Haskell types and MPI types is encoded in 'Repr' typeclass.
Below is a small but complete MPI program utilising this Module. Process 0 sends the array of @Int@s
process 1. Process 1 receives the message and prints it
to standard output. It assumes that there are at least 2 MPI processes
available. Further examples in this module would provide different implementation of
@process@ function.
@
\{\-\# LANGUAGE ScopedTypeVariables \#\-\}
module Main where
import Control.Parallel.MPI.Fast
import Data.Array.Storable
type ArrMsg = StorableArray Int Int
bounds :: (Int, Int)
bounds = (1,10)
arrMsg :: IO (StorableArray Int Int)
arrMsg = newListArray bounds [1..10]
main :: IO ()
main = mpi $ do
rank <- commRank commWorld
process rank
process :: Rank -> IO ()
process rank
| rank == 0 = do sendMsg <- arrMsg
send commWorld 1 2 sendMsg
| rank == 1 = do (recvMsg::ArrMsg, status) <- intoNewArray bounds $ recv commWorld 0 2
els <- getElems recvMsg
putStrLn $ \"Got message: \" ++ show els
| otherwise = return ()
@
-}
-----------------------------------------------------------------------------
module Control.Parallel.MPI.Fast
(
-- * Mapping between Haskell and MPI types
Repr (..)
-- * Treating Haskell values as send or receive buffers
, SendFrom (..)
, RecvInto (..)
-- * On-the-fly buffer allocation helpers
, intoNewArray
, intoNewArray_
, intoNewVal
, intoNewVal_
, intoNewBS
, intoNewBS_
-- * Point-to-point operations.
-- ** Blocking.
, send
, ssend
, rsend
, recv
-- ** Non-blocking.
, isend
, issend
, irecv
, isendPtr
, issendPtr
, irecvPtr
, waitall
-- * Collective operations.
-- ** One-to-all.
, bcastSend
, bcastRecv
, scatterSend
, scatterRecv
, scattervSend
, scattervRecv
-- ** All-to-one.
, gatherSend
, gatherRecv
, gathervSend
, gathervRecv
, reduceSend
, reduceRecv
-- ** All-to-all.
, allgather
, allgatherv
, alltoall
, alltoallv
, allreduce
, reduceScatterBlock
, reduceScatter
, opCreate
, Internal.opFree
, module Data.Word
, module Control.Parallel.MPI.Base
) where
#include "MachDeps.h"
import Data.Array.Base (unsafeNewArray_)
import Data.Array.IO
import Data.Array.Storable
import Control.Applicative ((<$>))
import Data.ByteString.Unsafe as BS
import qualified Data.ByteString as BS
import qualified Control.Parallel.MPI.Internal as Internal
import Control.Parallel.MPI.Base
import Data.Int()
import Data.Word
import Foreign
import Foreign.C.Types
{-
In-place receive vs new array allocation for Storable Array
-----------------------------------------------------------
When using StorableArray API in tight numeric loops, it is best to
reuse existing arrays and avoid penalties incurred by
allocation/deallocation of memory. Which is why destinations/receive
buffers in StorableArray API are specified exclusively as
(StorableArray i e).
If you'd rather allocate new array for a particular operation, you
could use withNewArray/withNewArray_:
Instead of (recv comm rank tag arr) you would write
(arr <- withNewArray bounds $ recv comm rank tag), and new array would
be allocated, supplied as the target of the (recv) operation and
returned to you.
You could easily write your own convenience wrappers similar to
withNewArray. For example, you could create wrapper that would take an
array size as a simple number instead of range.
-}
{- | Helper wrapper function that would allocate array of the given size and use it as receive buffer, without the need to
preallocate it explicitly.
Most of the functions in this API could reuse receive buffer (like 'StorableArray') over and over again.
If you do not have preallocated buffer you could use this wrapper to get yourself one.
Consider the following code that uses preallocated buffer:
@
scattervRecv root comm arr
@
Same code with buffer allocation:
@
(arr,status) <- intoNewArray range $ scattervRecv root comm
@
-}
intoNewArray :: (Ix i, MArray a e m, RecvInto (a i e)) => (i, i) -> (a i e -> m r) -> m (a i e, r)
intoNewArray range f = do
arr <- unsafeNewArray_ range -- New, uninitialized array, According to http://hackage.haskell.org/trac/ghc/ticket/3586
-- should be faster than newArray_
res <- f arr
return (arr, res)
-- | Variant of 'intoNewArray' that discards the result of the wrapped function.
-- Useful for discarding @()@ from functions like 'scatterSend' that return @IO ()@
intoNewArray_ :: (Ix i, MArray a e m, RecvInto (a i e)) => (i, i) -> (a i e -> m r) -> m (a i e)
intoNewArray_ range f = do
arr <- unsafeNewArray_ range
_ <- f arr
return arr
-- | Sends @v@ to the process identified by @(Comm, Rank, Tag)@. Call will return as soon as MPI has copied data from its internal send buffer.
send :: (SendFrom v) => Comm -> Rank -> Tag -> v -> IO ()
send = sendWith Internal.send
-- | Sends @v@ to the process identified by @(Comm, Rank, Tag)@. Call will return as soon as receiving process started receiving data.
ssend :: (SendFrom v) => Comm -> Rank -> Tag -> v -> IO ()
ssend = sendWith Internal.ssend
-- | Sends @v@ to the process identified by @(Comm, Rank, Tag)@. Matching 'recv' should already be posted, otherwise MPI error could occur.
rsend :: (SendFrom v) => Comm -> Rank -> Tag -> v -> IO ()
rsend = sendWith Internal.rsend
type SendPrim = Ptr () -> CInt -> Datatype -> Rank -> Tag -> Comm -> IO ()
sendWith :: (SendFrom v) => SendPrim -> Comm -> Rank -> Tag -> v -> IO ()
sendWith send_function comm rank tag val = do
sendFrom val $ \valPtr numBytes dtype -> do
send_function (castPtr valPtr) numBytes dtype rank tag comm
-- | Receives data from the process identified by @(Comm, Rank, Tag)@ and store it in @v@.
recv :: (RecvInto v) => Comm -> Rank -> Tag -> v -> IO Status
recv comm rank tag arr = do
recvInto arr $ \valPtr numBytes dtype ->
Internal.recv (castPtr valPtr) numBytes dtype rank tag comm
-- | \"Root\" process identified by @(Comm, Rank)@ sends value of @v@ to all processes in communicator @Comm@.
bcastSend :: (SendFrom v) => Comm -> Rank -> v -> IO ()
bcastSend comm sendRank val = do
sendFrom val $ \valPtr numBytes dtype -> do
Internal.bcast (castPtr valPtr) numBytes dtype sendRank comm
-- | Receive data distributed via 'bcaseSend' and store it in @v@.
bcastRecv :: (RecvInto v) => Comm -> Rank -> v -> IO ()
bcastRecv comm sendRank val = do
recvInto val $ \valPtr numBytes dtype -> do
Internal.bcast (castPtr valPtr) numBytes dtype sendRank comm
-- | Sends @v@ to the process identified by @(Comm, Rank, Tag)@ in non-blocking mode. @Request@ will be considered complete as soon as MPI copies the data from the send buffer. Use 'probe', 'test', 'cancel' or 'wait' to work with @Request@.
isend :: (SendFrom v) => Comm -> Rank -> Tag -> v -> IO Request
isend = isendWith Internal.isend
-- | Sends @v@ to the process identified by @(Comm, Rank, Tag)@ in non-blocking mode. @Request@ will be considered complete as soon as receiving process starts to receive data.
issend :: (SendFrom v) => Comm -> Rank -> Tag -> v -> IO Request
issend = isendWith Internal.issend
type ISendPrim = Ptr () -> CInt -> Datatype -> Rank -> Tag -> Comm -> IO (Request)
isendWith :: (SendFrom v) => ISendPrim -> Comm -> Rank -> Tag -> v -> IO Request
isendWith send_function comm recvRank tag val = do
sendFrom val $ \valPtr numBytes dtype -> do
send_function valPtr numBytes dtype recvRank tag comm
-- | Variant of 'isend' that stores @Request@ at the provided pointer. Useful for filling up arrays of @Request@s that would later be fed to 'waitall'.
isendPtr :: (SendFrom v) => Comm -> Rank -> Tag -> Ptr Request -> v -> IO ()
isendPtr = isendWithPtr Internal.isendPtr
-- | Variant of 'issend' that stores @Request@ at the provided pointer. Useful for filling up arrays of @Request@s that would later be fed to 'waitall'.
issendPtr :: (SendFrom v) => Comm -> Rank -> Tag -> Ptr Request -> v -> IO ()
issendPtr = isendWithPtr Internal.issendPtr
type ISendPtrPrim = Ptr () -> CInt -> Datatype -> Rank -> Tag -> Comm -> Ptr Request -> IO ()
isendWithPtr :: (SendFrom v) => ISendPtrPrim -> Comm -> Rank -> Tag -> Ptr Request -> v -> IO ()
isendWithPtr send_function comm recvRank tag requestPtr val = do
sendFrom val $ \valPtr numBytes dtype ->
send_function (castPtr valPtr) numBytes dtype recvRank tag comm requestPtr
-- | Variant of 'irecv' that stores @Request@ at the provided pointer.
irecvPtr :: (Storable e, Ix i, Repr e) => Comm -> Rank -> Tag -> Ptr Request -> StorableArray i e -> IO ()
irecvPtr comm sendRank tag requestPtr recvVal = do
recvInto recvVal $ \recvPtr recvElements recvType -> do
Internal.irecvPtr (castPtr recvPtr) recvElements recvType sendRank tag comm requestPtr
{-| Receive 'StorableArray' from the process identified by @(Comm, Rank, Tag)@ in non-blocking mode.
At the moment we are limiting this to 'StorableArray's because they
are compatible with C pointers. This means that the recieved data can
be written directly to the array, and does not have to be copied out
at the end. This is important for the non-blocking operation of @irecv@.
It is not safe to copy the data from the C pointer until the transfer
is complete. So any array type which requires copying of data after
receipt of the message would have to wait on complete transmission.
It is not clear how to incorporate the waiting automatically into
the same interface as the one below. One option is to use a Haskell
thread to do the data copying in the \"background\" (as was done for 'Simple.irecv'). Another option
is to introduce a new kind of data handle which would encapsulate the
wait operation, and would allow the user to request the data to be
copied when the wait was complete.
-}
irecv :: (Storable e, Ix i, Repr e) => Comm -> Rank -> Tag -> StorableArray i e -> IO Request
irecv comm sendRank tag recvVal = do
recvInto recvVal $ \recvPtr recvElements recvType -> do
Internal.irecv (castPtr recvPtr) recvElements recvType sendRank tag comm
-- | Wrapper around 'Internal.waitall' that operates on 'StorableArray's
waitall :: StorableArray Int Request -> StorableArray Int Status -> IO ()
waitall requests statuses = do
cnt <- rangeSize <$> getBounds requests
withStorableArray requests $ \reqs ->
withStorableArray statuses $ \stats ->
Internal.waitall (fromIntegral cnt) (castPtr reqs) (castPtr stats)
-- | Scatter elements of @v1@ to all members of communicator @Comm@ from the \"root\" process identified by @Rank@. Receive own slice of data
-- in @v2@. Note that when @Comm@ is inter-communicator, @Rank@ could differ from the rank of the calling process.
scatterSend :: (SendFrom v1, RecvInto v2) => Comm -> Rank -> v1 -> v2 -> IO ()
scatterSend comm root sendVal recvVal = do
recvInto recvVal $ \recvPtr recvElements recvType ->
sendFrom sendVal $ \sendPtr _ _ ->
Internal.scatter (castPtr sendPtr) recvElements recvType (castPtr recvPtr) recvElements recvType root comm
-- | Receive the slice of data scattered from \"root\" process identified by @(Comm, Rank)@ and store it into @v@.
scatterRecv :: (RecvInto v) => Comm -> Rank -> v -> IO ()
scatterRecv comm root recvVal = do
recvInto recvVal $ \recvPtr recvElements recvType ->
Internal.scatter nullPtr 0 byte (castPtr recvPtr) recvElements recvType root comm
-- | Variant of 'scatterSend' that allows to send data in uneven chunks.
-- Since interface is tailored for speed, @counts@ and @displacements@ should be in 'StorableArray's.
scattervSend :: (SendFrom v1, RecvInto v2) => Comm
-> Rank
-> v1 -- ^ Value (vector) to send from
-> StorableArray Int CInt -- ^ Length of each segment (in elements)
-> StorableArray Int CInt -- ^ Offset of each segment from the beginning of @v1@ (in elements)
-> v2
-> IO ()
scattervSend comm root sendVal counts displacements recvVal = do
-- myRank <- commRank comm
-- XXX: assert myRank == sendRank ?
recvInto recvVal $ \recvPtr recvElements recvType ->
sendFrom sendVal $ \sendPtr _ sendType->
withStorableArray counts $ \countsPtr ->
withStorableArray displacements $ \displPtr ->
Internal.scatterv (castPtr sendPtr) countsPtr displPtr sendType
(castPtr recvPtr) recvElements recvType root comm
-- | Variant of 'scatterRecv', to be used with 'scattervSend'
scattervRecv :: (RecvInto v) => Comm -> Rank -> v -> IO ()
scattervRecv comm root arr = do
-- myRank <- commRank comm
-- XXX: assert (myRank /= sendRank)
recvInto arr $ \recvPtr recvElements recvType ->
Internal.scatterv nullPtr nullPtr nullPtr byte (castPtr recvPtr) recvElements recvType root comm
{-
XXX we should check that the recvArray is large enough to store:
segmentSize * commSize
-}
-- | \"Root\" process identified by @(Comm, Rank)@ collects data sent via 'gatherSend' and stores them in @v2@. Collecting process supplies
-- its own share of data in @v1@.
gatherRecv :: (SendFrom v1, RecvInto v2) => Comm -> Rank -> v1 -> v2 -> IO ()
gatherRecv comm root segment recvVal = do
-- myRank <- commRank comm
-- XXX: assert myRank == root
sendFrom segment $ \sendPtr sendElements sendType ->
recvInto recvVal $ \recvPtr _ _ ->
Internal.gather (castPtr sendPtr) sendElements sendType (castPtr recvPtr) sendElements sendType root comm
-- | Send value of @v@ to the \"root\" process identified by @(Comm, Rank)@, to be collected with 'gatherRecv'.
gatherSend :: (SendFrom v) => Comm -> Rank -> v -> IO ()
gatherSend comm root segment = do
-- myRank <- commRank comm
-- XXX: assert it is /= root
sendFrom segment $ \sendPtr sendElements sendType ->
-- the recvPtr is ignored in this case, so we can make it NULL, likewise recvCount can be 0
Internal.gather (castPtr sendPtr) sendElements sendType nullPtr 0 byte root comm
-- | Variant of 'gatherRecv' that allows to collect data segments of uneven size (see 'scattervSend' for details)
gathervRecv :: (SendFrom v1, RecvInto v2) => Comm -> Rank -> v1 ->
StorableArray Int CInt -> StorableArray Int CInt -> v2 -> IO ()
gathervRecv comm root segment counts displacements recvVal = do
-- myRank <- commRank comm
-- XXX: assert myRank == root
sendFrom segment $ \sendPtr sendElements sendType ->
withStorableArray counts $ \countsPtr ->
withStorableArray displacements $ \displPtr ->
recvInto recvVal $ \recvPtr _ recvType->
Internal.gatherv (castPtr sendPtr) sendElements sendType
(castPtr recvPtr) countsPtr displPtr recvType
root comm
-- | Variant of 'gatherSend', to be used with 'gathervRecv'.
gathervSend :: (SendFrom v) => Comm -> Rank -> v -> IO ()
gathervSend comm root segment = do
-- myRank <- commRank comm
-- XXX: assert myRank == root
sendFrom segment $ \sendPtr sendElements sendType ->
-- the recvPtr, counts and displacements are ignored in this case, so we can make it NULL
Internal.gatherv (castPtr sendPtr) sendElements sendType nullPtr nullPtr nullPtr byte root comm
{- | A variation of 'gatherSend' and 'gatherRecv' where all members of
a group receive the result.
Caller is expected to make sure that types of send and receive buffers
are selected in a way such that amount of bytes sent equals amount of bytes received pairwise between all processes.
-}
allgather :: (SendFrom v1, RecvInto v2) => Comm -> v1 -> v2 -> IO ()
allgather comm sendVal recvVal = do
sendFrom sendVal $ \sendPtr sendElements sendType ->
recvInto recvVal $ \recvPtr _ _ -> -- Since amount sent equals amount received
Internal.allgather (castPtr sendPtr) sendElements sendType (castPtr recvPtr) sendElements sendType comm
-- | A variation of 'allgather' that allows to use data segments of
-- different length.
allgatherv :: (SendFrom v1, RecvInto v2) => Comm
-> v1 -- ^ Send buffer
-> StorableArray Int CInt -- ^ Lengths of segments in the send buffer
-> StorableArray Int CInt -- ^ Displacements of the segments in the send buffer
-> v2 -- ^ Receive buffer
-> IO ()
allgatherv comm segment counts displacements recvVal = do
sendFrom segment $ \sendPtr sendElements sendType ->
withStorableArray counts $ \countsPtr ->
withStorableArray displacements $ \displPtr ->
recvInto recvVal $ \recvPtr _ recvType ->
Internal.allgatherv (castPtr sendPtr) sendElements sendType (castPtr recvPtr) countsPtr displPtr recvType comm
{- | Scatter/Gather data from all
members to all members of a group (also called complete exchange).
Caller is expected to make sure that types of send and receive buffers and send/receive counts
are selected in a way such that amount of bytes sent equals amount of bytes received pairwise between all processes.
-}
alltoall :: (SendFrom v1, RecvInto v2) => Comm
-> v1 -- ^ Send buffer
-> Int -- ^ How many elements to /send/ to each process
-> Int -- ^ How many elements to /receive/ from each process
-> v2 -- ^ Receive buffer
-> IO ()
alltoall comm sendVal sendCount recvCount recvVal =
sendFrom sendVal $ \sendPtr _ sendType ->
recvInto recvVal $ \recvPtr _ recvType -> -- Since amount sent must equal amount received
Internal.alltoall (castPtr sendPtr) (fromIntegral sendCount) sendType (castPtr recvPtr) (fromIntegral recvCount) recvType comm
-- | A variation of 'alltoall' that allows to use data segments of
-- different length.
alltoallv :: (SendFrom v1, RecvInto v2) => Comm
-> v1 -- ^ Send buffer
-> StorableArray Int CInt -- ^ Lengths of segments in the send buffer
-> StorableArray Int CInt -- ^ Displacements of the segments in the send buffer
-> StorableArray Int CInt -- ^ Lengths of segments in the receive buffer
-> StorableArray Int CInt -- ^ Displacements of the segments in the receive buffer
-> v2 -- ^ Receive buffer
-> IO ()
alltoallv comm sendVal sendCounts sendDisplacements recvCounts recvDisplacements recvVal = do
sendFrom sendVal $ \sendPtr _ sendType ->
recvInto recvVal $ \recvPtr _ recvType ->
withStorableArray sendCounts $ \sendCountsPtr ->
withStorableArray sendDisplacements $ \sendDisplPtr ->
withStorableArray recvCounts $ \recvCountsPtr ->
withStorableArray recvDisplacements $ \recvDisplPtr ->
Internal.alltoallv (castPtr sendPtr) sendCountsPtr sendDisplPtr sendType
(castPtr recvPtr) recvCountsPtr recvDisplPtr recvType comm
{-| Reduce values from a group of processes into single value, which is delivered to single (so-called root) process.
See 'reduceRecv' for function that should be called by root process.
If the value is scalar, then reduction is similar to 'fold1'. For example, if the opreration is 'sumOp', then
@reduceSend@ would compute sum of values supplied by all processes.
-}
reduceSend :: SendFrom v => Comm
-> Rank -- ^ Rank of the root process
-> Operation -- ^ Reduction operation
-> v -- ^ Value supplied by this process
-> IO ()
reduceSend comm root op sendVal = do
sendFrom sendVal $ \sendPtr sendElements sendType ->
Internal.reduce (castPtr sendPtr) nullPtr sendElements sendType op root comm
{-| Obtain result of reduction initiated by 'reduceSend'. Note that root process supplies value for reduction as well.
-}
reduceRecv :: (SendFrom v, RecvInto v) => Comm
-> Rank -- ^ Rank of the root process
-> Operation -- ^ Reduction operation
-> v -- ^ Value supplied by this process
-> v -- ^ Reduction result
-> IO ()
reduceRecv comm root op sendVal recvVal =
sendFrom sendVal $ \sendPtr sendElements sendType ->
recvInto recvVal $ \recvPtr _ _ ->
Internal.reduce (castPtr sendPtr) (castPtr recvPtr) sendElements sendType op root comm
-- | Variant of 'reduceSend' and 'reduceRecv', where result is delivered to all participating processes.
allreduce :: (SendFrom v, RecvInto v) =>
Comm -- ^ Communicator engaged in reduction/
-> Operation -- ^ Reduction operation
-> v -- ^ Value supplied by this process
-> v -- ^ Reduction result
-> IO ()
allreduce comm op sendVal recvVal =
sendFrom sendVal $ \sendPtr sendElements sendType ->
recvInto recvVal $ \recvPtr _ _ ->
Internal.allreduce (castPtr sendPtr) (castPtr recvPtr) sendElements sendType op comm
-- | Combination of 'reduceSend' + 'reduceRecv' and 'scatterSend' + 'scatterRecv': reduction result
-- is split and scattered among participating processes.
--
-- See 'reduceScatter' if you want to be able to specify personal block size for each process.
--
-- Note that this function is not supported with OpenMPI 1.5
reduceScatterBlock :: (SendFrom v, RecvInto v) =>
Comm -- ^ Communicator engaged in reduction/
-> Operation -- ^ Reduction operation
-> Int -- ^ Size of the result block sent to each process
-> v -- ^ Value supplied by this process
-> v -- ^ Reduction result
-> IO ()
reduceScatterBlock comm op blocksize sendVal recvVal =
sendFrom sendVal $ \sendPtr _ sendType ->
recvInto recvVal $ \recvPtr _ _ ->
Internal.reduceScatterBlock (castPtr sendPtr) (castPtr recvPtr) (fromIntegral blocksize :: CInt) sendType op comm
-- | Combination of 'reduceSend' / 'reduceRecv' and 'scatterSend' / 'scatterRecv': reduction result
-- is split and scattered among participating processes.
reduceScatter :: (SendFrom v, RecvInto v) =>
Comm -- ^ Communicator engaged in reduction/
-> Operation -- ^ Reduction operation
-> StorableArray Int CInt -- ^ Sizes of block distributed to each process
-> v -- ^ Value supplied by this process
-> v -- ^ Reduction result
-> IO ()
reduceScatter comm op counts sendVal recvVal =
sendFrom sendVal $ \sendPtr _ sendType ->
recvInto recvVal $ \recvPtr _ _ ->
withStorableArray counts $ \countsPtr ->
Internal.reduceScatter (castPtr sendPtr) (castPtr recvPtr) countsPtr sendType op comm
-- | How many (consecutive) elements of given datatype do we need to represent given
-- the Haskell type in MPI operations
class Repr e where
representation :: e -> (Int, Datatype)
-- | Representation is one 'unsigned'
instance Repr Bool where
representation _ = (1,unsigned)
-- | Note that C @int@ is alway 32-bit, while Haskell @Int@ size is platform-dependent. Therefore on 32-bit platforms 'int'
-- is used to represent 'Int', and on 64-bit platforms 'longLong' is used
instance Repr Int where
#if SIZEOF_HSINT == 4
representation _ = (1,int)
#elif SIZEOF_HSINT == 8
representation _ = (1,longLong)
#else
#error Haskell MPI bindings not tested on architecture where size of Haskell Int is not 4 or 8
#endif
-- | Representation is one 'byte'
instance Repr Int8 where
representation _ = (1,byte)
-- | Representation is one 'short'
instance Repr Int16 where
representation _ = (1,short)
-- | Representation is one 'int'
instance Repr Int32 where
representation _ = (1,int)
-- | Representation is one 'longLong'
instance Repr Int64 where
representation _ = (1,longLong)
-- | Representation is one 'int'
instance Repr CInt where
representation _ = (1,int)
-- | Representation is either one 'int' or one 'longLong', depending on the platform. See comments for @Repr Int@.
instance Repr Word where
#if SIZEOF_HSINT == 4
representation _ = (1,unsigned)
#else
representation _ = (1,unsignedLongLong)
#endif
-- | Representation is one 'byte'
instance Repr Word8 where
representation _ = (1,byte)
-- | Representation is one 'unsignedShort'
instance Repr Word16 where
representation _ = (1,unsignedShort)
-- | Representation is one 'unsigned'
instance Repr Word32 where
representation _ = (1,unsigned)
-- | Representation is one 'unsignedLongLong'
instance Repr Word64 where
representation _ = (1,unsignedLongLong)
-- | Representation is one 'wchar'
instance Repr Char where
representation _ = (1,wchar)
-- | Representation is one 'char'
instance Repr CChar where
representation _ = (1,char)
-- | Representation is one 'double'
instance Repr Double where
representation _ = (1,double)
-- | Representation is one 'float'
instance Repr Float where
representation _ = (1,float)
instance Repr e => Repr (StorableArray i e) where
representation _ = representation (undefined::e)
instance Repr e => Repr (IOArray i e) where
representation _ = representation (undefined::e)
instance Repr e => Repr (IOUArray i e) where
representation _ = representation (undefined::e)
{- | Treat @v@ as send buffer suitable for the purposes of this API.
Method 'sendFrom' is expected to deduce how to use @v@ as a memory-mapped buffer that consist of a number of
elements of some 'Datatype'. It would then call the supplied function, passing it the pointer to the buffer,
its size (in elements) and type of the element.
Note that @e@ is not bound by the typeclass, so all kinds of foul play
are possible. However, since MPI declares all buffers as @void*@ anyway,
we are not making life all /that/ unsafe with this.
-}
class SendFrom v where
sendFrom :: v -- ^ Value to use as send buffer
-> (Ptr e -> CInt -> Datatype -> IO a) -- ^ Function that will accept pointer to buffer, its length and type of buffer elements
-> IO a
{- | Treat @v@ as receive buffer for the purposes of this API.
-}
class RecvInto v where
recvInto :: v -- ^ Value to use as receive buffer
-> (Ptr e -> CInt -> Datatype -> IO a) -- ^ Function that will accept pointer to buffer, its length and type of buffer elements
-> IO a
-- Sending from a single Storable values
instance SendFrom CInt where
sendFrom = sendFromSingleValue
instance SendFrom Int where
sendFrom = sendFromSingleValue
instance SendFrom Int8 where
sendFrom = sendFromSingleValue
instance SendFrom Int16 where
sendFrom = sendFromSingleValue
instance SendFrom Int32 where
sendFrom = sendFromSingleValue
instance SendFrom Int64 where
sendFrom = sendFromSingleValue
instance SendFrom Word where
sendFrom = sendFromSingleValue
instance SendFrom Word8 where
sendFrom = sendFromSingleValue
instance SendFrom Word16 where
sendFrom = sendFromSingleValue
instance SendFrom Word32 where
sendFrom = sendFromSingleValue
instance SendFrom Word64 where
sendFrom = sendFromSingleValue
instance SendFrom Bool where
sendFrom = sendFromSingleValue
instance SendFrom Float where
sendFrom = sendFromSingleValue
instance SendFrom Double where
sendFrom = sendFromSingleValue
instance SendFrom Char where
sendFrom = sendFromSingleValue
instance SendFrom CChar where
sendFrom = sendFromSingleValue
sendFromSingleValue :: (Repr v, Storable v) => v -> (Ptr e -> CInt -> Datatype -> IO a) -> IO a
sendFromSingleValue v f = do
alloca $ \ptr -> do
poke ptr v
let (1, dtype) = representation v
f (castPtr ptr) (1::CInt) dtype
-- | Sending from Storable arrays requres knowing MPI representation 'Repr' of its elements. This is very
-- fast and efficient, since array would be updated in-place.
instance (Storable e, Repr e, Ix i) => SendFrom (StorableArray i e) where
sendFrom = withStorableArrayAndSize
-- | Receiving into Storable arrays requres knowing MPI representation 'Repr' of its elements. This is very
-- fast and efficient, since array would be updated in-place.
instance (Storable e, Repr e, Ix i) => RecvInto (StorableArray i e) where
recvInto = withStorableArrayAndSize
withStorableArrayAndSize :: forall a i e z.(Repr e, Storable e, Ix i) => StorableArray i e -> (Ptr z -> CInt -> Datatype -> IO a) -> IO a
withStorableArrayAndSize arr f = do
rSize <- rangeSize <$> getBounds arr
let (scale, dtype) = (representation (undefined :: StorableArray i e))
numElements = fromIntegral (rSize * scale)
withStorableArray arr $ \ptr -> f (castPtr ptr) numElements dtype
-- | This is less efficient than using 'StorableArray'
-- since extra memory copy is required to represent array as continuous memory buffer.
instance (Storable e, Repr (IOArray i e), Ix i) => SendFrom (IOArray i e) where
sendFrom = sendWithMArrayAndSize
-- | This is less efficient than using 'StorableArray'
-- since extra memory copy is required to construct the resulting array.
instance (Storable e, Repr (IOArray i e), Ix i) => RecvInto (IOArray i e) where
recvInto = recvWithMArrayAndSize
recvWithMArrayAndSize :: forall i e r a z. (Storable e, Ix i, MArray a e IO, Repr (a i e)) => a i e -> (Ptr z -> CInt -> Datatype -> IO r) -> IO r
recvWithMArrayAndSize array f = do
bounds <- getBounds array
let (scale, dtype) = representation (undefined :: a i e)
numElements = fromIntegral $ rangeSize bounds * scale
allocaArray (rangeSize bounds) $ \ptr -> do
result <- f (castPtr ptr) numElements dtype
fillArrayFromPtr (range bounds) (rangeSize bounds) ptr array
return result
sendWithMArrayAndSize :: forall i e r a z. (Storable e, Ix i, MArray a e IO, Repr (a i e)) => a i e -> (Ptr z -> CInt -> Datatype -> IO r) -> IO r
sendWithMArrayAndSize array f = do
elements <- getElems array
bounds <- getBounds array
let (scale, dtype) = representation (undefined :: a i e)
numElements = fromIntegral $ rangeSize bounds * scale
withArray elements $ \ptr -> f (castPtr ptr) numElements dtype
-- XXX I wonder if this can be written without the intermediate list?
-- Maybe GHC can elimiate it. We should look at the generated compiled
-- code to see how well the loop is handled.
fillArrayFromPtr :: (MArray a e IO, Storable e, Ix i) => [i] -> Int -> Ptr e -> a i e -> IO ()
fillArrayFromPtr indices numElements startPtr array = do
elems <- peekArray numElements startPtr
mapM_ (\(index, element) -> writeArray array index element ) (zip indices elems)
-- | Sending from ByteString is efficient, since it already has the necessary memory layout.
instance SendFrom BS.ByteString where
sendFrom = sendWithByteStringAndSize
sendWithByteStringAndSize :: BS.ByteString -> (Ptr z -> CInt -> Datatype -> IO a) -> IO a
sendWithByteStringAndSize bs f = do
unsafeUseAsCStringLen bs $ \(bsPtr,len) -> f (castPtr bsPtr) (fromIntegral len) byte
-- | Receiving into pointers to 'Storable' scalars with known MPI representation
instance (Storable e, Repr e) => RecvInto (Ptr e) where
recvInto = recvIntoElemPtr (representation (undefined :: e))
where
recvIntoElemPtr (cnt,datatype) p f = f (castPtr p) (fromIntegral cnt) datatype
-- | Receiving into pointers to 'Storable' vectors with known MPI representation and length
instance (Storable e, Repr e) => RecvInto (Ptr e, Int) where
recvInto = recvIntoVectorPtr (representation (undefined :: e))
where
recvIntoVectorPtr (scale, datatype) (p,len) f = f (castPtr p) (fromIntegral (len * scale) :: CInt) datatype
-- | Allocate new 'Storable' value and use it as receive buffer
intoNewVal :: (Storable e) => (Ptr e -> IO r) -> IO (e, r)
intoNewVal f = do
alloca $ \ptr -> do
res <- f ptr
val <- peek ptr
return (val, res)
-- | Variant of 'intoNewVal' that discards result of the wrapped function
intoNewVal_ :: (Storable e) => (Ptr e -> IO r) -> IO e
intoNewVal_ f = do
(val, _) <- intoNewVal f
return val
-- | Allocate new 'ByteString' of the given length and use it as receive buffer
intoNewBS :: Integral a => a -> ((Ptr CChar,Int) -> IO r) -> IO (BS.ByteString, r)
intoNewBS len f = do
let l = fromIntegral len
allocaBytes l $ \ptr -> do
res <- f (ptr, l)
bs <- BS.packCStringLen (ptr, l)
return (bs, res)
-- | Variant of 'intoNewBS' that discards result of the wrapped function
intoNewBS_ :: Integral a => a -> ((Ptr CChar,Int) -> IO r) -> IO BS.ByteString
intoNewBS_ len f = do
(bs, _) <- intoNewBS len f
return bs
{- |
Binds a user-dened reduction operation to an 'Operation' handle that can
subsequently be used in 'reduceSend', 'reduceRecv', 'allreduce', and 'reduceScatter'.
The user-defined operation is assumed to be associative.
If first argument to @opCreate@ is @True@, then the operation should be both commutative and associative. If
it is not commutative, then the order of operands is fixed and is defined to be in ascending,
process rank order, beginning with process zero. The order of evaluation can be changed,
taking advantage of the associativity of the operation. If operation
is commutative then the order
of evaluation can be changed, taking advantage of commutativity and
associativity.
User-defined operation accepts four arguments, @invec@, @inoutvec@,
@len@ and @datatype@ and applies reduction operation to the elements
of @invec@ and @inoutvec@ in pariwise manner. In pseudocode:
@
for i in [0..len-1] { inoutvec[i] = op invec[i] inoutvec[i] }
@
Full example with user-defined function that mimics standard operation
'sumOp':
@
import "Control.Parallel.MPI.Fast"
foreign import ccall \"wrapper\"
wrap :: (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ())
-> IO (FunPtr (Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()))
reduceUserOpTest myRank = do
numProcs <- commSize commWorld
userSumPtr <- wrap userSum
mySumOp <- opCreate True userSumPtr
(src :: StorableArray Int Double) <- newListArray (0,99) [0..99]
if myRank /= root
then reduceSend commWorld root sumOp src
else do
(result :: StorableArray Int Double) <- intoNewArray_ (0,99) $ reduceRecv commWorld root mySumOp src
recvMsg <- getElems result
freeHaskellFunPtr userSumPtr
where
userSum :: Ptr CDouble -> Ptr CDouble -> Ptr CInt -> Ptr Datatype -> IO ()
userSum inPtr inoutPtr lenPtr _ = do
len <- peek lenPtr
let offs = sizeOf ( undefined :: CDouble )
let loop 0 _ _ = return ()
loop n inPtr inoutPtr = do
a <- peek inPtr
b <- peek inoutPtr
poke inoutPtr (a+b)
loop (n-1) (plusPtr inPtr offs) (plusPtr inoutPtr offs)
loop len inPtr inoutPtr
@
-}
opCreate :: Storable t => Bool
-- ^ Whether the operation is commutative
-> (FunPtr (Ptr t -> Ptr t -> Ptr CInt -> Ptr Datatype -> IO ()))
{- ^ Pointer to function that accepts, in order:
* @invec@, pointer to first input vector
* @inoutvec@, pointer to second input vector, which is also the output vector
* @len@, pointer to length of both vectors
* @datatype@, pointer to 'Datatype' of elements in both vectors
-}
-> IO Operation -- ^ Handle to the created user-defined operation
opCreate commute f = do
Internal.opCreate (castFunPtr f) commute
| bjpop/haskell-mpi | src/Control/Parallel/MPI/Fast.hs | bsd-3-clause | 36,270 | 0 | 21 | 7,828 | 6,705 | 3,481 | 3,224 | -1 | -1 |
-----------------------------------------------------------------------------
-- Strict State Thread module
--
-- This library provides support for strict state threads, as described
-- in the PLDI '94 paper by John Launchbury and Simon Peyton Jones.
-- In addition to the monad ST, it also provides mutable variables STRef
-- and mutable arrays STArray.
--
-- Suitable for use with Hugs 98.
-----------------------------------------------------------------------------
module Hugs.ST
( ST(..)
, runST
, unsafeRunST
, RealWorld
, stToIO
, unsafeIOToST
, unsafeSTToIO
, STRef
-- instance Eq (STRef s a)
, newSTRef
, readSTRef
, writeSTRef
, STArray
-- instance Eq (STArray s ix elt)
, newSTArray
, boundsSTArray
, numElementsSTArray
, readSTArray
, writeSTArray
, thawSTArray
, freezeSTArray
, unsafeFreezeSTArray
, unsafeReadSTArray
, unsafeWriteSTArray
) where
import Hugs.Prelude(IO(..))
import Hugs.Array(Array,Ix(index,rangeSize),bounds,elems)
import Hugs.IOExts(unsafePerformIO, unsafeCoerce)
import Control.Monad
-----------------------------------------------------------------------------
-- The ST representation generalizes that of IO (cf. Hugs.Prelude),
-- so it can use IO primitives that manipulate local state.
newtype ST s a = ST (forall r. (a -> r) -> r)
data RealWorld = RealWorld
primitive thenStrictST "primbindIO" :: ST s a -> (a -> ST s b) -> ST s b
primitive returnST "primretIO" :: a -> ST s a
unST :: ST s a -> (a -> r) -> r
unST (ST f) = f
runST :: (forall s. ST s a) -> a
runST m = unST m id
unsafeRunST :: ST s a -> a
unsafeRunST m = unST m id
stToIO :: ST RealWorld a -> IO a
stToIO (ST f) = IO f
unsafeIOToST :: IO a -> ST s a
unsafeIOToST = unsafePerformIO . liftM returnST
unsafeSTToIO :: ST s a -> IO a
unsafeSTToIO = stToIO . unsafeCoerce
instance Functor (ST s) where
fmap = liftM
instance Monad (ST s) where
(>>=) = thenStrictST
return = returnST
-----------------------------------------------------------------------------
data STRef s a -- implemented as an internal primitive
primitive newSTRef "newRef" :: a -> ST s (STRef s a)
primitive readSTRef "getRef" :: STRef s a -> ST s a
primitive writeSTRef "setRef" :: STRef s a -> a -> ST s ()
primitive eqSTRef "eqRef" :: STRef s a -> STRef s a -> Bool
instance Eq (STRef s a) where (==) = eqSTRef
-----------------------------------------------------------------------------
data STArray s ix elt -- implemented as an internal primitive
newSTArray :: Ix ix => (ix,ix) -> elt -> ST s (STArray s ix elt)
boundsSTArray :: Ix ix => STArray s ix elt -> (ix, ix)
readSTArray :: Ix ix => STArray s ix elt -> ix -> ST s elt
writeSTArray :: Ix ix => STArray s ix elt -> ix -> elt -> ST s ()
thawSTArray :: Ix ix => Array ix elt -> ST s (STArray s ix elt)
freezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
unsafeFreezeSTArray :: Ix ix => STArray s ix elt -> ST s (Array ix elt)
unsafeReadSTArray :: Ix i => STArray s i e -> Int -> ST s e
unsafeReadSTArray = primReadArr
unsafeWriteSTArray :: Ix i => STArray s i e -> Int -> e -> ST s ()
unsafeWriteSTArray = primWriteArr
newSTArray bs e = primNewArr bs (rangeSize bs) e
boundsSTArray a = primBounds a
numElementsSTArray a = primNumElements a
readSTArray a i = unsafeReadSTArray a (index (boundsSTArray a) i)
writeSTArray a i e = unsafeWriteSTArray a (index (boundsSTArray a) i) e
thawSTArray arr = do
stArr <- newSTArray (bounds arr) err
sequence_ (zipWith (unsafeWriteSTArray stArr)
[0..] (elems arr))
return stArr
where
err = error "thawArray: element not overwritten" -- shouldnae happen
freezeSTArray a = primFreeze a
unsafeFreezeSTArray = freezeSTArray -- not as fast as GHC
instance Eq (STArray s ix elt) where
(==) = eqSTArray
primitive primNewArr "IONewArr"
:: (a,a) -> Int -> b -> ST s (STArray s a b)
primitive primReadArr "IOReadArr"
:: STArray s a b -> Int -> ST s b
primitive primWriteArr "IOWriteArr"
:: STArray s a b -> Int -> b -> ST s ()
primitive primFreeze "IOFreeze"
:: STArray s a b -> ST s (Array a b)
primitive primBounds "IOBounds"
:: STArray s a b -> (a,a)
primitive primNumElements "IONumElements"
:: STArray s a b -> Int
primitive eqSTArray "IOArrEq"
:: STArray s a b -> STArray s a b -> Bool
-----------------------------------------------------------------------------
| FranklinChen/Hugs | libraries/hugsbase/Hugs/ST.hs | bsd-3-clause | 4,728 | 45 | 12 | 1,197 | 1,387 | 730 | 657 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : GSL.Random.Gen
-- Copyright : Copyright (c) , Patrick Perry <[email protected]>
-- License : BSD3
-- Maintainer : Patrick Perry <[email protected]>
-- Stability : experimental
--
-- Random number generators.
module GSL.Random.Gen (
module GSL.Random.Gen.Internal
) where
import GSL.Random.Gen.Internal hiding ( MkRNG )
| patperry/hs-gsl-random | lib/GSL/Random/Gen.hs | bsd-3-clause | 441 | 0 | 5 | 67 | 39 | 30 | 9 | 3 | 0 |
module CommandLine.TransformFiles
( Result
, TransformMode(..), applyTransformation
, ValidateMode(..), validateNoChanges
) where
-- This module provides reusable functions for command line tools that
-- transform files.
import CommandLine.InfoFormatter (ExecuteMode(..))
import qualified CommandLine.InfoFormatter as InfoFormatter
import CommandLine.World (World)
import qualified CommandLine.World as World
import Control.Monad.State hiding (runState)
import Data.Text (Text)
data Result a
= NoChange FilePath a
| Changed FilePath a
checkChange :: Eq a => (FilePath, a) -> a -> Result a
checkChange (inputFile, inputText) outputText =
if inputText == outputText
then NoChange inputFile outputText
else Changed inputFile outputText
updateFile :: World m => Result Text -> m ()
updateFile result =
case result of
NoChange _ _ -> return ()
Changed outputFile outputText -> World.writeUtf8File outputFile outputText
readStdin :: World m => m (FilePath, Text)
readStdin =
(,) "<STDIN>" <$> World.getStdin
readFromFile :: World m => (FilePath -> StateT s m ()) -> FilePath -> StateT s m (FilePath, Text)
readFromFile onProcessingFile filePath =
onProcessingFile filePath
*> lift (World.readUtf8FileWithPath filePath)
data TransformMode
= StdinToStdout
| StdinToFile FilePath
| FileToStdout FilePath
| FileToFile FilePath FilePath
| FilesInPlace FilePath [FilePath]
applyTransformation ::
World m =>
InfoFormatter.Loggable info =>
InfoFormatter.ToConsole prompt =>
(FilePath -> info)
-> Bool
-> ([FilePath] -> prompt)
-> ((FilePath, Text) -> Either info Text)
-> TransformMode
-> m Bool
applyTransformation processingFile autoYes confirmPrompt transform mode =
let
usesStdout =
case mode of
StdinToStdout -> True
StdinToFile _ -> True
FileToStdout _ -> True
FileToFile _ _ -> False
FilesInPlace _ _ -> False
infoMode = ForHuman usesStdout
onInfo = InfoFormatter.onInfo infoMode
approve = InfoFormatter.approve infoMode autoYes . confirmPrompt
in
runState (InfoFormatter.init infoMode) (InfoFormatter.done infoMode) $
case mode of
StdinToStdout ->
lift (transform <$> readStdin) >>= logErrorOr onInfo (lift . World.writeStdout)
StdinToFile outputFile ->
lift (transform <$> readStdin) >>= logErrorOr onInfo (lift . World.writeUtf8File outputFile)
FileToStdout inputFile ->
lift (transform <$> World.readUtf8FileWithPath inputFile) >>= logErrorOr onInfo (lift . World.writeStdout)
FileToFile inputFile outputFile ->
(transform <$> readFromFile (onInfo . processingFile) inputFile) >>= logErrorOr onInfo (lift . World.writeUtf8File outputFile)
FilesInPlace first rest ->
do
canOverwrite <- lift $ approve (first:rest)
if canOverwrite
then all id <$> mapM formatFile (first:rest)
else return True
where
formatFile file = ((\i -> checkChange i <$> transform i) <$> readFromFile (onInfo . processingFile) file) >>= logErrorOr onInfo (lift . updateFile)
data ValidateMode
= ValidateStdin
| ValidateFiles FilePath [FilePath]
validateNoChanges ::
World m =>
InfoFormatter.Loggable info =>
(FilePath -> info)
-> ((FilePath, Text) -> Either info ())
-> ValidateMode
-> m Bool
validateNoChanges processingFile validate mode =
let
infoMode = ForMachine
onInfo = InfoFormatter.onInfo infoMode
in
runState (InfoFormatter.init infoMode) (InfoFormatter.done infoMode) $
case mode of
ValidateStdin ->
lift (validate <$> readStdin) >>= logError onInfo
ValidateFiles first rest ->
and <$> mapM validateFile (first:rest)
where
validateFile file =
(validate <$> readFromFile (onInfo . processingFile) file)
>>= logError onInfo
logErrorOr :: Monad m => (error -> m ()) -> (a -> m ()) -> Either error a -> m Bool
logErrorOr onInfo fn result =
case result of
Left message ->
onInfo message *> return False
Right value ->
fn value *> return True
logError :: Monad m => (error -> m ()) -> Either error () -> m Bool
logError onInfo =
logErrorOr onInfo return
runState :: Monad m => (m (), state) -> (state -> m ()) -> StateT state m result -> m result
runState (initM, initialState) done run =
do
initM
(result, finalState) <- runStateT run initialState
done finalState
return result
| avh4/elm-format | elm-format-lib/src/CommandLine/TransformFiles.hs | bsd-3-clause | 4,823 | 0 | 19 | 1,338 | 1,424 | 719 | 705 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
module Service.BearyChat(
BearyChat(..)
, setBearyChat
, bearyChatService
, notifyText
, BearyChatApi(..)
) where
import Base
import Model
import Control.Lens ((^?))
import Data.Aeson (decode, toJSON)
import qualified Data.Text as T
import Database.Persist.Sql
import qualified Network.Wreq as W
import Servant
data BearyChat = BearyChat
{ incomingKey :: Text
, outgoingKey :: Text
} deriving (Show, Generic, FromJSON)
keyBearyChat :: Text
keyBearyChat = "Service.BearyChat"
getBearyChat :: (MonadIO m, MonadThrow m) => AppM m BearyChat
getBearyChat = getExtension keyBearyChat
setBearyChat :: (MonadIO m, MonadThrow m) => Maybe BearyChat -> AppM m ()
setBearyChat = maybe (infoLn "BearyChat Module not loaded") (setExtension keyBearyChat)
newtype IncomingAttachmentImage = IncomingAttachmentImage { url :: Text} deriving (Generic, ToSchema, FromJSON, ToJSON)
data IncomingAttachment = IncomingAttachment
{ title :: Maybe Text
, url :: Maybe Text
, text :: Maybe Text
, color :: Maybe Text
, images :: Maybe [IncomingAttachmentImage]
} deriving (Generic, ToSchema, FromJSON, ToJSON)
data IncomingRequest = IncomingRequest
{ text :: Text
, notification :: Maybe Bool
, markdown :: Bool
, channel :: Maybe Text
, user :: Maybe Text
, attachments :: Maybe [IncomingAttachment]
} deriving (Generic, ToSchema, FromJSON, ToJSON)
data IncomingResponse = IncomingResponse
{ code :: Int
, result :: Maybe Text
} deriving (Generic, ToSchema, FromJSON, ToJSON)
type BearyChatT = ReaderT BearyChat
sendRequest :: (MonadIO m) => BearyChat -> IncomingRequest -> AppM m IncomingResponse
sendRequest bc req = do
infoLn $ "Request: " <> encodeToText req
res <- liftIO $ do
res <- W.post ("https://hook.bearychat.com/" <> cs (incomingKey bc)) (toJSON req)
let r = join $ fmap decode $ res ^? W.responseBody
case r of Nothing -> return $ IncomingResponse (-1) Nothing
(Just a) -> return a
infoLn $ "Response: " <> encodeToText res
return res
type Channel = Text
instance Default IncomingRequest where
def = IncomingRequest "" Nothing True Nothing Nothing Nothing
data BearyChatRequest = BearyChatRequest
{ token :: Text
, ts :: Integer
, text :: Text
, trigger_word :: Text
, subdomain :: Text
, channel_name :: Maybe Text
, user_name :: Text
} deriving (Generic, ToSchema, FromJSON, ToJSON)
data BearyChatResponse = BearyChatResponse
{ text :: Text
, attachments :: Maybe [IncomingAttachment]
} deriving (Generic, ToSchema, FromJSON, ToJSON)
type BearyChatApi = "bearychat" :> "notify" :> ReqBody '[JSON] IncomingRequest :> Post '[JSON] IncomingResponse
:<|> "bearychat" :> ReqBody '[JSON] BearyChatRequest :> Post '[JSON] BearyChatResponse
bearyChatService :: ServerT BearyChatApi App
bearyChatService = notifyBearyChat
:<|> replyBearyChat
notifyText :: (MonadIO m, MonadThrow m) => Text -> AppM m IncomingResponse
notifyText t = notifyBearyChat def {text = t}
notifyBearyChat :: (MonadIO m, MonadThrow m) => IncomingRequest -> AppM m IncomingResponse
notifyBearyChat req = do
bc <- getBearyChat
sendRequest bc req
replyBearyChat :: (MonadIO m, MonadThrow m) => BearyChatRequest -> AppM m BearyChatResponse
replyBearyChat req = do
bc <- getBearyChat
let tokenStr = token (req :: BearyChatRequest)
when (outgoingKey bc /= tokenStr) $
throwM $ ServiceException_ "BearyChat Token check failed"
checkTimeOut $ ts req
let msg = text (req :: BearyChatRequest)
echo = T.strip $ fromMaybe msg $ T.stripPrefix (trigger_word req) msg
saveReq = do now <- getNow
insert $ EntityBearyChatMessage
tokenStr
(trigger_word req)
echo
(millisToUTC $ ts req)
(subdomain req)
(channel_name req)
(user_name req)
now
runTrans saveReq
return $ BearyChatResponse ("echo: " <> echo) Nothing
| leptonyu/mint | corn-server/src/Service/BearyChat.hs | bsd-3-clause | 4,546 | 0 | 17 | 1,255 | 1,236 | 658 | 578 | 109 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
module Scripts.ExpressionTest where
import ClassyPrelude hiding (assert)
import Appian
import Appian.Client
import Appian.Lens
import Appian.Types
import Appian.Instances
import Test.QuickCheck
import Test.QuickCheck.Monadic
import Appian.Internal.Arbitrary
import Control.Lens
import Control.Lens.Action
import Control.Lens.Action.Reified
import Data.Aeson
import Servant.Client (ClientEnv)
import Formatting
newtype ExpressionList = ExpressionList [Integer]
deriving (Show, Monoid, Read)
newtype Expression = Expression Text
instance Arbitrary ExpressionList where
arbitrary = ExpressionList <$> arbitrary
dispList :: ExpressionList -> Text
dispList (ExpressionList l) = dispList_ l (length l)
dispList_ :: [Integer] -> Int -> Text
dispList_ _ 0 = "List of Variant: " <> "0 items"
dispList_ l 1 = "List of Number (Integer): " <> "1 item\n " <> intercalate "\n " (fmap tshow l)
dispList_ l n = "List of Number (Integer): " <> (toStrict $ format commas n) <> " items\n " <> intercalate "\n " (fmap tshow l)
toAppianList :: ExpressionList -> Text
toAppianList (ExpressionList l) = "{" <> intercalate "," (fmap tshow l) <> "}"
arbitraryExpressionList :: MonadGen m => ExpressionEditorWidget -> m ExpressionEditorWidget
arbitraryExpressionList widget = do
l <- genArbitrary arbitrary
return $ expwValue .~ toAppianList l $ widget
expressionListArbitrary :: (Applicative f, Effective m r f, MonadGen m) => (Either Text Update -> f (Either Text Update)) -> Value -> f Value
expressionListArbitrary = failing (getExpressionInfoPanel . traverse . editor . to Right) (to $ const $ Left $ "Could not find Expression Editor Widget ") . act (mapM $ arbitraryExpressionList) . to (fmap toUpdate)
expressionListArbitraryF :: MonadGen m => ReifiedMonadicFold m Value (Either Text Update)
expressionListArbitraryF = MonadicFold expressionListArbitrary
testRule :: RapidFire m => Expression -> AppianT m Value
testRule (Expression expr) = do
v <- newRule
assign appianValue v
sendRuleUpdates "Sending blank expression" (MonadicFold $ getExpressionInfoPanel . traverse . editor . to (expwValue .~ "") . to toUpdate . to Right)
sendRuleUpdates "Sending arbitrary list" (MonadicFold $ getExpressionInfoPanel . traverse . editor . to (expwValue .~ expr) . to toUpdate . to Right)
sendRuleUpdates "Click 'Test Rule'" (MonadicFold $ to $ buttonUpdate "Test Rule")
use appianValue
prop_ruleTest :: Expression -> Text -> LogMode -> AppianState -> ClientEnv -> Login -> Property
prop_ruleTest expr txtGold logMode state env login = monadicIO $ do
v <- run $ runAppianT logMode (testRule expr) state env login
txtList <- case v ^? _Right . _Right . getParagraphField "Value" . pgfValue of
Nothing -> fail "Could not get the expression from the response!"
Just txt -> return txt
assert (txtList == txtGold)
testReverseList :: RapidFire m => ExpressionList -> AppianT m Value
testReverseList l = testRule $ Expression $ "fn!reverse(fn!reverse(" <> toAppianList l <> "))"
prop_reverseList :: LogMode -> AppianState -> ClientEnv -> Login -> ExpressionList -> Property
prop_reverseList logMode state env login l = prop_ruleTest (Expression $ "fn!reverse(fn!reverse(" <> toAppianList l <> "))") (dispList l) logMode state env login
testSortList :: RapidFire m => ExpressionList -> AppianT m Value
testSortList l = testRule $ Expression $ "fn!sort(" <> toAppianList l <> ")"
sortExpressionList :: ExpressionList -> ExpressionList
sortExpressionList (ExpressionList l) = ExpressionList (sort l)
-- fn!sort is not supported by
-- Appian. Probably because it
-- is slow.
prop_sortList :: LogMode -> AppianState -> ClientEnv -> Login -> ExpressionList -> Property
prop_sortList logMode state env login l = prop_ruleTest (Expression $ "fn!sort(" <> toAppianList l <> ")") (dispList $ sortExpressionList l) logMode state env login
| limaner2002/EPC-tools | USACScripts/src/Scripts/ExpressionTest.hs | bsd-3-clause | 4,128 | 0 | 14 | 748 | 1,170 | 589 | 581 | -1 | -1 |
module Problem135 where
import qualified Data.Vector.Unboxed as Vector
main :: IO ()
-- x=a+d,y=a,z=a-d
-- (a+d)^2-a^2-(a-d)^2 = n
-- 4ad-a^2=n
-- a(4d-a)=n = xy (say)
-- a=x,d=(x+y)/4
-- a-d>0 ⇒ (3x-y)/4 > 0 ⇒ 3x>y ⇒ n = xy < 3x^2
main =
print
. Vector.length
. Vector.elemIndices 10
. Vector.unsafeAccum (+) (Vector.replicate (1 + lim) 0)
$ ([ (n, 1)
| x <- [1 .. lim]
, n <- takeWhile (\n -> n < 3 * x * x) [x, 2 * x .. lim]
, (x + (n `div` x)) `mod` 4 == 0
] :: [(Int, Int)]
)
where lim = 1000000 :: Int
| adityagupta1089/Project-Euler-Haskell | src/problems/Problem135.hs | bsd-3-clause | 610 | 0 | 15 | 203 | 207 | 122 | 85 | 14 | 1 |
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Types where
import Database.Redis
import Data.Aeson as A
import qualified Data.ByteString as BS
import Data.Text.Encoding
import qualified Data.Vector as V
import Prelude hiding (error)
import Network.IPv6DB.Types
newtype Env = Env { redisConn :: Connection }
data RedisResponse
= RedisOk
| RedisError
{ entry :: !Entry
, error :: !BS.ByteString
}
deriving (Eq, Show)
instance ToJSON RedisResponse where
toJSON RedisError{entry=Entry{..},..} =
object
[ "list" .= list
, "address" .= address
, "error" .= decodeUtf8 error
]
toJSON _ = Null
newtype RedisErrors = RedisErrors [RedisResponse] deriving (Eq, Show)
instance ToJSON RedisErrors where
toJSON (RedisErrors rrs) =
object
[ ("errors", Array $ V.fromList $ toJSON <$> filter (/= RedisOk) rrs) ]
| MichelBoucey/IPv6DB | app/Types.hs | bsd-3-clause | 1,043 | 0 | 12 | 302 | 256 | 150 | 106 | 34 | 0 |
{-# LANGUAGE OverloadedStrings, ForeignFunctionInterface #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Blockchain.Data.Block (
BlockData (..),
Block (..),
migrateAll
) where
import Database.Persist
import Database.Persist.Types
import Database.Persist.TH
import Database.Persist.Postgresql
import Data.Time
import Data.Time.Clock.POSIX
import Data.ByteString as B
import Blockchain.Data.AddressState
import Blockchain.Data.Address
import Blockchain.SHA
import Blockchain.Data.SignedTransaction
import Blockchain.Util
import Blockchain.Database.MerklePatricia.SHAPtr
--import Debug.Trace
{-
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
BlockData
parentHash SHA
unclesHash SHA
coinbase Address
stateRoot SHAPtr
transactionsRoot SHAPtr
receiptsRoot SHAPtr
logBloom B.ByteString
difficulty Integer
number Integer
gasLimit Integer
gasUsed Integer
timestamp UTCTime
extraData Integer
nonce SHA
deriving Show Read Eq
Block
blockData BlockData
receiptTransactions [SignedTransaction]
blockUncles [BlockData]
deriving Show Read Eq
|]
{-
data BlockData = BlockData {
parentHash::SHA,
unclesHash::SHA,
coinbase::Address,
bStateRoot::SHAPtr,
transactionsRoot::SHAPtr,
receiptsRoot::SHAPtr,
logBloom::B.ByteString,
difficulty::Integer,
number::Integer,
gasLimit::Integer,
gasUsed::Integer,
timestamp::UTCTime,
extraData::Integer,
nonce::SHA
} deriving (Show, Read, Eq)
data Block = Block {
blockData::BlockData,
receiptTransactions::[SignedTransaction],
blockUncles::[BlockData]
} deriving (Show, Read, Eq)
-}
--derivePersistField "BlockData"
--derivePersistField "Block"
-}
| kejace/ethereum-data-sql | src/Blockchain/Data/Block.hs | bsd-3-clause | 2,085 | 0 | 5 | 408 | 115 | 81 | 34 | 27 | 0 |
{-# LINE 1 "Data.Bits.hs" #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Bits
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- This module defines bitwise operations for signed and unsigned
-- integers. Instances of the class 'Bits' for the 'Int' and
-- 'Integer' types are available from this module, and instances for
-- explicitly sized integral types are available from the
-- "Data.Int" and "Data.Word" modules.
--
-----------------------------------------------------------------------------
module Data.Bits (
Bits(
(.&.), (.|.), xor,
complement,
shift,
rotate,
zeroBits,
bit,
setBit,
clearBit,
complementBit,
testBit,
bitSizeMaybe,
bitSize,
isSigned,
shiftL, shiftR,
unsafeShiftL, unsafeShiftR,
rotateL, rotateR,
popCount
),
FiniteBits(
finiteBitSize,
countLeadingZeros,
countTrailingZeros
),
bitDefault,
testBitDefault,
popCountDefault,
toIntegralSized
) where
-- Defines the @Bits@ class containing bit-based operations.
-- See library document for details on the semantics of the
-- individual operations.
import Data.Maybe
import GHC.Enum
import GHC.Num
import GHC.Base
import GHC.Real
import GHC.Integer.GMP.Internals (bitInteger, popCountInteger)
infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR`
infixl 7 .&.
infixl 6 `xor`
infixl 5 .|.
{-# DEPRECATED bitSize "Use 'bitSizeMaybe' or 'finiteBitSize' instead" #-} -- deprecated in 7.8
-- | The 'Bits' class defines bitwise operations over integral types.
--
-- * Bits are numbered from 0 with bit 0 being the least
-- significant bit.
class Eq a => Bits a where
{-# MINIMAL (.&.), (.|.), xor, complement,
(shift | (shiftL, shiftR)),
(rotate | (rotateL, rotateR)),
bitSize, bitSizeMaybe, isSigned, testBit, bit, popCount #-}
-- | Bitwise \"and\"
(.&.) :: a -> a -> a
-- | Bitwise \"or\"
(.|.) :: a -> a -> a
-- | Bitwise \"xor\"
xor :: a -> a -> a
{-| Reverse all the bits in the argument -}
complement :: a -> a
{-| @'shift' x i@ shifts @x@ left by @i@ bits if @i@ is positive,
or right by @-i@ bits otherwise.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
An instance can define either this unified 'shift' or 'shiftL' and
'shiftR', depending on which is more convenient for the type in
question. -}
shift :: a -> Int -> a
x `shift` i | i<0 = x `shiftR` (-i)
| i>0 = x `shiftL` i
| otherwise = x
{-| @'rotate' x i@ rotates @x@ left by @i@ bits if @i@ is positive,
or right by @-i@ bits otherwise.
For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'.
An instance can define either this unified 'rotate' or 'rotateL' and
'rotateR', depending on which is more convenient for the type in
question. -}
rotate :: a -> Int -> a
x `rotate` i | i<0 = x `rotateR` (-i)
| i>0 = x `rotateL` i
| otherwise = x
{-
-- Rotation can be implemented in terms of two shifts, but care is
-- needed for negative values. This suggested implementation assumes
-- 2's-complement arithmetic. It is commented out because it would
-- require an extra context (Ord a) on the signature of 'rotate'.
x `rotate` i | i<0 && isSigned x && x<0
= let left = i+bitSize x in
((x `shift` i) .&. complement ((-1) `shift` left))
.|. (x `shift` left)
| i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x))
| i==0 = x
| i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x))
-}
-- | 'zeroBits' is the value with all bits unset.
--
-- The following laws ought to hold (for all valid bit indices @/n/@):
--
-- * @'clearBit' 'zeroBits' /n/ == 'zeroBits'@
-- * @'setBit' 'zeroBits' /n/ == 'bit' /n/@
-- * @'testBit' 'zeroBits' /n/ == False@
-- * @'popCount' 'zeroBits' == 0@
--
-- This method uses @'clearBit' ('bit' 0) 0@ as its default
-- implementation (which ought to be equivalent to 'zeroBits' for
-- types which possess a 0th bit).
--
-- @since 4.7.0.0
zeroBits :: a
zeroBits = clearBit (bit 0) 0
-- | @bit /i/@ is a value with the @/i/@th bit set and all other bits clear.
--
-- Can be implemented using `bitDefault' if @a@ is also an
-- instance of 'Num'.
--
-- See also 'zeroBits'.
bit :: Int -> a
-- | @x \`setBit\` i@ is the same as @x .|. bit i@
setBit :: a -> Int -> a
-- | @x \`clearBit\` i@ is the same as @x .&. complement (bit i)@
clearBit :: a -> Int -> a
-- | @x \`complementBit\` i@ is the same as @x \`xor\` bit i@
complementBit :: a -> Int -> a
-- | Return 'True' if the @n@th bit of the argument is 1
--
-- Can be implemented using `testBitDefault' if @a@ is also an
-- instance of 'Num'.
testBit :: a -> Int -> Bool
{-| Return the number of bits in the type of the argument. The actual
value of the argument is ignored. Returns Nothing
for types that do not have a fixed bitsize, like 'Integer'.
@since 4.7.0.0
-}
bitSizeMaybe :: a -> Maybe Int
{-| Return the number of bits in the type of the argument. The actual
value of the argument is ignored. The function 'bitSize' is
undefined for types that do not have a fixed bitsize, like 'Integer'.
-}
bitSize :: a -> Int
{-| Return 'True' if the argument is a signed type. The actual
value of the argument is ignored -}
isSigned :: a -> Bool
{-# INLINE setBit #-}
{-# INLINE clearBit #-}
{-# INLINE complementBit #-}
x `setBit` i = x .|. bit i
x `clearBit` i = x .&. complement (bit i)
x `complementBit` i = x `xor` bit i
{-| Shift the argument left by the specified number of bits
(which must be non-negative).
An instance can define either this and 'shiftR' or the unified
'shift', depending on which is more convenient for the type in
question. -}
shiftL :: a -> Int -> a
{-# INLINE shiftL #-}
x `shiftL` i = x `shift` i
{-| Shift the argument left by the specified number of bits. The
result is undefined for negative shift amounts and shift amounts
greater or equal to the 'bitSize'.
Defaults to 'shiftL' unless defined explicitly by an instance.
@since 4.5.0.0 -}
unsafeShiftL :: a -> Int -> a
{-# INLINE unsafeShiftL #-}
x `unsafeShiftL` i = x `shiftL` i
{-| Shift the first argument right by the specified number of bits. The
result is undefined for negative shift amounts and shift amounts
greater or equal to the 'bitSize'.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
An instance can define either this and 'shiftL' or the unified
'shift', depending on which is more convenient for the type in
question. -}
shiftR :: a -> Int -> a
{-# INLINE shiftR #-}
x `shiftR` i = x `shift` (-i)
{-| Shift the first argument right by the specified number of bits, which
must be non-negative an smaller than the number of bits in the type.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
Defaults to 'shiftR' unless defined explicitly by an instance.
@since 4.5.0.0 -}
unsafeShiftR :: a -> Int -> a
{-# INLINE unsafeShiftR #-}
x `unsafeShiftR` i = x `shiftR` i
{-| Rotate the argument left by the specified number of bits
(which must be non-negative).
An instance can define either this and 'rotateR' or the unified
'rotate', depending on which is more convenient for the type in
question. -}
rotateL :: a -> Int -> a
{-# INLINE rotateL #-}
x `rotateL` i = x `rotate` i
{-| Rotate the argument right by the specified number of bits
(which must be non-negative).
An instance can define either this and 'rotateL' or the unified
'rotate', depending on which is more convenient for the type in
question. -}
rotateR :: a -> Int -> a
{-# INLINE rotateR #-}
x `rotateR` i = x `rotate` (-i)
{-| Return the number of set bits in the argument. This number is
known as the population count or the Hamming weight.
Can be implemented using `popCountDefault' if @a@ is also an
instance of 'Num'.
@since 4.5.0.0 -}
popCount :: a -> Int
-- |The 'FiniteBits' class denotes types with a finite, fixed number of bits.
--
-- @since 4.7.0.0
class Bits b => FiniteBits b where
-- | Return the number of bits in the type of the argument.
-- The actual value of the argument is ignored. Moreover, 'finiteBitSize'
-- is total, in contrast to the deprecated 'bitSize' function it replaces.
--
-- @
-- 'finiteBitSize' = 'bitSize'
-- 'bitSizeMaybe' = 'Just' . 'finiteBitSize'
-- @
--
-- @since 4.7.0.0
finiteBitSize :: b -> Int
-- | Count number of zero bits preceding the most significant set bit.
--
-- @
-- 'countLeadingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)
-- @
--
-- 'countLeadingZeros' can be used to compute log base 2 via
--
-- @
-- logBase2 x = 'finiteBitSize' x - 1 - 'countLeadingZeros' x
-- @
--
-- Note: The default implementation for this method is intentionally
-- naive. However, the instances provided for the primitive
-- integral types are implemented using CPU specific machine
-- instructions.
--
-- @since 4.8.0.0
countLeadingZeros :: b -> Int
countLeadingZeros x = (w-1) - go (w-1)
where
go i | i < 0 = i -- no bit set
| testBit x i = i
| otherwise = go (i-1)
w = finiteBitSize x
-- | Count number of zero bits following the least significant set bit.
--
-- @
-- 'countTrailingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)
-- 'countTrailingZeros' . 'negate' = 'countTrailingZeros'
-- @
--
-- The related
-- <http://en.wikipedia.org/wiki/Find_first_set find-first-set operation>
-- can be expressed in terms of 'countTrailingZeros' as follows
--
-- @
-- findFirstSet x = 1 + 'countTrailingZeros' x
-- @
--
-- Note: The default implementation for this method is intentionally
-- naive. However, the instances provided for the primitive
-- integral types are implemented using CPU specific machine
-- instructions.
--
-- @since 4.8.0.0
countTrailingZeros :: b -> Int
countTrailingZeros x = go 0
where
go i | i >= w = i
| testBit x i = i
| otherwise = go (i+1)
w = finiteBitSize x
-- The defaults below are written with lambdas so that e.g.
-- bit = bitDefault
-- is fully applied, so inlining will happen
-- | Default implementation for 'bit'.
--
-- Note that: @bitDefault i = 1 `shiftL` i@
--
-- @since 4.6.0.0
bitDefault :: (Bits a, Num a) => Int -> a
bitDefault = \i -> 1 `shiftL` i
{-# INLINE bitDefault #-}
-- | Default implementation for 'testBit'.
--
-- Note that: @testBitDefault x i = (x .&. bit i) /= 0@
--
-- @since 4.6.0.0
testBitDefault :: (Bits a, Num a) => a -> Int -> Bool
testBitDefault = \x i -> (x .&. bit i) /= 0
{-# INLINE testBitDefault #-}
-- | Default implementation for 'popCount'.
--
-- This implementation is intentionally naive. Instances are expected to provide
-- an optimized implementation for their size.
--
-- @since 4.6.0.0
popCountDefault :: (Bits a, Num a) => a -> Int
popCountDefault = go 0
where
go !c 0 = c
go c w = go (c+1) (w .&. (w - 1)) -- clear the least significant
{-# INLINABLE popCountDefault #-}
-- Interpret 'Bool' as 1-bit bit-field; @since 4.7.0.0
instance Bits Bool where
(.&.) = (&&)
(.|.) = (||)
xor = (/=)
complement = not
shift x 0 = x
shift _ _ = False
rotate x _ = x
bit 0 = True
bit _ = False
testBit x 0 = x
testBit _ _ = False
bitSizeMaybe _ = Just 1
bitSize _ = 1
isSigned _ = False
popCount False = 0
popCount True = 1
instance FiniteBits Bool where
finiteBitSize _ = 1
countTrailingZeros x = if x then 0 else 1
countLeadingZeros x = if x then 0 else 1
instance Bits Int where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
zeroBits = 0
bit = bitDefault
testBit = testBitDefault
(I# x#) .&. (I# y#) = I# (x# `andI#` y#)
(I# x#) .|. (I# y#) = I# (x# `orI#` y#)
(I# x#) `xor` (I# y#) = I# (x# `xorI#` y#)
complement (I# x#) = I# (notI# x#)
(I# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = I# (x# `iShiftL#` i#)
| otherwise = I# (x# `iShiftRA#` negateInt# i#)
(I# x#) `shiftL` (I# i#) = I# (x# `iShiftL#` i#)
(I# x#) `unsafeShiftL` (I# i#) = I# (x# `uncheckedIShiftL#` i#)
(I# x#) `shiftR` (I# i#) = I# (x# `iShiftRA#` i#)
(I# x#) `unsafeShiftR` (I# i#) = I# (x# `uncheckedIShiftRA#` i#)
{-# INLINE rotate #-} -- See Note [Constant folding for rotate]
(I# x#) `rotate` (I# i#) =
I# ((x# `uncheckedIShiftL#` i'#) `orI#` (x# `uncheckedIShiftRL#` (wsib -# i'#)))
where
!i'# = i# `andI#` (wsib -# 1#)
!wsib = 64# {- work around preprocessor problem (??) -}
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
popCount (I# x#) = I# (word2Int# (popCnt# (int2Word# x#)))
isSigned _ = True
instance FiniteBits Int where
finiteBitSize _ = 64
countLeadingZeros (I# x#) = I# (word2Int# (clz# (int2Word# x#)))
countTrailingZeros (I# x#) = I# (word2Int# (ctz# (int2Word# x#)))
instance Bits Word where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W# x#) .&. (W# y#) = W# (x# `and#` y#)
(W# x#) .|. (W# y#) = W# (x# `or#` y#)
(W# x#) `xor` (W# y#) = W# (x# `xor#` y#)
complement (W# x#) = W# (x# `xor#` mb#)
where !(W# mb#) = maxBound
(W# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W# (x# `shiftL#` i#)
| otherwise = W# (x# `shiftRL#` negateInt# i#)
(W# x#) `shiftL` (I# i#) = W# (x# `shiftL#` i#)
(W# x#) `unsafeShiftL` (I# i#) = W# (x# `uncheckedShiftL#` i#)
(W# x#) `shiftR` (I# i#) = W# (x# `shiftRL#` i#)
(W# x#) `unsafeShiftR` (I# i#) = W# (x# `uncheckedShiftRL#` i#)
(W# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W# x#
| otherwise = W# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (wsib -# i'#)))
where
!i'# = i# `andI#` (wsib -# 1#)
!wsib = 64# {- work around preprocessor problem (??) -}
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W# x#) = I# (word2Int# (popCnt# x#))
bit = bitDefault
testBit = testBitDefault
instance FiniteBits Word where
finiteBitSize _ = 64
countLeadingZeros (W# x#) = I# (word2Int# (clz# x#))
countTrailingZeros (W# x#) = I# (word2Int# (ctz# x#))
instance Bits Integer where
(.&.) = andInteger
(.|.) = orInteger
xor = xorInteger
complement = complementInteger
shift x i@(I# i#) | i >= 0 = shiftLInteger x i#
| otherwise = shiftRInteger x (negateInt# i#)
testBit x (I# i) = testBitInteger x i
zeroBits = 0
bit (I# i#) = bitInteger i#
popCount x = I# (popCountInteger x)
rotate x i = shift x i -- since an Integer never wraps around
bitSizeMaybe _ = Nothing
bitSize _ = errorWithoutStackTrace "Data.Bits.bitSize(Integer)"
isSigned _ = True
-----------------------------------------------------------------------------
-- | Attempt to convert an 'Integral' type @a@ to an 'Integral' type @b@ using
-- the size of the types as measured by 'Bits' methods.
--
-- A simpler version of this function is:
--
-- > toIntegral :: (Integral a, Integral b) => a -> Maybe b
-- > toIntegral x
-- > | toInteger x == y = Just (fromInteger y)
-- > | otherwise = Nothing
-- > where
-- > y = toInteger x
--
-- This version requires going through 'Integer', which can be inefficient.
-- However, @toIntegralSized@ is optimized to allow GHC to statically determine
-- the relative type sizes (as measured by 'bitSizeMaybe' and 'isSigned') and
-- avoid going through 'Integer' for many types. (The implementation uses
-- 'fromIntegral', which is itself optimized with rules for @base@ types but may
-- go through 'Integer' for some type pairs.)
--
-- @since 4.8.0.0
toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b
toIntegralSized x -- See Note [toIntegralSized optimization]
| maybe True (<= x) yMinBound
, maybe True (x <=) yMaxBound = Just y
| otherwise = Nothing
where
y = fromIntegral x
xWidth = bitSizeMaybe x
yWidth = bitSizeMaybe y
yMinBound
| isBitSubType x y = Nothing
| isSigned x, not (isSigned y) = Just 0
| isSigned x, isSigned y
, Just yW <- yWidth = Just (negate $ bit (yW-1)) -- Assumes sub-type
| otherwise = Nothing
yMaxBound
| isBitSubType x y = Nothing
| isSigned x, not (isSigned y)
, Just xW <- xWidth, Just yW <- yWidth
, xW <= yW+1 = Nothing -- Max bound beyond a's domain
| Just yW <- yWidth = if isSigned y
then Just (bit (yW-1)-1)
else Just (bit yW-1)
| otherwise = Nothing
{-# INLINEABLE toIntegralSized #-}
-- | 'True' if the size of @a@ is @<=@ the size of @b@, where size is measured
-- by 'bitSizeMaybe' and 'isSigned'.
isBitSubType :: (Bits a, Bits b) => a -> b -> Bool
isBitSubType x y
-- Reflexive
| xWidth == yWidth, xSigned == ySigned = True
-- Every integer is a subset of 'Integer'
| ySigned, Nothing == yWidth = True
| not xSigned, not ySigned, Nothing == yWidth = True
-- Sub-type relations between fixed-with types
| xSigned == ySigned, Just xW <- xWidth, Just yW <- yWidth = xW <= yW
| not xSigned, ySigned, Just xW <- xWidth, Just yW <- yWidth = xW < yW
| otherwise = False
where
xWidth = bitSizeMaybe x
xSigned = isSigned x
yWidth = bitSizeMaybe y
ySigned = isSigned y
{-# INLINE isBitSubType #-}
{- Note [Constant folding for rotate]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The INLINE on the Int instance of rotate enables it to be constant
folded. For example:
sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int)
goes to:
Main.$wfold =
\ (ww_sO7 :: Int#) (ww1_sOb :: Int#) ->
case ww1_sOb of wild_XM {
__DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1);
10000000 -> ww_sO7
whereas before it was left as a call to $wrotate.
All other Bits instances seem to inline well enough on their
own to enable constant folding; for example 'shift':
sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int)
goes to:
Main.$wfold =
\ (ww_sOb :: Int#) (ww1_sOf :: Int#) ->
case ww1_sOf of wild_XM {
__DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1);
10000000 -> ww_sOb
}
-}
-- Note [toIntegralSized optimization]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- The code in 'toIntegralSized' relies on GHC optimizing away statically
-- decidable branches.
--
-- If both integral types are statically known, GHC will be able optimize the
-- code significantly (for @-O1@ and better).
--
-- For instance (as of GHC 7.8.1) the following definitions:
--
-- > w16_to_i32 = toIntegralSized :: Word16 -> Maybe Int32
-- >
-- > i16_to_w16 = toIntegralSized :: Int16 -> Maybe Word16
--
-- are translated into the following (simplified) /GHC Core/ language:
--
-- > w16_to_i32 = \x -> Just (case x of _ { W16# x# -> I32# (word2Int# x#) })
-- >
-- > i16_to_w16 = \x -> case eta of _
-- > { I16# b1 -> case tagToEnum# (<=# 0 b1) of _
-- > { False -> Nothing
-- > ; True -> Just (W16# (narrow16Word# (int2Word# b1)))
-- > }
-- > }
| phischu/fragnix | builtins/base/Data.Bits.hs | bsd-3-clause | 21,764 | 0 | 14 | 6,675 | 3,635 | 2,021 | 1,614 | 255 | 2 |
{- DO NOT EDIT THIS FILE
THIS FILE IS AUTOMAGICALLY GENERATED AND YOUR CHANGES WILL BE EATEN BY THE GENERATOR OVERLORD
All changes should go into the Model file (e.g. App/Models/ExampleModel.hs)
-}
module App.Models.Bases.TmpFunctions where
import App.Models.Bases.Common
import qualified Database.HDBC as HDBC
import Data.Maybe
import Data.Time
-- My type
import App.Models.Bases.TmpType
import Turbinado.Environment.Types
import Turbinado.Environment.Database
instance IsModel Tmp where
insert m returnId = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.run conn (" INSERT INTO tmp (ts,ts2) VALUES (" ++ (case (ts m) of Nothing -> "DEFAULT"; Just x -> "?") ++ "," ++ (case (ts2 m) of Nothing -> "DEFAULT"; Just x -> "?") ++ ")") ( (case (ts m) of Nothing -> []; Just x -> [HDBC.toSql x]) ++ (case (ts2 m) of Nothing -> []; Just x -> [HDBC.toSql x]))
case res of
0 -> (liftIO $ HDBC.handleSqlError $ HDBC.rollback conn) >>
(throwDyn $ HDBC.SqlError
{HDBC.seState = "",
HDBC.seNativeError = (-1),
HDBC.seErrorMsg = "Rolling back. No record inserted :tmp : " ++ (show m)
})
1 -> liftIO $ HDBC.handleSqlError $ HDBC.commit conn >>
if returnId
then do i <- liftIO $ HDBC.catchSql (HDBC.handleSqlError $ HDBC.quickQuery' conn "SELECT lastval()" []) (\_ -> HDBC.commit conn >> (return $ [[HDBC.toSql (0 :: Integer)]]) )
return $ HDBC.fromSql $ head $ head i
else return Nothing
findAll = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn "SELECT ts , ts2 FROM tmp" []
return $ map (\r -> Tmp (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1))) res
findAllWhere ss sp = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT ts , ts2 FROM tmp WHERE (" ++ ss ++ ") ") sp
return $ map (\r -> Tmp (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1))) res
findAllOrderBy op = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT ts , ts2 FROM tmp ORDER BY " ++ op) []
return $ map (\r -> Tmp (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1))) res
findAllWhereOrderBy ss sp op = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT ts , ts2 FROM tmp WHERE (" ++ ss ++ ") ORDER BY " ++ op) sp
return $ map (\r -> Tmp (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1))) res
findOneWhere ss sp = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT ts , ts2 FROM tmp WHERE (" ++ ss ++ ") LIMIT 1") sp
return $ (\r -> Tmp (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1))) (head res)
findOneOrderBy op = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT ts , ts2 FROM tmp ORDER BY " ++ op ++ " LIMIT 1") []
return $ (\r -> Tmp (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1))) (head res)
findOneWhereOrderBy ss sp op = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.quickQuery' conn ("SELECT ts , ts2 FROM tmp WHERE (" ++ ss ++ ") ORDER BY " ++ op ++" LIMIT 1") sp
return $ (\r -> Tmp (HDBC.fromSql (r !! 0)) (HDBC.fromSql (r !! 1))) (head res)
deleteWhere :: (HasEnvironment m) => SelectString -> SelectParams -> m Integer
deleteWhere ss sp = do
conn <- getEnvironment >>= (return . fromJust . getDatabase )
res <- liftIO $ HDBC.handleSqlError $ HDBC.run conn ("DELETE FROM tmp WHERE (" ++ ss ++ ") ") sp
return res
| alsonkemp/turbinado-website | App/Models/Bases/TmpFunctions.hs | bsd-3-clause | 4,179 | 10 | 32 | 1,130 | 1,459 | 750 | 709 | 56 | 1 |
{-# OPTIONS_GHC -cpp -fglasgow-exts -package hsgnutls -package Network.HaskellNet #-}
-- examples to connect server by hsgnutls
module DebugStream
( connectD
, connectDPort
, DebugStream
, withDebug
, module BS
)
where
import Network
import Network.HaskellNet.BSStream
import Data.ByteString (ByteString)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Base as BSB
import System.IO
import Data.IORef
import Control.Monad
import Foreign.ForeignPtr
import Foreign.Ptr
newtype (BSStream s) => DebugStream s = DS s
withDebug :: BSStream s => s -> DebugStream s
withDebug = DS
connectD :: HostName -> PortNumber -> IO (DebugStream Handle)
connectD host port = connectDPort host (PortNumber port)
connectDPort :: HostName -> PortID -> IO (DebugStream Handle)
connectDPort host port =
do h <- connectTo host port
hPutStrLn stderr "connected"
return $ DS h
instance (BSStream s) => BSStream (DebugStream s) where
bsGetLine (DS h) =
do hPutStr stderr "reading with bsGetLine..."
hFlush stderr
l <- bsGetLine h
BS.hPutStrLn stderr l
return l
bsGet (DS h) len =
do hPutStr stderr $ "reading with bsGet "++show len++"..."
hFlush stderr
chunk <- bsGet h len
BS.hPutStrLn stderr chunk
return chunk
bsPut (DS h) s =
do hPutStr stderr "putting with bsPut ("
BS.hPutStrLn stderr s
hPutStr stderr (")...")
hFlush stderr
bsPut h s
bsFlush h
hPutStrLn stderr "done"
return ()
bsPutStrLn (DS h) s =
do hPutStr stderr "putting with bsPutStrLn("
BS.hPutStrLn stderr s
hPutStr stderr (")...")
hFlush stderr
bsPutStrLn h s
bsFlush h
hPutStrLn stderr "done"
return ()
bsPutCrLf (DS h) s =
do hPutStr stderr "putting with bsPutCrLf("
BS.hPutStrLn stderr s
hPutStr stderr (")...")
hFlush stderr
bsPutCrLf h s
bsFlush h
hPutStrLn stderr "done"
return ()
bsPutNoFlush (DS h) s =
do hPutStr stderr "putting with bsPutNoFlush ("
BS.hPutStrLn stderr s
hPutStr stderr (")...")
hFlush stderr
bsPut h s
hPutStrLn stderr "done"
return ()
bsFlush (DS h) = bsFlush h
bsClose (DS h) = bsClose h
| d3zd3z/HaskellNet-old | example/DebugStream.hs | bsd-3-clause | 2,508 | 0 | 11 | 828 | 733 | 340 | 393 | 77 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module IRTS.CodegenLLVM (codegenLLVM) where
import IRTS.CodegenCommon
import IRTS.Lang
import IRTS.Simplified
import IRTS.System
import qualified Idris.Core.TT as TT
import Idris.Core.TT (ArithTy(..), IntTy(..), NativeTy(..), nativeTyWidth)
import Util.System
import Paths_idris
import LLVM.General.Context
import LLVM.General.Diagnostic
import LLVM.General.AST
import LLVM.General.AST.AddrSpace
import LLVM.General.Target ( TargetMachine
, withTargetOptions, withTargetMachine, getTargetMachineDataLayout
, initializeAllTargets, lookupTarget
)
import LLVM.General.AST.DataLayout
import qualified LLVM.General.PassManager as PM
import qualified LLVM.General.Module as MO
import qualified LLVM.General.AST.IntegerPredicate as IPred
import qualified LLVM.General.AST.FloatingPointPredicate as FPred
import qualified LLVM.General.AST.Linkage as L
import qualified LLVM.General.AST.Visibility as V
import qualified LLVM.General.AST.CallingConvention as CC
import qualified LLVM.General.AST.Attribute as A
import qualified LLVM.General.AST.Global as G
import qualified LLVM.General.AST.Constant as C
import qualified LLVM.General.AST.Float as F
import qualified LLVM.General.Relocation as R
import qualified LLVM.General.CodeModel as CM
import qualified LLVM.General.CodeGenOpt as CGO
import Data.List
import Data.Maybe
import Data.Word
import Data.Map (Map)
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Vector.Unboxed as V
import Control.Applicative
import Control.Monad.RWS
import Control.Monad.Writer
import Control.Monad.State
import Control.Monad.Error
import qualified System.Info as SI (arch, os)
import System.IO
import System.Directory (removeFile)
import System.FilePath ((</>))
import System.Process (rawSystem)
import System.Exit (ExitCode(..))
import Debug.Trace
data Target = Target { triple :: String, dataLayout :: DataLayout }
codegenLLVM :: [(TT.Name, SDecl)] ->
String -> -- target triple
String -> -- target CPU
Word -> -- Optimization degree
FilePath -> -- output file name
OutputType ->
IO ()
codegenLLVM defs triple cpu optimize file outty = withContext $ \context -> do
initializeAllTargets
(target, _) <- failInIO $ lookupTarget Nothing triple
withTargetOptions $ \options ->
withTargetMachine target triple cpu S.empty options R.Default CM.Default CGO.Default $ \tm ->
do layout <- getTargetMachineDataLayout tm
let ast = codegen (Target triple layout) (map snd defs)
result <- runErrorT . MO.withModuleFromAST context ast $ \m ->
do let opts = PM.defaultCuratedPassSetSpec
{ PM.optLevel = Just optimize
, PM.simplifyLibCalls = Just True
, PM.useInlinerWithThreshold = Just 225
}
when (optimize /= 0) $ PM.withPassManager opts $ void . flip PM.runPassManager m
outputModule tm file outty m
case result of
Right _ -> return ()
Left msg -> ierror msg
failInIO :: ErrorT String IO a -> IO a
failInIO = either fail return <=< runErrorT
outputModule :: TargetMachine -> FilePath -> OutputType -> MO.Module -> IO ()
outputModule _ file Raw m = failInIO $ MO.writeBitcodeToFile file m
outputModule tm file Object m = failInIO $ MO.writeObjectToFile tm file m
outputModule tm file Executable m = withTmpFile $ \obj -> do
outputModule tm obj Object m
cc <- getCC
defs <- (</> "llvm" </> "libidris_rts.a") <$> getDataDir
exit <- rawSystem cc [obj, defs, "-lm", "-lgmp", "-lgc", "-o", file]
when (exit /= ExitSuccess) $ ierror "FAILURE: Linking"
outputModule _ _ MavenProject _ = ierror "FAILURE: unsupported output type"
withTmpFile :: (FilePath -> IO a) -> IO a
withTmpFile f = do
(path, handle) <- tempfile
hClose handle
result <- f path
removeFile path
return result
ierror :: String -> a
ierror msg = error $ "INTERNAL ERROR: IRTS.CodegenLLVM: " ++ msg
mainDef :: Global
mainDef =
functionDefaults
{ G.returnType = IntegerType 32
, G.parameters =
([ Parameter (IntegerType 32) (Name "argc") []
, Parameter (PointerType (PointerType (IntegerType 8) (AddrSpace 0)) (AddrSpace 0)) (Name "argv") []
], False)
, G.name = Name "main"
, G.basicBlocks =
[ BasicBlock (UnName 0)
[ Do $ simpleCall "GC_init" [] -- Initialize Boehm GC
, Do $ simpleCall "__gmp_set_memory_functions"
[ ConstantOperand . C.GlobalReference . Name $ "__idris_gmpMalloc"
, ConstantOperand . C.GlobalReference . Name $ "__idris_gmpRealloc"
, ConstantOperand . C.GlobalReference . Name $ "__idris_gmpFree"
]
, Do $ Store False (ConstantOperand . C.GlobalReference . Name $ "__idris_argc")
(LocalReference (Name "argc")) Nothing 0 []
, Do $ Store False (ConstantOperand . C.GlobalReference . Name $ "__idris_argv")
(LocalReference (Name "argv")) Nothing 0 []
, UnName 1 := idrCall "{runMain0}" [] ]
(Do $ Ret (Just (ConstantOperand (C.Int 32 0))) [])
]}
initDefs :: Target -> [Definition]
initDefs tgt =
[ TypeDefinition (Name "valTy")
(Just $ StructureType False
[ IntegerType 32
, ArrayType 0 (PointerType valueType (AddrSpace 0))
])
, TypeDefinition (Name "mpz")
(Just $ StructureType False
[ IntegerType 32
, IntegerType 32
, PointerType intPtr (AddrSpace 0)
])
, GlobalDefinition $ globalVariableDefaults
{ G.name = Name "__idris_intFmtStr"
, G.linkage = L.Internal
, G.isConstant = True
, G.hasUnnamedAddr = True
, G.type' = ArrayType 5 (IntegerType 8)
, G.initializer = Just $ C.Array (IntegerType 8) (map (C.Int 8 . fromIntegral . fromEnum) "%lld" ++ [C.Int 8 0])
}
, rtsFun "intStr" ptrI8 [IntegerType 64]
[ BasicBlock (UnName 0)
[ UnName 1 := simpleCall "GC_malloc_atomic" [ConstantOperand (C.Int (tgtWordSize tgt) 21)]
, UnName 2 := simpleCall "snprintf"
[ LocalReference (UnName 1)
, ConstantOperand (C.Int (tgtWordSize tgt) 21)
, ConstantOperand $ C.GetElementPtr True (C.GlobalReference . Name $ "__idris_intFmtStr") [C.Int 32 0, C.Int 32 0]
, LocalReference (UnName 0)
]
]
(Do $ Ret (Just (LocalReference (UnName 1))) [])
]
, GlobalDefinition $ globalVariableDefaults
{ G.name = Name "__idris_floatFmtStr"
, G.linkage = L.Internal
, G.isConstant = True
, G.hasUnnamedAddr = True
, G.type' = ArrayType 5 (IntegerType 8)
, G.initializer = Just $ C.Array (IntegerType 8) (map (C.Int 8 . fromIntegral . fromEnum) "%g" ++ [C.Int 8 0])
}
, rtsFun "floatStr" ptrI8 [FloatingPointType 64 IEEE]
[ BasicBlock (UnName 0)
[ UnName 1 := simpleCall "GC_malloc_atomic" [ConstantOperand (C.Int (tgtWordSize tgt) 21)]
, UnName 2 := simpleCall "snprintf"
[ LocalReference (UnName 1)
, ConstantOperand (C.Int (tgtWordSize tgt) 21)
, ConstantOperand $ C.GetElementPtr True (C.GlobalReference . Name $ "__idris_floatFmtStr") [C.Int 32 0, C.Int 32 0]
, LocalReference (UnName 0)
]
]
(Do $ Ret (Just (LocalReference (UnName 1))) [])
]
, exfun "llvm.sin.f64" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "llvm.cos.f64" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "llvm.pow.f64" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "llvm.ceil.f64" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "llvm.floor.f64" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "llvm.exp.f64" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "llvm.log.f64" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "llvm.sqrt.f64" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "tan" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "asin" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "acos" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "atan" (FloatingPointType 64 IEEE) [ FloatingPointType 64 IEEE ] False
, exfun "llvm.trap" VoidType [] False
-- , exfun "llvm.llvm.memcpy.p0i8.p0i8.i32" VoidType [ptrI8, ptrI8, IntegerType 32, IntegerType 32, IntegerType 1] False
-- , exfun "llvm.llvm.memcpy.p0i8.p0i8.i64" VoidType [ptrI8, ptrI8, IntegerType 64, IntegerType 32, IntegerType 1] False
, exfun "memcpy" ptrI8 [ptrI8, ptrI8, intPtr] False
, exfun "llvm.invariant.start" (PointerType (StructureType False []) (AddrSpace 0)) [IntegerType 64, ptrI8] False
, exfun "snprintf" (IntegerType 32) [ptrI8, intPtr, ptrI8] True
, exfun "strcmp" (IntegerType 32) [ptrI8, ptrI8] False
, exfun "strlen" intPtr [ptrI8] False
, exfun "GC_init" VoidType [] False
, exfun "GC_malloc" ptrI8 [intPtr] False
, exfun "GC_malloc_atomic" ptrI8 [intPtr] False
, exfun "__gmp_set_memory_functions" VoidType
[ PointerType (FunctionType ptrI8 [intPtr] False) (AddrSpace 0)
, PointerType (FunctionType ptrI8 [ptrI8, intPtr, intPtr] False) (AddrSpace 0)
, PointerType (FunctionType VoidType [ptrI8, intPtr] False) (AddrSpace 0)
] False
, exfun "__gmpz_init" VoidType [pmpz] False
, exfun "__gmpz_init_set_str" (IntegerType 32) [pmpz, ptrI8, IntegerType 32] False
, exfun "__gmpz_get_str" ptrI8 [ptrI8, IntegerType 32, pmpz] False
, exfun "__gmpz_get_ui" intPtr [pmpz] False
, exfun "__gmpz_cmp" (IntegerType 32) [pmpz, pmpz] False
, exfun "__gmpz_fdiv_q_2exp" VoidType [pmpz, pmpz, intPtr] False
, exfun "__gmpz_mul_2exp" VoidType [pmpz, pmpz, intPtr] False
, exfun "__gmpz_get_d" (FloatingPointType 64 IEEE) [pmpz] False
, exfun "__gmpz_set_d" VoidType [pmpz, FloatingPointType 64 IEEE] False
, exfun "mpz_get_ull" (IntegerType 64) [pmpz] False
, exfun "mpz_init_set_ull" VoidType [pmpz, IntegerType 64] False
, exfun "mpz_init_set_sll" VoidType [pmpz, IntegerType 64] False
, exfun "__idris_strCons" ptrI8 [IntegerType 8, ptrI8] False
, exfun "__idris_readStr" ptrI8 [ptrI8] False -- Actually pointer to FILE, but it's opaque anyway
, exfun "__idris_gmpMalloc" ptrI8 [intPtr] False
, exfun "__idris_gmpRealloc" ptrI8 [ptrI8, intPtr, intPtr] False
, exfun "__idris_gmpFree" VoidType [ptrI8, intPtr] False
, exfun "__idris_strRev" ptrI8 [ptrI8] False
, exfun "strtoll" (IntegerType 64) [ptrI8, PointerType ptrI8 (AddrSpace 0), IntegerType 32] False
, exfun "putErr" VoidType [ptrI8] False
, exVar (stdinName tgt) ptrI8
, exVar (stdoutName tgt) ptrI8
, exVar (stderrName tgt) ptrI8
, exVar "__idris_argc" (IntegerType 32)
, exVar "__idris_argv" (PointerType ptrI8 (AddrSpace 0))
, GlobalDefinition mainDef
] ++ map mpzBinFun ["add", "sub", "mul", "fdiv_q", "fdiv_r", "and", "ior", "xor"]
where
intPtr = IntegerType (tgtWordSize tgt)
ptrI8 = PointerType (IntegerType 8) (AddrSpace 0)
pmpz = PointerType mpzTy (AddrSpace 0)
mpzBinFun n = exfun ("__gmpz_" ++ n) VoidType [pmpz, pmpz, pmpz] False
rtsFun :: String -> Type -> [Type] -> [BasicBlock] -> Definition
rtsFun name rty argtys def =
GlobalDefinition $ functionDefaults
{ G.linkage = L.Internal
, G.returnType = rty
, G.parameters = (flip map argtys $ \ty -> Parameter ty (UnName 0) [], False)
, G.name = Name $ "__idris_" ++ name
, G.basicBlocks = def
}
exfun :: String -> Type -> [Type] -> Bool -> Definition
exfun name rty argtys vari =
GlobalDefinition $ functionDefaults
{ G.returnType = rty
, G.name = Name name
, G.parameters = (flip map argtys $ \ty -> Parameter ty (UnName 0) [], vari)
}
exVar :: String -> Type -> Definition
exVar name ty = GlobalDefinition $ globalVariableDefaults { G.name = Name name, G.type' = ty }
isApple :: Target -> Bool
isApple (Target { triple = t }) = isJust . stripPrefix "-apple" $ dropWhile (/= '-') t
stdinName, stdoutName, stderrName :: Target -> String
stdinName t | isApple t = "__stdinp"
stdinName _ = "stdin"
stdoutName t | isApple t = "__stdoutp"
stdoutName _ = "stdout"
stderrName t | isApple t = "__stderrp"
stderrName _ = "stderr"
getStdIn, getStdOut, getStdErr :: Codegen Operand
getStdIn = ConstantOperand . C.GlobalReference . Name . stdinName <$> asks target
getStdOut = ConstantOperand . C.GlobalReference . Name . stdoutName <$> asks target
getStdErr = ConstantOperand . C.GlobalReference . Name . stderrName <$> asks target
codegen :: Target -> [SDecl] -> Module
codegen tgt defs = Module "idris" (Just . dataLayout $ tgt) (Just . triple $ tgt) (initDefs tgt ++ globals ++ gendefs)
where
(gendefs, _, globals) = runRWS (mapM cgDef defs) tgt initialMGS
valueType :: Type
valueType = NamedTypeReference (Name "valTy")
nullValue :: C.Constant
nullValue = C.Null (PointerType valueType (AddrSpace 0))
primTy :: Type -> Type
primTy inner = StructureType False [IntegerType 32, inner]
mpzTy :: Type
mpzTy = NamedTypeReference (Name "mpz")
conType :: Word64 -> Type
conType nargs = StructureType False
[ IntegerType 32
, ArrayType nargs (PointerType valueType (AddrSpace 0))
]
data MGS = MGS { mgsNextGlobalName :: Word
, mgsForeignSyms :: Map String (FType, [FType])
}
type Modgen = RWS Target [Definition] MGS
initialMGS :: MGS
initialMGS = MGS { mgsNextGlobalName = 0
, mgsForeignSyms = M.empty
}
cgDef :: SDecl -> Modgen Definition
cgDef (SFun name argNames _ expr) = do
nextGlobal <- gets mgsNextGlobalName
existingForeignSyms <- gets mgsForeignSyms
tgt <- ask
let (_, CGS { nextGlobalName = nextGlobal', foreignSyms = foreignSyms' }, (allocas, bbs, globals)) =
runRWS (do r <- cgExpr expr
case r of
Nothing -> terminate $ Unreachable []
Just r' -> terminate $ Ret (Just r') [])
(CGR tgt (show name))
(CGS 0 nextGlobal (Name "begin") [] (map (Just . LocalReference . Name . show) argNames) existingForeignSyms)
entryTerm = case bbs of
[] -> Do $ Ret Nothing []
BasicBlock n _ _:_ -> Do $ Br n []
tell globals
put (MGS { mgsNextGlobalName = nextGlobal', mgsForeignSyms = foreignSyms' })
return . GlobalDefinition $ functionDefaults
{ G.linkage = L.Internal
, G.callingConvention = CC.Fast
, G.name = Name (show name)
, G.returnType = PointerType valueType (AddrSpace 0)
, G.parameters = (flip map argNames $ \argName ->
Parameter (PointerType valueType (AddrSpace 0)) (Name (show argName)) []
, False)
, G.basicBlocks =
BasicBlock (Name "entry")
(map (\(n, t) -> n := Alloca t Nothing 0 []) allocas)
entryTerm
: bbs
}
type CGW = ([(Name, Type)], [BasicBlock], [Definition])
type Env = [Maybe Operand]
data CGS = CGS { nextName :: Word
, nextGlobalName :: Word
, currentBlockName :: Name
, instAccum :: [Named Instruction]
, lexenv :: Env
, foreignSyms :: Map String (FType, [FType])
}
data CGR = CGR { target :: Target
, funcName :: String }
type Codegen = RWS CGR CGW CGS
getFuncName :: Codegen String
getFuncName = asks funcName
getGlobalUnName :: Codegen Name
getGlobalUnName = do
i <- gets nextGlobalName
modify $ \s -> s { nextGlobalName = 1 + i }
return (UnName i)
getUnName :: Codegen Name
getUnName = do
i <- gets nextName
modify $ \s -> s { nextName = 1 + i }
return (UnName i)
getName :: String -> Codegen Name
getName n = do
i <- gets nextName
modify $ \s -> s { nextName = 1 + i }
return (Name $ n ++ show i)
alloca :: Name -> Type -> Codegen ()
alloca n t = tell ([(n, t)], [], [])
terminate :: Terminator -> Codegen ()
terminate term = do
name <- gets currentBlockName
insts <- gets instAccum
modify $ \s -> s { instAccum = ierror "Not in a block"
, currentBlockName = ierror "Not in a block" }
tell ([], [BasicBlock name insts (Do term)], [])
newBlock :: Name -> Codegen ()
newBlock name = modify $ \s -> s { instAccum = []
, currentBlockName = name
}
inst :: Instruction -> Codegen Operand
inst i = do
n <- getUnName
modify $ \s -> s { instAccum = instAccum s ++ [n := i] }
return $ LocalReference n
ninst :: String -> Instruction -> Codegen Operand
ninst name i = do
n <- getName name
modify $ \s -> s { instAccum = instAccum s ++ [n := i] }
return $ LocalReference n
inst' :: Instruction -> Codegen ()
inst' i = modify $ \s -> s { instAccum = instAccum s ++ [Do i] }
insts :: [Named Instruction] -> Codegen ()
insts is = modify $ \s -> s { instAccum = instAccum s ++ is }
var :: LVar -> Codegen (Maybe Operand)
var (Loc level) = (!! level) <$> gets lexenv
var (Glob n) = return . Just . ConstantOperand . C.GlobalReference . Name $ show n
binds :: Env -> Codegen (Maybe Operand) -> Codegen (Maybe Operand)
binds vals cg = do
envLen <- length <$> gets lexenv
modify $ \s -> s { lexenv = lexenv s ++ vals }
value <- cg
modify $ \s -> s { lexenv = take envLen $ lexenv s }
return value
replaceElt :: Int -> a -> [a] -> [a]
replaceElt _ val [] = error "replaceElt: Ran out of list"
replaceElt 0 val (x:xs) = val:xs
replaceElt n val (x:xs) = x : replaceElt (n-1) val xs
alloc' :: Operand -> Codegen Operand
alloc' size = inst $ simpleCall "GC_malloc" [size]
allocAtomic' :: Operand -> Codegen Operand
allocAtomic' size = inst $ simpleCall "GC_malloc_atomic" [size]
alloc :: Type -> Codegen Operand
alloc ty = do
size <- sizeOf ty
mem <- alloc' size
inst $ BitCast mem (PointerType ty (AddrSpace 0)) []
allocAtomic :: Type -> Codegen Operand
allocAtomic ty = do
size <- sizeOf ty
mem <- allocAtomic' size
inst $ BitCast mem (PointerType ty (AddrSpace 0)) []
sizeOf :: Type -> Codegen Operand
sizeOf ty = ConstantOperand . C.PtrToInt
(C.GetElementPtr True (C.Null (PointerType ty (AddrSpace 0))) [C.Int 32 1])
. IntegerType <$> getWordSize
loadInv :: Operand -> Instruction
loadInv ptr = Load False ptr Nothing 0 [("invariant.load", MetadataNode [])]
tgtWordSize :: Target -> Word32
tgtWordSize (Target { dataLayout = DataLayout { pointerLayouts = l } }) =
fst . fromJust $ M.lookup (AddrSpace 0) l
getWordSize :: Codegen Word32
getWordSize = tgtWordSize <$> asks target
cgExpr :: SExp -> Codegen (Maybe Operand)
cgExpr (SV v) = var v
cgExpr (SApp tailcall fname args) = do
argSlots <- mapM var args
case sequence argSlots of
Nothing -> return Nothing
Just argVals -> do
fn <- var (Glob fname)
Just <$> inst ((idrCall (show fname) argVals) { isTailCall = tailcall })
cgExpr (SLet _ varExpr bodyExpr) = do
val <- cgExpr varExpr
binds [val] $ cgExpr bodyExpr
cgExpr (SUpdate (Loc level) expr) = do
val <- cgExpr expr
modify $ \s -> s { lexenv = replaceElt level val (lexenv s) }
return val
cgExpr (SUpdate x expr) = cgExpr expr
cgExpr (SCon tag name args) = do
argSlots <- mapM var args
case sequence argSlots of
Nothing -> return Nothing
Just argVals -> do
let ty = conType . fromIntegral . length $ argVals
con <- alloc ty
tagPtr <- inst $ GetElementPtr True con [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 0)] []
inst' $ Store False tagPtr (ConstantOperand (C.Int 32 (fromIntegral tag))) Nothing 0 []
forM_ (zip argVals [0..]) $ \(arg, i) -> do
ptr <- inst $ GetElementPtr True con [ ConstantOperand (C.Int 32 0)
, ConstantOperand (C.Int 32 1)
, ConstantOperand (C.Int 32 i)] []
inst' $ Store False ptr arg Nothing 0 []
ptrI8 <- inst $ BitCast con (PointerType (IntegerType 8) (AddrSpace 0)) []
inst' $ simpleCall "llvm.invariant.start" [ConstantOperand $ C.Int 64 (-1), ptrI8]
Just <$> inst (BitCast con (PointerType valueType (AddrSpace 0)) [])
cgExpr (SCase inspect alts) = do
val <- var inspect
case val of
Nothing -> return Nothing
Just v -> cgCase v alts
cgExpr (SChkCase inspect alts) = do
mval <- var inspect
case mval of
Nothing -> return Nothing
Just val ->
do endBBN <- getName "endChkCase"
notNullBBN <- getName "notNull"
originBlock <- gets currentBlockName
isNull <- inst $ ICmp IPred.EQ val (ConstantOperand nullValue) []
terminate $ CondBr isNull endBBN notNullBBN []
newBlock notNullBBN
ptr <- inst $ BitCast val (PointerType (IntegerType 32) (AddrSpace 0)) []
flag <- inst $ loadInv ptr
isVal <- inst $ ICmp IPred.EQ flag (ConstantOperand (C.Int 32 (-1))) []
conBBN <- getName "constructor"
terminate $ CondBr isVal endBBN conBBN []
newBlock conBBN
result <- cgCase val alts
caseExitBlock <- gets currentBlockName
case result of
Nothing -> do
terminate $ Unreachable []
newBlock endBBN
return $ Just val
Just caseVal -> do
terminate $ Br endBBN []
newBlock endBBN
Just <$> inst (Phi (PointerType valueType (AddrSpace 0))
[(val, originBlock), (val, notNullBBN), (caseVal, caseExitBlock)] [])
cgExpr (SProj conVar idx) = do
val <- var conVar
case val of
Nothing -> return Nothing
Just v ->
do ptr <- inst $ GetElementPtr True v
[ ConstantOperand (C.Int 32 0)
, ConstantOperand (C.Int 32 1)
, ConstantOperand (C.Int 32 (fromIntegral idx))
] []
Just <$> inst (loadInv ptr)
cgExpr (SConst c) = Just <$> cgConst c
cgExpr (SForeign LANG_C rty fname args) = do
func <- ensureCDecl fname rty (map fst args)
argVals <- forM args $ \(fty, v) -> do
v' <- var v
case v' of
Just val -> return $ Just (fty, val)
Nothing -> return Nothing
case sequence argVals of
Nothing -> return Nothing
Just argVals' -> do
argUVals <- mapM (uncurry unbox) argVals'
result <- inst Call { isTailCall = False
, callingConvention = CC.C
, returnAttributes = []
, function = Right func
, arguments = map (\v -> (v, [])) argUVals
, functionAttributes = []
, metadata = []
}
Just <$> box rty result
cgExpr (SOp fn args) = do
argVals <- mapM var args
case sequence argVals of
Just ops -> Just <$> cgOp fn ops
Nothing -> return Nothing
cgExpr SNothing = return . Just . ConstantOperand $ nullValue
cgExpr (SError msg) = do
str <- addGlobal' (ArrayType (2 + fromIntegral (length msg)) (IntegerType 8))
(cgConst' (TT.Str (msg ++ "\n")))
inst' $ simpleCall "putErr" [ConstantOperand $ C.GetElementPtr True str [ C.Int 32 0
, C.Int 32 0]]
inst' Call { isTailCall = True
, callingConvention = CC.C
, returnAttributes = []
, function = Right . ConstantOperand . C.GlobalReference . Name $ "llvm.trap"
, arguments = []
, functionAttributes = [A.NoReturn]
, metadata = []
}
return Nothing
cgCase :: Operand -> [SAlt] -> Codegen (Maybe Operand)
cgCase val alts =
case find isConstCase alts of
Just (SConstCase (TT.BI _) _) -> cgChainCase val defExp constAlts
Just (SConstCase (TT.Str _) _) -> cgChainCase val defExp constAlts
Just (SConstCase _ _) -> cgPrimCase val defExp constAlts
Nothing -> cgConCase val defExp conAlts
where
defExp = getDefExp =<< find isDefCase alts
constAlts = filter isConstCase alts
conAlts = filter isConCase alts
isConstCase (SConstCase {}) = True
isConstCase _ = False
isConCase (SConCase {}) = True
isConCase _ = False
isDefCase (SDefaultCase _) = True
isDefCase _ = False
getDefExp (SDefaultCase e) = Just e
getDefExp _ = Nothing
cgPrimCase :: Operand -> Maybe SExp -> [SAlt] -> Codegen (Maybe Operand)
cgPrimCase caseValPtr defExp alts = do
let caseTy = case head alts of
SConstCase (TT.I _) _ -> IntegerType 32
SConstCase (TT.B8 _) _ -> IntegerType 8
SConstCase (TT.B16 _) _ -> IntegerType 16
SConstCase (TT.B32 _) _ -> IntegerType 32
SConstCase (TT.B64 _) _ -> IntegerType 64
SConstCase (TT.Fl _) _ -> FloatingPointType 64 IEEE
SConstCase (TT.Ch _) _ -> IntegerType 32
realPtr <- inst $ BitCast caseValPtr (PointerType (primTy caseTy) (AddrSpace 0)) []
valPtr <- inst $ GetElementPtr True realPtr [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 1)] []
caseVal <- inst $ loadInv valPtr
defBlockName <- getName "default"
exitBlockName <- getName "caseExit"
namedAlts <- mapM (\a -> do n <- nameAlt defBlockName a; return (n, a)) alts
terminate $ Switch caseVal defBlockName (map (\(n, SConstCase c _) -> (cgConst' c, n)) namedAlts) []
initEnv <- gets lexenv
defResult <- cgDefaultAlt exitBlockName defBlockName defExp
results <- forM namedAlts $ \(name, SConstCase _ exp) -> cgAlt initEnv exitBlockName name Nothing exp
finishCase initEnv exitBlockName (defResult:results)
cgConCase :: Operand -> Maybe SExp -> [SAlt] -> Codegen (Maybe Operand)
cgConCase con defExp alts = do
tagPtr <- inst $ GetElementPtr True con [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 0)] []
tag <- inst $ loadInv tagPtr
defBlockName <- getName "default"
exitBlockName <- getName "caseExit"
namedAlts <- mapM (\a -> do n <- nameAlt defBlockName a; return (n, a)) alts
terminate $ Switch tag defBlockName (map (\(n, SConCase _ tag _ _ _) ->
(C.Int 32 (fromIntegral tag), n)) namedAlts) []
initEnv <- gets lexenv
defResult <- cgDefaultAlt exitBlockName defBlockName defExp
results <- forM namedAlts $ \(name, SConCase _ _ _ argns exp) ->
cgAlt initEnv exitBlockName name (Just (con, map show argns)) exp
finishCase initEnv exitBlockName (defResult:results)
cgChainCase :: Operand -> Maybe SExp -> [SAlt] -> Codegen (Maybe Operand)
cgChainCase caseValPtr defExp alts = do
let (caseTy, comparator) =
case head alts of
SConstCase (TT.BI _) _ -> (FArith (ATInt ITBig), "__gmpz_cmp")
SConstCase (TT.Str _) _ -> (FString, "strcmp")
caseVal <- unbox caseTy caseValPtr
defBlockName <- getName "default"
exitBlockName <- getName "caseExit"
namedAlts <- mapM (\a -> do n <- nameAlt defBlockName a; return (n, a)) alts
initEnv <- gets lexenv
results <- forM namedAlts $ \(name, SConstCase c e) ->
do const <- unbox caseTy =<< cgConst c
cmp <- inst $ simpleCall comparator [const, caseVal]
cmpResult <- inst $ ICmp IPred.EQ cmp (ConstantOperand (C.Int 32 0)) []
elseName <- getName "else"
terminate $ CondBr cmpResult name elseName []
result <- cgAlt initEnv exitBlockName name Nothing e
newBlock elseName
return result
modify $ \s -> s { lexenv = initEnv }
fname <- getFuncName
defaultVal <- cgExpr (fromMaybe (SError $ "Inexhaustive case failure in " ++ fname) defExp)
defaultBlock <- gets currentBlockName
defaultEnv <- gets lexenv
defResult <- case defaultVal of
Just v -> do
terminate $ Br exitBlockName []
return $ Just (v, defaultBlock, defaultEnv)
Nothing -> do
terminate $ Unreachable []
return Nothing
finishCase initEnv exitBlockName (defResult:results)
finishCase :: Env -> Name -> [Maybe (Operand, Name, Env)] -> Codegen (Maybe Operand)
finishCase initEnv exitBlockName results = do
let definedResults = mapMaybe id results
case definedResults of
[] -> do modify $ \s -> s { lexenv = initEnv }
return Nothing
xs -> do
newBlock exitBlockName
mergeEnvs $ map (\(_, altBlock, altEnv) -> (altBlock, altEnv)) xs
Just <$> inst (Phi (PointerType valueType (AddrSpace 0))
(map (\(altVal, altBlock, _) -> (altVal, altBlock)) xs) [])
cgDefaultAlt :: Name -> Name -> Maybe SExp -> Codegen (Maybe (Operand, Name, Env))
cgDefaultAlt exitName name exp = do
newBlock name
fname <- getFuncName
val <- cgExpr (fromMaybe (SError $ "Inexhaustive case failure in " ++ fname) exp)
env <- gets lexenv
block <- gets currentBlockName
case val of
Just v ->
do terminate $ Br exitName []
return $ Just (v, block, env)
Nothing ->
do terminate $ Unreachable []
return Nothing
cgAlt :: Env -> Name -> Name -> Maybe (Operand, [String]) -> SExp
-> Codegen (Maybe (Operand, Name, Env))
cgAlt initEnv exitBlockName name destr exp = do
modify $ \s -> s { lexenv = initEnv }
newBlock name
locals <- case destr of
Nothing -> return []
Just (con, argns) ->
forM (zip argns [0..]) $ \(argName, i) ->
do ptr <- inst $ GetElementPtr True con [ ConstantOperand (C.Int 32 0)
, ConstantOperand (C.Int 32 1)
, ConstantOperand (C.Int 32 i)] []
Just <$> ninst argName (loadInv ptr)
altVal <- binds locals $ cgExpr exp
altEnv <- gets lexenv
altBlock <- gets currentBlockName
case altVal of
Just v -> do
terminate $ Br exitBlockName []
return $ Just (v, altBlock, altEnv)
Nothing -> do
terminate $ Unreachable []
return Nothing
mergeEnvs :: [(Name, Env)] -> Codegen ()
mergeEnvs es = do
let vars = transpose
. map (\(block, env) -> map (\x -> (x, block)) env)
$ es
env <- forM vars $ \var ->
case var of
[] -> ierror "mergeEnvs: impossible"
[(v, _)] -> return v
vs@((v, _):_)
| all (== v) (map fst vs) -> return v
| otherwise ->
let valid = map (\(a, b) -> (fromJust a, b)) . filter (isJust . fst) $ vs in
Just <$> inst (Phi (PointerType valueType (AddrSpace 0)) valid [])
modify $ \s -> s { lexenv = env }
nameAlt :: Name -> SAlt -> Codegen Name
nameAlt d (SDefaultCase _) = return d
nameAlt _ (SConCase _ _ name _ _) = getName (show name)
nameAlt _ (SConstCase const _) = getName (show const)
isHeapFTy :: FType -> Bool
isHeapFTy f = elem f [FString, FPtr, FAny, FArith (ATInt ITBig)]
box :: FType -> Operand -> Codegen Operand
box FUnit _ = return $ ConstantOperand nullValue
box fty fval = do
let ty = primTy (ftyToTy fty)
val <- if isHeapFTy fty then alloc ty else allocAtomic ty
tagptr <- inst $ GetElementPtr True val [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 0)] []
valptr <- inst $ GetElementPtr True val [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 1)] []
inst' $ Store False tagptr (ConstantOperand (C.Int 32 (-1))) Nothing 0 []
inst' $ Store False valptr fval Nothing 0 []
ptrI8 <- inst $ BitCast val (PointerType (IntegerType 8) (AddrSpace 0)) []
inst' $ simpleCall "llvm.invariant.start" [ConstantOperand $ C.Int 64 (-1), ptrI8]
inst $ BitCast val (PointerType valueType (AddrSpace 0)) []
unbox :: FType -> Operand -> Codegen Operand
unbox FUnit x = return x
unbox fty bval = do
val <- inst $ BitCast bval (PointerType (primTy (ftyToTy fty)) (AddrSpace 0)) []
fvalptr <- inst $ GetElementPtr True val [ConstantOperand (C.Int 32 0), ConstantOperand (C.Int 32 1)] []
inst $ loadInv fvalptr
cgConst' :: TT.Const -> C.Constant
cgConst' (TT.I i) = C.Int 32 (fromIntegral i)
cgConst' (TT.B8 i) = C.Int 8 (fromIntegral i)
cgConst' (TT.B16 i) = C.Int 16 (fromIntegral i)
cgConst' (TT.B32 i) = C.Int 32 (fromIntegral i)
cgConst' (TT.B64 i) = C.Int 64 (fromIntegral i)
cgConst' (TT.B8V v) = C.Vector (map ((C.Int 8) . fromIntegral) . V.toList $ v)
cgConst' (TT.B16V v) = C.Vector (map ((C.Int 16) . fromIntegral) . V.toList $ v)
cgConst' (TT.B32V v) = C.Vector (map ((C.Int 32) . fromIntegral) . V.toList $ v)
cgConst' (TT.B64V v) = C.Vector (map ((C.Int 64) . fromIntegral) . V.toList $ v)
cgConst' (TT.BI i) = C.Array (IntegerType 8) (map (C.Int 8 . fromIntegral . fromEnum) (show i) ++ [C.Int 8 0])
cgConst' (TT.Fl f) = C.Float (F.Double f)
cgConst' (TT.Ch c) = C.Int 32 . fromIntegral . fromEnum $ c
cgConst' (TT.Str s) = C.Array (IntegerType 8) (map (C.Int 8 . fromIntegral . fromEnum) s ++ [C.Int 8 0])
cgConst' x = ierror $ "Unsupported constant: " ++ show x
cgConst :: TT.Const -> Codegen Operand
cgConst c@(TT.I _) = box (FArith (ATInt ITNative)) (ConstantOperand $ cgConst' c)
cgConst c@(TT.B8 _) = box (FArith (ATInt (ITFixed IT8))) (ConstantOperand $ cgConst' c)
cgConst c@(TT.B16 _) = box (FArith (ATInt (ITFixed IT16))) (ConstantOperand $ cgConst' c)
cgConst c@(TT.B32 _) = box (FArith (ATInt (ITFixed IT32))) (ConstantOperand $ cgConst' c)
cgConst c@(TT.B64 _) = box (FArith (ATInt (ITFixed IT64))) (ConstantOperand $ cgConst' c)
cgConst c@(TT.B8V v) = box (FArith (ATInt (ITVec IT8 (V.length v)))) (ConstantOperand $ cgConst' c)
cgConst c@(TT.B16V v) = box (FArith (ATInt (ITVec IT16 (V.length v)))) (ConstantOperand $ cgConst' c)
cgConst c@(TT.B32V v) = box (FArith (ATInt (ITVec IT32 (V.length v)))) (ConstantOperand $ cgConst' c)
cgConst c@(TT.B64V v) = box (FArith (ATInt (ITVec IT64 (V.length v)))) (ConstantOperand $ cgConst' c)
cgConst c@(TT.Fl _) = box (FArith ATFloat) (ConstantOperand $ cgConst' c)
cgConst c@(TT.Ch _) = box (FArith (ATInt ITChar)) (ConstantOperand $ cgConst' c)
cgConst c@(TT.Str s) = do
str <- addGlobal' (ArrayType (1 + fromIntegral (length s)) (IntegerType 8)) (cgConst' c)
box FString (ConstantOperand $ C.GetElementPtr True str [C.Int 32 0, C.Int 32 0])
cgConst c@(TT.BI i) = do
let stringRepLen = (if i < 0 then 2 else 1) + fromInteger (numDigits 10 i)
str <- addGlobal' (ArrayType stringRepLen (IntegerType 8)) (cgConst' c)
mpz <- alloc mpzTy
inst $ simpleCall "__gmpz_init_set_str" [mpz
, ConstantOperand $ C.GetElementPtr True str [ C.Int 32 0, C.Int 32 0]
, ConstantOperand $ C.Int 32 10
]
box (FArith (ATInt ITBig)) mpz
cgConst x = return $ ConstantOperand nullValue
numDigits :: Integer -> Integer -> Integer
numDigits b n = 1 + fst (ilog b n) where
ilog b n
| n < b = (0, n)
| otherwise = let (e, r) = ilog (b*b) n
in if r < b then (2*e, r) else (2*e+1, r `div` b)
addGlobal :: Global -> Codegen ()
addGlobal def = tell ([], [], [GlobalDefinition def])
addGlobal' :: Type -> C.Constant -> Codegen C.Constant
addGlobal' ty val = do
name <- getGlobalUnName
addGlobal $ globalVariableDefaults
{ G.name = name
, G.linkage = L.Internal
, G.hasUnnamedAddr = True
, G.isConstant = True
, G.type' = ty
, G.initializer = Just val
}
return . C.GlobalReference $ name
ensureCDecl :: String -> FType -> [FType] -> Codegen Operand
ensureCDecl name rty argtys = do
syms <- gets foreignSyms
case M.lookup name syms of
Nothing -> do addGlobal (ffunDecl name rty argtys)
modify $ \s -> s { foreignSyms = M.insert name (rty, argtys) (foreignSyms s) }
Just (rty', argtys') -> unless (rty == rty' && argtys == argtys') . fail $
"Mismatched type declarations for foreign symbol \"" ++ name ++ "\": " ++ show (rty, argtys) ++ " vs " ++ show (rty', argtys')
return $ ConstantOperand (C.GlobalReference (Name name))
ffunDecl :: String -> FType -> [FType] -> Global
ffunDecl name rty argtys =
functionDefaults
{ G.returnType = ftyToTy rty
, G.name = Name name
, G.parameters = (flip map argtys $ \fty ->
Parameter (ftyToTy fty) (UnName 0) []
, False)
}
ftyToTy :: FType -> Type
ftyToTy (FArith (ATInt ITNative)) = IntegerType 32
ftyToTy (FArith (ATInt ITBig)) = PointerType mpzTy (AddrSpace 0)
ftyToTy (FArith (ATInt (ITFixed ty))) = IntegerType (fromIntegral $ nativeTyWidth ty)
ftyToTy (FArith (ATInt (ITVec e c)))
= VectorType (fromIntegral c) (IntegerType (fromIntegral $ nativeTyWidth e))
ftyToTy (FArith (ATInt ITChar)) = IntegerType 32
ftyToTy (FArith ATFloat) = FloatingPointType 64 IEEE
ftyToTy FString = PointerType (IntegerType 8) (AddrSpace 0)
ftyToTy FUnit = VoidType
ftyToTy FPtr = PointerType (IntegerType 8) (AddrSpace 0)
ftyToTy FAny = valueType
-- Only use when known not to be ITBig
itWidth :: IntTy -> Word32
itWidth ITNative = 32
itWidth ITChar = 32
itWidth (ITFixed x) = fromIntegral $ nativeTyWidth x
itWidth x = ierror $ "itWidth: " ++ show x
itConst :: IntTy -> Integer -> C.Constant
itConst (ITFixed n) x = C.Int (fromIntegral $ nativeTyWidth n) x
itConst ITNative x = itConst (ITFixed IT32) x
itConst ITChar x = itConst (ITFixed IT32) x
itConst (ITVec elts size) x = C.Vector (replicate size (itConst (ITFixed elts) x))
cgOp :: PrimFn -> [Operand] -> Codegen Operand
cgOp (LTrunc ITBig ity) [x] = do
nx <- unbox (FArith (ATInt ITBig)) x
val <- inst $ simpleCall "mpz_get_ull" [nx]
v <- case ity of
(ITFixed IT64) -> return val
_ -> inst $ Trunc val (ftyToTy (FArith (ATInt ity))) []
box (FArith (ATInt ity)) v
cgOp (LZExt from ITBig) [x] = do
nx <- unbox (FArith (ATInt from)) x
nx' <- case from of
(ITFixed IT64) -> return nx
_ -> inst $ ZExt nx (IntegerType 64) []
mpz <- alloc mpzTy
inst' $ simpleCall "mpz_init_set_ull" [mpz, nx']
box (FArith (ATInt ITBig)) mpz
cgOp (LSExt from ITBig) [x] = do
nx <- unbox (FArith (ATInt from)) x
nx' <- case from of
(ITFixed IT64) -> return nx
_ -> inst $ SExt nx (IntegerType 64) []
mpz <- alloc mpzTy
inst' $ simpleCall "mpz_init_set_sll" [mpz, nx']
box (FArith (ATInt ITBig)) mpz
-- ITChar, ITNative, and IT32 all share representation
cgOp (LChInt ITNative) [x] = return x
cgOp (LIntCh ITNative) [x] = return x
cgOp (LSLt (ATInt ITBig)) [x,y] = mpzCmp IPred.SLT x y
cgOp (LSLe (ATInt ITBig)) [x,y] = mpzCmp IPred.SLE x y
cgOp (LEq (ATInt ITBig)) [x,y] = mpzCmp IPred.EQ x y
cgOp (LSGe (ATInt ITBig)) [x,y] = mpzCmp IPred.SGE x y
cgOp (LSGt (ATInt ITBig)) [x,y] = mpzCmp IPred.SGT x y
cgOp (LPlus (ATInt ITBig)) [x,y] = mpzBin "add" x y
cgOp (LMinus (ATInt ITBig)) [x,y] = mpzBin "sub" x y
cgOp (LTimes (ATInt ITBig)) [x,y] = mpzBin "mul" x y
cgOp (LSDiv (ATInt ITBig)) [x,y] = mpzBin "fdiv_q" x y
cgOp (LSRem (ATInt ITBig)) [x,y] = mpzBin "fdiv_r" x y
cgOp (LAnd ITBig) [x,y] = mpzBin "and" x y
cgOp (LOr ITBig) [x,y] = mpzBin "ior" x y
cgOp (LXOr ITBig) [x,y] = mpzBin "xor" x y
cgOp (LCompl ITBig) [x] = mpzUn "com" x
cgOp (LSHL ITBig) [x,y] = mpzBit "mul_2exp" x y
cgOp (LASHR ITBig) [x,y] = mpzBit "fdiv_q_2exp" x y
cgOp (LTrunc ITNative (ITFixed to)) [x]
| 32 >= nativeTyWidth to = iCoerce Trunc IT32 to x
cgOp (LZExt ITNative (ITFixed to)) [x]
| 32 <= nativeTyWidth to = iCoerce ZExt IT32 to x
cgOp (LSExt ITNative (ITFixed to)) [x]
| 32 <= nativeTyWidth to = iCoerce SExt IT32 to x
cgOp (LTrunc (ITFixed from) ITNative) [x]
| nativeTyWidth from >= 32 = iCoerce Trunc from IT32 x
cgOp (LZExt (ITFixed from) ITNative) [x]
| nativeTyWidth from <= 32 = iCoerce ZExt from IT32 x
cgOp (LSExt (ITFixed from) ITNative) [x]
| nativeTyWidth from <= 32 = iCoerce SExt from IT32 x
cgOp (LTrunc (ITFixed from) (ITFixed to)) [x]
| nativeTyWidth from > nativeTyWidth to = iCoerce Trunc from to x
cgOp (LZExt (ITFixed from) (ITFixed to)) [x]
| nativeTyWidth from < nativeTyWidth to = iCoerce ZExt from to x
cgOp (LSExt (ITFixed from) (ITFixed to)) [x]
| nativeTyWidth from < nativeTyWidth to = iCoerce SExt from to x
cgOp (LSLt (ATInt ity)) [x,y] = iCmp ity IPred.SLT x y
cgOp (LSLe (ATInt ity)) [x,y] = iCmp ity IPred.SLE x y
cgOp (LLt ity) [x,y] = iCmp ity IPred.ULT x y
cgOp (LLe ity) [x,y] = iCmp ity IPred.ULE x y
cgOp (LEq (ATInt ity)) [x,y] = iCmp ity IPred.EQ x y
cgOp (LSGe (ATInt ity)) [x,y] = iCmp ity IPred.SGE x y
cgOp (LSGt (ATInt ity)) [x,y] = iCmp ity IPred.SGT x y
cgOp (LGe ity) [x,y] = iCmp ity IPred.UGE x y
cgOp (LGt ity) [x,y] = iCmp ity IPred.UGT x y
cgOp (LPlus ty@(ATInt _)) [x,y] = binary ty x y (Add False False)
cgOp (LMinus ty@(ATInt _)) [x,y] = binary ty x y (Sub False False)
cgOp (LTimes ty@(ATInt _)) [x,y] = binary ty x y (Mul False False)
cgOp (LSDiv ty@(ATInt _)) [x,y] = binary ty x y (SDiv False)
cgOp (LSRem ty@(ATInt _)) [x,y] = binary ty x y SRem
cgOp (LUDiv ity) [x,y] = binary (ATInt ity) x y (UDiv False)
cgOp (LURem ity) [x,y] = binary (ATInt ity) x y URem
cgOp (LAnd ity) [x,y] = binary (ATInt ity) x y And
cgOp (LOr ity) [x,y] = binary (ATInt ity) x y Or
cgOp (LXOr ity) [x,y] = binary (ATInt ity) x y Xor
cgOp (LCompl ity) [x] = unary (ATInt ity) x (Xor . ConstantOperand $ itConst ity (-1))
cgOp (LSHL ity) [x,y] = binary (ATInt ity) x y (Shl False False)
cgOp (LLSHR ity) [x,y] = binary (ATInt ity) x y (LShr False)
cgOp (LASHR ity) [x,y] = binary (ATInt ity) x y (AShr False)
cgOp (LSLt ATFloat) [x,y] = fCmp FPred.OLT x y
cgOp (LSLe ATFloat) [x,y] = fCmp FPred.OLE x y
cgOp (LEq ATFloat) [x,y] = fCmp FPred.OEQ x y
cgOp (LSGe ATFloat) [x,y] = fCmp FPred.OGE x y
cgOp (LSGt ATFloat) [x,y] = fCmp FPred.OGT x y
cgOp (LPlus ATFloat) [x,y] = binary ATFloat x y FAdd
cgOp (LMinus ATFloat) [x,y] = binary ATFloat x y FSub
cgOp (LTimes ATFloat) [x,y] = binary ATFloat x y FMul
cgOp (LSDiv ATFloat) [x,y] = binary ATFloat x y FDiv
cgOp LFExp [x] = nunary ATFloat "llvm.exp.f64" x
cgOp LFLog [x] = nunary ATFloat "llvm.log.f64" x
cgOp LFSin [x] = nunary ATFloat "llvm.sin.f64" x
cgOp LFCos [x] = nunary ATFloat "llvm.cos.f64" x
cgOp LFTan [x] = nunary ATFloat "tan" x
cgOp LFASin [x] = nunary ATFloat "asin" x
cgOp LFACos [x] = nunary ATFloat "acos" x
cgOp LFATan [x] = nunary ATFloat "atan" x
cgOp LFSqrt [x] = nunary ATFloat "llvm.sqrt.f64" x
cgOp LFFloor [x] = nunary ATFloat "llvm.floor.f64" x
cgOp LFCeil [x] = nunary ATFloat "llvm.ceil.f64" x
cgOp (LIntFloat ITBig) [x] = do
x' <- unbox (FArith (ATInt ITBig)) x
uflt <- inst $ simpleCall "__gmpz_get_d" [ x' ]
box (FArith ATFloat) uflt
cgOp (LIntFloat ity) [x] = do
x' <- unbox (FArith (ATInt ity)) x
x'' <- inst $ SIToFP x' (FloatingPointType 64 IEEE) []
box (FArith ATFloat) x''
cgOp (LFloatInt ITBig) [x] = do
x' <- unbox (FArith ATFloat) x
z <- alloc mpzTy
inst' $ simpleCall "__gmpz_init" [z]
inst' $ simpleCall "__gmpz_set_d" [ z, x' ]
box (FArith (ATInt ITBig)) z
cgOp (LFloatInt ity) [x] = do
x' <- unbox (FArith ATFloat) x
x'' <- inst $ FPToSI x' (ftyToTy $ cmpResultTy ity) []
box (FArith (ATInt ity)) x''
cgOp LFloatStr [x] = do
x' <- unbox (FArith ATFloat) x
ustr <- inst (idrCall "__idris_floatStr" [x'])
box FString ustr
cgOp LNoOp xs = return $ last xs
cgOp (LMkVec ety c) xs | c == length xs = do
nxs <- mapM (unbox (FArith (ATInt (ITFixed ety)))) xs
vec <- foldM (\v (e, i) -> inst $ InsertElement v e (ConstantOperand (C.Int 32 i)) [])
(ConstantOperand $ C.Vector (replicate c (C.Undef (IntegerType . fromIntegral $ nativeTyWidth ety))))
(zip nxs [0..])
box (FArith (ATInt (ITVec ety c))) vec
cgOp (LIdxVec ety c) [v,i] = do
nv <- unbox (FArith (ATInt (ITVec ety c))) v
ni <- unbox (FArith (ATInt (ITFixed IT32))) i
elt <- inst $ ExtractElement nv ni []
box (FArith (ATInt (ITFixed ety))) elt
cgOp (LUpdateVec ety c) [v,i,e] = do
let fty = FArith (ATInt (ITVec ety c))
nv <- unbox fty v
ni <- unbox (FArith (ATInt (ITFixed IT32))) i
ne <- unbox (FArith (ATInt (ITFixed ety))) e
nv' <- inst $ InsertElement nv ne ni []
box fty nv'
cgOp (LBitCast from to) [x] = do
nx <- unbox (FArith from) x
nx' <- inst $ BitCast nx (ftyToTy (FArith to)) []
box (FArith to) nx'
cgOp LStrEq [x,y] = do
x' <- unbox FString x
y' <- unbox FString y
cmp <- inst $ simpleCall "strcmp" [x', y']
flag <- inst $ ICmp IPred.EQ cmp (ConstantOperand (C.Int 32 0)) []
val <- inst $ ZExt flag (IntegerType 32) []
box (FArith (ATInt (ITFixed IT32))) val
cgOp LStrLt [x,y] = do
nx <- unbox FString x
ny <- unbox FString y
cmp <- inst $ simpleCall "strcmp" [nx, ny]
flag <- inst $ ICmp IPred.ULT cmp (ConstantOperand (C.Int 32 0)) []
val <- inst $ ZExt flag (IntegerType 32) []
box (FArith (ATInt (ITFixed IT32))) val
cgOp (LIntStr ITBig) [x] = do
x' <- unbox (FArith (ATInt ITBig)) x
ustr <- inst $ simpleCall "__gmpz_get_str"
[ ConstantOperand (C.Null (PointerType (IntegerType 8) (AddrSpace 0)))
, ConstantOperand (C.Int 32 10)
, x'
]
box FString ustr
cgOp (LIntStr ity) [x] = do
x' <- unbox (FArith (ATInt ity)) x
x'' <- if itWidth ity < 64
then inst $ SExt x' (IntegerType 64) []
else return x'
box FString =<< inst (idrCall "__idris_intStr" [x''])
cgOp (LStrInt ITBig) [s] = do
ns <- unbox FString s
mpz <- alloc mpzTy
inst $ simpleCall "__gmpz_init_set_str" [mpz, ns, ConstantOperand $ C.Int 32 10]
box (FArith (ATInt ITBig)) mpz
cgOp (LStrInt ity) [s] = do
ns <- unbox FString s
nx <- inst $ simpleCall "strtoll"
[ns
, ConstantOperand $ C.Null (PointerType (PointerType (IntegerType 8) (AddrSpace 0)) (AddrSpace 0))
, ConstantOperand $ C.Int 32 10
]
nx' <- case ity of
(ITFixed IT64) -> return nx
_ -> inst $ Trunc nx (IntegerType (itWidth ity)) []
box (FArith (ATInt ity)) nx'
cgOp LStrConcat [x,y] = cgStrCat x y
cgOp LStrCons [c,s] = do
nc <- unbox (FArith (ATInt ITChar)) c
ns <- unbox FString s
nc' <- inst $ Trunc nc (IntegerType 8) []
r <- inst $ simpleCall "__idris_strCons" [nc', ns]
box FString r
cgOp LStrHead [c] = do
s <- unbox FString c
c <- inst $ loadInv s
c' <- inst $ ZExt c (IntegerType 32) []
box (FArith (ATInt ITChar)) c'
cgOp LStrIndex [s, i] = do
ns <- unbox FString s
ni <- unbox (FArith (ATInt (ITFixed IT32))) i
p <- inst $ GetElementPtr True ns [ni] []
c <- inst $ loadInv p
c' <- inst $ ZExt c (IntegerType 32) []
box (FArith (ATInt ITChar)) c'
cgOp LStrTail [c] = do
s <- unbox FString c
c <- inst $ GetElementPtr True s [ConstantOperand $ C.Int 32 1] []
box FString c
cgOp LStrLen [s] = do
ns <- unbox FString s
len <- inst $ simpleCall "strlen" [ns]
ws <- getWordSize
len' <- case ws of
32 -> return len
x | x > 32 -> inst $ Trunc len (IntegerType 32) []
| x < 32 -> inst $ ZExt len (IntegerType 32) []
box (FArith (ATInt (ITFixed IT32))) len'
cgOp LStrRev [s] = do
ns <- unbox FString s
box FString =<< inst (simpleCall "__idris_strRev" [ns])
cgOp LReadStr [p] = do
np <- unbox FPtr p
s <- inst $ simpleCall "__idris_readStr" [np]
box FString s
cgOp LStdIn [] = do
stdin <- getStdIn
ptr <- inst $ loadInv stdin
box FPtr ptr
cgOp LStdOut [] = do
stdout <- getStdOut
ptr <- inst $ loadInv stdout
box FPtr ptr
cgOp LStdErr [] = do
stdErr <- getStdErr
ptr <- inst $ loadInv stdErr
box FPtr ptr
cgOp prim args = ierror $ "Unimplemented primitive: <" ++ show prim ++ ">("
++ intersperse ',' (take (length args) ['a'..]) ++ ")"
iCoerce :: (Operand -> Type -> InstructionMetadata -> Instruction) -> NativeTy -> NativeTy -> Operand -> Codegen Operand
iCoerce _ from to x | from == to = return x
iCoerce operator from to x = do
x' <- unbox (FArith (ATInt (ITFixed from))) x
x'' <- inst $ operator x' (ftyToTy (FArith (ATInt (ITFixed to)))) []
box (FArith (ATInt (ITFixed to))) x''
cgStrCat :: Operand -> Operand -> Codegen Operand
cgStrCat x y = do
x' <- unbox FString x
y' <- unbox FString y
xlen <- inst $ simpleCall "strlen" [x']
ylen <- inst $ simpleCall "strlen" [y']
zlen <- inst $ Add False True xlen ylen []
ws <- getWordSize
total <- inst $ Add False True zlen (ConstantOperand (C.Int ws 1)) []
mem <- allocAtomic' total
inst $ simpleCall "memcpy" [mem, x', xlen]
i <- inst $ PtrToInt mem (IntegerType ws) []
offi <- inst $ Add False True i xlen []
offp <- inst $ IntToPtr offi (PointerType (IntegerType 8) (AddrSpace 0)) []
inst $ simpleCall "memcpy" [offp, y', ylen]
j <- inst $ PtrToInt offp (IntegerType ws) []
offj <- inst $ Add False True j ylen []
end <- inst $ IntToPtr offj (PointerType (IntegerType 8) (AddrSpace 0)) []
inst' $ Store False end (ConstantOperand (C.Int 8 0)) Nothing 0 []
box FString mem
binary :: ArithTy -> Operand -> Operand
-> (Operand -> Operand -> InstructionMetadata -> Instruction) -> Codegen Operand
binary ty x y instCon = do
nx <- unbox (FArith ty) x
ny <- unbox (FArith ty) y
nr <- inst $ instCon nx ny []
box (FArith ty) nr
unary :: ArithTy -> Operand
-> (Operand -> InstructionMetadata -> Instruction) -> Codegen Operand
unary ty x instCon = do
nx <- unbox (FArith ty) x
nr <- inst $ instCon nx []
box (FArith ty) nr
nunary :: ArithTy -> String
-> Operand -> Codegen Operand
nunary ty name x = do
nx <- unbox (FArith ty) x
nr <- inst $ simpleCall name [nx]
box (FArith ty) nr
iCmp :: IntTy -> IPred.IntegerPredicate -> Operand -> Operand -> Codegen Operand
iCmp ity pred x y = do
nx <- unbox (FArith (ATInt ity)) x
ny <- unbox (FArith (ATInt ity)) y
nr <- inst $ ICmp pred nx ny []
nr' <- inst $ SExt nr (ftyToTy $ cmpResultTy ity) []
box (cmpResultTy ity) nr'
fCmp :: FPred.FloatingPointPredicate -> Operand -> Operand -> Codegen Operand
fCmp pred x y = do
nx <- unbox (FArith ATFloat) x
ny <- unbox (FArith ATFloat) y
nr <- inst $ FCmp pred nx ny []
box (FArith (ATInt (ITFixed IT32))) nr
cmpResultTy :: IntTy -> FType
cmpResultTy v@(ITVec _ _) = FArith (ATInt v)
cmpResultTy _ = FArith (ATInt (ITFixed IT32))
mpzBin :: String -> Operand -> Operand -> Codegen Operand
mpzBin name x y = do
nx <- unbox (FArith (ATInt ITBig)) x
ny <- unbox (FArith (ATInt ITBig)) y
nz <- alloc mpzTy
inst' $ simpleCall "__gmpz_init" [nz]
inst' $ simpleCall ("__gmpz_" ++ name) [nz, nx, ny]
box (FArith (ATInt ITBig)) nz
mpzBit :: String -> Operand -> Operand -> Codegen Operand
mpzBit name x y = do
nx <- unbox (FArith (ATInt ITBig)) x
ny <- unbox (FArith (ATInt ITBig)) y
bitcnt <- inst $ simpleCall "__gmpz_get_ui" [ny]
nz <- alloc mpzTy
inst' $ simpleCall "__gmpz_init" [nz]
inst' $ simpleCall ("__gmpz_" ++ name) [nz, nx, bitcnt]
box (FArith (ATInt ITBig)) nz
mpzUn :: String -> Operand -> Codegen Operand
mpzUn name x = do
nx <- unbox (FArith (ATInt ITBig)) x
nz <- alloc mpzTy
inst' $ simpleCall "__gmpz_init" [nz]
inst' $ simpleCall ("__gmpz_" ++ name) [nz, nx]
box (FArith (ATInt ITBig)) nz
mpzCmp :: IPred.IntegerPredicate -> Operand -> Operand -> Codegen Operand
mpzCmp pred x y = do
nx <- unbox (FArith (ATInt ITBig)) x
ny <- unbox (FArith (ATInt ITBig)) y
cmp <- inst $ simpleCall "__gmpz_cmp" [nx, ny]
result <- inst $ ICmp pred cmp (ConstantOperand (C.Int 32 0)) []
i <- inst $ ZExt result (IntegerType 32) []
box (FArith (ATInt (ITFixed IT32))) i
simpleCall :: String -> [Operand] -> Instruction
simpleCall name args =
Call { isTailCall = False
, callingConvention = CC.C
, returnAttributes = []
, function = Right . ConstantOperand . C.GlobalReference . Name $ name
, arguments = map (\x -> (x, [])) args
, functionAttributes = []
, metadata = []
}
idrCall :: String -> [Operand] -> Instruction
idrCall name args =
Call { isTailCall = False
, callingConvention = CC.Fast
, returnAttributes = []
, function = Right . ConstantOperand . C.GlobalReference . Name $ name
, arguments = map (\x -> (x, [])) args
, functionAttributes = []
, metadata = []
}
assert :: Operand -> String -> Codegen ()
assert condition message = do
passed <- getName "assertPassed"
failed <- getName "assertFailed"
terminate $ CondBr condition passed failed []
newBlock failed
cgExpr (SError message)
terminate $ Unreachable []
newBlock passed
| ctford/Idris-Elba-dev | src/IRTS/CodegenLLVM.hs | bsd-3-clause | 54,387 | 0 | 25 | 14,771 | 22,213 | 11,069 | 11,144 | 1,143 | 10 |
split :: [a] -> Int -> ([a], [a])
split xs n = (take n xs, drop n xs)
| cjhveal/H-99 | 17.hs | mit | 70 | 0 | 8 | 18 | 55 | 30 | 25 | 2 | 1 |
{-|
Manipulate the time periods typically used for reports with Period,
a richer abstraction than DateSpan. See also Types and Dates.
-}
module Hledger.Data.Period
where
import Data.Time.Calendar
import Data.Time.Calendar.MonthDay
import Data.Time.Calendar.OrdinalDate
import Data.Time.Calendar.WeekDate
import Data.Time.Format
import Text.Printf
import Hledger.Data.Types
-- | Convert Periods to DateSpans.
--
-- >>> periodAsDateSpan (MonthPeriod 2000 1) == DateSpan (Just $ fromGregorian 2000 1 1) (Just $ fromGregorian 2000 2 1)
-- True
periodAsDateSpan :: Period -> DateSpan
periodAsDateSpan (DayPeriod d) = DateSpan (Just d) (Just $ addDays 1 d)
periodAsDateSpan (WeekPeriod b) = DateSpan (Just b) (Just $ addDays 7 b)
periodAsDateSpan (MonthPeriod y m) = DateSpan (Just $ fromGregorian y m 1) (Just $ fromGregorian y' m' 1)
where
(y',m') | m==12 = (y+1,1)
| otherwise = (y,m+1)
periodAsDateSpan (QuarterPeriod y q) = DateSpan (Just $ fromGregorian y m 1) (Just $ fromGregorian y' m' 1)
where
(y', q') | q==4 = (y+1,1)
| otherwise = (y,q+1)
quarterAsMonth q = (q-1) * 3 + 1
m = quarterAsMonth q
m' = quarterAsMonth q'
periodAsDateSpan (YearPeriod y) = DateSpan (Just $ fromGregorian y 1 1) (Just $ fromGregorian (y+1) 1 1)
periodAsDateSpan (PeriodBetween b e) = DateSpan (Just b) (Just e)
periodAsDateSpan (PeriodFrom b) = DateSpan (Just b) Nothing
periodAsDateSpan (PeriodTo e) = DateSpan Nothing (Just e)
periodAsDateSpan (PeriodAll) = DateSpan Nothing Nothing
-- | Convert DateSpans to Periods.
--
-- >>> dateSpanAsPeriod $ DateSpan (Just $ fromGregorian 2000 1 1) (Just $ fromGregorian 2000 2 1)
-- MonthPeriod 2000 1
dateSpanAsPeriod :: DateSpan -> Period
dateSpanAsPeriod (DateSpan (Just b) (Just e)) = simplifyPeriod $ PeriodBetween b e
dateSpanAsPeriod (DateSpan (Just b) Nothing) = PeriodFrom b
dateSpanAsPeriod (DateSpan Nothing (Just e)) = PeriodTo e
dateSpanAsPeriod (DateSpan Nothing Nothing) = PeriodAll
-- | Convert PeriodBetweens to a more abstract period where possible.
--
-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 1 1 1) (fromGregorian 2 1 1)
-- YearPeriod 1
-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 10 1) (fromGregorian 2001 1 1)
-- QuarterPeriod 2000 4
-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 1) (fromGregorian 2000 3 1)
-- MonthPeriod 2000 2
-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2016 7 25) (fromGregorian 2016 8 1)
-- WeekPeriod 2016-07-25
-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 1 1) (fromGregorian 2000 1 2)
-- DayPeriod 2000-01-01
-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 28) (fromGregorian 2000 3 1)
-- PeriodBetween 2000-02-28 2000-03-01
-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 2 29) (fromGregorian 2000 3 1)
-- DayPeriod 2000-02-29
-- >>> simplifyPeriod $ PeriodBetween (fromGregorian 2000 12 31) (fromGregorian 2001 1 1)
-- DayPeriod 2000-12-31
--
simplifyPeriod :: Period -> Period
simplifyPeriod (PeriodBetween b e) =
case (toGregorian b, toGregorian e) of
-- a year
((by,1,1), (ey,1,1)) | by+1==ey -> YearPeriod by
-- a half-year
-- ((by,1,1), (ey,7,1)) | by==ey ->
-- ((by,7,1), (ey,1,1)) | by+1==ey ->
-- a quarter
((by,1,1), (ey,4,1)) | by==ey -> QuarterPeriod by 1
((by,4,1), (ey,7,1)) | by==ey -> QuarterPeriod by 2
((by,7,1), (ey,10,1)) | by==ey -> QuarterPeriod by 3
((by,10,1), (ey,1,1)) | by+1==ey -> QuarterPeriod by 4
-- a month
((by,bm,1), (ey,em,1)) | by==ey && bm+1==em -> MonthPeriod by bm
((by,12,1), (ey,1,1)) | by+1==ey -> MonthPeriod by 12
-- a week (two successive mondays),
-- YYYYwN ("week N of year YYYY")
-- _ | let ((by,bw,bd), (ey,ew,ed)) = (toWeekDate from, toWeekDate to) in by==ey && fw+1==tw && bd==1 && ed==1 ->
-- a week starting on a monday
_ | let ((by,bw,bd), (ey,ew,ed)) = (toWeekDate b, toWeekDate (addDays (-1) e))
in by==ey && bw==ew && bd==1 && ed==7 -> WeekPeriod b
-- a day
((by,bm,bd), (ey,em,ed)) |
(by==ey && bm==em && bd+1==ed) ||
(by+1==ey && bm==12 && em==1 && bd==31 && ed==1) || -- crossing a year boundary
(by==ey && bm+1==em && isLastDayOfMonth by bm bd && ed==1) -- crossing a month boundary
-> DayPeriod b
_ -> PeriodBetween b e
simplifyPeriod p = p
isLastDayOfMonth y m d =
case m of
1 -> d==31
2 | isLeapYear y -> d==29
| otherwise -> d==28
3 -> d==31
4 -> d==30
5 -> d==31
6 -> d==30
7 -> d==31
8 -> d==31
9 -> d==30
10 -> d==31
11 -> d==30
12 -> d==31
_ -> False
-- | Is this period a "standard" period, referencing a particular day, week, month, quarter, or year ?
-- Periods of other durations, or infinite duration, or not starting on a standard period boundary, are not.
isStandardPeriod = isStandardPeriod' . simplifyPeriod
where
isStandardPeriod' (DayPeriod _) = True
isStandardPeriod' (WeekPeriod _) = True
isStandardPeriod' (MonthPeriod _ _) = True
isStandardPeriod' (QuarterPeriod _ _) = True
isStandardPeriod' (YearPeriod _) = True
isStandardPeriod' _ = False
-- | Render a period as a compact display string suitable for user output.
--
-- >>> showPeriod (WeekPeriod (fromGregorian 2016 7 25))
-- "2016/07/25w30"
showPeriod (DayPeriod b) = formatTime defaultTimeLocale "%0C%y/%m/%d" b -- DATE
showPeriod (WeekPeriod b) = formatTime defaultTimeLocale "%0C%y/%m/%dw%V" b -- STARTDATEwYEARWEEK
showPeriod (MonthPeriod y m) = printf "%04d/%02d" y m -- YYYY/MM
showPeriod (QuarterPeriod y q) = printf "%04dq%d" y q -- YYYYqN
showPeriod (YearPeriod y) = printf "%04d" y -- YYYY
showPeriod (PeriodBetween b e) = formatTime defaultTimeLocale "%0C%y/%m/%d" b
++ formatTime defaultTimeLocale "-%0C%y/%m/%d" (addDays (-1) e) -- STARTDATE-INCLUSIVEENDDATE
showPeriod (PeriodFrom b) = formatTime defaultTimeLocale "%0C%y/%m/%d-" b -- STARTDATE-
showPeriod (PeriodTo e) = formatTime defaultTimeLocale "-%0C%y/%m/%d" (addDays (-1) e) -- -INCLUSIVEENDDATE
showPeriod PeriodAll = "-"
periodStart :: Period -> Maybe Day
periodStart p = mb
where
DateSpan mb _ = periodAsDateSpan p
periodEnd :: Period -> Maybe Day
periodEnd p = me
where
DateSpan _ me = periodAsDateSpan p
-- | Move a standard period to the following period of same duration.
-- Non-standard periods are unaffected.
periodNext :: Period -> Period
periodNext (DayPeriod b) = DayPeriod (addDays 1 b)
periodNext (WeekPeriod b) = WeekPeriod (addDays 7 b)
periodNext (MonthPeriod y 12) = MonthPeriod (y+1) 1
periodNext (MonthPeriod y m) = MonthPeriod y (m+1)
periodNext (QuarterPeriod y 4) = QuarterPeriod (y+1) 1
periodNext (QuarterPeriod y q) = QuarterPeriod y (q+1)
periodNext (YearPeriod y) = YearPeriod (y+1)
periodNext p = p
-- | Move a standard period to the preceding period of same duration.
-- Non-standard periods are unaffected.
periodPrevious :: Period -> Period
periodPrevious (DayPeriod b) = DayPeriod (addDays (-1) b)
periodPrevious (WeekPeriod b) = WeekPeriod (addDays (-7) b)
periodPrevious (MonthPeriod y 1) = MonthPeriod (y-1) 12
periodPrevious (MonthPeriod y m) = MonthPeriod y (m-1)
periodPrevious (QuarterPeriod y 1) = QuarterPeriod (y-1) 4
periodPrevious (QuarterPeriod y q) = QuarterPeriod y (q-1)
periodPrevious (YearPeriod y) = YearPeriod (y-1)
periodPrevious p = p
-- | Move a standard period to the following period of same duration, staying within enclosing dates.
-- Non-standard periods are unaffected.
periodNextIn :: DateSpan -> Period -> Period
periodNextIn (DateSpan _ (Just e)) p =
case mb of
Just b -> if b < e then p' else p
_ -> p
where
p' = periodNext p
mb = periodStart p'
periodNextIn _ p = periodNext p
-- | Move a standard period to the preceding period of same duration, staying within enclosing dates.
-- Non-standard periods are unaffected.
periodPreviousIn :: DateSpan -> Period -> Period
periodPreviousIn (DateSpan (Just b) _) p =
case me of
Just e -> if e > b then p' else p
_ -> p
where
p' = periodPrevious p
me = periodEnd p'
periodPreviousIn _ p = periodPrevious p
-- | Move a standard period stepwise so that it encloses the given date.
-- Non-standard periods are unaffected.
periodMoveTo :: Day -> Period -> Period
periodMoveTo d (DayPeriod _) = DayPeriod d
periodMoveTo d (WeekPeriod _) = WeekPeriod $ mondayBefore d
periodMoveTo d (MonthPeriod _ _) = MonthPeriod y m where (y,m,_) = toGregorian d
periodMoveTo d (QuarterPeriod _ _) = QuarterPeriod y q
where
(y,m,_) = toGregorian d
q = quarterContainingMonth m
periodMoveTo d (YearPeriod _) = YearPeriod y where (y,_,_) = toGregorian d
periodMoveTo _ p = p
-- | Enlarge a standard period to the next larger enclosing standard period, if there is one.
-- Eg, a day becomes the enclosing week.
-- A week becomes whichever month the week's thursday falls into.
-- A year becomes all (unlimited).
-- Non-standard periods (arbitrary dates, or open-ended) are unaffected.
periodGrow :: Period -> Period
periodGrow (DayPeriod b) = WeekPeriod $ mondayBefore b
periodGrow (WeekPeriod b) = MonthPeriod y m
where (y,m) = yearMonthContainingWeekStarting b
periodGrow (MonthPeriod y m) = QuarterPeriod y (quarterContainingMonth m)
periodGrow (QuarterPeriod y _) = YearPeriod y
periodGrow (YearPeriod _) = PeriodAll
periodGrow p = p
-- | Shrink a period to the next smaller standard period inside it,
-- choosing the subperiod which contains today's date if possible,
-- otherwise the first subperiod. It goes like this:
-- unbounded periods and nonstandard periods (between two arbitrary dates) ->
-- current year ->
-- current quarter if it's in selected year, otherwise first quarter of selected year ->
-- current month if it's in selected quarter, otherwise first month of selected quarter ->
-- current week if it's in selected month, otherwise first week of selected month ->
-- today if it's in selected week, otherwise first day of selected week,
-- unless that's in previous month, in which case first day of month containing selected week.
-- Shrinking a day has no effect.
periodShrink :: Day -> Period -> Period
periodShrink _ p@(DayPeriod _) = p
periodShrink today (WeekPeriod b)
| today >= b && diffDays today b < 7 = DayPeriod today
| m /= weekmonth = DayPeriod $ fromGregorian weekyear weekmonth 1
| otherwise = DayPeriod b
where
(_,m,_) = toGregorian b
(weekyear,weekmonth) = yearMonthContainingWeekStarting b
periodShrink today (MonthPeriod y m)
| (y',m') == (y,m) = WeekPeriod $ mondayBefore today
| otherwise = WeekPeriod $ startOfFirstWeekInMonth y m
where (y',m',_) = toGregorian today
periodShrink today (QuarterPeriod y q)
| quarterContainingMonth thismonth == q = MonthPeriod y thismonth
| otherwise = MonthPeriod y (firstMonthOfQuarter q)
where (_,thismonth,_) = toGregorian today
periodShrink today (YearPeriod y)
| y == thisyear = QuarterPeriod y thisquarter
| otherwise = QuarterPeriod y 1
where
(thisyear,thismonth,_) = toGregorian today
thisquarter = quarterContainingMonth thismonth
periodShrink today _ = YearPeriod y
where (y,_,_) = toGregorian today
mondayBefore d = addDays (fromIntegral (1 - wd)) d
where
(_,_,wd) = toWeekDate d
yearMonthContainingWeekStarting weekstart = (y,m)
where
thu = addDays 3 weekstart
(y,yd) = toOrdinalDate thu
(m,_) = dayOfYearToMonthAndDay (isLeapYear y) yd
quarterContainingMonth m = (m-1) `div` 3 + 1
firstMonthOfQuarter q = (q-1)*3 + 1
startOfFirstWeekInMonth y m
| monthstartday <= 4 = mon
| otherwise = addDays 7 mon -- month starts with a fri/sat/sun
where
monthstart = fromGregorian y m 1
mon = mondayBefore monthstart
(_,_,monthstartday) = toWeekDate monthstart
| ony/hledger | hledger-lib/Hledger/Data/Period.hs | gpl-3.0 | 12,144 | 0 | 23 | 2,618 | 3,516 | 1,825 | 1,691 | 176 | 13 |
<?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="pt-BR">
<title>SOAP Scanner | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_pt_BR/helpset_pt_BR.hs | apache-2.0 | 974 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Test.Vector.Dense
-- Copyright : Copyright (c) 2008, Patrick Perry <[email protected]>
-- License : BSD3
-- Maintainer : Patrick Perry <[email protected]>
-- Stability : experimental
--
module Test.Vector.Dense (
SubVector(..),
VectorPair(..),
VectorTriple(..),
vector,
) where
import Test.QuickCheck hiding ( vector )
import Test.QuickCheck.BLAS ( TestElem )
import qualified Test.QuickCheck.BLAS as Test
import Data.Vector.Dense hiding ( vector )
import Data.Elem.BLAS ( BLAS1 )
vector :: (TestElem e) => Int -> Gen (Vector e)
vector = Test.vector
data VectorPair e =
VectorPair (Vector e)
(Vector e)
deriving (Show)
data VectorTriple e =
VectorTriple (Vector e)
(Vector e)
(Vector e)
deriving (Show)
instance (TestElem e) => Arbitrary (Vector e) where
arbitrary = do
n <- Test.dim
Test.vector n
instance (TestElem e) => Arbitrary (VectorPair e) where
arbitrary = do
n <- Test.dim
x <- vector n
y <- vector n
return $ VectorPair x y
instance (TestElem e) => Arbitrary (VectorTriple e) where
arbitrary = do
n <- Test.dim
x <- vector n
y <- vector n
z <- vector n
return $ VectorTriple x y z
data SubVector e =
SubVector Int
(Vector e)
Int
Int
deriving (Show)
instance (TestElem e) => Arbitrary (SubVector e) where
arbitrary = do
n <- Test.dim
o <- choose (0,5)
s <- choose (1,5)
e <- choose (0,5)
x <- Test.vector (o + s*n + e)
return (SubVector s x o n)
| patperry/hs-linear-algebra | tests-old/Test/Vector/Dense.hs | bsd-3-clause | 1,866 | 0 | 13 | 579 | 556 | 297 | 259 | 54 | 1 |
-- Copyright (c) 2016 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 #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts,
FlexibleInstances, UndecidableInstances #-}
module Control.Monad.Symbols(
MonadSymbols(..),
SymbolsT,
Symbols,
runSymbolsT,
runSymbols,
mapSymbolsT
) where
import Control.Applicative
import Control.Monad.Artifacts.Class
import Control.Monad.CommentBuffer.Class
import Control.Monad.Comments.Class
import Control.Monad.Cont
import Control.Monad.Except
import Control.Monad.Genpos.Class
import Control.Monad.Gensym.Class
import Control.Monad.GraphBuilder.Class
import Control.Monad.Journal
import Control.Monad.Loader.Class
import Control.Monad.Messages.Class
import Control.Monad.Positions.Class
import Control.Monad.Reader
import Control.Monad.ScopeBuilder.Class
import Control.Monad.SourceFiles.Class
import Control.Monad.SourceBuffer.Class
import Control.Monad.State
import Control.Monad.Symbols.Class
import Control.Monad.Writer
import Data.Array
import Data.ByteString hiding (empty)
import Data.Symbol
newtype SymbolsT m a =
SymbolsT { unpackSymbolsT :: (ReaderT (Array Symbol ByteString) m) a }
type Symbols a = SymbolsT IO a
-- | Execute the computation represented by a Symbols monad.
runSymbols :: Symbols a
-- ^ The Symbols monad to execute.
-> (Symbol, Symbol)
-- ^ The low and high range of the symbols.
-> [(Symbol, ByteString)]
-- ^ The mapping of symbols. The mapping to the lowest
-- index is taken as the null symbol.
-> IO a
runSymbols = runSymbolsT
-- | Execute the computation wrapped in a SymbolsT monad transformer.
runSymbolsT :: Monad m =>
SymbolsT m a
-- ^ The SymbolsT monad to execute.
-> (Symbol, Symbol)
-- ^ The low and high range of the symbols. The lowest
-- index is used as the index of the null symbol.
-> [(Symbol, ByteString)]
-- ^ The mapping of symbols to indexes. The mapping to the
-- lowest index is taken as the null symbol.
-> m a
runSymbolsT s bound = runReaderT (unpackSymbolsT s) . array bound
mapSymbolsT :: (Monad m, Monad n) =>
(m a -> n b) -> SymbolsT m a -> SymbolsT n b
mapSymbolsT f = SymbolsT . mapReaderT f . unpackSymbolsT
nullSym' :: Monad m => (ReaderT (Array Symbol ByteString) m) Symbol
nullSym' = liftM (fst . bounds) ask
allNames' :: Monad m => (ReaderT (Array Symbol ByteString) m) [ByteString]
allNames' = liftM elems ask
name' :: Monad m => Symbol -> (ReaderT (Array Symbol ByteString) m) ByteString
name' sym = liftM (! sym) ask
allSyms' :: Monad m => (ReaderT (Array Symbol ByteString) m) [Symbol]
allSyms' = liftM indices ask
instance Monad m => Monad (SymbolsT m) where
return = SymbolsT . return
s >>= f = SymbolsT $ unpackSymbolsT s >>= unpackSymbolsT . f
instance Monad m => Applicative (SymbolsT m) where
pure = return
(<*>) = ap
instance (Monad m, Alternative m) => Alternative (SymbolsT m) where
empty = lift empty
s1 <|> s2 = SymbolsT (unpackSymbolsT s1 <|> unpackSymbolsT s2)
instance Functor (SymbolsT m) where
fmap = fmap
instance Monad m => MonadSymbols (SymbolsT m) where
nullSym = SymbolsT nullSym'
allNames = SymbolsT allNames'
allSyms = SymbolsT allSyms'
name = SymbolsT . name'
instance MonadIO m => MonadIO (SymbolsT m) where
liftIO = SymbolsT . liftIO
instance MonadTrans SymbolsT where
lift = SymbolsT . lift
instance MonadArtifacts path m => MonadArtifacts path (SymbolsT m) where
artifact path = lift . artifact path
artifactBytestring path = lift . artifactBytestring path
artifactLazyBytestring path = lift . artifactLazyBytestring path
instance MonadCommentBuffer m => MonadCommentBuffer (SymbolsT m) where
startComment = lift startComment
appendComment = lift . appendComment
finishComment = lift finishComment
addComment = lift . addComment
saveCommentsAsPreceeding = lift . saveCommentsAsPreceeding
clearComments = lift clearComments
instance MonadComments m => MonadComments (SymbolsT m) where
preceedingComments = lift . preceedingComments
instance MonadCont m => MonadCont (SymbolsT m) where
callCC f = SymbolsT (callCC (\c -> unpackSymbolsT (f (SymbolsT . c))))
instance (MonadError e m) => MonadError e (SymbolsT m) where
throwError = lift . throwError
m `catchError` h =
SymbolsT (unpackSymbolsT m `catchError` (unpackSymbolsT . h))
instance MonadEdgeBuilder nodety m =>
MonadEdgeBuilder nodety (SymbolsT m) where
addEdge src dst = lift . addEdge src dst
instance MonadGenpos m => MonadGenpos (SymbolsT m) where
point = lift . point
filename = lift . filename
instance MonadGensym m => MonadGensym (SymbolsT m) where
symbol = lift . symbol
unique = lift . unique
instance (Monoid w, MonadJournal w m) => MonadJournal w (SymbolsT m) where
journal = lift . journal
history = lift history
clear = lift clear
instance MonadMessages msg m => MonadMessages msg (SymbolsT m) where
message = lift . message
instance MonadLoader path info m => MonadLoader path info (SymbolsT m) where
load = lift . load
instance MonadNodeBuilder nodety m =>
MonadNodeBuilder nodety (SymbolsT m) where
addNode = lift . addNode
instance MonadPositions m => MonadPositions (SymbolsT m) where
pointInfo = lift . pointInfo
fileInfo = lift . fileInfo
instance MonadScopeStack m => MonadScopeStack (SymbolsT m) where
enterScope = lift . enterScope
finishScope = lift finishScope
instance MonadScopeBuilder tmpscope m =>
MonadScopeBuilder tmpscope (SymbolsT m) where
getScope = lift getScope
setScope = lift . setScope
instance MonadSourceFiles m => MonadSourceFiles (SymbolsT m) where
sourceFile = lift . sourceFile
instance MonadSourceBuffer m => MonadSourceBuffer (SymbolsT m) where
linebreak = lift . linebreak
startFile fname = lift . startFile fname
finishFile = lift finishFile
instance MonadState s m => MonadState s (SymbolsT m) where
get = lift get
put = lift . put
instance MonadReader r m => MonadReader r (SymbolsT m) where
ask = lift ask
local f = mapSymbolsT (local f)
instance MonadWriter w m => MonadWriter w (SymbolsT m) where
tell = lift . tell
listen = mapSymbolsT listen
pass = mapSymbolsT pass
instance MonadPlus m => MonadPlus (SymbolsT m) where
mzero = lift mzero
mplus s1 s2 = SymbolsT (mplus (unpackSymbolsT s1) (unpackSymbolsT s2))
instance MonadFix m => MonadFix (SymbolsT m) where
mfix f = SymbolsT (mfix (unpackSymbolsT . f))
| saltlang/compiler-toolbox | src/Control/Monad/Symbols.hs | bsd-3-clause | 8,116 | 0 | 15 | 1,623 | 1,958 | 1,039 | 919 | 148 | 1 |
-- | This module defines the type 'Opts' and gives a function to parse commandline arguments.
{-# LANGUAGE BangPatterns #-}
module Euphs.Options
( Opts(..)
, parseOpts
, OptsList
, defaults
, options
, getOpts
) where
import System.Exit
import System.Console.GetOpt
import System.Environment (getArgs)
import Control.Monad (when)
-- | The main options structure.
data Opts = Opts { heimHost :: !String -- ^ Heim instance hoster
, heimPort :: !Int -- ^ The port to connect to
, useSSL :: !Bool -- ^ Whether to use wss or ws
, roomList :: !String -- ^ A list of initial rooms separated by whitespace in the format of <room name>[-<pw>]
, showHelp :: !Bool -- ^ Print help on startup
, logTarget :: !FilePath -- ^ The log file to write to.
-- Fall back to 'stdout' when
-- empty
, botAccount :: !FilePath -- ^ Email and password for logging into the account
, botNick :: !String -- ^ The nick the Bot will be using.
, config :: !FilePath -- ^ Config file for specific bot options
}
deriving (Show)
-- | Type synonym for the list of options to the bot
type OptsList = [OptDescr (Opts -> Opts)]
-- | Default options
defaults :: Opts
defaults = Opts { heimHost = "euphoria.io"
, heimPort = 443
, useSSL = True
, roomList = "test"
, showHelp = False
, logTarget = ""
, botAccount = ""
, botNick = "EmptyBot"
, config = ""
}
-- | List of options available
options :: OptsList
options =
[ Option "e" ["host"]
(ReqArg (\arg opt -> opt {heimHost = arg}) "HOST") "Heim instance to connect to"
, Option "p" ["port"]
(ReqArg (\arg opt -> opt {heimPort = read arg :: Int}) "PORT") "Port to use"
, Option "r" ["rooms", "room"]
(ReqArg (\arg opt -> opt {roomList = arg}) "ROOMS") "Rooms to join"
, Option "s" ["nossl"]
(NoArg (\opt -> opt {useSSL = False})) "Disable SSL"
, Option "l" ["log"]
(ReqArg (\arg opt -> opt {logTarget = arg}) "LOG") "Logging FilePath"
, Option "i" ["identity"]
(ReqArg (\arg opt -> opt {botAccount = arg}) "ID") "Bot Identity FilePath"
, Option "c" ["config"]
(ReqArg (\arg opt -> opt {config = arg}) "CONFIG") "Path for the bot config file"
, Option "n" ["nick"]
(ReqArg (\arg opt -> opt {botNick = arg}) "NICK") "Nickname to use"
, Option "h" ["help"]
(NoArg (\opt -> opt {showHelp = True})) "Shows this help."
]
header :: String
header = "Usage: Euphs [options]"
-- | Function to parse commandline Options
parseOpts :: Opts -> OptsList -> [String] -> IO (Opts, [String])
parseOpts defOpts opts argv =
case getOpt Permute opts argv of
(o,n,[] ) -> return (foldl (flip id) defOpts o, n)
(_,_,errs) -> ioError (userError (concat errs ++ showUsage))
-- | Shows the usage message
showUsage :: String
showUsage = usageInfo header options
-- | Prints the usage message to stdout and exits.
showUsageAndExit :: IO ()
showUsageAndExit = do
putStrLn showUsage
exitSuccess
-- | Parses options from the commandline, using the Opts given in as a default to be overridden
getOpts :: Opts -> OptsList -> IO Opts
getOpts opt optL = do
(opts, _) <- getArgs >>= parseOpts opt optL
when (showHelp opts) showUsageAndExit
return opts
| MicheleCastrovilli/EuPhBot | Library/Euphs/Options.hs | bsd-3-clause | 3,712 | 0 | 13 | 1,224 | 871 | 498 | 373 | 89 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Vim.TestExCommandParsers (tests) where
import Data.List (inits)
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import Test.QuickCheck
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck
import Yi.Keymap.Vim.Common
import Yi.Keymap.Vim.Ex
import qualified Yi.Keymap.Vim.Ex.Commands.Buffer as Buffer
import qualified Yi.Keymap.Vim.Ex.Commands.BufferDelete as BufferDelete
import qualified Yi.Keymap.Vim.Ex.Commands.Delete as Delete
import qualified Yi.Keymap.Vim.Ex.Commands.Registers as Registers
import qualified Yi.Keymap.Vim.Ex.Commands.Nohl as Nohl
data CommandParser = CommandParser
{ cpDescription :: String
, cpParser :: String -> Maybe ExCommand
, cpNames :: [String]
, cpAcceptsBang :: Bool
, cpAcceptsCount :: Bool
, cpArgs :: Gen String
}
addingSpace :: Gen String -> Gen String
addingSpace = fmap (" " <>)
numberString :: Gen String
numberString = (\(NonNegative n) -> show n) <$> (arbitrary :: Gen (NonNegative Int))
-- | QuickCheck Generator of buffer identifiers.
--
-- A buffer identifier is either an empty string, a "%" character, a "#"
-- character, a string containing only numbers (optionally preceeded by
-- a space), or a string containing any chars preceeded by a space. E.g.,
--
-- ["", "%", "#", " myBufferName", " 45", "45"]
--
-- TODO Don't select "", "%", "#" half of the time.
bufferIdentifier :: Gen String
bufferIdentifier =
oneof [ addingSpace arbitrary
, addingSpace numberString
, numberString
, oneof [pure "%", pure " %"]
, oneof [pure "#", pure " #"]
, pure ""
]
-- | QuickCheck generator of strings suitable for use as register names in Vim
-- ex command lines. Does not include a preceding @"@.
registerName :: Gen String
registerName =
(:[]) <$> oneof [ elements ['0'..'9']
, elements ['a'..'z']
, elements ['A'..'Z']
, elements ['"', '-', '=', '*', '+', '~', '_', '/']
-- TODO Should the read-only registers be included here?
-- , element [':', '.', '%', '#']
]
-- | QuickCheck generator of strings suitable for use as counts in Vim ex
-- command lines
count :: Gen String
count = numberString
commandParsers :: [CommandParser]
commandParsers =
[ CommandParser
"Buffer.parse"
(Buffer.parse . Ev . T.pack)
["buffer", "buf", "bu", "b"]
True
True
bufferIdentifier
, CommandParser
"BufferDelete.parse"
(BufferDelete.parse . Ev . T.pack)
["bdelete", "bdel", "bd"]
True
False
(unwords <$> listOf bufferIdentifier)
, CommandParser
"Delete.parse"
(Delete.parse . Ev . T.pack)
["delete", "del", "de", "d"]
-- XXX TODO support these weird abbreviations too?
-- :dl, :dell, :delel, :deletl, :deletel
-- :dp, :dep, :delp, :delep, :deletp, :deletep
True
False
(oneof [ pure ""
, addingSpace registerName
, addingSpace count
, (<>) <$> addingSpace registerName <*> addingSpace count
])
, CommandParser
"Registers.parse"
(Registers.parse . Ev . T.pack)
[ "reg"
, "regi"
, "regis"
, "regist"
, "registe"
, "register"
, "registers"
]
False
False
(pure "")
, CommandParser
"Nohl.parse"
(Nohl.parse . Ev . T.pack)
(drop 3 $ inits "nohlsearch")
False
False
(pure "")
]
commandString :: CommandParser -> Gen String
commandString cp = do
name <- elements $ cpNames cp
bang <- if cpAcceptsBang cp
then elements ["!", ""]
else pure ""
count' <- if cpAcceptsCount cp
then count
else pure ""
args <- cpArgs cp
return $ concat [count', name, bang, args]
expectedParserParses :: CommandParser -> TestTree
expectedParserParses commandParser =
testProperty (cpDescription commandParser <> " parses expected input") $
forAll (commandString commandParser)
(isJust . cpParser commandParser)
expectedParserSelected :: CommandParser -> TestTree
expectedParserSelected expectedCommandParser =
testProperty testName $
forAll (commandString expectedCommandParser) $ \s ->
let expectedName = expectedCommandName (Ev $ T.pack s)
actualName = actualCommandName (Ev $ T.pack s)
in counterexample (errorMessage s actualName)
(expectedName == actualName)
where
unE = T.unpack . _unEv
expectedCommandName = commandNameFor [cpParser expectedCommandParser . unE]
actualCommandName = commandNameFor defExCommandParsers
commandNameFor parsers s =
cmdShow <$> evStringToExCommand parsers s
errorMessage s actualName =
"Parsed " <> show s <> " to " <> show actualName <> " command"
testName =
cpDescription expectedCommandParser <> " selected for expected input"
-- | Tests for the Ex command parsers in the Vim Keymap.
--
-- Tests that the parsers parse the strings they are expected to and that
-- the expected parser is selected for string.
--
-- The actions of the ex commands are not tested here.
tests :: TestTree
tests =
testGroup "Vim keymap ex command parsers"
[ testGroup "Expected parser parses" $
map expectedParserParses commandParsers
, testGroup "Expected parser selected" $
map expectedParserSelected commandParsers
]
| yi-editor/yi | yi-keymap-vim/tests/Vim/TestExCommandParsers.hs | gpl-2.0 | 5,941 | 0 | 15 | 1,831 | 1,198 | 667 | 531 | 129 | 3 |
{-# LANGUAGE OverloadedStrings #-}
-- Module : Route53
-- Copyright : (c) 2013-2015 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)
module Route53 where
import Control.Applicative
import Control.Lens
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.AWS
import Network.AWS.Route53
import System.IO
example :: IO (Either Error ListHostedZonesResponse)
example = do
lgr <- newLogger Debug stdout
env <- getEnv Ireland Discover <&> envLogger .~ lgr
runAWST env
. once
$ send listHostedZones
| romanb/amazonka | amazonka-route53/examples/src/Route53.hs | mpl-2.0 | 934 | 0 | 10 | 208 | 124 | 71 | 53 | 16 | 1 |
module Main where
import System
import Control.Monad (when)
main = do print 'b'
args <- getArgs
let isB = head args
when (isB /= "isB") (error "B is not B!")
| dcreager/cabal | tests/systemTests/twoMains/MainB.hs | bsd-3-clause | 188 | 0 | 10 | 60 | 68 | 34 | 34 | 7 | 1 |
{-
Querying for back/in links to a given page.
foo$ path/to/linksTo "Haskell"
...
foo$
-}
module Main(main) where
import MediaWiki.API.Base
import MediaWiki.API.Types ( PageTitle(..) )
import MediaWiki.API
import MediaWiki.API.Query.BackLinks.Import as Back
import Util.GetOpts
-- begin option handling
data Options
= Options
{ optWiki :: String
, optUser :: Maybe String
, optPass :: Maybe String
, optPage :: Maybe String
}
nullOptions :: Options
nullOptions = Options
{ optWiki = "http://en.wikipedia.org/w/"
, optUser = Nothing
, optPass = Nothing
, optPage = Nothing
}
option_descr :: [OptDescr (Options -> Options)]
option_descr =
[ Option ['u'] ["user"]
(ReqArg (\ x o -> o{optUser=Just x}) "USER")
"Wiki user name to login as"
, Option ['p'] ["pass"]
(ReqArg (\ x o -> o{optPass=Just x}) "PASSWORD")
"user's password credentials to supply if logging in"
, Option ['w'] ["wiki"]
(ReqArg (\ x o -> o{optWiki=x}) "WIKI")
"the Wiki to access"
, Option ['P'] ["page"]
(ReqArg (\ x o -> o{optPage=Just x}) "PAGE")
"the page title to list category pages for"
]
-- end option handling
queryPageInLinks :: URLString -> String -> IO [PageTitle]
queryPageInLinks url pgName = queryInLinks emptyBackLinksRequest{blTitle=Just pgName} []
where
queryInLinks bReq acc = do
let req = emptyXmlRequest (mkQueryAction (queryPage pgName) bReq)
mb <- webGetXml Back.stringXml url req
case mb of
Nothing -> fail ("Failed to fetch page" ++ pgName ++ " from " ++ url)
Just c -> do
let acc' = acc ++ blLinks c
case blContinue c of
Nothing -> return acc'
Just x -> queryInLinks bReq{blContinueFrom=Just x} acc'
main :: IO ()
main = do
(opts, fs) <- processOptions option_descr nullOptions
let url = optWiki opts
case mbCons (optPage opts) fs of
[] -> return ()
xs -> mapM_ (linksToPage url) xs
linksToPage :: URLString -> String -> IO ()
linksToPage url pgName = do
ps <- queryPageInLinks url pgName
putStrLn ("Page " ++ show pgName ++ " has the following backlinks: ")
mapM_ (putStrLn.toTitle) ps
where
toTitle pg = ' ':pgTitle pg
mbCons :: Maybe a -> [a] -> [a]
mbCons Nothing xs = xs
mbCons (Just x) xs = x:xs
| HyperGainZ/neobot | mediawiki/examples/LinksTo.hs | bsd-3-clause | 2,310 | 9 | 19 | 560 | 782 | 412 | 370 | 60 | 3 |
module Main (main) where
import Text.PrettyPrint.ANSI.Leijen
import System.IO
main :: IO ()
main = do
-- Going directly to the console is portable across Unix and Windows...
putDoc $ red (text "Red") <> comma <+> white (text "white") <+> text "and" <+> blue (text "blue") <> char '!' <> linebreak
putDoc $ blue (text "Nested" <+> dullyellow (text "colors") <+> text "example") <> linebreak
hPutDoc stdout $ onred (text "Red") <> comma <+> onwhite (text "white") <+> text "and" <+> onblue (text "blue") <> char '!' <> linebreak
hPutDoc stdout $ onblue (text "Nested" <+> ondullyellow (text "colors") <+> text "example") <> linebreak
-- ...but going via a string will only preserve formatting information information on Unix
putStr $ show $ green (text "I will be green on Unix but uncolored on Windows") <> linebreak
-- Let's see some non-color formatting:
putDoc $ text "We can do" <+> bold (text "boldness") <> text ", if your terminal supports it, and even perhaps" <+> underline (text "underlining") <> linebreak
-- Just a little test of the formatting removal:
putDoc $ text "There is a handy utility called 'plain' to" <+> plain (bold $ text "remove formatting") <+>
plain (text "if you need to e.g. support" <+> red (text "non-ANSI") <+> text "terminals") | seereason/ansi-wl-pprint | Text/PrettyPrint/ANSI/Example.hs | bsd-2-clause | 1,334 | 0 | 16 | 283 | 385 | 181 | 204 | 13 | 1 |
{-@ LIQUID "--no-termination" @-}
module GhcSort () where
import Language.Haskell.Liquid.Prelude
{-@ type OList a = [a]<{\fld v -> (v >= fld)}> @-}
---------------------------------------------------------------------------
--------------------------- Official GHC Sort ----------------------------
---------------------------------------------------------------------------
{-@ sort1 :: (Ord a) => [a] -> OList a @-}
sort1 :: (Ord a) => [a] -> [a]
sort1 = mergeAll . sequences
where
sequences (a:b:xs)
| a `compare` b == GT = descending b [a] xs
| otherwise = ascending b (a:) xs
sequences [x] = [[x]]
sequences [] = [[]]
descending a as (b:bs)
| a `compare` b == GT = descending b (a:as) bs
descending a as bs = (a:as): sequences bs
ascending a as (b:bs)
| a `compare` b /= GT = ascending b (\ys -> as (a:ys)) bs
ascending a as bs = as [a]: sequences bs
mergeAll [x] = x
mergeAll xs = mergeAll (mergePairs xs)
mergePairs (a:b:xs) = merge1 a b: mergePairs xs
mergePairs [x] = [x]
mergePairs [] = []
-- merge1 needs to be toplevel,
-- to get applied transformRec tx
merge1 (a:as') (b:bs')
| a `compare` b == GT = b:merge1 (a:as') bs'
| otherwise = a:merge1 as' (b:bs')
merge1 [] bs = bs
merge1 as [] = as
---------------------------------------------------------------------------
------------------- Mergesort ---------------------------------------------
---------------------------------------------------------------------------
{-@ sort2 :: (Ord a) => [a] -> OList a @-}
sort2 :: (Ord a) => [a] -> [a]
sort2 = mergesort
mergesort :: (Ord a) => [a] -> [a]
mergesort = mergesort' . map wrap
mergesort' :: (Ord a) => [[a]] -> [a]
mergesort' [] = []
mergesort' [xs] = xs
mergesort' xss = mergesort' (merge_pairs xss)
merge_pairs :: (Ord a) => [[a]] -> [[a]]
merge_pairs [] = []
merge_pairs [xs] = [xs]
merge_pairs (xs:ys:xss) = merge xs ys : merge_pairs xss
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
= case x `compare` y of
GT -> y : merge (x:xs) ys
_ -> x : merge xs (y:ys)
wrap :: a -> [a]
wrap x = [x]
----------------------------------------------------------------------
-------------------- QuickSort ---------------------------------------
----------------------------------------------------------------------
{-@ sort3 :: (Ord a) => w:a -> [{v:a|v<=w}] -> OList a @-}
sort3 :: (Ord a) => a -> [a] -> [a]
sort3 w ls = qsort w ls []
-- qsort is stable and does not concatenate.
qsort :: (Ord a) => a -> [a] -> [a] -> [a]
qsort _ [] r = r
qsort _ [x] r = x:r
qsort w (x:xs) r = qpart w x xs [] [] r
-- qpart partitions and sorts the sublists
qpart :: (Ord a) => a -> a -> [a] -> [a] -> [a] -> [a] -> [a]
qpart w x [] rlt rge r =
-- rlt and rge are in reverse order and must be sorted with an
-- anti-stable sorting
rqsort x rlt (x:rqsort w rge r)
qpart w x (y:ys) rlt rge r =
case compare x y of
GT -> qpart w x ys (y:rlt) rge r
_ -> qpart w x ys rlt (y:rge) r
-- rqsort is as qsort but anti-stable, i.e. reverses equal elements
rqsort :: (Ord a) => a -> [a] -> [a] -> [a]
rqsort _ [] r = r
rqsort _ [x] r = x:r
rqsort w (x:xs) r = rqpart w x xs [] [] r
rqpart :: (Ord a) => a -> a -> [a] -> [a] -> [a] -> [a] -> [a]
rqpart w x [] rle rgt r =
qsort x rle (x:qsort w rgt r)
rqpart w x (y:ys) rle rgt r =
case compare y x of
GT -> rqpart w x ys rle (y:rgt) r
_ -> rqpart w x ys (y:rle) rgt r
| ssaavedra/liquidhaskell | benchmarks/esop2013-submission/GhcListSort.hs | bsd-3-clause | 3,627 | 0 | 13 | 898 | 1,507 | 804 | 703 | 70 | 8 |
{-# LANGUAGE MagicHash #-}
module ShouldCompile where
-- exposed a bug in the NCG in 6.4.2
import GHC.Base
class Unboxable a where
writeUnboxable :: MutableByteArray# RealWorld -> a -> State# RealWorld -> State# RealWorld
writeUnboxable arr a s = writeInt8Array# arr 0# (getTag 0) s
| siddhanathan/ghc | testsuite/tests/codeGen/should_compile/cg006.hs | bsd-3-clause | 294 | 0 | 10 | 56 | 73 | 37 | 36 | 6 | 0 |
{-# LANGUAGE FlexibleInstances #-}
module Fib where
import Data.Bits
-- exercise 1
fib :: Integer -> Integer
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
fibs1 :: [Integer]
fibs1 = map fib [0..]
-- exercise 2
fibs2 :: [Integer]
fibs2 = map fst $ iterate stepper (0, 1)
where stepper (n0, n1) = (n1, n0 + n1)
-- exercise 3
data Stream a = Cons a (Stream a)
deriving (Ord, Eq)
instance Show a => Show (Stream a) where
show xs = "Stream " ++ (show $ take 20 $ streamToList xs)
streamToList :: Stream a -> [a]
streamToList (Cons x xs) = x : streamToList xs
-- exercise 4
streamRepeat :: a -> Stream a
streamRepeat a = Cons a (streamRepeat a)
streamMap :: (a -> b) -> Stream a -> Stream b
streamMap f (Cons x xs) = Cons (f x) $ streamMap f xs
streamFromSeed :: (a -> a) -> a -> Stream a
streamFromSeed f a = Cons a $ streamFromSeed f (f a)
-- exercise 5
nats :: Stream Integer
nats = streamFromSeed (+1) 0
interleaveStreams :: Stream a -> Stream a -> Stream a
interleaveStreams (Cons a as) (Cons b bs) = Cons a $ Cons b $ interleaveStreams as bs
numZeroRightBits :: Integer -> Integer
numZeroRightBits a = numBits 0 a
where
numBits n 0 = n
numBits n a = case a .&. 1 of
0 -> numBits (n + 1) (a `shiftR` 1)
otherwise -> n
zeroes :: Stream Integer
zeroes = streamRepeat 0
ruler :: Stream Integer
ruler = interleaveStreams (streamRepeat 0)
(streamMap numZeroRightBits (streamFromSeed (+2) 2))
-- exercise 6
x :: Stream Integer
x = Cons 0 $ Cons 1 $ streamRepeat 0
scalarMul :: Integer -> Stream Integer -> Stream Integer
scalarMul n (Cons x xs) = Cons (n * x) $ scalarMul n xs
instance Num (Stream Integer) where
fromInteger n = Cons n $ streamRepeat 0
negate (Cons x xs) = Cons (-x) $ negate xs
(+) (Cons a as) (Cons b bs) = Cons (a + b) $ as + bs
(*) (Cons a as) bigB@(Cons b bs) =
Cons (a * b) $ (scalarMul a bs) + (as * bigB)
instance Fractional (Stream Integer) where
(/) (Cons a0 a') (Cons b0 b') =
Cons (a0 `div` b0) $ scalarMul (1 `div` b0) (a' - q * b')
where
q :: Stream Integer
q = Cons (a0 `div` b0) (scalarMul (1 `div` b0) (a' - q * b'))
fibs3 :: Stream Integer
fibs3 = x / (1 - x - x^2)
-- exercise 7
type Matrix = ((Integer, Integer), (Integer, Integer))
matrixRow :: Integer -> Matrix -> (Integer, Integer)
matrixRow n m
| n == 0 = fst m
| n == 1 = snd m
| otherwise = error $ show n ++ " out of row num"
matrixCol :: Integer -> Matrix -> (Integer, Integer)
matrixCol n m
| n == 0 = ((fst . fst) m, (fst . snd) m)
| n == 1 = ((snd . fst) m, (snd . snd) m)
| otherwise = error $ show n ++ " out of col num"
tupleMul :: (Integer, Integer) -> (Integer, Integer) -> Integer
tupleMul t1 t2 = fst t1 * fst t2 + snd t1 * snd t2
instance Num (Matrix) where
(*) m1 m2 = ((tupleMul (matrixRow 0 m1) (matrixCol 0 m2),
tupleMul (matrixRow 0 m1) (matrixCol 1 m2)),
(tupleMul (matrixRow 1 m1) (matrixCol 0 m2),
tupleMul (matrixRow 1 m1) (matrixCol 1 m2)))
fib4 :: Integer -> Integer
fib4 0 = 0
fib4 n =
let f = ((1, 1), (1, 0)) :: Matrix
fm = f^n
in (snd . fst) fm
| dirkz/haskell-cis-194 | 06/Fib.hs | isc | 3,262 | 0 | 13 | 919 | 1,564 | 810 | 754 | 80 | 3 |
module Hunch.Runner (
runSimulation
, runCreation
, printVersion
) where
import Hunch.Constants
import qualified Paths_hunch as Meta
import Hunch.Options.Data
import Hunch.Language.Syntax
import Hunch.Language.Parser
import Hunch.Language.PrettyPrinter
import Data.Version (showVersion)
import Data.List (intercalate)
import Control.Monad (when, unless, forM_)
import Control.Exception (catch)
import System.Exit (exitSuccess, exitFailure)
import System.IO (hPutStrLn, stderr)
import System.FilePath (combine, joinPath, isValid, isAbsolute)
import System.Directory
-- Successfully terminate the program by printing a given message
terminate :: String -> IO ()
terminate str = putStrLn str >> exitSuccess
-- Forcefully exit the program by printing a given error message
fatal :: String -> IO ()
fatal str = hPutStrLn stderr ("(FATAL) " ++ str ++ helpText) >> exitFailure
where
helpText = "\n\nType `hunch --help` for more information on Hunch usage."
-- Catch exception and print it as other errors
withCatch :: IO () -> IO ()
withCatch todo = catch todo recover
where
recover :: IOError -> IO ()
recover e = fatal $ intercalate "\n" ["Runtime error:", " " ++ show e]
-- Execute a given IO action and logs the given message, if wanted.
withLog :: Bool -> String -> IO () -> IO ()
withLog logB msg f = f >> when logB (putStrLn msg)
-- Execute a given IO action with the AST corresponding to the given opts.
-- Die with the returned error message if any.
withAST :: Options -> (FileSystem -> IO ()) -> IO ()
withAST opts successFn =
case parseExp expr srcs root sep token start of
Right tree -> do
errors <- if shouldCheck
then checkIntegrity True (templates opts) tree
else return []
if null errors
then successFn tree
else fatal $ formatErrors errors
Left errMsg -> fatal errMsg
where
(Just expr) = input opts
srcs = sources opts
root = rootDir opts
sep = delimiter opts
token = sigil opts
start = startAt opts
shouldCheck = not . noCheck $ opts
-- Recursively copy a directory.
-- No existence checks are done.
copyDir :: FilePath -> FilePath -> IO ()
copyDir from to = do
createDirectoryIfMissing False to
entries <- getDirectoryContents from
let entries' = filter (`notElem` [".", ".."]) entries
forM_ entries' $ \name -> do
let from' = from `combine` name
to' = to `combine` name
isDirectory <- doesDirectoryExist from'
if isDirectory then copyDir from' to' else copyFile from' to'
-- Write an empty file in target, or a file copied from the specified entry
-- template if present.
writeFileOrTpl :: FTemplate -> FilePath -> FilePath -> IO ()
writeFileOrTpl Default target _ = writeFile target ""
writeFileOrTpl (Source tpl) target dir = copyFile (dir `combine` tpl) target
-- Create an empty dir in target, or a directory copied from the specified
-- template dir if present.
makeDirOrTpl :: FTemplate -> FilePath -> FilePath -> IO ()
makeDirOrTpl Default target _ = createDirectory target
makeDirOrTpl (Source tpl) target dir = copyDir (dir `combine` tpl) target
-- Generic function to derive makeFile and makeDir functions.
genericMake :: (FilePath -> IO Bool)
-> (FsEntry -> FilePath -> FilePath -> IO ())
-> Options -> [FilePath] -> FsEntry -> IO ()
genericMake checkFn writeFn opts base entry =
unless (entry == currentDir) $ do
let path = joinPath base `combine` (_entryNameName . _entryName) entry
kindS = show . _entryKind $ entry
indent = (++) $ replicate (length base * 3) ' '
createdMsg = kindS ++ " created: " ++ path
existsMsg = kindS ++ " already exists: " ++ path
existsOMsg = createdMsg ++ " (overriden)"
-- Directories are not overriden ; there's no point.
overrideB = (_entryKind entry == File) && override opts
logB = verbose opts
tplDir = templates opts
exists <- checkFn path
if not exists || overrideB
then let msg = if exists
then "+= " ++ indent existsOMsg
else "++ " ++ indent createdMsg
in withLog logB msg $ writeFn entry path tplDir
else withLog logB ("== " ++ indent existsMsg) $ return ()
-- Create a file from a given entry.
makeFile :: Options -> [FilePath] -> FsEntry -> IO ()
makeFile = genericMake doesFileExist (writeFileOrTpl . _entryTmpl)
-- Create a directory from a given entry.
makeDir :: Options -> [FilePath] -> FsEntry -> IO ()
makeDir = genericMake doesDirectoryExist (makeDirOrTpl . _entryTmpl)
-- Create the given tree in the filesystem by recursively walking over its
-- children.
createTree :: Options -> [FilePath] -> FileSystem -> IO ()
createTree opts base (Node entry children) = do
let newBasePath = base ++ currentPath
currentPath = if entry == currentDir
then []
else [_entryNameName . _entryName $ entry]
case _entryKind entry of
File -> makeFile opts base entry
Directory -> makeDir opts base entry
mapM_ (createTree opts newBasePath) children
-- Check if the given template exists, from base templaate dir tplDir.
getTplErrors :: FilePath -> FsEntry -> IO [String]
getTplErrors tplDir e
| _entryTmpl e == Default = return []
| otherwise = do
fileExists <- doesFileExist path
dirExists <- doesDirectoryExist path
return $ if _entryKind e == File
then if not fileExists
then if dirExists then [errFDir] else [errF]
else []
else if not dirExists
then if fileExists then [errDFile] else [errD]
else []
where
path = tplDir `combine` (_entryTmplSource . _entryTmpl) e
errFDir = "Template '" ++ path ++ "' is a directory, expected a file"
errF = "Template file '" ++ path ++ "' not found"
errDFile = "Template '" ++ path ++ "' is a file, expected a directory"
errD = "Template directory '" ++ path ++ "' not found"
-- Return errors if name is invalid or path is absolute
getNameErrors :: Bool -> FsEntry -> [String]
getNameErrors isRoot node = validMsg ++ absoluteMsg
where
validMsg = [validErr | not . isValid $ filePath]
absoluteMsg = [absErr | not isRoot && isAbsolute filePath]
filePath = _entryNameName . _entryName $ node
validErr = "Invalid name: '" ++ filePath ++ "'"
absErr = "Absolute path: '" ++ filePath ++ "'"
-- Check the integrity of a given file system, collecting errors recursively.
checkIntegrity :: Bool -> FilePath -> FileSystem -> IO [String]
checkIntegrity isRoot tplDir fs = do
tplCheck <- getTplErrors tplDir $ rootLabel fs
childrenErrors <- mapM (checkIntegrity False tplDir) $ subForest fs
let nameCheck = getNameErrors isRoot $ rootLabel fs
errors = concat [nameCheck, tplCheck, concat childrenErrors]
return errors
-- Format list of errors to a string with a visual list of errors.
formatErrors :: [String] -> String
formatErrors errs = introText ++ "\n" ++ errorList
where
introText = "The following " ++ singularOrPlural ++ " encountered:"
singularOrPlural = if length errs == 1 then "error was" else "errors were"
errorList = intercalate "\n" $ map (" - " ++) errs
---
--- Runnners
---
runSimulation :: Options -> IO ()
runSimulation opts = withAST opts $ terminate . showTree
runCreation :: Options -> IO ()
runCreation opts = withAST opts $ \ast -> do
let cr = if verbose opts then "\n" else ""
withCatch $ createTree opts [] ast
terminate $ cr ++ "Done creating entries."
printVersion :: Options -> IO ()
printVersion opts = do
let base = projectName ++ " v" ++ showVersion Meta.version
isVerbose = verbose opts
repository = projectRepo ++ " (" ++ projectLicense ++ " License)"
info = show projectYear ++ ", " ++ maintainerInfo
complementary = if isVerbose
then "\n\n" ++ repository ++ "\n" ++ info
else ""
terminate $ base ++ complementary
| loganbraga/hunch | app/Hunch/Runner.hs | mit | 8,266 | 0 | 15 | 2,153 | 2,211 | 1,140 | 1,071 | 152 | 6 |
module Light.Film
( Film, film, filmDimensions, filmSampleBounds, filmFilter, filmPixels, addSample
, film1080, film720, film480, film2k, film4k, film8k, filmQVGA, filmVGA
, Pixel, pixelSum, pixelWeightSum
, toPNG
)
where
import qualified Codec.Picture as P
import Data.Array
import qualified Data.ByteString.Lazy as BS
import qualified Data.Vector.Storable as V
import Light.Filter
data Pixel = Pixel { pixelSum :: Double
, pixelWeightSum :: Double
}
deriving (Show)
data Film = Film { filmDimensions :: (Int, Int)
, filmFilter :: FilterBox
, filmPixels :: Array (Int, Int) Pixel
}
deriving (Show)
film :: (Show f, Filter f) => (Int, Int) -> f -> Film
film b@(w, h) f = Film b (filterBox f) (listArray ((0, 0), (w-1, h-1)) (cycle [Pixel 0 0]))
filmSampleBounds :: Film -> ((Int, Int), (Int, Int))
filmSampleBounds (Film (w, h) f _) = let (ex, ey) = filterExtent f
in ((floor (-ex), floor (-ey)), (ceiling (fromIntegral w+ex), ceiling (fromIntegral h+ey)))
addSample :: Film -> (Double, Double) -> P.Pixel8 -> Film
addSample (Film (fw, fh) f p) (x, y) v = Film (fw, fh) f (p // updates)
where (ex, ey) = filterExtent f
(minX, minY) = (max 0 (ceiling (x - 0.5 - ex)), max 0 (ceiling (y - 0.5 - ey)))
(maxX, maxY) = (min (fw-1) (floor (x - 0.5 + ex)), min (fh-1) (floor (y - 0.5 + ey)))
updates = [((ux, uy), update ux uy) | ux <- [minX..maxX], uy <- [minY..maxY]]
update ux uy = let (Pixel s ws) = p ! (ux, uy)
pv = filterWeight f (fromIntegral ux - x - 0.5, fromIntegral uy - y - 0.5)
in Pixel (s + fromIntegral v*pv) (ws + pv)
toPNG :: Film -> BS.ByteString
toPNG (Film (w, h) _ p) = P.encodePng (P.Image w h (V.fromList $ map (\ (Pixel s w) -> round (s/w)) [p!(x,y) | y <- [h-1,h-2..0], x <- [0..w-1]]) :: P.Image P.Pixel8)
film1080, film720, film480, film2k, film4k, film8k, filmQVGA, filmVGA :: (Filter f, Show f) => f -> Film
film1080 = film (1920, 1080)
film720 = film (1280, 720)
film480 = film ( 720, 480)
film2k = film (2048, 1080)
film4k = film (4096, 2160)
film8k = film (8192, 4608)
filmQVGA = film ( 320, 240)
filmVGA = film ( 640, 480)
| jtdubs/Light | src/Light/Film.hs | mit | 2,396 | 0 | 15 | 713 | 1,121 | 634 | 487 | -1 | -1 |
{-# language NumDecimals #-}
{-# language OverloadedStrings #-}
module Main where
import Data.Foldable
import Data.Monoid
import Data.ByteString(ByteString)
import Data.ByteString.Char8(unpack)
import qualified Data.ByteString as Bytes
import Control.Concurrent (threadDelay)
import Control.Monad
import Control.Exception
import Data.IORef
import Control.Concurrent.Conceit
import Test.Tasty
import Test.Tasty.HUnit
import System.Directory
import System.FilePath((</>))
import System.IO
import System.IO.Error
import System.Process.Streaming
import System.IO.TailFile
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Tests" [ testCase "notExistingAtFirst" testNotExistingAtFirst
, testCase "preexisting" testPreexisting
, testCase "truncation" testTruncation
, testCase "move" testMove
]
testPreexisting :: IO ()
testPreexisting =
do (filename1,_) <- deleteFiles
Bytes.writeFile filename1 "previous content\n"
let content1 = "1 new content"
content2 = "2 new content"
bytes <- tailToIORef (\filepath ->
do catToFile filepath content1
halfsec
catToFile filepath content2)
filename1
assertEqual "" (newlines [content1,content2]) bytes
testTruncation :: IO ()
testTruncation =
do (filename1,_) <- deleteFiles
Bytes.writeFile filename1 "previous content\n"
let content1 = "1 new content"
content2 = "2 new content"
bytes <- tailToIORef (\filepath ->
do catToFile filepath content1
halfsec
truncateFile filepath
halfsec
catToFile filepath content2)
filename1
assertEqual "" (newlines [content1,content2]) bytes
testMove :: IO ()
testMove =
do (filename1,filename2) <- deleteFiles
let content1 = "1 new content"
content2 = "2 new content"
bytes <- tailToIORef (\filepath ->
do catToFile filepath content1
halfsec
renameFile filepath filename2
halfsec
catToFile filepath content2
halfsec
halfsec
halfsec)
filename1
assertEqual "" (newlines [content1,content2]) bytes
testNotExistingAtFirst :: IO ()
testNotExistingAtFirst =
do (filename1,_) <- deleteFiles
let content1 = "1 new content"
content2 = "2 new content"
bytes <- tailToIORef (\filepath ->
do catToFile filepath content1
halfsec
catToFile filepath content2
halfsec
halfsec)
filename1
assertEqual "" (newlines [content1,content2]) bytes
truncateFile :: FilePath -> IO ()
truncateFile filepath =
execute (piped (shell ("truncate -s 0 "<> filepath)))
(pure ())
catToFile :: FilePath -> ByteString -> IO ()
catToFile filepath content =
execute (piped (shell ("echo \"" <> unpack content <> "\" >> " <> filepath)))
(pure ())
halfsec :: IO ()
halfsec = threadDelay 5e5
newlines :: [ByteString] -> ByteString
newlines bs = mconcat . map (\b -> b <> "\n") $ bs
deleteFiles :: IO (FilePath,FilePath)
deleteFiles = do
tmp <- getTemporaryDirectory
let (basename1,basename2) = ("haskell_tailfile_test_1_387493423492347.txt"
,"haskell_tailfile_test_2_387493423492347.txt")
(filename1,filename2) = (tmp </> basename1,tmp </> basename2)
for_ [filename1,filename2]
(\filepath -> do _ <- tryJust (guard . isDoesNotExistError)
(removeFile filepath)
pure ())
return (filename1,filename2)
tailToIORef :: (FilePath -> IO ()) -> FilePath -> IO Data.ByteString.ByteString
tailToIORef writer filepath =
do ref <- newIORef mempty
let addToRef _ bytes = modifyIORef' ref (\b -> b <> bytes)
runConceit (Conceit (Left <$> (halfsec *> halfsec *> writer filepath))
*>
_Conceit (tailFile filepath addToRef (pure ())))
readIORef ref
| danidiaz/tailfile-hinotify | tests/tests.hs | mit | 4,638 | 0 | 15 | 1,684 | 1,132 | 573 | 559 | 114 | 1 |
module Latte.Commons where
import Control.Monad.Except
import Control.Monad.State
import Latte.Errors
type Runner stateType returnType = StateT stateType (ExceptT LatteError IO) returnType
type ReturnType r s = IO (Either LatteError (r, s))
type RunReturnType r = IO (Either LatteError r)
runRunner :: Runner s r -> s -> ReturnType r s
runRunner runner initialState = runExceptT (runStateT runner initialState)
| mpsk2/LatteCompiler | src/Latte/Commons.hs | mit | 415 | 0 | 8 | 61 | 133 | 74 | 59 | 9 | 1 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.HTMLCollection
(item, item_, itemUnsafe, itemUnchecked, namedItem, namedItem_,
namedItemUnsafe, namedItemUnchecked, getLength, HTMLCollection(..),
gTypeHTMLCollection, IsHTMLCollection, toHTMLCollection)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.item Mozilla HTMLCollection.item documentation>
item ::
(MonadDOM m, IsHTMLCollection self) =>
self -> Word -> m (Maybe Element)
item self index
= liftDOM
(((toHTMLCollection self) ^. jsf "item" [toJSVal index]) >>=
fromJSVal)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.item Mozilla HTMLCollection.item documentation>
item_ ::
(MonadDOM m, IsHTMLCollection self) => self -> Word -> m ()
item_ self index
= liftDOM
(void ((toHTMLCollection self) ^. jsf "item" [toJSVal index]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.item Mozilla HTMLCollection.item documentation>
itemUnsafe ::
(MonadDOM m, IsHTMLCollection self, HasCallStack) =>
self -> Word -> m Element
itemUnsafe self index
= liftDOM
((((toHTMLCollection self) ^. jsf "item" [toJSVal index]) >>=
fromJSVal)
>>= maybe (Prelude.error "Nothing to return") return)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.item Mozilla HTMLCollection.item documentation>
itemUnchecked ::
(MonadDOM m, IsHTMLCollection self) => self -> Word -> m Element
itemUnchecked self index
= liftDOM
(((toHTMLCollection self) ^. jsf "item" [toJSVal index]) >>=
fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.namedItem Mozilla HTMLCollection.namedItem documentation>
namedItem ::
(MonadDOM m, IsHTMLCollection self, ToJSString name) =>
self -> name -> m (Maybe Element)
namedItem self name
= liftDOM (((toHTMLCollection self) ! name) >>= fromJSVal)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.namedItem Mozilla HTMLCollection.namedItem documentation>
namedItem_ ::
(MonadDOM m, IsHTMLCollection self, ToJSString name) =>
self -> name -> m ()
namedItem_ self name
= liftDOM (void ((toHTMLCollection self) ! name))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.namedItem Mozilla HTMLCollection.namedItem documentation>
namedItemUnsafe ::
(MonadDOM m, IsHTMLCollection self, ToJSString name,
HasCallStack) =>
self -> name -> m Element
namedItemUnsafe self name
= liftDOM
((((toHTMLCollection self) ! name) >>= fromJSVal) >>=
maybe (Prelude.error "Nothing to return") return)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.namedItem Mozilla HTMLCollection.namedItem documentation>
namedItemUnchecked ::
(MonadDOM m, IsHTMLCollection self, ToJSString name) =>
self -> name -> m Element
namedItemUnchecked self name
= liftDOM (((toHTMLCollection self) ! name) >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection.length Mozilla HTMLCollection.length documentation>
getLength :: (MonadDOM m, IsHTMLCollection self) => self -> m Word
getLength self
= liftDOM
(round <$>
(((toHTMLCollection self) ^. js "length") >>= valToNumber))
| ghcjs/jsaddle-dom | src/JSDOM/Generated/HTMLCollection.hs | mit | 4,354 | 0 | 14 | 768 | 1,044 | 588 | 456 | -1 | -1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.ValidityState
(js_getValueMissing, getValueMissing, js_getTypeMismatch,
getTypeMismatch, js_getPatternMismatch, getPatternMismatch,
js_getTooLong, getTooLong, js_getRangeUnderflow, getRangeUnderflow,
js_getRangeOverflow, getRangeOverflow, js_getStepMismatch,
getStepMismatch, js_getBadInput, getBadInput, js_getCustomError,
getCustomError, js_getValid, getValid, ValidityState,
castToValidityState, gTypeValidityState)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "($1[\"valueMissing\"] ? 1 : 0)"
js_getValueMissing :: ValidityState -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.valueMissing Mozilla ValidityState.valueMissing documentation>
getValueMissing :: (MonadIO m) => ValidityState -> m Bool
getValueMissing self = liftIO (js_getValueMissing (self))
foreign import javascript unsafe "($1[\"typeMismatch\"] ? 1 : 0)"
js_getTypeMismatch :: ValidityState -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.typeMismatch Mozilla ValidityState.typeMismatch documentation>
getTypeMismatch :: (MonadIO m) => ValidityState -> m Bool
getTypeMismatch self = liftIO (js_getTypeMismatch (self))
foreign import javascript unsafe
"($1[\"patternMismatch\"] ? 1 : 0)" js_getPatternMismatch ::
ValidityState -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.patternMismatch Mozilla ValidityState.patternMismatch documentation>
getPatternMismatch :: (MonadIO m) => ValidityState -> m Bool
getPatternMismatch self = liftIO (js_getPatternMismatch (self))
foreign import javascript unsafe "($1[\"tooLong\"] ? 1 : 0)"
js_getTooLong :: ValidityState -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.tooLong Mozilla ValidityState.tooLong documentation>
getTooLong :: (MonadIO m) => ValidityState -> m Bool
getTooLong self = liftIO (js_getTooLong (self))
foreign import javascript unsafe "($1[\"rangeUnderflow\"] ? 1 : 0)"
js_getRangeUnderflow :: ValidityState -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.rangeUnderflow Mozilla ValidityState.rangeUnderflow documentation>
getRangeUnderflow :: (MonadIO m) => ValidityState -> m Bool
getRangeUnderflow self = liftIO (js_getRangeUnderflow (self))
foreign import javascript unsafe "($1[\"rangeOverflow\"] ? 1 : 0)"
js_getRangeOverflow :: ValidityState -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.rangeOverflow Mozilla ValidityState.rangeOverflow documentation>
getRangeOverflow :: (MonadIO m) => ValidityState -> m Bool
getRangeOverflow self = liftIO (js_getRangeOverflow (self))
foreign import javascript unsafe "($1[\"stepMismatch\"] ? 1 : 0)"
js_getStepMismatch :: ValidityState -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.stepMismatch Mozilla ValidityState.stepMismatch documentation>
getStepMismatch :: (MonadIO m) => ValidityState -> m Bool
getStepMismatch self = liftIO (js_getStepMismatch (self))
foreign import javascript unsafe "($1[\"badInput\"] ? 1 : 0)"
js_getBadInput :: ValidityState -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.badInput Mozilla ValidityState.badInput documentation>
getBadInput :: (MonadIO m) => ValidityState -> m Bool
getBadInput self = liftIO (js_getBadInput (self))
foreign import javascript unsafe "($1[\"customError\"] ? 1 : 0)"
js_getCustomError :: ValidityState -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.customError Mozilla ValidityState.customError documentation>
getCustomError :: (MonadIO m) => ValidityState -> m Bool
getCustomError self = liftIO (js_getCustomError (self))
foreign import javascript unsafe "($1[\"valid\"] ? 1 : 0)"
js_getValid :: ValidityState -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/ValidityState.valid Mozilla ValidityState.valid documentation>
getValid :: (MonadIO m) => ValidityState -> m Bool
getValid self = liftIO (js_getValid (self)) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/ValidityState.hs | mit | 5,002 | 60 | 8 | 649 | 982 | 559 | 423 | 64 | 1 |
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Text.XML.Light
import Text.Feed.Import
import Text.Feed.Query
import System.Environment
import System.Directory
import System.Process
import System.Exit
import Database.HDBC
import Database.HDBC.Sqlite3 (connectSqlite3)
import Data.Convertible.Base
import Data.Convertible (convert)
import Data.Time.Clock (UTCTime (..))
import Data.List.Split
import Data.Maybe
import Data.List
import Control.Exception
-- Data --------------------------------------------------------------
data RSSItem = RSSItem { it_title :: Maybe String
, it_url :: Maybe String
, it_feed_url :: Maybe String
, it_description :: Maybe String
, it_author :: Maybe String
, it_guid :: Maybe String
, it_pubDate :: Maybe Integer
, it_enc_url :: Maybe String
, it_enc_type :: Maybe String
, it_id :: Maybe Integer
, it_unread :: Maybe Bool
} deriving (Show)
data FDType = Plain | Filter | Exec
data RSSFeed = RSSFeed { fd_rssurl :: Maybe String
, fd_url :: Maybe String
, fd_title :: Maybe String
, fd_type :: Maybe FDType
, fd_tags :: Maybe [String]
} deriving (Show)
-- Data classes
showFDType :: FDType -> String
showFDType Plain = "Plain"
showFDType Filter = "Filter"
showFDType Exec = "Exec"
instance Show FDType where
show = showFDType
-- Database Querying -------------------------------------------------
rowToFeed :: [SqlValue] -> RSSFeed
rowToFeed (r:u:t:[]) = RSSFeed (Just $ fromSql r) (Just $ fromSql u) (Just $ fromSql t) Nothing Nothing
rowToFeed _ = RSSFeed Nothing Nothing Nothing Nothing Nothing
loadFeeds :: (IConnection c) => c -> IO [RSSFeed]
loadFeeds conn = do rows <- quickQuery' conn "SELECT rssurl,url,title FROM rss_feed" []
return $ map rowToFeed rows
hasFeed :: (IConnection c) => c -> RSSFeed -> IO Bool
hasFeed _ (RSSFeed Nothing _ _ _ _) = return False
hasFeed conn (RSSFeed rssurl _ _ _ _) = do lst <- quickQuery' conn "SELECT rssurl FROM rss_feed WHERE rssurl = ?" [toSql rssurl]
return (length lst /= 0)
populateFeed :: (IConnection c) => c -> RSSFeed -> IO RSSFeed
populateFeed conn fd = do query <- quickQuery' conn "SELECT rssurl,url,title FROM rss_feed WHERE rssurl = ?" [rurl]
return $ mergeTwo fd $ rowToFeed $ head query
where rurl = toSql $ fd_rssurl fd
mergeTwo :: RSSFeed -> RSSFeed -> RSSFeed
mergeTwo (RSSFeed rss _ _ _ tgs) (RSSFeed _ u t _ _) = RSSFeed rss u t Nothing tgs
findByGuid :: (IConnection c) => c -> RSSItem -> IO Bool
findByGuid conn (RSSItem _ _ _ _ _ (Just g) _ _ _ _ _) =
do query <- quickQuery' conn "SELECT guid FROM rss_item WHERE guid = ?" [toSql g]
return $ length query /= 0
findByGuid _ _ = return False
rowToItem :: [SqlValue] -> RSSItem
rowToItem (t:u:f:a:g:p:eu:et:id:ur:[]) = RSSItem (mfsql t) (mfsql u) (mfsql f)
Nothing (mfsql a) (mfsql g)
(mfsql p) (mfsql eu) (mfsql et)
(mfsql id) (bfsql ur)
where mfsql :: (Convertible SqlValue a) => SqlValue -> Maybe a
mfsql v = Just $ fromSql v
bfsql :: SqlValue -> Maybe Bool
bfsql v = Just $ intToBool $ fromSql v
where intToBool :: Int -> Bool
intToBool 0 = False
intToBool _ = True
readItem :: (IConnection c) => c -> RSSItem -> IO RSSItem
readItem conn it@(RSSItem t u f d a (Just g) p eu et id ur) =
do query <- quickQuery' conn "SELECT title,url,feedurl,author,guid,pubDate,enclosure_url,enclosure_type,id,unread FROM rss_item WHERE guid = ?" [toSql g]
if query == [] then return it
else return $ rowToItem $ head query
readItem conn it = return it
loadFeedItems :: (IConnection c) => c -> RSSFeed -> IO [RSSItem]
loadFeedItems _ (RSSFeed Nothing _ _ _ _) = return []
loadFeedItems conn fd = do query <- quickQuery' conn "SELECT title,url,feedurl,author,guid,pubDate,enclosure_url,enclosure_type,id,unread FROM rss_item WHERE feedurl = ?" [url]
return $ map rowToItem query
where url = toSql $ fd_rssurl fd
-- Database writing (caller must call commit itself) -----------------
addFeed :: (IConnection c) => c -> RSSFeed -> IO ()
addFeed conn fd = do insert_if conn r
updateFeed conn fd
where r = fd_rssurl fd
insert_if c (Just r) = do run c "INSERT INTO rss_feed (rssurl,url,title) VALUES (?,'','')" [toSql r]
return ()
insert_if _ Nothing = return()
updateFeed :: (IConnection c) => c -> RSSFeed -> IO()
updateFeed _ (RSSFeed Nothing _ _ _ _) = return()
updateFeed c (RSSFeed r u t _ _) = do update_if c r u "url"
update_if c r t "title"
where update_if _ _ Nothing _ = return()
update_if c (Just r) (Just v) s = do run c ("UPDATE rss_feed SET " ++ s ++ " = ? WHERE rssurl = ?") [toSql v, toSql r]
return()
addItem :: (IConnection c) => c -> RSSItem -> IO()
addItem conn it = do x <- quickQuery' conn "SELECT MAX(id) FROM rss_item" []
run conn "INSERT INTO rss_item (guid,title,author,url,feedurl,pubDate,content,unread,enclosure_url,enclosure_type) VALUES ('','','','','',0,'',1,'','')" []
updateItem conn $ setId it $ (pop x) + 1
where pop :: [[SqlValue]] -> Integer
pop x = fromSql $ head $ head x
setId (RSSItem t u f d a g p eu et _ ur) id = RSSItem t u f d a g p eu et (Just id) ur
updateItem :: (IConnection c) => c -> RSSItem -> IO()
updateItem _ (RSSItem _ _ _ _ _ _ _ _ _ Nothing _) = return()
updateItem c (RSSItem t u f d a g p eu et id urd) = do update_if c t id "title"
update_if c u id "url"
update_if c f id "feedurl"
update_if c d id "content"
update_if c a id "author"
update_if c g id "guid"
update_if c p id "pubDate"
update_if c eu id "enclosure_url"
update_if c et id "enclosure_type"
update_if c ur id "unread"
where ur = bti urd
update_if _ Nothing _ _ = return()
update_if c (Just v) (Just id) s = do run c ("UPDATE rss_item SET " ++ s ++ " = ? WHERE id = ?") [toSql v, toSql id]
return()
bti :: Maybe Bool -> Maybe Int
bti Nothing = Nothing
bti (Just True) = Just 1
bti (Just False) = Just 0
-- Load RSSFeeds from url file ---------------------------------------
cutLine :: String -> String -> Bool -> [String]
cutLine "" "" _ = []
cutLine "" chunk _ = [chunk]
cutLine ('"':ls) "" True = cutLine ls "" False
cutLine ('"':ls) chunk True = chunk : cutLine ls "" False
cutLine (l:ls) chunk True = cutLine ls (chunk ++ [l]) True
cutLine ('"':ls) "" False = cutLine ls "" True
cutLine ('"':ls) chunk False = chunk:cutLine ls "" True
cutLine (l:ls) chunk False
| isBlank l = if chunk == "" then cutLine ls "" False
else chunk : cutLine ls "" False
| otherwise = cutLine ls (chunk ++ [l]) False
where isBlank ' ' = True
isBlank '\t' = True
isBlank '\n' = True
isBlank _ = False
loadFeedsFromFile :: FilePath -> IO [RSSFeed]
loadFeedsFromFile "" = return []
loadFeedsFromFile path = do file <- readFile path
return $ rmNothing $ map parseLine $ lines file
where rmNothing :: [Maybe RSSFeed] -> [RSSFeed]
rmNothing [] = []
rmNothing (Nothing:rs) = rmNothing rs
rmNothing ((Just r):rs) = r:rmNothing rs
parseLine :: String -> Maybe RSSFeed
parseLine str
| parts == [] = Nothing
| otherwise = Just $ RSSFeed (Just $ head parts) Nothing Nothing Nothing (Just $ tail parts)
where parts = cutLine str "" False
-- Initialisation of data --------------------------------------------
newFeeds :: (IConnection c) => c -> [RSSFeed] -> IO [RSSFeed]
newFeeds _ [] = return []
newFeeds conn (l:ls) = do b <- hasFeed conn l
if b then newFeeds conn ls
else do nfds <- newFeeds conn ls
return $ l : nfds
addNewFeed :: (IConnection c) => c -> RSSFeed -> IO()
addNewFeed conn fd = addFeed conn toadd
where toadd = setTitle fd $ fd_rssurl fd
setTitle :: RSSFeed -> Maybe String -> RSSFeed
setTitle (RSSFeed r u _ ty tgs) title = RSSFeed r u title ty tgs
-- TODO Find right type for this function
initing urls db = do conn <- connectSqlite3 db
ufds <- loadFeedsFromFile urls
nfds <- newFeeds conn ufds
mapM_ (addNewFeed conn) nfds
commit conn
fds <- mapM (populateFeed conn) ufds
return (conn, fds)
-- Feed manipulation -------------------------------------------------
findType :: RSSFeed -> Maybe FDType
findType (RSSFeed Nothing _ _ _ _) = Nothing
findType (RSSFeed (Just url) _ _ _ _) = Just $ typeFromUrl url
where typeFromUrl :: String -> FDType
typeFromUrl ('f':'i':'l':'t':'e':'r':_) = Filter
typeFromUrl ('e':'x':'e':'c':_) = Exec
typeFromUrl _ = Plain
setType :: RSSFeed -> RSSFeed
setType fd@(RSSFeed r u t _ tgs) = RSSFeed r u t tpe tgs
where tpe = findType fd
parseFilter :: String -> (String,[String],String)
parseFilter str
| id /= "filter" || fl == "" || url == "" = ("", [], "")
| otherwise = (head flct, tail flct, url)
where parts = splitOn ":" str
(id:fl:urls) = parts
url = intercalate ":" urls
flct = splitOn " " fl
parseExec :: String -> (String,[String])
parseExec str
| length parts /= 2 || id /= "exec" || ex == "" = ("", [])
| otherwise = (head exct, tail exct)
where parts = splitOn ":" str
(id:ex:[]) = parts
exct = splitOn " " ex
-- Downloading a feed ------------------------------------------------
adapt :: (ExitCode, String, String) -> IO (Maybe String)
adapt (ExitFailure _, _, _) = return Nothing
adapt (ExitSuccess, out, _) = return $ Just out
dlUrl :: String -> IO (Maybe String)
dlUrl url = readProcessWithExitCode cmd args "" >>= adapt
where cmd = "/usr/bin/curl"
args = [url]
dlFilter :: String -> [String] -> String -> IO (Maybe String)
dlFilter cmd args input = readProcessWithExitCode cmd args input >>= adapt
dlExec :: String -> [String] -> IO (Maybe String)
dlExec cmd args = dlFilter cmd args ""
download :: RSSFeed -> IO (Maybe String)
download (RSSFeed (Just url) _ _ (Just Plain) _) = dlUrl url
download (RSSFeed (Just ul) _ _ (Just Filter) _) = do dl <- dlUrl url
if isNothing dl then return Nothing
else let (Just s) = dl in dlFilter c a s
where (c,a,url) = parseFilter ul
download (RSSFeed (Just url) _ _ (Just Exec) _) = dlExec cmd args
where (cmd,args) = parseExec url
download fd@(RSSFeed (Just _) _ _ Nothing _) = download $ setType fd
download _ = return Nothing
-- Parsing xml feed --------------------------------------------------
parseFeed :: RSSFeed -> String -> Maybe (RSSFeed, [RSSItem])
parseFeed fd xml
| isNothing psfd = Nothing
| otherwise = Just (setTitle fd $ getFeedTitle feed, map parseItem $ feedItems feed)
where psfd = parseFeedString xml
(Just feed) = psfd
setTitle :: RSSFeed -> String -> RSSFeed
setTitle (RSSFeed r u _ tp tg) t = RSSFeed r u (Just t) tp tg
parseItem v = RSSItem (getItemTitle v)
(getItemLink v)
Nothing
(getItemDescription v)
(getItemAuthor v)
(getItemId v >>= (\(_,g) -> Just g))
(getItemPublishDate v >>= (>>= Just . utcTimeToEpochTime))
(getItemEnclosure v >>= (\(e,_,_) -> Just e))
(getItemEnclosure v >>= (\(_,e,_) -> e))
Nothing
Nothing
where utcTimeToEpochTime :: UTCTime -> Integer
utcTimeToEpochTime = convert
-- Updating a feed ---------------------------------------------------
dlUpdateFeed :: (IConnection c) => c -> RSSFeed -> IO [RSSItem]
dlUpdateFeed conn fd = do dlxml <- download fd
let psfd = dlxml >>= parseFeed fd
if isNothing psfd then return []
else let (Just (feed,its)) = psfd in upgradeFeed conn
feed
$ map (prep feed) its
where prep :: RSSFeed -> RSSItem -> RSSItem
prep fd@(RSSFeed r@(Just _) _ _ _ _) (RSSItem t u Nothing d a g p eu et id ur) = prep fd $ RSSItem t u r d a g p eu et id ur
prep fd (RSSItem t u@(Just _) r d a Nothing p eu et id ur) = prep fd $ RSSItem t u r d a u p eu et id ur
prep fd (RSSItem t u r d a g p eu et id Nothing) = prep fd $ RSSItem t u r d a g p eu et id (Just False)
prep _ it = it
upgradeFeed :: (IConnection c) => c -> RSSFeed -> [RSSItem] -> IO [RSSItem]
upgradeFeed conn _ its = mapM (procFDItem conn) its
where procFDItem :: (IConnection c) => c -> RSSItem -> IO RSSItem
procFDItem conn it = do b <- findByGuid conn it
if b then readItem conn it
else do addItem conn it
return it
-- Get the paths -----------------------------------------------------
safeGetEnv :: String -> IO (Maybe String)
safeGetEnv var = handle mcatch $ menv var
where mcatch :: IOError -> IO (Maybe String)
mcatch _ = return Nothing
menv :: String -> IO (Maybe String)
menv var = do val <- getEnv var
return $ Just val
firstNotNothing :: [Maybe a] -> a -> a
firstNotNothing [] d = d
firstNotNothing (Nothing:ls) d = firstNotNothing ls d
firstNotNothing ((Just v):ls) _ = v
getVar :: String -> String -> IO (Maybe String)
getVar var end = do home <- safeGetEnv var
mgetHome ('/':end) home
where mgetHome :: String -> Maybe String -> IO (Maybe String)
mgetHome _ Nothing = return Nothing
mgetHome end (Just h) = return $ Just $ h ++ end
getArg :: [String] -> String -> Maybe String
getArg (('-':'-':ag):v:vs) nm
| ag == nm = Just v
| otherwise = getArg (v:vs) nm
getArg (_:ags) nm = getArg ags nm
getArg [] _ = Nothing
getDefaultDir :: [String] -> IO String
getDefaultDir args = do vals <- sequence $ sup:def:env:xdg:[]
return $ firstNotNothing vals "."
where env = getVar "XDG_DATA_HOME" "newsbeuter"
xdg = getVar "HOME" ".local/share/newsbeuter" >>= exists
def = getVar "HOME" ".newsbeuter" >>= exists
sup = return $ getArg args "dir"
exists :: Maybe String -> IO (Maybe String)
exists Nothing = return Nothing
exists (Just p) = do b <- doesDirectoryExist p
if b then return $ Just p
else return Nothing
-- Main process ------------------------------------------------------
main :: IO()
main = do args <- getArgs
dir <- getDefaultDir args
let urls = dir ++ "/urls"
let cache = dir ++ "/cache.db"
(conn, feeds) <- initing urls cache
mapM_ (\x -> let (Just t) = fd_title x in putStrLn t) feeds
disconnect conn
| lucas8/cli_newsbeuter | rss.hs | mit | 16,954 | 0 | 17 | 6,090 | 5,696 | 2,836 | 2,860 | 304 | 5 |
{-# LANGUAGE DeriveDataTypeable #-}
module JavaScript.Web.ErrorEvent.Internal where
import GHCJS.Types
import Data.Typeable
newtype ErrorEvent = ErrorEvent JSRef deriving Typeable
| tavisrudd/ghcjs-base | JavaScript/Web/ErrorEvent/Internal.hs | mit | 184 | 0 | 5 | 22 | 30 | 20 | 10 | 5 | 0 |
module Examples.Tests.BranchingEuterpea where
import Euterpea
-- Test case generated with seed 0
branchingEuterpea = Modify (Tempo (1 / 1)) (Modify (Instrument AcousticGrandPiano) (Prim (Note (1 / 4) (C,4)) :+: Prim (Note (1 / 2) (Ef,4)))) :: Music Pitch
| michaelbjames/improb | Examples/Tests/BranchingEuterpea.hs | mit | 257 | 0 | 14 | 40 | 109 | 60 | 49 | 3 | 1 |
module Primitives where
import qualified Data.Text as T
data Prim = Text T.Text
| Number Integer
deriving (Eq, Ord, Show)
| imccoy/utopia | src/Primitives.hs | mit | 137 | 0 | 7 | 35 | 43 | 26 | 17 | 5 | 0 |
module Yage.Formats.AMDCubeMap where
import Yage.Prelude hiding ( toList, left, right )
import Yage.Rendering.GL
import System.Directory
import Data.List ( (!!) )
import Data.Foldable ( toList )
import GHC.Exts ( groupWith )
import Text.Regex.Posix
import Text.Read
import Yage.Resources
data LoadCubeMapException = LoadCubeMapException String deriving ( Show, Typeable )
instance Exception LoadCubeMapException
type GLFaceTarget = GLenum
data CubeMapSelection = CubeMapSelection
{ selectionDirectory :: FilePath
, selectionFiles :: FilePath -> Bool
, selectionLevelAndSide :: FilePath -> (Int, GLFaceTarget)
-- ^ a projection from FilePath to mipmap level and cube face
}
amdSeperateFiles :: FilePath -> Text -> CubeMapSelection
amdSeperateFiles dir ext = CubeMapSelection
{ selectionDirectory = dir
, selectionFiles = matchFiles
, selectionLevelAndSide = matchLevelAndSide
}
where
matchFiles f = (fpToString f) =~ ("^[[:alnum:]]*_m[[:digit:]]{1,2}_c[[:digit:]]{1,2}\\." ++unpack ext++"$")
matchLevelAndSide f =
let sub :: String
sub = (fpToString f) =~ (asString "_m[[:digit:]]{1,2}_c[[:digit:]]{1,2}\\.")
nums :: [Int]
nums = (concatMap . map) read (sub =~ (asString "[[:digit:]]{1,2}") :: [[String]])
in (nums!!0, toCubeSide $ nums !! 1)
toCubeSide i = toList glFaceTargets !! i
singleCubemapMipFiles :: MonadIO m => CubeMapSelection -> m (MipmapChain (Cubemap FilePath))
singleCubemapMipFiles CubeMapSelection{..} = do
selectedFiles <- io $ filter selectionFiles . map fromString <$> getDirectoryContents (fpToString selectionDirectory)
let mipmaps = groupWith (fst.selectionLevelAndSide) selectedFiles
cubes = map (cubeFromList.sortWith (snd.selectionLevelAndSide)) $ mipmaps
mMipCubes :: Maybe (MipmapChain (Cubemap FilePath))
mMipCubes = mipMapChain $ map (fmap (mappend selectionDirectory)) cubes
case mMipCubes of
Nothing -> io $ throwIO $ LoadCubeMapException $ "at least one complete cube map with base texture for MipMapChain required!"
Just mipCubes -> return $ mipCubes
where
cubeFromList [right,left,top,bottom,front,back] = Cubemap right left top bottom front back
cubeFromList _ = error "singleCubemapMipFiles: invalid pattern"
| MaxDaten/yage | src/Yage/Formats/AMDCubeMap.hs | mit | 2,558 | 1 | 15 | 680 | 614 | 331 | 283 | -1 | -1 |
strlen :: IO ()
strlen= do
putStr "Enter a string: "
xs <- getLine
putStrLn $ "The string has "++(show (length xs))++ " characters"
beep :: IO ()
beep =putStr "\BEL"
cls :: IO ()
cls =putStr "\ESC[2J"
-- By convention, the position of each character on the screen is given by a pair (x , y ) of positive integers, with (1, 1) being the top-left corner.
type Pos = (Int,Int)
-- moves the cursor to a given position
-- the cursor is a marker that indicates where the next character displayed will appear
goto :: Pos -> IO ()
goto(x,y) = putStr ("\ESC[" ++ show y ++ ";" ++ show x ++ "H") -- 有点厉害.. \ESC[magic]
writeat :: Pos -> String -> IO ()
writeat p xs = do
goto p
putStr xs
seqn :: [IO a]->IO()
seqn [] = return ()
seqn (a:as) = do
a
seqn as
-- ORZ
-- box :: [String]
-- box = ["+---------------+",
-- "| |",
-- "+---+---+---+---+",
-- "| q | c | d | = |",
-- "+---+---+---+---+",
-- "| 1 | 2 | 3 | + |",
-- "+---+---+---+---+",
-- "| 4 | 5 | 6 | - |",
-- "+---+---+---+---+",
-- "| 7 | 8 | 9 | * |",
-- "+---+---+---+---+",
-- "| 0 | ( | ) | / |",
-- "+---+---+---+---+"]
-- buttons :: [Char ]
-- buttons = standard ++ extra
-- where
-- standard = "qcd=123+456-789*0()/"
-- extra = "QCD \ESC\BS\DEL\n"
-- showbox :: IO ()
-- showbox = seqn [writeat (1,y) xs | (y,xs) <- zip [1..13] box]
-- display :: String → IO ()
-- display xs =
-- do
-- writeat (3, 2) " "
-- writeat (3,2) (reverse (take 13 (reverse xs)))
-- calc :: String -> IO ()
-- calc xs = do
-- display xs
-- c <- getCh
-- if elem c buttons then
-- process c xs
-- else
-- do
-- beep
-- calc xs
| SnowOnion/GrahamHaskellPractice | ch09/play.hs | mit | 1,693 | 2 | 12 | 454 | 302 | 168 | 134 | 21 | 1 |
{-
Let a, b and c be the length of the edges of the cuboide along the axis X, Y and
Z with a ≥ b ≥ c ≥ 1.
Suppose that the spider moves in straight line on the face XY and joins the edge
of length a opposite to its starting point at the location (λ a, b, 0) and
then continue its move up to its destination point (a, b, c).
This distance it travels is given by:
l(λ) = (λ²a² + b²)^½ + ((1-λ)²a² + c²)^½.
To find the value of λ that minimizes that distance, we solve ∂l(λ)/∂λ=0 and get
λ=b/(b+c). This leads in turn, after simplification to:
l_min = (a² + (b+c)²)^½
The other shortest path candidates are obtained by permuting a, b and c.
However, from the three possibilities, the expression above corresponds to the
shortest path as a is not smaller than b and c.
Let pose d=b+c. It comes that 2 ≤ d ≤ 2a. Given a, we have to find the values of
d such that a²+d² is a perfect square.
For each of them, the valid values of b range from b_min = floor((d-1)/2)+1 to
b_max = min(a, d-1). The length of this interval is thus
b_max - b_min + 1 = min(a, d-1) - floor((d-1)/2)
-}
isPerfectSquare :: Int -> Bool
isPerfectSquare n2 = (n*n == n2) where n = round $ sqrt $ fromIntegral n2
candidates :: [(Int, Int)]
candidates = [(a, d) | a <- [1..], d <- [2..2*a], isPerfectSquare (a*a+d*d)]
accumulate acc ((a, d):ls) = (a, acc') : accumulate acc' ls
where acc' = acc + (min a (d-1)) - (div (d-1) 2)
euler n = head $ dropWhile (\(a, acc) -> acc<n) $ accumulate 0 candidates
main = print $ euler 1000000
| dpieroux/euler | 0/0086.hs | mit | 1,569 | 0 | 12 | 338 | 263 | 142 | 121 | 8 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Hetcons.Parsable
(Parsable
,parse
) where
import Charlotte_Types
(Proposal_1a
,decode_Proposal_1a
,Public_Crypto_Key(Public_Crypto_Key
,public_Crypto_Key_public_crypto_key_x509)
,Proof_of_Consensus
,decode_Proof_of_Consensus
,Phase_2b
,decode_Phase_2b
,Phase_2a
,decode_Phase_2a
,Phase_1b
,decode_Phase_1b
,Slot_Value
,decode_Slot_Value
)
import Data.ByteString.Lazy ( ByteString )
import Thrift.Protocol.Binary ( BinaryProtocol(BinaryProtocol) )
import Thrift.Transport.Empty ( EmptyTransport(EmptyTransport) )
-- | We have messages serialized for transport within Signed_Messages.
-- However, deserializing them into their thrift data structures is not enough,
-- if we want to recursively parse and verify the signed messags they carry within themselves.
-- Therefore, we create the Parsable class for stuff which might require such recursive verification.
class Parsable a where
-- | The parse function is meant to deserialize an object, but also deserialize and verify any signed messages within it.
-- Of course, this depends on the type of the object.
parse :: ByteString -> a
-- | Parse a Slot_Value using Thrift
instance {-# OVERLAPPING #-} (Monad m) => Parsable (m Slot_Value) where
parse = return . (decode_Slot_Value (BinaryProtocol EmptyTransport))
-- | Parse a Proposal_1a using Thrift
instance {-# OVERLAPPING #-} (Monad m) => Parsable (m Proposal_1a) where
parse = return . (decode_Proposal_1a (BinaryProtocol EmptyTransport))
-- | Parse a Phase_1b using Thrift
instance {-# OVERLAPPING #-} (Monad m) => Parsable (m Phase_1b) where
parse = return . (decode_Phase_1b (BinaryProtocol EmptyTransport))
-- | Parse a Phase_2a using Thrift
instance {-# OVERLAPPING #-} (Monad m) => Parsable (m Phase_2a) where
parse = return . (decode_Phase_2a (BinaryProtocol EmptyTransport))
-- | Parse a Phase_2b using Thrift
instance {-# OVERLAPPING #-} (Monad m) => Parsable (m Phase_2b) where
parse = return . (decode_Phase_2b (BinaryProtocol EmptyTransport))
-- | Parse a Proof_of_Consensus using Thrift
instance {-# OVERLAPPING #-} (Monad m) => Parsable (m Proof_of_Consensus) where
parse = return . (decode_Proof_of_Consensus (BinaryProtocol EmptyTransport))
| isheff/hetcons | src/Hetcons/Parsable.hs | mit | 2,398 | 0 | 10 | 446 | 407 | 237 | 170 | 37 | 0 |
import Data.Char
import Numeric
isPalindrome :: String -> Bool
isPalindrome s = s == reverse s
showIntInBinary :: Int -> String
showIntInBinary n = showIntAtBase 2 intToDigit n ""
solve :: Int
solve = sum nums
where
nums = [x | x <- [1..999999], isPalindrome $ show x, isPalindrome $ showIntInBinary x]
main :: IO ()
main = print solve
| jwtouron/haskell-play | ProjectEuler/Problem36.hs | mit | 346 | 0 | 10 | 70 | 135 | 69 | 66 | 11 | 1 |
{-|
Module : Dvx.Utils
Description : Utils functions
-}
module Dvx.Utils
( boolToInt
, isNumeric
, joinstr
, joinsub
, middle
, splitAndKeep
, splitOn
, trim
) where
import Data.Char (isSpace, isDigit)
import Data.List (intercalate)
-- |Trim whitespace from a string
trim :: String -> String
trim = f . f where f = reverse . dropWhile isSpace
-- |Split a list of lists based on a single item separator
splitOn :: Eq a => a -> [a] -> [[a]]
splitOn _ [] = []
splitOn i lst | null b = [a]
| otherwise = a : splitOn i (tail b)
where
(a, b) = break (== i) lst -- Get before/after separator
-- |Split a string based on multiple separators while keeping them as items
splitAndKeep :: String -> String -> [String]
splitAndKeep _ [] = []
splitAndKeep f s | null b = [a]
| otherwise = a : [head b] : splitAndKeep f (tail b)
where
(a, b) = break (`elem` f) $ trim s
-- |Check if a string is an integer
isNumeric :: String -> Bool
isNumeric = all isDigit
-- |Take out the first and last character of a string
middle :: String -> String
middle [] = error "Called middle on empty string."
middle (_:[]) = error "Called middle on length 1 string."
middle x = tail $ init x
-- |Merge a list of lists into a single list
joinsub :: [[a]] -> [a]
joinsub = foldr (\a b -> a ++ b) []
-- |Create string tokens from a list of strings
-- This is a workaround to a design fault in our tokenizer
joinstr :: [String] -> Int -> [String] -> [String]
joinstr acc 0 [] = reverse acc
joinstr acc _ [] = error $ "unclosed string: " ++ (intercalate [] $ reverse acc)
joinstr acc 0 (('{':x):xs) | last x == '}' = joinstr (('{':x):acc) 0 xs
| otherwise = joinstr (('{':x):acc) 1 xs
joinstr acc 0 (x:xs) | last x == '}' = error $ "unexpected string closing: " ++ (intercalate [] $ reverse acc)
| otherwise = joinstr (x:acc) 0 xs
joinstr acc depth (x:xs) =
joinstr ((head acc ++ x):(tail acc)) (depth + nesting x) xs
where
nesting c | head c == '{' = 1
| last c == '}' = -1
| otherwise = 0
-- |1 if given True, 0 if given False
boolToInt :: Bool -> Int
boolToInt True = 1
boolToInt False = 0
| Hamcha/dvx | Dvx/Utils.hs | mit | 2,367 | 0 | 11 | 729 | 826 | 429 | 397 | 46 | 1 |
-- Just code from the blog post http://stochastix.wordpress.com/2011/09/05/circular-convolution-in-haskell
--
--
circShiftR :: [a] -> [a]
circShiftR [] = []
circShiftR x = last x : init x
circShiftL :: [a] -> [a]
circShiftL [] = []
circShiftL xs = (tail xs) : [head xs]
--iterate :: (a -> a) -> a -> [a]
--iterate f x = x : iterate f (f x)
--
innerProd :: Num a => [a] -> [a] -> a
innerProd xs ys = sum(zipWith (*) xs ys)
circConv :: Num a => [a] -> [a] -> [a]
circConv xs ys = map (innerProd xs) ys
where
n = length xs
ys' = (circShiftR . reverse) ys
yss = take n (iterate circShiftR ys')
main = do return Nothing
| softwaremechanic/Miscellaneous | Haskell/Circular_convolution.hs | gpl-2.0 | 690 | 0 | 9 | 198 | 258 | 136 | 122 | 14 | 1 |
module HoS.Network.Handler.FastCGI (
getResponseFromCGI,
getDataFrom,
) where
import HoS.Network.Base
import HoS.Network.Server
import HoS.System.Thread
import HoS.Network.Http
import HoS.Network.Util
import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Data.ByteString.Internal as BSI
import Network.Socket
import Data.Word
import Data.DateTime
import Data.Maybe
import Data.Char
import Data.Bits
import qualified Data.Map as M
data FastCGIRecord = FastCGIRecord
{ fcgiVersion :: Word8
, fcgiType :: Word8
, fcgiRequestIdB1 :: Word8
, fcgiRequestIdB0 :: Word8
, fcgiContentLengthB1 :: Word8
, fcgiContentLengthB0 :: Word8
, fcgiPaddingLength :: Word8
, fcgiReserved :: Word8
, fcgiContentData :: [Word8]
, fcgiPaddingData :: [Word8]
} deriving (Show)
--recordToString :: FastCGIRecord -> String
--recordToString record = map BSI.w2c $
--writeRecord :: Socket -> FastCGIRecord -> IO Bool
--writeRecord sock record = do
getResponseFromCGI :: SvHost -> Request -> IO Response
getResponseFromCGI host request = do
now <- getCurrentTime
let filepath = svRoot (svConfig host) ++ rqURI request
contents <- getDataFrom filepath
let contents' = reverse . (dropWhile (=='\0')) . (drop 16) . reverse $ contents
let (headers, body) = fromJust $ splitAtEmptyLine contents'
return $ getResponse 1.1 200
[ (Server, "hos")
, (Date, httpDate now)
-- , (ContentType, fromJust $ getRequestHeader req ContentType)
, (ContentLength, show $ length body)
] body
getDataFrom :: String -> IO String
getDataFrom filepath = do
hostAddress <- inet_addr "127.0.0.1"
let sockAddr = SockAddrInet 9000 hostAddress
-- Create a socket
sock <- socket AF_INET Stream defaultProtocol
-- Connect to server
connect sock sockAddr
let fisrt = [ '\1', '\1', '\0', '\0', '\0', '\8', '\0', '\0'
, '\0', '\1', '\0', '\0', '\0', '\0', '\0', '\0'
]
let nameParis =
[ ("GATEWAY_INTERFACE", "FastCGI/1.0")
, ("REQUEST_METHOD", "GET")
, ("SCRIPT_FILENAME", filepath)
, ("SERVER_PORT", "8080")
]
let params = toNameValuePairs nameParis
let params_len = length params
let params_padding_len = (8 - params_len `mod` 8)
let second = ['\1', '\4', '\0', '\1'] ++ showContentLength params_len ++ showPaddingLength params_padding_len ++ ['\0']
let second' = params ++ replicate params_padding_len '\0'
let third = ['\1', '\4', '\0', '\1', '\0', '\0', '\0', '\0']
let four = ['\1', '\5', '\0', '\1', '\0', '\0', '\0', '\0']
let request = [fisrt, second, second', third, four]
print $ map length request
send sock $ concat request
s <- parseFastCGIRecord sock
sClose sock
return s
showContentLength :: Int -> String
showContentLength num = map chr . map (.&. 0xff) $ [shiftR num 8, num]
showPaddingLength :: Int -> String
showPaddingLength num = map chr . map (.&. 0xff) $ [num]
toNameValuePairs :: [ (String, String) ] -> String
toNameValuePairs (x:xs) = toNameValuePair x ++ toNameValuePairs xs
where
toNameValuePair (name, value) =
(showLength . length $ name) ++ (showLength . length $ value)
++ name ++ value
where
showLength :: Int -> String
showLength num
| num <= 127 = [chr num]
| otherwise = map chr . map (.&. 0xff) $
[ clearBit (shiftR num 24) 7
, shiftR num 16
, shiftR num 8
, num
]
toNameValuePairs [] = ""
parseFastCGIRecord :: Socket -> IO String
parseFastCGIRecord sock = do
s <- recv sock 8
s <- recv sock 100000
return s
| Cofyc/hos | src/HoS/Network/Handler/FastCGI.hs | gpl-2.0 | 3,864 | 8 | 19 | 1,065 | 1,122 | 606 | 516 | 90 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module ParseArgs (
parseArgs
) where
import System.Console.CmdArgs
import System.Environment (getProgName)
data Options = Options
{ query :: String
, file :: [String]
, output :: String
, positional :: [String]
}
deriving (Data, Typeable)
options = Options
{ query = def &= typ "QUERY" &= help "Set Prolog query (If not set, first positional argument is used)"
, file = def &= typ "FILE" &= help "Consult file before executing query"
, output = "graph.png" &= typ "FILE" &= help "Save generated image to file (default: 'graph.png')"
, positional = def &= args &= typ "QUERY [FILE]..."
}
&= versionArg [ignore]
&= helpArg [name "h"]
parseArgs = do
opts <- getProgName >>= cmdArgs . ((options &=) . program)
return $ case opts of
Options q fs o [] -> (q, fs, o)
Options _ fs o [q] -> (q, fs, o)
Options _ fs o (q:fs') -> (q, fs++fs', o)
| nishiuramakoto/logiku | prolog/prolog-graph/ParseArgs.hs | gpl-3.0 | 958 | 0 | 13 | 242 | 313 | 172 | 141 | 24 | 3 |
{-|
--------------------------------------------------------------------------------
-----------------------------------Exercise 1-----------------------------------
--------------------------------------------------------------------------------
-}
newtype ZipList a = Z [a]
deriving (Show)
instance Functor ZipList where
fmap f (Z xs) = Z (map f xs)
instance Applicative ZipList where
pure x = Z (repeat x)
Z fs <*> Z xs = Z (zipWith (\f x -> f x) fs xs)
{-|
--------------------------------------------------------------------------------
-----------------------------------Exercise 2-----------------------------------
--------------------------------------------------------------------------------
-}
{-|
Write an Haskell program that, given three lists L1, l2 and L3 of length n >0,
computes the list containing all lists of three elements where the first element
comes from L1, the second element from L2 and the third from L3.
-}
-- This function uses the normal lists and not the ZipLists. This because the
-- exercise requires *all lists*, so a cartesian product is required.
allLists :: [a] -> [a] -> [a] -> [[a]]
allLists xs ys zs = (\x y z -> [x, y, z]) <$> xs Prelude.<*> ys Prelude.<*> zs
{-|
Write an Haskell program that, given lists L1, L2 and L3 of length n>0, computes
the list containing n lists of three elements where for the i-th such list, the
first element is the i-th element of L1, the second element is the i-th element
of L2 and the third is the i-th element of L3.
-}
-- Here I use ZipLists so I can apply operation between elements which are in
-- the same position in the input lists.
takeElements :: [a] -> [a] -> [a] -> [[a]]
takeElements xs ys zs = (\(Z e) -> e) (Main.pure (\x y z -> [x, y, z]) Main.<*> (Z xs) Main.<*> (Z ys) Main.<*> (Z zs))
{-|
Write an Haskell program that, given a list L of lists of Int, produces a new
list that is obtained from L by adding 1 to the first list contained in L, then
adding 2 to the second list of L ad so on.
-}
-- Here I use again ZipLists. First of all, `increments` cntains a list of
-- sections. These sections represent the desired increments. The list is like
-- [(+1), (+2), .., +(length xss)]. After that I use the applicative style for
-- performing the required operation. With a combination of ZipList and the list
-- fmap I apply the right increment to every element of the right list. Finally,
-- I unbox the ZipList using a lambda.
incrementalAddition :: [[Int]] -> [[Int]]
incrementalAddition xss = (\(Z e) -> e) (Main.pure sum Main.<*> (Z increments) Main.<*> (Z xss))
where increments = zipWith (\f x -> f x) (repeat (+)) [1..length xss]
sum f xs = Prelude.fmap f xs
| mdipirro/functional-languages-homeworks | Week 8/zipList.hs | gpl-3.0 | 2,745 | 0 | 13 | 515 | 483 | 264 | 219 | 15 | 1 |
{-# OPTIONS_GHC -XOverloadedStrings #-}
module Folsolver.LP
( module Folsolver.LP.LPSolver
, module Folsolver.LP.Arithmetic
) where
import Folsolver.LP.LPSolver
import Folsolver.LP.Arithmetic | traeger/fol-solver | Folsolver/LP.hs | gpl-3.0 | 196 | 0 | 5 | 22 | 35 | 24 | 11 | 6 | 0 |
{-# Language GADTs #-}
{-# Language KindSignatures #-}
{-# LAnguage TypeOperators #-}
{-# Language ConstraintKinds #-}
{-# Language UndecidableInstances #-}
{-# Language ExistentialQuantification #-}
{-# Language Rank2Types #-}
{-# Language DataKinds #-}
{-# Language FlexibleInstances #-}
{-# Language FlexibleContexts #-}
{-# Language ScopedTypeVariables #-}
{-# Language MultiParamTypeClasses #-}
{-# Language UnicodeSyntax #-}
module Data.SMT.Abstract.Types where
import Data.Extensible
import qualified Data.IntSet as IS
data FComponent = EQUAL | LESSTHAN | AND | OR
data TComponent = VAR | INT | ADD | NEG | MUL
type AllFComponent = [EQUAL, LESSTHAN, AND, OR]
type AllTComponent = [VAR, INT, ADD, NEG, MUL]
class Ppr a where
ppr :: a -> String
class GetVariables a where
fv :: a -> IS.IntSet
data AbstFormula term (cs :: [FComponent]) (a :: FComponent) where
(:=:) :: (EQUAL ∈ cs) => term -> term -> AbstFormula term cs EQUAL
(:<:) :: (LESSTHAN ∈ cs) => term -> term -> AbstFormula term cs LESSTHAN
(:&:) :: (AND ∈ cs) => AbstFormula term cs :| cs -> AbstFormula term cs :| cs -> AbstFormula term cs AND
(:|:) :: (OR ∈ cs) => AbstFormula term cs :| cs -> AbstFormula term cs :| cs -> AbstFormula term cs OR
instance Ppr term => Ppr (AbstFormula term cs EQUAL) where
ppr (t1 :=: t2) = ppr t1 ++ "=" ++ ppr t2
instance (Ppr term, Ppr (AbstFormula term cs :| cs)) => Ppr (AbstFormula term cs AND) where
ppr (f1 :&: f2) = ppr f1 ++ "&" ++ ppr f2
instance Ppr term => Ppr (AbstFormula term cs LESSTHAN) where
ppr (t1 :<: t2) = ppr t1 ++ "<" ++ ppr t2
instance (Ppr term, Ppr (AbstFormula term cs :| cs)) => Ppr (AbstFormula term cs OR) where
ppr (f1 :|: f2) = ppr f1 ++ "|" ++ ppr f2
data AbstTerm (cs :: [TComponent]) (c :: TComponent) where
Var :: (VAR ∈ cs) => Int -> AbstTerm cs VAR
IConst :: (INT ∈ cs) => Int -> AbstTerm cs INT
(:*:) :: (MUL ∈ cs) => AbstTerm cs :| cs -> AbstTerm cs :| cs -> AbstTerm cs MUL
(:+:) :: (ADD ∈ cs) => AbstTerm cs :| cs -> AbstTerm cs :| cs -> AbstTerm cs ADD
Neg :: (NEG ∈ cs) => AbstTerm cs :| cs -> AbstTerm cs NEG
instance Ppr (AbstTerm cs VAR) where
ppr (Var i) = "X" ++ show i
instance Ppr (AbstTerm cs INT) where
ppr (IConst i) = show i
instance Ppr (AbstTerm cs :| cs) => Ppr (AbstTerm cs ADD) where
ppr (t1 :+: t2) = ppr t1 ++ "+" ++ ppr t2
instance Ppr (AbstTerm cs :| cs) => Ppr (AbstTerm cs MUL) where
ppr (t1 :*: t2) = ppr t1 ++ "*" ++ ppr t2
instance Ppr (AbstTerm cs :| cs) => Ppr (AbstTerm cs NEG) where
ppr (Neg t) = "(-" ++ ppr t ++ ")"
instance GetVariables (AbstTerm cs VAR) where
fv (Var i) = IS.singleton i
instance GetVariables (AbstTerm cs INT) where
fv _ = IS.empty
instance GetVariables (AbstTerm cs :| cs) => GetVariables (AbstTerm cs ADD) where
fv (t1 :+: t2) = fv t1 `IS.union` fv t2
instance GetVariables (AbstTerm cs :| cs) => GetVariables (AbstTerm cs MUL) where
fv (t1 :*: t2) = fv t1 `IS.union` fv t2
instance GetVariables (AbstTerm cs :| cs) => GetVariables (AbstTerm cs NEG) where
fv (Neg t) = fv t
instance GetVariables term => GetVariables (AbstFormula term cs EQUAL) where
fv (t1 :=: t2) = fv t1 `IS.union` fv t2
instance GetVariables term => GetVariables (AbstFormula term cs LESSTHAN) where
fv (t1 :<: t2) = fv t1 `IS.union` fv t2
instance (GetVariables (AbstFormula term cs :| cs)) => GetVariables (AbstFormula term cs AND) where
fv (f1 :&: f2) = fv f1 `IS.union` fv f2
instance (GetVariables (AbstFormula term cs :| cs)) => GetVariables (AbstFormula term cs OR) where
fv (f1 :|: f2) = fv f1 `IS.union` fv f2 | xenophobia/experimental-smt-solver | src/Data/SMT/Abstract/Types.hs | gpl-3.0 | 3,597 | 0 | 9 | 741 | 1,516 | 790 | 726 | 71 | 0 |
module Main where
import System.CPUTime
import System.FilePath
import Data.Maybe
import TagFS
import TagSet hiding (TagSet)
benchmark :: String -> IO a -> IO ()
benchmark name io = do
putStrLn $ "Starting " ++ name ++ "…"
start <- getCPUTime
_ <- io
end <- getCPUTime
let t = fromInteger (end - start) / (1000000000000 :: Double)
putStrLn $ name ++ " done in " ++ show t ++ " seconds."
ts :: TagSet
ts = fromFiles [] (map (\x -> (File [show x], [])) [1..10000 :: Int])
entryInt :: Either Dir Entry -> Int
entryInt (Left _) = 13
entryInt (Right _) = 17
ls :: Route Entry -> FilePath -> IO ()
ls r p = do
-- first get all dir entries
let Just (Just entries) = routeDir r p
-- stat every entry (as ls would do)
let stated = map (\(f,_) -> fromJust $ route r (p </> f)) entries
-- perform evaluation
let res = sum (map entryInt stated)
print res
main :: IO ()
main = do
let r = buildBaseRoute ts
benchmark "ls" $ ls r "/"
| ffwng/tagfs | Benchmark.hs | gpl-3.0 | 943 | 0 | 16 | 208 | 419 | 210 | 209 | 29 | 1 |
module HMail.TH where
import Control.Lens
import Language.Haskell.TH
myMakeLenses :: Name -> DecsQ
myMakeLenses = makeLensesWith
( lensRules & lensField .~ mappingNamer f )
where
f name = [name ++ "l"]
| xaverdh/hmail | HMail/TH.hs | gpl-3.0 | 213 | 0 | 8 | 41 | 65 | 36 | 29 | 7 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.KnowledgeGraphSearch
-- 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)
--
-- Searches the Google Knowledge Graph for entities.
--
-- /See:/ <https://developers.google.com/knowledge-graph/ Knowledge Graph Search API Reference>
module Network.Google.KnowledgeGraphSearch
(
-- * Service Configuration
knowledgeGraphSearchService
-- * API Declaration
, KnowledgeGraphSearchAPI
-- * Resources
-- ** kgsearch.entities.search
, module Network.Google.Resource.Kgsearch.Entities.Search
-- * Types
-- ** SearchResponse
, SearchResponse
, searchResponse
, srContext
, srItemListElement
, srType
-- ** Xgafv
, Xgafv (..)
) where
import Network.Google.KnowledgeGraphSearch.Types
import Network.Google.Prelude
import Network.Google.Resource.Kgsearch.Entities.Search
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Knowledge Graph Search API service.
type KnowledgeGraphSearchAPI = EntitiesSearchResource
| rueshyna/gogol | gogol-kgsearch/gen/Network/Google/KnowledgeGraphSearch.hs | mpl-2.0 | 1,469 | 0 | 5 | 298 | 100 | 78 | 22 | 20 | 0 |
{-# LANGUAGE TypeOperators,DataKinds,TypeFamilies#-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE Rank2Types #-}
module Main where
import OpenCog.AtomSpace
import OpenCog.Test
import System.Exit
import Test.Tasty
import Test.Tasty.HUnit
import Data.Typeable
import GHC.Exts
main :: IO ()
main = defaultMain suite
suite :: TestTree
suite = testGroup "Haskell Test-Suite"
[ testCase "simple Insert Test" $ assert testInsertGet ]
testInsertGet :: IO (Bool)
testInsertGet = do
test <- mapM insertGet testData
return $ and test
insertGet :: Gen AtomT -> IO Bool
insertGet a = do
let prog = genInsert a >> genGet a
res <- runOnNewAtomSpace prog
case res of
Just na -> return (na == a)
Nothing -> error $ "Test Failed for atom: " ++ show a
| rodsol/atomspace | tests/haskell/insertTest/Main.hs | agpl-3.0 | 999 | 0 | 12 | 214 | 227 | 117 | 110 | 32 | 2 |
module Development.Fex.Depend
( EnvVar, mkEnvVar, runEnvVar
, Exe, mkExe, runExe
, File, mkFile, runFile
, Dir, mkDir, runDir
, F.FlagSpec
, mkFlagBool, mkFlagString, mkFlagInt, mkFlagDouble, mkFlagFile, mkFlagDir
, runFlagBool, runFlagString, runFlagInt, runFlagDouble, runFlagFile, runFlagDir
)
where
import System.Directory (findExecutable, doesDirectoryExist, doesFileExist)
import System.Environment (getEnv, lookupEnv)
import System.Process (createProcess, proc, waitForProcess)
import Text.Printf (printf)
import Development.Fex.Experiment
import qualified Development.Fex.Flag as F
-- | An environment variable dependency. Currently, an environment variable
-- can only be read.
--
-- The existence of the environment variable is checked at program startup.
-- If it disappears during execution, a runtime error will be raised.
newtype EnvVar = EnvVar String deriving Show
instance Depend EnvVar where
missing (EnvVar v) = do
v' <- liftIO $ lookupEnv v
case v' of
Nothing -> return $ Just
$ printf "Environment variable '%s' is not defined." v
_ -> return Nothing
-- | Declare a dependency on a particular environment variable.
mkEnvVar :: String -- ^ Name of environment variable.
-> Experiment EnvVar
mkEnvVar = dep . EnvVar
-- | Reads the current value of the environment variable.
-- If it no longer exists, a run time error will occur.
runEnvVar :: EnvVar -> Experiment String
runEnvVar (EnvVar v) = liftIO $ getEnv v
newtype File = File String deriving Show
instance Depend File where
missing (File path) = do
exists <- liftIO $ doesFileExist path
return $ if exists then Nothing else
Just $ printf "Path '%s' does not exist or is not a file.\n" path
mkFile :: String -- ^ Path to file.
-> Experiment File
mkFile = dep . File
runFile :: File -> Experiment String
runFile (File f) = return f
newtype Dir = Dir String deriving Show
instance Depend Dir where
missing (Dir path) = do
exists <- liftIO $ doesDirectoryExist path
return $ if exists then Nothing else
Just $ printf "Path '%s' does not exist or is not a directory.\n" path
mkDir :: String -- ^ Path to directory.
-> Experiment Dir
mkDir = dep . Dir
runDir :: Dir -> Experiment String
runDir (Dir f) = return f
-- | A executable dependency. Currently, only the name is required. The
-- system's PATH variable will be searched to determined if the dependency
-- exists.
newtype Exe = Exe String deriving Show
instance Depend Exe where
missing (Exe cmd) = do
r <- liftIO $ findExecutable cmd
case r of
Nothing -> return $ Just $ printf "Could not find executable '%s'" cmd
_ -> return Nothing
-- | Declare a dependency on a particular executable in the environment.
mkExe :: String -> Experiment Exe
mkExe s = mkEnvVar "PATH" >> dep (Exe s)
-- | Run an executable in the current environment.
--
-- INCOMPLETE.
runExe :: [String] -> Exe -> Experiment ()
runExe args (Exe cmd) = liftIO $ do
(_, _, _, h) <- createProcess (proc cmd args)
waitForProcess h
return ()
-- Flag dependencies
instance Depend F.FlagSpec where
missing spec = flagValue (F.long spec) >>= check
where check :: F.FlagV -> Experiment (Maybe String)
check (F.FFile s) = mkFile s >>= missing
check (F.FDir s) = mkDir s >>= missing
check _ = return Nothing
mkFlag :: String -> String -> F.FlagV -> Experiment F.FlagSpec
mkFlag name help defv = do
let spec = F.FlagSpec { F.short = "", F.long = name
, F.help = help, F.defv = defv }
addFlag spec
dep spec
-- | Declare a dependency on a boolean command line flag. Boolean flags
-- are always satisfied.
mkFlagBool :: String -- ^ The long flag name.
-> String -- ^ The help message.
-> Experiment F.FlagSpec
mkFlagBool name help = mkFlag name help $ F.FBool False
-- | Read the value of a boolean flag.
runFlagBool :: F.FlagSpec -> Experiment Bool
runFlagBool (F.FlagSpec { F.long = k }) = flagValue k >>= \flagv ->
case flagv of F.FBool b -> return b
_ -> error $ printf "BUG: Flag '%s' is not a bool." k
-- | Declare a dependency on a string command line flag. String flags
-- are always satisfied.
mkFlagString :: String -- ^ The long flag name.
-> String -- ^ The default value.
-> String -- ^ The help message.
-> Experiment F.FlagSpec
mkFlagString name def help = mkFlag name help $ F.FString def
-- | Read the value of a string flag.
runFlagString :: F.FlagSpec -> Experiment String
runFlagString (F.FlagSpec { F.long = k }) = flagValue k >>= \flagv ->
case flagv of F.FString s -> return s
_ -> error $ printf "BUG: Flag '%s' is not a string." k
-- | Declare a dependency on an int command line flag. Int flags
-- are always satisfied.
mkFlagInt :: String -- ^ The long flag name.
-> Int -- ^ The default value.
-> String -- ^ The help message.
-> Experiment F.FlagSpec
mkFlagInt name def help = mkFlag name help $ F.FInt def
-- | Read the value of an int flag.
runFlagInt :: F.FlagSpec -> Experiment Int
runFlagInt (F.FlagSpec { F.long = k }) = flagValue k >>= \flagv ->
case flagv of F.FInt s -> return s
_ -> error $ printf "BUG: Flag '%s' is not an int." k
-- | Declare a dependency on a double command line flag. Double flags
-- are always satisfied.
mkFlagDouble :: String -- ^ The long flag name.
-> Double -- ^ The default value.
-> String -- ^ The help message.
-> Experiment F.FlagSpec
mkFlagDouble name def help = mkFlag name help $ F.FDouble def
-- | Read the value of a double flag.
runFlagDouble :: F.FlagSpec -> Experiment Double
runFlagDouble (F.FlagSpec { F.long = k }) = flagValue k >>= \flagv ->
case flagv of F.FDouble s -> return s
_ -> error $ printf "BUG: Flag '%s' is not a double." k
-- | Declare a dependency on a file command line flag. File flags are only
-- satisfied when they refer to files that exist. (To accept a file that
-- does not exist, use a string flag.)
mkFlagFile :: String -- ^ The long flag name.
-> String -- ^ The default file.
-> String -- ^ The help message.
-> Experiment F.FlagSpec
mkFlagFile name def help = mkFlag name help $ F.FFile def
-- | Read the value of a file flag.
runFlagFile :: F.FlagSpec -> Experiment String
runFlagFile (F.FlagSpec { F.long = k }) = flagValue k >>= \flagv ->
case flagv of F.FFile s -> return s
_ -> error $ printf "BUG: Flag '%s' is not a file." k
-- | Declare a dependency on a directory command line flag. Directory flags are
-- only satisfied when they refer to directories that exist. (To accept
-- a directory that does not exist, use a string flag.)
mkFlagDir :: String -- ^ The long flag name.
-> String -- ^ The default directory.
-> String -- ^ The help message.
-> Experiment F.FlagSpec
mkFlagDir name def help = mkFlag name help $ F.FDir def
-- | Read the value of a directory flag.
runFlagDir :: F.FlagSpec -> Experiment String
runFlagDir (F.FlagSpec { F.long = k }) = flagValue k >>= \flagv ->
case flagv of F.FDir s -> return s
_ -> error $ printf "BUG: Flag '%s' is not a directory." k
| BurntSushi/fex | Development/Fex/Depend.hs | unlicense | 7,381 | 0 | 12 | 1,824 | 1,778 | 929 | 849 | 128 | 2 |
module Problem037 where
import Data.List
main =
print $ sum $ take 11 $ filter isTruncatablePrime primes
isTruncatablePrime x = x > 7 && all isPrime (variants x)
variants x = sort $ nub $ map (read :: String -> Int) $ u
where s = show x
u = filter (\x -> length x > 0) $ tails s ++ inits s
isPrime x = isPrime' primes x
where isPrime' _ 1 = False
isPrime' (p:ps) x
| p * p > x = True
| x `rem` p == 0 = False
| otherwise = isPrime' ps x
primes = 2 : 3 : filter (f primes) [5, 7 ..]
where f (p:ps) x = p * p > x || x `rem` p /= 0 && f ps x
| vasily-kartashov/playground | euler/problem-037.hs | apache-2.0 | 609 | 0 | 13 | 202 | 311 | 157 | 154 | 16 | 2 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
module Network.GRPC.LowLevel.GRPC.MetadataMap where
import Data.ByteString (ByteString)
import Data.Function (on)
import GHC.Exts (IsList(..))
import Data.List (sortBy, groupBy)
import Data.Ord (comparing)
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as M
{- | Represents metadata for a given RPC, consisting of key-value pairs (often
referred to as "GRPC custom metadata headers").
Keys are allowed to be repeated, with the 'last' value element (i.e., the
last-presented) usually taken as the value for that key (see 'lookupLast' and
'lookupAll').
Since repeated keys are unlikely in practice, the 'IsList' instance for
'MetadataMap' uses key-value pairs as items, and treats duplicates
appropriately.
>>> lookupAll "k1" (fromList [("k1","x"), ("k2", "z"), ("k1", "y")])
Just ("x" :| ["y"])
>>> lookupLast "k1" (fromList [("k1","x"), ("k2", "z"), ("k1", "y")])
Just "y"
-}
newtype MetadataMap = MetadataMap {unMap :: M.Map ByteString [ByteString]}
deriving Eq
instance Show MetadataMap where
show m = "fromList " ++ show (M.toList (unMap m))
instance Semigroup MetadataMap where
MetadataMap m1 <> MetadataMap m2 =
MetadataMap $ M.unionWith (<>) m1 m2
instance Monoid MetadataMap where
mempty = MetadataMap M.empty
instance IsList MetadataMap where
type Item MetadataMap = (ByteString, ByteString)
fromList = MetadataMap
. M.fromList
. map (\xs -> ((fst . head) xs, map snd xs))
. groupBy ((==) `on` fst)
. sortBy (comparing fst)
toList = concatMap (\(k,vs) -> map (k,) vs)
. map (fmap toList)
. M.toList
. unMap
-- | Obtain all header values for a given header key, in presentation order.
lookupAll :: ByteString -> MetadataMap -> Maybe (NE.NonEmpty ByteString)
lookupAll k (MetadataMap md) = NE.nonEmpty =<< M.lookup k md
-- | Obtain the last-presented header value for a given header key.
lookupLast :: ByteString -> MetadataMap -> Maybe ByteString
lookupLast k = fmap NE.last . lookupAll k
| awakenetworks/gRPC-haskell | core/src/Network/GRPC/LowLevel/GRPC/MetadataMap.hs | apache-2.0 | 2,135 | 0 | 15 | 440 | 454 | 250 | 204 | 34 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : Script.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:34
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Classes.Script (
qScriptEngine, evaluate, newObject, globalObject, newQObject, newQMetaObject, toScriptValue, fromScriptValue, toScriptQObjectValue, fromScriptQObjectValue
, construct, call, setScriptProperty, scriptProperty, qScriptValue_delete
, toScriptInt, toBool, toScriptString
, fromScriptInt, fromBool, fromScriptString
, argument, argumentCount, thisObject, qScriptContext_delete
, qNsfContainer
, registerDsSignal, dsSignal_nll, dsSignal_int, dsSignal_bool, dsSignal_ptr, connectDynamic, connectDynamicSlot
, scriptSlot_nll, scriptSlot_int, scriptSlot_bool, scriptSlot_ptr
)
where
import Qtc.Classes.Base
import Qtc.ClassTypes.Core
import Qtc.Core.Base
import Qtc.ClassTypes.Script
import Data.List
class QqScriptEngine x1 where
qScriptEngine :: x1 -> IO (QScriptEngine ())
instance QqScriptEngine (()) where
qScriptEngine ()
= withQScriptEngineResult $
qtc_QScriptEngine
foreign import ccall "qtc_QScriptEngine" qtc_QScriptEngine :: IO (Ptr (TQScriptEngine ()))
instance QqScriptEngine ((QObject a)) where
qScriptEngine _qobj
= withQScriptEngineResult $
withObjectPtr _qobj $ \cobj_qobj ->
qtc_QScriptEngine1 cobj_qobj
foreign import ccall "qtc_QScriptEngine1" qtc_QScriptEngine1 :: Ptr (TQObject a) -> IO (Ptr (TQScriptEngine ()))
evaluate :: QScriptEngine a -> String -> IO (QScriptValue ())
evaluate _qsce _sdat
= withQScriptValueResult $
withObjectPtr _qsce $ \cobj_qsce ->
withCWString _sdat $ \cstr_sdat ->
qtc_QScriptEngine_evaluate cobj_qsce cstr_sdat
foreign import ccall "qtc_QScriptEngine_evaluate" qtc_QScriptEngine_evaluate :: Ptr (TQScriptEngine a) -> CWString -> IO (Ptr (TQScriptValue ()))
newObject :: QScriptEngine a -> IO (QScriptValue ())
newObject _qsce
= withQScriptValueResult $
withObjectPtr _qsce $ \cobj_qsce ->
qtc_QScriptEngine_newObject cobj_qsce
foreign import ccall "qtc_QScriptEngine_newObject" qtc_QScriptEngine_newObject :: Ptr (TQScriptEngine a) -> IO (Ptr (TQScriptValue ()))
globalObject :: QScriptEngine a -> IO (QScriptValue ())
globalObject _qsce
= withQScriptValueResult $
withObjectPtr _qsce $ \cobj_qsce ->
qtc_QScriptEngine_globalObject cobj_qsce
foreign import ccall "qtc_QScriptEngine_globalObject" qtc_QScriptEngine_globalObject :: Ptr (TQScriptEngine a) -> IO (Ptr (TQScriptValue ()))
newQObject :: QScriptEngine a -> QObject b -> IO (QScriptValue ())
newQObject _qsce _qobj
= withQScriptValueResult $
withObjectPtr _qsce $ \cobj_qsce ->
withObjectPtr _qobj $ \cobj_qobj ->
qtc_QScriptEngine_newQObject cobj_qsce cobj_qobj
foreign import ccall "qtc_QScriptEngine_newQObject" qtc_QScriptEngine_newQObject :: Ptr (TQScriptEngine a) -> Ptr (TQObject b) -> IO (Ptr (TQScriptValue ()))
newQMetaObject :: QScriptEngine a -> QMetaObject b -> IO (QScriptValue ())
newQMetaObject _qsce _qobj
= withQScriptValueResult $
withObjectPtr _qsce $ \cobj_qsce ->
withObjectPtr _qobj $ \cobj_qobj ->
qtc_QScriptEngine_newQMetaObject cobj_qsce cobj_qobj
foreign import ccall "qtc_QScriptEngine_newQMetaObject" qtc_QScriptEngine_newQMetaObject :: Ptr (TQScriptEngine a) -> Ptr (TQMetaObject b) -> IO (Ptr (TQScriptValue ()))
toScriptValue :: String -> QScriptEngine a -> Object b -> IO (QScriptValue ())
toScriptValue _qtyp _qsce _qobj
= withQScriptValueResult $
withCWString _qtyp $ \cstr_qtyp ->
withObjectPtr _qsce $ \cobj_qsce ->
withObjectPtr _qobj $ \cobj_qobj ->
qtc_QScriptEngine_toScriptValue cstr_qtyp cobj_qsce cobj_qobj
foreign import ccall "qtc_QScriptEngine_toScriptValue" qtc_QScriptEngine_toScriptValue :: CWString -> Ptr (TQScriptEngine a) -> Ptr b -> IO (Ptr (TQScriptValue ()))
toScriptQObjectValue :: String -> QScriptEngine a -> QObject b -> IO (QScriptValue ())
toScriptQObjectValue _qtyp _qsce _qobj
= withQScriptValueResult $
withCWString _qtyp $ \cstr_qtyp ->
withObjectPtr _qsce $ \cobj_qsce ->
withObjectPtr _qobj $ \cobj_qobj ->
qtc_QScriptEngine_toScriptQObjectValue cstr_qtyp cobj_qsce cobj_qobj
foreign import ccall "qtc_QScriptEngine_toScriptQObjectValue" qtc_QScriptEngine_toScriptQObjectValue :: CWString -> Ptr (TQScriptEngine a) -> Ptr (TQObject b) -> IO (Ptr (TQScriptValue ()))
fromScriptValue :: String -> QScriptEngine a -> QScriptValue () -> IO (Object ())
fromScriptValue _qtyp _qsce _qscv
= withObjectRefResult $
withCWString _qtyp $ \cstr_qtyp ->
withObjectPtr _qsce $ \cobj_qsce ->
withObjectPtr _qscv $ \cobj_qscv ->
qtc_QScriptEngine_fromScriptValue cstr_qtyp cobj_qsce cobj_qscv
foreign import ccall "qtc_QScriptEngine_fromScriptValue" qtc_QScriptEngine_fromScriptValue :: CWString -> Ptr (TQScriptEngine a) -> Ptr (TQScriptValue b) -> IO (Ptr ())
fromScriptQObjectValue :: String -> QScriptEngine a -> QScriptValue () -> IO (QObject ())
fromScriptQObjectValue _qtyp _qsce _qscv
= withQObjectResult $
withCWString _qtyp $ \cstr_qtyp ->
withObjectPtr _qsce $ \cobj_qsce ->
withObjectPtr _qscv $ \cobj_qscv ->
qtc_QScriptEngine_fromScriptQObjectValue cstr_qtyp cobj_qsce cobj_qscv
foreign import ccall "qtc_QScriptEngine_fromScriptQObjectValue" qtc_QScriptEngine_fromScriptQObjectValue :: CWString -> Ptr (TQScriptEngine a) -> Ptr (TQScriptValue b) -> IO (Ptr (TQObject ()))
construct :: QScriptValue () -> [QScriptValue ()] -> IO (QScriptValue ())
construct _qsvl _qsva
= withQScriptValueResult $
withObjectPtr _qsvl $ \cobj_qsvl ->
withQListObject _qsva $ \cqlistlen_qsva cqlistobj_qsva ->
qtc_QScriptValue_construct cobj_qsvl cqlistlen_qsva cqlistobj_qsva
foreign import ccall "qtc_QScriptValue_construct" qtc_QScriptValue_construct :: Ptr (TQScriptValue ()) -> CInt -> Ptr (Ptr (TQScriptValue ())) -> IO (Ptr (TQScriptValue ()))
call :: QScriptValue () -> QScriptValue () -> [QScriptValue ()] -> IO (QScriptValue ())
call _qsvl _qsvt _qsva
= withQScriptValueResult $
withObjectPtr _qsvl $ \cobj_qsvl ->
withObjectPtr _qsvt $ \cobj_qsvt ->
withQListObject _qsva $ \cqlistlen_qsva cqlistobj_qsva ->
qtc_QScriptValue_call cobj_qsvl cobj_qsvt cqlistlen_qsva cqlistobj_qsva
foreign import ccall "qtc_QScriptValue_call" qtc_QScriptValue_call :: Ptr (TQScriptValue ()) -> Ptr (TQScriptValue ()) -> CInt -> Ptr (Ptr (TQScriptValue ())) -> IO (Ptr (TQScriptValue ()))
setScriptProperty :: QScriptValue () -> String -> QScriptValue () -> IO ()
setScriptProperty _qsvl _sprp _qstv
= withObjectPtr _qsvl $ \cobj_qsvl ->
withCWString _sprp $ \cstr_sprp ->
withObjectPtr _qstv $ \cobj_qstv ->
qtc_QScriptValue_setProperty cobj_qsvl cstr_sprp cobj_qstv
foreign import ccall "qtc_QScriptValue_setProperty" qtc_QScriptValue_setProperty :: Ptr (TQScriptValue ()) -> CWString -> Ptr (TQScriptValue ()) -> IO ()
scriptProperty :: QScriptValue () -> String -> IO (QScriptValue ())
scriptProperty _qsvl _sprp
= withQScriptValueResult $
withObjectPtr _qsvl $ \cobj_qsvl ->
withCWString _sprp $ \cstr_sprp ->
qtc_QScriptValue_property cobj_qsvl cstr_sprp
foreign import ccall "qtc_QScriptValue_property" qtc_QScriptValue_property :: Ptr (TQScriptValue ()) -> CWString -> IO (Ptr (TQScriptValue ()))
qScriptValue_delete :: QScriptValue () -> IO ()
qScriptValue_delete _qsvl
= withObjectPtr _qsvl $ \cobj_qsvl ->
qtc_QScriptValue_delete cobj_qsvl
foreign import ccall "qtc_QScriptValue_delete" qtc_QScriptValue_delete :: Ptr (TQScriptValue ()) -> IO ()
toScriptInt :: QScriptValue () -> IO (Int)
toScriptInt _qsvl
= withIntResult $
withObjectPtr _qsvl $ \cobj_qsvl ->
qtc_QScriptValue_toInt cobj_qsvl
foreign import ccall "qtc_QScriptValue_toInt" qtc_QScriptValue_toInt :: Ptr (TQScriptValue ()) -> IO (CInt)
toBool :: QScriptValue () -> IO (Bool)
toBool _qsvl
= withBoolResult $
withObjectPtr _qsvl $ \cobj_qsvl ->
qtc_QScriptValue_toBool cobj_qsvl
foreign import ccall "qtc_QScriptValue_toBool" qtc_QScriptValue_toBool :: Ptr (TQScriptValue ()) -> IO (CBool)
toScriptString :: QScriptValue () -> IO (String)
toScriptString _qsvl
= withStringResult $
withObjectPtr _qsvl $ \cobj_qsvl ->
qtc_QScriptValue_toString cobj_qsvl
foreign import ccall "qtc_QScriptValue_toString" qtc_QScriptValue_toString :: Ptr (TQScriptValue ()) -> IO (Ptr (TQString ()))
fromScriptInt :: QScriptEngine () -> Int -> IO (QScriptValue ())
fromScriptInt _qsce _aind
= withQScriptValueResult $
withObjectPtr _qsce $ \cobj_qsce ->
qtc_QScriptValue_fromInt cobj_qsce (toCInt _aind)
foreign import ccall "qtc_QScriptValue_fromInt" qtc_QScriptValue_fromInt :: Ptr (TQScriptEngine ()) -> CInt -> IO (Ptr (TQScriptValue ()))
fromBool :: QScriptEngine () -> Bool -> IO (QScriptValue ())
fromBool _qsce _abool
= withQScriptValueResult $
withObjectPtr _qsce $ \cobj_qsce ->
qtc_QScriptValue_fromBool cobj_qsce (toCBool _abool)
foreign import ccall "qtc_QScriptValue_fromBool" qtc_QScriptValue_fromBool :: Ptr (TQScriptEngine ()) -> CBool -> IO (Ptr (TQScriptValue ()))
fromScriptString :: QScriptEngine () -> String -> IO (QScriptValue ())
fromScriptString _qsce _astr
= withQScriptValueResult $
withObjectPtr _qsce $ \cobj_qsce ->
withCWString _astr $ \cstr_a ->
qtc_QScriptValue_fromString cobj_qsce cstr_a
foreign import ccall "qtc_QScriptValue_fromString" qtc_QScriptValue_fromString :: Ptr (TQScriptEngine ()) -> CWString -> IO (Ptr (TQScriptValue ()))
argumentCount :: QScriptContext () -> IO (Int)
argumentCount _qctx
= withIntResult $
withObjectPtr _qctx $ \cobj_qctx ->
qtc_QScriptContext_argumentCount cobj_qctx
foreign import ccall "qtc_QScriptContext_argumentCount" qtc_QScriptContext_argumentCount :: Ptr (TQScriptContext ()) -> IO (CInt)
argument :: QScriptContext () -> Int -> IO (QScriptValue ())
argument _qctx _aind
= withQScriptValueResult $
withObjectPtr _qctx $ \cobj_qctx ->
qtc_QScriptContext_argument cobj_qctx (toCInt _aind)
foreign import ccall "qtc_QScriptContext_argument" qtc_QScriptContext_argument :: Ptr (TQScriptContext ()) -> CInt -> IO (Ptr (TQScriptValue ()))
thisObject :: QScriptContext () -> IO (QScriptValue ())
thisObject _qctx
= withQScriptValueResult $
withObjectPtr _qctx $ \cobj_qctx ->
qtc_QScriptContext_thisObject cobj_qctx
foreign import ccall "qtc_QScriptContext_thisObject" qtc_QScriptContext_thisObject :: Ptr (TQScriptContext ()) -> IO (Ptr (TQScriptValue ()))
qScriptContext_delete :: QScriptContext () -> IO ()
qScriptContext_delete _qctx
= withObjectPtr _qctx $ \cobj_qctx ->
qtc_QScriptContext_delete cobj_qctx
foreign import ccall "qtc_QScriptContext_delete" qtc_QScriptContext_delete :: Ptr (TQScriptContext ()) -> IO ()
class QqNsfContainer x1 where
qNsfContainer :: x1 -> IO (QNsfContainer ())
instance QqNsfContainer ((QScriptContext () -> IO ())) where
qNsfContainer (_qnsf)
= do
funptr <- wrapNsfHandler2 nsfHandlerWrapper2
stptr <- newStablePtr (Wrap _qnsf)
withQNsfContainerResult $
qtc_QNsfContainer (toCFunPtr funptr) (castStablePtrToPtr stptr)
where
nsfHandlerWrapper2 :: Ptr fun -> Ptr () -> Ptr (TQScriptContext ()) -> IO ()
nsfHandlerWrapper2 funptr stptr x0
= do x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _qnsf x0obj
return ()
foreign import ccall "qtc_QNsfContainer" qtc_QNsfContainer :: Ptr (Ptr fun -> Ptr state -> Ptr (TQScriptContext ()) -> IO ()) -> Ptr () -> IO (Ptr (TQNsfContainer ()))
foreign import ccall "wrapper" wrapNsfHandler2 :: (Ptr fun -> Ptr state -> Ptr (TQScriptContext ()) -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr (TQScriptContext ()) -> IO ()))
instance QqNsfContainer (QObject a, (QScriptContext () -> IO ())) where
qNsfContainer (_parent, _qnsf)
= do
funptr <- wrapNsfHandler3 nsfHandlerWrapper3
stptr <- newStablePtr (Wrap _qnsf)
withQNsfContainerResult $
withObjectPtr _parent $ \cobj_parent ->
qtc_QNsfContainer1 cobj_parent (toCFunPtr funptr) (castStablePtrToPtr stptr)
where
nsfHandlerWrapper3 :: Ptr fun -> Ptr () -> Ptr (TQScriptContext ()) -> IO ()
nsfHandlerWrapper3 funptr stptr x0
= do x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _qnsf x0obj
return ()
foreign import ccall "qtc_QNsfContainer1" qtc_QNsfContainer1 :: Ptr (TQObject a) -> Ptr (Ptr fun -> Ptr state -> Ptr (TQScriptContext ()) -> IO ()) -> Ptr () -> IO (Ptr (TQNsfContainer ()))
foreign import ccall "wrapper" wrapNsfHandler3 :: (Ptr fun -> Ptr state -> Ptr (TQScriptContext ()) -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr (TQScriptContext ()) -> IO ()))
instance QqNsfContainer (QObject a, String, (QScriptContext () -> IO ())) where
qNsfContainer (_parent, _cnam, _qnsf)
= do
funptr <- wrapNsfHandler4 nsfHandlerWrapper4
stptr <- newStablePtr (Wrap _qnsf)
withQNsfContainerResult $
withObjectPtr _parent $ \cobj_parent ->
withCWString _cnam $ \cstr_cnam ->
qtc_QNsfContainer2 cobj_parent cstr_cnam (toCFunPtr funptr) (castStablePtrToPtr stptr)
where
nsfHandlerWrapper4 :: Ptr fun -> Ptr () -> Ptr (TQScriptContext ()) -> IO ()
nsfHandlerWrapper4 funptr stptr x0
= do x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _qnsf x0obj
return ()
foreign import ccall "qtc_QNsfContainer2" qtc_QNsfContainer2 :: Ptr (TQObject a) -> CWString -> Ptr (Ptr fun -> Ptr state -> Ptr (TQScriptContext ()) -> IO ()) -> Ptr () -> IO (Ptr (TQNsfContainer ()))
foreign import ccall "wrapper" wrapNsfHandler4 :: (Ptr fun -> Ptr state -> Ptr (TQScriptContext ()) -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr (TQScriptContext ()) -> IO ()))
registerDsSignal :: QObject a -> QScriptEngine () -> QObject b -> String -> IO ()
registerDsSignal _this _eng _dom _sig
| isSuffixOf "()" _sig
= do
let nam = take ((length _sig) - 2) _sig
qNsfContainer (_dom, nam, dsSignal_nll _this _sig)
return ()
| isSuffixOf "(int)" _sig
= do
let nam = take ((length _sig) - 5) _sig
qNsfContainer (_dom, nam, dsSignal_int _this _sig)
return ()
| isSuffixOf "(bool)" _sig
= do
let nam = take ((length _sig) - 6) _sig
qNsfContainer (_dom, nam, dsSignal_bool _this _sig)
return ()
| isPtrSuffix _sig
= do
let nam = take ((length _sig) - 7) _sig
qNsfContainer (_dom, nam, dsSignal_ptr _this _eng _sig)
return ()
| otherwise
= return ()
dsSignal_nll :: QObject a -> String -> QScriptContext () -> IO ()
dsSignal_nll _this _sig _ctx
= emitSignal _this _sig ()
dsSignal_int :: QObject a -> String -> QScriptContext () -> IO ()
dsSignal_int _this _sig _ctx
= emitSignal _this _sig =<< toScriptInt =<< argument _ctx 0
dsSignal_bool :: QObject a -> String -> QScriptContext () -> IO ()
dsSignal_bool _this _sig _ctx
= emitSignal _this _sig =<< toBool =<< argument _ctx 0
dsSignal_ptr :: QObject a -> QScriptEngine () -> String -> QScriptContext () -> IO ()
dsSignal_ptr _this _eng _sig _ctx
= do
ptr <- fromScriptValue (getSigPtrTyp _sig) _eng =<< argument _ctx 0
emitSignal _this _sig ptr
connectDynamic :: QObject a -> QScriptEngine () -> QScriptContext () -> IO ()
connectDynamic _this _eng _ctx
= do
sfv <- argument _ctx 3
stv <- argument _ctx 1
sig_nam <- toScriptString =<< argument _ctx 0
slt_nam <- toScriptString =<< argument _ctx 2
connectDynamicSlot _this _eng sig_nam slt_nam sfv stv
connectDynamicSlot :: QObject a -> QScriptEngine () -> String -> String -> QScriptValue () -> QScriptValue () -> IO ()
connectDynamicSlot _this _eng _sig_nam _slt_nam _sfv _stv
| (isSuffixOf "()" _sig_nam) && (isSuffixOf "()" _slt_nam)
= connectSlot _this _sig_nam _this _slt_nam $ scriptSlot_nll _eng _sfv _stv
| (isSuffixOf "(int)" _sig_nam) && (isSuffixOf "(int)" _slt_nam)
= connectSlot _this _sig_nam _this _slt_nam $ scriptSlot_int _eng _sfv _stv
| (isSuffixOf "(bool)" _sig_nam) && (isSuffixOf "(bool)" _slt_nam)
= connectSlot _this _sig_nam _this _slt_nam $ scriptSlot_bool _eng _sfv _stv
| (isPtrSuffix _sig_nam) && (isPtrSuffix _slt_nam)
= connectSlot _this _sig_nam _this _slt_nam $ scriptSlot_ptr _eng _sfv _stv $ getSigPtrTyp _sig_nam
| otherwise
= return ()
scriptSlot_nll :: QScriptEngine() -> QScriptValue () -> QScriptValue () -> QObject () -> IO ()
scriptSlot_nll _eng _sfv _stv _this
= do
rfv <- call _sfv _stv []
return ()
scriptSlot_int :: QScriptEngine() -> QScriptValue () -> QScriptValue () -> QObject () -> Int -> IO ()
scriptSlot_int _eng _sfv _stv _this _int
= do
dso <- fromScriptInt _eng _int
rfv <- call _sfv _stv [dso]
return ()
scriptSlot_bool :: QScriptEngine() -> QScriptValue () -> QScriptValue () -> QObject () -> Bool -> IO ()
scriptSlot_bool _eng _sfv _stv _this _bool
= do
dso <- fromBool _eng _bool
rfv <- call _sfv _stv [dso]
return ()
scriptSlot_ptr :: QScriptEngine() -> QScriptValue () -> QScriptValue () -> String -> QObject () -> Object a -> IO ()
scriptSlot_ptr _eng _sfv _stv _spt _this _ptr
= do
dso <- toScriptValue _spt _eng _ptr
rfv <- call _sfv _stv [dso]
return ()
isPtrSuffix :: String -> Bool
isPtrSuffix sig
= if (t1 == [])
then False
else
if (((last t1) == ')') && ((last (init t1)) == '*'))
then True
else False
where
t1 = dropWhile ('('/=) sig
getSigPtrTyp :: String -> String
getSigPtrTyp sig
= "<" ++ (init $ tail $ dropWhile ('('/=) sig) ++ ">"
| uduki/hsQt | Qtc/Classes/Script.hs | bsd-2-clause | 18,503 | 0 | 17 | 3,419 | 6,041 | 2,934 | 3,107 | 341 | 3 |
-- TODO
-- Read from config file rather than flag
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
module Main where
import Development.Ecstatic.CallGraph
import Development.Ecstatic.Utils
import Development.Ecstatic.StackUsage
import qualified Development.Ecstatic.Assumptions as A
import Language.C
import Language.C.Analysis
import Text.Printf
import System.Console.ANSI
import qualified Text.PrettyPrint as PP
import System.Environment (getArgs)
import Control.Monad.State
import Control.Applicative((<$>))
import Data.Either (partitionEithers)
import System.Console.GetOpt
declHeader :: VarDecl -> String
declHeader d =
printf "%s (%s:%d):" name file line
where
i = declIdent d
name = identToString i
p = posOfNode . nodeInfo $ i
line = posRow p
file = posFile p
ppDeclCG :: (VarDecl, CallGraph) -> IO ()
ppDeclCG (d, cg1) = do
setSGR [Reset]
putStrLn $ declHeader d
let str1 = ppCallGraph cg1
setSGR [SetColor Foreground Dull Blue]
putStrLn $ str1
setSGR [Reset]
-- Pretty print a parsed AST
reprintAST :: CTranslUnit -> String
reprintAST ast = do
PP.render . prettyUsingInclude $ ast
declString :: VarDecl -> String
declString = identToString . declIdent
filterCallGraphFn :: VarDecl -> Bool
filterCallGraphFn =
(`elem` (map fst A.stack_limits)) . declString
-- TODO overflow return code?
analyzeFiles :: FilePath -> [FilePath] -> IO (Maybe (String, [(VarDecl, CallGraph)]))
analyzeFiles base files = do
mast <- parseASTFiles base files
case mast of
Nothing -> putStrLn "analyzeFile: Invalid file." >> return Nothing
Just (globals, funcs) -> do
-- Calculate graphs, keep only those with stack limits
let pairs = filter (filterCallGraphFn . fst)
$ evalStack $ mapM (go globals) funcs
--mapM_ ppDeclCG pairs
-- Lookup stack limits
let limitPairs =
[ (limit, (name, cg))
| (decl, cg) <- pairs
, let name = declString decl
, let Just limit = lookup name A.stack_limits]
let traces = map (uncurry maxTraces) limitPairs
(bad, good) = partitionEithers traces
lines <- mapM (ppTraceLimit False) good
-- Output string
let
nsString = "num_sats: " ++ show (A.num_dds+1) ++ "\n"
errors = case bad of
[] -> ""
_ ->
"analyzeFiles. error: symbolic values in\n"
++ show bad
overflows = if any isOverflow good then "POSSIBLE OVERFLOW DETECTED" else ""
outputString = unlines $ overflows : errors : nsString : lines
return $ Just (outputString, pairs)
where
go :: GlobalDecls -> FunDef -> State StackMap (VarDecl, CallGraph)
go g (FunDef d s _) | Just params <- funParams d =
(d,) <$> defStackUsage g (s, params)
go _ f = error $ "analyzeFiles. not a FunDef?: " ++ show f
ppTraceLimit :: Bool -> Trace -> IO String
ppTraceLimit put trace = do
let limitString = "(limit " ++ show (trLimit trace) ++ ")"
traceString = ppTrace trace
if put
then do
setSGR [SetColor Foreground Dull Blue]
putStrLn limitString
setSGR [Reset]
putStrLn $ traceString
else return ()
return $ unlines [limitString, traceString]
printParse :: FilePath -> FilePath -> IO ()
printParse base file = do
mast <- parseASTFiles base [file]
case mast of
Nothing -> putStrLn "analyzeFile: Invalid file."
Just (_, funcs) -> do
mapM_ print funcs
doParse base output files = do
pps <- mapM (preprocessFile base) files
writeFile output (concat pps)
return Nothing
doSimpleMode files = error "doSimpleMode. not implemented."
doMain :: FilePath -> FilePath -> [FilePath] -> IO (Maybe (String, [(VarDecl, CallGraph)]))
doMain base output files = do
mpair <- analyzeFiles base files
case mpair of
Just (str, _) -> writeFile output ("<pre>\n" ++ str ++ "</pre>")
Nothing -> return ()
return mpair
data Options = Options
{ optBaseDir :: FilePath
, optOutputFile :: FilePath
, optOnlyParse :: Bool
, optSimpleMode :: Bool
}
defaultOptions = Options
{ optBaseDir = "./piksi_firmware"
, optOutputFile = "ecstatic-output"
, optOnlyParse = False
, optSimpleMode = False
}
type FlagMod = Options -> Options
mainOptions :: [OptDescr FlagMod]
mainOptions =
[ Option "E" ["preprocess"]
(NoArg $ \o -> o { optOnlyParse = True })
"Write preprocessor output and stop."
-- , Option "s" ["simple"]
-- (NoArg $ \o -> o { optSimpleMode = True })
-- "Analyze all functions in a single file."
, Option "o" ["output"]
(ReqArg (\s o -> o { optOutputFile = s }) "FILE")
"Output file."
, Option "b" ["src"]
(ReqArg (\s o -> o { optBaseDir = s }) "DIR")
"Location of piksi_firmware source."
]
main = do
args <- getArgs
case getOpt Permute mainOptions args of
(flags, files, []) ->
let options = foldr ($) defaultOptions flags
base = (optBaseDir options)
output = (optOutputFile options)
in
if optOnlyParse options
then do
doParse base output files
else if optSimpleMode options
then doSimpleMode files
else doMain base output files
(_, _, errs) -> ioError $ userError $ concat errs ++ usageInfo optHeader mainOptions
where
optHeader = "Usage: "
| kovach/ecstatic | Development/Ecstatic.hs | bsd-2-clause | 5,416 | 19 | 18 | 1,384 | 1,592 | 839 | 753 | 139 | 6 |
{-# LANGUAGE CPP, NondecreasingIndentation, TupleSections, RecordWildCards #-}
{-# OPTIONS_GHC -fno-cse #-}
--
-- (c) The University of Glasgow 2002-2006
--
-- -fno-cse is needed for GLOBAL_VAR's to behave properly
-- | The dynamic linker for GHCi.
--
-- This module deals with the top-level issues of dynamic linking,
-- calling the object-code linker and the byte-code linker where
-- necessary.
module Linker ( getHValue, showLinkerState,
linkExpr, linkDecls, unload, withExtendedLinkEnv,
extendLinkEnv, deleteFromLinkEnv,
extendLoadedPkgs,
linkPackages,initDynLinker,linkModule,
linkCmdLineLibs,
-- Saving/restoring globals
PersistentLinkerState, saveLinkerGlobals, restoreLinkerGlobals
) where
#include "HsVersions.h"
import GHCi
import GHCi.RemoteTypes
import LoadIface
import ByteCodeLink
import ByteCodeAsm
import ByteCodeTypes
import TcRnMonad
import Packages
import DriverPhases
import Finder
import HscTypes
import Name
import NameEnv
import NameSet
import UniqFM
import Module
import ListSetOps
import DynFlags
import BasicTypes
import Outputable
import Panic
import Util
import ErrUtils
import SrcLoc
import qualified Maybes
import UniqSet
import FastString
import Platform
import SysTools
-- Standard libraries
import Control.Monad
import Control.Applicative((<|>))
import Data.IORef
import Data.List
import Data.Maybe
import Control.Concurrent.MVar
import System.FilePath
import System.Directory
import Exception
{- **********************************************************************
The Linker's state
********************************************************************* -}
{-
The persistent linker state *must* match the actual state of the
C dynamic linker at all times, so we keep it in a private global variable.
The global IORef used for PersistentLinkerState actually contains another MVar.
The reason for this is that we want to allow another loaded copy of the GHC
library to side-effect the PLS and for those changes to be reflected here.
The PersistentLinkerState maps Names to actual closures (for
interpreted code only), for use during linking.
-}
GLOBAL_VAR_M(v_PersistentLinkerState, newMVar (panic "Dynamic linker not initialised"), MVar PersistentLinkerState)
GLOBAL_VAR(v_InitLinkerDone, False, Bool) -- Set True when dynamic linker is initialised
modifyPLS_ :: (PersistentLinkerState -> IO PersistentLinkerState) -> IO ()
modifyPLS_ f = readIORef v_PersistentLinkerState >>= flip modifyMVar_ f
modifyPLS :: (PersistentLinkerState -> IO (PersistentLinkerState, a)) -> IO a
modifyPLS f = readIORef v_PersistentLinkerState >>= flip modifyMVar f
data PersistentLinkerState
= PersistentLinkerState {
-- Current global mapping from Names to their true values
closure_env :: ClosureEnv,
-- The current global mapping from RdrNames of DataCons to
-- info table addresses.
-- When a new Unlinked is linked into the running image, or an existing
-- module in the image is replaced, the itbl_env must be updated
-- appropriately.
itbl_env :: !ItblEnv,
-- The currently loaded interpreted modules (home package)
bcos_loaded :: ![Linkable],
-- And the currently-loaded compiled modules (home package)
objs_loaded :: ![Linkable],
-- The currently-loaded packages; always object code
-- Held, as usual, in dependency order; though I am not sure if
-- that is really important
pkgs_loaded :: ![UnitId],
-- we need to remember the name of previous temporary DLL/.so
-- libraries so we can link them (see #10322)
temp_sos :: ![(FilePath, String)] }
emptyPLS :: DynFlags -> PersistentLinkerState
emptyPLS _ = PersistentLinkerState {
closure_env = emptyNameEnv,
itbl_env = emptyNameEnv,
pkgs_loaded = init_pkgs,
bcos_loaded = [],
objs_loaded = [],
temp_sos = [] }
-- Packages that don't need loading, because the compiler
-- shares them with the interpreted program.
--
-- The linker's symbol table is populated with RTS symbols using an
-- explicit list. See rts/Linker.c for details.
where init_pkgs = [rtsUnitId]
extendLoadedPkgs :: [UnitId] -> IO ()
extendLoadedPkgs pkgs =
modifyPLS_ $ \s ->
return s{ pkgs_loaded = pkgs ++ pkgs_loaded s }
extendLinkEnv :: [(Name,ForeignHValue)] -> IO ()
extendLinkEnv new_bindings =
modifyPLS_ $ \pls -> do
let ce = closure_env pls
let new_ce = extendClosureEnv ce new_bindings
return pls{ closure_env = new_ce }
deleteFromLinkEnv :: [Name] -> IO ()
deleteFromLinkEnv to_remove =
modifyPLS_ $ \pls -> do
let ce = closure_env pls
let new_ce = delListFromNameEnv ce to_remove
return pls{ closure_env = new_ce }
-- | Get the 'HValue' associated with the given name.
--
-- May cause loading the module that contains the name.
--
-- Throws a 'ProgramError' if loading fails or the name cannot be found.
getHValue :: HscEnv -> Name -> IO ForeignHValue
getHValue hsc_env name = do
initDynLinker hsc_env
pls <- modifyPLS $ \pls -> do
if (isExternalName name) then do
(pls', ok) <- linkDependencies hsc_env pls noSrcSpan
[nameModule name]
if (failed ok) then throwGhcExceptionIO (ProgramError "")
else return (pls', pls')
else
return (pls, pls)
case lookupNameEnv (closure_env pls) name of
Just (_,aa) -> return aa
Nothing
-> ASSERT2(isExternalName name, ppr name)
do let sym_to_find = nameToCLabel name "closure"
m <- lookupClosure hsc_env (unpackFS sym_to_find)
case m of
Just hvref -> mkFinalizedHValue hsc_env hvref
Nothing -> linkFail "ByteCodeLink.lookupCE"
(unpackFS sym_to_find)
linkDependencies :: HscEnv -> PersistentLinkerState
-> SrcSpan -> [Module]
-> IO (PersistentLinkerState, SuccessFlag)
linkDependencies hsc_env pls span needed_mods = do
-- initDynLinker (hsc_dflags hsc_env)
let hpt = hsc_HPT hsc_env
dflags = hsc_dflags hsc_env
-- The interpreter and dynamic linker can only handle object code built
-- the "normal" way, i.e. no non-std ways like profiling or ticky-ticky.
-- So here we check the build tag: if we're building a non-standard way
-- then we need to find & link object files built the "normal" way.
maybe_normal_osuf <- checkNonStdWay dflags span
-- Find what packages and linkables are required
(lnks, pkgs) <- getLinkDeps hsc_env hpt pls
maybe_normal_osuf span needed_mods
-- Link the packages and modules required
pls1 <- linkPackages' hsc_env pkgs pls
linkModules hsc_env pls1 lnks
-- | Temporarily extend the linker state.
withExtendedLinkEnv :: (ExceptionMonad m) =>
[(Name,ForeignHValue)] -> m a -> m a
withExtendedLinkEnv new_env action
= gbracket (liftIO $ extendLinkEnv new_env)
(\_ -> reset_old_env)
(\_ -> action)
where
-- Remember that the linker state might be side-effected
-- during the execution of the IO action, and we don't want to
-- lose those changes (we might have linked a new module or
-- package), so the reset action only removes the names we
-- added earlier.
reset_old_env = liftIO $ do
modifyPLS_ $ \pls ->
let cur = closure_env pls
new = delListFromNameEnv cur (map fst new_env)
in return pls{ closure_env = new }
-- | Display the persistent linker state.
showLinkerState :: DynFlags -> IO ()
showLinkerState dflags
= do pls <- readIORef v_PersistentLinkerState >>= readMVar
log_action dflags dflags SevDump noSrcSpan defaultDumpStyle
(vcat [text "----- Linker state -----",
text "Pkgs:" <+> ppr (pkgs_loaded pls),
text "Objs:" <+> ppr (objs_loaded pls),
text "BCOs:" <+> ppr (bcos_loaded pls)])
{- **********************************************************************
Initialisation
********************************************************************* -}
-- | Initialise the dynamic linker. This entails
--
-- a) Calling the C initialisation procedure,
--
-- b) Loading any packages specified on the command line,
--
-- c) Loading any packages specified on the command line, now held in the
-- @-l@ options in @v_Opt_l@,
--
-- d) Loading any @.o\/.dll@ files specified on the command line, now held
-- in @ldInputs@,
--
-- e) Loading any MacOS frameworks.
--
-- NOTE: This function is idempotent; if called more than once, it does
-- nothing. This is useful in Template Haskell, where we call it before
-- trying to link.
--
initDynLinker :: HscEnv -> IO ()
initDynLinker hsc_env =
modifyPLS_ $ \pls0 -> do
done <- readIORef v_InitLinkerDone
if done then return pls0
else do writeIORef v_InitLinkerDone True
reallyInitDynLinker hsc_env
reallyInitDynLinker :: HscEnv -> IO PersistentLinkerState
reallyInitDynLinker hsc_env = do
-- Initialise the linker state
let dflags = hsc_dflags hsc_env
pls0 = emptyPLS dflags
-- (a) initialise the C dynamic linker
initObjLinker hsc_env
-- (b) Load packages from the command-line (Note [preload packages])
pls <- linkPackages' hsc_env (preloadPackages (pkgState dflags)) pls0
-- steps (c), (d) and (e)
linkCmdLineLibs' hsc_env pls
linkCmdLineLibs :: HscEnv -> IO ()
linkCmdLineLibs hsc_env = do
initDynLinker hsc_env
modifyPLS_ $ \pls -> do
linkCmdLineLibs' hsc_env pls
linkCmdLineLibs' :: HscEnv -> PersistentLinkerState -> IO PersistentLinkerState
linkCmdLineLibs' hsc_env pls =
do
let dflags@(DynFlags { ldInputs = cmdline_ld_inputs
, libraryPaths = lib_paths}) = hsc_dflags hsc_env
-- (c) Link libraries from the command-line
let minus_ls = [ lib | Option ('-':'l':lib) <- cmdline_ld_inputs ]
libspecs <- mapM (locateLib hsc_env False lib_paths) minus_ls
-- (d) Link .o files from the command-line
classified_ld_inputs <- mapM (classifyLdInput dflags)
[ f | FileOption _ f <- cmdline_ld_inputs ]
-- (e) Link any MacOS frameworks
let platform = targetPlatform dflags
let (framework_paths, frameworks) =
if platformUsesFrameworks platform
then (frameworkPaths dflags, cmdlineFrameworks dflags)
else ([],[])
-- Finally do (c),(d),(e)
let cmdline_lib_specs = catMaybes classified_ld_inputs
++ libspecs
++ map Framework frameworks
if null cmdline_lib_specs then return pls
else do
-- Add directories to library search paths
let all_paths = let paths = framework_paths
++ lib_paths
++ [ takeDirectory dll | DLLPath dll <- libspecs ]
in nub $ map normalise paths
pathCache <- mapM (addLibrarySearchPath hsc_env) all_paths
pls1 <- foldM (preloadLib hsc_env lib_paths framework_paths) pls
cmdline_lib_specs
maybePutStr dflags "final link ... "
ok <- resolveObjs hsc_env
-- DLLs are loaded, reset the search paths
mapM_ (removeLibrarySearchPath hsc_env) $ reverse pathCache
if succeeded ok then maybePutStrLn dflags "done"
else throwGhcExceptionIO (ProgramError "linking extra libraries/objects failed")
return pls1
{- Note [preload packages]
Why do we need to preload packages from the command line? This is an
explanation copied from #2437:
I tried to implement the suggestion from #3560, thinking it would be
easy, but there are two reasons we link in packages eagerly when they
are mentioned on the command line:
* So that you can link in extra object files or libraries that
depend on the packages. e.g. ghc -package foo -lbar where bar is a
C library that depends on something in foo. So we could link in
foo eagerly if and only if there are extra C libs or objects to
link in, but....
* Haskell code can depend on a C function exported by a package, and
the normal dependency tracking that TH uses can't know about these
dependencies. The test ghcilink004 relies on this, for example.
I conclude that we need two -package flags: one that says "this is a
package I want to make available", and one that says "this is a
package I want to link in eagerly". Would that be too complicated for
users?
-}
classifyLdInput :: DynFlags -> FilePath -> IO (Maybe LibrarySpec)
classifyLdInput dflags f
| isObjectFilename platform f = return (Just (Object f))
| isDynLibFilename platform f = return (Just (DLLPath f))
| otherwise = do
log_action dflags dflags SevInfo noSrcSpan defaultUserStyle
(text ("Warning: ignoring unrecognised input `" ++ f ++ "'"))
return Nothing
where platform = targetPlatform dflags
preloadLib
:: HscEnv -> [String] -> [String] -> PersistentLinkerState
-> LibrarySpec -> IO PersistentLinkerState
preloadLib hsc_env lib_paths framework_paths pls lib_spec = do
maybePutStr dflags ("Loading object " ++ showLS lib_spec ++ " ... ")
case lib_spec of
Object static_ish -> do
(b, pls1) <- preload_static lib_paths static_ish
maybePutStrLn dflags (if b then "done" else "not found")
return pls1
Archive static_ish -> do
b <- preload_static_archive lib_paths static_ish
maybePutStrLn dflags (if b then "done" else "not found")
return pls
DLL dll_unadorned -> do
maybe_errstr <- loadDLL hsc_env (mkSOName platform dll_unadorned)
case maybe_errstr of
Nothing -> maybePutStrLn dflags "done"
Just mm | platformOS platform /= OSDarwin ->
preloadFailed mm lib_paths lib_spec
Just mm | otherwise -> do
-- As a backup, on Darwin, try to also load a .so file
-- since (apparently) some things install that way - see
-- ticket #8770.
let libfile = ("lib" ++ dll_unadorned) <.> "so"
err2 <- loadDLL hsc_env libfile
case err2 of
Nothing -> maybePutStrLn dflags "done"
Just _ -> preloadFailed mm lib_paths lib_spec
return pls
DLLPath dll_path -> do
do maybe_errstr <- loadDLL hsc_env dll_path
case maybe_errstr of
Nothing -> maybePutStrLn dflags "done"
Just mm -> preloadFailed mm lib_paths lib_spec
return pls
Framework framework ->
if platformUsesFrameworks (targetPlatform dflags)
then do maybe_errstr <- loadFramework hsc_env framework_paths framework
case maybe_errstr of
Nothing -> maybePutStrLn dflags "done"
Just mm -> preloadFailed mm framework_paths lib_spec
return pls
else panic "preloadLib Framework"
where
dflags = hsc_dflags hsc_env
platform = targetPlatform dflags
preloadFailed :: String -> [String] -> LibrarySpec -> IO ()
preloadFailed sys_errmsg paths spec
= do maybePutStr dflags "failed.\n"
throwGhcExceptionIO $
CmdLineError (
"user specified .o/.so/.DLL could not be loaded ("
++ sys_errmsg ++ ")\nWhilst trying to load: "
++ showLS spec ++ "\nAdditional directories searched:"
++ (if null paths then " (none)" else
intercalate "\n" (map (" "++) paths)))
-- Not interested in the paths in the static case.
preload_static _paths name
= do b <- doesFileExist name
if not b then return (False, pls)
else if dynamicGhc
then do pls1 <- dynLoadObjs hsc_env pls [name]
return (True, pls1)
else do loadObj hsc_env name
return (True, pls)
preload_static_archive _paths name
= do b <- doesFileExist name
if not b then return False
else do if dynamicGhc
then panic "Loading archives not supported"
else loadArchive hsc_env name
return True
{- **********************************************************************
Link a byte-code expression
********************************************************************* -}
-- | Link a single expression, /including/ first linking packages and
-- modules that this expression depends on.
--
-- Raises an IO exception ('ProgramError') if it can't find a compiled
-- version of the dependents to link.
--
linkExpr :: HscEnv -> SrcSpan -> UnlinkedBCO -> IO ForeignHValue
linkExpr hsc_env span root_ul_bco
= do {
-- Initialise the linker (if it's not been done already)
; initDynLinker hsc_env
-- Take lock for the actual work.
; modifyPLS $ \pls0 -> do {
-- Link the packages and modules required
; (pls, ok) <- linkDependencies hsc_env pls0 span needed_mods
; if failed ok then
throwGhcExceptionIO (ProgramError "")
else do {
-- Link the expression itself
let ie = itbl_env pls
ce = closure_env pls
-- Link the necessary packages and linkables
; let nobreakarray = error "no break array"
bco_ix = mkNameEnv [(unlinkedBCOName root_ul_bco, 0)]
; resolved <- linkBCO hsc_env ie ce bco_ix nobreakarray root_ul_bco
; [root_hvref] <- iservCmd hsc_env (CreateBCOs [resolved])
; fhv <- mkFinalizedHValue hsc_env root_hvref
; return (pls, fhv)
}}}
where
free_names = nameSetElems (bcoFreeNames root_ul_bco)
needed_mods :: [Module]
needed_mods = [ nameModule n | n <- free_names,
isExternalName n, -- Names from other modules
not (isWiredInName n) -- Exclude wired-in names
] -- (see note below)
-- Exclude wired-in names because we may not have read
-- their interface files, so getLinkDeps will fail
-- All wired-in names are in the base package, which we link
-- by default, so we can safely ignore them here.
dieWith :: DynFlags -> SrcSpan -> MsgDoc -> IO a
dieWith dflags span msg = throwGhcExceptionIO (ProgramError (showSDoc dflags (mkLocMessage SevFatal span msg)))
checkNonStdWay :: DynFlags -> SrcSpan -> IO (Maybe FilePath)
checkNonStdWay dflags srcspan
| gopt Opt_ExternalInterpreter dflags = return Nothing
-- with -fexternal-interpreter we load the .o files, whatever way
-- they were built. If they were built for a non-std way, then
-- we will use the appropriate variant of the iserv binary to load them.
| interpWays == haskellWays = return Nothing
-- Only if we are compiling with the same ways as GHC is built
-- with, can we dynamically load those object files. (see #3604)
| objectSuf dflags == normalObjectSuffix && not (null haskellWays)
= failNonStd dflags srcspan
| otherwise = return (Just (interpTag ++ "o"))
where
haskellWays = filter (not . wayRTSOnly) (ways dflags)
interpTag = case mkBuildTag interpWays of
"" -> ""
tag -> tag ++ "_"
normalObjectSuffix :: String
normalObjectSuffix = phaseInputExt StopLn
failNonStd :: DynFlags -> SrcSpan -> IO (Maybe FilePath)
failNonStd dflags srcspan = dieWith dflags srcspan $
text "Cannot load" <+> compWay <+>
text "objects when GHC is built" <+> ghciWay $$
text "To fix this, either:" $$
text " (1) Use -fexternal-interprter, or" $$
text " (2) Build the program twice: once" <+>
ghciWay <> text ", and then" $$
text " with" <+> compWay <+>
text "using -osuf to set a different object file suffix."
where compWay
| WayDyn `elem` ways dflags = text "-dynamic"
| WayProf `elem` ways dflags = text "-prof"
| otherwise = text "normal"
ghciWay
| dynamicGhc = text "with -dynamic"
| rtsIsProfiled = text "with -prof"
| otherwise = text "the normal way"
getLinkDeps :: HscEnv -> HomePackageTable
-> PersistentLinkerState
-> Maybe FilePath -- replace object suffices?
-> SrcSpan -- for error messages
-> [Module] -- If you need these
-> IO ([Linkable], [UnitId]) -- ... then link these first
-- Fails with an IO exception if it can't find enough files
getLinkDeps hsc_env hpt pls replace_osuf span mods
-- Find all the packages and linkables that a set of modules depends on
= do {
-- 1. Find the dependent home-pkg-modules/packages from each iface
-- (omitting modules from the interactive package, which is already linked)
; (mods_s, pkgs_s) <- follow_deps (filterOut isInteractiveModule mods)
emptyUniqSet emptyUniqSet;
; let {
-- 2. Exclude ones already linked
-- Main reason: avoid findModule calls in get_linkable
mods_needed = mods_s `minusList` linked_mods ;
pkgs_needed = pkgs_s `minusList` pkgs_loaded pls ;
linked_mods = map (moduleName.linkableModule)
(objs_loaded pls ++ bcos_loaded pls) }
-- 3. For each dependent module, find its linkable
-- This will either be in the HPT or (in the case of one-shot
-- compilation) we may need to use maybe_getFileLinkable
; let { osuf = objectSuf dflags }
; lnks_needed <- mapM (get_linkable osuf) mods_needed
; return (lnks_needed, pkgs_needed) }
where
dflags = hsc_dflags hsc_env
this_pkg = thisPackage dflags
-- The ModIface contains the transitive closure of the module dependencies
-- within the current package, *except* for boot modules: if we encounter
-- a boot module, we have to find its real interface and discover the
-- dependencies of that. Hence we need to traverse the dependency
-- tree recursively. See bug #936, testcase ghci/prog007.
follow_deps :: [Module] -- modules to follow
-> UniqSet ModuleName -- accum. module dependencies
-> UniqSet UnitId -- accum. package dependencies
-> IO ([ModuleName], [UnitId]) -- result
follow_deps [] acc_mods acc_pkgs
= return (uniqSetToList acc_mods, uniqSetToList acc_pkgs)
follow_deps (mod:mods) acc_mods acc_pkgs
= do
mb_iface <- initIfaceCheck hsc_env $
loadInterface msg mod (ImportByUser False)
iface <- case mb_iface of
Maybes.Failed err -> throwGhcExceptionIO (ProgramError (showSDoc dflags err))
Maybes.Succeeded iface -> return iface
when (mi_boot iface) $ link_boot_mod_error mod
let
pkg = moduleUnitId mod
deps = mi_deps iface
pkg_deps = dep_pkgs deps
(boot_deps, mod_deps) = partitionWith is_boot (dep_mods deps)
where is_boot (m,True) = Left m
is_boot (m,False) = Right m
boot_deps' = filter (not . (`elementOfUniqSet` acc_mods)) boot_deps
acc_mods' = addListToUniqSet acc_mods (moduleName mod : mod_deps)
acc_pkgs' = addListToUniqSet acc_pkgs $ map fst pkg_deps
--
if pkg /= this_pkg
then follow_deps mods acc_mods (addOneToUniqSet acc_pkgs' pkg)
else follow_deps (map (mkModule this_pkg) boot_deps' ++ mods)
acc_mods' acc_pkgs'
where
msg = text "need to link module" <+> ppr mod <+>
text "due to use of Template Haskell"
link_boot_mod_error mod =
throwGhcExceptionIO (ProgramError (showSDoc dflags (
text "module" <+> ppr mod <+>
text "cannot be linked; it is only available as a boot module")))
no_obj :: Outputable a => a -> IO b
no_obj mod = dieWith dflags span $
text "cannot find object file for module " <>
quotes (ppr mod) $$
while_linking_expr
while_linking_expr = text "while linking an interpreted expression"
-- This one is a build-system bug
get_linkable osuf mod_name -- A home-package module
| Just mod_info <- lookupUFM hpt mod_name
= adjust_linkable (Maybes.expectJust "getLinkDeps" (hm_linkable mod_info))
| otherwise
= do -- It's not in the HPT because we are in one shot mode,
-- so use the Finder to get a ModLocation...
mb_stuff <- findHomeModule hsc_env mod_name
case mb_stuff of
Found loc mod -> found loc mod
_ -> no_obj mod_name
where
found loc mod = do {
-- ...and then find the linkable for it
mb_lnk <- findObjectLinkableMaybe mod loc ;
case mb_lnk of {
Nothing -> no_obj mod ;
Just lnk -> adjust_linkable lnk
}}
adjust_linkable lnk
| Just new_osuf <- replace_osuf = do
new_uls <- mapM (adjust_ul new_osuf)
(linkableUnlinked lnk)
return lnk{ linkableUnlinked=new_uls }
| otherwise =
return lnk
adjust_ul new_osuf (DotO file) = do
MASSERT(osuf `isSuffixOf` file)
let file_base = fromJust (stripExtension osuf file)
new_file = file_base <.> new_osuf
ok <- doesFileExist new_file
if (not ok)
then dieWith dflags span $
text "cannot find object file "
<> quotes (text new_file) $$ while_linking_expr
else return (DotO new_file)
adjust_ul _ (DotA fp) = panic ("adjust_ul DotA " ++ show fp)
adjust_ul _ (DotDLL fp) = panic ("adjust_ul DotDLL " ++ show fp)
adjust_ul _ l@(BCOs {}) = return l
{- **********************************************************************
Loading a Decls statement
********************************************************************* -}
linkDecls :: HscEnv -> SrcSpan -> CompiledByteCode -> IO ()
linkDecls hsc_env span cbc@CompiledByteCode{..} = do
-- Initialise the linker (if it's not been done already)
initDynLinker hsc_env
-- Take lock for the actual work.
modifyPLS $ \pls0 -> do
-- Link the packages and modules required
(pls, ok) <- linkDependencies hsc_env pls0 span needed_mods
if failed ok
then throwGhcExceptionIO (ProgramError "")
else do
-- Link the expression itself
let ie = plusNameEnv (itbl_env pls) bc_itbls
ce = closure_env pls
-- Link the necessary packages and linkables
new_bindings <- linkSomeBCOs hsc_env ie ce [cbc]
nms_fhvs <- makeForeignNamedHValueRefs hsc_env new_bindings
let pls2 = pls { closure_env = extendClosureEnv ce nms_fhvs
, itbl_env = ie }
return (pls2, ())
where
free_names = concatMap (nameSetElems . bcoFreeNames) bc_bcos
needed_mods :: [Module]
needed_mods = [ nameModule n | n <- free_names,
isExternalName n, -- Names from other modules
not (isWiredInName n) -- Exclude wired-in names
] -- (see note below)
-- Exclude wired-in names because we may not have read
-- their interface files, so getLinkDeps will fail
-- All wired-in names are in the base package, which we link
-- by default, so we can safely ignore them here.
{- **********************************************************************
Loading a single module
********************************************************************* -}
linkModule :: HscEnv -> Module -> IO ()
linkModule hsc_env mod = do
initDynLinker hsc_env
modifyPLS_ $ \pls -> do
(pls', ok) <- linkDependencies hsc_env pls noSrcSpan [mod]
if (failed ok) then throwGhcExceptionIO (ProgramError "could not link module")
else return pls'
{- **********************************************************************
Link some linkables
The linkables may consist of a mixture of
byte-code modules and object modules
********************************************************************* -}
linkModules :: HscEnv -> PersistentLinkerState -> [Linkable]
-> IO (PersistentLinkerState, SuccessFlag)
linkModules hsc_env pls linkables
= mask_ $ do -- don't want to be interrupted by ^C in here
let (objs, bcos) = partition isObjectLinkable
(concatMap partitionLinkable linkables)
-- Load objects first; they can't depend on BCOs
(pls1, ok_flag) <- dynLinkObjs hsc_env pls objs
if failed ok_flag then
return (pls1, Failed)
else do
pls2 <- dynLinkBCOs hsc_env pls1 bcos
return (pls2, Succeeded)
-- HACK to support f-x-dynamic in the interpreter; no other purpose
partitionLinkable :: Linkable -> [Linkable]
partitionLinkable li
= let li_uls = linkableUnlinked li
li_uls_obj = filter isObject li_uls
li_uls_bco = filter isInterpretable li_uls
in
case (li_uls_obj, li_uls_bco) of
(_:_, _:_) -> [li {linkableUnlinked=li_uls_obj},
li {linkableUnlinked=li_uls_bco}]
_ -> [li]
findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
findModuleLinkable_maybe lis mod
= case [LM time nm us | LM time nm us <- lis, nm == mod] of
[] -> Nothing
[li] -> Just li
_ -> pprPanic "findModuleLinkable" (ppr mod)
linkableInSet :: Linkable -> [Linkable] -> Bool
linkableInSet l objs_loaded =
case findModuleLinkable_maybe objs_loaded (linkableModule l) of
Nothing -> False
Just m -> linkableTime l == linkableTime m
{- **********************************************************************
The object-code linker
********************************************************************* -}
dynLinkObjs :: HscEnv -> PersistentLinkerState -> [Linkable]
-> IO (PersistentLinkerState, SuccessFlag)
dynLinkObjs hsc_env pls objs = do
-- Load the object files and link them
let (objs_loaded', new_objs) = rmDupLinkables (objs_loaded pls) objs
pls1 = pls { objs_loaded = objs_loaded' }
unlinkeds = concatMap linkableUnlinked new_objs
wanted_objs = map nameOfObject unlinkeds
if interpreterDynamic (hsc_dflags hsc_env)
then do pls2 <- dynLoadObjs hsc_env pls1 wanted_objs
return (pls2, Succeeded)
else do mapM_ (loadObj hsc_env) wanted_objs
-- Link them all together
ok <- resolveObjs hsc_env
-- If resolving failed, unload all our
-- object modules and carry on
if succeeded ok then do
return (pls1, Succeeded)
else do
pls2 <- unload_wkr hsc_env [] pls1
return (pls2, Failed)
dynLoadObjs :: HscEnv -> PersistentLinkerState -> [FilePath]
-> IO PersistentLinkerState
dynLoadObjs _ pls [] = return pls
dynLoadObjs hsc_env pls objs = do
let dflags = hsc_dflags hsc_env
let platform = targetPlatform dflags
let minus_ls = [ lib | Option ('-':'l':lib) <- ldInputs dflags ]
let minus_big_ls = [ lib | Option ('-':'L':lib) <- ldInputs dflags ]
(soFile, libPath , libName) <- newTempLibName dflags (soExt platform)
let
dflags2 = dflags {
-- We don't want the original ldInputs in
-- (they're already linked in), but we do want
-- to link against previous dynLoadObjs
-- libraries if there were any, so that the linker
-- can resolve dependencies when it loads this
-- library.
ldInputs =
concatMap
(\(lp, l) ->
[ Option ("-L" ++ lp)
, Option ("-Wl,-rpath")
, Option ("-Wl," ++ lp)
, Option ("-l" ++ l)
])
(temp_sos pls)
++ concatMap
(\lp ->
[ Option ("-L" ++ lp)
, Option ("-Wl,-rpath")
, Option ("-Wl," ++ lp)
])
minus_big_ls
++ map (\l -> Option ("-l" ++ l)) minus_ls,
-- Add -l options and -L options from dflags.
--
-- When running TH for a non-dynamic way, we still
-- need to make -l flags to link against the dynamic
-- libraries, so we need to add WayDyn to ways.
--
-- Even if we're e.g. profiling, we still want
-- the vanilla dynamic libraries, so we set the
-- ways / build tag to be just WayDyn.
ways = [WayDyn],
buildTag = mkBuildTag [WayDyn],
outputFile = Just soFile
}
-- link all "loaded packages" so symbols in those can be resolved
-- Note: We are loading packages with local scope, so to see the
-- symbols in this link we must link all loaded packages again.
linkDynLib dflags2 objs (pkgs_loaded pls)
consIORef (filesToNotIntermediateClean dflags) soFile
m <- loadDLL hsc_env soFile
case m of
Nothing -> return pls { temp_sos = (libPath, libName) : temp_sos pls }
Just err -> panic ("Loading temp shared object failed: " ++ err)
rmDupLinkables :: [Linkable] -- Already loaded
-> [Linkable] -- New linkables
-> ([Linkable], -- New loaded set (including new ones)
[Linkable]) -- New linkables (excluding dups)
rmDupLinkables already ls
= go already [] ls
where
go already extras [] = (already, extras)
go already extras (l:ls)
| linkableInSet l already = go already extras ls
| otherwise = go (l:already) (l:extras) ls
{- **********************************************************************
The byte-code linker
********************************************************************* -}
dynLinkBCOs :: HscEnv -> PersistentLinkerState -> [Linkable]
-> IO PersistentLinkerState
dynLinkBCOs hsc_env pls bcos = do
let (bcos_loaded', new_bcos) = rmDupLinkables (bcos_loaded pls) bcos
pls1 = pls { bcos_loaded = bcos_loaded' }
unlinkeds :: [Unlinked]
unlinkeds = concatMap linkableUnlinked new_bcos
cbcs :: [CompiledByteCode]
cbcs = map byteCodeOfObject unlinkeds
ies = map bc_itbls cbcs
gce = closure_env pls
final_ie = foldr plusNameEnv (itbl_env pls) ies
names_and_refs <- linkSomeBCOs hsc_env final_ie gce cbcs
-- We only want to add the external ones to the ClosureEnv
let (to_add, to_drop) = partition (isExternalName.fst) names_and_refs
-- Immediately release any HValueRefs we're not going to add
freeHValueRefs hsc_env (map snd to_drop)
-- Wrap finalizers on the ones we want to keep
new_binds <- makeForeignNamedHValueRefs hsc_env to_add
return pls1 { closure_env = extendClosureEnv gce new_binds,
itbl_env = final_ie }
-- Link a bunch of BCOs and return references to their values
linkSomeBCOs :: HscEnv
-> ItblEnv
-> ClosureEnv
-> [CompiledByteCode]
-> IO [(Name,HValueRef)]
-- The returned HValueRefs are associated 1-1 with
-- the incoming unlinked BCOs. Each gives the
-- value of the corresponding unlinked BCO
linkSomeBCOs hsc_env ie ce mods = foldr fun do_link mods []
where
fun CompiledByteCode{..} inner accum =
case bc_breaks of
Nothing -> inner ((panic "linkSomeBCOs: no break array", bc_bcos) : accum)
Just mb -> withForeignRef (modBreaks_flags mb) $ \breakarray ->
inner ((breakarray, bc_bcos) : accum)
do_link [] = return []
do_link mods = do
let flat = [ (breakarray, bco) | (breakarray, bcos) <- mods, bco <- bcos ]
names = map (unlinkedBCOName . snd) flat
bco_ix = mkNameEnv (zip names [0..])
resolved <- sequence [ linkBCO hsc_env ie ce bco_ix breakarray bco
| (breakarray, bco) <- flat ]
hvrefs <- iservCmd hsc_env (CreateBCOs resolved)
return (zip names hvrefs)
-- | Useful to apply to the result of 'linkSomeBCOs'
makeForeignNamedHValueRefs
:: HscEnv -> [(Name,HValueRef)] -> IO [(Name,ForeignHValue)]
makeForeignNamedHValueRefs hsc_env bindings =
mapM (\(n, hvref) -> (n,) <$> mkFinalizedHValue hsc_env hvref) bindings
{- **********************************************************************
Unload some object modules
********************************************************************* -}
-- ---------------------------------------------------------------------------
-- | Unloading old objects ready for a new compilation sweep.
--
-- The compilation manager provides us with a list of linkables that it
-- considers \"stable\", i.e. won't be recompiled this time around. For
-- each of the modules current linked in memory,
--
-- * if the linkable is stable (and it's the same one -- the user may have
-- recompiled the module on the side), we keep it,
--
-- * otherwise, we unload it.
--
-- * we also implicitly unload all temporary bindings at this point.
--
unload :: HscEnv
-> [Linkable] -- ^ The linkables to *keep*.
-> IO ()
unload hsc_env linkables
= mask_ $ do -- mask, so we're safe from Ctrl-C in here
-- Initialise the linker (if it's not been done already)
initDynLinker hsc_env
new_pls
<- modifyPLS $ \pls -> do
pls1 <- unload_wkr hsc_env linkables pls
return (pls1, pls1)
let dflags = hsc_dflags hsc_env
debugTraceMsg dflags 3 $
text "unload: retaining objs" <+> ppr (objs_loaded new_pls)
debugTraceMsg dflags 3 $
text "unload: retaining bcos" <+> ppr (bcos_loaded new_pls)
return ()
unload_wkr :: HscEnv
-> [Linkable] -- stable linkables
-> PersistentLinkerState
-> IO PersistentLinkerState
-- Does the core unload business
-- (the wrapper blocks exceptions and deals with the PLS get and put)
unload_wkr hsc_env keep_linkables pls = do
let (objs_to_keep, bcos_to_keep) = partition isObjectLinkable keep_linkables
discard keep l = not (linkableInSet l keep)
(objs_to_unload, remaining_objs_loaded) =
partition (discard objs_to_keep) (objs_loaded pls)
(bcos_to_unload, remaining_bcos_loaded) =
partition (discard bcos_to_keep) (bcos_loaded pls)
mapM_ unloadObjs objs_to_unload
mapM_ unloadObjs bcos_to_unload
-- If we unloaded any object files at all, we need to purge the cache
-- of lookupSymbol results.
when (not (null (objs_to_unload ++
filter (not . null . linkableObjs) bcos_to_unload))) $
purgeLookupSymbolCache hsc_env
let bcos_retained = map linkableModule remaining_bcos_loaded
-- Note that we want to remove all *local*
-- (i.e. non-isExternal) names too (these are the
-- temporary bindings from the command line).
keep_name (n,_) = isExternalName n &&
nameModule n `elem` bcos_retained
itbl_env' = filterNameEnv keep_name (itbl_env pls)
closure_env' = filterNameEnv keep_name (closure_env pls)
new_pls = pls { itbl_env = itbl_env',
closure_env = closure_env',
bcos_loaded = remaining_bcos_loaded,
objs_loaded = remaining_objs_loaded }
return new_pls
where
unloadObjs :: Linkable -> IO ()
unloadObjs lnk
| dynamicGhc = return ()
-- We don't do any cleanup when linking objects with the
-- dynamic linker. Doing so introduces extra complexity for
-- not much benefit.
| otherwise
= mapM_ (unloadObj hsc_env) [f | DotO f <- linkableUnlinked lnk]
-- The components of a BCO linkable may contain
-- dot-o files. Which is very confusing.
--
-- But the BCO parts can be unlinked just by
-- letting go of them (plus of course depopulating
-- the symbol table which is done in the main body)
{- **********************************************************************
Loading packages
********************************************************************* -}
data LibrarySpec
= Object FilePath -- Full path name of a .o file, including trailing .o
-- For dynamic objects only, try to find the object
-- file in all the directories specified in
-- v_Library_paths before giving up.
| Archive FilePath -- Full path name of a .a file, including trailing .a
| DLL String -- "Unadorned" name of a .DLL/.so
-- e.g. On unix "qt" denotes "libqt.so"
-- On Windows "burble" denotes "burble.DLL" or "libburble.dll"
-- loadDLL is platform-specific and adds the lib/.so/.DLL
-- suffixes platform-dependently
| DLLPath FilePath -- Absolute or relative pathname to a dynamic library
-- (ends with .dll or .so).
| Framework String -- Only used for darwin, but does no harm
-- If this package is already part of the GHCi binary, we'll already
-- have the right DLLs for this package loaded, so don't try to
-- load them again.
--
-- But on Win32 we must load them 'again'; doing so is a harmless no-op
-- as far as the loader is concerned, but it does initialise the list
-- of DLL handles that rts/Linker.c maintains, and that in turn is
-- used by lookupSymbol. So we must call addDLL for each library
-- just to get the DLL handle into the list.
partOfGHCi :: [PackageName]
partOfGHCi
| isWindowsHost || isDarwinHost = []
| otherwise = map (PackageName . mkFastString)
["base", "template-haskell", "editline"]
showLS :: LibrarySpec -> String
showLS (Object nm) = "(static) " ++ nm
showLS (Archive nm) = "(static archive) " ++ nm
showLS (DLL nm) = "(dynamic) " ++ nm
showLS (DLLPath nm) = "(dynamic) " ++ nm
showLS (Framework nm) = "(framework) " ++ nm
-- | Link exactly the specified packages, and their dependents (unless of
-- course they are already linked). The dependents are linked
-- automatically, and it doesn't matter what order you specify the input
-- packages.
--
linkPackages :: HscEnv -> [UnitId] -> IO ()
-- NOTE: in fact, since each module tracks all the packages it depends on,
-- we don't really need to use the package-config dependencies.
--
-- However we do need the package-config stuff (to find aux libs etc),
-- and following them lets us load libraries in the right order, which
-- perhaps makes the error message a bit more localised if we get a link
-- failure. So the dependency walking code is still here.
linkPackages hsc_env new_pkgs = do
-- It's probably not safe to try to load packages concurrently, so we take
-- a lock.
initDynLinker hsc_env
modifyPLS_ $ \pls -> do
linkPackages' hsc_env new_pkgs pls
linkPackages' :: HscEnv -> [UnitId] -> PersistentLinkerState
-> IO PersistentLinkerState
linkPackages' hsc_env new_pks pls = do
pkgs' <- link (pkgs_loaded pls) new_pks
return $! pls { pkgs_loaded = pkgs' }
where
dflags = hsc_dflags hsc_env
link :: [UnitId] -> [UnitId] -> IO [UnitId]
link pkgs new_pkgs =
foldM link_one pkgs new_pkgs
link_one pkgs new_pkg
| new_pkg `elem` pkgs -- Already linked
= return pkgs
| Just pkg_cfg <- lookupPackage dflags new_pkg
= do { -- Link dependents first
pkgs' <- link pkgs (depends pkg_cfg)
-- Now link the package itself
; linkPackage hsc_env pkg_cfg
; return (new_pkg : pkgs') }
| otherwise
= throwGhcExceptionIO (CmdLineError ("unknown package: " ++ unitIdString new_pkg))
linkPackage :: HscEnv -> PackageConfig -> IO ()
linkPackage hsc_env pkg
= do
let dflags = hsc_dflags hsc_env
platform = targetPlatform dflags
dirs = Packages.libraryDirs pkg
let hs_libs = Packages.hsLibraries pkg
-- The FFI GHCi import lib isn't needed as
-- compiler/ghci/Linker.hs + rts/Linker.c link the
-- interpreted references to FFI to the compiled FFI.
-- We therefore filter it out so that we don't get
-- duplicate symbol errors.
hs_libs' = filter ("HSffi" /=) hs_libs
-- Because of slight differences between the GHC dynamic linker and
-- the native system linker some packages have to link with a
-- different list of libraries when using GHCi. Examples include: libs
-- that are actually gnu ld scripts, and the possibility that the .a
-- libs do not exactly match the .so/.dll equivalents. So if the
-- package file provides an "extra-ghci-libraries" field then we use
-- that instead of the "extra-libraries" field.
extra_libs =
(if null (Packages.extraGHCiLibraries pkg)
then Packages.extraLibraries pkg
else Packages.extraGHCiLibraries pkg)
++ [ lib | '-':'l':lib <- Packages.ldOptions pkg ]
hs_classifieds <- mapM (locateLib hsc_env True dirs) hs_libs'
extra_classifieds <- mapM (locateLib hsc_env False dirs) extra_libs
let classifieds = hs_classifieds ++ extra_classifieds
-- Complication: all the .so's must be loaded before any of the .o's.
let known_dlls = [ dll | DLLPath dll <- classifieds ]
dlls = [ dll | DLL dll <- classifieds ]
objs = [ obj | Object obj <- classifieds ]
archs = [ arch | Archive arch <- classifieds ]
-- Add directories to library search paths
let dll_paths = map takeDirectory known_dlls
all_paths = nub $ map normalise $ dll_paths ++ dirs
pathCache <- mapM (addLibrarySearchPath hsc_env) all_paths
maybePutStr dflags
("Loading package " ++ sourcePackageIdString pkg ++ " ... ")
-- See comments with partOfGHCi
when (packageName pkg `notElem` partOfGHCi) $ do
loadFrameworks hsc_env platform pkg
mapM_ (load_dyn hsc_env)
(known_dlls ++ map (mkSOName platform) dlls)
-- DLLs are loaded, reset the search paths
mapM_ (removeLibrarySearchPath hsc_env) $ reverse pathCache
-- After loading all the DLLs, we can load the static objects.
-- Ordering isn't important here, because we do one final link
-- step to resolve everything.
mapM_ (loadObj hsc_env) objs
mapM_ (loadArchive hsc_env) archs
maybePutStr dflags "linking ... "
ok <- resolveObjs hsc_env
if succeeded ok
then maybePutStrLn dflags "done."
else let errmsg = "unable to load package `"
++ sourcePackageIdString pkg ++ "'"
in throwGhcExceptionIO (InstallationError errmsg)
-- we have already searched the filesystem; the strings passed to load_dyn
-- can be passed directly to loadDLL. They are either fully-qualified
-- ("/usr/lib/libfoo.so"), or unqualified ("libfoo.so"). In the latter case,
-- loadDLL is going to search the system paths to find the library.
--
load_dyn :: HscEnv -> FilePath -> IO ()
load_dyn hsc_env dll = do
r <- loadDLL hsc_env dll
case r of
Nothing -> return ()
Just err -> throwGhcExceptionIO (CmdLineError ("can't load .so/.DLL for: "
++ dll ++ " (" ++ err ++ ")" ))
loadFrameworks :: HscEnv -> Platform -> PackageConfig -> IO ()
loadFrameworks hsc_env platform pkg
= when (platformUsesFrameworks platform) $ mapM_ load frameworks
where
fw_dirs = Packages.frameworkDirs pkg
frameworks = Packages.frameworks pkg
load fw = do r <- loadFramework hsc_env fw_dirs fw
case r of
Nothing -> return ()
Just err -> throwGhcExceptionIO (CmdLineError ("can't load framework: "
++ fw ++ " (" ++ err ++ ")" ))
-- Try to find an object file for a given library in the given paths.
-- If it isn't present, we assume that addDLL in the RTS can find it,
-- which generally means that it should be a dynamic library in the
-- standard system search path.
locateLib :: HscEnv -> Bool -> [FilePath] -> String -> IO LibrarySpec
locateLib hsc_env is_hs dirs lib
| not is_hs
-- For non-Haskell libraries (e.g. gmp, iconv):
-- first look in library-dirs for a dynamic library (libfoo.so)
-- then look in library-dirs for a static library (libfoo.a)
-- first look in library-dirs and inplace GCC for a dynamic library (libfoo.so)
-- then check for system dynamic libraries (e.g. kernel32.dll on windows)
-- then try "gcc --print-file-name" to search gcc's search path
-- then look in library-dirs and inplace GCC for a static library (libfoo.a)
-- for a dynamic library (#5289)
-- otherwise, assume loadDLL can find it
--
= findDll `orElse`
findSysDll `orElse`
tryGcc `orElse`
findArchive `orElse`
assumeDll
| loading_dynamic_hs_libs -- search for .so libraries first.
= findHSDll `orElse`
findDynObject `orElse`
assumeDll
| loading_profiled_hs_libs -- only a libHSfoo_p.a archive will do.
= findArchive `orElse`
assumeDll
| otherwise
-- HSfoo.o is the best, but only works for the normal way
-- libHSfoo.a is the backup option.
= findObject `orElse`
findArchive `orElse`
assumeDll
where
dflags = hsc_dflags hsc_env
obj_file = lib <.> "o"
dyn_obj_file = lib <.> "dyn_o"
arch_file = "lib" ++ lib ++ lib_tag <.> "a"
lib_tag = if is_hs && loading_profiled_hs_libs then "_p" else ""
loading_profiled_hs_libs = interpreterProfiled dflags
loading_dynamic_hs_libs = interpreterDynamic dflags
hs_dyn_lib_name = lib ++ '-':programName dflags ++ projectVersion dflags
hs_dyn_lib_file = mkHsSOName platform hs_dyn_lib_name
so_name = mkSOName platform lib
lib_so_name = "lib" ++ so_name
dyn_lib_file = case (arch, os) of
(ArchX86_64, OSSolaris2) -> "64" </> so_name
_ -> so_name
findObject = liftM (fmap Object) $ findFile dirs obj_file
findDynObject = liftM (fmap Object) $ findFile dirs dyn_obj_file
findArchive = let local = liftM (fmap Archive) $ findFile dirs arch_file
linked = liftM (fmap Archive) $ searchForLibUsingGcc dflags arch_file dirs
in liftM2 (<|>) local linked
findHSDll = liftM (fmap DLLPath) $ findFile dirs hs_dyn_lib_file
findDll = liftM (fmap DLLPath) $ findFile dirs dyn_lib_file
findSysDll = fmap (fmap $ DLL . takeFileName) $ findSystemLibrary hsc_env so_name
tryGcc = let short = liftM (fmap DLLPath) $ searchForLibUsingGcc dflags so_name dirs
full = liftM (fmap DLLPath) $ searchForLibUsingGcc dflags lib_so_name dirs
in liftM2 (<|>) short full
assumeDll = return (DLL lib)
infixr `orElse`
f `orElse` g = f >>= maybe g return
platform = targetPlatform dflags
arch = platformArch platform
os = platformOS platform
searchForLibUsingGcc :: DynFlags -> String -> [FilePath] -> IO (Maybe FilePath)
searchForLibUsingGcc dflags so dirs = do
-- GCC does not seem to extend the library search path (using -L) when using
-- --print-file-name. So instead pass it a new base location.
str <- askCc dflags (map (FileOption "-B") dirs
++ [Option "--print-file-name", Option so])
let file = case lines str of
[] -> ""
l:_ -> l
if (file == so)
then return Nothing
else return (Just file)
-- ----------------------------------------------------------------------------
-- Loading a dynamic library (dlopen()-ish on Unix, LoadLibrary-ish on Win32)
-- Darwin / MacOS X only: load a framework
-- a framework is a dynamic library packaged inside a directory of the same
-- name. They are searched for in different paths than normal libraries.
loadFramework :: HscEnv -> [FilePath] -> FilePath -> IO (Maybe String)
loadFramework hsc_env extraPaths rootname
= do { either_dir <- tryIO getHomeDirectory
; let homeFrameworkPath = case either_dir of
Left _ -> []
Right dir -> [dir </> "Library/Frameworks"]
ps = extraPaths ++ homeFrameworkPath ++ defaultFrameworkPaths
; mb_fwk <- findFile ps fwk_file
; case mb_fwk of
Just fwk_path -> loadDLL hsc_env fwk_path
Nothing -> return (Just "not found") }
-- Tried all our known library paths, but dlopen()
-- has no built-in paths for frameworks: give up
where
fwk_file = rootname <.> "framework" </> rootname
-- sorry for the hardcoded paths, I hope they won't change anytime soon:
defaultFrameworkPaths = ["/Library/Frameworks", "/System/Library/Frameworks"]
{- **********************************************************************
Helper functions
********************************************************************* -}
maybePutStr :: DynFlags -> String -> IO ()
maybePutStr dflags s
= when (verbosity dflags > 1) $
do let act = log_action dflags
act dflags SevInteractive noSrcSpan defaultUserStyle (text s)
maybePutStrLn :: DynFlags -> String -> IO ()
maybePutStrLn dflags s = maybePutStr dflags (s ++ "\n")
{- **********************************************************************
Tunneling global variables into new instance of GHC library
********************************************************************* -}
saveLinkerGlobals :: IO (MVar PersistentLinkerState, Bool)
saveLinkerGlobals = liftM2 (,) (readIORef v_PersistentLinkerState) (readIORef v_InitLinkerDone)
restoreLinkerGlobals :: (MVar PersistentLinkerState, Bool) -> IO ()
restoreLinkerGlobals (pls, ild) = do
writeIORef v_PersistentLinkerState pls
writeIORef v_InitLinkerDone ild
| gridaphobe/ghc | compiler/ghci/Linker.hs | bsd-3-clause | 56,784 | 185 | 22 | 17,199 | 10,205 | 5,326 | 4,879 | -1 | -1 |
module Parser where
import qualified Text.ParserCombinators.Parsec as P
import HTTP
import System.Locale (defaultTimeLocale)
import Data.Time (UTCTime, parseTime, formatTime, getCurrentTime)
import Numeric (readHex)
char :: P.Parser Char
char = P.anyChar
upalpha = P.upper
loalpha = P.lower
alpha = upalpha <!> loalpha
digit = P.digit
cr = P.char '\r'
lf = P.char '\n'
sp = P.space
ht = P.tab
quote = P.char '*'
crlf :: Parser ()
crlf = do cr
lf
ctlString = "\0\SOH\STX\ETX\EOT\ENQ\ACK\BEL\BS\HT\LF\VT\FF\CR\SO\SI\DLE\DC1\DC2\DC3\DC4\NAK\SYN\ETB\CAN\EM\SUB\ESC\FS\GS\RS\US\DEL"
ctl = P.oneOf ctlString
lws :: Parser Char -- replace linear white space with a single space
lws = do
P.skipMany crlf
P.skipMany1 (sp <|> ht)
return ' '
text = P.many (P.noneOf ctlString)
hex = P.hexdigit
separators = P.oneOf "()<>@,;:\\\"/[]?={} \t"
token = P.many1 (P.noneOf ctlString <|> separators)
comment = do
P.char '('
res <- P.many (ctext <|> quoted_pair <|> comment)
P.char ')'
return res
ctext = P.many (P.noneOf "()")
quoted_string = do
P.char '"'
res <- P.many (qdtext <|> quoted_pair)
P.char '"'
return res
qdtext = P.many (P.noneOf "\"")
quoted_pair = do
P.char '\\'
c <- char
return c
-- TIME PARSER
rfc1123FormatString = "%a, %d %b %Y %T GMT"
rfc850FormatString = "%A, %d-%b-%y %T GMT"
asctimeFormatString = "%a %b %d %T %Y"
parseRFC1123 :: String -> Maybe UTCTime
parseRFC1123 = parseTime defaultTimeLocale rfc1123FormatString
parseRFC850 = parseTime defaultTimeLocale rfc850FormatString
parseASCTime = parseTime defaultTimeLocale asctimeFormatString
-- we MUST only generate RFC1123 format time.
buildRFC1123 :: UTCTime -> String
buildRFC1123 = formatTime defaultTimeLocale rfc1123FormatString
-- charactor set
charset = token
content_coding = token
transfer_coding = P.string "chunked" <|> transfer_extension
transfer_extension = do
t <- token
p <- P.many parameter
return (t,p)
parameter = do
att <- token
P.char '='
val <- token <|> quoted_string
return (att,val)
chunked_body = do
chk <- P.many chunk
lch <- last_chunk
trl <- trailer
crlf
return $ ChunkedBody {chunk=chk, lastChunk=lch, trailer=trl}
chunk = do
size <- chunk_size
chkExt <- P.many chunk_extension
crlf
dat <- chunk_data
crlf
return $ Chunk {chunkSize=size, chunkExtension=chkExt, chunkData=dat}
chunk_size :: Parser Int
chunk_size =do
h<- P.many1 hex
let res = readHex h
return $ fst $ head res
last_chunk = do
zero <- P.many1 (P.char '0')
ext <- P.many chunk_extension
crlf
return ext --------------- undefined here
chunk_extension = do
P.char ';'
name <- token
P.option (name,"") (do
P.char '='
val <- token <|> quoted_string
return (name,val))
chunk_data size = P.count size char
trailer = P.many entity_header
media_type = do
tp <- token
P.char '/'
subtp <- token
para <- P.many parameter
return $ MediaType{mType = tp, subtype = subtp, parameter = para}
product = do
p <- token
P.option (Product {name = p, version = ""} (do
P.char '/'
ver <- token
return $ Product {name = p, version = ver}
)
| manyoo/Morakot | Parser.hs | bsd-3-clause | 3,404 | 1 | 13 | 882 | 1,078 | 540 | 538 | -1 | -1 |
-- NaturalNumbers.hs
-- | A module implementating the Natural Numbers within the Haskell
-- type system using the Peano-Dedekind Axioms for arithmetic.
module NaturalNumber where
-- | Data structure representing the natural number 0,
-- or a successor of a natural number.
data NaturalNumber = Zero | S NaturalNumber
deriving (Show)
-- Common names for some small natural numbers.
zero = Zero
one = S zero
two = S one
three = S two
four = S three
five = S four
six = S five
seven = S six
eight = S seven
nine = S eight
ten = S nine
eleven = S ten
twelve = S eleven
-- Some examples of a non-grounded data type.
infinity = S infinity
loop :: NaturalNumber
loop = loop
-- | NaturalNumber is an instance of typeclass EQ.
instance Eq NaturalNumber where
S x == S y = x == y
Zero == Zero = True
Zero == S _ = False
S _ == Zero = False
-- | NaturalNumber is an instance of typeclass Ord
instance Ord NaturalNumber where
compare (S a) (S b) = compare a b
compare Zero Zero = EQ
compare Zero _ = LT
compare _ Zero = GT
-- | NaturalNumber is an instance of typeclass Num
instance Num NaturalNumber where
x + Zero = x
x + S y = S (x + y)
Zero * _ = Zero
x * S y = x * y + x
_ * _ = Zero
(S x) - (S y) = x - y
x - Zero = x
Zero - _ = Zero
abs = id
signum Zero = Zero
signum (S _) = S(Zero)
fromInteger n
| n > 0 = S (fromInteger (n-1))
| n == 0 = Zero
-- To make an instance of Integral, ghc is telling me that I need
-- to make NaturalNumber an instance of Real and Enum. I'll come
-- back later when I better understand these type classes.
-- instance Integral NaturalNumber where
-- quotRem _ Zero = error "Division by Zero undefined."
-- quotRem n d
-- | n < d = (Zero, n)
-- | n >= d = let
-- (q, r) = quotRem (n - d) d
-- in
-- (S(q), r)
--
-- -- Stack crancky? Should I make this tail recursive?
--
-- toInteger Zero = 0
-- toInteger (S n) = 1 + toInteger n
-- | A NaturalNumber context helper function.
--
-- In the expression "nat (4 + 3*5)" 3, 4, and 5 are interpretted as
-- NaturalNumbers. Also, "nat (-5)" is "Zero", consistent with our
-- notion of subtraction. The magic is in the type signature and how
-- negation is defined in the Num typeclass.
nat :: NaturalNumber -> NaturalNumber
nat = id
-- | Determine if a natural number is even.
--
-- Unsafe for Fractional data types if typed
-- even' :: (Eq t, Num t) => t -> Bool
-- Also, the name "even" collides with the one from the
-- Integral typeclass imported from Prelude.
even' :: NaturalNumber -> Bool
even' n
| n == 0 = True
| n == 1 = False
| otherwise = even' $ n-2
-- | Determine if a natural number is odd.
odd' :: NaturalNumber -> Bool
odd' = not . even'
| grscheller/scheller-linux-archive | grok/Haskell/haskellIntroProgramming/PeanoArithmetic/NaturalNumbers.hs | bsd-3-clause | 2,956 | 0 | 11 | 894 | 620 | 323 | 297 | 53 | 1 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, GeneralizedNewtypeDeriving, MultiParamTypeClasses, StandaloneDeriving, UndecidableInstances, OverloadedStrings #-}
module Network.IRC.Bot.BotMonad
( BotPartT(..)
, BotMonad(..)
, BotEnv(..)
, runBotPartT
, mapBotPartT
, maybeZero
) where
import Control.Applicative (Applicative, Alternative, (<$>))
import Control.Arrow (first)
import Control.Monad (MonadPlus(mplus, mzero), forever, replicateM, when)
import Control.Monad.Cont (MonadCont)
import Control.Monad.Error (MonadError)
import Control.Monad.Reader (MonadReader(ask, local), MonadTrans, ReaderT(runReaderT), mapReaderT)
import Control.Monad.Writer (MonadWriter)
import Control.Monad.State (MonadState)
import Control.Monad.RWS (MonadRWS)
import Control.Concurrent.Chan (Chan, dupChan, newChan, readChan, writeChan)
import Control.Monad.Fix (MonadFix)
import Control.Monad.Trans
import Data.ByteString (ByteString)
import Network.IRC (Command, Message(Message, msg_prefix, msg_command, msg_params), Prefix(NickName), UserName, encode, decode, joinChan, nick, user)
import Network.IRC.Bot.Log
class (Functor m, MonadPlus m, MonadIO m) => BotMonad m where
askBotEnv :: m BotEnv
askMessage :: m Message
askOutChan :: m (Chan Message)
localMessage :: (Message -> Message) -> m a -> m a
sendMessage :: Message -> m ()
logM :: LogLevel -> ByteString -> m ()
whoami :: m ByteString
data BotEnv = BotEnv
{ message :: Message
, outChan :: Chan Message
, logFn :: Logger
, botName :: ByteString
, cmdPrefix :: String
}
newtype BotPartT m a = BotPartT { unBotPartT :: ReaderT BotEnv m a }
deriving (Applicative, Alternative, Functor, Monad, MonadFix, MonadPlus, MonadTrans, MonadIO, MonadWriter w, MonadState s, MonadError e, MonadCont)
instance (MonadReader r m) => MonadReader r (BotPartT m) where
ask = BotPartT (lift ask)
local f = BotPartT . mapReaderT (local f) . unBotPartT
instance (MonadRWS r w s m) => MonadRWS r w s (BotPartT m)
runBotPartT :: BotPartT m a -> BotEnv -> m a
runBotPartT botPartT = runReaderT (unBotPartT botPartT)
mapBotPartT :: (m a -> n b) -> BotPartT m a -> BotPartT n b
mapBotPartT f (BotPartT r) = BotPartT $ mapReaderT f r
instance (Functor m, MonadIO m, MonadPlus m) => BotMonad (BotPartT m) where
askBotEnv = BotPartT ask
askMessage = BotPartT (message <$> ask)
askOutChan = BotPartT (outChan <$> ask)
localMessage f (BotPartT r) = BotPartT (local (\e -> e { message = f (message e) }) r)
sendMessage msg =
BotPartT $ do out <- outChan <$> ask
liftIO $ writeChan out msg
return ()
logM lvl msg =
BotPartT $ do l <- logFn <$> ask
liftIO $ l lvl msg
whoami = BotPartT $ botName <$> ask
maybeZero :: (MonadPlus m) => Maybe a -> m a
maybeZero Nothing = mzero
maybeZero (Just a) = return a | eigengrau/haskell-ircbot | Network/IRC/Bot/BotMonad.hs | bsd-3-clause | 2,931 | 0 | 15 | 604 | 997 | 552 | 445 | 63 | 1 |
-- | The method of moments can be used to estimate a number of commonly used distributions. This module is still under construction as I work out the best way to handle morphisms from the Moments3 type to types of other distributions. For more information, see the wikipedia entry: <https://en.wikipedia.org/wiki/Method_of_moments_(statistics)>
module HLearn.Models.Distributions.Univariate.Exponential
( Exponential
)
where
import Control.DeepSeq
import GHC.TypeLits
import qualified Data.Vector.Unboxed as U
import Data.Vector.Unboxed.Deriving
import HLearn.Algebra
import HLearn.Models.Distributions.Common
import HLearn.Models.Distributions.Univariate.Internal.Moments
import HLearn.Models.Distributions.Visualization.Gnuplot
-------------------------------------------------------------------------------
-- Exponential
newtype Exponential prob dp = Exponential (Moments3 prob)
deriving (Read,Show,Eq,Ord,Monoid,Group)
instance (Num prob) => HomTrainer (Exponential prob prob) where
type Datapoint (Exponential prob prob) = prob
train1dp dp = Exponential $ train1dp dp
instance (Num prob) => Probabilistic (Exponential prob dp) where
type Probability (Exponential prob dp) = prob
instance (Floating prob) => PDF (Exponential prob prob) where
pdf dist dp = lambda*(exp $ (-1)*lambda*dp)
where
lambda = e_lambda dist
e_lambda (Exponential dist) = (m0 dist)/(m1 dist)
instance (Fractional prob) => Mean (Exponential prob prob) where
mean dist = 1/(e_lambda dist)
instance (Fractional prob) => Variance (Exponential prob prob) where
variance dist = 1/(e_lambda dist)^^2
instance
( Floating prob
, Enum prob
, Show prob
, Ord prob
) => PlottableDistribution (Exponential prob prob) where
plotType _ = Continuous
samplePoints dist = samplesFromMinMax 0 $ (mean dist)*3
| ehlemur/HLearn | src/HLearn/Models/Distributions/Univariate/Exponential.hs | bsd-3-clause | 1,881 | 0 | 12 | 328 | 479 | 262 | 217 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
------------------------------------------------------------------------------
-- |
-- Module : Data.XML.DTD.Render
-- Copyright : Suite Solutions Ltd., Israel 2011
-- (c) 2013 Montez Fitzpatrick
--
-- Maintainer : Montez Fitzpatrick <[email protected]>
-- Portability : portable
--
-- A "Data.Text.Lazy.Builder" renderer for XML Document Type
-- Declaration (DTD) documents.
{-
Copyright (c) 2011 Suite Solutions Ltd., Israel. All rights reserved.
For licensing information, see the BSD3-style license in the file
license.txt that was originally distributed by the author together
with this file.
-}
module Data.XML.DTD.Render
( -- * DTD structure
buildDTD
, buildDTDTextDecl
, buildDTDComponent
-- * Entity declarations and references
, buildEntityDecl
, buildEntityValue
, buildPERef
-- * Element declarations
, buildElementDecl
, buildContentDecl
, buildContentModel
, buildRepeat
-- * Attribute declarations
, buildAttList
, buildAttDecl
, buildAttType
, buildAttDefault
-- * Notation declarations
, buildNotation
, buildNotationSource
-- * Comments and processing instructions
, buildInstruction
, buildComment
-- * Builder combinators for general DTD syntax
, buildExternalID
, buildList
, buildChoice
, buildMaybe
, newline
, space
, quote
, pbracket
, parens
)
where
import Data.XML.DTD.Types
import Data.XML.Types (ExternalID(..), Instruction(..))
import Data.Text (Text)
import Data.Text.Lazy.Builder (Builder, fromText, singleton)
import Data.Monoid (Monoid(..))
import Data.List (intersperse)
import System.IO (nativeNewline, Newline(CRLF))
-- Inline Builder combinator
(<>) = mappend
-- | Build an optional item.
buildMaybe :: (a -> Builder) -> Maybe a -> Builder
buildMaybe = maybe mempty
-- | Build a newline.
newline :: Builder
newline = fromText $ case nativeNewline of
CRLF -> "\r\n"
_ -> "\n"
-- | Build a space.
space :: Builder
space = singleton ' '
-- | Build a quoted string.
quote :: Builder -> Builder
quote = (singleton '"' <>) . (<> singleton '"')
-- | Build a string quoted by angle brackets, with an exclamation mark.
pbracket :: Builder -> Builder
pbracket = (fromText "<!" <>) . (<> singleton '>')
-- | Build a string surround by parentheses.
parens :: Builder -> Builder
parens = (singleton '(' <>) . (<> singleton ')')
-- | Build a list of items
buildList :: Text -> (a -> Builder) -> [a] -> Builder
buildList sep build =
parens . mconcat . intersperse (fromText sep) . map build
-- | Build a choice expression.
buildChoice :: (a -> Builder) -> [a] -> Builder
buildChoice = buildList " | "
-- | A 'Builder' for a 'DTD'.
buildDTD (DTD decl cmps) = buildMaybe buildDTDTextDecl decl <>
mconcat (map ((<> newline) . buildDTDComponent) cmps)
-- | A 'Builder' for a 'DTDTextDecl'.
buildDTDTextDecl :: DTDTextDecl -> Builder
buildDTDTextDecl (DTDTextDecl ver enc) = fromText "<?xml " <>
buildMaybe
((fromText "version=" <>) . (<> space) . quote . fromText) ver <>
fromText "encoding=" <> quote (fromText enc) <> fromText "?>" <> newline
-- | A 'Builder' for a 'DTDComponent'.
buildDTDComponent :: DTDComponent -> Builder
buildDTDComponent (DTDEntityDecl d) = buildEntityDecl d
buildDTDComponent (DTDElementDecl d) = buildElementDecl d
buildDTDComponent (DTDAttList a) = buildAttList a
buildDTDComponent (DTDNotation n) = buildNotation n
buildDTDComponent (DTDPERef r) = buildPERef r
buildDTDComponent (DTDInstruction i) = buildInstruction i
buildDTDComponent (DTDComment c) = buildComment c
-- | A 'Builder' for an 'EntityDecl'.
buildEntityDecl :: EntityDecl -> Builder
buildEntityDecl d = pbracket $ fromText "ENTITY " <> pct <> name <> val
where
name = fromText (entityDeclName d) <> space
(pct, val) = case d of
InternalGeneralEntityDecl _ val -> (mempty, buildEntityValue val)
ExternalGeneralEntityDecl _ eid nt -> (mempty, ege eid nt)
InternalParameterEntityDecl _ val -> (pctBld, buildEntityValue val)
ExternalParameterEntityDecl _ eid -> (pctBld, buildExternalID eid)
pctBld = fromText "% "
ege eid nt = buildExternalID eid <>
buildMaybe ((fromText " NDATA " <>) . quote . fromText) nt
-- | A 'Builder' for an 'ExternalID'.
buildExternalID :: ExternalID -> Builder
buildExternalID (SystemID sys) = fromText "SYSTEM " <>
quote (fromText sys)
buildExternalID (PublicID pub sys) = fromText "PUBLIC " <>
quote (fromText pub) <> space <>
quote (fromText sys)
-- | A 'Builder' for an entity value, consisting of a list of
-- 'EntityValue'.
buildEntityValue :: [EntityValue] -> Builder
buildEntityValue = quote . mconcat . map val
where
val (EntityText t) = fromText t
val (EntityPERef r) = buildPERef r
-- | A builder for a 'PERef'.
buildPERef :: PERef -> Builder
buildPERef r = singleton '%' <> fromText r <> singleton ';'
-- | A 'Builder' for an 'ElementDecl'.
buildElementDecl :: ElementDecl -> Builder
buildElementDecl (ElementDecl name content) = pbracket $
fromText "ELEMENT " <> fromText name <> space <> buildContentDecl content
-- | A 'Builder' for a 'ContentDecl'.
buildContentDecl :: ContentDecl -> Builder
buildContentDecl ContentEmpty = fromText "EMPTY"
buildContentDecl ContentAny = fromText "ANY"
buildContentDecl (ContentElement cm) = buildContentModel cm
buildContentDecl (ContentMixed names) =
buildChoice fromText ("#PCDATA" : names) <> singleton '*'
-- | A 'Builder' for a 'ContentModel'.
buildContentModel :: ContentModel -> Builder
buildContentModel (CMName nam rpt) = parens $ fromText nam <> buildRepeat rpt
buildContentModel cm = buildCM cm
where
buildCM (CMName name rpt) = fromText name <> buildRepeat rpt
buildCM (CMChoice cms rpt) = cp buildChoice cms rpt
buildCM (CMSeq cms rpt) = cp (buildList ", ") cms rpt
cp f cms rpt = f buildCM cms <> buildRepeat rpt
-- | A 'Builder' for a 'Repeat'.
buildRepeat :: Repeat -> Builder
buildRepeat One = mempty
buildRepeat ZeroOrOne = singleton '?'
buildRepeat ZeroOrMore = singleton '*'
buildRepeat OneOrMore = singleton '+'
-- | A 'Builder' for an 'AttList'.
buildAttList :: AttList -> Builder
buildAttList (AttList name decls) = pbracket $
fromText "ATTLIST " <> fromText name <> mconcat
(map ((newline <>) . (fromText " " <>) . buildAttDecl) decls)
-- | A 'Builder' for an 'AttDecl'.
buildAttDecl :: AttDecl -> Builder
buildAttDecl (AttDecl name typ dflt) = fromText name <> space <>
buildAttType typ <> space <> buildAttDefault dflt
-- | A 'Builder' for an 'AttType'.
buildAttType :: AttType -> Builder
buildAttType AttStringType = fromText "CDATA"
buildAttType AttIDType = fromText "ID"
buildAttType AttIDRefType = fromText "IDREF"
buildAttType AttIDRefsType = fromText "IDREFS"
buildAttType AttEntityType = fromText "ENTITY"
buildAttType AttEntitiesType = fromText "ENTITIES"
buildAttType AttNmTokenType = fromText "NMTOKEN"
buildAttType AttNmTokensType = fromText "NMTOKENS"
buildAttType (AttEnumType vs) = buildChoice fromText vs
buildAttType (AttNotationType ns) = fromText "NOTATION " <>
buildChoice fromText ns
-- | A 'Builder' for an 'AttDefault'.
buildAttDefault :: AttDefault -> Builder
buildAttDefault AttRequired = fromText "#REQUIRED"
buildAttDefault AttImplied = fromText "#IMPLIED"
buildAttDefault (AttDefaultValue val) = quote (fromText val)
buildAttDefault (AttFixed val) = fromText "#FIXED " <>
quote (fromText val)
-- | A 'Builder' for a 'Notation'.
buildNotation :: Notation -> Builder
buildNotation (Notation name src) = pbracket $
fromText "NOTATION " <> fromText name <> space <> buildNotationSource src
-- | A 'Builder' for a 'NotationSource'.
buildNotationSource :: NotationSource -> Builder
buildNotationSource (NotationSysID sys) = fromText "SYSTEM " <>
quote (fromText sys)
buildNotationSource (NotationPubID pub) = fromText "PUBLIC " <>
quote (fromText pub)
buildNotationSource (NotationPubSysID pub sys) = fromText "PUBLIC " <>
quote (fromText pub) <>
space <>
quote (fromText sys)
-- | A 'Builder' for an 'Instruction'.
buildInstruction :: Instruction -> Builder
buildInstruction (Instruction trgt dat) =
fromText "<?" <> fromText trgt <> space <> fromText dat <> fromText "?>"
-- | A 'Builder' for a comment. The comment text cannot be null,
-- cannot contain two consecutive '-', and cannot end in '-'.
buildComment :: Text -> Builder
buildComment cmt = pbracket $ fromText "--" <> fromText cmt <> fromText "--"
| m15k/hs-dtd-text | Data/XML/DTD/Render.hs | bsd-3-clause | 9,117 | 0 | 16 | 2,144 | 2,115 | 1,099 | 1,016 | 158 | 4 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.TimeGrain.CA.Rules
( rules ) where
import Data.Text (Text)
import Prelude
import Data.String
import Duckling.Dimensions.Types
import qualified Duckling.TimeGrain.Types as TG
import Duckling.Types
grains :: [(Text, String, TG.Grain)]
grains = [ ("segon (grain)", "seg(on)?s?", TG.Second)
, ("minuts (grain)", "min(ut)?s?", TG.Minute)
, ("hora (grain)", "h(or(a|es))?", TG.Hour)
, ("dia (grain)", "d(í|i)(a|es)", TG.Day)
, ("setmana (grain)", "setman(a|es)", TG.Week)
, ("mes (grain)", "mes(os)?", TG.Month)
, ("trimestre (grain)", "trimestres?", TG.Quarter)
, ("any (grain)", "anys?", TG.Year)
]
rules :: [Rule]
rules = map go grains
where
go (name, regexPattern, grain) = Rule
{ name = name
, pattern = [regex regexPattern]
, prod = \_ -> Just $ Token TimeGrain grain
}
| facebookincubator/duckling | Duckling/TimeGrain/CA/Rules.hs | bsd-3-clause | 1,161 | 0 | 11 | 259 | 271 | 172 | 99 | 25 | 1 |
module Win32Key where
import Win32Types
import GDITypes
import StdDIS
type VKey = DWORD
vK_LBUTTON :: VKey
vK_LBUTTON =
unsafePerformIO(
prim_Win32Key_cpp_vK_LBUTTON >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_LBUTTON :: IO (Word32)
vK_RBUTTON :: VKey
vK_RBUTTON =
unsafePerformIO(
prim_Win32Key_cpp_vK_RBUTTON >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_RBUTTON :: IO (Word32)
vK_CANCEL :: VKey
vK_CANCEL =
unsafePerformIO(
prim_Win32Key_cpp_vK_CANCEL >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_CANCEL :: IO (Word32)
vK_MBUTTON :: VKey
vK_MBUTTON =
unsafePerformIO(
prim_Win32Key_cpp_vK_MBUTTON >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_MBUTTON :: IO (Word32)
vK_BACK :: VKey
vK_BACK =
unsafePerformIO(
prim_Win32Key_cpp_vK_BACK >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_BACK :: IO (Word32)
vK_TAB :: VKey
vK_TAB =
unsafePerformIO(
prim_Win32Key_cpp_vK_TAB >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_TAB :: IO (Word32)
vK_CLEAR :: VKey
vK_CLEAR =
unsafePerformIO(
prim_Win32Key_cpp_vK_CLEAR >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_CLEAR :: IO (Word32)
vK_RETURN :: VKey
vK_RETURN =
unsafePerformIO(
prim_Win32Key_cpp_vK_RETURN >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_RETURN :: IO (Word32)
vK_SHIFT :: VKey
vK_SHIFT =
unsafePerformIO(
prim_Win32Key_cpp_vK_SHIFT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_SHIFT :: IO (Word32)
vK_CONTROL :: VKey
vK_CONTROL =
unsafePerformIO(
prim_Win32Key_cpp_vK_CONTROL >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_CONTROL :: IO (Word32)
vK_MENU :: VKey
vK_MENU =
unsafePerformIO(
prim_Win32Key_cpp_vK_MENU >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_MENU :: IO (Word32)
vK_PAUSE :: VKey
vK_PAUSE =
unsafePerformIO(
prim_Win32Key_cpp_vK_PAUSE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_PAUSE :: IO (Word32)
vK_CAPITAL :: VKey
vK_CAPITAL =
unsafePerformIO(
prim_Win32Key_cpp_vK_CAPITAL >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_CAPITAL :: IO (Word32)
vK_ESCAPE :: VKey
vK_ESCAPE =
unsafePerformIO(
prim_Win32Key_cpp_vK_ESCAPE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_ESCAPE :: IO (Word32)
vK_SPACE :: VKey
vK_SPACE =
unsafePerformIO(
prim_Win32Key_cpp_vK_SPACE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_SPACE :: IO (Word32)
vK_PRIOR :: VKey
vK_PRIOR =
unsafePerformIO(
prim_Win32Key_cpp_vK_PRIOR >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_PRIOR :: IO (Word32)
vK_NEXT :: VKey
vK_NEXT =
unsafePerformIO(
prim_Win32Key_cpp_vK_NEXT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NEXT :: IO (Word32)
vK_END :: VKey
vK_END =
unsafePerformIO(
prim_Win32Key_cpp_vK_END >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_END :: IO (Word32)
vK_HOME :: VKey
vK_HOME =
unsafePerformIO(
prim_Win32Key_cpp_vK_HOME >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_HOME :: IO (Word32)
vK_LEFT :: VKey
vK_LEFT =
unsafePerformIO(
prim_Win32Key_cpp_vK_LEFT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_LEFT :: IO (Word32)
vK_UP :: VKey
vK_UP =
unsafePerformIO(
prim_Win32Key_cpp_vK_UP >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_UP :: IO (Word32)
vK_RIGHT :: VKey
vK_RIGHT =
unsafePerformIO(
prim_Win32Key_cpp_vK_RIGHT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_RIGHT :: IO (Word32)
vK_DOWN :: VKey
vK_DOWN =
unsafePerformIO(
prim_Win32Key_cpp_vK_DOWN >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_DOWN :: IO (Word32)
vK_SELECT :: VKey
vK_SELECT =
unsafePerformIO(
prim_Win32Key_cpp_vK_SELECT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_SELECT :: IO (Word32)
vK_EXECUTE :: VKey
vK_EXECUTE =
unsafePerformIO(
prim_Win32Key_cpp_vK_EXECUTE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_EXECUTE :: IO (Word32)
vK_SNAPSHOT :: VKey
vK_SNAPSHOT =
unsafePerformIO(
prim_Win32Key_cpp_vK_SNAPSHOT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_SNAPSHOT :: IO (Word32)
vK_INSERT :: VKey
vK_INSERT =
unsafePerformIO(
prim_Win32Key_cpp_vK_INSERT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_INSERT :: IO (Word32)
vK_DELETE :: VKey
vK_DELETE =
unsafePerformIO(
prim_Win32Key_cpp_vK_DELETE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_DELETE :: IO (Word32)
vK_HELP :: VKey
vK_HELP =
unsafePerformIO(
prim_Win32Key_cpp_vK_HELP >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_HELP :: IO (Word32)
vK_NUMPAD0 :: VKey
vK_NUMPAD0 =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMPAD0 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMPAD0 :: IO (Word32)
vK_NUMPAD1 :: VKey
vK_NUMPAD1 =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMPAD1 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMPAD1 :: IO (Word32)
vK_NUMPAD2 :: VKey
vK_NUMPAD2 =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMPAD2 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMPAD2 :: IO (Word32)
vK_NUMPAD3 :: VKey
vK_NUMPAD3 =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMPAD3 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMPAD3 :: IO (Word32)
vK_NUMPAD4 :: VKey
vK_NUMPAD4 =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMPAD4 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMPAD4 :: IO (Word32)
vK_NUMPAD5 :: VKey
vK_NUMPAD5 =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMPAD5 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMPAD5 :: IO (Word32)
vK_NUMPAD6 :: VKey
vK_NUMPAD6 =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMPAD6 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMPAD6 :: IO (Word32)
vK_NUMPAD7 :: VKey
vK_NUMPAD7 =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMPAD7 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMPAD7 :: IO (Word32)
vK_NUMPAD8 :: VKey
vK_NUMPAD8 =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMPAD8 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMPAD8 :: IO (Word32)
vK_NUMPAD9 :: VKey
vK_NUMPAD9 =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMPAD9 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMPAD9 :: IO (Word32)
vK_MULTIPLY :: VKey
vK_MULTIPLY =
unsafePerformIO(
prim_Win32Key_cpp_vK_MULTIPLY >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_MULTIPLY :: IO (Word32)
vK_ADD :: VKey
vK_ADD =
unsafePerformIO(
prim_Win32Key_cpp_vK_ADD >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_ADD :: IO (Word32)
vK_SEPARATOR :: VKey
vK_SEPARATOR =
unsafePerformIO(
prim_Win32Key_cpp_vK_SEPARATOR >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_SEPARATOR :: IO (Word32)
vK_SUBTRACT :: VKey
vK_SUBTRACT =
unsafePerformIO(
prim_Win32Key_cpp_vK_SUBTRACT >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_SUBTRACT :: IO (Word32)
vK_DECIMAL :: VKey
vK_DECIMAL =
unsafePerformIO(
prim_Win32Key_cpp_vK_DECIMAL >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_DECIMAL :: IO (Word32)
vK_DIVIDE :: VKey
vK_DIVIDE =
unsafePerformIO(
prim_Win32Key_cpp_vK_DIVIDE >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_DIVIDE :: IO (Word32)
vK_F1 :: VKey
vK_F1 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F1 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F1 :: IO (Word32)
vK_F2 :: VKey
vK_F2 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F2 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F2 :: IO (Word32)
vK_F3 :: VKey
vK_F3 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F3 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F3 :: IO (Word32)
vK_F4 :: VKey
vK_F4 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F4 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F4 :: IO (Word32)
vK_F5 :: VKey
vK_F5 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F5 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F5 :: IO (Word32)
vK_F6 :: VKey
vK_F6 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F6 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F6 :: IO (Word32)
vK_F7 :: VKey
vK_F7 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F7 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F7 :: IO (Word32)
vK_F8 :: VKey
vK_F8 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F8 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F8 :: IO (Word32)
vK_F9 :: VKey
vK_F9 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F9 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F9 :: IO (Word32)
vK_F10 :: VKey
vK_F10 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F10 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F10 :: IO (Word32)
vK_F11 :: VKey
vK_F11 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F11 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F11 :: IO (Word32)
vK_F12 :: VKey
vK_F12 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F12 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F12 :: IO (Word32)
vK_F13 :: VKey
vK_F13 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F13 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F13 :: IO (Word32)
vK_F14 :: VKey
vK_F14 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F14 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F14 :: IO (Word32)
vK_F15 :: VKey
vK_F15 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F15 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F15 :: IO (Word32)
vK_F16 :: VKey
vK_F16 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F16 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F16 :: IO (Word32)
vK_F17 :: VKey
vK_F17 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F17 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F17 :: IO (Word32)
vK_F18 :: VKey
vK_F18 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F18 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F18 :: IO (Word32)
vK_F19 :: VKey
vK_F19 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F19 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F19 :: IO (Word32)
vK_F20 :: VKey
vK_F20 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F20 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F20 :: IO (Word32)
vK_F21 :: VKey
vK_F21 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F21 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F21 :: IO (Word32)
vK_F22 :: VKey
vK_F22 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F22 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F22 :: IO (Word32)
vK_F23 :: VKey
vK_F23 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F23 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F23 :: IO (Word32)
vK_F24 :: VKey
vK_F24 =
unsafePerformIO(
prim_Win32Key_cpp_vK_F24 >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_F24 :: IO (Word32)
vK_NUMLOCK :: VKey
vK_NUMLOCK =
unsafePerformIO(
prim_Win32Key_cpp_vK_NUMLOCK >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_NUMLOCK :: IO (Word32)
vK_SCROLL :: VKey
vK_SCROLL =
unsafePerformIO(
prim_Win32Key_cpp_vK_SCROLL >>= \ (res1) ->
(return (res1)))
primitive prim_Win32Key_cpp_vK_SCROLL :: IO (Word32)
enableWindow :: HWND -> Bool -> IO Bool
enableWindow arg1 gc_arg1 =
(marshall_bool_ gc_arg1) >>= \ (arg2) ->
prim_Win32Key_cpp_enableWindow arg1 arg2 >>= \ (res1) ->
(unmarshall_bool_ res1) >>= \ gc_res1 ->
(return (gc_res1))
primitive prim_Win32Key_cpp_enableWindow :: Addr -> Int -> IO (Int)
getActiveWindow :: IO MbHWND
getActiveWindow =
prim_Win32Key_cpp_getActiveWindow >>= \ (res1) ->
(if nullHANDLE == (res1)
then return Nothing
else (return ((Just res1)))) >>= \ gc_res1 ->
(return (gc_res1))
primitive prim_Win32Key_cpp_getActiveWindow :: IO (Addr)
getAsyncKeyState :: Int -> IO WORD
getAsyncKeyState arg1 =
prim_Win32Key_cpp_getAsyncKeyState arg1 >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1))
primitive prim_Win32Key_cpp_getAsyncKeyState :: Int -> IO (Word32)
getFocus :: IO MbHWND
getFocus =
prim_Win32Key_cpp_getFocus >>= \ (res1) ->
(if nullHANDLE == (res1)
then return Nothing
else (return ((Just res1)))) >>= \ gc_res1 ->
(return (gc_res1))
primitive prim_Win32Key_cpp_getFocus :: IO (Addr)
getKBCodePage :: IO UINT
getKBCodePage =
prim_Win32Key_cpp_getKBCodePage >>= \ (res1) ->
(return (res1))
primitive prim_Win32Key_cpp_getKBCodePage :: IO (Word32)
isWindowEnabled :: HWND -> IO Bool
isWindowEnabled arg1 =
prim_Win32Key_cpp_isWindowEnabled arg1 >>= \ (res1) ->
(unmarshall_bool_ res1) >>= \ gc_res1 ->
(return (gc_res1))
primitive prim_Win32Key_cpp_isWindowEnabled :: Addr -> IO (Int)
lOWORD :: DWORD -> WORD
lOWORD arg1 =
unsafePerformIO(
prim_Win32Key_cpp_lOWORD arg1 >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Key_cpp_lOWORD :: Word32 -> IO (Word32)
hIWORD :: DWORD -> WORD
hIWORD arg1 =
unsafePerformIO(
prim_Win32Key_cpp_hIWORD arg1 >>= \ (res1) ->
let gc_res1 = ( fromIntegral (res1)) in
(return (gc_res1)))
primitive prim_Win32Key_cpp_hIWORD :: Word32 -> IO (Word32)
needPrims_hugs 2
| OS2World/DEV-UTIL-HUGS | libraries/win32/Win32Key.hs | bsd-3-clause | 13,868 | 170 | 16 | 2,346 | 4,381 | 2,357 | 2,024 | -1 | -1 |
module Hib.Plugins.Piato (plugin) where
import Data.List (find)
import Data.Char (toLower)
import Hib.Types
import Text.XML.Light
import Network.HTTP (simpleHTTP, getResponseBody, getRequest)
type Restaurant = (String,String)
name :: String
name = "piato"
f :: Message -> IO String
f (Msg _ _ _) = parseMenu
plugin :: Plugin
plugin = Plugin name f
feed :: String
feed = "http://www.sonaatti.fi/rssfeed/"
-- clean restaurant name and menu.
cleanRestaurant :: (Maybe Element,Maybe Element) -> Maybe Restaurant
cleanRestaurant (Nothing,_) = Nothing
cleanRestaurant (_,Nothing) = Nothing
cleanRestaurant ((Just t),(Just d)) =
let cleanT x = takeWhile (/= ' ') $ strContent x
cleanD y = filter (not . flip elem ['\t', '\n']) $ strContent y
in Just (cleanT t, cleanD d)
-- Parse restaurant from XML element.
parseRestaurant :: Element -> [Restaurant] -> [Restaurant]
parseRestaurant x acc =
let mTitle = findElement (QName "title" Nothing Nothing) x
mDesc = findElement (QName "description" Nothing Nothing) x
in case cleanRestaurant (mTitle, mDesc) of
Nothing -> acc
Just (food) -> food:acc
-- Parse restaurants from XML.
parseRestaurants :: Maybe Element -> [Restaurant]
parseRestaurants Nothing = []
parseRestaurants (Just doc) =
let itemElem = QName "item" Nothing Nothing
items = findElements itemElem doc
in foldr parseRestaurant [] items
-- Restaurant as a string.
toStr :: Maybe Restaurant -> String
toStr Nothing = "Failed to parse."
toStr (Just (t,d)) = concat [t, ": ", d]
-- Find restaurant from list.
getRestaurant :: String -> [Restaurant] -> Maybe Restaurant
getRestaurant x = find (\(t,_) -> (map toLower t) == x)
-- Read RSS feed to string.
readFeed :: String -> IO String
readFeed url = simpleHTTP (getRequest url) >>= getResponseBody
-- Parse Sonaatti restaurants and return menu from Piato.
parseMenu :: IO String
parseMenu = do
source <- readFeed feed
let doc = parseXMLDoc source
piato = getRestaurant "piato" (parseRestaurants doc)
return (toStr piato)
| keveri/hib | src/Hib/Plugins/Piato.hs | bsd-3-clause | 2,101 | 0 | 14 | 431 | 690 | 363 | 327 | 48 | 2 |
module Main
( main
) where
import Protolude
import Control.Monad.Log (Severity(..))
import Servant.QuickCheck
((<%>), createContainsValidLocation, defaultArgs, not500,
notLongerThan, serverSatisfies,
unauthorizedContainsWWWAuthenticate, withServantServer)
import Test.Tasty (defaultMain, TestTree, testGroup)
import Test.Tasty.Hspec (Spec, it, testSpec)
import HiCkevInServant.API (api)
import HiCkevInServant.Server (server)
main :: IO ()
main = defaultMain =<< tests
tests :: IO TestTree
tests = do
specs <- testSpec "quickcheck tests" spec
pure $ testGroup "HiCkevInServant.Server" [specs]
spec :: Spec
spec =
it "follows best practices" $
withServantServer api (pure (server Error)) $
\burl ->
serverSatisfies
api
burl
defaultArgs
(not500 <%> createContainsValidLocation <%> notLongerThan 100000000 <%> unauthorizedContainsWWWAuthenticate <%>
mempty)
| zchn/hi-ckev-in-servant | hi-ckev-in-servant-server/tests/Main.hs | bsd-3-clause | 939 | 0 | 12 | 180 | 246 | 139 | 107 | 29 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Rachel.Primitive (
-- * Primitives
-- | The list of every primitive entity.
allPrimitives
) where
import Rachel.Types
import Rachel.TH
import Control.Arrow (second)
import Data.Sound -- wavy
import Data.Sound.Core.Chunked
a, b, c :: Type
a = TVar "a"
b = TVar "b"
c = TVar "c"
infixr 3 ->>
(->>) :: Type -> Type -> Type
(->>) = TFun
decons2 :: t a b -> (a,b)
decons2 = undefined
$(genPrim 0)
$(genPrim 1)
$(genPrim 2)
$(genPrim 3)
$(genPrim 4)
-- | Boolean value /true/.
--
-- > true : Bool
-- > true = true
e_true :: Entity
e_true = prim0 "true" True
-- | Boolean value /false/.
--
-- > false : Bool
-- > false = false
e_false :: Entity
e_false = prim0 "false" False
-- | Integer equality.
--
-- > intEq : Integer -> Integer -> Bool
-- > intEq x y = x == y
e_intEq :: Entity
e_intEq = prim2 "intEq" ((==) :: Integer -> Integer -> Bool)
-- | Real equality.
--
-- > realEq : Real -> Real -> Bool
-- > realEq x y = x == y
e_realEq :: Entity
e_realEq = prim2 "realEq" ((==) :: Double -> Double -> Bool)
-- | Integer addition.
--
-- > intPlus : Integer -> Integer -> Integer
-- > intPlus x y = x + y
e_intPlus :: Entity
e_intPlus = prim2 "intPlus" ((+) :: Integer -> Integer -> Integer)
-- | Real addition.
--
-- > realPlus : Real -> Real -> Real
-- > realPlus x y = x + y
e_realPlus :: Entity
e_realPlus = prim2 "realPlus" ((+) :: Double -> Double -> Double)
-- | Integer product.
--
-- > intProd : Integer -> Integer -> Integer
-- > intProd x y = x * y
e_intProd :: Entity
e_intProd = prim2 "intProd" ((*) :: Integer -> Integer -> Integer)
-- | Real product.
--
-- > realProd : Real -> Real -> Real
-- > realProd x y = x * y
e_realProd :: Entity
e_realProd = prim2 "realProd" ((*) :: Double -> Double -> Double)
-- | Integer division.
e_intDiv :: Entity
e_intDiv = prim2 "intDiv" (div :: Integer -> Integer -> Integer)
-- | Real division.
e_realDiv :: Entity
e_realDiv = prim2 "realDiv" ((/) :: Double -> Double -> Double)
-- | Fixed-point combinator.
--
-- > fix : (a -> a) -> a
-- > fix f = let x = f x in x
e_fix :: Entity
e_fix = Entity "fix" ((a ->> a) ->> a) defaultFixity $
VFun $ \v ->
case v of
VFun f -> let x = f x in x
VBottom str -> VBottom str
_ -> error "Unexpected value, aborting..."
-- | Conditional combinator.
--
-- > if : Bool -> a -> a -> a
-- > if b x y = if b then x else y
e_if :: Entity
e_if = Entity "if" (TBool ->> a ->> a ->> a) defaultFixity $
VFun $ \(VBool (RBool p)) ->
VFun $ \x ->
VFun $ \y -> if p then x else y
-- | Tau constant.
e_tau :: Entity
e_tau = prim0 "tau" (2*pi :: Double)
-- | Sine function.
e_sin :: Entity
e_sin = prim1 "sin" (sin :: Double -> Double)
-- | Cosine function.
e_cos :: Entity
e_cos = prim1 "cos" (cos :: Double -> Double)
-- | Integer negation.
e_intNeg :: Entity
e_intNeg = prim1 "intNeg" (negate :: Integer -> Integer)
-- | Real negation.
e_realNeg :: Entity
e_realNeg = prim1 "realNeg" (negate :: Double -> Double)
-- | Alternative application using sum type.
e_choice :: Entity
e_choice = Entity "choice" ((a ->> c) ->> (b ->> c) ->> TSum a b ->> c) defaultFixity $
VFun $ \(VFun f) ->
VFun $ \(VFun g) ->
VFun $ \s ->
case s of
VSumL x -> f x
VSumR x -> g x
_ -> undefined
e_bottom :: Entity
e_bottom = Entity "bottom" a defaultFixity $ VBottom "bottom"
e_soundSeq :: Entity
e_soundSeq = prim2 "soundSeq" (<.>)
e_soundAdd :: Entity
e_soundAdd = prim2 "soundAdd" (<+>)
e_zeroSound :: Entity
e_zeroSound = prim1 "zeroSound" zeroSound
e_addAt :: Entity
e_addAt = prim3 "addAt" addAt
-- e_soundFunction :: Entity
-- e_soundFunction = prim2 "soundFunction" (\d f -> fromFunction 16 d Nothing f)
e_soundFunction :: Entity
e_soundFunction = Entity "soundFunction" (TReal ->> (TReal ->> TReal) ->> TSound) defaultFixity $
VFun $ \(VReal (RReal d)) ->
VFun $ \(VFun f) ->
VSound $ RSound $
fromFunction 44100 d Nothing $ \t ->
case fromValue . f . toValue . toPrimitive $ t of
Nothing -> undefined
Just x -> monoSample $ fromPrimitive x
-- Requires Strings...
-- e_soundFile :: Entity
-- e_soundFile = Entity "soundFile"
-- Generate list of all primitives
$(genEntList)
| Daniel-Diaz/rachel | Rachel/Primitive.hs | bsd-3-clause | 4,263 | 0 | 15 | 994 | 1,176 | 661 | 515 | 93 | 3 |
module EFA.Signal.Colour where
import qualified Data.Colour.Names as Colour
import Data.Colour.SRGB (sRGB24show)
import Data.Colour (Colour)
import qualified Data.Stream as Stream
import Data.Stream (Stream)
import EFA.Utility (zipWithTraversable)
import Data.Traversable (Traversable)
newtype Name = Name { unpackName :: String } deriving (Show)
showf :: Colour Double -> Name
showf = Name . sRGB24show
adorn :: Traversable f => f a -> f (Name, a)
adorn = zipWithTraversable (,) colours
defltColour :: Name
defltColour = showf Colour.red
colours :: Stream Name
colours = Stream.cycle cls
cls :: [Name]
cls = map showf $
Colour.red :
Colour.blue :
Colour.green :
Colour.orange :
Colour.gray :
Colour.magenta :
Colour.cyan :
Colour.chocolate :
Colour.olive :
Colour.purple :
Colour.lightblue :
Colour.violet :
Colour.darkblue :
Colour.lightcoral :
Colour.darkcyan :
Colour.lightcyan :
Colour.darkgoldenrod :
Colour.lightgoldenrodyellow :
Colour.darkgray :
Colour.lightgray :
Colour.darkgreen :
Colour.lightgreen :
Colour.darkkhaki :
Colour.lightpink :
Colour.darkmagenta :
Colour.lightsalmon :
Colour.darkolivegreen :
Colour.lightseagreen :
Colour.darkorange :
Colour.lightskyblue :
Colour.darkorchid :
Colour.lightslategray :
Colour.darkred :
Colour.lightslategrey :
Colour.darksalmon :
Colour.lightsteelblue :
Colour.darkseagreen :
Colour.lightyellow :
Colour.darkslateblue :
Colour.darkslategray :
Colour.darkturquoise :
Colour.darkviolet :
Colour.deeppink :
Colour.deepskyblue :
Colour.dimgray :
Colour.dodgerblue :
Colour.firebrick :
Colour.floralwhite :
Colour.forestgreen :
Colour.fuchsia :
Colour.gainsboro :
Colour.ghostwhite :
Colour.gold :
Colour.goldenrod :
Colour.greenyellow :
Colour.honeydew :
Colour.hotpink :
Colour.indianred :
Colour.indigo :
Colour.ivory :
Colour.khaki :
Colour.lavender :
Colour.lavenderblush :
Colour.lawngreen :
Colour.lemonchiffon :
Colour.lime :
Colour.limegreen :
Colour.linen :
Colour.maroon :
Colour.mediumaquamarine :
Colour.mediumblue :
Colour.mediumorchid :
Colour.mediumpurple :
Colour.mediumseagreen :
Colour.mediumslateblue :
Colour.mediumspringgreen :
Colour.mediumturquoise :
Colour.mediumvioletred :
Colour.midnightblue :
Colour.mintcream :
Colour.mistyrose :
Colour.moccasin :
Colour.navajowhite :
Colour.navy :
Colour.oldlace :
Colour.olivedrab :
Colour.orangered :
Colour.orchid :
Colour.palegoldenrod :
Colour.palegreen :
Colour.paleturquoise :
Colour.palevioletred :
Colour.aliceblue :
Colour.antiquewhite :
Colour.aqua :
Colour.aquamarine :
Colour.azure :
Colour.beige :
Colour.bisque :
Colour.black :
Colour.blanchedalmond :
Colour.blueviolet :
Colour.brown :
Colour.burlywood :
Colour.cadetblue :
Colour.chartreuse :
Colour.coral :
Colour.cornflowerblue :
Colour.cornsilk :
Colour.crimson :
Colour.papayawhip :
Colour.peachpuff :
Colour.peru :
Colour.pink :
Colour.plum :
Colour.powderblue :
Colour.rosybrown :
Colour.royalblue :
Colour.saddlebrown :
Colour.salmon :
Colour.sandybrown :
Colour.seagreen :
Colour.seashell :
Colour.sienna :
Colour.silver :
Colour.skyblue :
Colour.slateblue :
Colour.slategray :
Colour.snow :
Colour.springgreen :
Colour.steelblue :
Colour.tan :
Colour.teal :
Colour.thistle :
Colour.tomato :
Colour.turquoise :
Colour.wheat :
Colour.whitesmoke :
Colour.yellowgreen :
Colour.yellow :
Colour.white :
[]
| energyflowanalysis/efa-2.1 | src/EFA/Signal/Colour.hs | bsd-3-clause | 3,587 | 0 | 147 | 666 | 1,058 | 546 | 512 | 161 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Auth ( Assertion (..)
, VerifierResponse (..)
, AuthToken (..)
, checkAssertion
, checkAuthToken
, parseAuthToken
, encryptAndSerialise
) where
import Control.Applicative ((<$>), (<*>))
import Data.Aeson
import Text.ParserCombinators.Parsec
import Network.HTTP.Conduit
import Data.Maybe (fromJust)
import Data.ByteString (ByteString)
import Data.ByteString.Char8 (pack)
import Data.ByteString.Lazy (fromChunks)
import Data.Text.Lazy (Text, unpack)
import Data.Text.Lazy.Encoding (decodeUtf8)
import Web.ClientSession (Key, encryptIO, decrypt)
import Control.Error (hush)
-- | Identity assertion recieved from a user
data Assertion = Assertion String deriving (Show)
instance FromJSON Assertion where
parseJSON (Object v) = Assertion <$> v .: "assertion"
parseJSON _ = error "Invalid JSON"
-- | The validity of an assertion, as determined by the Persona verifer
data VerifierResponse = VerifierResponse { verifierStatus :: String
, verifierEmail :: String
} deriving (Show)
instance FromJSON VerifierResponse where
parseJSON (Object v) = VerifierResponse <$> v .: "status" <*> v .: "email"
parseJSON _ = error "Invalid JSON"
-- | The authentication token of a user already logged in
data AuthToken = AuthToken { tokenEmail :: String
, tokenSession :: String
} deriving (Show)
instance FromJSON AuthToken where
parseJSON (Object v) = AuthToken <$> v .: "email" <*> v .: "session"
parseJSON _ = error "Invalid JSON"
-- | check the validity of an assertion using the Persona verfier. Thread-blocking.
checkAssertion :: ByteString -> Assertion -> IO VerifierResponse
checkAssertion hostUrl (Assertion a) = do
url <- parseUrl "https://verifier.login.persona.org/verify"
let req = urlEncodedBody [("audience", hostUrl), ("assertion", pack a)] url
response <- withManager . httpLbs $ req
-- TODO: check certificate - at present we're open to a MitM
return . fromJust . decode . responseBody $ response
-- | Check that an auth token was issued by the server, and that the user is who he thinks he is.
checkAuthToken :: Key -> AuthToken -> Maybe String
checkAuthToken key (AuthToken email session) =
case decrypt key $ pack session of
Nothing -> Nothing
Just str -> if str == pack email then Just email
else Nothing
encryptAndSerialise :: Key -> String -> IO Text
encryptAndSerialise key msg = do
encMsg <- encryptIO key . pack $ msg
return $ decodeUtf8 $ fromChunks [encMsg]
-- | Parse the text of a "Cookie" header, extracting an auth token if the appropriate fields are set
parseAuthToken :: Text -> Maybe AuthToken
parseAuthToken str = case parseCookie $ unpack str of
Nothing -> Nothing
Just c -> AuthToken <$> lookup "email" c <*> lookup "session" c
-- | Parse the text of a "Cookie" header.
parseCookie :: String -> Maybe [(String, String)]
parseCookie = hush . parse cookieFields "(Unknown)"
cookieFields :: GenParser Char st [(String, String)]
cookieFields = do
first <- cookieField
next <- (string "; " >> cookieFields) <|> return []
return $ first:next
cookieField :: GenParser Char st (String, String)
cookieField = do
name <- many (noneOf "=")
char '='
value <- many (noneOf ";\n")
return (name, value)
| asayers/TaskAgent-web | src/Auth.hs | bsd-3-clause | 3,543 | 0 | 13 | 869 | 882 | 471 | 411 | 69 | 3 |
{-# LANGUAGE OverloadedStrings, RankNTypes #-}
module EventToElement (
eventToElementAll,
eventToElement,
showElement,
convert,
) where
import Data.Conduit
-- import Control.Arrow
import Control.Applicative
import Data.XML.Types
-- import Data.Text (Text)
import qualified Data.Text as T
import Control.Monad.IO.Class
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
eventToElementAll :: (Monad m, MonadIO m) => Conduit Event m Element
eventToElementAll = do
mev <- await
case mev of
Just EventBeginDocument -> eventToElementAll
Just (EventBeginElement (Name "stream" _ _) _) -> eventToElementAll
Just (EventBeginElement nm ats) -> do
mel <- toElement nm ats
case mel of
Just el -> do
yield el
eventToElementAll
_ -> return ()
Just (EventEndElement (Name "stream" _ _)) ->
liftIO $ putStrLn "end stream"
Just ev -> error $ "eventToElementAll: bad: " ++ show ev
_ -> return ()
eventToElement :: Monad m => Conduit Event m Element
eventToElement = do
mev <- await
case mev of
Just (EventBeginElement nm ats) -> do
mel <- toElement nm ats
case mel of
Just el -> do
yield el
eventToElement
_ -> return ()
Just ev -> error $ "bad: " ++ show ev
_ -> return ()
toElement :: Monad m => Name -> [(Name, [Content])] ->
Consumer Event m (Maybe Element)
toElement nm ats = do
mev <- await
case mev of
Just ev -> do
ret <- Element nm ats <$> toNodeList nm ev
return $ Just ret
_ -> return Nothing
toNodeList :: Monad m => Name -> Event -> Consumer Event m [Node]
toNodeList nm (EventEndElement n)
| nm == n = return []
| otherwise = error "not match tag names"
toNodeList nm (EventContent c) = do
mev <- await
case mev of
Just ev -> (NodeContent c :) <$> toNodeList nm ev
_ -> return [NodeContent c]
toNodeList nm0 (EventBeginElement nm ats) = do
mel <- toElement nm ats
case mel of
Just el -> do
mev <- await
case mev of
Just ev -> (NodeElement el :) <$> toNodeList nm0 ev
_ -> return [NodeElement el]
_ -> return []
toNodeList _ _ = error "not implemented"
convert :: Monad m => (i -> o) -> Conduit i m o
convert f = do
mx <- await
case mx of
Just x -> yield $ f x
_ -> return ()
{-
testEventList :: [Event]
testEventList = [
EventBeginElement hello [],
EventContent $ ContentText "world",
EventEndElement hello,
EventBeginElement (name "yoshio") [],
EventBeginElement (name "j") [],
EventContent $ ContentText "hacker",
EventEndElement (name "j"),
EventEndElement (name "yoshio")
]
hello :: Name
hello = Name "hello" Nothing Nothing
name :: Text -> Name
name n = Name n Nothing Nothing
eventListToElement :: [Event] -> (Element, [Event])
eventListToElement (EventBeginElement name attrs : rest) =
first (Element name attrs) $ eventListToNodeList rest
eventListToElement _ = error "Not element"
eventListToNodeList :: [Event] -> ([Node], [Event])
eventListToNodeList [] = ([], [])
eventListToNodeList (EventEndElement _ : rest) = ([], rest)
eventListToNodeList (EventContent cnt : rest) =
first (NodeContent cnt :) $ eventListToNodeList rest
eventListToNodeList evs@(EventBeginElement _ _ : _) =
(NodeElement elm : nds, evs'')
where
(elm, evs') = eventListToElement evs
(nds, evs'') = eventListToNodeList evs'
eventListToNodeList _ = error "eventListToNodeList: not implemented yet"
-}
showElement :: Element -> BS.ByteString
showElement (Element nm ats []) =
"<" +++ showNameOpen nm +++ showAttributeList ats +++ "/>"
showElement (Element nm ats nds) =
"<" +++ showNameOpen nm +++ showAttributeList ats +++ ">" +++
BS.concat (map showNode nds) +++ "</" +++ showName nm +++ ">"
showName, showNameOpen :: Name -> BS.ByteString
showName (Name n _ (Just np)) =
BSC.pack (T.unpack np) +++ ":" +++ BSC.pack (T.unpack n)
-- showName (Name n (Just ns) _) = -- "{" ++ T.unpack ns ++ "}" ++ T.unpack n
-- T.unpack n ++ " " ++ "xmlns=\"" ++ T.unpack ns ++ "\""
showName (Name n _ _) = BSC.pack $ T.unpack n
showNameOpen (Name n _ (Just np)) =
BSC.pack (T.unpack np) +++ ":" +++ BSC.pack (T.unpack n)
showNameOpen (Name n (Just ns) _) =
BSC.pack (T.unpack n) +++ " " +++ "xmlns=\"" +++
BSC.pack (T.unpack ns) +++ "\""
showNameOpen (Name n _ _) = BSC.pack (T.unpack n)
showAttributeList :: [(Name, [Content])] -> BS.ByteString
showAttributeList = BS.concat . map ((" " +++) . showAttribute)
showAttribute :: (Name, [Content]) -> BS.ByteString
showAttribute (n, cs) =
showName n +++ "=\"" +++ BS.concat (map showContent cs) +++ "\""
showContent :: Content -> BS.ByteString
showContent (ContentText t) = BSC.pack (T.unpack t)
showContent _ = error "EventListToNodeList.showContent: not implemented"
showNode :: Node -> BS.ByteString
showNode (NodeElement e) = showElement e
showNode (NodeContent c) = showContent c
showNode (NodeComment c) = "<!-- " +++ BSC.pack (T.unpack c) +++ "-->"
showNode _ = error "EventListToNodeList.showNode: not implemented"
(+++) :: BS.ByteString -> BS.ByteString -> BS.ByteString
(+++) = BS.append
| YoshikuniJujo/forest | subprojects/xmpp-tls-analysis/EventToElement.hs | bsd-3-clause | 5,011 | 28 | 17 | 953 | 1,561 | 769 | 792 | 108 | 7 |
{-# LANGUAGE FlexibleInstances #-}
module Data.Json.Pretty where
import JPrelude
import Data.Json.Path
import Data.Aeson.Lens
import Data.Text (Text, pack)
import Data.Scientific (Scientific(..))
class Pretty a where
pretty :: a -> Text
instance Pretty Path where
pretty = toText
instance Pretty (Path, String) where
pretty (p, s) = pretty (p, pack s)
instance Pretty (Path, Text) where
pretty (p, t) = pretty p <> ": " <> t
instance Pretty (Path, Primitive) where
pretty (p, StringPrim x) = pretty (p, show x)
pretty (p, NumberPrim n) = pretty (p, show n)
pretty (p, BoolPrim b) = pretty (p, if b then "true" :: Text else "false")
pretty (p, NullPrim) = pretty (p, "null" :: Text)
tshow :: Show a => a -> Text
tshow = pack.show
instance Pretty Primitive where
pretty (StringPrim x) = tshow x
pretty (NumberPrim x)
| base10Exponent x >= 0 = tshow $ (coefficient x) * 10 ^ (base10Exponent x)
| otherwise = tshow $ x
pretty (BoolPrim x) = if x then "true" else "false"
pretty (NullPrim) = "null"
class PrettyRaw a where
prettyRaw :: a -> Text
instance PrettyRaw Primitive where
prettyRaw (StringPrim x) = x
prettyRaw x = pretty x
| Prillan/haskell-jsontools | src/Data/Json/Pretty.hs | bsd-3-clause | 1,190 | 0 | 11 | 256 | 491 | 263 | 228 | 34 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts #-}
module Text.RegExp.Matching where
import Data.Semiring
import Text.RegExp.Data
import Text.RegExp.Matching.Leftmost.Type
import Text.RegExp.Matching.Longest.Type
import Text.RegExp.Matching.LeftLong.Type
-- |
-- Checks whether a regular expression matches the given word. For
-- example, @acceptFull (fromString \"b|abc\") \"b\"@ yields @True@
-- because the first alternative of @b|abc@ matches the string
-- @\"b\"@.
--
acceptFull :: RegExp c -> [c] -> Bool
acceptFull r = fullMatch r
-- |
-- Checks whether a regular expression matches a subword of the given
-- word. For example, @acceptPartial (fromString \"b\") \"abc\"@
-- yields @True@ because @\"abc\"@ contains the substring @\"b\"@.
--
acceptPartial :: RegExp c -> [c] -> Bool
acceptPartial r = partialMatch r
-- |
-- Computes in how many ways a word can be matched against a regular
-- expression.
--
matchingCount :: (Eq a, Num a) => RegExp c -> [c] -> a
matchingCount r = getNumeric . fullMatch r
{-# SPECIALIZE matchingCount :: RegExp c -> [c] -> Int #-}
-- |
-- Matches a regular expression against a word computing a weight in
-- an arbitrary semiring.
--
-- The symbols can have associated weights associated by the
-- 'symWeight' function of the 'Weight' class. This function also
-- allows to adjust the type of the used alphabet such that, for
-- example, positional information can be taken into account by
-- 'zip'ping the word with positions.
--
fullMatch :: Weight a b w => RegExp a -> [b] -> w
fullMatch (RegExp r) = matchW (weighted r)
{-# SPECIALIZE fullMatch :: RegExp c -> [c] -> Bool #-}
{-# SPECIALIZE fullMatch :: RegExp c -> [c] -> Numeric Int #-}
{-# SPECIALIZE fullMatch :: (Eq a, Num a) => RegExp c -> [c] -> Numeric a #-}
{-# SPECIALIZE fullMatch :: RegExp c -> [(Int,c)] -> Leftmost #-}
{-# SPECIALIZE fullMatch :: RegExp c -> [c] -> Longest #-}
{-# SPECIALIZE fullMatch :: RegExp c -> [(Int,c)] -> LeftLong #-}
-- |
-- Matches a regular expression against substrings of a word computing
-- a weight in an arbitrary semiring. Similar to 'fullMatch' the
-- 'Weight' class is used to associate weights to the symbols of the
-- regular expression.
--
partialMatch :: Weight a b w => RegExp a -> [b] -> w
partialMatch (RegExp r) = matchW (arb `seqW` weighted r `seqW` arb)
where RegExp arb = rep anySym
{-# SPECIALIZE partialMatch :: RegExp c -> [c] -> Bool #-}
{-# SPECIALIZE partialMatch :: RegExp c -> [c] -> Numeric Int #-}
{-# SPECIALIZE partialMatch :: (Eq a, Num a) => RegExp c -> [c] -> Numeric a #-}
{-# SPECIALIZE partialMatch :: RegExp c -> [(Int,c)] -> Leftmost #-}
{-# SPECIALIZE partialMatch :: RegExp c -> [c] -> Longest #-}
{-# SPECIALIZE partialMatch :: RegExp c -> [(Int,c)] -> LeftLong #-}
matchW :: Semiring w => RegW w c -> [c] -> w
matchW r [] = empty r
matchW r (c:cs) = final (foldl (shiftW zero) (shiftW one r c) cs)
{-# SPECIALIZE matchW :: RegW Bool c -> [c] -> Bool #-}
{-# SPECIALIZE matchW :: RegW (Numeric Int) c -> [c] -> Numeric Int #-}
{-# SPECIALIZE matchW :: (Eq a, Num a) => RegW (Numeric a) c -> [c] -> Numeric a #-}
{-# SPECIALIZE matchW :: RegW Leftmost (Int,c) -> [(Int,c)] -> Leftmost #-}
{-# SPECIALIZE matchW :: RegW Longest c -> [c] -> Longest #-}
{-# SPECIALIZE matchW :: RegW LeftLong (Int,c) -> [(Int,c)] -> LeftLong #-}
shiftW :: Semiring w => w -> RegW w c -> c -> RegW w c
shiftW w r c | active r || w /= zero = shift w (reg r) c
| otherwise = r
shift :: Semiring w => w -> Reg w c -> c -> RegW w c
shift _ Eps _ = epsW
shift w (Sym s f) c = let w' = w .*. f c
in (symW s f) { active = w' /= zero, final_ = w' }
shift w (Alt p q) c = altW (shiftW w p c) (shiftW w q c)
shift w (Seq p q) c = seqW (shiftW w p c)
(shiftW (w .*. empty p .+. final p) q c)
shift w (Rep r) c = repW (shiftW (w .+. final r) r c)
| sebfisch/haskell-regexp | src/Text/RegExp/Matching.hs | bsd-3-clause | 3,908 | 0 | 11 | 826 | 766 | 412 | 354 | 51 | 1 |
module Main where
--import Data.IORef
import System.Exit
import Test.QuickCheck
import Data.Graph.Inductive.Tree
import Data.Graph.Inductive.Graph
import Data.List (delete)
-- | Runs the test suite for the replay library
main :: IO ()
main = do
results <- return [True]
if and results
then return ()
else exitFailure
instance Arbitrary (Gr () ()) where
arbitrary = choose (1, 100) >>= arbitraryGraph
--sized arbitraryGraph
where
arbitraryGraph :: Int -> Gen (Gr () ())
arbitraryGraph 1 = return $ insNode (1, ()) empty
arbitraryGraph n = do
g <- arbitraryGraph (n-1)
let ns = nodes g
npred <- choose (1, n`div`2)
nsucc <- choose (1, n`div`2)
pred <- sampleList npred ns
succ <- sampleList nsucc (n:ns) -- include cycles
return $ (toAdj pred, n, (), toAdj succ) & g
where toAdj = map $ (,) ()
-- | returns a random sample list of given length
sampleList :: Int -> [a] -> Gen [a]
sampleList n xs = sample' n [0..length xs - 1] xs
where sample' :: Int -> [Int] -> [a] -> Gen [a]
sample' 1 _ _ = return []
sample' _ [] _ = return []
sample' n ind xs = do
i <- elements ind
let v = xs !! i
xs' <- sample' (n-1) (delete i ind) xs
return $ v : xs'
| zydeon/fglext | test/Test.hs | bsd-3-clause | 1,474 | 1 | 16 | 547 | 539 | 275 | 264 | 35 | 2 |
module Matterhorn.Clipboard
( copyToClipboard
)
where
import Prelude ()
import Matterhorn.Prelude
import Control.Exception ( try )
import qualified Data.Text as T
import System.Hclip ( setClipboard, ClipboardException(..) )
import Matterhorn.Types
copyToClipboard :: Text -> MH ()
copyToClipboard txt = do
result <- liftIO (try (setClipboard (T.unpack txt)))
case result of
Left e -> do
let errMsg = case e of
UnsupportedOS _ ->
"Matterhorn does not support yanking on this operating system."
NoTextualData ->
"Textual data is required to set the clipboard."
MissingCommands cmds ->
"Could not set clipboard due to missing one of the " <>
"required program(s): " <> (T.pack $ show cmds)
mhError $ ClipboardError errMsg
Right () ->
return ()
| matterhorn-chat/matterhorn | src/Matterhorn/Clipboard.hs | bsd-3-clause | 922 | 0 | 21 | 294 | 213 | 110 | 103 | 24 | 4 |
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
module HW06 where
import Data.Aeson
import Data.Monoid
import GHC.Generics
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.Text as T
import qualified Data.Text.IO as T
| sm-haskell-users-group/cis-194 | src/Cis194/Hw/Week6.hs | bsd-3-clause | 244 | 0 | 4 | 32 | 47 | 34 | 13 | 8 | 0 |
{-# LANGUAGE TypeSynonymInstances #-}
-- | Make a Num String instance to allow
-- overloading of (+) to be addition and
-- concatenation
module NumString where
import Data.Char
import Data.List
instance Num String where
(+) = (++)
(*) a b = b ++ a ++ b
(-) a b = isSuffixOf b a ? take (length a - length b) a $ a
negate = reverse
abs a = reverse $ dropWhile isSpace $ reverse (dropWhile isSpace a)
signum a = ""
fromInteger = show
(?) :: Bool -> a -> a -> a
(?) True t _ = t
(?) False _ f = f
| dterei/Scraps | haskell/NumString.hs | bsd-3-clause | 556 | 0 | 11 | 169 | 193 | 107 | 86 | 15 | 1 |
{-# LANGUAGE OverloadedStrings, RankNTypes #-}
{-# OPTIONS_GHC -Wwarn #-}
-- | For practical examples see "Qualys.Cookbook.WasSearchScans".
module Qualys.WasScan
(
-- * Actions
getWasScanCount
, runWasSearchScans
, getWasScanDetail
, getWasScanStatus
, getWasScanResult
-- * Filters
-- ** WasScan Search Filters
, wssFiltId
, wssFiltName
, wssFiltWebAppName
, wssFiltWebAppId
, wssFiltWebAppTags
, wssFiltWebAppTagsId
, wssFiltReference
, wssFiltLaunchedDate
, wssFiltType
, wssFiltMode
, wssFiltStatus
, wssFiltAuthStatus
, wssFiltResultsStatus
-- * Types
, WasScan (..)
, WsScanProfile (..)
, WsTarget (..)
, WsWebApp (..)
, WsTag (..)
, WsAuthRec (..)
, WsProxy (..)
, WsUser (..)
, WsSummary (..)
, WsStat (..)
, WsGlobalStat (..)
, WsNameStat (..)
, WsScanResult (..)
, WsInstance (..)
, WsPayload (..)
, WsIg (..)
) where
import Control.Monad (join)
import Control.Monad.Catch (MonadThrow)
import Control.Monad.IO.Class (MonadIO)
import Data.Conduit (($$))
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Time.Clock (UTCTime)
import Network.HTTP.Client hiding (Proxy)
import Text.XML.Stream.Parse
import Qualys.Internal
import Qualys.Internal.ParseWasScan
import Qualys.V3api
import Qualys.Types.Was
-- | Filter by scan ID.
wssFiltId :: CritField Int
wssFiltId = CF "id"
-- | Filter by scan name.
wssFiltName :: CritField Text
wssFiltName = CF "name"
-- | Filter by web application name.
wssFiltWebAppName :: CritField Text
wssFiltWebAppName = CF "webApp.name"
-- | Filter by web application ID.
wssFiltWebAppId :: CritField Int
wssFiltWebAppId = CF "webApp.id"
-- | Filter if no tags.
wssFiltWebAppTags :: CritField ()
wssFiltWebAppTags = CF "webApp.tags"
-- | Filter by tag ID.
wssFiltWebAppTagsId :: CritField Int
wssFiltWebAppTagsId = CF "webApp.tags.id"
-- | Filter by scan reference
wssFiltReference :: CritField Text
wssFiltReference = CF "reference"
-- | Filter by scan launch date/time.
wssFiltLaunchedDate :: CritField UTCTime
wssFiltLaunchedDate = CF "launchedDate"
-- | Filter by type (VULNERABILITY or DISCOVERY).
wssFiltType :: CritField Text
wssFiltType = CF "type"
-- | Filter by mode (ONDEMAND, SCHEDULED, API).
wssFiltMode :: CritField Text
wssFiltMode = CF "mode"
-- | Filter by status (SUBMITTED, RUNNING, FINISHED, ERROR, CANCELLED).
wssFiltStatus :: CritField Text
wssFiltStatus = CF "status"
-- | Filter by auth status (NONE, NOT_USED, SUCCESSFUL, FAILED, PARTIAL).
wssFiltAuthStatus :: CritField Text
wssFiltAuthStatus = CF "authStatus"
-- | Filter by results status (NOT_USED, TO_BE_PROCESSED, NO_HOST_ALIVE,
-- NO_WEB_SERVICE, TIME_LIMIT_EXCEEDED, SCAN_RESULTS_INVALID, SUCCESSFUL,
-- PROCESSING)
wssFiltResultsStatus :: CritField Text
wssFiltResultsStatus = CF "resultsStatus"
-- | Get the number of scans in your account
getWasScanCount :: (MonadIO m, MonadThrow m) => QualysT m (Maybe Int)
getWasScanCount = do
res <- processV3With V3v30 "count/was/wasscan" Nothing (return ())
return $ v3rCount $ fst res
-- | Search WAS scans
runWasSearchScans :: (MonadIO m, MonadThrow m) => Maybe V3Options ->
QualysT m (Maybe [WasScan])
runWasSearchScans opt = do
res <- processV3PageWith V3v30 "search/was/wasscan" opt parseWasScans
return $ snd res
-- | Retrieve scan details, given the scan ID.
getWasScanDetail :: (MonadIO m, MonadThrow m) => Int ->
QualysT m (Maybe WasScan)
getWasScanDetail x = do
res <- processV3With V3v30 ("get/was/wasscan/" <> show x) Nothing parseWasScan
return . join $ snd res
-- | Given a scan ID return the status of the scan.
getWasScanStatus :: (MonadIO m, MonadThrow m) => Int -> QualysT m (Maybe Text)
getWasScanStatus x = do
res <- processV3With V3v30 ("status/was/wasscan/" <> show x) Nothing parseWasScan
return $ wsStatus =<< (join . snd) res
-- | Given a scan ID, retrieve the results of a scan.
getWasScanResult :: (MonadIO m, MonadThrow m) => Int ->
QualysT m (Maybe WasScan)
getWasScanResult x = do
res <- fetchV3 V3v30 ("download/was/wasscan/" <> show x) Nothing
parseLBS def (responseBody res) $$ parseWasScan
| ahodgen/qualys | Qualys/WasScan.hs | bsd-3-clause | 4,410 | 0 | 11 | 983 | 937 | 527 | 410 | 100 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- Haskell imports
import qualified Snap.Core as SC
import qualified Snap.Http.Server as SHS
-- My imports
import qualified Routes.FileUploadRoute as FUR
site :: SC.Snap ()
site = SC.route [("fileUpload", FUR.handle)]
main :: IO ()
main = SHS.quickHttpServe site
| sudohalt/HaskellFileServer | src/Main.hs | bsd-3-clause | 321 | 0 | 8 | 65 | 82 | 50 | 32 | 8 | 1 |
module Util where
import qualified Control.Exception as E
import System.Process
import System.IO (hClose)
import System.Exit
import Data.Text
import Data.Text.IO
system :: String -> IO Text
system cmd = E.mask $ \restore -> do
(Nothing, Just h, Nothing, pid) <- createProcess (shell cmd) {std_out = CreatePipe}
restore $ do
output <- hGetContents h
waitForProcess pid >>= \r -> case r of
ExitSuccess -> return output
ExitFailure c ->
(E.throwIO . userError) ("system: " ++ cmd ++ " (exit " ++ show c ++ ")")
`E.onException` do
hClose h
terminateProcess pid
waitForProcess pid
| beni55/inject | src/Util.hs | mit | 683 | 0 | 23 | 198 | 227 | 117 | 110 | 20 | 2 |
{- |
Module : ./atermlib/src/ATerm/Lib.hs
Description : reexports modules needed for ATC generation
Copyright : (c) Klaus Luettich, Uni Bremen 2002-2004
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (via imports)
reexports the names needed for many 'ShATermConvertible'
instances. For converting 'ShATerm's to and from 'String's you'll need
the module "ATerm.ReadWrite".
For more information on ATerms look under
<http://www.asfsdf.org>, <http://www.asfsdf.org/Meta-Environment/ATerms>.
-}
module ATerm.Lib
( ShATerm (..)
, ATermTable
, addATerm
, getShATerm
, ShATermConvertible (toShATermAux, fromShATermAux)
, toShATerm'
, fromShATerm'
, fromShATermError
) where
import ATerm.AbstractSyntax
import ATerm.Conversion
| spechub/Hets | atermlib/src/ATerm/Lib.hs | gpl-2.0 | 866 | 0 | 5 | 158 | 53 | 36 | 17 | 13 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ElasticTranscoder.CreateJob
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- When you create a job, Elastic Transcoder returns JSON data that
-- includes the values that you specified plus information about the job
-- that is created.
--
-- If you have specified more than one output for your jobs (for example,
-- one output for the Kindle Fire and another output for the Apple iPhone
-- 4s), you currently must use the Elastic Transcoder API to list the jobs
-- (as opposed to the AWS Console).
--
-- /See:/ <http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/CreateJob.html AWS API Reference> for CreateJob.
module Network.AWS.ElasticTranscoder.CreateJob
(
-- * Creating a Request
createJob
, CreateJob
-- * Request Lenses
, cjUserMetadata
, cjOutputs
, cjOutput
, cjPlaylists
, cjOutputKeyPrefix
, cjPipelineId
, cjInput
-- * Destructuring the Response
, createJobResponse
, CreateJobResponse
-- * Response Lenses
, cjrsJob
, cjrsResponseStatus
) where
import Network.AWS.ElasticTranscoder.Types
import Network.AWS.ElasticTranscoder.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | The 'CreateJobRequest' structure.
--
-- /See:/ 'createJob' smart constructor.
data CreateJob = CreateJob'
{ _cjUserMetadata :: !(Maybe (Map Text Text))
, _cjOutputs :: !(Maybe [CreateJobOutput])
, _cjOutput :: !(Maybe CreateJobOutput)
, _cjPlaylists :: !(Maybe [CreateJobPlaylist])
, _cjOutputKeyPrefix :: !(Maybe Text)
, _cjPipelineId :: !Text
, _cjInput :: !JobInput
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateJob' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cjUserMetadata'
--
-- * 'cjOutputs'
--
-- * 'cjOutput'
--
-- * 'cjPlaylists'
--
-- * 'cjOutputKeyPrefix'
--
-- * 'cjPipelineId'
--
-- * 'cjInput'
createJob
:: Text -- ^ 'cjPipelineId'
-> JobInput -- ^ 'cjInput'
-> CreateJob
createJob pPipelineId_ pInput_ =
CreateJob'
{ _cjUserMetadata = Nothing
, _cjOutputs = Nothing
, _cjOutput = Nothing
, _cjPlaylists = Nothing
, _cjOutputKeyPrefix = Nothing
, _cjPipelineId = pPipelineId_
, _cjInput = pInput_
}
-- | User-defined metadata that you want to associate with an Elastic
-- Transcoder job. You specify metadata in 'key\/value' pairs, and you can
-- add up to 10 'key\/value' pairs per job. Elastic Transcoder does not
-- guarantee that 'key\/value' pairs will be returned in the same order in
-- which you specify them.
cjUserMetadata :: Lens' CreateJob (HashMap Text Text)
cjUserMetadata = lens _cjUserMetadata (\ s a -> s{_cjUserMetadata = a}) . _Default . _Map;
-- | A section of the request body that provides information about the
-- transcoded (target) files. We recommend that you use the 'Outputs'
-- syntax instead of the 'Output' syntax.
cjOutputs :: Lens' CreateJob [CreateJobOutput]
cjOutputs = lens _cjOutputs (\ s a -> s{_cjOutputs = a}) . _Default . _Coerce;
-- | Undocumented member.
cjOutput :: Lens' CreateJob (Maybe CreateJobOutput)
cjOutput = lens _cjOutput (\ s a -> s{_cjOutput = a});
-- | If you specify a preset in 'PresetId' for which the value of 'Container'
-- is fmp4 (Fragmented MP4) or ts (MPEG-TS), Playlists contains information
-- about the master playlists that you want Elastic Transcoder to create.
--
-- The maximum number of master playlists in a job is 30.
cjPlaylists :: Lens' CreateJob [CreateJobPlaylist]
cjPlaylists = lens _cjPlaylists (\ s a -> s{_cjPlaylists = a}) . _Default . _Coerce;
-- | The value, if any, that you want Elastic Transcoder to prepend to the
-- names of all files that this job creates, including output files,
-- thumbnails, and playlists.
cjOutputKeyPrefix :: Lens' CreateJob (Maybe Text)
cjOutputKeyPrefix = lens _cjOutputKeyPrefix (\ s a -> s{_cjOutputKeyPrefix = a});
-- | The 'Id' of the pipeline that you want Elastic Transcoder to use for
-- transcoding. The pipeline determines several settings, including the
-- Amazon S3 bucket from which Elastic Transcoder gets the files to
-- transcode and the bucket into which Elastic Transcoder puts the
-- transcoded files.
cjPipelineId :: Lens' CreateJob Text
cjPipelineId = lens _cjPipelineId (\ s a -> s{_cjPipelineId = a});
-- | A section of the request body that provides information about the file
-- that is being transcoded.
cjInput :: Lens' CreateJob JobInput
cjInput = lens _cjInput (\ s a -> s{_cjInput = a});
instance AWSRequest CreateJob where
type Rs CreateJob = CreateJobResponse
request = postJSON elasticTranscoder
response
= receiveJSON
(\ s h x ->
CreateJobResponse' <$>
(x .?> "Job") <*> (pure (fromEnum s)))
instance ToHeaders CreateJob where
toHeaders = const mempty
instance ToJSON CreateJob where
toJSON CreateJob'{..}
= object
(catMaybes
[("UserMetadata" .=) <$> _cjUserMetadata,
("Outputs" .=) <$> _cjOutputs,
("Output" .=) <$> _cjOutput,
("Playlists" .=) <$> _cjPlaylists,
("OutputKeyPrefix" .=) <$> _cjOutputKeyPrefix,
Just ("PipelineId" .= _cjPipelineId),
Just ("Input" .= _cjInput)])
instance ToPath CreateJob where
toPath = const "/2012-09-25/jobs"
instance ToQuery CreateJob where
toQuery = const mempty
-- | The CreateJobResponse structure.
--
-- /See:/ 'createJobResponse' smart constructor.
data CreateJobResponse = CreateJobResponse'
{ _cjrsJob :: !(Maybe Job')
, _cjrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateJobResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cjrsJob'
--
-- * 'cjrsResponseStatus'
createJobResponse
:: Int -- ^ 'cjrsResponseStatus'
-> CreateJobResponse
createJobResponse pResponseStatus_ =
CreateJobResponse'
{ _cjrsJob = Nothing
, _cjrsResponseStatus = pResponseStatus_
}
-- | A section of the response body that provides information about the job
-- that is created.
cjrsJob :: Lens' CreateJobResponse (Maybe Job')
cjrsJob = lens _cjrsJob (\ s a -> s{_cjrsJob = a});
-- | The response status code.
cjrsResponseStatus :: Lens' CreateJobResponse Int
cjrsResponseStatus = lens _cjrsResponseStatus (\ s a -> s{_cjrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-elastictranscoder/gen/Network/AWS/ElasticTranscoder/CreateJob.hs | mpl-2.0 | 7,338 | 0 | 13 | 1,601 | 1,095 | 659 | 436 | 122 | 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.CodeDeploy.DeleteApplication
-- 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.
-- | Deletes an application.
--
-- <http://docs.aws.amazon.com/codedeploy/latest/APIReference/API_DeleteApplication.html>
module Network.AWS.CodeDeploy.DeleteApplication
(
-- * Request
DeleteApplication
-- ** Request constructor
, deleteApplication
-- ** Request lenses
, daApplicationName
-- * Response
, DeleteApplicationResponse
-- ** Response constructor
, deleteApplicationResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CodeDeploy.Types
import qualified GHC.Exts
newtype DeleteApplication = DeleteApplication
{ _daApplicationName :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteApplication' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'daApplicationName' @::@ 'Text'
--
deleteApplication :: Text -- ^ 'daApplicationName'
-> DeleteApplication
deleteApplication p1 = DeleteApplication
{ _daApplicationName = p1
}
-- | The name of an existing AWS CodeDeploy application associated with the
-- applicable IAM user or AWS account.
daApplicationName :: Lens' DeleteApplication Text
daApplicationName =
lens _daApplicationName (\s a -> s { _daApplicationName = a })
data DeleteApplicationResponse = DeleteApplicationResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteApplicationResponse' constructor.
deleteApplicationResponse :: DeleteApplicationResponse
deleteApplicationResponse = DeleteApplicationResponse
instance ToPath DeleteApplication where
toPath = const "/"
instance ToQuery DeleteApplication where
toQuery = const mempty
instance ToHeaders DeleteApplication
instance ToJSON DeleteApplication where
toJSON DeleteApplication{..} = object
[ "applicationName" .= _daApplicationName
]
instance AWSRequest DeleteApplication where
type Sv DeleteApplication = CodeDeploy
type Rs DeleteApplication = DeleteApplicationResponse
request = post "DeleteApplication"
response = nullResponse DeleteApplicationResponse
| kim/amazonka | amazonka-codedeploy/gen/Network/AWS/CodeDeploy/DeleteApplication.hs | mpl-2.0 | 3,156 | 0 | 9 | 653 | 357 | 218 | 139 | 49 | 1 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hi-IN">
<title>Support for the Open API Specification | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | veggiespam/zap-extensions | addOns/openapi/src/main/javahelp/org/zaproxy/zap/extension/openapi/resources/help_hi_IN/helpset_hi_IN.hs | apache-2.0 | 1,000 | 85 | 52 | 164 | 406 | 214 | 192 | -1 | -1 |
{-# LANGUAGE Safe #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.Parsec.ByteString
-- Copyright : (c) Paolo Martini 2007
-- License : BSD-style (see the LICENSE file)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Convinience definitions for working with 'C.ByteString's.
--
-----------------------------------------------------------------------------
module Text.Parsec.ByteString
( Parser, GenParser, parseFromFile
) where
import Text.Parsec.Error
import Text.Parsec.Prim
import qualified Data.ByteString.Char8 as C
type Parser = Parsec C.ByteString ()
type GenParser t st = Parsec C.ByteString st
-- | @parseFromFile p filePath@ runs a strict bytestring parser @p@ on the
-- input read from @filePath@ using 'ByteString.Char8.readFile'. Returns either a 'ParseError'
-- ('Left') or a value of type @a@ ('Right').
--
-- > main = do{ result <- parseFromFile numbers "digits.txt"
-- > ; case result of
-- > Left err -> print err
-- > Right xs -> print (sum xs)
-- > }
parseFromFile :: Parser a -> FilePath -> IO (Either ParseError a)
parseFromFile p fname
= do input <- C.readFile fname
return (runP p () fname input)
| aslatter/parsec | src/Text/Parsec/ByteString.hs | bsd-2-clause | 1,346 | 0 | 10 | 288 | 161 | 99 | 62 | 12 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Stack.Setup
( setupEnv
, ensureGHC
, SetupOpts (..)
) where
import Control.Applicative
import Control.Exception.Enclosed (catchIO)
import Control.Monad (liftM, when, join, void)
import Control.Monad.Catch
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger
import Control.Monad.Reader (MonadReader, ReaderT (..), asks)
import Control.Monad.State (get, put, modify)
import Control.Monad.Trans.Control
import Data.Aeson.Extended
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import Data.Conduit (Conduit, ($$), (=$), await, yield, awaitForever)
import Data.Conduit.Lift (evalStateC)
import qualified Data.Conduit.List as CL
import Data.IORef
import Data.List (intercalate)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (mapMaybe, catMaybes, fromMaybe)
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime)
import Data.Typeable (Typeable)
import qualified Data.Yaml as Yaml
import Distribution.System (OS (..), Arch (..), Platform (..))
import Distribution.Text (simpleParse)
import Network.HTTP.Client.Conduit
import Network.HTTP.Download (verifiedDownload, DownloadRequest(..), drRetriesDefault)
import Path
import Path.IO
import Prelude -- Fix AMP warning
import Safe (headMay, readMay)
import Stack.Build.Types
import Stack.Constants (distRelativeDir)
import Stack.GhcPkg (createDatabase, getCabalPkgVer, getGlobalDB)
import Stack.Solver (getGhcVersion)
import Stack.Types
import Stack.Types.StackT
import System.Directory (createDirectoryIfMissing, removeFile)
import System.Environment (getExecutablePath)
import System.Exit (ExitCode (ExitSuccess))
import System.FilePath (searchPathSeparator)
import qualified System.FilePath as FP
import System.IO.Temp (withSystemTempDirectory)
import System.Process (rawSystem)
import System.Process.Read
data SetupOpts = SetupOpts
{ soptsInstallIfMissing :: !Bool
, soptsUseSystem :: !Bool
, soptsExpected :: !Version
, soptsStackYaml :: !(Maybe (Path Abs File))
-- ^ If we got the desired GHC version from that file
, soptsForceReinstall :: !Bool
, soptsSanityCheck :: !Bool
-- ^ Run a sanity check on the selected GHC
, soptsSkipGhcCheck :: !Bool
-- ^ Don't check for a compatible GHC version/architecture
, soptsSkipMsys :: !Bool
-- ^ Do not use a custom msys installation on Windows
}
deriving Show
data SetupException = UnsupportedSetupCombo OS Arch
| MissingDependencies [String]
| UnknownGHCVersion Text Version (Set MajorVersion)
| UnknownOSKey Text
| GHCSanityCheckCompileFailed ReadProcessException (Path Abs File)
deriving Typeable
instance Exception SetupException
instance Show SetupException where
show (UnsupportedSetupCombo os arch) = concat
[ "I don't know how to install GHC for "
, show (os, arch)
, ", please install manually"
]
show (MissingDependencies tools) =
"The following executables are missing and must be installed: " ++
intercalate ", " tools
show (UnknownGHCVersion oskey version known) = concat
[ "No information found for GHC version "
, versionString version
, ".\nSupported GHC major versions for OS key '" ++ T.unpack oskey ++ "': "
, intercalate ", " (map show $ Set.toList known)
]
show (UnknownOSKey oskey) =
"Unable to find installation URLs for OS key: " ++
T.unpack oskey
show (GHCSanityCheckCompileFailed e ghc) = concat
[ "The GHC located at "
, toFilePath ghc
, " failed to compile a sanity check. Please see:\n\n"
, " https://github.com/commercialhaskell/stack/wiki/Downloads\n\n"
, "for more information. Exception was:\n"
, show e
]
-- | Modify the environment variables (like PATH) appropriately, possibly doing installation too
setupEnv :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasBuildConfig env, HasHttpManager env, MonadBaseControl IO m)
=> m EnvConfig
setupEnv = do
bconfig <- asks getBuildConfig
let platform = getPlatform bconfig
sopts = SetupOpts
{ soptsInstallIfMissing = configInstallGHC $ bcConfig bconfig
, soptsUseSystem = configSystemGHC $ bcConfig bconfig
, soptsExpected = bcGhcVersionExpected bconfig
, soptsStackYaml = Just $ bcStackYaml bconfig
, soptsForceReinstall = False
, soptsSanityCheck = False
, soptsSkipGhcCheck = configSkipGHCCheck $ bcConfig bconfig
, soptsSkipMsys = configSkipMsys $ bcConfig bconfig
}
mghcBin <- ensureGHC sopts
menv0 <- getMinimalEnvOverride
-- Modify the initial environment to include the GHC path, if a local GHC
-- is being used
let env0 = case mghcBin of
Nothing -> unEnvOverride menv0
Just ghcBin ->
let x = unEnvOverride menv0
mpath = Map.lookup "PATH" x
path = T.intercalate (T.singleton searchPathSeparator)
$ map (stripTrailingSlashT . T.pack) ghcBin
++ maybe [] return mpath
in Map.insert "PATH" path x
-- Remove potentially confusing environment variables
env1 = Map.delete "GHC_PACKAGE_PATH"
$ Map.delete "HASKELL_PACKAGE_SANDBOX"
$ Map.delete "HASKELL_PACKAGE_SANDBOXES"
$ Map.delete "HASKELL_DIST_DIR"
env0
menv1 <- mkEnvOverride platform env1
ghcVer <- getGhcVersion menv1
cabalVer <- getCabalPkgVer menv1
let envConfig0 = EnvConfig
{ envConfigBuildConfig = bconfig
, envConfigCabalVersion = cabalVer
, envConfigGhcVersion = ghcVer
}
-- extra installation bin directories
mkDirs <- runReaderT extraBinDirs envConfig0
let mpath = Map.lookup "PATH" env1
mkDirs' = map toFilePath . mkDirs
depsPath = augmentPath (mkDirs' False) mpath
localsPath = augmentPath (mkDirs' True) mpath
deps <- runReaderT packageDatabaseDeps envConfig0
createDatabase menv1 deps
localdb <- runReaderT packageDatabaseLocal envConfig0
createDatabase menv1 localdb
globalDB <- mkEnvOverride platform env1 >>= getGlobalDB
let mkGPP locals = T.pack $ intercalate [searchPathSeparator] $ concat
[ [toFilePathNoTrailingSlash localdb | locals]
, [toFilePathNoTrailingSlash deps]
, [toFilePathNoTrailingSlash globalDB]
]
distDir <- runReaderT distRelativeDir envConfig0
executablePath <- liftIO getExecutablePath
envRef <- liftIO $ newIORef Map.empty
let getEnvOverride' es = do
m <- readIORef envRef
case Map.lookup es m of
Just eo -> return eo
Nothing -> do
eo <- mkEnvOverride platform
$ Map.insert "PATH" (if esIncludeLocals es then localsPath else depsPath)
$ (if esIncludeGhcPackagePath es
then Map.insert "GHC_PACKAGE_PATH" (mkGPP (esIncludeLocals es))
else id)
$ (if esStackExe es
then Map.insert "STACK_EXE" (T.pack executablePath)
else id)
-- For reasoning and duplication, see: https://github.com/fpco/stack/issues/70
$ Map.insert "HASKELL_PACKAGE_SANDBOX" (T.pack $ toFilePathNoTrailingSlash deps)
$ Map.insert "HASKELL_PACKAGE_SANDBOXES"
(T.pack $ if esIncludeLocals es
then intercalate [searchPathSeparator]
[ toFilePathNoTrailingSlash localdb
, toFilePathNoTrailingSlash deps
, ""
]
else intercalate [searchPathSeparator]
[ toFilePathNoTrailingSlash deps
, ""
])
$ Map.insert "HASKELL_DIST_DIR" (T.pack $ toFilePathNoTrailingSlash distDir)
$ env1
!() <- atomicModifyIORef envRef $ \m' ->
(Map.insert es eo m', ())
return eo
return EnvConfig
{ envConfigBuildConfig = bconfig
{ bcConfig = (bcConfig bconfig) { configEnvOverride = getEnvOverride' }
}
, envConfigCabalVersion = cabalVer
, envConfigGhcVersion = ghcVer
}
-- | Augment the PATH environment variable with the given extra paths
augmentPath :: [FilePath] -> Maybe Text -> Text
augmentPath dirs mpath =
T.pack $ intercalate [searchPathSeparator]
(map stripTrailingSlashS dirs ++ maybe [] (return . T.unpack) mpath)
where
stripTrailingSlashS = T.unpack . stripTrailingSlashT . T.pack
stripTrailingSlashT :: Text -> Text
stripTrailingSlashT t = fromMaybe t $ T.stripSuffix
(T.singleton FP.pathSeparator)
t
-- | Ensure GHC is installed and provide the PATHs to add if necessary
ensureGHC :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> SetupOpts
-> m (Maybe [FilePath])
ensureGHC sopts = do
-- Check the available GHCs
menv0 <- getMinimalEnvOverride
msystem <-
if soptsUseSystem sopts
then getSystemGHC menv0
else return Nothing
Platform expectedArch _ <- asks getPlatform
let needLocal = case msystem of
Nothing -> True
Just _ | soptsSkipGhcCheck sopts -> False
Just (system, arch) ->
-- we allow a newer version of GHC within the same major series
getMajorVersion system /= getMajorVersion expected ||
expected > system ||
arch /= expectedArch
-- If we need to install a GHC, try to do so
mpaths <- if needLocal
then do
config <- asks getConfig
let tools =
case configPlatform config of
Platform _ os | isWindows os ->
($(mkPackageName "ghc"), Just expected)
: (if soptsSkipMsys sopts
then []
else [($(mkPackageName "git"), Nothing)])
_ ->
[ ($(mkPackageName "ghc"), Just expected)
]
-- Avoid having to load it twice
siRef <- liftIO $ newIORef Nothing
manager <- asks getHttpManager
let getSetupInfo' = liftIO $ do
msi <- readIORef siRef
case msi of
Just si -> return si
Nothing -> do
si <- getSetupInfo manager
writeIORef siRef $ Just si
return si
installed <- runReaderT listInstalled config
idents <- mapM (ensureTool menv0 sopts installed getSetupInfo' msystem) tools
paths <- runReaderT (mapM binDirs $ catMaybes idents) config
return $ Just $ map toFilePathNoTrailingSlash $ concat paths
else return Nothing
when (soptsSanityCheck sopts) $ do
menv <-
case mpaths of
Nothing -> return menv0
Just paths -> do
config <- asks getConfig
let m0 = unEnvOverride menv0
path0 = Map.lookup "PATH" m0
path = augmentPath paths path0
m = Map.insert "PATH" path m0
mkEnvOverride (configPlatform config) m
sanityCheck menv
return mpaths
where
expected = soptsExpected sopts
-- | Get the major version of the system GHC, if available
getSystemGHC :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m) => EnvOverride -> m (Maybe (Version, Arch))
getSystemGHC menv = do
exists <- doesExecutableExist menv "ghc"
if exists
then do
eres <- tryProcessStdout Nothing menv "ghc" ["--info"]
return $ do
Right bs <- Just eres
pairs <- readMay $ S8.unpack bs :: Maybe [(String, String)]
version <- lookup "Project version" pairs >>= parseVersionFromString
arch <- lookup "Target platform" pairs >>= simpleParse . takeWhile (/= '-')
Just (version, arch)
else return Nothing
data DownloadPair = DownloadPair Version Text
deriving Show
instance FromJSON DownloadPair where
parseJSON = withObject "DownloadPair" $ \o -> DownloadPair
<$> o .: "version"
<*> o .: "url"
data SetupInfo = SetupInfo
{ siSevenzExe :: Text
, siSevenzDll :: Text
, siPortableGit :: DownloadPair
, siGHCs :: Map Text (Map MajorVersion DownloadPair)
}
deriving Show
instance FromJSON SetupInfo where
parseJSON = withObject "SetupInfo" $ \o -> SetupInfo
<$> o .: "sevenzexe"
<*> o .: "sevenzdll"
<*> o .: "portable-git"
<*> o .: "ghc"
-- | Download the most recent SetupInfo
getSetupInfo :: (MonadIO m, MonadThrow m) => Manager -> m SetupInfo
getSetupInfo manager = do
bss <- liftIO $ flip runReaderT manager
$ withResponse req $ \res -> responseBody res $$ CL.consume
let bs = S8.concat bss
either throwM return $ Yaml.decodeEither' bs
where
req = "https://raw.githubusercontent.com/fpco/stackage-content/master/stack/stack-setup.yaml"
markInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m)
=> PackageIdentifier -- ^ e.g., ghc-7.8.4, git-2.4.0.1
-> m ()
markInstalled ident = do
dir <- asks $ configLocalPrograms . getConfig
fpRel <- parseRelFile $ packageIdentifierString ident ++ ".installed"
liftIO $ writeFile (toFilePath $ dir </> fpRel) "installed"
unmarkInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m)
=> PackageIdentifier
-> m ()
unmarkInstalled ident = do
dir <- asks $ configLocalPrograms . getConfig
fpRel <- parseRelFile $ packageIdentifierString ident ++ ".installed"
removeFileIfExists $ dir </> fpRel
listInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m)
=> m [PackageIdentifier]
listInstalled = do
dir <- asks $ configLocalPrograms . getConfig
liftIO $ createDirectoryIfMissing True $ toFilePath dir
(_, files) <- listDirectory dir
return $ mapMaybe toIdent files
where
toIdent fp = do
x <- T.stripSuffix ".installed" $ T.pack $ toFilePath $ filename fp
parsePackageIdentifierFromString $ T.unpack x
installDir :: (MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m)
=> PackageIdentifier
-> m (Path Abs Dir)
installDir ident = do
config <- asks getConfig
reldir <- parseRelDir $ packageIdentifierString ident
return $ configLocalPrograms config </> reldir
-- | Binary directories for the given installed package
binDirs :: (MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m)
=> PackageIdentifier
-> m [Path Abs Dir]
binDirs ident = do
config <- asks getConfig
dir <- installDir ident
case (configPlatform config, packageNameString $ packageIdentifierName ident) of
(Platform _ (isWindows -> True), "ghc") -> return
[ dir </> $(mkRelDir "bin")
, dir </> $(mkRelDir "mingw") </> $(mkRelDir "bin")
]
(Platform _ (isWindows -> True), "git") -> return
[ dir </> $(mkRelDir "cmd")
, dir </> $(mkRelDir "usr") </> $(mkRelDir "bin")
]
(_, "ghc") -> return
[ dir </> $(mkRelDir "bin")
]
(Platform _ x, tool) -> do
$logWarn $ "binDirs: unexpected OS/tool combo: " <> T.pack (show (x, tool))
return []
ensureTool :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> EnvOverride
-> SetupOpts
-> [PackageIdentifier] -- ^ already installed
-> m SetupInfo
-> Maybe (Version, Arch) -- ^ installed GHC
-> (PackageName, Maybe Version)
-> m (Maybe PackageIdentifier)
ensureTool menv sopts installed getSetupInfo' msystem (name, mversion)
| not $ null available = return $ Just $ PackageIdentifier name $ maximum available
| not $ soptsInstallIfMissing sopts =
if name == $(mkPackageName "ghc")
then do
Platform arch _ <- asks getPlatform
throwM $ GHCVersionMismatch msystem (soptsExpected sopts, arch) (soptsStackYaml sopts)
else do
$logWarn $ "Continuing despite missing tool: " <> T.pack (packageNameString name)
return Nothing
| otherwise = do
si <- getSetupInfo'
(pair@(DownloadPair version _), installer) <-
case packageNameString name of
"git" -> do
let pair = siPortableGit si
return (pair, installGitWindows)
"ghc" -> do
osKey <- getOSKey menv
pairs <-
case Map.lookup osKey $ siGHCs si of
Nothing -> throwM $ UnknownOSKey osKey
Just pairs -> return pairs
version <-
case mversion of
Nothing -> error "invariant violated: ghc must have a version"
Just version -> return version
pair <-
case Map.lookup (getMajorVersion version) pairs of
Nothing -> throwM $ UnknownGHCVersion osKey version (Map.keysSet pairs)
Just pair -> return pair
platform <- asks $ configPlatform . getConfig
let installer =
case platform of
Platform _ os | isWindows os -> installGHCWindows
_ -> installGHCPosix
return (pair, installer)
x -> error $ "Invariant violated: ensureTool on " ++ x
let ident = PackageIdentifier name version
(file, at) <- downloadPair pair ident
dir <- installDir ident
unmarkInstalled ident
installer si file at dir ident
markInstalled ident
return $ Just ident
where
available
| soptsForceReinstall sopts = []
| otherwise = filter goodVersion
$ map packageIdentifierVersion
$ filter (\pi' -> packageIdentifierName pi' == name) installed
goodVersion =
case mversion of
Nothing -> const True
Just expected -> \actual ->
getMajorVersion expected == getMajorVersion actual &&
actual >= expected
getOSKey :: (MonadReader env m, MonadThrow m, HasConfig env, MonadLogger m, MonadIO m, MonadCatch m, MonadBaseControl IO m)
=> EnvOverride -> m Text
getOSKey menv = do
platform <- asks $ configPlatform . getConfig
case platform of
Platform I386 Linux -> ("linux32" <>) <$> getLinuxSuffix
Platform X86_64 Linux -> ("linux64" <>) <$> getLinuxSuffix
Platform I386 OSX -> return "macosx"
Platform X86_64 OSX -> return "macosx"
Platform I386 FreeBSD -> return "freebsd32"
Platform X86_64 FreeBSD -> return "freebsd64"
Platform I386 OpenBSD -> return "openbsd32"
Platform X86_64 OpenBSD -> return "openbsd64"
Platform I386 Windows -> return "windows32"
Platform X86_64 Windows -> return "windows64"
Platform I386 (OtherOS "windowsintegersimple") -> return "windowsintegersimple32"
Platform X86_64 (OtherOS "windowsintegersimple") -> return "windowsintegersimple64"
Platform arch os -> throwM $ UnsupportedSetupCombo os arch
where
getLinuxSuffix = do
executablePath <- liftIO getExecutablePath
elddOut <- tryProcessStdout Nothing menv "ldd" [executablePath]
return $ case elddOut of
Left _ -> ""
Right lddOut -> if hasLineWithFirstWord "libgmp.so.3" lddOut then "-gmp4" else ""
hasLineWithFirstWord w =
elem (Just w) . map (headMay . T.words) . T.lines . T.decodeUtf8With T.lenientDecode
downloadPair :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> DownloadPair
-> PackageIdentifier
-> m (Path Abs File, ArchiveType)
downloadPair (DownloadPair _ url) ident = do
config <- asks getConfig
at <-
case extension of
".tar.xz" -> return TarXz
".tar.bz2" -> return TarBz2
".7z.exe" -> return SevenZ
_ -> error $ "Unknown extension: " ++ extension
relfile <- parseRelFile $ packageIdentifierString ident ++ extension
let path = configLocalPrograms config </> relfile
chattyDownload (packageIdentifierText ident) url path
return (path, at)
where
extension =
loop $ T.unpack url
where
loop fp
| ext `elem` [".tar", ".bz2", ".xz", ".exe", ".7z"] = loop fp' ++ ext
| otherwise = ""
where
(fp', ext) = FP.splitExtension fp
data ArchiveType
= TarBz2
| TarXz
| SevenZ
installGHCPosix :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> SetupInfo
-> Path Abs File
-> ArchiveType
-> Path Abs Dir
-> PackageIdentifier
-> m ()
installGHCPosix _ archiveFile archiveType destDir ident = do
menv <- getMinimalEnvOverride
zipTool <-
case archiveType of
TarXz -> return "xz"
TarBz2 -> return "bzip2"
SevenZ -> error "Don't know how to deal with .7z files on non-Windows"
checkDependencies $ zipTool : ["make", "tar"]
withSystemTempDirectory "stack-setup" $ \root' -> do
root <- parseAbsDir root'
dir <- liftM (root Path.</>) $ parseRelDir $ packageIdentifierString ident
$logSticky $ "Unpacking GHC ..."
$logDebug $ "Unpacking " <> T.pack (toFilePath archiveFile)
readInNull root "tar" menv ["xf", toFilePath archiveFile] Nothing
$logSticky "Configuring GHC ..."
readInNull dir (toFilePath $ dir Path.</> $(mkRelFile "configure"))
menv ["--prefix=" ++ toFilePath destDir] Nothing
$logSticky "Installing GHC ..."
readInNull dir "make" menv ["install"] Nothing
$logStickyDone $ "Installed GHC."
$logDebug $ "GHC installed to " <> T.pack (toFilePath destDir)
where
-- | Check if given processes appear to be present, throwing an exception if
-- missing.
checkDependencies :: (MonadIO m, MonadThrow m, MonadReader env m, HasConfig env)
=> [String] -> m ()
checkDependencies tools = do
menv <- getMinimalEnvOverride
missing <- liftM catMaybes $ mapM (check menv) tools
if null missing
then return ()
else throwM $ MissingDependencies missing
where
check menv tool = do
exists <- doesExecutableExist menv tool
return $ if exists then Nothing else Just tool
installGHCWindows :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> SetupInfo
-> Path Abs File
-> ArchiveType
-> Path Abs Dir
-> PackageIdentifier
-> m ()
installGHCWindows si archiveFile archiveType destDir _ = do
suffix <-
case archiveType of
TarXz -> return ".xz"
TarBz2 -> return ".bz2"
_ -> error $ "GHC on Windows must be a tarball file"
tarFile <-
case T.stripSuffix suffix $ T.pack $ toFilePath archiveFile of
Nothing -> error $ "Invalid GHC filename: " ++ show archiveFile
Just x -> parseAbsFile $ T.unpack x
config <- asks getConfig
run7z <- setup7z si config
run7z (parent archiveFile) archiveFile
run7z (parent archiveFile) tarFile
liftIO (removeFile $ toFilePath tarFile) `catchIO` \e ->
$logWarn (T.concat
[ "Exception when removing "
, T.pack $ toFilePath tarFile
, ": "
, T.pack $ show e
])
$logInfo $ "GHC installed to " <> T.pack (toFilePath destDir)
installGitWindows :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m)
=> SetupInfo
-> Path Abs File
-> ArchiveType
-> Path Abs Dir
-> PackageIdentifier
-> m ()
installGitWindows si archiveFile archiveType destDir _ = do
case archiveType of
SevenZ -> return ()
_ -> error $ "Git on Windows must be a 7z archive"
config <- asks getConfig
run7z <- setup7z si config
run7z destDir archiveFile
-- | Download 7z as necessary, and get a function for unpacking things.
--
-- Returned function takes an unpack directory and archive.
setup7z :: (MonadReader env m, HasHttpManager env, MonadThrow m, MonadIO m, MonadIO n, MonadLogger m, MonadBaseControl IO m)
=> SetupInfo
-> Config
-> m (Path Abs Dir -> Path Abs File -> n ())
setup7z si config = do
chattyDownload "7z.dll" (siSevenzDll si) dll
chattyDownload "7z.exe" (siSevenzExe si) exe
return $ \outdir archive -> liftIO $ do
ec <- rawSystem (toFilePath exe)
[ "x"
, "-o" ++ toFilePath outdir
, "-y"
, toFilePath archive
]
when (ec /= ExitSuccess)
$ error $ "Problem while decompressing " ++ toFilePath archive
where
dir = configLocalPrograms config </> $(mkRelDir "7z")
exe = dir </> $(mkRelFile "7z.exe")
dll = dir </> $(mkRelFile "7z.dll")
chattyDownload :: (MonadReader env m, HasHttpManager env, MonadIO m, MonadLogger m, MonadThrow m, MonadBaseControl IO m)
=> Text
-> Text -- ^ URL
-> Path Abs File -- ^ destination
-> m ()
chattyDownload label url path = do
req <- parseUrl $ T.unpack url
$logSticky $ T.concat
[ "Preparing to download "
, label
, " ..."
]
$logDebug $ T.concat
[ "Downloading from "
, url
, " to "
, T.pack $ toFilePath path
, " ..."
]
let dReq = DownloadRequest
{ drRequest = req
, drHashChecks = []
, drLengthCheck = Nothing
, drRetries = drRetriesDefault
}
runInBase <- liftBaseWith $ \run -> return (void . run)
x <- verifiedDownload dReq path (chattyDownloadProgress runInBase)
if x
then $logStickyDone ("Downloaded " <> label <> ".")
else $logStickyDone "Already downloaded."
where
chattyDownloadProgress runInBase = do
_ <- liftIO $ runInBase $ $logSticky $
label <> ": download has begun"
CL.map (Sum . S.length)
=$ chunksOverTime 1
=$ go
where
go = evalStateC 0 $ awaitForever $ \(Sum size) -> do
modify (+ size)
totalSoFar <- get
liftIO $ runInBase $ $logSticky $
label <> ": " <> T.pack (show totalSoFar) <> " bytes downloaded..."
-- Await eagerly (collect with monoidal append),
-- but space out yields by at least the given amount of time.
-- The final yield may come sooner, and may be a superfluous mempty.
-- Note that Integer and Float literals can be turned into NominalDiffTime
-- (these literals are interpreted as "seconds")
chunksOverTime :: (Monoid a, MonadIO m) => NominalDiffTime -> Conduit a m a
chunksOverTime diff = do
currentTime <- liftIO getCurrentTime
evalStateC (currentTime, mempty) go
where
-- State is a tuple of:
-- * the last time a yield happened (or the beginning of the sink)
-- * the accumulated awaits since the last yield
go = await >>= \case
Nothing -> do
(_, acc) <- get
yield acc
Just a -> do
(lastTime, acc) <- get
let acc' = acc <> a
currentTime <- liftIO getCurrentTime
if diff < diffUTCTime currentTime lastTime
then put (currentTime, mempty) >> yield acc'
else put (lastTime, acc')
go
-- | Perform a basic sanity check of GHC
sanityCheck :: (MonadIO m, MonadMask m, MonadLogger m, MonadBaseControl IO m)
=> EnvOverride
-> m ()
sanityCheck menv = withSystemTempDirectory "stack-sanity-check" $ \dir -> do
dir' <- parseAbsDir dir
let fp = toFilePath $ dir' </> $(mkRelFile "Main.hs")
liftIO $ writeFile fp $ unlines
[ "import Distribution.Simple" -- ensure Cabal library is present
, "main = putStrLn \"Hello World\""
]
ghc <- join $ findExecutable menv "ghc"
$logDebug $ "Performing a sanity check on: " <> T.pack (toFilePath ghc)
eres <- tryProcessStdout (Just dir') menv "ghc"
[ fp
, "-no-user-package-db"
]
case eres of
Left e -> throwM $ GHCSanityCheckCompileFailed e ghc
Right _ -> return () -- TODO check that the output of running the command is correct
toFilePathNoTrailingSlash :: Path loc Dir -> FilePath
toFilePathNoTrailingSlash = FP.dropTrailingPathSeparator . toFilePath
| k-bx/stack | src/Stack/Setup.hs | bsd-3-clause | 31,313 | 0 | 30 | 10,294 | 7,738 | 3,853 | 3,885 | 650 | 15 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module HsFirelib (standardSpread) where
import qualified Language.C.Inline as C (include)
import qualified Language.C.Inline.Unsafe as C
import Foreign.C.Types
import Foreign.Ptr
import System.IO.Unsafe (unsafePerformIO)
import Behave (SpreadEnv(..), Spread(..), SpreadAtAzimuth(..))
import Behave.Units
C.include "fireLib.h"
newtype Catalog = Catalog (Ptr ())
standardCatalog :: IO Catalog
standardCatalog
= fmap Catalog [C.exp| void *{Fire_FuelCatalogCreateStandard("standard", 20)}|]
initFuel :: Catalog -> Int -> SpreadEnv -> IO ()
initFuel (Catalog catalog) fuel SpreadEnv{..} = do
let d1hr = realToFrac (_seD1hr /~ one)
d10hr = realToFrac (_seD10hr /~ one)
d100hr = realToFrac (_seD100hr /~ one)
herb = realToFrac (_seHerb /~ one)
wood = realToFrac (_seWood /~ one)
model = fromIntegral fuel
windFpm = realToFrac (_seWindSpeed /~ footMin)
windDeg = realToFrac (_seWindAzimuth /~ degree)
slope = realToFrac (_seSlope /~ one)
aspect = realToFrac (_seAspect /~ degree)
[C.block| void {
double moisture[6] = { $(double d1hr)
, $(double d10hr)
, $(double d100hr)
, 0
, $(double herb)
, $(double wood)
};
Fire_SpreadNoWindNoSlope($(void *catalog), $(size_t model), moisture);
Fire_SpreadWindSlopeMax( $(void *catalog), $(size_t model)
, $(double windFpm), $(double windDeg)
, $(double slope), $(double aspect));
double az = Fuel_AzimuthMax( (FuelCatalogPtr)$(void *catalog)
, $(size_t model));
size_t w = FIRE_BYRAMS | FIRE_FLAME;
Fire_SpreadAtAzimuth( $(void *catalog), $(size_t model), az, w);
} |]
setAzimuth :: Catalog -> Int -> Azimuth -> IO ()
setAzimuth (Catalog catalog) fuel azimuth = do
let az = realToFrac (azimuth /~ degree)
model = fromIntegral fuel
[C.block| void {
size_t w = FIRE_BYRAMS | FIRE_FLAME;
Fire_SpreadAtAzimuth( $(void *catalog), $(size_t model), $(double az), w);
} |]
destroyCatalog :: Catalog -> IO ()
destroyCatalog (Catalog catalog)
= [C.exp|void {Fire_FuelCatalogDestroy($(void *catalog))}|]
withCatalog :: (Catalog -> IO a) -> IO a
withCatalog f = do
c <- standardCatalog
ret <- f c
destroyCatalog c
return ret
standardSpread :: Int -> SpreadEnv -> Azimuth -> (Spread, SpreadAtAzimuth)
standardSpread fuel env azimuth = unsafePerformIO $ do
let f = fromIntegral fuel
d g = fmap (g . realToFrac)
withCatalog $ \catalog@(Catalog c) -> do
initFuel catalog fuel env
spread <- Spread
<$> d (*~btuSqFtMin) [C.exp|double {
Fuel_RxIntensity((FuelCatalogPtr)$(void *c), $(size_t f))}|]
<*> d (*~footMin) [C.exp|double {
Fuel_Spread0((FuelCatalogPtr)$(void *c), $(size_t f))}|]
<*> d (*~btuSqFt) [C.exp|double {
Fuel_HeatPerUnitArea((FuelCatalogPtr)$(void *c), $(size_t f))}|]
<*> d (*~one) [C.exp|double {
Fuel_PhiEffWind((FuelCatalogPtr)$(void *c), $(size_t f))}|]
<*> d (*~footMin) [C.exp|double {
Fuel_SpreadMax((FuelCatalogPtr)$(void *c), $(size_t f))}|]
<*> d (*~degree) [C.exp|double {
Fuel_AzimuthMax((FuelCatalogPtr)$(void *c), $(size_t f))}|]
<*> d (*~one) [C.exp|double {
Fuel_Eccentricity((FuelCatalogPtr)$(void *c), $(size_t f))}|]
<*> d (*~btuFtSec) [C.exp|double {
Fuel_ByramsIntensity((FuelCatalogPtr)$(void *c), $(size_t f))}|]
<*> d (*~foot) [C.exp|double {
Fuel_FlameLength((FuelCatalogPtr)$(void *c), $(size_t f))}|]
setAzimuth catalog fuel azimuth
spreadAz <- SpreadAtAzimuth
<$> d (*~footMin) [C.exp|double {
Fuel_SpreadAny((FuelCatalogPtr)$(void *c), $(size_t f))}|]
<*> d (*~btuFtSec) [C.exp|double {
Fuel_ByramsIntensity((FuelCatalogPtr)$(void *c), $(size_t f))}|]
<*> d (*~foot) [C.exp|double {
Fuel_FlameLength((FuelCatalogPtr)$(void *c), $(size_t f))}|]
return (spread, spreadAz)
| albertov/behave-hs | test/HsFirelib.hs | bsd-3-clause | 4,370 | 0 | 23 | 1,193 | 872 | 488 | 384 | 65 | 1 |
{-# LANGUAGE BangPatterns, NamedFieldPuns, GeneralizedNewtypeDeriving #-}
module Distribution.Server.Features.Search.ExtractNameTerms (
extractPackageNameTerms,
extractModuleNameTerms,
) where
import Data.Text (Text)
import qualified Data.Text as T
import Data.Char (isUpper, isDigit)
import Data.List
import Data.List.Split hiding (Splitter)
import Data.Maybe (maybeToList)
import Data.Functor.Identity
import Control.Monad
import Control.Monad.List
import Control.Monad.Writer
import Control.Monad.State
import Control.Applicative
extractModuleNameTerms :: String -> [Text]
extractModuleNameTerms modname =
map T.toCaseFold $
nub $
map T.pack $
flip runSplitter modname $ do
_ <- forEachPart splitDot
_ <- forEachPart splitCamlCase
satisfy (not . singleChar)
get >>= emit
extractPackageNameTerms :: String -> [Text]
extractPackageNameTerms pkgname =
map T.toCaseFold $
nub $
map T.pack $
flip runSplitter pkgname $ do
fstComponentHyphen <- forEachPart splitHyphen
satisfy (`notElem` ["hs", "haskell"])
_ <- forEachPart stripPrefixH
fstComponentCaml <- forEachPart splitCamlCase
fstComponent2 <- forEachPart splitOn2
when (fstComponentHyphen && fstComponentCaml && fstComponent2) $ do
forEachPartAndWhole stripPrefix_h
_ <- forEachPart (maybeToList . stripPrefix "lib")
_ <- forEachPart (maybeToList . stripSuffix "lib")
_ <- forEachPart stripSuffixNum
satisfy (not . singleChar)
get >>= emit
newtype Split a = Split (StateT String (ListT (WriterT [String] Identity)) a)
deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadState String)
emit :: String -> Split ()
emit x = Split (lift (lift (tell [x])))
forEach :: [a] -> Split a
forEach = msum . map return
runSplitter :: Split () -> String -> [String]
runSplitter (Split m) s = snd (runWriter (runListT (runStateT m s)))
singleChar :: String -> Bool
singleChar [_] = True
singleChar _ = False
satisfy :: (String -> Bool) -> Split ()
satisfy p = get >>= guard . p
forEachPart :: (String -> [String]) -> Split Bool
forEachPart parts = do
t <- get
case parts t of
[] -> return True
[t'] | t == t' -> return True
ts -> do emit t
(t', n) <- forEach (zip ts [1::Int ..])
put t'
return (n==1)
forEachPartAndWhole :: (String -> [String]) -> Split ()
forEachPartAndWhole parts = do
t <- get
case parts t of
[] -> return ()
ts -> forEach (t:ts) >>= put
splitDot :: String -> [String]
splitDot = split (dropBlanks $ dropDelims $ whenElt (=='.'))
splitHyphen :: String -> [String]
splitHyphen = split (dropBlanks $ dropDelims $ whenElt (=='-'))
splitCamlCase :: String -> [String]
splitCamlCase = split (dropInitBlank $ condense $ keepDelimsL $ whenElt isUpper)
stripPrefixH :: String -> [String]
stripPrefixH ('H':'S':frag) | all isUpper frag = [frag]
stripPrefixH "HTTP" = []
stripPrefixH ('H':frag@(c:_)) | isUpper c = [frag]
stripPrefixH _ = []
stripPrefix_h :: String -> [String]
stripPrefix_h "http" = []
stripPrefix_h "html" = []
stripPrefix_h ('h':'s':frag) = ['s':frag, frag]
stripPrefix_h ('h':frag) {- | Set.notMember (T.pack w) ws -} = [frag]
stripPrefix_h _ = []
stripSuffix :: String -> String -> Maybe String
stripSuffix s t = fmap reverse (stripPrefix (reverse s) (reverse t))
stripSuffixNum :: String -> [String]
stripSuffixNum s
| null rd || null rs' = []
| otherwise = [s', d]
where
rs = reverse s
(rd, rs') = span isDigit rs
d = reverse rd
s' = reverse rs'
splitOn2 :: String -> [String]
splitOn2 t =
case break (=='2') t of
(from@(_:_), '2':to@(c:_))
| not (isDigit c)
, not (length from == 1 && length to == 1)
-> [from, to]
_ -> []
-------------------
-- experiment
--
{-
main = do
pkgsFile <- readFile "pkgs3"
let pkgs :: [PackageDescription]
pkgs = map read (lines pkgsFile)
-- print "forcing pkgs..."
-- evaluate (foldl' (\a p -> seq p a) () pkgs)
sequence_
[ putStrLn $ display (packageName pkg) ++ ": " ++ display mod ++ " -> "
++ intercalate ", " (map T.unpack $ extractModuleNameTerms (display mod))
| pkg <- pkgs
, Just lib <- [library pkg]
, let mods = exposedModules lib
, mod <- mods ]
-}
| snoyberg/hackage-server | Distribution/Server/Features/Search/ExtractNameTerms.hs | bsd-3-clause | 4,522 | 0 | 16 | 1,156 | 1,478 | 760 | 718 | 108 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module ConversionTest (tests) where
import Test.Tasty
import Test.Tasty.HUnit
import DBus.UDisks2.Internal
import qualified DBus.UDisks2.Types as U
tests :: TestTree
tests = testGroup "Conversions" [errorTests]
errorTests :: TestTree
errorTests = testGroup "Errors"
[ testCase "Parse simple error type" $
parseErrorType "org.freedesktop.UDisks2.Error.NotAuthorizedCanObtain" @=? U.ErrorNotAuthorizedCanObtain
]
| rootzlevel/device-manager | test/ConversionTest.hs | bsd-3-clause | 463 | 0 | 9 | 63 | 88 | 52 | 36 | 12 | 1 |
{-
(c) The University of Glasgow 2006
Functions for working with the typechecker environment (setters, getters...).
-}
{-# LANGUAGE CPP, ExplicitForAll, FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module TcRnMonad(
module TcRnMonad,
module TcRnTypes,
module IOEnv
) where
#include "HsVersions.h"
import TcRnTypes -- Re-export all
import IOEnv -- Re-export all
import TcEvidence
import HsSyn hiding (LIE)
import HscTypes
import Module
import RdrName
import Name
import Type
import TcType
import InstEnv
import FamInstEnv
import PrelNames
import Id
import VarSet
import VarEnv
import ErrUtils
import SrcLoc
import NameEnv
import NameSet
import Bag
import Outputable
import UniqSupply
import UniqFM
import DynFlags
import StaticFlags
import FastString
import Panic
import Util
import Annotations
import BasicTypes( TopLevelFlag )
import Control.Exception
import Data.IORef
import Control.Monad
#ifdef GHCI
import qualified Data.Map as Map
#endif
{-
************************************************************************
* *
initTc
* *
************************************************************************
-}
-- | Setup the initial typechecking environment
initTc :: HscEnv
-> HscSource
-> Bool -- True <=> retain renamed syntax trees
-> Module
-> RealSrcSpan
-> TcM r
-> IO (Messages, Maybe r)
-- Nothing => error thrown by the thing inside
-- (error messages should have been printed already)
initTc hsc_env hsc_src keep_rn_syntax mod loc do_this
= do { errs_var <- newIORef (emptyBag, emptyBag) ;
tvs_var <- newIORef emptyVarSet ;
keep_var <- newIORef emptyNameSet ;
used_gre_var <- newIORef [] ;
th_var <- newIORef False ;
th_splice_var<- newIORef False ;
infer_var <- newIORef (True, emptyBag) ;
lie_var <- newIORef emptyWC ;
dfun_n_var <- newIORef emptyOccSet ;
type_env_var <- case hsc_type_env_var hsc_env of {
Just (_mod, te_var) -> return te_var ;
Nothing -> newIORef emptyNameEnv } ;
dependent_files_var <- newIORef [] ;
static_wc_var <- newIORef emptyWC ;
#ifdef GHCI
th_topdecls_var <- newIORef [] ;
th_topnames_var <- newIORef emptyNameSet ;
th_modfinalizers_var <- newIORef [] ;
th_state_var <- newIORef Map.empty ;
#endif /* GHCI */
let {
dflags = hsc_dflags hsc_env ;
maybe_rn_syntax :: forall a. a -> Maybe a ;
maybe_rn_syntax empty_val
| keep_rn_syntax = Just empty_val
| otherwise = Nothing ;
gbl_env = TcGblEnv {
#ifdef GHCI
tcg_th_topdecls = th_topdecls_var,
tcg_th_topnames = th_topnames_var,
tcg_th_modfinalizers = th_modfinalizers_var,
tcg_th_state = th_state_var,
#endif /* GHCI */
tcg_mod = mod,
tcg_src = hsc_src,
tcg_sig_of = getSigOf dflags (moduleName mod),
tcg_impl_rdr_env = Nothing,
tcg_rdr_env = emptyGlobalRdrEnv,
tcg_fix_env = emptyNameEnv,
tcg_field_env = emptyNameEnv,
tcg_default = if moduleUnitId mod == primUnitId
then Just [] -- See Note [Default types]
else Nothing,
tcg_type_env = emptyNameEnv,
tcg_type_env_var = type_env_var,
tcg_inst_env = emptyInstEnv,
tcg_fam_inst_env = emptyFamInstEnv,
tcg_ann_env = emptyAnnEnv,
tcg_th_used = th_var,
tcg_th_splice_used = th_splice_var,
tcg_exports = [],
tcg_imports = emptyImportAvails,
tcg_used_gres = used_gre_var,
tcg_dus = emptyDUs,
tcg_rn_imports = [],
tcg_rn_exports = maybe_rn_syntax [],
tcg_rn_decls = maybe_rn_syntax emptyRnGroup,
tcg_tr_module = Nothing,
tcg_binds = emptyLHsBinds,
tcg_imp_specs = [],
tcg_sigs = emptyNameSet,
tcg_ev_binds = emptyBag,
tcg_warns = NoWarnings,
tcg_anns = [],
tcg_tcs = [],
tcg_insts = [],
tcg_fam_insts = [],
tcg_rules = [],
tcg_fords = [],
tcg_vects = [],
tcg_patsyns = [],
tcg_dfun_n = dfun_n_var,
tcg_keep = keep_var,
tcg_doc_hdr = Nothing,
tcg_hpc = False,
tcg_main = Nothing,
tcg_self_boot = NoSelfBoot,
tcg_safeInfer = infer_var,
tcg_dependent_files = dependent_files_var,
tcg_tc_plugins = [],
tcg_static_wc = static_wc_var
} ;
lcl_env = TcLclEnv {
tcl_errs = errs_var,
tcl_loc = loc, -- Should be over-ridden very soon!
tcl_ctxt = [],
tcl_rdr = emptyLocalRdrEnv,
tcl_th_ctxt = topStage,
tcl_th_bndrs = emptyNameEnv,
tcl_arrow_ctxt = NoArrowCtxt,
tcl_env = emptyNameEnv,
tcl_bndrs = [],
tcl_tidy = emptyTidyEnv,
tcl_tyvars = tvs_var,
tcl_lie = lie_var,
tcl_tclvl = topTcLevel
} ;
} ;
-- OK, here's the business end!
maybe_res <- initTcRnIf 'a' hsc_env gbl_env lcl_env $
do { r <- tryM do_this
; case r of
Right res -> return (Just res)
Left _ -> return Nothing } ;
-- Check for unsolved constraints
lie <- readIORef lie_var ;
if isEmptyWC lie
then return ()
else pprPanic "initTc: unsolved constraints" (ppr lie) ;
-- Collect any error messages
msgs <- readIORef errs_var ;
let { final_res | errorsFound dflags msgs = Nothing
| otherwise = maybe_res } ;
return (msgs, final_res)
}
initTcInteractive :: HscEnv -> TcM a -> IO (Messages, Maybe a)
-- Initialise the type checker monad for use in GHCi
initTcInteractive hsc_env thing_inside
= initTc hsc_env HsSrcFile False
(icInteractiveModule (hsc_IC hsc_env))
(realSrcLocSpan interactive_src_loc)
thing_inside
where
interactive_src_loc = mkRealSrcLoc (fsLit "<interactive>") 1 1
initTcForLookup :: HscEnv -> TcM a -> IO a
-- The thing_inside is just going to look up something
-- in the environment, so we don't need much setup
initTcForLookup hsc_env thing_inside
= do { (msgs, m) <- initTcInteractive hsc_env thing_inside
; case m of
Nothing -> throwIO $ mkSrcErr $ snd msgs
Just x -> return x }
{- Note [Default types]
~~~~~~~~~~~~~~~~~~~~~~~
The Integer type is simply not available in package ghc-prim (it is
declared in integer-gmp). So we set the defaulting types to (Just
[]), meaning there are no default types, rather then Nothing, which
means "use the default default types of Integer, Double".
If you don't do this, attempted defaulting in package ghc-prim causes
an actual crash (attempting to look up the Integer type).
************************************************************************
* *
Initialisation
* *
************************************************************************
-}
initTcRnIf :: Char -- Tag for unique supply
-> HscEnv
-> gbl -> lcl
-> TcRnIf gbl lcl a
-> IO a
initTcRnIf uniq_tag hsc_env gbl_env lcl_env thing_inside
= do { us <- mkSplitUniqSupply uniq_tag ;
; us_var <- newIORef us ;
; let { env = Env { env_top = hsc_env,
env_us = us_var,
env_gbl = gbl_env,
env_lcl = lcl_env} }
; runIOEnv env thing_inside
}
{-
************************************************************************
* *
Simple accessors
* *
************************************************************************
-}
discardResult :: TcM a -> TcM ()
discardResult a = a >> return ()
getTopEnv :: TcRnIf gbl lcl HscEnv
getTopEnv = do { env <- getEnv; return (env_top env) }
getGblEnv :: TcRnIf gbl lcl gbl
getGblEnv = do { env <- getEnv; return (env_gbl env) }
updGblEnv :: (gbl -> gbl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
updGblEnv upd = updEnv (\ env@(Env { env_gbl = gbl }) ->
env { env_gbl = upd gbl })
setGblEnv :: gbl -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
setGblEnv gbl_env = updEnv (\ env -> env { env_gbl = gbl_env })
getLclEnv :: TcRnIf gbl lcl lcl
getLclEnv = do { env <- getEnv; return (env_lcl env) }
updLclEnv :: (lcl -> lcl) -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
updLclEnv upd = updEnv (\ env@(Env { env_lcl = lcl }) ->
env { env_lcl = upd lcl })
setLclEnv :: lcl' -> TcRnIf gbl lcl' a -> TcRnIf gbl lcl a
setLclEnv lcl_env = updEnv (\ env -> env { env_lcl = lcl_env })
getEnvs :: TcRnIf gbl lcl (gbl, lcl)
getEnvs = do { env <- getEnv; return (env_gbl env, env_lcl env) }
setEnvs :: (gbl', lcl') -> TcRnIf gbl' lcl' a -> TcRnIf gbl lcl a
setEnvs (gbl_env, lcl_env) = updEnv (\ env -> env { env_gbl = gbl_env, env_lcl = lcl_env })
-- Command-line flags
xoptM :: ExtensionFlag -> TcRnIf gbl lcl Bool
xoptM flag = do { dflags <- getDynFlags; return (xopt flag dflags) }
doptM :: DumpFlag -> TcRnIf gbl lcl Bool
doptM flag = do { dflags <- getDynFlags; return (dopt flag dflags) }
goptM :: GeneralFlag -> TcRnIf gbl lcl Bool
goptM flag = do { dflags <- getDynFlags; return (gopt flag dflags) }
woptM :: WarningFlag -> TcRnIf gbl lcl Bool
woptM flag = do { dflags <- getDynFlags; return (wopt flag dflags) }
setXOptM :: ExtensionFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
setXOptM flag = updEnv (\ env@(Env { env_top = top }) ->
env { env_top = top { hsc_dflags = xopt_set (hsc_dflags top) flag}} )
unsetGOptM :: GeneralFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
unsetGOptM flag = updEnv (\ env@(Env { env_top = top }) ->
env { env_top = top { hsc_dflags = gopt_unset (hsc_dflags top) flag}} )
unsetWOptM :: WarningFlag -> TcRnIf gbl lcl a -> TcRnIf gbl lcl a
unsetWOptM flag = updEnv (\ env@(Env { env_top = top }) ->
env { env_top = top { hsc_dflags = wopt_unset (hsc_dflags top) flag}} )
-- | Do it flag is true
whenDOptM :: DumpFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
whenDOptM flag thing_inside = do b <- doptM flag
when b thing_inside
whenGOptM :: GeneralFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
whenGOptM flag thing_inside = do b <- goptM flag
when b thing_inside
whenWOptM :: WarningFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
whenWOptM flag thing_inside = do b <- woptM flag
when b thing_inside
whenXOptM :: ExtensionFlag -> TcRnIf gbl lcl () -> TcRnIf gbl lcl ()
whenXOptM flag thing_inside = do b <- xoptM flag
when b thing_inside
getGhcMode :: TcRnIf gbl lcl GhcMode
getGhcMode = do { env <- getTopEnv; return (ghcMode (hsc_dflags env)) }
withDoDynamicToo :: TcRnIf gbl lcl a -> TcRnIf gbl lcl a
withDoDynamicToo m = do env <- getEnv
let dflags = extractDynFlags env
dflags' = dynamicTooMkDynamicDynFlags dflags
env' = replaceDynFlags env dflags'
setEnv env' m
getEpsVar :: TcRnIf gbl lcl (TcRef ExternalPackageState)
getEpsVar = do { env <- getTopEnv; return (hsc_EPS env) }
getEps :: TcRnIf gbl lcl ExternalPackageState
getEps = do { env <- getTopEnv; readMutVar (hsc_EPS env) }
-- | Update the external package state. Returns the second result of the
-- modifier function.
--
-- This is an atomic operation and forces evaluation of the modified EPS in
-- order to avoid space leaks.
updateEps :: (ExternalPackageState -> (ExternalPackageState, a))
-> TcRnIf gbl lcl a
updateEps upd_fn = do
traceIf (text "updating EPS")
eps_var <- getEpsVar
atomicUpdMutVar' eps_var upd_fn
-- | Update the external package state.
--
-- This is an atomic operation and forces evaluation of the modified EPS in
-- order to avoid space leaks.
updateEps_ :: (ExternalPackageState -> ExternalPackageState)
-> TcRnIf gbl lcl ()
updateEps_ upd_fn = do
traceIf (text "updating EPS_")
eps_var <- getEpsVar
atomicUpdMutVar' eps_var (\eps -> (upd_fn eps, ()))
getHpt :: TcRnIf gbl lcl HomePackageTable
getHpt = do { env <- getTopEnv; return (hsc_HPT env) }
getEpsAndHpt :: TcRnIf gbl lcl (ExternalPackageState, HomePackageTable)
getEpsAndHpt = do { env <- getTopEnv; eps <- readMutVar (hsc_EPS env)
; return (eps, hsc_HPT env) }
{-
************************************************************************
* *
Arrow scopes
* *
************************************************************************
-}
newArrowScope :: TcM a -> TcM a
newArrowScope
= updLclEnv $ \env -> env { tcl_arrow_ctxt = ArrowCtxt (tcl_rdr env) (tcl_lie env) }
-- Return to the stored environment (from the enclosing proc)
escapeArrowScope :: TcM a -> TcM a
escapeArrowScope
= updLclEnv $ \ env ->
case tcl_arrow_ctxt env of
NoArrowCtxt -> env
ArrowCtxt rdr_env lie -> env { tcl_arrow_ctxt = NoArrowCtxt
, tcl_lie = lie
, tcl_rdr = rdr_env }
{-
************************************************************************
* *
Unique supply
* *
************************************************************************
-}
newUnique :: TcRnIf gbl lcl Unique
newUnique
= do { env <- getEnv ;
let { u_var = env_us env } ;
us <- readMutVar u_var ;
case takeUniqFromSupply us of { (uniq, us') -> do {
writeMutVar u_var us' ;
return $! uniq }}}
-- NOTE 1: we strictly split the supply, to avoid the possibility of leaving
-- a chain of unevaluated supplies behind.
-- NOTE 2: we use the uniq in the supply from the MutVar directly, and
-- throw away one half of the new split supply. This is safe because this
-- is the only place we use that unique. Using the other half of the split
-- supply is safer, but slower.
newUniqueSupply :: TcRnIf gbl lcl UniqSupply
newUniqueSupply
= do { env <- getEnv ;
let { u_var = env_us env } ;
us <- readMutVar u_var ;
case splitUniqSupply us of { (us1,us2) -> do {
writeMutVar u_var us1 ;
return us2 }}}
newLocalName :: Name -> TcM Name
newLocalName name = newName (nameOccName name)
newName :: OccName -> TcM Name
newName occ
= do { uniq <- newUnique
; loc <- getSrcSpanM
; return (mkInternalName uniq occ loc) }
newSysName :: OccName -> TcM Name
newSysName occ
= do { uniq <- newUnique
; return (mkSystemName uniq occ) }
newSysLocalId :: FastString -> TcType -> TcRnIf gbl lcl TcId
newSysLocalId fs ty
= do { u <- newUnique
; return (mkSysLocal fs u ty) }
newSysLocalIds :: FastString -> [TcType] -> TcRnIf gbl lcl [TcId]
newSysLocalIds fs tys
= do { us <- newUniqueSupply
; return (zipWith (mkSysLocal fs) (uniqsFromSupply us) tys) }
instance MonadUnique (IOEnv (Env gbl lcl)) where
getUniqueM = newUnique
getUniqueSupplyM = newUniqueSupply
{-
************************************************************************
* *
Accessing input/output
* *
************************************************************************
-}
newTcRef :: a -> TcRnIf gbl lcl (TcRef a)
newTcRef = newMutVar
readTcRef :: TcRef a -> TcRnIf gbl lcl a
readTcRef = readMutVar
writeTcRef :: TcRef a -> a -> TcRnIf gbl lcl ()
writeTcRef = writeMutVar
updTcRef :: TcRef a -> (a -> a) -> TcRnIf gbl lcl ()
-- Returns ()
updTcRef ref fn = liftIO $ do { old <- readIORef ref
; writeIORef ref (fn old) }
updTcRefX :: TcRef a -> (a -> a) -> TcRnIf gbl lcl a
-- Returns previous value
updTcRefX ref fn = liftIO $ do { old <- readIORef ref
; writeIORef ref (fn old)
; return old }
{-
************************************************************************
* *
Debugging
* *
************************************************************************
-}
traceTc :: String -> SDoc -> TcRn ()
traceTc herald doc = traceTcN 1 (hang (text herald) 2 doc)
-- | Typechecker trace
traceTcN :: Int -> SDoc -> TcRn ()
traceTcN level doc
= do dflags <- getDynFlags
when (level <= traceLevel dflags && not opt_NoDebugOutput) $
traceOptTcRn Opt_D_dump_tc_trace doc
traceRn :: SDoc -> TcRn ()
traceRn = traceOptTcRn Opt_D_dump_rn_trace -- Renamer Trace
-- | Output a doc if the given 'DumpFlag' is set.
--
-- By default this logs to stdout
-- However, if the `-ddump-to-file` flag is set,
-- then this will dump output to a file
--
-- Just a wrapper for 'dumpSDoc'
traceOptTcRn :: DumpFlag -> SDoc -> TcRn ()
traceOptTcRn flag doc
= do { dflags <- getDynFlags
; when (dopt flag dflags) (traceTcRn flag doc)
}
traceTcRn :: DumpFlag -> SDoc -> TcRn ()
-- ^ Unconditionally dump some trace output
--
-- The DumpFlag is used only to set the output filename
-- for --dump-to-file, not to decide whether or not to output
-- That part is done by the caller
traceTcRn flag doc
= do { real_doc <- prettyDoc doc
; dflags <- getDynFlags
; printer <- getPrintUnqualified dflags
; liftIO $ dumpSDoc dflags printer flag "" real_doc }
where
-- Add current location if opt_PprStyle_Debug
prettyDoc :: SDoc -> TcRn SDoc
prettyDoc doc = if opt_PprStyle_Debug
then do { loc <- getSrcSpanM; return $ mkLocMessage SevOutput loc doc }
else return doc -- The full location is usually way too much
getPrintUnqualified :: DynFlags -> TcRn PrintUnqualified
getPrintUnqualified dflags
= do { rdr_env <- getGlobalRdrEnv
; return $ mkPrintUnqualified dflags rdr_env }
-- | Like logInfoTcRn, but for user consumption
printForUserTcRn :: SDoc -> TcRn ()
printForUserTcRn doc
= do { dflags <- getDynFlags
; printer <- getPrintUnqualified dflags
; liftIO (printOutputForUser dflags printer doc) }
-- | Typechecker debug
debugDumpTcRn :: SDoc -> TcRn ()
debugDumpTcRn doc = unless opt_NoDebugOutput $
traceOptTcRn Opt_D_dump_tc doc
{-
traceIf and traceHiDiffs work in the TcRnIf monad, where no RdrEnv is
available. Alas, they behave inconsistently with the other stuff;
e.g. are unaffected by -dump-to-file.
-}
traceIf, traceHiDiffs :: SDoc -> TcRnIf m n ()
traceIf = traceOptIf Opt_D_dump_if_trace
traceHiDiffs = traceOptIf Opt_D_dump_hi_diffs
traceOptIf :: DumpFlag -> SDoc -> TcRnIf m n ()
traceOptIf flag doc
= whenDOptM flag $ -- No RdrEnv available, so qualify everything
do { dflags <- getDynFlags
; liftIO (putMsg dflags doc) }
{-
************************************************************************
* *
Typechecker global environment
* *
************************************************************************
-}
setModule :: Module -> TcRn a -> TcRn a
setModule mod thing_inside = updGblEnv (\env -> env { tcg_mod = mod }) thing_inside
getIsGHCi :: TcRn Bool
getIsGHCi = do { mod <- getModule
; return (isInteractiveModule mod) }
getGHCiMonad :: TcRn Name
getGHCiMonad = do { hsc <- getTopEnv; return (ic_monad $ hsc_IC hsc) }
getInteractivePrintName :: TcRn Name
getInteractivePrintName = do { hsc <- getTopEnv; return (ic_int_print $ hsc_IC hsc) }
tcIsHsBootOrSig :: TcRn Bool
tcIsHsBootOrSig = do { env <- getGblEnv; return (isHsBootOrSig (tcg_src env)) }
tcSelfBootInfo :: TcRn SelfBootInfo
tcSelfBootInfo = do { env <- getGblEnv; return (tcg_self_boot env) }
getGlobalRdrEnv :: TcRn GlobalRdrEnv
getGlobalRdrEnv = do { env <- getGblEnv; return (tcg_rdr_env env) }
getRdrEnvs :: TcRn (GlobalRdrEnv, LocalRdrEnv)
getRdrEnvs = do { (gbl,lcl) <- getEnvs; return (tcg_rdr_env gbl, tcl_rdr lcl) }
getImports :: TcRn ImportAvails
getImports = do { env <- getGblEnv; return (tcg_imports env) }
getFixityEnv :: TcRn FixityEnv
getFixityEnv = do { env <- getGblEnv; return (tcg_fix_env env) }
extendFixityEnv :: [(Name,FixItem)] -> RnM a -> RnM a
extendFixityEnv new_bit
= updGblEnv (\env@(TcGblEnv { tcg_fix_env = old_fix_env }) ->
env {tcg_fix_env = extendNameEnvList old_fix_env new_bit})
getRecFieldEnv :: TcRn RecFieldEnv
getRecFieldEnv = do { env <- getGblEnv; return (tcg_field_env env) }
getDeclaredDefaultTys :: TcRn (Maybe [Type])
getDeclaredDefaultTys = do { env <- getGblEnv; return (tcg_default env) }
addDependentFiles :: [FilePath] -> TcRn ()
addDependentFiles fs = do
ref <- fmap tcg_dependent_files getGblEnv
dep_files <- readTcRef ref
writeTcRef ref (fs ++ dep_files)
{-
************************************************************************
* *
Error management
* *
************************************************************************
-}
getSrcSpanM :: TcRn SrcSpan
-- Avoid clash with Name.getSrcLoc
getSrcSpanM = do { env <- getLclEnv; return (RealSrcSpan (tcl_loc env)) }
setSrcSpan :: SrcSpan -> TcRn a -> TcRn a
setSrcSpan (RealSrcSpan real_loc) thing_inside
= updLclEnv (\env -> env { tcl_loc = real_loc }) thing_inside
-- Don't overwrite useful info with useless:
setSrcSpan (UnhelpfulSpan _) thing_inside = thing_inside
addLocM :: (a -> TcM b) -> Located a -> TcM b
addLocM fn (L loc a) = setSrcSpan loc $ fn a
wrapLocM :: (a -> TcM b) -> Located a -> TcM (Located b)
wrapLocM fn (L loc a) = setSrcSpan loc $ do b <- fn a; return (L loc b)
wrapLocFstM :: (a -> TcM (b,c)) -> Located a -> TcM (Located b, c)
wrapLocFstM fn (L loc a) =
setSrcSpan loc $ do
(b,c) <- fn a
return (L loc b, c)
wrapLocSndM :: (a -> TcM (b,c)) -> Located a -> TcM (b, Located c)
wrapLocSndM fn (L loc a) =
setSrcSpan loc $ do
(b,c) <- fn a
return (b, L loc c)
-- Reporting errors
getErrsVar :: TcRn (TcRef Messages)
getErrsVar = do { env <- getLclEnv; return (tcl_errs env) }
setErrsVar :: TcRef Messages -> TcRn a -> TcRn a
setErrsVar v = updLclEnv (\ env -> env { tcl_errs = v })
addErr :: MsgDoc -> TcRn () -- Ignores the context stack
addErr msg = do { loc <- getSrcSpanM; addErrAt loc msg }
failWith :: MsgDoc -> TcRn a
failWith msg = addErr msg >> failM
failAt :: SrcSpan -> MsgDoc -> TcRn a
failAt loc msg = addErrAt loc msg >> failM
addErrAt :: SrcSpan -> MsgDoc -> TcRn ()
-- addErrAt is mainly (exclusively?) used by the renamer, where
-- tidying is not an issue, but it's all lazy so the extra
-- work doesn't matter
addErrAt loc msg = do { ctxt <- getErrCtxt
; tidy_env <- tcInitTidyEnv
; err_info <- mkErrInfo tidy_env ctxt
; addLongErrAt loc msg err_info }
addErrs :: [(SrcSpan,MsgDoc)] -> TcRn ()
addErrs msgs = mapM_ add msgs
where
add (loc,msg) = addErrAt loc msg
checkErr :: Bool -> MsgDoc -> TcRn ()
-- Add the error if the bool is False
checkErr ok msg = unless ok (addErr msg)
warnIf :: Bool -> MsgDoc -> TcRn ()
warnIf True msg = addWarn msg
warnIf False _ = return ()
addMessages :: Messages -> TcRn ()
addMessages (m_warns, m_errs)
= do { errs_var <- getErrsVar ;
(warns, errs) <- readTcRef errs_var ;
writeTcRef errs_var (warns `unionBags` m_warns,
errs `unionBags` m_errs) }
discardWarnings :: TcRn a -> TcRn a
-- Ignore warnings inside the thing inside;
-- used to ignore-unused-variable warnings inside derived code
discardWarnings thing_inside
= do { errs_var <- getErrsVar
; (old_warns, _) <- readTcRef errs_var ;
; result <- thing_inside
-- Revert warnings to old_warns
; (_new_warns, new_errs) <- readTcRef errs_var
; writeTcRef errs_var (old_warns, new_errs)
; return result }
{-
************************************************************************
* *
Shared error message stuff: renamer and typechecker
* *
************************************************************************
-}
mkLongErrAt :: SrcSpan -> MsgDoc -> MsgDoc -> TcRn ErrMsg
mkLongErrAt loc msg extra
= do { dflags <- getDynFlags ;
printer <- getPrintUnqualified dflags ;
return $ mkLongErrMsg dflags loc printer msg extra }
addLongErrAt :: SrcSpan -> MsgDoc -> MsgDoc -> TcRn ()
addLongErrAt loc msg extra = mkLongErrAt loc msg extra >>= reportError
reportErrors :: [ErrMsg] -> TcM ()
reportErrors = mapM_ reportError
reportError :: ErrMsg -> TcRn ()
reportError err
= do { traceTc "Adding error:" (pprLocErrMsg err) ;
errs_var <- getErrsVar ;
(warns, errs) <- readTcRef errs_var ;
writeTcRef errs_var (warns, errs `snocBag` err) }
reportWarning :: ErrMsg -> TcRn ()
reportWarning err
= do { let warn = makeIntoWarning err
-- 'err' was build by mkLongErrMsg or something like that,
-- so it's of error severity. For a warning we downgrade
-- its severity to SevWarning
; traceTc "Adding warning:" (pprLocErrMsg warn)
; errs_var <- getErrsVar
; (warns, errs) <- readTcRef errs_var
; writeTcRef errs_var (warns `snocBag` warn, errs) }
try_m :: TcRn r -> TcRn (Either IOEnvFailure r)
-- Does tryM, with a debug-trace on failure
try_m thing
= do { mb_r <- tryM thing ;
case mb_r of
Left exn -> do { traceTc "tryTc/recoverM recovering from" $
text (showException exn)
; return mb_r }
Right _ -> return mb_r }
-----------------------
recoverM :: TcRn r -- Recovery action; do this if the main one fails
-> TcRn r -- Main action: do this first
-> TcRn r
-- Errors in 'thing' are retained
recoverM recover thing
= do { mb_res <- try_m thing ;
case mb_res of
Left _ -> recover
Right res -> return res }
-----------------------
mapAndRecoverM :: (a -> TcRn b) -> [a] -> TcRn [b]
-- Drop elements of the input that fail, so the result
-- list can be shorter than the argument list
mapAndRecoverM _ [] = return []
mapAndRecoverM f (x:xs) = do { mb_r <- try_m (f x)
; rs <- mapAndRecoverM f xs
; return (case mb_r of
Left _ -> rs
Right r -> r:rs) }
-- | Succeeds if applying the argument to all members of the lists succeeds,
-- but nevertheless runs it on all arguments, to collect all errors.
mapAndReportM :: (a -> TcRn b) -> [a] -> TcRn [b]
mapAndReportM f xs = checkNoErrs (mapAndRecoverM f xs)
-----------------------
tryTc :: TcRn a -> TcRn (Messages, Maybe a)
-- (tryTc m) executes m, and returns
-- Just r, if m succeeds (returning r)
-- Nothing, if m fails
-- It also returns all the errors and warnings accumulated by m
-- It always succeeds (never raises an exception)
tryTc m
= do { errs_var <- newTcRef emptyMessages ;
res <- try_m (setErrsVar errs_var m) ;
msgs <- readTcRef errs_var ;
return (msgs, case res of
Left _ -> Nothing
Right val -> Just val)
-- The exception is always the IOEnv built-in
-- in exception; see IOEnv.failM
}
-- (askNoErrs m) runs m
-- If m fails, (askNoErrs m) fails
-- If m succeeds with result r, (askNoErrs m) succeeds with result (r, b),
-- where b is True iff m generated no error
-- Regardless of success or failure, any errors generated by m are propagated
askNoErrs :: TcRn a -> TcRn (a, Bool)
askNoErrs m
= do { errs_var <- newTcRef emptyMessages
; res <- setErrsVar errs_var m
; (warns, errs) <- readTcRef errs_var
; addMessages (warns, errs)
; return (res, isEmptyBag errs) }
-----------------------
tryTcErrs :: TcRn a -> TcRn (Messages, Maybe a)
-- Run the thing, returning
-- Just r, if m succceeds with no error messages
-- Nothing, if m fails, or if it succeeds but has error messages
-- Either way, the messages are returned; even in the Just case
-- there might be warnings
tryTcErrs thing
= do { (msgs, res) <- tryTc thing
; dflags <- getDynFlags
; let errs_found = errorsFound dflags msgs
; return (msgs, case res of
Nothing -> Nothing
Just val | errs_found -> Nothing
| otherwise -> Just val)
}
-----------------------
tryTcLIE :: TcM a -> TcM (Messages, Maybe a)
-- Just like tryTcErrs, except that it ensures that the LIE
-- for the thing is propagated only if there are no errors
-- Hence it's restricted to the type-check monad
tryTcLIE thing_inside
= do { ((msgs, mb_res), lie) <- captureConstraints (tryTcErrs thing_inside) ;
; case mb_res of
Nothing -> return (msgs, Nothing)
Just val -> do { emitConstraints lie; return (msgs, Just val) }
}
-----------------------
tryTcLIE_ :: TcM r -> TcM r -> TcM r
-- (tryTcLIE_ r m) tries m;
-- if m succeeds with no error messages, it's the answer
-- otherwise tryTcLIE_ drops everything from m and tries r instead.
tryTcLIE_ recover main
= do { (msgs, mb_res) <- tryTcLIE main
; case mb_res of
Just val -> do { addMessages msgs -- There might be warnings
; return val }
Nothing -> recover -- Discard all msgs
}
-----------------------
checkNoErrs :: TcM r -> TcM r
-- (checkNoErrs m) succeeds iff m succeeds and generates no errors
-- If m fails then (checkNoErrsTc m) fails.
-- If m succeeds, it checks whether m generated any errors messages
-- (it might have recovered internally)
-- If so, it fails too.
-- Regardless, any errors generated by m are propagated to the enclosing context.
checkNoErrs main
= do { (msgs, mb_res) <- tryTcLIE main
; addMessages msgs
; case mb_res of
Nothing -> failM
Just val -> return val
}
whenNoErrs :: TcM () -> TcM ()
whenNoErrs thing = ifErrsM (return ()) thing
ifErrsM :: TcRn r -> TcRn r -> TcRn r
-- ifErrsM bale_out normal
-- does 'bale_out' if there are errors in errors collection
-- otherwise does 'normal'
ifErrsM bale_out normal
= do { errs_var <- getErrsVar ;
msgs <- readTcRef errs_var ;
dflags <- getDynFlags ;
if errorsFound dflags msgs then
bale_out
else
normal }
failIfErrsM :: TcRn ()
-- Useful to avoid error cascades
failIfErrsM = ifErrsM failM (return ())
#ifdef GHCI
checkTH :: a -> String -> TcRn ()
checkTH _ _ = return () -- OK
#else
checkTH :: Outputable a => a -> String -> TcRn ()
checkTH e what = failTH e what -- Raise an error in a stage-1 compiler
#endif
failTH :: Outputable a => a -> String -> TcRn x
failTH e what -- Raise an error in a stage-1 compiler
= failWithTc (vcat [ hang (char 'A' <+> text what
<+> ptext (sLit "requires GHC with interpreter support:"))
2 (ppr e)
, ptext (sLit "Perhaps you are using a stage-1 compiler?") ])
{-
************************************************************************
* *
Context management for the type checker
* *
************************************************************************
-}
getErrCtxt :: TcM [ErrCtxt]
getErrCtxt = do { env <- getLclEnv; return (tcl_ctxt env) }
setErrCtxt :: [ErrCtxt] -> TcM a -> TcM a
setErrCtxt ctxt = updLclEnv (\ env -> env { tcl_ctxt = ctxt })
addErrCtxt :: MsgDoc -> TcM a -> TcM a
addErrCtxt msg = addErrCtxtM (\env -> return (env, msg))
addErrCtxtM :: (TidyEnv -> TcM (TidyEnv, MsgDoc)) -> TcM a -> TcM a
addErrCtxtM ctxt = updCtxt (\ ctxts -> (False, ctxt) : ctxts)
addLandmarkErrCtxt :: MsgDoc -> TcM a -> TcM a
addLandmarkErrCtxt msg = updCtxt (\ctxts -> (True, \env -> return (env,msg)) : ctxts)
-- Helper function for the above
updCtxt :: ([ErrCtxt] -> [ErrCtxt]) -> TcM a -> TcM a
updCtxt upd = updLclEnv (\ env@(TcLclEnv { tcl_ctxt = ctxt }) ->
env { tcl_ctxt = upd ctxt })
popErrCtxt :: TcM a -> TcM a
popErrCtxt = updCtxt (\ msgs -> case msgs of { [] -> []; (_ : ms) -> ms })
getCtLocM :: CtOrigin -> TcM CtLoc
getCtLocM origin
= do { env <- getLclEnv
; return (CtLoc { ctl_origin = origin
, ctl_env = env
, ctl_depth = initialSubGoalDepth }) }
setCtLocM :: CtLoc -> TcM a -> TcM a
-- Set the SrcSpan and error context from the CtLoc
setCtLocM (CtLoc { ctl_env = lcl }) thing_inside
= updLclEnv (\env -> env { tcl_loc = tcl_loc lcl
, tcl_bndrs = tcl_bndrs lcl
, tcl_ctxt = tcl_ctxt lcl })
thing_inside
{-
************************************************************************
* *
Error message generation (type checker)
* *
************************************************************************
The addErrTc functions add an error message, but do not cause failure.
The 'M' variants pass a TidyEnv that has already been used to
tidy up the message; we then use it to tidy the context messages
-}
addErrTc :: MsgDoc -> TcM ()
addErrTc err_msg = do { env0 <- tcInitTidyEnv
; addErrTcM (env0, err_msg) }
addErrsTc :: [MsgDoc] -> TcM ()
addErrsTc err_msgs = mapM_ addErrTc err_msgs
addErrTcM :: (TidyEnv, MsgDoc) -> TcM ()
addErrTcM (tidy_env, err_msg)
= do { ctxt <- getErrCtxt ;
loc <- getSrcSpanM ;
add_err_tcm tidy_env err_msg loc ctxt }
-- Return the error message, instead of reporting it straight away
mkErrTcM :: (TidyEnv, MsgDoc) -> TcM ErrMsg
mkErrTcM (tidy_env, err_msg)
= do { ctxt <- getErrCtxt ;
loc <- getSrcSpanM ;
err_info <- mkErrInfo tidy_env ctxt ;
mkLongErrAt loc err_msg err_info }
-- The failWith functions add an error message and cause failure
failWithTc :: MsgDoc -> TcM a -- Add an error message and fail
failWithTc err_msg
= addErrTc err_msg >> failM
failWithTcM :: (TidyEnv, MsgDoc) -> TcM a -- Add an error message and fail
failWithTcM local_and_msg
= addErrTcM local_and_msg >> failM
checkTc :: Bool -> MsgDoc -> TcM () -- Check that the boolean is true
checkTc True _ = return ()
checkTc False err = failWithTc err
failIfTc :: Bool -> MsgDoc -> TcM () -- Check that the boolean is false
failIfTc False _ = return ()
failIfTc True err = failWithTc err
-- Warnings have no 'M' variant, nor failure
warnTc :: Bool -> MsgDoc -> TcM ()
warnTc warn_if_true warn_msg
| warn_if_true = addWarnTc warn_msg
| otherwise = return ()
addWarnTc :: MsgDoc -> TcM ()
addWarnTc msg = do { env0 <- tcInitTidyEnv
; addWarnTcM (env0, msg) }
addWarnTcM :: (TidyEnv, MsgDoc) -> TcM ()
addWarnTcM (env0, msg)
= do { ctxt <- getErrCtxt ;
err_info <- mkErrInfo env0 ctxt ;
add_warn msg err_info }
addWarn :: MsgDoc -> TcRn ()
addWarn msg = add_warn msg Outputable.empty
addWarnAt :: SrcSpan -> MsgDoc -> TcRn ()
addWarnAt loc msg = add_warn_at loc msg Outputable.empty
add_warn :: MsgDoc -> MsgDoc -> TcRn ()
add_warn msg extra_info
= do { loc <- getSrcSpanM
; add_warn_at loc msg extra_info }
add_warn_at :: SrcSpan -> MsgDoc -> MsgDoc -> TcRn ()
add_warn_at loc msg extra_info
= do { dflags <- getDynFlags ;
printer <- getPrintUnqualified dflags ;
let { warn = mkLongWarnMsg dflags loc printer
msg extra_info } ;
reportWarning warn }
tcInitTidyEnv :: TcM TidyEnv
tcInitTidyEnv
= do { lcl_env <- getLclEnv
; return (tcl_tidy lcl_env) }
{-
-----------------------------------
Other helper functions
-}
add_err_tcm :: TidyEnv -> MsgDoc -> SrcSpan
-> [ErrCtxt]
-> TcM ()
add_err_tcm tidy_env err_msg loc ctxt
= do { err_info <- mkErrInfo tidy_env ctxt ;
addLongErrAt loc err_msg err_info }
mkErrInfo :: TidyEnv -> [ErrCtxt] -> TcM SDoc
-- Tidy the error info, trimming excessive contexts
mkErrInfo env ctxts
-- | opt_PprStyle_Debug -- In -dppr-debug style the output
-- = return empty -- just becomes too voluminous
| otherwise
= go 0 env ctxts
where
go :: Int -> TidyEnv -> [ErrCtxt] -> TcM SDoc
go _ _ [] = return Outputable.empty
go n env ((is_landmark, ctxt) : ctxts)
| is_landmark || n < mAX_CONTEXTS -- Too verbose || opt_PprStyle_Debug
= do { (env', msg) <- ctxt env
; let n' = if is_landmark then n else n+1
; rest <- go n' env' ctxts
; return (msg $$ rest) }
| otherwise
= go n env ctxts
mAX_CONTEXTS :: Int -- No more than this number of non-landmark contexts
mAX_CONTEXTS = 3
-- debugTc is useful for monadic debugging code
debugTc :: TcM () -> TcM ()
debugTc thing
| debugIsOn = thing
| otherwise = return ()
{-
************************************************************************
* *
Type constraints
* *
************************************************************************
-}
newTcEvBinds :: TcM EvBindsVar
newTcEvBinds = do { ref <- newTcRef emptyEvBindMap
; uniq <- newUnique
; return (EvBindsVar ref uniq) }
addTcEvBind :: EvBindsVar -> EvBind -> TcM ()
-- Add a binding to the TcEvBinds by side effect
addTcEvBind (EvBindsVar ev_ref _) ev_bind
= do { traceTc "addTcEvBind" $ ppr ev_bind
; bnds <- readTcRef ev_ref
; writeTcRef ev_ref (extendEvBinds bnds ev_bind) }
getTcEvBinds :: EvBindsVar -> TcM (Bag EvBind)
getTcEvBinds (EvBindsVar ev_ref _)
= do { bnds <- readTcRef ev_ref
; return (evBindMapBinds bnds) }
chooseUniqueOccTc :: (OccSet -> OccName) -> TcM OccName
chooseUniqueOccTc fn =
do { env <- getGblEnv
; let dfun_n_var = tcg_dfun_n env
; set <- readTcRef dfun_n_var
; let occ = fn set
; writeTcRef dfun_n_var (extendOccSet set occ)
; return occ }
getConstraintVar :: TcM (TcRef WantedConstraints)
getConstraintVar = do { env <- getLclEnv; return (tcl_lie env) }
setConstraintVar :: TcRef WantedConstraints -> TcM a -> TcM a
setConstraintVar lie_var = updLclEnv (\ env -> env { tcl_lie = lie_var })
emitConstraints :: WantedConstraints -> TcM ()
emitConstraints ct
= do { lie_var <- getConstraintVar ;
updTcRef lie_var (`andWC` ct) }
emitSimple :: Ct -> TcM ()
emitSimple ct
= do { lie_var <- getConstraintVar ;
updTcRef lie_var (`addSimples` unitBag ct) }
emitSimples :: Cts -> TcM ()
emitSimples cts
= do { lie_var <- getConstraintVar ;
updTcRef lie_var (`addSimples` cts) }
emitImplication :: Implication -> TcM ()
emitImplication ct
= do { lie_var <- getConstraintVar ;
updTcRef lie_var (`addImplics` unitBag ct) }
emitImplications :: Bag Implication -> TcM ()
emitImplications ct
= do { lie_var <- getConstraintVar ;
updTcRef lie_var (`addImplics` ct) }
emitInsoluble :: Ct -> TcM ()
emitInsoluble ct
= do { lie_var <- getConstraintVar ;
updTcRef lie_var (`addInsols` unitBag ct) ;
v <- readTcRef lie_var ;
traceTc "emitInsoluble" (ppr v) }
captureConstraints :: TcM a -> TcM (a, WantedConstraints)
-- (captureConstraints m) runs m, and returns the type constraints it generates
captureConstraints thing_inside
= do { lie_var <- newTcRef emptyWC ;
res <- updLclEnv (\ env -> env { tcl_lie = lie_var })
thing_inside ;
lie <- readTcRef lie_var ;
return (res, lie) }
pushLevelAndCaptureConstraints :: TcM a -> TcM (a, TcLevel, WantedConstraints)
pushLevelAndCaptureConstraints thing_inside
= do { env <- getLclEnv
; lie_var <- newTcRef emptyWC ;
; let tclvl' = pushTcLevel (tcl_tclvl env)
; res <- setLclEnv (env { tcl_tclvl = tclvl'
, tcl_lie = lie_var })
thing_inside
; lie <- readTcRef lie_var
; return (res, tclvl', lie) }
pushTcLevelM_ :: TcM a -> TcM a
pushTcLevelM_ = updLclEnv (\ env -> env { tcl_tclvl = pushTcLevel (tcl_tclvl env) })
pushTcLevelM :: TcM a -> TcM (a, TcLevel)
pushTcLevelM thing_inside
= do { env <- getLclEnv
; let tclvl' = pushTcLevel (tcl_tclvl env)
; res <- setLclEnv (env { tcl_tclvl = tclvl' })
thing_inside
; return (res, tclvl') }
getTcLevel :: TcM TcLevel
getTcLevel = do { env <- getLclEnv
; return (tcl_tclvl env) }
setTcLevel :: TcLevel -> TcM a -> TcM a
setTcLevel tclvl thing_inside
= updLclEnv (\env -> env { tcl_tclvl = tclvl }) thing_inside
isTouchableTcM :: TcTyVar -> TcM Bool
isTouchableTcM tv
= do { env <- getLclEnv
; return (isTouchableMetaTyVar (tcl_tclvl env) tv) }
getLclTypeEnv :: TcM TcTypeEnv
getLclTypeEnv = do { env <- getLclEnv; return (tcl_env env) }
setLclTypeEnv :: TcLclEnv -> TcM a -> TcM a
-- Set the local type envt, but do *not* disturb other fields,
-- notably the lie_var
setLclTypeEnv lcl_env thing_inside
= updLclEnv upd thing_inside
where
upd env = env { tcl_env = tcl_env lcl_env,
tcl_tyvars = tcl_tyvars lcl_env }
traceTcConstraints :: String -> TcM ()
traceTcConstraints msg
= do { lie_var <- getConstraintVar
; lie <- readTcRef lie_var
; traceTc (msg ++ ": LIE:") (ppr lie)
}
emitWildcardHoleConstraints :: [(Name, TcTyVar)] -> TcM ()
emitWildcardHoleConstraints wcs
= do { ctLoc <- getCtLocM HoleOrigin
; forM_ wcs $ \(name, tv) -> do {
; let real_span = case nameSrcSpan name of
RealSrcSpan span -> span
UnhelpfulSpan str -> pprPanic "emitWildcardHoleConstraints"
(ppr name <+> quotes (ftext str))
-- Wildcards are defined locally, and so have RealSrcSpans
ctLoc' = setCtLocSpan ctLoc real_span
ty = mkTyVarTy tv
ev = mkLocalId name ty
can = CHoleCan { cc_ev = CtWanted ty ev ctLoc'
, cc_occ = occName name
, cc_hole = TypeHole }
; emitInsoluble can } }
{-
************************************************************************
* *
Template Haskell context
* *
************************************************************************
-}
recordThUse :: TcM ()
recordThUse = do { env <- getGblEnv; writeTcRef (tcg_th_used env) True }
recordThSpliceUse :: TcM ()
recordThSpliceUse = do { env <- getGblEnv; writeTcRef (tcg_th_splice_used env) True }
keepAlive :: Name -> TcRn () -- Record the name in the keep-alive set
keepAlive name
= do { env <- getGblEnv
; traceRn (ptext (sLit "keep alive") <+> ppr name)
; updTcRef (tcg_keep env) (`extendNameSet` name) }
getStage :: TcM ThStage
getStage = do { env <- getLclEnv; return (tcl_th_ctxt env) }
getStageAndBindLevel :: Name -> TcRn (Maybe (TopLevelFlag, ThLevel, ThStage))
getStageAndBindLevel name
= do { env <- getLclEnv;
; case lookupNameEnv (tcl_th_bndrs env) name of
Nothing -> return Nothing
Just (top_lvl, bind_lvl) -> return (Just (top_lvl, bind_lvl, tcl_th_ctxt env)) }
setStage :: ThStage -> TcM a -> TcRn a
setStage s = updLclEnv (\ env -> env { tcl_th_ctxt = s })
{-
************************************************************************
* *
Safe Haskell context
* *
************************************************************************
-}
-- | Mark that safe inference has failed
-- See Note [Safe Haskell Overlapping Instances Implementation]
-- although this is used for more than just that failure case.
recordUnsafeInfer :: WarningMessages -> TcM ()
recordUnsafeInfer warns =
getGblEnv >>= \env -> writeTcRef (tcg_safeInfer env) (False, warns)
-- | Figure out the final correct safe haskell mode
finalSafeMode :: DynFlags -> TcGblEnv -> IO SafeHaskellMode
finalSafeMode dflags tcg_env = do
safeInf <- fst <$> readIORef (tcg_safeInfer tcg_env)
return $ case safeHaskell dflags of
Sf_None | safeInferOn dflags && safeInf -> Sf_Safe
| otherwise -> Sf_None
s -> s
-- | Switch instances to safe instances if we're in Safe mode.
fixSafeInstances :: SafeHaskellMode -> [ClsInst] -> [ClsInst]
fixSafeInstances sfMode | sfMode /= Sf_Safe = id
fixSafeInstances _ = map fixSafe
where fixSafe inst = let new_flag = (is_flag inst) { isSafeOverlap = True }
in inst { is_flag = new_flag }
{-
************************************************************************
* *
Stuff for the renamer's local env
* *
************************************************************************
-}
getLocalRdrEnv :: RnM LocalRdrEnv
getLocalRdrEnv = do { env <- getLclEnv; return (tcl_rdr env) }
setLocalRdrEnv :: LocalRdrEnv -> RnM a -> RnM a
setLocalRdrEnv rdr_env thing_inside
= updLclEnv (\env -> env {tcl_rdr = rdr_env}) thing_inside
{-
************************************************************************
* *
Stuff for interface decls
* *
************************************************************************
-}
mkIfLclEnv :: Module -> SDoc -> IfLclEnv
mkIfLclEnv mod loc = IfLclEnv { if_mod = mod,
if_loc = loc,
if_tv_env = emptyUFM,
if_id_env = emptyUFM }
-- | Run an 'IfG' (top-level interface monad) computation inside an existing
-- 'TcRn' (typecheck-renaming monad) computation by initializing an 'IfGblEnv'
-- based on 'TcGblEnv'.
initIfaceTcRn :: IfG a -> TcRn a
initIfaceTcRn thing_inside
= do { tcg_env <- getGblEnv
; let { if_env = IfGblEnv {
if_rec_types = Just (tcg_mod tcg_env, get_type_env)
}
; get_type_env = readTcRef (tcg_type_env_var tcg_env) }
; setEnvs (if_env, ()) thing_inside }
initIfaceCheck :: HscEnv -> IfG a -> IO a
-- Used when checking the up-to-date-ness of the old Iface
-- Initialise the environment with no useful info at all
initIfaceCheck hsc_env do_this
= do let rec_types = case hsc_type_env_var hsc_env of
Just (mod,var) -> Just (mod, readTcRef var)
Nothing -> Nothing
gbl_env = IfGblEnv { if_rec_types = rec_types }
initTcRnIf 'i' hsc_env gbl_env () do_this
initIfaceTc :: ModIface
-> (TcRef TypeEnv -> IfL a) -> TcRnIf gbl lcl a
-- Used when type-checking checking an up-to-date interface file
-- No type envt from the current module, but we do know the module dependencies
initIfaceTc iface do_this
= do { tc_env_var <- newTcRef emptyTypeEnv
; let { gbl_env = IfGblEnv {
if_rec_types = Just (mod, readTcRef tc_env_var)
} ;
; if_lenv = mkIfLclEnv mod doc
}
; setEnvs (gbl_env, if_lenv) (do_this tc_env_var)
}
where
mod = mi_module iface
doc = ptext (sLit "The interface for") <+> quotes (ppr mod)
initIfaceLcl :: Module -> SDoc -> IfL a -> IfM lcl a
initIfaceLcl mod loc_doc thing_inside
= setLclEnv (mkIfLclEnv mod loc_doc) thing_inside
getIfModule :: IfL Module
getIfModule = do { env <- getLclEnv; return (if_mod env) }
--------------------
failIfM :: MsgDoc -> IfL a
-- The Iface monad doesn't have a place to accumulate errors, so we
-- just fall over fast if one happens; it "shouldnt happen".
-- We use IfL here so that we can get context info out of the local env
failIfM msg
= do { env <- getLclEnv
; let full_msg = (if_loc env <> colon) $$ nest 2 msg
; dflags <- getDynFlags
; liftIO (log_action dflags dflags SevFatal noSrcSpan (defaultErrStyle dflags) full_msg)
; failM }
--------------------
forkM_maybe :: SDoc -> IfL a -> IfL (Maybe a)
-- Run thing_inside in an interleaved thread.
-- It shares everything with the parent thread, so this is DANGEROUS.
--
-- It returns Nothing if the computation fails
--
-- It's used for lazily type-checking interface
-- signatures, which is pretty benign
forkM_maybe doc thing_inside
-- NB: Don't share the mutable env_us with the interleaved thread since env_us
-- does not get updated atomically (e.g. in newUnique and newUniqueSupply).
= do { child_us <- newUniqueSupply
; child_env_us <- newMutVar child_us
-- see Note [Masking exceptions in forkM_maybe]
; unsafeInterleaveM $ uninterruptibleMaskM_ $ updEnv (\env -> env { env_us = child_env_us }) $
do { traceIf (text "Starting fork {" <+> doc)
; mb_res <- tryM $
updLclEnv (\env -> env { if_loc = if_loc env $$ doc }) $
thing_inside
; case mb_res of
Right r -> do { traceIf (text "} ending fork" <+> doc)
; return (Just r) }
Left exn -> do {
-- Bleat about errors in the forked thread, if -ddump-if-trace is on
-- Otherwise we silently discard errors. Errors can legitimately
-- happen when compiling interface signatures (see tcInterfaceSigs)
whenDOptM Opt_D_dump_if_trace $ do
dflags <- getDynFlags
let msg = hang (text "forkM failed:" <+> doc)
2 (text (show exn))
liftIO $ log_action dflags dflags SevFatal noSrcSpan (defaultErrStyle dflags) msg
; traceIf (text "} ending fork (badly)" <+> doc)
; return Nothing }
}}
forkM :: SDoc -> IfL a -> IfL a
forkM doc thing_inside
= do { mb_res <- forkM_maybe doc thing_inside
; return (case mb_res of
Nothing -> pgmError "Cannot continue after interface file error"
-- pprPanic "forkM" doc
Just r -> r) }
{-
Note [Masking exceptions in forkM_maybe]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When using GHC-as-API it must be possible to interrupt snippets of code
executed using runStmt (#1381). Since commit 02c4ab04 this is almost possible
by throwing an asynchronous interrupt to the GHC thread. However, there is a
subtle problem: runStmt first typechecks the code before running it, and the
exception might interrupt the type checker rather than the code. Moreover, the
typechecker might be inside an unsafeInterleaveIO (through forkM_maybe), and
more importantly might be inside an exception handler inside that
unsafeInterleaveIO. If that is the case, the exception handler will rethrow the
asynchronous exception as a synchronous exception, and the exception will end
up as the value of the unsafeInterleaveIO thunk (see #8006 for a detailed
discussion). We don't currently know a general solution to this problem, but
we can use uninterruptibleMask_ to avoid the situation.
-}
| elieux/ghc | compiler/typecheck/TcRnMonad.hs | bsd-3-clause | 54,762 | 63 | 25 | 17,259 | 12,730 | 6,628 | 6,102 | 889 | 5 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.SES.GetSendStatistics
-- 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.
-- | Returns the user's sending statistics. The result is a list of data points,
-- representing the last two weeks of sending activity.
--
-- Each data point in the list contains statistics for a 15-minute interval.
--
-- This action is throttled at one request per second.
--
-- <http://docs.aws.amazon.com/ses/latest/APIReference/API_GetSendStatistics.html>
module Network.AWS.SES.GetSendStatistics
(
-- * Request
GetSendStatistics
-- ** Request constructor
, getSendStatistics
-- * Response
, GetSendStatisticsResponse
-- ** Response constructor
, getSendStatisticsResponse
-- ** Response lenses
, gssrSendDataPoints
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.SES.Types
import qualified GHC.Exts
data GetSendStatistics = GetSendStatistics
deriving (Eq, Ord, Read, Show, Generic)
-- | 'GetSendStatistics' constructor.
getSendStatistics :: GetSendStatistics
getSendStatistics = GetSendStatistics
newtype GetSendStatisticsResponse = GetSendStatisticsResponse
{ _gssrSendDataPoints :: List "member" SendDataPoint
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList GetSendStatisticsResponse where
type Item GetSendStatisticsResponse = SendDataPoint
fromList = GetSendStatisticsResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _gssrSendDataPoints
-- | 'GetSendStatisticsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'gssrSendDataPoints' @::@ ['SendDataPoint']
--
getSendStatisticsResponse :: GetSendStatisticsResponse
getSendStatisticsResponse = GetSendStatisticsResponse
{ _gssrSendDataPoints = mempty
}
-- | A list of data points, each of which represents 15 minutes of activity.
gssrSendDataPoints :: Lens' GetSendStatisticsResponse [SendDataPoint]
gssrSendDataPoints =
lens _gssrSendDataPoints (\s a -> s { _gssrSendDataPoints = a })
. _List
instance ToPath GetSendStatistics where
toPath = const "/"
instance ToQuery GetSendStatistics where
toQuery = const mempty
instance ToHeaders GetSendStatistics
instance AWSRequest GetSendStatistics where
type Sv GetSendStatistics = SES
type Rs GetSendStatistics = GetSendStatisticsResponse
request = post "GetSendStatistics"
response = xmlResponse
instance FromXML GetSendStatisticsResponse where
parseXML = withElement "GetSendStatisticsResult" $ \x -> GetSendStatisticsResponse
<$> x .@? "SendDataPoints" .!@ mempty
| romanb/amazonka | amazonka-ses/gen/Network/AWS/SES/GetSendStatistics.hs | mpl-2.0 | 3,563 | 0 | 10 | 707 | 396 | 242 | 154 | 52 | 1 |
{-# LANGUAGE RecordWildCards, TupleSections, CPP #-}
-- | Implements HTTP Basic Authentication.
--
-- This module may add digest authentication in the future.
module Network.Wai.Middleware.HttpAuth
( -- * Middleware
basicAuth
, basicAuth'
, CheckCreds
, AuthSettings
, authRealm
, authOnNoAuth
, authIsProtected
-- * Helping functions
, extractBasicAuth
, extractBearerAuth
) where
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Data.ByteString (ByteString)
import Data.ByteString.Base64 (decodeLenient)
import Data.String (IsString (..))
import Data.Word8 (isSpace, _colon, toLower)
import Network.HTTP.Types (status401, hContentType, hAuthorization)
import Network.Wai
import qualified Data.ByteString as S
-- | Check if a given username and password is valid.
type CheckCreds = ByteString
-> ByteString
-> IO Bool
-- | Perform basic authentication.
--
-- > basicAuth (\u p -> return $ u == "michael" && p == "mypass") "My Realm"
--
-- @since 1.3.4
basicAuth :: CheckCreds
-> AuthSettings
-> Middleware
basicAuth checkCreds = basicAuth' (\_ -> checkCreds)
-- | Like 'basicAuth', but also passes a request to the authentication function.
--
-- @since 3.0.19
basicAuth' :: (Request -> CheckCreds)
-> AuthSettings
-> Middleware
basicAuth' checkCreds AuthSettings {..} app req sendResponse = do
isProtected <- authIsProtected req
allowed <- if isProtected then check else return True
if allowed
then app req sendResponse
else authOnNoAuth authRealm req sendResponse
where
check =
case (lookup hAuthorization $ requestHeaders req)
>>= extractBasicAuth of
Nothing -> return False
Just (username, password) -> checkCreds req username password
-- | Basic authentication settings. This value is an instance of
-- @IsString@, so the recommended approach to create a value is to
-- provide a string literal (which will be the realm) and then
-- overriding individual fields.
--
-- > "My Realm" { authIsProtected = someFunc } :: AuthSettings
--
-- @since 1.3.4
data AuthSettings = AuthSettings
{ authRealm :: !ByteString
-- ^
--
-- @since 1.3.4
, authOnNoAuth :: !(ByteString -> Application)
-- ^ Takes the realm and returns an appropriate 401 response when
-- authentication is not provided.
--
-- @since 1.3.4
, authIsProtected :: !(Request -> IO Bool)
-- ^ Determine if access to the requested resource is restricted.
--
-- Default: always returns @True@.
--
-- @since 1.3.4
}
instance IsString AuthSettings where
fromString s = AuthSettings
{ authRealm = fromString s
, authOnNoAuth = \realm _req f -> f $ responseLBS
status401
[ (hContentType, "text/plain")
, ("WWW-Authenticate", S.concat
[ "Basic realm=\""
, realm
, "\""
])
]
"Basic authentication is required"
, authIsProtected = const $ return True
}
-- | Extract basic authentication data from usually __Authorization__
-- header value. Returns username and password
--
-- @since 3.0.5
extractBasicAuth :: ByteString -> Maybe (ByteString, ByteString)
extractBasicAuth bs =
let (x, y) = S.break isSpace bs
in if S.map toLower x == "basic"
then extract $ S.dropWhile isSpace y
else Nothing
where
extract encoded =
let raw = decodeLenient encoded
(username, password') = S.break (== _colon) raw
in ((username,) . snd) <$> S.uncons password'
-- | Extract bearer authentication data from __Authorization__ header
-- value. Returns bearer token
--
-- @since 3.0.5
extractBearerAuth :: ByteString -> Maybe ByteString
extractBearerAuth bs =
let (x, y) = S.break isSpace bs
in if S.map toLower x == "bearer"
then Just $ S.dropWhile isSpace y
else Nothing
| creichert/wai | wai-extra/Network/Wai/Middleware/HttpAuth.hs | mit | 4,037 | 0 | 14 | 1,046 | 737 | 420 | 317 | 79 | 4 |
--
-- Copyright (c) 2012 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
module Template ( Pattern, Replacement, Rule
, substRules
, untemplatise
) where
import Control.Applicative
import Data.List
import qualified Data.Text.Lazy as T
type Pattern = String
type Replacement = String
type Rule = (Pattern, Replacement)
substRules :: [Rule] -> String -> String
substRules rules input =
T.unpack $ foldl' subst inputT rules
where
inputT = T.pack input
subst text (pattern,replacement) = T.replace (T.pack pattern) (T.pack replacement) text
untemplatise :: [Rule] -> FilePath -> IO String
untemplatise rules file =
substRules rules <$> readFile file
| eric-ch/idl | rpcgen/Template.hs | gpl-2.0 | 1,412 | 0 | 10 | 296 | 212 | 126 | 86 | 17 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.