code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
module Plots.Types.Points
( -- * Polar scatter plot
GPointsPlot
, mkPointsPlot
-- * Lenses
, doFill
-- * Points plot
, pointsPlot
, pointsPlot'
) where
import Control.Lens hiding (lmap, none, transform,
( # ))
import Control.Monad.State.Lazy
import Data.Typeable
import Diagrams.Prelude
import Diagrams.Coordinates.Isomorphic
import Diagrams.Coordinates.Polar
import Plots.Themes
import Plots.Types
import Plots.API
------------------------------------------------------------------------
-- GPoints plot
------------------------------------------------------------------------
data GPointsPlot n = GPointsPlot
{ sPoints :: [(n, Angle n)]
, sFill :: Bool
} deriving Typeable
-- options for style and transform.
-- lenses for style and transform,
-- scatter plot for example.
type instance V (GPointsPlot n) = V2
type instance N (GPointsPlot n) = n
instance (OrderedField n) => Enveloped (GPointsPlot n) where
getEnvelope GPointsPlot {..} = mempty
instance (v ~ V2, Typeable b, TypeableFloat n, Renderable (Path v n) b)
=> Plotable (GPointsPlot n) b where
renderPlotable _ GPointsPlot {..} pp =
mconcat [marker # applyMarkerStyle pp # scale 0.1 # moveTo (p2 (r*(cosA theta),r*(sinA theta)))| (r,theta) <- sPoints]
<> if sFill
then doline <> doarea
else mempty
where
marker = pp ^. plotMarker
doline = fromVertices (map p2 [(r*(cosA theta),r*(sinA theta)) | (r,theta) <- sPoints]) # mapLoc closeLine # stroke # applyLineStyle pp
doarea = fromVertices (map p2 [(r*(cosA theta),r*(sinA theta)) | (r,theta) <- sPoints]) # mapLoc closeLine # stroke # lw none # applyBarStyle pp
defLegendPic GPointsPlot {..} pp
= pp ^. plotMarker
& applyMarkerStyle pp
------------------------------------------------------------------------
-- Points plot
------------------------------------------------------------------------
-- | Plot a polar scatter plot given a list of radius and angle.
mkPointsPlot :: (RealFloat n, PointLike V2 n (Polar n), Num n)
=> [(n, Angle n)] -> GPointsPlot n
mkPointsPlot ds = GPointsPlot
{ sPoints = ds
, sFill = False
}
------------------------------------------------------------------------
-- Points lenses
------------------------------------------------------------------------
class HasPoints a n | a -> n where
pts :: Lens' a (GPointsPlot n)
doFill :: Lens' a Bool
doFill = pts . lens sFill (\s b -> (s {sFill = b}))
instance HasPoints (GPointsPlot n) n where
pts = id
instance HasPoints (PropertiedPlot (GPointsPlot n) b) n where
pts = _pp
------------------------------------------------------------------------
-- Points plot
------------------------------------------------------------------------
-- $ points plot
-- Points plot display data as scatter (dots) on polar co-ord.
-- Points plots have the following lenses:
--
-- @
-- * 'doFill' :: 'Lens'' ('BoxPlot' v n) 'Bool' - False
-- @
--
-- | Add a 'PointsPlot' to the 'AxisState' from a data set.
--
-- @
-- myaxis = polarAxis ~&
-- pointsPlot data1
-- @
--
-- === __Example__
--
-- <<plots/points.png#diagram=points&width=300>>
--
-- @
--
-- myaxis :: Axis B Polar Double
-- myaxis = polarAxis &~ do
-- pointsPlot mydata1
-- pointsPlot mydata2
-- pointsPlot mydata3
--
-- @
pointsPlot
:: (v ~ BaseSpace c, v ~ V2,
PointLike v n (Polar n),
MonadState (Axis b c n) m,
Plotable (GPointsPlot n) b,
RealFloat n)
=> [(n,Angle n)] -> m ()
pointsPlot ds = addPlotable (mkPointsPlot ds)
-- | Make a 'PointsPlot' and take a 'State' on the plot to alter it's
-- options
--
-- @
-- myaxis = polarAxis &~ do
-- pointsPlot' pointData1 $ do
-- addLegendEntry "data 1"
-- doFill .= True
-- @
pointsPlot'
:: (v ~ BaseSpace c, v ~ V2,
PointLike v n (Polar n),
MonadState (Axis b c n) m,
Plotable (GPointsPlot n) b,
RealFloat n)
=> [(n,Angle n)] -> PlotState (GPointsPlot n) b -> m ()
pointsPlot' ds = addPlotable' (mkPointsPlot ds)
| bergey/plots | src/Plots/Types/Points.hs | bsd-3-clause | 4,812 | 0 | 19 | 1,171 | 1,084 | 610 | 474 | 80 | 1 |
{-# LANGUAGE
OverlappingInstances
,EmptyDataDecls
,FlexibleContexts
,FlexibleInstances
,FunctionalDependencies
,GeneralizedNewtypeDeriving
,KindSignatures
,MultiParamTypeClasses
,NoMonomorphismRestriction
,ScopedTypeVariables
,TemplateHaskell
,TypeOperators
,TypeSynonymInstances
,UndecidableInstances
,ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures
-fcontext-stack=81 #-}
-- I can't figure out an acceptable type for 'set' and similar:
-- ghc doesn't accept the type inferred by ghci
{- |
Module : XMonad.Config.Alt.Internal
Copyright : Adam Vogt <[email protected]>
License : BSD3-style (see LICENSE)
Maintainer : Adam Vogt <[email protected]>
Stability : unstable
Portability : unportable
Import "XMonad.Config.Alt".
-}
module XMonad.Config.Alt.Internal (
module XMonad.Config.Alt.QQ,
-- * Running
runConfig,
runConfig',
-- * Actions
-- $actions
set,
add,
modify,
modifyIO,
-- ** less useful
modifyIO',
insertInto,
-- * Things to modify
-- ** Special
LayoutHook(LayoutHook),
-- ** Others
FocusFollowsMouse(FocusFollowsMouse),
StartupHook(StartupHook),
LogHook(LogHook),
BorderWidth(BorderWidth),
MouseBindings(MouseBindings),
Keys(Keys),
ModMask(ModMask),
Workspaces(Workspaces),
HandleEventHook(HandleEventHook),
ManageHook(ManageHook),
Terminal(Terminal),
FocusedBorderColor(FocusedBorderColor),
NormalBorderColor(NormalBorderColor),
-- * Relatively private
-- | You probably don't need these
defaultPrec,
-- ** Ordered Insertion into HLists like [(Nat,a)]
insLt,
insGeq,
Ins2(..),
Ins'(..),
ins,
-- ** Useful functions
HCompose(hComp),
Snd(Snd),
HSubtract(hSubtract),
HReplicateF(hReplicateF),
HPred'(hPred'),
-- ** For overloading
Mode(..),
Add(Add),
Set(Set),
Modify(Modify),
ModifyIO(ModifyIO),
Config(..),
test,
module Data.HList,
) where
import Control.Monad.Writer
import Data.Char
import Data.HList
import Language.Haskell.TH
import qualified XMonad as X
import XMonad.Config.Alt.Types
import XMonad.Config.Alt.QQ
-- * Class to write set / modify as functions
class Mode action field e x y | action field e x -> y, action field x y -> e where
m :: action -> field -> e -> X.XConfig x -> Config (X.XConfig y)
-- * Actions for 'Mode'
data Add = Add -- ^ the 'Mode' instance combines the old value like @new `mappend` old@
data Set = Set
data Modify = Modify
data ModifyIO = ModifyIO
$(decNat "defaultPrec" 4)
{- $actions
Use 'set', 'add', 'modify', 'modifyIO' for most predefined fields in 'XConfig'.
For constructing things to modify a config:
> insertInto action hold prec field v
* @action@ is an instance of 'Mode' so you only need to write 'ModifyIO' to describe how to access this field.
* @hold@ is 'HTrue' if you don't want to overwrite a preexisting value at the same @prec@. This is for things that should be applied once-only.
* @field@ used with the 'Mode'
* @v@ the value that is being updated (or a function if you use 'Modify' or similar)
-}
set f v = insertInto Set hFalse defaultPrec f v
add f v = insertInto Add hFalse defaultPrec f v
modify f v = insertInto Modify hFalse defaultPrec f v
modifyIO = modifyIO' hFalse defaultPrec
modifyIO' x = insertInto ModifyIO x
insertInto action hold prec f x = ins' prec hold (m action f x =<<)
-- | Represent setting layouts and layout modifiers
data LayoutHook = LayoutHook
instance Mode ModifyIO LayoutHook (l X.Window -> Config (m X.Window)) l m where
m _ _ l c = do
l' <- l $ X.layoutHook c
return $ c { X.layoutHook = l' }
-- | 'Add' means something else for 'X.layoutHook' because there's no suitable
-- mempty for the general instance of 'X.LayoutClass'
instance (X.LayoutClass l X.Window, X.LayoutClass l' X.Window) =>
Mode Add LayoutHook (l' X.Window) l (X.Choose l' l) where
m _ _ l = \x -> return $ x { X.layoutHook = l X.||| X.layoutHook x }
instance (Read (l X.Window), X.LayoutClass l X.Window,
Read (l' X.Window), X.LayoutClass l' X.Window) =>
Mode Modify LayoutHook (l X.Window -> l' X.Window) l l' where
m _ _ l = \x -> return $ x { X.layoutHook = l (X.layoutHook x) }
instance (X.LayoutClass l' X.Window) =>
Mode Set LayoutHook (l' X.Window) l l' where
m _ _ l = \x -> return $ x { X.layoutHook = l }
data Snd = Snd
instance Apply Snd (a, b) b where
apply _ (_, b) = b
-- | like @foldr (.) id@, but for a heteregenous list.
class HCompose l f | l -> f where
hComp :: l -> f
instance HCompose HNil (a -> a) where
hComp _ = id
instance HCompose r (a -> b) => HCompose ((b -> c) :*: r) (a -> c) where
hComp (HCons g r) = g . hComp r
-- | The difference between HNats. Clamped to HZero
class HSubtract a b c | a b -> c where
hSubtract :: a -> b -> c
instance (HNat a, HNat b, HSubtract a b c) => HSubtract (HSucc a) (HSucc b) c where
hSubtract a b = hSubtract (hPred a) (hPred b)
instance HNat a => HSubtract a HZero a where
hSubtract a _ = a
instance HSubtract HZero b HZero where
hSubtract _ _ = hZero
class HNat n => HReplicateF n e l | n e -> l where
hReplicateF :: n -> e -> l
instance HReplicateF HZero e HNil where
hReplicateF _ _ = HNil
instance (Apply e x y, HReplicateF n e r) => HReplicateF (HSucc n) e ((HFalse, x -> y) :*: r) where
hReplicateF n e = (hFalse, apply e) `HCons` hReplicateF (hPred n) e
-- | exactly like hPred, but accept HZero too
class HPred' n n' | n -> n' where
hPred' :: n -> n'
instance HPred' HZero HZero where
hPred' _ = hZero
instance HNat n => HPred' (HSucc n) n where
hPred' = hPred
insLt n hold f l =
l
`hAppend`
(hReplicateF ({-hPred' $ -} n `hSubtract` hLength l) Id)
`hAppend`
((hold,f) `HCons` HNil)
insGeq n a f l =
let (b,g) = hLookupByHNat n l
h = hCond b (b,g) (a,f . g)
in hUpdateAtHNat n h l
-- | utility class, so that we can use contexts that may not be satisfied,
-- depending on the length of the accumulated list.
class (HBool hold) => Ins2 b n hold f l l' | b n hold f l -> l' where
ins2 :: b -> n -> hold -> f -> l -> l'
-- | when l needs to be padded with id
instance
(-- HPred' a n',
HLength l n,
HSubtract a1 n a,
-- HReplicateF n' Id l',
HReplicateF a Id l',
HAppend l l' l'',
HAppend l'' (HCons (hold,e) HNil) l''1,
HBool hold) =>
Ins2 HTrue a1 hold e l l''1
where ins2 _ = insLt
-- | when l already has enough elements, just compose. Only when the existing HBool is HFalse
instance
(HLookupByHNat n l (t, a -> b),
HUpdateAtHNat n z l l',
HCond t (t, a -> b) (t1, a -> c) z,
HBool t1) =>
Ins2 HFalse n t1 (b -> c) l l'
where ins2 _ = insGeq
class Ins' n hold f l l' | n hold f l -> l' where
ins' :: n -> hold -> f -> l -> l'
instance (HLength l ll, HLt ll n b, Ins2 b n hold f l l') => Ins' n hold f l l' where
ins' = ins2 (undefined :: b)
{- | @ins n f xs@ inserts at index @n@ the function f, or extends the list @xs@
with 'id' if there are too few elements. This way the precedence is not
bounded.
-}
ins n e = ins' n hFalse (e =<<)
runConfig' defConfig x = do
let Config c = hComp (hMap Snd (hComp (hEnd x) HNil)) (return defConfig)
(a,w) <- runWriterT c
print (w [])
return a
--runConfig :: (X.LayoutClass l X.Window, Read (l X.Window)) => Config (X.XConfig l) -> IO ()
runConfig x = X.xmonad =<< runConfig' X.defaultConfig x
-- * Tests
data T1 a = T1 a deriving Show
data T2 a = T2 a deriving Show
data T3 a = T3 a deriving Show
data T3a a = T3a a deriving Show
data RunMWR = RunMWR
instance (Monad m, HCompose l (m () -> Writer w a)) => Apply RunMWR l (a, w) where
apply _ x = runWriter $ hComp x (return ())
data Print = Print
instance Show a => Apply Print a (IO ()) where
apply _ = print
data HHMap a = HHMap a
instance HMap f a b => Apply (HHMap f) a b where
apply (HHMap f) = hMap f
{- | Verification that insertions happen in order
> (T1 (),"3")
> (T2 (T1 ()),"31")
> (T2 (T3 (T1 ())),"321")
> (T2 (T3a (T3 (T1 ()))),"3221")
-}
test :: IO ()
test = sequence_ $ hMapM Print $ hMap RunMWR $ hMap (HHMap Snd) $ hEnd $ hBuild
test1_
test2_
test3_
test3a_
where
test1_ = ins (undefined `asTypeOf` hSucc (hSucc (hSucc hZero))) (\x -> tell "3" >> return (T1 x)) hNil
test2_ = ins (hSucc hZero) (\x -> tell "1" >> return (T2 x)) test1_
test3_ = ins (hSucc (hSucc hZero)) (\x -> tell "2" >> return (T3 x)) test2_
test3a_ = ins (hSucc (hSucc hZero)) (\x -> tell "2" >> return (T3a x)) test3_
{- Generated instances for monomorphic fields in 'X.XConfig'
Follows the style of:
> data FFM = FFM
> instance Mode ModifyIO FFM (Bool -> Config Bool) l l where
> m _ _ f c = do
> r <- f (X.fFM c)
> return $ c { X.fFM = r }
And the same for Modify, Set
> instance (Fail (Expected String)) => Mode ModifyIO FFM y z w where
> instance (Fail (Expected String)) => Mode Modify FFM y z w where
> instance (Fail (Expected String)) => Mode Set FFM y z w where
The last set of overlapping instances exist to help type inference here:
> :t m ModifyIO NormalBorderColor
> m ModifyIO NormalBorderColor
> :: (String -> Config String) -> XConfig x -> Config (XConfig x)
Otherwise it would just give you:
> m ModifyIO NormalBorderColor
> :: Mode ModifyIO NormalBorderColor e x y =>
> e -> XConfig x -> Config (XConfig y)
Which doesn't really matter overall since @x@ ends up fixed when you try
to run the config.
-}
-- | Improve error messages maybe.
data Expected a
$(fmap concat $ sequence
[ do
-- do better by using quoted names in the first place?
let accessor = "X." ++ (case nameBase d of
x:xs -> toLower x:xs
_ -> [])
acc = mkName accessor
VarI _ (ForallT _ _ (_ `AppT` (return -> ty))) _ _ <- reify acc
l <- fmap varT $ newName "l"
let mkId action tyIn body = instanceD
(return [])
[t| $(conT ''Mode) $(conT action) $(conT d) $(tyIn) $l $l |]
[funD 'm
[clause
[wildP,wildP]
(normalB body
)
[]
]
]
`const` (action, tyIn) -- suppress unused var warning
let fallback act = instanceD
(sequence [classP ''Fail [[t| Expected $ty |]]])
[t| $(conT ''Mode) $act $(conT d) $(varT =<< newName "x") $l $l |]
[funD 'm [clause [] (normalB [| error "impossible to satisfy" |]) [] ]]
`const` act -- suppress unused var warning
sequence $
[fallback (conT n) | n <- [''ModifyIO, ''Modify, ''Set] ] ++
[dataD (return []) d [] [normalC d []] []
,mkId ''ModifyIO [t| $ty -> Config $ty |]
[| \f c -> do
r <- f ($(varE acc) c)
return $(recUpdE
[| c |]
[fmap (\r' -> (acc,r')) [| r |]])
|]
,mkId ''Modify [t| $ty -> $ty |]
[| \f c -> do
r <- return $ f ($(varE acc) c)
return $(recUpdE
[| c |]
[fmap (\r' -> (acc,r')) [| r |]])
|]
,mkId ''Set [t| $ty |]
[| \f c -> do
return $(recUpdE
[| c |]
[fmap ((,) acc) [| f |]])
|]
]
| d <- map mkName
-- fields in XConf
-- XXX make these ' versions so we can be hygenic
["NormalBorderColor",
"FocusedBorderColor",
"Terminal",
-- "LayoutHook", -- types $l and $l change with updates
"ManageHook",
"HandleEventHook",
"Workspaces",
"ModMask",
"Keys",
"MouseBindings",
"BorderWidth",
"LogHook",
"StartupHook",
"FocusFollowsMouse"]
]
)
| LeifW/xmonad-extras | XMonad/Config/Alt/Internal.hs | bsd-3-clause | 12,595 | 5 | 22 | 3,931 | 3,240 | 1,781 | 1,459 | -1 | -1 |
module Bead.View.Markdown (
markdownToHtml
, serveMarkdown
) where
{- A markdown to HTML conversion. -}
import Control.Monad.IO.Class
import qualified Data.ByteString.Char8 as BS
import Data.Either
import Data.String
import Data.String.Utils (replace)
import System.Directory
import System.FilePath
import Snap.Core
import Text.Pandoc.Options
import Text.Pandoc.Readers.Markdown (readMarkdown)
import Text.Pandoc.Writers.HTML (writeHtml)
import Text.Blaze.Html5
import Bead.View.BeadContext
import Bead.View.ContentHandler
import Bead.View.I18N
import Bead.View.Pagelets
import Bead.View.Translation
-- Produces an HTML value from the given markdown formatted strings what
-- comes from a text area field, crlf endings must be replaced with lf in the string
markdownToHtml :: String -> Html
markdownToHtml = either (fromString . show) (writeHtml def') . readMarkdown def . replaceCrlf
where def' = def { writerHTMLMathMethod = MathML Nothing }
replaceCrlf :: String -> String
replaceCrlf = replace "\r\n" "\n"
serveMarkdown :: BeadHandler ()
serveMarkdown = do
rq <- getRequest
let path = "markdown" </> (BS.unpack $ rqPathInfo rq)
exists <- liftIO $ doesFileExist path
let render = renderBootstrapPublicPage . publicFrame
if exists
then do
contents <- liftIO $ readFile path
render $ return $ markdownToHtml contents
else do
render $ do
msg <- getI18N
return $ do
p $ fromString . msg $
msg_Markdown_NotFound "Sorry, but the requested page could not be found."
| pgj/bead | src/Bead/View/Markdown.hs | bsd-3-clause | 1,713 | 0 | 18 | 447 | 367 | 203 | 164 | 41 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module UnitTest.Util.HogeTest (testSuite) where
import Test.Framework (defaultMain, Test)
import Test.Framework.Providers.QuickCheck2
import Test.Framework.TH
main = defaultMain [testSuite]
testSuite :: Test
testSuite = $(testGroupGenerator)
prop_concat :: [[Int]] -> Bool
prop_concat xs = concat xs == foldr (++) [] xs
| hyone/haskell-unittest-project-template | src/UnitTest/Util/HogeTest.hs | bsd-3-clause | 360 | 0 | 7 | 48 | 105 | 62 | 43 | 10 | 1 |
module System.GPIO
-- Re-exported types
( Pin(..)
, fromInt
, ActivePin
, Value(..)
, Direction
-- Exported API
, initReaderPin
, initWriterPin
, readPin
, writePin
, reattachToReaderPin
, reattachToWriterPin
, closePin
) where
import Control.Exception (SomeException (..))
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Maybe
import Safe
import System.Directory
import System.GPIO.Path
import System.GPIO.Types
data PinException
= InitPinException Pin String
| SetDirectionException Pin Direction String
| ReadPinException Pin String
| WritePinException Pin Value String
| ReattachPinException Pin String
| ClosePinException Pin String
deriving (Show)
instance Exception PinException
initReaderPin :: (MonadCatch m, MonadIO m) => Pin -> m (ActivePin 'In)
initReaderPin = initPin . ReaderPin
initWriterPin :: (MonadCatch m, MonadIO m) => Pin -> m (ActivePin 'Out)
initWriterPin = initPin . WriterPin
initPin :: (MonadCatch m, MonadIO m) => ActivePin a -> m (ActivePin a)
initPin pin = do
withVerboseError (InitPinException (unpin pin)) $
writeFileM exportPath (toData $ unpin pin)
withVerboseError (SetDirectionException (unpin pin) (direction pin)) $
writeFileM (directionPath $ unpin pin) (toData (direction pin))
return pin
readPin :: (MonadCatch m, MonadIO m) => ActivePin a -> m Value
readPin pin = do
x <- readFirstLine $ valuePath (unpin pin)
case fromData x of
Right v -> return v
Left e -> throwM $ ReadPinException (unpin pin) e
writePin :: (MonadCatch m, MonadIO m) => Value -> ActivePin 'Out -> m ()
writePin value pin = withVerboseError (WritePinException (unpin pin) value)
$ writeFileM (valuePath $ unpin pin) (toData value)
-- Get an active pin from a pin, preserving the invariants required when a pin is initialized.
-- Useful for CLI type commands where pointers to an active pin can be lost between calls.
reattachToReaderPin :: (MonadCatch m, MonadIO m) => Pin -> m (ActivePin 'In)
reattachToReaderPin = reattachToPin . ReaderPin
reattachToWriterPin :: (MonadCatch m, MonadIO m) => Pin -> m (ActivePin 'Out)
reattachToWriterPin = reattachToPin . WriterPin
reattachToPin :: (MonadCatch m, MonadIO m) => ActivePin a -> m (ActivePin a)
reattachToPin pin = do
let err = ReattachPinException (unpin pin)
exists <- liftIO $ doesFileExist (directionPath (unpin pin))
unless exists $ throwM (err "Pin was never initialized")
v <- fromData <$> readFirstLine (directionPath (unpin pin))
dir <- either (throwM . err) return v
unless (dir == direction pin) $ throwM (err "Attempting to reattach to pin in wrong direction")
return pin
closePin :: (MonadCatch m, MonadIO m) => ActivePin a -> m ()
closePin pin = withVerboseError (ClosePinException (unpin pin))
$ writeFileM unexportPath (toData $ unpin pin)
withVerboseError :: MonadCatch m => (String -> PinException) -> m () -> m ()
withVerboseError pinException = handle $ \(e :: SomeException) -> throwM $ pinException (show e)
writeFileM :: MonadIO m => FilePath -> String -> m ()
writeFileM fp = liftIO . writeFile fp
readFileM :: MonadIO m => FilePath -> m String
readFileM = liftIO . readFile
readFirstLine :: MonadIO m => FilePath -> m String
readFirstLine = fmap (fromMaybe mempty . headMay . lines) . readFileM
| TGOlson/gpio | lib/System/GPIO.hs | bsd-3-clause | 3,434 | 0 | 13 | 698 | 1,141 | 578 | 563 | -1 | -1 |
module Tests.Development.Cake where
import qualified Tests.Development.Cake.Options
import qualified Tests.Development.Cake.Core.Types
import Test.Framework
tests =
[ testGroup "Tests.Development.Cake.Core.Types"
Tests.Development.Cake.Core.Types.tests
, testGroup "Tests.Development.Cake.Options"
Tests.Development.Cake.Options.tests
]
main = defaultMain tests | nominolo/cake | unittests/Tests/Development/Cake.hs | bsd-3-clause | 399 | 0 | 7 | 63 | 69 | 45 | 24 | 10 | 1 |
module Text.Icalendar (
module Text.Icalendar.Event
, module Text.Icalendar.Types
, events
, parser
) where
import Data.Maybe
import Data.Time
import Text.Parsec
import qualified Text.Parsec.ByteString as PBS
import Text.Icalendar.Event
import Text.Icalendar.Parser
import Text.Icalendar.Token
import Text.Icalendar.Types
import Text.Icalendar.Util
parser :: PBS.Parser Vcalendar
parser = vcalendar <.> many tokenP
events :: Vcalendar -> [Event]
events = map nicerEvent . vcalEvents
nicerEvent :: Component -> Event
nicerEvent evt | isEvent evt = Event {
eventStart = start
, eventEnd = end
, eventSummary = summary
, eventProperties = properties
} where
properties = map prop2tuple $ componentProperties evt
prop2tuple (Property k params v) = (k, (params, v))
start = uncurry parseDateTimeField $ properties <!> "DTSTART"
end = uncurry parseDateTimeField $ properties <!> "DTEND"
summary = snd $ properties <!> "SUMMARY"
nicerEvent c = error $ "Unexpected component type " ++ componentType c
parseDateTimeField :: [(String, String)] -> String -> ZonedTime
parseDateTimeField params s = if isDate then parseDate Nothing s else parseDateTime tz s
where
isDate = Just "DATE" == lookup "VALUE" params
tz | last s == 'Z' = Nothing
| otherwise = Just . zone $ fromMaybe (error $ "Can't determine time zone for " ++ s) $ lookup "TZID" params
zone _ = read "PST" :: TimeZone -- TODO!
(<!>) :: [(String, v)] -> String -> v
l <!> k = fromMaybe (error $ "missing property " ++ k) $ lookup k l
| samstokes/icalendar-parser | Text/Icalendar.hs | bsd-3-clause | 1,558 | 0 | 13 | 306 | 491 | 267 | 224 | 38 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Parse ( train,
test
) where
import DataPath
import qualified Data.ByteString as B
import qualified Data.Attoparsec.ByteString as P
--parsing byte file
read32BitInt :: (Num a) => B.ByteString -> a
read32BitInt b = fromInteger $ sum $ fmap (uncurry (*)) $ zip [2^24,2^16,2^8,1] $ toInteger <$> ub
where ub = B.unpack b
parse32BitInt = read32BitInt <$> (P.take 4)
parseLabels = do magicNumber <- parse32BitInt
numberOfItems <- parse32BitInt
labels' <- B.unpack <$> (P.take numberOfItems)
let labels = toInteger <$> labels'
return ((magicNumber,numberOfItems),labels)
parseRow numberOfCols = B.unpack <$> (P.take numberOfCols)
parseImage numberOfRows numberOfCols = sequence $ take numberOfRows $ repeat $ parseRow numberOfCols
parseImages = do magicNumber <- parse32BitInt
numberOfImages <- parse32BitInt
numberOfRows <- parse32BitInt
numberOfCols <- parse32BitInt
images' <- P.many1 $ parseImage numberOfRows numberOfCols
let images = (fmap . fmap . fmap) toInteger images'
return ((magicNumber,numberOfImages,numberOfRows,numberOfCols),images)
killEither :: Either a b -> b
killEither (Left x) = undefined
killEither (Right x) = x
train' :: IO [(Integer,[[Integer]])]
train' = do labels' <- (P.parseOnly parseLabels) <$> (B.readFile trainLabelPath)
let labels = snd $ killEither labels'
images' <- (P.parseOnly parseImages) <$> (B.readFile trainImagePath)
let images = snd $ killEither images'
return $ zip labels images
test' :: IO [(Integer,[[Integer]])]
test' = do labels' <- (P.parseOnly parseLabels) <$> (B.readFile testLabelPath)
let labels = snd $ killEither labels'
images' <- (P.parseOnly parseImages) <$> (B.readFile testImagePath)
let images = snd $ killEither images'
return $ zip labels images
-- pixels above 100 go to 1
-- pixels below 100 go to 0
threshhold = 127
f x = if x < threshhold then 0 else 1
removeGreyScale (x,y) = (x, (fmap . fmap) f y)
train = (fmap . fmap) removeGreyScale train'
test = (fmap . fmap) removeGreyScale test'
| danielbarter/personal_website_code | blog_notebooks/Niave_Bayes_classification_MNIST/mnistclean/app/Parse.hs | bsd-3-clause | 2,317 | 0 | 13 | 610 | 757 | 391 | 366 | 44 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module API.Campbx (
feed
)
where
---------------------------------------------------------------------------------------------------
import Pipes
---------------------------------------------------------------------------------------------------
import qualified Data.ByteString.Char8 as BC
---------------------------------------------------------------------------------------------------
import API.BtcExchanges.Internal
feed :: Producer BC.ByteString IO ()
feed = httpFeed "campbx.com" 443 "/api/xdepth.php" 1
| RobinKrom/BtcExchanges | src/API/Campbx.hs | bsd-3-clause | 565 | 0 | 6 | 51 | 63 | 39 | 24 | 8 | 1 |
-- Copyright (c) 2015, Travis Bemann
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- o Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- o 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.
--
-- o Neither the name of the copyright holder nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{-# LANGUAGE OverloadedStrings #-}
module Network.IRC.Client.Amphibian.Default
(getDefaultConfig)
where
import Network.IRC.Client.Amphibian.Types
import qualified Network.IRC.Client.Amphibian.Encoding as E
import qualified Data.Text as T
import System.Locale (TimeLocale,
defaultTimeLocale)
import System.IO (FilePath)
import System.Directory (createDirectoryIfMissing,
doesDirectoryExist,
getAppUserDataDirectory)
import System.Environment.XDG.BaseDir (getUserConfigDir, getUserDataDir)
-- | Application name
applicationName :: T.Text
applicationName = "amphibian"
-- | Get default configuration.
getDefaultConfig :: IO Config
getDefaultConfig = do
configDir <- getDirectory getUserConfigDir
dataDir <- getDirectory getUserDataDir
return $ Config { confConfigDir = configDir,
confDataDir = dataDir,
confConfigPluginName = "amphibian.hs",
confPluginError = Right (),
confServerList = [],
confDefaultScriptEntry = "entry",
confScriptCompileOptions = ["-O2"],
confScriptEvalOptions = ["-02"],
confLanguage = "en",
confTimeLocale = defaultTimeLocale,
confLightBackground = False,
confCtcpVersion = "Amphibian 0.1",
confCtcpSource = "http://github.com/tabemann/amphibian",
confDefaultPort = 6667,
confDefaultUserName = "jrandomhacker",
confDefaultName = "J. Random Hacker",
confDefaultAllNicks = ["jrandomhacker"],
confDefaultPassword = Nothing,
confDefaultMode = [],
confDefaultEncoding = E.defaultEncoding,
confDefaultCtcpUserInfo = "I am J. Random Hacker." }
-- | Get directory.
getDirectory :: (String -> IO FilePath) -> IO FilePath
getDirectory query = do
newDir <- query $ T.unpack applicationName
newDirExists <- doesDirectoryExist newDir
if newDirExists
then return newDir
else do
oldDir <- getAppUserDataDirectory $ T.upack applicationName
oldDirExists <- doesDirectoryExist oldDir
if oldDirExists
then return oldDir
else do
createDirectoryIfMissing True newDir
return newDir
| tabemann/amphibian | src_old/Network/IRC/Client/Amphibian/Default.hs | bsd-3-clause | 3,985 | 0 | 13 | 996 | 450 | 273 | 177 | 54 | 3 |
-- |
-- Module : Data.CVector.Mutable
-- Copyright : (c) 2012-2013 Michal Terepeta
-- (c) 2009-2010 Roman Leshchinskiy
-- License : BSD-style
--
-- Maintainer : Michal Terepeta <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Wrapper around unboxed mutable 'Vector's implementing efficient 'pushBack' and
-- 'popBack' operations.
--
module Data.CVector.Unboxed.Mutable (
-- * CVector specific
CMVector, MVector(..), IOCVector, STCVector, Unbox,
capacity, fromVector, toVector, pushBack, popBack,
-- * Accessors
-- ** Length information
length, null,
-- ** Extracting subvectors
slice, init, tail, take, drop, splitAt,
unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop,
-- ** Overlapping
overlaps,
-- * Construction
-- ** Initialisation
new, unsafeNew, replicate, replicateM, clone,
-- ** Growing
grow, unsafeGrow,
-- ** Restricting memory usage
clear,
-- FIXME: what's up with those..?
-- * Zipping and unzipping
-- zip, zip3, zip4, zip5, zip6,
-- unzip, unzip3, unzip4, unzip5, unzip6,
-- * Accessing individual elements
read, write, swap,
unsafeRead, unsafeWrite, unsafeSwap,
-- * Modifying vectors
-- ** Filling and copying
set, copy, move, unsafeCopy, unsafeMove
) where
import Data.Vector.Unboxed.Base
import qualified Data.CVector.Generic.Mutable as G
import Control.Monad.Primitive
import Prelude hiding ( length, null, replicate, reverse, map, read,
take, drop, splitAt, init, tail,
zip, zip3, unzip, unzip3 )
import qualified Data.CVector.Generic.MutableInternal as GI
--
-- CVector specific
--
type CMVector = GI.CMVector MVector
type IOCVector = CMVector RealWorld
type STCVector = CMVector
-- | Yields the allocated size of the underlying 'Vector' (not the number of
-- elements kept in the CMVector). /O(1)/
capacity :: (Unbox a) => CMVector s a -> Int
capacity = G.capacity
{-# INLINE capacity #-}
-- | Create a CMVector from MVector. /O(1)/
fromVector :: (Unbox a) => MVector s a -> CMVector s a
fromVector = G.fromVector
{-# INLINE fromVector #-}
-- | Convert the CMVector to MVector (using 'slice'). /O(1)/
toVector :: (Unbox a) => CMVector s a -> MVector s a
toVector = G.toVector
{-# INLINE toVector #-}
-- | Push an element at the back of the CVector. If the size of the CVector and
-- its length are equal (i.e., it's full), the underlying Vector will be doubled
-- in size. Otherwise no allocation will be done and the underlying vector will
-- be shared between the argument and the result. /amortized O(1)/
pushBack :: (Unbox a, PrimMonad m)
=> CMVector (PrimState m) a -> a -> m (CMVector (PrimState m) a)
pushBack = G.pushBack
{-# INLINE pushBack #-}
-- | Remove an element from the back of the CVector. Calls 'error' if the
-- CVector is empty. Does not shrink the underlying Vector. /O(1)/
popBack :: (Unbox a, PrimMonad m) =>
CMVector (PrimState m) a -> m (CMVector (PrimState m) a)
popBack = G.popBack
{-# INLINE popBack #-}
--
-- Length information
--
length :: Unbox a => CMVector s a -> Int
length = G.length
{-# INLINE length #-}
null :: Unbox a => CMVector s a -> Bool
null = G.null
{-# INLINE null #-}
--
-- Extracting subvectors
--
slice :: Unbox a => Int -> Int -> CMVector s a -> CMVector s a
slice = G.slice
{-# INLINE slice #-}
take :: Unbox a => Int -> CMVector s a -> CMVector s a
take = G.take
{-# INLINE take #-}
drop :: Unbox a => Int -> CMVector s a -> CMVector s a
drop = G.drop
{-# INLINE drop #-}
splitAt :: Unbox a => Int -> CMVector s a -> (CMVector s a, CMVector s a)
splitAt = G.splitAt
{-# INLINE splitAt #-}
init :: Unbox a => CMVector s a -> CMVector s a
init = G.init
{-# INLINE init #-}
tail :: Unbox a => CMVector s a -> CMVector s a
tail = G.tail
{-# INLINE tail #-}
unsafeSlice :: (Unbox a) => Int -> Int -> CMVector s a -> CMVector s a
unsafeSlice = G.unsafeSlice
{-# INLINE unsafeSlice #-}
unsafeTake :: Unbox a => Int -> CMVector s a -> CMVector s a
unsafeTake = G.unsafeTake
{-# INLINE unsafeTake #-}
unsafeDrop :: Unbox a => Int -> CMVector s a -> CMVector s a
unsafeDrop = G.unsafeDrop
{-# INLINE unsafeDrop #-}
unsafeInit :: Unbox a => CMVector s a -> CMVector s a
unsafeInit = G.unsafeInit
{-# INLINE unsafeInit #-}
unsafeTail :: Unbox a => CMVector s a -> CMVector s a
unsafeTail = G.unsafeTail
{-# INLINE unsafeTail #-}
--
-- Overlapping
--
overlaps :: Unbox a => CMVector s a -> CMVector s a -> Bool
overlaps = G.overlaps
{-# INLINE overlaps #-}
--
-- Initialisation
--
new :: (PrimMonad m, Unbox a) => Int -> m (CMVector (PrimState m) a)
new = G.new
{-# INLINE new #-}
unsafeNew :: (PrimMonad m, Unbox a) => Int -> m (CMVector (PrimState m) a)
unsafeNew = G.unsafeNew
{-# INLINE unsafeNew #-}
replicate :: (PrimMonad m, Unbox a) => Int -> a -> m (CMVector (PrimState m) a)
replicate = G.replicate
{-# INLINE replicate #-}
replicateM :: (PrimMonad m, Unbox a) => Int -> m a -> m (CMVector (PrimState m) a)
replicateM = G.replicateM
{-# INLINE replicateM #-}
clone :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> m (CMVector (PrimState m) a)
clone = G.clone
{-# INLINE clone #-}
-- Growing
-- -------
grow :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> Int -> m (CMVector (PrimState m) a)
grow = G.grow
{-# INLINE grow #-}
unsafeGrow :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> Int -> m (CMVector (PrimState m) a)
unsafeGrow = G.unsafeGrow
{-# INLINE unsafeGrow #-}
--
-- Restricting memory usage
--
clear :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> m ()
clear = G.clear
{-# INLINE clear #-}
--
-- Accessing individual elements
--
read :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> Int -> m a
read = G.read
{-# INLINE read #-}
write :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> Int -> a -> m ()
write = G.write
{-# INLINE write #-}
swap :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> Int -> Int -> m ()
swap = G.swap
{-# INLINE swap #-}
unsafeRead :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> Int -> m a
unsafeRead = G.unsafeRead
{-# INLINE unsafeRead #-}
unsafeWrite :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> Int -> a -> m ()
unsafeWrite = G.unsafeWrite
{-# INLINE unsafeWrite #-}
unsafeSwap :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> Int -> Int -> m ()
unsafeSwap = G.unsafeSwap
{-# INLINE unsafeSwap #-}
--
-- Filling and copying
--
set :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> a -> m ()
set = G.set
{-# INLINE set #-}
copy :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> CMVector (PrimState m) a -> m ()
copy = G.copy
{-# INLINE copy #-}
unsafeCopy :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> CMVector (PrimState m) a -> m ()
unsafeCopy = G.unsafeCopy
{-# INLINE unsafeCopy #-}
move :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> CMVector (PrimState m) a -> m ()
move = G.move
{-# INLINE move #-}
unsafeMove :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> CMVector (PrimState m) a -> m ()
unsafeMove = G.unsafeMove
{-# INLINE unsafeMove #-}
| michalt/cvector | Data/CVector/Unboxed/Mutable.hs | bsd-3-clause | 7,195 | 0 | 12 | 1,482 | 2,135 | 1,170 | 965 | 148 | 1 |
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- | This module provides the abstract domain for primitive values.
module Jat.PState.AbstrDomain
( AbstrDomain (..), mkcon)
where
import Jat.JatM
import Jat.Utils.Pretty
import Jat.Constraints (PATerm, ass)
import Data.Maybe (isJust)
-- | The 'AbstrDomain' class.
class Pretty a => AbstrDomain a b | a -> b where
--join semi lattice
lub :: Monad m => a -> a -> JatM m a
top :: Monad m => JatM m a
isTop :: a -> Bool
leq :: a -> a -> Bool
--abstract domain
atom :: a -> PATerm
constant :: b -> a
fromConstant :: a -> Maybe b
isConstant :: a -> Bool
isConstant = isJust . fromConstant
widening :: Monad m => a -> a -> JatM m a
widening = lub
-- | Assignment constructor.
mkcon :: (AbstrDomain a b, AbstrDomain c d, AbstrDomain e f) =>
a -> (PATerm -> PATerm -> PATerm) -> c -> e -> PATerm
mkcon i f j k = atom i `ass` (atom j `f` atom k)
| ComputationWithBoundedResources/jat | src/Jat/PState/AbstrDomain.hs | bsd-3-clause | 961 | 0 | 10 | 220 | 323 | 177 | 146 | 23 | 1 |
module Main where
import qualified Text.Scalar.CLI as CLI
main :: IO ()
main = CLI.main
| corajr/scalar-convert | app/Main.hs | bsd-3-clause | 90 | 0 | 6 | 17 | 30 | 19 | 11 | 4 | 1 |
{-# LANGUAGE MultiParamTypeClasses,TemplateHaskell,QuasiQuotes #-}
module Language.XHaskell where
import Data.List (zip4,sort,nub,foldl1)
import qualified Data.Traversable as Trvsbl (mapM)
-- import Data.Generics
import Control.Monad
import qualified Language.Haskell.TH as TH
import Language.Haskell.TH.Quote
import qualified Data.Map as M
import Language.Haskell.Exts.Parser
import Language.Haskell.Exts.Syntax
import Language.Haskell.Exts.Extension
import Language.Haskell.Exts.Pretty
import qualified Language.XHaskell.Source as S
import qualified Language.XHaskell.Target as T
import Language.XHaskell.Error
import Language.XHaskell.Subtype
import Language.XHaskell.Environment ( TyEnv, mkTyEnv, addTyEnv, addRecTyEnv, unionTyEnv,
BdEnv, mkBdEnv,
ClEnv, mkClEnv, mkClTyEnv,
mkDtTyEnv,
InstEnv, mkInstEnv,
Constraint, ConstrEnv, unionConstrEnv, cxtToConstrs, cxtToConstrEnv, addConstrEnv, buildConstrEnv, deducible,
translateKind, translateType, translateContext, translateAsst, translateTyVarBind,
translateName, translateQName, untranslateName,
lookupQName, checkLitTy
)
import Language.XHaskell.LocalTypeInference ( SubtypeConstr, genSubtypeConstrs, solveSubtypeConstrs,
collapseConstrs, findMinSubst
)
-- | main function
xhDecls :: String -> TH.DecsQ
xhDecls s = case parseModuleWithMode S.xhPm s of
{ ParseFailed srcLoc errMsg -> failWithSrcLoc srcLoc $ "Parser failed " ++ errMsg
; ParseOk (Module srcLoc moduleName pragmas mb_warning mb_export import_decs decs) -> do
{ let tySigs = filter S.isTypeSig decs
funBinds = filter S.isFunBind decs
clDecls = filter S.isClassDecl decs
instDecls = filter S.isInstDecl decs
dtDecls = filter S.isDtDecl decs
; tyEnv1 <- mkTyEnv tySigs -- the type environment is using TH.Type
; tyEnv2 <- mkClTyEnv clDecls
; tyEnv3 <- mkDtTyEnv dtDecls
; let tyEnv = tyEnv1 `unionTyEnv` tyEnv2 `unionTyEnv` tyEnv3 -- 2) get the type environment
bdEnv = mkBdEnv funBinds -- 3) build the function name -> def binding environment
clEnv = mkClEnv clDecls -- 4) get the type class environment, name -> vars, functional dep, classFuncDecs
instEnv = mkInstEnv instDecls -- we don't need this -- 5) get the type class instance decls
; decsTH <- translateDecs tyEnv bdEnv clEnv instEnv decs
-- 6) for each type sig \in tyTEnv,
-- a) translate the type signatures to haskell representation
-- b) translate the body decl to haskell representation
; return decsTH }
}
translateDataDecl :: Decl -> TH.Q TH.Dec
translateDataDecl (DataDecl srcLoc DataType context dtName tyVarBinds qualConDecls derivings) = do
{ cxt <- translateContext context
; dtName' <- translateName dtName
; tyVarBinds' <- mapM translateTyVarBind tyVarBinds
; cons <- mapM translateQualConDecl qualConDecls
; names <- mapM translateDeriving derivings
; return $ TH.DataD cxt dtName' tyVarBinds' cons names
}
translateDataDecl (DataDecl srcLoc NewType context dtName tyVarBinds qualConDecls derivings) = do
{ cxt <- translateContext context
; dtName' <- translateName dtName
; tyVarBinds' <- mapM translateTyVarBind tyVarBinds
; con <- translateQualConDecl (head qualConDecls)
; names <- mapM translateDeriving derivings
; return $ TH.NewtypeD cxt dtName' tyVarBinds' con names
}
translateQualConDecl :: QualConDecl -> TH.Q TH.Con
translateQualConDecl (QualConDecl srcLoc [] [] (ConDecl dcName dtypes)) = do
-- NormalC
{ sTys <- mapM translateBangType dtypes
; name' <- translateName dcName
; return (TH.NormalC name' sTys)
}
translateQualConDecl (QualConDecl srcLoc [] [] (RecDecl dcName names_type_pair)) = do
-- RecC
{ varStrictTypes <- mapM (\ (names, dtype) -> do
{ (s,ty) <- translateBangType dtype
; names' <- mapM translateName names
; return (map (\name' -> (name', s, ty)) names')
} ) names_type_pair
; name' <- translateName dcName
; return (TH.RecC name' (concat varStrictTypes))
}
translateQualConDecl (QualConDecl srcLoc [] [] (InfixConDecl dtype1 dcName dtype2)) = do
-- InfixC
{ name' <- translateName dcName
; sty1 <- translateBangType dtype1
; sty2 <- translateBangType dtype2
; return (TH.InfixC sty1 name' sty2)
}
translateQualConDecl (QualConDecl srcLoc tyVarBinds context condecl) = do
{ con <- translateQualConDecl (QualConDecl srcLoc [] [] condecl)
; tyVarBinds' <- mapM translateTyVarBind tyVarBinds
; context' <- translateContext context
; return (TH.ForallC tyVarBinds' context' con)
}
translateBangType :: Type -> TH.Q (TH.Strict, TH.Type)
translateBangType (TyBang BangedTy t) = do
{ t' <- translateType t
; return (TH.IsStrict, T.xhTyToHsTy t')
}
translateBangType (TyBang UnpackedTy t) = do
{ t' <- translateType t
; return (TH.Unpacked, T.xhTyToHsTy t')
}
translateBangType t = do
{ t' <- translateType t
; return (TH.NotStrict, T.xhTyToHsTy t')
}
translateDeriving :: Deriving -> TH.Q TH.Name
translateDeriving (qname, tys) = translateQName qname -- what are the types 'tys'?
-- getting across target and src types
instance Subtype TH.Type Type where
ucast srcLoc t1 t2 = do
{ t2' <- translateType t2
; ucast srcLoc t1 t2'
}
dcast srcLoc t1 t2 = do
{ t2' <- translateType t2
; dcast srcLoc t1 t2'
}
-- | translate XHaskell Decls (in Language.Haskell.Exts.Syntax ) to Template Haskell (in Language.Haskell.TH.Syntax)
translateDecs :: TyEnv -> BdEnv -> ClEnv -> InstEnv -> [Decl] -> TH.Q [TH.Dec]
translateDecs tyEnv bdEnv clEnv instEnv [] = return []
{-
tenv U { (f:t) }, bdEnv, clEnv |- bdEnv(f) : t ~> E
------------------------------------------------------------
tenv, bdEnv, clEnv |- f : t ~> f : [[t]]
f = E
-}
translateDecs tyEnv bdEnv clEnv instEnv ((TypeSig src idents ty):decs) = do
-- The translation is triggered by the type signature (which is compulsory in xhaskell)
-- The function bindings are read off from bdEnv. Those remain in decs will be skipped.
{ qDecs <- mapM (\ident -> translateFunc tyEnv bdEnv clEnv instEnv ident) idents
-- ; TH.runIO (putStrLn (TH.pprint qDecs))
; qDecss <- translateDecs tyEnv bdEnv clEnv instEnv decs
; return ((concat qDecs) ++ qDecss)
}
translateDecs tyEnv bdEnv clEnv instEnv (dec@(InstDecl src mb_overlap tvbs ctxt name tys instDecl):decs) = do
{ qDec <- translateInst tyEnv clEnv instEnv dec
; qDecss <- translateDecs tyEnv bdEnv clEnv instEnv decs
; return (qDec:qDecss)
}
translateDecs tyEnv bdEnv clEnv instEnv (dec@(ClassDecl src ctxt name tybnd fds classDecl):decs) = do
{ qDec <- translateClass tyEnv clEnv instEnv dec
; qDecss <- translateDecs tyEnv bdEnv clEnv instEnv decs
; return (qDec:qDecss)
}
translateDecs tyEnv bdEnv clEnv instEnv (dec@(DataDecl src dataOrNew context dtName tyVarBinds qualConDecls derivings):decs) = do
{ qDec <- translateDataDecl dec
; qDecss <- translateDecs tyEnv bdEnv clEnv instEnv decs
; return (qDec:qDecss)
}
translateDecs tyEnv bdEnv clEnv instEnv (pBnd@(PatBind src p {- mbTy -} rhs bdDecs):decs) = do
{ qDec <- translatePatBind tyEnv bdEnv clEnv instEnv pBnd
; qDecss <- translateDecs tyEnv bdEnv clEnv instEnv decs
; return (qDec:qDecss)
}
translateDecs tyEnv bdEnv clEnv instEnv (_:decs) = translateDecs tyEnv bdEnv clEnv instEnv decs
translatePatBind :: TyEnv -> BdEnv -> ClEnv -> InstEnv -> Decl -> TH.Q TH.Dec {- removed after HSX 1.16. Question when do we get this on the declaration level???
translatePatBind tyEnv bdEnv clEnv instEnv (PatBind src (PVar ident) (Just ty) (UnGuardedRhs e) bdDecs) = do
{ let cenv = buildConstrEnv clEnv instEnv
; ident' <- translateName ident
; ty' <- translateType ty
; e' <- translateExpC src tyEnv cenv e ty'
; return $ TH.ValD (TH.VarP ident') (TH.NormalB e') []
}
-}
translatePatBind tyEnv bdEnv clEnv instEnv (PatBind src (PVar ident) {- Nothing -} (UnGuardedRhs e) bdDecs) = do
{ let cenv = buildConstrEnv clEnv instEnv
; ident' <- translateName ident
; case M.lookup ident tyEnv of
{ Nothing -> failWithSrcLoc src $ "unable to find type info for variable " ++ TH.pprint ident'
; Just (ty',_) -> do
{ e' <- translateExpC src tyEnv cenv e ty'
; return $ TH.ValD (TH.VarP ident') (TH.NormalB e') []
}
}
}
{-
tenv, bdEnv, clEnv |- class ctxt => C \bar{t} | \bar{fd} where \bar{f:t'} ~>
class ctxt => C \bar{t} | \bar{fd} where \bar{f:[[t']]}
-}
translateClass :: TyEnv -> ClEnv -> InstEnv -> Decl -> TH.Q TH.Dec
translateClass tyEnv clEnv instEnv (ClassDecl src ctxt name tybnds fds classDecls) = do
{ ctxt' <- translateContext ctxt
; name' <- translateName name
; tybnds' <- mapM translateTyVarBind tybnds
; fds' <- mapM translateFunDep fds
; classDecls' <- mapM translateClassDecl classDecls
; return (TH.ClassD ctxt' name' tybnds' fds' (concat classDecls'))
}
{-
clEnv(C) = class C \bar{a} | \bar{fd} where \bar{f:t'}
theta = [\bar{t/a}]
tenv_c = \bar{f:theta(t')}
tenv U tenv_c, bdEnv, clEnv U \theta(ctxt) |- \bar{f = e : \theta(t')} ~> \bar{f = E}
-------------------------------------------------------------------------------------------------
tenv, bdEnv, clEnv |- instance ctxt => C \bar{t} where \bar{f=e} ~> instance ctxt => C \bar{[[t]]} where \bar{f=E}
-}
translateInst :: TyEnv -> ClEnv -> InstEnv -> Decl -> TH.Q TH.Dec
translateInst tyEnv clEnv instEnv (InstDecl src mb_overlap tvbs ctxt (UnQual name) tys instDecls) = do
{ ctxt' <- translateContext ctxt
; name' <- translateName name
; tys' <- mapM translateType tys
-- look for the theta, and the type class function definitions \bar{ f : t'}
; mbSubsts <- case M.lookup name clEnv of
{ Nothing -> {- get from reification -}
do { info <- TH.reify name'
; case info of
{ TH.ClassI (TH.ClassD cxt name tvbs fds decs) classInstances -> do
-- subst from TH.names to TH.types
-- tyEnv from class function name to TH.type
-- for tyEnv, we need to convert TH.name back to name,
-- todo: in future maybe tyenv should map TH.name to TH.type instead of name ot TH.type
{ let vs = map T.getTvFromTvb tvbs
subst = M.fromList (zip vs tys')
extractNameType (TH.SigD n t) = (untranslateName n,t)
tyEnv' = M.fromList (map extractNameType decs)
; return (Just (subst, M.map (T.applySubst subst) tyEnv'))
}
; _ -> return Nothing
}
}
; Just (srcLoc, ctxt, tvbs, fds, classDecls) ->
let varNames = map (\tyVar -> case tyVar of
{ UnkindedVar n -> n
; KindedVar n _ -> n
}) tvbs
in do
{ tyEnv' <- do { ntys <- mapM (\(ClsDecl (TypeSig src idents ty)) -> do
{ ty' <- translateType ty
; return (zip idents (repeat ty'))
}) classDecls
; return (M.fromList (concat ntys))
}
; varNames' <- mapM translateName varNames
; let subst = M.fromList (zip varNames' tys')
; return (Just (subst, M.map (T.applySubst subst) tyEnv'))
}
}
; case mbSubsts of
{ Nothing -> failWithSrcLoc src $ "unable to find the class definition given the instance definition"
; Just (subst, tenv') -> do
{ let tenv'' = M.map (\t -> (t,[])) tenv' -- padding with the empty list of record label names
tyEnv' = tyEnv `unionTyEnv` tenv''
cenv = buildConstrEnv clEnv instEnv
cenv' = cxtToConstrEnv ctxt'
cenv'' = cenv `unionConstrEnv` cenv'
; instDecls' <- mapM (translateInstDecl tyEnv' cenv'' subst tenv'') instDecls
; let htys' = map T.xhTyToHsTy tys'
; let ty' = foldl TH.AppT (TH.ConT name') htys'
; return (TH.InstanceD ctxt' ty' instDecls')
}
}
}
translateInst tyEnv clEnv instEnv (InstDecl src mb_overlap tvbs ctxt qname@(Qual modName name) tys instDecls) = -- since the the modName is qualified, it must be from another module
do
{ ctxt' <- translateContext ctxt
; name' <- translateQName qname
; tys' <- mapM translateType tys
; mbSubsts <- do
{ info <- TH.reify name'
; case info of
{ TH.ClassI (TH.ClassD cxt name tvbs fds decs) classInstances -> do
-- subst from TH.names to TH.types
-- tyEnv from class function name to TH.type
-- for tyEnv, we need to convert TH.name back to name,
-- todo: in future maybe tyenv should map TH.name to TH.type instead of name ot TH.type
{ let vs = map T.getTvFromTvb tvbs
subst = M.fromList (zip vs tys')
extractNameType (TH.SigD n t) = (untranslateName n,t)
tyEnv' = M.fromList (map extractNameType decs)
; return (Just (subst, M.map (T.applySubst subst) tyEnv'))
}
; _ -> return Nothing
}
}
; case mbSubsts of
{ Nothing -> failWithSrcLoc src $ "unable to find the class definition given the instance definition"
; Just (subst, tenv') -> do
{ let tenv'' = M.map (\t -> (t,[])) tenv' -- padding with the empty list of record label names
tyEnv' = tyEnv `unionTyEnv` tenv''
cenv = buildConstrEnv clEnv instEnv
cenv' = cxtToConstrEnv ctxt'
cenv'' = cenv `unionConstrEnv` cenv'
; instDecls' <- mapM (translateInstDecl tyEnv' cenv'' subst tenv'') instDecls
; let ty' = foldl TH.AppT (TH.ConT name') tys'
; return (TH.InstanceD ctxt' ty' instDecls')
}
}
}
-- | translate the instance function declaration
translateInstDecl :: TyEnv -> ConstrEnv -> T.Subst -> TyEnv -> InstDecl -> TH.Q TH.Dec
translateInstDecl tyEnv cenv subst tyEnv' (InsDecl (FunBind matches@((Match srcLoc name _ _ _ _):_))) =
case M.lookup name tyEnv' of
{ Nothing -> failWithSrcLoc srcLoc $ "unable to find type info for instance method"
; Just (ty,_) -> translateBody srcLoc tyEnv cenv name ty matches
}
-- translateBody tyEnv clEnv instEnv name ty matches
translateInstDecl _ _ _ _ _ = fail "associate data type declaration in type class instance is not suppported."
-- | translate a function definition
translateFunc :: TyEnv -> BdEnv -> ClEnv -> InstEnv -> Name -> TH.Q [TH.Dec]
translateFunc tyEnv bdEnv clEnv instEnv name =
case (M.lookup name tyEnv, M.lookup name bdEnv) of
{ (Just (ty,_), Just matches@((Match srcLoc _ _ _ _ _):_)) -> do
{ qTySig <- translateTypeSig name ty
; let cenv = buildConstrEnv clEnv instEnv
; qFunDec <- translateBody srcLoc tyEnv cenv name ty matches
; return [qTySig, qFunDec]
}
; (_, _) -> return []
}
{- not needed
isPolymorphic :: Type -> Bool
isPolymorphic (TyForall _ ctxt t) = isPolymorphic t
isPolymorphic (TyFun t1 t2) = isPolymorphic t1 || isPolymorphic t2
isPolymorphic (TyTuple _ ts) = any isPolymorphic ts
isPolymorphic (TyList t) = isPolymorphic t
isPolymorphic (TyApp t1 t2) = isPolymorphic t1 || isPolymorphic t2
isPolymorphic (TyVar _ ) = True
isPolymorphic (TyCon _ ) = False
isPolymorphic (TyParen t) = isPolymorphic t
isPolymorphic (TyInfix t1 qop t2) = isPolymorphic t1 || isPolymorphic t2
isPolymorphic (TyKind t k) = False
-}
-- | translate a type signature, the XHaskell type will be turned into Haskell type
translateTypeSig :: Name -> TH.Type -> TH.Q TH.Dec
translateTypeSig name ty = do
{ qName <- translateName name
-- ; qType <- translateType ty -- already in TH.Type
; let hsType = T.xhTyToHsTy ty
; return (TH.SigD qName hsType)
{- tvs = nub (sort (T.typeVars hsType))
; if (length tvs == 0)
then return (TH.SigD qName hsType)
else return (TH.SigD qName (TH.ForallT (map (\n -> TH.PlainTV n) tvs) emptyCtxt hsType))
-}
}
where emptyCtxt = []
-- | translate the functional dependency
translateFunDep :: FunDep -> TH.Q TH.FunDep
translateFunDep (FunDep names names') = do
{ names'' <- mapM translateName names
; names''' <- mapM translateName names'
; return (TH.FunDep names'' names''')
}
-- | translate the class function declaration
translateClassDecl :: ClassDecl -> TH.Q [TH.Dec]
translateClassDecl (ClsDecl (TypeSig src idents ty)) = do
{ ty' <- translateType ty
; mapM (\ident -> translateTypeSig ident ty') idents
}
translateClassDecl (ClsDecl decl) | S.isFunBind decl = fail "default function declaration in type class is not supported."
translateClassDecl (ClsDataFam _ _ _ _ _) = fail "associate data type declaration in type class is not suppported."
translateClassDecl (ClsTyFam _ _ _ _) = fail "type family declaration in type class is not suppported."
translateClassDecl (ClsTyDef _ _ _) = fail "associate type synonum declaration in type class is not suppported."
-- | translate a literal from Haskell Source Exts to Template Haskell Representation
translateLit :: Literal -> TH.Q TH.Lit
translateLit (Char c) = return (TH.CharL c)
translateLit (String s) = return (TH.StringL s)
translateLit (Int i) = return (TH.IntegerL i)
translateLit (Frac r) = return (TH.RationalL r)
translateLit (PrimInt i) = return (TH.IntPrimL i)
translateLit (PrimWord w) = return (TH.WordPrimL w)
translateLit (PrimFloat f) = return (TH.FloatPrimL f)
translateLit (PrimDouble d) = return (TH.DoublePrimL d)
translateLit (PrimChar c) = return (TH.CharL c)
translateLit (PrimString s) = return (TH.StringL s)
-- | translate the body of a function definition, which is a list of match-clauses from Haskell Source Exts to Template Haskell Representation
translateBody :: SrcLoc -> TyEnv -> ConstrEnv -> Name -> TH.Type -> [Match] -> TH.Q TH.Dec
translateBody pSrcLoc tenv cenv name ty ms = do
{ e <- desugarMatches pSrcLoc ms
; qe <- translateExpC pSrcLoc tenv cenv e ty
; qName <- translateName name
; return (TH.ValD (TH.VarP qName) (TH.NormalB qe) [{-todo:where clause-}] ) -- f = \x -> ...
}
{- | desugaring the function pattern syntax to the unabridged version
f [p = e] ==> f = \x -> case x of [p -> e]
-}
desugarMatches pSrcLoc ms = do
{ alts <- mapM matchToAlt ms
; let srcLoc = pSrcLoc
e = Lambda srcLoc [PVar (Ident "x")] (Case (Var (UnQual (Ident "x"))) alts)
; return e
}
where matchToAlt (Match srcLoc name [p] mbTy rhs binds) =
return (Alt srcLoc p rhs binds)
{-
where matchToAlt (Match srcLoc name [p] mbTy rhs binds) = do
{ let guardAlt = rhsToGuardAlt rhs
; return (Alt srcLoc p guardAlt binds) }
matchToAlt (Match srcLoc name _ mbTy rhs binds) = failWithSrcLoc srcLoc $ "can't handle multiple patterns binding \"f p1 p2 ... = e\" yet"
rhsToGuardAlt (UnGuardedRhs e) = UnGuardedAlt e
rhsToGuardAlt (GuardedRhss grhss) = GuardedAlts (map gRhsToGAlt grhss)
gRhsToGAlt (GuardedRhs srcLoc stmts e) = GuardedAlt srcLoc stmts e
-}
{-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| tenv |- e : t ~> E |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-}
{-
getType :: String -> TH.Q TH.Info
getType s = do
{ let n = TH.mkName s
; info <- TH.reify n
; return info -- we will get can't run reify in IO Monad error if we do it in GHCi, we need
-- $(TH.stringE . show =<< TH.reify (TH.mkName "map"))
}
-}
{-
*XHaskell Data.Typeable Language.Haskell.Exts.Pretty Language.Haskell.TH.Ppr> let (ParseOk t) = parseType ("Choice (Star Char) Int")
*XHaskell Data.Typeable Language.Haskell.Exts.Pretty Language.Haskell.TH.Ppr> x <- TH.runQ $ translateType t
*XHaskell Data.Typeable Language.Haskell.Exts.Pretty Language.Haskell.TH.Ppr> toRE x
Choice (Star (L "Char")) (L "Int")
-}
-- | translation of expression from Haskell Source Exts to TH.
-- | semantic subtyping is translated into ucast and regular expression pattern matching is translated into dcast
-- | type checking mode
translateExpC :: SrcLoc -> TyEnv -> ConstrEnv -> Exp -> TH.Type -> (TH.Q TH.Exp)
translateExpC pSrcLoc tenv cenv e@(Var qn) ty = do
{ (ty',_) <- lookupQName qn tenv
; case (T.isMono ty, T.isMono ty') of
{-
x : t' \in tenv
|- t' <= t ~> u
--------------------- (CVarM)
tenv, cenv |-^c x : t ~> u x
-}
{ (True, True) -> -- both are mono types
do
{ uc <- ucast pSrcLoc ty' ty
; qName <- translateQName qn
; return (TH.AppE uc (TH.VarE qName))
}
{-
x : \forall \bar{a}. C' => t' \in tenv
C' == C t' == t note: == modulo \bar{a}
--------------------- (CVarP)
tenv, cenv |-^c x : \forall \bar{a}. C => t ~> x
-}
; (False, False) | T.isomorphic ty ty' -> do
{ qName <- translateQName qn
; return (TH.VarE qName)
}
{- The inferred type is poly, but the incoming type is mono, it is a type application
x : \forall \bar{a}. C' => t' \in tenv
dom(theta) = \bar{a}
theta(t') = t note theta is a just substitution that grounds t' to t
theta(C) \subseteq cenv
--------------------- (CVarA)
tenv, cenv |-^c x : t ~> u x
-}
; (True, False) ->
case ty' of
{ TH.ForallT tvbs cxt ty'' ->
case T.findSubst ty' ty of
{ Just theta -> do
{ let constrs = cxtToConstrs $ T.applySubst theta cxt
; qName <- translateQName qn
; if (deducible constrs cenv)
then return (TH.VarE qName)
else failWithSrcLoc pSrcLoc $ "Unable to deduce " ++ (TH.pprint cxt) ++ " from the context " ++ (show cenv)
}
; Nothing -> failWithSrcLoc pSrcLoc $ "Unable to build substitution of " ++ (prettyPrint e) ++ ":" ++ (TH.pprint ty') ++ " from the type " ++ (TH.pprint ty)
}
}
; _ -> failWithSrcLoc pSrcLoc $ "translation failed. Trying to match expected type " ++ (TH.pprint ty) ++ " with inferred type " ++ (TH.pprint ty')
}
}
translateExpC pSrcLoc tenv cenv e@(Con qn) ty = do
{ (ty',_) <- lookupQName qn tenv
; case (T.isMono ty, T.isMono ty') of
{-
K : \forall a. C' => t' \in tenv
C' == C t' == t
--------------------- (CConP)
tenv, cenv |-^c K : \forall a. C => t ~> x
-}
{ (True, True) -> -- both are mono types
do
{ uc <- ucast pSrcLoc ty' ty
; qName <- translateQName qn
; return (TH.AppE uc (TH.ConE qName))
}
{-
K : t' \in tenv
|- t' <= t ~> u
--------------------- (CConM)
tenv, cenv |-^c K : t ~> u x
-}
; (False, False) | T.isomorphic ty ty' -> do
{ qName <- translateQName qn
; return (TH.ConE qName)
}
{-
K : \forall \bar{a}. C' => t' \in tenv
dom(theta) = \bar{a}
theta(t') = t note theta is a just subsitution that grounds t' to t
theta(C) \subseteq cenv
--------------------- (CConA)
tenv, cenv |-^c K : t ~> x
-}
; (True, False) ->
case ty' of
{ TH.ForallT tvbs cxt ty'' ->
case T.findSubst ty' ty of
{ Just theta -> do
{ let constrs = cxtToConstrs $ T.applySubst theta cxt
; qName <- translateQName qn
; if (deducible constrs cenv)
then return (TH.ConE qName)
else failWithSrcLoc pSrcLoc $ "Unable to deduce " ++ (TH.pprint cxt) ++ " from the context " ++ (show cenv)
}
; Nothing -> failWithSrcLoc pSrcLoc $ "Unable to build substitution of " ++ (prettyPrint e) ++ ":" ++ (TH.pprint ty') ++ " from the type " ++ (TH.pprint ty)
}
}
; _ -> failWithSrcLoc pSrcLoc $ "translation failed. Trying to match expected type " ++ (TH.pprint ty) ++ " with inferred type " ++ (TH.pprint ty')
}
}
{-
|- Lit : t'
t' <= t ~> u
--------------------------- (CLit)
tenv, cenv |-^c Lit : t ~> u Lit
-}
translateExpC pSrcLoc tenv cenv (Lit l) ty = do
{ ql <- translateLit l
; ty' <- checkLitTy l
; uc <- ucast pSrcLoc ty' ty
; return (TH.AppE uc (TH.LitE ql))
}
{-
(op : t1 -> t2 -> t3) \in tenv
tenv, cenv |-^i e1 : t1' ~> E1
tenv, cenv |-^i e2 : t2' ~> E2
|- t1' <= t1 ~> u1
|- t2' <= t2 ~> u2
|- t3 <= t ~> u3
-------------------------------------- (CBinOp)
tenv, cenv |-^c e1 `op` e2 : t ~> u3 ((op (u1 E1)) (u2 E2))
-}
translateExpC pSrcLoc tenv cenv (InfixApp e1 qop e2) ty = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e1
; (e2',t2') <- translateExpI pSrcLoc tenv cenv e2
; (qn, op') <- case qop of
{ QVarOp qn -> do
{ n <- translateQName qn
; return (qn, TH.VarE n)
}
; QConOp qn -> do
{ n <- translateQName qn
; return (qn, TH.ConE n)
}
}
; (ty',_) <- lookupQName qn tenv -- TH type
; case ty' of
{ TH.AppT (TH.AppT TH.ArrowT t1) (TH.AppT (TH.AppT TH.ArrowT t2) t3) -> do
{ u1 <- ucast pSrcLoc t1' t1
; u2 <- ucast pSrcLoc t2' t2
; u3 <- ucast pSrcLoc t3 ty
; return (TH.AppE u3 (TH.AppE (TH.AppE op' (TH.AppE u1 e1')) (TH.AppE u2 e2')))
}
; TH.ForallT tyVarBnds cxt t -> failWithSrcLoc pSrcLoc ((prettyPrint qop) ++ " has the the type " ++ (TH.pprint ty') ++ " is still polymorphic, please give it a type annotation.")
; _ -> failWithSrcLoc pSrcLoc ((prettyPrint qop) ++ ":" ++ (TH.pprint ty') ++ " is not a binary op.")
}
}
{-
f : forall \bar{a}. c => t1' -> ... tn' -> r \in tenv
tenv,cenv |-^i ei : ti ~> Ei
\bar{a} |- ti <: ti' ==> Di
S = solve(D1++ ... ++Dn, r)
|- ti <= S(ti') ~> ui
S(c) \subseteq cenv
S(r) <= t ~> u
----------------------------------------- (CEAppInf)
tenv,cenv |-^c f e1 ... en : t ~>
u (f (u1 E1) ... (un En))
-}
translateExpC pSrcLoc tenv cenv e@(App e1 e2) ty = do
{ mb <- appWithPolyFunc tenv e
; case mb of
{ Just (f, es) -> do
{ (f', tyF) <- translateExpI pSrcLoc tenv cenv f
; e't's <- mapM (translateExpI pSrcLoc tenv cenv) es
; case tyF of
{ TH.ForallT tyVarBnds ctxt t -> do
{ let as = map T.getTvFromTvb tyVarBnds
(ts, r) = T.breakFuncType t (length e't's)
es' = map fst e't's
ts' = map snd e't's
ds = concatMap (\(t,t') -> genSubtypeConstrs as [] t t') (zip ts' ts)
; s <- solveSubtypeConstrs ds r
{- ; TH.runIO ((putStrLn "====") >> putStrLn (prettyPrint e) >> (putStrLn ("s" ++ (show s))))
; TH.runIO (putStrLn ("ts':" ++ (TH.pprint ts')))
; TH.runIO (putStrLn ("t:" ++ (TH.pprint t)))
; TH.runIO (putStrLn ("ds:" ++ (show ds)))
; TH.runIO (putStrLn ("r:" ++ (TH.pprint r))) -}
; if deducible (cxtToConstrs $ T.applySubst s ctxt) cenv
then do
{ -- TH.runIO (putStrLn (TH.pprint (T.applySubst s t)))
; us <- mapM (\(t,t') -> inferThenUpCast pSrcLoc t t' -- t might be still polymorphic
) (zip ts' (map (T.applySubst s) ts))
; let ues = map (\(u,e) -> TH.AppE u e) (zip us es')
; u <- ucast pSrcLoc (T.applySubst s r) ty
; return (TH.AppE u (foldl TH.AppE f' ues))
}
else failWithSrcLoc pSrcLoc $ "Unable to deduce " ++ (TH.pprint (T.applySubst s ctxt)) ++ "from the context " ++ show cenv
}
; _ -> failWithSrcLoc pSrcLoc (TH.pprint tyF ++ " is not polymorphic.")
}
}
; _ -> do
{-
tenv, cenv |-^I e1 : t1 -> t2 ~> E1
tenv, cenv |-^I e2 : t1' ~> E2
|- t1' <= t1 ~> u1
|- t2 <= t ~> u2
------------------------------------- (CEApp)
tenv , cenv |-^c e1 e2 : t ~> u2 (E1 (u1 E2))
-}
{ (e1', t12) <- translateExpI pSrcLoc tenv cenv e1
; case t12 of
{ TH.AppT (TH.AppT TH.ArrowT t1) t2 -> do
{ (e2', t1') <- translateExpI pSrcLoc tenv cenv e2
; u1 <- ucast pSrcLoc t1' t1
; u2 <- ucast pSrcLoc t2 ty
; return (TH.AppE u2 (TH.AppE e1' (TH.AppE u1 e2')))
}
; TH.ForallT tyVarBnds cxt t -> failWithSrcLoc pSrcLoc ((prettyPrint e1) ++ ":" ++ (TH.pprint t12) ++ " is still polymorphic, please give it a type annotation.")
; _ -> failWithSrcLoc pSrcLoc ((prettyPrint e1) ++ ":" ++ (TH.pprint t12) ++ " is not a function.")
}
}
}
}
{-
tenv, cenv |-^c e : t ~> E
----------------------------- (CNeg)
tenv, cenv |-^c -e : t ~> -E
-}
translateExpC pSrcLoc tenv cenv (NegApp e) ty = do
{ e' <- translateExpC pSrcLoc tenv cenv e ty
; return (TH.AppE (TH.VarE (TH.mkName "GHC.Num.negate")) e')
}
{-
tenv U {(x:t1)}, cenv U C |- e : t2 ~> E
--------------------------------------------------------------------(CAbs)
tenv, cenv |-^c \x -> e : \forall \bar{a} C => t1 -> t2 ~> \x -> E
-}
translateExpC pSrcLoc tenv cenv e1@(Lambda srcLoc [PVar x] e) ty =
case ty of
{ TH.AppT (TH.AppT TH.ArrowT t1) t2 -> do
{ let tenv' = addTyEnv x t1 tenv
; e' <- translateExpC srcLoc tenv' cenv e t2
; x' <- translateName x
; return (TH.LamE [TH.VarP x'] e')
}
; TH.ForallT tvbs ctxt (TH.AppT (TH.AppT TH.ArrowT t1) t2) -> do
{ let tenv' = addTyEnv x t1 tenv
cenv' = addConstrEnv ctxt cenv
; e' <- translateExpC srcLoc tenv' cenv' e t2
; x' <- translateName x
; return (TH.LamE [TH.VarP x'] e')
}
; _ -> failWithSrcLoc srcLoc $ ((prettyPrint e1) ++ ":" ++ (TH.pprint ty) ++ " is not a function.")
}
{-
tenv U {(x:t3)}, cenv |- e : t2 ~> E
t1 <= t3 ~> u
-------------------------------------------------------(CAbsVA)
tenv, cenv |-^c \x:t3 -> e : t1 -> t2 ~> (\x -> E) . u
-}
translateExpC pSrcLoc tenv cenv e1@(Lambda srcLoc [(PParen (PatTypeSig srcLoc' (PVar x) t3))] e) ty =
case ty of
{ TH.AppT (TH.AppT TH.ArrowT t1) t2 -> do
{ t3' <- translateType t3
; u <- ucast srcLoc' t1 t3'
; let tenv' = addTyEnv x t3' tenv
; e' <- translateExpC srcLoc tenv' cenv e t2
; x' <- translateName x
; y <- TH.newName "y"
; return (TH.LamE [TH.VarP y] (TH.AppE (TH.LamE [TH.VarP x'] e') (TH.AppE u (TH.VarE y))))
}
; TH.ForallT tvbs ctxt (TH.AppT (TH.AppT TH.ArrowT t1) t2) ->
failWithSrcLoc srcLoc $ ((prettyPrint e1) ++ " has an polymorphic type annotation " ++ (TH.pprint ty))
; _ -> failWithSrcLoc srcLoc $ ((prettyPrint e1) ++ ":" ++ (TH.pprint ty) ++ " is not a function.")
}
{-
tenv, cenv |-^c \x -> case x of p -> e : t1 -> t2 ~> E
---------------------------------------------
tenv, cenv |-^c \p -> e : t1 -> t2 ~> \x -> E
-}
translateExpC pSrcLoc tenv cenv e0@(Lambda srcLoc [p] e) ty =
translateExpC pSrcLoc tenv cenv (Lambda srcLoc [PVar (Ident "x")]
(Case (Var (UnQual (Ident "x"))) [Alt srcLoc p (UnGuardedRhs e) (BDecls [])])) ty
translateExpC pSrcLoc tenv cenv (Lambda srcLoc ps e) ty = failWithSrcLoc srcLoc $ "can't handle multiple patterns lambda yet."
translateExpC pSrcLoc tenv cenv (Let binds e) ty = failWithSrcLoc pSrcLoc $ "can't handle let bindings yet."
{- tenv |-^c e1 : Bool ~> E1
tenv |-^c e2 : t ~> E2
tenv |-^c e3 : t ~> E3
------------------------------------------------------------ (CIf)
tenv |-^c if e1 then e2 else e3 : t ~> if E1 then E2 else E3
-}
translateExpC pSrcLoc tenv cenv (If e1 e2 e3) ty = do
{ e1' <- translateExpC pSrcLoc tenv cenv e1 (TH.ConT (TH.mkName "Bool"))
; e2' <- translateExpC pSrcLoc tenv cenv e2 ty
; e3' <- translateExpC pSrcLoc tenv cenv e3 ty
; return (TH.CondE e1' e2' e3')
}
{- old
tenv |-^I e : t ~> E'
foreach i
stripT p_i = t_i
stripP p_i = p_i'
p_i |- tenv_i
tenv U tenv_i |-^c e_i : t ~> E_i
|- t_i <= t ~> d_i
g_i next = case d_i E of {Just p_i' -> E_i; _ -> next}
--------------------------------------------------- (CCase)
tenv |-^c case e of [p -> e] : t ~>
g_1 (g_2 ... (g_n (error "unexhaustive pattern")))
-}
{-
translateExpC tenv cenv (Case e alts) ty = do
{ pis <- mapM pat alts
; eis <- mapM rhs alts
; pi's <- mapM patStripP pis
; tis <- mapM (patStripT tenv) pis
; tenvis <- mapM patTEnv pis
; (e', t) <- translateExpI tenv cenv e
; dis <- mapM (\ti -> dcast ti t) tis
; gis <- mapM (\(di,pi',ei, tenvi) -> do
{ let tenv' = unionTyEnv tenvi tenv
; ei' <- translateExpC tenv' cenv ei ty
; return (TH.LamE [TH.VarP (TH.mkName "next")]
(TH.CaseE (TH.AppE di e')
[ (TH.Match (TH.ConP (TH.mkName "Just") [pi']) (TH.NormalB ei') [])
, (TH.Match TH.WildP (TH.NormalB (TH.VarE (TH.mkName "next"))) [] )
]))
}) (zip4 dis pi's eis tenvis)
; err <- [|error "Pattern is not exhaustive."|]
; return $ foldl (\e g -> TH.AppE g e) err (reverse gis)
}
where pat :: Alt -> TH.Q Pat
pat (Alt srcLoc p _ _) = return p
rhs :: Alt -> TH.Q Exp
rhs (Alt srcLoc p (UnGuardedAlt e) _) = return e
rhs _ = fail "can't handled guarded pattern."
-}
{- newly extended with nested pattern matching
tenv,cenv |-^I e : t ~> E'
foreach i
stripT p_i = t_i
stripP p_i = p_i'
t_i, p_i |- tenv_i, guard_i, extract_i , p_i'', t_i' -- new extension
tenv U tenv_i, cenv |-^c e_i : t ~> E_i
|- t_i <= t ~> d_i
g_i guard_i extract_i next = case d_i E of {Just x@p_i' | guard_i x -> let p_i'' = extract_i x
in E_i; _ -> next}
--------------------------------------------------- (CCaseNested)
tenv,cenv |-^c case e of [p -> e] : t ~>
g_1 guard_1 extract_1 (g_2 ... (g_n guard_n extract_n (error "unexhaustive pattern")))
-}
translateExpC pSrcLoc tenv cenv (Case e alts) ty = do
{ pis <- mapM pat alts
; eis <- mapM rhs alts
; pi's <- mapM (patStripP pSrcLoc) pis
; tis <- mapM (patStripT pSrcLoc tenv) pis
; tenv_gd_ex_pi''s <- mapM (\(ti,pi) -> patEnv pSrcLoc tenv ti pi) (zip tis pis)
; (e', t) <- translateExpI pSrcLoc tenv cenv e
; dis <- mapM (\ti -> dcast pSrcLoc ti t) tis
; gis <- mapM (\(di,pi',ei, (tenvi,gdi,exti,pi'')) -> do
{ let tenv' = unionTyEnv tenvi tenv
; ei' <- translateExpC pSrcLoc tenv' cenv ei ty
; nn <- TH.newName "x"
; return (TH.LamE [TH.VarP (TH.mkName "next")]
(TH.CaseE (TH.AppE di e')
[ (TH.Match (TH.ConP (TH.mkName "Just") [TH.AsP nn pi']) (TH.GuardedB [ (TH.NormalG (TH.AppE gdi (TH.VarE nn)),
{- ei' -} TH.LetE [TH.ValD pi'' (TH.NormalB (TH.AppE exti (TH.VarE nn))) []] ei')]) [])
, (TH.Match TH.WildP (TH.NormalB (TH.VarE (TH.mkName "next"))) [] )
]))
}) (zip4 dis pi's eis tenv_gd_ex_pi''s)
; err <- [|error "Pattern is not exhaustive."|]
; return $ foldl (\e g -> TH.AppE g e) err (reverse gis)
}
where pat :: Alt -> TH.Q Pat
pat (Alt srcLoc p _ _) = return p
rhs :: Alt -> TH.Q Exp
rhs (Alt srcLoc p (UnGuardedRhs e) _) = return e
rhs (Alt srcLoc p _ _) = failWithSrcLoc srcLoc $ "can't handled guarded pattern."
patToExp :: TH.Pat -> TH.Exp
patToExp (TH.VarP n) = TH.VarE n
patToExp (TH.ConP n ps) = foldl (\e1 e2 -> TH.AppE e1 e2) (TH.ConE n) (map patToExp ps)
patToExp (TH.TupP ps) = TH.TupE (map patToExp ps)
patToExp p = error $ "patToExp failed: unexpected pattern " ++ (TH.pprint p)
{-
tenv, cenv |-^i e1 : t1 ~> E1
tenv, cenv |-^i e2 : t2 ~> E2
(t1,t2) <= t ~> u
--------------------------------------
tenv, cenv |-^c (e1,e2) : t ~> u (E1,E2)
-}
translateExpC pSrcLoc tenv cenv (Tuple boxed []) _ = failWithSrcLoc pSrcLoc ("empty tuple expxpression")
translateExpC pSrcLoc tenv cenv (Tuple boxed [e]) _ = failWithSrcLoc pSrcLoc ("singleton tuple expression")
translateExpC pSrcLoc tenv cenv (Tuple boxed [e1,e2]) t = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e1 -- todo: ensure t, t1' and t2' are monotype
; (e2',t2') <- translateExpI pSrcLoc tenv cenv e2
; u <- ucast pSrcLoc (TH.AppT (TH.AppT (TH.TupleT 2) t1') t2') t
; return (TH.AppE u (TH.TupE [e1',e2']))
}
translateExpC pSrcLoc tenv cenv (Tuple boxed (e:es)) t = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e
; (e2',t2') <- translateExpI pSrcLoc tenv cenv (Tuple boxed es)
; u <- ucast pSrcLoc (TH.AppT (TH.AppT (TH.TupleT 2) t1') t2') t
; return (TH.AppE u (TH.TupE [e1',e2']))
}
{-
tenv, cenv |-^c e : t ~> E
t <= t' ~> u
------------------------------------- (CTApp)
tenv , cenv |-^c (e :: t) : t' ~> u E
-}
translateExpC pSrcLoc tenv cenv e1@(ExpTypeSig srcLoc e t) t' = do
{ t'' <- translateType t
; e' <- translateExpC pSrcLoc tenv cenv e t''
; u <- ucast srcLoc t'' t'
; return (TH.AppE u e')
}
{-
tenv, cenv |-^i e : t' ~> E
for each i
l_i : t' -> t_i \in tenv
tenv, cenv |-^c e_i : t_i ~> E_i
|- t' <= t ~> u
------------------------------------- (CRecUM)
tenv, cenv |-^c e@{[l=e]} : t ~> u e@{[l=E]}
-}
{-
tenv, cenv |-^i e : forall a. t' ~> E
for each i
l_i : forall a. C => t' -> t_i \in tenv
\theta(t') = t \theta is a substitution grounds t' to t
\theta(C) \subseteq cenv
tenv, cenv |-^c e_i : \theta(t_i) ~> E_i
------------------------------------- (CRecUP)
tenv, cenv |-^c e@{[l=e]} : t ~> e@{[l=E]}
-}
translateExpC pSrcLoc tenv cenv (RecUpdate e fieldUpds) t = do -- todo poly version
{ (e',t') <- translateExpI pSrcLoc tenv cenv e
; if T.isMono t'
then do
{ fieldExps' <- mapM (\fu -> translateFieldUpd pSrcLoc tenv cenv fu t) fieldUpds
; u <- ucast pSrcLoc t' t
; return (TH.AppE u (TH.RecUpdE e' fieldExps'))
}
else failWithSrcLoc pSrcLoc $ "Type checker can't to handle polymorphic record exp"
}
{-
tenv, cenv |-^i K : t1 -> ... -> tn -> t' ~> K
for each i
l_i : t' -> t_i \in tenv
tenv, cenv |-^c e_i : t_i ~> E_i
|- t' <= t ~> u
------------------------------------- (CRecKM)
tenv, cenv |-^c e@{[l=e]} : t ~> u e@{[l=E]}
-}
{-
tenv, cenv |-^i e : forall a. t' ~> E
for each i
l_i : forall a. C => t' -> t_i \in tenv
\theta(t') = t \theta is a substitution grounds t' to t
\theta(C) \subseteq cenv
tenv, cenv |-^c e_i : \theta(t_i) ~> E_i
------------------------------------- (CRecKP)
tenv, cenv |-^c e@{[l=e]} : t ~> e@{[l=E]}
-}
translateExpC pSrcLoc tenv cenv (RecConstr n fieldUpds) t = do
-- todo poly version
{ n' <- translateQName n
; (r,ns) <- lookupQName n tenv
-- check the parity and prepare to fill the missing optional filed with ()s
; let missingFieldNames = findMissingFieldNames ns fieldUpds
; missingFieldNameTypeLookups <- mapM (\n -> lookupQName (UnQual n) tenv) missingFieldNames
; let missingFieldNameResultTypes = map (\(t,_) -> T.resultType t) missingFieldNameTypeLookups
; if T.isMono r
then do
{ let t' = T.resultType r
; fieldExps' <- mapM (\fu -> translateFieldUpd pSrcLoc tenv cenv fu t') fieldUpds
; u <- ucast pSrcLoc t' t
-- make sure all the missing names are having optional result type
-- and generate the expression
; missingFExps <- mapM (reconstructMissingFieldUpd pSrcLoc)
(zip missingFieldNames missingFieldNameResultTypes)
; return (TH.AppE u (TH.RecConE n' (fieldExps' ++ missingFExps)))
}
else failWithSrcLoc pSrcLoc "Type checker can't to handle polymorphic record exp"
}
translateExpC pSrcLoc tenv cenv (Paren e) t = translateExpC pSrcLoc tenv cenv e t
translateExpC pSrcLoc tenv cenv e ty = failWithSrcLoc pSrcLoc ("Type checker can't handle expression : " ++ (prettyPrint e))
-- | Inference mode
translateExpI :: SrcLoc -> TyEnv -> ConstrEnv -> Exp -> TH.Q (TH.Exp, TH.Type)
{-
x : \forall \bar{a}. C => t \in tenv
----------------------------------(IVarP)
tenv, cenv |-^i x : \forall \bar{a} . C => t ~> x
x : t \in tenv
-----------------------------------(IVarM)
tenv, cenv |-^i x : t ~> x
-}
translateExpI pSrcLoc tenv cenv (Var qn) = do
{ (ty,_) <- lookupQName qn tenv
; qName <- translateQName qn
; return (TH.VarE qName, ty)
}
{-
K : \forall \bar{a}. C => t \in tenv
----------------------------------(IConP)
tenv, cenv |-^i K : \forall \bar{a} . C => t ~> K
K : t \in tenv
-----------------------------------(IConM)
tenv, cenv |-^i K : t ~> K
-}
translateExpI pSrcLoc tenv cenv (Con qn) = do
{ (ty,_) <- lookupQName qn tenv
; qName <- translateQName qn
; return (TH.ConE qName, ty)
}
{-
|- Lit : t
--------------------------- (ILit)
tenv, cenv |-^c Lit : t ~> Lit
-}
translateExpI pSrcLoc tenv cenv (Lit l) = do
{ ql <- translateLit l
; ty <- checkLitTy l
; return (TH.LitE ql, ty)
}
{-
(op : t1 -> t2 -> t3) \in tenv
tenv,cenv |-^i e1 : t1' ~> E1
tenv,cenv |-^i e2 : t2' ~> E2
|- t1' <= t1 ~> u1
|- t2' <= t2 ~> u2
----------------------------- (IBinOp)
tenv,cenv |-^i e1 `op` e2 : t3 ~> (op (u1 E1)) (u2 E2)
-}
translateExpI pSrcLoc tenv cenv (InfixApp e1 qop e2) = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e1
; (e2',t2') <- translateExpI pSrcLoc tenv cenv e2
; (qn, op') <- case qop of
{ QVarOp qn -> do
{ n <- translateQName qn
; return (qn, TH.VarE n)
}
; QConOp qn -> do
{ n <- translateQName qn
; return (qn, TH.ConE n)
}
}
; (ty',_) <- lookupQName qn tenv -- TH type
; case ty' of
{ TH.AppT (TH.AppT TH.ArrowT t1) (TH.AppT (TH.AppT TH.ArrowT t2) t3) -> do
{ u1 <- ucast pSrcLoc t1' t1
; u2 <- ucast pSrcLoc t2' t2
; return (TH.AppE (TH.AppE op' (TH.AppE u1 e1')) (TH.AppE u2 e2'), t3)
}
; TH.ForallT tyVarBnds cxt t -> failWithSrcLoc pSrcLoc $ ((prettyPrint qop) ++ ":" ++ (TH.pprint ty') ++ " is still polymorphic, please give it a type annotation.")
; _ -> failWithSrcLoc pSrcLoc ((prettyPrint qop) ++ ":" ++ (TH.pprint ty') ++ " is not a binary op")
}
}
{-
f : forall \bar{a}. c => t1' -> ... tn' -> r \in tenv
tenv,cenv |-^i ei : ti ~> Ei
\bar{a} |- ti <: ti' ==> Di
S = solve(D1++ ... ++Dn, r)
|- ti <= S(ti') ~> ui
S(c) \subseteq cenv
----------------------------------------- (IEAppInf)
tenv,cenv |-^i f e1 ... en : S(r) ~>
f (u1 E1) ... (un En)
-}
translateExpI pSrcLoc tenv cenv e@(App e1 e2) = do
{ mb <- appWithPolyFunc tenv e
; case mb of
{ Just (f, es) -> do
{ (f', tyF) <- translateExpI pSrcLoc tenv cenv f
; e't's <- mapM (translateExpI pSrcLoc tenv cenv) es
; case tyF of
{ TH.ForallT tyVarBnds ctxt t -> do
{ let as = map T.getTvFromTvb tyVarBnds
(ts, r) = T.breakFuncType t (length e't's)
es' = map fst e't's
ts' = map snd e't's
ds = concatMap (\(t,t') -> genSubtypeConstrs as [] t t') (zip ts' ts)
; s <- solveSubtypeConstrs ds r
{- ; TH.runIO ((putStrLn "====") >> putStrLn (prettyPrint e) >> (putStrLn ("s" ++ (show s))))
; TH.runIO (putStrLn ("ts':" ++ (TH.pprint ts')))
; TH.runIO (putStrLn ("t:" ++ (TH.pprint t)))
; TH.runIO (putStrLn ("ds:" ++ (show ds)))
; TH.runIO (putStrLn ("r:" ++ (TH.pprint r))) -}
; if deducible (cxtToConstrs $ T.applySubst s ctxt) cenv
then do
{ -- TH.runIO (putStrLn (TH.pprint (T.applySubst s t)))
; us <- mapM (\(t,t') -> inferThenUpCast pSrcLoc t t' -- t might be still polymorphic
) (zip ts' (map (T.applySubst s) ts))
; let ues = map (\(u,e) -> TH.AppE u e) (zip us es')
; return (foldl TH.AppE f' ues, T.applySubst s r)
}
else failWithSrcLoc pSrcLoc $ "Unable to deduce " ++ (TH.pprint (T.applySubst s ctxt)) ++ "from the context " ++ show cenv
}
; _ -> failWithSrcLoc pSrcLoc (TH.pprint tyF ++ " is not polymorphic.")
}
}
; _ -> do
{-
tenv,cenv |-^i e1 : t1 -> t2 ~> E1
tenv,cenv |-^i e2 : t1' ~> E2
|- t1' <= t1 ~> u1
----------------------------------------- (IEApp)
tenv,cenv |-^c e1 e2 : t2 ~> E1 (u1 E2)
-}
-- translateExpI tenv cenv (App e1 e2) = do
{ (e1', t12) <- translateExpI pSrcLoc tenv cenv e1
; case t12 of
{ TH.AppT (TH.AppT TH.ArrowT t1) t2 -> do
{ (e2', t1') <- translateExpI pSrcLoc tenv cenv e2
; u1 <- ucast pSrcLoc t1' t1
; return (TH.AppE e1' (TH.AppE u1 e2'), t2)
}
; TH.ForallT tyVarBnds cxt t -> failWithSrcLoc pSrcLoc ((prettyPrint e1) ++ ":" ++ (TH.pprint t12) ++ " is still polymorphic, please give it a type annotation.")
; _ -> failWithSrcLoc pSrcLoc ((prettyPrint e1) ++ ":" ++ (TH.pprint t12) ++ " is not a function.")
}
}
}
}
{-
tenv |-^i e : t ~> E
-------------------------- (INeg)
tenv |-^i -e : t ~> -E
-}
translateExpI pSrcLoc tenv cenv (NegApp e) = do
{ (e',t) <- translateExpI pSrcLoc tenv cenv e
; return (TH.AppE (TH.VarE (TH.mkName "GHC.Num.negate")) e',t)
}
translateExpI pSrcLoc tenv cenv (Let binds e) = failWithSrcLoc pSrcLoc $ "can't handle let bindings yet."
{- tenv, cenv |-^c e1 : Bool ~> E1
tenv, cenv |-^i e2 : t2 ~> E2
tenv,cenv |-^i e3 : t3 ~> E3
------------------------------------------------------------
tenv, cenv |-^i if e1 then e2 else e3 : (t2|t3) ~> if E1 then E2 else E3
-}
translateExpI pSrcLoc tenv cenv (If e1 e2 e3) = do
{ e1' <- translateExpC pSrcLoc tenv cenv e1 (TH.ConT (TH.mkName "Bool")) -- (TyCon (UnQual (Ident "Bool")))
; (e2',t2) <- translateExpI pSrcLoc tenv cenv e2
; (e3',t3) <- translateExpI pSrcLoc tenv cenv e3
; return (TH.CondE e1' e2' e3', TH.AppT (TH.AppT (TH.ConT (TH.mkName "Choice")) t2) t3)
}
{-
tenv |-^i e1 : t1 ~> E1
tenv |-^i e2 : t2 ~> E2
--------------------------------------
tenv |-^i (e1,e2) : (t1,t2) ~> (E1,E2)
-}
translateExpI pSrcLoc tenv cenv (Tuple boxed []) = failWithSrcLoc pSrcLoc ("empty tuple expxpression")
translateExpI pSrcLoc tenv cenv (Tuple boxed [e]) = failWithSrcLoc pSrcLoc ("singleton tuple expression")
translateExpI pSrcLoc tenv cenv (Tuple boxed [e1,e2]) = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e1
; (e2',t2') <- translateExpI pSrcLoc tenv cenv e2
; let t = TH.AppT (TH.AppT (TH.TupleT 2) t1') t2'
; return (TH.TupE [e1',e2'], t)
}
translateExpI pSrcLoc tenv cenv (Tuple boxed (e:es)) = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e
; (e2',t2') <- translateExpI pSrcLoc tenv cenv (Tuple boxed es)
; let t = TH.AppT (TH.AppT (TH.TupleT 2) t1') t2'
; return (TH.TupE [e1',e2'], t)
}
{-
tenv, cenv |-^c e : t ~> E
------------------------ (ITApp)
tenv, cenv |-^i e :: t : t ~> E
-}
translateExpI pSrcLoc tenv cenv e1@(ExpTypeSig srcLoc e t) = do
{ t' <- translateType t
; e' <- translateExpC pSrcLoc tenv cenv e t'
; return (e', t')
}
{-
tenv U {(x:t1)}, cenv |-^i e : t2 ~> E
-----------------------------------------(IAbsVA)
tenv, cenv |-^i \x::t1 -> e : t1 -> t2 ~> \x -> E
-}
translateExpI pSrcLoc tenv cenv e1@(Lambda srcLoc [(PParen (PatTypeSig srcLoc' (PVar x) t1))] e) = do
{ t1' <- translateType t1
; let tenv' = addTyEnv x t1' tenv
; (e',t2) <- translateExpI srcLoc tenv' cenv e
; x' <- translateName x
; return ((TH.LamE [TH.VarP x'] e'), TH.AppT (TH.AppT TH.ArrowT t1') t2)
}
{-
---------------------------------------------
tenv |-^i \x -> e : ~> error
-}
translateExpI pSrcLoc tenv cenv e1@(Lambda srcLoc _ e) = failWithSrcLoc srcLoc $ "Type inferencer failed: unannotated lambda expression : \n " ++ (prettyPrint e1)
translateExpI pSrcLoc tenv cenv e1@(Case _ _) = failWithSrcLoc pSrcLoc $ "Type inferencer failed: unannotated case expression : \n" ++ (prettyPrint e1)
translateExpI pSrcLoc tenv cenv (Paren e) = translateExpI pSrcLoc tenv cenv e
{-
tenv, cenv |-^i e : t' ~> E
for each i
l_i : t' -> t_i \in tenv
tenv, cenv |-^c e_i : t_i ~> E_i
------------------------------------- (IRecUM)
tenv, cenv |-^i e@{[l=e]} : t' ~> e@{[l=E]}
-}
{-
tenv, cenv |-^i e : forall a. t' ~> E
for each i
l_i : forall a. C => t' -> t_i \in tenv
\theta(t') = t \theta is a substitution grounds t' to t
\theta(C) \subseteq cenv
tenv, cenv |-^c e_i : \theta(t_i) ~> E_i
------------------------------------- (IRecUP)
tenv, cenv |-^i e@{[l=e]} : t ~> e@{[l=E]}
-}
translateExpI pSrcLoc tenv cenv (RecUpdate e fieldUpds) = do
{ (e',t) <- translateExpI pSrcLoc tenv cenv e
; if T.isMono t
then do
{ fieldExps' <- mapM (\fu -> translateFieldUpd pSrcLoc tenv cenv fu t) fieldUpds
; return (TH.RecUpdE e' fieldExps', t)
}
else failWithSrcLoc pSrcLoc $ "Type inferencer can't to handle polymorphic record exp"
}
{-
tenv, cenv |-^i K : t1 -> ... -> tn -> t' ~> K
for each i
l_i : t' -> t_i \in tenv
tenv, cenv |-^c e_i : t_i ~> E_i
------------------------------------- (IRecKM)
tenv, cenv |-^i e@{[l=e]} : t' ~> e@{[l=E]}
-}
{-
tenv, cenv |-^i e : forall a. t' ~> E
for each i
-- we might need to build the theta from the individual e_i
------------------------------------- (IRecKP)
tenv, cenv |-^c e@{[l=e]} : t ~> e@{[l=E]}
-}
translateExpI pSrcLoc tenv cenv (RecConstr n fieldUpds) = do
-- todo polymoprhic
{ n' <- translateQName n
; (r,ns) <- lookupQName n tenv
-- check the parity and prepare to fill the missing optional filed with ()s
; let missingFieldNames = findMissingFieldNames ns fieldUpds
; missingFieldNameTypeLookups <- mapM (\n -> lookupQName (UnQual n) tenv) missingFieldNames
; let missingFieldNameResultTypes = map (\(t,_) -> T.resultType t) missingFieldNameTypeLookups
; if T.isMono r
then do
{ let t' = T.resultType r
; fieldExps' <- mapM (\fu -> translateFieldUpd pSrcLoc tenv cenv fu t') fieldUpds
-- make sure all the missing names are having optional result type
-- and generate the expression
; missingFExps <- mapM (reconstructMissingFieldUpd pSrcLoc)
(zip missingFieldNames missingFieldNameResultTypes)
; return (TH.RecConE n' (fieldExps' ++ missingFExps),t')
}
else failWithSrcLoc pSrcLoc $ "Type inferencer can't unable to handle polymorphic record exp"
}
translateExpI pSrcLoc tenv cenv e = failWithSrcLoc pSrcLoc ("Type inferencer can't handle expression : \n" ++ (prettyPrint e))
-- translate the field update
translateFieldUpd :: SrcLoc -> TyEnv -> ConstrEnv -> FieldUpdate -> TH.Type -> TH.Q TH.FieldExp
translateFieldUpd pSrcLoc tenv cenv (FieldUpdate qname e) t = do
{ (t',_) <- lookupQName qname tenv
; if T.isMono t'
then do
{ let r = T.resultType t'
; e' <- translateExpC pSrcLoc tenv cenv e r
; n' <- translateQName qname
; return (n',e')
}
else failWithSrcLoc pSrcLoc $ "Type inferencer can't handle polymorphic record exp"
}
-- find the missing field names
findMissingFieldNames :: [Name] -> [FieldUpdate] -> [Name]
findMissingFieldNames allNames fieldUpds =
let names = foldl (\names fu -> case fu of
{ FieldUpdate qn _ ->
let n = case qn of {UnQual x-> x; Qual mn x -> x; e -> error (show e)}
in if n `elem` names
then names
else names ++ [n]
; _ -> names }) [] fieldUpds
in filter (\n -> not (n `elem` names)) allNames
-- reconstruct the missing field name expression from ()s
reconstructMissingFieldUpd :: SrcLoc -> (Name, TH.Type) -> TH.Q TH.FieldExp
reconstructMissingFieldUpd pSrcLoc (n,t) = do
{ u <- ucast pSrcLoc (TH.ConT $ TH.mkName "()") t
; n' <- translateName n
; return $ (n', TH.AppE u (TH.ConE $ TH.mkName "()"))
}
-- | extract the type annotations from a pattern
-- | | (x :: t) | = t
-- | | (p1,p2) | = (|p1|, |p2|)
patStripT :: SrcLoc -> TyEnv -> Pat -> TH.Q TH.Type
-- for haskell-src-exts 1.14 +
patStripT pSrcLoc _ (PTuple box []) = failWithSrcLoc pSrcLoc "empty tuple pattern encountered"
patStripT pSrcLoc tenv (PTuple box [p]) = patStripT pSrcLoc tenv p
patStripT pSrcLoc tenv (PTuple box (p:ps)) = do
{ t <- patStripT pSrcLoc tenv p
; ts <- mapM (patStripT pSrcLoc tenv) ps
; return $ foldl (\t1 t2 -> TH.AppT (TH.AppT (TH.TupleT 2) t1) t2) t ts
}
-- for haskell-src-exts < 1.14
{-
patStripT (PTuple []) = fail "empty tuple pattern encountered"
patStripT (PTuple [p]) = patStripT p
patStripT (PTuple (p:ps)) = do
{ t <- patStripT p
; ts <- mapM patStripT ps
; return $ foldl (\t1 t2 -> TH.AppT (TH.AppT (TH.TupleT 2) t1) t2) t ts
}
-}
patStripT pSrcLoc tenv (PatTypeSig srcLoc (PVar n) t) = translateType t
patStripT pSrcLoc tenv (PParen p) = patStripT pSrcLoc tenv p
patStripT pSrcLoc tenv (PApp qname ps) = do
{ ts <- mapM (patStripT pSrcLoc tenv) ps -- todo check ts with the type of qName : t \in tenv
; (ty,_) <- lookupQName qname tenv
; T.lineUpTypes pSrcLoc ty ts
}
patStripT pSrcLoc tenv (PRec qname fps) = do
{ (ty,_) <- lookupQName qname tenv
; return $ T.resultType ty
}
patStripT pSrcLoc _ p = failWithSrcLoc pSrcLoc ("unhandle pattern " ++ (prettyPrint p) ++ (show p))
-- | remove the type annotation from a pattern
-- | { x :: t } = x
-- | { (p1,p2) } = ({p1},{p2})
patStripP :: SrcLoc -> Pat -> TH.Q TH.Pat
patStripP pSrcLoc (PTuple box []) = failWithSrcLoc pSrcLoc "empty tuple pattern encountered"
patStripP pSrcLoc (PTuple box [p]) = patStripP pSrcLoc p
patStripP pSrcLoc (PTuple box (p:ps)) = do
{ q <- patStripP pSrcLoc p
; qs <- mapM (patStripP pSrcLoc) ps
; return $ foldl (\p1 p2 -> TH.TupP [p1, p2]) q qs
}
patStripP pSrcLoc (PatTypeSig srcLoc (PVar n) t) = do
{ n' <- translateName n
; return (TH.VarP n')
}
patStripP pSrcLoc (PParen p) = patStripP pSrcLoc p
patStripP pSrcLoc (PApp qname ps) = do
{ qs <- mapM (patStripP pSrcLoc) ps
; name' <- translateQName qname
; return (TH.ConP name' qs)
}
patStripP pSrcLoc (PRec qname fps) = do
{ name' <- translateQName qname
; fps' <- mapM (\(PFieldPat qname p) -> do
{ p' <- patStripP pSrcLoc p
; name' <- translateQName qname
; return (name', p')
}) fps
; return (TH.RecP name' fps')
}
patStripP pSrcLoc p = failWithSrcLoc pSrcLoc ("unhandle pattern " ++ (prettyPrint p) ++ (show p))
{-
-- | build type environment from a pattern
-- | [ x :: t ] = { (x, t) }
-- | [ (p1,p2) ] = [p1] ++ [p2]
patTEnv :: Pat -> TH.Q TyEnv
patTEnv (PTuple box []) = fail "empty tuple pattern encountered"
patTEnv (PTuple box [p]) = patTEnv p
patTEnv (PTuple box (p:ps)) = do
{ e <- patTEnv p
; es <- mapM patTEnv ps
; return $ foldl unionTyEnv e es
}
patTEnv (PatTypeSig srcLoc (PVar n) t) = do
{ t' <- translateType t
; return (addTyEnv n t' M.empty)
}
patTEnv (PParen p) = patTEnv p
patTEnv (PApp qname ps) = do
{ es <- mapM patTEnv ps
; return $ foldl unionTyEnv M.empty es
}
patTEnv p = fail ("unhandle pattern " ++ (prettyPrint p) ++ (show p))
-}
-------------------------------------------- helper functions for nested pattern matching -------------------------
-- | extended patTEnv
patEnv :: SrcLoc -> TyEnv -> TH.Type -> Pat -> TH.Q (TyEnv, TH.Exp, TH.Exp, TH.Pat) -- the codomain type env is not generated
patEnv pSrcLoc te t (PTuple box []) = failWithSrcLoc pSrcLoc "Pattern Environment construction failed, an empty tuple pattern encountered."
patEnv pSrcLoc te t (PTuple box [p]) = patEnv pSrcLoc te t p
{-
t1,p1 |- tenv1, gd1, ex1, dom1, cod1
t2,p2 |- tenv2, gd2, ex2, dom2, cod2
------------------------------------------------------------------------------
(t1,t2), (p1,p2) |- tenv1 U tenv2, \(x,y) -> (gd1 x && gd2 y), \(x,y) -> (ex1 x, ex2 y), (dom1,dom2), (cod1,cod2)
-}
patEnv pSrcLoc te t (PTuple box (p:ps)) = do
{ let ts = unTupleTy t
; xs <- mapM (\ (t',p) -> patEnv pSrcLoc te t' p) (zip ts (p:ps))
; names' <- T.newNames (length (p:ps)) "x"
; let (tenv, gds, exs, ps') = foldl (\(tenv,gds,exs,qs) (tenv',gd,ex,q) ->
(tenv `unionTyEnv` tenv',
gds ++ [gd],
exs ++ [ex],
qs ++ [q])) (M.empty,[],[],[]) xs
p' = TH.TupP ps'
vps = map TH.VarP names'
ves = map TH.VarE names'
gdes = map (\(gd,ve) -> TH.AppE gd ve) (zip gds ves)
gd = TH.LamE [TH.TupP vps] (TH.AppE (TH.VarE $ TH.mkName "and") (TH.ListE gdes))
exes = map (\(ex,ve) -> TH.AppE ex ve) (zip exs ves)
ex = TH.LamE [TH.TupP vps] (TH.TupE exes)
; return (tenv, gd, ex, p')
}
patEnv pSrcLoc te t (PatTypeSig srcLoc (PVar n) t') = do
{ t'' <- translateType t'
; if (t'' == t)
then do
{- t, (x :: t) |- { (x, t) }, (\x -> True), id, x, t -}
{ let tenv = addTyEnv n t M.empty
gd = TH.LamE [TH.VarP (TH.mkName "x")] (TH.ConE (TH.mkName "True"))
ex = TH.LamE [TH.VarP (TH.mkName "x")] (TH.VarE (TH.mkName "x"))
; n' <- translateName n
; let p' = TH.VarP n'
; return (tenv, gd, ex, p')
}
else do
{-
t' <= t ~> d
-----------------------------------------
t, (x :: t') |- { (x, t') }, isJust . d, fromJust . d , x, t'
-}
{ d <- dcast pSrcLoc t'' t
; let tenv = addTyEnv n t'' M.empty
gd = TH.LamE [TH.VarP (TH.mkName "x")] (TH.AppE (TH.VarE $ TH.mkName "Data.Maybe.isJust") (TH.AppE d (TH.VarE $ TH.mkName "x")))
ex = TH.LamE [TH.VarP (TH.mkName "x")] (TH.AppE (TH.VarE $ TH.mkName "Data.Maybe.fromJust") (TH.AppE d (TH.VarE $ TH.mkName "x")))
; n' <- translateName n
; let p' = TH.VarP n'
; return (tenv, gd, ex, p')
}
}
patEnv pSrcLoc te t (PParen p) = patEnv pSrcLoc te t p
{-
K :: t1 -> ... -> tn -> t
t_i, p_i |- tenv_i, gd_i, ex_i, dom_i, cod_i
------------------------------------------------------------------------------------------------------------------------------------------------
t, K [p] |- U tenv_i, \(K [p']) -> gd_1 p_1' && ... && gd_n p_n', \(K [p']) -> (ex1 p'1, ex2 p_2', ... ), (dom_1,...,dom_n), (cod_1,...,cod_i)
-}
patEnv pSrcLoc te t p@(PApp qname ps) = do
{ (t',_) <- lookupQName qname te
; let ts = T.argsTypes t'
r = T.resultType t'
-- todo check r == t?
; if (length ps == length ts)
then do
{ let tps = zip ts ps
; qname' <- translateQName qname
; xs <- mapM (\(t,p) -> patEnv pSrcLoc te t p) tps
; names' <- T.newNames (length ps) "x"
; let (tenv, gds, exs, ps') = foldl (\(tenv,gds,exs,qs) (tenv',gd,ex,q) ->
(tenv `unionTyEnv` tenv',
gds ++ [gd],
exs ++ [ex],
qs ++ [q])) (M.empty,[],[],[]) xs
p' = TH.TupP ps'
vps = map TH.VarP names'
ves = map TH.VarE names'
gdes = map (\(gd,ve) -> TH.AppE gd ve) (zip gds ves)
gd = TH.LamE [TH.ConP qname' vps] (TH.AppE (TH.VarE $ TH.mkName "and") (TH.ListE gdes))
exes = map (\(ex,ve) -> TH.AppE ex ve) (zip exs ves)
ex = TH.LamE [TH.ConP qname' vps] (TH.TupE exes)
; return (tenv, gd, ex, p')
}
else failWithSrcLoc pSrcLoc ("Fail to construct pattern environment from the pattern " ++ (prettyPrint p) ++ " the number of pattern args is wrong.")
}
{-
l_i :: t -> t_i
t_i, p_i |- tenv_i, gd_i, ex_i, dom_i, cod_i
---------------------------------------
t, K { [l=p] } |- U tenv_i, \x -> gd_1 (l_1 x) && ... && gd_n (l_n x), \x ->(ex1 (l_1 x), ..., (exn (l_n x) )), (dom_1,...,dom_n), (cod_1,...,cod_i)
-}
patEnv pSrcLoc te t p@(PRec qname fps) = do
{ (t', ns) <- lookupQName qname te
; let ts = T.argsTypes t'
r = T.resultType t'
names = map (\(PFieldPat l p) -> l) fps
ps = map (\(PFieldPat l p) -> p) fps
; ats <- mapM (\l -> lookupQName l te) names
; let ts = map (T.resultType . fst) ats
; xs <- mapM (\(t,p) -> patEnv pSrcLoc te t p) (zip ts ps)
; nn <- TH.newName "x"
; names' <- mapM translateQName names
; let (tenv, gds, exs, ps') = foldl (\(tenv, gds, exs, qs) (tenv', gd,ex,q) ->
(tenv `unionTyEnv` tenv',
gds ++ [gd],
exs ++ [ex],
qs ++ [q])) (M.empty,[],[],[]) xs
p' = TH.TupP ps'
gdes = map (\(l,gd) -> TH.AppE gd (TH.AppE (TH.VarE l) (TH.VarE nn))) (zip names' gds)
gd = TH.LamE [TH.VarP nn] (TH.AppE (TH.VarE $ TH.mkName "and") (TH.ListE gdes))
exes = map (\(l,ex) -> TH.AppE ex (TH.AppE (TH.VarE l) (TH.VarE nn))) (zip names' exs)
ex = TH.LamE [TH.VarP nn] (TH.TupE (exes))
; return (tenv, gd, ex, p')
}
patEnv pSrcLoc te t p = failWithSrcLoc pSrcLoc ("Fail to construct pattern environment from the pattern " ++ (prettyPrint p) ++ (show p))
{-
joinAppEWith :: TH.Exp -> TH.Exp -> TH.Exp -> TH.Exp
joinAppEWith e1 e2 e3 =
TH.LamE [TH.TupP [ TH.VarP (TH.mkName "x"), TH.VarP (TH.mkName "y")]] (TH.AppE
(TH.AppE
e1
(TH.AppE e2 (TH.VarE (TH.mkName "x"))))
(TH.AppE e3 (TH.VarE (TH.mkName "y"))))
-}
-- (t1,t2,t3) -> [t1,t2,t3]
unTupleTy :: TH.Type -> [TH.Type]
unTupleTy (TH.AppT (TH.AppT (TH.TupleT 2) t1) t2) =
let ts = unTupleTy t1
in ts ++ [t2]
unTupleTy t = [t]
---------------- helper functions for local type inference ------------------------
-- test whether a application expression is started with an polymoprhic f
-- if so, the f and the args are seperated and returned as a pair
appWithPolyFunc :: TyEnv -> Exp -> TH.Q (Maybe (Exp, [Exp]))
appWithPolyFunc tenv e =
case S.flatten e of
{ l@((Var f):es) -> do
{ (t,_) <- lookupQName f tenv
; if T.isPoly t
then return (Just (Var f, es))
else return Nothing
}
; _ -> return Nothing }
inferThenUpCast :: SrcLoc -> TH.Type -> TH.Type -> TH.Q TH.Exp
inferThenUpCast pSrcLoc (TH.ForallT tvbs ctxt t1) t2 | T.isMono t2 = do -- the arg type can be still poly, we apply local inference again
{ let as = map T.getTvFromTvb tvbs
ts1 = T.argsTypes t1
ts2 = T.argsTypes t2
r1 = T.resultType t1
ds = concatMap (\(t,t') -> genSubtypeConstrs as [] t t') (zip ts1 ts2)
; s <- solveSubtypeConstrs ds r1
; ucast pSrcLoc (T.applySubst s t1) t2
}
inferThenUpCast pSrcLoc t1 t2 = ucast pSrcLoc t1 t2
xh :: QuasiQuoter
xh = QuasiQuoter { quoteExp = undefined, -- not in used
quotePat = undefined, -- not in used
quoteType = undefined, -- not in used
quoteDec = xhDecls
}
{-
import Language.Haskell.TH as TH
$(TH.stringE . show =<< TH.reify (TH.mkName "()"))
parseDeclWithMode pmScopedTyVar "f x = g f x"
-} | luzhuomi/xhaskell | Language/XHaskell.hs | bsd-3-clause | 69,224 | 2 | 34 | 22,722 | 16,783 | 8,637 | 8,146 | 783 | 29 |
-- | Download and import feeds from various sources.
module HN.Model.Feeds where
import HN.Data
import HN.Monads
import HN.Model.Items
import HN.Types
import HN.Curl
import qualified HN.Model.Mailman (downloadFeed)
import Control.Applicative
import Network.URI
import Snap.App
import Text.Feed.Import
import Text.Feed.Query
import Text.Feed.Types
--------------------------------------------------------------------------------
-- Various service feeds
importHaskellCafe :: Model c s (Either String ())
importHaskellCafe =
importMailman 50
HaskellCafe
"https://mail.haskell.org/pipermail/haskell-cafe/"
(\item -> return (item { niTitle = strip "[Haskell-cafe]" (niTitle item) }))
importLibraries :: Model c s (Either String ())
importLibraries =
importMailman 50
Libraries
"https://mail.haskell.org/pipermail/libraries/"
(\item -> return (item { niTitle = strip "[libraries]" (niTitle item) }))
importGhcDevs :: Model c s (Either String ())
importGhcDevs =
importMailman 50
GhcDevs
"https://mail.haskell.org/pipermail/ghc-devs/"
(\item -> return (item { niTitle = strip "[ghc-devs]" (niTitle item) }))
strip label x | isPrefixOf "re: " (map toLower x) = strip label (drop 4 x)
| isPrefixOf label x = drop (length label) x
| otherwise = x
importPlanetHaskell :: Model c s (Either String ())
importPlanetHaskell =
importGeneric PlanetHaskell "http://planet.haskell.org/rss20.xml"
importJobs :: Model c s (Either String ())
importJobs =
importGeneric Jobs "http://www.haskellers.com/feed/jobs"
importStackOverflow :: Model c s (Either String ())
importStackOverflow = do
importGeneric StackOverflow "http://stackoverflow.com/feeds/tag/haskell"
importGeneric StackOverflow "http://programmers.stackexchange.com/feeds/tag/haskell"
importGeneric StackOverflow "http://codereview.stackexchange.com/feeds/tag/haskell"
importHaskellWiki :: Model c s (Either String ())
importHaskellWiki =
importGeneric HaskellWiki "http://wiki.haskell.org/index.php?title=Special:RecentChanges&feed=atom"
importHackage :: Model c s (Either String ())
importHackage =
importGeneric Hackage "http://hackage.haskell.org/packages/recent.rss"
-- | Import all vimeo content.
importVimeo :: Model c s (Either String ())
importVimeo = do
importGeneric Vimeo "https://vimeo.com/channels/haskell/videos/rss"
importGeneric Vimeo "https://vimeo.com/channels/galois/videos/rss"
importGenerically Vimeo "https://vimeo.com/rickasaurus/videos/rss"
(\ni -> if isInfixOf "haskell" (map toLower (niTitle ni)) then return ni else Nothing)
-- | Import @remember'd IRC quotes from ircbrowse.
importIrcQuotes :: Model c s (Either String ())
importIrcQuotes = do
importGeneric IrcQuotes
"http://ircbrowse.net/quotes.rss"
-- | Import pastes about Haskell.
importPastes :: Model c s (Either String ())
importPastes = do
importGeneric Pastes
"http://lpaste.net/channel/haskell/rss"
--------------------------------------------------------------------------------
-- Reddit
-- | Get /r/haskell.
importRedditHaskell :: Model c s (Either String ())
importRedditHaskell = do
result <- io $ getReddit "haskell"
case result of
Left e -> return (Left e)
Right items -> do
mapM_ (addItem Reddit) items
return (Right ())
-- | Import from proggit.
importProggit :: Model c s (Either String ())
importProggit = do
result <- io $ getReddit "programming"
case result of
Left e -> return (Left e)
Right items -> do
mapM_ (addItem Reddit) (filter (hasHaskell . niTitle) items)
return (Right ())
where hasHaskell = isInfixOf "haskell" . map toLower
-- | Get Reddit feed.
getReddit :: String -> IO (Either String [NewItem])
getReddit subreddit = do
result <- downloadFeed ("https://www.reddit.com/r/" ++ subreddit ++ "/.rss")
case result of
Left e -> return (Left e)
Right e -> return (mapM makeItem (feedItems e))
--------------------------------------------------------------------------------
-- Get feeds
-- | Import from a generic feed source.
importGeneric :: Source -> String -> Model c s (Either String ())
importGeneric source uri = do
importGenerically source uri return
-- | Import from a generic feed source.
importGenerically :: Source -> String -> (NewItem -> Maybe NewItem) -> Model c s (Either String ())
importGenerically source uri f = do
result <- io $ downloadFeed uri
case result >>= mapM (fmap f . makeItem) . feedItems of
Left e -> do
return (Left e)
Right items -> do
mapM_ (addItem source) (catMaybes items)
return (Right ())
importMailman :: Int -> Source -> String -> (NewItem -> Maybe NewItem) -> Model c s (Either String ())
importMailman its source uri f = do
result <- io $ HN.Model.Mailman.downloadFeed its uri
case result >>= mapM (fmap f . makeItem) . feedItems of
Left e -> do
return (Left e)
Right items -> do
mapM_ (addItem source) (catMaybes items)
return (Right ())
-- | Make an item from a feed item.
makeItem :: Item -> Either String NewItem
makeItem item =
NewItem <$> extract "item" (getItemTitle item)
<*> extract "publish date" (join (getItemPublishDate item))
<*> extract "description" (getItemDescription item <|> getItemTitle item)
<*> extract "link" (getItemLink item >>= parseURILeniently)
where extract label = maybe (Left ("Unable to extract " ++ label ++ " for " ++ show item)) Right
-- | Escape any characters not allowed in URIs because at least one
-- feed (I'm looking at you, reddit) do not escape characters like ö.
parseURILeniently :: String -> Maybe URI
parseURILeniently = parseURI . escapeURIString isAllowedInURI
-- | Download and parse a feed.
downloadFeed :: String -> IO (Either String Feed)
downloadFeed uri = do
result <- downloadString uri
case result of
Left e -> return (Left (show e))
Right str -> case parseFeedString str of
Nothing -> do
writeFile "/tmp/feed.xml" str
return (Left ("Unable to parse feed from: " ++ uri))
Just feed -> return (Right feed)
--------------------------------------------------------------------------------
-- Utilities
-- | Parse one of the two dates that might occur out there.
parseDate :: String -> Maybe ZonedTime
parseDate x = parseRFC822 x <|> parseRFC3339 x
-- | Parse an RFC 3339 timestamp.
parseRFC3339 :: String -> Maybe ZonedTime
parseRFC3339 = (parseTimeM True) defaultTimeLocale "%Y-%m-%dT%TZ"
-- | Parse an RFC 822 timestamp.
parseRFC822 :: String -> Maybe ZonedTime
parseRFC822 = (parseTimeM True) defaultTimeLocale rfc822DateFormat
| jwaldmann/haskellnews | src/HN/Model/Feeds.hs | bsd-3-clause | 6,761 | 0 | 19 | 1,318 | 1,836 | 903 | 933 | 134 | 3 |
{-# LINE 1 "System.Environment.ExecutablePath.hsc" #-}
{-# LANGUAGE Safe #-}
{-# LINE 2 "System.Environment.ExecutablePath.hsc" #-}
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Environment.ExecutablePath
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Function to retrieve the absolute filepath of the current executable.
--
-- @since 4.6.0.0
-----------------------------------------------------------------------------
module System.Environment.ExecutablePath ( getExecutablePath ) where
-- The imports are purposely kept completely disjoint to prevent edits
-- to one OS implementation from breaking another.
{-# LINE 42 "System.Environment.ExecutablePath.hsc" #-}
import Foreign.C
import Foreign.Marshal.Alloc
import Foreign.Ptr
import Foreign.Storable
import System.Posix.Internals
{-# LINE 48 "System.Environment.ExecutablePath.hsc" #-}
-- The exported function is defined outside any if-guard to make sure
-- every OS implements it with the same type.
-- | Returns the absolute pathname of the current executable.
--
-- Note that for scripts and interactive sessions, this is the path to
-- the interpreter (e.g. ghci.)
--
-- @since 4.6.0.0
getExecutablePath :: IO FilePath
--------------------------------------------------------------------------------
-- Mac OS X
{-# LINE 156 "System.Environment.ExecutablePath.hsc" #-}
foreign import ccall unsafe "getFullProgArgv"
c_getFullProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO ()
getExecutablePath =
alloca $ \ p_argc ->
alloca $ \ p_argv -> do
c_getFullProgArgv p_argc p_argv
argc <- peek p_argc
if argc > 0
-- If argc > 0 then argv[0] is guaranteed by the standard
-- to be a pointer to a null-terminated string.
then peek p_argv >>= peek >>= peekFilePath
else errorWithoutStackTrace $ "getExecutablePath: " ++ msg
where msg = "no OS specific implementation and program name couldn't be " ++
"found in argv"
--------------------------------------------------------------------------------
{-# LINE 176 "System.Environment.ExecutablePath.hsc" #-}
| phischu/fragnix | builtins/base/System.Environment.ExecutablePath.hs | bsd-3-clause | 2,382 | 0 | 14 | 419 | 209 | 128 | 81 | 21 | 2 |
-- | This module provides functionality for retrieving and parsing the
-- quantum random number data from the Australian National University QRN server.
--
-- This module can be used when one only wants to use live data directly from the server,
-- without using any of the data store functionality.
--
-- In most other cases it should be imported via the "Quantum.Random" module.
module Quantum.Random.ANU (
-- ** QRN data retrieval
fetchQR,
fetchQRBits,
) where
import Quantum.Random.Codec
import Quantum.Random.Exceptions
import Data.Word (Word8)
import Data.Bits (testBit)
import Data.ByteString.Lazy (ByteString)
import Network.HTTP.Conduit (simpleHttp)
anuURL :: Int -> String
anuURL n = "https://qrng.anu.edu.au/API/jsonI.php?length=" ++ show n ++ "&type=uint8"
getANU :: Int -> IO ByteString
getANU = simpleHttp . anuURL
fetchQRResponse :: Int -> IO QRResponse
fetchQRResponse n = throwLeft $ parseResponse <$> getANU n
-- | Fetch quantum random data from ANU server as a linked list of bytes via HTTPS. Network
-- problems may result in an `HttpException`. An invalid response triggers a 'QRException'.
fetchQR :: Int -> IO [Word8]
fetchQR n = map fromIntegral . qdata <$> fetchQRResponse n
-- | Fetch QRN data from ANU server as a linked list of booleans via HTTPS. Network
-- problems may result in an `HttpException`. An invalid response triggers a 'QRException'.
fetchQRBits :: Int -> IO [Bool]
fetchQRBits n = concat . map w8bools <$> fetchQR n
-- Converts a byte (Word8) to the corresponding list of 8 boolean values.
-- 'Bits' type class indexes bits from least to most significant, thus the reverse
w8bools :: Word8 -> [Bool]
w8bools w = reverse $ testBit w <$> [0..7]
| BlackBrane/quantum-random-numbers | src-lib/Quantum/Random/ANU.hs | mit | 1,737 | 0 | 7 | 318 | 274 | 154 | 120 | 21 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Napm.Types(
Domain(..)
, PasswordLength(..)
, Passphrase(..)
, ContextMap
) where
import Control.Applicative
import Data.Map (Map)
import Data.Text (Text)
import qualified Data.Text as T
import Test.QuickCheck
-- FIXME: unicode
text :: Gen Text
text = fmap T.pack $ listOf1 textChar
where
textChar = elements . concat $ [ ['a'..'z']
, ['A'..'Z']
, ['0'..'9']
, [' '..'/']
]
{-
Password domain/textual context, e.g.,
"[email protected]". Mostly-freeform, but can't contain whitespace or
colons (':').
-}
newtype Domain = Domain
{ unDomain :: Text }
deriving (Eq, Show, Ord)
-- FIXME: unicode
instance Arbitrary Domain where
arbitrary = Domain <$> text
{-
Length of a generated password.
-}
newtype PasswordLength = PasswordLength
{ unPasswordLength :: Int }
deriving (Eq, Show, Ord, Num)
instance Arbitrary PasswordLength where
arbitrary = PasswordLength <$> positive
where
positive = arbitrary `suchThat` (\l -> l > 0 && l <= 64)
newtype Passphrase = Passphrase
{ unPassphrase :: Text }
deriving (Eq, Show, Ord)
instance Arbitrary Passphrase where
arbitrary = Passphrase <$> text
{-
The context in which passwords are generated. Consists of a password
domain/textual context that's not secret and easy for the user to
remember (hostname, URL, whatever), plus the length of the generated
password. Revealing a context should not compromise the password, but
they're considered non-public.
-}
type ContextMap = Map Domain PasswordLength
| fractalcat/napm | lib/Napm/Types.hs | mit | 1,750 | 0 | 13 | 486 | 331 | 197 | 134 | 34 | 1 |
import Control.Monad
import Control.Concurrent
import Data.Word
import Sleep
import Led
ledGroupA, ledGroupB :: [Word16]
ledGroupA = [led3, led5, led7, led9]
ledGroupB = [led4, led6, led8, led10]
blinkLedLoop :: [Word16] -> Word32 -> IO ()
blinkLedLoop leds sleep = forever $ sequence_ dos
where
delays = repeat $ threadDelayMicroseconds sleep
ledsOnOff = fmap ledOn leds ++ fmap ledOff leds
dos = concat $ zipWith (\a b -> [a,b]) ledsOnOff delays
main :: IO ()
main = do mapM_ ledOff $ ledGroupA ++ ledGroupB
forkOS $ blinkLedLoop ledGroupB 50
blinkLedLoop ledGroupA 170
| metasepi/chibios-arafura | demos/ARMCM4-STM32F303-DISCOVERY_hs/hs_src/MainBlinkLed.hs | gpl-3.0 | 610 | 0 | 11 | 128 | 218 | 117 | 101 | 17 | 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="ru-RU">
<title>Passive Scan Rules - Beta | 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>Индекс</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Поиск</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/pscanrulesBeta/src/main/javahelp/org/zaproxy/zap/extension/pscanrulesBeta/resources/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 998 | 80 | 67 | 163 | 442 | 222 | 220 | -1 | -1 |
#!/usr/bin/env runhaskell
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
{-# OPTIONS -Wall #-}
import Data.Dynamic
import Data.Tensor.TypeLevel
import qualified Data.Text.IO as T
import Language.Paraiso.Annotation (Annotation)
import Language.Paraiso.Generator (generateIO)
import qualified Language.Paraiso.Generator.Native as Native
import Language.Paraiso.Name
import Language.Paraiso.OM
import Language.Paraiso.OM.Builder
import Language.Paraiso.OM.DynValue as DVal
import Language.Paraiso.OM.PrettyPrint
import Language.Paraiso.OM.Realm
import qualified Language.Paraiso.OM.Reduce as Reduce
import Language.Paraiso.Optimization
import NumericPrelude
import System.Process (system)
bind :: (Monad m, Functor m) => m a -> m (m a)
bind = fmap return
initialize :: Builder Vec1 Int Annotation ()
initialize = do
i <- bind $ loadIndex (0::Double) $ Axis 0
n <- bind $ loadSize TLocal (0::Double) $ Axis 0
x <- bind $ 2 * pi / n * (i + 0.5)
store fieldF $ sin(x)
store fieldG $ cos(3*x)
proceed :: Builder Vec1 Int Annotation ()
proceed = do
c <- bind $ imm 3.43
n <- bind $ loadSize TLocal (0::Double) $ Axis 0
f0 <- bind $ load TLocal (0::Double) $ fieldF
g0 <- bind $ load TLocal (0::Double) $ fieldG
dx <- bind $ 2 * pi / n
dt <- bind $ dx / c
f1 <- bind $ f0 + dt * g0
fR <- bind $ shift (Vec:~ -1) f1
fL <- bind $ shift (Vec:~ 1) f1
g1 <- bind $ g0 + dt * c^2 / dx^2 *
(fL + fR - 2 * f1)
store fieldF f1
store fieldG g1
dfdx <- bind $ (fR - fL) / (2*dx)
store energy $ reduce Reduce.Sum $
0.5 * (c^2 * dfdx^2 + ((g0+g1)/2)^2) * dx
fieldF, fieldG, energy :: Name
fieldF = mkName "fieldF"
fieldG = mkName "fieldG"
energy = mkName "energy"
myVars :: [Named DynValue]
myVars = [Named fieldF DynValue{DVal.realm = Local, typeRep = typeOf (0::Double)},
Named fieldG DynValue{DVal.realm = Local, typeRep = typeOf (0::Double)},
Named energy DynValue{DVal.realm = Global, typeRep = typeOf (0::Double)}
]
myOM :: OM Vec1 Int Annotation
myOM = optimize O3 $
makeOM (mkName "LinearWave") [] myVars
[(mkName "initialize", initialize),
(mkName "proceed", proceed)]
mySetup :: Int -> Native.Setup Vec1 Int
mySetup n =
(Native.defaultSetup $ Vec :~ n)
{ Native.directory = "./dist/"
}
mainTest :: Int -> IO ()
mainTest n = do
_ <- system "mkdir -p output"
T.writeFile "output/OM.txt" $ prettyPrintA1 $ myOM
_ <- generateIO (mySetup n) myOM
_ <- system "make"
_ <- system "./a.out"
return ()
main :: IO ()
main = mapM_ mainTest $
concat $ [[2*2^n, 3*2^n]| n <- [2..10]]
| drmaruyama/Paraiso | examples-old/LinearWave/Convergence.hs | bsd-3-clause | 2,761 | 0 | 15 | 701 | 1,108 | 582 | 526 | 73 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{- |
Module : Verifier.SAW.Prelude
Copyright : Galois, Inc. 2012-2015
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (language extensions)
-}
module Verifier.SAW.Prelude
( Module
, module Verifier.SAW.Prelude
, module Verifier.SAW.Prelude.Constants
) where
import qualified Data.Map as Map
import Verifier.SAW.ParserUtils
import Verifier.SAW.Prelude.Constants
import Verifier.SAW.SharedTerm
import Verifier.SAW.FiniteValue
import Verifier.SAW.Simulator.Concrete (evalSharedTerm)
import Verifier.SAW.Simulator.Value (asFirstOrderTypeValue)
$(defineModuleFromFileWithFns
"preludeModule" "scLoadPreludeModule" "prelude/Prelude.sawcore")
-- | Given two terms, compute a term representing a decidable
-- equality test between them. The terms are assumed to
-- be of the same type, which must be a first-order type.
-- The returned term will be of type @Bool@.
scEq :: SharedContext -> Term -> Term -> IO Term
scEq sc x y = do
xty <- scTypeOf sc x
mmap <- scGetModuleMap sc
case asFirstOrderTypeValue (evalSharedTerm mmap mempty mempty xty) of
Just fot -> scDecEq sc fot (Just (x,y))
Nothing -> fail ("scEq: expected first order type, but got: " ++ showTerm xty)
-- | Given a first-order type, return the decidable equality
-- operation on that type. If arguments are provided, they
-- will be applied, returning a value of type @Bool@. If no
-- arguments are provided a function of type @tp -> tp -> Bool@
-- will be returned.
scDecEq ::
SharedContext ->
FirstOrderType {- ^ Type of elements to test for equality -} ->
Maybe (Term,Term) {- ^ optional arguments to apply -} ->
IO Term
scDecEq sc fot args = case fot of
FOTBit ->
do fn <- scGlobalDef sc "Prelude.boolEq"
case args of
Nothing -> return fn
Just (x,y) -> scApplyAll sc fn [x,y]
FOTInt ->
do fn <- scGlobalDef sc "Prelude.intEq"
case args of
Nothing -> return fn
Just (x,y) -> scApplyAll sc fn [x,y]
FOTIntMod m ->
do fn <- scGlobalDef sc "Prelude.intModEq"
m' <- scNat sc m
case args of
Nothing -> scApply sc fn m'
Just (x,y) -> scApplyAll sc fn [m',x,y]
FOTVec w FOTBit ->
do fn <- scGlobalDef sc "Prelude.bvEq"
w' <- scNat sc w
case args of
Nothing -> scApply sc fn w'
Just (x,y) -> scApplyAll sc fn [w',x,y]
FOTVec w t ->
do fn <- scGlobalDef sc "Prelude.vecEq"
w' <- scNat sc w
t' <- scFirstOrderType sc t
subFn <- scDecEq sc t Nothing
case args of
Nothing -> scApplyAll sc fn [w',t',subFn]
Just (x,y) -> scApplyAll sc fn [w',t',subFn,x,y]
FOTArray a b ->
do a' <- scFirstOrderType sc a
b' <- scFirstOrderType sc b
fn <- scGlobalDef sc "Prelude.arrayEq"
case args of
Nothing -> scApplyAll sc fn [a',b']
Just (x,y) -> scApplyAll sc fn [a',b',x,y]
FOTTuple [] ->
case args of
Nothing -> scGlobalDef sc "Prelude.unitEq"
Just _ -> scBool sc True
FOTTuple [t] -> scDecEq sc t args
FOTTuple (t:ts) ->
do fnLeft <- scDecEq sc t Nothing
fnRight <- scDecEq sc (FOTTuple ts) Nothing
fn <- scGlobalDef sc "Prelude.pairEq"
t' <- scFirstOrderType sc t
ts' <- scFirstOrderType sc (FOTTuple ts)
case args of
Nothing -> scApplyAll sc fn [t',ts',fnLeft,fnRight]
Just (x,y) -> scApplyAll sc fn [t',ts',fnLeft,fnRight,x,y]
FOTRec fs ->
case args of
Just (x,y) ->
mkRecordEqBody (Map.toList fs) x y
Nothing ->
do x <- scLocalVar sc 1
y <- scLocalVar sc 0
tp <- scFirstOrderType sc fot
body <- mkRecordEqBody (Map.toList fs) x y
scLambdaList sc [("x",tp),("y",tp)] body
where
mkRecordEqBody [] _x _y = scBool sc True
mkRecordEqBody [(f,tp)] x y =
do xf <- scRecordSelect sc x f
yf <- scRecordSelect sc y f
scDecEq sc tp (Just (xf,yf))
mkRecordEqBody ((f,tp):fs) x y =
do xf <- scRecordSelect sc x f
yf <- scRecordSelect sc y f
fp <- scDecEq sc tp (Just (xf,yf))
fsp <- mkRecordEqBody fs x y
scAnd sc fp fsp
-- | For backwards compatibility: @Bool@ used to be a datatype, and so its
-- creation function was called @scPrelude_Bool@ instead of
-- @scApplyPrelude_Bool@
scPrelude_Bool :: SharedContext -> IO Term
scPrelude_Bool = scApplyPrelude_Bool
| GaloisInc/saw-script | saw-core/src/Verifier/SAW/Prelude.hs | bsd-3-clause | 4,624 | 0 | 17 | 1,248 | 1,382 | 694 | 688 | 103 | 21 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[HsLit]{Abstract syntax: source-language literals}
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
module HsLit where
#include "HsVersions.h"
import {-# SOURCE #-} HsExpr( HsExpr, pprExpr )
import BasicTypes ( FractionalLit(..),SourceText )
import Type ( Type )
import Outputable
import FastString
import PlaceHolder ( PostTc,PostRn,DataId,OutputableBndrId )
import Data.ByteString (ByteString)
import Data.Data hiding ( Fixity )
{-
************************************************************************
* *
\subsection[HsLit]{Literals}
* *
************************************************************************
-}
-- Note [Literal source text] in BasicTypes for SourceText fields in
-- the following
data HsLit
= HsChar SourceText Char -- Character
| HsCharPrim SourceText Char -- Unboxed character
| HsString SourceText FastString -- String
| HsStringPrim SourceText ByteString -- Packed bytes
| HsInt SourceText Integer -- Genuinely an Int; arises from
-- TcGenDeriv, and from TRANSLATION
| HsIntPrim SourceText Integer -- literal Int#
| HsWordPrim SourceText Integer -- literal Word#
| HsInt64Prim SourceText Integer -- literal Int64#
| HsWord64Prim SourceText Integer -- literal Word64#
| HsInteger SourceText Integer Type -- Genuinely an integer; arises only
-- from TRANSLATION (overloaded
-- literals are done with HsOverLit)
| HsRat FractionalLit Type -- Genuinely a rational; arises only from
-- TRANSLATION (overloaded literals are
-- done with HsOverLit)
| HsFloatPrim FractionalLit -- Unboxed Float
| HsDoublePrim FractionalLit -- Unboxed Double
deriving Data
instance Eq HsLit where
(HsChar _ x1) == (HsChar _ x2) = x1==x2
(HsCharPrim _ x1) == (HsCharPrim _ x2) = x1==x2
(HsString _ x1) == (HsString _ x2) = x1==x2
(HsStringPrim _ x1) == (HsStringPrim _ x2) = x1==x2
(HsInt _ x1) == (HsInt _ x2) = x1==x2
(HsIntPrim _ x1) == (HsIntPrim _ x2) = x1==x2
(HsWordPrim _ x1) == (HsWordPrim _ x2) = x1==x2
(HsInt64Prim _ x1) == (HsInt64Prim _ x2) = x1==x2
(HsWord64Prim _ x1) == (HsWord64Prim _ x2) = x1==x2
(HsInteger _ x1 _) == (HsInteger _ x2 _) = x1==x2
(HsRat x1 _) == (HsRat x2 _) = x1==x2
(HsFloatPrim x1) == (HsFloatPrim x2) = x1==x2
(HsDoublePrim x1) == (HsDoublePrim x2) = x1==x2
_ == _ = False
data HsOverLit id -- An overloaded literal
= OverLit {
ol_val :: OverLitVal,
ol_rebindable :: PostRn id Bool, -- Note [ol_rebindable]
ol_witness :: HsExpr id, -- Note [Overloaded literal witnesses]
ol_type :: PostTc id Type }
deriving instance (DataId id) => Data (HsOverLit id)
-- Note [Literal source text] in BasicTypes for SourceText fields in
-- the following
data OverLitVal
= HsIntegral !SourceText !Integer -- Integer-looking literals;
| HsFractional !FractionalLit -- Frac-looking literals
| HsIsString !SourceText !FastString -- String-looking literals
deriving Data
overLitType :: HsOverLit a -> PostTc a Type
overLitType = ol_type
{-
Note [ol_rebindable]
~~~~~~~~~~~~~~~~~~~~
The ol_rebindable field is True if this literal is actually
using rebindable syntax. Specifically:
False iff ol_witness is the standard one
True iff ol_witness is non-standard
Equivalently it's True if
a) RebindableSyntax is on
b) the witness for fromInteger/fromRational/fromString
that happens to be in scope isn't the standard one
Note [Overloaded literal witnesses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*Before* type checking, the HsExpr in an HsOverLit is the
name of the coercion function, 'fromInteger' or 'fromRational'.
*After* type checking, it is a witness for the literal, such as
(fromInteger 3) or lit_78
This witness should replace the literal.
This dual role is unusual, because we're replacing 'fromInteger' with
a call to fromInteger. Reason: it allows commoning up of the fromInteger
calls, which wouldn't be possible if the desguarar made the application.
The PostTcType in each branch records the type the overload literal is
found to have.
-}
-- Comparison operations are needed when grouping literals
-- for compiling pattern-matching (module MatchLit)
instance Eq (HsOverLit id) where
(OverLit {ol_val = val1}) == (OverLit {ol_val=val2}) = val1 == val2
instance Eq OverLitVal where
(HsIntegral _ i1) == (HsIntegral _ i2) = i1 == i2
(HsFractional f1) == (HsFractional f2) = f1 == f2
(HsIsString _ s1) == (HsIsString _ s2) = s1 == s2
_ == _ = False
instance Ord (HsOverLit id) where
compare (OverLit {ol_val=val1}) (OverLit {ol_val=val2}) = val1 `compare` val2
instance Ord OverLitVal where
compare (HsIntegral _ i1) (HsIntegral _ i2) = i1 `compare` i2
compare (HsIntegral _ _) (HsFractional _) = LT
compare (HsIntegral _ _) (HsIsString _ _) = LT
compare (HsFractional f1) (HsFractional f2) = f1 `compare` f2
compare (HsFractional _) (HsIntegral _ _) = GT
compare (HsFractional _) (HsIsString _ _) = LT
compare (HsIsString _ s1) (HsIsString _ s2) = s1 `compare` s2
compare (HsIsString _ _) (HsIntegral _ _) = GT
compare (HsIsString _ _) (HsFractional _) = GT
instance Outputable HsLit where
ppr (HsChar _ c) = pprHsChar c
ppr (HsCharPrim _ c) = pprPrimChar c
ppr (HsString _ s) = pprHsString s
ppr (HsStringPrim _ s) = pprHsBytes s
ppr (HsInt _ i) = integer i
ppr (HsInteger _ i _) = integer i
ppr (HsRat f _) = ppr f
ppr (HsFloatPrim f) = ppr f <> primFloatSuffix
ppr (HsDoublePrim d) = ppr d <> primDoubleSuffix
ppr (HsIntPrim _ i) = pprPrimInt i
ppr (HsWordPrim _ w) = pprPrimWord w
ppr (HsInt64Prim _ i) = pprPrimInt64 i
ppr (HsWord64Prim _ w) = pprPrimWord64 w
-- in debug mode, print the expression that it's resolved to, too
instance (OutputableBndrId id) => Outputable (HsOverLit id) where
ppr (OverLit {ol_val=val, ol_witness=witness})
= ppr val <+> (ifPprDebug (parens (pprExpr witness)))
instance Outputable OverLitVal where
ppr (HsIntegral _ i) = integer i
ppr (HsFractional f) = ppr f
ppr (HsIsString _ s) = pprHsString s
-- | pmPprHsLit pretty prints literals and is used when pretty printing pattern
-- match warnings. All are printed the same (i.e., without hashes if they are
-- primitive and not wrapped in constructors if they are boxed). This happens
-- mainly for too reasons:
-- * We do not want to expose their internal representation
-- * The warnings become too messy
pmPprHsLit :: HsLit -> SDoc
pmPprHsLit (HsChar _ c) = pprHsChar c
pmPprHsLit (HsCharPrim _ c) = pprHsChar c
pmPprHsLit (HsString _ s) = pprHsString s
pmPprHsLit (HsStringPrim _ s) = pprHsBytes s
pmPprHsLit (HsInt _ i) = integer i
pmPprHsLit (HsIntPrim _ i) = integer i
pmPprHsLit (HsWordPrim _ w) = integer w
pmPprHsLit (HsInt64Prim _ i) = integer i
pmPprHsLit (HsWord64Prim _ w) = integer w
pmPprHsLit (HsInteger _ i _) = integer i
pmPprHsLit (HsRat f _) = ppr f
pmPprHsLit (HsFloatPrim f) = ppr f
pmPprHsLit (HsDoublePrim d) = ppr d
| sgillespie/ghc | compiler/hsSyn/HsLit.hs | bsd-3-clause | 8,103 | 0 | 12 | 2,172 | 1,885 | 977 | 908 | 124 | 1 |
-- | Spawn subprocesses and interact with them using "Pipes"
--
-- The interface in this module deliberately resembles the interface
-- in "System.Process". However, one consequence of this is that you
-- will not want to have unqualified names from this module and from
-- "System.Process" in scope at the same time.
--
-- As in "System.Process", you create a subprocess by creating a
-- 'CreateProcess' record and then applying a function to that
-- record. Unlike "System.Process", you use functions such as
-- 'pipeInput' or 'pipeInputOutput' to specify what streams you want
-- to use a 'Proxy' for and what streams you wish to be 'Inherit'ed
-- or if you want to 'UseHandle'. You then send or receive
-- information using one or more 'Proxy'.
--
-- __Use the @-threaded@ GHC option__ when compiling your programs or
-- when using GHCi. Internally, this module uses
-- 'System.Process.waitForProcess' from the "System.Process" module.
-- As the documentation for 'waitForProcess' states, you must use the
-- @-threaded@ option to prevent every thread in the system from
-- suspending when 'waitForProcess' is used. So, if your program
-- experiences deadlocks, be sure you used the @-threaded@ option.
--
-- This module relies on the "Pipes", "Pipes.Safe",
-- "Control.Concurrent.Async", and "System.Process" modules. You will
-- want to have basic familiarity with what all of those modules do
-- before using this module.
--
-- All communcation with subprocesses is done with strict
-- 'ByteString's. If you are dealing with textual data, the @text@
-- library has functions to convert a 'ByteString' to a @Text@; you
-- will want to look at @Data.Text.Encoding@.
--
-- Nobody would mistake this module for a shell; nothing beats the
-- shell as a language for starting other programs, as the shell is
-- designed for that. This module allows you to perform simple
-- streaming with subprocesses without leaving the comfort of Haskell.
-- Take a look at the README.md file, which is distributed with the
-- tarball or is available at Github at
--
-- <https://github.com/massysett/pipes-cliff>
--
-- There you will find references to other libraries that you might
-- find more useful than this one.
--
-- You will want to consult "Pipes.Cliff.Examples" for some examples
-- before getting started. There are some important notes in there
-- about how to run pipelines.
module Pipes.Cliff
( -- * Specifying a subprocess's properties
CmdSpec(..)
, NonPipe(..)
, CreateProcess(..)
, procSpec
, squelch
-- * Creating processes
-- $process
, pipeInput
, pipeOutput
, pipeError
, pipeInputOutput
, pipeInputError
, pipeOutputError
, pipeInputOutputError
-- * 'Proxy' combinators
, conveyor
, safeEffect
-- * Querying and terminating the process
, ProcessHandle
, originalCreateProcess
, isStillRunning
, waitForProcess
, terminateProcess
-- * Exception safety
-- | These are some simple combinators built with
-- 'Control.Exception.bracket'; feel free to use your own favorite
-- idioms for exception safety.
, withProcess
, withConveyor
-- * Errors and warnings
-- | You will only need what's in this section if you want to
-- examine errors more closely.
, Activity(..)
, Outbound(..)
, HandleDesc(..)
, Oopsie(..)
-- * Re-exports
-- $reexports
, module Control.Concurrent.Async
, module Pipes
, module Pipes.Safe
, module System.Exit
-- * Some design notes
-- $designNotes
) where
import Control.Concurrent.Async
import Pipes.Cliff.Core
import Pipes
import Pipes.Safe (runSafeT)
import System.Exit
{- $process
Each of these functions creates a process. The process begins
running immediately in a separate process while your Haskell program
continues concurrently. A function is provided for each possible
combination of standard input, standard output, and standard error.
Use the 'NonPipe' type to describe what you want to do with streams
you do NOT want to create a stream for. For example, to create a
subprocess that creates a 'Proxy' for standard input and standard
output, use 'pipeInputOutput'. You must describe what you want done
with standard error. A 'Producer' is returned for standard output
and a 'Consumer' for standard input.
Each function also returns a 'ProcessHandle'; this is not the same
'ProcessHandle' that you will find in "System.Process". You can use
this 'ProcessHandle' to obtain some information about the process that
is created and to get the eventual 'ExitCode'.
Every time you create a process with one of these functions, some
additional behind-the-scenes resources are created, such as some
threads to move data to and from the process. In normal usage, these
threads will be cleaned up after the process exits. However, if
exceptions are thrown, there could be resource leaks. Applying
'terminateProcess' to a 'ProcessHandle' makes a best effort to clean
up all the resources that Cliff may create, including the process
itself and any additional threads. To guard against resource leaks,
use the functions found in "Control.Exception" or in
"Control.Monad.Catch". "Control.Monad.Catch" provides operations that
are the same as those in "Control.Exception", but they are not limited
to 'IO'.
I say that 'terminateProcess' \"makes a best effort\" to release
resources because in UNIX it merely sends a @SIGTERM@ to the process.
That should kill well-behaved processes, but 'terminateProcess' does
not send a @SIGKILL@. 'terminateProcess' always closes all handles
associated with the process and it kills all Haskell threads that were
moving data to and from the process. ('terminateProcess' does not
kill threads it does not know about, such as threads you created with
'conveyor'.)
There is no function that will create a process that has no 'Proxy'
at all. For that, just use 'System.Process.createProcess' in
"System.Process".
-}
{- $reexports
* "Control.Concurrent.Async" reexports all bindings
* "Pipes" reexports all bindings
* "Pipes.Safe" reexports 'runSafeT'
* "System.Exit" reexports all bindings
-}
{- $designNotes
Two overarching principles guided the design of this
library. First, I wanted the interface to use simple
ByteStrings. That most closely represents what a UNIX process
sees. If the user wants to use Text or String, it's easy
enough to convert between those types and a ByteString. Then
the user has to pay explicit attention to encoding issues--as
she should, because not all UNIX processes deal with encoded
textual data.
Second, I paid meticulous attention to resource management. Resources
are deterministically destroyed immediately after use. This
eliminates many bugs. Even so, I decided to leave it up to the user
to use something like 'Control.Exception.bracket' to ensure that all
resources are cleaned up if there is an exception. Originally I tried
to have the library do this, but that turned out not to be very
composable. There are already many exception-handling mechanisms
available in "Control.Exception", "Pipes.Safe", and
"Control.Monad.Catch", and it seems best to let the user choose how to
handle this issue; she can just perform a 'Control.Exception.bracket'
and may combine this with the @ContT@ monad in @transformers@ or @mtl@
if she wishes, or perhaps with the @managed@ library.
An earlier version of this library (see version 0.8.0.0) tried to use
the return value of a 'Proxy' to indicate the return value of both
processes in the pipeline, not just one. I removed this because it
interfered heavily with composability.
You might wonder why, if you are using an external process as
a pipeline, why can't you create, well, a 'Pipe'? Wouldn't
that be an obvious choice? Well, if such an interface is
possible using Pipes in its current incarnation, nobody has
figured it out yet. I don't think it's possible. See also
<https://groups.google.com/d/msg/haskell-pipes/JFfyquj5HAg/Lxz7p50JOh4J>
for a discussion about this.
-}
| massysett/pipes-cliff | pipes-cliff/lib/Pipes/Cliff.hs | bsd-3-clause | 7,997 | 0 | 5 | 1,394 | 231 | 178 | 53 | 36 | 0 |
module Reinforce.Agents
( runLearner
, clockEpisodes
, clockSteps
) where
import Control.Monad
import Control.Monad.IO.Class
import Control.MonadEnv
import qualified Control.MonadEnv as Env (reset)
runLearner
:: MonadEnv m o a r
=> MonadIO m
=> Maybe Integer
-> Maybe Integer
-> (Maybe Integer -> o -> m ())
-> m ()
runLearner maxEps maxSteps rollout =
clockEpisodes maxEps 0 maxSteps rollout
clockEpisodes
:: forall m o a r . MonadEnv m o a r
=> Maybe Integer
-> Integer
-> Maybe Integer
-> (Maybe Integer -> o -> m ())
-> m ()
clockEpisodes maxEps epn maxSteps rollout = do
case maxEps of
Nothing -> tick
Just mx -> unless (epn > mx) tick
where
tick :: m ()
tick = Env.reset >>= \case
EmptyEpisode -> pure ()
Initial s -> do
rollout maxSteps s
clockEpisodes maxEps (epn+1) maxSteps rollout
clockSteps :: Monad m => Maybe Integer -> Integer -> (Integer -> m ()) -> m ()
clockSteps Nothing st tickAct = tickAct st
clockSteps (Just mx) st tickAct = unless (st >= mx) (tickAct st)
| stites/reinforce | reinforce-algorithms/src/Reinforce/Agents.hs | bsd-3-clause | 1,073 | 0 | 15 | 268 | 422 | 211 | 211 | -1 | -1 |
module Main where
import IO
import Wash.HTMLMonad
import Wash.CGI
import Data.Char( toLower )
-- autoan-modules
import HTMLshortcuts
import SQLqueries
import Helper
import Exception
-- EX
import Database.MySQL.HSQL
--
-- TODO
-- SQL-Exception fangen
-- Seiten Struktur rausziehen: stdpage ttl bdy menu
main :: IO ()
main =
run [] (
--findStudPage
loginPage "" F0 --mainCGI
)
`Exception.catch` \ ex -> putStrLn $ "\n\n" ++ show ex
-- Einstieg: loginPage
loginPage lgn F0 =
standardQuery "Willkommen zum Autotool-Admin." $ do
table $ do
attr "width" "600"
hrrow
lgnF <- promptedInput "Name:" $ (fieldSIZE 30) ## ( fieldVALUE lgn )
pwdF <- promptedPassword "Passwort:" (fieldSIZE 30)
hrrow
smallSubButton (F2 lgnF pwdF) checkLoginPage "Login"
-- TODO admin id muss durch gereicht werden, um verschieden rechte zuzulassen...."
-- z.B. Korrektor
checkLoginPage (F2 lgnF pwdF) =
let
lgn = unNonEmpty ( value lgnF )
pass = unNonEmpty ( value pwdF )
in
do
-- lgnok <- io $ checkAdminNamePasswortDB lgn passwort
-- EX
lgnok <- io $ failDB lgn pass `catchSql` \e -> do
error $ "sql fehler!" ++ (seErrorMsg e)
if lgnok
then findStudPage
else standardQuery "Fehler" $ do
hrline
h3 $ text "Name oder Passwort fehlerhaft."
hrline
submit F0 (loginPage lgn) (fieldVALUE "Zurück")
-- do inh <- io $ checkPasswdMNrDB (Just pass) lgn
-- if ( (length inh) == 0 ) -- passwort nicht okay?
-- then
-- do standardQuery "Fehler:" $
-- table $ do
-- hrrow
-- th3 "Passwort und Matrikelnummer stimmen nicht überein!"
-- hrrow
-- smallSubButton F0 (loginPage lgn) "Login wiederholen"
-- smallSubButton F0 endPage "Ende"
-- else
-- do
--
findStudPage = do
standardQuery "Auto-Admin" $
do
findStudTable "" "" "" "" ""
findStudTable vnm nme mat eml vrl = do
table $ do
th3 "Suche nach Teilworten (und verknüpft)"
ttxt "Pattern \'_\' = ein Zeichen \'#\' = bel. viele Zeichen"
spacerow
matF <- promptedInput "Matrikelnr.:" ( (fieldSIZE 30) ## (fieldVALUE mat) )
vnmF <- promptedInput "Vorname:" ( (fieldSIZE 30) ## (fieldVALUE vnm) )
nmeF <- promptedInput "Name:" ( (fieldSIZE 30) ## (fieldVALUE nme) )
emlF <- promptedInput "Email:" ( (fieldSIZE 30) ## (fieldVALUE eml) )
vrlF <- promptedInput "Vorlesung:" ( (fieldSIZE 30) ## (fieldVALUE vrl) )
tr $
do
td $ submit (F5 vnmF nmeF matF emlF vrlF) foundStudPage (fieldVALUE "Suche")
foundStudPage (F5 vnmF nmeF matF emlF vrlF) =
let vnm = unText $ value vnmF
nme = unText $ value nmeF
mat = unText $ value matF
eml = unText $ value emlF
vrl = unText $ value vrlF
in
do
erg <- io $ findStudDB vnm nme mat eml vrl
standardQuery "Suchergebnis:" $ do
hrline
findStudTable vnm nme mat eml vrl
hrline
table $ do
attr "border" "1"
attr "frame" "void"
attr "rules" "rows"
attr "cellspacing" "2"
attr "cellpadding" "5"
sel <- radioGroup empty
-- Edit Menu
tr $ do
td $ submit (F1 sel) (editStudentPage') (fieldVALUE "Edt")
td $ submit (F1 sel) removeStudentPage (fieldVALUE "Del")
-- Head [ "Sel." , Table-Head ... ]
let thtxt x = th ( text x ## attr "align" "left")
tr $ th (text "Sel.") >> mapM_ thtxt ( fst erg )
-- Data [ radioButton , Table-Data ... ]
let { sline xs = tr $
( td (radioButton sel (tos xs) empty ) ) ##
( sequence $ Prelude.map textOrInt' xs )
; textOrInt' (I i ) = td $ text (show i)
; textOrInt' (S s ) = td $ text s
; textOrInt2Str (I i) = show i;
; textOrInt2Str (S s) = s;
; tos xs = Prelude.map textOrInt2Str xs
}
mapM_ sline ( snd erg )
radioError sel
editStudentPage' (F1 sel) =
let
str :: [ String ]
str = value sel
mat = str!!1
in
editStudentPage mat F0
inputStudent mat vnm nme eml pas =
do
matF <- promptedInput "Matrikelnr.:" ( (fieldSIZE 30) ## (fieldVALUE mat) )
vnmF <- promptedInput "Vorname:" ( (fieldSIZE 30) ## (fieldVALUE vnm) )
nmeF <- promptedInput "Name:" ( (fieldSIZE 30) ## (fieldVALUE nme) )
emlF <- promptedInput "Email:" ( (fieldSIZE 30) ## (fieldVALUE eml) )
pasF <- promptedInput "Passwd:" ( (fieldSIZE 30) ## (fieldVALUE pas) )
return (matF, vnmF , nmeF , emlF , pasF )
addVorlesungChoice mat mgladdVl =
do
if length mgladdVl > 0
then
tr $ do
addVlF <- td (selectSingle show Nothing mgladdVl empty)
td $ submit (F1 addVlF) (addedVorlesungPage mat mgladdVl) (fieldVALUE "Add")
else
do
ttxt "Add Vorlesung: Bereits alle Vorlesungen ausgewählt."
removeVorlesungChoice mat mgldelVl = do
if length mgldelVl > 0
then
tr $ do
delVlF <- td (selectSingle show Nothing mgldelVl empty)
td $ submit (F1 delVlF) (deledVorlesungPage mat mgldelVl) (fieldVALUE "Del")
else do
ttxt "Del Vorlesung: Alle Vorlesungen des Studenten sind bepunktet. "
editStudentPage mat F0 =
do
inh <- io $ getStudentDB mat
result <- io $ studAufgDB mat
-- besuchte, bepunktete und alle mgl. Vorlesungen
vl <- io $ studVorlDB mat
vlwpt <- io $ getVorlesungWithPointsDB mat
vls <- io $ getAllVorlesungenDB
let
( S vnm , S nme , S eml , S sta , S pas ) = inh !! 0
mgladdVl = [ v | v <- vls , not ( v `elem` vl ) ]
mgldelVl = [ v | v <- vl , not ( v `elem` vlwpt ) ]
standardQuery "Edit Student" $
table $
do
hrrow
-- Stammdaten ändern
(matF,vnmF,nmeF,emlF,pasF) <- inputStudent mat vnm nme eml pas
submit (F5 matF vnmF nmeF emlF pasF)
(editSubmitStudentPage mat vnm nme eml pas)
(fieldVALUE "Submit")
hrrow
-- Vorlesungen
tableRow2 (text "Vorlesung:") $ text $ if length vl > 0 then foldr1 kommas vl else "keine"
-- Vorlesungen hinzufügen (bereits verhanden ignorieren)
addVorlesungChoice mat mgladdVl
-- Vorlesung entfernen (bepunktete ignorien)
removeVorlesungChoice mat mgldelVl
-- Ergebnisse des Studenten
hrrow
smallspacerow
if length (snd result) > 0
then do { h3 $ text "Ergebnisse" ; ( showAsTable result ) }
else do { h3 $ text "keine Ergebnisse" }
hrrow
editSubmitStudentPage mat' vnm' nme' eml' pas' (F5 matF vnmF nmeF emlF pasF) =
let
mat = unAllDigits $ value matF
vnm = unNonEmpty $ value vnmF
nme = unNonEmpty $ value nmeF
eml = unNonEmpty $ value emlF
pas = unText $ value pasF
matok = if allDigits mat then (read mat) > 1024 else False
in
do
-- suche nach dupletten von email or mat
( matDup , emlDup ) <- io $ duplMatOrEmailDB mat eml
-- [(was kann schief gehen , fehlermsg )]
let { checks = [ ( not matok
, "Die Matrikelnummer muss größer 1024 sein.")
, ( length vnm < 2
, "Der Vorname muss mindestens 2 Buchstaben lang sein.")
, ( length nme < 2
, "Der Name muss mindestens 2 Buchstaben lang sein.")
, ( matDup && (mat' /= mat)
, "Matrikelnummer bereits registiert." )
, ( emlDup && (eml' /= eml)
, "Email bereits registiert." )
]
-- alles ok?
; allok = and [ not (fst c) | c <- checks ]
}
-- alles ok -> abfeuern
if allok
then io $ updateStudDB mat' mat vnm nme eml pas
else return ()
standardQuery "Hello" $ table $
do
if allok
then ttxt "Alles Okay"
else mapM_ ttxt [ msg | ( ok , msg ) <- checks , ok ]
addedVorlesungPage mat mglVl (F1 addVlF) = do
let addVl = value $ addVlF
io $ insertStudVorlDB mat addVl
standardQuery "Vorlesung hinzufügen" $
do
table $ do
attr "width" "600"
hrrow
tr $ td $ text $ "Vorlesung " ++ addVl ++ " hinzugefügt."
hrrow
smallSubButton F0 (editStudentPage mat) "Weiter"
deledVorlesungPage mat mglVl (F1 addVlF) = do
let addVl = value $ addVlF
io $ removeStudVorlDB mat addVl
standardQuery "Vorlesung entfernt." $
do
table $ do
attr "width" "600"
hrrow
tr $ td $ text $ "Vorlesung " ++ addVl ++ " entfernt."
hrrow
smallSubButton F0 (editStudentPage mat) "Weiter"
removeStudentPage (F1 sel) =
let
str :: [String]
str = value sel
in
standardQuery "Remove Student" $
table $
do
h3 $ text "noch nicht fertig..."
tr $ text $ show str
| Erdwolf/autotool-bonn | src/control/autoadmin.hs | gpl-2.0 | 8,256 | 175 | 25 | 2,169 | 2,810 | 1,382 | 1,428 | -1 | -1 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Internal
-- Copyright : (C) 2012-16 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : Rank2Types
--
-- These are some of the explicit 'Functor' instances that leak into the
-- type signatures of @Control.Lens@. You shouldn't need to import this
-- module directly for most use-cases.
--
----------------------------------------------------------------------------
module Control.Lens.Internal
( module Control.Lens.Internal.Bazaar
, module Control.Lens.Internal.Context
, module Control.Lens.Internal.Fold
, module Control.Lens.Internal.Getter
, module Control.Lens.Internal.Indexed
, module Control.Lens.Internal.Iso
, module Control.Lens.Internal.Level
, module Control.Lens.Internal.Magma
, module Control.Lens.Internal.Prism
, module Control.Lens.Internal.Review
, module Control.Lens.Internal.Setter
, module Control.Lens.Internal.Zoom
) where
import Control.Lens.Internal.Bazaar
import Control.Lens.Internal.Context
import Control.Lens.Internal.Fold
import Control.Lens.Internal.Getter
import Control.Lens.Internal.Indexed
import Control.Lens.Internal.Instances ()
import Control.Lens.Internal.Iso
import Control.Lens.Internal.Level
import Control.Lens.Internal.Magma
import Control.Lens.Internal.Prism
import Control.Lens.Internal.Review
import Control.Lens.Internal.Setter
import Control.Lens.Internal.Zoom
#ifdef HLINT
{-# ANN module "HLint: ignore Use import/export shortcut" #-}
#endif
| ddssff/lens | src/Control/Lens/Internal.hs | bsd-3-clause | 1,676 | 0 | 5 | 200 | 217 | 163 | 54 | 27 | 0 |
module Data.Graph.Inductive.Query.MaxFlow2
(Network, ekSimple, ekFused, ekList) where
{ import Data.List;
import Data.Maybe;
import Data.Graph.Inductive.Graph;
import Data.Graph.Inductive.Tree;
import Data.Graph.Inductive.Internal.FiniteMap;
import Data.Graph.Inductive.Internal.Queue;
import Data.Graph.Inductive.Query.BFS (bft);
type Network = Gr () (Double, Double);
data Direction = Forward
| Backward
deriving (Eq, Show);
type DirEdge b = (Node, Node, b, Direction);
type DirPath = [(Node, Direction)];
type DirRTree = [DirPath];
pathFromDirPath = map (\ (n, _) -> n);
augPathFused :: Network -> Node -> Node -> Maybe DirPath;
augPathFused g s t
= listToMaybe $ map reverse $
filter (\ ((u, _) : _) -> u == t) tree
where { tree = bftForEK s g};
bftForEK :: Node -> Network -> DirRTree;
bftForEK v = bfForEK (queuePut [(v, Forward)] mkQueue);
bfForEK :: Queue DirPath -> Network -> DirRTree;
bfForEK q g
| queueEmpty q || isEmpty g = []
| otherwise =
case match v g of
{ (Nothing, g') -> bfForEK q1 g';
(Just (preAdj, _, _, sucAdj), g') -> p : bfForEK q2 g'
where { q2 = queuePutList suc1 $ queuePutList suc2 q1;
suc1
= [(preNode, Backward) : p | ((_, f), preNode) <- preAdj, f > 0];
suc2
= [(sucNode, Forward) : p | ((c, f), sucNode) <- sucAdj, c > f]}}
where { (p@((v, _) : _), q1) = queueGet q};
extractPathFused ::
Network -> DirPath -> ([DirEdge (Double, Double)], Network);
extractPathFused g [] = ([], g);
extractPathFused g [(_, _)] = ([], g);
extractPathFused g ((u, _) : rest@((v, Forward) : _))
= ((u, v, l, Forward) : tailedges, newerg)
where { (tailedges, newerg) = extractPathFused newg rest;
Just (l, newg) = extractEdge g u v (\ (c, f) -> (c > f))};
extractPathFused g ((u, _) : rest@((v, Backward) : _))
= ((v, u, l, Backward) : tailedges, newerg)
where { (tailedges, newerg) = extractPathFused newg rest;
Just (l, newg) = extractEdge g v u (\ (_, f) -> (f > 0))};
ekFusedStep g s t
= case maybePath of
{ Just _
-> Just ((insEdges (integrateDelta es delta) newg), delta);
Nothing -> Nothing}
where { maybePath = augPathFused g s t;
(es, newg) = extractPathFused g (fromJust maybePath);
delta = minimum $ getPathDeltas es};
ekFused :: Network -> Node -> Node -> (Network, Double);
ekFused = ekWith ekFusedStep;
residualGraph :: Network -> Gr () Double;
residualGraph g
= mkGraph (labNodes g)
([(u, v, c - f) | (u, v, (c, f)) <- labEdges g, c > f] ++
[(v, u, f) | (u, v, (_, f)) <- labEdges g, f > 0]);
augPath :: Network -> Node -> Node -> Maybe Path;
augPath g s t
= listToMaybe $ map reverse $ filter (\ (u : _) -> u == t) tree
where { tree = bft s (residualGraph g)};
extractPath ::
Network -> Path -> ([DirEdge (Double, Double)], Network);
extractPath g [] = ([], g);
extractPath g [_] = ([], g);
extractPath g (u : v : ws)
= case fwdExtract of
{ Just (l, newg) -> ((u, v, l, Forward) : tailedges, newerg)
where { (tailedges, newerg) = extractPath newg (v : ws)};
Nothing
-> case revExtract of
{ Just (l, newg) -> ((v, u, l, Backward) : tailedges, newerg)
where { (tailedges, newerg) = extractPath newg (v : ws)};
Nothing -> error "extractPath: revExtract == Nothing"}}
where { fwdExtract = extractEdge g u v (\ (c, f) -> (c > f));
revExtract = extractEdge g v u (\ (_, f) -> (f > 0))};
extractEdge ::
Gr a b -> Node -> Node -> (b -> Bool) -> Maybe (b, Gr a b);
extractEdge g u v p
= case adj of
{ Just (el, _) -> Just (el, (p', node, l, rest) & newg);
Nothing -> Nothing}
where { (Just (p', node, l, s), newg) = match u g;
(adj, rest)
= extractAdj s (\ (l', dest) -> (dest == v) && (p l'))};
extractAdj ::
Adj b -> ((b, Node) -> Bool) -> (Maybe (b, Node), Adj b);
extractAdj [] _ = (Nothing, []);
extractAdj (adj : adjs) p
| p adj = (Just adj, adjs)
| otherwise = (theone, adj : rest)
where { (theone, rest) = extractAdj adjs p};
getPathDeltas :: [DirEdge (Double, Double)] -> [Double];
getPathDeltas [] = [];
getPathDeltas (e : es)
= case e of
{ (_, _, (c, f), Forward) -> (c - f) : (getPathDeltas es);
(_, _, (_, f), Backward) -> f : (getPathDeltas es)};
integrateDelta ::
[DirEdge (Double, Double)] -> Double -> [LEdge (Double, Double)];
integrateDelta [] _ = [];
integrateDelta (e : es) delta
= case e of
{ (u, v, (c, f), Forward)
-> (u, v, (c, f + delta)) : (integrateDelta es delta);
(u, v, (c, f), Backward)
-> (u, v, (c, f - delta)) : (integrateDelta es delta)};
type EKStepFunc =
Network -> Node -> Node -> Maybe (Network, Double);
ekSimpleStep :: EKStepFunc;
ekSimpleStep g s t
= case maybePath of
{ Just _
-> Just ((insEdges (integrateDelta es delta) newg), delta);
Nothing -> Nothing}
where { maybePath = augPath g s t;
(es, newg) = extractPath g (fromJust maybePath);
delta = minimum $ getPathDeltas es};
ekWith ::
EKStepFunc -> Network -> Node -> Node -> (Network, Double);
ekWith stepfunc g s t
= case stepfunc g s t of
{ Just (newg, delta) -> (finalg, capacity + delta)
where { (finalg, capacity) = (ekWith stepfunc newg s t)};
Nothing -> (g, 0)};
ekSimple :: Network -> Node -> Node -> (Network, Double);
ekSimple = ekWith ekSimpleStep;
setFromList :: (Ord a) => [a] -> FiniteMap a ();
setFromList [] = emptyFM;
setFromList (x : xs) = addToFM (setFromList xs) x ();
setContains :: (Ord a) => FiniteMap a () -> a -> Bool;
setContains m i
= case (lookupFM m i) of
{ Nothing -> False;
Just () -> True};
extractPathList ::
[LEdge (Double, Double)] ->
FiniteMap (Node, Node) () ->
([DirEdge (Double, Double)], [LEdge (Double, Double)]);
extractPathList [] _ = ([], []);
extractPathList (edge@(u, v, l@(c, f)) : es) set
| (c > f) && (setContains set (u, v)) =
let { (pathrest, notrest)
= extractPathList es (delFromFM set (u, v))}
in ((u, v, l, Forward) : pathrest, notrest)
| (f > 0) && (setContains set (v, u)) =
let { (pathrest, notrest)
= extractPathList es (delFromFM set (u, v))}
in ((u, v, l, Backward) : pathrest, notrest)
| otherwise =
let { (pathrest, notrest) = extractPathList es set} in
(pathrest, edge : notrest);
ekStepList :: EKStepFunc;
ekStepList g s t
= case maybePath of
{ Just _ -> Just (mkGraph (labNodes g) newEdges, delta);
Nothing -> Nothing}
where { newEdges = (integrateDelta es delta) ++ otheredges;
maybePath = augPathFused g s t;
(es, otheredges)
= extractPathList (labEdges g)
(setFromList (zip justPath (tail justPath)));
delta = minimum $ getPathDeltas es;
justPath = pathFromDirPath (fromJust maybePath)};
ekList :: Network -> Node -> Node -> (Network, Double);
ekList = ekWith ekStepList}
| ckaestne/CIDE | other/CaseStudies/fgl/CIDEfgl/Data/Graph/Inductive/Query/MaxFlow2.hs | gpl-3.0 | 7,718 | 0 | 15 | 2,501 | 3,320 | 1,895 | 1,425 | 173 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Yesod.Form.I18n.English where
import Yesod.Form.Types (FormMessage (..))
import Data.Monoid (mappend)
import Data.Text (Text)
englishFormMessage :: FormMessage -> Text
englishFormMessage (MsgInvalidInteger t) = "Invalid integer: " `Data.Monoid.mappend` t
englishFormMessage (MsgInvalidNumber t) = "Invalid number: " `mappend` t
englishFormMessage (MsgInvalidEntry t) = "Invalid entry: " `mappend` t
englishFormMessage MsgInvalidTimeFormat = "Invalid time, must be in HH:MM[:SS] format"
englishFormMessage MsgInvalidDay = "Invalid day, must be in YYYY-MM-DD format"
englishFormMessage (MsgInvalidUrl t) = "Invalid URL: " `mappend` t
englishFormMessage (MsgInvalidEmail t) = "Invalid e-mail address: " `mappend` t
englishFormMessage (MsgInvalidHour t) = "Invalid hour: " `mappend` t
englishFormMessage (MsgInvalidMinute t) = "Invalid minute: " `mappend` t
englishFormMessage (MsgInvalidSecond t) = "Invalid second: " `mappend` t
englishFormMessage MsgCsrfWarning = "As a protection against cross-site request forgery attacks, please confirm your form submission."
englishFormMessage MsgValueRequired = "Value is required"
englishFormMessage (MsgInputNotFound t) = "Input not found: " `mappend` t
englishFormMessage MsgSelectNone = "<None>"
englishFormMessage (MsgInvalidBool t) = "Invalid boolean: " `mappend` t
englishFormMessage MsgBoolYes = "Yes"
englishFormMessage MsgBoolNo = "No"
englishFormMessage MsgDelete = "Delete?"
| s9gf4ult/yesod | yesod-form/Yesod/Form/I18n/English.hs | mit | 1,469 | 0 | 7 | 174 | 320 | 178 | 142 | 24 | 1 |
module RefacGenCache where
import TypeCheck
import PrettyPrint
import PosSyntax
import AbstractIO
import Data.Maybe
import TypedIds
import UniqueNames hiding (srcLoc)
import PNT
import TiPNT
import Data.List
import RefacUtils hiding (getParams)
import PFE0 (findFile, allFiles, allModules)
import MUtils (( # ))
import RefacLocUtils
-- import System
import System.IO
import Relations
import Ents
import Data.Set (toList)
import Data.List
import System.IO.Unsafe
import System.Cmd
import LocalSettings (genFoldPath)
-- allows the selection of a function equation to
-- be outputted as AST representation to a file.
genFoldCache args
= do
let fileName = args!!0
begin = read (args!!1)::Int
end = read (args!!2)::Int
(inscps, exps, mod, tokList) <- parseSourceFile fileName
case checkCursor fileName begin end mod of
Left errMsg -> do error errMsg
Right decl ->
do
AbstractIO.writeFile genFoldPath (show decl)
AbstractIO.putStrLn "refacGenFoldCache"
checkCursor :: String -> Int -> Int -> HsModuleP -> Either String HsDeclP
checkCursor fileName row col mod
= case locToPName of
Nothing -> Left ("Invalid cursor position. Please place cursor at the beginning of the definition!")
Just decl -> Right decl
where
locToPName
= case res of
Nothing -> find (definesPNT (locToPNT fileName (row, col) mod)) (hsDecls mod)
_ -> res
res = find (defines (locToPN fileName (row, col) mod)) (concat (map hsDecls (hsModDecls mod)))
definesPNT pnt d@(Dec (HsPatBind loc p e ds))
= findPNT pnt d
definesPNT pnt d@(Dec (HsFunBind loc ms))
= findPNT pnt d
definesPNT _ _ = False
| kmate/HaRe | old/refactorer/RefacGenCache.hs | bsd-3-clause | 1,783 | 0 | 15 | 456 | 525 | 281 | 244 | 50 | 5 |
{-# NOINLINE f #-}
f :: Int -> Int
f = {-# SCC f #-} g
{-# NOINLINE g #-}
g :: Int -> Int
g x = {-# SCC g #-} x + 1
main = {-# SCC main #-} return $! f 3
| urbanslug/ghc | testsuite/tests/profiling/should_run/scc004.hs | bsd-3-clause | 157 | 0 | 6 | 48 | 53 | 30 | 23 | -1 | -1 |
-- #hide, prune, ignore-exports
-- |Module description
module A where
| siddhanathan/ghc | testsuite/tests/haddock/should_compile_noflag_haddock/haddockC016.hs | bsd-3-clause | 71 | 0 | 2 | 11 | 6 | 5 | 1 | 1 | 0 |
------------------------------------------------------------
-- Card ! Made by Mega Chan !
------------------------------------------------------------
card_valid :: String -> Bool
card_valid str = if ((card_value str) `mod` 10 == 0) then True else False
card_value :: String -> Int
card_value str = (add_even (map mul_2 (get_arr_even str ((length str) - 2)))) + (add_odd (get_arr_even str ((length str) - 1)))
add_odd :: [Int] -> Int
add_odd [] = 0
add_odd (x:xs) = x + (add_odd xs)
add_even :: [Int] -> Int
add_even [] = 0
add_even (x:xs) = (sum_digit x) + (add_even xs)
sum_digit :: Int -> Int
sum_digit 0 = 0
sum_digit x = (x `mod` 10) + (sum_digit (x `div` 10))
get_arr_even :: String -> Int -> [Int]
get_arr_even xs (-1) = []
get_arr_even xs (-2) = []
get_arr_even xs x = (read [(xs!!x)] :: Int) : (get_arr_even xs (x-2))
mul_2 :: Int -> Int
mul_2 x = x * 2
-- 下面乱七八糟 --
isValid :: Integer -> Bool
isValid x = card_valid (show x)
numValid :: [Integer] -> Integer
numValid xs = sum . map (\_ -> 1) $ filter isValid xs
creditcards :: [Integer]
creditcards = [ 4716347184862961,
4532899082537349,
4485429517622493,
4320635998241421,
4929778869082405,
5256283618614517,
5507514403575522,
5191806267524120,
5396452857080331,
5567798501168013,
6011798764103720,
6011970953092861,
6011486447384806,
6011337752144550,
6011442159205994,
4916188093226163,
4916699537435624,
4024607115319476,
4556945538735693,
4532818294886666,
5349308918130507,
5156469512589415,
5210896944802939,
5442782486960998,
5385907818416901,
6011920409800508,
6011978316213975,
6011221666280064,
6011285399268094,
6011111757787451,
4024007106747875,
4916148692391990,
4916918116659358,
4024007109091313,
4716815014741522,
5370975221279675,
5586822747605880,
5446122675080587,
5361718970369004,
5543878863367027,
6011996932510178,
6011475323876084,
6011358905586117,
6011672107152563,
6011660634944997,
4532917110736356,
4485548499291791,
4532098581822262,
4018626753711468,
4454290525773941,
5593710059099297,
5275213041261476,
5244162726358685,
5583726743957726,
5108718020905086,
6011887079002610,
6011119104045333,
6011296087222376,
6011183539053619,
6011067418196187,
4532462702719400,
4420029044272063,
4716494048062261,
4916853817750471,
4327554795485824,
5138477489321723,
5452898762612993,
5246310677063212,
5211257116158320,
5230793016257272,
6011265295282522,
6011034443437754,
6011582769987164,
6011821695998586,
6011420220198992,
4716625186530516,
4485290399115271,
4556449305907296,
4532036228186543,
4916950537496300,
5188481717181072,
5535021441100707,
5331217916806887,
5212754109160056,
5580039541241472,
6011450326200252,
6011141461689343,
6011886911067144,
6011835735645726,
6011063209139742,
379517444387209,
377250784667541,
347171902952673,
379852678889749,
345449316207827,
349968440887576,
347727987370269,
370147776002793,
374465794689268,
340860752032008,
349569393937707,
379610201376008,
346590844560212,
376638943222680,
378753384029375,
348159548355291,
345714137642682,
347556554119626,
370919740116903,
375059255910682,
373129538038460,
346734548488728,
370697814213115,
377968192654740,
379127496780069,
375213257576161,
379055805946370,
345835454524671,
377851536227201,
345763240913232
] | MegaShow/college-programming | Homework/Haskell Function Programming/card.hs | mit | 5,136 | 0 | 15 | 2,235 | 847 | 503 | 344 | 144 | 2 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Robot
( Bearing ( East
, North
, South
, West
)
, bearing
, coordinates
, mkRobot
, move
)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = do
describe "mkRobot" $ do
-- The function described by the reference file
-- as `create` is called `mkRobot` in this track.
it "Create robot at origin facing north" $ do
let robot = mkRobot North (0, 0)
coordinates robot `shouldBe` (0, 0)
bearing robot `shouldBe` North
it "Create robot at negative position facing south" $ do
let robot = mkRobot South (-1, -1)
coordinates robot `shouldBe` (-1, -1)
bearing robot `shouldBe` South
let turnTest inst dir dir2 =
let robot = mkRobot dir (0, 0) in
describe ("from " ++ show dir) $ do
it "should change direction" $
bearing (move robot inst) `shouldBe` dir2
it "shouldn't change position" $
coordinates (move robot inst) `shouldBe` (0, 0)
describe "Rotating clockwise" $ do
let rightTest = turnTest "R"
rightTest North East
rightTest East South
rightTest South West
rightTest West North
describe "Rotating counter-clockwise" $ do
let leftTest = turnTest "L"
leftTest North West
leftTest West South
leftTest South East
leftTest East North
describe "Moving forward one" $ do
let dir `from` pos = move (mkRobot dir pos) "A"
let test desc dir pos =
describe (show dir ++ " from " ++ show pos) $ do
it "shouldn't change direction" $
bearing (dir `from` (0, 0)) `shouldBe` dir
it desc $
coordinates (dir `from` (0, 0)) `shouldBe` pos
test "facing north increments Y" North (0, 1)
test "facing south decrements Y" South (0, -1)
test "facing east increments X" East (1, 0)
test "facing west decrements X" West (-1, 0)
describe "Follow series of instructions" $ do
let simulation pos dir = move (mkRobot dir pos)
it "moving east and north from README" $ do
let robot = simulation (7, 3) North "RAALAL"
coordinates robot `shouldBe` (9, 4)
bearing robot `shouldBe` West
it "moving west and north" $ do
let robot = simulation (0, 0) North "LAAARALA"
coordinates robot `shouldBe` (-4, 1)
bearing robot `shouldBe` West
it "moving west and south" $ do
let robot = simulation (2, -7) East "RRAAAAALA"
coordinates robot `shouldBe` (-3, -8)
bearing robot `shouldBe` South
it "moving east and north" $ do
let robot = simulation (8, 4) South "LAAARRRALLLL"
coordinates robot `shouldBe` (11, 5)
bearing robot `shouldBe` North
-- 7b07324f0a901c9234e9ffbb0beb889e9421e187
| exercism/xhaskell | exercises/practice/robot-simulator/test/Tests.hs | mit | 3,120 | 0 | 21 | 989 | 977 | 487 | 490 | 74 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
module Typeclasses where
import Prelude (not, Bool(..))
data Animal = Dog | Cat
class EqClass t where
equal :: t -> t -> Bool
neq :: t -> t -> Bool
neq a b = not (equal a b)
instance EqClass Animal where
equal Dog Dog = True
equal Cat Cat = True
equal _ _ = False
data EqDict t = EqDict { equal' :: t -> t -> Bool }
equalAnimal Dog Dog = True
equalAnimal Cat Cat = True
equalAnimal _ _ = False
animalEq :: EqDict Animal
animalEq = EqDict equalAnimal
neqAnimal :: EqClass t => t -> t -> Bool
neqAnimal a b = neq a b
neqAnimal' :: EqDict t -> t -> t -> Bool
neqAnimal' dict a b = not (equal' dict a b)
| riwsky/wiwinwlh | src/dictionaries.hs | mit | 661 | 0 | 10 | 162 | 274 | 143 | 131 | 22 | 1 |
module Euler.E54 where
import Data.List (sort, nub)
import Data.Maybe
import Euler.Lib (rotations)
data Rank = Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King | Ace
deriving (Eq, Ord, Show, Enum)
data Suit = Hearts | Spades | Diamonds | Clubs
deriving (Eq, Ord, Show)
data Card = Card
{ rank :: Rank
, suit :: Suit
}
deriving (Eq, Ord)
data HandVal =
HighCard [Rank]
| OnePair Rank HandVal
| TwoPairs Rank Rank HandVal
| ThreeOfAKind Rank HandVal
| Straight Rank
| Flush Suit HandVal
| FullHouse Rank Rank
| FourOfAKind Rank HandVal
| StraightFlush Rank
| RoyalFlush Suit
deriving (Eq, Ord, Show)
type Hand = [Card]
instance Read Rank where
readsPrec x (' ':s) = readsPrec x s
readsPrec _ ('2':s) = [(Two, s)]
readsPrec _ ('3':s) = [(Three, s)]
readsPrec _ ('4':s) = [(Four, s)]
readsPrec _ ('5':s) = [(Five, s)]
readsPrec _ ('6':s) = [(Six, s)]
readsPrec _ ('7':s) = [(Seven, s)]
readsPrec _ ('8':s) = [(Eight, s)]
readsPrec _ ('9':s) = [(Nine, s)]
readsPrec _ ('T':s) = [(Ten, s)]
readsPrec _ ('J':s) = [(Jack, s)]
readsPrec _ ('Q':s) = [(Queen, s)]
readsPrec _ ('K':s) = [(King, s)]
readsPrec _ ('A':s) = [(Ace, s)]
readsPrec _ s = error $ "read Rank: could not parse string '" ++ s ++ "'."
instance Read Suit where
readsPrec x (' ':s) = readsPrec x s
readsPrec _ ('H':s) = [(Hearts, s)]
readsPrec _ ('S':s) = [(Spades, s)]
readsPrec _ ('D':s) = [(Diamonds, s)]
readsPrec _ ('C':s) = [(Clubs, s)]
readsPrec _ s = error $ "read Suit: could not parse string '" ++ s ++ "'."
instance Show Card where
show (Card r s) = show r ++ " of " ++ show s
instance Read Card where
readsPrec x (' ':s) = readsPrec x s
readsPrec _ (r:s:x) = [(Card (read [r]) (read [s]), x)]
readsPrec _ s = error $ "read Card: could not parse string '" ++ s ++ "'."
instance Enum Card where
toEnum i = Card (toEnum i :: Rank) Spades
fromEnum (Card r _) = fromEnum r
euler54 :: [String] -> Int
euler54 ss = length $ filter isWinnerPlayer1 ss
debug :: String -> String
debug s = s ++ " -> " ++ (show v1) ++ " | " ++ (show v2) ++ " | " ++ (show $ v1 > v2)
where
(h1, h2) = mkHands 5 s
v1 = getHandVal h1
v2 = getHandVal h2
isWinnerPlayer1 :: String -> Bool
isWinnerPlayer1 s = v1 > v2
where
(h1, h2) = mkHands 5 s
v1 = getHandVal h1
v2 = getHandVal h2
mkHands :: Int -> String -> (Hand, Hand)
mkHands n s = readHands n $ words s
readHands :: Int -> [String] -> (Hand, Hand)
readHands n ss = (h1, h2)
where
cs = map (\s -> read s :: Card) ss
h1 = sort $ take n cs
h2 = sort $ take n $ drop n cs
getHandVal :: Hand -> HandVal
getHandVal h
| isJust $ rf = RoyalFlush (fromJust rf)
| isJust $ sf = StraightFlush (fromJust sf)
| isJust $ fk = FourOfAKind (fst $ fromJust fk) (HighCard $ s' $snd $ fromJust fk)
| isJust $ fh = FullHouse (fst $ fromJust fh) (snd $ fromJust fh)
| isJust $ f = Flush (fromJust f) (HighCard $ s' rs)
| isJust $ s = Straight (fromJust s)
| isJust $ tk = ThreeOfAKind (fst $ fromJust tk) (HighCard $ s' $ snd $ fromJust tk)
| isJust $ tp = TwoPairs (head $ fst $ fromJust tp) (last $ fst $ fromJust tp) (HighCard $ s' $snd $ fromJust tp)
| isJust $ p = OnePair (fst $ fromJust p) (HighCard $ s' $snd $ fromJust p)
| otherwise = HighCard (s' rs)
where
rs = map rank h
ss = map suit h
rf = isRoyalFlush h
sf = isStraightFlush h
fk = isFourOfAKind rs
fh = isFullHouse rs
f = isFlush ss
s = isStraight rs
tk = isThreeOfAKind rs
tp = isTwoPairs rs
p = isPair rs
s' = reverse . sort
isU :: Eq a => [a] -> Bool
isU xs = (length $ nub xs) == 1
-- This one works with any size of hand!
isNSame :: Int -> [Rank] -> Maybe (Rank,[Rank])
isNSame n r
| not $ null ps = Just (head $ head ps, sort $ drop n $ head ps)
| otherwise = Nothing
where
ps = filter (isU . (take n)) $ rotations r
isPair :: [Rank] -> Maybe (Rank,[Rank])
isPair r = isNSame 2 r
isTwoPairs :: [Rank] -> Maybe ([Rank], [Rank])
isTwoPairs r
| and [ isJust p1, isJust p2 ] = Just ([fst $ fromJust p1, fst $ fromJust p2], snd $ fromJust p2)
| otherwise = Nothing
where
p1 = isPair r
p2 = isPair (snd $ fromJust p1)
isThreeOfAKind :: [Rank] -> Maybe (Rank,[Rank])
isThreeOfAKind r = isNSame 3 r
isStraight :: [Rank] -> Maybe Rank
isStraight r
| r == [head r .. last r] = Just $ head r
| otherwise = Nothing
isFlush :: [Suit] -> Maybe Suit
isFlush s
| (isU s) = Just (head s)
| otherwise = Nothing
isFullHouse :: [Rank] -> Maybe (Rank,Rank)
isFullHouse r
| and [ isJust tk, isJust $ isPair r' ] = Just (r1, r'!!0)
| otherwise = Nothing
where
tk = isThreeOfAKind r
(r1,r') = fromJust tk
isFourOfAKind :: [Rank] -> Maybe (Rank, [Rank])
isFourOfAKind r = isNSame 4 r
isStraightFlush :: Hand -> Maybe Rank
isStraightFlush h
| and [isJust $ isStraight r, isJust $ isFlush s] = Just $ head r
| otherwise = Nothing
where
r = map rank h
s = map suit h
isRoyal :: [Rank] -> Bool
isRoyal r = r == [Ten, Jack, Queen, King, Ace]
isRoyalFlush :: Hand -> Maybe Suit
isRoyalFlush h
| and [isJust $ isFlush s, isRoyal r] = Just $ suit $ head h
| otherwise = Nothing
where
r = map rank h
s = map suit h
main :: IO ()
main = interact $ show . euler54 . lines
| D4r1/project-euler | Euler/E54.hs | mit | 5,208 | 14 | 12 | 1,225 | 2,662 | 1,386 | 1,276 | 149 | 1 |
{-# LANGUAGE MagicHash, UnboxedTuples, Rank2Types, BangPatterns, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-full-laziness -fno-warn-name-shadowing #-}
module Data.TrieVector.ArrayArray (
A.run
, A.sizeof
, A.thaw
, A.unsafeThaw
, A.write
, ptrEq
, update
, modify
, noCopyModify
, index
, new
, newM
, init1
, init2
, foldr
, map
, mapInitLast
, foldl'
, rfoldl'
, rfoldr
, read
, AArray
, MAArray
) where
import Prelude hiding (foldr, read, map)
import GHC.Prim
import qualified Data.TrieVector.ArrayPrimWrap as A
type AArray = A.Array Any
type MAArray s = A.MArray s Any
-- ThawArray should be preferably given a statically known length parameter,
-- hence the length param in every function that calls it.
update :: Int# -> AArray -> Int# -> AArray -> AArray
update size arr i a = A.run $ \s ->
case A.thaw arr 0# size s of
(# s, marr #) -> case write marr i a s of
s -> A.unsafeFreeze marr s
{-# INLINE update #-}
ptrEq :: AArray -> AArray -> Int#
ptrEq a b = reallyUnsafePtrEquality#
(unsafeCoerce# a :: Any) (unsafeCoerce# b :: Any)
{-# INLINE ptrEq #-}
modify :: Int# -> AArray -> Int# -> (AArray -> AArray) -> AArray
modify size arr i f = A.run $ \s ->
case A.thaw arr 0# size s of
(# s, marr #) -> case read marr i s of
(# s, a #) -> case write marr i (f a) s of
s -> A.unsafeFreeze marr s
{-# INLINE modify #-}
noCopyModify :: Int# -> AArray -> Int# -> (AArray -> AArray) -> AArray
noCopyModify size arr i f = let
a = index arr i
a' = f a
in case reallyUnsafePtrEquality# (unsafeCoerce# a :: Any) (unsafeCoerce# a' :: Any) of
1# -> arr
_ -> update size arr i a'
{-# INLINE noCopyModify #-}
map :: Int# -> (AArray -> AArray) -> AArray -> AArray
map size f = \arr ->
let go :: Int# -> MAArray s -> Int# -> State# s -> State# s
go i marr size s = case i <# size of
1# -> case write marr i (f (index arr i)) s of
s -> go (i +# 1#) marr size s
_ -> s
in A.run $ \s ->
case newM size arr s of
(# s, marr #) -> case go 0# marr size s of
s -> A.unsafeFreeze marr s
{-# INLINE map #-}
mapInitLast :: Int# -> (AArray -> AArray) -> (AArray -> AArray) -> AArray -> AArray
mapInitLast lasti f g = \arr ->
let go :: Int# -> MAArray s -> Int# -> State# s -> State# s
go i marr lasti s = case i <# lasti of
1# -> case write marr i (f (index arr i)) s of
s -> go (i +# 1#) marr lasti s
_ -> write marr lasti (g (index arr lasti)) s
in A.run $ \s ->
case newM (lasti +# 1#) arr s of
(# s, marr #) -> case go 0# marr lasti s of
s -> A.unsafeFreeze marr s
{-# INLINE mapInitLast #-}
foldr :: Int# -> (AArray -> b -> b) -> b -> AArray -> b
foldr size f = \z arr -> go 0# size z arr where
go i s z arr = case i <# s of
1# -> f (index arr i) (go (i +# 1#) s z arr)
_ -> z
{-# INLINE foldr #-}
rfoldr :: Int# -> (AArray -> b -> b) -> b -> AArray -> b
rfoldr size f = \z arr -> go (size -# 1#) z arr where
go i z arr = case i >=# 0# of
1# -> f (index arr i) (go (i -# 1#) z arr)
_ -> z
{-# INLINE rfoldr #-}
foldl' :: Int# -> (b -> AArray -> b) -> b -> AArray -> b
foldl' size f = \z arr -> go 0# size z arr where
go i s !z arr = case i <# s of
1# -> go (i +# 1#) s (f z (index arr i)) arr
_ -> z
{-# INLINE foldl' #-}
rfoldl' :: Int# -> (b -> AArray -> b) -> b -> AArray -> b
rfoldl' size f = \z arr -> go (size -# 1#) z arr where
go i !z arr = case i >=# 0# of
1# -> go (i -# 1#) (f z (index arr i)) arr
_ -> z
{-# INLINE rfoldl' #-}
index :: AArray -> Int# -> AArray
index arr i = case A.index arr i of
(# a #) -> unsafeCoerce# a
{-# INLINE index #-}
read :: MAArray s -> Int# -> State# s -> (# State# s, AArray #)
read marr i s = unsafeCoerce# (A.read marr i s)
{-# INLINE read #-}
write :: MAArray s -> Int# -> AArray -> State# s -> State# s
write marr i a s = A.write marr i (unsafeCoerce# a) s
{-# INLINE write #-}
new :: Int# -> a -> AArray
new size def = A.run $ \s ->
case A.new size def s of
(# s, marr #) -> A.unsafeFreeze (unsafeCoerce# marr) s
{-# INLINE new #-}
newM :: Int# -> AArray -> State# s -> (# State# s, MAArray s #)
newM size def s = A.new size (unsafeCoerce# def) s
{-# INLINE newM #-}
-- | Create a new array with a given element in the front and the rest filled with a default element.
-- Here we allow an "a" default parameter mainly for error-throwing undefined elements.
init1 :: Int# -> AArray -> AArray -> AArray
init1 size arr def = A.run $ \s ->
case newM size (unsafeCoerce# def) s of
(# s, marr #) -> case write marr 0# arr s of
s -> A.unsafeFreeze marr s
{-# INLINE init1 #-}
-- | Create a new array with a two given elements in the front and the rest filled with a default element.
-- Here we allow an "a" default parameter mainly for error-throwing undefined elements.
init2 :: Int# -> AArray -> AArray -> AArray -> AArray
init2 size a1 a2 def = A.run $ \s ->
case newM size (unsafeCoerce# def) s of
(# s, marr #) -> case write marr 0# a1 s of
s -> case write marr 1# a2 s of
s -> A.unsafeFreeze marr s
{-# INLINE init2 #-}
| AndrasKovacs/trie-vector | Data/TrieVector/ArrayArray.hs | mit | 5,418 | 0 | 18 | 1,635 | 2,049 | 1,056 | 993 | 135 | 2 |
{-# LANGUAGE TupleSections #-}
module Data.Tuple.Extra where
import Data.Tuple (uncurry)
import Data.Functor
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 f (x,y,z) = f x y z
uncurry4 :: (a -> b -> c -> d -> e) -> (a, b, c, d) -> e
uncurry4 f (w,x,y,z) = f w x y z
uncurry5 :: (a -> b -> c -> d -> e -> f) -> (a, b, c, d, e) -> f
uncurry5 f (v, w,x,y,z) = f v w x y z
uncurry6 :: (a -> b -> c -> d -> e -> f -> g) -> (a, b, c, d, e, f) -> g
uncurry6 f (u,v,w,x,y,z) = f u v w x y z
sequenceFst :: (Functor f) => (f a, b) -> f (a, b)
sequenceFst (a,b) = fmap (,b) a
sequenceSnd :: (Functor f) => (a, f b) -> f (a, b)
sequenceSnd (a,b) = fmap (a,) b
uncurryProduct :: (a -> b -> c) -> (a, b) -> c
uncurryProduct = uncurry
uncurryProduct3 :: (a -> b -> c -> d) -> (a, (b, c)) -> d
uncurryProduct3 f (x,(y,z)) = f x y z
uncurryProduct4 :: (a -> b -> c -> d -> e) -> (a, (b, (c, d))) -> e
uncurryProduct4 f (w,(x,(y,z))) = f w x y z
uncurryProduct5 :: (a -> b -> c -> d -> e -> f) -> (a, (b, (c, (d, e)))) -> f
uncurryProduct5 f (v,(w,(x,(y,z)))) = f v w x y z
uncurryProduct6 :: (a -> b -> c -> d -> e -> f -> g) -> (a, (b, (c, (d, (e, f))))) -> g
uncurryProduct6 f (u,(v,(w,(x,(y,z))))) = f u v w x y z
| circuithub/circuithub-prelude | Data/Tuple/Extra.hs | mit | 1,223 | 0 | 12 | 307 | 884 | 505 | 379 | 26 | 1 |
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
module YesodCoreTest.CleanPath (cleanPathTest, Widget) where
import Test.Hspec
import Yesod.Core hiding (Request)
import Network.Wai
import Network.Wai.Test
import Network.HTTP.Types (status200, decodePathSegments)
import qualified Data.ByteString.Lazy.Char8 as L8
import qualified Data.Text as TS
import qualified Data.Text.Encoding as TE
import Control.Arrow ((***))
import Network.HTTP.Types (encodePath)
import Data.Monoid (mappend)
import Blaze.ByteString.Builder.Char.Utf8 (fromText)
data Subsite = Subsite
getSubsite :: a -> Subsite
getSubsite = const Subsite
instance RenderRoute Subsite where
data Route Subsite = SubsiteRoute [TS.Text]
deriving (Eq, Show, Read)
renderRoute (SubsiteRoute x) = (x, [])
instance YesodDispatch Subsite master where
yesodDispatch _ _ _ _ _ _ _ pieces _ _ = return $ responseLBS
status200
[ ("Content-Type", "SUBSITE")
] $ L8.pack $ show pieces
data Y = Y
mkYesod "Y" [parseRoutes|
/foo FooR GET
/foo/#String FooStringR GET
/bar BarR GET
/subsite SubsiteR Subsite getSubsite
/plain PlainR GET
|]
instance Yesod Y where
approot = ApprootStatic "http://test"
cleanPath _ s@("subsite":_) = Right s
cleanPath _ ["bar", ""] = Right ["bar"]
cleanPath _ ["bar"] = Left ["bar", ""]
cleanPath _ s =
if corrected == s
then Right s
else Left corrected
where
corrected = filter (not . TS.null) s
joinPath Y ar pieces' qs' =
fromText ar `mappend` encodePath pieces qs
where
pieces = if null pieces' then [""] else pieces'
qs = map (TE.encodeUtf8 *** go) qs'
go "" = Nothing
go x = Just $ TE.encodeUtf8 x
getFooR :: Handler RepPlain
getFooR = return $ RepPlain "foo"
getFooStringR :: String -> Handler RepPlain
getFooStringR = return . RepPlain . toContent
getBarR, getPlainR :: Handler RepPlain
getBarR = return $ RepPlain "bar"
getPlainR = return $ RepPlain "plain"
cleanPathTest :: Spec
cleanPathTest =
describe "Test.CleanPath" $ do
it "remove trailing slash" removeTrailingSlash
it "noTrailingSlash" noTrailingSlash
it "add trailing slash" addTrailingSlash
it "has trailing slash" hasTrailingSlash
it "/foo/something" fooSomething
it "subsite dispatch" subsiteDispatch
it "redirect with query string" redQueryString
runner :: Session () -> IO ()
runner f = toWaiApp Y >>= runSession f
removeTrailingSlash :: IO ()
removeTrailingSlash = runner $ do
res <- request defaultRequest
{ pathInfo = decodePathSegments "/foo/"
}
assertStatus 301 res
assertHeader "Location" "http://test/foo" res
noTrailingSlash :: IO ()
noTrailingSlash = runner $ do
res <- request defaultRequest
{ pathInfo = decodePathSegments "/foo"
}
assertStatus 200 res
assertContentType "text/plain; charset=utf-8" res
assertBody "foo" res
addTrailingSlash :: IO ()
addTrailingSlash = runner $ do
res <- request defaultRequest
{ pathInfo = decodePathSegments "/bar"
}
assertStatus 301 res
assertHeader "Location" "http://test/bar/" res
hasTrailingSlash :: IO ()
hasTrailingSlash = runner $ do
res <- request defaultRequest
{ pathInfo = decodePathSegments "/bar/"
}
assertStatus 200 res
assertContentType "text/plain; charset=utf-8" res
assertBody "bar" res
fooSomething :: IO ()
fooSomething = runner $ do
res <- request defaultRequest
{ pathInfo = decodePathSegments "/foo/something"
}
assertStatus 200 res
assertContentType "text/plain; charset=utf-8" res
assertBody "something" res
subsiteDispatch :: IO ()
subsiteDispatch = runner $ do
res <- request defaultRequest
{ pathInfo = decodePathSegments "/subsite/1/2/3/"
}
assertStatus 200 res
assertContentType "SUBSITE" res
assertBody "[\"1\",\"2\",\"3\",\"\"]" res
redQueryString :: IO ()
redQueryString = runner $ do
res <- request defaultRequest
{ pathInfo = decodePathSegments "/plain/"
, rawQueryString = "?foo=bar"
}
assertStatus 301 res
assertHeader "Location" "http://test/plain?foo=bar" res
| piyush-kurur/yesod | yesod-core/test/YesodCoreTest/CleanPath.hs | mit | 4,465 | 0 | 12 | 1,097 | 1,154 | 586 | 568 | 112 | 1 |
module Main where
import qualified Labyrinth.Helpers
import qualified Labyrinth.Models
import qualified Labyrinth.Game
import qualified Labyrinth.Factory
import qualified Labyrinth.Board
import qualified Labyrinth.Parser
import qualified Data.List
import qualified System.Random
import qualified System.Environment
createNewGame :: IO Labyrinth.Models.Game
createNewGame = do
putStrLn "Hello and welcome to Labyrinth! How many players will be playing today?"
numberOfPlayersAsString <- getLine
let numberOfPlayers = read numberOfPlayersAsString :: Int
generator <- System.Random.getStdGen
return $ Labyrinth.Factory.createNewGame numberOfPlayers generator
openExistingGame :: String -> IO Labyrinth.Models.Game
openExistingGame gameFileName = do
gameFileContents <- readFile gameFileName
let game = (fst . head) $ Labyrinth.Parser.apply Labyrinth.Parser.labyrinth gameFileContents
return game
startGame :: Labyrinth.Models.Game -> IO()
startGame game = do
Labyrinth.Game.takeTurn game
return ()
main :: IO ()
main = do
args <- System.Environment.getArgs
case args of
[] -> createNewGame >>= startGame
[file] -> openExistingGame file >>= startGame
_ -> putStrLn "Wrong number of arguments. Pass in zero arguments to start a new game, or pass in a file name to resume an existing game."
| amoerie/labyrinth | Main.hs | mit | 1,335 | 0 | 12 | 208 | 308 | 160 | 148 | 33 | 3 |
module Y2016.M12.D26.Exercise where
import Data.Array
import Data.Map (Map)
-- below imports available via 1HaskellADay git repository
import Data.SAIPE.USCounties
import Graph.KMeans
import Graph.ScoreCard
import Graph.ScoreCard.Clusters
import Y2016.M12.D15.Exercise
import Y2016.M12.D21.Exercise
{--
Good morning, all. Happy Boxing Day!
So, last week we clustered SAIPE/poverty data for Counties of the US, and saw
some interesting things that we'll explore later this week, and associate back
to US States. But that later.
The K-means algorithm is a good classifier, no doubt; I mean, it's way better
than going through a spreadsheet, row-by-row...
... and guess how most companies look at their data-sets?
Yup, in a spreadsheet, row-by-row.
But K-means is not the only way to look at a data-set, by no means. It's a
good one, but not the only one, and issues with k-means, particularly the time-
cost of classification as the data-sets get larger, as you saw when you
classified the SAIPE-data. That took a bit of time to do.
So, other forms of classification? What are your recommendations, Haskellers?
Tweet me and we can look at those.
For today, we're going to do an eh-classification. That is to say, we're going
to use the old eyeballs or our seats-of-the-pants method of classification to
divvy up these data into one of five categories:
--}
data Size = Tiny | Small | Medium | Large | YUGE
deriving (Eq, Ord, Enum, Bounded, Ix, Show, Read)
{--
Today's Haskell problem: take the data at
Y2016/M12/D15/SAIPESNC_15DEC16_11_35_13_00.csv.gz
read it in, and, using a classification method of your choice, partition
these data in to the groups of your choosing. How do divvy up these data?
Well, you have population, you have poverty, and you have the ratio of the
two, don't you? So, you choose which attribute you use to partition the data.
--}
partitionSAIPEBySize :: SAIPEData -> Map Size SAIPERow
partitionSAIPEBySize saipe = undefined
{--
There is a more general activity you are doing here, however, and that is,
you are partitioning any kind of data by some measure of their size. We do
have a container-type for 'any kind of measured data,' and that is the
ScoreCard.
Partition the ScoreCards of SAIPE data by size. I mean USE the SAIPE data set
but, more generally, partition ANY ScoreCard-type by Size:
--}
partitionBySize :: RealFrac c => [ScoreCard a b c] -> Map Size [ScoreCard a b c]
partitionBySize scorecards = undefined
{-- BONUS -----------------------------------------------------------------
Display your partitioned-by-size data-set using the charting tool of your
choice
--}
drawSizedPartitions :: (Show a, Show b, Show c) => Map Size [ScoreCard a b c] -> IO ()
drawSizedPartitions partitions = undefined
{-- HINT ------------------------------------------------------------------
You can use the Clusters-type, you know. kmeans doesn't own that type, and
each cluster is identified by its corresponding Size-value. If you reorganize
the Map Size [ScoreCard a b c] as Graph.KMeans.Clusters value with a little
Map.map-magic, then the resulting value draws itself, as you saw from the
solution from the Y2016.M12.D23 solution.
--}
{-- BONUS-BONUS -----------------------------------------------------------
Now that we have size information in the graphed data set, re-lable each of
the Cell nodes with Size information, so that, e.g.: small nodes show visually
as small and YUGE nodes show as YUGE!
YUGE, adj.: means YUGE, ICYMI
--}
relableNodesBySize :: (Show a, Show b, Show c) => Map Size [ScoreCard a b c] -> IO ()
relableNodesBySize sizeddata = undefined
{-- MOTIVATION ------------------------------------------------------------
This relable function comes from me asking the Neo Tech folks how I could
programatically resize nodes from their attributed data. I didn't get a
satisifactory answer. Is this, here a satifactory way programatically to
resize data nodes? We shall see, shan't we!
--}
| geophf/1HaskellADay | exercises/HAD/Y2016/M12/D26/Exercise.hs | mit | 3,973 | 0 | 9 | 643 | 304 | 168 | 136 | 19 | 1 |
module Main where
import Test.Tasty (defaultMain,testGroup,TestTree)
import AlgorithmsAtHandHaskell.Swallow.Test
import AlgorithmsAtHandHaskell.Coconut.Test
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "All Tests"
[ swallowSuite
, coconutSuite
]
| antonlogvinenko/algorithms-at-hand | algorithms-at-hand-haskell/test/Test.hs | mit | 316 | 0 | 6 | 71 | 71 | 42 | 29 | 10 | 1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
import Diagrams.Prelude
import Diagrams.Backend.SVG.CmdLine
h = hexagon 1 # fc lightgreen
sOrigin = showOrigin' (with & oScale .~ 0.04)
diagram :: Diagram B
diagram = h # snugBL # sOrigin
main = mainWith $ frame 0.1 diagram
| jeffreyrosenbluth/NYC-meetup | meetup/SnugBL.hs | mit | 292 | 0 | 8 | 66 | 83 | 44 | 39 | 8 | 1 |
module Chapter05.Sing where
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
sing :: Ord a => a -> a -> [Char]
sing x y =
if (x > y)
then fstString "Signin"
else sndString "Somewhere"
| brodyberg/LearnHaskell | HaskellProgramming.hsproj/Chapter05/Sing.hs | mit | 300 | 0 | 8 | 87 | 114 | 62 | 52 | 10 | 2 |
module Heuristics where
import Data.Array
import Data.List
import NPuzzle
manhattan :: NPuzzle.Grid -> NPuzzle.Grid -> Int
manhattan end start = sum $ map go (indices start)
where
manhattan' (gx, gy) (cx, cy) = abs (gx - cx) + abs (gy - cy)
go i = manhattan' (end!i) (start!i)
| Shakadak/n-puzzle | Heuristics.hs | mit | 298 | 0 | 10 | 69 | 134 | 72 | 62 | 8 | 1 |
module FileTools (
find,
ls,
cat
) where
import System.Directory
import System.IO.Error
import qualified Data.ByteString.Lazy.Char8 as B
cat :: FilePath -> IO B.ByteString
cat file = catchIOError (B.readFile file) (\e -> return $ B.pack [])
ls :: String -> IO [FilePath]
ls dir = getDirectoryContents dir >>= return . filter (`notElem` [".",".."])
find :: FilePath -> IO [FilePath]
find dir = ls dir
>>= mapM (\x -> return $ dir ++ "/" ++ x)
>>= mapM find'
>>= return . concat
find' :: FilePath -> IO [FilePath]
find' path = do b <- doesDirectoryExist path
if b then find path else return [path]
| ryuichiueda/UspMagazineHaskell | Study1_Q3/FileTools.hs | mit | 653 | 0 | 14 | 160 | 260 | 139 | 121 | 19 | 2 |
module GitStatus where
import GitWorkflow
type GitStatus = (Char, Char, String, Maybe String)
pathStatuses :: IO (Either String [GitStatus])
pathStatuses = do
r <- runGitProcess ["status", "-s"]
case r of
Left err -> return (Left err)
Right ss -> return $Right $map readStatus $lines ss
where readStatus (i:w:xs) = case words xs of
(path:[]) -> (i,w,path,Nothing)
(path1:"->":path2:[]) -> (i,w,path1,Just path2)
statusToString :: GitStatus -> String
statusToString (i,w,p,Nothing) = i:w:' ':p
statusToString (i,w,p1,Just p2) = i:w:' ':(p1 ++ " -> " ++ p2)
pathFromStatus :: GitStatus -> String
pathFromStatus (_,_,p,_) = p
| yamamotoj/alfred-git-workflow | src/GitStatus.hs | mit | 711 | 0 | 14 | 179 | 326 | 176 | 150 | 17 | 3 |
module Lib where
import Data.List as List
import Data.List.Split
import Data.Map.Strict as Map
data BinSize = Small | Large deriving Show
data ShelfDifficulty = Normal | Level3 | Level4 deriving Show
data Bin = Bin { warehouse :: String,
room :: String,
bay :: String,
shelf :: String,
number :: String,
size :: BinSize,
difficulty :: ShelfDifficulty
} deriving Show
type ProductId = String
type Quantity = Int
parseBinSize :: String -> BinSize
parseBinSize "S" = Small
parseBinSize "L" = Large
parseShelfDifficulty :: String -> ShelfDifficulty
parseShelfDifficulty "S01" = Normal
parseShelfDifficulty "S02" = Normal
parseShelfDifficulty "S03" = Level3
parseShelfDifficulty "S04" = Level4
parseBin :: String -> Bin
parseBin binStr =
let [w, r, b, s, n, sz] = splitOn "-" binStr in
Bin w r b s n (parseBinSize sz) (parseShelfDifficulty s)
parseLine :: String -> (ProductId, [(Bin, Quantity)])
parseLine line =
let [b, p, q] = splitOn "\t" line in
(p, [(parseBin b, read q)])
parseFile :: String -> Map.Map ProductId [(Bin, Quantity)]
parseFile f =
Map.fromListWith (++) $ List.map parseLine (lines f)
| NashFP/pick-and-grin | mark_wutka+hakan+kate+haskell/src/Lib.hs | mit | 1,261 | 0 | 10 | 335 | 401 | 228 | 173 | 35 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Utils.NuxmvCode
Description : Utilities for producing nuXmv code
Copyright : (c) Tessa Belder 2015-2016
This module contains useful functions for producing nuXmv code.
-}
module Utils.NuxmvCode where
import Data.List (intersperse)
import Utils.Concatable as C
-- * Declarations
-- | INVAR declaration
nuxmv_invar :: (IsString a, Monoid a) => a -> a
nuxmv_invar = nuxmv_keyword "INVAR"
-- | INVARSPEC declaration
nuxmv_invarspec :: (IsString a, Monoid a) => a -> a
nuxmv_invarspec = nuxmv_keyword "INVARSPEC"
-- | NuXmv keyword declarations
nuxmv_keyword :: (IsString a, Monoid a) => a -> a -> a
nuxmv_keyword keyword assignment = C.unwords[keyword,assignment]
-- | CONSTANTS declaration
nuxmv_constants :: (IsString a, Monoid a) => [a] -> a
nuxmv_constants consts = "CONSTANTS " <> C.intercalate ", " consts <> ";"
-- | NuXmv variable types
data NuxmvVariableType =
Input -- ^ Input variable (IVAR)
| State -- ^ State variable (VAR)
| Frozen -- ^ Frozen variable (FROZENVAR)
-- | Boolean variable declaration
nuxmv_bool :: (IsString a, Monoid a) => NuxmvVariableType -> a -> a
nuxmv_bool varType = nuxmv_var varType bool_type
-- | Integer variable declaration
nuxmv_int :: (IsString a, Monoid a) => NuxmvVariableType -> Int -> a -> a
nuxmv_int varType n = nuxmv_var varType (int_type n)
-- | Enumeration declaration
nuxmv_enum :: (IsString a, Monoid a) => NuxmvVariableType -> [a] -> a -> a
nuxmv_enum varType vals = nuxmv_var varType (enum_type vals)
-- | Array declaration
nuxmv_array :: (IsString a, Monoid a) => NuxmvVariableType -> a -> a -> a -> a
nuxmv_array varType t t' name = nuxmv_var varType (array_type t t') name
-- | NuXmv keyword for nuXmv variable types
nuxmv_var :: (IsString a, Monoid a) => NuxmvVariableType -> a -> a -> a
nuxmv_var State = nuxmv_declaration "VAR"
nuxmv_var Input = nuxmv_declaration "IVAR"
nuxmv_var Frozen = nuxmv_declaration "FROZENVAR"
-- | General nuXmv declaration
nuxmv_declaration :: (IsString a, Monoid a) => a -> a -> a -> a
nuxmv_declaration keyword t name = nuxmv_keyword keyword $ name <> ": " <> t <> ";"
-- * Types
-- | NuXmv boolean type
bool_type :: IsString a => a
bool_type = "boolean"
-- | nuXmv integer type
int_type :: (IsString a, Monoid a) => Int -> a
int_type n = range_type 0 (n-1)
-- | nuXmv range type
range_type :: (IsString a, Monoid a) => Int -> Int -> a
range_type n m = C.show n <> ".." <> C.show m
-- | nuXmv enumeration type
enum_type :: (IsString a, Monoid a) => [a] -> a
enum_type [] = "{no_values}" -- empty enumerations are not allowed
enum_type vals = "{" <> C.intercalate ", " vals <> "}"
-- | nuXmv array type
array_type :: (IsString a, Monoid a) => a -> a -> a
array_type t t' = "array " <> t <> " of " <> t'
-- | Position in an array
nuxmv_array_pos :: (IsString a, Monoid a) => a -> Int -> a
nuxmv_array_pos arr pos = arr <> "[" <> (C.show pos) <> "]"
-- * Constants
-- | True
nuxmv_true :: IsString a => a
nuxmv_true = "TRUE"
-- | False
nuxmv_false :: IsString a => a
nuxmv_false = "FALSE"
-- * Operators
-- ** Unary operators
-- | Boolean negation
nuxmv_negate :: (IsString a, Monoid a) => a -> a
nuxmv_negate = nuxmv_un_operator "!"
-- | General unary operator
nuxmv_un_operator :: (IsString a, Monoid a) => a -> a -> a
nuxmv_un_operator op arg = "(" <> op <> arg <> ")"
-- ** Binary operators
-- | Equality operator
nuxmv_equals :: (IsString a, Monoid a) => a -> a -> a
nuxmv_equals = nuxmv_bin_operator "="
-- | Inequality operator
nuxmv_unequal :: (IsString a, Monoid a) => a -> a -> a
nuxmv_unequal = nuxmv_bin_operator "!="
-- | At most operator
nuxmv_atmost :: (IsString a, Monoid a) => a -> a -> a
nuxmv_atmost = nuxmv_bin_operator "<="
-- | Greater than operator
nuxmv_gt :: (IsString a, Monoid a) => a -> a -> a
nuxmv_gt = nuxmv_bin_operator ">"
-- | Set inclusion ("in") operator
nuxmv_in :: (IsString a, Monoid a) => a -> a -> a
nuxmv_in = nuxmv_bin_operator "in"
-- | Addition
nuxmv_add_bin :: (IsString a, Monoid a) => a -> a -> a
nuxmv_add_bin x y = nuxmv_add [x, y]
-- | Multiplication
nuxmv_mult_bin :: (IsString a, Monoid a) => a -> a -> a
nuxmv_mult_bin x y = nuxmv_mult [x, y]
-- | Subtraction
nuxmv_minus :: (IsString a, Monoid a) => a -> a -> a
nuxmv_minus = nuxmv_bin_operator "-"
-- | Modulo
nuxmv_mod :: (IsString a, Monoid a) => a -> a -> a
nuxmv_mod = nuxmv_bin_operator "mod"
-- | Disjunction
nuxmv_or_bin :: (IsString a, Monoid a) => a -> a -> a
nuxmv_or_bin x y = nuxmv_or [x, y]
-- | Conjunction
nuxmv_and_bin :: (IsString a, Monoid a) => a -> a -> a
nuxmv_and_bin x y = nuxmv_and [x, y]
-- | General binary operator
nuxmv_bin_operator :: (IsString a, Monoid a) => a -> a -> a -> a
nuxmv_bin_operator op arg1 arg2 = "(" <> C.unwords [arg1, op, arg2] <> ")"
-- ** Tertiary operators
-- | In range operator (at least "low" and at most "high")
nuxmv_inrange :: (IsString a, Monoid a) => a -> (Int, Int) -> a
nuxmv_inrange val (l, h) = nuxmv_and[nuxmv_atmost (C.show l) val, nuxmv_atmost val (C.show h)]
-- ** N-ary operators
-- | Addition
nuxmv_add :: (IsString a, Monoid a) => [a] -> a
nuxmv_add = nuxmv_n_operator "+"
-- | Multiplication
nuxmv_mult :: (IsString a, Monoid a) => [a] -> a
nuxmv_mult = nuxmv_n_operator "*"
-- | Disjunction
nuxmv_or :: (IsString a, Monoid a) => [a] -> a
nuxmv_or = nuxmv_n_operator "|"
-- | Conjunction
nuxmv_and :: (IsString a, Monoid a) => [a] -> a
nuxmv_and = nuxmv_n_operator "&"
-- | General n-ary operator
nuxmv_n_operator :: (IsString a, Monoid a) => a -> [a] -> a
nuxmv_n_operator _ [] = ""
nuxmv_n_operator _ [x] = x
nuxmv_n_operator op xs = "(" <> C.unwords (intersperse op xs) <> ")"
-- * Functions
-- | Cast to integer
nuxmv_toint :: (IsString a, Monoid a) => a -> a
nuxmv_toint = nuxmv_function "toint" . (:[])
-- | Count function
nuxmv_count :: (IsString a, Monoid a) => [a] -> a
nuxmv_count = nuxmv_function "count"
-- | General function application
nuxmv_function :: (IsString a, Monoid a) => a -> [a] -> a
nuxmv_function fun args = fun <> "(" <> C.intercalate ", " args <> ")"
-- * Assignments
-- | Init assignment
nuxmv_init :: (IsString a, Monoid a) => a -> a -> a
nuxmv_init var = head . nuxmv_assignment (nuxmv_function "init" [var]) . (:[])
-- | Next assignment
nuxmv_next :: (IsString a, Monoid a) => a -> [a] -> [a]
nuxmv_next var = nuxmv_assignment $ nuxmv_function "next" [var]
-- | General assignment
nuxmv_assignment :: (IsString a, Monoid a) => a -> [a] -> [a]
nuxmv_assignment _ [] = fatal (513::Int) "Empty assignment not allowed" where
fatal i s = error ("Fatal " ++ Prelude.show i ++ " in " ++ fileName ++ ":\n " ++ s)
fileName = "Utils.NuxmvCode"
nuxmv_assignment name [assignment] = [name <> " := " <> assignment <> ";"]
nuxmv_assignment name (asg:asgs) = [name <> " := " <> asg] ++ init asgs ++ [last asgs <> ";"]
-- * Case distinction
-- | Switch statement
nuxmv_switch :: (IsString a, Monoid a) => [(a, a)] -> [a]
nuxmv_switch cases = ["case"] ++ nuxmv_indent (map (uncurry nuxmv_case) cases) ++ ["esac"] where
-- | A single switch case
nuxmv_case :: (IsString a, Monoid a) => a -> a -> a
nuxmv_case ifval thenval = ifval <> ": " <> thenval <> ";"
-- | If-then-else statement
nuxmv_ite :: (IsString a, Monoid a) => a -> a -> a -> a
nuxmv_ite ifval thenval elseval = "(" <> C.unwords[ifval, "?", thenval, ":", elseval] <> ")"
-- * File generation
-- | "MODULE" block
nuxmv_module :: (IsString a, Monoid a) => a -> [a] -> [a]
nuxmv_module name = nuxmv_file_block (C.unwords["MODULE",name])
-- | "ASSIGN" block
nuxmv_assign :: (IsString a, Monoid a) => [a] -> [a]
nuxmv_assign = nuxmv_file_block "ASSIGN"
-- | General block
nuxmv_file_block :: (IsString a, Monoid a) => a -> [a] -> [a]
nuxmv_file_block header contents = if null contents then [] else header:(nuxmv_indent contents)
-- | Indent 2 spaces
nuxmv_indent :: (IsString a, Monoid a) => [a] -> [a]
nuxmv_indent = map (" " <>) | julienschmaltz/madl | src/Utils/NuxmvCode.hs | mit | 7,873 | 0 | 15 | 1,455 | 2,672 | 1,446 | 1,226 | 119 | 2 |
module Network.Mosquitto (
-- * Data structure
Mosquitto
, Event(..)
-- * Mosquitto
, initializeMosquittoLib
, cleanupMosquittoLib
, newMosquitto
, destroyMosquitto
, setWill
, clearWill
, connect
, disconnect
, getNextEvents
, subscribe
, publish
-- * Helper
, withInit
, withMosquitto
, withConnect
-- * Utility
, strerror
) where
import Network.Mosquitto.C.Interface
import Network.Mosquitto.C.Types
import Control.Monad
import Control.Monad.IO.Class
import Data.IORef
import qualified Data.ByteString as BS
import Data.ByteString.Internal(toForeignPtr)
import Control.Exception(bracket, bracket_, throwIO, AssertionFailed(..))
import Foreign.Ptr(Ptr, FunPtr, nullPtr, plusPtr, castFunPtr, freeHaskellFunPtr)
import Foreign.ForeignPtr(withForeignPtr)
import Foreign.Storable(peek)
import Foreign.C.String(withCString, peekCString)
import Foreign.C.Types(CInt(..))
import Foreign.Marshal.Array(peekArray)
import Foreign.Marshal.Utils(fromBool)
import Foreign.Marshal.Alloc(malloc, free)
data Mosquitto = Mosquitto
{ mosquittoObject :: !Mosq
, mosquittoEvents :: IORef [Event]
, mosquittoCallbacks :: ![FunPtr ()]
}
data Event = Message
{ messageID :: !Int
, messageTopic :: !String
, messagePayload :: !BS.ByteString
, messageQos :: !Int
, messageRetain :: !Bool
}
| ConnectResult
{ connectResultCode :: !Int
, connectResultString :: !String
}
| DisconnectResult
{ disconnectResultCode :: !Int
, disconnectResultString :: !String
}
| Published { messageID :: !Int }
deriving Show
initializeMosquittoLib :: IO ()
initializeMosquittoLib = do
result <- c_mosquitto_lib_init
when (result /= 0) $ do
msg <- strerror $ fromIntegral result
throwIO $ AssertionFailed $ "initializeMosquitto: " ++ msg
cleanupMosquittoLib :: IO ()
cleanupMosquittoLib = do
result <- c_mosquitto_lib_cleanup
when (result /= 0) $ do
msg <- strerror $ fromIntegral result
throwIO $ AssertionFailed $ "cleanupMosquittoLib: " ++ msg
newMosquitto :: Maybe String -> IO Mosquitto
newMosquitto Nothing = c_mosquitto_new nullPtr 1 nullPtr >>= newMosquitto'
newMosquitto (Just s) = (withCString s $ \sC ->
c_mosquitto_new sC 1 nullPtr) >>= newMosquitto'
newMosquitto' :: Mosq -> IO Mosquitto
newMosquitto' mosq = if mosq == nullPtr
then throwIO $ AssertionFailed "invalid mosq object"
else do
events <- newIORef ([] :: [Event])
connectCallbackC <- wrapOnConnectCallback (connectCallback events)
c_mosquitto_connect_callback_set mosq connectCallbackC
messageCallbackC <- wrapOnMessageCallback (messageCallback events)
c_mosquitto_message_callback_set mosq messageCallbackC
disconnectCallbackC <- wrapOnDisconnectCallback (disconnectCallback events)
c_mosquitto_disconnect_callback_set mosq disconnectCallbackC
publishCallbackC <- wrapOnPublishCallback (publishCallback events)
c_mosquitto_publish_callback_set mosq publishCallbackC
return Mosquitto { mosquittoObject = mosq
, mosquittoEvents = events
, mosquittoCallbacks = [ castFunPtr connectCallbackC
, castFunPtr messageCallbackC
, castFunPtr disconnectCallbackC
, castFunPtr publishCallbackC
]
}
where
connectCallback :: IORef [Event] -> Mosq -> Ptr () -> CInt -> IO ()
connectCallback events _mosq _ result = do
let code = fromIntegral result
str <- strerror code
pushEvent events $ ConnectResult code str
messageCallback :: IORef [Event] -> Mosq -> Ptr () -> Ptr MessageC -> IO ()
messageCallback events _mosq _ messageC = do
msg <- peek messageC
topic <- peekCString (messageCTopic msg)
payload <- peekArray (fromIntegral $ messageCPayloadLen msg) (messageCPayload msg)
pushEvent events $ Message (fromIntegral $ messageCID msg)
topic
(BS.pack payload)
(fromIntegral $ messageCQos msg)
(messageCRetain msg)
disconnectCallback :: IORef [Event] -> Mosq -> Ptr () -> CInt -> IO ()
disconnectCallback events _mosq _ result = do
let code = fromIntegral result
str <- strerror code
pushEvent events $ DisconnectResult code str
publishCallback :: IORef [Event] -> Mosq -> Ptr () -> CInt -> IO ()
publishCallback events _mosq _ mid = do
pushEvent events $ Published (fromIntegral mid)
pushEvent :: IORef [Event] -> Event -> IO ()
pushEvent ref e = do
es <- readIORef ref
writeIORef ref (e:es)
destroyMosquitto :: Mosquitto -> IO ()
destroyMosquitto mosquitto = do
mapM_ freeHaskellFunPtr (mosquittoCallbacks mosquitto)
writeIORef (mosquittoEvents mosquitto) []
c_mosquitto_destroy (mosquittoObject mosquitto)
setWill :: Mosquitto -> String -> BS.ByteString -> Int -> Bool -> IO Int
setWill mosquitto topicName payload qos retain = do
let (payloadFP, off, _len) = toForeignPtr payload
fmap fromIntegral $ withCString topicName $ \topicNameC ->
withForeignPtr payloadFP $ \payloadP -> do
c_mosquitto_will_set (mosquittoObject mosquitto)
topicNameC
(fromIntegral (BS.length payload))
(payloadP `plusPtr` off)
(fromIntegral qos)
(fromBool retain)
clearWill :: Mosquitto -> IO Int
clearWill mosquitto = c_mosquitto_will_clear (mosquittoObject mosquitto) >>= return . fromIntegral
connect :: Mosquitto -> String -> Int -> Int -> IO Int
connect mosquitto hostname port keepAlive =
fmap fromIntegral . withCString hostname $ \hostnameC ->
c_mosquitto_connect (mosquittoObject mosquitto) hostnameC (fromIntegral port) (fromIntegral keepAlive)
disconnect :: Mosquitto -> IO Int
disconnect mosquitto =
fmap fromIntegral . c_mosquitto_disconnect $ mosquittoObject mosquitto
getNextEvents :: Mosquitto -> Int -> IO (Int, [Event])
getNextEvents mosquitto timeout = do
result <- fmap fromIntegral . liftIO $ c_mosquitto_loop (mosquittoObject mosquitto) (fromIntegral timeout) 1
if result == 0
then do events <- liftIO . fmap reverse $ readIORef (mosquittoEvents mosquitto)
writeIORef (mosquittoEvents mosquitto) []
return (result, events)
else return (result, [])
subscribe :: Mosquitto -> String -> Int -> IO Int
subscribe mosquitto topicName qos = do
fmap fromIntegral . withCString topicName $ \topicNameC ->
c_mosquitto_subscribe (mosquittoObject mosquitto) nullPtr topicNameC (fromIntegral qos)
publish :: Mosquitto -> String -> BS.ByteString -> Int -> Bool -> IO (Int, Int)
publish mosquitto topicName payload qos retain = do
midC <- (malloc :: IO (Ptr CInt))
let (payloadFP, off, _len) = toForeignPtr payload
res <- fmap fromIntegral $ withCString topicName $ \topicNameC ->
withForeignPtr payloadFP $ \payloadP ->
c_mosquitto_publish (mosquittoObject mosquitto)
midC
topicNameC
(fromIntegral (BS.length payload))
(payloadP `plusPtr` off)
(fromIntegral qos)
(fromBool retain)
mid <- fromIntegral <$> peek midC
free midC
return (res, mid)
-- Utility
strerror :: Int -> IO String
strerror err = c_mosquitto_strerror (fromIntegral err) >>= peekCString
-- Helper
withInit :: IO a -> IO a
withInit = bracket_ initializeMosquittoLib cleanupMosquittoLib
withMosquitto :: Maybe String -> (Mosquitto -> IO a) -> IO a
withMosquitto clientId = bracket (newMosquitto clientId) destroyMosquitto
withConnect :: Mosquitto -> String -> Int -> Int -> IO a -> IO a
withConnect mosquitto hostname port keepAlive = bracket_ connectI (disconnect mosquitto)
where
connectI :: IO ()
connectI = do
result <- connect mosquitto hostname (fromIntegral port) (fromIntegral keepAlive)
when (result /= 0) $ do
err <- strerror result
throwIO $ AssertionFailed $ "withConnect:" ++ (show result) ++ ": " ++ err
| uwitty/mosquitto | src/Network/Mosquitto.hs | mit | 9,202 | 0 | 18 | 2,966 | 2,371 | 1,194 | 1,177 | 205 | 2 |
-- Get the difference between the sum of squares and the square of sum for the numbers between 1 and 100
main = print getProblem6Value
getProblem6Value :: Integer
getProblem6Value = getSquareOfSumMinusSumOfSquares [1..100]
getSquareOfSumMinusSumOfSquares :: [Integer] -> Integer
getSquareOfSumMinusSumOfSquares nums = (getSquareOfSum nums) - (getSumOfSquares nums)
getSquareOfSum :: [Integer] -> Integer
getSquareOfSum nums = (sum nums) ^ 2
getSumOfSquares :: [Integer] -> Integer
getSumOfSquares nums = sum $ map (^2) nums
| jchitel/ProjectEuler.hs | Problems/Problem0006.hs | mit | 529 | 0 | 7 | 75 | 127 | 68 | 59 | 9 | 1 |
module Data.NameSupply
( NameSupply (..), mkNameSupply, getFreshName
, NS, runNS
, newName, findName, withName
) where
import Common
import Control.Monad.Reader
import Control.Monad.State
import qualified Data.Map as M
import qualified Data.Set as S
newtype NameSupply = NameSupply { getNames :: [Name] }
mkNameSupply :: S.Set Name -> NameSupply
mkNameSupply usedNames = NameSupply freeNames
where mkName suffix = map (:suffix) ['a'..'z']
allNames = concatMap mkName ("":map show [1..])
freeNames = filter (\name -> S.notMember name usedNames) allNames
getFreshName :: NameSupply -> (Name, NameSupply)
getFreshName (NameSupply (name:xs)) = (name, NameSupply xs)
type NS = ReaderT (M.Map Name Name) (State NameSupply)
runNS :: NS a -> NameSupply -> (a, NameSupply)
runNS ns supply = runState (runReaderT ns M.empty) supply
newName :: NS Name
newName = do
(name, supply) <- gets getFreshName
put supply
return name
findName :: Name -> NS Name
findName name = reader (M.findWithDefault name name)
withName :: Name -> Name -> NS a -> NS a
withName name name1 = local (M.insert name name1)
| meimisaki/Rin | src/Data/NameSupply.hs | mit | 1,119 | 0 | 11 | 197 | 421 | 228 | 193 | 29 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
module EC.ES where
import qualified Control.Monad.Primitive as Prim
--import qualified System.Random.MWC as MWC
import System.Random.MWC
import Control.Monad.ST
import Control.Monad
import Control.Monad.State
newtype S s a = S { runS :: StateT (GenST s) (ST s) a }
deriving (Monad, MonadState (GenST s))
--init :: S s ()
--init :: (MonadTrans t, Prim.PrimMonad (ST s), MonadState (GenST s) (t (ST s))) => t (ST s) ()
--init = lift create >>= put
--a :: ST s [Int]
--a = do
-- gen <- create
-- i <- replicateM 10 $ uniform gen
-- return (i :: [Int])
--b = do
-- i <- a
-- j <- a
-- return $ i ++ j | banacorn/evolutionary-computation | EC/es.hs | mit | 705 | 0 | 9 | 151 | 106 | 71 | 35 | 10 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Model.Mongo.Common
where
import Common (loggerName)
import Config (Database)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.Trans.Resource (runResourceT, allocate, release)
import Data.Aeson (FromJSON(..), ToJSON(..), Value(..))
import Data.Aeson.Types (typeMismatch)
import Data.String (IsString(fromString))
import Data.Text (Text)
import Language.Haskell.TH.Syntax (nameBase)
import System.IO.Error (catchIOError, ioeGetErrorString)
import System.Log.Logger (infoM)
import Text.Read (readMaybe)
import qualified Config as C
import qualified Database.MongoDB as M
import qualified Data.Text as T
data Connection = Connection
{ pipe :: M.Pipe
, dbName :: T.Text
}
connect :: Database -> IO Connection
connect dbConf = do
infoM loggerName "Connecting to the database"
catchIOError (do
pipe <- M.connect $ M.Host host $ M.PortNumber $ fromIntegral port
return $ Connection pipe (fromString $ C.dbName dbConf)
) $ \e -> do
fail $ "Can't connect to the database: " ++ (ioeGetErrorString e)
where
host = C.dbHost dbConf
port = C.dbPort dbConf
closeConnection :: Connection -> IO ()
closeConnection (Connection pipe _) = M.close pipe
withDB :: Database -> M.Action IO a -> IO a
withDB dbConf f = runResourceT $ do
(releaseKey, pipe) <- allocate (connect dbConf) closeConnection
v <- lift $ runDB pipe f
release releaseKey
return v
runDB :: MonadIO m => Connection -> M.Action m a -> m a
runDB (Connection p dbName) f = M.access p M.UnconfirmedWrites dbName f
affectedDocs :: MonadIO m => M.Action m Int
affectedDocs = do
le <- M.runCommand ["getLastError" M.=: (M.Int32 1)]
mn <- M.look "n" le
case mn of
(M.Int32 n) -> return $ fromIntegral n
_ -> fail "Mongodb returned non integer n from getLastError commmand"
instance FromJSON M.ObjectId where
parseJSON (String s) = case readMaybe $ T.unpack s of
Just v -> return v
Nothing -> fail $ "Invalid object id - " ++ (T.unpack s)
parseJSON v = typeMismatch (nameBase ''M.ObjectId) v
instance ToJSON M.ObjectId where
toJSON v = String $ T.pack $ show v
duplicateE :: M.ErrorCode
duplicateE = 11000
-- Common fields that are used around
idF = "_id"
idF :: Text
-- Common database commands that are user around.
currentDateC = "$currentDate"
decC = "$dec"
inC = "$in"
incC = "$inc"
matchC = "$match"
neC = "$ne"
projectC = "$project"
pullC = "$pull"
pushC = "$push"
setC = "$set"
unwindC = "$unwind"
currentDateC :: Text
decC :: Text
inC :: Text
incC :: Text
matchC :: Text
neC :: Text
projectC :: Text
pullC :: Text
pushC :: Text
setC :: Text
unwindC :: Text
(+.+) :: Text -> Text -> Text
a +.+ b = a `T.append` "." `T.append` b
(+++) :: Text -> Text -> Text
a +++ b = a `T.append` b
| VictorDenisov/keystone | src/Model/Mongo/Common.hs | gpl-2.0 | 3,131 | 0 | 17 | 767 | 997 | 541 | 456 | 87 | 2 |
{-# LANGUAGE DoAndIfThenElse #-}
-----------------------------------------------------------------------------
--
-- Module : Search.Indexer
-- Copyright : Francisco Soares
-- License : GPL (Just (Version {versionBranch = [2], versionTags = []}))
--
-- Maintainer : Francisco Soares
-- Stability : experimental
-- Portability :
--
-----------------------------------------------------------------------------
module Search.Indexer (
indexFile
) where
import Search.Utils
import System.Directory (getDirectoryContents, doesDirectoryExist)
import Data.Char (isAlphaNum, toLower)
import Data.List (groupBy, sort, isSuffixOf)
import qualified Control.Exception as Exc
import System.FilePath
-- | Front for the indexing
indexFile :: FilePath -> IO [(String, [(String, [Integer])])]
indexFile filename = do
indexed <- indexFile' filename
let x = sort indexed
let x' = groupBy eqFst x
return $! toMap2 x'
-- | Performs the actual indexing, organizing how subdirectories are recursively processed
-- and how text files are interpreted and indexed, all based on a root FilePath.
indexFile' :: FilePath -> IO [(String, [(String, [Integer])])]
indexFile' filename = do
existence <- doesDirectoryExist filename
if existence then do
subfiles <- getDirectoryContents filename
let cleanSubfiles = filter (not . (`elem` [".",".."])) subfiles
let realPathSubfiles = map (filename </>) cleanSubfiles
results <- mapM indexFile realPathSubfiles
return $! concat results
else
if takeExtension filename == ".txt" then do
contents <- Prelude.readFile filename :: IO String
let contents' = map toLower contents
let splitString = breakInto contents' isDesirableChar (/='-')
return $! toWordFileMap' filename $ toMap $ sort $ toPosition splitString
else return []
-- | returns a mapping from a filepath to the list of words contained in it, along with their positions.
toWordFileMap :: FilePath -> [(String, [Integer])] -> [(FilePath, [(String, [Integer])])]
toWordFileMap filename wordMap = [(filename, wordMap)]
-- | returns a mapping from a word to the list of filepaths it's contained in, along with the position
-- where it's found in them.
toWordFileMap' :: FilePath -> [(String, [Integer])] -> [(String, [(FilePath, [Integer])])]
toWordFileMap' filename wordMap = map (wordInFile filename) wordMap where
wordInFile :: FilePath -> (String,[Integer]) -> (String, [(FilePath, [Integer])])
wordInFile filename (word, positions) = (word, [(filename, positions)])
-- == Utility functions ==
toPosition :: [a] -> [(a, Integer)]
toPosition list = toPosition' list 0 where
toPosition' [] _ = []
toPosition' (h:t) index = (h, index): toPosition' t (index+1)
toMap :: Eq a => [(a, b)] -> [(a, [b])]
toMap list = toMap' $ groupBy eqFst list
toMap' :: [[(a, b)]] -> [(a, [b])]
toMap' = map (\ h -> ((fst . head) h, map snd h))
toMap2 :: [[(a, [b])]] -> [(a, [b])]
toMap2 = map messInside
-- | assuming the first elements are all equal
messInside :: [(a,[b])] -> (a, [b])
messInside complicatedMap = ((fst.head) complicatedMap, concatMap snd complicatedMap)
| frsoares/hsimplesearch | src/Search/Indexer.hs | gpl-2.0 | 3,378 | 0 | 17 | 780 | 939 | 531 | 408 | 48 | 3 |
--unha declaracion require unha definicion
--o everflow da warning pero non erro na definicion
--na operacion é silencioso
x :: Int
x = 555555555555555555555555555555555555555555555555
--x ^ 20000 -- da overflow e retorna 0 se o casteamos ou indicamos o tipo con :: Int se non infire que é un integer
y :: Integer -- é mais largo que o Int
y = 200000000000000000000000000000000000000000000000 :: Integer
--char
letra :: Char
letra = 'x'
--float
numeroF :: Float
numeroF = 2.3 :: Float
numeroD :: Double
numeroD = 2.3 --coma na resto de linguaxes por defecto haskell utiliza o double esta desaconsellado usar o float
--Bool
bool :: Bool
bool = False
-- e interesante que cando definimos unha variable en haskell temos que lembrar que non estamos asignando un valor a unha variable
-- xa que todo é unha funcion e definimos unha funcion que non ten parametros e devolve o valor Y
-- ollo porque as veces os tipos son alias de outros String é un alias de [Char]
-- ollo tamen porque as listas aqui teñen que ter o mesmo tipo o senon ter o mesmo tipo pai
lista :: [Int]
lista = [1,2,34]
cadea :: String
cadea = "hola mundo"
cadeaC :: [Char]
cadeaC = ['h','o','l','a']
--temos tamen as tuplas que poden estar formadas por elementos de tipos distintos
tupla :: (String,Int)
tupla = ("hola",1)
--as funcions que se definen dunha forma peculiar xa que non fai distincion entre retorno e argumentos
--o ultimo sempre é o retorno
-- tal que nome :: tipo1 -> tipoArg2 ..... -> tipoArgn -> tipoRetorno
func :: Int -> String
func num = show num
func2 :: Int -> Int -> String
func2 num num2 = (show num) ++ " primeiro argumento o segundo é" ++ (show num2)
--ollo porque haskell é de tipado moi forte nunca vai facer conversions por nos
div2 :: Int -> Double
--por este motivo non podemos devolver un int se a sinatura da funcion pon un double
div2 num = (fromIntegral num) / 2 --se non casteamos primeiro infire que é unha operacion non fracional e peta
-- o facer esto considera o segundo un fracional si ou si xa que os numeros son polimorficos
-- por defecto un numero sen coma flotante interpretao como integer pero se o primeiro é de coma flotante
-- enton o ser polimorficos tratao como un coma flotante
--quiz 9.1
div3 :: Int -> Int
-- so devolve numeros enteiros
div3 num = num `div` 2
--temos para pasar de string a X tipo read
--temos para pasar de X tipo a String show
str = show 5
-- nos non indicamos o tipo
-- infireo el
dbl = read "2.5" :: Double
--quiz 9.2
printDouble :: Int -> String
--non convertimos a tipo especifico concreto convirte a funcion o tipo necesario
printDouble numero = show (fromIntegral numero / 1)
--o curioso e que en haskell as funcions so reciven un argumento
--é equivalente
funcE :: Int -> Int -> Int
--funcE num1 num2 = num1 + num2
--podemos entendelo coma unha funcion que devolve unha funcion que devolve un int
--aqui entra moito en xogo as funcions parcialmente aplicadas
funcE = (\num1 ->
(\num2 -> num1 + num2))
--quiz 9.3
-- se non especificamos o tipo e poñemos unha letra minuscula convirtese nunha funcion xenerica
--ie
--func :: a -> a
--se usamos diferentes letras non ten porque ser o mesmo
--func :: a -> b -> c
--o primeiro obriga a que sexa o mesmo tipo o segundo non ten porque
makeAddress :: (String -> (String -> (String -> String)))
makeAddress = (\x -> (\y ->(\z -> x ++ y ++ z)))
| jmlb23/haskell | ch09/types.hs | gpl-3.0 | 3,396 | 0 | 12 | 666 | 452 | 276 | 176 | 37 | 1 |
class TupMat t where
type TupleComps t :: *
fromTups :: TupleComps t -> t
-- instance TupMat Double where
-- type TupleComps t = Double
-- fromTups = id
-- instance TupMat (s,t) where
-- type TupleComps (s,t) = (s,t)
-- fromTups = id
--
newtype Row v = R v deriving (AdditiveGroup)
instance (VectorSpace v) => VectorSpace (Row v) where
type Scalar(Row v)=Scalar v
instance ( CountablySpanned u, CountablySpanned v
, Scalar u~k, Scalar v~k
instance ( CountablySpanned u, CountablySpanned v, CountablySpanned w
, Scalar u~k, Scalar v~k, Scalar w~k, TupMat (Lin k w u), TupMat (Lin k w v)
) => TupMat (Lin k w (u,v)) where
type TupleComps (Lin k w (u,v)) = (TupleComps(Lin k w u), TupleComps(Lin k w v))
fromTups (f,g) = Lin . linear $ \w -> (f$w, g$w)
| leftaroundabout/constrained-categories | wild-ideas/TupMat.hs | gpl-3.0 | 802 | 7 | 12 | 188 | 338 | 176 | 162 | -1 | -1 |
problem1 = sum [ x | x <- [1..999], (x `mod` 3 == 0) || (x `mod` 5 == 0) ]
| vonmoltke/project_euler | haskell/problem1.hs | gpl-3.0 | 75 | 0 | 11 | 21 | 59 | 33 | 26 | 1 | 1 |
{-
Copyright (C) 2014 Richard Larocque <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
module Wiki.Latin.AdjectiveDecl(getAdjectiveInflections) where
import qualified Data.Text as T
import Data.Maybe
import Latin.Grammar
import Wiki.Types
import Wiki.PageParser
getAdjectiveInflections :: [TemplateRef] -> Maybe (T.Text, [GenderedInflection])
getAdjectiveInflections trefs = listToMaybe $ mapMaybe readInflectionTemplates trefs
readInflectionTemplates :: TemplateRef -> Maybe (T.Text, [GenderedInflection])
readInflectionTemplates (TemplateRef (name:params))
| name == (T.pack "la-decl-1&2") = wrapReadFunc la_decl_12 name params
| name == (T.pack "la-decl-1&2-ius") = wrapReadFunc la_decl_12ius name params
| name == (T.pack "la-decl-1&2-plural") = wrapReadFunc la_decl_12_plural name params
| name == (T.pack "la-decl-3rd-1E") = wrapReadFunc la_decl_3_1E name params
| name == (T.pack "la-decl-3rd-1E-PAR") = wrapReadFunc la_decl_3_1E_PAR name params
| name == (T.pack "la-decl-3rd-2E") = wrapReadFunc la_decl_3_2E name params
| name == (T.pack "la-decl-3rd-2E-pl") = wrapReadFunc la_decl_3_2E_pl name params
| name == (T.pack "la-decl-3rd-3E") = wrapReadFunc la_decl_3_3E name params
readInflectionTemplates (TemplateRef _) = Nothing
wrapReadFunc :: ([T.Text] -> Maybe [GenderedInflection]) -> T.Text -> [T.Text] -> Maybe (T.Text, [GenderedInflection])
wrapReadFunc f n xs = f xs >>= \x -> return (n, x)
nom_sg_m = GenderedInflection Nominative Singular Masculine
gen_sg_m = GenderedInflection Genitive Singular Masculine
dat_sg_m = GenderedInflection Dative Singular Masculine
acc_sg_m = GenderedInflection Accusative Singular Masculine
abl_sg_m = GenderedInflection Ablative Singular Masculine
voc_sg_m = GenderedInflection Vocative Singular Masculine
nom_pl_m = GenderedInflection Nominative Plural Masculine
gen_pl_m = GenderedInflection Genitive Plural Masculine
dat_pl_m = GenderedInflection Dative Plural Masculine
acc_pl_m = GenderedInflection Accusative Plural Masculine
abl_pl_m = GenderedInflection Ablative Plural Masculine
voc_pl_m = GenderedInflection Vocative Plural Masculine
nom_sg_f = GenderedInflection Nominative Singular Feminine
gen_sg_f = GenderedInflection Genitive Singular Feminine
dat_sg_f = GenderedInflection Dative Singular Feminine
acc_sg_f = GenderedInflection Accusative Singular Feminine
abl_sg_f = GenderedInflection Ablative Singular Feminine
voc_sg_f = GenderedInflection Vocative Singular Feminine
nom_pl_f = GenderedInflection Nominative Plural Feminine
gen_pl_f = GenderedInflection Genitive Plural Feminine
dat_pl_f = GenderedInflection Dative Plural Feminine
acc_pl_f = GenderedInflection Accusative Plural Feminine
abl_pl_f = GenderedInflection Ablative Plural Feminine
voc_pl_f = GenderedInflection Vocative Plural Feminine
nom_sg_n = GenderedInflection Nominative Singular Neuter
gen_sg_n = GenderedInflection Genitive Singular Neuter
dat_sg_n = GenderedInflection Dative Singular Neuter
acc_sg_n = GenderedInflection Accusative Singular Neuter
abl_sg_n = GenderedInflection Ablative Singular Neuter
voc_sg_n = GenderedInflection Vocative Singular Neuter
nom_pl_n = GenderedInflection Nominative Plural Neuter
gen_pl_n = GenderedInflection Genitive Plural Neuter
dat_pl_n = GenderedInflection Dative Plural Neuter
acc_pl_n = GenderedInflection Accusative Plural Neuter
abl_pl_n = GenderedInflection Ablative Plural Neuter
voc_pl_n = GenderedInflection Vocative Plural Neuter
nom_sg_m, gen_sg_m, dat_sg_m, acc_sg_m, abl_sg_m, voc_sg_m, nom_pl_m, gen_pl_m, dat_pl_m, acc_pl_m, abl_pl_m, voc_pl_m, nom_sg_f, gen_sg_f, dat_sg_f, acc_sg_f, abl_sg_f, voc_sg_f, nom_pl_f, gen_pl_f, dat_pl_f, acc_pl_f, abl_pl_f, voc_pl_f, nom_sg_n, gen_sg_n, dat_sg_n, acc_sg_n, abl_sg_n, voc_sg_n, nom_pl_n, gen_pl_n, dat_pl_n, acc_pl_n, abl_pl_n, voc_pl_n :: T.Text -> GenderedInflection
withSuffix :: T.Text -> String -> T.Text
withSuffix a b = a `T.append` (T.pack b)
la_decl_12, la_decl_12ius, la_decl_12_plural, la_decl_3_1E, la_decl_3_1E_PAR, la_decl_3_2E, la_decl_3_2E_pl, la_decl_3_3E :: [T.Text] -> Maybe [GenderedInflection]
la_decl_12', la_decl_12ius', la_decl_12_plural', la_decl_3_2E', la_decl_3_2E_pl' :: T.Text -> Maybe [GenderedInflection]
la_decl_3_1E', la_decl_3_1E_PAR', la_decl_3_3E' :: T.Text -> T.Text -> Maybe [GenderedInflection]
la_decl_12 [_,stem] = la_decl_12' stem
la_decl_12 [stem] = la_decl_12' stem
la_decl_12 _ = Nothing
la_decl_12' stem = Just [
nom_sg_m (stem `withSuffix` "us"),
gen_sg_m (stem `withSuffix` "ī"),
dat_sg_m (stem `withSuffix` "ō"),
acc_sg_m (stem `withSuffix` "um"),
abl_sg_m (stem `withSuffix` "ō"),
voc_sg_m (stem `withSuffix` "e"),
nom_sg_f (stem `withSuffix` "a"),
gen_sg_f (stem `withSuffix` "ae"),
dat_sg_f (stem `withSuffix` "ae"),
acc_sg_f (stem `withSuffix` "am"),
abl_sg_f (stem `withSuffix` "ā"),
voc_sg_f (stem `withSuffix` "a"),
nom_sg_n (stem `withSuffix` "um"),
gen_sg_n (stem `withSuffix` "ī"),
dat_sg_n (stem `withSuffix` "ō"),
acc_sg_n (stem `withSuffix` "um"),
abl_sg_n (stem `withSuffix` "ō"),
voc_sg_n (stem `withSuffix` "um"),
nom_pl_m (stem `withSuffix` "ī"),
gen_pl_m (stem `withSuffix` "ōrum"),
dat_pl_m (stem `withSuffix` "īs"),
acc_pl_m (stem `withSuffix` "ōs"),
abl_pl_m (stem `withSuffix` "īs"),
voc_pl_m (stem `withSuffix` "ī"),
nom_pl_f (stem `withSuffix` "ae"),
gen_pl_f (stem `withSuffix` "ārum"),
dat_pl_f (stem `withSuffix` "īs"),
acc_pl_f (stem `withSuffix` "ās"),
abl_pl_f (stem `withSuffix` "īs"),
voc_pl_f (stem `withSuffix` "ae"),
nom_pl_n (stem `withSuffix` "a"),
gen_pl_n (stem `withSuffix` "ōrum"),
dat_pl_n (stem `withSuffix` "īs"),
acc_pl_n (stem `withSuffix` "a"),
abl_pl_n (stem `withSuffix` "īs"),
voc_pl_n (stem `withSuffix` "a")]
la_decl_12ius [_,stem] = la_decl_12ius' stem
la_decl_12ius [stem] = la_decl_12ius' stem
la_decl_12ius _ = Nothing
la_decl_12ius' stem = Just [
nom_sg_m (stem `withSuffix` "us"),
gen_sg_m (stem `withSuffix` "īus"),
dat_sg_m (stem `withSuffix` "ī"),
acc_sg_m (stem `withSuffix` "um"),
abl_sg_m (stem `withSuffix` "ō"),
voc_sg_m (stem `withSuffix` "e"),
nom_sg_f (stem `withSuffix` "a"),
gen_sg_f (stem `withSuffix` "īus"),
dat_sg_f (stem `withSuffix` "ī"),
acc_sg_f (stem `withSuffix` "am"),
abl_sg_f (stem `withSuffix` "ā"),
voc_sg_f (stem `withSuffix` "a"),
nom_sg_n (stem `withSuffix` "um"),
gen_sg_n (stem `withSuffix` "īus"),
dat_sg_n (stem `withSuffix` "ī"),
acc_sg_n (stem `withSuffix` "um"),
abl_sg_n (stem `withSuffix` "ō"),
voc_sg_n (stem `withSuffix` "um"),
nom_pl_m (stem `withSuffix` "ī"),
gen_pl_m (stem `withSuffix` "ōrum"),
dat_pl_m (stem `withSuffix` "īs"),
acc_pl_m (stem `withSuffix` "ōs"),
abl_pl_m (stem `withSuffix` "īs"),
voc_pl_m (stem `withSuffix` "ī"),
nom_pl_f (stem `withSuffix` "ae"),
gen_pl_f (stem `withSuffix` "ārum"),
dat_pl_f (stem `withSuffix` "īs"),
acc_pl_f (stem `withSuffix` "ās"),
abl_pl_f (stem `withSuffix` "īs"),
voc_pl_f (stem `withSuffix` "ae"),
nom_pl_n (stem `withSuffix` "a"),
gen_pl_n (stem `withSuffix` "ōrum"),
dat_pl_n (stem `withSuffix` "īs"),
acc_pl_n (stem `withSuffix` "a"),
abl_pl_n (stem `withSuffix` "īs"),
voc_pl_n (stem `withSuffix` "a")]
la_decl_12_plural [_,stem] = la_decl_12_plural' stem
la_decl_12_plural [stem] = la_decl_12_plural' stem
la_decl_12_plural _ = Nothing
la_decl_12_plural' stem = Just [
nom_pl_m (stem `withSuffix` "ī"),
nom_pl_f (stem `withSuffix` "ae"),
nom_pl_n (stem `withSuffix` "a"),
gen_pl_m (stem `withSuffix` "ōrum"),
gen_pl_f (stem `withSuffix` "ārum"),
gen_pl_n (stem `withSuffix` "ōrum"),
dat_pl_m (stem `withSuffix` "īs"),
dat_pl_f (stem `withSuffix` "īs"),
dat_pl_n (stem `withSuffix` "īs"),
acc_pl_m (stem `withSuffix` "ōs"),
acc_pl_f (stem `withSuffix` "ās"),
acc_pl_n (stem `withSuffix` "a"),
abl_pl_m (stem `withSuffix` "īs"),
abl_pl_f (stem `withSuffix` "īs"),
abl_pl_n (stem `withSuffix` "īs"),
voc_pl_m (stem `withSuffix` "ī"),
voc_pl_f (stem `withSuffix` "ae"),
voc_pl_n (stem `withSuffix` "a")]
la_decl_3_1E [nom,stem] = la_decl_3_1E' nom stem
la_decl_3_1E [stem] = la_decl_3_1E' stem stem
la_decl_3_1E _ = Nothing
la_decl_3_1E' nom stem = Just [
nom_sg_m nom,
gen_sg_m (stem `withSuffix` "is"),
dat_sg_m (stem `withSuffix` "ī"),
acc_sg_m (stem `withSuffix` "em"),
abl_sg_m (stem `withSuffix` "ī"),
voc_sg_m nom,
nom_sg_f nom,
gen_sg_f (stem `withSuffix` "is"),
dat_sg_f (stem `withSuffix` "ī"),
acc_sg_f (stem `withSuffix` "em"),
abl_sg_f (stem `withSuffix` "ī"),
voc_sg_f nom,
nom_sg_n nom,
gen_sg_n (stem `withSuffix` "is"),
dat_sg_n (stem `withSuffix` "ī"),
acc_sg_n nom,
abl_sg_n (stem `withSuffix` "ī"),
voc_sg_n nom,
nom_pl_m (stem `withSuffix` "ēs"),
gen_pl_m (stem `withSuffix` "ium"),
dat_pl_m (stem `withSuffix` "ibus"),
acc_pl_m (stem `withSuffix` "ēs"),
abl_pl_m (stem `withSuffix` "ibus"),
voc_pl_m (stem `withSuffix` "ēs"),
nom_pl_f (stem `withSuffix` "ēs"),
gen_pl_f (stem `withSuffix` "ium"),
dat_pl_f (stem `withSuffix` "ibus"),
acc_pl_f (stem `withSuffix` "ēs"),
abl_pl_f (stem `withSuffix` "ibus"),
voc_pl_f (stem `withSuffix` "ēs"),
nom_pl_n (stem `withSuffix` "ia"),
gen_pl_n (stem `withSuffix` "ium"),
dat_pl_n (stem `withSuffix` "ibus"),
acc_pl_n (stem `withSuffix` "ia"),
abl_pl_n (stem `withSuffix` "ibus"),
voc_pl_n (stem `withSuffix` "ia")]
la_decl_3_1E_PAR [nom,stem] = la_decl_3_1E_PAR' nom stem
la_decl_3_1E_PAR [stem] = la_decl_3_1E_PAR' stem stem
la_decl_3_1E_PAR _ = Nothing
la_decl_3_1E_PAR' nom stem = Just [
nom_sg_m nom,
gen_sg_m (stem `withSuffix` "is"),
dat_sg_m (stem `withSuffix` "ī"),
acc_sg_m (stem `withSuffix` "em"),
abl_sg_m (stem `withSuffix` "e"),
voc_sg_m nom,
nom_sg_f nom,
gen_sg_f (stem `withSuffix` "is"),
dat_sg_f (stem `withSuffix` "ī"),
acc_sg_f (stem `withSuffix` "em"),
abl_sg_f (stem `withSuffix` "e"),
voc_sg_f nom,
nom_sg_n nom,
gen_sg_n (stem `withSuffix` "is"),
dat_sg_n (stem `withSuffix` "ī"),
acc_sg_n nom,
abl_sg_n (stem `withSuffix` "e"),
voc_sg_n nom,
nom_pl_m (stem `withSuffix` "ēs"),
gen_pl_m (stem `withSuffix` "um"),
dat_pl_m (stem `withSuffix` "ibus"),
acc_pl_m (stem `withSuffix` "ēs"),
abl_pl_m (stem `withSuffix` "ibus"),
voc_pl_m (stem `withSuffix` "ēs"),
nom_pl_f (stem `withSuffix` "ēs"),
gen_pl_f (stem `withSuffix` "um"),
dat_pl_f (stem `withSuffix` "ibus"),
acc_pl_f (stem `withSuffix` "ēs"),
abl_pl_f (stem `withSuffix` "ibus"),
voc_pl_f (stem `withSuffix` "ēs"),
nom_pl_n (stem `withSuffix` "a"),
gen_pl_n (stem `withSuffix` "um"),
dat_pl_n (stem `withSuffix` "ibus"),
acc_pl_n (stem `withSuffix` "a"),
abl_pl_n (stem `withSuffix` "ibus"),
voc_pl_n (stem `withSuffix` "a")]
la_decl_3_2E [_,stem] = la_decl_3_2E' stem
la_decl_3_2E [stem] = la_decl_3_2E' stem
la_decl_3_2E _ = Nothing
la_decl_3_2E' stem = Just [
nom_sg_m (stem `withSuffix` "is"),
gen_sg_m (stem `withSuffix` "is"),
dat_sg_m (stem `withSuffix` "ī"),
acc_sg_m (stem `withSuffix` "em"),
abl_sg_m (stem `withSuffix` "ī"),
voc_sg_m (stem `withSuffix` "is"),
nom_sg_f (stem `withSuffix` "is"),
gen_sg_f (stem `withSuffix` "is"),
dat_sg_f (stem `withSuffix` "ī"),
acc_sg_f (stem `withSuffix` "em"),
abl_sg_f (stem `withSuffix` "ī"),
voc_sg_f (stem `withSuffix` "is"),
nom_sg_n (stem `withSuffix` "e"),
gen_sg_n (stem `withSuffix` "is"),
dat_sg_n (stem `withSuffix` "ī"),
acc_sg_n (stem `withSuffix` "e"),
abl_sg_n (stem `withSuffix` "ī"),
voc_sg_n (stem `withSuffix` "e"),
nom_pl_m (stem `withSuffix` "ēs"),
gen_pl_m (stem `withSuffix` "ium"),
dat_pl_m (stem `withSuffix` "ibus"),
acc_pl_m (stem `withSuffix` "ēs"),
abl_pl_m (stem `withSuffix` "ibus"),
voc_pl_m (stem `withSuffix` "ēs"),
nom_pl_f (stem `withSuffix` "ēs"),
gen_pl_f (stem `withSuffix` "ium"),
dat_pl_f (stem `withSuffix` "ibus"),
acc_pl_f (stem `withSuffix` "ēs"),
abl_pl_f (stem `withSuffix` "ibus"),
voc_pl_f (stem `withSuffix` "ēs"),
nom_pl_n (stem `withSuffix` "ia"),
gen_pl_n (stem `withSuffix` "ium"),
dat_pl_n (stem `withSuffix` "ibus"),
acc_pl_n (stem `withSuffix` "ia"),
abl_pl_n (stem `withSuffix` "ibus"),
voc_pl_n (stem `withSuffix` "ia")]
la_decl_3_2E_pl [stem] = la_decl_3_2E_pl' stem
la_decl_3_2E_pl [_,stem] = la_decl_3_2E_pl' stem
la_decl_3_2E_pl _ = Nothing
la_decl_3_2E_pl' stem = Just [
nom_pl_m (stem `withSuffix` "ēs"),
nom_pl_f (stem `withSuffix` "ēs"),
nom_pl_n (stem `withSuffix` "ia"),
gen_pl_m (stem `withSuffix` "ium"),
gen_pl_f (stem `withSuffix` "ium"),
gen_pl_n (stem `withSuffix` "ium"),
dat_pl_m (stem `withSuffix` "ibus"),
dat_pl_f (stem `withSuffix` "ibus"),
dat_pl_n (stem `withSuffix` "ibus"),
acc_pl_m (stem `withSuffix` "ēs"),
acc_pl_f (stem `withSuffix` "ēs"),
acc_pl_n (stem `withSuffix` "ia"),
abl_pl_m (stem `withSuffix` "ibus"),
abl_pl_f (stem `withSuffix` "ibus"),
abl_pl_n (stem `withSuffix` "ibus"),
voc_pl_m (stem `withSuffix` "ēs"),
voc_pl_f (stem `withSuffix` "ēs"),
voc_pl_n (stem `withSuffix` "ia")]
la_decl_3_3E [stem] = la_decl_3_3E' stem stem
la_decl_3_3E [nom,stem] = la_decl_3_3E' nom stem
la_decl_3_3E _ = Nothing
la_decl_3_3E' nom stem = Just $ [
nom_sg_m nom,
gen_sg_m (stem `withSuffix` "is"),
dat_sg_m (stem `withSuffix` "ī"),
acc_sg_m (stem `withSuffix` "em"),
abl_sg_m (stem `withSuffix` "ī"),
voc_sg_m nom,
nom_sg_f (stem `withSuffix` "is"),
gen_sg_f (stem `withSuffix` "is"),
dat_sg_f (stem `withSuffix` "ī"),
acc_sg_f (stem `withSuffix` "em"),
abl_sg_f (stem `withSuffix` "ī"),
voc_sg_f (stem `withSuffix` "is"),
nom_sg_n (stem `withSuffix` "e"),
gen_sg_n (stem `withSuffix` "is"),
dat_sg_n (stem `withSuffix` "ī"),
acc_sg_n (stem `withSuffix` "e"),
abl_sg_n (stem `withSuffix` "ī"),
voc_sg_n (stem `withSuffix` "e"),
nom_pl_m (stem `withSuffix` "ēs"),
gen_pl_m (stem `withSuffix` "ium"),
dat_pl_m (stem `withSuffix` "ibus"),
acc_pl_m (stem `withSuffix` "ēs"),
abl_pl_m (stem `withSuffix` "ibus"),
voc_pl_m (stem `withSuffix` "ēs"),
nom_pl_f (stem `withSuffix` "ēs"),
gen_pl_f (stem `withSuffix` "ium"),
dat_pl_f (stem `withSuffix` "ibus"),
acc_pl_f (stem `withSuffix` "ēs"),
abl_pl_f (stem `withSuffix` "ibus"),
voc_pl_f (stem `withSuffix` "ēs"),
nom_pl_n (stem `withSuffix` "ia"),
gen_pl_n (stem `withSuffix` "ium"),
dat_pl_n (stem `withSuffix` "ibus"),
acc_pl_n (stem `withSuffix` "ia"),
abl_pl_n (stem `withSuffix` "ibus"),
voc_pl_n (stem `withSuffix` "ia")]
| richardlarocque/latin-db-builder | Wiki/Latin/AdjectiveDecl.hs | gpl-3.0 | 15,086 | 504 | 11 | 2,043 | 5,653 | 3,238 | 2,415 | 347 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Pretty.Fields.Persistent
( module Pretty.Fields
, idField
, namedIdField
, textField
, doubleField
, doubleField_
, fieldVia
, maybeTextField
, multilineTextField
, maybeFieldVia
) where
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import Database.Persist.Class (EntityField)
import Pretty.Fields
import Sql.Core (Entity, Key, MonadSql, SqlBackend, SqlRecord, ToBackendKey)
import qualified Sql.Core as Sql
pattern FieldInfo
:: SqlRecord rec
=> EntityField rec v -> (v -> Text) -> Bool -> FieldInfo (Entity rec)
pattern FieldInfo field conv b <- VerboseFieldInfo (PersistField field) conv _ b where
FieldInfo field conv b = VerboseFieldInfo (PersistField field) conv Nothing b
idField
:: (ToBackendKey SqlBackend k, SqlRecord v)
=> EntityField v (Key k) -> FieldInfo (Entity v)
idField f = FieldInfo f (T.pack . show . Sql.fromSqlKey) False
namedIdField
:: forall k v
. (ToBackendKey SqlBackend k, NamedEntity k, SqlRecord v)
=> EntityField v (Key k) -> FieldInfo (Entity v)
namedIdField f = VerboseFieldInfo (PersistField f) showKey (Just prettyName) False
where
showKey :: Key k -> Text
showKey = T.pack . show . Sql.fromSqlKey
prettyName :: MonadSql m => Key k -> m Text
prettyName k = do
value <- Sql.getJust k
return $ entityName value <> " (#" <> showKey k <> ")"
textField :: SqlRecord v => EntityField v Text -> FieldInfo (Entity v)
textField f = FieldInfo f id False
doubleField
:: SqlRecord v => Int -> EntityField v Double -> FieldInfo (Entity v)
doubleField n f = VerboseFieldInfo (PersistField f) prettyShow (Just mkPretty) False
where
mkPretty :: Monad m => Double -> m Text
mkPretty = return . prettyDouble n
doubleField_ :: SqlRecord v => EntityField v Double -> FieldInfo (Entity v)
doubleField_ = doubleField 2
fieldVia
:: SqlRecord v => EntityField v r -> (r -> Text) -> FieldInfo (Entity v)
fieldVia f conv = FieldInfo f conv False
maybeTextField
:: SqlRecord v => EntityField v (Maybe Text) -> FieldInfo (Entity v)
maybeTextField f = FieldInfo f (fromMaybe "") False
multilineTextField
:: SqlRecord v => EntityField v (Maybe Text) -> FieldInfo (Entity v)
multilineTextField f = FieldInfo f (maybe "" format) True
where
format :: Text -> Text
format = mappend "\n" . T.unlines . map (" " <>) . T.lines
maybeFieldVia
:: SqlRecord v
=> EntityField v (Maybe r) -> (r -> Text) -> FieldInfo (Entity v)
maybeFieldVia f conv = FieldInfo f (maybe "" conv) False
| merijn/GPU-benchmarks | benchmark-analysis/src/Pretty/Fields/Persistent.hs | gpl-3.0 | 2,784 | 0 | 13 | 585 | 960 | 489 | 471 | 68 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Database.Hedsql.Tests.Update
( tests
) where
--------------------------------------------------------------------------------
-- IMPORTS
--------------------------------------------------------------------------------
import Data.Monoid
import Database.Hedsql.Examples.Update
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit hiding (Test)
import qualified Database.Hedsql.PostgreSQL as P
import qualified Database.Hedsql.SqLite as S
--------------------------------------------------------------------------------
-- PRIVATE
--------------------------------------------------------------------------------
----------------------------------------
-- All vendors
----------------------------------------
testEqualTo :: Test
testEqualTo = testCase "Update with equal-to" assertUpdate
where
assertUpdate :: Assertion
assertUpdate = assertEqual
"Update with equal-to is incorrect"
"UPDATE \"People\" SET \"age\" = 2050 WHERE \"lastName\" = 'Ceasar'"
(S.codeGen equalTo)
testUpdateSelect :: Test
testUpdateSelect = testCase "Update with a SELECT" assertUpdate
where
assertUpdate :: Assertion
assertUpdate = assertEqual
"Update with a SELECT is incorrect"
( "UPDATE \"People\" SET \"age\" = \"age\" + 1 "
<> "WHERE \"countryId\" IN "
<> "(SELECT \"countryId\" FROM \"Countries\" "
<> "WHERE \"name\" = 'Italy')"
)
(S.codeGen updateSelect)
----------------------------------------
-- PostgreSQL
----------------------------------------
testDefaultVal :: Test
testDefaultVal = testCase "Update with defaultValue" assertUpdate
where
assertUpdate :: Assertion
assertUpdate = assertEqual
"Update with a default value is incorrect"
"UPDATE \"People\" SET \"title\" = DEFAULT WHERE \"personId\" = 1"
(P.codeGen defaultVal)
testReturning :: Test
testReturning = testCase "Update with RETURNING clause" assertUpdate
where
assertUpdate :: Assertion
assertUpdate = assertEqual
"Update with a RETURNING clause is incorrect"
( "UPDATE \"People\" SET \"age\" = 2050 "
<> "WHERE \"personId\" = 1 "
<> "RETURNING \"personId\""
)
(P.codeGen updateReturningClause)
--------------------------------------------------------------------------------
-- PUBLIC
--------------------------------------------------------------------------------
-- | Gather all tests.
tests :: Test
tests = testGroup "Update"
[ testGroup "All vendors"
[ testEqualTo
, testUpdateSelect
]
, testGroup "PostgreSQL"
[ testDefaultVal
, testReturning
]
]
| momomimachli/Hedsql-tests | src/Database/Hedsql/Tests/Update.hs | gpl-3.0 | 2,929 | 0 | 11 | 683 | 333 | 197 | 136 | 51 | 1 |
module Math.LinearAlgebra.GramSchmidt.Tests (
tests
) where
import Test.Framework
import qualified Test.HUnit as H
import Test.Framework.Providers.HUnit
import Data.Ratio
import Math.LinearAlgebra.GramSchmidt
simpleTest = H.assert $ computed == correct
where
computed = gramSchmidtOrthogonalization $ map (map toRational) [ [1, 1, 0], [1, 0, 1], [0, 1, 1] ]
correct = ([[1 % 1,1 % 1,0 % 1],[1 % 2,(-1) % 2,1 % 1],[(-2) % 3,2 % 3,2 % 3]],[[1 % 2],[1 % 2,1 % 3]])
tests :: [Test]
tests = concat
[
[testCase "Simple G-S test on Rationals" simpleTest]
]
| bcoppens/Lattices | tests/Math/LinearAlgebra/GramSchmidt/Tests.hs | gpl-3.0 | 594 | 0 | 12 | 131 | 264 | 159 | 105 | 14 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.AdExchangeSeller
-- 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)
--
-- Accesses the inventory of Ad Exchange seller users and generates
-- reports.
--
-- /See:/ <https://developers.google.com/ad-exchange/seller-rest/ Ad Exchange Seller API Reference>
module Network.Google.AdExchangeSeller
(
-- * Service Configuration
adExchangeSellerService
-- * OAuth Scopes
, adExchangeSellerReadOnlyScope
, adExchangeSellerScope
-- * API Declaration
, AdExchangeSellerAPI
-- * Resources
-- ** adexchangeseller.accounts.adclients.list
, module Network.Google.Resource.AdExchangeSeller.Accounts.AdClients.List
-- ** adexchangeseller.accounts.alerts.list
, module Network.Google.Resource.AdExchangeSeller.Accounts.Alerts.List
-- ** adexchangeseller.accounts.customchannels.get
, module Network.Google.Resource.AdExchangeSeller.Accounts.CustomChannels.Get
-- ** adexchangeseller.accounts.customchannels.list
, module Network.Google.Resource.AdExchangeSeller.Accounts.CustomChannels.List
-- ** adexchangeseller.accounts.get
, module Network.Google.Resource.AdExchangeSeller.Accounts.Get
-- ** adexchangeseller.accounts.list
, module Network.Google.Resource.AdExchangeSeller.Accounts.List
-- ** adexchangeseller.accounts.metadata.dimensions.list
, module Network.Google.Resource.AdExchangeSeller.Accounts.Metadata.Dimensions.List
-- ** adexchangeseller.accounts.metadata.metrics.list
, module Network.Google.Resource.AdExchangeSeller.Accounts.Metadata.Metrics.List
-- ** adexchangeseller.accounts.preferreddeals.get
, module Network.Google.Resource.AdExchangeSeller.Accounts.PreferredDeals.Get
-- ** adexchangeseller.accounts.preferreddeals.list
, module Network.Google.Resource.AdExchangeSeller.Accounts.PreferredDeals.List
-- ** adexchangeseller.accounts.reports.generate
, module Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Generate
-- ** adexchangeseller.accounts.reports.saved.generate
, module Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Saved.Generate
-- ** adexchangeseller.accounts.reports.saved.list
, module Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Saved.List
-- ** adexchangeseller.accounts.urlchannels.list
, module Network.Google.Resource.AdExchangeSeller.Accounts.URLChannels.List
-- * Types
-- ** AdClients
, AdClients
, adClients
, acEtag
, acNextPageToken
, acKind
, acItems
-- ** ReportingMetadataEntry
, ReportingMetadataEntry
, reportingMetadataEntry
, rmeKind
, rmeRequiredMetrics
, rmeCompatibleMetrics
, rmeRequiredDimensions
, rmeId
, rmeCompatibleDimensions
, rmeSupportedProducts
-- ** Accounts
, Accounts
, accounts
, aEtag
, aNextPageToken
, aKind
, aItems
-- ** Alerts
, Alerts
, alerts
, aleKind
, aleItems
-- ** SavedReports
, SavedReports
, savedReports
, srEtag
, srNextPageToken
, srKind
, srItems
-- ** SavedReport
, SavedReport
, savedReport
, sKind
, sName
, sId
-- ** URLChannels
, URLChannels
, urlChannels
, ucEtag
, ucNextPageToken
, ucKind
, ucItems
-- ** CustomChannels
, CustomChannels
, customChannels
, ccEtag
, ccNextPageToken
, ccKind
, ccItems
-- ** Report
, Report
, report
, rKind
, rAverages
, rWarnings
, rRows
, rTotals
, rHeaders
, rTotalMatchedRows
-- ** Alert
, Alert
, alert
, aaKind
, aaSeverity
, aaId
, aaType
, aaMessage
-- ** Account
, Account
, account
, accKind
, accName
, accId
-- ** AdClient
, AdClient
, adClient
, adKind
, adArcOptIn
, adSupportsReporting
, adId
, adProductCode
-- ** ReportHeadersItem
, ReportHeadersItem
, reportHeadersItem
, rhiName
, rhiCurrency
, rhiType
-- ** CustomChannelTargetingInfo
, CustomChannelTargetingInfo
, customChannelTargetingInfo
, cctiLocation
, cctiSiteLanguage
, cctiAdsAppearOn
, cctiDescription
-- ** PreferredDeals
, PreferredDeals
, preferredDeals
, pdKind
, pdItems
-- ** Metadata
, Metadata
, metadata
, mKind
, mItems
-- ** CustomChannel
, CustomChannel
, customChannel
, cTargetingInfo
, cKind
, cName
, cCode
, cId
-- ** URLChannel
, URLChannel
, urlChannel
, urlcKind
, urlcId
, urlcURLPattern
-- ** PreferredDeal
, PreferredDeal
, preferredDeal
, pAdvertiserName
, pCurrencyCode
, pStartTime
, pKind
, pBuyerNetworkName
, pEndTime
, pId
, pFixedCpm
) where
import Network.Google.AdExchangeSeller.Types
import Network.Google.Prelude
import Network.Google.Resource.AdExchangeSeller.Accounts.AdClients.List
import Network.Google.Resource.AdExchangeSeller.Accounts.Alerts.List
import Network.Google.Resource.AdExchangeSeller.Accounts.CustomChannels.Get
import Network.Google.Resource.AdExchangeSeller.Accounts.CustomChannels.List
import Network.Google.Resource.AdExchangeSeller.Accounts.Get
import Network.Google.Resource.AdExchangeSeller.Accounts.List
import Network.Google.Resource.AdExchangeSeller.Accounts.Metadata.Dimensions.List
import Network.Google.Resource.AdExchangeSeller.Accounts.Metadata.Metrics.List
import Network.Google.Resource.AdExchangeSeller.Accounts.PreferredDeals.Get
import Network.Google.Resource.AdExchangeSeller.Accounts.PreferredDeals.List
import Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Generate
import Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Saved.Generate
import Network.Google.Resource.AdExchangeSeller.Accounts.Reports.Saved.List
import Network.Google.Resource.AdExchangeSeller.Accounts.URLChannels.List
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Ad Exchange Seller API service.
type AdExchangeSellerAPI =
AccountsAdClientsListResource :<|>
AccountsReportsSavedListResource
:<|> AccountsReportsSavedGenerateResource
:<|> AccountsReportsGenerateResource
:<|> AccountsAlertsListResource
:<|> AccountsURLChannelsListResource
:<|> AccountsCustomChannelsListResource
:<|> AccountsCustomChannelsGetResource
:<|> AccountsPreferredDealsListResource
:<|> AccountsPreferredDealsGetResource
:<|> AccountsMetadataMetricsListResource
:<|> AccountsMetadataDimensionsListResource
:<|> AccountsListResource
:<|> AccountsGetResource
| rueshyna/gogol | gogol-adexchange-seller/gen/Network/Google/AdExchangeSeller.hs | mpl-2.0 | 7,300 | 0 | 17 | 1,598 | 798 | 586 | 212 | 173 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CloudWatchLogs.Types
-- 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.
module Network.AWS.CloudWatchLogs.Types
(
-- * Service
CloudWatchLogs
-- ** Error
, JSONError
-- * MetricFilter
, MetricFilter
, metricFilter
, mfCreationTime
, mfFilterName
, mfFilterPattern
, mfMetricTransformations
-- * MetricFilterMatchRecord
, MetricFilterMatchRecord
, metricFilterMatchRecord
, mfmrEventMessage
, mfmrEventNumber
, mfmrExtractedValues
-- * MetricTransformation
, MetricTransformation
, metricTransformation
, mtMetricName
, mtMetricNamespace
, mtMetricValue
-- * LogStream
, LogStream
, logStream
, lsArn
, lsCreationTime
, lsFirstEventTimestamp
, lsLastEventTimestamp
, lsLastIngestionTime
, lsLogStreamName
, lsStoredBytes
, lsUploadSequenceToken
-- * LogGroup
, LogGroup
, logGroup
, lgArn
, lgCreationTime
, lgLogGroupName
, lgMetricFilterCount
, lgRetentionInDays
, lgStoredBytes
-- * InputLogEvent
, InputLogEvent
, inputLogEvent
, ileMessage
, ileTimestamp
-- * OutputLogEvent
, OutputLogEvent
, outputLogEvent
, oleIngestionTime
, oleMessage
, oleTimestamp
) where
import Network.AWS.Prelude
import Network.AWS.Signing
import qualified GHC.Exts
-- | Version @2014-03-28@ of the Amazon CloudWatch Logs service.
data CloudWatchLogs
instance AWSService CloudWatchLogs where
type Sg CloudWatchLogs = V4
type Er CloudWatchLogs = JSONError
service = service'
where
service' :: Service CloudWatchLogs
service' = Service
{ _svcAbbrev = "CloudWatchLogs"
, _svcPrefix = "logs"
, _svcVersion = "2014-03-28"
, _svcTargetPrefix = Just "Logs_20140328"
, _svcJSONVersion = Just "1.1"
, _svcHandle = handle
, _svcRetry = retry
}
handle :: Status
-> Maybe (LazyByteString -> ServiceError JSONError)
handle = jsonError statusSuccess service'
retry :: Retry CloudWatchLogs
retry = Exponential
{ _retryBase = 0.05
, _retryGrowth = 2
, _retryAttempts = 5
, _retryCheck = check
}
check :: Status
-> JSONError
-> Bool
check (statusCode -> s) (awsErrorCode -> e)
| s == 500 = True -- General Server Error
| s == 509 = True -- Limit Exceeded
| s == 503 = True -- Service Unavailable
| otherwise = False
data MetricFilter = MetricFilter
{ _mfCreationTime :: Maybe Nat
, _mfFilterName :: Maybe Text
, _mfFilterPattern :: Maybe Text
, _mfMetricTransformations :: List1 "metricTransformations" MetricTransformation
} deriving (Eq, Read, Show)
-- | 'MetricFilter' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'mfCreationTime' @::@ 'Maybe' 'Natural'
--
-- * 'mfFilterName' @::@ 'Maybe' 'Text'
--
-- * 'mfFilterPattern' @::@ 'Maybe' 'Text'
--
-- * 'mfMetricTransformations' @::@ 'NonEmpty' 'MetricTransformation'
--
metricFilter :: NonEmpty MetricTransformation -- ^ 'mfMetricTransformations'
-> MetricFilter
metricFilter p1 = MetricFilter
{ _mfMetricTransformations = withIso _List1 (const id) p1
, _mfFilterName = Nothing
, _mfFilterPattern = Nothing
, _mfCreationTime = Nothing
}
mfCreationTime :: Lens' MetricFilter (Maybe Natural)
mfCreationTime = lens _mfCreationTime (\s a -> s { _mfCreationTime = a }) . mapping _Nat
mfFilterName :: Lens' MetricFilter (Maybe Text)
mfFilterName = lens _mfFilterName (\s a -> s { _mfFilterName = a })
mfFilterPattern :: Lens' MetricFilter (Maybe Text)
mfFilterPattern = lens _mfFilterPattern (\s a -> s { _mfFilterPattern = a })
mfMetricTransformations :: Lens' MetricFilter (NonEmpty MetricTransformation)
mfMetricTransformations =
lens _mfMetricTransformations (\s a -> s { _mfMetricTransformations = a })
. _List1
instance FromJSON MetricFilter where
parseJSON = withObject "MetricFilter" $ \o -> MetricFilter
<$> o .:? "creationTime"
<*> o .:? "filterName"
<*> o .:? "filterPattern"
<*> o .: "metricTransformations"
instance ToJSON MetricFilter where
toJSON MetricFilter{..} = object
[ "filterName" .= _mfFilterName
, "filterPattern" .= _mfFilterPattern
, "metricTransformations" .= _mfMetricTransformations
, "creationTime" .= _mfCreationTime
]
data MetricFilterMatchRecord = MetricFilterMatchRecord
{ _mfmrEventMessage :: Maybe Text
, _mfmrEventNumber :: Maybe Integer
, _mfmrExtractedValues :: Map Text Text
} deriving (Eq, Read, Show)
-- | 'MetricFilterMatchRecord' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'mfmrEventMessage' @::@ 'Maybe' 'Text'
--
-- * 'mfmrEventNumber' @::@ 'Maybe' 'Integer'
--
-- * 'mfmrExtractedValues' @::@ 'HashMap' 'Text' 'Text'
--
metricFilterMatchRecord :: MetricFilterMatchRecord
metricFilterMatchRecord = MetricFilterMatchRecord
{ _mfmrEventNumber = Nothing
, _mfmrEventMessage = Nothing
, _mfmrExtractedValues = mempty
}
mfmrEventMessage :: Lens' MetricFilterMatchRecord (Maybe Text)
mfmrEventMessage = lens _mfmrEventMessage (\s a -> s { _mfmrEventMessage = a })
mfmrEventNumber :: Lens' MetricFilterMatchRecord (Maybe Integer)
mfmrEventNumber = lens _mfmrEventNumber (\s a -> s { _mfmrEventNumber = a })
mfmrExtractedValues :: Lens' MetricFilterMatchRecord (HashMap Text Text)
mfmrExtractedValues =
lens _mfmrExtractedValues (\s a -> s { _mfmrExtractedValues = a })
. _Map
instance FromJSON MetricFilterMatchRecord where
parseJSON = withObject "MetricFilterMatchRecord" $ \o -> MetricFilterMatchRecord
<$> o .:? "eventMessage"
<*> o .:? "eventNumber"
<*> o .:? "extractedValues" .!= mempty
instance ToJSON MetricFilterMatchRecord where
toJSON MetricFilterMatchRecord{..} = object
[ "eventNumber" .= _mfmrEventNumber
, "eventMessage" .= _mfmrEventMessage
, "extractedValues" .= _mfmrExtractedValues
]
data MetricTransformation = MetricTransformation
{ _mtMetricName :: Text
, _mtMetricNamespace :: Text
, _mtMetricValue :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'MetricTransformation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'mtMetricName' @::@ 'Text'
--
-- * 'mtMetricNamespace' @::@ 'Text'
--
-- * 'mtMetricValue' @::@ 'Text'
--
metricTransformation :: Text -- ^ 'mtMetricName'
-> Text -- ^ 'mtMetricNamespace'
-> Text -- ^ 'mtMetricValue'
-> MetricTransformation
metricTransformation p1 p2 p3 = MetricTransformation
{ _mtMetricName = p1
, _mtMetricNamespace = p2
, _mtMetricValue = p3
}
mtMetricName :: Lens' MetricTransformation Text
mtMetricName = lens _mtMetricName (\s a -> s { _mtMetricName = a })
mtMetricNamespace :: Lens' MetricTransformation Text
mtMetricNamespace =
lens _mtMetricNamespace (\s a -> s { _mtMetricNamespace = a })
mtMetricValue :: Lens' MetricTransformation Text
mtMetricValue = lens _mtMetricValue (\s a -> s { _mtMetricValue = a })
instance FromJSON MetricTransformation where
parseJSON = withObject "MetricTransformation" $ \o -> MetricTransformation
<$> o .: "metricName"
<*> o .: "metricNamespace"
<*> o .: "metricValue"
instance ToJSON MetricTransformation where
toJSON MetricTransformation{..} = object
[ "metricName" .= _mtMetricName
, "metricNamespace" .= _mtMetricNamespace
, "metricValue" .= _mtMetricValue
]
data LogStream = LogStream
{ _lsArn :: Maybe Text
, _lsCreationTime :: Maybe Nat
, _lsFirstEventTimestamp :: Maybe Nat
, _lsLastEventTimestamp :: Maybe Nat
, _lsLastIngestionTime :: Maybe Nat
, _lsLogStreamName :: Maybe Text
, _lsStoredBytes :: Maybe Nat
, _lsUploadSequenceToken :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'LogStream' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lsArn' @::@ 'Maybe' 'Text'
--
-- * 'lsCreationTime' @::@ 'Maybe' 'Natural'
--
-- * 'lsFirstEventTimestamp' @::@ 'Maybe' 'Natural'
--
-- * 'lsLastEventTimestamp' @::@ 'Maybe' 'Natural'
--
-- * 'lsLastIngestionTime' @::@ 'Maybe' 'Natural'
--
-- * 'lsLogStreamName' @::@ 'Maybe' 'Text'
--
-- * 'lsStoredBytes' @::@ 'Maybe' 'Natural'
--
-- * 'lsUploadSequenceToken' @::@ 'Maybe' 'Text'
--
logStream :: LogStream
logStream = LogStream
{ _lsLogStreamName = Nothing
, _lsCreationTime = Nothing
, _lsFirstEventTimestamp = Nothing
, _lsLastEventTimestamp = Nothing
, _lsLastIngestionTime = Nothing
, _lsUploadSequenceToken = Nothing
, _lsArn = Nothing
, _lsStoredBytes = Nothing
}
lsArn :: Lens' LogStream (Maybe Text)
lsArn = lens _lsArn (\s a -> s { _lsArn = a })
lsCreationTime :: Lens' LogStream (Maybe Natural)
lsCreationTime = lens _lsCreationTime (\s a -> s { _lsCreationTime = a }) . mapping _Nat
lsFirstEventTimestamp :: Lens' LogStream (Maybe Natural)
lsFirstEventTimestamp =
lens _lsFirstEventTimestamp (\s a -> s { _lsFirstEventTimestamp = a })
. mapping _Nat
lsLastEventTimestamp :: Lens' LogStream (Maybe Natural)
lsLastEventTimestamp =
lens _lsLastEventTimestamp (\s a -> s { _lsLastEventTimestamp = a })
. mapping _Nat
lsLastIngestionTime :: Lens' LogStream (Maybe Natural)
lsLastIngestionTime =
lens _lsLastIngestionTime (\s a -> s { _lsLastIngestionTime = a })
. mapping _Nat
lsLogStreamName :: Lens' LogStream (Maybe Text)
lsLogStreamName = lens _lsLogStreamName (\s a -> s { _lsLogStreamName = a })
lsStoredBytes :: Lens' LogStream (Maybe Natural)
lsStoredBytes = lens _lsStoredBytes (\s a -> s { _lsStoredBytes = a }) . mapping _Nat
lsUploadSequenceToken :: Lens' LogStream (Maybe Text)
lsUploadSequenceToken =
lens _lsUploadSequenceToken (\s a -> s { _lsUploadSequenceToken = a })
instance FromJSON LogStream where
parseJSON = withObject "LogStream" $ \o -> LogStream
<$> o .:? "arn"
<*> o .:? "creationTime"
<*> o .:? "firstEventTimestamp"
<*> o .:? "lastEventTimestamp"
<*> o .:? "lastIngestionTime"
<*> o .:? "logStreamName"
<*> o .:? "storedBytes"
<*> o .:? "uploadSequenceToken"
instance ToJSON LogStream where
toJSON LogStream{..} = object
[ "logStreamName" .= _lsLogStreamName
, "creationTime" .= _lsCreationTime
, "firstEventTimestamp" .= _lsFirstEventTimestamp
, "lastEventTimestamp" .= _lsLastEventTimestamp
, "lastIngestionTime" .= _lsLastIngestionTime
, "uploadSequenceToken" .= _lsUploadSequenceToken
, "arn" .= _lsArn
, "storedBytes" .= _lsStoredBytes
]
data LogGroup = LogGroup
{ _lgArn :: Maybe Text
, _lgCreationTime :: Maybe Nat
, _lgLogGroupName :: Maybe Text
, _lgMetricFilterCount :: Maybe Int
, _lgRetentionInDays :: Maybe Int
, _lgStoredBytes :: Maybe Nat
} deriving (Eq, Ord, Read, Show)
-- | 'LogGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lgArn' @::@ 'Maybe' 'Text'
--
-- * 'lgCreationTime' @::@ 'Maybe' 'Natural'
--
-- * 'lgLogGroupName' @::@ 'Maybe' 'Text'
--
-- * 'lgMetricFilterCount' @::@ 'Maybe' 'Int'
--
-- * 'lgRetentionInDays' @::@ 'Maybe' 'Int'
--
-- * 'lgStoredBytes' @::@ 'Maybe' 'Natural'
--
logGroup :: LogGroup
logGroup = LogGroup
{ _lgLogGroupName = Nothing
, _lgCreationTime = Nothing
, _lgRetentionInDays = Nothing
, _lgMetricFilterCount = Nothing
, _lgArn = Nothing
, _lgStoredBytes = Nothing
}
lgArn :: Lens' LogGroup (Maybe Text)
lgArn = lens _lgArn (\s a -> s { _lgArn = a })
lgCreationTime :: Lens' LogGroup (Maybe Natural)
lgCreationTime = lens _lgCreationTime (\s a -> s { _lgCreationTime = a }) . mapping _Nat
lgLogGroupName :: Lens' LogGroup (Maybe Text)
lgLogGroupName = lens _lgLogGroupName (\s a -> s { _lgLogGroupName = a })
lgMetricFilterCount :: Lens' LogGroup (Maybe Int)
lgMetricFilterCount =
lens _lgMetricFilterCount (\s a -> s { _lgMetricFilterCount = a })
lgRetentionInDays :: Lens' LogGroup (Maybe Int)
lgRetentionInDays =
lens _lgRetentionInDays (\s a -> s { _lgRetentionInDays = a })
lgStoredBytes :: Lens' LogGroup (Maybe Natural)
lgStoredBytes = lens _lgStoredBytes (\s a -> s { _lgStoredBytes = a }) . mapping _Nat
instance FromJSON LogGroup where
parseJSON = withObject "LogGroup" $ \o -> LogGroup
<$> o .:? "arn"
<*> o .:? "creationTime"
<*> o .:? "logGroupName"
<*> o .:? "metricFilterCount"
<*> o .:? "retentionInDays"
<*> o .:? "storedBytes"
instance ToJSON LogGroup where
toJSON LogGroup{..} = object
[ "logGroupName" .= _lgLogGroupName
, "creationTime" .= _lgCreationTime
, "retentionInDays" .= _lgRetentionInDays
, "metricFilterCount" .= _lgMetricFilterCount
, "arn" .= _lgArn
, "storedBytes" .= _lgStoredBytes
]
data InputLogEvent = InputLogEvent
{ _ileMessage :: Text
, _ileTimestamp :: Nat
} deriving (Eq, Ord, Read, Show)
-- | 'InputLogEvent' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ileMessage' @::@ 'Text'
--
-- * 'ileTimestamp' @::@ 'Natural'
--
inputLogEvent :: Natural -- ^ 'ileTimestamp'
-> Text -- ^ 'ileMessage'
-> InputLogEvent
inputLogEvent p1 p2 = InputLogEvent
{ _ileTimestamp = withIso _Nat (const id) p1
, _ileMessage = p2
}
ileMessage :: Lens' InputLogEvent Text
ileMessage = lens _ileMessage (\s a -> s { _ileMessage = a })
ileTimestamp :: Lens' InputLogEvent Natural
ileTimestamp = lens _ileTimestamp (\s a -> s { _ileTimestamp = a }) . _Nat
instance FromJSON InputLogEvent where
parseJSON = withObject "InputLogEvent" $ \o -> InputLogEvent
<$> o .: "message"
<*> o .: "timestamp"
instance ToJSON InputLogEvent where
toJSON InputLogEvent{..} = object
[ "timestamp" .= _ileTimestamp
, "message" .= _ileMessage
]
data OutputLogEvent = OutputLogEvent
{ _oleIngestionTime :: Maybe Nat
, _oleMessage :: Maybe Text
, _oleTimestamp :: Maybe Nat
} deriving (Eq, Ord, Read, Show)
-- | 'OutputLogEvent' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'oleIngestionTime' @::@ 'Maybe' 'Natural'
--
-- * 'oleMessage' @::@ 'Maybe' 'Text'
--
-- * 'oleTimestamp' @::@ 'Maybe' 'Natural'
--
outputLogEvent :: OutputLogEvent
outputLogEvent = OutputLogEvent
{ _oleTimestamp = Nothing
, _oleMessage = Nothing
, _oleIngestionTime = Nothing
}
oleIngestionTime :: Lens' OutputLogEvent (Maybe Natural)
oleIngestionTime = lens _oleIngestionTime (\s a -> s { _oleIngestionTime = a }) . mapping _Nat
oleMessage :: Lens' OutputLogEvent (Maybe Text)
oleMessage = lens _oleMessage (\s a -> s { _oleMessage = a })
oleTimestamp :: Lens' OutputLogEvent (Maybe Natural)
oleTimestamp = lens _oleTimestamp (\s a -> s { _oleTimestamp = a }) . mapping _Nat
instance FromJSON OutputLogEvent where
parseJSON = withObject "OutputLogEvent" $ \o -> OutputLogEvent
<$> o .:? "ingestionTime"
<*> o .:? "message"
<*> o .:? "timestamp"
instance ToJSON OutputLogEvent where
toJSON OutputLogEvent{..} = object
[ "timestamp" .= _oleTimestamp
, "message" .= _oleMessage
, "ingestionTime" .= _oleIngestionTime
]
| dysinger/amazonka | amazonka-cloudwatch-logs/gen/Network/AWS/CloudWatchLogs/Types.hs | mpl-2.0 | 17,159 | 0 | 23 | 4,369 | 3,425 | 1,940 | 1,485 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Monitoring.Projects.MonitoredResourceDescriptors.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists monitored resource descriptors that match a filter. This method
-- does not require a Workspace.
--
-- /See:/ <https://cloud.google.com/monitoring/api/ Cloud Monitoring API Reference> for @monitoring.projects.monitoredResourceDescriptors.list@.
module Network.Google.Resource.Monitoring.Projects.MonitoredResourceDescriptors.List
(
-- * REST Resource
ProjectsMonitoredResourceDescriptorsListResource
-- * Creating a Request
, projectsMonitoredResourceDescriptorsList
, ProjectsMonitoredResourceDescriptorsList
-- * Request Lenses
, pmrdlXgafv
, pmrdlUploadProtocol
, pmrdlAccessToken
, pmrdlUploadType
, pmrdlName
, pmrdlFilter
, pmrdlPageToken
, pmrdlPageSize
, pmrdlCallback
) where
import Network.Google.Monitoring.Types
import Network.Google.Prelude
-- | A resource alias for @monitoring.projects.monitoredResourceDescriptors.list@ method which the
-- 'ProjectsMonitoredResourceDescriptorsList' request conforms to.
type ProjectsMonitoredResourceDescriptorsListResource
=
"v3" :>
Capture "name" Text :>
"monitoredResourceDescriptors" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON]
ListMonitoredResourceDescriptorsResponse
-- | Lists monitored resource descriptors that match a filter. This method
-- does not require a Workspace.
--
-- /See:/ 'projectsMonitoredResourceDescriptorsList' smart constructor.
data ProjectsMonitoredResourceDescriptorsList =
ProjectsMonitoredResourceDescriptorsList'
{ _pmrdlXgafv :: !(Maybe Xgafv)
, _pmrdlUploadProtocol :: !(Maybe Text)
, _pmrdlAccessToken :: !(Maybe Text)
, _pmrdlUploadType :: !(Maybe Text)
, _pmrdlName :: !Text
, _pmrdlFilter :: !(Maybe Text)
, _pmrdlPageToken :: !(Maybe Text)
, _pmrdlPageSize :: !(Maybe (Textual Int32))
, _pmrdlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsMonitoredResourceDescriptorsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pmrdlXgafv'
--
-- * 'pmrdlUploadProtocol'
--
-- * 'pmrdlAccessToken'
--
-- * 'pmrdlUploadType'
--
-- * 'pmrdlName'
--
-- * 'pmrdlFilter'
--
-- * 'pmrdlPageToken'
--
-- * 'pmrdlPageSize'
--
-- * 'pmrdlCallback'
projectsMonitoredResourceDescriptorsList
:: Text -- ^ 'pmrdlName'
-> ProjectsMonitoredResourceDescriptorsList
projectsMonitoredResourceDescriptorsList pPmrdlName_ =
ProjectsMonitoredResourceDescriptorsList'
{ _pmrdlXgafv = Nothing
, _pmrdlUploadProtocol = Nothing
, _pmrdlAccessToken = Nothing
, _pmrdlUploadType = Nothing
, _pmrdlName = pPmrdlName_
, _pmrdlFilter = Nothing
, _pmrdlPageToken = Nothing
, _pmrdlPageSize = Nothing
, _pmrdlCallback = Nothing
}
-- | V1 error format.
pmrdlXgafv :: Lens' ProjectsMonitoredResourceDescriptorsList (Maybe Xgafv)
pmrdlXgafv
= lens _pmrdlXgafv (\ s a -> s{_pmrdlXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pmrdlUploadProtocol :: Lens' ProjectsMonitoredResourceDescriptorsList (Maybe Text)
pmrdlUploadProtocol
= lens _pmrdlUploadProtocol
(\ s a -> s{_pmrdlUploadProtocol = a})
-- | OAuth access token.
pmrdlAccessToken :: Lens' ProjectsMonitoredResourceDescriptorsList (Maybe Text)
pmrdlAccessToken
= lens _pmrdlAccessToken
(\ s a -> s{_pmrdlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pmrdlUploadType :: Lens' ProjectsMonitoredResourceDescriptorsList (Maybe Text)
pmrdlUploadType
= lens _pmrdlUploadType
(\ s a -> s{_pmrdlUploadType = a})
-- | Required. The project
-- (https:\/\/cloud.google.com\/monitoring\/api\/v3#project_name) on which
-- to execute the request. The format is: projects\/[PROJECT_ID_OR_NUMBER]
pmrdlName :: Lens' ProjectsMonitoredResourceDescriptorsList Text
pmrdlName
= lens _pmrdlName (\ s a -> s{_pmrdlName = a})
-- | An optional filter
-- (https:\/\/cloud.google.com\/monitoring\/api\/v3\/filters) describing
-- the descriptors to be returned. The filter can reference the
-- descriptor\'s type and labels. For example, the following filter returns
-- only Google Compute Engine descriptors that have an id label:
-- resource.type = starts_with(\"gce_\") AND resource.label:id
pmrdlFilter :: Lens' ProjectsMonitoredResourceDescriptorsList (Maybe Text)
pmrdlFilter
= lens _pmrdlFilter (\ s a -> s{_pmrdlFilter = a})
-- | If this field is not empty then it must contain the nextPageToken value
-- returned by a previous call to this method. Using this field causes the
-- method to return additional results from the previous method call.
pmrdlPageToken :: Lens' ProjectsMonitoredResourceDescriptorsList (Maybe Text)
pmrdlPageToken
= lens _pmrdlPageToken
(\ s a -> s{_pmrdlPageToken = a})
-- | A positive number that is the maximum number of results to return.
pmrdlPageSize :: Lens' ProjectsMonitoredResourceDescriptorsList (Maybe Int32)
pmrdlPageSize
= lens _pmrdlPageSize
(\ s a -> s{_pmrdlPageSize = a})
. mapping _Coerce
-- | JSONP
pmrdlCallback :: Lens' ProjectsMonitoredResourceDescriptorsList (Maybe Text)
pmrdlCallback
= lens _pmrdlCallback
(\ s a -> s{_pmrdlCallback = a})
instance GoogleRequest
ProjectsMonitoredResourceDescriptorsList
where
type Rs ProjectsMonitoredResourceDescriptorsList =
ListMonitoredResourceDescriptorsResponse
type Scopes ProjectsMonitoredResourceDescriptorsList
=
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring",
"https://www.googleapis.com/auth/monitoring.read",
"https://www.googleapis.com/auth/monitoring.write"]
requestClient
ProjectsMonitoredResourceDescriptorsList'{..}
= go _pmrdlName _pmrdlXgafv _pmrdlUploadProtocol
_pmrdlAccessToken
_pmrdlUploadType
_pmrdlFilter
_pmrdlPageToken
_pmrdlPageSize
_pmrdlCallback
(Just AltJSON)
monitoringService
where go
= buildClient
(Proxy ::
Proxy
ProjectsMonitoredResourceDescriptorsListResource)
mempty
| brendanhay/gogol | gogol-monitoring/gen/Network/Google/Resource/Monitoring/Projects/MonitoredResourceDescriptors/List.hs | mpl-2.0 | 7,694 | 0 | 19 | 1,705 | 978 | 569 | 409 | 147 | 1 |
module Core.Http where
import qualified Network.Wreq as Wreq
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Char8 as BS
import Control.Lens ((^.))
data Version = Version {
major :: {-# UNPACK #-} !Int,
minor :: {-# UNPACK #-} !Int
} deriving (Show)
fetch :: BS.ByteString -> IO BS.ByteString
fetch url = do
response <- Wreq.get $ BS.unpack url
return $ BS.concat $ BSL.toChunks (response ^. Wreq.responseBody)
| inq/manicure | src/Core/Http.hs | agpl-3.0 | 494 | 0 | 11 | 112 | 146 | 85 | 61 | 13 | 1 |
module Chapter2.Section2.Example where
| wangyixiang/beginninghaskell | chapter2/src/Chapter2/Section2/Example.hs | unlicense | 41 | 2 | 3 | 5 | 9 | 6 | 3 | 1 | 0 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module HepMC.Parse
( module X
, tuple, vector, eol
, hmcvers, hmcend
, xyzt
) where
import Control.Applicative as X (many, (<|>))
import Control.Applicative (liftA2)
import Control.Monad as X (void)
import Data.Attoparsec.ByteString.Char8 as X hiding (parse)
import Data.ByteString (ByteString)
import Data.HEP.LorentzVector
import Data.Vector as X (Vector)
import Data.Vector
tuple :: Applicative f => f a -> f b -> f (a, b)
tuple = liftA2 (,)
vector :: Parser a -> Parser (Vector a)
vector p = do
n <- decimal <* skipSpace
replicateM n p
eol :: Char -> Bool
eol = isEndOfLine . toEnum . fromEnum
hmcvers :: Parser (Int, Int, Int)
hmcvers = do
skipSpace
string "HepMC::Version" *> skipSpace
x <- decimal <* char '.'
y <- decimal <* char '.'
z <- decimal <* skipSpace
string "HepMC::IO_GenEvent-START_EVENT_LISTING" *> skipSpace
return (x, y, z)
hmcend :: Parser ByteString
hmcend = do
_ <- string "HepMC::IO_GenEvent-END_EVENT_LISTING"
skipSpace
return "end"
xyzt :: Parser XYZT
xyzt =
XYZT
<$> double <* skipSpace
<*> double <* skipSpace
<*> double <* skipSpace
<*> double
| cspollard/HHepMC | src/HepMC/Parse.hs | apache-2.0 | 1,380 | 0 | 11 | 411 | 407 | 219 | 188 | 44 | 1 |
{-# language CPP #-}
-- No documentation found for Chapter "ViewStateFlagBits"
module OpenXR.Core10.Enums.ViewStateFlagBits ( ViewStateFlags
, ViewStateFlagBits( VIEW_STATE_ORIENTATION_VALID_BIT
, VIEW_STATE_POSITION_VALID_BIT
, VIEW_STATE_ORIENTATION_TRACKED_BIT
, VIEW_STATE_POSITION_TRACKED_BIT
, ..
)
) where
import OpenXR.Internal.Utils (enumReadPrec)
import OpenXR.Internal.Utils (enumShowsPrec)
import GHC.Show (showString)
import Numeric (showHex)
import OpenXR.Zero (Zero)
import Data.Bits (Bits)
import Data.Bits (FiniteBits)
import Foreign.Storable (Storable)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
import OpenXR.Core10.FundamentalTypes (Flags64)
type ViewStateFlags = ViewStateFlagBits
-- No documentation found for TopLevel "XrViewStateFlagBits"
newtype ViewStateFlagBits = ViewStateFlagBits Flags64
deriving newtype (Eq, Ord, Storable, Zero, Bits, FiniteBits)
-- No documentation found for Nested "XrViewStateFlagBits" "XR_VIEW_STATE_ORIENTATION_VALID_BIT"
pattern VIEW_STATE_ORIENTATION_VALID_BIT = ViewStateFlagBits 0x0000000000000001
-- No documentation found for Nested "XrViewStateFlagBits" "XR_VIEW_STATE_POSITION_VALID_BIT"
pattern VIEW_STATE_POSITION_VALID_BIT = ViewStateFlagBits 0x0000000000000002
-- No documentation found for Nested "XrViewStateFlagBits" "XR_VIEW_STATE_ORIENTATION_TRACKED_BIT"
pattern VIEW_STATE_ORIENTATION_TRACKED_BIT = ViewStateFlagBits 0x0000000000000004
-- No documentation found for Nested "XrViewStateFlagBits" "XR_VIEW_STATE_POSITION_TRACKED_BIT"
pattern VIEW_STATE_POSITION_TRACKED_BIT = ViewStateFlagBits 0x0000000000000008
conNameViewStateFlagBits :: String
conNameViewStateFlagBits = "ViewStateFlagBits"
enumPrefixViewStateFlagBits :: String
enumPrefixViewStateFlagBits = "VIEW_STATE_"
showTableViewStateFlagBits :: [(ViewStateFlagBits, String)]
showTableViewStateFlagBits =
[ (VIEW_STATE_ORIENTATION_VALID_BIT , "ORIENTATION_VALID_BIT")
, (VIEW_STATE_POSITION_VALID_BIT , "POSITION_VALID_BIT")
, (VIEW_STATE_ORIENTATION_TRACKED_BIT, "ORIENTATION_TRACKED_BIT")
, (VIEW_STATE_POSITION_TRACKED_BIT , "POSITION_TRACKED_BIT")
]
instance Show ViewStateFlagBits where
showsPrec = enumShowsPrec enumPrefixViewStateFlagBits
showTableViewStateFlagBits
conNameViewStateFlagBits
(\(ViewStateFlagBits x) -> x)
(\x -> showString "0x" . showHex x)
instance Read ViewStateFlagBits where
readPrec =
enumReadPrec enumPrefixViewStateFlagBits showTableViewStateFlagBits conNameViewStateFlagBits ViewStateFlagBits
| expipiplus1/vulkan | openxr/src/OpenXR/Core10/Enums/ViewStateFlagBits.hs | bsd-3-clause | 3,054 | 1 | 10 | 780 | 395 | 235 | 160 | -1 | -1 |
--
-- @file
--
-- @brief Normalizes RegexTypes
--
-- Normalizes a RegexType by applying commutativity of intersection.
--
-- @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
--
{-# LANGUAGE LambdaCase #-}
module Elektra.Normalize (normalize) where
import Control.Monad (foldM)
import Data.Maybe (maybe, fromJust, fromMaybe)
import Data.Either (either)
import Data.List (nub, sortBy)
import Data.Function (on)
import Elektra.Types
import qualified FiniteAutomata as FA
-- Set intersection is associative and commutative
-- Thus we can intersect all concrete regexes in advance
-- and leave the remaining intersections in the order that
-- variable intersections are first, then a concrete regex
-- follows (or another variable)
normalize :: RegexType -> IO RegexType
normalize i@(RegexIntersection _ _) = either return fold $ collect i ([], [])
where
fold (ts, ss) = do
b <- (\(Right r) -> r) <$> FA.compile ".*"
e <- FA.makeBasic FA.Empty
s <- case length ss of
0 -> return Nothing
1 -> return . Just $ head ss
_ -> let ss' = map (\(Regex _ r) -> r) ss in do
s' <- foldM (FA.intersect) (head ss') (tail ss')
FA.minimize s'
isEmpty <- (\case
x | x <= 0 -> False
| otherwise -> True) <$> FA.equals e s'
if isEmpty then return $ Just EmptyRegex else Just . maybe EmptyRegex (flip Regex s') . rightToMaybe <$> FA.asRegexp s'
return $ finalize (sortBy (compare `on` \(RegexVar v) -> v) ts, s)
finalize (_, Just EmptyRegex) = EmptyRegex
finalize ([], Just sr) = sr
finalize (ts, Nothing) = foldTyVars ts
finalize (ts, Just sr) = RegexIntersection (foldTyVars ts) sr
foldTyVars [] = EmptyRegex
foldTyVars [x] = x
foldTyVars (t:ts) = RegexIntersection t (foldTyVars ts)
collect (RegexIntersection l r) p = collect r =<< collect l p
collect r@(Regex _ _) (ts, ss) = Right (ts, r : ss)
collect v@(RegexVar _) (ts, ss) = Right (v : ts, ss)
collect EmptyRegex _ = Left EmptyRegex
normalize r = return r
fromRight :: Either a b -> b
fromRight (Right b) = b
fromRight _ = error "fromRight without right value"
| e1528532/libelektra | src/libs/typesystem/specelektra/Elektra/Normalize.hs | bsd-3-clause | 2,296 | 0 | 26 | 619 | 764 | 399 | 365 | 40 | 12 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
module Youtube.Channel
( getChannelId
) where
import Network.Wreq
import Control.Lens
import GHC.Generics
import Data.Aeson
import Data.Maybe
import Prelude hiding (id)
import qualified Data.Text as T
data ChannelItem = ChannelItem {
id :: String
} deriving (Show, Generic)
data ChannelItemArray = ChannelItemArray {
items :: [ChannelItem]
} deriving (Show, Generic)
instance FromJSON ChannelItem
instance FromJSON ChannelItemArray
-- todo cache id with name into txt
getChannelId :: String -> IO (Maybe String)
getChannelId channelName = do
let opts = defaults & param "part" .~ ["id"]
& param "forUsername" .~ [T.pack channelName]
& param "fields" .~ ["items/id"]
& param "key" .~ ["AIzaSyClRz-XU6gAt4h-_JRdIA2UIQn8TroxTIk"]
r <- asJSON =<< getWith opts "https://www.googleapis.com/youtube/v3/channels"
let is = items $ (r ^. responseBody)
if length is == 1
then
return (Just ((id.head) is))
else
return (Nothing) | kelvinlouis/spotell | src/Youtube/Channel.hs | bsd-3-clause | 1,082 | 0 | 18 | 248 | 300 | 160 | 140 | 29 | 2 |
module Utils
( isqrt
, numFactors
, dataFile
) where
import Paths_project_euler
isqrt
:: Integral i
=> i -> i
isqrt = floor . sqrt . fromIntegral
numFactors :: Int -> Int
numFactors x =
let top = isqrt x
nonSquareFactors = [i | i <- [1 .. top], i < top, x `mod` i == 0]
addSquareFactor y =
if y `mod` top == 0
then y + 1
else y
in addSquareFactor . (* 2) . length $ nonSquareFactors
dataFile :: String -> IO String
dataFile file = do
fullPath <- getDataFileName $ "data/" ++ file ++ ".txt"
readFile fullPath
| anup-2s/project-euler | src/Utils.hs | bsd-3-clause | 572 | 0 | 12 | 166 | 213 | 114 | 99 | 22 | 2 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE TypeOperators #-}
module Spanout.Gameplay (game) where
import Prelude hiding (id, (.))
import Spanout.Common
import Spanout.Graphics
import Spanout.Level
import qualified Spanout.Wire as Wire
import Control.Applicative
import Control.Arrow
import Control.Category
import Control.Lens
import Control.Monad
import Data.Either
import Data.Maybe
import Data.Monoid
import qualified Data.Set as Set
import qualified Graphics.Gloss.Interface.IO.Game as Gloss
import Linear
-- The reactive view of the game
game :: a ->> Gloss.Picture
game = Wire.bindW gsInit gameBegin
where
gsInit = do
bricks <- generateBricks
return GameState
{ _gsBall = ballInit
, _gsBatX = 0
, _gsBricks = bricks
}
-- Displays the level and a countdown before the actual gameplay
gameBegin :: GameState -> a ->> Gloss.Picture
gameBegin gsInit = Wire.switch $ proc _ -> do
batX <- view _x ^<< mousePos -< ()
time <- Wire.time -< ()
let
gs = set gsBatX batX gsInit
remainingTime = countdownTime - time
returnA -< if
| remainingTime > 0 -> Right $ gamePic gs <> countdownPic remainingTime
| otherwise -> Left $ gameLevel gs
-- Gameplay from an initial game state
gameLevel :: GameState -> a ->> Gloss.Picture
gameLevel gsInit = Wire.switch $ proc _ -> do
batX <- view _x ^<< mousePos -< ()
rec
-- Binding previous values
ball' <- Wire.delay $ view gsBall gsInit -< ball
bricks' <- Wire.delay $ view gsBricks gsInit -< bricks
-- Current position
pos <- Wire.accum (\dt p v -> p + dt *^ v) $ view (gsBall . ballPos) gsInit
-< view ballVel ball'
-- Collision and its normal
let
edgeNormal = ballEdgeNormal pos
batNormal = ballBatNormal batX pos
ballBrickColl = ballBrickCollision (ball' {_ballPos = pos}) bricks'
brickNormals = fst <$> ballBrickColl
normal = mfilter (faceAway $ view ballVel ball') . mergeNormalEvents $
maybeToList edgeNormal
++ maybeToList batNormal
++ fromMaybe [] brickNormals
-- Current velocity
vel <- Wire.accumE reflect $ view (gsBall . ballVel) gsInit -< normal
-- Binding current values
let
ball = Ball pos vel
bricks = fromMaybe bricks' (snd <$> ballBrickColl)
let gs = GameState {_gsBall = ball, _gsBatX = batX, _gsBricks = bricks}
spacePressed <- keyPressed $ Gloss.SpecialKey Gloss.KeySpace -< ()
returnA -< if
| spacePressed ->
Left game
| null bricks ->
Left $ levelEnd gs
| view (ballPos . _y) ball <= -screenBoundY - ballRadius ->
Left $ gameBegin gsInit
| otherwise ->
Right $ gamePic gs
-- Displays the final game state for some time after the end of the level
levelEnd :: GameState -> a ->> Gloss.Picture
levelEnd gs = Wire.switch $ Wire.forThen levelEndTime game . pure pic
where
pic = gamePic gs <> levelEndPic
-- The sum of zero or more normals
mergeNormalEvents :: (Floating a, Epsilon a) => [V2 a] -> Maybe (V2 a)
mergeNormalEvents [] = Nothing
mergeNormalEvents normals = Just . normalize $ sum normals
-- Collision between the ball and the screen edges
ballEdgeNormal :: V2 Float -> Maybe (V2 Float)
ballEdgeNormal (V2 px py)
| px <= -screenBoundX + ballRadius = Just $ unit _x
| px >= screenBoundX - ballRadius = Just $ -unit _x
| py >= screenBoundY - ballRadius = Just $ -unit _y
| otherwise = Nothing
-- Collision between the ball and the bat
ballBatNormal :: Float -> V2 Float -> Maybe (V2 Float)
ballBatNormal batX (V2 px py)
| bxl && bxr && by = Just $ batNormalAt px batX
| otherwise = Nothing
where
bxl = px >= batX - batWidth / 2
bxr = px <= batX + batWidth / 2
by = py <= batPositionY + batHeight / 2 + ballRadius
-- Collision between the ball and the bricks.
-- Calculates the resulting normals and the remaining bricks.
ballBrickCollision :: Ball -> [Brick] -> Maybe ([V2 Float], [Brick])
ballBrickCollision ball bricks =
case collisionNormals of
[] -> Nothing
_ -> Just (collisionNormals, remBricks)
where
check brick =
case ballBrickNormal brick ball of
Just normal -> Right normal
_ -> Left brick
(remBricks, collisionNormals) = partitionEithers . map check $ bricks
-- Collision between the ball and a brick
ballBrickNormal :: Brick -> Ball -> Maybe (V2 Float)
ballBrickNormal (Brick pos (Circle radius)) (Ball bpos _)
| hit = Just . normalize $ bpos - pos
| otherwise = Nothing
where
hit = distance bpos pos <= radius + ballRadius
ballBrickNormal (Brick pos@(V2 x y) (Rectangle width height)) (Ball bpos bvel)
| tooFar = Nothing
| hitX = Just normalX
| hitY = Just normalY
| hitCorner = listToMaybe . filter (faceAway bvel) $ [normalX, normalY]
| otherwise = Nothing
where
dist = bpos - pos
V2 distAbsX distAbsY = abs <$> dist
V2 ballX ballY = bpos
tooFar = distAbsX > width / 2 + ballRadius
|| distAbsY > height / 2 + ballRadius
hitX = distAbsX <= width / 2
hitY = distAbsY <= height / 2
hitCorner = quadrance (V2 (distAbsX - width / 2) (distAbsY - height / 2))
<= ballRadius ^ (2 :: Int)
normalX = signum (ballY - y) *^ unit _y
normalY = signum (ballX - x) *^ unit _x
-- The normal at a point of the bat
batNormalAt :: Float -> Float -> V2 Float
batNormalAt x batX = perp . angle $ batSpread * relX
where
relX = (batX - x) / (batWidth / 2)
-- Checks if two vectors face away from each other
faceAway :: (Num a, Ord a) => V2 a -> V2 a -> Bool
faceAway u v = u `dot` v < 0
-- The reflection of a vector based on a normal
reflect :: Num a => V2 a -> V2 a -> V2 a
reflect v normal = v - (2 * v `dot` normal) *^ normal
-- The reactive position of the mouse
mousePos :: a ->> V2 Float
mousePos = Wire.constM $ view envMouse
-- The reactive state of a keyboard button
keyPressed :: Gloss.Key -> a ->> Bool
keyPressed key = Wire.constM $ views envKeys (Set.member key)
| vtan/spanout | src/Spanout/Gameplay.hs | bsd-3-clause | 6,047 | 4 | 21 | 1,484 | 1,973 | 1,002 | 971 | 132 | 4 |
{-# OPTIONS_GHC -fno-warn-orphans -fsimpl-tick-factor=500 #-}
module Macro.PkgCereal where
import Macro.Types
import Data.Serialize as Cereal
import Data.ByteString.Lazy as BS
serialise :: [GenericPackageDescription] -> BS.ByteString
serialise pkgs = Cereal.encodeLazy pkgs
deserialise :: BS.ByteString -> [GenericPackageDescription]
deserialise = (\(Right x) -> x) . Cereal.decodeLazy
deserialiseNull :: BS.ByteString -> ()
deserialiseNull bs =
case Cereal.runGetLazy decodeListNull bs of
Right () -> ()
where
decodeListNull = do
n <- get :: Get Int
go n
go 0 = return ()
go i = do x <- get :: Get GenericPackageDescription
x `seq` go (i-1)
instance Serialize Version
instance Serialize PackageName
instance Serialize PackageId
instance Serialize VersionRange
instance Serialize Dependency
instance Serialize CompilerFlavor
instance Serialize License
instance Serialize SourceRepo
instance Serialize RepoKind
instance Serialize RepoType
instance Serialize BuildType
instance Serialize Library
instance Serialize Executable
instance Serialize TestSuite
instance Serialize TestSuiteInterface
instance Serialize TestType
instance Serialize Benchmark
instance Serialize BenchmarkInterface
instance Serialize BenchmarkType
instance Serialize BuildInfo
instance Serialize ModuleName
instance Serialize Language
instance Serialize Extension
instance Serialize KnownExtension
instance Serialize PackageDescription
instance Serialize OS
instance Serialize Arch
instance Serialize Flag
instance Serialize FlagName
instance (Serialize a, Serialize b, Serialize c) => Serialize (CondTree a b c)
instance Serialize ConfVar
instance Serialize a => Serialize (Condition a)
instance Serialize GenericPackageDescription
| arianvp/binary-serialise-cbor | bench/Macro/PkgCereal.hs | bsd-3-clause | 1,759 | 0 | 12 | 257 | 492 | 236 | 256 | 52 | 2 |
module Data.SequentialIndex.Open
(
SequentialIndex
, mantissa
, exponent
, sequentialIndex
, tryFromBools
, toClosed
, fromClosed
, root
, leftChild
, rightChild
, parent
, prefixBits
, toByteString
, fromByteString
)
where
import Control.Monad
import Data.Bits
import Data.Maybe
import Prelude hiding (exponent)
import qualified Data.ByteString as B
import qualified Data.SequentialIndex as Closed
newtype SequentialIndex = OSI Closed.SequentialIndex
deriving (Eq, Ord)
mantissa :: SequentialIndex -> Integer
mantissa = Closed.mantissa . toClosed
exponent :: SequentialIndex -> Int
exponent = Closed.exponent . toClosed
sequentialIndex :: Int -> Integer -> SequentialIndex
sequentialIndex eb me = OSI $ Closed.prefixBits eb me Closed.one
tryFromBools :: [Bool] -> Maybe SequentialIndex
tryFromBools = fromClosed <=< Closed.tryFromBools
toClosed :: SequentialIndex -> Closed.SequentialIndex
toClosed (OSI si) = si
fromClosed :: Closed.SequentialIndex -> Maybe SequentialIndex
fromClosed si = case () of
_ | si == Closed.zero -> Nothing
| si == Closed.one -> Nothing
| otherwise -> Just $ OSI si
root :: SequentialIndex
root = OSI Closed.root
leftChild :: SequentialIndex -> SequentialIndex
leftChild = OSI . fromJust . Closed.leftChild . toClosed
rightChild :: SequentialIndex -> SequentialIndex
rightChild = OSI . fromJust . Closed.rightChild . toClosed
parent :: SequentialIndex -> Maybe SequentialIndex
parent = fmap OSI . Closed.parent . toClosed
prefixBits :: Int -> Integer -> SequentialIndex -> SequentialIndex
prefixBits eb mb = OSI . Closed.prefixBits eb mb . toClosed
toByteString :: SequentialIndex -> B.ByteString
toByteString = Closed.toByteString . toClosed
fromByteString :: B.ByteString -> Maybe SequentialIndex
fromByteString = fromClosed <=< Closed.fromByteString
instance Show SequentialIndex where
show si = '*' : map (\i -> if testBit m i then 'R' else 'L') [e - 2, e - 3 .. 1]
where m = mantissa si
e = exponent si
| aristidb/sequential-index | Data/SequentialIndex/Open.hs | bsd-3-clause | 2,111 | 0 | 12 | 451 | 589 | 319 | 270 | 57 | 1 |
module Data.Vhd.Bitmap
( Bitmap (..)
, bitmapGet
, bitmapSet
, bitmapSetRange
, bitmapClear
) where
import Data.Bits
import Data.Word
import Foreign.Ptr
import Foreign.Storable
data Bitmap = Bitmap (Ptr Word8)
bitmapGet :: Bitmap -> Int -> IO Bool
bitmapGet (Bitmap ptr) n = test `fmap` peekByteOff ptr offset
where
test :: Word8 -> Bool
test = flip testBit (7 - bit)
(offset, bit) = n `divMod` 8
bitmapModify :: Bitmap -> Int -> (Int -> Word8 -> Word8) -> IO ()
bitmapModify (Bitmap bptr) n f = peek ptr >>= poke ptr . f (7 - bit)
where
ptr = bptr `plusPtr` offset
(offset, bit) = n `divMod` 8
bitmapSet :: Bitmap -> Int -> IO ()
bitmapSet bitmap n = bitmapModify bitmap n (flip setBit)
bitmapSetRange :: Bitmap -> Int -> Int -> IO ()
bitmapSetRange bitmap start end
| start < end = bitmapSet bitmap start >> bitmapSetRange bitmap (start + 1) end
| otherwise = return ()
bitmapClear :: Bitmap -> Int -> IO ()
bitmapClear bitmap n = bitmapModify bitmap n (flip clearBit)
| jonathanknowles/hs-vhd | Data/Vhd/Bitmap.hs | bsd-3-clause | 1,000 | 4 | 10 | 205 | 425 | 223 | 202 | 28 | 1 |
module Main where
import Test.Framework (defaultMain, testGroup)
import qualified Tests.Database.Cassandra.CQL.Protocol as Protocol
import qualified Tests.Database.Cassandra.CQL.Protocol.Properties as Properties
main :: IO ()
main = defaultMain tests
where
tests =
[ testGroup "Tests.Database.Cassandra.CQL.Protocol" Protocol.tests
, testGroup "Tests.Database.Cassandra.CQL.Protocol.Properties" Properties.tests
]
| romanb/cassandra-cql-protocol | test/TestSuite.hs | bsd-3-clause | 446 | 0 | 9 | 69 | 85 | 53 | 32 | 9 | 1 |
-- | Checks for a `Square` being attacked by one of the players.
--
-- https://chessprogramming.wikispaces.com/Square+Attacked+By
module Chess.Board.Attacks
( isAttacked
, attackedFromBB
, inCheck
, inCheckWithNoFriendly
) where
import Data.Monoid
import Chess.Board.Board
import Chess.Magic
import Data.BitBoard
import Data.ChessTypes
import qualified Data.ChessTypes as T (opponent)
import Data.Square
------------------------------------------------------------------------------
-- | are any of the given player's pieces attacking the given square?
--
-- Boolean test with sliding piece occupancy testing (magic look up).
isAttacked :: Board -> Colour -> Square -> Bool
isAttacked b c s = isAttackedWithOccupancy b (occupancy b) c s
------------------------------------------------------------------------------
-- | is the specified player in check?
inCheck :: Board -> Colour -> Bool
inCheck b c = let kP = head $ toList $ piecesOf b c King
in isAttacked b (T.opponent c) kP
------------------------------------------------------------------------------
-- | is the specified player in check with the friendly pieces removed?
inCheckWithNoFriendly :: Board -> Colour -> Bool
inCheckWithNoFriendly b c =
let occ = piecesByColour b (T.opponent c)
kP = head $ toList $ piecesOf b c King
in isAttackedWithOccupancy b occ (T.opponent c) kP
------------------------------------------------------------------------------
-- Short circuit the Boolean condition.
isAttackedWithOccupancy :: Board -> BitBoard -> Colour -> Square -> Bool
isAttackedWithOccupancy b occ c s =
any (/= mempty)
$ attackList [Pawn, Knight, King, Queen, Bishop, Rook] b occ c s
------------------------------------------------------------------------------
-- | Bitboard with the position of the attacking pieces set. Occupancy can be
-- specified, ie. we can remove pieces from the board.
attackedFromBB :: Board -> BitBoard -> Colour -> Square -> BitBoard
attackedFromBB b occ c s = foldr1 (<>)
$ attackList [ Queen, Bishop, Rook, Knight, King, Pawn ] b occ c s
------------------------------------------------------------------------------
attackList
:: [PieceType]
-> Board
-> BitBoard
-> Colour
-> Square
-> [BitBoard]
attackList l b occ c s =
[ attackBitBoard pt s occ c .&. piecesOf b c pt | pt <- l ]
------------------------------------------------------------------------------
attackBitBoard :: PieceType -> Square -> BitBoard -> Colour -> BitBoard
attackBitBoard Bishop pos occ _ =
{-# SCC attackBitBoardBishop #-} magic Bishop pos occ
attackBitBoard Rook pos occ _ =
{-# SCC attackBitBoardRook #-} magic Rook pos occ
attackBitBoard Queen pos occ c =
{-# SCC attackBitBoardQueen #-}
attackBitBoard Bishop pos occ c <> attackBitBoard Rook pos occ c
attackBitBoard Knight pos _ _ =
{-# SCC attackBitBoardKnight #-} knightAttackBB pos
attackBitBoard King pos _ _ =
{-# SCC attackBitBoardKing #-} kingAttackBB pos
attackBitBoard Pawn pos _ c =
{-# SCC attackBitBoardPawn #-} pawnAttackBB pos (T.opponent c)
| phaul/chess | Chess/Board/Attacks.hs | bsd-3-clause | 3,121 | 0 | 12 | 545 | 667 | 358 | 309 | -1 | -1 |
module Control.ConstraintClasses.KeyZip
(
-- * Constraint KeyZip
CKeyZip (..)
) where
import Control.ConstraintClasses.Domain
import Control.ConstraintClasses.Key
import Control.ConstraintClasses.KeyFunctor
import Control.ConstraintClasses.Zip
import Data.Key
-- base
import Data.Functor.Product
import Data.Functor.Sum
import Data.Functor.Compose
-- vector
import qualified Data.Vector as Vector
import qualified Data.Vector.Storable as VectorStorable
import qualified Data.Vector.Unboxed as VectorUnboxed
--------------------------------------------------------------------------------
-- CLASS
--------------------------------------------------------------------------------
-- | Equivalent to the @Zip@ class.
class (CKeyFunctor f, CZip f) => CKeyZip f where
_izipWith ::
(Dom f a, Dom f b, Dom f c) =>
(CKey f -> a -> b -> c) -> f a -> f b -> f c
--------------------------------------------------------------------------------
-- INSTANCES
--------------------------------------------------------------------------------
-- base
-- vector
instance CKeyZip VectorStorable.Vector where
_izipWith = VectorStorable.izipWith
{-# INLINE _izipWith #-}
instance CKeyZip VectorUnboxed.Vector where
_izipWith = VectorUnboxed.izipWith
{-# INLINE _izipWith #-}
| guaraqe/constraint-classes | src/Control/ConstraintClasses/KeyZip.hs | bsd-3-clause | 1,293 | 0 | 12 | 163 | 232 | 141 | 91 | 24 | 0 |
module Drones where
import qualified Test.HUnit as H
import NPNTool.PetriNet
import NPNTool.PTConstr
import NPNTool.NPNConstr (arcExpr, liftPTC, liftElemNet, addElemNet, NPNConstrM)
import qualified NPNTool.NPNConstr as NPC
import NPNTool.Graphviz
import NPNTool.Bisimilarity
import NPNTool.Liveness
import NPNTool.AlphaTrail
import NPNTool.NPNet
import NPNTool.CTL
import Control.Monad
import Data.List
import Data.Maybe
data DroneLabels = Leave | Orbit | Attack
deriving (Show,Eq,Ord)
data V = X | Y | Z
deriving (Show,Ord,Eq)
drone :: PTConstrM DroneLabels ()
drone = do
[station,air,searching,orbiting,attacking,fin,avoid] <- replicateM 7 mkPlace
[leave,orbit,startSearch,start,finish,returnBack,tooClose,continue] <- replicateM 8 mkTrans
label leave Leave
label orbit Orbit
label start Attack
arc station leave
arc leave air
arc air startSearch
arc startSearch searching
arc searching orbit
arc orbit orbiting
arc orbiting tooClose
arc tooClose avoid
arc avoid continue
arc continue orbiting
arc orbiting start
arc start attacking
arc attacking finish
arc finish fin
arc fin returnBack
arc returnBack station
mark station
return ()
x = Var X
y = Var Y
z = Var Z
droneSystem :: NPNConstrM DroneLabels V [PTPlace]
droneSystem = do
let n = 3
basePs <- replicateM n NPC.mkPlace
leaveTs <- replicateM n NPC.mkTrans
airPs <- replicateM n NPC.mkPlace
orbitTs <- replicateM n NPC.mkTrans
orbitingPs <- replicateM n NPC.mkPlace
attack <- NPC.mkTrans
finPs <- replicateM n NPC.mkPlace
retTs <- replicateM n NPC.mkTrans
drones <- replicateM n (NPC.liftElemNet drone)
NPC.label attack Attack
forM orbitTs (flip NPC.label Orbit)
forM leaveTs (flip NPC.label Leave)
forM_ (zip basePs drones) $ \(b,d) -> NPC.mark b (Right d)
forM_ (zip5 basePs leaveTs airPs orbitTs orbitingPs) $ \(b,l,a,o,orbiting) -> do
arcExpr b x l
arcExpr l x a
arcExpr a x o
arcExpr o x orbiting
forM_ (zip3 [x,y,z] orbitingPs finPs) $ \(v,orbiting,fin) -> do
arcExpr orbiting v attack
arcExpr attack v fin
forM_ (zip3 finPs retTs basePs) $ \(fin,ret,base) -> do
arcExpr fin x ret
arcExpr ret x base
return basePs
droneNet :: NPNet DroneLabels V Int
bases :: [PTPlace]
(bases,droneNet) = NPC.run (droneSystem) NPC.new
sn = net droneNet
ss = reachabilityGraph sn
((),droneElemNet, droneL) = runL drone new
(atN,atL) = alphaTrail droneNet 1
(nm,rg) = reachabilityGraph' atN
droneTest = H.TestCase $ do
H.assertBool "Normal agent liveness" $
isLive (reachabilityGraph droneElemNet) droneElemNet
H.assertBool "System net liveness" $
isLive ss sn
mapM_ (H.assertBool "Agent is m-bisimilar to the alpha-trail net"
. isJust
. isMBisim (droneElemNet,droneL)
. alphaTrail droneNet)
bases
return ()
droneTestXML = H.TestCase $ do
npn <- runConstr "./test/Drones.npnets"
-- [base,air,orbiting,fin] <- replicateM 4 NPC.mkPlace
-- [leave,orbit,attack,ret] <- replicateM 4 NPC.mkTrans
-- arcExpr base x leave
-- arcExpr leave x air
-- arcExpr air x orbit
-- arcExpr orbit x orbiting
-- arcExpr orbiting x attack
-- arcExpr attack x fin
-- arcExpr fin x ret
-- arcExpr ret x base
-- NPC.label attack Attack
-- d1 <- NPC.liftElemNet drone
-- NPC.mark base (Right d1)
-- return [base]
-- if (null nodes) then do
-- trace "sim1" $ return ()
-- traceShow l $ return ()
-- traceShow m1 $ traceShow m2 $ return ()
-- else return ()
| co-dan/NPNTool | tests/Drones.hs | bsd-3-clause | 3,560 | 0 | 14 | 770 | 1,133 | 563 | 570 | -1 | -1 |
-- | The code that powers the searchbox.
module Guide.Search
(
SearchResult(..),
search,
)
where
import Imports
-- Text
import qualified Data.Text.All as T
-- Sets
import qualified Data.Set as S
import Guide.Types
import Guide.State
import Guide.Markdown
-- | A search result.
data SearchResult
-- | Category's title matches the query
= SRCategory Category
-- | Item's name matches the query
| SRItem Category Item
-- | Item's ecosystem matches the query
| SRItemEcosystem Category Item
deriving (Show, Generic)
{- | Find things matching a simple text query, and return results ranked by
importance. Categories are considered more important than items.
Currently 'search' doesn't do any fuzzy search whatsoever – only direct word
matches are considered. See 'match' for the description of the matching
algorithm.
-}
search :: Text -> GlobalState -> [SearchResult]
search query gs =
-- category titles
sortByRank [(SRCategory cat, rank)
| cat <- gs^.categories
, let rank = match query (cat^.title)
, rank > 0 ] ++
-- item names
sortByRank [(SRItem cat item, rank)
| cat <- gs^.categories
, item <- cat^.items
, let rank = match query (item^.name)
, rank > 0 ] ++
-- item ecosystems
sortByRank [(SRItemEcosystem cat item, rank)
| cat <- gs^.categories
, item <- cat^.items
, let rank = match query (item^.ecosystem.mdSource)
, rank > 0 ]
where
sortByRank :: [(a, Int)] -> [a]
sortByRank = map fst . sortOn (Down . snd)
{- | How many words in two strings match?
Words are defined as sequences of letters, digits and characters like “-”;
separators are everything else. Comparisons are case-insensitive.
-}
match :: Text -> Text -> Int
match a b = common (getWords a) (getWords b)
where
isWordPart c = isLetter c || isDigit c || c == '-'
getWords =
map T.toTitle .
filter (not . T.null) .
T.split (not . isWordPart)
-- | Find how many elements two lists have in common.
common :: Ord a => [a] -> [a] -> Int
common a b = S.size (S.intersection (S.fromList a) (S.fromList b))
| aelve/hslibs | src/Guide/Search.hs | bsd-3-clause | 2,257 | 0 | 15 | 617 | 558 | 302 | 256 | -1 | -1 |
{-
(c) The University of Glasgow, 2006
\section[HscTypes]{Types for the per-module compiler}
-}
{-# LANGUAGE CPP, ScopedTypeVariables #-}
-- | Types for the per-module compiler
module HscTypes (
-- * compilation state
HscEnv(..), hscEPS,
FinderCache, FindResult(..),
Target(..), TargetId(..), pprTarget, pprTargetId,
ModuleGraph, emptyMG,
HscStatus(..),
#ifdef GHCI
IServ(..),
#endif
-- * Hsc monad
Hsc(..), runHsc, runInteractiveHsc,
-- * Information about modules
ModDetails(..), emptyModDetails,
ModGuts(..), CgGuts(..), ForeignStubs(..), appendStubC,
ImportedMods, ImportedModsVal(..),
ModSummary(..), ms_imps, ms_mod_name, showModMsg, isBootSummary,
msHsFilePath, msHiFilePath, msObjFilePath,
SourceModified(..),
-- * Information about the module being compiled
-- (re-exported from DriverPhases)
HscSource(..), isHsBootOrSig, hscSourceString,
-- * State relating to modules in this package
HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
hptInstances, hptRules, hptVectInfo, pprHPT,
hptObjs,
-- * State relating to known packages
ExternalPackageState(..), EpsStats(..), addEpsInStats,
PackageTypeEnv, PackageIfaceTable, emptyPackageIfaceTable,
lookupIfaceByModule, emptyModIface, lookupHptByModule,
PackageInstEnv, PackageFamInstEnv, PackageRuleBase,
mkSOName, mkHsSOName, soExt,
-- * Metaprogramming
MetaRequest(..),
MetaResult, -- data constructors not exported to ensure correct response type
metaRequestE, metaRequestP, metaRequestT, metaRequestD, metaRequestAW,
MetaHook,
-- * Annotations
prepareAnnotations,
-- * Interactive context
InteractiveContext(..), emptyInteractiveContext,
icPrintUnqual, icInScopeTTs, icExtendGblRdrEnv,
extendInteractiveContext, extendInteractiveContextWithIds,
substInteractiveContext,
setInteractivePrintName, icInteractiveModule,
InteractiveImport(..), setInteractivePackage,
mkPrintUnqualified, pprModulePrefix,
mkQualPackage, mkQualModule, pkgQual,
-- * Interfaces
ModIface(..), mkIfaceWarnCache, mkIfaceHashCache, mkIfaceFixCache,
emptyIfaceWarnCache, mi_boot, mi_fix,
-- * Fixity
FixityEnv, FixItem(..), lookupFixity, emptyFixityEnv,
-- * TyThings and type environments
TyThing(..), tyThingAvailInfo,
tyThingTyCon, tyThingDataCon,
tyThingId, tyThingCoAxiom, tyThingParent_maybe, tyThingsTyCoVars,
implicitTyThings, implicitTyConThings, implicitClassThings,
isImplicitTyThing,
TypeEnv, lookupType, lookupTypeHscEnv, mkTypeEnv, emptyTypeEnv,
typeEnvFromEntities, mkTypeEnvWithImplicits,
extendTypeEnv, extendTypeEnvList,
extendTypeEnvWithIds,
lookupTypeEnv,
typeEnvElts, typeEnvTyCons, typeEnvIds, typeEnvPatSyns,
typeEnvDataCons, typeEnvCoAxioms, typeEnvClasses,
-- * MonadThings
MonadThings(..),
-- * Information on imports and exports
WhetherHasOrphans, IsBootInterface, Usage(..),
Dependencies(..), noDependencies,
NameCache(..), OrigNameCache, updNameCacheIO,
IfaceExport,
-- * Warnings
Warnings(..), WarningTxt(..), plusWarns,
-- * Linker stuff
Linkable(..), isObjectLinkable, linkableObjs,
Unlinked(..), CompiledByteCode,
isObject, nameOfObject, isInterpretable, byteCodeOfObject,
-- * Program coverage
HpcInfo(..), emptyHpcInfo, isHpcUsed, AnyHpcUsage,
-- * Breakpoints
ModBreaks (..), emptyModBreaks,
-- * Vectorisation information
VectInfo(..), IfaceVectInfo(..), noVectInfo, plusVectInfo,
noIfaceVectInfo, isNoIfaceVectInfo,
-- * Safe Haskell information
IfaceTrustInfo, getSafeMode, setSafeMode, noIfaceTrustInfo,
trustInfoToNum, numToTrustInfo, IsSafeImport,
-- * result of the parser
HsParsedModule(..),
-- * Compilation errors and warnings
SourceError, GhcApiError, mkSrcErr, srcErrorMessages, mkApiErr,
throwOneError, handleSourceError,
handleFlagWarnings, printOrThrowWarnings,
) where
#include "HsVersions.h"
#ifdef GHCI
import ByteCodeTypes
import InteractiveEvalTypes ( Resume )
import GHCi.Message ( Pipe )
import GHCi.RemoteTypes
#endif
import HsSyn
import RdrName
import Avail
import Module
import InstEnv ( InstEnv, ClsInst, identicalClsInstHead )
import FamInstEnv
import CoreSyn ( CoreProgram, RuleBase )
import Name
import NameEnv
import NameSet
import VarEnv
import VarSet
import Var
import Id
import IdInfo ( IdDetails(..), RecSelParent(..))
import Type
import ApiAnnotation ( ApiAnns )
import Annotations ( Annotation, AnnEnv, mkAnnEnv, plusAnnEnv )
import Class
import TyCon
import CoAxiom
import ConLike
import DataCon
import PatSyn
import PrelNames ( gHC_PRIM, ioTyConName, printName, mkInteractiveModule
, eqTyConName )
import TysWiredIn
import Packages hiding ( Version(..) )
import DynFlags
import DriverPhases ( Phase, HscSource(..), isHsBootOrSig, hscSourceString )
import BasicTypes
import IfaceSyn
import CoreSyn ( CoreRule, CoreVect )
import Maybes
import Outputable
import SrcLoc
-- import Unique
import UniqFM
import UniqSupply
import FastString
import StringBuffer ( StringBuffer )
import Fingerprint
import MonadUtils
import Bag
import Binary
import ErrUtils
import Platform
import Util
import GHC.Serialized ( Serialized )
import Foreign
import Control.Monad ( guard, liftM, when, ap )
import Data.IORef
import Data.Time
import Exception
import System.FilePath
#ifdef GHCI
import Control.Concurrent
import System.Process ( ProcessHandle )
#endif
-- -----------------------------------------------------------------------------
-- Compilation state
-- -----------------------------------------------------------------------------
-- | Status of a compilation to hard-code
data HscStatus
= HscNotGeneratingCode
| HscUpToDate
| HscUpdateBoot
| HscUpdateSig
| HscRecomp CgGuts ModSummary
-- -----------------------------------------------------------------------------
-- The Hsc monad: Passing an environment and warning state
newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages))
instance Functor Hsc where
fmap = liftM
instance Applicative Hsc where
pure a = Hsc $ \_ w -> return (a, w)
(<*>) = ap
instance Monad Hsc where
Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w
case k a of
Hsc k' -> k' e w1
instance MonadIO Hsc where
liftIO io = Hsc $ \_ w -> do a <- io; return (a, w)
instance HasDynFlags Hsc where
getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w)
runHsc :: HscEnv -> Hsc a -> IO a
runHsc hsc_env (Hsc hsc) = do
(a, w) <- hsc hsc_env emptyBag
printOrThrowWarnings (hsc_dflags hsc_env) w
return a
runInteractiveHsc :: HscEnv -> Hsc a -> IO a
-- A variant of runHsc that switches in the DynFlags from the
-- InteractiveContext before running the Hsc computation.
runInteractiveHsc hsc_env
= runHsc (hsc_env { hsc_dflags = interactive_dflags })
where
interactive_dflags = ic_dflags (hsc_IC hsc_env)
-- -----------------------------------------------------------------------------
-- Source Errors
-- When the compiler (HscMain) discovers errors, it throws an
-- exception in the IO monad.
mkSrcErr :: ErrorMessages -> SourceError
mkSrcErr = SourceError
srcErrorMessages :: SourceError -> ErrorMessages
srcErrorMessages (SourceError msgs) = msgs
mkApiErr :: DynFlags -> SDoc -> GhcApiError
mkApiErr dflags msg = GhcApiError (showSDoc dflags msg)
throwOneError :: MonadIO m => ErrMsg -> m ab
throwOneError err = liftIO $ throwIO $ mkSrcErr $ unitBag err
-- | A source error is an error that is caused by one or more errors in the
-- source code. A 'SourceError' is thrown by many functions in the
-- compilation pipeline. Inside GHC these errors are merely printed via
-- 'log_action', but API clients may treat them differently, for example,
-- insert them into a list box. If you want the default behaviour, use the
-- idiom:
--
-- > handleSourceError printExceptionAndWarnings $ do
-- > ... api calls that may fail ...
--
-- The 'SourceError's error messages can be accessed via 'srcErrorMessages'.
-- This list may be empty if the compiler failed due to @-Werror@
-- ('Opt_WarnIsError').
--
-- See 'printExceptionAndWarnings' for more information on what to take care
-- of when writing a custom error handler.
newtype SourceError = SourceError ErrorMessages
instance Show SourceError where
show (SourceError msgs) = unlines . map show . bagToList $ msgs
instance Exception SourceError
-- | Perform the given action and call the exception handler if the action
-- throws a 'SourceError'. See 'SourceError' for more information.
handleSourceError :: (ExceptionMonad m) =>
(SourceError -> m a) -- ^ exception handler
-> m a -- ^ action to perform
-> m a
handleSourceError handler act =
gcatch act (\(e :: SourceError) -> handler e)
-- | An error thrown if the GHC API is used in an incorrect fashion.
newtype GhcApiError = GhcApiError String
instance Show GhcApiError where
show (GhcApiError msg) = msg
instance Exception GhcApiError
-- | Given a bag of warnings, turn them into an exception if
-- -Werror is enabled, or print them out otherwise.
printOrThrowWarnings :: DynFlags -> Bag WarnMsg -> IO ()
printOrThrowWarnings dflags warns
| gopt Opt_WarnIsError dflags
= when (not (isEmptyBag warns)) $ do
throwIO $ mkSrcErr $ warns `snocBag` warnIsErrorMsg dflags
| otherwise
= printBagOfErrors dflags warns
handleFlagWarnings :: DynFlags -> [Located String] -> IO ()
handleFlagWarnings dflags warns
= when (wopt Opt_WarnDeprecatedFlags dflags) $ do
-- It would be nicer if warns :: [Located MsgDoc], but that
-- has circular import problems.
let bag = listToBag [ mkPlainWarnMsg dflags loc (text warn)
| L loc warn <- warns ]
printOrThrowWarnings dflags bag
{-
************************************************************************
* *
\subsection{HscEnv}
* *
************************************************************************
-}
-- | HscEnv is like 'Session', except that some of the fields are immutable.
-- An HscEnv is used to compile a single module from plain Haskell source
-- code (after preprocessing) to either C, assembly or C--. Things like
-- the module graph don't change during a single compilation.
--
-- Historical note: \"hsc\" used to be the name of the compiler binary,
-- when there was a separate driver and compiler. To compile a single
-- module, the driver would invoke hsc on the source code... so nowadays
-- we think of hsc as the layer of the compiler that deals with compiling
-- a single module.
data HscEnv
= HscEnv {
hsc_dflags :: DynFlags,
-- ^ The dynamic flag settings
hsc_targets :: [Target],
-- ^ The targets (or roots) of the current session
hsc_mod_graph :: ModuleGraph,
-- ^ The module graph of the current session
hsc_IC :: InteractiveContext,
-- ^ The context for evaluating interactive statements
hsc_HPT :: HomePackageTable,
-- ^ The home package table describes already-compiled
-- home-package modules, /excluding/ the module we
-- are compiling right now.
-- (In one-shot mode the current module is the only
-- home-package module, so hsc_HPT is empty. All other
-- modules count as \"external-package\" modules.
-- However, even in GHCi mode, hi-boot interfaces are
-- demand-loaded into the external-package table.)
--
-- 'hsc_HPT' is not mutable because we only demand-load
-- external packages; the home package is eagerly
-- loaded, module by module, by the compilation manager.
--
-- The HPT may contain modules compiled earlier by @--make@
-- but not actually below the current module in the dependency
-- graph.
--
-- (This changes a previous invariant: changed Jan 05.)
hsc_EPS :: {-# UNPACK #-} !(IORef ExternalPackageState),
-- ^ Information about the currently loaded external packages.
-- This is mutable because packages will be demand-loaded during
-- a compilation run as required.
hsc_NC :: {-# UNPACK #-} !(IORef NameCache),
-- ^ As with 'hsc_EPS', this is side-effected by compiling to
-- reflect sucking in interface files. They cache the state of
-- external interface files, in effect.
hsc_FC :: {-# UNPACK #-} !(IORef FinderCache),
-- ^ The cached result of performing finding in the file system
hsc_type_env_var :: Maybe (Module, IORef TypeEnv)
-- ^ Used for one-shot compilation only, to initialise
-- the 'IfGblEnv'. See 'TcRnTypes.tcg_type_env_var' for
-- 'TcRnTypes.TcGblEnv'
#ifdef GHCI
, hsc_iserv :: MVar (Maybe IServ)
-- ^ interactive server process. Created the first
-- time it is needed.
#endif
}
#ifdef GHCI
data IServ = IServ
{ iservPipe :: Pipe
, iservProcess :: ProcessHandle
, iservLookupSymbolCache :: IORef (UniqFM (Ptr ()))
, iservPendingFrees :: [HValueRef]
}
#endif
-- | Retrieve the ExternalPackageState cache.
hscEPS :: HscEnv -> IO ExternalPackageState
hscEPS hsc_env = readIORef (hsc_EPS hsc_env)
-- | A compilation target.
--
-- A target may be supplied with the actual text of the
-- module. If so, use this instead of the file contents (this
-- is for use in an IDE where the file hasn't been saved by
-- the user yet).
data Target
= Target {
targetId :: TargetId, -- ^ module or filename
targetAllowObjCode :: Bool, -- ^ object code allowed?
targetContents :: Maybe (StringBuffer,UTCTime)
-- ^ in-memory text buffer?
}
data TargetId
= TargetModule ModuleName
-- ^ A module name: search for the file
| TargetFile FilePath (Maybe Phase)
-- ^ A filename: preprocess & parse it to find the module name.
-- If specified, the Phase indicates how to compile this file
-- (which phase to start from). Nothing indicates the starting phase
-- should be determined from the suffix of the filename.
deriving Eq
pprTarget :: Target -> SDoc
pprTarget (Target id obj _) =
(if obj then char '*' else empty) <> pprTargetId id
instance Outputable Target where
ppr = pprTarget
pprTargetId :: TargetId -> SDoc
pprTargetId (TargetModule m) = ppr m
pprTargetId (TargetFile f _) = text f
instance Outputable TargetId where
ppr = pprTargetId
{-
************************************************************************
* *
\subsection{Package and Module Tables}
* *
************************************************************************
-}
-- | Helps us find information about modules in the home package
type HomePackageTable = ModuleNameEnv HomeModInfo
-- Domain = modules in the home package that have been fully compiled
-- "home" unit id cached here for convenience
-- | Helps us find information about modules in the imported packages
type PackageIfaceTable = ModuleEnv ModIface
-- Domain = modules in the imported packages
-- | Constructs an empty HomePackageTable
emptyHomePackageTable :: HomePackageTable
emptyHomePackageTable = emptyUFM
-- | Constructs an empty PackageIfaceTable
emptyPackageIfaceTable :: PackageIfaceTable
emptyPackageIfaceTable = emptyModuleEnv
pprHPT :: HomePackageTable -> SDoc
-- A bit aribitrary for now
pprHPT hpt = pprUFM hpt $ \hms ->
vcat [ hang (ppr (mi_module (hm_iface hm)))
2 (ppr (md_types (hm_details hm)))
| hm <- hms ]
lookupHptByModule :: HomePackageTable -> Module -> Maybe HomeModInfo
-- The HPT is indexed by ModuleName, not Module,
-- we must check for a hit on the right Module
lookupHptByModule hpt mod
= case lookupUFM hpt (moduleName mod) of
Just hm | mi_module (hm_iface hm) == mod -> Just hm
_otherwise -> Nothing
-- | Information about modules in the package being compiled
data HomeModInfo
= HomeModInfo {
hm_iface :: !ModIface,
-- ^ The basic loaded interface file: every loaded module has one of
-- these, even if it is imported from another package
hm_details :: !ModDetails,
-- ^ Extra information that has been created from the 'ModIface' for
-- the module, typically during typechecking
hm_linkable :: !(Maybe Linkable)
-- ^ The actual artifact we would like to link to access things in
-- this module.
--
-- 'hm_linkable' might be Nothing:
--
-- 1. If this is an .hs-boot module
--
-- 2. Temporarily during compilation if we pruned away
-- the old linkable because it was out of date.
--
-- After a complete compilation ('GHC.load'), all 'hm_linkable' fields
-- in the 'HomePackageTable' will be @Just@.
--
-- When re-linking a module ('HscMain.HscNoRecomp'), we construct the
-- 'HomeModInfo' by building a new 'ModDetails' from the old
-- 'ModIface' (only).
}
-- | Find the 'ModIface' for a 'Module', searching in both the loaded home
-- and external package module information
lookupIfaceByModule
:: DynFlags
-> HomePackageTable
-> PackageIfaceTable
-> Module
-> Maybe ModIface
lookupIfaceByModule _dflags hpt pit mod
= case lookupHptByModule hpt mod of
Just hm -> Just (hm_iface hm)
Nothing -> lookupModuleEnv pit mod
-- If the module does come from the home package, why do we look in the PIT as well?
-- (a) In OneShot mode, even home-package modules accumulate in the PIT
-- (b) Even in Batch (--make) mode, there is *one* case where a home-package
-- module is in the PIT, namely GHC.Prim when compiling the base package.
-- We could eliminate (b) if we wanted, by making GHC.Prim belong to a package
-- of its own, but it doesn't seem worth the bother.
-- | Find all the instance declarations (of classes and families) from
-- the Home Package Table filtered by the provided predicate function.
-- Used in @tcRnImports@, to select the instances that are in the
-- transitive closure of imports from the currently compiled module.
hptInstances :: HscEnv -> (ModuleName -> Bool) -> ([ClsInst], [FamInst])
hptInstances hsc_env want_this_module
= let (insts, famInsts) = unzip $ flip hptAllThings hsc_env $ \mod_info -> do
guard (want_this_module (moduleName (mi_module (hm_iface mod_info))))
let details = hm_details mod_info
return (md_insts details, md_fam_insts details)
in (concat insts, concat famInsts)
-- | Get the combined VectInfo of all modules in the home package table. In
-- contrast to instances and rules, we don't care whether the modules are
-- "below" us in the dependency sense. The VectInfo of those modules not "below"
-- us does not affect the compilation of the current module.
hptVectInfo :: HscEnv -> VectInfo
hptVectInfo = concatVectInfo . hptAllThings ((: []) . md_vect_info . hm_details)
-- | Get rules from modules "below" this one (in the dependency sense)
hptRules :: HscEnv -> [(ModuleName, IsBootInterface)] -> [CoreRule]
hptRules = hptSomeThingsBelowUs (md_rules . hm_details) False
-- | Get annotations from modules "below" this one (in the dependency sense)
hptAnns :: HscEnv -> Maybe [(ModuleName, IsBootInterface)] -> [Annotation]
hptAnns hsc_env (Just deps) = hptSomeThingsBelowUs (md_anns . hm_details) False hsc_env deps
hptAnns hsc_env Nothing = hptAllThings (md_anns . hm_details) hsc_env
hptAllThings :: (HomeModInfo -> [a]) -> HscEnv -> [a]
hptAllThings extract hsc_env = concatMap extract (eltsUFM (hsc_HPT hsc_env))
-- | Get things from modules "below" this one (in the dependency sense)
-- C.f Inst.hptInstances
hptSomeThingsBelowUs :: (HomeModInfo -> [a]) -> Bool -> HscEnv -> [(ModuleName, IsBootInterface)] -> [a]
hptSomeThingsBelowUs extract include_hi_boot hsc_env deps
| isOneShot (ghcMode (hsc_dflags hsc_env)) = []
| otherwise
= let hpt = hsc_HPT hsc_env
in
[ thing
| -- Find each non-hi-boot module below me
(mod, is_boot_mod) <- deps
, include_hi_boot || not is_boot_mod
-- unsavoury: when compiling the base package with --make, we
-- sometimes try to look up RULES etc for GHC.Prim. GHC.Prim won't
-- be in the HPT, because we never compile it; it's in the EPT
-- instead. ToDo: clean up, and remove this slightly bogus filter:
, mod /= moduleName gHC_PRIM
-- Look it up in the HPT
, let things = case lookupUFM hpt mod of
Just info -> extract info
Nothing -> pprTrace "WARNING in hptSomeThingsBelowUs" msg []
msg = vcat [text "missing module" <+> ppr mod,
text "Probable cause: out-of-date interface files"]
-- This really shouldn't happen, but see Trac #962
-- And get its dfuns
, thing <- things ]
hptObjs :: HomePackageTable -> [FilePath]
hptObjs hpt = concat (map (maybe [] linkableObjs . hm_linkable) (eltsUFM hpt))
{-
************************************************************************
* *
\subsection{Metaprogramming}
* *
************************************************************************
-}
-- | The supported metaprogramming result types
data MetaRequest
= MetaE (LHsExpr RdrName -> MetaResult)
| MetaP (LPat RdrName -> MetaResult)
| MetaT (LHsType RdrName -> MetaResult)
| MetaD ([LHsDecl RdrName] -> MetaResult)
| MetaAW (Serialized -> MetaResult)
-- | data constructors not exported to ensure correct result type
data MetaResult
= MetaResE { unMetaResE :: LHsExpr RdrName }
| MetaResP { unMetaResP :: LPat RdrName }
| MetaResT { unMetaResT :: LHsType RdrName }
| MetaResD { unMetaResD :: [LHsDecl RdrName] }
| MetaResAW { unMetaResAW :: Serialized }
type MetaHook f = MetaRequest -> LHsExpr Id -> f MetaResult
metaRequestE :: Functor f => MetaHook f -> LHsExpr Id -> f (LHsExpr RdrName)
metaRequestE h = fmap unMetaResE . h (MetaE MetaResE)
metaRequestP :: Functor f => MetaHook f -> LHsExpr Id -> f (LPat RdrName)
metaRequestP h = fmap unMetaResP . h (MetaP MetaResP)
metaRequestT :: Functor f => MetaHook f -> LHsExpr Id -> f (LHsType RdrName)
metaRequestT h = fmap unMetaResT . h (MetaT MetaResT)
metaRequestD :: Functor f => MetaHook f -> LHsExpr Id -> f [LHsDecl RdrName]
metaRequestD h = fmap unMetaResD . h (MetaD MetaResD)
metaRequestAW :: Functor f => MetaHook f -> LHsExpr Id -> f Serialized
metaRequestAW h = fmap unMetaResAW . h (MetaAW MetaResAW)
{-
************************************************************************
* *
\subsection{Dealing with Annotations}
* *
************************************************************************
-}
-- | Deal with gathering annotations in from all possible places
-- and combining them into a single 'AnnEnv'
prepareAnnotations :: HscEnv -> Maybe ModGuts -> IO AnnEnv
prepareAnnotations hsc_env mb_guts = do
eps <- hscEPS hsc_env
let -- Extract annotations from the module being compiled if supplied one
mb_this_module_anns = fmap (mkAnnEnv . mg_anns) mb_guts
-- Extract dependencies of the module if we are supplied one,
-- otherwise load annotations from all home package table
-- entries regardless of dependency ordering.
home_pkg_anns = (mkAnnEnv . hptAnns hsc_env) $ fmap (dep_mods . mg_deps) mb_guts
other_pkg_anns = eps_ann_env eps
ann_env = foldl1' plusAnnEnv $ catMaybes [mb_this_module_anns,
Just home_pkg_anns,
Just other_pkg_anns]
return ann_env
{-
************************************************************************
* *
\subsection{The Finder cache}
* *
************************************************************************
-}
-- | The 'FinderCache' maps modules to the result of
-- searching for that module. It records the results of searching for
-- modules along the search path. On @:load@, we flush the entire
-- contents of this cache.
--
-- Although the @FinderCache@ range is 'FindResult' for convenience,
-- in fact it will only ever contain 'Found' or 'NotFound' entries.
--
type FinderCache = ModuleEnv FindResult
-- | The result of searching for an imported module.
data FindResult
= Found ModLocation Module
-- ^ The module was found
| NoPackage UnitId
-- ^ The requested package was not found
| FoundMultiple [(Module, ModuleOrigin)]
-- ^ _Error_: both in multiple packages
-- | Not found
| NotFound
{ fr_paths :: [FilePath] -- Places where I looked
, fr_pkg :: Maybe UnitId -- Just p => module is in this package's
-- manifest, but couldn't find
-- the .hi file
, fr_mods_hidden :: [UnitId] -- Module is in these packages,
-- but the *module* is hidden
, fr_pkgs_hidden :: [UnitId] -- Module is in these packages,
-- but the *package* is hidden
, fr_suggestions :: [ModuleSuggestion] -- Possible mis-spelled modules
}
{-
************************************************************************
* *
\subsection{Symbol tables and Module details}
* *
************************************************************************
-}
-- | A 'ModIface' plus a 'ModDetails' summarises everything we know
-- about a compiled module. The 'ModIface' is the stuff *before* linking,
-- and can be written out to an interface file. The 'ModDetails is after
-- linking and can be completely recovered from just the 'ModIface'.
--
-- When we read an interface file, we also construct a 'ModIface' from it,
-- except that we explicitly make the 'mi_decls' and a few other fields empty;
-- as when reading we consolidate the declarations etc. into a number of indexed
-- maps and environments in the 'ExternalPackageState'.
data ModIface
= ModIface {
mi_module :: !Module, -- ^ Name of the module we are for
mi_sig_of :: !(Maybe Module), -- ^ Are we a sig of another mod?
mi_iface_hash :: !Fingerprint, -- ^ Hash of the whole interface
mi_mod_hash :: !Fingerprint, -- ^ Hash of the ABI only
mi_flag_hash :: !Fingerprint, -- ^ Hash of the important flags
-- used when compiling this module
mi_orphan :: !WhetherHasOrphans, -- ^ Whether this module has orphans
mi_finsts :: !WhetherHasFamInst, -- ^ Whether this module has family instances
mi_hsc_src :: !HscSource, -- ^ Boot? Signature?
mi_deps :: Dependencies,
-- ^ The dependencies of the module. This is
-- consulted for directly-imported modules, but not
-- for anything else (hence lazy)
mi_usages :: [Usage],
-- ^ Usages; kept sorted so that it's easy to decide
-- whether to write a new iface file (changing usages
-- doesn't affect the hash of this module)
-- NOT STRICT! we read this field lazily from the interface file
-- It is *only* consulted by the recompilation checker
mi_exports :: ![IfaceExport],
-- ^ Exports
-- Kept sorted by (mod,occ), to make version comparisons easier
-- Records the modules that are the declaration points for things
-- exported by this module, and the 'OccName's of those things
mi_exp_hash :: !Fingerprint,
-- ^ Hash of export list
mi_used_th :: !Bool,
-- ^ Module required TH splices when it was compiled.
-- This disables recompilation avoidance (see #481).
mi_fixities :: [(OccName,Fixity)],
-- ^ Fixities
-- NOT STRICT! we read this field lazily from the interface file
mi_warns :: Warnings,
-- ^ Warnings
-- NOT STRICT! we read this field lazily from the interface file
mi_anns :: [IfaceAnnotation],
-- ^ Annotations
-- NOT STRICT! we read this field lazily from the interface file
mi_decls :: [(Fingerprint,IfaceDecl)],
-- ^ Type, class and variable declarations
-- The hash of an Id changes if its fixity or deprecations change
-- (as well as its type of course)
-- Ditto data constructors, class operations, except that
-- the hash of the parent class/tycon changes
mi_globals :: !(Maybe GlobalRdrEnv),
-- ^ Binds all the things defined at the top level in
-- the /original source/ code for this module. which
-- is NOT the same as mi_exports, nor mi_decls (which
-- may contains declarations for things not actually
-- defined by the user). Used for GHCi and for inspecting
-- the contents of modules via the GHC API only.
--
-- (We need the source file to figure out the
-- top-level environment, if we didn't compile this module
-- from source then this field contains @Nothing@).
--
-- Strictly speaking this field should live in the
-- 'HomeModInfo', but that leads to more plumbing.
-- Instance declarations and rules
mi_insts :: [IfaceClsInst], -- ^ Sorted class instance
mi_fam_insts :: [IfaceFamInst], -- ^ Sorted family instances
mi_rules :: [IfaceRule], -- ^ Sorted rules
mi_orphan_hash :: !Fingerprint, -- ^ Hash for orphan rules, class and family
-- instances, and vectorise pragmas combined
mi_vect_info :: !IfaceVectInfo, -- ^ Vectorisation information
-- Cached environments for easy lookup
-- These are computed (lazily) from other fields
-- and are not put into the interface file
mi_warn_fn :: OccName -> Maybe WarningTxt,
-- ^ Cached lookup for 'mi_warns'
mi_fix_fn :: OccName -> Maybe Fixity,
-- ^ Cached lookup for 'mi_fixities'
mi_hash_fn :: OccName -> Maybe (OccName, Fingerprint),
-- ^ Cached lookup for 'mi_decls'.
-- The @Nothing@ in 'mi_hash_fn' means that the thing
-- isn't in decls. It's useful to know that when
-- seeing if we are up to date wrt. the old interface.
-- The 'OccName' is the parent of the name, if it has one.
mi_hpc :: !AnyHpcUsage,
-- ^ True if this program uses Hpc at any point in the program.
mi_trust :: !IfaceTrustInfo,
-- ^ Safe Haskell Trust information for this module.
mi_trust_pkg :: !Bool
-- ^ Do we require the package this module resides in be trusted
-- to trust this module? This is used for the situation where a
-- module is Safe (so doesn't require the package be trusted
-- itself) but imports some trustworthy modules from its own
-- package (which does require its own package be trusted).
-- See Note [RnNames . Trust Own Package]
}
-- | Old-style accessor for whether or not the ModIface came from an hs-boot
-- file.
mi_boot :: ModIface -> Bool
mi_boot iface = mi_hsc_src iface == HsBootFile
-- | Lookups up a (possibly cached) fixity from a 'ModIface'. If one cannot be
-- found, 'defaultFixity' is returned instead.
mi_fix :: ModIface -> OccName -> Fixity
mi_fix iface name = mi_fix_fn iface name `orElse` defaultFixity
instance Binary ModIface where
put_ bh (ModIface {
mi_module = mod,
mi_sig_of = sig_of,
mi_hsc_src = hsc_src,
mi_iface_hash= iface_hash,
mi_mod_hash = mod_hash,
mi_flag_hash = flag_hash,
mi_orphan = orphan,
mi_finsts = hasFamInsts,
mi_deps = deps,
mi_usages = usages,
mi_exports = exports,
mi_exp_hash = exp_hash,
mi_used_th = used_th,
mi_fixities = fixities,
mi_warns = warns,
mi_anns = anns,
mi_decls = decls,
mi_insts = insts,
mi_fam_insts = fam_insts,
mi_rules = rules,
mi_orphan_hash = orphan_hash,
mi_vect_info = vect_info,
mi_hpc = hpc_info,
mi_trust = trust,
mi_trust_pkg = trust_pkg }) = do
put_ bh mod
put_ bh hsc_src
put_ bh iface_hash
put_ bh mod_hash
put_ bh flag_hash
put_ bh orphan
put_ bh hasFamInsts
lazyPut bh deps
lazyPut bh usages
put_ bh exports
put_ bh exp_hash
put_ bh used_th
put_ bh fixities
lazyPut bh warns
lazyPut bh anns
put_ bh decls
put_ bh insts
put_ bh fam_insts
lazyPut bh rules
put_ bh orphan_hash
put_ bh vect_info
put_ bh hpc_info
put_ bh trust
put_ bh trust_pkg
put_ bh sig_of
get bh = do
mod_name <- get bh
hsc_src <- get bh
iface_hash <- get bh
mod_hash <- get bh
flag_hash <- get bh
orphan <- get bh
hasFamInsts <- get bh
deps <- lazyGet bh
usages <- {-# SCC "bin_usages" #-} lazyGet bh
exports <- {-# SCC "bin_exports" #-} get bh
exp_hash <- get bh
used_th <- get bh
fixities <- {-# SCC "bin_fixities" #-} get bh
warns <- {-# SCC "bin_warns" #-} lazyGet bh
anns <- {-# SCC "bin_anns" #-} lazyGet bh
decls <- {-# SCC "bin_tycldecls" #-} get bh
insts <- {-# SCC "bin_insts" #-} get bh
fam_insts <- {-# SCC "bin_fam_insts" #-} get bh
rules <- {-# SCC "bin_rules" #-} lazyGet bh
orphan_hash <- get bh
vect_info <- get bh
hpc_info <- get bh
trust <- get bh
trust_pkg <- get bh
sig_of <- get bh
return (ModIface {
mi_module = mod_name,
mi_sig_of = sig_of,
mi_hsc_src = hsc_src,
mi_iface_hash = iface_hash,
mi_mod_hash = mod_hash,
mi_flag_hash = flag_hash,
mi_orphan = orphan,
mi_finsts = hasFamInsts,
mi_deps = deps,
mi_usages = usages,
mi_exports = exports,
mi_exp_hash = exp_hash,
mi_used_th = used_th,
mi_anns = anns,
mi_fixities = fixities,
mi_warns = warns,
mi_decls = decls,
mi_globals = Nothing,
mi_insts = insts,
mi_fam_insts = fam_insts,
mi_rules = rules,
mi_orphan_hash = orphan_hash,
mi_vect_info = vect_info,
mi_hpc = hpc_info,
mi_trust = trust,
mi_trust_pkg = trust_pkg,
-- And build the cached values
mi_warn_fn = mkIfaceWarnCache warns,
mi_fix_fn = mkIfaceFixCache fixities,
mi_hash_fn = mkIfaceHashCache decls })
-- | The original names declared of a certain module that are exported
type IfaceExport = AvailInfo
-- | Constructs an empty ModIface
emptyModIface :: Module -> ModIface
emptyModIface mod
= ModIface { mi_module = mod,
mi_sig_of = Nothing,
mi_iface_hash = fingerprint0,
mi_mod_hash = fingerprint0,
mi_flag_hash = fingerprint0,
mi_orphan = False,
mi_finsts = False,
mi_hsc_src = HsSrcFile,
mi_deps = noDependencies,
mi_usages = [],
mi_exports = [],
mi_exp_hash = fingerprint0,
mi_used_th = False,
mi_fixities = [],
mi_warns = NoWarnings,
mi_anns = [],
mi_insts = [],
mi_fam_insts = [],
mi_rules = [],
mi_decls = [],
mi_globals = Nothing,
mi_orphan_hash = fingerprint0,
mi_vect_info = noIfaceVectInfo,
mi_warn_fn = emptyIfaceWarnCache,
mi_fix_fn = emptyIfaceFixCache,
mi_hash_fn = emptyIfaceHashCache,
mi_hpc = False,
mi_trust = noIfaceTrustInfo,
mi_trust_pkg = False }
-- | Constructs cache for the 'mi_hash_fn' field of a 'ModIface'
mkIfaceHashCache :: [(Fingerprint,IfaceDecl)]
-> (OccName -> Maybe (OccName, Fingerprint))
mkIfaceHashCache pairs
= \occ -> lookupOccEnv env occ
where
env = foldr add_decl emptyOccEnv pairs
add_decl (v,d) env0 = foldr add env0 (ifaceDeclFingerprints v d)
where
add (occ,hash) env0 = extendOccEnv env0 occ (occ,hash)
emptyIfaceHashCache :: OccName -> Maybe (OccName, Fingerprint)
emptyIfaceHashCache _occ = Nothing
-- | The 'ModDetails' is essentially a cache for information in the 'ModIface'
-- for home modules only. Information relating to packages will be loaded into
-- global environments in 'ExternalPackageState'.
data ModDetails
= ModDetails {
-- The next two fields are created by the typechecker
md_exports :: [AvailInfo],
md_types :: !TypeEnv, -- ^ Local type environment for this particular module
-- Includes Ids, TyCons, PatSyns
md_insts :: ![ClsInst], -- ^ 'DFunId's for the instances in this module
md_fam_insts :: ![FamInst],
md_rules :: ![CoreRule], -- ^ Domain may include 'Id's from other modules
md_anns :: ![Annotation], -- ^ Annotations present in this module: currently
-- they only annotate things also declared in this module
md_vect_info :: !VectInfo -- ^ Module vectorisation information
}
-- | Constructs an empty ModDetails
emptyModDetails :: ModDetails
emptyModDetails
= ModDetails { md_types = emptyTypeEnv,
md_exports = [],
md_insts = [],
md_rules = [],
md_fam_insts = [],
md_anns = [],
md_vect_info = noVectInfo }
-- | Records the modules directly imported by a module for extracting e.g.
-- usage information, and also to give better error message
type ImportedMods = ModuleEnv [ImportedModsVal]
data ImportedModsVal
= ImportedModsVal {
imv_name :: ModuleName, -- ^ The name the module is imported with
imv_span :: SrcSpan, -- ^ the source span of the whole import
imv_is_safe :: IsSafeImport, -- ^ whether this is a safe import
imv_is_hiding :: Bool, -- ^ whether this is an "hiding" import
imv_all_exports :: GlobalRdrEnv, -- ^ all the things the module could provide
imv_qualified :: Bool -- ^ whether this is a qualified import
}
-- | A ModGuts is carried through the compiler, accumulating stuff as it goes
-- There is only one ModGuts at any time, the one for the module
-- being compiled right now. Once it is compiled, a 'ModIface' and
-- 'ModDetails' are extracted and the ModGuts is discarded.
data ModGuts
= ModGuts {
mg_module :: !Module, -- ^ Module being compiled
mg_hsc_src :: HscSource, -- ^ Whether it's an hs-boot module
mg_loc :: SrcSpan, -- ^ For error messages from inner passes
mg_exports :: ![AvailInfo], -- ^ What it exports
mg_deps :: !Dependencies, -- ^ What it depends on, directly or
-- otherwise
mg_usages :: ![Usage], -- ^ What was used? Used for interfaces.
mg_used_th :: !Bool, -- ^ Did we run a TH splice?
mg_rdr_env :: !GlobalRdrEnv, -- ^ Top-level lexical environment
-- These fields all describe the things **declared in this module**
mg_fix_env :: !FixityEnv, -- ^ Fixities declared in this module.
-- Used for creating interface files.
mg_tcs :: ![TyCon], -- ^ TyCons declared in this module
-- (includes TyCons for classes)
mg_insts :: ![ClsInst], -- ^ Class instances declared in this module
mg_fam_insts :: ![FamInst],
-- ^ Family instances declared in this module
mg_patsyns :: ![PatSyn], -- ^ Pattern synonyms declared in this module
mg_rules :: ![CoreRule], -- ^ Before the core pipeline starts, contains
-- See Note [Overall plumbing for rules] in Rules.hs
mg_binds :: !CoreProgram, -- ^ Bindings for this module
mg_foreign :: !ForeignStubs, -- ^ Foreign exports declared in this module
mg_warns :: !Warnings, -- ^ Warnings declared in the module
mg_anns :: [Annotation], -- ^ Annotations declared in this module
mg_hpc_info :: !HpcInfo, -- ^ Coverage tick boxes in the module
mg_modBreaks :: !(Maybe ModBreaks), -- ^ Breakpoints for the module
mg_vect_decls:: ![CoreVect], -- ^ Vectorisation declarations in this module
-- (produced by desugarer & consumed by vectoriser)
mg_vect_info :: !VectInfo, -- ^ Pool of vectorised declarations in the module
-- The next two fields are unusual, because they give instance
-- environments for *all* modules in the home package, including
-- this module, rather than for *just* this module.
-- Reason: when looking up an instance we don't want to have to
-- look at each module in the home package in turn
mg_inst_env :: InstEnv, -- ^ Class instance environment for
-- /home-package/ modules (including this
-- one); c.f. 'tcg_inst_env'
mg_fam_inst_env :: FamInstEnv, -- ^ Type-family instance environment for
-- /home-package/ modules (including this
-- one); c.f. 'tcg_fam_inst_env'
mg_safe_haskell :: SafeHaskellMode, -- ^ Safe Haskell mode
mg_trust_pkg :: Bool -- ^ Do we need to trust our
-- own package for Safe Haskell?
-- See Note [RnNames . Trust Own Package]
}
-- The ModGuts takes on several slightly different forms:
--
-- After simplification, the following fields change slightly:
-- mg_rules Orphan rules only (local ones now attached to binds)
-- mg_binds With rules attached
---------------------------------------------------------
-- The Tidy pass forks the information about this module:
-- * one lot goes to interface file generation (ModIface)
-- and later compilations (ModDetails)
-- * the other lot goes to code generation (CgGuts)
-- | A restricted form of 'ModGuts' for code generation purposes
data CgGuts
= CgGuts {
cg_module :: !Module,
-- ^ Module being compiled
cg_tycons :: [TyCon],
-- ^ Algebraic data types (including ones that started
-- life as classes); generate constructors and info
-- tables. Includes newtypes, just for the benefit of
-- External Core
cg_binds :: CoreProgram,
-- ^ The tidied main bindings, including
-- previously-implicit bindings for record and class
-- selectors, and data constructor wrappers. But *not*
-- data constructor workers; reason: we we regard them
-- as part of the code-gen of tycons
cg_foreign :: !ForeignStubs, -- ^ Foreign export stubs
cg_dep_pkgs :: ![UnitId], -- ^ Dependent packages, used to
-- generate #includes for C code gen
cg_hpc_info :: !HpcInfo, -- ^ Program coverage tick box information
cg_modBreaks :: !(Maybe ModBreaks) -- ^ Module breakpoints
}
-----------------------------------
-- | Foreign export stubs
data ForeignStubs
= NoStubs
-- ^ We don't have any stubs
| ForeignStubs SDoc SDoc
-- ^ There are some stubs. Parameters:
--
-- 1) Header file prototypes for
-- "foreign exported" functions
--
-- 2) C stubs to use when calling
-- "foreign exported" functions
appendStubC :: ForeignStubs -> SDoc -> ForeignStubs
appendStubC NoStubs c_code = ForeignStubs empty c_code
appendStubC (ForeignStubs h c) c_code = ForeignStubs h (c $$ c_code)
{-
************************************************************************
* *
The interactive context
* *
************************************************************************
Note [The interactive package]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Type, class, and value declarations at the command prompt are treated
as if they were defined in modules
interactive:Ghci1
interactive:Ghci2
...etc...
with each bunch of declarations using a new module, all sharing a
common package 'interactive' (see Module.interactiveUnitId, and
PrelNames.mkInteractiveModule).
This scheme deals well with shadowing. For example:
ghci> data T = A
ghci> data T = B
ghci> :i A
data Ghci1.T = A -- Defined at <interactive>:2:10
Here we must display info about constructor A, but its type T has been
shadowed by the second declaration. But it has a respectable
qualified name (Ghci1.T), and its source location says where it was
defined.
So the main invariant continues to hold, that in any session an
original name M.T only refers to one unique thing. (In a previous
iteration both the T's above were called :Interactive.T, albeit with
different uniques, which gave rise to all sorts of trouble.)
The details are a bit tricky though:
* The field ic_mod_index counts which Ghci module we've got up to.
It is incremented when extending ic_tythings
* ic_tythings contains only things from the 'interactive' package.
* Module from the 'interactive' package (Ghci1, Ghci2 etc) never go
in the Home Package Table (HPT). When you say :load, that's when we
extend the HPT.
* The 'thisPackage' field of DynFlags is *not* set to 'interactive'.
It stays as 'main' (or whatever -this-unit-id says), and is the
package to which :load'ed modules are added to.
* So how do we arrange that declarations at the command prompt get to
be in the 'interactive' package? Simply by setting the tcg_mod
field of the TcGblEnv to "interactive:Ghci1". This is done by the
call to initTc in initTcInteractive, which in turn get the module
from it 'icInteractiveModule' field of the interactive context.
The 'thisPackage' field stays as 'main' (or whatever -this-unit-id says.
* The main trickiness is that the type environment (tcg_type_env) and
fixity envt (tcg_fix_env), now contain entities from all the
interactive-package modules (Ghci1, Ghci2, ...) together, rather
than just a single module as is usually the case. So you can't use
"nameIsLocalOrFrom" to decide whether to look in the TcGblEnv vs
the HPT/PTE. This is a change, but not a problem provided you
know.
* However, the tcg_binds, tcg_sigs, tcg_insts, tcg_fam_insts, etc fields
of the TcGblEnv, which collect "things defined in this module", all
refer to stuff define in a single GHCi command, *not* all the commands
so far.
In contrast, tcg_inst_env, tcg_fam_inst_env, have instances from
all GhciN modules, which makes sense -- they are all "home package"
modules.
Note [Interactively-bound Ids in GHCi]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Ids bound by previous Stmts in GHCi are currently
a) GlobalIds, with
b) An External Name, like Ghci4.foo
See Note [The interactive package] above
c) A tidied type
(a) They must be GlobalIds (not LocalIds) otherwise when we come to
compile an expression using these ids later, the byte code
generator will consider the occurrences to be free rather than
global.
(b) Having an External Name is important because of Note
[GlobalRdrEnv shadowing] in RdrName
(c) Their types are tidied. This is important, because :info may ask
to look at them, and :info expects the things it looks up to have
tidy types
Where do interactively-bound Ids come from?
- GHCi REPL Stmts e.g.
ghci> let foo x = x+1
These start with an Internal Name because a Stmt is a local
construct, so the renamer naturally builds an Internal name for
each of its binders. Then in tcRnStmt they are externalised via
TcRnDriver.externaliseAndTidyId, so they get Names like Ghic4.foo.
- Ids bound by the debugger etc have Names constructed by
IfaceEnv.newInteractiveBinder; at the call sites it is followed by
mkVanillaGlobal or mkVanillaGlobalWithInfo. So again, they are
all Global, External.
- TyCons, Classes, and Ids bound by other top-level declarations in
GHCi (eg foreign import, record selectors) also get External
Names, with Ghci9 (or 8, or 7, etc) as the module name.
Note [ic_tythings]
~~~~~~~~~~~~~~~~~~
The ic_tythings field contains
* The TyThings declared by the user at the command prompt
(eg Ids, TyCons, Classes)
* The user-visible Ids that arise from such things, which
*don't* come from 'implicitTyThings', notably:
- record selectors
- class ops
The implicitTyThings are readily obtained from the TyThings
but record selectors etc are not
It does *not* contain
* DFunIds (they can be gotten from ic_instances)
* CoAxioms (ditto)
See also Note [Interactively-bound Ids in GHCi]
Note [Override identical instances in GHCi]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If you declare a new instance in GHCi that is identical to a previous one,
we simply override the previous one; we don't regard it as overlapping.
e.g. Prelude> data T = A | B
Prelude> instance Eq T where ...
Prelude> instance Eq T where ... -- This one overrides
It's exactly the same for type-family instances. See Trac #7102
-}
-- | Interactive context, recording information about the state of the
-- context in which statements are executed in a GHC session.
data InteractiveContext
= InteractiveContext {
ic_dflags :: DynFlags,
-- ^ The 'DynFlags' used to evaluate interative expressions
-- and statements.
ic_mod_index :: Int,
-- ^ Each GHCi stmt or declaration brings some new things into
-- scope. We give them names like interactive:Ghci9.T,
-- where the ic_index is the '9'. The ic_mod_index is
-- incremented whenever we add something to ic_tythings
-- See Note [The interactive package]
ic_imports :: [InteractiveImport],
-- ^ The GHCi top-level scope (ic_rn_gbl_env) is extended with
-- these imports
--
-- This field is only stored here so that the client
-- can retrieve it with GHC.getContext. GHC itself doesn't
-- use it, but does reset it to empty sometimes (such
-- as before a GHC.load). The context is set with GHC.setContext.
ic_tythings :: [TyThing],
-- ^ TyThings defined by the user, in reverse order of
-- definition (ie most recent at the front)
-- See Note [ic_tythings]
ic_rn_gbl_env :: GlobalRdrEnv,
-- ^ The cached 'GlobalRdrEnv', built by
-- 'InteractiveEval.setContext' and updated regularly
-- It contains everything in scope at the command line,
-- including everything in ic_tythings
ic_instances :: ([ClsInst], [FamInst]),
-- ^ All instances and family instances created during
-- this session. These are grabbed en masse after each
-- update to be sure that proper overlapping is retained.
-- That is, rather than re-check the overlapping each
-- time we update the context, we just take the results
-- from the instance code that already does that.
ic_fix_env :: FixityEnv,
-- ^ Fixities declared in let statements
ic_default :: Maybe [Type],
-- ^ The current default types, set by a 'default' declaration
#ifdef GHCI
ic_resume :: [Resume],
-- ^ The stack of breakpoint contexts
#endif
ic_monad :: Name,
-- ^ The monad that GHCi is executing in
ic_int_print :: Name,
-- ^ The function that is used for printing results
-- of expressions in ghci and -e mode.
ic_cwd :: Maybe FilePath
-- virtual CWD of the program
}
data InteractiveImport
= IIDecl (ImportDecl RdrName)
-- ^ Bring the exports of a particular module
-- (filtered by an import decl) into scope
| IIModule ModuleName
-- ^ Bring into scope the entire top-level envt of
-- of this module, including the things imported
-- into it.
-- | Constructs an empty InteractiveContext.
emptyInteractiveContext :: DynFlags -> InteractiveContext
emptyInteractiveContext dflags
= InteractiveContext {
ic_dflags = dflags,
ic_imports = [],
ic_rn_gbl_env = emptyGlobalRdrEnv,
ic_mod_index = 1,
ic_tythings = [],
ic_instances = ([],[]),
ic_fix_env = emptyNameEnv,
ic_monad = ioTyConName, -- IO monad by default
ic_int_print = printName, -- System.IO.print by default
ic_default = Nothing,
#ifdef GHCI
ic_resume = [],
#endif
ic_cwd = Nothing }
icInteractiveModule :: InteractiveContext -> Module
icInteractiveModule (InteractiveContext { ic_mod_index = index })
= mkInteractiveModule index
-- | This function returns the list of visible TyThings (useful for
-- e.g. showBindings)
icInScopeTTs :: InteractiveContext -> [TyThing]
icInScopeTTs = ic_tythings
-- | Get the PrintUnqualified function based on the flags and this InteractiveContext
icPrintUnqual :: DynFlags -> InteractiveContext -> PrintUnqualified
icPrintUnqual dflags InteractiveContext{ ic_rn_gbl_env = grenv } =
mkPrintUnqualified dflags grenv
-- | extendInteractiveContext is called with new TyThings recently defined to update the
-- InteractiveContext to include them. Ids are easily removed when shadowed,
-- but Classes and TyCons are not. Some work could be done to determine
-- whether they are entirely shadowed, but as you could still have references
-- to them (e.g. instances for classes or values of the type for TyCons), it's
-- not clear whether removing them is even the appropriate behavior.
extendInteractiveContext :: InteractiveContext
-> [TyThing]
-> [ClsInst] -> [FamInst]
-> Maybe [Type]
-> FixityEnv
-> InteractiveContext
extendInteractiveContext ictxt new_tythings new_cls_insts new_fam_insts defaults fix_env
= ictxt { ic_mod_index = ic_mod_index ictxt + 1
-- Always bump this; even instances should create
-- a new mod_index (Trac #9426)
, ic_tythings = new_tythings ++ old_tythings
, ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings
, ic_instances = ( new_cls_insts ++ old_cls_insts
, new_fam_insts ++ old_fam_insts )
, ic_default = defaults
, ic_fix_env = fix_env -- See Note [Fixity declarations in GHCi]
}
where
new_ids = [id | AnId id <- new_tythings]
old_tythings = filterOut (shadowed_by new_ids) (ic_tythings ictxt)
-- Discard old instances that have been fully overrridden
-- See Note [Override identical instances in GHCi]
(cls_insts, fam_insts) = ic_instances ictxt
old_cls_insts = filterOut (\i -> any (identicalClsInstHead i) new_cls_insts) cls_insts
old_fam_insts = filterOut (\i -> any (identicalFamInstHead i) new_fam_insts) fam_insts
extendInteractiveContextWithIds :: InteractiveContext -> [Id] -> InteractiveContext
-- Just a specialised version
extendInteractiveContextWithIds ictxt new_ids
| null new_ids = ictxt
| otherwise = ictxt { ic_mod_index = ic_mod_index ictxt + 1
, ic_tythings = new_tythings ++ old_tythings
, ic_rn_gbl_env = ic_rn_gbl_env ictxt `icExtendGblRdrEnv` new_tythings }
where
new_tythings = map AnId new_ids
old_tythings = filterOut (shadowed_by new_ids) (ic_tythings ictxt)
shadowed_by :: [Id] -> TyThing -> Bool
shadowed_by ids = shadowed
where
shadowed id = getOccName id `elemOccSet` new_occs
new_occs = mkOccSet (map getOccName ids)
setInteractivePackage :: HscEnv -> HscEnv
-- Set the 'thisPackage' DynFlag to 'interactive'
setInteractivePackage hsc_env
= hsc_env { hsc_dflags = (hsc_dflags hsc_env) { thisPackage = interactiveUnitId } }
setInteractivePrintName :: InteractiveContext -> Name -> InteractiveContext
setInteractivePrintName ic n = ic{ic_int_print = n}
-- ToDo: should not add Ids to the gbl env here
-- | Add TyThings to the GlobalRdrEnv, earlier ones in the list shadowing
-- later ones, and shadowing existing entries in the GlobalRdrEnv.
icExtendGblRdrEnv :: GlobalRdrEnv -> [TyThing] -> GlobalRdrEnv
icExtendGblRdrEnv env tythings
= foldr add env tythings -- Foldr makes things in the front of
-- the list shadow things at the back
where
-- One at a time, to ensure each shadows the previous ones
add thing env
| is_sub_bndr thing
= env
| otherwise
= foldl extendGlobalRdrEnv env1 (concatMap localGREsFromAvail avail)
where
env1 = shadowNames env (concatMap availNames avail)
avail = tyThingAvailInfo thing
-- Ugh! The new_tythings may include record selectors, since they
-- are not implicit-ids, and must appear in the TypeEnv. But they
-- will also be brought into scope by the corresponding (ATyCon
-- tc). And we want the latter, because that has the correct
-- parent (Trac #10520)
is_sub_bndr (AnId f) = case idDetails f of
RecSelId {} -> True
ClassOpId {} -> True
_ -> False
is_sub_bndr _ = False
substInteractiveContext :: InteractiveContext -> TCvSubst -> InteractiveContext
substInteractiveContext ictxt@InteractiveContext{ ic_tythings = tts } subst
| isEmptyTCvSubst subst = ictxt
| otherwise = ictxt { ic_tythings = map subst_ty tts }
where
subst_ty (AnId id) = AnId $ id `setIdType` substTyUnchecked subst (idType id)
subst_ty tt = tt
instance Outputable InteractiveImport where
ppr (IIModule m) = char '*' <> ppr m
ppr (IIDecl d) = ppr d
{-
************************************************************************
* *
Building a PrintUnqualified
* *
************************************************************************
Note [Printing original names]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Deciding how to print names is pretty tricky. We are given a name
P:M.T, where P is the package name, M is the defining module, and T is
the occurrence name, and we have to decide in which form to display
the name given a GlobalRdrEnv describing the current scope.
Ideally we want to display the name in the form in which it is in
scope. However, the name might not be in scope at all, and that's
where it gets tricky. Here are the cases:
1. T uniquely maps to P:M.T ---> "T" NameUnqual
2. There is an X for which X.T
uniquely maps to P:M.T ---> "X.T" NameQual X
3. There is no binding for "M.T" ---> "M.T" NameNotInScope1
4. Otherwise ---> "P:M.T" NameNotInScope2
(3) and (4) apply when the entity P:M.T is not in the GlobalRdrEnv at
all. In these cases we still want to refer to the name as "M.T", *but*
"M.T" might mean something else in the current scope (e.g. if there's
an "import X as M"), so to avoid confusion we avoid using "M.T" if
there's already a binding for it. Instead we write P:M.T.
There's one further subtlety: in case (3), what if there are two
things around, P1:M.T and P2:M.T? Then we don't want to print both of
them as M.T! However only one of the modules P1:M and P2:M can be
exposed (say P2), so we use M.T for that, and P1:M.T for the other one.
This is handled by the qual_mod component of PrintUnqualified, inside
the (ppr mod) of case (3), in Name.pprModulePrefix
Note [Printing unit ids]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the old days, original names were tied to PackageIds, which directly
corresponded to the entities that users wrote in Cabal files, and were perfectly
suitable for printing when we need to disambiguate packages. However, with
UnitId, the situation can be different: if the key is instantiated with
some holes, we should try to give the user some more useful information.
-}
-- | Creates some functions that work out the best ways to format
-- names for the user according to a set of heuristics.
mkPrintUnqualified :: DynFlags -> GlobalRdrEnv -> PrintUnqualified
mkPrintUnqualified dflags env = QueryQualify qual_name
(mkQualModule dflags)
(mkQualPackage dflags)
where
qual_name mod occ
| [gre] <- unqual_gres
, right_name gre
= NameUnqual -- If there's a unique entity that's in scope
-- unqualified with 'occ' AND that entity is
-- the right one, then we can use the unqualified name
| [] <- unqual_gres
, any is_name forceUnqualNames
, not (isDerivedOccName occ)
= NameUnqual -- Don't qualify names that come from modules
-- that come with GHC, often appear in error messages,
-- but aren't typically in scope. Doing this does not
-- cause ambiguity, and it reduces the amount of
-- qualification in error messages thus improving
-- readability.
--
-- A motivating example is 'Constraint'. It's often not
-- in scope, but printing GHC.Prim.Constraint seems
-- overkill.
| [gre] <- qual_gres
= NameQual (greQualModName gre)
| null qual_gres
= if null (lookupGRE_RdrName (mkRdrQual (moduleName mod) occ) env)
then NameNotInScope1
else NameNotInScope2
| otherwise
= NameNotInScope1 -- Can happen if 'f' is bound twice in the module
-- Eg f = True; g = 0; f = False
where
is_name :: Name -> Bool
is_name name = nameModule name == mod && nameOccName name == occ
forceUnqualNames :: [Name]
forceUnqualNames =
map tyConName [ constraintKindTyCon, heqTyCon, coercibleTyCon
, starKindTyCon, unicodeStarKindTyCon ]
++ [ eqTyConName ]
right_name gre = nameModule_maybe (gre_name gre) == Just mod
unqual_gres = lookupGRE_RdrName (mkRdrUnqual occ) env
qual_gres = filter right_name (lookupGlobalRdrEnv env occ)
-- we can mention a module P:M without the P: qualifier iff
-- "import M" would resolve unambiguously to P:M. (if P is the
-- current package we can just assume it is unqualified).
-- | Creates a function for formatting modules based on two heuristics:
-- (1) if the module is the current module, don't qualify, and (2) if there
-- is only one exposed package which exports this module, don't qualify.
mkQualModule :: DynFlags -> QueryQualifyModule
mkQualModule dflags mod
| moduleUnitId mod == thisPackage dflags = False
| [(_, pkgconfig)] <- lookup,
packageConfigId pkgconfig == moduleUnitId mod
-- this says: we are given a module P:M, is there just one exposed package
-- that exposes a module M, and is it package P?
= False
| otherwise = True
where lookup = lookupModuleInAllPackages dflags (moduleName mod)
-- | Creates a function for formatting packages based on two heuristics:
-- (1) don't qualify if the package in question is "main", and (2) only qualify
-- with a unit id if the package ID would be ambiguous.
mkQualPackage :: DynFlags -> QueryQualifyPackage
mkQualPackage dflags pkg_key
| pkg_key == mainUnitId || pkg_key == interactiveUnitId
-- Skip the lookup if it's main, since it won't be in the package
-- database!
= False
| Just pkgid <- mb_pkgid
, searchPackageId dflags pkgid `lengthIs` 1
-- this says: we are given a package pkg-0.1@MMM, are there only one
-- exposed packages whose package ID is pkg-0.1?
= False
| otherwise
= True
where mb_pkgid = fmap sourcePackageId (lookupPackage dflags pkg_key)
-- | A function which only qualifies package names if necessary; but
-- qualifies all other identifiers.
pkgQual :: DynFlags -> PrintUnqualified
pkgQual dflags = alwaysQualify {
queryQualifyPackage = mkQualPackage dflags
}
{-
************************************************************************
* *
Implicit TyThings
* *
************************************************************************
Note [Implicit TyThings]
~~~~~~~~~~~~~~~~~~~~~~~~
DEFINITION: An "implicit" TyThing is one that does not have its own
IfaceDecl in an interface file. Instead, its binding in the type
environment is created as part of typechecking the IfaceDecl for
some other thing.
Examples:
* All DataCons are implicit, because they are generated from the
IfaceDecl for the data/newtype. Ditto class methods.
* Record selectors are *not* implicit, because they get their own
free-standing IfaceDecl.
* Associated data/type families are implicit because they are
included in the IfaceDecl of the parent class. (NB: the
IfaceClass decl happens to use IfaceDecl recursively for the
associated types, but that's irrelevant here.)
* Dictionary function Ids are not implicit.
* Axioms for newtypes are implicit (same as above), but axioms
for data/type family instances are *not* implicit (like DFunIds).
-}
-- | Determine the 'TyThing's brought into scope by another 'TyThing'
-- /other/ than itself. For example, Id's don't have any implicit TyThings
-- as they just bring themselves into scope, but classes bring their
-- dictionary datatype, type constructor and some selector functions into
-- scope, just for a start!
-- N.B. the set of TyThings returned here *must* match the set of
-- names returned by LoadIface.ifaceDeclImplicitBndrs, in the sense that
-- TyThing.getOccName should define a bijection between the two lists.
-- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
-- The order of the list does not matter.
implicitTyThings :: TyThing -> [TyThing]
implicitTyThings (AnId _) = []
implicitTyThings (ACoAxiom _cc) = []
implicitTyThings (ATyCon tc) = implicitTyConThings tc
implicitTyThings (AConLike cl) = implicitConLikeThings cl
implicitConLikeThings :: ConLike -> [TyThing]
implicitConLikeThings (RealDataCon dc)
= dataConImplicitTyThings dc
implicitConLikeThings (PatSynCon {})
= [] -- Pattern synonyms have no implicit Ids; the wrapper and matcher
-- are not "implicit"; they are simply new top-level bindings,
-- and they have their own declaration in an interface file
-- Unless a record pat syn when there are implicit selectors
-- They are still not included here as `implicitConLikeThings` is
-- used by `tcTyClsDecls` whilst pattern synonyms are typed checked
-- by `tcTopValBinds`.
implicitClassThings :: Class -> [TyThing]
implicitClassThings cl
= -- Does not include default methods, because those Ids may have
-- their own pragmas, unfoldings etc, not derived from the Class object
-- associated types
-- No recursive call for the classATs, because they
-- are only the family decls; they have no implicit things
map ATyCon (classATs cl) ++
-- superclass and operation selectors
map AnId (classAllSelIds cl)
implicitTyConThings :: TyCon -> [TyThing]
implicitTyConThings tc
= class_stuff ++
-- fields (names of selectors)
-- (possibly) implicit newtype axioms
-- or type family axioms
implicitCoTyCon tc ++
-- for each data constructor in order,
-- the contructor, worker, and (possibly) wrapper
[ thing | dc <- tyConDataCons tc
, thing <- AConLike (RealDataCon dc) : dataConImplicitTyThings dc ]
-- NB. record selectors are *not* implicit, they have fully-fledged
-- bindings that pass through the compilation pipeline as normal.
where
class_stuff = case tyConClass_maybe tc of
Nothing -> []
Just cl -> implicitClassThings cl
-- For newtypes and closed type families (only) add the implicit coercion tycon
implicitCoTyCon :: TyCon -> [TyThing]
implicitCoTyCon tc
| Just co <- newTyConCo_maybe tc = [ACoAxiom $ toBranchedAxiom co]
| Just co <- isClosedSynFamilyTyConWithAxiom_maybe tc
= [ACoAxiom co]
| otherwise = []
-- | Returns @True@ if there should be no interface-file declaration
-- for this thing on its own: either it is built-in, or it is part
-- of some other declaration, or it is generated implicitly by some
-- other declaration.
isImplicitTyThing :: TyThing -> Bool
isImplicitTyThing (AConLike cl) = case cl of
RealDataCon {} -> True
PatSynCon {} -> False
isImplicitTyThing (AnId id) = isImplicitId id
isImplicitTyThing (ATyCon tc) = isImplicitTyCon tc
isImplicitTyThing (ACoAxiom ax) = isImplicitCoAxiom ax
-- | tyThingParent_maybe x returns (Just p)
-- when pprTyThingInContext sould print a declaration for p
-- (albeit with some "..." in it) when asked to show x
-- It returns the *immediate* parent. So a datacon returns its tycon
-- but the tycon could be the associated type of a class, so it in turn
-- might have a parent.
tyThingParent_maybe :: TyThing -> Maybe TyThing
tyThingParent_maybe (AConLike cl) = case cl of
RealDataCon dc -> Just (ATyCon (dataConTyCon dc))
PatSynCon{} -> Nothing
tyThingParent_maybe (ATyCon tc) = case tyConAssoc_maybe tc of
Just cls -> Just (ATyCon (classTyCon cls))
Nothing -> Nothing
tyThingParent_maybe (AnId id) = case idDetails id of
RecSelId { sel_tycon = RecSelData tc } ->
Just (ATyCon tc)
ClassOpId cls ->
Just (ATyCon (classTyCon cls))
_other -> Nothing
tyThingParent_maybe _other = Nothing
tyThingsTyCoVars :: [TyThing] -> TyCoVarSet
tyThingsTyCoVars tts =
unionVarSets $ map ttToVarSet tts
where
ttToVarSet (AnId id) = tyCoVarsOfType $ idType id
ttToVarSet (AConLike cl) = case cl of
RealDataCon dc -> tyCoVarsOfType $ dataConRepType dc
PatSynCon{} -> emptyVarSet
ttToVarSet (ATyCon tc)
= case tyConClass_maybe tc of
Just cls -> (mkVarSet . fst . classTvsFds) cls
Nothing -> tyCoVarsOfType $ tyConKind tc
ttToVarSet (ACoAxiom _) = emptyVarSet
-- | The Names that a TyThing should bring into scope. Used to build
-- the GlobalRdrEnv for the InteractiveContext.
tyThingAvailInfo :: TyThing -> [AvailInfo]
tyThingAvailInfo (ATyCon t)
= case tyConClass_maybe t of
Just c -> [AvailTC n (n : map getName (classMethods c)
++ map getName (classATs c))
[] ]
where n = getName c
Nothing -> [AvailTC n (n : map getName dcs) flds]
where n = getName t
dcs = tyConDataCons t
flds = tyConFieldLabels t
tyThingAvailInfo (AConLike (PatSynCon p))
= map patSynAvail ((getName p) : map flSelector (patSynFieldLabels p))
tyThingAvailInfo t
= [avail (getName t)]
{-
************************************************************************
* *
TypeEnv
* *
************************************************************************
-}
-- | A map from 'Name's to 'TyThing's, constructed by typechecking
-- local declarations or interface files
type TypeEnv = NameEnv TyThing
emptyTypeEnv :: TypeEnv
typeEnvElts :: TypeEnv -> [TyThing]
typeEnvTyCons :: TypeEnv -> [TyCon]
typeEnvCoAxioms :: TypeEnv -> [CoAxiom Branched]
typeEnvIds :: TypeEnv -> [Id]
typeEnvPatSyns :: TypeEnv -> [PatSyn]
typeEnvDataCons :: TypeEnv -> [DataCon]
typeEnvClasses :: TypeEnv -> [Class]
lookupTypeEnv :: TypeEnv -> Name -> Maybe TyThing
emptyTypeEnv = emptyNameEnv
typeEnvElts env = nameEnvElts env
typeEnvTyCons env = [tc | ATyCon tc <- typeEnvElts env]
typeEnvCoAxioms env = [ax | ACoAxiom ax <- typeEnvElts env]
typeEnvIds env = [id | AnId id <- typeEnvElts env]
typeEnvPatSyns env = [ps | AConLike (PatSynCon ps) <- typeEnvElts env]
typeEnvDataCons env = [dc | AConLike (RealDataCon dc) <- typeEnvElts env]
typeEnvClasses env = [cl | tc <- typeEnvTyCons env,
Just cl <- [tyConClass_maybe tc]]
mkTypeEnv :: [TyThing] -> TypeEnv
mkTypeEnv things = extendTypeEnvList emptyTypeEnv things
mkTypeEnvWithImplicits :: [TyThing] -> TypeEnv
mkTypeEnvWithImplicits things =
mkTypeEnv things
`plusNameEnv`
mkTypeEnv (concatMap implicitTyThings things)
typeEnvFromEntities :: [Id] -> [TyCon] -> [FamInst] -> TypeEnv
typeEnvFromEntities ids tcs famInsts =
mkTypeEnv ( map AnId ids
++ map ATyCon all_tcs
++ concatMap implicitTyConThings all_tcs
++ map (ACoAxiom . toBranchedAxiom . famInstAxiom) famInsts
)
where
all_tcs = tcs ++ famInstsRepTyCons famInsts
lookupTypeEnv = lookupNameEnv
-- Extend the type environment
extendTypeEnv :: TypeEnv -> TyThing -> TypeEnv
extendTypeEnv env thing = extendNameEnv env (getName thing) thing
extendTypeEnvList :: TypeEnv -> [TyThing] -> TypeEnv
extendTypeEnvList env things = foldl extendTypeEnv env things
extendTypeEnvWithIds :: TypeEnv -> [Id] -> TypeEnv
extendTypeEnvWithIds env ids
= extendNameEnvList env [(getName id, AnId id) | id <- ids]
-- | Find the 'TyThing' for the given 'Name' by using all the resources
-- at our disposal: the compiled modules in the 'HomePackageTable' and the
-- compiled modules in other packages that live in 'PackageTypeEnv'. Note
-- that this does NOT look up the 'TyThing' in the module being compiled: you
-- have to do that yourself, if desired
lookupType :: DynFlags
-> HomePackageTable
-> PackageTypeEnv
-> Name
-> Maybe TyThing
lookupType dflags hpt pte name
| isOneShot (ghcMode dflags) -- in one-shot, we don't use the HPT
= lookupNameEnv pte name
| otherwise
= case lookupHptByModule hpt mod of
Just hm -> lookupNameEnv (md_types (hm_details hm)) name
Nothing -> lookupNameEnv pte name
where
mod = ASSERT2( isExternalName name, ppr name ) nameModule name
-- | As 'lookupType', but with a marginally easier-to-use interface
-- if you have a 'HscEnv'
lookupTypeHscEnv :: HscEnv -> Name -> IO (Maybe TyThing)
lookupTypeHscEnv hsc_env name = do
eps <- readIORef (hsc_EPS hsc_env)
return $! lookupType dflags hpt (eps_PTE eps) name
where
dflags = hsc_dflags hsc_env
hpt = hsc_HPT hsc_env
-- | Get the 'TyCon' from a 'TyThing' if it is a type constructor thing. Panics otherwise
tyThingTyCon :: TyThing -> TyCon
tyThingTyCon (ATyCon tc) = tc
tyThingTyCon other = pprPanic "tyThingTyCon" (pprTyThing other)
-- | Get the 'CoAxiom' from a 'TyThing' if it is a coercion axiom thing. Panics otherwise
tyThingCoAxiom :: TyThing -> CoAxiom Branched
tyThingCoAxiom (ACoAxiom ax) = ax
tyThingCoAxiom other = pprPanic "tyThingCoAxiom" (pprTyThing other)
-- | Get the 'DataCon' from a 'TyThing' if it is a data constructor thing. Panics otherwise
tyThingDataCon :: TyThing -> DataCon
tyThingDataCon (AConLike (RealDataCon dc)) = dc
tyThingDataCon other = pprPanic "tyThingDataCon" (pprTyThing other)
-- | Get the 'Id' from a 'TyThing' if it is a id *or* data constructor thing. Panics otherwise
tyThingId :: TyThing -> Id
tyThingId (AnId id) = id
tyThingId (AConLike (RealDataCon dc)) = dataConWrapId dc
tyThingId other = pprPanic "tyThingId" (pprTyThing other)
{-
************************************************************************
* *
\subsection{MonadThings and friends}
* *
************************************************************************
-}
-- | Class that abstracts out the common ability of the monads in GHC
-- to lookup a 'TyThing' in the monadic environment by 'Name'. Provides
-- a number of related convenience functions for accessing particular
-- kinds of 'TyThing'
class Monad m => MonadThings m where
lookupThing :: Name -> m TyThing
lookupId :: Name -> m Id
lookupId = liftM tyThingId . lookupThing
lookupDataCon :: Name -> m DataCon
lookupDataCon = liftM tyThingDataCon . lookupThing
lookupTyCon :: Name -> m TyCon
lookupTyCon = liftM tyThingTyCon . lookupThing
{-
************************************************************************
* *
\subsection{Auxiliary types}
* *
************************************************************************
These types are defined here because they are mentioned in ModDetails,
but they are mostly elaborated elsewhere
-}
------------------ Warnings -------------------------
-- | Warning information for a module
data Warnings
= NoWarnings -- ^ Nothing deprecated
| WarnAll WarningTxt -- ^ Whole module deprecated
| WarnSome [(OccName,WarningTxt)] -- ^ Some specific things deprecated
-- Only an OccName is needed because
-- (1) a deprecation always applies to a binding
-- defined in the module in which the deprecation appears.
-- (2) deprecations are only reported outside the defining module.
-- this is important because, otherwise, if we saw something like
--
-- {-# DEPRECATED f "" #-}
-- f = ...
-- h = f
-- g = let f = undefined in f
--
-- we'd need more information than an OccName to know to say something
-- about the use of f in h but not the use of the locally bound f in g
--
-- however, because we only report about deprecations from the outside,
-- and a module can only export one value called f,
-- an OccName suffices.
--
-- this is in contrast with fixity declarations, where we need to map
-- a Name to its fixity declaration.
deriving( Eq )
instance Binary Warnings where
put_ bh NoWarnings = putByte bh 0
put_ bh (WarnAll t) = do
putByte bh 1
put_ bh t
put_ bh (WarnSome ts) = do
putByte bh 2
put_ bh ts
get bh = do
h <- getByte bh
case h of
0 -> return NoWarnings
1 -> do aa <- get bh
return (WarnAll aa)
_ -> do aa <- get bh
return (WarnSome aa)
-- | Constructs the cache for the 'mi_warn_fn' field of a 'ModIface'
mkIfaceWarnCache :: Warnings -> OccName -> Maybe WarningTxt
mkIfaceWarnCache NoWarnings = \_ -> Nothing
mkIfaceWarnCache (WarnAll t) = \_ -> Just t
mkIfaceWarnCache (WarnSome pairs) = lookupOccEnv (mkOccEnv pairs)
emptyIfaceWarnCache :: OccName -> Maybe WarningTxt
emptyIfaceWarnCache _ = Nothing
plusWarns :: Warnings -> Warnings -> Warnings
plusWarns d NoWarnings = d
plusWarns NoWarnings d = d
plusWarns _ (WarnAll t) = WarnAll t
plusWarns (WarnAll t) _ = WarnAll t
plusWarns (WarnSome v1) (WarnSome v2) = WarnSome (v1 ++ v2)
-- | Creates cached lookup for the 'mi_fix_fn' field of 'ModIface'
mkIfaceFixCache :: [(OccName, Fixity)] -> OccName -> Maybe Fixity
mkIfaceFixCache pairs
= \n -> lookupOccEnv env n
where
env = mkOccEnv pairs
emptyIfaceFixCache :: OccName -> Maybe Fixity
emptyIfaceFixCache _ = Nothing
-- | Fixity environment mapping names to their fixities
type FixityEnv = NameEnv FixItem
-- | Fixity information for an 'Name'. We keep the OccName in the range
-- so that we can generate an interface from it
data FixItem = FixItem OccName Fixity
instance Outputable FixItem where
ppr (FixItem occ fix) = ppr fix <+> ppr occ
emptyFixityEnv :: FixityEnv
emptyFixityEnv = emptyNameEnv
lookupFixity :: FixityEnv -> Name -> Fixity
lookupFixity env n = case lookupNameEnv env n of
Just (FixItem _ fix) -> fix
Nothing -> defaultFixity
{-
************************************************************************
* *
\subsection{WhatsImported}
* *
************************************************************************
-}
-- | Records whether a module has orphans. An \"orphan\" is one of:
--
-- * An instance declaration in a module other than the definition
-- module for one of the type constructors or classes in the instance head
--
-- * A transformation rule in a module other than the one defining
-- the function in the head of the rule
--
-- * A vectorisation pragma
type WhetherHasOrphans = Bool
-- | Does this module define family instances?
type WhetherHasFamInst = Bool
-- | Did this module originate from a *-boot file?
type IsBootInterface = Bool
-- | Dependency information about ALL modules and packages below this one
-- in the import hierarchy.
--
-- Invariant: the dependencies of a module @M@ never includes @M@.
--
-- Invariant: none of the lists contain duplicates.
data Dependencies
= Deps { dep_mods :: [(ModuleName, IsBootInterface)]
-- ^ All home-package modules transitively below this one
-- I.e. modules that this one imports, or that are in the
-- dep_mods of those directly-imported modules
, dep_pkgs :: [(UnitId, Bool)]
-- ^ All packages transitively below this module
-- I.e. packages to which this module's direct imports belong,
-- or that are in the dep_pkgs of those modules
-- The bool indicates if the package is required to be
-- trusted when the module is imported as a safe import
-- (Safe Haskell). See Note [RnNames . Tracking Trust Transitively]
, dep_orphs :: [Module]
-- ^ Transitive closure of orphan modules (whether
-- home or external pkg).
--
-- (Possible optimization: don't include family
-- instance orphans as they are anyway included in
-- 'dep_finsts'. But then be careful about code
-- which relies on dep_orphs having the complete list!)
, dep_finsts :: [Module]
-- ^ Modules that contain family instances (whether the
-- instances are from the home or an external package)
}
deriving( Eq )
-- Equality used only for old/new comparison in MkIface.addFingerprints
-- See 'TcRnTypes.ImportAvails' for details on dependencies.
instance Binary Dependencies where
put_ bh deps = do put_ bh (dep_mods deps)
put_ bh (dep_pkgs deps)
put_ bh (dep_orphs deps)
put_ bh (dep_finsts deps)
get bh = do ms <- get bh
ps <- get bh
os <- get bh
fis <- get bh
return (Deps { dep_mods = ms, dep_pkgs = ps, dep_orphs = os,
dep_finsts = fis })
noDependencies :: Dependencies
noDependencies = Deps [] [] [] []
-- | Records modules for which changes may force recompilation of this module
-- See wiki: http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance
--
-- This differs from Dependencies. A module X may be in the dep_mods of this
-- module (via an import chain) but if we don't use anything from X it won't
-- appear in our Usage
data Usage
-- | Module from another package
= UsagePackageModule {
usg_mod :: Module,
-- ^ External package module depended on
usg_mod_hash :: Fingerprint,
-- ^ Cached module fingerprint
usg_safe :: IsSafeImport
-- ^ Was this module imported as a safe import
}
-- | Module from the current package
| UsageHomeModule {
usg_mod_name :: ModuleName,
-- ^ Name of the module
usg_mod_hash :: Fingerprint,
-- ^ Cached module fingerprint
usg_entities :: [(OccName,Fingerprint)],
-- ^ Entities we depend on, sorted by occurrence name and fingerprinted.
-- NB: usages are for parent names only, e.g. type constructors
-- but not the associated data constructors.
usg_exports :: Maybe Fingerprint,
-- ^ Fingerprint for the export list of this module,
-- if we directly imported it (and hence we depend on its export list)
usg_safe :: IsSafeImport
-- ^ Was this module imported as a safe import
} -- ^ Module from the current package
-- | A file upon which the module depends, e.g. a CPP #include, or using TH's
-- 'addDependentFile'
| UsageFile {
usg_file_path :: FilePath,
-- ^ External file dependency. From a CPP #include or TH
-- addDependentFile. Should be absolute.
usg_file_hash :: Fingerprint
-- ^ 'Fingerprint' of the file contents.
-- Note: We don't consider things like modification timestamps
-- here, because there's no reason to recompile if the actual
-- contents don't change. This previously lead to odd
-- recompilation behaviors; see #8114
}
deriving( Eq )
-- The export list field is (Just v) if we depend on the export list:
-- i.e. we imported the module directly, whether or not we
-- enumerated the things we imported, or just imported
-- everything
-- We need to recompile if M's exports change, because
-- if the import was import M, we might now have a name clash
-- in the importing module.
-- if the import was import M(x) M might no longer export x
-- The only way we don't depend on the export list is if we have
-- import M()
-- And of course, for modules that aren't imported directly we don't
-- depend on their export lists
instance Binary Usage where
put_ bh usg@UsagePackageModule{} = do
putByte bh 0
put_ bh (usg_mod usg)
put_ bh (usg_mod_hash usg)
put_ bh (usg_safe usg)
put_ bh usg@UsageHomeModule{} = do
putByte bh 1
put_ bh (usg_mod_name usg)
put_ bh (usg_mod_hash usg)
put_ bh (usg_exports usg)
put_ bh (usg_entities usg)
put_ bh (usg_safe usg)
put_ bh usg@UsageFile{} = do
putByte bh 2
put_ bh (usg_file_path usg)
put_ bh (usg_file_hash usg)
get bh = do
h <- getByte bh
case h of
0 -> do
nm <- get bh
mod <- get bh
safe <- get bh
return UsagePackageModule { usg_mod = nm, usg_mod_hash = mod, usg_safe = safe }
1 -> do
nm <- get bh
mod <- get bh
exps <- get bh
ents <- get bh
safe <- get bh
return UsageHomeModule { usg_mod_name = nm, usg_mod_hash = mod,
usg_exports = exps, usg_entities = ents, usg_safe = safe }
2 -> do
fp <- get bh
hash <- get bh
return UsageFile { usg_file_path = fp, usg_file_hash = hash }
i -> error ("Binary.get(Usage): " ++ show i)
{-
************************************************************************
* *
The External Package State
* *
************************************************************************
-}
type PackageTypeEnv = TypeEnv
type PackageRuleBase = RuleBase
type PackageInstEnv = InstEnv
type PackageFamInstEnv = FamInstEnv
type PackageVectInfo = VectInfo
type PackageAnnEnv = AnnEnv
-- | Information about other packages that we have slurped in by reading
-- their interface files
data ExternalPackageState
= EPS {
eps_is_boot :: !(ModuleNameEnv (ModuleName, IsBootInterface)),
-- ^ In OneShot mode (only), home-package modules
-- accumulate in the external package state, and are
-- sucked in lazily. For these home-pkg modules
-- (only) we need to record which are boot modules.
-- We set this field after loading all the
-- explicitly-imported interfaces, but before doing
-- anything else
--
-- The 'ModuleName' part is not necessary, but it's useful for
-- debug prints, and it's convenient because this field comes
-- direct from 'TcRnTypes.imp_dep_mods'
eps_PIT :: !PackageIfaceTable,
-- ^ The 'ModIface's for modules in external packages
-- whose interfaces we have opened.
-- The declarations in these interface files are held in the
-- 'eps_decls', 'eps_inst_env', 'eps_fam_inst_env' and 'eps_rules'
-- fields of this record, not in the 'mi_decls' fields of the
-- interface we have sucked in.
--
-- What /is/ in the PIT is:
--
-- * The Module
--
-- * Fingerprint info
--
-- * Its exports
--
-- * Fixities
--
-- * Deprecations and warnings
eps_PTE :: !PackageTypeEnv,
-- ^ Result of typechecking all the external package
-- interface files we have sucked in. The domain of
-- the mapping is external-package modules
eps_inst_env :: !PackageInstEnv, -- ^ The total 'InstEnv' accumulated
-- from all the external-package modules
eps_fam_inst_env :: !PackageFamInstEnv,-- ^ The total 'FamInstEnv' accumulated
-- from all the external-package modules
eps_rule_base :: !PackageRuleBase, -- ^ The total 'RuleEnv' accumulated
-- from all the external-package modules
eps_vect_info :: !PackageVectInfo, -- ^ The total 'VectInfo' accumulated
-- from all the external-package modules
eps_ann_env :: !PackageAnnEnv, -- ^ The total 'AnnEnv' accumulated
-- from all the external-package modules
eps_mod_fam_inst_env :: !(ModuleEnv FamInstEnv), -- ^ The family instances accumulated from external
-- packages, keyed off the module that declared them
eps_stats :: !EpsStats -- ^ Stastics about what was loaded from external packages
}
-- | Accumulated statistics about what we are putting into the 'ExternalPackageState'.
-- \"In\" means stuff that is just /read/ from interface files,
-- \"Out\" means actually sucked in and type-checked
data EpsStats = EpsStats { n_ifaces_in
, n_decls_in, n_decls_out
, n_rules_in, n_rules_out
, n_insts_in, n_insts_out :: !Int }
addEpsInStats :: EpsStats -> Int -> Int -> Int -> EpsStats
-- ^ Add stats for one newly-read interface
addEpsInStats stats n_decls n_insts n_rules
= stats { n_ifaces_in = n_ifaces_in stats + 1
, n_decls_in = n_decls_in stats + n_decls
, n_insts_in = n_insts_in stats + n_insts
, n_rules_in = n_rules_in stats + n_rules }
{-
Names in a NameCache are always stored as a Global, and have the SrcLoc
of their binding locations.
Actually that's not quite right. When we first encounter the original
name, we might not be at its binding site (e.g. we are reading an
interface file); so we give it 'noSrcLoc' then. Later, when we find
its binding site, we fix it up.
-}
-- | The NameCache makes sure that there is just one Unique assigned for
-- each original name; i.e. (module-name, occ-name) pair and provides
-- something of a lookup mechanism for those names.
data NameCache
= NameCache { nsUniqs :: !UniqSupply,
-- ^ Supply of uniques
nsNames :: !OrigNameCache
-- ^ Ensures that one original name gets one unique
}
updNameCacheIO :: HscEnv
-> (NameCache -> (NameCache, c)) -- The updating function
-> IO c
updNameCacheIO hsc_env upd_fn
= atomicModifyIORef' (hsc_NC hsc_env) upd_fn
-- | Per-module cache of original 'OccName's given 'Name's
type OrigNameCache = ModuleEnv (OccEnv Name)
mkSOName :: Platform -> FilePath -> FilePath
mkSOName platform root
= case platformOS platform of
OSDarwin -> ("lib" ++ root) <.> "dylib"
OSMinGW32 -> root <.> "dll"
_ -> ("lib" ++ root) <.> "so"
mkHsSOName :: Platform -> FilePath -> FilePath
mkHsSOName platform root = ("lib" ++ root) <.> soExt platform
soExt :: Platform -> FilePath
soExt platform
= case platformOS platform of
OSDarwin -> "dylib"
OSMinGW32 -> "dll"
_ -> "so"
{-
************************************************************************
* *
The module graph and ModSummary type
A ModSummary is a node in the compilation manager's
dependency graph, and it's also passed to hscMain
* *
************************************************************************
-}
-- | A ModuleGraph contains all the nodes from the home package (only).
-- There will be a node for each source module, plus a node for each hi-boot
-- module.
--
-- The graph is not necessarily stored in topologically-sorted order. Use
-- 'GHC.topSortModuleGraph' and 'Digraph.flattenSCC' to achieve this.
type ModuleGraph = [ModSummary]
emptyMG :: ModuleGraph
emptyMG = []
-- | A single node in a 'ModuleGraph'. The nodes of the module graph
-- are one of:
--
-- * A regular Haskell source module
-- * A hi-boot source module
--
data ModSummary
= ModSummary {
ms_mod :: Module,
-- ^ Identity of the module
ms_hsc_src :: HscSource,
-- ^ The module source either plain Haskell or hs-boot
ms_location :: ModLocation,
-- ^ Location of the various files belonging to the module
ms_hs_date :: UTCTime,
-- ^ Timestamp of source file
ms_obj_date :: Maybe UTCTime,
-- ^ Timestamp of object, if we have one
ms_iface_date :: Maybe UTCTime,
-- ^ Timestamp of hi file, if we *only* are typechecking (it is
-- 'Nothing' otherwise.
-- See Note [Recompilation checking when typechecking only] and #9243
ms_srcimps :: [(Maybe FastString, Located ModuleName)],
-- ^ Source imports of the module
ms_textual_imps :: [(Maybe FastString, Located ModuleName)],
-- ^ Non-source imports of the module from the module *text*
ms_hspp_file :: FilePath,
-- ^ Filename of preprocessed source file
ms_hspp_opts :: DynFlags,
-- ^ Cached flags from @OPTIONS@, @INCLUDE@ and @LANGUAGE@
-- pragmas in the modules source code
ms_hspp_buf :: Maybe StringBuffer
-- ^ The actual preprocessed source, if we have it
}
ms_mod_name :: ModSummary -> ModuleName
ms_mod_name = moduleName . ms_mod
ms_imps :: ModSummary -> [(Maybe FastString, Located ModuleName)]
ms_imps ms =
ms_textual_imps ms ++
map mk_additional_import (dynFlagDependencies (ms_hspp_opts ms))
where
mk_additional_import mod_nm = (Nothing, noLoc mod_nm)
-- The ModLocation contains both the original source filename and the
-- filename of the cleaned-up source file after all preprocessing has been
-- done. The point is that the summariser will have to cpp/unlit/whatever
-- all files anyway, and there's no point in doing this twice -- just
-- park the result in a temp file, put the name of it in the location,
-- and let @compile@ read from that file on the way back up.
-- The ModLocation is stable over successive up-sweeps in GHCi, wheres
-- the ms_hs_date and imports can, of course, change
msHsFilePath, msHiFilePath, msObjFilePath :: ModSummary -> FilePath
msHsFilePath ms = expectJust "msHsFilePath" (ml_hs_file (ms_location ms))
msHiFilePath ms = ml_hi_file (ms_location ms)
msObjFilePath ms = ml_obj_file (ms_location ms)
-- | Did this 'ModSummary' originate from a hs-boot file?
isBootSummary :: ModSummary -> Bool
isBootSummary ms = ms_hsc_src ms == HsBootFile
instance Outputable ModSummary where
ppr ms
= sep [text "ModSummary {",
nest 3 (sep [text "ms_hs_date = " <> text (show (ms_hs_date ms)),
text "ms_mod =" <+> ppr (ms_mod ms)
<> text (hscSourceString (ms_hsc_src ms)) <> comma,
text "ms_textual_imps =" <+> ppr (ms_textual_imps ms),
text "ms_srcimps =" <+> ppr (ms_srcimps ms)]),
char '}'
]
showModMsg :: DynFlags -> HscTarget -> Bool -> ModSummary -> String
showModMsg dflags target recomp mod_summary
= showSDoc dflags $
hsep [text (mod_str ++ replicate (max 0 (16 - length mod_str)) ' '),
char '(', text (normalise $ msHsFilePath mod_summary) <> comma,
case target of
HscInterpreted | recomp
-> text "interpreted"
HscNothing -> text "nothing"
_ | HsigFile == ms_hsc_src mod_summary -> text "nothing"
| otherwise -> text (normalise $ msObjFilePath mod_summary),
char ')']
where
mod = moduleName (ms_mod mod_summary)
mod_str = showPpr dflags mod
++ hscSourceString' dflags mod (ms_hsc_src mod_summary)
-- | Variant of hscSourceString which prints more information for signatures.
-- This can't live in DriverPhases because this would cause a module loop.
hscSourceString' :: DynFlags -> ModuleName -> HscSource -> String
hscSourceString' _ _ HsSrcFile = ""
hscSourceString' _ _ HsBootFile = "[boot]"
hscSourceString' dflags mod HsigFile =
"[" ++ (maybe "abstract sig"
(("sig of "++).showPpr dflags)
(getSigOf dflags mod)) ++ "]"
-- NB: -sig-of could be missing if we're just typechecking
{-
************************************************************************
* *
\subsection{Recmpilation}
* *
************************************************************************
-}
-- | Indicates whether a given module's source has been modified since it
-- was last compiled.
data SourceModified
= SourceModified
-- ^ the source has been modified
| SourceUnmodified
-- ^ the source has not been modified. Compilation may or may
-- not be necessary, depending on whether any dependencies have
-- changed since we last compiled.
| SourceUnmodifiedAndStable
-- ^ the source has not been modified, and furthermore all of
-- its (transitive) dependencies are up to date; it definitely
-- does not need to be recompiled. This is important for two
-- reasons: (a) we can omit the version check in checkOldIface,
-- and (b) if the module used TH splices we don't need to force
-- recompilation.
{-
************************************************************************
* *
\subsection{Hpc Support}
* *
************************************************************************
-}
-- | Information about a modules use of Haskell Program Coverage
data HpcInfo
= HpcInfo
{ hpcInfoTickCount :: Int
, hpcInfoHash :: Int
}
| NoHpcInfo
{ hpcUsed :: AnyHpcUsage -- ^ Is hpc used anywhere on the module \*tree\*?
}
-- | This is used to signal if one of my imports used HPC instrumentation
-- even if there is no module-local HPC usage
type AnyHpcUsage = Bool
emptyHpcInfo :: AnyHpcUsage -> HpcInfo
emptyHpcInfo = NoHpcInfo
-- | Find out if HPC is used by this module or any of the modules
-- it depends upon
isHpcUsed :: HpcInfo -> AnyHpcUsage
isHpcUsed (HpcInfo {}) = True
isHpcUsed (NoHpcInfo { hpcUsed = used }) = used
{-
************************************************************************
* *
\subsection{Vectorisation Support}
* *
************************************************************************
The following information is generated and consumed by the vectorisation
subsystem. It communicates the vectorisation status of declarations from one
module to another.
Why do we need both f and f_v in the ModGuts/ModDetails/EPS version VectInfo
below? We need to know `f' when converting to IfaceVectInfo. However, during
vectorisation, we need to know `f_v', whose `Var' we cannot lookup based
on just the OccName easily in a Core pass.
-}
-- |Vectorisation information for 'ModGuts', 'ModDetails' and 'ExternalPackageState'; see also
-- documentation at 'Vectorise.Env.GlobalEnv'.
--
-- NB: The following tables may also include 'Var's, 'TyCon's and 'DataCon's from imported modules,
-- which have been subsequently vectorised in the current module.
--
data VectInfo
= VectInfo
{ vectInfoVar :: VarEnv (Var , Var ) -- ^ @(f, f_v)@ keyed on @f@
, vectInfoTyCon :: NameEnv (TyCon , TyCon) -- ^ @(T, T_v)@ keyed on @T@
, vectInfoDataCon :: NameEnv (DataCon, DataCon) -- ^ @(C, C_v)@ keyed on @C@
, vectInfoParallelVars :: VarSet -- ^ set of parallel variables
, vectInfoParallelTyCons :: NameSet -- ^ set of parallel type constructors
}
-- |Vectorisation information for 'ModIface'; i.e, the vectorisation information propagated
-- across module boundaries.
--
-- NB: The field 'ifaceVectInfoVar' explicitly contains the workers of data constructors as well as
-- class selectors — i.e., their mappings are /not/ implicitly generated from the data types.
-- Moreover, whether the worker of a data constructor is in 'ifaceVectInfoVar' determines
-- whether that data constructor was vectorised (or is part of an abstractly vectorised type
-- constructor).
--
data IfaceVectInfo
= IfaceVectInfo
{ ifaceVectInfoVar :: [Name] -- ^ All variables in here have a vectorised variant
, ifaceVectInfoTyCon :: [Name] -- ^ All 'TyCon's in here have a vectorised variant;
-- the name of the vectorised variant and those of its
-- data constructors are determined by
-- 'OccName.mkVectTyConOcc' and
-- 'OccName.mkVectDataConOcc'; the names of the
-- isomorphisms are determined by 'OccName.mkVectIsoOcc'
, ifaceVectInfoTyConReuse :: [Name] -- ^ The vectorised form of all the 'TyCon's in here
-- coincides with the unconverted form; the name of the
-- isomorphisms is determined by 'OccName.mkVectIsoOcc'
, ifaceVectInfoParallelVars :: [Name] -- iface version of 'vectInfoParallelVar'
, ifaceVectInfoParallelTyCons :: [Name] -- iface version of 'vectInfoParallelTyCon'
}
noVectInfo :: VectInfo
noVectInfo
= VectInfo emptyVarEnv emptyNameEnv emptyNameEnv emptyVarSet emptyNameSet
plusVectInfo :: VectInfo -> VectInfo -> VectInfo
plusVectInfo vi1 vi2 =
VectInfo (vectInfoVar vi1 `plusVarEnv` vectInfoVar vi2)
(vectInfoTyCon vi1 `plusNameEnv` vectInfoTyCon vi2)
(vectInfoDataCon vi1 `plusNameEnv` vectInfoDataCon vi2)
(vectInfoParallelVars vi1 `unionVarSet` vectInfoParallelVars vi2)
(vectInfoParallelTyCons vi1 `unionNameSet` vectInfoParallelTyCons vi2)
concatVectInfo :: [VectInfo] -> VectInfo
concatVectInfo = foldr plusVectInfo noVectInfo
noIfaceVectInfo :: IfaceVectInfo
noIfaceVectInfo = IfaceVectInfo [] [] [] [] []
isNoIfaceVectInfo :: IfaceVectInfo -> Bool
isNoIfaceVectInfo (IfaceVectInfo l1 l2 l3 l4 l5)
= null l1 && null l2 && null l3 && null l4 && null l5
instance Outputable VectInfo where
ppr info = vcat
[ text "variables :" <+> ppr (vectInfoVar info)
, text "tycons :" <+> ppr (vectInfoTyCon info)
, text "datacons :" <+> ppr (vectInfoDataCon info)
, text "parallel vars :" <+> ppr (vectInfoParallelVars info)
, text "parallel tycons :" <+> ppr (vectInfoParallelTyCons info)
]
instance Outputable IfaceVectInfo where
ppr info = vcat
[ text "variables :" <+> ppr (ifaceVectInfoVar info)
, text "tycons :" <+> ppr (ifaceVectInfoTyCon info)
, text "tycons reuse :" <+> ppr (ifaceVectInfoTyConReuse info)
, text "parallel vars :" <+> ppr (ifaceVectInfoParallelVars info)
, text "parallel tycons :" <+> ppr (ifaceVectInfoParallelTyCons info)
]
instance Binary IfaceVectInfo where
put_ bh (IfaceVectInfo a1 a2 a3 a4 a5) = do
put_ bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
get bh = do
a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
return (IfaceVectInfo a1 a2 a3 a4 a5)
{-
************************************************************************
* *
\subsection{Safe Haskell Support}
* *
************************************************************************
This stuff here is related to supporting the Safe Haskell extension,
primarily about storing under what trust type a module has been compiled.
-}
-- | Is an import a safe import?
type IsSafeImport = Bool
-- | Safe Haskell information for 'ModIface'
-- Simply a wrapper around SafeHaskellMode to sepperate iface and flags
newtype IfaceTrustInfo = TrustInfo SafeHaskellMode
getSafeMode :: IfaceTrustInfo -> SafeHaskellMode
getSafeMode (TrustInfo x) = x
setSafeMode :: SafeHaskellMode -> IfaceTrustInfo
setSafeMode = TrustInfo
noIfaceTrustInfo :: IfaceTrustInfo
noIfaceTrustInfo = setSafeMode Sf_None
trustInfoToNum :: IfaceTrustInfo -> Word8
trustInfoToNum it
= case getSafeMode it of
Sf_None -> 0
Sf_Unsafe -> 1
Sf_Trustworthy -> 2
Sf_Safe -> 3
numToTrustInfo :: Word8 -> IfaceTrustInfo
numToTrustInfo 0 = setSafeMode Sf_None
numToTrustInfo 1 = setSafeMode Sf_Unsafe
numToTrustInfo 2 = setSafeMode Sf_Trustworthy
numToTrustInfo 3 = setSafeMode Sf_Safe
numToTrustInfo 4 = setSafeMode Sf_Safe -- retained for backwards compat, used
-- to be Sf_SafeInfered but we no longer
-- differentiate.
numToTrustInfo n = error $ "numToTrustInfo: bad input number! (" ++ show n ++ ")"
instance Outputable IfaceTrustInfo where
ppr (TrustInfo Sf_None) = text "none"
ppr (TrustInfo Sf_Unsafe) = text "unsafe"
ppr (TrustInfo Sf_Trustworthy) = text "trustworthy"
ppr (TrustInfo Sf_Safe) = text "safe"
instance Binary IfaceTrustInfo where
put_ bh iftrust = putByte bh $ trustInfoToNum iftrust
get bh = getByte bh >>= (return . numToTrustInfo)
{-
************************************************************************
* *
\subsection{Parser result}
* *
************************************************************************
-}
data HsParsedModule = HsParsedModule {
hpm_module :: Located (HsModule RdrName),
hpm_src_files :: [FilePath],
-- ^ extra source files (e.g. from #includes). The lexer collects
-- these from '# <file> <line>' pragmas, which the C preprocessor
-- leaves behind. These files and their timestamps are stored in
-- the .hi file, so that we can force recompilation if any of
-- them change (#3589)
hpm_annotations :: ApiAnns
-- See note [Api annotations] in ApiAnnotation.hs
}
{-
************************************************************************
* *
\subsection{Linkable stuff}
* *
************************************************************************
This stuff is in here, rather than (say) in Linker.hs, because the Linker.hs
stuff is the *dynamic* linker, and isn't present in a stage-1 compiler
-}
-- | Information we can use to dynamically link modules into the compiler
data Linkable = LM {
linkableTime :: UTCTime, -- ^ Time at which this linkable was built
-- (i.e. when the bytecodes were produced,
-- or the mod date on the files)
linkableModule :: Module, -- ^ The linkable module itself
linkableUnlinked :: [Unlinked]
-- ^ Those files and chunks of code we have yet to link.
--
-- INVARIANT: A valid linkable always has at least one 'Unlinked' item.
-- If this list is empty, the Linkable represents a fake linkable, which
-- is generated in HscNothing mode to avoid recompiling modules.
--
-- ToDo: Do items get removed from this list when they get linked?
}
isObjectLinkable :: Linkable -> Bool
isObjectLinkable l = not (null unlinked) && all isObject unlinked
where unlinked = linkableUnlinked l
-- A linkable with no Unlinked's is treated as a BCO. We can
-- generate a linkable with no Unlinked's as a result of
-- compiling a module in HscNothing mode, and this choice
-- happens to work well with checkStability in module GHC.
linkableObjs :: Linkable -> [FilePath]
linkableObjs l = [ f | DotO f <- linkableUnlinked l ]
instance Outputable Linkable where
ppr (LM when_made mod unlinkeds)
= (text "LinkableM" <+> parens (text (show when_made)) <+> ppr mod)
$$ nest 3 (ppr unlinkeds)
-------------------------------------------
-- | Objects which have yet to be linked by the compiler
data Unlinked
= DotO FilePath -- ^ An object file (.o)
| DotA FilePath -- ^ Static archive file (.a)
| DotDLL FilePath -- ^ Dynamically linked library file (.so, .dll, .dylib)
| BCOs CompiledByteCode -- ^ A byte-code object, lives only in memory
#ifndef GHCI
data CompiledByteCode = CompiledByteCodeUndefined
_unusedCompiledByteCode :: CompiledByteCode
_unusedCompiledByteCode = CompiledByteCodeUndefined
data ModBreaks = ModBreaksUndefined
emptyModBreaks :: ModBreaks
emptyModBreaks = ModBreaksUndefined
#endif
instance Outputable Unlinked where
ppr (DotO path) = text "DotO" <+> text path
ppr (DotA path) = text "DotA" <+> text path
ppr (DotDLL path) = text "DotDLL" <+> text path
#ifdef GHCI
ppr (BCOs bcos) = text "BCOs" <+> ppr bcos
#else
ppr (BCOs _) = text "No byte code"
#endif
-- | Is this an actual file on disk we can link in somehow?
isObject :: Unlinked -> Bool
isObject (DotO _) = True
isObject (DotA _) = True
isObject (DotDLL _) = True
isObject _ = False
-- | Is this a bytecode linkable with no file on disk?
isInterpretable :: Unlinked -> Bool
isInterpretable = not . isObject
-- | Retrieve the filename of the linkable if possible. Panic if it is a byte-code object
nameOfObject :: Unlinked -> FilePath
nameOfObject (DotO fn) = fn
nameOfObject (DotA fn) = fn
nameOfObject (DotDLL fn) = fn
nameOfObject other = pprPanic "nameOfObject" (ppr other)
-- | Retrieve the compiled byte-code if possible. Panic if it is a file-based linkable
byteCodeOfObject :: Unlinked -> CompiledByteCode
byteCodeOfObject (BCOs bc) = bc
byteCodeOfObject other = pprPanic "byteCodeOfObject" (ppr other)
| vikraman/ghc | compiler/main/HscTypes.hs | bsd-3-clause | 119,276 | 0 | 21 | 36,411 | 15,231 | 8,485 | 6,746 | 1,405 | 6 |
module Module2.Task4 where
doItYourself = f . g . h
f = logBase 2
g = (^ 3)
h = max 42
| dstarcev/stepic-haskell | src/Module2/Task4.hs | bsd-3-clause | 91 | 0 | 6 | 26 | 44 | 25 | 19 | 5 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
module Database.Relational.Schema.OracleDataDictionary.ConsColumns where
import Data.Int (Int32)
import Database.Record.TH (derivingShow)
import Database.Relational.Query.TH (defineTableTypesAndRecordDefault)
$(defineTableTypesAndRecordDefault
"SYS" "dba_cons_columns"
-- Column NULL? Datatype
-- ----------------------------------------- -------- ----------------------------
-- OWNER NOT NULL VARCHAR2(30)
[ ("owner", [t|String|])
-- CONSTRAINT_NAME NOT NULL VARCHAR2(30)
, ("constraint_name", [t|String|])
-- TABLE_NAME NOT NULL VARCHAR2(30)
, ("table_name", [t|String|])
-- COLUMN_NAME VARCHAR2(4000)
, ("column_name", [t|Maybe String|])
-- POSITION NUMBER
, ("position", [t|Maybe Int32|])
] [derivingShow])
| amutake/haskell-relational-record-driver-oracle | src/Database/Relational/Schema/OracleDataDictionary/ConsColumns.hs | bsd-3-clause | 1,052 | 0 | 9 | 343 | 135 | 96 | 39 | 14 | 0 |
module Import.NoFoundation
( module Import
) where
import ClassyPrelude.Yesod as Import
import Control.Concurrent.STM.TBMQueue as Import
import Lens as Import
import Model as Import
import RPC as Import
import Settings as Import
import Settings.StaticFiles as Import
import Types as Import
import Yesod.Auth as Import
import Yesod.Core.Types as Import (loggerSet)
import Yesod.Default.Config2 as Import
| konn/leport | leport-web/Import/NoFoundation.hs | bsd-3-clause | 611 | 0 | 5 | 260 | 88 | 65 | 23 | 13 | 0 |
module OIS ( module OIS.OISEvents
, module OIS.OISFactoryCreator
, module OIS.OISInputManager
, module OIS.OISInterface
, module OIS.OISJoyStick
, module OIS.OISKeyboard
, module OIS.OISMouse
, module OIS.OISMultiTouch
, module OIS.OISObject
, module OIS.OISPrereqs
) where
import OIS.OISEvents
import OIS.OISFactoryCreator
import OIS.OISInputManager
import OIS.OISInterface
import OIS.OISJoyStick
import OIS.OISKeyboard
import OIS.OISMouse
import OIS.OISMultiTouch
import OIS.OISObject
import OIS.OISPrereqs
| ghorn/hois | OIS.hs | bsd-3-clause | 620 | 0 | 5 | 165 | 116 | 74 | 42 | 20 | 0 |
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MonoLocalBinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Generics.Product.Any
-- Copyright : (C) 2020 Csongor Kiss
-- License : BSD3
-- Maintainer : Csongor Kiss <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Derive a variety of lenses generically.
--
-----------------------------------------------------------------------------
module Data.Generics.Product.Any
( -- *Lenses
--
-- $setup
HasAny (..)
) where
import "this" Data.Generics.Internal.VL.Lens
import "this" Data.Generics.Product.Fields
import "this" Data.Generics.Product.Positions
import "this" Data.Generics.Product.Typed
-- $setup
-- == /Running example:/
--
-- >>> :set -XTypeApplications
-- >>> :set -XDataKinds
-- >>> :set -XDeriveGeneric
-- >>> import GHC.Generics
-- >>> :m +Data.Generics.Internal.VL.Lens
-- >>> :{
-- data Human = Human
-- { name :: String
-- , age :: Int
-- , address :: String
-- }
-- deriving (Generic, Show)
-- human :: Human
-- human = Human "Tunyasz" 50 "London"
-- :}
class HasAny sel s t a b | s sel -> a where
-- |A lens that focuses on a part of a product as identified by some
-- selector. Currently supported selectors are field names, positions and
-- unique types. Compatible with the lens package's 'Control.Lens.Lens'
-- type.
--
-- >>> human ^. the @Int
-- 50
--
-- >>> human ^. the @"name"
-- "Tunyasz"
--
-- >>> human ^. the @3
-- "London"
the :: Lens s t a b
instance HasPosition i s t a b => HasAny i s t a b where
the = position @i
instance HasField field s t a b => HasAny field s t a b where
the = field @field
instance (HasType a s, t ~ s, a ~ b) => HasAny a s t a b where
the = typed @a
| kcsongor/generic-lens | generic-lens/src/Data/Generics/Product/Any.hs | bsd-3-clause | 2,226 | 0 | 7 | 477 | 280 | 181 | 99 | 26 | 0 |
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2015 Dimitri Sabadie
-- License : BSD3
--
-- Maintainer : Dimitri Sabadie <[email protected]>
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
module Graphics.Luminance.Tuple where
import Foreign.Storable ( Storable(..) )
import Foreign.Ptr ( castPtr, plusPtr )
-- |A tuple of types, right-associated.
--
-- The Storable instance is used for foreign packing.
data a :. b = a :. b deriving (Eq,Functor,Ord,Show)
infixr 6 :.
instance (Storable a,Storable b) => Storable (a :. b) where
sizeOf (a :. b) = sizeOf a + sizeOf b
alignment _ = 4 -- packed data
peek p = do
a <- peek $ castPtr p
b <- peek . castPtr $ p `plusPtr` sizeOf (undefined :: a)
pure $ a :. b
poke p (a :. b) = do
poke (castPtr p) a
poke (castPtr $ p `plusPtr` sizeOf (undefined :: a)) b
| apriori/luminance | src/Graphics/Luminance/Tuple.hs | bsd-3-clause | 988 | 0 | 12 | 190 | 271 | 150 | 121 | -1 | -1 |
{-# LANGUAGE CPP, OverloadedStrings #-}
-- | Serve static files, subject to a policy that can filter or
-- modify incoming URIs. The flow is:
--
-- incoming request URI ==> policies ==> exists? ==> respond
--
-- If any of the polices fail, or the file doesn't
-- exist, then the middleware gives up and calls the inner application.
-- If the file is found, the middleware chooses a content type based
-- on the file extension and returns the file contents as the response.
module Network.Wai.Middleware.Static
( -- * Middlewares
static, staticPolicy, unsafeStaticPolicy
, static', staticPolicy', unsafeStaticPolicy'
, -- * Cache Control
CachingStrategy(..), FileMeta(..), initCaching, CacheContainer
, -- * Policies
Policy, (<|>), (>->), policy, predicate
, addBase, addSlash, contains, hasPrefix, hasSuffix, noDots, isNotAbsolute, only
, -- * Utilities
tryPolicy
, -- * MIME types
getMimeType
) where
import Caching.ExpiringCacheMap.HashECM (newECMIO, lookupECM, CacheSettings(..), consistentDuration)
import Control.Monad.Trans (liftIO)
import Data.List
import Data.Maybe (fromMaybe)
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid
#endif
import Data.Time
import Data.Time.Clock.POSIX
import Network.HTTP.Types (status200, status304)
import Network.HTTP.Types.Header (RequestHeaders)
import Network.Wai
import System.Directory (doesFileExist, getModificationTime)
#if !(MIN_VERSION_time(1,5,0))
import System.Locale
#endif
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Data.ByteString as B
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Map as M
import qualified Data.Text as T
import qualified System.FilePath as FP
-- | Take an incoming URI and optionally modify or filter it.
-- The result will be treated as a filepath.
newtype Policy = Policy { tryPolicy :: String -> Maybe String -- ^ Run a policy
}
-- | A cache strategy which should be used to
-- serve content matching a policy. Meta information is cached for a maxium of
-- 100 seconds before being recomputed.
data CachingStrategy
-- | Do not send any caching headers
= NoCaching
-- | Send common caching headers for public (non dynamic) static files
| PublicStaticCaching
-- | Compute caching headers using the user specified function.
-- See <http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/> for a detailed guide
| CustomCaching (FileMeta -> RequestHeaders)
-- | Note:
-- 'mempty' == @policy Just@ (the always accepting policy)
-- 'mappend' == @>->@ (policy sequencing)
instance Monoid Policy where
mempty = policy Just
mappend p1 p2 = policy (maybe Nothing (tryPolicy p2) . tryPolicy p1)
-- | Lift a function into a 'Policy'
policy :: (String -> Maybe String) -> Policy
policy = Policy
-- | Lift a predicate into a 'Policy'
predicate :: (String -> Bool) -> Policy
predicate p = policy (\s -> if p s then Just s else Nothing)
-- | Sequence two policies. They are run from left to right. (Note: this is `mappend`)
infixr 5 >->
(>->) :: Policy -> Policy -> Policy
(>->) = mappend
-- | Choose between two policies. If the first fails, run the second.
infixr 4 <|>
(<|>) :: Policy -> Policy -> Policy
p1 <|> p2 = policy (\s -> maybe (tryPolicy p2 s) Just (tryPolicy p1 s))
-- | Add a base path to the URI
--
-- > staticPolicy (addBase "/home/user/files")
--
-- GET \"foo\/bar\" looks for \"\/home\/user\/files\/foo\/bar\"
--
addBase :: String -> Policy
addBase b = policy (Just . (b FP.</>))
-- | Add an initial slash to to the URI, if not already present.
--
-- > staticPolicy addSlash
--
-- GET \"foo\/bar\" looks for \"\/foo\/bar\"
addSlash :: Policy
addSlash = policy slashOpt
where slashOpt s@('/':_) = Just s
slashOpt s = Just ('/':s)
-- | Accept only URIs with given suffix
hasSuffix :: String -> Policy
hasSuffix = predicate . isSuffixOf
-- | Accept only URIs with given prefix
hasPrefix :: String -> Policy
hasPrefix = predicate . isPrefixOf
-- | Accept only URIs containing given string
contains :: String -> Policy
contains = predicate . isInfixOf
-- | Reject URIs containing \"..\"
noDots :: Policy
noDots = predicate (not . isInfixOf "..")
-- | Reject URIs that are absolute paths
isNotAbsolute :: Policy
isNotAbsolute = predicate $ not . FP.isAbsolute
-- | Use URI as the key to an association list, rejecting those not found.
-- The policy result is the matching value.
--
-- > staticPolicy (only [("foo/bar", "/home/user/files/bar")])
--
-- GET \"foo\/bar\" looks for \"\/home\/user\/files\/bar\"
-- GET \"baz\/bar\" doesn't match anything
--
only :: [(String,String)] -> Policy
only al = policy (flip lookup al)
-- | Serve static files out of the application root (current directory).
-- If file is found, it is streamed to the client and no further middleware is run. Disables caching.
--
-- Note: for security reasons, this uses the 'noDots' and 'isNotAbsolute' policy by default.
static :: Middleware
static = staticPolicy mempty
-- | Serve static files out of the application root (current directory).
-- If file is found, it is streamed to the client and no further middleware is run. Allows a 'CachingStrategy'.
--
-- Note: for security reasons, this uses the 'noDots' and 'isNotAbsolute' policy by default.
static' :: CacheContainer -> Middleware
static' cc = staticPolicy' cc mempty
-- | Serve static files subject to a 'Policy'. Disables caching.
--
-- Note: for security reasons, this uses the 'noDots' and 'isNotAbsolute' policy by default.
staticPolicy :: Policy -> Middleware
staticPolicy = staticPolicy' CacheContainerEmpty
-- | Serve static files subject to a 'Policy' using a specified 'CachingStrategy'
--
-- Note: for security reasons, this uses the 'noDots' and 'isNotAbsolute' policy by default.
staticPolicy' :: CacheContainer -> Policy -> Middleware
staticPolicy' cc p = unsafeStaticPolicy' cc $ noDots >-> isNotAbsolute >-> p
-- | Serve static files subject to a 'Policy'. Unlike 'static' and 'staticPolicy', this
-- has no policies enabled by default, and is hence insecure. Disables caching.
unsafeStaticPolicy :: Policy -> Middleware
unsafeStaticPolicy = unsafeStaticPolicy' CacheContainerEmpty
-- | Serve static files subject to a 'Policy'. Unlike 'static' and 'staticPolicy', this
-- has no policies enabled by default, and is hence insecure. Also allows to set a 'CachingStrategy'.
unsafeStaticPolicy' ::
CacheContainer
-> Policy
-> Middleware
unsafeStaticPolicy' cacheContainer p app req callback =
maybe (app req callback)
(\fp ->
do exists <- liftIO $ doesFileExist fp
if exists
then case cacheContainer of
CacheContainerEmpty ->
sendFile fp []
CacheContainer _ NoCaching ->
sendFile fp []
CacheContainer getFileMeta strategy ->
do fileMeta <- getFileMeta fp
if checkNotModified fileMeta (readHeader "If-Modified-Since") (readHeader "If-None-Match")
then sendNotModified fileMeta strategy
else sendFile fp (computeHeaders fileMeta strategy)
else app req callback)
(tryPolicy p $ T.unpack $ T.intercalate "/" $ pathInfo req)
where
readHeader header =
lookup header $ requestHeaders req
checkNotModified fm modSince etag =
or [ Just (fm_lastModified fm) == modSince
, Just (fm_etag fm) == etag
]
computeHeaders fm cs =
case cs of
NoCaching -> []
PublicStaticCaching ->
[ ("Cache-Control", "no-transform,public,max-age=300,s-maxage=900")
, ("Last-Modified", fm_lastModified fm)
, ("ETag", fm_etag fm)
, ("Vary", "Accept-Encoding")
]
CustomCaching f -> f fm
sendNotModified fm cs =
do let cacheHeaders = computeHeaders fm cs
callback $ responseLBS status304 cacheHeaders BSL.empty
sendFile fp extraHeaders =
do let basicHeaders =
[ ("Content-Type", getMimeType fp)
]
headers =
basicHeaders ++ extraHeaders
callback $ responseFile status200 headers fp Nothing
-- | Container caching file meta information. Create using 'initCaching'
data CacheContainer
= CacheContainerEmpty
| CacheContainer (FilePath -> IO FileMeta) CachingStrategy
-- | Meta information about a file to calculate cache headers
data FileMeta
= FileMeta
{ fm_lastModified :: !BS.ByteString
, fm_etag :: !BS.ByteString
, fm_fileName :: FilePath
} deriving (Show, Eq)
-- | Initialize caching. This should only be done once per application launch.
initCaching :: CachingStrategy -> IO CacheContainer
initCaching cs =
do let cacheAccess =
consistentDuration 100 $ \state fp ->
do fileMeta <- computeFileMeta fp
return $! (state, fileMeta)
cacheTick =
do time <- getPOSIXTime
return (round (time * 100))
cacheFreq = 1
cacheLRU =
CacheWithLRUList 100 100 200
filecache <- newECMIO cacheAccess cacheTick cacheFreq cacheLRU
return (CacheContainer (lookupECM filecache) cs)
computeFileMeta :: FilePath -> IO FileMeta
computeFileMeta fp =
do mtime <- getModificationTime fp
ct <- BSL.readFile fp
return $ FileMeta
{ fm_lastModified =
BSC.pack $ formatTime defaultTimeLocale "%a, %d-%b-%Y %X %Z" mtime
, fm_etag = B16.encode (SHA1.hashlazy ct)
, fm_fileName = fp
}
type Ascii = B.ByteString
-- | Guess MIME type from file extension
getMimeType :: FilePath -> B.ByteString
getMimeType = go . extensions
where go [] = defaultMimeType
go (ext:exts) = fromMaybe (go exts) $ M.lookup ext defaultMimeTypes
extensions :: FilePath -> [String]
extensions [] = []
extensions fp = case dropWhile (/= '.') fp of
[] -> []
s -> let ext = tail s
in ext : extensions ext
defaultMimeType :: Ascii
defaultMimeType = "application/octet-stream"
-- This list taken from snap-core's Snap.Util.FileServe
defaultMimeTypes :: M.Map String Ascii
defaultMimeTypes = M.fromList [
( "asc" , "text/plain" ),
( "asf" , "video/x-ms-asf" ),
( "asx" , "video/x-ms-asf" ),
( "avi" , "video/x-msvideo" ),
( "bz2" , "application/x-bzip" ),
( "c" , "text/plain" ),
( "class" , "application/octet-stream" ),
( "conf" , "text/plain" ),
( "cpp" , "text/plain" ),
( "css" , "text/css" ),
( "cxx" , "text/plain" ),
( "dtd" , "text/xml" ),
( "dvi" , "application/x-dvi" ),
( "gif" , "image/gif" ),
( "gz" , "application/x-gzip" ),
( "hs" , "text/plain" ),
( "htm" , "text/html" ),
( "html" , "text/html" ),
( "jar" , "application/x-java-archive" ),
( "jpeg" , "image/jpeg" ),
( "jpg" , "image/jpeg" ),
( "js" , "text/javascript" ),
( "json" , "application/json" ),
( "log" , "text/plain" ),
( "m3u" , "audio/x-mpegurl" ),
( "mov" , "video/quicktime" ),
( "mp3" , "audio/mpeg" ),
( "mp4" , "video/mp4" ),
( "mpeg" , "video/mpeg" ),
( "mpg" , "video/mpeg" ),
( "ogg" , "application/ogg" ),
( "ogv" , "video/ogg" ),
( "pac" , "application/x-ns-proxy-autoconfig" ),
( "pdf" , "application/pdf" ),
( "png" , "image/png" ),
( "ps" , "application/postscript" ),
( "qt" , "video/quicktime" ),
( "sig" , "application/pgp-signature" ),
( "spl" , "application/futuresplash" ),
( "svg" , "image/svg+xml" ),
( "swf" , "application/x-shockwave-flash" ),
( "tar" , "application/x-tar" ),
( "tar.bz2" , "application/x-bzip-compressed-tar" ),
( "tar.gz" , "application/x-tgz" ),
( "tbz" , "application/x-bzip-compressed-tar" ),
( "text" , "text/plain" ),
( "tgz" , "application/x-tgz" ),
( "torrent" , "application/x-bittorrent" ),
( "ttf" , "application/x-font-truetype" ),
( "txt" , "text/plain" ),
( "wav" , "audio/x-wav" ),
( "wax" , "audio/x-ms-wax" ),
( "wma" , "audio/x-ms-wma" ),
( "wmv" , "video/x-ms-wmv" ),
( "woff" , "application/font-woff" ),
( "xbm" , "image/x-xbitmap" ),
( "xml" , "text/xml" ),
( "xpm" , "image/x-xpixmap" ),
( "xwd" , "image/x-xwindowdump" ),
( "zip" , "application/zip" ) ]
| Shimuuar/wai-middleware-static | Network/Wai/Middleware/Static.hs | bsd-3-clause | 14,041 | 0 | 19 | 4,374 | 2,458 | 1,434 | 1,024 | 232 | 7 |
module JFP.Threads where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
-- | Makes asynchronous message handler for handling hard tasks. Messages sent
-- while handling previous message are dropped except last one. Last message is
-- always handled.
makeSequencer
:: (a -> IO ())
-> IO (a -> IO ())
makeSequencer handler = do
msgVar <- newEmptyTMVarIO
let
sender msg = atomically $ do
done <- tryPutTMVar msgVar msg
unless done $ void $ swapTMVar msgVar msg
worker = forever $ do
msg <- atomically $ takeTMVar msgVar
handler msg
void $ forkIO worker
return sender
| s9gf4ult/jfprrd | src/JFP/Threads.hs | bsd-3-clause | 640 | 0 | 15 | 141 | 168 | 81 | 87 | 18 | 1 |
{-# LANGUAGE QuasiQuotes #-}
module Text.Parakeet (
parakeet
, templateTeX
, templateHTML
, OutputFormat (..)
, module Parakeet.Types.Options
) where
import Control.Monad.Parakeet (runParakeet, SomeException)
import Data.Text.Lazy (unpack)
import Text.QuasiEmbedFile (rfile)
import Parakeet.Parser.Parser (parse)
import Parakeet.Printer.TeX (tex)
import Parakeet.Printer.HTML (html)
import Parakeet.Types.Options
data OutputFormat = TeXFormat | HTMLFormat
parakeet :: Options -> OutputFormat -> Either SomeException String
parakeet opts format = runParakeet opts $ do
parsed <- parse
let printer = case format of
TeXFormat -> tex
HTMLFormat -> html
unpack <$> printer parsed
templateTeX :: String
templateTeX = [rfile|template.tex|]
templateHTML :: String
templateHTML = [rfile|template.html|]
| foreverbell/parakeet | src/Text/Parakeet.hs | mit | 846 | 0 | 13 | 147 | 221 | 131 | 90 | 26 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns#-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -ddump-splices #-}
import Test.Hspec
import Test.HUnit ((@?=))
import Data.Text (Text, pack, unpack, singleton)
import Yesod.Routes.Class hiding (Route)
import qualified Yesod.Routes.Class as YRC
import Yesod.Routes.Parse (parseRoutesNoCheck, parseTypeTree, TypeTree (..))
import Yesod.Routes.Overlap (findOverlapNames)
import Yesod.Routes.TH hiding (Dispatch)
import Language.Haskell.TH.Syntax
import Hierarchy
import qualified Data.ByteString.Char8 as S8
import qualified Data.Set as Set
data MyApp = MyApp
data MySub = MySub
instance RenderRoute MySub where
data
#if MIN_VERSION_base(4,5,0)
Route
#else
YRC.Route
#endif
MySub = MySubRoute ([Text], [(Text, Text)])
deriving (Show, Eq, Read)
renderRoute (MySubRoute x) = x
instance ParseRoute MySub where
parseRoute = Just . MySubRoute
getMySub :: MyApp -> MySub
getMySub MyApp = MySub
data MySubParam = MySubParam Int
instance RenderRoute MySubParam where
data
#if MIN_VERSION_base(4,5,0)
Route
#else
YRC.Route
#endif
MySubParam = ParamRoute Char
deriving (Show, Eq, Read)
renderRoute (ParamRoute x) = ([singleton x], [])
instance ParseRoute MySubParam where
parseRoute ([unpack -> [x]], _) = Just $ ParamRoute x
parseRoute _ = Nothing
getMySubParam :: MyApp -> Int -> MySubParam
getMySubParam _ = MySubParam
do
texts <- [t|[Text]|]
let resLeaves = map ResourceLeaf
[ Resource "RootR" [] (Methods Nothing ["GET"]) ["foo", "bar"] True
, Resource "BlogPostR" [Static "blog", Dynamic $ ConT ''Text] (Methods Nothing ["GET", "POST"]) [] True
, Resource "WikiR" [Static "wiki"] (Methods (Just texts) []) [] True
, Resource "SubsiteR" [Static "subsite"] (Subsite (ConT ''MySub) "getMySub") [] True
, Resource "SubparamR" [Static "subparam", Dynamic $ ConT ''Int] (Subsite (ConT ''MySubParam) "getMySubParam") [] True
]
resParent = ResourceParent
"ParentR"
True
[ Static "foo"
, Dynamic $ ConT ''Text
]
[ ResourceLeaf $ Resource "ChildR" [] (Methods Nothing ["GET"]) ["child"] True
]
ress = resParent : resLeaves
rrinst <- mkRenderRouteInstance (ConT ''MyApp) ress
rainst <- mkRouteAttrsInstance (ConT ''MyApp) ress
prinst <- mkParseRouteInstance (ConT ''MyApp) ress
dispatch <- mkDispatchClause MkDispatchSettings
{ mdsRunHandler = [|runHandler|]
, mdsSubDispatcher = [|subDispatch dispatcher|]
, mdsGetPathInfo = [|fst|]
, mdsMethod = [|snd|]
, mdsSetPathInfo = [|\p (_, m) -> (p, m)|]
, mds404 = [|pack "404"|]
, mds405 = [|pack "405"|]
, mdsGetHandler = defaultGetHandler
, mdsUnwrapper = return
} ress
return
#if MIN_VERSION_template_haskell(2,11,0)
$ InstanceD Nothing
#else
$ InstanceD
#endif
[]
(ConT ''Dispatcher
`AppT` ConT ''MyApp
`AppT` ConT ''MyApp)
[FunD (mkName "dispatcher") [dispatch]]
: prinst
: rainst
: rrinst
instance Dispatcher MySub master where
dispatcher env (pieces, _method) =
( pack $ "subsite: " ++ show pieces
, Just $ envToMaster env route
)
where
route = MySubRoute (pieces, [])
instance Dispatcher MySubParam master where
dispatcher env (pieces, method) =
case map unpack pieces of
[[c]] ->
let route = ParamRoute c
toMaster = envToMaster env
MySubParam i = envSub env
in ( pack $ "subparam " ++ show i ++ ' ' : [c]
, Just $ toMaster route
)
_ -> (pack "404", Nothing)
{-
thDispatchAlias
:: (master ~ MyApp, sub ~ MyApp, handler ~ String, app ~ (String, Maybe (YRC.Route MyApp)))
=> master
-> sub
-> (YRC.Route sub -> YRC.Route master)
-> app -- ^ 404 page
-> handler -- ^ 405 page
-> Text -- ^ method
-> [Text]
-> app
--thDispatchAlias = thDispatch
thDispatchAlias master sub toMaster app404 handler405 method0 pieces0 =
case dispatch pieces0 of
Just f -> f master sub toMaster app404 handler405 method0
Nothing -> app404
where
dispatch = toDispatch
[ Route [] False $ \pieces ->
case pieces of
[] -> do
Just $ \master' sub' toMaster' _app404' handler405' method ->
let handler =
case Map.lookup method methodsRootR of
Just f -> f
Nothing -> handler405'
in runHandler handler master' sub' RootR toMaster'
_ -> error "Invariant violated"
, Route [D.Static "blog", D.Dynamic] False $ \pieces ->
case pieces of
[_, x2] -> do
y2 <- fromPathPiece x2
Just $ \master' sub' toMaster' _app404' handler405' method ->
let handler =
case Map.lookup method methodsBlogPostR of
Just f -> f y2
Nothing -> handler405'
in runHandler handler master' sub' (BlogPostR y2) toMaster'
_ -> error "Invariant violated"
, Route [D.Static "wiki"] True $ \pieces ->
case pieces of
_:x2 -> do
y2 <- fromPathMultiPiece x2
Just $ \master' sub' toMaster' _app404' _handler405' _method ->
let handler = handleWikiR y2
in runHandler handler master' sub' (WikiR y2) toMaster'
_ -> error "Invariant violated"
, Route [D.Static "subsite"] True $ \pieces ->
case pieces of
_:x2 -> do
Just $ \master' sub' toMaster' app404' handler405' method ->
dispatcher master' (getMySub sub') (toMaster' . SubsiteR) app404' handler405' method x2
_ -> error "Invariant violated"
, Route [D.Static "subparam", D.Dynamic] True $ \pieces ->
case pieces of
_:x2:x3 -> do
y2 <- fromPathPiece x2
Just $ \master' sub' toMaster' app404' handler405' method ->
dispatcher master' (getMySubParam sub' y2) (toMaster' . SubparamR y2) app404' handler405' method x3
_ -> error "Invariant violated"
]
methodsRootR = Map.fromList [("GET", getRootR)]
methodsBlogPostR = Map.fromList [("GET", getBlogPostR), ("POST", postBlogPostR)]
-}
main :: IO ()
main = hspec $ do
describe "RenderRoute instance" $ do
it "renders root correctly" $ renderRoute RootR @?= ([], [])
it "renders blog post correctly" $ renderRoute (BlogPostR $ pack "foo") @?= (map pack ["blog", "foo"], [])
it "renders wiki correctly" $ renderRoute (WikiR $ map pack ["foo", "bar"]) @?= (map pack ["wiki", "foo", "bar"], [])
it "renders subsite correctly" $ renderRoute (SubsiteR $ MySubRoute (map pack ["foo", "bar"], [(pack "baz", pack "bin")]))
@?= (map pack ["subsite", "foo", "bar"], [(pack "baz", pack "bin")])
it "renders subsite param correctly" $ renderRoute (SubparamR 6 $ ParamRoute 'c')
@?= (map pack ["subparam", "6", "c"], [])
describe "thDispatch" $ do
let disp m ps = dispatcher
(Env
{ envToMaster = id
, envMaster = MyApp
, envSub = MyApp
})
(map pack ps, S8.pack m)
it "routes to root" $ disp "GET" [] @?= (pack "this is the root", Just RootR)
it "POST root is 405" $ disp "POST" [] @?= (pack "405", Just RootR)
it "invalid page is a 404" $ disp "GET" ["not-found"] @?= (pack "404", Nothing :: Maybe (YRC.Route MyApp))
it "routes to blog post" $ disp "GET" ["blog", "somepost"]
@?= (pack "some blog post: somepost", Just $ BlogPostR $ pack "somepost")
it "routes to blog post, POST method" $ disp "POST" ["blog", "somepost2"]
@?= (pack "POST some blog post: somepost2", Just $ BlogPostR $ pack "somepost2")
it "routes to wiki" $ disp "DELETE" ["wiki", "foo", "bar"]
@?= (pack "the wiki: [\"foo\",\"bar\"]", Just $ WikiR $ map pack ["foo", "bar"])
it "routes to subsite" $ disp "PUT" ["subsite", "baz"]
@?= (pack "subsite: [\"baz\"]", Just $ SubsiteR $ MySubRoute ([pack "baz"], []))
it "routes to subparam" $ disp "PUT" ["subparam", "6", "q"]
@?= (pack "subparam 6 q", Just $ SubparamR 6 $ ParamRoute 'q')
describe "parsing" $ do
it "subsites work" $ do
parseRoute ([pack "subsite", pack "foo"], [(pack "bar", pack "baz")]) @?=
Just (SubsiteR $ MySubRoute ([pack "foo"], [(pack "bar", pack "baz")]))
describe "overlap checking" $ do
it "catches overlapping statics" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/foo Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping dynamics" $ do
let routes = [parseRoutesNoCheck|
/#Int Foo1
/#String Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping statics and dynamics" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/#String Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping multi" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/##*Strings Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping subsite" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/foo Foo2 Subsite getSubsite
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "no false positives" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/bar/#String Foo2
|]
findOverlapNames routes @?= []
it "obeys ignore rules" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/#!String Foo2
/!foo Foo3
|]
findOverlapNames routes @?= []
it "obeys multipiece ignore rules #779" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/+![String] Foo2
|]
findOverlapNames routes @?= []
it "ignore rules for entire route #779" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
!/+[String] Foo2
!/#String Foo3
!/foo Foo4
|]
findOverlapNames routes @?= []
it "ignore rules for hierarchy" $ do
let routes = [parseRoutesNoCheck|
/+[String] Foo1
!/foo Foo2:
/foo Foo3
/foo Foo4:
/!#foo Foo5
|]
findOverlapNames routes @?= []
it "proper boolean logic" $ do
let routes = [parseRoutesNoCheck|
/foo/bar Foo1
/foo/baz Foo2
/bar/baz Foo3
|]
findOverlapNames routes @?= []
describe "routeAttrs" $ do
it "works" $ do
routeAttrs RootR @?= Set.fromList [pack "foo", pack "bar"]
it "hierarchy" $ do
routeAttrs (ParentR (pack "ignored") ChildR) @?= Set.singleton (pack "child")
hierarchy
describe "parseRouteTyoe" $ do
let success s t = it s $ parseTypeTree s @?= Just t
failure s = it s $ parseTypeTree s @?= Nothing
success "Int" $ TTTerm "Int"
success "(Int)" $ TTTerm "Int"
failure "(Int"
failure "(Int))"
failure "[Int"
failure "[Int]]"
success "[Int]" $ TTList $ TTTerm "Int"
success "Foo-Bar" $ TTApp (TTTerm "Foo") (TTTerm "Bar")
success "Foo-Bar-Baz" $ TTApp (TTTerm "Foo") (TTTerm "Bar") `TTApp` TTTerm "Baz"
getRootR :: Text
getRootR = pack "this is the root"
getBlogPostR :: Text -> String
getBlogPostR t = "some blog post: " ++ unpack t
postBlogPostR :: Text -> Text
postBlogPostR t = pack $ "POST some blog post: " ++ unpack t
handleWikiR :: [Text] -> String
handleWikiR ts = "the wiki: " ++ show ts
getChildR :: Text -> Text
getChildR = id
| tolysz/yesod | yesod-core/test/RouteSpec.hs | mit | 12,733 | 0 | 22 | 4,022 | 2,814 | 1,454 | 1,360 | 200 | 1 |
--
--
--
------------------
-- Exercise 11.32.
------------------
--
--
--
module E'11'32 where
-- Notes:
--
-- - Use/See templates for proofs by structural induction.
-- - Note: Re/-member/-think/-view the definitions of "++", "." and "foldr".
-- ---------------
-- 1. Proposition:
-- ---------------
--
-- foldr f st (xs ++ ys) = f (foldr f st xs) (foldr f st ys)
--
--
-- Assumption 1: "f" is associative
--
-- Assumption 2: "st" is an identity for "f"
--
--
-- Proof By Structural Induction:
-- ------------------------------
--
--
-- 1. Induction Beginning (1. I.B.):
-- ---------------------------------
--
--
-- (Base case 1.) :<=> xs := []
--
-- => (left) := foldr f st (xs ++ ys)
-- | (Base case 1.)
-- = foldr f st ([] ++ ys)
-- | ++
-- = foldr f st ys
--
--
-- (right) := f (foldr f st xs) (foldr f st ys)
-- | (Base case 1.)
-- = f (foldr f st []) (foldr f st ys)
-- | (Assumption 1)
-- | foldr
-- = f st (foldr f st ys)
-- | (Assumption 2)
-- | st
-- = foldr f st ys
--
--
-- => (left) = (right)
--
-- ✔
--
--
-- 1. Induction Hypothesis (1. I.H.):
-- ----------------------------------
--
-- For all lists "ys" and for an arbitrary, but fixed "xs", the statement ...
--
-- foldr f st (xs ++ ys) = f (foldr f st xs) (foldr f st ys)
--
-- ... holds.
--
--
-- 1. Induction Step (1. I.S.):
-- ----------------------------
--
--
-- (left) := foldr f st ( (x : xs) ++ ys )
-- | ++
-- = foldr f st ( x : (xs ++ ys) )
-- | (Assumption 1)
-- | foldr
-- = x `f` foldr f st (xs ++ ys)
-- | (1. I.H.)
-- = x `f` f (foldr f st xs) (foldr f st ys)
--
-- = x `f` (foldr f st xs) `f` (foldr f st ys)
--
-- = ( x `f` (foldr f st xs) ) `f` (foldr f st ys)
-- | General rule of function application (left associativity)
-- = ( foldr f st (x : xs) ) `f` (foldr f st ys)
--
--
-- (right) := f ( foldr f st (x : xs) ) (foldr f st ys)
--
-- = ( foldr f st (x : xs) ) `f` (foldr f st ys)
--
--
-- => (left) = (right)
--
--
-- ■ (1. Proof)
-- Question: Is "foldr f st ( foldr (++) [] ls ) = foldr ( f . (foldr f st) ) st ls" true?
| pascal-knodel/haskell-craft | _/links/E'11'32.hs | mit | 3,008 | 0 | 2 | 1,442 | 102 | 101 | 1 | 1 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module %PACKAGE%.%MODEL%
( module Export
)where
import %PACKAGE%.%MODEL%.Import
import %PACKAGE%.%MODEL%.Foundation as Export
import %PACKAGE%.%MODEL%.Models as Export
import %PACKAGE%.%MODEL%.Handler.%MODEL% as Export
instance %PACKAGE%%MODEL% master => YesodSubDispatch %MODEL%Admin (HandlerT master IO) where
yesodSubDispatch = $(mkYesodSubDispatch resources%MODEL%Admin)
| lambdacms/lambdacms | scaffold-extension/PACKAGE/MODEL.hs | mit | 649 | 11 | 10 | 122 | 134 | 88 | 46 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
module Database.Persist.Postgresql.Internal
( P(..)
, PgInterval(..)
, getGetter
) where
import qualified Database.PostgreSQL.Simple as PG
import qualified Database.PostgreSQL.Simple.FromField as PGFF
import qualified Database.PostgreSQL.Simple.Internal as PG
import qualified Database.PostgreSQL.Simple.ToField as PGTF
import qualified Database.PostgreSQL.Simple.TypeInfo.Static as PS
import qualified Database.PostgreSQL.Simple.Types as PG
import qualified Blaze.ByteString.Builder.Char8 as BBB
import qualified Data.Attoparsec.ByteString.Char8 as P
import Data.Bits ((.&.))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Builder as BB
import qualified Data.ByteString.Char8 as B8
import Data.Char (ord)
import Data.Data (Typeable)
import Data.Fixed (Fixed(..), Pico)
import Data.Int (Int64)
import qualified Data.IntMap as I
import Data.Maybe (fromMaybe)
import Data.String.Conversions.Monomorphic (toStrictByteString)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time (NominalDiffTime, localTimeToUTC, utc)
import Database.Persist.Sql
-- | Newtype used to avoid orphan instances for @postgresql-simple@ classes.
--
-- @since 2.13.2.0
newtype P = P { unP :: PersistValue }
instance PGTF.ToField P where
toField (P (PersistText t)) = PGTF.toField t
toField (P (PersistByteString bs)) = PGTF.toField (PG.Binary bs)
toField (P (PersistInt64 i)) = PGTF.toField i
toField (P (PersistDouble d)) = PGTF.toField d
toField (P (PersistRational r)) = PGTF.Plain $
BBB.fromString $
show (fromRational r :: Pico) -- FIXME: Too Ambigous, can not select precision without information about field
toField (P (PersistBool b)) = PGTF.toField b
toField (P (PersistDay d)) = PGTF.toField d
toField (P (PersistTimeOfDay t)) = PGTF.toField t
toField (P (PersistUTCTime t)) = PGTF.toField t
toField (P PersistNull) = PGTF.toField PG.Null
toField (P (PersistList l)) = PGTF.toField $ listToJSON l
toField (P (PersistMap m)) = PGTF.toField $ mapToJSON m
toField (P (PersistLiteral_ DbSpecific s)) = PGTF.toField (Unknown s)
toField (P (PersistLiteral_ Unescaped l)) = PGTF.toField (UnknownLiteral l)
toField (P (PersistLiteral_ Escaped e)) = PGTF.toField (Unknown e)
toField (P (PersistArray a)) = PGTF.toField $ PG.PGArray $ P <$> a
toField (P (PersistObjectId _)) =
error "Refusing to serialize a PersistObjectId to a PostgreSQL value"
instance PGFF.FromField P where
fromField field mdata = fmap P $ case mdata of
-- If we try to simply decode based on oid, we will hit unexpected null
-- errors.
Nothing -> pure PersistNull
data' -> getGetter (PGFF.typeOid field) field data'
newtype Unknown = Unknown { unUnknown :: ByteString }
deriving (Eq, Show, Read, Ord)
instance PGFF.FromField Unknown where
fromField f mdata =
case mdata of
Nothing -> PGFF.returnError PGFF.UnexpectedNull f "Database.Persist.Postgresql/PGFF.FromField Unknown"
Just dat -> return (Unknown dat)
instance PGTF.ToField Unknown where
toField (Unknown a) = PGTF.Escape a
newtype UnknownLiteral = UnknownLiteral { unUnknownLiteral :: ByteString }
deriving (Eq, Show, Read, Ord, Typeable)
instance PGFF.FromField UnknownLiteral where
fromField f mdata =
case mdata of
Nothing -> PGFF.returnError PGFF.UnexpectedNull f "Database.Persist.Postgresql/PGFF.FromField UnknownLiteral"
Just dat -> return (UnknownLiteral dat)
instance PGTF.ToField UnknownLiteral where
toField (UnknownLiteral a) = PGTF.Plain $ BB.byteString a
type Getter a = PGFF.FieldParser a
convertPV :: PGFF.FromField a => (a -> b) -> Getter b
convertPV f = (fmap f .) . PGFF.fromField
builtinGetters :: I.IntMap (Getter PersistValue)
builtinGetters = I.fromList
[ (k PS.bool, convertPV PersistBool)
, (k PS.bytea, convertPV (PersistByteString . unBinary))
, (k PS.char, convertPV PersistText)
, (k PS.name, convertPV PersistText)
, (k PS.int8, convertPV PersistInt64)
, (k PS.int2, convertPV PersistInt64)
, (k PS.int4, convertPV PersistInt64)
, (k PS.text, convertPV PersistText)
, (k PS.xml, convertPV (PersistByteString . unUnknown))
, (k PS.float4, convertPV PersistDouble)
, (k PS.float8, convertPV PersistDouble)
, (k PS.money, convertPV PersistRational)
, (k PS.bpchar, convertPV PersistText)
, (k PS.varchar, convertPV PersistText)
, (k PS.date, convertPV PersistDay)
, (k PS.time, convertPV PersistTimeOfDay)
, (k PS.timestamp, convertPV (PersistUTCTime. localTimeToUTC utc))
, (k PS.timestamptz, convertPV PersistUTCTime)
, (k PS.interval, convertPV (PersistLiteralEscaped . pgIntervalToBs))
, (k PS.bit, convertPV PersistInt64)
, (k PS.varbit, convertPV PersistInt64)
, (k PS.numeric, convertPV PersistRational)
, (k PS.void, \_ _ -> return PersistNull)
, (k PS.json, convertPV (PersistByteString . unUnknown))
, (k PS.jsonb, convertPV (PersistByteString . unUnknown))
, (k PS.unknown, convertPV (PersistByteString . unUnknown))
-- Array types: same order as above.
-- The OIDs were taken from pg_type.
, (1000, listOf PersistBool)
, (1001, listOf (PersistByteString . unBinary))
, (1002, listOf PersistText)
, (1003, listOf PersistText)
, (1016, listOf PersistInt64)
, (1005, listOf PersistInt64)
, (1007, listOf PersistInt64)
, (1009, listOf PersistText)
, (143, listOf (PersistByteString . unUnknown))
, (1021, listOf PersistDouble)
, (1022, listOf PersistDouble)
, (1023, listOf PersistUTCTime)
, (1024, listOf PersistUTCTime)
, (791, listOf PersistRational)
, (1014, listOf PersistText)
, (1015, listOf PersistText)
, (1182, listOf PersistDay)
, (1183, listOf PersistTimeOfDay)
, (1115, listOf PersistUTCTime)
, (1185, listOf PersistUTCTime)
, (1187, listOf (PersistLiteralEscaped . pgIntervalToBs))
, (1561, listOf PersistInt64)
, (1563, listOf PersistInt64)
, (1231, listOf PersistRational)
-- no array(void) type
, (2951, listOf (PersistLiteralEscaped . unUnknown))
, (199, listOf (PersistByteString . unUnknown))
, (3807, listOf (PersistByteString . unUnknown))
-- no array(unknown) either
]
where
k (PGFF.typoid -> i) = PG.oid2int i
-- A @listOf f@ will use a @PGArray (Maybe T)@ to convert
-- the values to Haskell-land. The @Maybe@ is important
-- because the usual way of checking NULLs
-- (c.f. withStmt') won't check for NULL inside
-- arrays---or any other compound structure for that matter.
listOf f = convertPV (PersistList . map (nullable f) . PG.fromPGArray)
where nullable = maybe PersistNull
-- | Get the field parser corresponding to the given 'PG.Oid'.
--
-- For example, pass in the 'PG.Oid' of 'PS.bool', and you will get back a
-- field parser which parses boolean values in the table into 'PersistBool's.
--
-- @since 2.13.2.0
getGetter :: PG.Oid -> Getter PersistValue
getGetter oid
= fromMaybe defaultGetter $ I.lookup (PG.oid2int oid) builtinGetters
where defaultGetter = convertPV (PersistLiteralEscaped . unUnknown)
unBinary :: PG.Binary a -> a
unBinary (PG.Binary x) = x
-- | Represent Postgres interval using NominalDiffTime
--
-- @since 2.11.0.0
newtype PgInterval = PgInterval { getPgInterval :: NominalDiffTime }
deriving (Eq, Show)
pgIntervalToBs :: PgInterval -> ByteString
pgIntervalToBs = toStrictByteString . show . getPgInterval
instance PGTF.ToField PgInterval where
toField (PgInterval t) = PGTF.toField t
instance PGFF.FromField PgInterval where
fromField f mdata =
if PGFF.typeOid f /= PS.typoid PS.interval
then PGFF.returnError PGFF.Incompatible f ""
else case mdata of
Nothing -> PGFF.returnError PGFF.UnexpectedNull f ""
Just dat -> case P.parseOnly (nominalDiffTime <* P.endOfInput) dat of
Left msg -> PGFF.returnError PGFF.ConversionFailed f msg
Right t -> return $ PgInterval t
where
toPico :: Integer -> Pico
toPico = MkFixed
-- Taken from Database.PostgreSQL.Simple.Time.Internal.Parser
twoDigits :: P.Parser Int
twoDigits = do
a <- P.digit
b <- P.digit
let c2d c = ord c .&. 15
return $! c2d a * 10 + c2d b
-- Taken from Database.PostgreSQL.Simple.Time.Internal.Parser
seconds :: P.Parser Pico
seconds = do
real <- twoDigits
mc <- P.peekChar
case mc of
Just '.' -> do
t <- P.anyChar *> P.takeWhile1 P.isDigit
return $! parsePicos (fromIntegral real) t
_ -> return $! fromIntegral real
where
parsePicos :: Int64 -> B8.ByteString -> Pico
parsePicos a0 t = toPico (fromIntegral (t' * 10^n))
where n = max 0 (12 - B8.length t)
t' = B8.foldl' (\a c -> 10 * a + fromIntegral (ord c .&. 15)) a0
(B8.take 12 t)
parseSign :: P.Parser Bool
parseSign = P.choice [P.char '-' >> return True, return False]
-- Db stores it in [-]HHH:MM:SS.[SSSS]
-- For example, nominalDay is stored as 24:00:00
interval :: P.Parser (Bool, Int, Int, Pico)
interval = do
s <- parseSign
h <- P.decimal <* P.char ':'
m <- twoDigits <* P.char ':'
ss <- seconds
if m < 60 && ss <= 60
then return (s, h, m, ss)
else fail "Invalid interval"
nominalDiffTime :: P.Parser NominalDiffTime
nominalDiffTime = do
(s, h, m, ss) <- interval
let pico = ss + 60 * (fromIntegral m) + 60 * 60 * (fromIntegral (abs h))
return . fromRational . toRational $ if s then (-pico) else pico
fromPersistValueError :: Text -- ^ Haskell type, should match Haskell name exactly, e.g. "Int64"
-> Text -- ^ Database type(s), should appear different from Haskell name, e.g. "integer" or "INT", not "Int".
-> PersistValue -- ^ Incorrect value
-> Text -- ^ Error message
fromPersistValueError haskellType databaseType received = T.concat
[ "Failed to parse Haskell type `"
, haskellType
, "`; expected "
, databaseType
, " from database, but received: "
, T.pack (show received)
, ". Potential solution: Check that your database schema matches your Persistent model definitions."
]
instance PersistField PgInterval where
toPersistValue = PersistLiteralEscaped . pgIntervalToBs
fromPersistValue (PersistLiteral_ DbSpecific bs) =
fromPersistValue (PersistLiteralEscaped bs)
fromPersistValue x@(PersistLiteral_ Escaped bs) =
case P.parseOnly (P.signed P.rational <* P.char 's' <* P.endOfInput) bs of
Left _ -> Left $ fromPersistValueError "PgInterval" "Interval" x
Right i -> Right $ PgInterval i
fromPersistValue x = Left $ fromPersistValueError "PgInterval" "Interval" x
instance PersistFieldSql PgInterval where
sqlType _ = SqlOther "interval"
| paul-rouse/persistent | persistent-postgresql/Database/Persist/Postgresql/Internal.hs | mit | 11,983 | 0 | 19 | 3,291 | 3,274 | 1,750 | 1,524 | 217 | 1 |
import Data.Time.Calendar
import Data.Time.Calendar.WeekDate
ans = length [(y,m,d) | y <- [1901..2000],
m <- [1..12],
let (_, _, d) = toWeekDate $ fromGregorian y m 1,
d == 7] | stefan-j/ProjectEuler | q19.hs | mit | 271 | 0 | 12 | 124 | 99 | 55 | 44 | 6 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.OpsWorks.DescribeUserProfiles
-- 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.
-- | Describe specified users.
--
-- Required Permissions: To use this action, an IAM user must have an attached
-- policy that explicitly grants permissions. For more information on user
-- permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>.
--
-- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DescribeUserProfiles.html>
module Network.AWS.OpsWorks.DescribeUserProfiles
(
-- * Request
DescribeUserProfiles
-- ** Request constructor
, describeUserProfiles
-- ** Request lenses
, dupIamUserArns
-- * Response
, DescribeUserProfilesResponse
-- ** Response constructor
, describeUserProfilesResponse
-- ** Response lenses
, duprUserProfiles
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
newtype DescribeUserProfiles = DescribeUserProfiles
{ _dupIamUserArns :: List "IamUserArns" Text
} deriving (Eq, Ord, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeUserProfiles where
type Item DescribeUserProfiles = Text
fromList = DescribeUserProfiles . GHC.Exts.fromList
toList = GHC.Exts.toList . _dupIamUserArns
-- | 'DescribeUserProfiles' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dupIamUserArns' @::@ ['Text']
--
describeUserProfiles :: DescribeUserProfiles
describeUserProfiles = DescribeUserProfiles
{ _dupIamUserArns = mempty
}
-- | An array of IAM user ARNs that identify the users to be described.
dupIamUserArns :: Lens' DescribeUserProfiles [Text]
dupIamUserArns = lens _dupIamUserArns (\s a -> s { _dupIamUserArns = a }) . _List
newtype DescribeUserProfilesResponse = DescribeUserProfilesResponse
{ _duprUserProfiles :: List "UserProfiles" UserProfile
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeUserProfilesResponse where
type Item DescribeUserProfilesResponse = UserProfile
fromList = DescribeUserProfilesResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _duprUserProfiles
-- | 'DescribeUserProfilesResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'duprUserProfiles' @::@ ['UserProfile']
--
describeUserProfilesResponse :: DescribeUserProfilesResponse
describeUserProfilesResponse = DescribeUserProfilesResponse
{ _duprUserProfiles = mempty
}
-- | A 'Users' object that describes the specified users.
duprUserProfiles :: Lens' DescribeUserProfilesResponse [UserProfile]
duprUserProfiles = lens _duprUserProfiles (\s a -> s { _duprUserProfiles = a }) . _List
instance ToPath DescribeUserProfiles where
toPath = const "/"
instance ToQuery DescribeUserProfiles where
toQuery = const mempty
instance ToHeaders DescribeUserProfiles
instance ToJSON DescribeUserProfiles where
toJSON DescribeUserProfiles{..} = object
[ "IamUserArns" .= _dupIamUserArns
]
instance AWSRequest DescribeUserProfiles where
type Sv DescribeUserProfiles = OpsWorks
type Rs DescribeUserProfiles = DescribeUserProfilesResponse
request = post "DescribeUserProfiles"
response = jsonResponse
instance FromJSON DescribeUserProfilesResponse where
parseJSON = withObject "DescribeUserProfilesResponse" $ \o -> DescribeUserProfilesResponse
<$> o .:? "UserProfiles" .!= mempty
| romanb/amazonka | amazonka-opsworks/gen/Network/AWS/OpsWorks/DescribeUserProfiles.hs | mpl-2.0 | 4,524 | 0 | 10 | 842 | 560 | 337 | 223 | 63 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Route53Domains.Types.Sum
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.Route53Domains.Types.Sum where
import Network.AWS.Prelude
data ContactType
= Association
| Company
| Person
| PublicBody
| Reseller
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ContactType where
parser = takeLowerText >>= \case
"association" -> pure Association
"company" -> pure Company
"person" -> pure Person
"public_body" -> pure PublicBody
"reseller" -> pure Reseller
e -> fromTextError $ "Failure parsing ContactType from value: '" <> e
<> "'. Accepted values: ASSOCIATION, COMPANY, PERSON, PUBLIC_BODY, RESELLER"
instance ToText ContactType where
toText = \case
Association -> "ASSOCIATION"
Company -> "COMPANY"
Person -> "PERSON"
PublicBody -> "PUBLIC_BODY"
Reseller -> "RESELLER"
instance Hashable ContactType
instance ToByteString ContactType
instance ToQuery ContactType
instance ToHeader ContactType
instance ToJSON ContactType where
toJSON = toJSONText
instance FromJSON ContactType where
parseJSON = parseJSONText "ContactType"
data CountryCode
= AD
| AE
| AF
| AG
| AI
| AL
| AM
| AN
| AO
| AQ
| AR
| AS
| AT
| AU
| AW
| AZ
| BA
| BB
| BD
| BE
| BF
| BG
| BH
| BI
| BJ
| BL
| BM
| BN
| BO
| BR
| BS
| BT
| BW
| BY
| BZ
| CA
| CC
| CD
| CF
| CG
| CH
| CI
| CK
| CL
| CM
| CN
| CO
| CR
| CU
| CV
| CX
| CY
| CZ
| DE
| DJ
| DK
| DM
| DO
| DZ
| EC
| EE
| EG
| ER
| ES
| ET
| FI
| FJ
| FK
| FM
| FO
| FR
| GA
| GB
| GD
| GE
| GH
| GI
| GL
| GM
| GN
| GQ
| GR
| GT'
| GU
| GW
| GY
| HK
| HN
| HR
| HT
| HU
| IE
| IL
| IM
| IN
| IQ
| IR
| IS
| IT
| Id
| JM
| JO
| JP
| KE
| KG
| KH
| KI
| KM
| KN
| KP
| KR
| KW
| KY
| KZ
| LA
| LB
| LC
| LI
| LK
| LR
| LS
| LT'
| LU
| LV
| LY
| MA
| MC
| MD
| ME
| MF
| MG
| MH
| MK
| ML
| MM
| MN
| MO
| MP
| MR
| MS
| MT
| MU
| MV
| MW
| MX
| MY
| MZ
| NA
| NC
| NE
| NG
| NI
| NL
| NO
| NP
| NR
| NU
| NZ
| OM
| PA
| PE
| PF
| PG
| PH
| PK
| PL
| PM
| PN
| PR
| PT
| PW
| PY
| QA
| RO
| RS
| RU
| RW
| SA
| SB
| SC
| SD
| SE
| SG
| SH
| SI
| SK
| SL
| SM
| SN
| SO
| SR
| ST
| SV
| SY
| SZ
| TC
| TD
| TG
| TH
| TJ
| TK
| TL
| TM
| TN
| TO
| TR
| TT
| TV
| TW
| TZ
| UA
| UG
| US
| UY
| UZ
| VA
| VC
| VE
| VG
| VI
| VN
| VU
| WF
| WS
| YE
| YT
| ZA
| ZM
| ZW
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText CountryCode where
parser = takeLowerText >>= \case
"ad" -> pure AD
"ae" -> pure AE
"af" -> pure AF
"ag" -> pure AG
"ai" -> pure AI
"al" -> pure AL
"am" -> pure AM
"an" -> pure AN
"ao" -> pure AO
"aq" -> pure AQ
"ar" -> pure AR
"as" -> pure AS
"at" -> pure AT
"au" -> pure AU
"aw" -> pure AW
"az" -> pure AZ
"ba" -> pure BA
"bb" -> pure BB
"bd" -> pure BD
"be" -> pure BE
"bf" -> pure BF
"bg" -> pure BG
"bh" -> pure BH
"bi" -> pure BI
"bj" -> pure BJ
"bl" -> pure BL
"bm" -> pure BM
"bn" -> pure BN
"bo" -> pure BO
"br" -> pure BR
"bs" -> pure BS
"bt" -> pure BT
"bw" -> pure BW
"by" -> pure BY
"bz" -> pure BZ
"ca" -> pure CA
"cc" -> pure CC
"cd" -> pure CD
"cf" -> pure CF
"cg" -> pure CG
"ch" -> pure CH
"ci" -> pure CI
"ck" -> pure CK
"cl" -> pure CL
"cm" -> pure CM
"cn" -> pure CN
"co" -> pure CO
"cr" -> pure CR
"cu" -> pure CU
"cv" -> pure CV
"cx" -> pure CX
"cy" -> pure CY
"cz" -> pure CZ
"de" -> pure DE
"dj" -> pure DJ
"dk" -> pure DK
"dm" -> pure DM
"do" -> pure DO
"dz" -> pure DZ
"ec" -> pure EC
"ee" -> pure EE
"eg" -> pure EG
"er" -> pure ER
"es" -> pure ES
"et" -> pure ET
"fi" -> pure FI
"fj" -> pure FJ
"fk" -> pure FK
"fm" -> pure FM
"fo" -> pure FO
"fr" -> pure FR
"ga" -> pure GA
"gb" -> pure GB
"gd" -> pure GD
"ge" -> pure GE
"gh" -> pure GH
"gi" -> pure GI
"gl" -> pure GL
"gm" -> pure GM
"gn" -> pure GN
"gq" -> pure GQ
"gr" -> pure GR
"gt" -> pure GT'
"gu" -> pure GU
"gw" -> pure GW
"gy" -> pure GY
"hk" -> pure HK
"hn" -> pure HN
"hr" -> pure HR
"ht" -> pure HT
"hu" -> pure HU
"ie" -> pure IE
"il" -> pure IL
"im" -> pure IM
"in" -> pure IN
"iq" -> pure IQ
"ir" -> pure IR
"is" -> pure IS
"it" -> pure IT
"id" -> pure Id
"jm" -> pure JM
"jo" -> pure JO
"jp" -> pure JP
"ke" -> pure KE
"kg" -> pure KG
"kh" -> pure KH
"ki" -> pure KI
"km" -> pure KM
"kn" -> pure KN
"kp" -> pure KP
"kr" -> pure KR
"kw" -> pure KW
"ky" -> pure KY
"kz" -> pure KZ
"la" -> pure LA
"lb" -> pure LB
"lc" -> pure LC
"li" -> pure LI
"lk" -> pure LK
"lr" -> pure LR
"ls" -> pure LS
"lt" -> pure LT'
"lu" -> pure LU
"lv" -> pure LV
"ly" -> pure LY
"ma" -> pure MA
"mc" -> pure MC
"md" -> pure MD
"me" -> pure ME
"mf" -> pure MF
"mg" -> pure MG
"mh" -> pure MH
"mk" -> pure MK
"ml" -> pure ML
"mm" -> pure MM
"mn" -> pure MN
"mo" -> pure MO
"mp" -> pure MP
"mr" -> pure MR
"ms" -> pure MS
"mt" -> pure MT
"mu" -> pure MU
"mv" -> pure MV
"mw" -> pure MW
"mx" -> pure MX
"my" -> pure MY
"mz" -> pure MZ
"na" -> pure NA
"nc" -> pure NC
"ne" -> pure NE
"ng" -> pure NG
"ni" -> pure NI
"nl" -> pure NL
"no" -> pure NO
"np" -> pure NP
"nr" -> pure NR
"nu" -> pure NU
"nz" -> pure NZ
"om" -> pure OM
"pa" -> pure PA
"pe" -> pure PE
"pf" -> pure PF
"pg" -> pure PG
"ph" -> pure PH
"pk" -> pure PK
"pl" -> pure PL
"pm" -> pure PM
"pn" -> pure PN
"pr" -> pure PR
"pt" -> pure PT
"pw" -> pure PW
"py" -> pure PY
"qa" -> pure QA
"ro" -> pure RO
"rs" -> pure RS
"ru" -> pure RU
"rw" -> pure RW
"sa" -> pure SA
"sb" -> pure SB
"sc" -> pure SC
"sd" -> pure SD
"se" -> pure SE
"sg" -> pure SG
"sh" -> pure SH
"si" -> pure SI
"sk" -> pure SK
"sl" -> pure SL
"sm" -> pure SM
"sn" -> pure SN
"so" -> pure SO
"sr" -> pure SR
"st" -> pure ST
"sv" -> pure SV
"sy" -> pure SY
"sz" -> pure SZ
"tc" -> pure TC
"td" -> pure TD
"tg" -> pure TG
"th" -> pure TH
"tj" -> pure TJ
"tk" -> pure TK
"tl" -> pure TL
"tm" -> pure TM
"tn" -> pure TN
"to" -> pure TO
"tr" -> pure TR
"tt" -> pure TT
"tv" -> pure TV
"tw" -> pure TW
"tz" -> pure TZ
"ua" -> pure UA
"ug" -> pure UG
"us" -> pure US
"uy" -> pure UY
"uz" -> pure UZ
"va" -> pure VA
"vc" -> pure VC
"ve" -> pure VE
"vg" -> pure VG
"vi" -> pure VI
"vn" -> pure VN
"vu" -> pure VU
"wf" -> pure WF
"ws" -> pure WS
"ye" -> pure YE
"yt" -> pure YT
"za" -> pure ZA
"zm" -> pure ZM
"zw" -> pure ZW
e -> fromTextError $ "Failure parsing CountryCode from value: '" <> e
<> "'. Accepted values: AD, AE, AF, AG, AI, AL, AM, AN, AO, AQ, AR, AS, AT, AU, AW, AZ, BA, BB, BD, BE, BF, BG, BH, BI, BJ, BL, BM, BN, BO, BR, BS, BT, BW, BY, BZ, CA, CC, CD, CF, CG, CH, CI, CK, CL, CM, CN, CO, CR, CU, CV, CX, CY, CZ, DE, DJ, DK, DM, DO, DZ, EC, EE, EG, ER, ES, ET, FI, FJ, FK, FM, FO, FR, GA, GB, GD, GE, GH, GI, GL, GM, GN, GQ, GR, GT, GU, GW, GY, HK, HN, HR, HT, HU, IE, IL, IM, IN, IQ, IR, IS, IT, ID, JM, JO, JP, KE, KG, KH, KI, KM, KN, KP, KR, KW, KY, KZ, LA, LB, LC, LI, LK, LR, LS, LT, LU, LV, LY, MA, MC, MD, ME, MF, MG, MH, MK, ML, MM, MN, MO, MP, MR, MS, MT, MU, MV, MW, MX, MY, MZ, NA, NC, NE, NG, NI, NL, NO, NP, NR, NU, NZ, OM, PA, PE, PF, PG, PH, PK, PL, PM, PN, PR, PT, PW, PY, QA, RO, RS, RU, RW, SA, SB, SC, SD, SE, SG, SH, SI, SK, SL, SM, SN, SO, SR, ST, SV, SY, SZ, TC, TD, TG, TH, TJ, TK, TL, TM, TN, TO, TR, TT, TV, TW, TZ, UA, UG, US, UY, UZ, VA, VC, VE, VG, VI, VN, VU, WF, WS, YE, YT, ZA, ZM, ZW"
instance ToText CountryCode where
toText = \case
AD -> "AD"
AE -> "AE"
AF -> "AF"
AG -> "AG"
AI -> "AI"
AL -> "AL"
AM -> "AM"
AN -> "AN"
AO -> "AO"
AQ -> "AQ"
AR -> "AR"
AS -> "AS"
AT -> "AT"
AU -> "AU"
AW -> "AW"
AZ -> "AZ"
BA -> "BA"
BB -> "BB"
BD -> "BD"
BE -> "BE"
BF -> "BF"
BG -> "BG"
BH -> "BH"
BI -> "BI"
BJ -> "BJ"
BL -> "BL"
BM -> "BM"
BN -> "BN"
BO -> "BO"
BR -> "BR"
BS -> "BS"
BT -> "BT"
BW -> "BW"
BY -> "BY"
BZ -> "BZ"
CA -> "CA"
CC -> "CC"
CD -> "CD"
CF -> "CF"
CG -> "CG"
CH -> "CH"
CI -> "CI"
CK -> "CK"
CL -> "CL"
CM -> "CM"
CN -> "CN"
CO -> "CO"
CR -> "CR"
CU -> "CU"
CV -> "CV"
CX -> "CX"
CY -> "CY"
CZ -> "CZ"
DE -> "DE"
DJ -> "DJ"
DK -> "DK"
DM -> "DM"
DO -> "DO"
DZ -> "DZ"
EC -> "EC"
EE -> "EE"
EG -> "EG"
ER -> "ER"
ES -> "ES"
ET -> "ET"
FI -> "FI"
FJ -> "FJ"
FK -> "FK"
FM -> "FM"
FO -> "FO"
FR -> "FR"
GA -> "GA"
GB -> "GB"
GD -> "GD"
GE -> "GE"
GH -> "GH"
GI -> "GI"
GL -> "GL"
GM -> "GM"
GN -> "GN"
GQ -> "GQ"
GR -> "GR"
GT' -> "GT"
GU -> "GU"
GW -> "GW"
GY -> "GY"
HK -> "HK"
HN -> "HN"
HR -> "HR"
HT -> "HT"
HU -> "HU"
IE -> "IE"
IL -> "IL"
IM -> "IM"
IN -> "IN"
IQ -> "IQ"
IR -> "IR"
IS -> "IS"
IT -> "IT"
Id -> "ID"
JM -> "JM"
JO -> "JO"
JP -> "JP"
KE -> "KE"
KG -> "KG"
KH -> "KH"
KI -> "KI"
KM -> "KM"
KN -> "KN"
KP -> "KP"
KR -> "KR"
KW -> "KW"
KY -> "KY"
KZ -> "KZ"
LA -> "LA"
LB -> "LB"
LC -> "LC"
LI -> "LI"
LK -> "LK"
LR -> "LR"
LS -> "LS"
LT' -> "LT"
LU -> "LU"
LV -> "LV"
LY -> "LY"
MA -> "MA"
MC -> "MC"
MD -> "MD"
ME -> "ME"
MF -> "MF"
MG -> "MG"
MH -> "MH"
MK -> "MK"
ML -> "ML"
MM -> "MM"
MN -> "MN"
MO -> "MO"
MP -> "MP"
MR -> "MR"
MS -> "MS"
MT -> "MT"
MU -> "MU"
MV -> "MV"
MW -> "MW"
MX -> "MX"
MY -> "MY"
MZ -> "MZ"
NA -> "NA"
NC -> "NC"
NE -> "NE"
NG -> "NG"
NI -> "NI"
NL -> "NL"
NO -> "NO"
NP -> "NP"
NR -> "NR"
NU -> "NU"
NZ -> "NZ"
OM -> "OM"
PA -> "PA"
PE -> "PE"
PF -> "PF"
PG -> "PG"
PH -> "PH"
PK -> "PK"
PL -> "PL"
PM -> "PM"
PN -> "PN"
PR -> "PR"
PT -> "PT"
PW -> "PW"
PY -> "PY"
QA -> "QA"
RO -> "RO"
RS -> "RS"
RU -> "RU"
RW -> "RW"
SA -> "SA"
SB -> "SB"
SC -> "SC"
SD -> "SD"
SE -> "SE"
SG -> "SG"
SH -> "SH"
SI -> "SI"
SK -> "SK"
SL -> "SL"
SM -> "SM"
SN -> "SN"
SO -> "SO"
SR -> "SR"
ST -> "ST"
SV -> "SV"
SY -> "SY"
SZ -> "SZ"
TC -> "TC"
TD -> "TD"
TG -> "TG"
TH -> "TH"
TJ -> "TJ"
TK -> "TK"
TL -> "TL"
TM -> "TM"
TN -> "TN"
TO -> "TO"
TR -> "TR"
TT -> "TT"
TV -> "TV"
TW -> "TW"
TZ -> "TZ"
UA -> "UA"
UG -> "UG"
US -> "US"
UY -> "UY"
UZ -> "UZ"
VA -> "VA"
VC -> "VC"
VE -> "VE"
VG -> "VG"
VI -> "VI"
VN -> "VN"
VU -> "VU"
WF -> "WF"
WS -> "WS"
YE -> "YE"
YT -> "YT"
ZA -> "ZA"
ZM -> "ZM"
ZW -> "ZW"
instance Hashable CountryCode
instance ToByteString CountryCode
instance ToQuery CountryCode
instance ToHeader CountryCode
instance ToJSON CountryCode where
toJSON = toJSONText
instance FromJSON CountryCode where
parseJSON = parseJSONText "CountryCode"
data DomainAvailability
= Available
| AvailablePreorder
| AvailableReserved
| DontKnow
| Reserved
| Unavailable
| UnavailablePremium
| UnavailableRestricted
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText DomainAvailability where
parser = takeLowerText >>= \case
"available" -> pure Available
"available_preorder" -> pure AvailablePreorder
"available_reserved" -> pure AvailableReserved
"dont_know" -> pure DontKnow
"reserved" -> pure Reserved
"unavailable" -> pure Unavailable
"unavailable_premium" -> pure UnavailablePremium
"unavailable_restricted" -> pure UnavailableRestricted
e -> fromTextError $ "Failure parsing DomainAvailability from value: '" <> e
<> "'. Accepted values: AVAILABLE, AVAILABLE_PREORDER, AVAILABLE_RESERVED, DONT_KNOW, RESERVED, UNAVAILABLE, UNAVAILABLE_PREMIUM, UNAVAILABLE_RESTRICTED"
instance ToText DomainAvailability where
toText = \case
Available -> "AVAILABLE"
AvailablePreorder -> "AVAILABLE_PREORDER"
AvailableReserved -> "AVAILABLE_RESERVED"
DontKnow -> "DONT_KNOW"
Reserved -> "RESERVED"
Unavailable -> "UNAVAILABLE"
UnavailablePremium -> "UNAVAILABLE_PREMIUM"
UnavailableRestricted -> "UNAVAILABLE_RESTRICTED"
instance Hashable DomainAvailability
instance ToByteString DomainAvailability
instance ToQuery DomainAvailability
instance ToHeader DomainAvailability
instance FromJSON DomainAvailability where
parseJSON = parseJSONText "DomainAvailability"
data ExtraParamName
= AuIdNumber
| AuIdType
| BirthCity
| BirthCountry
| BirthDateInYyyyMmDd
| BirthDepartment
| BrandNumber
| CaLegalType
| DocumentNumber
| DunsNumber
| EsIdentification
| EsIdentificationType
| EsLegalForm
| FiBusinessNumber
| FiIdNumber
| ItPin
| RuPassportData
| SeIdNumber
| SgIdNumber
| VatNumber
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText ExtraParamName where
parser = takeLowerText >>= \case
"au_id_number" -> pure AuIdNumber
"au_id_type" -> pure AuIdType
"birth_city" -> pure BirthCity
"birth_country" -> pure BirthCountry
"birth_date_in_yyyy_mm_dd" -> pure BirthDateInYyyyMmDd
"birth_department" -> pure BirthDepartment
"brand_number" -> pure BrandNumber
"ca_legal_type" -> pure CaLegalType
"document_number" -> pure DocumentNumber
"duns_number" -> pure DunsNumber
"es_identification" -> pure EsIdentification
"es_identification_type" -> pure EsIdentificationType
"es_legal_form" -> pure EsLegalForm
"fi_business_number" -> pure FiBusinessNumber
"fi_id_number" -> pure FiIdNumber
"it_pin" -> pure ItPin
"ru_passport_data" -> pure RuPassportData
"se_id_number" -> pure SeIdNumber
"sg_id_number" -> pure SgIdNumber
"vat_number" -> pure VatNumber
e -> fromTextError $ "Failure parsing ExtraParamName from value: '" <> e
<> "'. Accepted values: AU_ID_NUMBER, AU_ID_TYPE, BIRTH_CITY, BIRTH_COUNTRY, BIRTH_DATE_IN_YYYY_MM_DD, BIRTH_DEPARTMENT, BRAND_NUMBER, CA_LEGAL_TYPE, DOCUMENT_NUMBER, DUNS_NUMBER, ES_IDENTIFICATION, ES_IDENTIFICATION_TYPE, ES_LEGAL_FORM, FI_BUSINESS_NUMBER, FI_ID_NUMBER, IT_PIN, RU_PASSPORT_DATA, SE_ID_NUMBER, SG_ID_NUMBER, VAT_NUMBER"
instance ToText ExtraParamName where
toText = \case
AuIdNumber -> "AU_ID_NUMBER"
AuIdType -> "AU_ID_TYPE"
BirthCity -> "BIRTH_CITY"
BirthCountry -> "BIRTH_COUNTRY"
BirthDateInYyyyMmDd -> "BIRTH_DATE_IN_YYYY_MM_DD"
BirthDepartment -> "BIRTH_DEPARTMENT"
BrandNumber -> "BRAND_NUMBER"
CaLegalType -> "CA_LEGAL_TYPE"
DocumentNumber -> "DOCUMENT_NUMBER"
DunsNumber -> "DUNS_NUMBER"
EsIdentification -> "ES_IDENTIFICATION"
EsIdentificationType -> "ES_IDENTIFICATION_TYPE"
EsLegalForm -> "ES_LEGAL_FORM"
FiBusinessNumber -> "FI_BUSINESS_NUMBER"
FiIdNumber -> "FI_ID_NUMBER"
ItPin -> "IT_PIN"
RuPassportData -> "RU_PASSPORT_DATA"
SeIdNumber -> "SE_ID_NUMBER"
SgIdNumber -> "SG_ID_NUMBER"
VatNumber -> "VAT_NUMBER"
instance Hashable ExtraParamName
instance ToByteString ExtraParamName
instance ToQuery ExtraParamName
instance ToHeader ExtraParamName
instance ToJSON ExtraParamName where
toJSON = toJSONText
instance FromJSON ExtraParamName where
parseJSON = parseJSONText "ExtraParamName"
data OperationStatus
= Error'
| Failed
| InProgress
| Submitted
| Successful
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText OperationStatus where
parser = takeLowerText >>= \case
"error" -> pure Error'
"failed" -> pure Failed
"in_progress" -> pure InProgress
"submitted" -> pure Submitted
"successful" -> pure Successful
e -> fromTextError $ "Failure parsing OperationStatus from value: '" <> e
<> "'. Accepted values: ERROR, FAILED, IN_PROGRESS, SUBMITTED, SUCCESSFUL"
instance ToText OperationStatus where
toText = \case
Error' -> "ERROR"
Failed -> "FAILED"
InProgress -> "IN_PROGRESS"
Submitted -> "SUBMITTED"
Successful -> "SUCCESSFUL"
instance Hashable OperationStatus
instance ToByteString OperationStatus
instance ToQuery OperationStatus
instance ToHeader OperationStatus
instance FromJSON OperationStatus where
parseJSON = parseJSONText "OperationStatus"
data OperationType
= ChangePrivacyProtection
| DeleteDomain
| DomainLock
| RegisterDomain
| TransferInDomain
| UpdateDomainContact
| UpdateNameserver
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText OperationType where
parser = takeLowerText >>= \case
"change_privacy_protection" -> pure ChangePrivacyProtection
"delete_domain" -> pure DeleteDomain
"domain_lock" -> pure DomainLock
"register_domain" -> pure RegisterDomain
"transfer_in_domain" -> pure TransferInDomain
"update_domain_contact" -> pure UpdateDomainContact
"update_nameserver" -> pure UpdateNameserver
e -> fromTextError $ "Failure parsing OperationType from value: '" <> e
<> "'. Accepted values: CHANGE_PRIVACY_PROTECTION, DELETE_DOMAIN, DOMAIN_LOCK, REGISTER_DOMAIN, TRANSFER_IN_DOMAIN, UPDATE_DOMAIN_CONTACT, UPDATE_NAMESERVER"
instance ToText OperationType where
toText = \case
ChangePrivacyProtection -> "CHANGE_PRIVACY_PROTECTION"
DeleteDomain -> "DELETE_DOMAIN"
DomainLock -> "DOMAIN_LOCK"
RegisterDomain -> "REGISTER_DOMAIN"
TransferInDomain -> "TRANSFER_IN_DOMAIN"
UpdateDomainContact -> "UPDATE_DOMAIN_CONTACT"
UpdateNameserver -> "UPDATE_NAMESERVER"
instance Hashable OperationType
instance ToByteString OperationType
instance ToQuery OperationType
instance ToHeader OperationType
instance FromJSON OperationType where
parseJSON = parseJSONText "OperationType"
| olorin/amazonka | amazonka-route53-domains/gen/Network/AWS/Route53Domains/Types/Sum.hs | mpl-2.0 | 22,405 | 0 | 12 | 9,025 | 5,810 | 2,914 | 2,896 | 919 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Snap.Internal.Http.Server.Socket.Tests (tests) where
------------------------------------------------------------------------------
import Control.Applicative ((<$>))
import qualified Network.Socket as N
------------------------------------------------------------------------------
import Control.Concurrent (forkIO, killThread, newEmptyMVar, putMVar, readMVar, takeMVar)
import qualified Control.Exception as E
import Data.IORef (newIORef, readIORef, writeIORef)
import Test.Framework (Test)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (assertEqual)
------------------------------------------------------------------------------
import qualified Snap.Internal.Http.Server.Socket as Sock
import Snap.Test.Common (eatException, expectException, withSock)
------------------------------------------------------------------------------
#ifdef HAS_UNIX_SOCKETS
import System.Directory (getTemporaryDirectory)
import System.FilePath ((</>))
import qualified System.Posix as Posix
# if !MIN_VERSION_unix(2,6,0)
import Control.Monad.State (replicateM)
import Control.Monad.Trans.State.Strict as State
import qualified Data.Vector.Unboxed as V
import System.Directory (createDirectoryIfMissing)
import System.Random (StdGen, newStdGen, randomR)
# endif
#else
import Snap.Internal.Http.Server.Address (AddressNotSupportedException)
#endif
------------------------------------------------------------------------------
#ifdef HAS_UNIX_SOCKETS
mkdtemp :: String -> IO FilePath
# if MIN_VERSION_unix(2,6,0)
mkdtemp = Posix.mkdtemp
# else
tMPCHARS :: V.Vector Char
tMPCHARS = V.fromList $! ['a'..'z'] ++ ['0'..'9']
mkdtemp template = do
suffix <- newStdGen >>= return . State.evalState (chooseN 8 tMPCHARS)
let dir = template ++ suffix
createDirectoryIfMissing False dir
return dir
where
choose :: V.Vector Char -> State.State StdGen Char
choose v = do let sz = V.length v
idx <- State.state $ randomR (0, sz - 1)
return $! (V.!) v idx
chooseN :: Int -> V.Vector Char -> State.State StdGen String
chooseN n v = replicateM n $ choose v
#endif
#endif
------------------------------------------------------------------------------
tests :: [Test]
tests = [ testSockClosedOnListenException
, testAcceptFailure
, testUnixSocketBind
]
------------------------------------------------------------------------------
testSockClosedOnListenException :: Test
testSockClosedOnListenException = testCase "socket/closedOnListenException" $ do
ref <- newIORef Nothing
expectException $ Sock.bindSocketImpl (sso ref) bs ls "127.0.0.1" 4444
(Just sock) <- readIORef ref
let (N.MkSocket _ _ _ _ mvar) = sock
readMVar mvar >>= assertEqual "socket closed" N.Closed
where
sso ref sock _ _ = do
let (N.MkSocket _ _ _ _ mvar) = sock
readMVar mvar >>= assertEqual "socket not connected" N.NotConnected
writeIORef ref (Just sock) >> fail "set socket option"
bs _ _ = fail "bindsocket"
ls _ _ = fail "listen"
------------------------------------------------------------------------------
testAcceptFailure :: Test
testAcceptFailure = testCase "socket/acceptAndInitialize" $ do
sockmvar <- newEmptyMVar
donemvar <- newEmptyMVar
E.bracket (Sock.bindSocket "127.0.0.1" $ fromIntegral N.aNY_PORT)
(N.close)
(\s -> do
p <- fromIntegral <$> N.socketPort s
forkIO $ server s sockmvar donemvar
E.bracket (forkIO $ client p)
(killThread)
(\_ -> do
csock <- takeMVar sockmvar
takeMVar donemvar
N.isConnected csock >>=
assertEqual "closed" False
)
)
where
server sock sockmvar donemvar = serve `E.finally` putMVar donemvar ()
where
serve = eatException $ E.mask $ \restore ->
Sock.acceptAndInitialize sock restore $ \(csock, _) -> do
putMVar sockmvar csock
fail "error"
client port = withSock port (const $ return ())
testUnixSocketBind :: Test
#ifdef HAS_UNIX_SOCKETS
testUnixSocketBind = testCase "socket/unixSocketBind" $
withSocketPath $ \path -> do
E.bracket (Sock.bindUnixSocket Nothing path) N.close $ \sock -> do
N.isListening sock >>= assertEqual "listening" True
expectException $ E.bracket (Sock.bindUnixSocket Nothing "a/relative/path")
N.close doNothing
expectException $ E.bracket (Sock.bindUnixSocket Nothing "/relative/../path")
N.close doNothing
expectException $ E.bracket (Sock.bindUnixSocket Nothing "/hopefully/not/existing/path")
N.close doNothing
#ifdef LINUX
-- Most (all?) BSD systems ignore access mode on unix sockets.
-- Should we still check it?
-- This is pretty much for 100% coverage
expectException $ E.bracket (Sock.bindUnixSocket Nothing "/")
N.close doNothing
let mode = 0o766
E.bracket (Sock.bindUnixSocket (Just mode) path) N.close $ \_ -> do
-- Should check sockFd instead of path?
sockMode <- fmap Posix.fileMode $ Posix.getFileStatus path
assertEqual "access mode" (fromIntegral mode) $
Posix.intersectFileModes Posix.accessModes sockMode
#endif
where
doNothing _ = return ()
withSocketPath act = do
tmpRoot <- getTemporaryDirectory
tmpDir <- mkdtemp $ tmpRoot </> "snap-server-test-"
let path = tmpDir </> "unixSocketBind.sock"
E.finally (act path) $ do
eatException $ Posix.removeLink path
eatException $ Posix.removeDirectory tmpDir
#else
testUnixSocketBind = testCase "socket/unixSocketBind" $ do
caught <- E.catch (Sock.bindUnixSocket Nothing "/tmp/snap-sock.sock" >> return False)
$ \(e :: AddressNotSupportedException) -> length (show e) `seq` return True
assertEqual "not supported" True caught
#endif
| 23Skidoo/snap-server | test/Snap/Internal/Http/Server/Socket/Tests.hs | bsd-3-clause | 6,678 | 0 | 20 | 1,872 | 1,410 | 729 | 681 | 59 | 1 |
module BootImport where
data Foo = Foo Int
| mpickering/ghc-exactprint | tests/examples/ghc710/BootImport.hs | bsd-3-clause | 44 | 0 | 6 | 9 | 13 | 8 | 5 | 2 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.