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 MultiParamTypeClasses
, FlexibleInstances
, FlexibleContexts #-}
module XMonad.Hooks.DynamicLog.Dzen2.Width where
import XMonad hiding (Font, Status)
import XMonad.Util.Font
import XMonad.Util.Font.Width
import XMonad.Hooks.DynamicLog.Dzen2.Content
import XMonad.Hooks.DynamicLog.Dzen2.Font
import XMonad.Hooks.DynamicLog.Dzen2.StatusText
import XMonad.Hooks.DynamicLog.Dzen2.Status
type PixelWidth = Int
class Monad m => Width w m where
width :: w -> m PixelWidth
-- | Return the width in pixels of the StatusText. FIXME: This only
-- works on xftFonts
instance Font (StatusText fnt) => Width (StatusText fnt) X where
width x = do
fnt <- font x
width (unpack x, fnt)
instance Width (Status String, XMonadFont) X where
width (s, xmf) = withDisplay (\disp -> xmfWidth disp xmf $ content s)
-- import XMonad hiding (Status)
-- import XMonad.Util.Font
-- import XMonad.Util.Font.Width
-- import XMonad.Hooks.DynamicLog.Dzen2.Font
-- import XMonad.Hooks.DynamicLog.Dzen2.StatusText
-- type PixelWidth = Int
-- -- | The width of something in _pixels_
-- class Monad m => Width s m where
-- width :: s -> m PixelWidth
-- width = const $ return 0
-- instance {-# OVERLAPS #-} Monad m => Width Static m where
-- width (SI _ (Dimension w) _) = return w
-- width (SR (Dimension w) _) = return w
-- width (SRO (Dimension w) _) = return w
-- width (SC (Dimension r)) = return $ 2 * r
-- width (SCO (Dimension r)) = return $ 2 * r
-- width s = return 0
-- instance {-# OVERLAPS #-} Width s m => Width (Status s) m where
-- width (SAtom x) = width x
-- width (SList xs) = fmap sum $ sequence $ fmap width xs
-- width (SP _ x) = width x
-- width (SPA _ x) = width x
-- width (SFG _ x) = width x
-- width (SBG _ x) = width x
-- width (SCA _ _ x) = width x
-- width (SStatic s) = width s
-- instance {-# OVERLAPS #-} Width StatusText X where
-- width (StatusText (fnt, s)) = do
-- xftFont <- font fnt
-- withDisplay (\disp -> xftWidth disp xftFont s)
| Fizzixnerd/xmonad-config | site-haskell/src/XMonad/Hooks/DynamicLog/Dzen2/Width.hs | gpl-3.0 | 2,044 | 0 | 10 | 435 | 253 | 157 | 96 | 20 | 0 |
module HW08.Employee where
import Data.Tree
-- Employee names are represented by Strings.
type Name = String
-- The amount of fun an employee would have at the party, represented
-- by an Integer
type Fun = Integer
-- An Employee consists of a name and a fun score.
data Employee = Emp { empName :: Name, empFun :: Fun }
deriving (Show, Read, Eq)
-- A small company hierarchy to use for testing purposes.
testCompany :: Tree Employee
testCompany
= Node (Emp "Stan" 9)
[ Node (Emp "Bob" 2)
[ Node (Emp "Joe" 5)
[ Node (Emp "John" 1) []
, Node (Emp "Sue" 5) []
]
, Node (Emp "Fred" 3) []
]
, Node (Emp "Sarah" 17)
[ Node (Emp "Sam" 4) []
]
]
testCompany2 :: Tree Employee
testCompany2
= Node (Emp "Stan" 9)
[ Node (Emp "Bob" 3) -- (8, 8)
[ Node (Emp "Joe" 5) -- (5, 6)
[ Node (Emp "John" 1) [] -- (1, 0)
, Node (Emp "Sue" 5) [] -- (5, 0)
]
, Node (Emp "Fred" 3) [] -- (3, 0)
]
, Node (Emp "Sarah" 17) -- (17, 4)
[ Node (Emp "Sam" 4) [] -- (4, 0)
]
]
testCompany3 :: Tree Employee
testCompany3
= Node (Emp "Stan" 9)
[ Node (Emp "Bob" 9)
[ Node (Emp "Joe" 9)
[ Node (Emp "John" 9) []
, Node (Emp "Sue" 9) []
]
, Node (Emp "Fred" 9) []
]
, Node (Emp "Sarah" 9)
[ Node (Emp "Sam" 9) []
]
]
-- A type to store a list of guests and their total fun score.
data GuestList = GL [Employee] Fun
deriving (Eq)
instance Ord GuestList where
compare (GL _ f1) (GL _ f2) = compare f1 f2
| martinvlk/cis194-homeworks | src/HW08/Employee.hs | gpl-3.0 | 1,599 | 0 | 13 | 521 | 570 | 299 | 271 | 40 | 1 |
module Movie where
import Data.Function
import Data.List
import Data.List.Split
-- | Movie data type. Used to store, print and compare Movies.
data Movie = Movie { movieId :: Int
, title :: String
, date :: String
, url :: String
, rating :: Double
, genres :: [Genre]
} deriving (Eq, Read)
-- | Data type holding each of the Genre types.
-- This is an instance of Enum so that I can convert between Int and Genre
-- pretty easily.
-- This is also an instance of Ord, so that I can sort by Genre if needed at
-- some point in the future
data Genre = Unknown | Action | Adventure | Animation | Children | Comedy
| Crime | Documentary | Drama | Fantasy | FilmNoir | Horror
| Musical | Mystery | Romance | SciFi | Thriller | Western
deriving (Eq, Enum, Ord, Read, Show)
-- | Changing the way Movies are printed so that they print in the form
-- `ID Title Rating`
instance Show Movie where
show m = intercalate "\t" . map ($m) $ [show . movieId, title, show . rating]
-- | Instancing Ord to compare Movies by their rating.
instance Ord Movie where
compare = compare `on` rating
genreID :: Genre -> Int
genreID = (+1) . fromEnum
toGenre :: Int -> Genre
toGenre = toEnum . (\x -> x - 1)
data Rating = Rating { userId :: Int
, rMovieId :: Int
, rRating :: Int
} deriving (Eq)
instance Show Rating where
show r = intercalate "\t" [show $ userId r, show $ rMovieId r, show $ rRating r]
instance Ord Rating where
compare = compare `on` rMovieId
| Jiggins/CS210 | Movie.hs | gpl-3.0 | 1,708 | 0 | 10 | 554 | 395 | 233 | 162 | 31 | 1 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, Rank2Types, RecordWildCards #-}
module Main
( main
) where
import Prelude.Compat
import qualified Control.Exception as E
import Control.Lens.Operators
import Control.Monad (join, unless, replicateM_)
import Data.IORef
import Data.MRUMemo (memoIO)
import Data.Maybe
import qualified Data.Monoid as Monoid
import Data.Store.Db (Db)
import qualified Data.Store.IRef as IRef
import Data.Store.Transaction (Transaction)
import qualified Data.Store.Transaction as Transaction
import GHC.Conc (setNumCapabilities, getNumProcessors)
import Graphics.UI.Bottle.MainLoop (mainLoopWidget)
import Graphics.UI.Bottle.Widget (Widget)
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Graphics.UI.Bottle.Widgets.EventMapDoc as EventMapDoc
import qualified Graphics.UI.Bottle.Widgets.FlyNav as FlyNav
import qualified Graphics.UI.GLFW as GLFW
import qualified Graphics.UI.GLFW.Utils as GLFWUtils
import Lamdu.Config (Config)
import qualified Lamdu.Config as Config
import Lamdu.Config.Sampler (Sampler)
import qualified Lamdu.Config.Sampler as ConfigSampler
import qualified Lamdu.Data.DbLayout as DbLayout
import qualified Lamdu.Data.ExampleDB as ExampleDB
import Lamdu.DataFile (getLamduDir)
import qualified Lamdu.DefEvaluators as DefEvaluators
import qualified Lamdu.Font as Font
import Lamdu.GUI.CodeEdit.Settings (Settings(..))
import qualified Lamdu.GUI.CodeEdit.Settings as Settings
import qualified Lamdu.GUI.Main as GUIMain
import qualified Lamdu.GUI.WidgetIds as WidgetIds
import qualified Lamdu.GUI.Zoom as Zoom
import qualified Lamdu.Opts as Opts
import qualified Lamdu.Style as Style
import qualified Lamdu.VersionControl as VersionControl
import Lamdu.VersionControl.Actions (mUndo)
import qualified System.Directory as Directory
import System.IO (hPutStrLn, stderr)
main :: IO ()
main =
do
setNumCapabilities =<< getNumProcessors
lamduDir <- getLamduDir
opts <- either fail return =<< Opts.get
let withDB = ExampleDB.withDB lamduDir
case opts of
Opts.Parsed{..}
| _poShouldDeleteDB -> deleteDB lamduDir
| _poUndoCount > 0 -> withDB $ undoN _poUndoCount
| otherwise -> withDB $ runEditor _poMFontPath
`E.catch` \[email protected]{} -> do
hPutStrLn stderr $ "Main exiting due to exception: " ++ show e
return ()
deleteDB :: FilePath -> IO ()
deleteDB lamduDir =
do
putStrLn "Deleting DB..."
Directory.removeDirectoryRecursive lamduDir
undoN :: Int -> Db -> IO ()
undoN n db =
do
putStrLn $ "Undoing " ++ show n ++ " times"
DbLayout.runDbTransaction db $ replicateM_ n undo
where
undo =
do
actions <- VersionControl.makeActions
fromMaybe (fail "Cannot undo any further") $ mUndo actions
runEditor :: Maybe FilePath -> Db -> IO ()
runEditor mFontPath db =
do
-- GLFW changes the directory from start directory, at least on macs.
startDir <- Directory.getCurrentDirectory
-- Load config as early as possible, before we open any windows/etc
configSampler <- ConfigSampler.new startDir
GLFWUtils.withGLFW $ do
win <- GLFWUtils.createWindow "Lamdu" =<< GLFWUtils.getVideoModeSize
Font.with startDir mFontPath $ \font -> do
-- Fonts must be loaded after the GL context is created..
zoom <- Zoom.make =<< GLFWUtils.getDisplayScale win
addHelpWithStyle <- EventMapDoc.makeToggledHelpAdder EventMapDoc.HelpNotShown
settingsRef <- newIORef Settings
{ _sInfoMode = Settings.defaultInfoMode
}
wrapFlyNav <- FlyNav.makeIO Style.flyNav WidgetIds.flyNav
invalidateCacheRef <- newIORef (return ())
let invalidateCache = join (readIORef invalidateCacheRef)
evaluators <- DefEvaluators.new invalidateCache db
let onSettingsChange settings =
case settings ^. Settings.sInfoMode of
Settings.Evaluation -> DefEvaluators.start evaluators
_ -> DefEvaluators.stop evaluators
let makeWidget (config, size) =
do
cursor <-
DbLayout.cursor DbLayout.revisionProps
& Transaction.getP
& DbLayout.runDbTransaction db
sizeFactor <- Zoom.getSizeFactor zoom
globalEventMap <- Settings.mkEventMap onSettingsChange config settingsRef
let eventMap = globalEventMap `mappend` Zoom.eventMap zoom (Config.zoom config)
evalResults <- DefEvaluators.getResults evaluators
settings <- readIORef settingsRef
let env = GUIMain.Env
{ envEvalMap = evalResults
, envConfig = config
, envSettings = settings
, envStyle = Style.base config font
, envFullSize = size / sizeFactor
, envCursor = cursor
}
let dbToIO =
case settings ^. Settings.sInfoMode of
Settings.Evaluation ->
DefEvaluators.runTransactionAndMaybeRestartEvaluators evaluators
_ -> DbLayout.runDbTransaction db
widget <- mkWidgetWithFallback dbToIO env
return . Widget.scale sizeFactor $ Widget.weakerEvents eventMap widget
(invalidateCacheAction, makeWidgetCached) <- cacheMakeWidget makeWidget
refreshScheduler <- newRefreshScheduler
writeIORef invalidateCacheRef $
do
invalidateCacheAction
scheduleRefresh refreshScheduler
DefEvaluators.start evaluators
mainLoop win refreshScheduler configSampler $
\config size ->
( wrapFlyNav =<< makeWidgetCached (config, size)
, addHelpWithStyle (Style.help font (Config.help config)) size
)
newtype RefreshScheduler = RefreshScheduler (IORef Bool)
newRefreshScheduler :: IO RefreshScheduler
newRefreshScheduler = newIORef False <&> RefreshScheduler
shouldRefresh :: RefreshScheduler -> IO Bool
shouldRefresh (RefreshScheduler ref) = atomicModifyIORef ref $ \r -> (False, r)
scheduleRefresh :: RefreshScheduler -> IO ()
scheduleRefresh (RefreshScheduler ref) = writeIORef ref True
mainLoop ::
GLFW.Window -> RefreshScheduler -> Sampler Config ->
( Config -> Widget.Size ->
( IO (Widget IO)
, Widget IO -> IO (Widget IO)
)
) -> IO ()
mainLoop win refreshScheduler configSampler iteration =
do
lastVersionNumRef <- newIORef 0
let getAnimHalfLife =
ConfigSampler.getConfig configSampler <&> Style.anim . snd
makeWidget size =
do
(_, config) <- ConfigSampler.getConfig configSampler
let (makeBaseWidget, addHelp) = iteration config size
addHelp =<< makeBaseWidget
tickHandler =
do
(curVersionNum, _) <- ConfigSampler.getConfig configSampler
configChanged <- atomicModifyIORef lastVersionNumRef $ \lastVersionNum ->
(curVersionNum, lastVersionNum /= curVersionNum)
if configChanged
then return True
else shouldRefresh refreshScheduler
mainLoopWidget win tickHandler makeWidget getAnimHalfLife
cacheMakeWidget :: Eq a => (a -> IO (Widget IO)) -> IO (IO (), a -> IO (Widget IO))
cacheMakeWidget mkWidget =
do
widgetCacheRef <- newIORef =<< memoIO mkWidget
let invalidateCache = writeIORef widgetCacheRef =<< memoIO mkWidget
return
( invalidateCache
, \x ->
readIORef widgetCacheRef
>>= ($ x)
<&> Widget.events %~ (<* invalidateCache)
)
rootCursor :: Widget.Id
rootCursor = WidgetIds.fromGuid $ IRef.guid $ DbLayout.panes DbLayout.codeIRefs
mkWidgetWithFallback ::
(forall a. Transaction DbLayout.DbM a -> IO a) ->
GUIMain.Env -> IO (Widget IO)
mkWidgetWithFallback dbToIO env =
do
(isValid, widget) <-
dbToIO $
do
candidateWidget <- makeMainGui dbToIO env
(isValid, widget) <-
if candidateWidget ^. Widget.isFocused
then return (True, candidateWidget)
else do
finalWidget <- makeMainGui dbToIO env { GUIMain.envCursor = rootCursor }
Transaction.setP (DbLayout.cursor DbLayout.revisionProps) rootCursor
return (False, finalWidget)
unless (widget ^. Widget.isFocused) $
fail "Root cursor did not match"
return (isValid, widget)
unless isValid $ putStrLn $ "Invalid cursor: " ++ show (GUIMain.envCursor env)
widget
& Widget.backgroundColor
(Config.layerMax (Config.layers config))
["background"] (bgColor isValid config)
& return
where
config = GUIMain.envConfig env
bgColor False = Config.invalidCursorBGColor
bgColor True = Config.backgroundColor
makeMainGui ::
(forall a. Transaction DbLayout.DbM a -> f a) ->
GUIMain.Env -> Transaction DbLayout.DbM (Widget f)
makeMainGui runTransaction env =
GUIMain.make env rootCursor
<&> Widget.events %~ runTransaction . (attachCursor =<<)
where
attachCursor eventResult =
do
maybe (return ()) (Transaction.setP (DbLayout.cursor DbLayout.revisionProps)) .
Monoid.getLast $ eventResult ^. Widget.eCursor
return eventResult
| rvion/lamdu | Lamdu/Main.hs | gpl-3.0 | 10,645 | 21 | 32 | 3,624 | 2,358 | 1,220 | 1,138 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ScopedTypeVariables #-}
module EpsilonNFA where
import Data.Set
import qualified Data.List as L
import Control.Monad
import Control.Lens
import qualified DFA as D (State(State), Input(Input), Rule(Rule), DFA, mkDFA)
import qualified Debug.Trace as De
data Epsilon = Epsilon deriving (Show, Eq)
data Rule a b = Rule (D.State a) (Either (b -> Bool) Epsilon) (D.State a) deriving (Show)
matchRule :: (Eq a) => D.Input b -> D.State a -> [Rule a b] -> [Rule a b]
matchRule (D.Input i) cs rs =
L.filter (\(Rule c y _) -> case y of
(Left f) -> (cs == c) && (f i)
(Right _) -> False) rs
--Epsilonルール1ステップで移動可能な状態の集合を得る
eclose' :: (Eq a) => D.State a -> [Rule a b] -> [D.State a]
eclose' s rs = enext
where
erule = L.filter (\(Rule x y _) -> case y of
(Right _) -> (x == s)
(Left _) -> False) rs
enext = L.map (\(Rule _ _ ns) -> ns) erule
--Epsilonルールで移動可能な状態の集合を得る
eclose'' :: (Eq a) => [D.State a] -> [Rule a b] -> [D.State a] -> [D.State a]
eclose'' s rs acc
| epNexts == [] = acc
| otherwise = eclose'' s rs (acc ++ epNexts)
where
epNexts = L.filter (\es -> not (elem es acc)) $
concat $ L.map (\a -> eclose' a rs) acc
eclose :: (Eq a) => [D.State a] -> [Rule a b] -> [D.State a]
eclose s rs = eclose'' s rs s
data EpsilonNFA a b = EpsilonNFA {
_fstState :: D.State a
,_currState :: [D.State a]
,_rules :: [Rule a b]
,_goalState :: [D.State a]
} deriving (Show)
$(makeLenses ''EpsilonNFA)
mkEpsilonNFA :: (Eq a) => D.State a -> [Rule a b] -> [D.State a] -> EpsilonNFA a b
mkEpsilonNFA s rs gs = EpsilonNFA {
_fstState = s
,_currState = eclose [s] rs
,_rules = rs
,_goalState = gs
}
updateEpsilonNFA :: (Eq a) => EpsilonNFA a b -> D.Input b -> Maybe (EpsilonNFA a b)
updateEpsilonNFA enfa i = updateEpsilonNFA' enfa nxtStates
where
rs = concat $ L.map (\s -> matchRule i s (enfa^.rules))
(enfa^.currState)
nxtStates = eclose (L.map (\(Rule _ _ ns) -> ns) rs) (enfa^.rules)
updateEpsilonNFA' :: (Eq a) => EpsilonNFA a b -> [D.State a] -> Maybe (EpsilonNFA a b)
updateEpsilonNFA' _ [] = Nothing
updateEpsilonNFA' nfa ns = Just (nfa&currState.~ns)
runEpsilonNFA :: (Eq a) => EpsilonNFA a b -> [D.Input b] -> Maybe (EpsilonNFA a b)
runEpsilonNFA enfa is = foldM updateEpsilonNFA enfa is
accept :: (Eq a) => EpsilonNFA a b -> [b] -> Bool
accept enfa is = accept' res
where
res = runEpsilonNFA enfa $ L.map (\x -> (D.Input x)) is
accept' Nothing = False
accept' (Just f) = L.any (\s -> elem s (f^.goalState)) (f^.currState)
{-
- Convert Epsilon-NFA -> DFA
-}
type ENFARule a b = Rule a b
type DFARule a b = D.Rule (Set a) b
genDFARule' :: forall a b. (Ord a) => (D.State (Set a)) -> [ENFARule a b] -> [DFARule a b]
genDFARule' (D.State s) rs = L.map nxt matchedRules
where
matchedRules :: [ENFARule a b]
matchedRules = L.filter (\(Rule (D.State x) y _) -> case y of
(Right _) -> False
(Left _) -> (member x s)) rs
nxt :: ENFARule a b -> DFARule a b
nxt (Rule (D.State f) (Left i) t) = D.Rule (D.State s) i (D.State (fromList (L.map (\(D.State x) -> x) (eclose [t] rs))))
nxt (Rule _ (Right Epsilon) t) = error "Can't convert epsilon rule to dfa-rule. (Illigal state)"
genDFARule'' :: forall a b. (Ord a) => [ENFARule a b] -> [DFARule a b] -> [D.State (Set a)] -> [D.State (Set a)] -> [DFARule a b]
genDFARule'' rs acc visitedStates tmpStates
| L.null newTmpStates = acc ++ generatedRules
| otherwise = genDFARule'' rs (generatedRules ++ acc) (visitedStates ++ newTmpStates) newTmpStates
where
generatedRules :: [DFARule a b]
generatedRules = concat $ L.map (\x -> genDFARule' x rs) tmpStates
newTmpStates = L.filter (\x -> not (elem x visitedStates)) $ L.map (\(D.Rule _ _ x) -> x) generatedRules
genDFA :: forall a b. (Ord a) => EpsilonNFA a b -> D.DFA (Set a) b
genDFA enfa = D.mkDFA fst dfaRules dfaGoal
where
fstClose = eclose [(enfa^.fstState)] (enfa^.rules)
fst :: D.State (Set a)
fst = D.State $ fromList $ L.map (\(D.State x) -> x) fstClose
enfaRules = enfa^.rules
fstDFARules = genDFARule' fst enfaRules
fstTmpStates = L.filter (\x -> x /= fst) $ L.map (\(D.Rule _ _ x) -> x) fstDFARules
dfaRules = (genDFARule'' enfaRules fstDFARules [fst] fstTmpStates)
dfaGoal = L.nub $ L.filter (\(D.State t) -> any (\(D.State x) -> member x t) (enfa^.goalState)) $ [fst] ++ (L.map (\(D.Rule _ _ g) -> g) dfaRules)
| pocket7878/mini-reg | src/EpsilonNFA.hs | gpl-3.0 | 4,941 | 0 | 18 | 1,389 | 2,222 | 1,165 | 1,057 | 86 | 3 |
{-# 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.AdSenseHost.AssociationSessions.Start
-- 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)
--
-- Create an association session for initiating an association with an
-- AdSense user.
--
-- /See:/ <https://developers.google.com/adsense/host/ AdSense Host API Reference> for @adsensehost.associationsessions.start@.
module Network.Google.Resource.AdSenseHost.AssociationSessions.Start
(
-- * REST Resource
AssociationSessionsStartResource
-- * Creating a Request
, associationSessionsStart
, AssociationSessionsStart
-- * Request Lenses
, assCallbackURL
, assWebsiteLocale
, assUserLocale
, assWebsiteURL
, assProductCode
) where
import Network.Google.AdSenseHost.Types
import Network.Google.Prelude
-- | A resource alias for @adsensehost.associationsessions.start@ method which the
-- 'AssociationSessionsStart' request conforms to.
type AssociationSessionsStartResource =
"adsensehost" :>
"v4.1" :>
"associationsessions" :>
"start" :>
QueryParams "productCode"
AssociationSessionsStartProductCode
:>
QueryParam "websiteUrl" Text :>
QueryParam "callbackUrl" Text :>
QueryParam "websiteLocale" Text :>
QueryParam "userLocale" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] AssociationSession
-- | Create an association session for initiating an association with an
-- AdSense user.
--
-- /See:/ 'associationSessionsStart' smart constructor.
data AssociationSessionsStart =
AssociationSessionsStart'
{ _assCallbackURL :: !(Maybe Text)
, _assWebsiteLocale :: !(Maybe Text)
, _assUserLocale :: !(Maybe Text)
, _assWebsiteURL :: !Text
, _assProductCode :: ![AssociationSessionsStartProductCode]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AssociationSessionsStart' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'assCallbackURL'
--
-- * 'assWebsiteLocale'
--
-- * 'assUserLocale'
--
-- * 'assWebsiteURL'
--
-- * 'assProductCode'
associationSessionsStart
:: Text -- ^ 'assWebsiteURL'
-> [AssociationSessionsStartProductCode] -- ^ 'assProductCode'
-> AssociationSessionsStart
associationSessionsStart pAssWebsiteURL_ pAssProductCode_ =
AssociationSessionsStart'
{ _assCallbackURL = Nothing
, _assWebsiteLocale = Nothing
, _assUserLocale = Nothing
, _assWebsiteURL = pAssWebsiteURL_
, _assProductCode = _Coerce # pAssProductCode_
}
-- | The URL to redirect the user to once association is completed. It
-- receives a token parameter that can then be used to retrieve the
-- associated account.
assCallbackURL :: Lens' AssociationSessionsStart (Maybe Text)
assCallbackURL
= lens _assCallbackURL
(\ s a -> s{_assCallbackURL = a})
-- | The locale of the user\'s hosted website.
assWebsiteLocale :: Lens' AssociationSessionsStart (Maybe Text)
assWebsiteLocale
= lens _assWebsiteLocale
(\ s a -> s{_assWebsiteLocale = a})
-- | The preferred locale of the user.
assUserLocale :: Lens' AssociationSessionsStart (Maybe Text)
assUserLocale
= lens _assUserLocale
(\ s a -> s{_assUserLocale = a})
-- | The URL of the user\'s hosted website.
assWebsiteURL :: Lens' AssociationSessionsStart Text
assWebsiteURL
= lens _assWebsiteURL
(\ s a -> s{_assWebsiteURL = a})
-- | Products to associate with the user.
assProductCode :: Lens' AssociationSessionsStart [AssociationSessionsStartProductCode]
assProductCode
= lens _assProductCode
(\ s a -> s{_assProductCode = a})
. _Coerce
instance GoogleRequest AssociationSessionsStart where
type Rs AssociationSessionsStart = AssociationSession
type Scopes AssociationSessionsStart =
'["https://www.googleapis.com/auth/adsensehost"]
requestClient AssociationSessionsStart'{..}
= go _assProductCode (Just _assWebsiteURL)
_assCallbackURL
_assWebsiteLocale
_assUserLocale
(Just AltJSON)
adSenseHostService
where go
= buildClient
(Proxy :: Proxy AssociationSessionsStartResource)
mempty
| brendanhay/gogol | gogol-adsense-host/gen/Network/Google/Resource/AdSenseHost/AssociationSessions/Start.hs | mpl-2.0 | 5,067 | 0 | 17 | 1,150 | 648 | 381 | 267 | 103 | 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.Spanner.Projects.Instances.Databases.GetDdl
-- 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)
--
-- Returns the schema of a Cloud Spanner database as a list of formatted
-- DDL statements. This method does not show pending schema updates, those
-- may be queried using the Operations API.
--
-- /See:/ <https://cloud.google.com/spanner/ Cloud Spanner API Reference> for @spanner.projects.instances.databases.getDdl@.
module Network.Google.Resource.Spanner.Projects.Instances.Databases.GetDdl
(
-- * REST Resource
ProjectsInstancesDatabasesGetDdlResource
-- * Creating a Request
, projectsInstancesDatabasesGetDdl
, ProjectsInstancesDatabasesGetDdl
-- * Request Lenses
, pidgdXgafv
, pidgdUploadProtocol
, pidgdDatabase
, pidgdAccessToken
, pidgdUploadType
, pidgdCallback
) where
import Network.Google.Prelude
import Network.Google.Spanner.Types
-- | A resource alias for @spanner.projects.instances.databases.getDdl@ method which the
-- 'ProjectsInstancesDatabasesGetDdl' request conforms to.
type ProjectsInstancesDatabasesGetDdlResource =
"v1" :>
Capture "database" Text :>
"ddl" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] GetDatabaseDdlResponse
-- | Returns the schema of a Cloud Spanner database as a list of formatted
-- DDL statements. This method does not show pending schema updates, those
-- may be queried using the Operations API.
--
-- /See:/ 'projectsInstancesDatabasesGetDdl' smart constructor.
data ProjectsInstancesDatabasesGetDdl =
ProjectsInstancesDatabasesGetDdl'
{ _pidgdXgafv :: !(Maybe Xgafv)
, _pidgdUploadProtocol :: !(Maybe Text)
, _pidgdDatabase :: !Text
, _pidgdAccessToken :: !(Maybe Text)
, _pidgdUploadType :: !(Maybe Text)
, _pidgdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsInstancesDatabasesGetDdl' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pidgdXgafv'
--
-- * 'pidgdUploadProtocol'
--
-- * 'pidgdDatabase'
--
-- * 'pidgdAccessToken'
--
-- * 'pidgdUploadType'
--
-- * 'pidgdCallback'
projectsInstancesDatabasesGetDdl
:: Text -- ^ 'pidgdDatabase'
-> ProjectsInstancesDatabasesGetDdl
projectsInstancesDatabasesGetDdl pPidgdDatabase_ =
ProjectsInstancesDatabasesGetDdl'
{ _pidgdXgafv = Nothing
, _pidgdUploadProtocol = Nothing
, _pidgdDatabase = pPidgdDatabase_
, _pidgdAccessToken = Nothing
, _pidgdUploadType = Nothing
, _pidgdCallback = Nothing
}
-- | V1 error format.
pidgdXgafv :: Lens' ProjectsInstancesDatabasesGetDdl (Maybe Xgafv)
pidgdXgafv
= lens _pidgdXgafv (\ s a -> s{_pidgdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pidgdUploadProtocol :: Lens' ProjectsInstancesDatabasesGetDdl (Maybe Text)
pidgdUploadProtocol
= lens _pidgdUploadProtocol
(\ s a -> s{_pidgdUploadProtocol = a})
-- | Required. The database whose schema we wish to get. Values are of the
-- form \`projects\/\/instances\/\/databases\/\`
pidgdDatabase :: Lens' ProjectsInstancesDatabasesGetDdl Text
pidgdDatabase
= lens _pidgdDatabase
(\ s a -> s{_pidgdDatabase = a})
-- | OAuth access token.
pidgdAccessToken :: Lens' ProjectsInstancesDatabasesGetDdl (Maybe Text)
pidgdAccessToken
= lens _pidgdAccessToken
(\ s a -> s{_pidgdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pidgdUploadType :: Lens' ProjectsInstancesDatabasesGetDdl (Maybe Text)
pidgdUploadType
= lens _pidgdUploadType
(\ s a -> s{_pidgdUploadType = a})
-- | JSONP
pidgdCallback :: Lens' ProjectsInstancesDatabasesGetDdl (Maybe Text)
pidgdCallback
= lens _pidgdCallback
(\ s a -> s{_pidgdCallback = a})
instance GoogleRequest
ProjectsInstancesDatabasesGetDdl
where
type Rs ProjectsInstancesDatabasesGetDdl =
GetDatabaseDdlResponse
type Scopes ProjectsInstancesDatabasesGetDdl =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/spanner.admin"]
requestClient ProjectsInstancesDatabasesGetDdl'{..}
= go _pidgdDatabase _pidgdXgafv _pidgdUploadProtocol
_pidgdAccessToken
_pidgdUploadType
_pidgdCallback
(Just AltJSON)
spannerService
where go
= buildClient
(Proxy ::
Proxy ProjectsInstancesDatabasesGetDdlResource)
mempty
| brendanhay/gogol | gogol-spanner/gen/Network/Google/Resource/Spanner/Projects/Instances/Databases/GetDdl.hs | mpl-2.0 | 5,594 | 0 | 16 | 1,224 | 708 | 416 | 292 | 110 | 1 |
module Ledger.Application.Action (module Action) where
import Ledger.Application.Action.Common as Action
import Ledger.Application.Action.Entries as Action
import Ledger.Application.Action.Keys as Action
import Ledger.Application.Action.Root as Action
| asm-products/ledger-backend | library/Ledger/Application/Action.hs | agpl-3.0 | 253 | 0 | 4 | 22 | 49 | 37 | 12 | 5 | 0 |
module Jaek.UI.ControlGraph (
jaekControlGraph
)
where
import Jaek.Base
import Jaek.Tree
import Jaek.UI.AllSources
import Jaek.UI.Controllers
import Jaek.UI.Focus
import Jaek.UI.Views
import Reactive.Banana
jaekControlGraph
:: Sources
-> Discrete (Int,Int)
-> Discrete Focus
-> Discrete ViewMap
-> Discrete TreeZip
-> ControlGraph ()
jaekControlGraph sources dSize dFocus dViewMap dZip = do
baseNav <- buildController (allNav sources dFocus dZip dViewMap)
let dView = dState baseNav
wvSelectCtrl <- buildController (selectCtrl dSize dView dZip)
clipCtrl <- buildController
(clipboardCtrl dSize dViewMap dZip wvSelectCtrl sources)
let editCtrl = bindController (editCtrl1 dSize dViewMap clipCtrl
wvSelectCtrl sources)
wvSelectCtrl
addController editCtrl
when debug $ do
watch "waveSelection" wvSelectCtrl (changes . dState)
watch "clipboard" clipCtrl (changes . dState)
watch "commands" editCtrl
( fmap (liftZ getTransforms) . applyD (flip ($) <$> dZip) . eZipChange )
buildController (waveNav dFocus dZip)
return ()
| JohnLato/jaek | src/Jaek/UI/ControlGraph.hs | lgpl-3.0 | 1,170 | 0 | 17 | 280 | 338 | 165 | 173 | 33 | 1 |
--module Main where
import Debug.Trace
import Data.List
palinize2 :: Integer -> Integer
palinize2 x = read $ (show x) ++ (reverse $ show x)
palinize3 :: Integer -> [Integer]
palinize3 x = map (\i -> read $ ((show x)) ++ (i : reverse (show x))) "0123456789"
palins2 = map palinize2 [1..]
palins3 = [2..9] ++ concat (map palinize3 $ [1..])
isPalin x = (show x) == (reverse $ show x)
palins = filter isPalin [10..]
squares :: [Integer]
squares = (map (^2) [1..])
limit :: Integer
limit = 10^8
sqrtl = floor $ sqrt $ fromIntegral limit
searchfunc :: Integer -> [Integer]
searchfunc target = rec_search 0 [] $ reverse (takeWhile (<target) squares)
where
rec_search :: Integer -> [Integer] -> [Integer] -> [Integer]
rec_search sm [] [] = []
rec_search sm l1 [] =
if sm == target then l1 else
if sm > target then
rec_search (sm - head l1) (tail l1) []
else []
rec_search sm l1 l2 =
if sm > target then rec_search (sm - head l1) (tail l1) l2
else if sm < target then rec_search (sm + head l2) (l1 ++ [head l2]) (tail l2)
else l1
prob125 :: [Integer]
prob125 = filter (/=0) $ map (sum.searchfunc) mypalins
where
mypalins = concat (map (takeWhile (<limit)) [palins2,palins3])
main = putStrLn (show (sum prob125)) | jdavidberger/project-euler | prob125.hs | lgpl-3.0 | 1,570 | 0 | 13 | 585 | 601 | 320 | 281 | 32 | 7 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Log.Filter
-- Copyright : (C) 2015 Flowbox
-- License : Apache-2.0
-- Maintainer : Wojciech Daniło <[email protected]>
-- Stability : stable
-- Portability : portable
-----------------------------------------------------------------------------
module System.Log.Filter where
import System.Log.Log (Log)
import System.Log.Data (Lvl(Lvl), Msg(Msg), LevelData(LevelData), readData, DataOf, Lookup, LookupDataSet)
----------------------------------------------------------------------
-- Filter
----------------------------------------------------------------------
newtype Filter a = Filter { runFilter :: Log a -> Bool }
lvlFilter' :: (LookupDataSet Lvl l, Enum a) => a -> Log l -> Bool
lvlFilter' lvl l = (i >= fromEnum lvl) where
LevelData i _ = readData Lvl l
lvlFilter lvl = Filter (lvlFilter' lvl)
| wdanilo/haskell-logger | src/System/Log/Filter.hs | apache-2.0 | 1,094 | 0 | 8 | 148 | 184 | 112 | 72 | -1 | -1 |
module Sing where
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
sing :: [Char]
sing =
if (x > y) then fstString x else sndString y
where
x = "Singin"
y = "Somewhere"
| OCExercise/haskellbook-solutions | chapters/chapter05/exercises/sing.hs | bsd-2-clause | 292 | 0 | 7 | 92 | 104 | 59 | 45 | 10 | 2 |
module GTKUnit where
import Debug
import BattleContext
import Force
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Trans.Reader
import qualified Data.Text as DT
import qualified GI.Gtk as Gtk
import qualified GI.GdkPixbuf as GP
data GTKUnit = GTKUnit
{ gunitSyncId :: Int
, gunitEventBox :: Gtk.EventBox
, gunitImage :: Gtk.Image
-- upper-left positions in the Fixed container
, gunitImageX :: Int
, gunitImageY :: Int
, gunitVisible :: Bool
}
-- | Construct a new invisible GTK unit from a Unit (but do not attach to a layout yet)
newFromUnit :: FilePath -> Color -> Unit -> IO GTKUnit
newFromUnit iconsdir color unit@(Unit long lat name typ size rcp i) = do
let imagex = round long
let imagey = round lat
let iconf = iconsdir ++ "/" ++ (pickUnitIconFileName color typ size)
-- construct both the image and its EventBox container (used to handle click events)
image <- Gtk.imageNewFromFile iconf
evbox <- Gtk.eventBoxNew
_ <- Gtk.containerAdd evbox image
-- liftIO $ putInfo $ "newFromUnit: new GTK unit: unit " ++ show unit ++ ", icon " ++ iconf
return $ GTKUnit i evbox image imagex imagey False
-- | Select the unit's correct icon filename
pickUnitIconFileName :: Color -> Type -> Size -> FilePath
pickUnitIconFileName color typ size = let
charcolor = case color of
Blue -> "b"
Red -> "r"
chartyp = case typ of
Armor -> "arm"
Mech -> "mec"
charsize = case size of
Battalion -> "4"
Brigade -> "5"
in
charcolor ++ chartyp ++ charsize ++ ".ico"
-- | Construct gtk unit widgets for the force
constructForceUnitImages :: FilePath -> Force -> IO [GTKUnit]
constructForceUnitImages iconsdir force = do
gunits <- mapM (newFromUnit iconsdir (forceColor force)) (forceUnits force)
return gunits
destructUnitImage :: GTKUnit -> IO ()
destructUnitImage gunit = do
let evbox = gunitEventBox gunit
Gtk.widgetDestroy evbox
-- | Destroy gtk units's widgets
destructUnitImages :: [GTKUnit] -> IO ()
destructUnitImages gunits = do
_ <- mapM destructUnitImage gunits
return ()
| nbrk/ld | executable/GTKUnit.hs | bsd-2-clause | 2,084 | 0 | 12 | 421 | 534 | 279 | 255 | 50 | 4 |
module MessStart where
import Rumpus
start :: Start
start _entityID = do
forM_ [1..20::Int] $ \_ -> do
color <- liftIO $ randomRIO (0,1)
traverseM_ (spawnEntity "MessyBall") $
setEntityColor (color & _w .~ 1)
traverseM_ (spawnEntity "SoundCube") $
setEntityColor (color & _w .~ 1)
return Nothing
| lukexi/rumpus | util/DevScenes/scenes-old/fountain/MessStart.hs | bsd-3-clause | 355 | 0 | 15 | 105 | 129 | 64 | 65 | 11 | 1 |
module TNParser
(parseTNGraphEdgesFile
) where
import Text.ParserCombinators.Parsec
import TNTypes
import System.IO
import qualified Data.ByteString as S
import TNGraph as TNGraph
import qualified Data.Map.Strict as M
-- |Parses file contents into a TNGraph
-- Look at test_picture.txt to see file format
parseTNGraphEdgesFile :: String -> Either String TNGraph
parseTNGraphEdgesFile input =
let result = parse parseGraphEdgesFile "(unknown)" input
in finalResult(result)
finalResult:: Either ParseError TGraphInfo -> Either String TNGraph
finalResult input = either (Left . show) (Right . (TNGraph.buildTNGraphFromInfo TNDGraph)) input
parseGraphEdgesFile = do
skipMany comments
edges <- endBy edgeLine eol
skipMany comments
vertexValues <- endBy vertexValueLine eol
eof
return (edges, M.fromList vertexValues)
vertexValueLine = do
vertexId <- many1 digit
tab
sign <- optionMaybe ((char '+') <|> (char '-'))
value <- many1 digit
let vertexIdInt = read vertexId :: TNVertex
let valueInt = read value :: TNVertexValue
let signedInt =
case sign of
Nothing -> valueInt
Just(sign) -> if (sign == '-') then -valueInt else valueInt
return (vertexIdInt, signedInt)
comments = do
string "#"
comment <- (manyTill anyChar newline)
return ""
edgeLine = do
from <- many1 digit
tab
to <- many1 digit
let fromInt = read from :: TNVertex
let toInt = read to :: TNVertex
return (fromInt, toInt)
eol = char '\n'
| astarostap/cs240h_final_project | src/TNParser.hs | bsd-3-clause | 1,451 | 8 | 15 | 258 | 475 | 235 | 240 | 45 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Chess.PGN ( pgnParser
, PGN(..)
, GameResult(..)) where
import Chess
import Control.Applicative
import Data.Attoparsec.ByteString.Char8
import Data.ByteString.Char8 (pack, unpack)
import Data.Map (fromList, (!))
type Move = String
data PGN = PGN { event :: String
, site :: String
, date :: String
, round :: String
, whitePlayer :: String
, blackPlayer :: String
, result :: Maybe GameResult
, initialPosition :: Maybe Board
, moves :: [Move]
} deriving (Show)
data GameResult = WhiteWon
| BlackWon
| Draw
deriving (Eq, Show)
pgnParser = many gameParse
gameParse = do
skipSpace
tagsTups <- many1 parseTag
let tags = fromList tagsTups
let gameResult = case tags ! "Result" of
"1/2-1/2" -> Just Draw
"1-0" -> Just WhiteWon
"0-1" -> Just BlackWon
_ -> Nothing
moves <- many parseMove
many uselessStuff
endResult
return $ PGN (unpack $ tags ! "Event")
(unpack $ tags ! "Site")
(unpack $ tags ! "Date")
(unpack $ tags ! "Round")
(unpack $ tags ! "White")
(unpack $ tags ! "Black")
gameResult
Nothing
moves
-- todo: handle escaping
stringLiteral = do
char '"'
value <- takeTill ((==) '"')
char '"'
return value
parseTag = do
skipSpace
char '['
tagType <- takeTill ((==) ' ')
skipSpace
tagValue <- stringLiteral
char ']'
return (tagType, tagValue)
moveNumber = do
decimal
many $ char '.'
whitespace
nag = do
char '$'
decimal
whitespace
rav = do
char '('
scan 1 (\s a -> let news = if a == '('
then s+1
else (if a == ')'
then s-1
else s) in
if news == 0 then Nothing else Just news)
char ')'
comment = braceCmt <|> semiCmt where
braceCmt = do
char '{'
cmt <- takeTill ((==) '}')
char '}'
return cmt
semiCmt = do
char ';'
cmt <- takeTill ((==) '\n')
char '\n'
return cmt
discard a = do
a
return ()
whitespace = discard (char ' ') <|>
discard (char '\n') <|>
discard (string "\r\n") <|>
discard (char '\t')
uselessStuff = discard moveNumber <|>
discard comment <|>
discard whitespace <|>
discard nag <|>
discard rav
endResult = string "1-0" <|>
string "0-1" <|>
string "1/2-1/2" <|>
string "*"
parseMove = do
skipMany uselessStuff
movestr <- many1 $ satisfy (not . isSpace)
if movestr `elem` ["1-0", "0-1", "1/2-1/2", "*"] then
fail "end of game reached"
else
return movestr
| ArnoVanLumig/chesshs | Chess/PGN.hs | bsd-3-clause | 3,005 | 0 | 17 | 1,179 | 911 | 459 | 452 | 109 | 4 |
{-# LANGUAGE UnicodeSyntax #-}
module Tests.TicTacToe.Actions
(
spec
)
where
import Test.HUnit
import AXT.TicTacToe.Actions as GA(changeWorld)
import TestData as TD (fields)
import AXT.TicTacToe.Types as GT (CoorOnField, GameType(..), Field(F), State(..), StepResult(..), toCoorOnField)
import Helpers (mapTests)
spec = let
gg = [ ((GA, F ["XOO","X "," "]), changeWorld GA (head fields) (toCoorOnField 1 0) X VS_USER),
((GA, F ["XOO","X "," "]), changeWorld GA (head fields) (toCoorOnField 1 0) X VS_USER),
((GA, F ["XOO","X "," "]), changeWorld GA (head fields) (toCoorOnField 1 0) X VS_USER)]
in mapTests " changeWorld " gg
| xruzzz/axt-tic-tac-toe-gl-haskell | test/Tests/TicTacToe/Actions.hs | bsd-3-clause | 716 | 0 | 13 | 178 | 270 | 161 | 109 | 14 | 1 |
module Simulator (module Simulator) where
import Graphics.Gloss
import Control.Lens
import Control.Arrow
import Convenience
import Numeric.FastMath()
import Control.Monad.Random
class CanRender a where
simRender :: a Double -> Picture
class Steppable a where
simStep :: Floating f => a f -> a f
class HasCost a where
simCost :: Floating float => a float -> float
type CostStep a = (HasCost a, Steppable a)
class (CostStep a, CanRender a,Random (a Double)) => Simulator a where
realToFracSim :: Floating floating => a Double -> a floating
simulateN :: (CostStep t,Floating float) => Int -> t float -> (float, t float)
simulateN n initState = apply n simStep initState & simCost &&& id
trackCost :: (Default (a Double), CostStep a) => Int -> a Double -> [Double]
trackCost iterations a = iterate (apply iterations simStep) a &> simCost
simsRender l = l &!> simRender & pictures
simsStep l = l &!> simStep
simsCost l = l &!> simCost & sum
| bmabsout/neural-swarm | src/Simulator.hs | bsd-3-clause | 967 | 0 | 9 | 187 | 375 | 192 | 183 | -1 | -1 |
{- chris
zipper.hs:24:5:
"zipper.hs" (line 26, column 12):
listDup([]) = {v | Set_emp v }
^
unexpected "]"
expecting "forall", binder, "(", "{", "[", type variable, module qualifier, type constructor or type constructor operator
-}
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import Prelude hiding (reverse, (++))
import Data.Set
data Stack a = Stack { focus :: !a -- focused thing in this set
, up :: [a] -- jokers to the left
, down :: [a] } -- jokers to the right
deriving (Show, Eq)
-- LIQUID deriving (Show, Read, Eq)
-------------------------------------------------------------------------------
----------------------------- Refinements on Lists ---------------------------
-------------------------------------------------------------------------------
-- measures
[lq|
measure listDup :: [a] -> (Set a)
listDup([]) = {v | Set_emp v }
listDup(x:xs) = {v | v = if (Set_mem x (listElts xs)) then (Set_cup (Set_sng x) (listDup xs)) else (listDup xs) }
|]
-- predicates
[lq| predicate EqElts X Y =
((listElts X) = (listElts Y)) |]
[lq| predicate SubElts X Y =
(Set_sub (listElts X) (listElts Y)) |]
[lq| predicate UnionElts X Y Z =
((listElts X) = (Set_cup (listElts Y) (listElts Z))) |]
[lq| predicate ListElt N LS =
(Set_mem N (listElts LS)) |]
[lq| predicate ListUnique LS =
(Set_emp (listDup LS)) |]
[lq| predicate ListDisjoint X Y =
(Set_emp (Set_cap (listElts X) (listElts Y))) |]
-- types
[lq| type UList a = {v:[a] | (ListUnique v)} |]
[lq| type UListDif a N = {v:[a] | ((not (ListElt N v)) && (ListUnique v))} |]
-------------------------------------------------------------------------------
----------------------------- Refinements on Stacks ---------------------------
-------------------------------------------------------------------------------
[lq|
data Stack a = Stack { focus :: a
, up :: UListDif a focus
, down :: UListDif a focus }
|]
[lq| type UStack a = {v:Stack a | (ListDisjoint (getUp v) (getDown v))}|]
[lq| measure getUp :: forall a. (Stack a) -> [a]
getUp (Stack focus up down) = up
|]
[lq| measure getDown :: forall a. (Stack a) -> [a]
getDown (Stack focus up down) = down
|]
-------------------------------------------------------------------------------
------------------------------ Functions on Stacks ----------------------------
-------------------------------------------------------------------------------
[lq| differentiate :: UList a -> Maybe (UStack a) |]
differentiate :: [a] -> Maybe (Stack a)
differentiate [] = Nothing
differentiate (x:xs) = Just $ Stack x [] xs
[lq| integrate :: UStack a -> UList a |]
integrate :: Stack a -> [a]
integrate (Stack x l r) = reverse l ++ x : r
[lq| integrate' :: Maybe (UStack a) -> UList a |]
integrate' :: Maybe (Stack a) -> [a]
integrate' = maybe [] integrate
[lq| focusUp :: UStack a -> UStack a |]
focusUp :: Stack a -> Stack a
focusUp (Stack t [] rs) = Stack x xs [] where (x:xs) = reverse (t:rs)
focusUp (Stack t (l:ls) rs) = Stack l ls (t:rs)
[lq| focusDown :: UStack a -> UStack a |]
focusDown :: Stack a -> Stack a
focusDown = reverseStack . focusUp . reverseStack
[lq| reverseStack :: UStack a -> UStack a |]
reverseStack :: Stack a -> Stack a
reverseStack (Stack t ls rs) = Stack t rs ls
[lq| swapUp :: UStack a -> UStack a |]
swapUp :: Stack a -> Stack a
swapUp (Stack t (l:ls) rs) = Stack t ls (l:rs)
swapUp (Stack t [] rs) = Stack t (reverse rs) []
[lq| filter :: (a -> Bool) -> UStack a -> Maybe (UStack a) |]
filter :: (a -> Bool) -> Stack a -> Maybe (Stack a)
filter p (Stack f ls rs) = case filterL p (f:rs) of
f':rs' -> Just $ Stack f' (filterL p ls) rs' -- maybe move focus down
[] -> case filterL p ls of -- filter back up
f':ls' -> Just $ Stack f' ls' [] -- else up
[] -> Nothing
-------------------------------------------------------------------------------
------------------------------- Functions on Lists ----------------------------
-------------------------------------------------------------------------------
infixr 5 ++
[lq| Zipper.++ :: xs:(UList a)
-> ys:{v: UList a | (ListDisjoint v xs)}
-> {v: UList a | (UnionElts v xs ys)}
|]
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x: (xs ++ ys)
[lq| reverse :: xs:(UList a)
-> {v: UList a | (EqElts v xs)}
|]
reverse :: [a] -> [a]
reverse = rev []
[lq| rev :: ack:(UList a)
-> xs:{v: UList a | (ListDisjoint ack v)}
-> {v:UList a |(UnionElts v xs ack)}
|]
[lq| Decrease rev 2 |]
rev :: [a] -> [a] -> [a]
rev a [] = a
rev a (x:xs) = rev (x:a) xs
[lq| filterL :: (a -> Bool) -> xs:(UList a) -> {v:UList a | (SubElts v xs)} |]
filterL :: (a -> Bool) -> [a] -> [a]
filterL p [] = []
filterL p (x:xs) | p x = x : filterL p xs
| otherwise = filterL p xs
-- QUALIFIERS
[lq| q :: x:a -> {v:[a] |(not (Set_mem x (listElts v)))} |]
q :: a -> [a]
q = undefined
| spinda/liquidhaskell | tests/gsoc15/unknown/pos/zipper.hs | bsd-3-clause | 5,175 | 5 | 11 | 1,243 | 1,092 | 612 | 480 | 75 | 3 |
-- |
-- Module : Data.Memory.Internal.Imports
-- License : BSD-style
-- Maintainer : Vincent Hanquez <[email protected]>
-- Stability : experimental
-- Portability : unknown
--
{-# LANGUAGE CPP #-}
module Data.Memory.Internal.Imports
( module X
) where
import Data.Word as X
import Control.Applicative as X
import Control.Monad as X (forM, forM_, void)
import Control.Arrow as X (first, second)
import Data.Memory.Internal.DeepSeq as X
| NicolasDP/hs-memory | Data/Memory/Internal/Imports.hs | bsd-3-clause | 515 | 0 | 5 | 140 | 78 | 57 | 21 | 8 | 0 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Geometry.BoundingBox
-- Copyright : (c) 2011-2017 diagrams team (see LICENSE)
-- License : BSD-style (see LICENSE)
-- Maintainer : [email protected]
--
-- Bounding boxes are not very compositional (/e.g./ it is not
-- possible to do anything sensible with them under rotation), so they
-- are not a good choice for a fundamental simplified representation
-- of an object's geometry. However, they do have their uses; this
-- module provides definitions and functions for working with them.
-- In particular it is very fast to query whether a given point is
-- contained in a bounding box (/e.g./ using the
-- 'Geometry.Query.inquire' function).
--
-----------------------------------------------------------------------------
module Geometry.BoundingBox
( -- * Bounding boxes
BoundingBox (..)
-- * Constructing bounding boxes
, emptyBox, fromCorners, fromPoint, fromPoints
-- * Queries on bounding boxes
, isEmptyBox
, getCorners, getAllCorners
, boxExtents, boxCenter
, boxTransform
, boxContains, boxContains'
, insideBox, insideBox', outsideBox, outsideBox'
-- * Operations on bounding boxes
, boxUnion, boxIntersection
) where
import Control.Applicative
import Control.Lens
import Data.Coerce
import Data.Foldable as F
import Data.Functor.Classes
import Data.Maybe (fromMaybe)
import Data.Semigroup
import qualified Data.Sequence as Seq
import Text.Read
import Data.Traversable as T
import Linear.Affine
import Linear.Vector
import Geometry.Query
import Geometry.Space
import Geometry.Trace
import Geometry.Transform
-- | A bounding box is an axis-aligned region determined by two points
-- indicating its \"lower\" and \"upper\" corners. It can also
-- represent an empty bounding box.
--
-- The 'Semigroup' and 'Monoid' instances of 'BoundingBox' can be
-- used to take the union of bounding boxes, with the empty bounding
-- box as the identity.
data BoundingBox v n
= EmptyBox
| BoundingBox !(Point v n) !(Point v n)
-- Invariant: the first point is coordinatewise <= the second point.
type instance V (BoundingBox v n) = v
type instance N (BoundingBox v n) = n
instance (Eq1 v, Eq n) => Eq (BoundingBox v n) where
EmptyBox == EmptyBox = True
BoundingBox a1 b1 == BoundingBox a2 b2 = eq1 a1 a2 && eq1 b1 b2
_ == _ = False
{-# INLINE (==) #-}
-- | The combination of two bounding boxes is the smallest bounding
-- box that contains both.
instance (Additive v, Ord n) => Semigroup (BoundingBox v n) where
EmptyBox <> bb2 = bb2
bb1 <> EmptyBox = bb1
BoundingBox a1 b1 <> BoundingBox a2 b2 = BoundingBox (liftU2 min a1 a2) (liftU2 max b1 b2)
{-# INLINE (<>) #-}
stimes = stimesIdempotentMonoid
instance (Additive v, Ord n) => Monoid (BoundingBox v n) where
mappend = (<>)
{-# INLINE mappend #-}
mempty = EmptyBox
{-# INLINE mempty #-}
instance AsEmpty (BoundingBox v n) where
_Empty = nearly emptyBox isEmptyBox
{-# INLINE _Empty #-}
-- A traversal over the two defining corners (pointwise min and max)
-- of a bounding box. This is an unexported internal utility; it
-- should *not* be exported because it would allow making arbitrary
-- modifications to the box's corners, which could invalidate the
-- invariant that the first corner is coordinatewise <= the second.
boxPoints :: Traversal' (BoundingBox v n) (Point v n)
boxPoints f (BoundingBox a b) = BoundingBox <$> f a <*> f b
boxPoints _ eb = pure eb
{-# INLINE boxPoints #-}
instance (Additive v, Num n) => HasOrigin (BoundingBox v n) where
moveOriginTo p = boxPoints %~ moveOriginTo p
{-# INLINE moveOriginTo #-}
instance (Additive v, Foldable v, Ord n) => HasQuery (BoundingBox v n) Any where
getQuery = coerce (boxContains :: BoundingBox v n -> Point v n -> Bool)
{-# INLINE getQuery #-}
-- | Possible time values for intersecting a bounding box. Either we
-- intersect for all values of t, two specific values of t or no
-- values of t.
data Intersect a
= AllT -- all values may lead to infinite number of intersections
| MaxTwo -- all values of t lead two intersections
| Range !a !a -- intersection for a range of t values
| Two !a !a -- two t values for intersections
| None -- no t values lead to intersections
instance Ord a => Semigroup (Intersect a) where
None <> _ = None
_ <> None = None
AllT <> a = allT a
a <> AllT = allT a
MaxTwo <> a = a
a <> MaxTwo = a
Two a1 b1 <> Two a2 b2 = check Two (max a1 a2) (min b1 b2)
Range a1 b1 <> Range a2 b2 = check Range (max a1 a2) (min b1 b2)
Range a1 b1 <> Two a2 b2 = if a1 < a2 && b1 > b2 then Two a2 b2 else None
Two a1 b1 <> Range a2 b2 = if a2 < a1 && b2 > b1 then Two a1 b1 else None
{-# INLINE (<>) #-}
check :: Ord a => (a -> a -> Intersect a) -> a -> a -> Intersect a
check f a b = if a <= b then f a b else None
{-# INLINE check #-}
allT :: Intersect a -> Intersect a
allT (Two a b) = Range a b
allT MaxTwo = MaxTwo
allT a = a
{-# INLINE allT #-}
instance Ord a => Monoid (Intersect a) where
mappend = (<>)
{-# INLINE mappend #-}
mempty = MaxTwo
{-# INLINE mempty #-}
bbIntersection
:: (Additive v, Foldable v, Fractional n, Ord n)
=> BoundingBox v n -> Point v n -> v n -> Intersect n
bbIntersection EmptyBox _ _ = None
bbIntersection (BoundingBox l u) p v = foldr (<>) AllT (liftI4 l u p v)
where
-- The near coordinate is the first intersection from coming from
-- -Infinity *^ v. The far intersection is the first intersection
-- coming from +Infinity *^ v. The the direcion is negative, the
-- means the near and far coordinates are flipped.
-- We return the time where the near and far intersections occur.
--
-- a - lower point of bounding box
-- b - upper point of bounding box
-- s - trace starting point
-- d - direction of trace
f a b s d
| d == 0 = if s >= a && s <= b then AllT else None
| otherwise = two ((a-s)/d) ((b-s)/d)
-- utilities
liftI4 (P a) (P b) (P c) = liftI2 id (liftI2 id (liftI2 f a b) c)
{-# INLINE liftI4 #-}
two :: Ord a => a -> a -> Intersect a
two a b = if a < b then Two a b else Two b a
{-# INLINE two #-}
instance (HasLinearMap v, Fractional n, Ord n) => Traced (BoundingBox v n) where
getTrace bb = mkTrace $ \p v ->
case bbIntersection bb p v of
Range a b -> Seq.fromList [a,b]
Two a b -> Seq.fromList [a,b]
_ -> mempty
instance (Show1 v, Show n) => Show (BoundingBox v n) where
showsPrec d b = case b of
BoundingBox l u -> showParen (d > 10) $
showString "fromCorners " . showsPrec1 11 l . showChar ' ' . showsPrec1 11 u
EmptyBox -> showString "emptyBox"
instance (Read1 v, Read n) => Read (BoundingBox v n) where
readPrec = parens $
(do
Ident "emptyBox" <- lexP
pure emptyBox
) <|>
(prec 10 $ do
Ident "fromCorners" <- lexP
l <- step (readS_to_Prec readsPrec1)
h <- step (readS_to_Prec readsPrec1)
pure $ BoundingBox l h
)
-- instance Hashable (v n) => Hashable (BoundingBox v n) where
-- hashWithSalt s EmptyBox = s `hashWithSalt` 0
-- hashWithSalt s (BoundingBox l u) = s `hashWithSalt` l `hashWithSalt` u
-- | An empty bounding box. This is the same thing as @mempty@, but it doesn't
-- require the same type constraints that the @Monoid@ instance does.
-- This is a specialised version of 'Empty'.
emptyBox :: BoundingBox v n
emptyBox = EmptyBox
{-# INLINE emptyBox #-}
-- | Create a bounding box from a point that is component-wise @(<=)@ than the
-- other. If this is not the case, then @mempty@ is returned.
fromCorners
:: (Additive v, Foldable v, Ord n)
=> Point v n -> Point v n -> BoundingBox v n
fromCorners l h
| F.and (liftI2 (<=) l h) = BoundingBox l h
| otherwise = EmptyBox
{-# INLINE fromCorners #-}
-- | Create a degenerate bounding \"box\" containing only a single
-- point. This is a specialised version of
-- 'Geometry.Envelope.boundingBox'.
fromPoint :: Point v n -> BoundingBox v n
fromPoint p = BoundingBox p p
{-# INLINE fromPoint #-}
-- | Create the smallest bounding box containing all the given points.
-- This is a specialised version of 'Geometry.Envelope.boundingBox'.
fromPoints :: (Additive v, Ord n) => [Point v n] -> BoundingBox v n
fromPoints = mconcat . map fromPoint
{-# INLINE fromPoints #-}
-- | Test whether the BoundingBox is empty.
isEmptyBox :: BoundingBox v n -> Bool
isEmptyBox = \case EmptyBox -> True; _ -> False
{-# INLINE isEmptyBox #-}
-- | Get the lower and upper corners that define the bounding box.
getCorners :: BoundingBox v n -> Maybe (Point v n, Point v n)
getCorners (BoundingBox l u) = Just (l, u)
getCorners _ = Nothing
{-# INLINE getCorners #-}
-- | List all of the corners of the bounding box.
getAllCorners :: (Additive v, Traversable v) => BoundingBox v n -> [Point v n]
getAllCorners EmptyBox = []
getAllCorners (BoundingBox l u) = T.sequence (liftI2 (\a b -> [a,b]) l u)
{-# INLINE getAllCorners #-}
-- | Get the size of the bounding box, that is, the vector from the (component-wise)
-- smallest corner to the greatest corner. An empty bounding box has 'zero'
-- extent.
boxExtents :: (Additive v, Num n) => BoundingBox v n -> v n
boxExtents (BoundingBox l u) = u .-. l
boxExtents _ = zero
-- | Get the center point in a bounding box.
boxCenter :: (Additive v, Fractional n) => BoundingBox v n -> Maybe (Point v n)
boxCenter = fmap (uncurry (lerp 0.5)) . getCorners
{-# INLINE boxCenter #-}
-- | Create a transformation mapping points from the first bounding box to the
-- second. Returns 'Nothing' if either of the boxes are empty.
boxTransform
:: (HasLinearMap v, Fractional n)
=> BoundingBox v n -> BoundingBox v n -> Maybe (Transformation v n)
boxTransform u v = do
(P ul, _) <- getCorners u
(P vl, _) <- getCorners v
let vec = liftU2 (/) (boxExtents v) (boxExtents u)
T m m_ _ = scalingV vec
return $ T m m_ (vl ^-^ liftU2 (*) vec ul)
-- | Check whether a point is contained in a bounding box (inclusive
-- of its boundary). This is a specialised version of 'inquire'.
boxContains :: (Additive v, Foldable v, Ord n) => BoundingBox v n -> Point v n -> Bool
boxContains b p = maybe False test $ getCorners b
where
test (l, h) = F.and (liftI2 (<=) l p)
&& F.and (liftI2 (<=) p h)
-- | Check whether a point is /strictly/ contained in a bounding box,
-- /i.e./ excluding the boundary.
boxContains' :: (Additive v, Foldable v, Ord n) => BoundingBox v n -> Point v n -> Bool
boxContains' b p = maybe False test $ getCorners b
where
test (l, h) = F.and (liftI2 (<) l p)
&& F.and (liftI2 (<) p h)
-- | Test whether the first bounding box is contained inside
-- the second.
insideBox :: (Additive v, Foldable v, Ord n) => BoundingBox v n -> BoundingBox v n -> Bool
insideBox u v = fromMaybe False $ do
(ul, uh) <- getCorners u
(vl, vh) <- getCorners v
return $ F.and (liftI2 (>=) ul vl)
&& F.and (liftI2 (<=) uh vh)
-- | Test whether the first bounding box is /strictly/ contained
-- inside the second.
insideBox' :: (Additive v, Foldable v, Ord n) => BoundingBox v n -> BoundingBox v n -> Bool
insideBox' u v = fromMaybe False $ do
(ul, uh) <- getCorners u
(vl, vh) <- getCorners v
return $ F.and (liftI2 (>) ul vl)
&& F.and (liftI2 (<) uh vh)
-- | Test whether the first bounding box lies outside the second
-- (although they may intersect in their boundaries).
outsideBox :: (Additive v, Foldable v, Ord n) => BoundingBox v n -> BoundingBox v n -> Bool
outsideBox u v = fromMaybe True $ do
(ul, uh) <- getCorners u
(vl, vh) <- getCorners v
return $ F.or (liftI2 (<=) uh vl)
|| F.or (liftI2 (>=) ul vh)
-- | Test whether the first bounding box lies /strictly/ outside the second
-- (they do not intersect at all).
outsideBox' :: (Additive v, Foldable v, Ord n) => BoundingBox v n -> BoundingBox v n -> Bool
outsideBox' u v = fromMaybe True $ do
(ul, uh) <- getCorners u
(vl, vh) <- getCorners v
return $ F.or (liftI2 (<) uh vl)
|| F.or (liftI2 (>) ul vh)
-- | Form the largest bounding box contained within the given two
-- bounding boxes, or @Nothing@ if the two bounding boxes do not
-- overlap at all.
boxIntersection
:: (Additive v, Foldable v, Ord n)
=> BoundingBox v n -> BoundingBox v n -> BoundingBox v n
boxIntersection u v = maybe mempty (uncurry fromCorners) $ do
(ul, uh) <- getCorners u
(vl, vh) <- getCorners v
return (liftI2 max ul vl, liftI2 min uh vh)
-- | Form the smallest bounding box containing the given two bounding
-- boxes. This is a specialised version of 'mappend'.
boxUnion :: (Additive v, Ord n) => BoundingBox v n -> BoundingBox v n -> BoundingBox v n
boxUnion = mappend
| cchalmers/geometry | src/Geometry/BoundingBox.hs | bsd-3-clause | 13,738 | 0 | 15 | 3,444 | 3,585 | 1,862 | 1,723 | 232 | 3 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
-}
{-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
-- in module PlaceHolder
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE DeriveFunctor #-}
-- | Abstract Haskell syntax for expressions.
module HsExpr where
#include "HsVersions.h"
-- friends:
import HsDecls
import HsPat
import HsLit
import PlaceHolder ( PostTc,PostRn,DataId,DataIdPost,
NameOrRdrName,OutputableBndrId )
import HsTypes
import HsBinds
-- others:
import TcEvidence
import CoreSyn
import Var
import DynFlags ( gopt, GeneralFlag(Opt_PrintExplicitCoercions) )
import Name
import NameSet
import RdrName ( GlobalRdrEnv )
import BasicTypes
import ConLike
import SrcLoc
import Util
import StaticFlags( opt_PprStyle_Debug )
import Outputable
import FastString
import Type
-- libraries:
import Data.Data hiding (Fixity(..))
import qualified Data.Data as Data (Fixity(..))
import Data.Maybe (isNothing)
#ifdef GHCI
import GHCi.RemoteTypes ( ForeignRef )
import qualified Language.Haskell.TH as TH (Q)
#endif
{-
************************************************************************
* *
\subsection{Expressions proper}
* *
************************************************************************
-}
-- * Expressions proper
-- | Located Haskell Expression
type LHsExpr id = Located (HsExpr id)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
-- in a list
-- For details on above see note [Api annotations] in ApiAnnotation
-------------------------
-- | Post-Type checking Expression
--
-- PostTcExpr is an evidence expression attached to the syntax tree by the
-- type checker (c.f. postTcType).
type PostTcExpr = HsExpr Id
-- | Post-Type checking Table
--
-- We use a PostTcTable where there are a bunch of pieces of evidence, more
-- than is convenient to keep individually.
type PostTcTable = [(Name, PostTcExpr)]
noPostTcExpr :: PostTcExpr
noPostTcExpr = HsLit (HsString "" (fsLit "noPostTcExpr"))
noPostTcTable :: PostTcTable
noPostTcTable = []
-------------------------
-- | Syntax Expression
--
-- SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier,
-- by the renamer. It's used for rebindable syntax.
--
-- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for
-- @(>>=)@, and then instantiated by the type checker with its type args
-- etc
--
-- This should desugar to
--
-- > syn_res_wrap $ syn_expr (syn_arg_wraps[0] arg0)
-- > (syn_arg_wraps[1] arg1) ...
--
-- where the actual arguments come from elsewhere in the AST.
-- This could be defined using @PostRn@ and @PostTc@ and such, but it's
-- harder to get it all to work out that way. ('noSyntaxExpr' is hard to
-- write, for example.)
data SyntaxExpr id = SyntaxExpr { syn_expr :: HsExpr id
, syn_arg_wraps :: [HsWrapper]
, syn_res_wrap :: HsWrapper }
deriving instance (DataId id) => Data (SyntaxExpr id)
-- | This is used for rebindable-syntax pieces that are too polymorphic
-- for tcSyntaxOp (trS_fmap and the mzip in ParStmt)
noExpr :: HsExpr id
noExpr = HsLit (HsString "" (fsLit "noExpr"))
noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after,
-- (if the syntax slot makes no sense)
noSyntaxExpr = SyntaxExpr { syn_expr = HsLit (HsString "" (fsLit "noSyntaxExpr"))
, syn_arg_wraps = []
, syn_res_wrap = WpHole }
-- | Make a 'SyntaxExpr Name' (the "rn" is because this is used in the
-- renamer), missing its HsWrappers.
mkRnSyntaxExpr :: Name -> SyntaxExpr Name
mkRnSyntaxExpr name = SyntaxExpr { syn_expr = HsVar $ noLoc name
, syn_arg_wraps = []
, syn_res_wrap = WpHole }
-- don't care about filling in syn_arg_wraps because we're clearly
-- not past the typechecker
instance (OutputableBndrId id) => Outputable (SyntaxExpr id) where
ppr (SyntaxExpr { syn_expr = expr
, syn_arg_wraps = arg_wraps
, syn_res_wrap = res_wrap })
= sdocWithDynFlags $ \ dflags ->
getPprStyle $ \s ->
if debugStyle s || gopt Opt_PrintExplicitCoercions dflags
then ppr expr <> braces (pprWithCommas ppr arg_wraps)
<> braces (ppr res_wrap)
else ppr expr
-- | Command Syntax Table (for Arrow syntax)
type CmdSyntaxTable id = [(Name, HsExpr id)]
-- See Note [CmdSyntaxTable]
{-
Note [CmdSyntaxtable]
~~~~~~~~~~~~~~~~~~~~~
Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps
track of the methods needed for a Cmd.
* Before the renamer, this list is an empty list
* After the renamer, it takes the form @[(std_name, HsVar actual_name)]@
For example, for the 'arr' method
* normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr)
* with rebindable syntax: (GHC.Control.Arrow.arr, arr_22)
where @arr_22@ is whatever 'arr' is in scope
* After the type checker, it takes the form [(std_name, <expression>)]
where <expression> is the evidence for the method. This evidence is
instantiated with the class, but is still polymorphic in everything
else. For example, in the case of 'arr', the evidence has type
forall b c. (b->c) -> a b c
where 'a' is the ambient type of the arrow. This polymorphism is
important because the desugarer uses the same evidence at multiple
different types.
This is Less Cool than what we normally do for rebindable syntax, which is to
make fully-instantiated piece of evidence at every use site. The Cmd way
is Less Cool because
* The renamer has to predict which methods are needed.
See the tedious RnExpr.methodNamesCmd.
* The desugarer has to know the polymorphic type of the instantiated
method. This is checked by Inst.tcSyntaxName, but is less flexible
than the rest of rebindable syntax, where the type is less
pre-ordained. (And this flexibility is useful; for example we can
typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.)
-}
-- | An unbound variable; used for treating out-of-scope variables as
-- expression holes
data UnboundVar
= OutOfScope OccName GlobalRdrEnv -- ^ An (unqualified) out-of-scope
-- variable, together with the GlobalRdrEnv
-- with respect to which it is unbound
-- See Note [OutOfScope and GlobalRdrEnv]
| TrueExprHole OccName -- ^ A "true" expression hole (_ or _x)
deriving Data
instance Outputable UnboundVar where
ppr = ppr . unboundVarOcc
unboundVarOcc :: UnboundVar -> OccName
unboundVarOcc (OutOfScope occ _) = occ
unboundVarOcc (TrueExprHole occ) = occ
{-
Note [OutOfScope and GlobalRdrEnv]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To understand why we bundle a GlobalRdrEnv with an out-of-scope variable,
consider the following module:
module A where
foo :: ()
foo = bar
bat :: [Double]
bat = [1.2, 3.4]
$(return [])
bar = ()
bad = False
When A is compiled, the renamer determines that `bar` is not in scope in the
declaration of `foo` (since `bar` is declared in the following inter-splice
group). Once it has finished typechecking the entire module, the typechecker
then generates the associated error message, which specifies both the type of
`bar` and a list of possible in-scope alternatives:
A.hs:6:7: error:
• Variable not in scope: bar :: ()
• ‘bar’ (line 13) is not in scope before the splice on line 11
Perhaps you meant ‘bat’ (line 9)
When it calls RnEnv.unknownNameSuggestions to identify these alternatives, the
typechecker must provide a GlobalRdrEnv. If it provided the current one, which
contains top-level declarations for the entire module, the error message would
incorrectly suggest the out-of-scope `bar` and `bad` as possible alternatives
for `bar` (see Trac #11680). Instead, the typechecker must use the same
GlobalRdrEnv the renamer used when it determined that `bar` is out-of-scope.
To obtain this GlobalRdrEnv, can the typechecker simply use the out-of-scope
`bar`'s location to either reconstruct it (from the current GlobalRdrEnv) or to
look it up in some global store? Unfortunately, no. The problem is that
location information is not always sufficient for this task. This is most
apparent when dealing with the TH function addTopDecls, which adds its
declarations to the FOLLOWING inter-splice group. Consider these declarations:
ex9 = cat -- cat is NOT in scope here
$(do -------------------------------------------------------------
ds <- [d| f = cab -- cat and cap are both in scope here
cat = ()
|]
addTopDecls ds
[d| g = cab -- only cap is in scope here
cap = True
|])
ex10 = cat -- cat is NOT in scope here
$(return []) -----------------------------------------------------
ex11 = cat -- cat is in scope
Here, both occurrences of `cab` are out-of-scope, and so the typechecker needs
the GlobalRdrEnvs which were used when they were renamed. These GlobalRdrEnvs
are different (`cat` is present only in the GlobalRdrEnv for f's `cab'), but the
locations of the two `cab`s are the same (they are both created in the same
splice). Thus, we must include some additional information with each `cab` to
allow the typechecker to obtain the correct GlobalRdrEnv. Clearly, the simplest
information to use is the GlobalRdrEnv itself.
-}
-- | A Haskell expression.
data HsExpr id
= HsVar (Located id) -- ^ Variable
-- See Note [Located RdrNames]
| HsUnboundVar UnboundVar -- ^ Unbound variable; also used for "holes"
-- (_ or _x).
-- Turned from HsVar to HsUnboundVar by the
-- renamer, when it finds an out-of-scope
-- variable or hole.
-- Turned into HsVar by type checker, to support
-- deferred type errors.
| HsRecFld (AmbiguousFieldOcc id) -- ^ Variable pointing to record selector
| HsOverLabel FastString -- ^ Overloaded label (See Note [Overloaded labels]
-- in GHC.OverloadedLabels)
| HsIPVar HsIPName -- ^ Implicit parameter
| HsOverLit (HsOverLit id) -- ^ Overloaded literals
| HsLit HsLit -- ^ Simple (non-overloaded) literals
| HsLam (MatchGroup id (LHsExpr id)) -- ^ Lambda abstraction. Currently always a single match
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
-- 'ApiAnnotation.AnnRarrow',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsLamCase (MatchGroup id (LHsExpr id)) -- ^ Lambda-case
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
-- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsApp (LHsExpr id) (LHsExpr id) -- ^ Application
| HsAppType (LHsExpr id) (LHsWcType id) -- ^ Visible type application
--
-- Explicit type argument; e.g f @Int x y
-- NB: Has wildcards, but no implicit quantification
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt',
| HsAppTypeOut (LHsExpr id) (LHsWcType Name) -- just for pretty-printing
-- | Operator applications:
-- NB Bracketed ops such as (+) come out as Vars.
-- NB We need an expr for the operator in an OpApp/Section since
-- the typechecker may need to apply the operator to a few types.
| OpApp (LHsExpr id) -- left operand
(LHsExpr id) -- operator
(PostRn id Fixity) -- Renamer adds fixity; bottom until then
(LHsExpr id) -- right operand
-- | Negation operator. Contains the negated expression and the name
-- of 'negate'
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus'
-- For details on above see note [Api annotations] in ApiAnnotation
| NegApp (LHsExpr id)
(SyntaxExpr id)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
-- 'ApiAnnotation.AnnClose' @')'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsPar (LHsExpr id) -- ^ Parenthesised expr; see Note [Parens in HsSyn]
| SectionL (LHsExpr id) -- operand; see Note [Sections in HsSyn]
(LHsExpr id) -- operator
| SectionR (LHsExpr id) -- operator; see Note [Sections in HsSyn]
(LHsExpr id) -- operand
-- | Used for explicit tuples and sections thereof
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| ExplicitTuple
[LHsTupArg id]
Boxity
| ExplicitSum
ConTag -- Alternative (one-based)
Arity -- Sum arity
(LHsExpr id)
(PostTc id [Type]) -- the type arguments
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
-- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCase (LHsExpr id)
(MatchGroup id (LHsExpr id))
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
-- 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnElse',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsIf (Maybe (SyntaxExpr id)) -- cond function
-- Nothing => use the built-in 'if'
-- See Note [Rebindable if]
(LHsExpr id) -- predicate
(LHsExpr id) -- then part
(LHsExpr id) -- else part
-- | Multi-way if
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf'
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsMultiIf (PostTc id Type) [LGRHS id (LHsExpr id)]
-- | let(rec)
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
-- 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsLet (Located (HsLocalBinds id))
(LHsExpr id)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
-- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsDo (HsStmtContext Name) -- The parameterisation is unimportant
-- because in this context we never use
-- the PatGuard or ParStmt variant
(Located [ExprLStmt id]) -- "do":one or more stmts
(PostTc id Type) -- Type of the whole expression
-- | Syntactic list: [a,b,c,...]
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
-- 'ApiAnnotation.AnnClose' @']'@
-- For details on above see note [Api annotations] in ApiAnnotation
| ExplicitList
(PostTc id Type) -- Gives type of components of list
(Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromListN witness
[LHsExpr id]
-- | Syntactic parallel array: [:e1, ..., en:]
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
-- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma',
-- 'ApiAnnotation.AnnVbar'
-- 'ApiAnnotation.AnnClose' @':]'@
-- For details on above see note [Api annotations] in ApiAnnotation
| ExplicitPArr
(PostTc id Type) -- type of elements of the parallel array
[LHsExpr id]
-- | Record construction
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| RecordCon
{ rcon_con_name :: Located id -- The constructor name;
-- not used after type checking
, rcon_con_like :: PostTc id ConLike -- The data constructor or pattern synonym
, rcon_con_expr :: PostTcExpr -- Instantiated constructor function
, rcon_flds :: HsRecordBinds id } -- The fields
-- | Record update
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| RecordUpd
{ rupd_expr :: LHsExpr id
, rupd_flds :: [LHsRecUpdField id]
, rupd_cons :: PostTc id [ConLike]
-- Filled in by the type checker to the
-- _non-empty_ list of DataCons that have
-- all the upd'd fields
, rupd_in_tys :: PostTc id [Type] -- Argument types of *input* record type
, rupd_out_tys :: PostTc id [Type] -- and *output* record type
-- The original type can be reconstructed
-- with conLikeResTy
, rupd_wrap :: PostTc id HsWrapper -- See note [Record Update HsWrapper]
}
-- For a type family, the arg types are of the *instance* tycon,
-- not the family tycon
-- | Expression with an explicit type signature. @e :: type@
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
-- For details on above see note [Api annotations] in ApiAnnotation
| ExprWithTySig
(LHsExpr id)
(LHsSigWcType id)
| ExprWithTySigOut -- Post typechecking
(LHsExpr id)
(LHsSigWcType Name) -- Retain the signature,
-- as HsSigType Name, for
-- round-tripping purposes
-- | Arithmetic sequence
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
-- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
-- 'ApiAnnotation.AnnClose' @']'@
-- For details on above see note [Api annotations] in ApiAnnotation
| ArithSeq
PostTcExpr
(Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromList witness
(ArithSeqInfo id)
-- | Arithmetic sequence for parallel array
--
-- > [:e1..e2:] or [:e1, e2..e3:]
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
-- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot',
-- 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnClose' @':]'@
-- For details on above see note [Api annotations] in ApiAnnotation
| PArrSeq
PostTcExpr
(ArithSeqInfo id)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@,
-- 'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr',
-- 'ApiAnnotation.AnnClose' @'\#-}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsSCC SourceText -- Note [Pragma source text] in BasicTypes
StringLiteral -- "set cost centre" SCC pragma
(LHsExpr id) -- expr whose cost is to be measured
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@,
-- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCoreAnn SourceText -- Note [Pragma source text] in BasicTypes
StringLiteral -- hdaume: core annotation
(LHsExpr id)
-----------------------------------------------------------
-- MetaHaskell Extensions
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsBracket (HsBracket id)
-- See Note [Pending Splices]
| HsRnBracketOut
(HsBracket Name) -- Output of the renamer is the *original* renamed
-- expression, plus
[PendingRnSplice] -- _renamed_ splices to be type checked
| HsTcBracketOut
(HsBracket Name) -- Output of the type checker is the *original*
-- renamed expression, plus
[PendingTcSplice] -- _typechecked_ splices to be
-- pasted back in by the desugarer
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsSpliceE (HsSplice id)
-----------------------------------------------------------
-- Arrow notation extension
-- | @proc@ notation for Arrows
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc',
-- 'ApiAnnotation.AnnRarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsProc (LPat id) -- arrow abstraction, proc
(LHsCmdTop id) -- body of the abstraction
-- always has an empty stack
---------------------------------------
-- static pointers extension
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsStatic (PostRn id NameSet) -- Free variables of the body
(LHsExpr id) -- Body
---------------------------------------
-- The following are commands, not expressions proper
-- They are only used in the parsing stage and are removed
-- immediately in parser.RdrHsSyn.checkCommand
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
-- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
-- 'ApiAnnotation.AnnRarrowtail'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsArrApp -- Arrow tail, or arrow application (f -< arg)
(LHsExpr id) -- arrow expression, f
(LHsExpr id) -- input expression, arg
(PostTc id Type) -- type of the arrow expressions f,
-- of the form a t t', where arg :: t
HsArrAppType -- higher-order (-<<) or first-order (-<)
Bool -- True => right-to-left (f -< arg)
-- False => left-to-right (arg >- f)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@,
-- 'ApiAnnotation.AnnClose' @'|)'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsArrForm -- Command formation, (| e cmd1 .. cmdn |)
(LHsExpr id) -- the operator
-- after type-checking, a type abstraction to be
-- applied to the type of the local environment tuple
(Maybe Fixity) -- fixity (filled in by the renamer), for forms that
-- were converted from OpApp's by the renamer
[LHsCmdTop id] -- argument commands
---------------------------------------
-- Haskell program coverage (Hpc) Support
| HsTick
(Tickish id)
(LHsExpr id) -- sub-expression
| HsBinTick
Int -- module-local tick number for True
Int -- module-local tick number for False
(LHsExpr id) -- sub-expression
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
-- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@,
-- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnMinus',
-- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon',
-- 'ApiAnnotation.AnnVal',
-- 'ApiAnnotation.AnnClose' @'\#-}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsTickPragma -- A pragma introduced tick
SourceText -- Note [Pragma source text] in BasicTypes
(StringLiteral,(Int,Int),(Int,Int))
-- external span for this tick
((SourceText,SourceText),(SourceText,SourceText))
-- Source text for the four integers used in the span.
-- See note [Pragma source text] in BasicTypes
(LHsExpr id)
---------------------------------------
-- These constructors only appear temporarily in the parser.
-- The renamer translates them into the Right Thing.
| EWildPat -- wildcard
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt'
-- For details on above see note [Api annotations] in ApiAnnotation
| EAsPat (Located id) -- as pattern
(LHsExpr id)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| EViewPat (LHsExpr id) -- view pattern
(LHsExpr id)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
-- For details on above see note [Api annotations] in ApiAnnotation
| ELazyPat (LHsExpr id) -- ~ pattern
---------------------------------------
-- Finally, HsWrap appears only in typechecker output
| HsWrap HsWrapper -- TRANSLATION
(HsExpr id)
deriving instance (DataId id) => Data (HsExpr id)
-- | Located Haskell Tuple Argument
--
-- 'HsTupArg' is used for tuple sections
-- @(,a,)@ is represented by
-- @ExplicitTuple [Missing ty1, Present a, Missing ty3]@
-- Which in turn stands for @(\x:ty1 \y:ty2. (x,a,y))@
type LHsTupArg id = Located (HsTupArg id)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma'
-- For details on above see note [Api annotations] in ApiAnnotation
-- | Haskell Tuple Argument
data HsTupArg id
= Present (LHsExpr id) -- ^ The argument
| Missing (PostTc id Type) -- ^ The argument is missing, but this is its type
deriving instance (DataId id) => Data (HsTupArg id)
tupArgPresent :: LHsTupArg id -> Bool
tupArgPresent (L _ (Present {})) = True
tupArgPresent (L _ (Missing {})) = False
{-
Note [Parens in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~
HsPar (and ParPat in patterns, HsParTy in types) is used as follows
* Generally HsPar is optional; the pretty printer adds parens where
necessary. Eg (HsApp f (HsApp g x)) is fine, and prints 'f (g x)'
* HsPars are pretty printed as '( .. )' regardless of whether
or not they are strictly necssary
* HsPars are respected when rearranging operator fixities.
So a * (b + c) means what it says (where the parens are an HsPar)
Note [Sections in HsSyn]
~~~~~~~~~~~~~~~~~~~~~~~~
Sections should always appear wrapped in an HsPar, thus
HsPar (SectionR ...)
The parser parses sections in a wider variety of situations
(See Note [Parsing sections]), but the renamer checks for those
parens. This invariant makes pretty-printing easier; we don't need
a special case for adding the parens round sections.
Note [Rebindable if]
~~~~~~~~~~~~~~~~~~~~
The rebindable syntax for 'if' is a bit special, because when
rebindable syntax is *off* we do not want to treat
(if c then t else e)
as if it was an application (ifThenElse c t e). Why not?
Because we allow an 'if' to return *unboxed* results, thus
if blah then 3# else 4#
whereas that would not be possible using a all to a polymorphic function
(because you can't call a polymorphic function at an unboxed type).
So we use Nothing to mean "use the old built-in typing rule".
Note [Record Update HsWrapper]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There is a wrapper in RecordUpd which is used for the *required*
constraints for pattern synonyms. This wrapper is created in the
typechecking and is then directly used in the desugaring without
modification.
For example, if we have the record pattern synonym P,
pattern P :: (Show a) => a -> Maybe a
pattern P{x} = Just x
foo = (Just True) { x = False }
then `foo` desugars to something like
foo = case Just True of
P x -> P False
hence we need to provide the correct dictionaries to P's matcher on
the RHS so that we can build the expression.
Note [Located RdrNames]
~~~~~~~~~~~~~~~~~~~~~~~
A number of syntax elements have seemingly redundant locations attached to them.
This is deliberate, to allow transformations making use of the API Annotations
to easily correlate a Located Name in the RenamedSource with a Located RdrName
in the ParsedSource.
There are unfortunately enough differences between the ParsedSource and the
RenamedSource that the API Annotations cannot be used directly with
RenamedSource, so this allows a simple mapping to be used based on the location.
-}
instance (OutputableBndrId id) => Outputable (HsExpr id) where
ppr expr = pprExpr expr
-----------------------
-- pprExpr, pprLExpr, pprBinds call pprDeeper;
-- the underscore versions do not
pprLExpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
pprLExpr (L _ e) = pprExpr e
pprExpr :: (OutputableBndrId id) => HsExpr id -> SDoc
pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e
| otherwise = pprDeeper (ppr_expr e)
isQuietHsExpr :: HsExpr id -> Bool
-- Parentheses do display something, but it gives little info and
-- if we go deeper when we go inside them then we get ugly things
-- like (...)
isQuietHsExpr (HsPar _) = True
-- applications don't display anything themselves
isQuietHsExpr (HsApp _ _) = True
isQuietHsExpr (HsAppType _ _) = True
isQuietHsExpr (HsAppTypeOut _ _) = True
isQuietHsExpr (OpApp _ _ _ _) = True
isQuietHsExpr _ = False
pprBinds :: (OutputableBndrId idL, OutputableBndrId idR)
=> HsLocalBindsLR idL idR -> SDoc
pprBinds b = pprDeeper (ppr b)
-----------------------
ppr_lexpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
ppr_lexpr e = ppr_expr (unLoc e)
ppr_expr :: forall id. (OutputableBndrId id) => HsExpr id -> SDoc
ppr_expr (HsVar (L _ v)) = pprPrefixOcc v
ppr_expr (HsUnboundVar uv)= pprPrefixOcc (unboundVarOcc uv)
ppr_expr (HsIPVar v) = ppr v
ppr_expr (HsOverLabel l) = char '#' <> ppr l
ppr_expr (HsLit lit) = ppr lit
ppr_expr (HsOverLit lit) = ppr lit
ppr_expr (HsPar e) = parens (ppr_lexpr e)
ppr_expr (HsCoreAnn _ (StringLiteral _ s) e)
= vcat [text "HsCoreAnn" <+> ftext s, ppr_lexpr e]
ppr_expr e@(HsApp {}) = ppr_apps e []
ppr_expr e@(HsAppType {}) = ppr_apps e []
ppr_expr e@(HsAppTypeOut {}) = ppr_apps e []
ppr_expr (OpApp e1 op _ e2)
= case unLoc op of
HsVar (L _ v) -> pp_infixly v
HsRecFld f -> pp_infixly f
_ -> pp_prefixly
where
pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens
pp_e2 = pprDebugParendExpr e2 -- to make precedence clear
pp_prefixly
= hang (ppr op) 2 (sep [pp_e1, pp_e2])
pp_infixly v
= sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]]
ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e
ppr_expr (SectionL expr op)
= case unLoc op of
HsVar (L _ v) -> pp_infixly v
_ -> pp_prefixly
where
pp_expr = pprDebugParendExpr expr
pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op])
4 (hsep [pp_expr, text "x_ )"])
pp_infixly v = (sep [pp_expr, pprInfixOcc v])
ppr_expr (SectionR op expr)
= case unLoc op of
HsVar (L _ v) -> pp_infixly v
_ -> pp_prefixly
where
pp_expr = pprDebugParendExpr expr
pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"])
4 (pp_expr <> rparen)
pp_infixly v = sep [pprInfixOcc v, pp_expr]
ppr_expr (ExplicitTuple exprs boxity)
= tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs))
where
ppr_tup_args [] = []
ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es
ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es
punc (Present {} : _) = comma <> space
punc (Missing {} : _) = comma
punc [] = empty
ppr_expr (ExplicitSum alt arity expr _)
= text "(#" <+> ppr_bars (alt - 1) <+> ppr expr <+> ppr_bars (arity - alt) <+> text "#)"
where
ppr_bars n = hsep (replicate n (char '|'))
ppr_expr (HsLam matches)
= pprMatches matches
ppr_expr (HsLamCase matches)
= sep [ sep [text "\\case {"],
nest 2 (pprMatches matches <+> char '}') ]
ppr_expr (HsCase expr matches)
= sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
nest 2 (pprMatches matches <+> char '}') ]
ppr_expr (HsIf _ e1 e2 e3)
= sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")],
nest 4 (ppr e2),
text "else",
nest 4 (ppr e3)]
ppr_expr (HsMultiIf _ alts)
= sep $ text "if" : map ppr_alt alts
where ppr_alt (L _ (GRHS guards expr)) =
sep [ vbar <+> interpp'SP guards
, text "->" <+> pprDeeper (ppr expr) ]
-- special case: let ... in let ...
ppr_expr (HsLet (L _ binds) expr@(L _ (HsLet _ _)))
= sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
ppr_lexpr expr]
ppr_expr (HsLet (L _ binds) expr)
= sep [hang (text "let") 2 (pprBinds binds),
hang (text "in") 2 (ppr expr)]
ppr_expr (HsDo do_or_list_comp (L _ stmts) _) = pprDo do_or_list_comp stmts
ppr_expr (ExplicitList _ _ exprs)
= brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
ppr_expr (ExplicitPArr _ exprs)
= paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs)))
ppr_expr (RecordCon { rcon_con_name = con_id, rcon_flds = rbinds })
= hang (ppr con_id) 2 (ppr rbinds)
ppr_expr (RecordUpd { rupd_expr = L _ aexp, rupd_flds = rbinds })
= hang (pprParendExpr aexp) 2 (braces (fsep (punctuate comma (map ppr rbinds))))
ppr_expr (ExprWithTySig expr sig)
= hang (nest 2 (ppr_lexpr expr) <+> dcolon)
4 (ppr sig)
ppr_expr (ExprWithTySigOut expr sig)
= hang (nest 2 (ppr_lexpr expr) <+> dcolon)
4 (ppr sig)
ppr_expr (ArithSeq _ _ info) = brackets (ppr info)
ppr_expr (PArrSeq _ info) = paBrackets (ppr info)
ppr_expr EWildPat = char '_'
ppr_expr (ELazyPat e) = char '~' <> pprParendLExpr e
ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendLExpr e
ppr_expr (EViewPat p e) = ppr p <+> text "->" <+> ppr e
ppr_expr (HsSCC _ (StringLiteral _ lbl) expr)
= sep [ text "{-# SCC" <+> doubleQuotes (ftext lbl) <+> ptext (sLit "#-}"),
pprParendLExpr expr ]
ppr_expr (HsWrap co_fn e)
= pprHsWrapper co_fn (\parens -> if parens then pprParendExpr e
else pprExpr e)
ppr_expr (HsSpliceE s) = pprSplice s
ppr_expr (HsBracket b) = pprHsBracket b
ppr_expr (HsRnBracketOut e []) = ppr e
ppr_expr (HsRnBracketOut e ps) = ppr e $$ text "pending(rn)" <+> ppr ps
ppr_expr (HsTcBracketOut e []) = ppr e
ppr_expr (HsTcBracketOut e ps) = ppr e $$ text "pending(tc)" <+> ppr ps
ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _)))
= hsep [text "proc", ppr pat, ptext (sLit "->"), ppr cmd]
ppr_expr (HsStatic _ e)
= hsep [text "static", pprParendLExpr e]
ppr_expr (HsTick tickish exp)
= pprTicks (ppr exp) $
ppr tickish <+> ppr_lexpr exp
ppr_expr (HsBinTick tickIdTrue tickIdFalse exp)
= pprTicks (ppr exp) $
hcat [text "bintick<",
ppr tickIdTrue,
text ",",
ppr tickIdFalse,
text ">(",
ppr exp, text ")"]
ppr_expr (HsTickPragma _ externalSrcLoc _ exp)
= pprTicks (ppr exp) $
hcat [text "tickpragma<",
pprExternalSrcLoc externalSrcLoc,
text ">(",
ppr exp,
text ")"]
ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True)
= hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False)
= hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True)
= hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False)
= hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
ppr_expr (HsArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2])
= sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
ppr_expr (HsArrForm op _ args)
= hang (text "(|" <+> ppr_lexpr op)
4 (sep (map (pprCmdArg.unLoc) args) <+> text "|)")
ppr_expr (HsRecFld f) = ppr f
-- We must tiresomely make the "id" parameter to the LHsWcType existential
-- because it's different in the HsAppType case and the HsAppTypeOut case
-- | Located Haskell Wildcard Type Expression
data LHsWcTypeX = forall id. (OutputableBndrId id) => LHsWcTypeX (LHsWcType id)
ppr_apps :: (OutputableBndrId id)
=> HsExpr id
-> [Either (LHsExpr id) LHsWcTypeX]
-> SDoc
ppr_apps (HsApp (L _ fun) arg) args
= ppr_apps fun (Left arg : args)
ppr_apps (HsAppType (L _ fun) arg) args
= ppr_apps fun (Right (LHsWcTypeX arg) : args)
ppr_apps (HsAppTypeOut (L _ fun) arg) args
= ppr_apps fun (Right (LHsWcTypeX arg) : args)
ppr_apps fun args = hang (ppr_expr fun) 2 (sep (map pp args))
where
pp (Left arg) = pprParendLExpr arg
pp (Right (LHsWcTypeX (HsWC { hswc_body = L _ arg })))
= char '@' <> pprParendHsType arg
pprExternalSrcLoc :: (StringLiteral,(Int,Int),(Int,Int)) -> SDoc
pprExternalSrcLoc (StringLiteral _ src,(n1,n2),(n3,n4))
= ppr (src,(n1,n2),(n3,n4))
{-
HsSyn records exactly where the user put parens, with HsPar.
So generally speaking we print without adding any parens.
However, some code is internally generated, and in some places
parens are absolutely required; so for these places we use
pprParendLExpr (but don't print double parens of course).
For operator applications we don't add parens, because the operator
fixities should do the job, except in debug mode (-dppr-debug) so we
can see the structure of the parse tree.
-}
pprDebugParendExpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
pprDebugParendExpr expr
= getPprStyle (\sty ->
if debugStyle sty then pprParendLExpr expr
else pprLExpr expr)
pprParendLExpr :: (OutputableBndrId id) => LHsExpr id -> SDoc
pprParendLExpr (L _ e) = pprParendExpr e
pprParendExpr :: (OutputableBndrId id) => HsExpr id -> SDoc
pprParendExpr expr
| hsExprNeedsParens expr = parens (pprExpr expr)
| otherwise = pprExpr expr
-- Using pprLExpr makes sure that we go 'deeper'
-- I think that is usually (always?) right
hsExprNeedsParens :: HsExpr id -> Bool
-- True of expressions for which '(e)' and 'e'
-- mean the same thing
hsExprNeedsParens (ArithSeq {}) = False
hsExprNeedsParens (PArrSeq {}) = False
hsExprNeedsParens (HsLit {}) = False
hsExprNeedsParens (HsOverLit {}) = False
hsExprNeedsParens (HsVar {}) = False
hsExprNeedsParens (HsUnboundVar {}) = False
hsExprNeedsParens (HsIPVar {}) = False
hsExprNeedsParens (HsOverLabel {}) = False
hsExprNeedsParens (ExplicitTuple {}) = False
hsExprNeedsParens (ExplicitList {}) = False
hsExprNeedsParens (ExplicitPArr {}) = False
hsExprNeedsParens (HsPar {}) = False
hsExprNeedsParens (HsBracket {}) = False
hsExprNeedsParens (HsRnBracketOut {}) = False
hsExprNeedsParens (HsTcBracketOut {}) = False
hsExprNeedsParens (HsDo sc _ _)
| isListCompExpr sc = False
hsExprNeedsParens (HsRecFld{}) = False
hsExprNeedsParens _ = True
isAtomicHsExpr :: HsExpr id -> Bool
-- True of a single token
isAtomicHsExpr (HsVar {}) = True
isAtomicHsExpr (HsLit {}) = True
isAtomicHsExpr (HsOverLit {}) = True
isAtomicHsExpr (HsIPVar {}) = True
isAtomicHsExpr (HsOverLabel {}) = True
isAtomicHsExpr (HsUnboundVar {}) = True
isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e
isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e)
isAtomicHsExpr (HsRecFld{}) = True
isAtomicHsExpr _ = False
{-
************************************************************************
* *
\subsection{Commands (in arrow abstractions)}
* *
************************************************************************
We re-use HsExpr to represent these.
-}
-- | Located Haskell Command (for arrow syntax)
type LHsCmd id = Located (HsCmd id)
-- | Haskell Command (e.g. a "statement" in an Arrow proc block)
data HsCmd id
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail',
-- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail',
-- 'ApiAnnotation.AnnRarrowtail'
-- For details on above see note [Api annotations] in ApiAnnotation
= HsCmdArrApp -- Arrow tail, or arrow application (f -< arg)
(LHsExpr id) -- arrow expression, f
(LHsExpr id) -- input expression, arg
(PostTc id Type) -- type of the arrow expressions f,
-- of the form a t t', where arg :: t
HsArrAppType -- higher-order (-<<) or first-order (-<)
Bool -- True => right-to-left (f -< arg)
-- False => left-to-right (arg >- f)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@,
-- 'ApiAnnotation.AnnClose' @'|)'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |)
(LHsExpr id) -- the operator
-- after type-checking, a type abstraction to be
-- applied to the type of the local environment tuple
(Maybe Fixity) -- fixity (filled in by the renamer), for forms that
-- were converted from OpApp's by the renamer
[LHsCmdTop id] -- argument commands
| HsCmdApp (LHsCmd id)
(LHsExpr id)
| HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam',
-- 'ApiAnnotation.AnnRarrow',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdPar (LHsCmd id) -- parenthesised command
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
-- 'ApiAnnotation.AnnClose' @')'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdCase (LHsExpr id)
(MatchGroup id (LHsCmd id)) -- bodies are HsCmd's
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase',
-- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdIf (Maybe (SyntaxExpr id)) -- cond function
(LHsExpr id) -- predicate
(LHsCmd id) -- then part
(LHsCmd id) -- else part
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf',
-- 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnElse',
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdLet (Located (HsLocalBinds id)) -- let(rec)
(LHsCmd id)
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet',
-- 'ApiAnnotation.AnnOpen' @'{'@,
-- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdDo (Located [CmdLStmt id])
(PostTc id Type) -- Type of the whole expression
-- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo',
-- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi',
-- 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnClose'
-- For details on above see note [Api annotations] in ApiAnnotation
| HsCmdWrap HsWrapper
(HsCmd id) -- If cmd :: arg1 --> res
-- wrap :: arg1 "->" arg2
-- Then (HsCmdWrap wrap cmd) :: arg2 --> res
deriving instance (DataId id) => Data (HsCmd id)
-- | Haskell Array Application Type
data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp
deriving Data
{- | Top-level command, introducing a new arrow.
This may occur inside a proc (where the stack is empty) or as an
argument of a command-forming operator.
-}
-- | Located Haskell Top-level Command
type LHsCmdTop id = Located (HsCmdTop id)
-- | Haskell Top-level Command
data HsCmdTop id
= HsCmdTop (LHsCmd id)
(PostTc id Type) -- Nested tuple of inputs on the command's stack
(PostTc id Type) -- return type of the command
(CmdSyntaxTable id) -- See Note [CmdSyntaxTable]
deriving instance (DataId id) => Data (HsCmdTop id)
instance (OutputableBndrId id) => Outputable (HsCmd id) where
ppr cmd = pprCmd cmd
-----------------------
-- pprCmd and pprLCmd call pprDeeper;
-- the underscore versions do not
pprLCmd :: (OutputableBndrId id) => LHsCmd id -> SDoc
pprLCmd (L _ c) = pprCmd c
pprCmd :: (OutputableBndrId id) => HsCmd id -> SDoc
pprCmd c | isQuietHsCmd c = ppr_cmd c
| otherwise = pprDeeper (ppr_cmd c)
isQuietHsCmd :: HsCmd id -> Bool
-- Parentheses do display something, but it gives little info and
-- if we go deeper when we go inside them then we get ugly things
-- like (...)
isQuietHsCmd (HsCmdPar _) = True
-- applications don't display anything themselves
isQuietHsCmd (HsCmdApp _ _) = True
isQuietHsCmd _ = False
-----------------------
ppr_lcmd :: (OutputableBndrId id) => LHsCmd id -> SDoc
ppr_lcmd c = ppr_cmd (unLoc c)
ppr_cmd :: forall id. (OutputableBndrId id) => HsCmd id -> SDoc
ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c)
ppr_cmd (HsCmdApp c e)
= let (fun, args) = collect_args c [e] in
hang (ppr_lcmd fun) 2 (sep (map pprParendLExpr args))
where
collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args)
collect_args fun args = (fun, args)
ppr_cmd (HsCmdLam matches)
= pprMatches matches
ppr_cmd (HsCmdCase expr matches)
= sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")],
nest 2 (pprMatches matches <+> char '}') ]
ppr_cmd (HsCmdIf _ e ct ce)
= sep [hsep [text "if", nest 2 (ppr e), ptext (sLit "then")],
nest 4 (ppr ct),
text "else",
nest 4 (ppr ce)]
-- special case: let ... in let ...
ppr_cmd (HsCmdLet (L _ binds) cmd@(L _ (HsCmdLet _ _)))
= sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]),
ppr_lcmd cmd]
ppr_cmd (HsCmdLet (L _ binds) cmd)
= sep [hang (text "let") 2 (pprBinds binds),
hang (text "in") 2 (ppr cmd)]
ppr_cmd (HsCmdDo (L _ stmts) _) = pprDo ArrowExpr stmts
ppr_cmd (HsCmdWrap w cmd)
= pprHsWrapper w (\_ -> parens (ppr_cmd cmd))
ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True)
= hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg]
ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False)
= hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow]
ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True)
= hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg]
ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False)
= hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow]
ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2])
= sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]]
ppr_cmd (HsCmdArrForm op _ args)
= hang (text "(|" <> ppr_lexpr op)
4 (sep (map (pprCmdArg.unLoc) args) <> text "|)")
pprCmdArg :: (OutputableBndrId id) => HsCmdTop id -> SDoc
pprCmdArg (HsCmdTop cmd@(L _ (HsCmdArrForm _ Nothing [])) _ _ _)
= ppr_lcmd cmd
pprCmdArg (HsCmdTop cmd _ _ _)
= parens (ppr_lcmd cmd)
instance (OutputableBndrId id) => Outputable (HsCmdTop id) where
ppr = pprCmdArg
{-
************************************************************************
* *
\subsection{Record binds}
* *
************************************************************************
-}
-- | Haskell Record Bindings
type HsRecordBinds id = HsRecFields id (LHsExpr id)
{-
************************************************************************
* *
\subsection{@Match@, @GRHSs@, and @GRHS@ datatypes}
* *
************************************************************************
@Match@es are sets of pattern bindings and right hand sides for
functions, patterns or case branches. For example, if a function @g@
is defined as:
\begin{verbatim}
g (x,y) = y
g ((x:ys),y) = y+1,
\end{verbatim}
then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@.
It is always the case that each element of an @[Match]@ list has the
same number of @pats@s inside it. This corresponds to saying that
a function defined by pattern matching must have the same number of
patterns in each equation.
-}
data MatchGroup id body
= MG { mg_alts :: Located [LMatch id body] -- The alternatives
, mg_arg_tys :: [PostTc id Type] -- Types of the arguments, t1..tn
, mg_res_ty :: PostTc id Type -- Type of the result, tr
, mg_origin :: Origin }
-- The type is the type of the entire group
-- t1 -> ... -> tn -> tr
-- where there are n patterns
deriving instance (Data body,DataId id) => Data (MatchGroup id body)
-- | Located Match
type LMatch id body = Located (Match id body)
-- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a
-- list
-- For details on above see note [Api annotations] in ApiAnnotation
data Match id body
= Match {
m_ctxt :: HsMatchContext (NameOrRdrName id),
-- See note [m_ctxt in Match]
m_pats :: [LPat id], -- The patterns
m_type :: (Maybe (LHsType id)),
-- A type signature for the result of the match
-- Nothing after typechecking
-- NB: No longer supported
m_grhss :: (GRHSs id body)
}
deriving instance (Data body,DataId id) => Data (Match id body)
{-
Note [m_ctxt in Match]
~~~~~~~~~~~~~~~~~~~~~~
A Match can occur in a number of contexts, such as a FunBind, HsCase, HsLam and
so on.
In order to simplify tooling processing and pretty print output, the provenance
is captured in an HsMatchContext.
This is particularly important for the API Annotations for a multi-equation
FunBind.
The parser initially creates a FunBind with a single Match in it for
every function definition it sees.
These are then grouped together by getMonoBind into a single FunBind,
where all the Matches are combined.
In the process, all the original FunBind fun_id's bar one are
discarded, including the locations.
This causes a problem for source to source conversions via API
Annotations, so the original fun_ids and infix flags are preserved in
the Match, when it originates from a FunBind.
Example infix function definition requiring individual API Annotations
(&&& ) [] [] = []
xs &&& [] = xs
( &&& ) [] ys = ys
-}
isInfixMatch :: Match id body -> Bool
isInfixMatch match = case m_ctxt match of
FunRhs _ Infix -> True
_ -> False
isEmptyMatchGroup :: MatchGroup id body -> Bool
isEmptyMatchGroup (MG { mg_alts = ms }) = null $ unLoc ms
-- | Is there only one RHS in this list of matches?
isSingletonMatchGroup :: [LMatch id body] -> Bool
isSingletonMatchGroup matches
| [L _ match] <- matches
, Match { m_grhss = GRHSs { grhssGRHSs = [_] } } <- match
= True
| otherwise
= False
matchGroupArity :: MatchGroup id body -> Arity
-- Precondition: MatchGroup is non-empty
-- This is called before type checking, when mg_arg_tys is not set
matchGroupArity (MG { mg_alts = alts })
| L _ (alt1:_) <- alts = length (hsLMatchPats alt1)
| otherwise = panic "matchGroupArity"
hsLMatchPats :: LMatch id body -> [LPat id]
hsLMatchPats (L _ (Match _ pats _ _)) = pats
-- | Guarded Right-Hand Sides
--
-- GRHSs are used both for pattern bindings and for Matches
--
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere',
-- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose'
-- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi'
-- For details on above see note [Api annotations] in ApiAnnotation
data GRHSs id body
= GRHSs {
grhssGRHSs :: [LGRHS id body], -- ^ Guarded RHSs
grhssLocalBinds :: Located (HsLocalBinds id) -- ^ The where clause
}
deriving instance (Data body,DataId id) => Data (GRHSs id body)
-- | Located Guarded Right-Hand Side
type LGRHS id body = Located (GRHS id body)
-- | Guarded Right Hand Side.
data GRHS id body = GRHS [GuardLStmt id] -- Guards
body -- Right hand side
deriving instance (Data body,DataId id) => Data (GRHS id body)
-- We know the list must have at least one @Match@ in it.
pprMatches :: (OutputableBndrId idR, Outputable body)
=> MatchGroup idR body -> SDoc
pprMatches MG { mg_alts = matches }
= vcat (map pprMatch (map unLoc (unLoc matches)))
-- Don't print the type; it's only a place-holder before typechecking
-- Exported to HsBinds, which can't see the defn of HsMatchContext
pprFunBind :: (OutputableBndrId idR, Outputable body)
=> MatchGroup idR body -> SDoc
pprFunBind matches = pprMatches matches
-- Exported to HsBinds, which can't see the defn of HsMatchContext
pprPatBind :: forall bndr id body. (OutputableBndrId bndr,
OutputableBndrId id, Outputable body)
=> LPat bndr -> GRHSs id body -> SDoc
pprPatBind pat (grhss)
= sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)]
pprMatch :: (OutputableBndrId idR, Outputable body) => Match idR body -> SDoc
pprMatch match
= sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats)
, nest 2 ppr_maybe_ty
, nest 2 (pprGRHSs ctxt (m_grhss match)) ]
where
ctxt = m_ctxt match
(herald, other_pats)
= case ctxt of
FunRhs (L _ fun) fixity
| fixity == Prefix -> (pprPrefixOcc fun, m_pats match)
-- f x y z = e
-- Not pprBndr; the AbsBinds will
-- have printed the signature
| null pats2 -> (pp_infix, [])
-- x &&& y = e
| otherwise -> (parens pp_infix, pats2)
-- (x &&& y) z = e
where
pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2
LambdaExpr -> (char '\\', m_pats match)
_ -> ASSERT( null pats1 )
(ppr pat1, []) -- No parens around the single pat
(pat1:pats1) = m_pats match
(pat2:pats2) = pats1
ppr_maybe_ty = case m_type match of
Just ty -> dcolon <+> ppr ty
Nothing -> empty
pprGRHSs :: (OutputableBndrId idR, Outputable body)
=> HsMatchContext idL -> GRHSs idR body -> SDoc
pprGRHSs ctxt (GRHSs grhss (L _ binds))
= vcat (map (pprGRHS ctxt . unLoc) grhss)
$$ ppUnless (isEmptyLocalBinds binds)
(text "where" $$ nest 4 (pprBinds binds))
pprGRHS :: (OutputableBndrId idR, Outputable body)
=> HsMatchContext idL -> GRHS idR body -> SDoc
pprGRHS ctxt (GRHS [] body)
= pp_rhs ctxt body
pprGRHS ctxt (GRHS guards body)
= sep [vbar <+> interpp'SP guards, pp_rhs ctxt body]
pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc
pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs)
{-
************************************************************************
* *
\subsection{Do stmts and list comprehensions}
* *
************************************************************************
-}
-- | Located @do@ block Statement
type LStmt id body = Located (StmtLR id id body)
-- | Located Statement with separate Left and Right id's
type LStmtLR idL idR body = Located (StmtLR idL idR body)
-- | @do@ block Statement
type Stmt id body = StmtLR id id body
-- | Command Located Statement
type CmdLStmt id = LStmt id (LHsCmd id)
-- | Command Statement
type CmdStmt id = Stmt id (LHsCmd id)
-- | Expression Located Statement
type ExprLStmt id = LStmt id (LHsExpr id)
-- | Expression Statement
type ExprStmt id = Stmt id (LHsExpr id)
-- | Guard Located Statement
type GuardLStmt id = LStmt id (LHsExpr id)
-- | Guard Statement
type GuardStmt id = Stmt id (LHsExpr id)
-- | Ghci Located Statemnt
type GhciLStmt id = LStmt id (LHsExpr id)
-- | Ghci Statement
type GhciStmt id = Stmt id (LHsExpr id)
-- The SyntaxExprs in here are used *only* for do-notation and monad
-- comprehensions, which have rebindable syntax. Otherwise they are unused.
-- | API Annotations when in qualifier lists or guards
-- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar',
-- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen',
-- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy',
-- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing'
-- For details on above see note [Api annotations] in ApiAnnotation
data StmtLR idL idR body -- body should always be (LHs**** idR)
= LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp,
-- and (after the renamer) DoExpr, MDoExpr
-- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff
body
Bool -- True <=> return was stripped by ApplicativeDo
(SyntaxExpr idR) -- The return operator, used only for
-- MonadComp For ListComp, PArrComp, we
-- use the baked-in 'return' For DoExpr,
-- MDoExpr, we don't apply a 'return' at
-- all See Note [Monad Comprehensions] |
-- - 'ApiAnnotation.AnnKeywordId' :
-- 'ApiAnnotation.AnnLarrow'
-- For details on above see note [Api annotations] in ApiAnnotation
| BindStmt (LPat idL)
body
(SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind in Stmts]
(SyntaxExpr idR) -- The fail operator
-- The fail operator is noSyntaxExpr
-- if the pattern match can't fail
(PostTc idR Type) -- result type of the function passed to bind;
-- that is, S in (>>=) :: Q -> (R -> S) -> T
-- | 'ApplicativeStmt' represents an applicative expression built with
-- <$> and <*>. It is generated by the renamer, and is desugared into the
-- appropriate applicative expression by the desugarer, but it is intended
-- to be invisible in error messages.
--
-- For full details, see Note [ApplicativeDo] in RnExpr
--
| ApplicativeStmt
[ ( SyntaxExpr idR
, ApplicativeArg idL idR) ]
-- [(<$>, e1), (<*>, e2), ..., (<*>, en)]
(Maybe (SyntaxExpr idR)) -- 'join', if necessary
(PostTc idR Type) -- Type of the body
| BodyStmt body -- See Note [BodyStmt]
(SyntaxExpr idR) -- The (>>) operator
(SyntaxExpr idR) -- The `guard` operator; used only in MonadComp
-- See notes [Monad Comprehensions]
(PostTc idR Type) -- Element type of the RHS (used for arrows)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet'
-- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@,
-- For details on above see note [Api annotations] in ApiAnnotation
| LetStmt (Located (HsLocalBindsLR idL idR))
-- ParStmts only occur in a list/monad comprehension
| ParStmt [ParStmtBlock idL idR]
(HsExpr idR) -- Polymorphic `mzip` for monad comprehensions
(SyntaxExpr idR) -- The `>>=` operator
-- See notes [Monad Comprehensions]
(PostTc idR Type) -- S in (>>=) :: Q -> (R -> S) -> T
-- After renaming, the ids are the binders
-- bound by the stmts and used after themp
| TransStmt {
trS_form :: TransForm,
trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group'
-- which generates the tuples to be grouped
trS_bndrs :: [(idR, idR)], -- See Note [TransStmt binder map]
trS_using :: LHsExpr idR,
trS_by :: Maybe (LHsExpr idR), -- "by e" (optional)
-- Invariant: if trS_form = GroupBy, then grp_by = Just e
trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for
-- the inner monad comprehensions
trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator
trS_bind_arg_ty :: PostTc idR Type, -- R in (>>=) :: Q -> (R -> S) -> T
trS_fmap :: HsExpr idR -- The polymorphic 'fmap' function for desugaring
-- Only for 'group' forms
-- Just a simple HsExpr, because it's
-- too polymorphic for tcSyntaxOp
} -- See Note [Monad Comprehensions]
-- Recursive statement (see Note [How RecStmt works] below)
-- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec'
-- For details on above see note [Api annotations] in ApiAnnotation
| RecStmt
{ recS_stmts :: [LStmtLR idL idR body]
-- The next two fields are only valid after renaming
, recS_later_ids :: [idR] -- The ids are a subset of the variables bound by the
-- stmts that are used in stmts that follow the RecStmt
, recS_rec_ids :: [idR] -- Ditto, but these variables are the "recursive" ones,
-- that are used before they are bound in the stmts of
-- the RecStmt.
-- An Id can be in both groups
-- Both sets of Ids are (now) treated monomorphically
-- See Note [How RecStmt works] for why they are separate
-- Rebindable syntax
, recS_bind_fn :: SyntaxExpr idR -- The bind function
, recS_ret_fn :: SyntaxExpr idR -- The return function
, recS_mfix_fn :: SyntaxExpr idR -- The mfix function
, recS_bind_ty :: PostTc idR Type -- S in (>>=) :: Q -> (R -> S) -> T
-- These fields are only valid after typechecking
, recS_later_rets :: [PostTcExpr] -- (only used in the arrow version)
, recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1
-- with recS_later_ids and recS_rec_ids,
-- and are the expressions that should be
-- returned by the recursion.
-- They may not quite be the Ids themselves,
-- because the Id may be *polymorphic*, but
-- the returned thing has to be *monomorphic*,
-- so they may be type applications
, recS_ret_ty :: PostTc idR Type -- The type of
-- do { stmts; return (a,b,c) }
-- With rebindable syntax the type might not
-- be quite as simple as (m (tya, tyb, tyc)).
}
deriving instance (Data body, DataId idL, DataId idR)
=> Data (StmtLR idL idR body)
data TransForm -- The 'f' below is the 'using' function, 'e' is the by function
= ThenForm -- then f or then f by e (depending on trS_by)
| GroupForm -- then group using f or then group by e using f (depending on trS_by)
deriving Data
-- | Parenthesised Statement Block
data ParStmtBlock idL idR
= ParStmtBlock
[ExprLStmt idL]
[idR] -- The variables to be returned
(SyntaxExpr idR) -- The return operator
deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR)
-- | Applicative Argument
data ApplicativeArg idL idR
= ApplicativeArgOne -- pat <- expr (pat must be irrefutable)
(LPat idL)
(LHsExpr idL)
| ApplicativeArgMany -- do { stmts; return vars }
[ExprLStmt idL] -- stmts
(HsExpr idL) -- return (v1,..,vn), or just (v1,..,vn)
(LPat idL) -- (v1,...,vn)
deriving instance (DataId idL, DataId idR) => Data (ApplicativeArg idL idR)
{-
Note [The type of bind in Stmts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Some Stmts, notably BindStmt, keep the (>>=) bind operator.
We do NOT assume that it has type
(>>=) :: m a -> (a -> m b) -> m b
In some cases (see Trac #303, #1537) it might have a more
exotic type, such as
(>>=) :: m i j a -> (a -> m j k b) -> m i k b
So we must be careful not to make assumptions about the type.
In particular, the monad may not be uniform throughout.
Note [TransStmt binder map]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The [(idR,idR)] in a TransStmt behaves as follows:
* Before renaming: []
* After renaming:
[ (x27,x27), ..., (z35,z35) ]
These are the variables
bound by the stmts to the left of the 'group'
and used either in the 'by' clause,
or in the stmts following the 'group'
Each item is a pair of identical variables.
* After typechecking:
[ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ]
Each pair has the same unique, but different *types*.
Note [BodyStmt]
~~~~~~~~~~~~~~~
BodyStmts are a bit tricky, because what they mean
depends on the context. Consider the following contexts:
A do expression of type (m res_ty)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E any_ty: do { ....; E; ... }
E :: m any_ty
Translation: E >> ...
A list comprehensions of type [elt_ty]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E Bool: [ .. | .... E ]
[ .. | ..., E, ... ]
[ .. | .... | ..., E | ... ]
E :: Bool
Translation: if E then fail else ...
A guard list, guarding a RHS of type rhs_ty
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs...
E :: Bool
Translation: if E then fail else ...
A monad comprehension of type (m res_ty)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* BodyStmt E Bool: [ .. | .... E ]
E :: Bool
Translation: guard E >> ...
Array comprehensions are handled like list comprehensions.
Note [How RecStmt works]
~~~~~~~~~~~~~~~~~~~~~~~~
Example:
HsDo [ BindStmt x ex
, RecStmt { recS_rec_ids = [a, c]
, recS_stmts = [ BindStmt b (return (a,c))
, LetStmt a = ...b...
, BindStmt c ec ]
, recS_later_ids = [a, b]
, return (a b) ]
Here, the RecStmt binds a,b,c; but
- Only a,b are used in the stmts *following* the RecStmt,
- Only a,c are used in the stmts *inside* the RecStmt
*before* their bindings
Why do we need *both* rec_ids and later_ids? For monads they could be
combined into a single set of variables, but not for arrows. That
follows from the types of the respective feedback operators:
mfix :: MonadFix m => (a -> m a) -> m a
loop :: ArrowLoop a => a (b,d) (c,d) -> a b c
* For mfix, the 'a' covers the union of the later_ids and the rec_ids
* For 'loop', 'c' is the later_ids and 'd' is the rec_ids
Note [Typing a RecStmt]
~~~~~~~~~~~~~~~~~~~~~~~
A (RecStmt stmts) types as if you had written
(v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) ->
do { stmts
; return (v1,..vn, r1, ..., rm) })
where v1..vn are the later_ids
r1..rm are the rec_ids
Note [Monad Comprehensions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Monad comprehensions require separate functions like 'return' and
'>>=' for desugaring. These functions are stored in the statements
used in monad comprehensions. For example, the 'return' of the 'LastStmt'
expression is used to lift the body of the monad comprehension:
[ body | stmts ]
=>
stmts >>= \bndrs -> return body
In transform and grouping statements ('then ..' and 'then group ..') the
'return' function is required for nested monad comprehensions, for example:
[ body | stmts, then f, rest ]
=>
f [ env | stmts ] >>= \bndrs -> [ body | rest ]
BodyStmts require the 'Control.Monad.guard' function for boolean
expressions:
[ body | exp, stmts ]
=>
guard exp >> [ body | stmts ]
Parallel statements require the 'Control.Monad.Zip.mzip' function:
[ body | stmts1 | stmts2 | .. ]
=>
mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body
In any other context than 'MonadComp', the fields for most of these
'SyntaxExpr's stay bottom.
-}
instance (OutputableBndrId idL) => Outputable (ParStmtBlock idL idR) where
ppr (ParStmtBlock stmts _ _) = interpp'SP stmts
instance (OutputableBndrId idL, OutputableBndrId idR, Outputable body)
=> Outputable (StmtLR idL idR body) where
ppr stmt = pprStmt stmt
pprStmt :: forall idL idR body . (OutputableBndrId idL, OutputableBndrId idR,
Outputable body)
=> (StmtLR idL idR body) -> SDoc
pprStmt (LastStmt expr ret_stripped _)
= ifPprDebug (text "[last]") <+>
(if ret_stripped then text "return" else empty) <+>
ppr expr
pprStmt (BindStmt pat expr _ _ _) = hsep [ppr pat, larrow, ppr expr]
pprStmt (LetStmt (L _ binds)) = hsep [text "let", pprBinds binds]
pprStmt (BodyStmt expr _ _ _) = ppr expr
pprStmt (ParStmt stmtss _ _ _) = sep (punctuate (text " | ") (map ppr stmtss))
pprStmt (TransStmt { trS_stmts = stmts, trS_by = by, trS_using = using, trS_form = form })
= sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form])
pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids
, recS_later_ids = later_ids })
= text "rec" <+>
vcat [ ppr_do_stmts segment
, ifPprDebug (vcat [ text "rec_ids=" <> ppr rec_ids
, text "later_ids=" <> ppr later_ids])]
pprStmt (ApplicativeStmt args mb_join _)
= getPprStyle $ \style ->
if userStyle style
then pp_for_user
else pp_debug
where
-- make all the Applicative stuff invisible in error messages by
-- flattening the whole ApplicativeStmt nest back to a sequence
-- of statements.
pp_for_user = vcat $ punctuate semi $ concatMap flattenArg args
-- ppr directly rather than transforming here, because we need to
-- inject a "return" which is hard when we're polymorphic in the id
-- type.
flattenStmt :: ExprLStmt idL -> [SDoc]
flattenStmt (L _ (ApplicativeStmt args _ _)) = concatMap flattenArg args
flattenStmt stmt = [ppr stmt]
flattenArg (_, ApplicativeArgOne pat expr) =
[ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
:: ExprStmt idL)]
flattenArg (_, ApplicativeArgMany stmts _ _) =
concatMap flattenStmt stmts
pp_debug =
let
ap_expr = sep (punctuate (text " |") (map pp_arg args))
in
if isNothing mb_join
then ap_expr
else text "join" <+> parens ap_expr
pp_arg (_, ApplicativeArgOne pat expr) =
ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr (panic "pprStmt")
:: ExprStmt idL)
pp_arg (_, ApplicativeArgMany stmts return pat) =
ppr pat <+>
text "<-" <+>
ppr (HsDo DoExpr (noLoc
(stmts ++ [noLoc (LastStmt (noLoc return) False noSyntaxExpr)]))
(error "pprStmt"))
pprTransformStmt :: (OutputableBndrId id)
=> [id] -> LHsExpr id -> Maybe (LHsExpr id) -> SDoc
pprTransformStmt bndrs using by
= sep [ text "then" <+> ifPprDebug (braces (ppr bndrs))
, nest 2 (ppr using)
, nest 2 (pprBy by)]
pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc
pprTransStmt by using ThenForm
= sep [ text "then", nest 2 (ppr using), nest 2 (pprBy by)]
pprTransStmt by using GroupForm
= sep [ text "then group", nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)]
pprBy :: Outputable body => Maybe body -> SDoc
pprBy Nothing = empty
pprBy (Just e) = text "by" <+> ppr e
pprDo :: (OutputableBndrId id, Outputable body)
=> HsStmtContext any -> [LStmt id body] -> SDoc
pprDo DoExpr stmts = text "do" <+> ppr_do_stmts stmts
pprDo GhciStmtCtxt stmts = text "do" <+> ppr_do_stmts stmts
pprDo ArrowExpr stmts = text "do" <+> ppr_do_stmts stmts
pprDo MDoExpr stmts = text "mdo" <+> ppr_do_stmts stmts
pprDo ListComp stmts = brackets $ pprComp stmts
pprDo PArrComp stmts = paBrackets $ pprComp stmts
pprDo MonadComp stmts = brackets $ pprComp stmts
pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt
ppr_do_stmts :: (OutputableBndrId idL, OutputableBndrId idR, Outputable body)
=> [LStmtLR idL idR body] -> SDoc
-- Print a bunch of do stmts, with explicit braces and semicolons,
-- so that we are not vulnerable to layout bugs
ppr_do_stmts stmts
= lbrace <+> pprDeeperList vcat (punctuate semi (map ppr stmts))
<+> rbrace
pprComp :: (OutputableBndrId id, Outputable body)
=> [LStmt id body] -> SDoc
pprComp quals -- Prints: body | qual1, ..., qualn
| Just (initStmts, L _ (LastStmt body _ _)) <- snocView quals
= if null initStmts
-- If there are no statements in a list comprehension besides the last
-- one, we simply treat it like a normal list. This does arise
-- occasionally in code that GHC generates, e.g., in implementations of
-- 'range' for derived 'Ix' instances for product datatypes with exactly
-- one constructor (e.g., see Trac #12583).
then ppr body
else hang (ppr body <+> vbar) 2 (pprQuals initStmts)
| otherwise
= pprPanic "pprComp" (pprQuals quals)
pprQuals :: (OutputableBndrId id, Outputable body)
=> [LStmt id body] -> SDoc
-- Show list comprehension qualifiers separated by commas
pprQuals quals = interpp'SP quals
{-
************************************************************************
* *
Template Haskell quotation brackets
* *
************************************************************************
-}
-- | Haskell Splice
data HsSplice id
= HsTypedSplice -- $$z or $$(f 4)
id -- A unique name to identify this splice point
(LHsExpr id) -- See Note [Pending Splices]
| HsUntypedSplice -- $z or $(f 4)
id -- A unique name to identify this splice point
(LHsExpr id) -- See Note [Pending Splices]
| HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice
id -- Splice point
id -- Quoter
SrcSpan -- The span of the enclosed string
FastString -- The enclosed string
| HsSpliced -- See Note [Delaying modFinalizers in untyped splices] in
-- RnSplice.
-- This is the result of splicing a splice. It is produced by
-- the renamer and consumed by the typechecker. It lives only
-- between the two.
ThModFinalizers -- TH finalizers produced by the splice.
(HsSplicedThing id) -- The result of splicing
deriving Typeable
deriving instance (DataId id) => Data (HsSplice id)
isTypedSplice :: HsSplice id -> Bool
isTypedSplice (HsTypedSplice {}) = True
isTypedSplice _ = False -- Quasi-quotes are untyped splices
-- | Finalizers produced by a splice with
-- 'Language.Haskell.TH.Syntax.addModFinalizer'
--
-- See Note [Delaying modFinalizers in untyped splices] in RnSplice. For how
-- this is used.
--
#ifdef GHCI
newtype ThModFinalizers = ThModFinalizers [ForeignRef (TH.Q ())]
#else
data ThModFinalizers = ThModFinalizers
#endif
-- A Data instance which ignores the argument of 'ThModFinalizers'.
#ifdef GHCI
instance Data ThModFinalizers where
gunfold _ z _ = z $ ThModFinalizers []
toConstr a = mkConstr (dataTypeOf a) "ThModFinalizers" [] Data.Prefix
dataTypeOf a = mkDataType "HsExpr.ThModFinalizers" [toConstr a]
#else
instance Data ThModFinalizers where
gunfold _ z _ = z ThModFinalizers
toConstr a = mkConstr (dataTypeOf a) "ThModFinalizers" [] Data.Prefix
dataTypeOf a = mkDataType "HsExpr.ThModFinalizers" [toConstr a]
#endif
-- | Haskell Spliced Thing
--
-- Values that can result from running a splice.
data HsSplicedThing id
= HsSplicedExpr (HsExpr id) -- ^ Haskell Spliced Expression
| HsSplicedTy (HsType id) -- ^ Haskell Spliced Type
| HsSplicedPat (Pat id) -- ^ Haskell Spilced Pattern
deriving Typeable
deriving instance (DataId id) => Data (HsSplicedThing id)
-- See Note [Pending Splices]
type SplicePointName = Name
-- | Pending Renamer Splice
data PendingRnSplice
= PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr Name)
deriving Data
data UntypedSpliceFlavour
= UntypedExpSplice
| UntypedPatSplice
| UntypedTypeSplice
| UntypedDeclSplice
deriving Data
-- | Pending Type-checker Splice
data PendingTcSplice
= PendingTcSplice SplicePointName (LHsExpr Id)
deriving Data
{-
Note [Pending Splices]
~~~~~~~~~~~~~~~~~~~~~~
When we rename an untyped bracket, we name and lift out all the nested
splices, so that when the typechecker hits the bracket, it can
typecheck those nested splices without having to walk over the untyped
bracket code. So for example
[| f $(g x) |]
looks like
HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x)))
which the renamer rewrites to
HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x)))
[PendingRnSplice UntypedExpSplice sn (g x)]
* The 'sn' is the Name of the splice point, the SplicePointName
* The PendingRnExpSplice gives the splice that splice-point name maps to;
and the typechecker can now conveniently find these sub-expressions
* The other copy of the splice, in the second argument of HsSpliceE
in the renamed first arg of HsRnBracketOut
is used only for pretty printing
There are four varieties of pending splices generated by the renamer,
distinguished by their UntypedSpliceFlavour
* Pending expression splices (UntypedExpSplice), e.g.,
[|$(f x) + 2|]
UntypedExpSplice is also used for
* quasi-quotes, where the pending expression expands to
$(quoter "...blah...")
(see RnSplice.makePending, HsQuasiQuote case)
* cross-stage lifting, where the pending expression expands to
$(lift x)
(see RnSplice.checkCrossStageLifting)
* Pending pattern splices (UntypedPatSplice), e.g.,
[| \$(f x) -> x |]
* Pending type splices (UntypedTypeSplice), e.g.,
[| f :: $(g x) |]
* Pending declaration (UntypedDeclSplice), e.g.,
[| let $(f x) in ... |]
There is a fifth variety of pending splice, which is generated by the type
checker:
* Pending *typed* expression splices, (PendingTcSplice), e.g.,
[||1 + $$(f 2)||]
It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the
output of the renamer. However, when pretty printing the output of the renamer,
e.g., in a type error message, we *do not* want to print out the pending
splices. In contrast, when pretty printing the output of the type checker, we
*do* want to print the pending splices. So splitting them up seems to make
sense, although I hate to add another constructor to HsExpr.
-}
instance OutputableBndrId id => Outputable (HsSplicedThing id) where
ppr (HsSplicedExpr e) = ppr_expr e
ppr (HsSplicedTy t) = ppr t
ppr (HsSplicedPat p) = ppr p
instance (OutputableBndrId id) => Outputable (HsSplice id) where
ppr s = pprSplice s
pprPendingSplice :: (OutputableBndrId id)
=> SplicePointName -> LHsExpr id -> SDoc
pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr e)
pprSplice :: (OutputableBndrId id) => HsSplice id -> SDoc
pprSplice (HsTypedSplice n e) = ppr_splice (text "$$") n e
pprSplice (HsUntypedSplice n e) = ppr_splice (text "$") n e
pprSplice (HsQuasiQuote n q _ s) = ppr_quasi n q s
pprSplice (HsSpliced _ thing) = ppr thing
ppr_quasi :: OutputableBndr id => id -> id -> FastString -> SDoc
ppr_quasi n quoter quote = ifPprDebug (brackets (ppr n)) <>
char '[' <> ppr quoter <> vbar <>
ppr quote <> text "|]"
ppr_splice :: (OutputableBndrId id) => SDoc -> id -> LHsExpr id -> SDoc
ppr_splice herald n e
= herald <> ifPprDebug (brackets (ppr n)) <> eDoc
where
-- We use pprLExpr to match pprParendLExpr:
-- Using pprLExpr makes sure that we go 'deeper'
-- I think that is usually (always?) right
pp_as_was = pprLExpr e
eDoc = case unLoc e of
HsPar _ -> pp_as_was
HsVar _ -> pp_as_was
_ -> parens pp_as_was
-- | Haskell Bracket
data HsBracket id = ExpBr (LHsExpr id) -- [| expr |]
| PatBr (LPat id) -- [p| pat |]
| DecBrL [LHsDecl id] -- [d| decls |]; result of parser
| DecBrG (HsGroup id) -- [d| decls |]; result of renamer
| TypBr (LHsType id) -- [t| type |]
| VarBr Bool id -- True: 'x, False: ''T
-- (The Bool flag is used only in pprHsBracket)
| TExpBr (LHsExpr id) -- [|| expr ||]
deriving instance (DataId id) => Data (HsBracket id)
isTypedBracket :: HsBracket id -> Bool
isTypedBracket (TExpBr {}) = True
isTypedBracket _ = False
instance (OutputableBndrId id) => Outputable (HsBracket id) where
ppr = pprHsBracket
pprHsBracket :: (OutputableBndrId id) => HsBracket id -> SDoc
pprHsBracket (ExpBr e) = thBrackets empty (ppr e)
pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p)
pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp)
pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds))
pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t)
pprHsBracket (VarBr True n) = char '\'' <> ppr n
pprHsBracket (VarBr False n) = text "''" <> ppr n
pprHsBracket (TExpBr e) = thTyBrackets (ppr e)
thBrackets :: SDoc -> SDoc -> SDoc
thBrackets pp_kind pp_body = char '[' <> pp_kind <> vbar <+>
pp_body <+> text "|]"
thTyBrackets :: SDoc -> SDoc
thTyBrackets pp_body = text "[||" <+> pp_body <+> ptext (sLit "||]")
instance Outputable PendingRnSplice where
ppr (PendingRnSplice _ n e) = pprPendingSplice n e
instance Outputable PendingTcSplice where
ppr (PendingTcSplice n e) = pprPendingSplice n e
{-
************************************************************************
* *
\subsection{Enumerations and list comprehensions}
* *
************************************************************************
-}
-- | Arithmetic Sequence Information
data ArithSeqInfo id
= From (LHsExpr id)
| FromThen (LHsExpr id)
(LHsExpr id)
| FromTo (LHsExpr id)
(LHsExpr id)
| FromThenTo (LHsExpr id)
(LHsExpr id)
(LHsExpr id)
deriving instance (DataId id) => Data (ArithSeqInfo id)
instance (OutputableBndrId id) => Outputable (ArithSeqInfo id) where
ppr (From e1) = hcat [ppr e1, pp_dotdot]
ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot]
ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3]
ppr (FromThenTo e1 e2 e3)
= hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3]
pp_dotdot :: SDoc
pp_dotdot = text " .. "
{-
************************************************************************
* *
\subsection{HsMatchCtxt}
* *
************************************************************************
-}
data FunctionFixity = Prefix | Infix deriving (Typeable,Data,Eq)
instance Outputable FunctionFixity where
ppr Prefix = text "Prefix"
ppr Infix = text "Infix"
-- | Haskell Match Context
--
-- Context of a Match
data HsMatchContext id
= FunRhs (Located id) FunctionFixity -- ^Function binding for f, fixity
| LambdaExpr -- ^Patterns of a lambda
| CaseAlt -- ^Patterns and guards on a case alternative
| IfAlt -- ^Guards of a multi-way if alternative
| ProcExpr -- ^Patterns of a proc
| PatBindRhs -- ^A pattern binding eg [y] <- e = e
| RecUpd -- ^Record update [used only in DsExpr to
-- tell matchWrapper what sort of
-- runtime error message to generate]
| StmtCtxt (HsStmtContext id) -- ^Pattern of a do-stmt, list comprehension,
-- pattern guard, etc
| ThPatSplice -- ^A Template Haskell pattern splice
| ThPatQuote -- ^A Template Haskell pattern quotation [p| (a,b) |]
| PatSyn -- ^A pattern synonym declaration
deriving Functor
deriving instance (DataIdPost id) => Data (HsMatchContext id)
isPatSynCtxt :: HsMatchContext id -> Bool
isPatSynCtxt ctxt =
case ctxt of
PatSyn -> True
_ -> False
-- | Haskell Statement Context
data HsStmtContext id
= ListComp
| MonadComp
| PArrComp -- ^Parallel array comprehension
| DoExpr -- ^do { ... }
| MDoExpr -- ^mdo { ... } ie recursive do-expression
| ArrowExpr -- ^do-notation in an arrow-command context
| GhciStmtCtxt -- ^A command-line Stmt in GHCi pat <- rhs
| PatGuard (HsMatchContext id) -- ^Pattern guard for specified thing
| ParStmtCtxt (HsStmtContext id) -- ^A branch of a parallel stmt
| TransStmtCtxt (HsStmtContext id) -- ^A branch of a transform stmt
deriving Functor
deriving instance (DataIdPost id) => Data (HsStmtContext id)
isListCompExpr :: HsStmtContext id -> Bool
-- Uses syntax [ e | quals ]
isListCompExpr ListComp = True
isListCompExpr PArrComp = True
isListCompExpr MonadComp = True
isListCompExpr (ParStmtCtxt c) = isListCompExpr c
isListCompExpr (TransStmtCtxt c) = isListCompExpr c
isListCompExpr _ = False
isMonadCompExpr :: HsStmtContext id -> Bool
isMonadCompExpr MonadComp = True
isMonadCompExpr (ParStmtCtxt ctxt) = isMonadCompExpr ctxt
isMonadCompExpr (TransStmtCtxt ctxt) = isMonadCompExpr ctxt
isMonadCompExpr _ = False
matchSeparator :: HsMatchContext id -> SDoc
matchSeparator (FunRhs {}) = text "="
matchSeparator CaseAlt = text "->"
matchSeparator IfAlt = text "->"
matchSeparator LambdaExpr = text "->"
matchSeparator ProcExpr = text "->"
matchSeparator PatBindRhs = text "="
matchSeparator (StmtCtxt _) = text "<-"
matchSeparator RecUpd = panic "unused"
matchSeparator ThPatSplice = panic "unused"
matchSeparator ThPatQuote = panic "unused"
matchSeparator PatSyn = panic "unused"
pprMatchContext :: (Outputable (NameOrRdrName id),Outputable id)
=> HsMatchContext id -> SDoc
pprMatchContext ctxt
| want_an ctxt = text "an" <+> pprMatchContextNoun ctxt
| otherwise = text "a" <+> pprMatchContextNoun ctxt
where
want_an (FunRhs {}) = True -- Use "an" in front
want_an ProcExpr = True
want_an _ = False
pprMatchContextNoun :: (Outputable (NameOrRdrName id),Outputable id)
=> HsMatchContext id -> SDoc
pprMatchContextNoun (FunRhs (L _ fun) _) = text "equation for"
<+> quotes (ppr fun)
pprMatchContextNoun CaseAlt = text "case alternative"
pprMatchContextNoun IfAlt = text "multi-way if alternative"
pprMatchContextNoun RecUpd = text "record-update construct"
pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice"
pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation"
pprMatchContextNoun PatBindRhs = text "pattern binding"
pprMatchContextNoun LambdaExpr = text "lambda abstraction"
pprMatchContextNoun ProcExpr = text "arrow abstraction"
pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in"
$$ pprStmtContext ctxt
pprMatchContextNoun PatSyn = text "pattern synonym declaration"
-----------------
pprAStmtContext, pprStmtContext :: (Outputable id,
Outputable (NameOrRdrName id))
=> HsStmtContext id -> SDoc
pprAStmtContext ctxt = article <+> pprStmtContext ctxt
where
pp_an = text "an"
pp_a = text "a"
article = case ctxt of
MDoExpr -> pp_an
PArrComp -> pp_an
GhciStmtCtxt -> pp_an
_ -> pp_a
-----------------
pprStmtContext GhciStmtCtxt = text "interactive GHCi command"
pprStmtContext DoExpr = text "'do' block"
pprStmtContext MDoExpr = text "'mdo' block"
pprStmtContext ArrowExpr = text "'do' block in an arrow command"
pprStmtContext ListComp = text "list comprehension"
pprStmtContext MonadComp = text "monad comprehension"
pprStmtContext PArrComp = text "array comprehension"
pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt
-- Drop the inner contexts when reporting errors, else we get
-- Unexpected transform statement
-- in a transformed branch of
-- transformed branch of
-- transformed branch of monad comprehension
pprStmtContext (ParStmtCtxt c)
| opt_PprStyle_Debug = sep [text "parallel branch of", pprAStmtContext c]
| otherwise = pprStmtContext c
pprStmtContext (TransStmtCtxt c)
| opt_PprStyle_Debug = sep [text "transformed branch of", pprAStmtContext c]
| otherwise = pprStmtContext c
-- Used to generate the string for a *runtime* error message
matchContextErrString :: Outputable id
=> HsMatchContext id -> SDoc
matchContextErrString (FunRhs (L _ fun) _) = text "function" <+> ppr fun
matchContextErrString CaseAlt = text "case"
matchContextErrString IfAlt = text "multi-way if"
matchContextErrString PatBindRhs = text "pattern binding"
matchContextErrString RecUpd = text "record update"
matchContextErrString LambdaExpr = text "lambda"
matchContextErrString ProcExpr = text "proc"
matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime
matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime
matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime
matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c)
matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c)
matchContextErrString (StmtCtxt (PatGuard _)) = text "pattern guard"
matchContextErrString (StmtCtxt GhciStmtCtxt) = text "interactive GHCi command"
matchContextErrString (StmtCtxt DoExpr) = text "'do' block"
matchContextErrString (StmtCtxt ArrowExpr) = text "'do' block"
matchContextErrString (StmtCtxt MDoExpr) = text "'mdo' block"
matchContextErrString (StmtCtxt ListComp) = text "list comprehension"
matchContextErrString (StmtCtxt MonadComp) = text "monad comprehension"
matchContextErrString (StmtCtxt PArrComp) = text "array comprehension"
pprMatchInCtxt :: (OutputableBndrId idR,
Outputable (NameOrRdrName (NameOrRdrName idR)),
Outputable body)
=> Match idR body -> SDoc
pprMatchInCtxt match = hang (text "In" <+> pprMatchContext (m_ctxt match)
<> colon)
4 (pprMatch match)
pprStmtInCtxt :: (OutputableBndrId idL, OutputableBndrId idR, Outputable body)
=> HsStmtContext idL -> StmtLR idL idR body -> SDoc
pprStmtInCtxt ctxt (LastStmt e _ _)
| isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts"
= hang (text "In the expression:") 2 (ppr e)
pprStmtInCtxt ctxt stmt
= hang (text "In a stmt of" <+> pprAStmtContext ctxt <> colon)
2 (ppr_stmt stmt)
where
-- For Group and Transform Stmts, don't print the nested stmts!
ppr_stmt (TransStmt { trS_by = by, trS_using = using
, trS_form = form }) = pprTransStmt by using form
ppr_stmt stmt = pprStmt stmt
| snoyberg/ghc | compiler/hsSyn/HsExpr.hs | bsd-3-clause | 95,708 | 0 | 20 | 26,779 | 15,737 | 8,360 | 7,377 | 1,056 | 10 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module File.Header
( Info(..)
, readModule
, readOneFile
, readManyFiles
, readSource
)
where
import Control.Monad.Except (liftIO)
import qualified Data.ByteString as BS
import Data.List.NonEmpty (NonEmpty((:|)))
import qualified Data.Map as Map
import Data.Semigroup ((<>))
import qualified Data.Time.Calendar as Day
import qualified Data.Time.Clock as Time
import qualified System.Directory as Dir
import qualified Elm.Compiler.Module as Module
import qualified Elm.Header as Header
import qualified Elm.Project.Json as Project
import Elm.Project.Json (Project)
import Elm.Project.Summary (Summary(..))
import qualified File.IO as IO
import qualified Reporting.Error as Error
import qualified Reporting.Error.Crawl as E
import qualified Reporting.Task as Task
-- INFO
data Info =
Info
{ _path :: FilePath
, _time :: Time.UTCTime
, _source :: BS.ByteString
, _imports :: [Module.Raw]
}
atRoot :: Task.Task_ E.Problem a -> Task.Task_ E.Error a
atRoot task =
Task.mapError (\problem -> E.DependencyProblems problem []) task
-- READ MODULE
readModule :: Summary -> Module.Raw -> FilePath -> Task.Task_ E.Problem (Module.Raw, Info)
readModule summary expectedName path =
do time <- liftIO $ Dir.getModificationTime path
source <- liftIO $ IO.readUtf8 path
(maybeName, info) <- parse (_project summary) path time source
name <- checkName path expectedName maybeName
return (name, info)
checkName :: FilePath -> Module.Raw -> Maybe Module.Raw -> Task.Task_ E.Problem Module.Raw
checkName path expectedName maybeName =
case maybeName of
Nothing ->
Task.throw (E.ModuleNameMissing path expectedName)
Just actualName ->
if expectedName == actualName
then return expectedName
else Task.throw (E.ModuleNameMismatch path expectedName actualName)
-- READ ONE FILE
readOneFile :: Summary -> FilePath -> Task.Task (Maybe Module.Raw, Info)
readOneFile summary path =
Task.mapError Error.Crawl $
do (time, source) <- readOneHelp path
atRoot $ parse (_project summary) path time source
readOneHelp :: FilePath -> Task.Task_ E.Error (Time.UTCTime, BS.ByteString)
readOneHelp path =
do exists <- IO.exists path
if exists
then liftIO $ (,) <$> Dir.getModificationTime path <*> IO.readUtf8 path
else Task.throw $ E.RootFileNotFound path
-- READ MANY FILES
readManyFiles :: Summary -> NonEmpty FilePath -> Task.Task (NonEmpty (Module.Raw, Info))
readManyFiles summary files =
Task.mapError Error.Crawl $
do infos <- traverse (readManyFilesHelp summary) files
let insert (name, info) dict = Map.insertWith (<>) name (info :| []) dict
let nameTable = foldr insert Map.empty infos
_ <- Map.traverseWithKey detectDuplicateNames nameTable
return infos
readManyFilesHelp :: Summary -> FilePath -> Task.Task_ E.Error (Module.Raw, Info)
readManyFilesHelp summary path =
do (time, source) <- readOneHelp path
(maybeName, info) <- atRoot $ parse (_project summary) path time source
case maybeName of
Nothing ->
Task.throw (E.RootNameless path)
Just name ->
return (name, info)
detectDuplicateNames :: Module.Raw -> NonEmpty Info -> Task.Task_ E.Error ()
detectDuplicateNames name (info :| otherInfos) =
case otherInfos of
[] ->
return ()
_ ->
Task.throw (E.RootModuleNameDuplicate name (map _path (info : otherInfos)))
-- READ SOURCE
readSource :: Project -> BS.ByteString -> Task.Task (Maybe Module.Raw, Info)
readSource project source =
Task.mapError Error.Crawl $
atRoot $ parse project "elm" fakeTime source
fakeTime :: Time.UTCTime
fakeTime =
Time.UTCTime (Day.fromGregorian 3000 1 1) 0
-- PARSE HEADER
parse :: Project -> FilePath -> Time.UTCTime -> BS.ByteString -> Task.Task_ E.Problem (Maybe Module.Raw, Info)
parse project path time source =
-- TODO get regions on data extracted here
case Header.parse (Project.getName project) source of
Right (maybeDecl, deps) ->
do maybeName <- checkTag project path maybeDecl
return ( maybeName, Info path time source deps )
Left msg ->
Task.throw (E.BadHeader path source msg)
checkTag :: Project -> FilePath -> Maybe (Header.Tag, Module.Raw) -> Task.Task_ E.Problem (Maybe Module.Raw)
checkTag project path maybeDecl =
case maybeDecl of
Nothing ->
return Nothing
Just (tag, name) ->
let
success =
return (Just name)
in
case tag of
Header.Normal ->
success
Header.Port ->
case project of
Project.App _ ->
success
Project.Pkg _ ->
Task.throw (E.PortsInPackage path name)
Header.Effect ->
if Project.isPlatformPackage project then
success
else
Task.throw (E.EffectsUnexpected path name)
| evancz/builder | src/File/Header.hs | bsd-3-clause | 4,995 | 0 | 19 | 1,141 | 1,573 | 825 | 748 | 122 | 6 |
module TCPConnection ( TCPConnection
, openStream
, getStreamStart
)
where
import Network
import System.IO
import Data.IORef
import Control.Monad
import XMLParse
import XMPPConnection
-- |An XMPP connection over TCP.
data TCPConnection = TCPConnection Handle (IORef String)
-- |Open a TCP connection to the named server, port 5222, and send a
-- stream header. This should really check SRV records.
openStream :: String -> IO TCPConnection
openStream server =
do
h <- connectTo server (PortNumber 5222)
hSetBuffering h NoBuffering
hPutStr h $ xmlToString False $
XML "stream:stream"
[("to",server),
("xmlns","jabber:client"),
("xmlns:stream","http://etherx.jabber.org/streams")]
[]
buffer <- newIORef ""
return $ TCPConnection h buffer
-- |Get the stream header that the server sent. This needs to be
-- called before doing anything else with the stream.
getStreamStart :: TCPConnection -> IO XMLElem
getStreamStart c =
parseBuffered c xmppStreamStart
instance XMPPConnection TCPConnection where
getStanzas c = parseBuffered c deepTags
sendStanza (TCPConnection h _) x =
let str = xmlToString True x in
do
putStrLn $ "sent '" ++ str ++ "'"
hPutStr h str
closeConnection (TCPConnection h _) =
hClose h
parseBuffered :: TCPConnection -> Parser a -> IO a
parseBuffered c@(TCPConnection h bufvar) parser = do
buffer <- readIORef bufvar
input <- getString h
putStrLn $ "got '" ++ buffer ++ input ++ "'"
case parse (getRest parser) "" (buffer++input) of
Right (result, rest) ->
do
writeIORef bufvar rest
return result
Left e ->
do
putStrLn $ "An error? Hopefully doesn't matter.\n"++(show e)
parseBuffered c parser
getString :: Handle -> IO String
getString h =
do
hWaitForInput h (-1)
getEverything
where getEverything =
do
r <- hReady h
if r
then liftM2 (:) (hGetChar h) getEverything
else return []
| legoscia/hsxmpp | TCPConnection.hs | bsd-3-clause | 2,247 | 0 | 14 | 724 | 557 | 274 | 283 | 60 | 2 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.TextureBorderClamp
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/texture_border_clamp.txt ARB_texture_border_clamp> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.TextureBorderClamp (
-- * Enums
gl_CLAMP_TO_BORDER_ARB
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ARB/TextureBorderClamp.hs | bsd-3-clause | 677 | 0 | 4 | 78 | 37 | 31 | 6 | 3 | 0 |
{-# LANGUAGE RankNTypes, FlexibleContexts, TypeFamilies #-}
module Pipes.Process
( PipesProcess
, closeStdin
, withProcess
, readProcess
, writeProcess
, flushProcess
, start
, stop
) where
import Control.Concurrent (ThreadId, killThread, forkIO)
import Control.Concurrent.STM (atomically)
import Control.Concurrent.STM.TMVar (TMVar, newEmptyTMVar, putTMVar, takeTMVar)
import Control.Exception (SomeException, catch, throw)
import Control.Monad.Catch (MonadCatch)
import Data.ByteString (ByteString, hGetSome, hPut)
import Data.ByteString.Lazy.Internal (defaultChunkSize)
import Data.Maybe (catMaybes)
import Pipes
import Pipes.Safe (Base, MonadSafe, bracket, finally)
import System.Exit (ExitCode)
import System.IO (hClose, hIsEOF, hFlush)
import System.Process (StdStream(..), CreateProcess(..), ProcessHandle(..), createProcess, waitForProcess, terminateProcess, getProcessExitCode)
data PipesProcess = PipesProcess
{ action :: TMVar OutAction
, input :: TMVar InAction
, processHandle :: ProcessHandle
, tids :: [ThreadId]
}
data OutAction
= Stdout ByteString
| Stderr ByteString
| Terminated ExitCode
| ExceptionRaised SomeException
deriving Show
data InAction
= Stdin ByteString
| Flush
| CloseStdin
deriving Show
withProcess :: (MonadSafe m, Base m ~ IO) =>
CreateProcess
-> (PipesProcess -> m r)
-> m r
withProcess createProcess =
bracket (start createProcess) stop
start :: CreateProcess -> IO PipesProcess
start cp =
do action <- atomically newEmptyTMVar
outEOF <- atomically newEmptyTMVar
errEOF <- atomically newEmptyTMVar
input <- atomically newEmptyTMVar
(minh, mouth, merrh, proch) <- createProcess (cp { std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe })
inTid <- case minh of
Nothing -> return Nothing
(Just inh) ->
do tid <- forkIO $ let loop = do inaction <- atomically $ takeTMVar input
-- print ("in loop", inaction)
case inaction of
(Stdin bs) ->
do hPut inh bs
loop
Flush ->
do hFlush inh
loop
(CloseStdin) ->
do hFlush inh
hClose inh
in loop
return (Just tid)
outTid <- case mouth of
Nothing -> return Nothing
(Just outh) ->
do outTid <- forkIO $ let loop = do b <- hGetSome outh defaultChunkSize
-- print ("out",b)
atomically $ putTMVar action (Stdout b)
eof <- hIsEOF outh
if eof
then atomically $ putTMVar outEOF ()
else loop
in loop `catch` (\e -> do atomically $ putTMVar action (ExceptionRaised e))
return (Just outTid)
errTid <- case merrh of
Nothing -> return Nothing
(Just errh) ->
do errTid <- forkIO $ let loop = do b <- hGetSome errh 100
-- print ("err",b)
atomically $ putTMVar action (Stderr b)
eof <- hIsEOF errh
if eof
then atomically $ putTMVar errEOF ()
else loop
in loop `catch` (\e -> do atomically $ putTMVar action (ExceptionRaised e))
return (Just errTid)
termTid <- forkIO $
(do atomically $ takeTMVar outEOF
atomically $ takeTMVar errEOF
-- print ("term")
ec <- waitForProcess proch
atomically $ putTMVar action (Terminated ec))
`catch` (\e -> do atomically $ putTMVar action (ExceptionRaised e))
return $ PipesProcess action input proch (termTid : (catMaybes [inTid, outTid, errTid]))
stop :: PipesProcess -> IO ()
stop pipesProcess =
do atomically $ putTMVar (input pipesProcess) CloseStdin
let proch = processHandle pipesProcess
mec <- getProcessExitCode proch
case mec of
Nothing ->
do -- putStrLn "terminating process."
terminateProcess proch
_ <- waitForProcess proch
return ()
(Just _) -> return ()
-- putStrLn "cleaning up process threads"
mapM_ killThread (tids pipesProcess)
readProcess :: (MonadIO m) => PipesProcess -> Producer' (Either ByteString ByteString) m ExitCode
readProcess pipesProcess = loop where
loop = do a <- lift $ liftIO $ atomically $ takeTMVar (action pipesProcess)
-- liftIO $ print a
case a of
(Stdout b) ->
do yield (Right b)
loop
(Stderr b) ->
do yield (Left b)
loop
(Terminated ec) ->
do return ec
(ExceptionRaised e) ->
throw e
writeProcess :: (MonadSafe m, MonadIO (Base m), MonadIO m) => PipesProcess -> Consumer' ByteString m ()
writeProcess pipesProcess = loop `finally` (closeStdin pipesProcess) where
loop = do bs <- await
lift $ liftIO $ atomically $ putTMVar (input pipesProcess) (Stdin bs)
loop
closeStdin :: (MonadIO m) => PipesProcess -> m ()
closeStdin pipesProcess =
liftIO $ atomically $ putTMVar (input pipesProcess) CloseStdin
flushProcess :: (MonadIO m) => PipesProcess -> m ()
flushProcess pipesProcess =
liftIO $ atomically $ putTMVar (input pipesProcess) Flush | stepcut/pipes-process | Pipes/Process.hs | bsd-3-clause | 7,097 | 0 | 26 | 3,360 | 1,610 | 817 | 793 | 135 | 8 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module DataStore.Token where
import Database.Persist
import Database.Persist.TH
import Database.Persist.Sqlite
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
OAuth2Token
userID Int
token String
UniqueUserID userID
deriving Show
|]
| bgwines/hueue | src/DataStore/Token.hs | bsd-3-clause | 540 | 0 | 7 | 134 | 53 | 34 | 19 | 11 | 0 |
module Util.Cabal ( prettyVersion
, prettyPkgInfo
, parseVersion
, parsePkgInfo
, executableMatchesCabal
) where
import Distribution.Version (Version(..), withinRange)
import Distribution.Package (PackageName(..), Dependency(..), PackageIdentifier(..))
import Distribution.Compat.ReadP (readP_to_S)
import Distribution.Text (parse, Text)
import Distribution.PackageDescription (condTreeConstraints, condExecutables, GenericPackageDescription)
import Data.Char (isSpace)
import Data.List (isPrefixOf, intercalate)
-- render Version to human and ghc-pkg readable string
prettyVersion :: Version -> String
prettyVersion (Version [] _) = ""
prettyVersion (Version numbers _) = intercalate "." $ map show numbers
-- render PackageIdentifier to human and ghc-pkg readable string
prettyPkgInfo :: PackageIdentifier -> String
prettyPkgInfo (PackageIdentifier (PackageName name) (Version [] _)) = name
prettyPkgInfo (PackageIdentifier (PackageName name) version) =
name ++ "-" ++ prettyVersion version
parseVersion :: String -> Maybe Version
parseVersion = parseCheck
parseCheck :: Text a => String -> Maybe a
parseCheck str =
case [ x | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
[x] -> Just x
_ -> Nothing
parsePkgInfo :: String -> Maybe PackageIdentifier
parsePkgInfo str | "builtin_" `isPrefixOf` str =
let name = drop (length "builtin_") str -- ghc-pkg doesn't like builtin_ prefix
in Just $ PackageIdentifier (PackageName name) $ Version [] []
| otherwise = parseCheck str
executableMatchesCabal :: String -> Version -> GenericPackageDescription -> Bool
executableMatchesCabal executable cabalVersion pkgDescr =
case lookup executable $ condExecutables pkgDescr of
Nothing -> False
Just depGraph ->
let deps = condTreeConstraints depGraph
isCabalDep (Dependency (PackageName name) _) = name == "Cabal"
cabalDeps = filter isCabalDep deps
matchesDep (Dependency _ versionRange) = cabalVersion `withinRange` versionRange
in all matchesDep cabalDeps
| Paczesiowa/hsenv | src/Util/Cabal.hs | bsd-3-clause | 2,201 | 0 | 16 | 498 | 587 | 309 | 278 | 41 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-|
Module : $Header$
Copyright : (c) 2015 Swinburne Software Innovation Lab
License : BSD3
Maintainer : Shannon Pace <[email protected]>
Stability : unstable
Portability : portable
Client for Aegle API consuming machine resource data.
-}
module Eclogues.Monitoring.Monitor (slaveResources, followAegleMaster) where
import Eclogues.Monitoring.Cluster (Cluster, NodeResources (..))
import qualified Aegle.API as A
import Control.Concurrent.AdvSTM (AdvSTM, atomically, newTVar, readTVar)
import Control.Lens ((^.), view)
import Control.Monad (join)
import Control.Monad.Trans.Either (EitherT)
import qualified Data.HashMap.Lazy as HM
import Data.Maybe (catMaybes)
import Data.Proxy (Proxy (..))
import Database.Zookeeper (ZKError)
import Database.Zookeeper.Election (followLeaderInfo)
import Database.Zookeeper.ManagedEvents (ManagedZK)
import Servant.API ((:<|>) ((:<|>)))
import Servant.Client (client)
import Servant.Common.BaseUrl (BaseUrl (..), Scheme (Http))
import Servant.Common.Req (ServantError)
toNodeRes :: A.Resources -> Maybe NodeResources
toNodeRes res = NodeResources <$> res ^. A.disk
<*> res ^. A.ram
<*> res ^. A.cpu
slaveResources :: BaseUrl -> EitherT ServantError IO Cluster
slaveResources host = toCluster <$> getRes [] ["mesos-slave"]
where
(_ :<|> getRes :<|> _) = client (Proxy :: Proxy A.API) host
toCluster = catMaybes . fmap (toNodeRes . view A.total) . HM.elems
-- | Follow the elected Aegle master asynchronously. Returns an IO action to
-- run until a Zookeeper error occurs. Master details available via an 'AdvSTM'
-- action.
followAegleMaster :: ManagedZK -> IO (IO ZKError, AdvSTM (Maybe BaseUrl))
followAegleMaster zk = do
var <- atomically $ newTVar Nothing
let followThread = followLeaderInfo zk A.zkNode var
pure (followThread, getUrl var)
where
getUrl var = fmap toURI . (A.parseZKData =<<) . join <$> readTVar var
toURI (host, port) = BaseUrl Http host (fromIntegral port)
| futufeld/eclogues | eclogues-impl/app/api/Eclogues/Monitoring/Monitor.hs | bsd-3-clause | 2,105 | 0 | 13 | 381 | 531 | 303 | 228 | 34 | 1 |
-- | This module provides the 'Processor' type.
-- 'Processor' instances define transformations from problems to a (possible empty) set of subproblems.
module Tct.Core.Data.Processor
( Processor (..)
, Return (..)
, Fork
, ProofData
, CertificateFn
, apply
-- * Proof node construction.
, abortWith
, succeedWith
, succeedWith0
, succeedWith1
, succeedWithId
) where
import Tct.Core.Common.Error (catchError)
import qualified Tct.Core.Common.Pretty as PP
import qualified Tct.Core.Data.Forks as F
import Tct.Core.Data.Types
-- | Applies a processor. Transforms the result of an application, 'Return', to a 'ProofTree'.
-- Always creates a node.
apply :: (Processor p) => p -> In p -> TctM (ProofTree (Out p))
apply p i = (toProofTree <$> execute p i) `catchError` handler
where
toProofTree (NoProgress (SomeReason r)) = (Failure $ Failed p i r)
toProofTree (Progress pn cf ts) = Success (ProofNode p i pn) cf ts
handler = return . Failure . IOError
-- | Constructs a proof node with the given proof, certificate and output problems.
-- For a more general version, ie. if you want to provide proof trees instead of output problems, use 'Progress' and
-- 'NoProgress'.
succeedWith :: Processor p => ProofObject p -> CertificateFn p -> Forking p (Out p) -> TctM (Return p)
succeedWith pn cfn ts = return $ Progress pn cfn (Open <$> ts)
-- | Provide a judgement.
succeedWith0 :: (Processor p, Forking p ~ F.Judgement) => ProofObject p -> CertificateFn p -> TctM (Return p)
succeedWith0 pn cfn = return (Progress pn cfn F.Judgement)
-- | Succeed with a single child.
succeedWith1 :: (Processor p, Forking p ~ F.Id) => ProofObject p -> CertificateFn p -> Out p -> TctM (Return p)
succeedWith1 pn cfn p = return $ Progress pn cfn (F.toId $ Open p)
-- | Succeed with a single child such that the corresponding is complexity reflecting.
succeedWithId :: (Processor p, Forking p ~ F.Id) => ProofObject p -> Out p -> TctM (Return p)
succeedWithId pn p = return $ Progress pn F.fromId (F.toId $ Open p)
-- | Abort with a reason.
abortWith :: (Show r, PP.Pretty r) => r -> TctM (Return p)
abortWith = return . NoProgress . SomeReason
| ComputationWithBoundedResources/tct-core | src/Tct/Core/Data/Processor.hs | bsd-3-clause | 2,204 | 0 | 12 | 443 | 634 | 337 | 297 | 31 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
module Message where
import Data.Data
import Data.Typeable
import Network
import Data.Aeson
import System.IO(Handle, hFlush, hPutChar)
import qualified Data.Aeson.Generic as GJ
import Domain
import Render
import Log
import Missile
import MissileLogic
import GameLogic
import Json
handleMessage :: State -> Handle -> RendererCommunication -> [Char] -> Value -> IO (State)
handleMessage state h channel "gameIsOn" boardJson = do
let board = fromOk $ GJ.fromJSON boardJson :: Board
newBoardHistory = take 5 $ board : (boardHistory state)
oldDirection = lastDirection $ head $ commandHistory $ state
calculationResults = calculateDirection (State newBoardHistory (commandHistory state) oldMissiles launched)
newDirection = direction calculationResults
lastMessageTime = time board
oldCommandHistory = commandHistory state
oldMissiles = missiles state
velocity = ballVelocity newBoardHistory
wayPointsWithBall = reverse $ (ballCoordinates board : (reverse $ wayPoints calculationResults))
launched = removeMissedMissiles lastMessageTime (boardWidth board) (launchedMissiles state)
logStatistics board
rendererCommunication <- channel
rendererCommunication (Message lastMessageTime launched wayPointsWithBall board)
newmissiles <- sendmissile h board velocity wayPointsWithBall oldMissiles
result <- sendmessage h oldCommandHistory lastMessageTime oldDirection newDirection
case result of Just(command) -> return $ State newBoardHistory (take 100 $ command : oldCommandHistory) newmissiles launched
Nothing -> return $ State newBoardHistory (commandHistory state) newmissiles launched
handleMessage state h channel "missileReady" missilesJson = do
let missile = fromOk $ GJ.fromJSON missilesJson :: Missile
logMissilesReady missile
return (State (boardHistory state) (commandHistory state) (missile : (missiles state)) (launchedMissiles state))
handleMessage state h channel "missileLaunched" launchedJson = do
let newLaunch = fromOk $ GJ.fromJSON launchedJson :: MissileLaunched
logMissilesLaunched newLaunch
return (State (boardHistory state) (commandHistory state) (missiles state) (newLaunch : (launchedMissiles state)))
handleMessage state h channel "gameStarted" playersJson = do
logGameStart playersJson
return emptyState
handleMessage state h channel "gameIsOver" winnerJson = do
logGameEnd winnerJson
return emptyState
handleMessage state h channel anyMessage json = do
logUnknown anyMessage json
return state
fromOk (Success x) = x
sendmessage :: Handle -> CommandHistory -> Int -> Float -> Float -> IO( Maybe(Command))
sendmessage h commandHistory lastMessageTime oldDirection newDirection = do
let directionChanged = abs(oldDirection - newDirection) > 0.1
commandsInLastSec = length $ filter (duringLastSec lastMessageTime) commandHistory
doSend = directionChanged && (commandsInLastSec < 10)
case doSend of
True -> do
send h "changeDir" newDirection
return (Just(Command lastMessageTime newDirection))
False -> do
return (Nothing)
where
duringLastSec :: Int -> Command -> Bool
duringLastSec newest current = abs(newest - (timestamp current)) < 1100
| timorantalaiho/pong11 | src/Message.hs | bsd-3-clause | 3,330 | 0 | 16 | 610 | 935 | 463 | 472 | 66 | 2 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Astro.Trajectory
( Trajectory, startTime, endTime, ephemeris, ephemeris', datum
, Datum
) where
import Astro.Time
import Astro.Orbit.MEOE
import Numeric.Units.Dimensional.Prelude
import Data.Maybe (listToMaybe)
import qualified Prelude
-- | A @Trajectory@ is an abstraction for a position-velocity
-- path through space in a particular time window.
class (Fractional a, Ord a) => Trajectory x t a
where
-- | The earliest epoch at which this trajectory is valid.
startTime :: x t a -> E t a
-- | The last epoch at which this trajectory is valid.
endTime :: x t a -> E t a
-- | Produce an ephemeris with the given epochs.
-- The list of epochs must be increasing. If two identical
-- epochs are encountered behaviour is unspecified (one or
-- two data may be produced for that epoch).
-- Epochs outside the span of validity of the trajectory are ignored.
ephemeris :: x t a -> [E t a] -> [Datum t a]
-- | @ephemeris' traj t0 t1 dt@ produces an ephemeris starting
-- at @t0@ with data every @dt@ until @t1@. A datum at @t1@
-- is produced only if @(t1 - t0) / dt@ is an integer.
-- Epochs outside the span of validity of the trajectory are ignored.
ephemeris' :: x t a -> E t a -> E t a -> Time a -> [Datum t a]
ephemeris' x t0 t1 dt = ephemeris x ts
where
ts = takeWhile (<= t1) $ iterate (`addTime` dt) t0
-- | @datum traj t@ produces a datum at the time @t@, if the
-- trajectory is valid for time @t@.
datum :: x t a -> E t a -> Maybe (Datum t a)
datum x = listToMaybe . ephemeris x . return
| bjornbm/astro | src/Astro/Trajectory.hs | bsd-3-clause | 1,650 | 0 | 12 | 406 | 325 | 178 | 147 | 18 | 0 |
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-}
module Scoring (
UserScore(..),
emptyScore,
userScore,
addScore,
GroupScore(..),
scoreGroup,
groupScore,
renderGroups,
renderScores
) where
import Data.Data (Data)
import Data.Function (on)
import Data.List (sort)
import qualified Data.Map as M
import Data.Maybe (mapMaybe)
import qualified Data.Text as T
import Data.Time.Calendar (Day, fromGregorian)
import Data.Time.Clock (utctDay)
import Data.Typeable
import Prelude as P
import Text.Blaze.Html5 hiding (map, head)
--import qualified Text.Blaze.Html5 as H
import Text.Blaze.Html5.Attributes hiding (title, rows, accept, name, id)
--import qualified Text.Blaze.Html5.Attributes as A
import Strava (RideDetails(..))
rideMiles :: RideDetails -> Double
rideMiles = (*0.00062137119) . rideDistance
data UserScore = UserScore {
uid :: !Integer,
name :: !T.Text,
miles :: !Double,
days :: !Int,
rides :: !Int,
currentDay :: !Day,
currentMiles :: !Double,
currentRide :: !Integer
} deriving (Data, Eq, Show, Typeable)
emptyScore :: Integer -> T.Text -> UserScore
emptyScore myuid n = UserScore myuid n 0 0 0 (fromGregorian 0 0 0) 0 0
userScore :: UserScore -> Int
userScore score = 10 * days score + floor (miles score)
instance Ord UserScore where
compare = compare `on` (\u -> (userScore u, uid u))
addScore :: UserScore -> RideDetails -> UserScore
addScore score ride
| currentDay score /= utctDay (rideStart ride)
= addDay $ addMileage $ score { currentDay = utctDay $ rideStart ride, currentMiles = 0 }
| otherwise
= (if (currentMiles score < 1) then addDay else id) $ addMileage $ score
where
addMileage :: UserScore -> UserScore
addMileage s = s {
rides = rides s + 1,
miles = miles s + rideMiles ride,
currentMiles = currentMiles s + rideMiles ride,
currentRide = if (rideID ride > currentRide s) then rideID ride else currentRide s }
addDay :: UserScore -> UserScore
addDay s = if (currentMiles s >= 1) then s { days = days s + 1 } else s
data GroupScore = GroupScore {
gid :: Integer,
gname :: T.Text,
gscores :: [UserScore]
} deriving (Data, Eq, Typeable)
groupScore :: GroupScore -> Int
groupScore = sum . P.map userScore . gscores
instance Ord GroupScore where
compare = compare `on` (\g -> (groupScore g, gid g))
scoreGroup :: M.Map Integer UserScore -> ((T.Text, Integer), [(T.Text, Integer)]) -> GroupScore
scoreGroup scoreMap ((myname, gid'), members) = GroupScore gid' myname $
mapMaybe (flip M.lookup scoreMap . snd) members
renderScores :: [UserScore] -> Html
{-
renderScores scores = table $ do
tr $ do
th ""
th "Name"
th "Points"
mapM_ row $ zip [1..] $ reverse $ sort scores
where
row :: (Int, UserScore) -> Html
row (points, us) = tr $ do
td $ do
toHtml points
": "
td $ a ! href (toValue $ "http://app.strava.com/athletes/" ++ (show $ uid us)) $ toHtml $ name us
td $ toHtml $ userScore us
-}
renderScores scores = ol $ do
mapM_ row $ reverse $ sort scores
where
row us = li $ do
a ! href (toValue $ "http://app.strava.com/athletes/" ++ (show $ uid us)) $ toHtml $ name us
_ <- ": "
td $ toHtml $ userScore us
_ <- " points ("
toHtml (days us)
_ <- " days, "
toHtml (floor $ miles us :: Int)
" miles)"
renderGroups :: [GroupScore] -> Html
renderGroups groups = ol $ mapM_ groupHtml $ reverse $ sort groups
where
groupHtml :: GroupScore -> Html
groupHtml gs = li $ do
a ! href (toValue $ "http://app.strava.com/clubs/" ++ (show $ gid gs)) $ toHtml $ gname gs
_ <- ": "
toHtml (groupScore gs)
_ <- " points ("
toHtml ((floor :: Double -> Int) $ sum $ map miles $ gscores gs)
_ <- " miles) "
renderScores (gscores gs)
| ronwalf/ba-winter-challenge | src/Scoring.hs | bsd-3-clause | 3,950 | 0 | 18 | 1,006 | 1,244 | 669 | 575 | 107 | 4 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE DeriveDataTypeable #-}
-- | This module provides 'CtlStream', a data type that is a wrapper
-- around any 'ChunkData' type that allows control requests to be
-- interspersed with data. It is useful to construct 'Iter's and
-- 'Inum's on 'CtlStream' types if upstream enumerators need to send
-- control requests such as flush indicators (or maybe sendfile) to
-- downstream iteratees.
module Data.IterIO.CtlStream
(CtlStream (..), csData, csCtl
, inumToCS, inumFromCS
, cschunkI
) where
import Prelude hiding (null)
import Data.Typeable
import Data.Monoid
import Data.IterIO.Base
import Data.IterIO.Inum
-- | A @CtlStream@ is a stream of data of type @t@ interspersed with
-- control requests of type @d@. Each non-empty @CtlStream@ consists
-- of data or control requests followed by another @CtlStream@.
data CtlStream t d = CSData !t (CtlStream t d)
-- ^ Data in the stream. Invariants: @t@ must
-- always be non-null and the next @CtlStream@ must
-- never be of type @CSData@.
| CSCtl !d (CtlStream t d)
-- ^ A control request.
| CSEmpty
-- ^ An empty stream with no data or control requests.
deriving (Show, Typeable)
-- | Construct a 'CtlStream' given some data.
csData :: (ChunkData t) => t -> CtlStream t d
csData t | null t = CSEmpty
| otherwise = CSData t CSEmpty
-- | Construct a 'CtlStream' given a control request.
csCtl :: d -> CtlStream t d
csCtl d = CSCtl d CSEmpty
csAppend :: (Monoid t) => CtlStream t d -> CtlStream t d -> CtlStream t d
csAppend a CSEmpty = a
csAppend CSEmpty b = b
csAppend (CSData ah CSEmpty) (CSData bh bt) = CSData (mappend ah bh) bt
csAppend (CSData ah at) b = CSData ah $ csAppend at b
csAppend (CSCtl ah at) b = CSCtl ah $ csAppend at b
instance (Monoid t) => Monoid (CtlStream t d) where
mempty = CSEmpty
mappend = csAppend
instance (ChunkData t, Show d) => ChunkData (CtlStream t d) where
null CSEmpty = True
null _ = False
chunkShow CSEmpty = "CSEmpty"
chunkShow (CSData t rest) = chunkShow t ++ "+" ++ chunkShow rest
chunkShow (CSCtl d rest) = show d ++ "+" ++ chunkShow rest
-- | Adapt an ordinary data stream into a 'CtlStream' by wrapping all
-- data in the 'CSData' constructor.
inumToCS :: (ChunkData t, Show d, Monad m) => Inum t (CtlStream t d) m a
inumToCS = mkInumM $ withCleanup pullup $ irepeat $ dataI >>= ifeed . csData
where pullup = ipopresid >>= ungetI . flatten
flatten (CSData h t) = mappend h $ flatten t
flatten (CSCtl _ t) = flatten t
flatten CSEmpty = mempty
-- | Return the next chunk of data or next control request in a
-- 'CtlStream'. On end of file, returns 'CSEmpty'. On any other
-- condition, returns a 'CtlStream' in which the tail is always
-- 'CSEmpty' and thus may be ignored.
cschunkI :: (ChunkData t, Show d, Monad m) =>
Iter (CtlStream t d) m (CtlStream t d)
cschunkI = chunkI >>= check
where check (Chunk (CSData h t) eof) = Done (csData h) (Chunk t eof)
check (Chunk (CSCtl h t) eof) = Done (csCtl h) (Chunk t eof)
check (Chunk CSEmpty True) = Done CSEmpty (Chunk mempty True)
check _ = cschunkI
-- | Strip control requests out of an input stream of type
-- 'CtlStream', to produce a stream of ordinary data.
inumFromCS :: (ChunkData t, Show d, Monad m) => Inum (CtlStream t d) t m a
inumFromCS = mkInumM $ withCleanup pullup $ irepeat $ cschunkI >>= feed
where pullup = ipopresid >>= ungetI . csData
feed (CSData t _) = ifeed t
feed (CSCtl _ _) = return False
feed CSEmpty = idone
| scslab/iterIO | Data/IterIO/CtlStream.hs | bsd-3-clause | 3,987 | 0 | 11 | 1,117 | 979 | 509 | 470 | 60 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE QuasiQuotes #-}
--------------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (C) 2014-2015 Samuli Thomasson
-- License : MIT (see the file LICENSE)
-- Maintainer : Samuli Thomasson <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- This application is used to automatically generate web page bodies listing
-- the available courses at the department of physics at the University of
-- Helsinki. The data is parsed from a confluence Wiki Source Table containing
-- the information needed to either directly generate the list or lookup more
-- information from different web sites.
--
-- The application takes into consideration internationalization ('I18N') for
-- at least Finnish, Swedish and English, more languages might be supported in
-- the future.
--
-- The user guide for operating the software can be found at
-- <https://github.com/SimSaladin/opetussivut>
--
-- See /config.yaml/ for configuration options.
--
--------------------------------------------------------------------------------
module Main where
import Control.Applicative
import Control.Concurrent.MVar
import Control.Monad
import Control.Monad.Reader
import Codec.Text.IConv (convert)
import Data.Char
import Data.Function (on)
import qualified Data.List as L
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Monoid ((<>))
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
-- The 'Data.Text.Lazy' imports are needed when streaming large quantities of
-- 'Text' data and you want to be efficient doing so.
import qualified Data.Text.Lazy as LT
import qualified Data.Text.Lazy.IO as LT
import qualified Data.Text.Lazy.Encoding as LT
import Data.Time
-- Used to load the settings file.
import qualified Data.Yaml as Yaml
import Network.HTTP.Conduit (simpleHttp)
import Text.Blaze.Html (preEscapedToHtml)
import Text.Blaze.Renderer.Text (renderMarkup)
import Text.Hamlet
import Text.Julius
import Text.Markdown
import Text.Regex
import qualified Text.XML as XML
import Text.XML.Cursor
import System.Directory
import System.Environment (getArgs)
import System.Exit (exitFailure)
import System.IO.Unsafe (unsafePerformIO)
import GHC.Generics
{- Used to print to the console, during some of the parsing... Other prints are
done through the IO monad with the @putStrLn@ function.
-}
import Debug.Trace
{- | The entry point of the application.
It reads the /config.yaml/ file into memory before doing anything else.
After that it access the page data of the selected page, either from cache
or from the Wiki Table based on the command line arguments used.
When the page data is fetched it starts the 'Table' generation by calling
the @'parseTable'@ function and later loops over the different 'Lang'uages
found in the /config.yaml/ page configuration section and renders a
different page body for each of the languages.
-}
main :: IO ()
main = do
putStrLn ("============================================================\n" ++
" Running Application\n" ++
"============================================================\n" ++
" * Decoding config.yaml")
Yaml.decodeFileEither "config.yaml" >>= either (error . show) (runReaderT go)
where
go = do
Config{..} <- ask
forM_ pages $ \pc@PageConf{..} -> do
liftIO $ putStrLn (" * Reading data from Wiki page ID: " ++ pageId)
pageData <- getData pageId
case pageData of
Nothing -> liftIO $ putStrLn "!!! Warning: failed to fetch doc, not updating the listings..."
Just pageData' -> do
table <- parseTable pageData'
forM_ languages $ \lang -> do
liftIO $ putStrLn (" * Language: " ++ show lang)
renderTable rootDir lang pc table
-- =============================================================================
-- * Types
-- =============================================================================
{- | Creates a monad that handles the assignment of the @Config@ type. It uses
the functionality of both the @Reader@ monad and the @IO@ monad.
@ReaderT@ monad transformer
@Config@ the return value of @ask@ function
@IO@ monad on which the @Reader@ acts.
By using this monad, one can read all values of type @Config@ and perform
IO actions.
-}
type M = ReaderT Config IO
{- | The 'Lang' type is used as key for looking up the translations from the
internationalization ('I18N') database found in the /config.yaml/ file.
It is used with acronyms of the languages: @fi@, @se@, @en@, ...
-}
type Lang = Text
{- | Properties for generating individual web page bodies.
The 'PageConf' data type is used as a data holder for page information
of the generated web pages. Where they are stored locally, what the page
title is etc.
-}
data PageConf = PageConf {
-- Department web page properties
pageId :: String -- ^ Wiki Table ID
, pageUrl :: Map Lang Text -- ^ Local path
, pageTitle :: Map Lang Text -- ^ Local title
} deriving Generic
instance Yaml.FromJSON PageConf
{- | Overall properties used by the module to generate HTML code from the
source 'Table' found in the wiki pages.
The 'Config' data type is used to read the configuration properties from
the /config.yaml/ file. It holds references to all of the different
property fields and are accessed by their name in the /config.yaml/ file.
The fields are filled with the type constructor of @Config@ by a call to
the @'ask'@ function through the @M@ monad.
-}
data Config = Config {
-- File handling properties
rootDir :: FilePath -- ^ Local file path (root).
, cacheDir :: FilePath -- ^ Local cache path.
, fetchUrl :: String -- ^ URL to all Wiki Tables.
, weboodiUrl :: Text -- ^ URL to all WebOodi pages.
, oodiNameFile :: FilePath -- ^ File for course name translations.
-- Page generation properties
, languages :: [Lang] -- ^ All supported 'Lang'uages (@fi@, @en@, @se@, etc).
, pages :: [PageConf] -- ^ References to the different subject pages.
-- Internationalization properties
, i18n :: I18N -- ^ Database with translations.
-- Wiki Table properties
, categoryLevel :: Int
, categories :: [[Text]] -- ^ List of lists of 'Category's (used to nest the categories for the 'Course's).
, columnHeaders :: ColumnHeader -- ^ The @columnHeaders@ section of the /config.yaml/ file.
, classCur :: Text -- ^ HTML class for showing if the course is available this year.
} deriving Generic
instance Yaml.FromJSON Config
{- | Source 'Table'. Consists of a time stamp, a list of 'Header's and a list
of 'Course's (the 'Course' objects are used as rows in the 'Table').
-}
data Table = Table UTCTime [Header] [Course]
deriving (Show, Read)
{- | Synonym of 'Text'. Used as column 'Header's when reading the source
'Table'.
-}
type Header = Text
{- | A row in source 'Table'. Each cell of the 'Table' row is mapped to a
'Header', and each cell can have multiple 'Category's coupled to it (see
'Category'). The 'ContentBlock' contains all the information read from the
Wiki Table for the specified 'Course'.
-}
type Course = ([Category], Map Header ContentBlock)
{- | Synonym of 'Text'. First column in source 'Table'. Each 'Course' can
have several 'Category's (eg. @Pääaineopinnot@, @Perusopinnot@,
@Pakolliset@, etc).
-}
type Category = Text
-- | @\<td\>@ HTML tag in source 'Table'. Used to fill the 'Course' row.
type ContentBlock = Text
{- | Internationalization database.
Map of a Finnish 'Text' phrase (fragment) to a list of 'Text's mapped to
'Lang'uages. This way it is easy to translate a specific Finnish phrase to
one of the supported 'Lang'uages.
By first looking up the Finnish phrase from the internationalization
('I18N') database, one gets a 'Map' of languages to translations (proper
error handling is needed to fallback when looking up a translation that
does not exist see @'toLang'@ for implementation). Then one will only have
to lookup up the desired language from the result.
> Map.lookup [Language] $ Map.lookup [Finnish phrase] [I18N database]
-}
type I18N = Map Text (Map Lang Text)
{- | ColumnHeader database.
The different properties found in the @columnHeaders@ section of the
/config.yaml/ file. All the functions for this property is very similar to
the functions of the 'I18N' type.
When adding more column headers remember to check out the helper functions
inside the function body of @'tableBody'@.
-}
type ColumnHeader = Map Text (Map Text Text)
-- =============================================================================
-- * Utility functions
-- =============================================================================
{- | Appends /.html/ to the end of the argument. It's mainly used as a helper
function when creating the body files locally, this way it's possible to
generate links between the different web pages.
-}
toUrlPath :: Text -- ^ The URL without /.html/.
-> Text -- ^ The URL with /.html/ at the end.
toUrlPath = (<> ".html")
{- | Prepends the argument with the value of the @root@ parameter, and appends
/.body/ to the end of the argument.
> root [arg] .body
The PHP-engine used on physics.helsinki.fi utilizes a own /.html/ file
extension (/.body/) to show HTML output in the center of the page.
-}
toFilePath :: FilePath -- ^ The root directory.
-> Text -- ^ The file name.
-> FilePath -- ^ @root/filename.body@.
toFilePath root = (root <>) . T.unpack . (<> ".body")
{-| A hack, because confluence HTML is far from the (strictly) spec.
WebOodi's HTML is just horrible (imo it's not even HTML), so we use another
regex to parse it (before the XML parser is used).
-}
regexes :: [String -> String] -- ^ A list of functions for removing HTML-tags
regexes = [ rm "<meta [^>]*>", rm "<link [^>]*>", rm "<link [^>]*\">", rm "<img [^>]*>"
, rm "<br[^>]*>", rm "<col [^>]*>" ]
where
rm s i = subRegex (mkRegexWithOpts s False True) i ""
{- | Fetch a translation from the 'I18N' database, found in /config.yaml/ under
the 'I18N' section.
If the 'Text' that is to be translated can't be found in the given database
it'll fall back on the given 'Text' (the Finnish version). If the selected
'Lang'uage in this case is not Finnish it will also warn the user that no
translation for the selected 'Text' can be found.
-}
toLang :: I18N -- ^ The 'I18N' database to fetch translations from.
-> Lang -- ^ The 'Lang'uage to fetch translation for.
-> Text -- ^ The 'Text' to translate.
-> Text -- ^ The translation of the input 'Text'.
toLang db lang key = maybe (trace ("!!! Warning: no i18n db for key `" ++ T.unpack key ++ "'") key)
(fromMaybe fallback . Map.lookup lang) (Map.lookup key db)
where
fallback | "fi" <- lang = key
| otherwise = trace ("!!! Warning: no i18n for key `" ++ T.unpack key ++ "' with lang `" ++ T.unpack lang ++ "'") key
{- | Access the 'ColumnHeader' information with name of the column and with a
key to the information desired.
Returns the value of the desired column information. If the column name
doesn't exist it'll show a warning in the output and an empty 'Text' is
returned instead.
-}
columnInfo :: ColumnHeader -- ^ The 'ColumnHeader' to look for information in.
-> Text -- ^ The column information to look for (see /config.yaml/ for alternatives).
-> Text -- ^ The column name to look for.
-> Text -- ^ The value of the column information.
columnInfo db key column = maybe (trace ("!!! Warning: no column in db with name `" ++ T.unpack column ++ "'") column)
(fromMaybe "" . Map.lookup key) (Map.lookup column db)
{- | Wrapper function to access the @title@ information of the @column@. Calls
the @'columnInfo'@ function with \"title\" as the desired information.
-}
columnTitle :: ColumnHeader -- ^ The 'ColumnHeader' to look for information in.
-> Text -- ^ The column name to look for.
-> Text -- ^ The value of the column information with key \"title\".
columnTitle db column = columnInfo db "title" column
{- | Wrapper function to access the @width@ information of the @column@. Calls
the @'columnInfo'@ functio with \"width\" as the desired information.
-}
columnWidth :: ColumnHeader -- ^ The 'ColumnHeader' to look for information in.
-> Text -- ^ The column name to look for.
-> Text -- ^ The value of the column information with key \"width\".
columnWidth db column = columnInfo db "width" column
{- | Lookup a translation from any given map, containing 'y' types mapped to
'Lang' types. It only returns 'Just' values of the result.
-}
lookupLang :: Lang -- ^ The 'Lang'uage to look for.
-> Map Lang y -- ^ A map to fetch type 'y' from.
-> y -- ^ The value of type 'y' found in the map.
lookupLang i = fromJust . Map.lookup i
{- | This function removes all extra whitespaces between words in the input
'Text' and removes some unwanted text from the input 'Text'.
First it creates a list of 'Text's by splitting the input 'Text' on all
newline characters, then it removes all extra whitespaces between the words
in all rows in the created list, after this it merges all the rows into one
'Text' object separated by space characters.
It then replaces some unwanted text on the combined 'Text' object and
removes some unwanted text completely (cells only containing ' ', ',', '-'
or '!' characters).
-}
normalize :: Text -- ^ The 'Text' to normalize.
-> Text -- ^ The normalized 'Text'.
normalize =
T.dropAround (`elem` " ,-!")
. T.replace "ILMOITTAUTUMINEN PUUTTUU" ""
. T.unwords . map (T.unwords . T.words) . T.lines
-- =============================================================================
-- * Weboodi stuff
-- =============================================================================
{- | Fetch the 'Course' name from the WebOodi URL. It looks for a HTML tag
containing the text @tauluotsikko\"?>@ to find the name of the 'Course'. It
then replaces some sub strings in the 'Course' name with Unicode characters.
-}
getOodiName :: Text -- ^ 'Text' containing a raw version of the 'Course' name.
-> Maybe Text -- ^ The Unicode formatted version of the 'Course' name.
getOodiName =
fmap (T.pack
. sub "å" "å"
. sub "Å" "Å"
. sub "ä" "ä"
. sub "Ä" "Ä"
. sub "ö" "ö"
. sub "Ö" "Ö"
. sub ":" ":"
. sub "'" "'"
. sub "(" "("
. sub ")" ")"
. sub ";" ";"
. head) . matchRegex (mkRegexWithOpts s True False) . T.unpack
where
s = "tauluotsikko\"?>[0-9 ]*(.*),[^,]*<"
sub a b i = subRegex (mkRegexWithOpts a False True) i b
-- TODO: Move this into the 'webOodiLink' function
{- | Helper method to select the correct 'Lang'uage when using WebOodi. The
'Lang'uage is changed by switching a number in the URL:
* 1 : fi (Finnish version)
* 2 : se (Swedish version)
* 6 : en (English version)
If another 'Lang'uage than the provided ones is used, the function returns
an empty 'String' instead of a 'Num'ber.
-}
weboodiLang :: Lang -- ^ The 'Lang' to use on WebOodi.
-> Text -- ^ A 'Text' string consisting of the number to switch to in the WebOodi URL.
weboodiLang lang
| "fi" <- lang = "1"
| "se" <- lang = "2"
| "en" <- lang = "6"
| otherwise = ""
{- | Creates a hyperlink to use for accessing the selected 'Lang'uage version
of WebOodi. This webpage is later used to access translations for the
different course names, when altering the language on the course listing.
The return value has the form of:
<https://weboodi.helsinki.fi/hy/opintjakstied.jsp?html=1&Kieli=&Tunniste=[page ID]>.
-}
weboodiLink :: Text -- ^ The base URL of WebOodi.
-> Lang -- ^ Language to use on WebOodi.
-> Text -- ^ WebOodi page ID.
-> Text -- ^ The concatenated URL.
weboodiLink url lang pageId = url <> weboodiLang lang <> "&Tunniste=" <> pageId
{- | This is a helper function that gives a 'MVar' variable with a @('Lang',
[WebOodi code])@ mapped to a course name (for that specific 'Lang'uage).
This function is used when accessing the /oodi.names/ file for course name
translations. The /oodi.names/ file is generated from accessing the WebOodi
web page during the fetching process.
Initially the 'MVar' is empty. The 'MVar' variable in this case is used to
only have to fill the value once (when reading one of the languages), to
save computation time.
-}
oodiVar :: MVar (Map (Lang, Text) Text) -- ^ A 'MVar' containing a 'Map' between a @('Lang', [WebOodi code])@ and a @[Course name]@.
oodiVar = unsafePerformIO newEmptyMVar
{-# NOINLINE oodiVar #-}
{- If one is using the @unsafePerformIO@ function like this, it is
recommended to use the @NOINLINE@ pragma on the function to
prevent the compiler from adding it everywhere in the compiled code.
-}
{- | Read the course names from the @oodiNameFile@.
Helper function for reading the @oodiNameFile@ to get translations for the
course names. If the file can't be found it'll return an empty map.
If the file exists this function returns a 'Map' of translations for the
different 'Course' names, otherwise it'll return an empty 'Map'.
-}
readOodiNames :: M (Map (Lang, Text) Text) -- ^ A 'Map' of all the WebOodi translations.
readOodiNames = do
Config{..} <- ask
exists <- liftIO $ doesFileExist oodiNameFile
if exists
then liftIO $ read <$> readFile oodiNameFile
else return Map.empty
-- TODO: Check what this method does, step by step.
{- | Get a translated name for a specific 'Course', by looking it up from
WebOodi.
-}
i18nCourseNameFromOodi :: Lang -- ^ The 'Lang'uage to lookup.
-> Text -- ^ The WebOodi page ID.
-> M (Maybe Text) -- ^ The translation if found.
i18nCourseNameFromOodi lang pageId = do
Config{..} <- ask
ov <- liftIO $ tryTakeMVar oodiVar
oodiNames <- case ov of
Just x -> return x
Nothing -> readOodiNames
liftIO $ putMVar oodiVar oodiNames
case Map.lookup (lang, pageId) oodiNames of
Just name -> return $ Just name
Nothing -> do
raw <- liftIO $ fetch8859 (T.unpack $ weboodiLink weboodiUrl lang pageId)
case getOodiName raw of
Nothing -> return Nothing
Just name -> do
let newNames = Map.insert (lang, pageId) name oodiNames
liftIO $ do _ <- swapMVar oodiVar newNames
writeFile oodiNameFile (show newNames)
return $ Just name
{- | Reads the web page at the given URL and returns a utf-8 converted version
of the page. WebOodi is encoded in iso-8859-1 encoding.
-}
fetch8859 :: String -- ^ URL with iso-8859-1 encoding.
-> IO Text -- ^ The web page converted to utf-8.
fetch8859 url = LT.toStrict . LT.decodeUtf8 . convert "iso-8859-1" "utf-8" <$> simpleHttp url
-- =============================================================================
-- * Rendering
-- =============================================================================
-- | Create the final HTML version of the web page from the cached one.
renderTable :: FilePath -- ^ The root to where the HTML file should be saved.
-> Lang -- ^ The currently used language.
-> PageConf -- ^ More specific information of the current web page being created.
-> Table -- ^ The source table to use when creating the web page
-> M () -- ^ ReaderT Config IO, from the generated HTML file.
renderTable root lang pc@PageConf{..} table =
ask >>= lift . LT.writeFile fp . renderMarkup . tableBody lang pc table
where
fp = toFilePath root $ lookupLang lang pageUrl
-- =============================================================================
-- * Content
-- =============================================================================
{- | How to render the data of the selected 'Table' into HTML using WebOodi to
lookup course names in different languages.
-}
tableBody :: Lang -- ^ The currently used 'Lang'uage.
-> PageConf -- ^ More specific information of the current web page being created.
-> Table -- ^ The source 'Table' to use when creating the web page.
-> Config -- ^ 'Config'uration containing specific information about the source 'Table' and translation data.
-> Html -- ^ The generated HTML code.
tableBody lang page (Table time _ tableContent) cnf@Config{..} =
let
-- | Helper function to get the 'I18N' translation of the input.
i18nTranslationOf :: Text -- ^ The 'Text' to translate.
-> Text -- ^ Translation of the input.
i18nTranslationOf = toLang i18n lang
{- | Overriding the translations for some 'String's, for usage with the
/periodi/ column of the 'Table'.
-}
i18nTranslationOfPeriod :: Text -- ^ The cell content to be translated.
-> Text -- ^ The translation.
i18nTranslationOfPeriod cell
| "?" <- cell = cell
| "I" <- cell = cell
| "I-II" <- cell = cell
| "I-III" <- cell = cell
| "I-IV" <- cell = cell
| "I, III" <- cell = cell
| "II" <- cell = cell
| "II-III" <- cell = cell
| "II-IV" <- cell = cell
| "II, IV" <- cell = cell
| "III" <- cell = cell
| "III-IV" <- cell = cell
| "IV" <- cell = cell
| "" <- cell = cell
-- If non of the above \"exceptions\" is found in the listing,
-- the cell content will be translated.
| otherwise = i18nTranslationOf cell
-- | Helper method to fetch a translation of the 'Course' name
translateCourseName :: Text -- ^ WebOodi course code.
-> Maybe Text -- ^ Translation of the 'Course' name.
translateCourseName code = unsafePerformIO $
runReaderT (i18nCourseNameFromOodi lang code) cnf
-- Helper functions to access the different column header properties
colTitle col = columnTitle columnHeaders col
colCodeTitle = colTitle "colCode"
colCourseNameTitle = colTitle "colCourseName"
colPeriodTitle = colTitle "colPeriod"
colRepeatsTitle = colTitle "colRepeats"
colLangTitle = colTitle "colLang"
colWebsiteTitle = colTitle "colWebsite"
colWidth col = columnWidth columnHeaders col
colCodeWidth = colWidth "colCode"
colCourseNameWidth = colWidth "colCourseName"
colPeriodWidth = colWidth "colPeriod"
colRepeatsWidth = colWidth "colRepeats"
colLangWidth = colWidth "colLang"
colWebsiteWidth = colWidth "colWebsite"
------------------------------------------------------------------------
-- course table
------------------------------------------------------------------------
{- | Function for generating the nested @\<div.courses\>@ HTML-tags.
If the maximum number of @categories@ that can be nested not is
reached it'll continue trying to add 'Category' titles until the
maximum is reached. After that the 'Table' row is created.
-}
courseTable n rows
| n < length categories = withCat n rows $ courseTable (n + 1)
| otherwise =
[shamlet|
<table>
$forall c <- rows
<tr data-taso="#{fromMaybe "" $ catAt cnf categoryLevel c}"
data-kieli="#{getCellContent colLangTitle c}"
data-lukukausi="#{getCellContent "lukukausi" c}"
data-pidetaan="#{getCellContent "pidetään" c}">
<td style="width:#{colCodeWidth}">
<a href="#{weboodiLink weboodiUrl lang $ getCellContent colCodeTitle c}">
<b>#{getCellContent colCodeTitle c}
<td style="width:#{colCourseNameWidth}">
$maybe name <- translateCourseName (getCellContent colCodeTitle c)
#{name}
$nothing
#{getCellContent colCourseNameTitle c}
$with op <- getCellContent "op" c
$if not (T.null op)
\ (#{op} #{i18nTranslationOf "op"})
<td.compact style="width:#{colPeriodWidth}" title="#{getCellContent colPeriodTitle c}">#{i18nTranslationOfPeriod $ getCellContent colPeriodTitle c}
<td.compact style="width:#{colRepeatsWidth}" title="#{getCellContent colRepeatsTitle c}">#{getCellContent colRepeatsTitle c}
<td.compact style="width:#{colLangWidth};font-family:monospace" title="#{getCellContent colLangTitle c}">
$case T.words (getCellContent colLangTitle c)
$of []
$of rows
<b>#{head rows}
$if null $ tail rows
$else
(#{T.intercalate ", " $ tail rows})
<td.compact style="width:#{colWebsiteWidth}" title="#{colWebsiteTitle}">
$maybe p <- getCellContentMaybe colWebsiteTitle c
$if not (T.null p)
\ #
<a href="#{p}">#{i18nTranslationOf colWebsiteTitle}
|]
------------------------------------------------------------------------
-- if it begins with a number, apply appropriate header
------------------------------------------------------------------------
{- | Helper function to select the correct HTML-header tag for the
current 'Category'.
-}
catHeader n category =
[shamlet|
$case n
$of 0
<h1>
#{translation}
$of 1
<h2>
#{translation}
$of 2
<h3>
<i>#{translation}
$of 3
<h4>
#{translation}
$of 4
<h5>
#{translation}
$of 5
<h6>
#{translation}
$of _
<b>
#{translation}
|]
where
translation = i18nTranslationOf category
------------------------------------------------------------------------
-- course category div
------------------------------------------------------------------------
{- | Helper function to select if the HTML-header should be added or if
the content @\<div.courses\>@ tags should nested deeper.
Group the 'Table' rows into lists of 'Table' rows based on the
'Category' they belong to. Then loop over all 'Category' based
lists to generate the different listings.
-}
withCat n rows f =
[shamlet|
$forall groupedRows <- L.groupBy (catGroup cnf n) rows
<div.courses>
$maybe category <- catAt cnf n (head groupedRows)
#{catHeader n category}
#{f groupedRows}
|]
------------------------------------------------------------------------
-- put everything together
------------------------------------------------------------------------
in [shamlet|
\<!-- title: #{lookupLang lang $ pageTitle page} -->
\<!-- fi (Suomenkielinen versio): #{toUrlPath $ lookupLang "fi" $ pageUrl page} -->
\<!-- se (Svensk version): #{toUrlPath $ lookupLang "se" $ pageUrl page} -->
\<!-- en (English version): #{toUrlPath $ lookupLang "en" $ pageUrl page} -->
\
\<!-- !!! IMPORTANT !!! -->
\<!-- THIS PAGE IS GENERATED AUTOMATICALLY - DO NOT EDIT DIRECTLY! -->
\<!-- See https://github.com/SimSaladin/opetussivut for information on how to edit instead -->
\
<p>
$with pg <- head pages
<a href="#{toUrlPath $ lookupLang lang $ pageUrl pg}">#{lookupLang lang $ pageTitle pg}
$forall pg <- tail pages
|
<a href="#{toUrlPath $ lookupLang lang $ pageUrl pg}">#{lookupLang lang $ pageTitle pg}
#{markdown def $ LT.fromStrict $ i18nTranslationOf "aputeksti"}
<div>
<div.buttons>
#{i18nTranslationOf "Kieli"}:
<select id="select-kieli" name="kieli" onchange="updateList(this)">
<option value="any">#{i18nTranslationOf "Kaikki"}
$forall l <- languages
<option value="#{l}">#{i18nTranslationOf l}
#{i18nTranslationOf "Taso"}:
<select id="select-taso" name="taso" onchange="updateList(this)">
<option value="any">#{i18nTranslationOf "Kaikki"}
$forall cat <- (categories !! categoryLevel)
<option value="#{cat}">#{i18nTranslationOf cat}
#{i18nTranslationOf "Lukukausi"}:
<select id="select-lukukausi" name="lukukausi" onchange="updateList(this)">
<option value="any" >#{i18nTranslationOf "Kaikki"}
<option value="syksy" >#{i18nTranslationOf "Syksy"}
<option value="kevät" >#{i18nTranslationOf "Kevät"}
<option value="kesä" >#{i18nTranslationOf "Kesä"}
<div.headers>
<table style="width:100%">
<tr>
<td style="width:#{colCodeWidth}">#{i18nTranslationOf colCodeTitle}
<td style="width:#{colCourseNameWidth}">#{i18nTranslationOf colCourseNameTitle}
<td style="width:#{colPeriodWidth}" >#{i18nTranslationOf colPeriodTitle}
<td style="width:#{colRepeatsWidth}" >#{i18nTranslationOf colRepeatsTitle}
<td style="width:#{colLangWidth}" >#{i18nTranslationOf colLangTitle}
<td style="width:#{colWebsiteWidth}">#{i18nTranslationOf colWebsiteTitle}
#{courseTable 0 $ tableContent}
<p>
#{i18nTranslationOf "Päivitetty"} #{show time}
<style>
.buttons {
padding:1em;
}
.headers table {
width:100%;
table-layout:fixed;
}
.courses table {
width:100%;
table-layout:fixed;
}
.courses td.compact {
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
tr[data-pidetaan="next-year"] {
color:gray;
}
<script type="text/javascript">
#{preEscapedToHtml $ renderJavascript $ jsLogic undefined}
|]
{- | Creating the javascript functions of the buttons in the HTML files. Select
only a specific 'Lang'uage, only a specific level etc.
-}
jsLogic :: JavascriptUrl url -- ^ A link to the different scripts.
jsLogic = [julius|
window.history.navigationMode = "compatible";
fs = { };
updateList = function(e) {
var name = e.getAttribute("name");
var opts = e.selectedOptions;
fs[name] = [];
for (var i = 0; i < opts.length; i++) {
fs[name].push(opts[i].getAttribute("value"));
}
var xs = document.querySelectorAll(".courses tr");
for (var i = 0; i < xs.length; i++) {
xs[i].hidden = !matchesFilters(fs, xs[i]);
}
updateHiddenDivs();
}
matchesFilters = function(fs, thing) {
for (var f in fs) {
if (fs[f] != "any") {
var m = false;
for (var i = 0; i < fs[f].length; i++) {
if (thing.dataset[f].indexOf(fs[f][i]) > -1) {
m = true;
break;
}
}
if (!m) return false;
}
}
return true;
}
updateHiddenDivs = function() {
var xs = document.querySelectorAll(".courses");
for (var i = 0; i < xs.length; i++) {
var hidden = true;
var ts = xs[i].getElementsByTagName("tr");
for (var j = 0; j < ts.length; j++) {
if (!ts[j].hidden) {
hidden = false;
break;
}
}
xs[i].hidden = hidden;
}
}
onload = function(){
setDefaultSelectedValues();
}
setDefaultSelectedValues = function() {
document.getElementById("select-kieli").value = "any";
document.getElementById("select-taso").value = "any";
document.getElementById("select-lukukausi").value = "any";
}
|]
-- =============================================================================
-- * Get source
-- =============================================================================
{- | This function handles the command line arguments for caching and fetching
the wiki tables.
Fetch a confluence doc (wiki page) by id. This function reads the wiki page
with the given page ID, and parses it as an XML-document. The result is
cleaned with the @'regexes'@ function.
It returns the stripped HTML document in XML-format, if it can find the
currently selected Wiki page, otherwise it returns 'Nothing'.
-}
getData :: String -- ^ The page ID.
-> M (Maybe XML.Document) -- ^ The cleaned XML-document, if found any.
getData pageId = do
Config{..} <- ask
xs <- lift getArgs
let file = cacheDir <> "/" <> pageId <> ".html"
str <- lift $ case xs of
"cache" : _ -> Just <$> LT.readFile file
"fetch" : _ -> do
r <- LT.decodeUtf8 <$> simpleHttp (fetchUrl ++ pageId)
if "<title>Log In" `LT.isInfixOf` r
then do
liftIO $ putStrLn (" * Private Wiki Table - Can't read...")
return Nothing
else do
liftIO $ putStrLn (" * Writing to file: " ++ file)
LT.writeFile file r >> return (Just r)
_ -> putStrLn " * Usage: opetussivut <fetch|cache>" >> exitFailure
return $ cleanAndParse <$> str
{- | This function takes a whole wiki table in 'Text' form and removes some
standard HTML tags from the text (see @'regexes'@ for more information). It
then parses an XML document from the HTML body 'Text' stream.
Uses the @'XML.decodeHtmlEntities'@ setting to decode the 'LT.Text' into
XML.
-}
cleanAndParse :: LT.Text -- ^ The raw 'LT.Text' version of the cached wiki page.
-> XML.Document -- ^ The XML (HTML) version of the 'LT.Text'.
cleanAndParse = XML.parseText_ parseSettings . LT.pack . foldl1 (.) regexes . LT.unpack
where
parseSettings = XML.def { XML.psDecodeEntities = XML.decodeHtmlEntities }
-- =============================================================================
-- * Parse doc
-- =============================================================================
-- | Creates a HTML Table from the cache HTML (in XML format).
parseTable :: XML.Document -- ^ A 'XML.Document' prepared with the @'cleanAndParse'@ function.
-> M Table -- ^ The parsed 'Table'.
parseTable doc = head . catMaybes . findTable (fromDocument doc) <$> ask
{- | Looks for all tables in the generated XML document, with XML-attribute
/class/ @confluenceTable@, maps the function @'processTable'@ to the result
list, and finally returns a list containing the discovered 'Table's.
-}
findTable :: Cursor -- ^ XML document 'Cursor'.
-> Config -- ^ Pointer to the /config.yaml/ data.
-> [Maybe Table] -- ^ List of 'Maybe' 'Table's
findTable c cnf = map ($| processTable cnf) (c $.// attributeIs "class" "confluenceTable" :: [Cursor])
{- | This function takes a pointer to the 'Config' data and an XML 'Cursor'
(pointing to the class attributes with the value @confluenceTable@). It
picks out all the XML-elements beginning with the tag @tr@ from the
@confluenceTable@ class 'Cursor' and maps all child elements of the @tr@
element to it.
The @cells@ variable contains all the rows of the table. The first row
contains some higher-level 'Header's (eg. @Vastaava opettaja@), hence this
row is ignored. The second row contains the main 'Header's of the different
columns, and the rest of the rows are either 'Course' information or
'Category's separating the different 'Course' informations.
The first column in the main 'Header' row is empty (this is the column
containing the 'Category' headers when looking at the Wiki Table),
therefore only the 'tail' of it is necessary.
-}
processTable :: Config -- ^ Pointer to the /config.yaml/ file.
-> Cursor -- ^ XML document 'Cursor' pointing at @confluenceTable@ /class/ attribute.
-> Maybe Table -- ^ The processed 'Maybe' 'Table'.
processTable cnf c = case cells of
_ : headersRaw : xs ->
let headers = tail (mapMaybe getHeader headersRaw)
(_, mcourses) = L.mapAccumL (getRow cnf headers) [] xs
in Just $ Table (unsafePerformIO getCurrentTime) headers (catMaybes mcourses)
_ -> Nothing
where
cells = map ($/ anyElement) (c $// element "tr")
{- | Create a value of type 'Maybe' 'Header' corresponding to the value of the raw
XML-cell containing information about the 'Header'.
-}
getHeader :: Cursor -- ^ Pointer to the cell containing information about the 'Header'.
-> Maybe Header -- ^ A 'Maybe' 'Header' type corresponding to the 'Cursor' value.
getHeader c = return . T.toLower . normalize $ T.unwords (c $// content)
{- | A row is either a 'Category' or a 'Course'. The @['Category']@ is used as
an accumulator.
-}
getRow :: Config -- ^ Pointer to the 'Config' for use with the @'toCategory'@ function.
-> [Header] -- ^ List of the 'Table' 'Header's.
-> [Category] -- ^ A list of 'Category' objects associated with this 'Course'.
-> [Cursor] -- ^ The list of unprocessed rows in the 'Table'.
-> ([Category], Maybe Course) -- ^ A single row, containing 'Category's and the 'Course' data (if any).
getRow cnf@Config{..} headers cats cs = map (T.unwords . ($// content)) cs `go` head (cs !! 1 $| attribute "class")
where
go [] _ = (cats, Nothing)
go (mc : vs) classes = case toCategory cnf mc of
Just cat -> (accumCategory cnf cat cats, Nothing)
Nothing | null vs -> (cats, Nothing)
| T.null (normalize mc) -> (cats, Just $ toCourse cnf cats headers (classCur `T.isInfixOf` classes) vs)
| otherwise -> (cats, Just $ toCourse cnf cats headers (classCur `T.isInfixOf` classes) vs)
-- =============================================================================
-- ** Courses and categories
-- =============================================================================
{- | Checks if the given 'Text' is a 'Category' listed in the /config.yaml/
file. If it is, then it will return the name of the 'Category' otherwise
it'll return an empty 'Text'.
Because the Wiki Table column containing the categories also contains
semester information or empty cells, the function has to exclude those
cells before checking the 'Category' name.
-}
toCategory :: Config -- ^ Pointer to the 'Config' object, for accessing the @categories@.
-> Text -- ^ The cell value from the 'Table'.
-> Maybe Category -- ^ The name of the 'Category' if it is a category, otherwise an empty 'Text'.
toCategory Config{..} t = do
guard $ t /= "\160" && t /= "syksy" && t /= "kevät"
guard $ isJust $ L.find (`T.isInfixOf` (T.toLower t)) $ concat categories
return $ normalize $ T.toLower t
{- | Accumulate a 'Category' to a list of 'Category's based on what @categories@
cannot overlap.
In the /config.yaml/ file the @categories@ are listed in hierarchial order,
making the once from the top being on the top if more than one 'Category' is
found for that particular 'Course'.
If the 'Category' to check can be found in the list of @categories@, it will
grab the index in the list of @categories@ for that 'Category' and generate
the new list of 'Category's for the 'Course'.
-}
accumCategory :: Config -- ^ Pointer to the 'Config' for access to the @categories@.
-> Category -- ^ The current 'Category' to check.
-> [Category] -- ^ The previous 'Category's for the course.
-> [Category] -- ^ The list containing all 'Category's found for the course this far in the right order.
accumCategory Config{..} cat cats = case L.findIndex (any (`T.isPrefixOf` cat)) categories of
Nothing -> error $ "Unknown category: " ++ show cat
Just i -> L.deleteFirstsBy T.isPrefixOf cats (f i) ++ [cat]
where
f i = concat $ L.drop i categories
{- | Creates a row for the current 'Table'. The output will differ depending on
the content in the 'Config' data and the different arguments.
This function will return the finished row, containing the separating
'Category's and the correct 'Course' information from the source 'Table'.
-}
toCourse :: Config -- ^ The 'Config' to lookup page configuration data from.
-> [Category] -- ^ A list of 'Category's to pass on to the finished row.
-> [Header] -- ^ A list of 'Header's to select correct 'Text' from the given list.
-> Bool -- ^ If 'True' this will make the course available this year.
-> [Text] -- ^ Used to fill the columns of the row with values from the source 'Table'.
-> Course -- ^ The finished row.
toCourse Config{..} cats hs iscur xs =
(cats, Map.adjust doLang (columnTitle columnHeaders "colLang") $
Map.adjust doRepeats (columnTitle columnHeaders "colRepeats") $
Map.insert "pidetään" (if iscur then "this-year" else "next-year") $
Map.insert "lukukausi" lukukausi vals)
where
vals = Map.fromList $ zip hs $ map normalize xs
lukukausi = fromMaybe "syksy, kevät" $ Map.lookup (columnTitle columnHeaders "colPeriod") vals >>= toLukukausi
toLukukausi x
| "tammikuu" `T.isInfixOf` x = Just "kevät"
| "helmikuu" `T.isInfixOf` x = Just "kevät"
| "maaliskuu" `T.isInfixOf` x = Just "kevät"
| "huhtikuu" `T.isInfixOf` x = Just "kevät"
| "toukokuu" `T.isInfixOf` x = Just "kevät"
| "kesäkuu" `T.isInfixOf` x = Just "kesä"
| "heinäkuu" `T.isInfixOf` x = Just "kesä"
| "elokuu" `T.isInfixOf` x = Just "kesä, syksy"
| "syyskuu" `T.isInfixOf` x = Just "syksy"
| "lokakuu" `T.isInfixOf` x = Just "syksy"
| "marraskuu" `T.isInfixOf` x = Just "syksy"
| "joulukuu" `T.isInfixOf` x = Just "syksy"
| x == "I" || x == "II" || x == "I-II" = Just "syksy"
| x == "III" || x == "IV" || x == "III-IV" = Just "kevät"
| x == "I-IV" || x == "II-III" || x == "I, III" || x == "II, IV" = Just "syksy, kevät"
| x == "V" = Just "kesä"
| "kevät" `T.isInfixOf` x = Just "kevät"
| "syksy" `T.isInfixOf` x = Just "syksy"
| "kesä" `T.isInfixOf` x = Just "kesä"
| otherwise = Nothing
{- | Change the format of the @colLang@ column in the source 'Table' to be in
the correct format.
* Replace different ways of writing languages to the correct 'Lang'
format.
* Replace word separators to single spaces.
-}
doLang :: Text -- ^ The line of 'Text', that needs conversion.
-> Text -- ^ The correctly formatted 'Text'.
doLang = T.replace "suomi" "fi" . T.replace "eng" "en" . T.replace "englanti" "en"
. T.replace "ruotsi" "se"
. T.unwords . T.words
. T.replace "," " " . T.replace "." " " . T.replace "/" " " . T.toLower
{- | Checks the column @toistuu@ from the source 'Table'. If there's anything
but numericals or non-alpha characters, it'll return a 'Text' consisting
of the '-' character. Else it returns the value of the cell.
-}
doRepeats :: Text -- ^ The 'Text' in the cell of the column.
-> Text -- ^ The value of 'Text' argument if there isn't any alpha characters in the cell.
doRepeats x | T.any isLetter x = "-"
| otherwise = x
{- | The 'Course' in this case is a row in the 'Table'. This function compares
two rows and checks if the values are found in the @categories@ list.
It will compare the 'Text's of them and returns 'True' if both of the
applied 'Course' arguments have the same text.
-}
catGroup :: Config -- ^ Used to access all available @categories@ from /config.yaml/.
-> Int -- ^ 'Category' at level @n@ in /config.yaml/.
-> Course -- ^ First 'Table' row to compare.
-> Course -- ^ Second 'Table' row to compare.
-> Bool -- ^ 'True' if the two rows have the same 'Category' 'Text'.
catGroup cnf n = (==) `on` catAt cnf n
{- | Returns the value of the first found 'Category' that matches the
@categories@ at level @n@ in /config.yaml/.
-}
catAt :: Config -- ^ Used to access all available @categories@ from /config.yaml/.
-> Int -- ^ 'Category' at level @n@ in /config.yaml/.
-> Course -- ^ A 'Table' row consisting of only a 'Category' 'Text'.
-> Maybe Text -- ^ The first found value matching @categories@ at level @n@.
catAt Config{..} n (cats, _) =
case [ c | c <- cats, cr <- categories !! n, cr `T.isPrefixOf` c ] of
x:_ -> Just x
_ -> Nothing
{- | Get the content of a specific cell from the specified row. This function
works as a wrapper for the @'getCellContentMaybe'@ function, stripping it
of the 'Maybe' monad.
If the @'getCellContentMaybe'@ returns a 'Nothing' it'll return a 'Text'
saying that the /key couldn't be found/, otherwise it returns the value
of the cell.
-}
getCellContent :: Text -- ^ The 'Text' to look for in the row consisting of the 'Course' type.
-> Course -- ^ The row to look in.
-> Text -- ^ The result 'Text'.
getCellContent k c = fromMaybe (traceShow ("Key not found" :: String, k, c) $ "Key not found: " <> k) $ getCellContentMaybe k c
{- | Get the content of a specific cell form the specified row.
Returns 'Nothing' if the key isn't in the row, otherwise it returns the
value of the cell.
-}
getCellContentMaybe :: Text -- ^ The 'Text' to look for in the row.
-> Course -- ^ The row to look in.
-> Maybe Text -- ^ The 'Text' of the cell if it was found otherwise 'Nothing'.
getCellContentMaybe k (_, c) = Map.lookup k c
| HeavenlyAwe/opetussivut | main.hs | mit | 51,932 | 0 | 26 | 16,935 | 5,087 | 2,721 | 2,366 | 399 | 4 |
--
-- Chapter 11, definitions from the book.
--
module B'C'11 where
import Prelude hiding (succ)
-- Subchapter 11.1, forward composition ...
infixl 9 >.>
(>.>) :: (a -> b) -> (b -> c) -> (a -> c)
g >.> f = f . g
-- Subchapter 11.2, "mapFuns":
mapFuns :: [a -> b] -> a -> [b]
mapFuns fs x = map (\f -> f x) fs
-- Subchapter 11.2, "comp2":
comp2 :: (a -> b) -> (b -> b -> c) -> (a -> a -> c)
comp2 f g = \x y -> g (f x) (f y)
-- Subchapter 11.4, "double":
double :: Integer -> Integer
double = (* 2)
-- Subchapter 11.5 "iter", "succ":
iter :: Integer -> (a -> a) -> (a -> a)
iter n f
| n > 0 = f . iter (n - 1) f
| otherwise = id
succ :: Integer -> Integer
succ n = n + 1
| pascal-knodel/haskell-craft | _/links/B'C'11.hs | mit | 720 | 0 | 9 | 210 | 313 | 172 | 141 | 17 | 1 |
{-# LANGUAGE Arrows, OverloadedStrings, RecordWildCards #-}
module Bot where
import Control.Auto
import Control.Concurrent (Chan, newChan, writeChan, forkIO, threadDelay)
import Control.Auto.Run (runOnChanM)
import Control.Auto.Serialize (serializing')
import Control.Monad (void, forever)
import Control.Monad.IO.Class
import Data.Foldable (forM_)
import Data.Text hiding (words, unwords, map)
import Data.Text.Encoding
import Data.Time
import Network.SimpleIRC
import Prelude hiding ((.), id) -- we use (.) and id from `Control.Category`
import qualified Data.Map.Lazy as M
import Control.Exception (catch)
import Bot.Types
import Bot.Reputation
import Bot.Wolfram
import Bot.Seen
import Bot.Echo
import Bot.NowPlaying
import Bot.Define
import Bot.Data.Config
import Bot.URL
import Bot.Help
import Bot.Ping
import Bot.GIF
import Bot.Factoid
configFail :: String
configFail = "Unexpected error from getConfig"
main :: IO ()
main = do
config <- catch (getConfig "config.yml")
unexpectedConfigError -- Throw a custom error.
withIrcConf (genIrcConfig config) chatBot
forever (threadDelay 1000000000)
where unexpectedConfigError :: IOError -> IO Config
unexpectedConfigError ex =
ioError $ userError $ configFail ++ "Additional info: " ++ (show ex)
genIrcConfig :: Config -> IrcConfig
genIrcConfig Config {..} = (mkDefaultConfig server name) {cChannels = channels}
chatBot :: MonadIO m => ChatBot m
chatBot = mconcat [ serializing' "rep.dat" $ perRoom repBot
, serializing' "seen.dat" $ perRoom seenBot
, serializing' "np.dat" $ perRoom npBot
, serializing' "factoid.dat" $ perRoom factoidBot
, perRoom echoBot
, perRoom defineBot
, perRoom waBot
, perRoom urlBot
, perRoom helpBot
, perRoom pingBot
, perRoom gifBot
]
perRoom :: Monad m => RoomBot m -> ChatBot m
perRoom rb = proc inp@InMessage {..} -> do
blipOutput <- rb -< inp
output <- fromBlips [] -< blipOutput
id -< OutMessages $ M.singleton channel output
withIrcConf :: IrcConfig -> ChatBot IO -> IO ()
withIrcConf ircconf chatbot = do
-- chan to receive `InMessages`
inputChan <- newChan :: IO (Chan InMessage)
-- configuring IRC
let events = cEvents ircconf ++ [ Privmsg (onMessage inputChan) ]
ircconf' = ircconf { cEvents = events } -- ^ :: IrcConfig
-- connect; simplified for demonstration purposes
Right server' <- connect ircconf' True True
-- run `chatbot` on `inputChan`
void . forkIO . void $
runOnChanM id (processOutput server') inputChan chatbot
where
-- what to do when `chatBot` outputs
processOutput :: MIrc -> OutMessages -> IO Bool
processOutput server' (OutMessages outs) = do
print outs
_ <- flip M.traverseWithKey outs $ \channel messages -> do
let channel' = encodeUtf8 . pack $ channel
forM_ messages $ \message -> do
let message' = encodeUtf8 . pack $ message
sendMsg server' channel' message'
return True -- "yes, continue on"
-- what to do when you get a new message
onMessage :: Chan InMessage -> EventFunc
onMessage inputChan = \_ message -> do
case (mNick message, mOrigin message) of
(Just nick, Just src) -> do
time <- getCurrentTime
writeChan inputChan $ InMessage (unpack (decodeUtf8 nick))
(unpack (decodeUtf8 (mMsg message)))
(unpack (decodeUtf8 src))
time
(Just _ , Nothing) -> undefined
(Nothing, Just _) -> undefined
(Nothing, Nothing) -> undefined
| urbanslug/nairobi-bot | src/Bot.hs | gpl-3.0 | 3,885 | 1 | 22 | 1,111 | 1,028 | 535 | 493 | 88 | 4 |
module Directive.Parser (
parseCommand, Command(..)
) where
import Interface.Errors
import Tools.Parser
import Text.Parsec
data Command =
Replace String String |
Exec String |
PassThrough String |
DoWrite |
DoInclude
deriving Show
parseCommand :: FilePath -> String -> Either SPPError Command
parseCommand path input
= either (Left . sppError InvalidDirective path (Just input)) Right $ doParse command input
command :: Parser Command
command = do
spaces
replace <|> exec <|> passThrough <|> write <|> include
replace :: Parser Command
replace = do
spacedString "replace"
regex <- haskellString
spacedString "->"
replacement <- haskellString
return $ Replace regex replacement
exec :: Parser Command
exec = do
spacedString "exec"
toexec <- many anyChar
return $ Exec toexec
passThrough :: Parser Command
passThrough = do
spacedString "pass"
toPass <- many anyChar
return $ PassThrough toPass
write :: Parser Command
write = spacedString "write" >> return DoWrite
include :: Parser Command
include = spacedString "include" >> return DoInclude
| kavigupta/SimplePreprocessor | src/Directive/Parser.hs | gpl-3.0 | 1,148 | 0 | 11 | 258 | 335 | 164 | 171 | 40 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.S3.DeleteBucketTagging
-- 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)
--
-- Deletes the tags from the bucket.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonS3/latest/API/DeleteBucketTagging.html AWS API Reference> for DeleteBucketTagging.
module Network.AWS.S3.DeleteBucketTagging
(
-- * Creating a Request
deleteBucketTagging
, DeleteBucketTagging
-- * Request Lenses
, dbtBucket
-- * Destructuring the Response
, deleteBucketTaggingResponse
, DeleteBucketTaggingResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.S3.Types
import Network.AWS.S3.Types.Product
-- | /See:/ 'deleteBucketTagging' smart constructor.
newtype DeleteBucketTagging = DeleteBucketTagging'
{ _dbtBucket :: BucketName
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteBucketTagging' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dbtBucket'
deleteBucketTagging
:: BucketName -- ^ 'dbtBucket'
-> DeleteBucketTagging
deleteBucketTagging pBucket_ =
DeleteBucketTagging'
{ _dbtBucket = pBucket_
}
-- | Undocumented member.
dbtBucket :: Lens' DeleteBucketTagging BucketName
dbtBucket = lens _dbtBucket (\ s a -> s{_dbtBucket = a});
instance AWSRequest DeleteBucketTagging where
type Rs DeleteBucketTagging =
DeleteBucketTaggingResponse
request = delete s3
response = receiveNull DeleteBucketTaggingResponse'
instance ToHeaders DeleteBucketTagging where
toHeaders = const mempty
instance ToPath DeleteBucketTagging where
toPath DeleteBucketTagging'{..}
= mconcat ["/", toBS _dbtBucket]
instance ToQuery DeleteBucketTagging where
toQuery = const (mconcat ["tagging"])
-- | /See:/ 'deleteBucketTaggingResponse' smart constructor.
data DeleteBucketTaggingResponse =
DeleteBucketTaggingResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteBucketTaggingResponse' with the minimum fields required to make a request.
--
deleteBucketTaggingResponse
:: DeleteBucketTaggingResponse
deleteBucketTaggingResponse = DeleteBucketTaggingResponse'
| fmapfmapfmap/amazonka | amazonka-s3/gen/Network/AWS/S3/DeleteBucketTagging.hs | mpl-2.0 | 2,930 | 0 | 9 | 550 | 348 | 212 | 136 | 49 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Indexed
-- Copyright : (C) 2008 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable (rank-2 polymorphism)
--
----------------------------------------------------------------------------
module Control.Monad.Indexed
( IxFunctor(..)
, IxPointed(..)
, IxApplicative(..)
, IxMonad(..)
, IxMonadZero(..)
, IxMonadPlus(..)
, ijoin, (>>>=), (=<<<)
, iapIxMonad
) where
import Control.Functor.Indexed
class IxApplicative m => IxMonad m where
ibind :: (a -> m j k b) -> m i j a -> m i k b
ijoin :: IxMonad m => m i j (m j k a) -> m i k a
ijoin = ibind id
infixr 1 =<<<
infixl 1 >>>=
(>>>=) :: IxMonad m => m i j a -> (a -> m j k b) -> m i k b
m >>>= k = ibind k m
(=<<<) :: IxMonad m => (a -> m j k b) -> m i j a -> m i k b
(=<<<) = ibind
iapIxMonad :: IxMonad m => m i j (a -> b) -> m j k a -> m i k b
iapIxMonad f x = f >>>= \ f' -> x >>>= \x' -> ireturn (f' x')
class IxMonad m => IxMonadZero m where
imzero :: m i j a
class IxMonadZero m => IxMonadPlus m where
implus :: m i j a -> m i j a -> m i j a
| urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav | Control/Monad/Indexed.hs | apache-2.0 | 1,265 | 4 | 11 | 286 | 489 | 261 | 228 | 26 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wall #-}
{-|
Operators for expressions over lifted values
- Lifting Fortran types to higher-level representations
- Folds over arrays (sum, product)
- High-level mathematical functions (factorial...)
-}
module Language.Fortran.Model.Op.High where
import Control.Monad.Reader.Class (MonadReader, asks)
import Data.Functor.Compose
import Language.Expression
import Language.Expression.Pretty
import Language.Fortran.Model.Repr
import Language.Fortran.Model.Repr.Prim
--------------------------------------------------------------------------------
-- High-level Operations
--------------------------------------------------------------------------------
data HighOp t a where
HopLift :: LiftDOp t a -> HighOp t a
instance HFunctor HighOp
instance HTraversable HighOp where
htraverse f = \case
HopLift x -> HopLift <$> htraverse f x
instance (MonadReader r m, HasPrimReprHandlers r) => HFoldableAt (Compose m HighRepr) HighOp where
hfoldMap f = \case
HopLift x -> hfoldMap f x
instance Pretty2 HighOp where
prettys2Prec p (HopLift x) = prettys2Prec p x
--------------------------------------------------------------------------------
-- Lifting Fortran values
--------------------------------------------------------------------------------
data LiftDOp t a where
LiftDOp :: LiftD b a => t b -> LiftDOp t a
instance HFunctor LiftDOp where
instance HTraversable LiftDOp where
htraverse f = \case
LiftDOp x -> LiftDOp <$> f x
instance (MonadReader r m, HasPrimReprHandlers r
) => HFoldableAt (Compose m HighRepr) LiftDOp where
hfoldMap = implHfoldMapCompose $ \case
LiftDOp x -> do
env <- asks primReprHandlers
pure $ liftDRepr env x
instance Pretty2 LiftDOp where
prettys2Prec p = \case
-- TODO: Consider adding printed evidence of the lifting
LiftDOp x -> prettys1Prec p x
| dorchard/camfort | src/Language/Fortran/Model/Op/High.hs | apache-2.0 | 2,415 | 0 | 13 | 506 | 416 | 226 | 190 | 46 | 0 |
module Main where
import System.IO.Error
import System.Process
main :: IO ()
main = do test1 `catchIOError` \e -> putStrLn ("Exc: " ++ show e)
test2 `catchIOError` \e -> putStrLn ("Exc: " ++ show e)
test1 :: IO ()
test1 = do
(_, _, _, commhand) <-
runInteractiveProcess "true" [] (Just "/no/such/dir") Nothing
exitCode <- waitForProcess commhand
print exitCode
test2 :: IO ()
test2 = do
commhand <- runProcess "true" [] (Just "/no/such/dir") Nothing
Nothing Nothing Nothing
exitCode <- waitForProcess commhand
print exitCode
| DavidAlphaFox/ghc | libraries/process/tests/process004.hs | bsd-3-clause | 574 | 0 | 12 | 131 | 212 | 107 | 105 | 18 | 1 |
{-# LANGUAGE CPP, RankNTypes, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.InterfaceFile
-- Copyright : (c) David Waern 2006-2009,
-- Mateusz Kowalczyk 2013
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Reading and writing the .haddock interface file
-----------------------------------------------------------------------------
module Haddock.InterfaceFile (
InterfaceFile(..), ifPackageKey,
readInterfaceFile, nameCacheFromGhc, freshNameCache, NameCacheAccessor,
writeInterfaceFile, binaryInterfaceVersion, binaryInterfaceVersionCompatibility
) where
import Haddock.Types
import Haddock.Utils hiding (out)
import Control.Monad
import Data.Array
import Data.Functor ((<$>))
import Data.IORef
import Data.List
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Word
import BinIface (getSymtabName, getDictFastString)
import Binary
import FastMutInt
import FastString
import GHC hiding (NoLink)
import GhcMonad (withSession)
import HscTypes
import IfaceEnv
import Name
import UniqFM
import UniqSupply
import Unique
data InterfaceFile = InterfaceFile {
ifLinkEnv :: LinkEnv,
ifInstalledIfaces :: [InstalledInterface]
}
ifPackageKey :: InterfaceFile -> PackageKey
ifPackageKey if_ =
case ifInstalledIfaces if_ of
[] -> error "empty InterfaceFile"
iface:_ -> modulePackageKey $ instMod iface
binaryInterfaceMagic :: Word32
binaryInterfaceMagic = 0xD0Cface
-- IMPORTANT: Since datatypes in the GHC API might change between major
-- versions, and because we store GHC datatypes in our interface files, we need
-- to make sure we version our interface files accordingly.
--
-- If you change the interface file format or adapt Haddock to work with a new
-- major version of GHC (so that the format changes indirectly) *you* need to
-- follow these steps:
--
-- (1) increase `binaryInterfaceVersion`
--
-- (2) set `binaryInterfaceVersionCompatibility` to [binaryInterfaceVersion]
--
binaryInterfaceVersion :: Word16
#if (__GLASGOW_HASKELL__ >= 709) && (__GLASGOW_HASKELL__ < 711)
binaryInterfaceVersion = 27
binaryInterfaceVersionCompatibility :: [Word16]
binaryInterfaceVersionCompatibility = [binaryInterfaceVersion]
#else
#error Unsupported GHC version
#endif
initBinMemSize :: Int
initBinMemSize = 1024*1024
writeInterfaceFile :: FilePath -> InterfaceFile -> IO ()
writeInterfaceFile filename iface = do
bh0 <- openBinMem initBinMemSize
put_ bh0 binaryInterfaceMagic
put_ bh0 binaryInterfaceVersion
-- remember where the dictionary pointer will go
dict_p_p <- tellBin bh0
put_ bh0 dict_p_p
-- remember where the symbol table pointer will go
symtab_p_p <- tellBin bh0
put_ bh0 symtab_p_p
-- Make some intial state
symtab_next <- newFastMutInt
writeFastMutInt symtab_next 0
symtab_map <- newIORef emptyUFM
let bin_symtab = BinSymbolTable {
bin_symtab_next = symtab_next,
bin_symtab_map = symtab_map }
dict_next_ref <- newFastMutInt
writeFastMutInt dict_next_ref 0
dict_map_ref <- newIORef emptyUFM
let bin_dict = BinDictionary {
bin_dict_next = dict_next_ref,
bin_dict_map = dict_map_ref }
-- put the main thing
let bh = setUserData bh0 $ newWriteState (putName bin_symtab)
(putFastString bin_dict)
put_ bh iface
-- write the symtab pointer at the front of the file
symtab_p <- tellBin bh
putAt bh symtab_p_p symtab_p
seekBin bh symtab_p
-- write the symbol table itself
symtab_next' <- readFastMutInt symtab_next
symtab_map' <- readIORef symtab_map
putSymbolTable bh symtab_next' symtab_map'
-- write the dictionary pointer at the fornt of the file
dict_p <- tellBin bh
putAt bh dict_p_p dict_p
seekBin bh dict_p
-- write the dictionary itself
dict_next <- readFastMutInt dict_next_ref
dict_map <- readIORef dict_map_ref
putDictionary bh dict_next dict_map
-- and send the result to the file
writeBinMem bh filename
return ()
type NameCacheAccessor m = (m NameCache, NameCache -> m ())
nameCacheFromGhc :: NameCacheAccessor Ghc
nameCacheFromGhc = ( read_from_session , write_to_session )
where
read_from_session = do
ref <- withSession (return . hsc_NC)
liftIO $ readIORef ref
write_to_session nc' = do
ref <- withSession (return . hsc_NC)
liftIO $ writeIORef ref nc'
freshNameCache :: NameCacheAccessor IO
freshNameCache = ( create_fresh_nc , \_ -> return () )
where
create_fresh_nc = do
u <- mkSplitUniqSupply 'a' -- ??
return (initNameCache u [])
-- | Read a Haddock (@.haddock@) interface file. Return either an
-- 'InterfaceFile' or an error message.
--
-- This function can be called in two ways. Within a GHC session it will
-- update the use and update the session's name cache. Outside a GHC session
-- a new empty name cache is used. The function is therefore generic in the
-- monad being used. The exact monad is whichever monad the first
-- argument, the getter and setter of the name cache, requires.
--
readInterfaceFile :: forall m.
MonadIO m
=> NameCacheAccessor m
-> FilePath
-> m (Either String InterfaceFile)
readInterfaceFile (get_name_cache, set_name_cache) filename = do
bh0 <- liftIO $ readBinMem filename
magic <- liftIO $ get bh0
version <- liftIO $ get bh0
case () of
_ | magic /= binaryInterfaceMagic -> return . Left $
"Magic number mismatch: couldn't load interface file: " ++ filename
| version `notElem` binaryInterfaceVersionCompatibility -> return . Left $
"Interface file is of wrong version: " ++ filename
| otherwise -> with_name_cache $ \update_nc -> do
dict <- get_dictionary bh0
-- read the symbol table so we are capable of reading the actual data
bh1 <- do
let bh1 = setUserData bh0 $ newReadState (error "getSymtabName")
(getDictFastString dict)
symtab <- update_nc (get_symbol_table bh1)
return $ setUserData bh1 $ newReadState (getSymtabName (NCU (\f -> update_nc (return . f))) dict symtab)
(getDictFastString dict)
-- load the actual data
iface <- liftIO $ get bh1
return (Right iface)
where
with_name_cache :: forall a.
((forall n b. MonadIO n
=> (NameCache -> n (NameCache, b))
-> n b)
-> m a)
-> m a
with_name_cache act = do
nc_var <- get_name_cache >>= (liftIO . newIORef)
x <- act $ \f -> do
nc <- liftIO $ readIORef nc_var
(nc', x) <- f nc
liftIO $ writeIORef nc_var nc'
return x
liftIO (readIORef nc_var) >>= set_name_cache
return x
get_dictionary bin_handle = liftIO $ do
dict_p <- get bin_handle
data_p <- tellBin bin_handle
seekBin bin_handle dict_p
dict <- getDictionary bin_handle
seekBin bin_handle data_p
return dict
get_symbol_table bh1 theNC = liftIO $ do
symtab_p <- get bh1
data_p' <- tellBin bh1
seekBin bh1 symtab_p
(nc', symtab) <- getSymbolTable bh1 theNC
seekBin bh1 data_p'
return (nc', symtab)
-------------------------------------------------------------------------------
-- * Symbol table
-------------------------------------------------------------------------------
putName :: BinSymbolTable -> BinHandle -> Name -> IO ()
putName BinSymbolTable{
bin_symtab_map = symtab_map_ref,
bin_symtab_next = symtab_next } bh name
= do
symtab_map <- readIORef symtab_map_ref
case lookupUFM symtab_map name of
Just (off,_) -> put_ bh (fromIntegral off :: Word32)
Nothing -> do
off <- readFastMutInt symtab_next
writeFastMutInt symtab_next (off+1)
writeIORef symtab_map_ref
$! addToUFM symtab_map name (off,name)
put_ bh (fromIntegral off :: Word32)
data BinSymbolTable = BinSymbolTable {
bin_symtab_next :: !FastMutInt, -- The next index to use
bin_symtab_map :: !(IORef (UniqFM (Int,Name)))
-- indexed by Name
}
putFastString :: BinDictionary -> BinHandle -> FastString -> IO ()
putFastString BinDictionary { bin_dict_next = j_r,
bin_dict_map = out_r} bh f
= do
out <- readIORef out_r
let unique = getUnique f
case lookupUFM out unique of
Just (j, _) -> put_ bh (fromIntegral j :: Word32)
Nothing -> do
j <- readFastMutInt j_r
put_ bh (fromIntegral j :: Word32)
writeFastMutInt j_r (j + 1)
writeIORef out_r $! addToUFM out unique (j, f)
data BinDictionary = BinDictionary {
bin_dict_next :: !FastMutInt, -- The next index to use
bin_dict_map :: !(IORef (UniqFM (Int,FastString)))
-- indexed by FastString
}
putSymbolTable :: BinHandle -> Int -> UniqFM (Int,Name) -> IO ()
putSymbolTable bh next_off symtab = do
put_ bh next_off
let names = elems (array (0,next_off-1) (eltsUFM symtab))
mapM_ (\n -> serialiseName bh n symtab) names
getSymbolTable :: BinHandle -> NameCache -> IO (NameCache, Array Int Name)
getSymbolTable bh namecache = do
sz <- get bh
od_names <- replicateM sz (get bh)
let arr = listArray (0,sz-1) names
(namecache', names) = mapAccumR (fromOnDiskName arr) namecache od_names
return (namecache', arr)
type OnDiskName = (PackageKey, ModuleName, OccName)
fromOnDiskName
:: Array Int Name
-> NameCache
-> OnDiskName
-> (NameCache, Name)
fromOnDiskName _ nc (pid, mod_name, occ) =
let
modu = mkModule pid mod_name
cache = nsNames nc
in
case lookupOrigNameCache cache modu occ of
Just name -> (nc, name)
Nothing ->
let
us = nsUniqs nc
u = uniqFromSupply us
name = mkExternalName u modu occ noSrcSpan
new_cache = extendNameCache cache modu occ name
in
case splitUniqSupply us of { (us',_) ->
( nc{ nsUniqs = us', nsNames = new_cache }, name )
}
serialiseName :: BinHandle -> Name -> UniqFM (Int,Name) -> IO ()
serialiseName bh name _ = do
let modu = nameModule name
put_ bh (modulePackageKey modu, moduleName modu, nameOccName name)
-------------------------------------------------------------------------------
-- * GhcBinary instances
-------------------------------------------------------------------------------
instance (Ord k, Binary k, Binary v) => Binary (Map k v) where
put_ bh m = put_ bh (Map.toList m)
get bh = fmap (Map.fromList) (get bh)
instance Binary InterfaceFile where
put_ bh (InterfaceFile env ifaces) = do
put_ bh env
put_ bh ifaces
get bh = do
env <- get bh
ifaces <- get bh
return (InterfaceFile env ifaces)
instance Binary InstalledInterface where
put_ bh (InstalledInterface modu info docMap argMap
exps visExps opts subMap fixMap) = do
put_ bh modu
put_ bh info
put_ bh docMap
put_ bh argMap
put_ bh exps
put_ bh visExps
put_ bh opts
put_ bh subMap
put_ bh fixMap
get bh = do
modu <- get bh
info <- get bh
docMap <- get bh
argMap <- get bh
exps <- get bh
visExps <- get bh
opts <- get bh
subMap <- get bh
fixMap <- get bh
return (InstalledInterface modu info docMap argMap
exps visExps opts subMap fixMap)
instance Binary DocOption where
put_ bh OptHide = do
putByte bh 0
put_ bh OptPrune = do
putByte bh 1
put_ bh OptIgnoreExports = do
putByte bh 2
put_ bh OptNotHome = do
putByte bh 3
put_ bh OptShowExtensions = do
putByte bh 4
get bh = do
h <- getByte bh
case h of
0 -> do
return OptHide
1 -> do
return OptPrune
2 -> do
return OptIgnoreExports
3 -> do
return OptNotHome
4 -> do
return OptShowExtensions
_ -> fail "invalid binary data found"
instance Binary Example where
put_ bh (Example expression result) = do
put_ bh expression
put_ bh result
get bh = do
expression <- get bh
result <- get bh
return (Example expression result)
instance Binary Hyperlink where
put_ bh (Hyperlink url label) = do
put_ bh url
put_ bh label
get bh = do
url <- get bh
label <- get bh
return (Hyperlink url label)
instance Binary Picture where
put_ bh (Picture uri title) = do
put_ bh uri
put_ bh title
get bh = do
uri <- get bh
title <- get bh
return (Picture uri title)
instance Binary a => Binary (Header a) where
put_ bh (Header l t) = do
put_ bh l
put_ bh t
get bh = do
l <- get bh
t <- get bh
return (Header l t)
instance Binary Meta where
put_ bh Meta { _version = v } = put_ bh v
get bh = (\v -> Meta { _version = v }) <$> get bh
instance (Binary mod, Binary id) => Binary (MetaDoc mod id) where
put_ bh MetaDoc { _meta = m, _doc = d } = do
put_ bh m
put_ bh d
get bh = do
m <- get bh
d <- get bh
return $ MetaDoc { _meta = m, _doc = d }
{-* Generated by DrIFT : Look, but Don't Touch. *-}
instance (Binary mod, Binary id) => Binary (DocH mod id) where
put_ bh DocEmpty = do
putByte bh 0
put_ bh (DocAppend aa ab) = do
putByte bh 1
put_ bh aa
put_ bh ab
put_ bh (DocString ac) = do
putByte bh 2
put_ bh ac
put_ bh (DocParagraph ad) = do
putByte bh 3
put_ bh ad
put_ bh (DocIdentifier ae) = do
putByte bh 4
put_ bh ae
put_ bh (DocModule af) = do
putByte bh 5
put_ bh af
put_ bh (DocEmphasis ag) = do
putByte bh 6
put_ bh ag
put_ bh (DocMonospaced ah) = do
putByte bh 7
put_ bh ah
put_ bh (DocUnorderedList ai) = do
putByte bh 8
put_ bh ai
put_ bh (DocOrderedList aj) = do
putByte bh 9
put_ bh aj
put_ bh (DocDefList ak) = do
putByte bh 10
put_ bh ak
put_ bh (DocCodeBlock al) = do
putByte bh 11
put_ bh al
put_ bh (DocHyperlink am) = do
putByte bh 12
put_ bh am
put_ bh (DocPic x) = do
putByte bh 13
put_ bh x
put_ bh (DocAName an) = do
putByte bh 14
put_ bh an
put_ bh (DocExamples ao) = do
putByte bh 15
put_ bh ao
put_ bh (DocIdentifierUnchecked x) = do
putByte bh 16
put_ bh x
put_ bh (DocWarning ag) = do
putByte bh 17
put_ bh ag
put_ bh (DocProperty x) = do
putByte bh 18
put_ bh x
put_ bh (DocBold x) = do
putByte bh 19
put_ bh x
put_ bh (DocHeader aa) = do
putByte bh 20
put_ bh aa
get bh = do
h <- getByte bh
case h of
0 -> do
return DocEmpty
1 -> do
aa <- get bh
ab <- get bh
return (DocAppend aa ab)
2 -> do
ac <- get bh
return (DocString ac)
3 -> do
ad <- get bh
return (DocParagraph ad)
4 -> do
ae <- get bh
return (DocIdentifier ae)
5 -> do
af <- get bh
return (DocModule af)
6 -> do
ag <- get bh
return (DocEmphasis ag)
7 -> do
ah <- get bh
return (DocMonospaced ah)
8 -> do
ai <- get bh
return (DocUnorderedList ai)
9 -> do
aj <- get bh
return (DocOrderedList aj)
10 -> do
ak <- get bh
return (DocDefList ak)
11 -> do
al <- get bh
return (DocCodeBlock al)
12 -> do
am <- get bh
return (DocHyperlink am)
13 -> do
x <- get bh
return (DocPic x)
14 -> do
an <- get bh
return (DocAName an)
15 -> do
ao <- get bh
return (DocExamples ao)
16 -> do
x <- get bh
return (DocIdentifierUnchecked x)
17 -> do
ag <- get bh
return (DocWarning ag)
18 -> do
x <- get bh
return (DocProperty x)
19 -> do
x <- get bh
return (DocBold x)
20 -> do
aa <- get bh
return (DocHeader aa)
_ -> error "invalid binary data found in the interface file"
instance Binary name => Binary (HaddockModInfo name) where
put_ bh hmi = do
put_ bh (hmi_description hmi)
put_ bh (hmi_copyright hmi)
put_ bh (hmi_license hmi)
put_ bh (hmi_maintainer hmi)
put_ bh (hmi_stability hmi)
put_ bh (hmi_portability hmi)
put_ bh (hmi_safety hmi)
put_ bh (fromEnum <$> hmi_language hmi)
put_ bh (map fromEnum $ hmi_extensions hmi)
get bh = do
descr <- get bh
copyr <- get bh
licen <- get bh
maint <- get bh
stabi <- get bh
porta <- get bh
safet <- get bh
langu <- fmap toEnum <$> get bh
exten <- map toEnum <$> get bh
return (HaddockModInfo descr copyr licen maint stabi porta safet langu exten)
instance Binary DocName where
put_ bh (Documented name modu) = do
putByte bh 0
put_ bh name
put_ bh modu
put_ bh (Undocumented name) = do
putByte bh 1
put_ bh name
get bh = do
h <- getByte bh
case h of
0 -> do
name <- get bh
modu <- get bh
return (Documented name modu)
1 -> do
name <- get bh
return (Undocumented name)
_ -> error "get DocName: Bad h"
| DavidAlphaFox/ghc | utils/haddock/haddock-api/src/Haddock/InterfaceFile.hs | bsd-3-clause | 19,152 | 9 | 28 | 6,623 | 5,425 | 2,567 | 2,858 | -1 | -1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Lazyfoo.Lesson19 (main) where
import Prelude hiding (any, mapM_)
import Control.Applicative
import Control.Monad hiding (mapM_)
import Data.Foldable
import Data.Int
import Data.Maybe
import Data.Monoid
import Foreign.C.Types
import Linear
import Linear.Affine
import SDL (($=))
import qualified SDL
import qualified Data.Vector as V
import Paths_sdl2 (getDataFileName)
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
joystickDeadZone :: Int16
joystickDeadZone = 8000
data Texture = Texture SDL.Texture (V2 CInt)
loadTexture :: SDL.Renderer -> FilePath -> IO Texture
loadTexture r filePath = do
surface <- getDataFileName filePath >>= SDL.loadBMP
size <- SDL.surfaceDimensions surface
format <- SDL.surfaceFormat surface
key <- SDL.mapRGB format (V3 0 maxBound maxBound)
SDL.surfaceColorKey surface $= Just key
t <- SDL.createTextureFromSurface r surface
SDL.freeSurface surface
return (Texture t size)
renderTexture :: SDL.Renderer -> Texture -> Point V2 CInt -> Maybe (SDL.Rectangle CInt) -> Maybe CDouble -> Maybe (Point V2 CInt) -> Maybe (V2 Bool) -> IO ()
renderTexture r (Texture t size) xy clip theta center flips =
let dstSize =
maybe size (\(SDL.Rectangle _ size') -> size') clip
in SDL.copyEx r
t
clip
(Just (SDL.Rectangle xy dstSize))
(fromMaybe 0 theta)
center
(fromMaybe (pure False) flips)
textureSize :: Texture -> V2 CInt
textureSize (Texture _ sz) = sz
getJoystick :: IO (SDL.Joystick)
getJoystick = do
joysticks <- SDL.availableJoysticks
joystick <- if V.length joysticks == 0
then error "No joysticks connected!"
else return (joysticks V.! 0)
SDL.openJoystick joystick
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo, SDL.InitJoystick]
SDL.HintRenderScaleQuality $= SDL.ScaleLinear
do renderQuality <- SDL.get SDL.HintRenderScaleQuality
when (renderQuality /= SDL.ScaleLinear) $
putStrLn "Warning: Linear texture filtering not enabled!"
window <-
SDL.createWindow
"SDL Tutorial"
SDL.defaultWindow {SDL.windowInitialSize = V2 screenWidth screenHeight}
SDL.showWindow window
renderer <-
SDL.createRenderer
window
(-1)
(SDL.RendererConfig
{ SDL.rendererType = SDL.AcceleratedVSyncRenderer
, SDL.rendererTargetTexture = False
})
SDL.rendererDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
arrowTexture <- loadTexture renderer "examples/lazyfoo/arrow.bmp"
joystick <- getJoystick
joystickID <- SDL.getJoystickID joystick
let loop (xDir', yDir') = do
let collectEvents = do
e <- SDL.pollEvent
case e of
Nothing -> return []
Just e' -> (e' :) <$> collectEvents
events <- collectEvents
let (Any quit, Last newDir) =
foldMap (\case
SDL.QuitEvent -> (Any True, mempty)
SDL.KeyboardEvent e ->
if | SDL.keyboardEventKeyMotion e == SDL.Pressed ->
let scancode = SDL.keysymScancode (SDL.keyboardEventKeysym e)
in if | scancode == SDL.ScancodeEscape -> (Any True, mempty)
| otherwise -> mempty
| otherwise -> mempty
SDL.JoyAxisEvent e ->
if | SDL.joyAxisEventWhich e == joystickID ->
(\x -> (mempty, Last $ Just x)) $
case SDL.joyAxisEventAxis e of
0 -> if | SDL.joyAxisEventValue e < -joystickDeadZone -> (-1, yDir')
| SDL.joyAxisEventValue e > joystickDeadZone -> (1, yDir')
| otherwise -> (0, yDir')
1 -> if | SDL.joyAxisEventValue e < -joystickDeadZone -> (xDir', -1)
| SDL.joyAxisEventValue e > joystickDeadZone -> (xDir', 1)
| otherwise -> (xDir', 0)
_ -> (xDir', yDir')
| otherwise -> mempty
_ -> mempty) $
map SDL.eventPayload events
SDL.rendererDrawColor renderer $= V4 maxBound maxBound maxBound maxBound
SDL.clear renderer
let dir@(xDir, yDir) = fromMaybe (xDir', yDir') newDir
phi = if xDir == 0 && yDir == 0
then 0
else (atan2 yDir xDir) * (180.0 / pi)
renderTexture renderer arrowTexture (P (fmap (`div` 2) (V2 screenWidth screenHeight) - fmap (`div` 2) (textureSize arrowTexture))) Nothing (Just phi) Nothing Nothing
SDL.present renderer
unless quit $ loop dir
loop (0, 0)
SDL.closeJoystick joystick
SDL.destroyRenderer renderer
SDL.destroyWindow window
SDL.quit
| Velro/sdl2 | examples/lazyfoo/Lesson19.hs | bsd-3-clause | 5,232 | 10 | 25 | 1,730 | 1,504 | 762 | 742 | 121 | 15 |
{-# LANGUAGE LambdaCase #-}
module Main where
import Control.Concurrent
import Control.Exception
import Control.Monad
import Data.IORef
import Debug.Trace
import System.Mem.Weak
import System.Mem
import GHCJS.Foreign.Export
main :: IO ()
main = sequence_ [test1, test2, test3, test4]
p :: Weak (IORef String) -> Export (IORef String) -> IO ()
p w x = do
derefExport x >>= \case
Nothing -> putStrLn "<empty export>"
Just r -> readIORef r >>= putStrLn
deRefWeak w >>= \case
Nothing -> putStrLn "<empty weak>"
Just r -> readIORef r >>= putStrLn
-- simple export, with finalizer
test1 :: IO ()
test1 = do
let
putStrLn "test1"
ior <- newIORef "xyz"
w <- mkWeakIORef ior (putStrLn "ioref finalized")
r' <- withExport ior $ \r -> do
performGC
p w r
return r
performGC
p w r'
-- export with unboxed representation
test2 :: IO ()
test2 = do
putStrLn "test2"
let x = 42424242 :: Int
i <- js_getInt
x' <- evaluate (x*i)
r' <- withExport x' $ \r -> do
performGC
print =<< derefExport r
return r
performGC
print =<< derefExport r'
-- manual release
test3 :: IO ()
test3 = do
let pr xs = derefExport >=> maybe (return "<empty>") readIORef >=> putStrLn . ((xs ++ " ") ++)
putStrLn "test3"
ior <- newIORef "xyz"
e <- export ior
forkIO $ do
performGC
threadDelay 200000
pr "forked" e
releaseExport e
pr "forked" e
performGC
pr "main" e
threadDelay 400000
pr "main" e
-- test4: export falsy values
test4 :: IO ()
test4 = do
putStrLn "test4"
i1 <- js_getInt
i2 <- js_getInt
v1 <- evaluate (i1 /= i2)
v2 <- evaluate (i1 - i2)
withExport v1 $ derefExport >=> print
withExport v2 $ derefExport >=> print
foreign import javascript unsafe "$r = 2;" js_getInt :: IO Int
| seereason/ghcjs | test/ffi/export.hs | mit | 1,788 | 0 | 15 | 433 | 676 | 312 | 364 | -1 | -1 |
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
module YesodCoreTest.JsLoaderSites.Bottom
( B(..)
, Widget
, resourcesB -- avoid warning
) where
import Yesod.Core
data B = B
mkYesod "B" [parseRoutes|
/ BottomR GET
|]
instance Yesod B where
jsLoader _ = BottomOfBody
getBottomR :: Handler Html
getBottomR = defaultLayout $ addScriptRemote "load.js"
| s9gf4ult/yesod | yesod-core/test/YesodCoreTest/JsLoaderSites/Bottom.hs | mit | 474 | 0 | 7 | 80 | 86 | 51 | 35 | 14 | 1 |
-- The simplifier changes the shapes of closures that we expect.
{-# OPTIONS_GHC -O0 #-}
{-# LANGUAGE MagicHash, UnboxedTuples, LambdaCase #-}
import GHC.Exts.Heap
import GHC.IORef
import GHC.Weak
import System.Mem
main :: IO ()
main = do
key <- newIORef "key"
let val = "val"
wk@(Weak w) <- mkWeak key val Nothing
getClosureData w >>= \case
WeakClosure{} -> putStrLn "OK"
_ -> error "Weak is not a WeakClosure"
deRefWeak wk >>= \case
Nothing -> error "Weak dead when key alive"
Just _ -> pure ()
readIORef key >>= putStrLn
performMajorGC
deRefWeak wk >>= \case
Nothing -> pure ()
Just _ -> error "Weak alive when key dead"
getClosureData w >>= \case
ConstrClosure{} -> putStrLn "OK"
_ -> error "dead Weak should be a ConstrClosure"
| sdiehl/ghc | libraries/ghc-heap/tests/heap_weak.hs | bsd-3-clause | 825 | 1 | 12 | 215 | 236 | 108 | 128 | 25 | 5 |
{-# LANGUAGE OverloadedStrings #-}
-- | The pull requests API as documented at
-- <http://developer.github.com/v3/pulls/>.
module Github.PullRequests (
pullRequestsFor''
,pullRequestsFor'
,pullRequest'
,pullRequestCommits'
,pullRequestFiles'
,pullRequestsFor
,pullRequest
,pullRequestCommits
,pullRequestFiles
,isPullRequestMerged
,mergePullRequest
,createPullRequest
,updatePullRequest
,module Github.Data
) where
import Github.Data
import Github.Private
import Network.HTTP.Types
import qualified Data.Map as M
import Network.HTTP.Conduit (RequestBody(RequestBodyLBS))
import Data.Aeson
-- | All pull requests for the repo, by owner, repo name, and pull request state.
-- | With authentification
--
-- > pullRequestsFor' (Just ("github-username", "github-password")) "rails" "rails" (Just "open")
--
-- State can be one of @all@, @open@, or @closed@. Default is @open@.
--
pullRequestsFor'' :: Maybe GithubAuth -> Maybe String -> String -> String -> IO (Either Error [PullRequest])
pullRequestsFor'' auth state userName reqRepoName =
githubGetWithQueryString' auth ["repos", userName, reqRepoName, "pulls"] $
maybe "" ("state=" ++) state
-- | All pull requests for the repo, by owner and repo name.
-- | With authentification
--
-- > pullRequestsFor' (Just ("github-username", "github-password")) "rails" "rails"
pullRequestsFor' :: Maybe GithubAuth -> String -> String -> IO (Either Error [PullRequest])
pullRequestsFor' auth = pullRequestsFor'' auth Nothing
-- | All pull requests for the repo, by owner and repo name.
--
-- > pullRequestsFor "rails" "rails"
pullRequestsFor :: String -> String -> IO (Either Error [PullRequest])
pullRequestsFor = pullRequestsFor'' Nothing Nothing
-- | A detailed pull request, which has much more information. This takes the
-- repo owner and name along with the number assigned to the pull request.
-- | With authentification
--
-- > pullRequest' (Just ("github-username", "github-password")) "thoughtbot" "paperclip" 562
pullRequest' :: Maybe GithubAuth -> String -> String -> Int -> IO (Either Error DetailedPullRequest)
pullRequest' auth userName reqRepoName number =
githubGet' auth ["repos", userName, reqRepoName, "pulls", show number]
-- | A detailed pull request, which has much more information. This takes the
-- repo owner and name along with the number assigned to the pull request.
--
-- > pullRequest "thoughtbot" "paperclip" 562
pullRequest :: String -> String -> Int -> IO (Either Error DetailedPullRequest)
pullRequest = pullRequest' Nothing
-- | All the commits on a pull request, given the repo owner, repo name, and
-- the number of the pull request.
-- | With authentification
--
-- > pullRequestCommits' (Just ("github-username", "github-password")) "thoughtbot" "paperclip" 688
pullRequestCommits' :: Maybe GithubAuth -> String -> String -> Int -> IO (Either Error [Commit])
pullRequestCommits' auth userName reqRepoName number =
githubGet' auth ["repos", userName, reqRepoName, "pulls", show number, "commits"]
-- | All the commits on a pull request, given the repo owner, repo name, and
-- the number of the pull request.
--
-- > pullRequestCommits "thoughtbot" "paperclip" 688
pullRequestCommits :: String -> String -> Int -> IO (Either Error [Commit])
pullRequestCommits = pullRequestCommits' Nothing
-- | The individual files that a pull request patches. Takes the repo owner and
-- name, plus the number assigned to the pull request.
-- | With authentification
--
-- > pullRequestFiles' (Just ("github-username", "github-password")) "thoughtbot" "paperclip" 688
pullRequestFiles' :: Maybe GithubAuth -> String -> String -> Int -> IO (Either Error [File])
pullRequestFiles' auth userName reqRepoName number =
githubGet' auth ["repos", userName, reqRepoName, "pulls", show number, "files"]
-- | The individual files that a pull request patches. Takes the repo owner and
-- name, plus the number assigned to the pull request.
--
-- > pullRequestFiles "thoughtbot" "paperclip" 688
pullRequestFiles :: String -> String -> Int -> IO (Either Error [File])
pullRequestFiles = pullRequestFiles' Nothing
-- | Check if pull request has been merged
isPullRequestMerged :: GithubAuth -> String -> String -> Int -> IO(Either Error Status)
isPullRequestMerged auth reqRepoOwner reqRepoName reqPullRequestNumber =
doHttpsStatus "GET" (buildPath ["repos", reqRepoOwner, reqRepoName, "pulls", (show reqPullRequestNumber), "merge"]) auth Nothing
-- | Merge a pull request
mergePullRequest :: GithubAuth -> String -> String -> Int -> Maybe String -> IO(Either Error Status)
mergePullRequest auth reqRepoOwner reqRepoName reqPullRequestNumber commitMessage =
doHttpsStatus "PUT" (buildPath ["repos", reqRepoOwner, reqRepoName, "pulls", (show reqPullRequestNumber), "merge"]) auth (Just . RequestBodyLBS . encode . toJSON $ (buildCommitMessageMap commitMessage))
-- | Update a pull request
updatePullRequest :: GithubAuth -> String -> String -> Int -> EditPullRequest -> IO (Either Error DetailedPullRequest)
updatePullRequest auth reqRepoOwner reqRepoName reqPullRequestNumber editPullRequest =
githubPatch auth ["repos", reqRepoOwner, reqRepoName, "pulls", show reqPullRequestNumber] editPullRequest
buildCommitMessageMap :: Maybe String -> M.Map String String
buildCommitMessageMap (Just commitMessage) = M.singleton "commit_message" commitMessage
buildCommitMessageMap _ = M.empty
createPullRequest :: GithubAuth
-> String
-> String
-> CreatePullRequest
-> IO (Either Error DetailedPullRequest)
createPullRequest auth reqUserName reqRepoName createPR =
githubPost auth ["repos", reqUserName, reqRepoName, "pulls"] createPR
| adarqui/github | Github/PullRequests.hs | bsd-3-clause | 5,684 | 0 | 12 | 846 | 1,053 | 580 | 473 | 64 | 1 |
module AsPatIn2 where
f :: Either a b -> Either a b
f x@(x_1)
= case x of
x@(Left b_1) -> x_1
x@(Right b_1) -> x_1
f x@(x_1) = x_1 | SAdams601/HaRe | old/testing/introCase/AsPatIn2_TokOut.hs | bsd-3-clause | 162 | 0 | 10 | 61 | 85 | 46 | 39 | 7 | 2 |
module B(f) where
import C
| forste/haReFork | tools/base/Modules/tests/3/B.hs | bsd-3-clause | 27 | 0 | 4 | 5 | 12 | 8 | 4 | 2 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Main where
import Data.Kind (Type)
type family F a :: Type
type instance F Int = (Int, ())
class C a
instance C ()
instance (C (F a), C b) => C (a, b)
f :: C (F a) => a -> Int
f _ = 2
main :: IO ()
main = print (f (3 :: Int))
| sdiehl/ghc | testsuite/tests/typecheck/should_run/T3500a.hs | bsd-3-clause | 346 | 0 | 8 | 82 | 154 | 85 | 69 | -1 | -1 |
module App where
import Data.Coerce
foo :: Coercible (a b) (c d) => a b -> c d
foo = coerce
| urbanslug/ghc | testsuite/tests/typecheck/should_compile/T10494.hs | bsd-3-clause | 94 | 0 | 8 | 23 | 50 | 26 | 24 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Futhark.Doc.Generator (renderFile, indexPage) where
import Control.Monad
import Control.Monad.State
import Control.Monad.Reader
import Data.List (sort)
import Data.Monoid
import Data.Maybe (maybe,mapMaybe)
import qualified Data.Map as M
import System.FilePath (splitPath, (-<.>), makeRelative)
import Text.Blaze.Html5 as H hiding (text, map, main)
import qualified Text.Blaze.Html5.Attributes as A
import Data.String (fromString)
import Data.Version
import Prelude hiding (head, div)
import Language.Futhark.TypeChecker (FileModule(..))
import Language.Futhark.TypeChecker.Monad
import Language.Futhark
import Futhark.Doc.Html
import Futhark.Version
type Context = (String,FileModule)
type DocEnv = M.Map (Namespace,VName) String
type DocM = ReaderT Context (State DocEnv)
renderFile :: [Dec] -> DocM Html
renderFile ds = do
current <- asks fst
file_comment <- asks $ progDoc . fileProg . snd
moduleBoilerplate current .
((H.div ! A.id "file_comment" $ renderDoc file_comment) <>) <$>
renderDecs ds
indexPage :: [(String, String)] -> Html
indexPage pages = docTypeHtml $ addBoilerplate "/" "Futhark Library Documentation" $
ul (mconcat $ map linkTo $ sort pages)
where linkTo (name, _) =
let file = makeRelative "/" $ name -<.> "html"
in li $ a ! A.href (fromString file) $ fromString name
addBoilerplate :: String -> String -> Html -> Html
addBoilerplate current titleText bodyHtml =
let headHtml = head $
title (fromString titleText) <>
link ! A.href (fromString $ relativise "style.css" current)
! A.rel "stylesheet"
! A.type_ "text/css"
madeByHtml =
H.div ! A.id "footer" $ hr
<> "Generated by " <> (a ! A.href futhark_doc_url) "futhark-doc"
<> " " <> fromString (showVersion version)
in headHtml <> body (h1 (toHtml titleText) <> bodyHtml <> madeByHtml)
where futhark_doc_url =
"https://futhark.readthedocs.io/en/latest/man/futhark-doc.html"
moduleBoilerplate :: String -> Html -> Html
moduleBoilerplate current bodyHtml =
addBoilerplate current current ((H.div ! A.class_ "module") bodyHtml)
renderDecs :: [Dec] -> DocM Html
renderDecs decs = asks snd >>= f
where f fm = (H.div ! A.class_ "decs") . mconcat <$>
mapM (fmap $ H.div ! A.class_ "dec") (mapMaybe (prettyDec fm) decs)
prettyDec :: FileModule -> Dec -> Maybe (DocM Html)
prettyDec fileModule dec = case dec of
FunDec f -> return <$> prettyFun fileModule f
SigDec s -> prettySig fileModule s
ModDec m -> prettyMod fileModule m
ValDec v -> prettyVal fileModule v
TypeDec t -> renderType fileModule t
OpenDec _x _xs (Info _names) _ -> Nothing
--Just $ prettyOpen fileModule (x:xs) names
LocalDec _ _ -> Nothing
--prettyOpen :: FileModule -> [ModExpBase Info VName] -> [VName] -> DocM Html
--prettyOpen fm xs (Info names) = mconcat <$> mapM (renderModExp fm) xs
-- where FileModule (Env { envModTable = modtable }) = fm
--envs = foldMap (renderEnv . (\(ModEnv e) -> e) . (modtable M.!)) names
prettyFun :: FileModule -> FunBindBase t VName -> Maybe Html
prettyFun fm (FunBind _ name _retdecl _rettype _tparams _args _ doc _)
| Just (BoundF (tps,pts,rett)) <- M.lookup name vtable
, visible Term name fm = Just $
renderDoc doc <> "val " <> vnameHtml name <>
foldMap (" " <>) (map prettyTypeParam tps) <> ": " <>
foldMap (\t -> prettyParam t <> " -> ") pts <> prettyType rett
where FileModule Env {envVtable = vtable} _ = fm
prettyFun _ _ = Nothing
prettyVal :: FileModule -> ValBindBase Info VName -> Maybe (DocM Html)
prettyVal fm (ValBind _entry name maybe_t _ _e doc _)
| Just (BoundV st) <- M.lookup name vtable
, visible Term name fm =
Just . return . H.div $
renderDoc doc <> "let " <> vnameHtml name <> " : " <>
maybe (prettyType st) typeExpHtml maybe_t
where (FileModule Env {envVtable = vtable} _) = fm
prettyVal _ _ = Nothing
prettySig :: FileModule -> SigBindBase Info VName -> Maybe (DocM Html)
prettySig fm (SigBind vname se doc _)
| M.member vname sigtable && visible Signature vname fm =
Just $ H.div <$> do
name <- vnameHtmlM Signature vname
expHtml <- renderSigExp se
return $ renderDoc doc <> "module type " <> name <>
" = " <> expHtml
where (FileModule Env { envSigTable = sigtable } _) = fm
prettySig _ _ = Nothing
prettyMod :: FileModule -> ModBindBase Info VName -> Maybe (DocM Html)
prettyMod fm (ModBind name ps sig _me doc _)
| Just env <- M.lookup name modtable
, visible Term name fm = Just $ div ! A.class_ "mod" <$> do
vname <- vnameHtmlM Term name
params <- modParamHtml ps
s <- case sig of Nothing -> envSig env
Just (s,_) -> renderSigExp s
return $ renderDoc doc <> "module " <> vname <> ": " <> params <> s
where FileModule Env { envModTable = modtable} _ = fm
envSig (ModEnv e) = renderEnv e
envSig (ModFun (FunSig _ _ (MTy _ m))) = envSig m
prettyMod _ _ = Nothing
renderType :: FileModule -> TypeBindBase Info VName -> Maybe (DocM Html)
renderType fm tb
| M.member name typeTable
, visible Type name fm = Just $ H.div <$> typeBindHtml tb
where (FileModule Env {envTypeTable = typeTable} _) = fm
TypeBind { typeAlias = name } = tb
renderType _ _ = Nothing
visible :: Namespace -> VName -> FileModule -> Bool
visible ns vname@(VName name _) (FileModule env _)
| Just vname' <- M.lookup (ns,name) (envNameMap env)
= vname == vname'
visible _ _ _ = False
renderDoc :: Maybe String -> Html
renderDoc (Just doc) =
H.div ! A.class_ "comment" $ toHtml $ comments $ lines doc
where comments [] = ""
comments (x:xs) = unlines $ ("-- | " ++ x) : map ("--"++) xs
renderDoc Nothing = mempty
renderEnv :: Env -> DocM Html
renderEnv (Env vtable ttable sigtable modtable _) =
return $ braces (mconcat specs)
where specs = typeBinds ++ valBinds ++ sigBinds ++ modBinds
typeBinds = map renderTypeBind (M.toList ttable)
valBinds = map renderValBind (M.toList vtable)
sigBinds = map renderModType (M.toList sigtable)
modBinds = map renderMod (M.toList modtable)
renderModType :: (VName, MTy) -> Html
renderModType (name, _sig) =
"module type " <> vnameHtml name
renderMod :: (VName, Mod) -> Html
renderMod (name, _mod) =
"module " <> vnameHtml name
renderValBind :: (VName, ValBinding) -> Html
renderValBind = H.div . prettyValBind
renderTypeBind :: (VName, TypeBinding) -> Html
renderTypeBind (name, TypeAbbr tps tp) =
H.div $ typeHtml name tps <> prettyType tp
prettyValBind :: (VName, ValBinding) -> Html
prettyValBind (name, BoundF (tps, pts, rettype)) =
"val " <> vnameHtml name <>
foldMap (" " <>) (map prettyTypeParam tps) <> ": " <>
foldMap (\t -> prettyParam t <> " -> ") pts <> " " <>
prettyType rettype
prettyValBind (name, BoundV t) =
"val " <> vnameHtml name <> " : " <> prettyType t
prettyParam :: (Maybe VName, StructType) -> Html
prettyParam (Nothing, t) = prettyType t
prettyParam (Just v, t) = parens $ vnameHtml v <> ": " <> prettyType t
prettyType :: StructType -> Html
prettyType t = case t of
Prim et -> primTypeHtml et
Record fs
| Just ts <- areTupleFields fs ->
parens $ commas (map prettyType ts)
| otherwise ->
braces $ commas (map ppField $ M.toList fs)
where ppField (name, tp) =
toHtml (nameToString name) <> ":" <> prettyType tp
TypeVar et targs ->
prettyTypeName et <> foldMap ((<> " ") . prettyTypeArg) targs
Array arr -> prettyArray arr
prettyArray :: ArrayTypeBase (DimDecl VName) () -> Html
prettyArray arr = case arr of
PrimArray et (ShapeDecl ds) u _ ->
prettyU u <> foldMap (brackets . prettyD) ds <> primTypeHtml et
PolyArray et targs shape u _ ->
prettyU u <> prettyShapeDecl shape <> prettyTypeName et <>
foldMap (<> " ") (map prettyTypeArg targs)
RecordArray fs shape u
| Just ts <- areTupleFields fs ->
prefix <> parens (commas $ map prettyElem ts)
| otherwise ->
prefix <> braces (commas $ map ppField $ M.toList fs)
where prefix = prettyU u <> prettyShapeDecl shape
ppField (name, tp) = toHtml (nameToString name) <>
":" <> prettyElem tp
prettyElem :: RecordArrayElemTypeBase (DimDecl VName) () -> Html
prettyElem e = case e of
PrimArrayElem bt _ -> primTypeHtml bt
PolyArrayElem bt targs _ u ->
prettyU u <> prettyTypeName bt <> foldMap (" " <>)
(map prettyTypeArg targs)
ArrayArrayElem at -> prettyArray at
RecordArrayElem fs
| Just ts <- areTupleFields fs
-> parens $ commas $ map prettyElem ts
| otherwise
-> braces . commas $ map ppField $ M.toList fs
where ppField (name, t) = toHtml (nameToString name) <>
":" <> prettyElem t
prettyShapeDecl :: ShapeDecl (DimDecl VName) -> Html
prettyShapeDecl (ShapeDecl ds) =
foldMap (brackets . prettyDimDecl) ds
prettyTypeArg :: TypeArg (DimDecl VName) () -> Html
prettyTypeArg (TypeArgDim d _) = brackets $ prettyDimDecl d
prettyTypeArg (TypeArgType t _) = prettyType t
modParamHtml :: [ModParamBase Info VName] -> DocM Html
modParamHtml [] = return mempty
modParamHtml (ModParam pname psig _ : mps) =
liftM2 f (renderSigExp psig) (modParamHtml mps)
where f se params = "(" <> vnameHtml pname <>
": " <> se <> ") -> " <> params
prettyD :: DimDecl VName -> Html
prettyD (NamedDim v) = prettyQualName v
prettyD (ConstDim _) = mempty
prettyD AnyDim = mempty
renderSigExp :: SigExpBase Info VName -> DocM Html
renderSigExp e = case e of
SigVar v _ -> renderQualName Signature v
SigParens e' _ -> parens <$> renderSigExp e'
SigSpecs ss _ -> braces . (div ! A.class_ "specs") . mconcat <$> mapM specHtml ss
SigWith s (TypeRef v t) _ ->
do e' <- renderSigExp s
--name <- renderQualName Type v
return $ e' <> " with " <> prettyQualName v <>
" = " <> typeDeclHtml t
SigArrow Nothing e1 e2 _ ->
liftM2 f (renderSigExp e1) (renderSigExp e2)
where f e1' e2' = e1' <> " -> " <> e2'
SigArrow (Just v) e1 e2 _ ->
do name <- vnameHtmlM Signature v
e1' <- renderSigExp e1
e2' <- renderSigExp e2
return $ "(" <> name <> ": " <>
e1' <> ") -> " <> e2'
vnameHtml :: VName -> Html
vnameHtml (VName name tag) =
H.span ! A.id (fromString (show tag)) $ renderName name
vnameHtmlM :: Namespace -> VName -> DocM Html
vnameHtmlM ns (VName name tag) =
do file <- asks fst
modify (M.insert (ns,VName name tag) file)
return $ H.span ! A.id (fromString (show tag)) $ renderName name
specHtml :: SpecBase Info VName -> DocM Html
specHtml spec = case spec of
TypeAbbrSpec tpsig -> H.div <$> typeBindHtml tpsig
TypeSpec name ps doc _ -> return . H.div $
renderDoc doc <> "type " <> vnameHtml name <>
joinBy " " (map prettyTypeParam ps)
ValSpec name tparams params rettype doc _ -> return . H.div $
renderDoc doc <>
"val " <> vnameHtml name <>
foldMap (" " <>) (map prettyTypeParam tparams) <> " : " <>
foldMap (\tp -> paramBaseHtml tp <> " -> ") params <>
typeDeclHtml rettype
ModSpec name sig _ ->
do m <- vnameHtmlM Term name
s <- renderSigExp sig
return $ "module " <> m <> ": "<> s
IncludeSpec e _ -> H.div . ("include " <>) <$> renderSigExp e
paramBaseHtml :: ParamBase Info VName -> Html
paramBaseHtml (NamedParam v t _) =
parens $ vnameHtml v <> ": " <> typeDeclHtml t
paramBaseHtml (UnnamedParam t) = typeDeclHtml t
typeDeclHtml :: TypeDeclBase f VName -> Html
typeDeclHtml = typeExpHtml . declaredType
typeExpHtml :: TypeExp VName -> Html
typeExpHtml e = case e of
TEUnique t _ -> "*" >> typeExpHtml t
TEArray at d _ -> brackets (prettyDimDecl d) <> typeExpHtml at
TETuple ts _ -> parens $ commas (map typeExpHtml ts)
TERecord fs _ -> braces $ commas (map ppField fs)
where ppField (name, t) = toHtml (nameToString name) <>
"=" <> typeExpHtml t
TEVar name _ -> qualNameHtml name
TEApply t args _ ->
qualNameHtml t <> foldMap (" " <>) (map prettyTypeArgExp args)
qualNameHtml :: QualName VName -> Html
qualNameHtml (QualName names (VName name tag)) =
if tag <= maxIntrinsicTag
then prefix <> renderName name
else prefix <> (a ! A.href (fromString ("#" ++ show tag)) $ renderName name)
where prefix :: Html
prefix = foldMap ((<> ".") . renderName) names
renderQualName :: Namespace -> QualName VName -> DocM Html
renderQualName ns (QualName names (VName name tag)) =
if tag <= maxIntrinsicTag
then return $ prefix <> renderName name
else f <$> ref
where prefix :: Html
prefix = mapM_ ((<> ".") . renderName) names
f s = prefix <> (a ! A.href (fromString s) $ renderName name)
ref = do --vname <- getVName ns (QualName names name)
Just file <- gets (M.lookup (ns, VName name tag))
current <- asks fst
if file == current
then return ("#" ++ show tag)
else return $ relativise file current ++
".html#" ++ show tag
relativise :: FilePath -> FilePath -> FilePath
relativise dest src =
concat (replicate (length (splitPath src) - 2) "../") ++ dest
prettyDimDecl :: DimDecl VName -> Html
prettyDimDecl AnyDim = mempty
prettyDimDecl (NamedDim v) = prettyQualName v
prettyDimDecl (ConstDim n) = toHtml (show n)
prettyTypeArgExp :: TypeArgExp VName -> Html
prettyTypeArgExp (TypeArgExpDim d _) = prettyDimDecl d
prettyTypeArgExp (TypeArgExpType d) = typeExpHtml d
prettyTypeParam :: TypeParam -> Html
prettyTypeParam (TypeParamDim name _) = brackets $ vnameHtml name
prettyTypeParam (TypeParamType name _) = "'" <> vnameHtml name
typeBindHtml :: TypeBindBase Info VName -> DocM Html
typeBindHtml (TypeBind name params usertype doc _) =
return $ renderDoc doc <> typeHtml name params <> typeDeclHtml usertype
typeHtml :: VName -> [TypeParam] -> Html
typeHtml name params =
"type " <> vnameHtml name <>
joinBy " " (map prettyTypeParam params) <>
" = "
| ihc/futhark | src/Futhark/Doc/Generator.hs | isc | 14,144 | 0 | 18 | 3,333 | 5,254 | 2,583 | 2,671 | 316 | 7 |
main :: IO ()
main = putStrLn "Running with testing enabled"
| KarimxD/Evolverbetert | test/Test.hs | mit | 61 | 0 | 6 | 11 | 19 | 9 | 10 | 2 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : KD8ZRC.Mapview.Utility.Coordinates
-- Copyright : (C) 2015 Ricky Elrod
-- License : MIT (see LICENSE file)
-- Maintainer : Ricky Elrod <[email protected]>
-- Stability : experimental
-- Portability : ghc (lens)
--
-- Uses the <https://hackage.haskell.org/package/coordinate coordinate> package
-- to provide types for working with... coordinates.
----------------------------------------------------------------------------
module KD8ZRC.Mapview.Utility.Coordinates where
import Data.Geo.Coordinate
fromFractional :: Double -> Double -> Maybe Coordinate
fromFractional = (<°>)
| noexc/mapview | src/KD8ZRC/Mapview/Utility/Coordinates.hs | mit | 707 | 0 | 7 | 74 | 50 | 36 | 14 | 5 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
module System.Time.Native(
timeOpMicros
, nowClocks
, nowNanos
, nowMicros
, nowMillis
, nowSeconds
) where
import Control.Concurrent
import Control.Exception
import Data.Word
import Text.Printf
foreign import ccall unsafe "time_rdtsc" getRDTSC :: IO Word64
foreign import ccall unsafe "time_ns" getNanos :: IO Word64
foreign import ccall unsafe "time_s" getS :: IO Double
timeOpMicros :: IO a -> IO (a,Word64)
timeOpMicros io = do
t_st <- nowNanos
a <- io
t_en <- nowNanos
t_diff <- evaluate $! t_en - t_st
return (a, t_diff`div`1000)
nowClocks :: IO Word64
nowClocks = getRDTSC
nowNanos :: IO Word64
nowNanos = getNanos
nowMicros :: IO Word64
nowMicros = fmap (`div`1000) getNanos
nowMillis :: IO Word64
nowMillis = fmap (`div`1000000) getNanos
nowSeconds :: IO Double
nowSeconds = getS
| trbauer/native-time | System/Time/Native.hs | mit | 867 | 0 | 9 | 159 | 269 | 148 | 121 | 32 | 1 |
module Q19 where
import Q17
rotate :: [a] -> Int -> [a]
rotate p q =
let
(r, s) = split p (mod q (length p))
in
s ++ r | cshung/MiscLab | Haskell99/q19.hs | mit | 131 | 0 | 13 | 42 | 77 | 41 | 36 | 7 | 1 |
module Settings.Builders.GhcCabal (
ghcCabalBuilderArgs, ghcCabalHsColourBuilderArgs
) where
import Hadrian.Haskell.Cabal
import Context
import Flavour
import Settings.Builders.Common hiding (package)
import Utilities
ghcCabalBuilderArgs :: Args
ghcCabalBuilderArgs = builder GhcCabal ? do
verbosity <- expr getVerbosity
top <- expr topDirectory
context <- getContext
path <- getBuildPath
when (package context /= deriveConstants) $ expr (need inplaceLibCopyTargets)
mconcat [ arg "configure"
, arg =<< pkgPath <$> getPackage
, arg $ top -/- path
, dll0Args
, withStaged $ Ghc CompileHs
, withStaged (GhcPkg Update)
, bootPackageDatabaseArgs
, libraryArgs
, with HsColour
, configureArgs
, bootPackageConstraints
, withStaged $ Cc CompileC
, notStage0 ? with Ld
, withStaged Ar
, with Alex
, with Happy
, verbosity < Chatty ? pure [ "-v0", "--configure-option=--quiet"
, "--configure-option=--disable-option-checking" ] ]
ghcCabalHsColourBuilderArgs :: Args
ghcCabalHsColourBuilderArgs = builder GhcCabalHsColour ? do
srcPath <- pkgPath <$> getPackage
top <- expr topDirectory
path <- getBuildPath
pure [ "hscolour", srcPath, top -/- path ]
-- TODO: Isn't vanilla always built? If yes, some conditions are redundant.
-- TODO: Need compiler_stage1_CONFIGURE_OPTS += --disable-library-for-ghci?
libraryArgs :: Args
libraryArgs = do
ways <- getLibraryWays
withGhci <- expr ghcWithInterpreter
dynPrograms <- dynamicGhcPrograms <$> expr flavour
pure [ if vanilla `elem` ways
then "--enable-library-vanilla"
else "--disable-library-vanilla"
, if vanilla `elem` ways && withGhci && not dynPrograms
then "--enable-library-for-ghci"
else "--disable-library-for-ghci"
, if profiling `elem` ways
then "--enable-library-profiling"
else "--disable-library-profiling"
, if dynamic `elem` ways
then "--enable-shared"
else "--disable-shared" ]
-- TODO: LD_OPTS?
configureArgs :: Args
configureArgs = do
top <- expr topDirectory
root <- getBuildRoot
let conf key expr = do
values <- unwords <$> expr
not (null values) ?
arg ("--configure-option=" ++ key ++ "=" ++ values)
cFlags = mconcat [ remove ["-Werror"] cArgs
, getStagedSettingList ConfCcArgs
, arg $ "-I" ++ top -/- root -/- generatedDir ]
ldFlags = ldArgs <> (getStagedSettingList ConfGccLinkerArgs)
cppFlags = cppArgs <> (getStagedSettingList ConfCppArgs)
cldFlags <- unwords <$> (cFlags <> ldFlags)
mconcat
[ conf "CFLAGS" cFlags
, conf "LDFLAGS" ldFlags
, conf "CPPFLAGS" cppFlags
, not (null cldFlags) ? arg ("--gcc-options=" ++ cldFlags)
, conf "--with-iconv-includes" $ arg =<< getSetting IconvIncludeDir
, conf "--with-iconv-libraries" $ arg =<< getSetting IconvLibDir
, conf "--with-gmp-includes" $ arg =<< getSetting GmpIncludeDir
, conf "--with-gmp-libraries" $ arg =<< getSetting GmpLibDir
, conf "--with-curses-libraries" $ arg =<< getSetting CursesLibDir
, crossCompiling ? (conf "--host" $ arg =<< getSetting TargetPlatformFull)
, conf "--with-cc" $ arg =<< getBuilderPath . (Cc CompileC) =<< getStage ]
bootPackageConstraints :: Args
bootPackageConstraints = stage0 ? do
bootPkgs <- expr $ stagePackages Stage0
let pkgs = filter (\p -> p /= compiler && isLibrary p) bootPkgs
constraints <- expr $ forM (sort pkgs) $ \pkg -> do
version <- pkgVersion pkg
return (pkgName pkg ++ " == " ++ version)
pure $ concat [ ["--constraint", c] | c <- constraints ]
cppArgs :: Args
cppArgs = do
root <- getBuildRoot
arg $ "-I" ++ root -/- generatedDir
withBuilderKey :: Builder -> String
withBuilderKey b = case b of
Ar _ -> "--with-ar="
Ld -> "--with-ld="
Cc _ _ -> "--with-gcc="
Ghc _ _ -> "--with-ghc="
Alex -> "--with-alex="
Happy -> "--with-happy="
GhcPkg _ _ -> "--with-ghc-pkg="
HsColour -> "--with-hscolour="
_ -> error $ "withBuilderKey: not supported builder " ++ show b
-- Expression 'with Alex' appends "--with-alex=/path/to/alex" and needs Alex.
with :: Builder -> Args
with b = isSpecified b ? do
top <- expr topDirectory
path <- getBuilderPath b
expr $ needBuilder b
arg $ withBuilderKey b ++ unifyPath (top </> path)
withStaged :: (Stage -> Builder) -> Args
withStaged sb = with . sb =<< getStage
-- This is a positional argument, hence:
-- * if it is empty, we need to emit one empty string argument;
-- * otherwise, we must collapse it into one space-separated string.
dll0Args :: Args
dll0Args = do
context <- getContext
dll0 <- expr $ buildDll0 context
withGhci <- expr ghcWithInterpreter
arg . unwords . concat $ [ modules | dll0 ]
++ [ ghciModules | dll0 && withGhci ] -- see #9552
where
modules = [ "Annotations"
, "ApiAnnotation"
, "Avail"
, "Bag"
, "BasicTypes"
, "Binary"
, "BooleanFormula"
, "BreakArray"
, "BufWrite"
, "Class"
, "CmdLineParser"
, "CmmType"
, "CoAxiom"
, "ConLike"
, "Coercion"
, "Config"
, "Constants"
, "CoreArity"
, "CoreFVs"
, "CoreSubst"
, "CoreSyn"
, "CoreTidy"
, "CoreUnfold"
, "CoreUtils"
, "CoreSeq"
, "CoreStats"
, "CostCentre"
, "Ctype"
, "DataCon"
, "Demand"
, "Digraph"
, "DriverPhases"
, "DynFlags"
, "Encoding"
, "ErrUtils"
, "Exception"
, "ExtsCompat46"
, "FamInstEnv"
, "FastFunctions"
, "FastMutInt"
, "FastString"
, "FastTypes"
, "Fingerprint"
, "FiniteMap"
, "ForeignCall"
, "Hooks"
, "HsBinds"
, "HsDecls"
, "HsDoc"
, "HsExpr"
, "HsImpExp"
, "HsLit"
, "PlaceHolder"
, "HsPat"
, "HsSyn"
, "HsTypes"
, "HsUtils"
, "HscTypes"
, "IOEnv"
, "Id"
, "IdInfo"
, "IfaceSyn"
, "IfaceType"
, "InstEnv"
, "Kind"
, "Lexeme"
, "Lexer"
, "ListSetOps"
, "Literal"
, "Maybes"
, "MkCore"
, "MkId"
, "Module"
, "MonadUtils"
, "Name"
, "NameEnv"
, "NameSet"
, "OccName"
, "OccurAnal"
, "OptCoercion"
, "OrdList"
, "Outputable"
, "PackageConfig"
, "Packages"
, "Pair"
, "Panic"
, "PatSyn"
, "PipelineMonad"
, "Platform"
, "PlatformConstants"
, "PprCore"
, "PrelNames"
, "PrelRules"
, "Pretty"
, "PrimOp"
, "RdrName"
, "Rules"
, "Serialized"
, "SrcLoc"
, "StaticFlags"
, "StringBuffer"
, "TcEvidence"
, "TcRnTypes"
, "TcType"
, "TrieMap"
, "TyCon"
, "Type"
, "TypeRep"
, "TysPrim"
, "TysWiredIn"
, "Unify"
, "UniqFM"
, "UniqSet"
, "UniqSupply"
, "Unique"
, "Util"
, "Var"
, "VarEnv"
, "VarSet" ]
ghciModules = [ "Bitmap"
, "BlockId"
, "ByteCodeAsm"
, "ByteCodeInstr"
, "ByteCodeItbls"
, "CLabel"
, "Cmm"
, "CmmCallConv"
, "CmmExpr"
, "CmmInfo"
, "CmmMachOp"
, "CmmNode"
, "CmmSwitch"
, "CmmUtils"
, "CodeGen.Platform"
, "CodeGen.Platform.ARM"
, "CodeGen.Platform.ARM64"
, "CodeGen.Platform.NoRegs"
, "CodeGen.Platform.PPC"
, "CodeGen.Platform.PPC_Darwin"
, "CodeGen.Platform.SPARC"
, "CodeGen.Platform.X86"
, "CodeGen.Platform.X86_64"
, "FastBool"
, "InteractiveEvalTypes"
, "MkGraph"
, "PprCmm"
, "PprCmmDecl"
, "PprCmmExpr"
, "Reg"
, "RegClass"
, "SMRep"
, "StgCmmArgRep"
, "StgCmmClosure"
, "StgCmmEnv"
, "StgCmmLayout"
, "StgCmmMonad"
, "StgCmmProf"
, "StgCmmTicky"
, "StgCmmUtils"
, "StgSyn"
, "Stream" ]
| izgzhen/hadrian | src/Settings/Builders/GhcCabal.hs | mit | 9,977 | 0 | 17 | 4,267 | 1,795 | 983 | 812 | 280 | 9 |
import Data.Char (isAlphaNum)
import Data.List (elemIndex, sortOn)
import Data.Maybe (fromMaybe)
import Data.Bits (xor, (.|.), (.&.), unsafeShiftL, unsafeShiftR, shift)
import Data.Int (Int64)
import Data.Hashable
import qualified Data.Map.Strict as M
import qualified Data.Sequence as S
import qualified Data.HashSet as HS
-- an item (generator or microchip) is represented as a single bit
-- generators have even positions while microchips have the next odd positions
-- for example:
-- thorium generator -> bit #0 (0x1)
-- thorium microchip -> bit #1 (0x2)
-- plutonium generator -> bit #2 (0x4)
-- plutonium microchip -> bit #3 (0x8)
type Item = Int64
-- an item set is a group (bitwise or) of multiple items
-- thorium generator and thorium microchip and plutonium microchip
-- = 0x1 | 0x2 | 0x8 = 0xb
type ItemSet = Int64
-- the state represents the current floor (first Int) and the sets for all floors
-- the sets for the floors are all stored in a single Int64 type
-- since there are always 4 floors it means that there is space for 64 / 4 / 2 =
-- 8 types of elements
-- this is more than enough for this problem
data State = State
{-# UNPACK #-} !Int
{-# UNPACK #-} !ItemSet
deriving (Show, Eq, Ord)
-- needed for compatibility with Data.HashSet
instance Hashable State where
hashWithSalt s (State f v) = s `xor` f `xor` fromIntegral v
hash (State f v) = f `xor` fromIntegral v
-- number of bits per floor in the State
stateFloorSize :: Int
stateFloorSize = 16
-- mask for a floor in the State
stateFloorMask :: ItemSet
stateFloorMask = 0xffff
-- iinitialize state with floor number and list of floor item sets
initState :: Int -> [ItemSet] -> State
initState f = State f . foldl xor 0 .
zipWith (\i v -> v `unsafeShiftL` (i * stateFloorSize)) [0..]
-- returns the current floor number
getFloor :: State -> Int
getFloor (State f _) = f
-- returns the current floor items
getFloorItems :: State -> ItemSet
getFloorItems s@(State f _) = getFloorItems' s f
-- returns the floor items of the given floor
getFloorItems' :: State -> Int -> ItemSet
getFloorItems' (State _ v) f =
fromIntegral $ v `unsafeShiftR` (f * stateFloorSize) .&. stateFloorMask
-- updates the floor sets and increments the floor number
-- is represents the item set of items that will move
-- warning: it doesn't check if the move is valid by any means
moveUp :: State -> ItemSet -> State
moveUp (State f v) is = let
-- shift for the current floor
shift1 = f * stateFloorSize
-- shift for the upper floor
shift2 = shift1 + stateFloorSize
in
State (f + 1) (v `xor` (is `unsafeShiftL` shift1) `xor` (is `unsafeShiftL` shift2))
-- like moveUp
moveDown :: State -> ItemSet -> State
moveDown (State f v) is = let
shift1 = f * stateFloorSize
shift2 = shift1 - stateFloorSize
in
State (f - 1) (v `xor` (is `unsafeShiftL` shift1) `xor` (is `unsafeShiftL` shift2))
-- checks if the state is final (elevator at 4th floor and all floors below 4 empty)
stateIsFinal :: State -> Bool
stateIsFinal (State f v) = f == 3 && v .&. 0xffffffffffff == 0
-- given an item set and a start item it returns a sequence of all the individual
-- items in the set
expandItemSet :: ItemSet -> Item -> S.Seq ItemSet
expandItemSet v p
| p > v = S.empty
| v .&. p /= 0 = p S.<| expandItemSet v (p `unsafeShiftL` 1)
| otherwise = expandItemSet v (p `unsafeShiftL` 1)
-- builds an item set based item list
combineItems :: [Item] -> ItemSet
combineItems = foldl (.|.) 0
-- parses a list of words into a list of items descriptions
-- returns list of items like ('G', generator_name) or ('M', microchip_name)
parseItemList :: [String] -> [(Char, String)]
parseItemList [] = []
parseItemList ["nothing", "relevant"] = []
parseItemList ("and":xs) = parseItemList xs
parseItemList ("a":name:"microchip":xs) =
('M', take (length name - 10) name) : parseItemList xs
parseItemList ("a":name:"generator":xs) =
('G', name) : parseItemList xs
parseItemList p = error $ show p
-- parses a line from the input file
-- returns a (floor_number, list_of_items)
parseFloor :: String -> (Int, [(Char, String)])
parseFloor "" = (-1, [])
parseFloor str = let
-- remove punction marks and "and"
parts = filter (/="and") . map (filter isAlphaNum) $ words str
floorno = fromMaybe (-1) $
elemIndex (parts !! 1) ["first", "second", "third", "fourth"]
in
(floorno, parseItemList $ drop 4 parts)
-- converts the result of parseFloor into a numberical representation of
-- items conforming with the description of ItemSet
-- returns a pair containing the list of items on each floor and the map of
-- name -> bit pos / 2 associations
dataToNumeric :: [[(Char, String)]] -> ([[Item]], M.Map String Int)
dataToNumeric lst = let
-- assigns each element a unique number starting from 0
helper :: [(Char, String)] -> M.Map String Int -> M.Map String Int
helper [] m = m
helper ((_, name):xs) m = case M.lookup name m of
Just _ -> helper xs m
Nothing -> helper xs (M.insert name (M.size m) m)
names = helper (concat lst) M.empty
-- converts an item generated by parseItemList into a Item
convert :: (Char, String) -> Item
convert ('G', name) = 1 `shift` (2 * M.findWithDefault 0 name names)
convert ('M', name) = 1 `shift` (1 + 2 * M.findWithDefault 0 name names)
convert x = error $ show x
in
(map (map convert) lst, names)
-- checks if the state is valid (no floor has an unshielded microchip and at
-- least one generator)
checkState :: State -> Bool
checkState state = let
-- first bool of pair is true if an unshielded microchip exists
-- second bool of pair is true if at least one generator exists
checkIS :: ItemSet -> (Bool, Bool) -> Bool
checkIS 0 (mc, g) = not $ mc && g
checkIS _ (True, True) = False
checkIS i (mc, g) =
-- the way item sets are encoded allows very easy check for
-- unshielded microchip
checkIS (i `unsafeShiftR` 2) (mc || i .&. 3 == 2, g || i .&. 1 == 1)
in
all (\i -> checkIS (getFloorItems' state i) (False, False)) [0, 1, 2, 3]
-- given a state it returns all the valid states it can reach in one step
expandState :: State -> S.Seq State
expandState state = let
-- items on the current floor
allItems = getFloorItems state
newItemsHelper :: S.Seq ItemSet -> Item -> S.Seq ItemSet
newItemsHelper s i =
i S.<| foldl (\ss ii -> (i .|. ii) S.<| ss) s
(expandItemSet allItems (i `unsafeShiftL` 1))
-- pairs of items it can move
newItems :: S.Seq ItemSet
newItems = foldl newItemsHelper S.empty $ expandItemSet allItems 1
-- states when trying to move down
sdown = if getFloor state == 0 then S.empty else
S.filter checkState $ fmap (moveDown state) newItems
-- states when trying to move up
sup = if getFloor state == 3 then S.empty else
S.filter checkState $ fmap (moveUp state) newItems
in
sup S.>< sdown
-- solves the problem using a BFS
solveBFS :: State -> Int
solveBFS state = let
-- expands the state, filters out already visited states
-- returns the number of moves needed to reach the final state
step :: S.Seq (State, Int) -> HS.HashSet State -> Int
step q found
| stateIsFinal s = d
| otherwise = let
states = S.filter (not . flip HS.member found) $ expandState s
in
step
(qs S.>< fmap (\x -> (x, d + 1)) states)
(foldl (flip HS.insert) found states)
where ((s, d), qs) = (S.index q 0, S.drop 1 q)
in
step (S.singleton (state, 0)) (HS.singleton state)
main :: IO ()
main = do
contents <- readFile "input.txt"
let floors1 = map parseFloor $ lines contents
let (items1, _) = dataToNumeric . map snd . sortOn fst $ floors1
let initialState1 = initState 0 $ map combineItems items1
-- this should run fast
print $ solveBFS initialState1
let extra2 = [('G', "elerium"), ('M', "elerium"), ('G', "dilithium"), ('M', "dilithium")]
-- add extra2 to the first floor
let floors2 = (0, snd (head floors1) ++ extra2) : tail floors1
let (items2, _) = dataToNumeric . map snd . sortOn fst $ floors2
let initialState2 = initState 0 $ map combineItems items2
-- this will take some time
print $ solveBFS initialState2
| bno1/adventofcode_2016 | d11/main.hs | mit | 8,672 | 0 | 19 | 2,226 | 2,394 | 1,296 | 1,098 | 126 | 5 |
module Bitcoin.MerkleTree (
mtHash,
mtLeft, mtRight,
merkleTree
) where
import Data.Tree
import Bitcoin.Crypto
import qualified Data.ByteString as B
type MerkleTree = Tree Hash
-- | get the hash from a node
mtHash :: MerkleTree -> Hash
mtHash = rootLabel
-- | get the left child of a node
mtLeft :: MerkleTree -> MerkleTree
mtLeft t = subForest t !! 0
-- | get the right child of a node
mtRight :: MerkleTree -> MerkleTree
mtRight t = subForest t !! 1
-- | test with official data from here:
-- | http://blockexplorer.com/block/000000000000011278004e50a6cf8f2c8abbaf1fa7d030cc3e8573ac3476efe1
--
-- small function to convert from blockexplorer strings to hashes
-- >>> let getHash = Hash . B.reverse . fst . B16.decode . B.fromString
--
-- hashes from block 230006
-- >>> let a = getHash "4a4e3dbdac02401e355a76b2268e5ed9251c4386a5a0de5cf34fdfb2aef68b80"
-- >>> let b = getHash "07583643e9368492602051dbe52068802c7039c64c6defeeedd1f8a39c7737bc"
-- >>> let c = getHash "303a3bfa5007cedbaf4e5acd7e8a591c7f405b0f4834675617ded260239a1698"
-- >>> let d = getHash "5443fbb50ecd9c92713d8dec0700da85fa70a62018df9b56f86ccdd61293f2ae"
-- >>> let e = getHash "3297b0a7f724484d4cdc05446aea1c9de17f5c0ee667dc299a631b764fb35f34"
-- >>> let f = getHash "3c80aa36716cbc21686cbb252e474d49433330afa8ff14b11c17e5a59ef3411e"
--
-- calculate merkle tree and get root node
-- >>> let t = mtHash $ merkleTree [a,b,c,d,e,f]
--
-- merkle root from block 230006
-- >>> let r = getHash "3d55e5375ff7c223c2c3140fe3b1bf3701c53dbfb14154c302eeb716f872dd2b"
--
-- compare them
-- >>> t == r
-- True
merkleTree :: [Hash] -> MerkleTree
merkleTree hs = head . merkleTree' $ hs'
where hs' = map (`Node` []) hs
merkleTree' :: [MerkleTree] -> [MerkleTree]
merkleTree' hs | null $ tail hs = hs
| otherwise = merkleTree' $ go hs
where go (a:b:xs) = subTree a b : go xs
go (a:[]) = [subTree a a]
go [] = []
subTree a b =
Node (hashConcat (mtHash a) (mtHash b)) [a, b]
-- | combine two hashes by concatinating them and hash the resulting string
hashConcat :: Hash -> Hash -> Hash
hashConcat a b = btcHash $ B.append (unHash a) (unHash b)
| fhaust/bitcoin | src/Bitcoin/MerkleTree.hs | mit | 2,190 | 0 | 11 | 406 | 393 | 220 | 173 | 27 | 3 |
import Data.Char
main = do
contents <- getContents
putStrLn $ map toUpper contents
| yhoshino11/learning_haskell | ch9/capslocker_success.hs | mit | 88 | 0 | 8 | 18 | 30 | 14 | 16 | 4 | 1 |
module Data.CSV.Table.Email
( -- * Email representation
Email (..)
-- * Send function
, sendMail
) where
import Text.Printf (printf)
import System.Process
import Control.Monad (forM_)
import Data.List (intercalate)
import Data.CSV.Table.Types
import Data.CSV.Table.Ops
data Email = E { uid :: String
, to :: String
, cc :: [String]
, sender :: String
, subject :: String
, text :: String
, send :: Bool
} deriving (Show)
sendMail :: Table -> (RowInfo -> Email) -> IO ()
sendMail t f = forM_ (mapRows f t) sendMail1
sendMail1 :: Email -> IO ()
sendMail1 e = do
let tmp = uid e
let cmd = mailCmd e
writeFile tmp (text e)
status <- if send e then show `fmap` system cmd else return "FAKESEND"
putStrLn $ printf "[exec: %s] Status[%s]: %s %s" cmd status (uid e) (to e)
mailCmd :: Email -> String
mailCmd e =
printf "mail -s \"%s\" -aFrom:%s %s %s < %s" (subject e) (sender e) (to e) (ccs $ cc e) (uid e)
where
ccs [] = ""
ccs xs = "-c " ++ intercalate "," xs
| ucsd-progsys/csv-table | src/Data/CSV/Table/Email.hs | mit | 1,188 | 0 | 10 | 413 | 393 | 212 | 181 | 32 | 2 |
{-# LANGUAGE CPP #-}
module Import.NoFoundation
( module Import
, renderForm
, submitButton
) where
import ClassyPrelude.Yesod as Import
import Model as Import
import Settings as Import
import Settings.StaticFiles as Import
import Yesod.Auth as Import
import Yesod.Core.Types as Import (loggerSet)
import Yesod.Default.Config2 as Import
import Yesod.Form.Bootstrap3
renderForm :: Monad m => FormRender m a
renderForm = renderBootstrap3 dims
where
dims = BootstrapHorizontalForm (ColSm 0)
(ColSm 4)
(ColSm 0)
(ColSm 6)
submitButton :: MonadHandler m => Text -> AForm m ()
submitButton name = bootstrapSubmit
$ BootstrapSubmit
(name :: Text)
"btn-default"
[("attribute-name","attribute-value")]
| ranjitjhala/gradr | Import/NoFoundation.hs | mit | 972 | 0 | 9 | 370 | 199 | 117 | 82 | 25 | 1 |
--1.Mostre os resultados das seguintes expressões:
--1.1 / > [1,2,3,4] ++ [9,10,11,12]
con :: [Int] -> [Int] -> [Int]
con x y = x++y
--1.2 / > "hello" ++ " " ++ "world"
sayhello :: String -> String -> String
sayhello x y = x ++ y
--1.3 / > 5:[1,2,3,4,5]
incluir :: Int -> [Int] -> [Int]
incluir x y = x:y
--1.4 / > [[1,2,3,4],[5,3,3,3],[1,2,2,3,4],[1,2,3]] ++ [[1,1,1,1]]
--conlista :: [Integer] -> [Integer] -> [Integer]
--conlista x y = x++y
--1.5 / [9.4,33.2,96.2,11.2,23.25] !! 1
posicao_n :: [Float] -> Int -> Float --2° Argumento deve ser do tipo Int vide propósito do argumento
posicao_n x y = x !! y --x = Lista e y = Posição
--1.6 / head [5,4,3,2,1] -- Apenas o primeiro elemento da lista é retornado
funchead :: [Integer] -> Integer
funchead x = head x
--1.7 / tail [5,4,3,2,1] -- Retorna o corpo da lista
functail :: [Integer] -> [Integer]
functail x = tail x
{-2. Qual o resultado das expressões a seguir? Justifique.
> snd (fst ((True, 4), "Bom"))
1° Passo: 1ª Lista é ((True, 4), "Bom")) que retorna (True, 4)
2° Passo: 2° Elemento da Lista (True, 4) é 4
Hugs> snd(fst((True, 4), "Bom"))
4
> fst ((True, 'a'), 7)
Hugs> fst ((True, 'a'), 7)
(True,'a')
>snd (snd ((True, 4), (False, 7)))
Hugs> snd (snd ((True, 4), (False, 7)))
7
-}
{-
3. Implemente uma função que receba o primeiro e o último nome de alguém e retorne suas iniciais em uma tupla. Por exemplo:
> iniciais "Sara" "Luzia"
('S','L')
-}
e3 :: String -> String -> (Char,Char)
e3 x1 x2 = (head(x1),head(x2))
{-
4. Faça uma função que receba o nome de um aluno e uma lista com suas três notas. A função deve então devolver uma tupla com o nome do aluno e a média das notas. Exemplo:
> aprovado "Joao" [80, 60, 100]
("Joao", 80)
-}
e4 :: String -> [Float] -> (String, Float)
e4 nome notas = (nome, sum notas / 3)
--al_media nome notas = (nome, sum notas / fromIntegral(length notas)) --Para uma média perfeita que conta quantos elementos uma lista possui e retorna um número inteiro para a divisão.
{-
5. Diga quais são os tipos das seguintes expressões:
a) False
b) (["foo", "bar"], 'a')
c) [(True, []), (False, [['a']])]
d) 2.5
e) (1, 1.5, 2.5, 10)
Hugs> :type False
False :: Bool
Hugs> :type (["foo", "bar"], 'a')
(["foo","bar"],'a') :: ([[Char]],Char)
Hugs> :type [(True, []), (False, [['a']])]
[(True,[]),(False,[['a']])] :: [(Bool,[[Char]])]
Hugs> :type 2.5
2.5 :: Fractional a => a
Hugs> :type (1, 1.5, 2.5, 10)
(1,1.5,2.5,10) :: (Num a, Fractional b, Fractional c, Num d) => (d,c,b,a)
-}
{-
6. Crie as seguintes funções em Haskell definindo corretamente os tipos de dados.
a) Função para calcular a média de 4 números em ponto flutuante.
b) Função soma de 3 números inteiros.
c) Função que retorne a raiz quadrada de um número real. Utilize a função sqrt para o cálculo da raiz.
-}
e6a :: Float -> Float -> Float -> Float -> Float
e6a x1 x2 x3 x4 = (x1+x2+x3+x4)/4
e6b :: Int -> Int -> Int -> Int
e6b x1 x2 x3 = x1+x2+x3
e6c :: Float -> Float
e6c x1 = sqrt(x1)
{-
7. Defina uma lista por compreensão onde cada posição é uma tupla (x,y), com x < y, assumindo x como valores pertencentes à lista [1,3,5] e y pertencente a [2,4,6].
-}
e7 :: [(Int,Int)]
e7 = [(x,y) | x<-[1,3,5], y<-[2,4,6], x<y]
{-
8. Defina a lista abaixo por compreensão:
[0,3,6,9,12,15]
-}
e8 :: [Int]
e8 = [x | x<-[0,3..15]]
| hugonasciutti/Exercises | Haskell/Exercises/pratica2.hs | mit | 3,380 | 0 | 9 | 656 | 504 | 285 | 219 | 26 | 1 |
collatz :: Int -> Int
collatz n
| n `mod` 2 == 0 = n `div` 2
| otherwise = 3 * n + 1
countStepsToOne :: Int -> Int
countStepsToOne n = length (takeWhile (/=1) (iterate collatz n))
main = print $ countStepsToOne 10
| kdungs/coursework-functional-programming | 02/collatz.hs | mit | 229 | 0 | 9 | 60 | 109 | 56 | 53 | 7 | 1 |
module Unison.Test.Common where
import qualified Data.Map as Map
import qualified Unison.Builtin as B
import qualified Unison.FileParsers as FP
import Unison.Symbol (Symbol)
import Unison.Term (Term)
import Unison.Type (Type)
import qualified Unison.Typechecker as Typechecker
import qualified Unison.Result as Result
import Unison.Result (Result,Note)
tm :: String -> Term Symbol
tm = B.tm
file :: String -> Result (Note Symbol ()) (Term Symbol, Type Symbol)
file = FP.parseAndSynthesizeAsFile ""
fileTerm :: String -> Result (Note Symbol ()) (Term Symbol)
fileTerm = fmap fst . FP.parseAndSynthesizeAsFile "<test>"
fileTermType :: String -> Maybe (Term Symbol, Type Symbol)
fileTermType = Result.toMaybe . FP.parseAndSynthesizeAsFile "<test>"
t :: String -> Type Symbol
t = B.t
typechecks :: String -> Bool
typechecks = Result.isSuccess . file
env :: Monad m => Typechecker.Env m Symbol ()
env = Typechecker.Env () [] typeOf dd ed where
typeOf r = maybe (error $ "no type for: " ++ show r) pure $ Map.lookup r B.builtins
dd r = error $ "no data declaration for: " ++ show r
ed r = error $ "no effect declaration for: " ++ show r
typechecks' :: Term Symbol -> Bool
typechecks' term = Result.isSuccess $ Typechecker.synthesize env term
check' :: Term Symbol -> Type Symbol -> Bool
check' term typ = Result.isSuccess $ Typechecker.check env term typ
check :: String -> String -> Bool
check terms typs = check' (tm terms) (t typs)
| paulp/unison | parser-typechecker/tests/Unison/Test/Common.hs | mit | 1,476 | 0 | 11 | 274 | 523 | 275 | 248 | 33 | 1 |
{-
- Дадено е двоично наредено дърво, в което всеки връх съдържа цяло число и
- разликата на височините на двете му поддървета.
- Да се напише функция specialInsert x tree, която добавя връх със стойност
- x в двоичното наредено дърво tree (като правилно обновява разликите във
- височините за всеки връх).
-}
data Tree a = Empty | Node Int a (Tree a) (Tree a) deriving (Show)
tree = (Node 0 10 (Node 0 6 Empty Empty)
(Node 0 15 Empty Empty))
treeInsert :: Ord a => Tree a -> a -> Tree a
treeInsert Empty x = (Node 0 x Empty Empty)
treeInsert (Node diff root left right) x
| x < root = (Node diff root (treeInsert left x) right)
| otherwise = (Node diff root left (treeInsert right x))
updateDiffs :: Tree a -> Tree a
updateDiffs Empty = Empty
updateDiffs (Node _ root left right) =
(Node heightDiff root (updateDiffs left) (updateDiffs right))
where heightDiff = abs ((height left) - (height right))
height :: Tree a -> Int
height Empty = 0
height (Node _ _ left right) = 1 + max (height left) (height right)
specialInsert x tree = updateDiffs $ treeInsert tree x
| fmi-lab/fp-elective-2017 | exams/preparation/treeDifference.hs | mit | 1,325 | 0 | 11 | 243 | 386 | 192 | 194 | 17 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-tagoption.html
module Stratosphere.Resources.ServiceCatalogTagOption where
import Stratosphere.ResourceImports
-- | Full data type definition for ServiceCatalogTagOption. See
-- 'serviceCatalogTagOption' for a more convenient constructor.
data ServiceCatalogTagOption =
ServiceCatalogTagOption
{ _serviceCatalogTagOptionActive :: Maybe (Val Bool)
, _serviceCatalogTagOptionKey :: Val Text
, _serviceCatalogTagOptionValue :: Val Text
} deriving (Show, Eq)
instance ToResourceProperties ServiceCatalogTagOption where
toResourceProperties ServiceCatalogTagOption{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::ServiceCatalog::TagOption"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ fmap (("Active",) . toJSON) _serviceCatalogTagOptionActive
, (Just . ("Key",) . toJSON) _serviceCatalogTagOptionKey
, (Just . ("Value",) . toJSON) _serviceCatalogTagOptionValue
]
}
-- | Constructor for 'ServiceCatalogTagOption' containing required fields as
-- arguments.
serviceCatalogTagOption
:: Val Text -- ^ 'sctoKey'
-> Val Text -- ^ 'sctoValue'
-> ServiceCatalogTagOption
serviceCatalogTagOption keyarg valuearg =
ServiceCatalogTagOption
{ _serviceCatalogTagOptionActive = Nothing
, _serviceCatalogTagOptionKey = keyarg
, _serviceCatalogTagOptionValue = valuearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-tagoption.html#cfn-servicecatalog-tagoption-active
sctoActive :: Lens' ServiceCatalogTagOption (Maybe (Val Bool))
sctoActive = lens _serviceCatalogTagOptionActive (\s a -> s { _serviceCatalogTagOptionActive = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-tagoption.html#cfn-servicecatalog-tagoption-key
sctoKey :: Lens' ServiceCatalogTagOption (Val Text)
sctoKey = lens _serviceCatalogTagOptionKey (\s a -> s { _serviceCatalogTagOptionKey = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-tagoption.html#cfn-servicecatalog-tagoption-value
sctoValue :: Lens' ServiceCatalogTagOption (Val Text)
sctoValue = lens _serviceCatalogTagOptionValue (\s a -> s { _serviceCatalogTagOptionValue = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/ServiceCatalogTagOption.hs | mit | 2,487 | 0 | 15 | 309 | 370 | 211 | 159 | 36 | 1 |
module Lazy
F :: Bool -> () -> Bool
f x = \_ -> x
| ostera/asdf | haskell/Lazy.hs | mit | 51 | 2 | 5 | 16 | 24 | 14 | 10 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration-shutdowneventconfiguration.html
module Stratosphere.ResourceProperties.OpsWorksLayerShutdownEventConfiguration where
import Stratosphere.ResourceImports
-- | Full data type definition for OpsWorksLayerShutdownEventConfiguration.
-- See 'opsWorksLayerShutdownEventConfiguration' for a more convenient
-- constructor.
data OpsWorksLayerShutdownEventConfiguration =
OpsWorksLayerShutdownEventConfiguration
{ _opsWorksLayerShutdownEventConfigurationDelayUntilElbConnectionsDrained :: Maybe (Val Bool)
, _opsWorksLayerShutdownEventConfigurationExecutionTimeout :: Maybe (Val Integer)
} deriving (Show, Eq)
instance ToJSON OpsWorksLayerShutdownEventConfiguration where
toJSON OpsWorksLayerShutdownEventConfiguration{..} =
object $
catMaybes
[ fmap (("DelayUntilElbConnectionsDrained",) . toJSON) _opsWorksLayerShutdownEventConfigurationDelayUntilElbConnectionsDrained
, fmap (("ExecutionTimeout",) . toJSON) _opsWorksLayerShutdownEventConfigurationExecutionTimeout
]
-- | Constructor for 'OpsWorksLayerShutdownEventConfiguration' containing
-- required fields as arguments.
opsWorksLayerShutdownEventConfiguration
:: OpsWorksLayerShutdownEventConfiguration
opsWorksLayerShutdownEventConfiguration =
OpsWorksLayerShutdownEventConfiguration
{ _opsWorksLayerShutdownEventConfigurationDelayUntilElbConnectionsDrained = Nothing
, _opsWorksLayerShutdownEventConfigurationExecutionTimeout = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration-shutdowneventconfiguration.html#cfn-opsworks-layer-lifecycleconfiguration-shutdowneventconfiguration-delayuntilelbconnectionsdrained
owlsecDelayUntilElbConnectionsDrained :: Lens' OpsWorksLayerShutdownEventConfiguration (Maybe (Val Bool))
owlsecDelayUntilElbConnectionsDrained = lens _opsWorksLayerShutdownEventConfigurationDelayUntilElbConnectionsDrained (\s a -> s { _opsWorksLayerShutdownEventConfigurationDelayUntilElbConnectionsDrained = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-opsworks-layer-lifecycleeventconfiguration-shutdowneventconfiguration.html#cfn-opsworks-layer-lifecycleconfiguration-shutdowneventconfiguration-executiontimeout
owlsecExecutionTimeout :: Lens' OpsWorksLayerShutdownEventConfiguration (Maybe (Val Integer))
owlsecExecutionTimeout = lens _opsWorksLayerShutdownEventConfigurationExecutionTimeout (\s a -> s { _opsWorksLayerShutdownEventConfigurationExecutionTimeout = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/OpsWorksLayerShutdownEventConfiguration.hs | mit | 2,764 | 0 | 12 | 206 | 265 | 152 | 113 | 27 | 1 |
module Yahtzee.ScoreCard where
import Text.Printf
import Text.Show.Functions
import Data.Tuple.Select
import Yahtzee.Scoring
data Score = Score Int | NoValue
instance Show Score where
show NoValue = " -"
show (Score n) = printf "%3d" n
type CategoryName = String
type CategoryId = Char
type ScoreFn = [Int] -> Int
type Category = (CategoryId, CategoryName, Score, ScoreFn)
type ScoreCard = [Category]
total :: [Score] -> Int
total [] = 0
total ((Score n):rest) = n + (total rest)
total (NoValue:rest) = total rest
getCategory :: CategoryId -> ScoreCard -> Category
getCategory cid card = head $ dropWhile wrong card
where wrong cat = (/=) cid $ sel1 cat
updateCategory :: Category -> ScoreCard -> ScoreCard
updateCategory new card = takeWhile wrong card ++ [new] ++ tail (dropWhile wrong card)
where cid = sel1 new
wrong cat = (/=) cid $ sel1 cat
emptyScoreCard = [
('a', "Ones", NoValue, scoreN 1),
('b', "Twos", NoValue, scoreN 2),
('c', "Threes", NoValue, scoreN 3),
('d', "Fours", NoValue, scoreN 4),
('e', "Fives", NoValue, scoreN 5),
('f', "Sixes", NoValue, scoreN 6),
('g', "Small straight", NoValue, scoreSmallStraight),
('h', "Large straight", NoValue, scoreLargeStraight),
('i', "Three of a kind", NoValue, scoreThreeOfAKind),
('j', "Four of a kind", NoValue, scoreFourOfAKind),
('k', "Full house", NoValue, scoreFullHouse),
('l', "Yahtzee", NoValue, scoreYahtzee),
('m', "Chance", NoValue, scoreChance)]
| kvalle/yahtzee.hs | src/Yahtzee/ScoreCard.hs | mit | 1,505 | 0 | 9 | 300 | 550 | 319 | 231 | 39 | 1 |
# DataVisualization
Data Visualization notes and exercises from the course in [Udacity](https://www.udacity.com/courses/ud507).
I expect to finish this in February'16 and share all my exercises here. If you want some explanation or contribute something to this repository you're welcome.
Why?
--
I think sharing this publicly will force me to make an effort to finish the course(I have never finished an online course or a MOOC, shame on me) and make progress continuosly. | hectorip/DataVisualization | 116113-68964-1vwzjm6.hs | cc0-1.0 | 477 | 0 | 15 | 76 | 188 | 93 | 95 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables, ExistentialQuantification, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
-- | This module defines implementations of syntax-awareness drivers.
module Yi.Syntax.Driver where
import qualified Data.Map as M
import Data.Map (Map)
import Yi.Buffer.Basic(WindowRef)
import Yi.Lexer.Alex (Tok)
import Yi.Syntax hiding (Cache)
import Yi.Syntax.Tree
type Path = [Int]
data Cache state tree tt = Cache {
path :: M.Map WindowRef Path,
cachedStates :: [state],
root :: tree (Tok tt),
focused :: !(M.Map WindowRef (tree (Tok tt)))
}
mkHighlighter :: forall state tree tt. (IsTree tree, Show state) =>
(Scanner Point Char -> Scanner state (tree (Tok tt))) ->
Highlighter (Cache state tree tt) (tree (Tok tt))
mkHighlighter scanner =
Yi.Syntax.SynHL
{ hlStartState = Cache M.empty [] emptyResult M.empty
, hlRun = updateCache
, hlGetTree = \(Cache _ _ _ focused) w -> M.findWithDefault emptyResult w focused
, hlFocus = focus
}
where startState :: state
startState = scanInit (scanner emptyFileScan)
emptyResult = scanEmpty (scanner emptyFileScan)
updateCache :: Scanner Point Char -> Point -> Cache state tree tt -> Cache state tree tt
updateCache newFileScan dirtyOffset (Cache path cachedStates oldResult _) = Cache path newCachedStates newResult M.empty
where newScan = scanner newFileScan
reused :: [state]
reused = takeWhile ((< dirtyOffset) . scanLooked (scanner newFileScan)) cachedStates
resumeState :: state
resumeState = if null reused then startState else last reused
newCachedStates = reused ++ fmap fst recomputed
recomputed = scanRun newScan resumeState
newResult :: tree (Tok tt)
newResult = if null recomputed then oldResult else snd $ head recomputed
focus r (Cache path states root _focused) =
Cache path' states root focused
where (path', focused) = unzipFM $ zipWithFM (\newpath oldpath -> fromNodeToFinal newpath (oldpath,root)) [] r path
unzipFM :: Ord k => [(k,(u,v))] -> (Map k u, Map k v)
unzipFM l = (M.fromList mu, M.fromList mv)
where (mu, mv) = unzip [((k,u),(k,v)) | (k,(u,v)) <- l]
zipWithFM :: Ord k => (u -> v -> w) -> v -> Map k u -> Map k v -> [(k,w)]
zipWithFM f v0 mu mv = [ (k,f u (M.findWithDefault v0 k mv) ) | (k,u) <- M.assocs mu]
| atsukotakahashi/wi | src/library/Yi/Syntax/Driver.hs | gpl-2.0 | 2,750 | 0 | 15 | 875 | 887 | 482 | 405 | 48 | 3 |
{--
-- Natume -- an implementation of Kana-Kanji conversion in Haskell
-- Copyright (C) 2006-2012 Takayuki Usui
--
-- 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--}
module Lib (
castInt,cint,call,
connect_init,connect_free,connect_start,connect_stop,
connect_add,connect_build,connect_load,connect_unload,
connect_search,connect_fetch,connect_dump,
dic_init,dic_free,dic_start,dic_stop,dic_add,dic_build,
dic_load,dic_unload,dic_update,dic_insert,
dic_search,dic_fetch,dic_dump,
canna_init,canna_free,canna_accept,canna_establish,
canna_request,canna_response,
) where
import Foreign.C.String
import Foreign.C.Types
import Foreign
castInt :: (Integral a, Integral b) => a -> b
castInt = fromInteger . toInteger
cint :: Int -> CInt
cint = castInt
call :: IO CInt -> IO Int
call x = x >>= (return . castInt)
foreign import ccall "static connect.h connect_init"
connect_init :: CString -> CString -> IO CInt
foreign import ccall "static connect.h connect_free"
connect_free :: CInt -> IO ()
foreign import ccall "static connect.h connect_start"
connect_start :: CInt -> IO CInt
foreign import ccall "static connect.h connect_stop"
connect_stop :: CInt -> IO ()
foreign import ccall "static connect.h connect_add"
connect_add :: CInt -> (Ptr CInt) -> CInt -> CInt -> IO CInt
foreign import ccall "static connect.h connect_build"
connect_build :: CInt -> IO CInt
foreign import ccall "static connect.h connect_load"
connect_load :: CInt -> IO CInt
foreign import ccall "static connect.h connect_unload"
connect_unload :: CInt -> IO ()
foreign import ccall "static connect.h connect_search"
connect_search :: CInt -> (Ptr CInt) -> CInt -> IO CInt
foreign import ccall "static connect.h connect_fetch"
connect_fetch :: CInt -> CInt -> (Ptr CInt) -> CInt -> (Ptr CInt) -> IO CInt
foreign import ccall "static connect.h connect_dump"
connect_dump :: CInt -> IO ()
foreign import ccall "static dic.h dic_init"
dic_init :: CString -> CString -> CString -> CString -> IO CInt
foreign import ccall "static dic.h dic_free"
dic_free :: CInt -> IO ()
foreign import ccall "static dic.h dic_start"
dic_start :: CInt -> IO CInt
foreign import ccall "static dic.h dic_stop"
dic_stop :: CInt -> IO ()
foreign import ccall "static dic.h dic_add"
dic_add :: CInt -> CString -> CString -> CInt -> CInt -> CInt -> IO CInt
foreign import ccall "static dic.h dic_build"
dic_build :: CInt -> IO CInt
foreign import ccall "static dic.h dic_load"
dic_load :: CInt -> IO CInt
foreign import ccall "static dic.h dic_unload"
dic_unload :: CInt -> IO ()
foreign import ccall "static dic.h dic_update"
dic_update :: CInt -> CInt -> CInt -> IO CInt
foreign import ccall "static dic.h dic_insert"
dic_insert :: CInt -> CString -> CString -> CInt -> CInt -> CInt -> IO CInt
foreign import ccall "static dic.h dic_search"
dic_search :: CInt -> CString -> CInt -> IO CInt
foreign import ccall "static dic.h dic_fetch"
dic_fetch :: CInt -> CInt -> (Ptr CString) -> (Ptr CString) ->
(Ptr CInt) -> (Ptr CInt) ->
(Ptr CInt) -> (Ptr CInt) -> (Ptr CInt) -> CInt -> CInt -> IO CInt
foreign import ccall "static dic.h dic_dump"
dic_dump :: CInt -> IO ()
foreign import ccall "static canna.h canna_init"
canna_init :: CString -> CInt -> CInt -> CInt -> IO CInt
foreign import ccall "static canna.h canna_free"
canna_free :: CInt -> IO ()
foreign import ccall "static canna.h canna_accept"
canna_accept :: CInt -> (Ptr CInt) -> (Ptr CInt) ->
(Ptr CInt) -> CString -> CInt -> IO CInt
foreign import ccall "static canna.h canna_establish"
canna_establish :: CInt -> (Ptr CInt) -> (Ptr CInt) ->
(Ptr CInt) -> (Ptr CInt) -> IO CInt
foreign import ccall "static canna.h canna_request"
canna_request :: CInt -> (Ptr CInt) -> (Ptr CInt) -> (Ptr CInt) ->
(Ptr CInt) -> (Ptr CInt) -> (Ptr CInt) -> CString -> CInt -> IO CInt
foreign import ccall "static canna.h canna_response"
canna_response :: CInt -> (Ptr CInt) -> (Ptr CInt) -> (Ptr CInt) ->
(Ptr CInt) -> (Ptr CInt) -> (Ptr CInt) -> (Ptr CString) -> IO CInt
| takayuki/natume | Lib.hs | gpl-2.0 | 4,832 | 0 | 17 | 934 | 1,233 | 655 | 578 | 85 | 1 |
module H28 where
sort :: (Ord b) => (a -> b) -> [a] -> [a]
sort _ [] = []
sort func xs = let k = func $ head xs
as = [x' | x' <- xs, func x' < k]
bs = [x' | x' <- xs, func x' == k]
cs = [x' | x' <- xs, func x' > k]
in
sort func as ++ bs ++ sort func cs
lsort :: [[a]] -> [[a]]
lsort xs = sort length xs
lfsort :: (Ord a) => [[a]] -> [[a]]
lfsort xs = let lengths = sort id $ map length xs
lf = freq lengths
in
sort (\x -> search lf (length x)) xs
where
freq' [] x n = [(x, n)]
freq' (x':xs) x n
| x' == x = freq' xs x (n + 1)
| otherwise = (x, n) : (freq' xs x' 1)
freq [] = []
freq (x:xs) = freq' xs x 1
search ((k', w):kws) k
| k' == k = w
| otherwise = search kws k
| hsinhuang/codebase | h99/H28.hs | gpl-2.0 | 902 | 0 | 12 | 411 | 485 | 250 | 235 | 23 | 3 |
--------------------------------------------------------------------------------
-- /////////////////////////////////////////////////////////////////////////////
--------------------------------------------------------------------------------
-- Benchmarks
--------------------------------------------------------------------------------
module RS_Benchmark (module RS_Benchmark)
where
import List
import IOExts
import CPUTime
import RS_Force
import RS_ListLib (cjustifyWith, rjustify)
--------------------------------------------------------------------------------
timeIt :: IO a -> IO Integer
timeIt cmd = do performGC
t1 <- getCPUTime
cmd
t2 <- getCPUTime
return (milliSeconds (t2 - t1))
where milliSeconds t = (t + 500000000) `div` 1000000000
time :: IO a -> IO ()
time cmd = do t <- timeIt cmd
putStrLn (showMilliSeconds t)
showMilliSeconds :: Integer -> String
showMilliSeconds t = show (t `div` 1000) ++ "." ++ frac
where ms = (t `mod` 1000) `div` 10
frac | ms < 10 = "0" ++ show ms
| otherwise = show ms
--------------------------------------------------------------------------------
benchmark :: (Force b, Force a) => [(String, a -> b)] -> [(String, a)] -> IO ()
benchmark cs gs =
let sgs = map fst gs in
force sgs `seq`
do putTitle "Running programs"
rts <- sequence [
sequence [
do putStrLn ("** Running " ++ strc ++ " on " ++ strg)
force g `seq` timeIt (return (force (c g) `seq` "done") >>= putStrLn)
| (strc, c) <- cs ]
| (strg, g) <- gs ]
putStrLn ""
putTitle "Results"
printResult (map fst cs) sgs rts
--------------------------------------------------------------------------------
putTitle :: String -> IO ()
putTitle s = do putStrLn (cjustifyWith '*' 78 "")
putStrLn (cjustifyWith '*' 78 (" "++s++" "))
putStrLn (cjustifyWith '*' 78 "")
putStrLn ""
--------------------------------------------------------------------------------
printResult :: [String] -> [String] -> [[Integer]] -> IO ()
printResult col0 row0 results
= putStrLn (formatTable table)
where table = ("" : col0 ++ ["*best*"]) :
[ e0 : [ showMilliSeconds e | e <- col ]
++ [ bestOf (zip col0 col) ]
| (e0, col) <- zip row0 results ]
bestOf :: (Ord b) => [(a, b)] -> a
bestOf = fst . foldl1 min2
where min2 p@(_,a) q@(_,b)
| a <= b = p
| otherwise = q
formatTable :: [[String]] -> String
formatTable table = unlines (map (concat . intersperse "|") lines)
where lines = transpose [
[ " "
++ rjustify (maximum [ length e | e <- col ]) e
++ " "
| e <- col ]
| col <- table ]
--------------------------------------------------------------------------------
-- /////////////////////////////////////////////////////////////////////////////
--------------------------------------------------------------------------------
| gennady-em/haskel | src/RS_Benchmark.hs | gpl-2.0 | 3,246 | 62 | 26 | 916 | 978 | 511 | 467 | 60 | 1 |
module Problem033 (answer) where
answer :: Int
answer = finalDenum `div` gcd finalDenum finalNum
where
(nums, denums) = unzip [(i, j) | j <- [2..99], i <- [1..j-1], isCurious i j]
finalNum = product nums
finalDenum = product denums
isCurious :: Int -> Int -> Bool
isCurious num denum = ((n1/=0) && (d1/=0)) && ((n2/=0) && (d2/=0)) && (
(n1==d1 && n2 * denum == d2 * num)
|| (n1==d2 && n2 * denum == d1 * num)
|| (n2==d1 && n1 * denum == d2 * num)
|| (n2==d2 && n1 * denum == d1 * num)
)
where
[n1, n2] = decompose num
[d1, d2] = decompose denum
-- simple decomposition for i<100
decompose n = [n `div` 10, n `mod` 10]
| geekingfrog/project-euler | Problem033.hs | gpl-3.0 | 663 | 0 | 15 | 169 | 350 | 191 | 159 | 15 | 1 |
module Language.Subleq.Assembly.Printer where
import Language.Subleq.Assembly.Prim
import Text.PrettyPrint
import qualified Data.Map as M
printId :: Id -> Doc
printId = text
printLoc :: Id -> Doc
printLoc = text . (++ ":")
printExpr :: Expr -> Doc
printExpr (Identifier i) = printId i
printExpr (Number n) = integer n
printExpr (EAdd e1 e2) = parens $ sep [text "+", printExpr e1, printExpr e2]
printExpr (ESub e1 e2) = parens $ sep [text "-", printExpr e1, printExpr e2]
printExpr (EShiftL e1 e2) = parens $ sep [text "shift", printExpr e1, printExpr e2]
printLocExpr :: LocExpr -> Doc
printLocExpr (l, e) = maybe empty printLoc l <> printExpr e
printInstruction :: Instruction -> Doc
printInstruction Subleq = empty
printElement :: Element -> Doc
printElement (ElemInst i es) = printInstruction i <+> hsep (map printLocExpr es) <> semi
printElement (SubroutineCall l x es) = maybe empty printLoc l <> text "$(@@" <> printId x <+> hsep (punctuate comma (map printExpr es)) <> text ")" <> semi
printElement (ElemLoc l) = printLoc l
printElements :: [Element] -> Doc
printElements = vcat . map printElement
printObject :: Object -> Doc
printObject (Subroutine n args elems) = text ("@" ++ n) <+> hsep (punctuate comma (map printId args)) $$ nest 4 (printElements elems)
printObject (Macro n args elems) = text ("@" ++ n) <+> hsep (punctuate comma (map printId args)) $$ nest 4 (printElements elems)
printModule :: Module -> Doc
printModule (Module m) = fsep . map printObject . M.elems $ m
| Hara-Laboratory/subleq-toolchain | Language/Subleq/Assembly/Printer.hs | gpl-3.0 | 1,500 | 0 | 12 | 256 | 626 | 317 | 309 | 29 | 1 |
// Challenges
// 1. Show the isomorphism between Maybe a and Either () a.
maybeToEither :: Maybe a -> Either () a
maybeToEither Nothing = Left ()
maybeToEither Just x = Right x
eitherToMaybe :: Either () a -> Maybe a
eitherToMaybe Left () = Nothing
eitherToMaybe Right x = Just x
| sujeet4github/MyLangUtils | CategoryTheory_BartoszMilewsky/PI_06_SimpleAlgebraicDataTypes/Maybe_Either.hs | gpl-3.0 | 285 | 5 | 8 | 57 | 123 | 58 | 65 | -1 | -1 |
{-# OPTIONS -Wall #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Graphics.UI.Bottle.Widgets.GridView(
make, makeGeneric, makeFromWidgets) where
import Control.Arrow (first, second)
import Control.Applicative (liftA2)
import Control.Monad (msum)
import Data.List (transpose)
import Data.Monoid (Monoid(..))
import Data.Vector.Vector2 (Vector2(..))
import Graphics.UI.Bottle.SizeRange (SizeRange(..), Size, Coordinate)
import Graphics.UI.Bottle.Sized (Sized(..))
import Graphics.UI.Bottle.Widget (Widget(..))
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Data.Vector.Vector2 as Vector2
import qualified Graphics.UI.Bottle.SizeRange as SizeRange
import qualified Graphics.UI.Bottle.Animation as Anim
--- Size computations:
-- Give each min-max range some of the extra budget...
disperse :: (Ord a, Num a) => a -> [(a, Maybe a)] -> [a]
disperse _ [] = []
disperse extra ((low, high):xs) = r : disperse remaining xs
where
r = max low . maybe id min high $ low + extra
remaining = low + extra - r
makeSizes :: [[SizeRange]] -> (SizeRange, Size -> [[Size]])
makeSizes rows = (reqSize, mkSizes)
where
reqSize = SizeRange minSize maxSize
minSize = fmap sum $ Vector2 columnMinWidths rowMinHeights
maxSize = fmap (fmap sum . sequence) $ Vector2 columnMaxWidths rowMaxHeights
(rowMinHeights, rowMaxHeights) =
computeSizeRanges Vector2.snd Vector2.snd rows
(columnMinWidths, columnMaxWidths) =
computeSizeRanges Vector2.fst Vector2.fst . transpose $ rows
-- computeSizeRanges takes f twice (as f0 and f1) to work around
-- lack of (proper) Rank2Types
computeSizeRanges f0 f1 xs =
(map (maximum . map (f0 . SizeRange.srMinSize)) xs,
map (fmap maximum . mapM (f1 . SizeRange.srMaxSize)) xs)
rowHeightRanges = zip rowMinHeights rowMaxHeights
columnWidthRanges = zip columnMinWidths columnMaxWidths
mkSizes givenSize = map (Vector2.zip columnWidths . repeat) rowHeights
where
Vector2 extraWidth extraHeight = liftA2 (-) givenSize minSize
columnWidths = disperse extraWidth columnWidthRanges
rowHeights = disperse extraHeight rowHeightRanges
--- Placables:
type Placement = (Coordinate, Size)
makePlacements :: [[SizeRange]] -> (SizeRange, Size -> [[Placement]])
makePlacements = (fmap . second . fmap) placements makeSizes
where
placements sizes = zipWith zip positions sizes
where
positions =
zipWith Vector2.zip
(map (scanl (+) 0 . map Vector2.fst) sizes)
(transpose . map (scanl (+) 0 . map Vector2.snd) . transpose $ sizes)
--- Displays:
-- Used by both make and Grid's make.
makeGeneric :: (a -> Anim.Frame) -> [[Sized a]] -> Sized (Anim.Frame, [[a]])
makeGeneric toFrame rows =
Sized reqSize mkRes
where
(reqSize, mkPlacements) = makePlacements $ (map . map) requestedSize rows
mkRes givenSize =
first (mconcat . concat) . unzip2d $
(zipWith . zipWith) locate (mkPlacements givenSize) rows
locate (pos, size) sized =
(Anim.translate pos (toFrame res), res)
where
res = fromSize sized size
unzip2d :: [[(a, b)]] -> ([[a]], [[b]])
unzip2d = unzip . map unzip
make :: [[Sized Anim.Frame]] -> Sized Anim.Frame
make = fmap fst . makeGeneric id
-- ^ This will send events to the first widget in the list that would
-- take them. It is useful especially for lifting views to widgets and
-- composing them with widgets.
makeFromWidgets :: [[Widget k]] -> Widget k
makeFromWidgets widgets =
Widget {
isFocused = any isFocused $ concat widgets,
content =
fmap combineEventHandlers .
makeGeneric Widget.uioFrame .
(map . map) content $ widgets
}
where
combineEventHandlers (frame, userIOss) =
Widget.UserIO {
Widget.uioFrame = frame,
Widget.uioMaybeEnter = mEnter,
Widget.uioEventMap = eventMap
}
where
eventMap = mconcat . map Widget.uioEventMap $ concat userIOss
mEnter = msum . map Widget.uioMaybeEnter $ concat userIOss
| alonho/bottle | src/Graphics/UI/Bottle/Widgets/GridView.hs | gpl-3.0 | 4,069 | 0 | 18 | 854 | 1,246 | 692 | 554 | 77 | 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.CloudKMS.Projects.Locations.KeyRings.TestIAMPermissions
-- 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)
--
-- Returns permissions that a caller has on the specified resource. If the
-- resource does not exist, this will return an empty set of permissions,
-- not a \`NOT_FOUND\` error. Note: This operation is designed to be used
-- for building permission-aware UIs and command-line tools, not for
-- authorization checking. This operation may \"fail open\" without
-- warning.
--
-- /See:/ <https://cloud.google.com/kms/ Cloud Key Management Service (KMS) API Reference> for @cloudkms.projects.locations.keyRings.testIamPermissions@.
module Network.Google.Resource.CloudKMS.Projects.Locations.KeyRings.TestIAMPermissions
(
-- * REST Resource
ProjectsLocationsKeyRingsTestIAMPermissionsResource
-- * Creating a Request
, projectsLocationsKeyRingsTestIAMPermissions
, ProjectsLocationsKeyRingsTestIAMPermissions
-- * Request Lenses
, plkrtipXgafv
, plkrtipUploadProtocol
, plkrtipAccessToken
, plkrtipUploadType
, plkrtipPayload
, plkrtipResource
, plkrtipCallback
) where
import Network.Google.CloudKMS.Types
import Network.Google.Prelude
-- | A resource alias for @cloudkms.projects.locations.keyRings.testIamPermissions@ method which the
-- 'ProjectsLocationsKeyRingsTestIAMPermissions' request conforms to.
type ProjectsLocationsKeyRingsTestIAMPermissionsResource
=
"v1" :>
CaptureMode "resource" "testIamPermissions" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TestIAMPermissionsRequest :>
Post '[JSON] TestIAMPermissionsResponse
-- | Returns permissions that a caller has on the specified resource. If the
-- resource does not exist, this will return an empty set of permissions,
-- not a \`NOT_FOUND\` error. Note: This operation is designed to be used
-- for building permission-aware UIs and command-line tools, not for
-- authorization checking. This operation may \"fail open\" without
-- warning.
--
-- /See:/ 'projectsLocationsKeyRingsTestIAMPermissions' smart constructor.
data ProjectsLocationsKeyRingsTestIAMPermissions =
ProjectsLocationsKeyRingsTestIAMPermissions'
{ _plkrtipXgafv :: !(Maybe Xgafv)
, _plkrtipUploadProtocol :: !(Maybe Text)
, _plkrtipAccessToken :: !(Maybe Text)
, _plkrtipUploadType :: !(Maybe Text)
, _plkrtipPayload :: !TestIAMPermissionsRequest
, _plkrtipResource :: !Text
, _plkrtipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsKeyRingsTestIAMPermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plkrtipXgafv'
--
-- * 'plkrtipUploadProtocol'
--
-- * 'plkrtipAccessToken'
--
-- * 'plkrtipUploadType'
--
-- * 'plkrtipPayload'
--
-- * 'plkrtipResource'
--
-- * 'plkrtipCallback'
projectsLocationsKeyRingsTestIAMPermissions
:: TestIAMPermissionsRequest -- ^ 'plkrtipPayload'
-> Text -- ^ 'plkrtipResource'
-> ProjectsLocationsKeyRingsTestIAMPermissions
projectsLocationsKeyRingsTestIAMPermissions pPlkrtipPayload_ pPlkrtipResource_ =
ProjectsLocationsKeyRingsTestIAMPermissions'
{ _plkrtipXgafv = Nothing
, _plkrtipUploadProtocol = Nothing
, _plkrtipAccessToken = Nothing
, _plkrtipUploadType = Nothing
, _plkrtipPayload = pPlkrtipPayload_
, _plkrtipResource = pPlkrtipResource_
, _plkrtipCallback = Nothing
}
-- | V1 error format.
plkrtipXgafv :: Lens' ProjectsLocationsKeyRingsTestIAMPermissions (Maybe Xgafv)
plkrtipXgafv
= lens _plkrtipXgafv (\ s a -> s{_plkrtipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plkrtipUploadProtocol :: Lens' ProjectsLocationsKeyRingsTestIAMPermissions (Maybe Text)
plkrtipUploadProtocol
= lens _plkrtipUploadProtocol
(\ s a -> s{_plkrtipUploadProtocol = a})
-- | OAuth access token.
plkrtipAccessToken :: Lens' ProjectsLocationsKeyRingsTestIAMPermissions (Maybe Text)
plkrtipAccessToken
= lens _plkrtipAccessToken
(\ s a -> s{_plkrtipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plkrtipUploadType :: Lens' ProjectsLocationsKeyRingsTestIAMPermissions (Maybe Text)
plkrtipUploadType
= lens _plkrtipUploadType
(\ s a -> s{_plkrtipUploadType = a})
-- | Multipart request metadata.
plkrtipPayload :: Lens' ProjectsLocationsKeyRingsTestIAMPermissions TestIAMPermissionsRequest
plkrtipPayload
= lens _plkrtipPayload
(\ s a -> s{_plkrtipPayload = a})
-- | REQUIRED: The resource for which the policy detail is being requested.
-- See the operation documentation for the appropriate value for this
-- field.
plkrtipResource :: Lens' ProjectsLocationsKeyRingsTestIAMPermissions Text
plkrtipResource
= lens _plkrtipResource
(\ s a -> s{_plkrtipResource = a})
-- | JSONP
plkrtipCallback :: Lens' ProjectsLocationsKeyRingsTestIAMPermissions (Maybe Text)
plkrtipCallback
= lens _plkrtipCallback
(\ s a -> s{_plkrtipCallback = a})
instance GoogleRequest
ProjectsLocationsKeyRingsTestIAMPermissions
where
type Rs ProjectsLocationsKeyRingsTestIAMPermissions =
TestIAMPermissionsResponse
type Scopes
ProjectsLocationsKeyRingsTestIAMPermissions
=
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloudkms"]
requestClient
ProjectsLocationsKeyRingsTestIAMPermissions'{..}
= go _plkrtipResource _plkrtipXgafv
_plkrtipUploadProtocol
_plkrtipAccessToken
_plkrtipUploadType
_plkrtipCallback
(Just AltJSON)
_plkrtipPayload
cloudKMSService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsKeyRingsTestIAMPermissionsResource)
mempty
| brendanhay/gogol | gogol-cloudkms/gen/Network/Google/Resource/CloudKMS/Projects/Locations/KeyRings/TestIAMPermissions.hs | mpl-2.0 | 7,029 | 0 | 16 | 1,455 | 793 | 468 | 325 | 125 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.AdSenseHost.Types
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.AdSenseHost.Types
(
-- * Service Configuration
adSenseHostService
-- * OAuth Scopes
, adSenseHostScope
-- * AdClients
, AdClients
, adClients
, acEtag
, acNextPageToken
, acKind
, acItems
-- * AssociationSession
, AssociationSession
, associationSession
, asStatus
, asKind
, asWebsiteLocale
, asUserLocale
, asAccountId
, asProductCodes
, asId
, asWebsiteURL
, asRedirectURL
-- * AssociationSessionsStartProductCode
, AssociationSessionsStartProductCode (..)
-- * Accounts
, Accounts
, accounts
, aEtag
, aKind
, aItems
-- * AdUnits
, AdUnits
, adUnits
, auEtag
, auNextPageToken
, auKind
, auItems
-- * URLChannels
, URLChannels
, urlChannels
, ucEtag
, ucNextPageToken
, ucKind
, ucItems
-- * CustomChannels
, CustomChannels
, customChannels
, ccEtag
, ccNextPageToken
, ccKind
, ccItems
-- * AdUnit
, AdUnit
, adUnit
, auuStatus
, auuMobileContentAdsSettings
, auuKind
, auuCustomStyle
, auuName
, auuContentAdsSettings
, auuCode
, auuId
-- * Report
, Report
, report
, rKind
, rAverages
, rWarnings
, rRows
, rTotals
, rHeaders
, rTotalMatchedRows
-- * AdStyleFont
, AdStyleFont
, adStyleFont
, asfSize
, asfFamily
-- * Account
, Account
, account
, accStatus
, accKind
, accName
, accId
-- * AdUnitMobileContentAdsSettings
, AdUnitMobileContentAdsSettings
, adUnitMobileContentAdsSettings
, aumcasSize
, aumcasScriptingLanguage
, aumcasMarkupLanguage
, aumcasType
-- * AdStyleColors
, AdStyleColors
, adStyleColors
, ascText
, ascURL
, ascBOrder
, ascTitle
, ascBackgRound
-- * AdUnitContentAdsSettingsBackupOption
, AdUnitContentAdsSettingsBackupOption
, adUnitContentAdsSettingsBackupOption
, aucasboColor
, aucasboURL
, aucasboType
-- * AdClient
, AdClient
, adClient
, adKind
, adArcOptIn
, adSupportsReporting
, adId
, adProductCode
-- * ReportHeadersItem
, ReportHeadersItem
, reportHeadersItem
, rhiName
, rhiCurrency
, rhiType
-- * AdStyle
, AdStyle
, adStyle
, assCorners
, assKind
, assFont
, assColors
-- * CustomChannel
, CustomChannel
, customChannel
, cKind
, cName
, cCode
, cId
-- * URLChannel
, URLChannel
, urlChannel
, urlcKind
, urlcId
, urlcURLPattern
-- * AdCode
, AdCode
, adCode
, aaKind
, aaAdCode
-- * AdUnitContentAdsSettings
, AdUnitContentAdsSettings
, adUnitContentAdsSettings
, aucasBackupOption
, aucasSize
, aucasType
) where
import Network.Google.AdSenseHost.Types.Product
import Network.Google.AdSenseHost.Types.Sum
import Network.Google.Prelude
-- | Default request referring to version 'v4.1' of the AdSense Host API. This contains the host and root path used as a starting point for constructing service requests.
adSenseHostService :: ServiceConfig
adSenseHostService
= defaultService (ServiceId "adsensehost:v4.1")
"www.googleapis.com"
-- | View and manage your AdSense host data and associated accounts
adSenseHostScope :: Proxy '["https://www.googleapis.com/auth/adsensehost"]
adSenseHostScope = Proxy
| brendanhay/gogol | gogol-adsense-host/gen/Network/Google/AdSenseHost/Types.hs | mpl-2.0 | 4,030 | 0 | 7 | 1,136 | 498 | 342 | 156 | 145 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.AppsCalendar
-- 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)
--
-- Manipulates events and other calendar data.
--
-- /See:/ <https://developers.google.com/google-apps/calendar/firstapp Calendar API Reference>
module Network.Google.AppsCalendar
(
-- * Service Configuration
appsCalendarService
-- * OAuth Scopes
, calendarScope
, calendarReadOnlyScope
, calendarEventsScope
, calendarSettingsReadOnlyScope
, calendarEventsReadOnlyScope
-- * API Declaration
, AppsCalendarAPI
-- * Resources
-- ** calendar.acl.delete
, module Network.Google.Resource.Calendar.ACL.Delete
-- ** calendar.acl.get
, module Network.Google.Resource.Calendar.ACL.Get
-- ** calendar.acl.insert
, module Network.Google.Resource.Calendar.ACL.Insert
-- ** calendar.acl.list
, module Network.Google.Resource.Calendar.ACL.List
-- ** calendar.acl.patch
, module Network.Google.Resource.Calendar.ACL.Patch
-- ** calendar.acl.update
, module Network.Google.Resource.Calendar.ACL.Update
-- ** calendar.acl.watch
, module Network.Google.Resource.Calendar.ACL.Watch
-- ** calendar.calendarList.delete
, module Network.Google.Resource.Calendar.CalendarList.Delete
-- ** calendar.calendarList.get
, module Network.Google.Resource.Calendar.CalendarList.Get
-- ** calendar.calendarList.insert
, module Network.Google.Resource.Calendar.CalendarList.Insert
-- ** calendar.calendarList.list
, module Network.Google.Resource.Calendar.CalendarList.List
-- ** calendar.calendarList.patch
, module Network.Google.Resource.Calendar.CalendarList.Patch
-- ** calendar.calendarList.update
, module Network.Google.Resource.Calendar.CalendarList.Update
-- ** calendar.calendarList.watch
, module Network.Google.Resource.Calendar.CalendarList.Watch
-- ** calendar.calendars.clear
, module Network.Google.Resource.Calendar.Calendars.Clear
-- ** calendar.calendars.delete
, module Network.Google.Resource.Calendar.Calendars.Delete
-- ** calendar.calendars.get
, module Network.Google.Resource.Calendar.Calendars.Get
-- ** calendar.calendars.insert
, module Network.Google.Resource.Calendar.Calendars.Insert
-- ** calendar.calendars.patch
, module Network.Google.Resource.Calendar.Calendars.Patch
-- ** calendar.calendars.update
, module Network.Google.Resource.Calendar.Calendars.Update
-- ** calendar.channels.stop
, module Network.Google.Resource.Calendar.Channels.Stop
-- ** calendar.colors.get
, module Network.Google.Resource.Calendar.Colors.Get
-- ** calendar.events.delete
, module Network.Google.Resource.Calendar.Events.Delete
-- ** calendar.events.get
, module Network.Google.Resource.Calendar.Events.Get
-- ** calendar.events.import
, module Network.Google.Resource.Calendar.Events.Import
-- ** calendar.events.insert
, module Network.Google.Resource.Calendar.Events.Insert
-- ** calendar.events.instances
, module Network.Google.Resource.Calendar.Events.Instances
-- ** calendar.events.list
, module Network.Google.Resource.Calendar.Events.List
-- ** calendar.events.move
, module Network.Google.Resource.Calendar.Events.Move
-- ** calendar.events.patch
, module Network.Google.Resource.Calendar.Events.Patch
-- ** calendar.events.quickAdd
, module Network.Google.Resource.Calendar.Events.QuickAdd
-- ** calendar.events.update
, module Network.Google.Resource.Calendar.Events.Update
-- ** calendar.events.watch
, module Network.Google.Resource.Calendar.Events.Watch
-- ** calendar.freebusy.query
, module Network.Google.Resource.Calendar.FreeBusy.Query
-- ** calendar.settings.get
, module Network.Google.Resource.Calendar.Settings.Get
-- ** calendar.settings.list
, module Network.Google.Resource.Calendar.Settings.List
-- ** calendar.settings.watch
, module Network.Google.Resource.Calendar.Settings.Watch
-- * Types
-- ** CalendarListEntry
, CalendarListEntry
, calendarListEntry
, cleSummary
, cleConferenceProperties
, cleEtag
, cleLocation
, cleKind
, cleNotificationSettings
, cleBackgRoundColor
, cleForegRoundColor
, cleDefaultReminders
, cleSelected
, clePrimary
, cleHidden
, cleId
, cleDeleted
, cleAccessRole
, cleSummaryOverride
, cleColorId
, cleTimeZone
, cleDescription
-- ** ConferenceParameters
, ConferenceParameters
, conferenceParameters
, cpAddOnParameters
-- ** Event
, Event
, event
, eSummary
, eOriginalStartTime
, eCreator
, eStatus
, eGuestsCanModify
, eEtag
, eAttachments
, eLocked
, eLocation
, eAttendees
, eReminders
, eKind
, eCreated
, eTransparency
, eRecurringEventId
, eStart
, ePrivateCopy
, eEndTimeUnspecified
, eConferenceData
, eExtendedProperties
, eVisibility
, eGuestsCanInviteOthers
, eRecurrence
, eGadget
, eEventType
, eSequence
, eICalUId
, eEnd
, eAttendeesOmitted
, eSource
, eId
, eHTMLLink
, eUpdated
, eColorId
, eAnyoneCanAddSelf
, eGuestsCanSeeOtherGuests
, eHangoutLink
, eDescription
, eOrganizer
-- ** CalendarListEntryNotificationSettings
, CalendarListEntryNotificationSettings
, calendarListEntryNotificationSettings
, clensNotifications
-- ** ConferenceProperties
, ConferenceProperties
, conferenceProperties
, cpAllowedConferenceSolutionTypes
-- ** ConferenceSolution
, ConferenceSolution
, conferenceSolution
, csIconURI
, csKey
, csName
-- ** EventsPatchSendUpdates
, EventsPatchSendUpdates (..)
-- ** ACLRuleScope
, ACLRuleScope
, aclRuleScope
, arsValue
, arsType
-- ** ColorsEvent
, ColorsEvent
, colorsEvent
, ceAddtional
-- ** EventsQuickAddSendUpdates
, EventsQuickAddSendUpdates (..)
-- ** Settings
, Settings
, settings
, sEtag
, sNextPageToken
, sKind
, sItems
, sNextSyncToken
-- ** FreeBusyRequestItem
, FreeBusyRequestItem
, freeBusyRequestItem
, fbriId
-- ** EventAttachment
, EventAttachment
, eventAttachment
, eaFileURL
, eaIconLink
, eaMimeType
, eaTitle
, eaFileId
-- ** EntryPoint
, EntryPoint
, entryPoint
, epPasscode
, epRegionCode
, epURI
, epMeetingCode
, epPassword
, epPin
, epEntryPointFeatures
, epEntryPointType
, epLabel
, epAccessCode
-- ** TimePeriod
, TimePeriod
, timePeriod
, tpStart
, tpEnd
-- ** EventsUpdateSendUpdates
, EventsUpdateSendUpdates (..)
-- ** ConferenceSolutionKey
, ConferenceSolutionKey
, conferenceSolutionKey
, cskType
-- ** EventsMoveSendUpdates
, EventsMoveSendUpdates (..)
-- ** EventCreator
, EventCreator
, eventCreator
, ecEmail
, ecSelf
, ecDisplayName
, ecId
-- ** Error'
, Error'
, error'
, eDomain
, eReason
-- ** ColorDefinition
, ColorDefinition
, colorDefinition
, cdForegRound
, cdBackgRound
-- ** EventsListOrderBy
, EventsListOrderBy (..)
-- ** EventsDeleteSendUpdates
, EventsDeleteSendUpdates (..)
-- ** Channel
, Channel
, channel
, cResourceURI
, cResourceId
, cKind
, cExpiration
, cToken
, cAddress
, cPayload
, cParams
, cId
, cType
-- ** ConferenceRequestStatus
, ConferenceRequestStatus
, conferenceRequestStatus
, crsStatusCode
-- ** FreeBusyCalendar
, FreeBusyCalendar
, freeBusyCalendar
, fbcBusy
, fbcErrors
-- ** ConferenceData
, ConferenceData
, conferenceData
, cdSignature
, cdConferenceSolution
, cdCreateRequest
, cdConferenceId
, cdParameters
, cdNotes
, cdEntryPoints
-- ** Setting
, Setting
, setting
, setEtag
, setKind
, setValue
, setId
-- ** FreeBusyResponseGroups
, FreeBusyResponseGroups
, freeBusyResponseGroups
, fbrgAddtional
-- ** EventsInsertSendUpdates
, EventsInsertSendUpdates (..)
-- ** EventReminders
, EventReminders
, eventReminders
, erOverrides
, erUseDefault
-- ** ColorsCalendar
, ColorsCalendar
, colorsCalendar
, ccAddtional
-- ** ConferenceParametersAddOnParametersParameters
, ConferenceParametersAddOnParametersParameters
, conferenceParametersAddOnParametersParameters
, cpaoppAddtional
-- ** CalendarNotification
, CalendarNotification
, calendarNotification
, cnMethod
, cnType
-- ** EventExtendedPropertiesPrivate
, EventExtendedPropertiesPrivate
, eventExtendedPropertiesPrivate
, eeppAddtional
-- ** ChannelParams
, ChannelParams
, channelParams
, cpAddtional
-- ** Events
, Events
, events
, eveSummary
, eveEtag
, eveNextPageToken
, eveKind
, eveItems
, eveDefaultReminders
, eveUpdated
, eveAccessRole
, eveTimeZone
, eveNextSyncToken
, eveDescription
-- ** EventAttendee
, EventAttendee
, eventAttendee
, eaEmail
, eaResponseStatus
, eaSelf
, eaResource
, eaAdditionalGuests
, eaDisplayName
, eaId
, eaComment
, eaOptional
, eaOrganizer
-- ** Calendar
, Calendar
, calendar
, calSummary
, calConferenceProperties
, calEtag
, calLocation
, calKind
, calId
, calTimeZone
, calDescription
-- ** FreeBusyResponse
, FreeBusyResponse
, freeBusyResponse
, fbrGroups
, fbrTimeMin
, fbrKind
, fbrCalendars
, fbrTimeMax
-- ** EventReminder
, EventReminder
, eventReminder
, erMethod
, erMinutes
-- ** EventExtendedProperties
, EventExtendedProperties
, eventExtendedProperties
, eepPrivate
, eepShared
-- ** EventDateTime
, EventDateTime
, eventDateTime
, edtDate
, edtTimeZone
, edtDateTime
-- ** EventOrganizer
, EventOrganizer
, eventOrganizer
, eoEmail
, eoSelf
, eoDisplayName
, eoId
-- ** CalendarList
, CalendarList
, calendarList
, clEtag
, clNextPageToken
, clKind
, clItems
, clNextSyncToken
-- ** CalendarListListMinAccessRole
, CalendarListListMinAccessRole (..)
-- ** EventGadget
, EventGadget
, eventGadget
, egHeight
, egDisplay
, egPreferences
, egLink
, egIconLink
, egWidth
, egTitle
, egType
-- ** EventGadgetPreferences
, EventGadgetPreferences
, eventGadgetPreferences
, egpAddtional
-- ** FreeBusyRequest
, FreeBusyRequest
, freeBusyRequest
, fCalendarExpansionMax
, fTimeMin
, fItems
, fGroupExpansionMax
, fTimeZone
, fTimeMax
-- ** ACLRule
, ACLRule
, aclRule
, arEtag
, arKind
, arRole
, arScope
, arId
-- ** EventsWatchOrderBy
, EventsWatchOrderBy (..)
-- ** CreateConferenceRequest
, CreateConferenceRequest
, createConferenceRequest
, ccrStatus
, ccrRequestId
, ccrConferenceSolutionKey
-- ** EventExtendedPropertiesShared
, EventExtendedPropertiesShared
, eventExtendedPropertiesShared
, eepsAddtional
-- ** CalendarListWatchMinAccessRole
, CalendarListWatchMinAccessRole (..)
-- ** FreeBusyResponseCalendars
, FreeBusyResponseCalendars
, freeBusyResponseCalendars
, fbrcAddtional
-- ** ACL
, ACL
, acl
, aEtag
, aNextPageToken
, aKind
, aItems
, aNextSyncToken
-- ** Colors
, Colors
, colors
, colEvent
, colKind
, colCalendar
, colUpdated
-- ** FreeBusyGroup
, FreeBusyGroup
, freeBusyGroup
, fbgCalendars
, fbgErrors
-- ** ConferenceParametersAddOnParameters
, ConferenceParametersAddOnParameters
, conferenceParametersAddOnParameters
, cpaopParameters
-- ** EventSource
, EventSource
, eventSource
, esURL
, esTitle
) where
import Network.Google.Prelude
import Network.Google.AppsCalendar.Types
import Network.Google.Resource.Calendar.ACL.Delete
import Network.Google.Resource.Calendar.ACL.Get
import Network.Google.Resource.Calendar.ACL.Insert
import Network.Google.Resource.Calendar.ACL.List
import Network.Google.Resource.Calendar.ACL.Patch
import Network.Google.Resource.Calendar.ACL.Update
import Network.Google.Resource.Calendar.ACL.Watch
import Network.Google.Resource.Calendar.CalendarList.Delete
import Network.Google.Resource.Calendar.CalendarList.Get
import Network.Google.Resource.Calendar.CalendarList.Insert
import Network.Google.Resource.Calendar.CalendarList.List
import Network.Google.Resource.Calendar.CalendarList.Patch
import Network.Google.Resource.Calendar.CalendarList.Update
import Network.Google.Resource.Calendar.CalendarList.Watch
import Network.Google.Resource.Calendar.Calendars.Clear
import Network.Google.Resource.Calendar.Calendars.Delete
import Network.Google.Resource.Calendar.Calendars.Get
import Network.Google.Resource.Calendar.Calendars.Insert
import Network.Google.Resource.Calendar.Calendars.Patch
import Network.Google.Resource.Calendar.Calendars.Update
import Network.Google.Resource.Calendar.Channels.Stop
import Network.Google.Resource.Calendar.Colors.Get
import Network.Google.Resource.Calendar.Events.Delete
import Network.Google.Resource.Calendar.Events.Get
import Network.Google.Resource.Calendar.Events.Import
import Network.Google.Resource.Calendar.Events.Insert
import Network.Google.Resource.Calendar.Events.Instances
import Network.Google.Resource.Calendar.Events.List
import Network.Google.Resource.Calendar.Events.Move
import Network.Google.Resource.Calendar.Events.Patch
import Network.Google.Resource.Calendar.Events.QuickAdd
import Network.Google.Resource.Calendar.Events.Update
import Network.Google.Resource.Calendar.Events.Watch
import Network.Google.Resource.Calendar.FreeBusy.Query
import Network.Google.Resource.Calendar.Settings.Get
import Network.Google.Resource.Calendar.Settings.List
import Network.Google.Resource.Calendar.Settings.Watch
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Calendar API service.
type AppsCalendarAPI =
SettingsListResource :<|> SettingsGetResource :<|>
SettingsWatchResource
:<|> ChannelsStopResource
:<|> CalendarsInsertResource
:<|> CalendarsPatchResource
:<|> CalendarsGetResource
:<|> CalendarsClearResource
:<|> CalendarsDeleteResource
:<|> CalendarsUpdateResource
:<|> EventsQuickAddResource
:<|> EventsInsertResource
:<|> EventsListResource
:<|> EventsPatchResource
:<|> EventsGetResource
:<|> EventsInstancesResource
:<|> EventsImportResource
:<|> EventsDeleteResource
:<|> EventsUpdateResource
:<|> EventsMoveResource
:<|> EventsWatchResource
:<|> CalendarListInsertResource
:<|> CalendarListListResource
:<|> CalendarListPatchResource
:<|> CalendarListGetResource
:<|> CalendarListDeleteResource
:<|> CalendarListUpdateResource
:<|> CalendarListWatchResource
:<|> ACLInsertResource
:<|> ACLListResource
:<|> ACLPatchResource
:<|> ACLGetResource
:<|> ACLDeleteResource
:<|> ACLUpdateResource
:<|> ACLWatchResource
:<|> ColorsGetResource
:<|> FreeBusyQueryResource
| brendanhay/gogol | gogol-apps-calendar/gen/Network/Google/AppsCalendar.hs | mpl-2.0 | 16,189 | 0 | 40 | 3,659 | 2,049 | 1,472 | 577 | 458 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.Reports.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a report by its ID.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.reports.get@.
module Network.Google.Resource.DFAReporting.Reports.Get
(
-- * REST Resource
ReportsGetResource
-- * Creating a Request
, reportsGet
, ReportsGet
-- * Request Lenses
, rgReportId
, rgProFileId
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.reports.get@ method which the
-- 'ReportsGet' request conforms to.
type ReportsGetResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"reports" :>
Capture "reportId" (Textual Int64) :>
QueryParam "alt" AltJSON :> Get '[JSON] Report
-- | Retrieves a report by its ID.
--
-- /See:/ 'reportsGet' smart constructor.
data ReportsGet = ReportsGet'
{ _rgReportId :: !(Textual Int64)
, _rgProFileId :: !(Textual Int64)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ReportsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rgReportId'
--
-- * 'rgProFileId'
reportsGet
:: Int64 -- ^ 'rgReportId'
-> Int64 -- ^ 'rgProFileId'
-> ReportsGet
reportsGet pRgReportId_ pRgProFileId_ =
ReportsGet'
{ _rgReportId = _Coerce # pRgReportId_
, _rgProFileId = _Coerce # pRgProFileId_
}
-- | The ID of the report.
rgReportId :: Lens' ReportsGet Int64
rgReportId
= lens _rgReportId (\ s a -> s{_rgReportId = a}) .
_Coerce
-- | The DFA user profile ID.
rgProFileId :: Lens' ReportsGet Int64
rgProFileId
= lens _rgProFileId (\ s a -> s{_rgProFileId = a}) .
_Coerce
instance GoogleRequest ReportsGet where
type Rs ReportsGet = Report
type Scopes ReportsGet =
'["https://www.googleapis.com/auth/dfareporting"]
requestClient ReportsGet'{..}
= go _rgProFileId _rgReportId (Just AltJSON)
dFAReportingService
where go
= buildClient (Proxy :: Proxy ReportsGetResource)
mempty
| rueshyna/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Reports/Get.hs | mpl-2.0 | 3,077 | 0 | 14 | 732 | 421 | 249 | 172 | 63 | 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.Jobs.Projects.Companies.Delete
-- 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)
--
-- Deletes specified company. Prerequisite: The company has no jobs
-- associated with it.
--
-- /See:/ <https://cloud.google.com/talent-solution/job-search/docs/ Cloud Talent Solution API Reference> for @jobs.projects.companies.delete@.
module Network.Google.Resource.Jobs.Projects.Companies.Delete
(
-- * REST Resource
ProjectsCompaniesDeleteResource
-- * Creating a Request
, projectsCompaniesDelete
, ProjectsCompaniesDelete
-- * Request Lenses
, pcdXgafv
, pcdUploadProtocol
, pcdAccessToken
, pcdUploadType
, pcdName
, pcdCallback
) where
import Network.Google.Jobs.Types
import Network.Google.Prelude
-- | A resource alias for @jobs.projects.companies.delete@ method which the
-- 'ProjectsCompaniesDelete' request conforms to.
type ProjectsCompaniesDeleteResource =
"v3p1beta1" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Empty
-- | Deletes specified company. Prerequisite: The company has no jobs
-- associated with it.
--
-- /See:/ 'projectsCompaniesDelete' smart constructor.
data ProjectsCompaniesDelete =
ProjectsCompaniesDelete'
{ _pcdXgafv :: !(Maybe Xgafv)
, _pcdUploadProtocol :: !(Maybe Text)
, _pcdAccessToken :: !(Maybe Text)
, _pcdUploadType :: !(Maybe Text)
, _pcdName :: !Text
, _pcdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsCompaniesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pcdXgafv'
--
-- * 'pcdUploadProtocol'
--
-- * 'pcdAccessToken'
--
-- * 'pcdUploadType'
--
-- * 'pcdName'
--
-- * 'pcdCallback'
projectsCompaniesDelete
:: Text -- ^ 'pcdName'
-> ProjectsCompaniesDelete
projectsCompaniesDelete pPcdName_ =
ProjectsCompaniesDelete'
{ _pcdXgafv = Nothing
, _pcdUploadProtocol = Nothing
, _pcdAccessToken = Nothing
, _pcdUploadType = Nothing
, _pcdName = pPcdName_
, _pcdCallback = Nothing
}
-- | V1 error format.
pcdXgafv :: Lens' ProjectsCompaniesDelete (Maybe Xgafv)
pcdXgafv = lens _pcdXgafv (\ s a -> s{_pcdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pcdUploadProtocol :: Lens' ProjectsCompaniesDelete (Maybe Text)
pcdUploadProtocol
= lens _pcdUploadProtocol
(\ s a -> s{_pcdUploadProtocol = a})
-- | OAuth access token.
pcdAccessToken :: Lens' ProjectsCompaniesDelete (Maybe Text)
pcdAccessToken
= lens _pcdAccessToken
(\ s a -> s{_pcdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pcdUploadType :: Lens' ProjectsCompaniesDelete (Maybe Text)
pcdUploadType
= lens _pcdUploadType
(\ s a -> s{_pcdUploadType = a})
-- | Required. The resource name of the company to be deleted. The format is
-- \"projects\/{project_id}\/companies\/{company_id}\", for example,
-- \"projects\/api-test-project\/companies\/foo\".
pcdName :: Lens' ProjectsCompaniesDelete Text
pcdName = lens _pcdName (\ s a -> s{_pcdName = a})
-- | JSONP
pcdCallback :: Lens' ProjectsCompaniesDelete (Maybe Text)
pcdCallback
= lens _pcdCallback (\ s a -> s{_pcdCallback = a})
instance GoogleRequest ProjectsCompaniesDelete where
type Rs ProjectsCompaniesDelete = Empty
type Scopes ProjectsCompaniesDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/jobs"]
requestClient ProjectsCompaniesDelete'{..}
= go _pcdName _pcdXgafv _pcdUploadProtocol
_pcdAccessToken
_pcdUploadType
_pcdCallback
(Just AltJSON)
jobsService
where go
= buildClient
(Proxy :: Proxy ProjectsCompaniesDeleteResource)
mempty
| brendanhay/gogol | gogol-jobs/gen/Network/Google/Resource/Jobs/Projects/Companies/Delete.hs | mpl-2.0 | 4,949 | 0 | 15 | 1,120 | 702 | 412 | 290 | 101 | 1 |
{-# LANGUAGE FlexibleContexts #-}
import AdventOfCode (readInputFile)
import AdventOfCode.Split (splitOnOne)
import Control.Arrow ((***))
import Control.Monad (forM_)
import Control.Monad.ST (ST)
import Data.Array.Base (UArray)
import Data.Array.IArray (IArray, elems)
import Data.Array.MArray (newArray, readArray, writeArray)
import Data.Array.ST (STUArray, runSTUArray)
import Data.Ix (Ix)
type Pos = (Int, Int)
data Command = TurnOn | TurnOff | Toggle
runCommands :: Unboxed a => [(Command, Pos, Pos)] -> (Command -> a -> a) -> Int
runCommands commands language = (reduce . elems) $ runSTUArray $ do
a <- newSTUArray ((0, 0), (999, 999)) zero
forM_ commands $ \(command, (x1, y1), (x2, y2)) ->
forM_ [(x, y) | x <- [x1..x2], y <- [y1..y2]] $ \pos -> do
val <- readSTUArray a pos
writeSTUArray a pos (language command val)
return a
onOrOff :: Command -> Bool -> Bool
onOrOff TurnOn = const True
onOrOff TurnOff = const False
onOrOff Toggle = not
brightness :: Command -> Int -> Int
brightness TurnOn n = n + 1
brightness TurnOff 0 = 0
brightness TurnOff n = n - 1
brightness Toggle n = n + 2
-- http://stackoverflow.com/questions/2222997/stuarray-with-polymorphic-type
class IArray UArray a => Unboxed a where
zero :: a
reduce :: [a] -> Int
newSTUArray :: Ix i => (i, i) -> a -> ST s (STUArray s i a)
readSTUArray :: Ix i => STUArray s i a -> i -> ST s a
writeSTUArray :: Ix i => STUArray s i a -> i -> a -> ST s ()
instance Unboxed Int where
zero = 0
reduce = sum
newSTUArray = newArray
readSTUArray = readArray
writeSTUArray = writeArray
instance Unboxed Bool where
zero = False
reduce = length . filter id
newSTUArray = newArray
readSTUArray = readArray
writeSTUArray = writeArray
parseCommand :: [String] -> (Command, Pos, Pos)
parseCommand s = (command, start, end)
where (command, rawCoords) = case s of
("turn" : "on" : rest) -> (TurnOn, rest)
("turn" : "off" : rest) -> (TurnOff, rest)
("toggle" : rest) -> (Toggle, rest)
_ -> error ("invalid command " ++ unwords s)
(start, end) = parseCoords rawCoords
parseCoords :: [String] -> (Pos, Pos)
parseCoords s = (parseCoord c1, parseCoord c2)
where (c1, c2) = case s of
[a, "through", b] -> (a, b)
_ -> error ("invalid coordinates " ++ unwords s)
parseCoord :: String -> Pos
parseCoord = (read *** read) . splitOnOne ','
main :: IO ()
main = do
s <- readInputFile
let commands = map (parseCommand . words) (lines s)
print (runCommands commands onOrOff)
print (runCommands commands brightness)
| petertseng/adventofcode-hs | bin/06_light_grid.hs | apache-2.0 | 2,600 | 0 | 16 | 564 | 1,045 | 566 | 479 | 69 | 4 |
{-# LANGUAGE FlexibleContexts, TypeOperators #-}
module Codec.FFMpeg.Codec (
decodeVideoFrames
) where
import Control.Eff
import Control.Eff.Coroutine
import Control.Eff.Exception
import Control.Eff.Lift
import Control.Eff.Reader.Strict
import Foreign ( Ptr )
import Foreign.C.Types ( CInt(..) )
import Foreign.Marshal.Alloc ( alloca )
import Foreign.Storable ( peek )
import Codec.FFMpeg.Frame
import Codec.FFMpeg.Internal.Codec
import Codec.FFMpeg.Internal.Frame
decodeVideoFrames
:: ( SetMember Lift (Lift IO) r
, Member (Reader AVCodecContext) r
, Member (Yield AVFrame) r
, Member (Exc IOError) r
)
=> Eff (Yield AVPacket :> r) ()
-> Eff r ()
decodeVideoFrames pkt = ask >>= \ctx -> do
f <- newAvFrame
runC pkt >>= loop ctx f where
loop :: ( SetMember Lift (Lift IO) r
, Member (Yield AVFrame) r
, Member (Exc IOError) r
) => AVCodecContext -> AVFrame -> Y r AVPacket () -> Eff r ()
loop _ _ (Done ()) = return ()
loop ctx f (Y p k) = do
(r, gp) <- lift $ alloca $ \gpp -> do
r <- withAvPacket p $ \p' ->
withAvFrame f $ \f' ->
c_avcodec_decode_video2 ctx f' gpp p'
peek gpp >>= \gp -> return (r, gp)
if r < 0
then throwExc $ userError $ "error decoding frame: " ++ show r
else if gp == 0
then yield f >> k () >>= loop ctx f
else k () >>= loop ctx f
-------------------------------------------------------------------------------
-- Imports
-------------------------------------------------------------------------------
foreign import ccall "avcodec_decode_video2"
c_avcodec_decode_video2 :: AVCodecContext -> Ptr AVFrame' -> Ptr CInt -> Ptr AVPacket' -> IO CInt
| waldheinz/ffmpeg-effects | src/Codec/FFMpeg/Codec.hs | apache-2.0 | 1,887 | 0 | 19 | 562 | 577 | 303 | 274 | 43 | 4 |
-----------------------------------------------------------------------------
-- |
-- Module : FFICXX.Generate.Code.Cabal
-- Copyright : (c) 2011-2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module FFICXX.Generate.Code.Cabal where
import FFICXX.Generate.Type.Class
cabalIndentation :: String
cabalIndentation = replicate 23 ' '
-- | generate exposed module list in cabal file
genExposedModules :: String -> [ClassModule] -> String
genExposedModules summarymod cmods =
let indentspace = cabalIndentation
summarystrs = indentspace ++ summarymod
cmodstrs = map ((\x->indentspace++x).cmModule) cmods
rawType = map ((\x->indentspace++x++".RawType").cmModule) cmods
ffi = map ((\x->indentspace++x++".FFI").cmModule) cmods
interface= map ((\x->indentspace++x++".Interface").cmModule) cmods
cast = map ((\x->indentspace++x++".Cast").cmModule) cmods
implementation = map ((\x->indentspace++x++".Implementation").cmModule) cmods
in unlines ([summarystrs]++cmodstrs++rawType++ffi++interface++cast++implementation)
-- | generate other modules in cabal file
genOtherModules :: [ClassModule] -> String
genOtherModules _cmods = ""
| Gabriel439/fficxx | lib/FFICXX/Generate/Code/Cabal.hs | bsd-2-clause | 1,385 | 0 | 15 | 223 | 324 | 184 | 140 | 17 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Tersus.Database where
--import Tersus
import Control.Monad.IO.Class
import Data.ByteString
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as Char8
import Data.String
import Data.Text
import qualified Data.Text as T
import Data.Text.Encoding
import Database.Redis
import Prelude
import System.IO.Unsafe
import Yesod.Handler
sep :: Char
sep = '$'
--(<.>) :: String -> Text -> ByteString
--s1 <:> s2 = encodeUtf8 $ (T.pack s1) `T.append` (sep `T.cons` s2)
(.>) :: String -> ByteString -> ByteString
(.>) s b = (encodeUtf8 . T.pack $ s ++ [sep]) `B.append` b
(<.) :: ByteString -> String -> ByteString
(<.) b s = b `B.append` (encodeUtf8 . T.pack $ sep:s)
(<.>) :: String -> String -> ByteString
(<.>) s s' = Char8.pack $ s ++ sep:s'
(<+>) :: ByteString -> ByteString -> ByteString
(<+>) b b' = b `B.append` Char8.pack [sep] `B.append` b'
foldEitherToMaybe :: Either a b -> Maybe b
foldEitherToMaybe (Left _) = Nothing
foldEitherToMaybe (Right b') = Just b'
byteStringToInteger :: ByteString -> Integer
byteStringToInteger = read . Char8.unpack
integerToByteString :: Integer -> ByteString
integerToByteString = Char8.pack . show
-- | Equivalent to join . foldEitherToMaybe
getRedisResponse :: Either Reply (Maybe e) -> Maybe e
getRedisResponse (Left _) = Nothing
getRedisResponse (Right me) = me
io = liftIO
uio = unsafePerformIO
| kmels/tersus | Tersus/Database.hs | bsd-2-clause | 1,512 | 0 | 10 | 320 | 441 | 255 | 186 | 36 | 1 |
module FractalFlame.GLDisplay (
displayLoop
) where
import Data.Array
import qualified Foreign
import GHC.Float
import Graphics.UI.GLUT
import System.Exit (exitWith, ExitCode(ExitSuccess))
import qualified FractalFlame.Histogram as H
import qualified FractalFlame.Color as C
import qualified FractalFlame.Types.PixelFlame as PF
import qualified FractalFlame.Types.Size as S
type Image = PixelData (Color3 GLfloat)
sizeRep :: PF.PixelFlame -> Size
sizeRep (PF.PixelFlame {size = (S.Size width height)}) =
let w = fromIntegral width
h = fromIntegral height
in Size w h
-- convert a Pixel to a type OpenGL can display
pixelRep :: C.Color -> Color3 GLfloat
pixelRep (C.Color r g b a) = Color3 (realToFrac r) (realToFrac g) (realToFrac b)
makeImage :: PF.PixelFlame -> IO Image
makeImage pixelFlame = do
fmap (PixelData RGB Float) . Foreign.newArray . map pixelRep $ PF.pixelFlame2Colors pixelFlame
display :: Size -> Image -> DisplayCallback
display size pixelData = do
clear [ColorBuffer]
-- resolve overloading, not needed in "real" programs
let rasterPos2i = rasterPos :: Vertex2 GLint -> IO ()
rasterPos2i (Vertex2 0 0)
drawPixels size pixelData
flush
reshape :: ReshapeCallback
reshape size@(Size w h) = do
viewport $= (Position 0 0, size)
matrixMode $= Projection
loadIdentity
ortho2D 0 (fromIntegral w) 0 (fromIntegral h)
matrixMode $= Modelview 0
loadIdentity
keyboard :: KeyboardMouseCallback
keyboard (Char '\27') Down _ _ = exitWith ExitSuccess
keyboard _ _ _ _ = return ()
myInit :: PF.PixelFlame -> IO (Size, Image)
myInit pixelFlame = do
let size = sizeRep pixelFlame
(progName, _args) <- getArgsAndInitialize
initialDisplayMode $= [SingleBuffered, RGBMode]
initialWindowSize $= size
initialWindowPosition $= Position 100 100
createWindow progName
clearColor $= Color4 0 0 0 0
shadeModel $= Flat
rowAlignment Unpack $= 1
image <- makeImage pixelFlame
return (size, image)
displayLoop :: PF.PixelFlame -> IO ()
displayLoop pixelFlame = do
(size, flameImage) <- myInit pixelFlame
displayCallback $= display size flameImage
reshapeCallback $= Just reshape
keyboardMouseCallback $= Just keyboard
mainLoop
| anthezium/fractal_flame_renderer_haskell | FractalFlame/GLDisplay.hs | bsd-2-clause | 2,220 | 0 | 12 | 407 | 726 | 363 | 363 | 60 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStyleOptionTabBarBase.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:15
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStyleOptionTabBarBase (
QqStyleOptionTabBarBase(..)
,QqStyleOptionTabBarBase_nf(..)
,qselectedTabRect, selectedTabRect
,qsetSelectedTabRect, setSelectedTabRect
,qsetTabBarRect, setTabBarRect
,qtabBarRect, tabBarRect
,qStyleOptionTabBarBase_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QTabBar
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqStyleOptionTabBarBase x1 where
qStyleOptionTabBarBase :: x1 -> IO (QStyleOptionTabBarBase ())
instance QqStyleOptionTabBarBase (()) where
qStyleOptionTabBarBase ()
= withQStyleOptionTabBarBaseResult $
qtc_QStyleOptionTabBarBase
foreign import ccall "qtc_QStyleOptionTabBarBase" qtc_QStyleOptionTabBarBase :: IO (Ptr (TQStyleOptionTabBarBase ()))
instance QqStyleOptionTabBarBase ((QStyleOptionTabBarBase t1)) where
qStyleOptionTabBarBase (x1)
= withQStyleOptionTabBarBaseResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabBarBase1 cobj_x1
foreign import ccall "qtc_QStyleOptionTabBarBase1" qtc_QStyleOptionTabBarBase1 :: Ptr (TQStyleOptionTabBarBase t1) -> IO (Ptr (TQStyleOptionTabBarBase ()))
class QqStyleOptionTabBarBase_nf x1 where
qStyleOptionTabBarBase_nf :: x1 -> IO (QStyleOptionTabBarBase ())
instance QqStyleOptionTabBarBase_nf (()) where
qStyleOptionTabBarBase_nf ()
= withObjectRefResult $
qtc_QStyleOptionTabBarBase
instance QqStyleOptionTabBarBase_nf ((QStyleOptionTabBarBase t1)) where
qStyleOptionTabBarBase_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabBarBase1 cobj_x1
qselectedTabRect :: QStyleOptionTabBarBase a -> (()) -> IO (QRect ())
qselectedTabRect x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_selectedTabRect cobj_x0
foreign import ccall "qtc_QStyleOptionTabBarBase_selectedTabRect" qtc_QStyleOptionTabBarBase_selectedTabRect :: Ptr (TQStyleOptionTabBarBase a) -> IO (Ptr (TQRect ()))
selectedTabRect :: QStyleOptionTabBarBase a -> (()) -> IO (Rect)
selectedTabRect x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_selectedTabRect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QStyleOptionTabBarBase_selectedTabRect_qth" qtc_QStyleOptionTabBarBase_selectedTabRect_qth :: Ptr (TQStyleOptionTabBarBase a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
qsetSelectedTabRect :: QStyleOptionTabBarBase a -> ((QRect t1)) -> IO ()
qsetSelectedTabRect x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabBarBase_setSelectedTabRect cobj_x0 cobj_x1
foreign import ccall "qtc_QStyleOptionTabBarBase_setSelectedTabRect" qtc_QStyleOptionTabBarBase_setSelectedTabRect :: Ptr (TQStyleOptionTabBarBase a) -> Ptr (TQRect t1) -> IO ()
setSelectedTabRect :: QStyleOptionTabBarBase a -> ((Rect)) -> IO ()
setSelectedTabRect x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QStyleOptionTabBarBase_setSelectedTabRect_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QStyleOptionTabBarBase_setSelectedTabRect_qth" qtc_QStyleOptionTabBarBase_setSelectedTabRect_qth :: Ptr (TQStyleOptionTabBarBase a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetShape (QStyleOptionTabBarBase a) ((QTabBarShape)) where
setShape x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_setShape cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QStyleOptionTabBarBase_setShape" qtc_QStyleOptionTabBarBase_setShape :: Ptr (TQStyleOptionTabBarBase a) -> CLong -> IO ()
qsetTabBarRect :: QStyleOptionTabBarBase a -> ((QRect t1)) -> IO ()
qsetTabBarRect x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStyleOptionTabBarBase_setTabBarRect cobj_x0 cobj_x1
foreign import ccall "qtc_QStyleOptionTabBarBase_setTabBarRect" qtc_QStyleOptionTabBarBase_setTabBarRect :: Ptr (TQStyleOptionTabBarBase a) -> Ptr (TQRect t1) -> IO ()
setTabBarRect :: QStyleOptionTabBarBase a -> ((Rect)) -> IO ()
setTabBarRect x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QStyleOptionTabBarBase_setTabBarRect_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QStyleOptionTabBarBase_setTabBarRect_qth" qtc_QStyleOptionTabBarBase_setTabBarRect_qth :: Ptr (TQStyleOptionTabBarBase a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qshape (QStyleOptionTabBarBase a) (()) (IO (QTabBarShape)) where
shape x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_shape cobj_x0
foreign import ccall "qtc_QStyleOptionTabBarBase_shape" qtc_QStyleOptionTabBarBase_shape :: Ptr (TQStyleOptionTabBarBase a) -> IO CLong
qtabBarRect :: QStyleOptionTabBarBase a -> (()) -> IO (QRect ())
qtabBarRect x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_tabBarRect cobj_x0
foreign import ccall "qtc_QStyleOptionTabBarBase_tabBarRect" qtc_QStyleOptionTabBarBase_tabBarRect :: Ptr (TQStyleOptionTabBarBase a) -> IO (Ptr (TQRect ()))
tabBarRect :: QStyleOptionTabBarBase a -> (()) -> IO (Rect)
tabBarRect x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_tabBarRect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QStyleOptionTabBarBase_tabBarRect_qth" qtc_QStyleOptionTabBarBase_tabBarRect_qth :: Ptr (TQStyleOptionTabBarBase a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
qStyleOptionTabBarBase_delete :: QStyleOptionTabBarBase a -> IO ()
qStyleOptionTabBarBase_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStyleOptionTabBarBase_delete cobj_x0
foreign import ccall "qtc_QStyleOptionTabBarBase_delete" qtc_QStyleOptionTabBarBase_delete :: Ptr (TQStyleOptionTabBarBase a) -> IO ()
| keera-studios/hsQt | Qtc/Gui/QStyleOptionTabBarBase.hs | bsd-2-clause | 6,697 | 0 | 12 | 884 | 1,619 | 830 | 789 | -1 | -1 |
module Jerimum.Tests.Unit.PostgreSQL.Types.TypeTest
( tests
) where
import Jerimum.PostgreSQL.Types.Type
import Jerimum.Tests.Unit.PostgreSQL.Types.Helpers
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
tests :: TestTree
tests =
testGroup "PostgreSQL.Types.Type" [testCodec, testParser, testPredicates]
testParser :: TestTree
testParser =
testGroup
"text codec"
[ testProperty "identity" $ \(TypeInfoG t) ->
Just t === parseType (formatType t)
]
testCodec :: TestTree
testCodec =
testGroup
"cbor codec"
[ testProperty "identity" $ \(TypeInfoG t) ->
Right t === runDecoder typeDecoderV0 (runEncoder (typeEncoderV0 t))
]
testPredicates :: TestTree
testPredicates =
testGroup
"predicates"
[ testCase "isText" $ assertBool "isText" (isText "text")
, testCase "isDateRange" $ assertBool "daterange" (isDateRange "daterange")
, testCase "isBoolean" $ assertBool "isBoolean" (isBoolean "boolean")
, testCase "isUUID" $ assertBool "isUUID" (isUUID "uuid")
, testCase "isSmallint" $ assertBool "isSmallint" (isSmallint "smallint")
, testCase "isInteger" $ assertBool "isInteger" (isInteger "integer")
, testCase "isBigint" $ assertBool "isBigint" (isBigint "bigint")
, testCase "isFloat32" $ assertBool "isFloat32" (isFloat32 "real")
, testCase "isFloat64" $
assertBool "isFloat64" (isFloat64 "double precision")
, testCase "isBinary" $ assertBool "isBinary" (isBinary "bytea")
, testCase "isLsn" $ assertBool "isLsn" (isLsn "pg_lsn")
, testCase "isDate" $ assertBool "isDate" (isDate "date")
, testCase "isTimeTz" $
assertBool "isTimeTz" (isTimeTz "time with time zone")
, testCase "isTimeNoTz" $ assertBool "isTimeNoTz" (isTimeNoTz "time")
, testCase "isTimestampTz" $
assertBool "isTimestampTz" (isTimestampTz "timestamp with time zone")
, testCase "isTimestampNoTz" $
assertBool "isTimestampNoTz" (isTimestampNoTz "timestamp")
]
| dgvncsz0f/nws | test/Jerimum/Tests/Unit/PostgreSQL/Types/TypeTest.hs | bsd-3-clause | 2,001 | 0 | 14 | 368 | 535 | 272 | 263 | 46 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE EmptyDataDecls #-}
#include "kinds.h"
#ifdef GenericDeriving
{-# LANGUAGE DeriveGeneric #-}
#endif
#ifdef SafeHaskell
#if __GLASGOW_HASKELL__ >= 704
{-# LANGUAGE Safe #-}
#else
{-# LANGUAGE Trustworthy #-}
#endif
#endif
module Type.Meta.Void
( Void, absurd
)
where
-- base ----------------------------------------------------------------------
#if MIN_VERSION_base(4, 8, 0)
import Data.Void (Void, absurd)
#else
import Control.Exception (Exception)
import Data.Ix (Ix, range, index, inRange, rangeSize)
import Data.Typeable (Typeable)
#if defined(GenericDeriving)
import GHC.Generics (Generic)
#endif
-- deepseq -------------------------------------------------------------------
import Control.DeepSeq (NFData, rnf)
------------------------------------------------------------------------------
data Void
deriving
( Typeable
#ifdef GenericDeriving
, Generic
#endif
)
------------------------------------------------------------------------------
instance Eq Void where
_ == _ = True
------------------------------------------------------------------------------
instance Ord Void where
compare _ _ = EQ
------------------------------------------------------------------------------
instance Ix Void where
range _ = []
index _ = absurd
inRange _ = absurd
rangeSize _ = 0
------------------------------------------------------------------------------
instance Read Void where
readsPrec _ _ = []
------------------------------------------------------------------------------
instance Show Void where
showsPrec _ = absurd
------------------------------------------------------------------------------
instance Exception Void
------------------------------------------------------------------------------
instance NFData Void where
rnf = absurd
------------------------------------------------------------------------------
absurd :: Void -> a
absurd _ = undefined
#endif
| duairc/symbols | types/src/Type/Meta/Void.hs | bsd-3-clause | 2,091 | 3 | 7 | 331 | 238 | 140 | 98 | -1 | -1 |
module Game.TicTacToe.Client
(
client
) where
client :: IO ()
client = putStrLn "--- TicTacToe client ---" >> putStrLn "exiting ..."
| peterson/hsttt | src/Game/TicTacToe/Client.hs | bsd-3-clause | 136 | 0 | 6 | 24 | 37 | 20 | 17 | 5 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.List
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (multi-parameter type classes)
--
-- The List monad.
--
-----------------------------------------------------------------------------
module Control.Monad.List (
ListT(..),
mapListT,
module Control.Monad,
module Control.Monad.Trans,
) where
import Prelude
import Control.Monad
import Control.Monad.Trans
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Cont
import Control.Monad.Error
-- ---------------------------------------------------------------------------
-- Our parameterizable list monad, with an inner monad
newtype ListT m a = ListT { runListT :: m [a] }
instance (Monad m) => Functor (ListT m) where
fmap f m = ListT $ do
a <- runListT m
return (map f a)
instance (Monad m) => Monad (ListT m) where
return a = ListT $ return [a]
m >>= k = ListT $ do
a <- runListT m
b <- mapM (runListT . k) a
return (concat b)
fail _ = ListT $ return []
instance (Monad m) => MonadPlus (ListT m) where
mzero = ListT $ return []
m `mplus` n = ListT $ do
a <- runListT m
b <- runListT n
return (a ++ b)
instance MonadTrans ListT where
lift m = ListT $ do
a <- m
return [a]
instance (MonadIO m) => MonadIO (ListT m) where
liftIO = lift . liftIO
instance (MonadReader s m) => MonadReader s (ListT m) where
ask = lift ask
local f m = ListT $ local f (runListT m)
instance (MonadState s m) => MonadState s (ListT m) where
get = lift get
put = lift . put
instance (MonadCont m) => MonadCont (ListT m) where
callCC f = ListT $
callCC $ \c ->
runListT (f (\a -> ListT $ c [a]))
instance (MonadError e m) => MonadError e (ListT m) where
throwError = lift . throwError
m `catchError` h = ListT $ runListT m
`catchError` \e -> runListT (h e)
mapListT :: (m [a] -> n [b]) -> ListT m a -> ListT n b
mapListT f m = ListT $ f (runListT m)
| OS2World/DEV-UTIL-HUGS | libraries/Control/Monad/List.hs | bsd-3-clause | 2,226 | 14 | 15 | 456 | 768 | 406 | 362 | -1 | -1 |
{-# LANGUAGE DeriveGeneric, DataKinds, OverloadedStrings, TypeOperators #-}
module Htrans.Cli (
-- funcs
cli,
appName
) where
import qualified Data.Text as T
import Paths_htrans (version)
import Data.Version (showVersion)
import Options.Generic
import Data.Maybe
import Htrans.Types (Lang(..), LogLevel(..), Config(..), Args(..))
appName :: String
appName = "htranslator"
getAppVersion :: T.Text
getAppVersion = T.pack $ showVersion version
defaultLangFrom :: Lang
defaultLangFrom = EN
defaultLangTo :: Lang
defaultLangTo = RU
defaultLogLevel :: LogLevel
defaultLogLevel = EME
defaultLogPath :: FilePath
defaultLogPath = "./" ++
appName ++ ".log"
defaultOnScreen :: Bool
defaultOnScreen = False
cli :: IO Config
cli = do
x <- getRecord $ T.append "Translate text from one language to another\
\ using Yandex Translate API ********\
\ translator - Yandex Translate API console tool version: " getAppVersion
return Config {
textToTranslate = unHelpful $ text x,
keyAPI = unHelpful $ key x,
fromLang = fromMaybe defaultLangFrom $ unHelpful $ from x,
toLang = fromMaybe defaultLangTo $ unHelpful $ to x,
logLevel = fromMaybe defaultLogLevel $ unHelpful $ logs x,
logPath = fromMaybe defaultLogPath $ unHelpful $ path x,
onScreen = fromMaybe defaultOnScreen $ unHelpful $ notify x
}
| johhy/htrans | src/Htrans/Cli.hs | bsd-3-clause | 1,421 | 0 | 12 | 326 | 341 | 191 | 150 | 37 | 1 |
module ImplicitRefs.Parser
( expression
, program
, parseProgram
) where
import Control.Monad (void)
import Data.Maybe (fromMaybe)
import ImplicitRefs.Data
import Text.Megaparsec hiding (ParseError)
import Text.Megaparsec.Expr
import qualified Text.Megaparsec.Lexer as L
import Text.Megaparsec.String
parseProgram :: String -> Try Program
parseProgram input = case runParser program "Program Parser" input of
Left err -> Left $ ParseError err
Right p -> Right p
spaceConsumer :: Parser ()
spaceConsumer = L.space (void spaceChar) lineCmnt blockCmnt
where lineCmnt = L.skipLineComment "//"
blockCmnt = L.skipBlockComment "/*" "*/"
symbol = L.symbol spaceConsumer
parens = between (symbol "(") (symbol ")")
minus = symbol "-"
equal = symbol "="
comma = symbol ","
longArrow = symbol "==>"
semiColon = symbol ";"
lexeme :: Parser a -> Parser a
lexeme = L.lexeme spaceConsumer
keyWord :: String -> Parser ()
keyWord w = string w *> notFollowedBy alphaNumChar *> spaceConsumer
reservedWords :: [String]
reservedWords =
[ "let", "in", "if", "then", "else", "zero?", "minus"
, "equal?", "greater?", "less?", "cond", "end", "proc", "letrec"
, "begin", "set", "setdynamic", "during", "ref", "deref", "setref"
]
binOpsMap :: [(String, BinOp)]
binOpsMap =
[ ("+", Add), ("-", Sub), ("*", Mul), ("/", Div), ("equal?", Eq)
, ("greater?", Gt), ("less?", Le) ]
binOp :: Parser BinOp
binOp = do
opStr <- foldl1 (<|>) (fmap (try . symbol . fst) binOpsMap)
return $ fromMaybe
(error ("Unknown operator '" `mappend` opStr `mappend` "'"))
(lookup opStr binOpsMap)
unaryOpsMap :: [(String, UnaryOp)]
unaryOpsMap =
[ ("minus", Minus), ("zero?", IsZero) ]
unaryOp :: Parser UnaryOp
unaryOp = do
opStr <- foldl1 (<|>) (fmap (try . symbol . fst) unaryOpsMap)
return $ fromMaybe
(error ("Unknown operator '" `mappend` opStr `mappend` "'"))
(lookup opStr unaryOpsMap)
-- | Identifier ::= String (without reserved words)
identifier :: Parser String
identifier = lexeme (p >>= check)
where
p = (:) <$> letterChar <*> many alphaNumChar
check x = if x `elem` reservedWords
then fail $
concat ["keyword ", show x, " cannot be an identifier"]
else return x
integer :: Parser Integer
integer = lexeme L.integer
signedInteger :: Parser Integer
signedInteger = L.signed spaceConsumer integer
pairOf :: Parser a -> Parser b -> Parser (a, b)
pairOf pa pb = parens $ do
a <- pa
comma
b <- pb
return (a, b)
-- expressionPair ::= (Expression, Expression)
expressionPair :: Parser (Expression, Expression)
expressionPair = pairOf expression expression
-- | ConstExpr ::= Number
constExpr :: Parser Expression
constExpr = ConstExpr . ExprNum <$> signedInteger
-- | BinOpExpr ::= BinOp (Expression, Expression)
binOpExpr :: Parser Expression
binOpExpr = do
op <- binOp
exprPair <- expressionPair
return $ uncurry (BinOpExpr op) exprPair
-- | UnaryOpExpr ::= UnaryOp (Expression)
unaryOpExpr :: Parser Expression
unaryOpExpr = do
op <- unaryOp
expr <- parens expression
return $ UnaryOpExpr op expr
-- | IfExpr ::= if Expression then Expression
ifExpr :: Parser Expression
ifExpr = do
keyWord "if"
ifE <- expression
keyWord "then"
thenE <- expression
keyWord "else"
elseE <- expression
return $ CondExpr [(ifE, thenE), (ConstExpr (ExprBool True), elseE)]
-- | VarExpr ::= Identifier
varExpr :: Parser Expression
varExpr = VarExpr <$> identifier
-- | LetExpr ::= let {Identifier = Expression}* in Expression
letExpr :: Parser Expression
letExpr = letFamilyExpr "let" LetExpr
letFamilyExpr :: String
-> ([(String, Expression)] -> Expression -> Expression)
-> Parser Expression
letFamilyExpr letType builder = do
keyWord letType
bindings <- many binding
keyWord "in"
body <- expression
return $ builder bindings body
where
binding = try assignment
-- | LetrecExpr ::= letrec {Identifier (Identifier) = Expression} in Expression
letRecExpr :: Parser Expression
letRecExpr = do
keyWord "letrec"
procBindings <- many procBinding
keyWord "in"
recBody <- expression
return $ LetRecExpr procBindings recBody
where
procBinding = try $ do
procName <- identifier
params <- parens $ many identifier
equal
procBody <- expression
return (procName, params, procBody)
-- | ManyExprs ::= <empty>
-- ::= Many1Exprs
manyExprs :: Parser [Expression]
manyExprs = sepBy expression comma
-- | Many1Exprs ::= Expression
-- ::= Expression , Many1Exprs
many1Exprs :: Parser [Expression]
many1Exprs = sepBy1 expression comma
-- | CondExpr ::= cond {Expression ==> Expression}* end
condExpr :: Parser Expression
condExpr = do
keyWord "cond"
pairs <- many pair
keyWord "end"
return $ CondExpr pairs
where
pair = try $ do
expr1 <- expression
longArrow
expr2 <- expression
return (expr1, expr2)
-- | ProcExpr ::= proc ({Identifier}*) Expression
procExpr :: Parser Expression
procExpr = do
keyWord "proc"
params <- parens $ many identifier
body <- expression
return $ ProcExpr params body
-- | CallExpr ::= (Expression {Expression}*)
callExpr :: Parser Expression
callExpr = parens $ do
rator <- expression
rands <- many expression
return $ CallExpr rator rands
-- | BeginExpr ::= begin BeginBody end
--
-- BeginBody ::= <empty>
-- ::= Expression BeginBodyTail
--
-- BeginBodyTail ::= <empty>
-- ::= ; Expression BeginBodyTail
beginExpr :: Parser Expression
beginExpr = do
keyWord "begin"
exprs <- sepBy1 (try expression) semiColon
keyWord "end"
return $ BeginExpr exprs
assignment :: Parser (String, Expression)
assignment = do
name <- identifier
equal
expr <- expression
return (name, expr)
-- | AssignExpr ::= set Identifier = Expression
assignExpr :: Parser Expression
assignExpr = do
keyWord "set"
assign <- assignment
return $ uncurry AssignExpr assign
-- | SetDynamicExpr ::= setdynamic Identifier = Expression during Expression
setDynamicExpr :: Parser Expression
setDynamicExpr = do
keyWord "setdynamic"
assign <- assignment
keyWord "during"
body <- expression
return $ uncurry SetDynamicExpr assign body
-- | RefExpr ::= ref Identifier
refExpr :: Parser Expression
refExpr = RefExpr <$> (keyWord "ref" >> identifier)
-- | DeRefExpr ::= deref (Identifier)
deRefExpr :: Parser Expression
deRefExpr = DeRefExpr <$> (keyWord "deref" >> parens identifier)
-- | SetRefExpr ::= setref (Identifier, Expression)
setRefExpr :: Parser Expression
setRefExpr = do
keyWord "setref"
pair <- pairOf identifier expression
return $ uncurry SetRefExpr pair
-- | Expression ::= ConstExpr
-- ::= BinOpExpr
-- ::= UnaryOpExpr
-- ::= IfExpr
-- ::= CondExpr
-- ::= VarExpr
-- ::= LetExpr
-- ::= LetRecExpr
-- ::= ProcExpr
-- ::= CallExpr
-- ::= BeginExpr
-- ::= AssignExpr
-- ::= SetDynamicExpr
-- ::= RefExpr
-- ::= DeRefExpr
-- ::= SetRefExpr
expression :: Parser Expression
expression = foldl1 (<|>) (fmap try expressionList)
where
expressionList =
[ constExpr
, binOpExpr
, unaryOpExpr
, ifExpr
, condExpr
, varExpr
, letExpr
, letRecExpr
, procExpr
, callExpr
, beginExpr
, assignExpr
, setDynamicExpr
, refExpr
, deRefExpr
, setRefExpr
]
program :: Parser Program
program = do
spaceConsumer
expr <- expression
eof
return $ Prog expr
| li-zhirui/EoplLangs | src/ImplicitRefs/Parser.hs | bsd-3-clause | 7,780 | 0 | 13 | 1,881 | 2,029 | 1,057 | 972 | 205 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module Karamaan.Opaleye.Distinct where
import Karamaan.Opaleye.QueryArr (Query, runSimpleQueryArr, simpleQueryArr)
import Karamaan.Opaleye.Wire (Wire(Wire))
import Database.HaskellDB.PrimQuery (PrimQuery(Group),PrimExpr(AttrExpr))
import Karamaan.Opaleye.Operators2 (union)
import Karamaan.Opaleye.QueryColspec (QueryColspec)
import qualified Karamaan.Opaleye.Unpackspec as U
import qualified Data.Profunctor.Product as PP
import qualified Data.Profunctor.Product.Default as D
import Data.Profunctor.Product.Default (Default)
distinct' :: U.Unpackspec wires -> Query wires -> Query wires
distinct' u q = simpleQueryArr $ \((), t0) ->
let (a, primQ, t1) = runSimpleQueryArr q ((), t0)
cols = U.runUnpackspec u a
in (a, Group (map (\oldCol -> (oldCol, AttrExpr oldCol)) cols) primQ, t1)
distinctBetter :: D.Default (PP.PPOfContravariant U.Unpackspec) wires wires =>
Query wires -> Query wires
distinctBetter = distinct' D.cdef
-- I realised you can implement distinct x = x `union` x!
-- This may fail massively with large queries unless the optimiser realises
-- that I'm taking the union of the same query twice.
-- TODO: Try to just implement this as x `union` "empty"?
{-# DEPRECATED distinct "Use 'distinctBetter' instead" #-}
distinct :: Default QueryColspec a a => Query a -> Query a
distinct x = x `union` x
-- This is how I used to implement it. It didn't work very well.
-- I think this is a correct implementation, but HaskellDB still seems to have
-- trouble dealing with GROUP BY. See Report.Trade.Descendants.activeEdgesBroken
{-# DEPRECATED distinct1 "Use 'distinctBetter' instead" #-}
distinct1 :: Query (Wire a) -> Query (Wire a)
distinct1 q = simpleQueryArr $ \((), t0) ->
let (Wire oldCol, primQ, t1) = runSimpleQueryArr q ((), t0)
-- vv We used to do
-- newCol = tagWith t1 oldCol
-- t2 = next t1
-- but now we just do
newCol = oldCol
t2 = t1
-- and HaskellDB seems happier with that. Note that 'tagWith t1
-- oldCol' adds an *additional* tag to a column name that presumably
-- already has one. I wasn't sure if that was a good idea anyway.
in (Wire newCol, Group [(newCol, AttrExpr oldCol)] primQ, t2)
| karamaan/karamaan-opaleye | Karamaan/Opaleye/Distinct.hs | bsd-3-clause | 2,216 | 0 | 16 | 380 | 492 | 285 | 207 | 29 | 1 |
module BSPM where
| schernichkin/BSPM | bsp/src/BSPM.hs | bsd-3-clause | 19 | 0 | 2 | 3 | 4 | 3 | 1 | 1 | 0 |
{-# LANGUAGE PatternGuards #-}
module Development.Shake.FilePattern(
FilePattern, (?==),
compatible, extract, substitute,
directories, directories1
) where
import System.FilePath(pathSeparators)
import Data.List
import Control.Arrow
---------------------------------------------------------------------
-- BASIC FILE PATTERN MATCHING
-- | A type synonym for file patterns, containing @\/\/@ and @*@. For the syntax
-- and semantics of 'FilePattern' see '?=='.
type FilePattern = String
data Lexeme = Star | SlashSlash | Char Char deriving (Show, Eq)
isChar (Char _) = True; isChar _ = False
isDull (Char x) = x /= '/'; isDull _ = False
fromChar (Char x) = x
data Regex = Lit [Char] | Not [Char] | Any
| Start | End
| Bracket Regex
| Or Regex Regex | Concat Regex Regex
| Repeat Regex | Empty
deriving Show
type SString = (Bool, String) -- fst is True if at the start of the string
lexer :: FilePattern -> [Lexeme]
lexer ('*':xs) = Star : lexer xs
lexer ('/':'/':xs) = SlashSlash : lexer xs
lexer (x:xs) = Char x : lexer xs
lexer [] = []
pattern :: [Lexeme] -> Regex
pattern = Concat Start . foldr Concat End . map f
where
f Star = Bracket $ Repeat $ Not pathSeparators
f SlashSlash = let s = Start `Or` End `Or` Lit pathSeparators in Bracket $
Or (s `Concat` Repeat Any `Concat` s) (Lit pathSeparators)
f (Char x) = Lit $ if x == '/' then pathSeparators else [x]
-- | Return is (brackets, matched, rest)
match :: Regex -> SString -> [([String], String, SString)]
match (Lit l) (_, x:xs) | x `elem` l = [([], [x], (False, xs))]
match (Not l) (_, x:xs) | x `notElem` l = [([], [x], (False, xs))]
match Any (_, x:xs) = [([], [x], (False, xs))]
match Start (True, xs) = [([], [], (True, xs))]
match End (s, []) = [([], [], (s, []))]
match (Bracket r) xs = [(a ++ [b], b, c) | (a,b,c) <- match r xs]
match (Or r1 r2) xs = match r1 xs ++ match r2 xs
match (Concat r1 r2) xs = [(a1++a2,b1++b2,c2) | (a1,b1,c1) <- match r1 xs, (a2,b2,c2) <- match r2 c1]
match (Repeat r) xs = match (Empty `Or` Concat r (Repeat r)) xs
match Empty xs = [([], "", xs)]
match _ _ = []
-- | Match a 'FilePattern' against a 'FilePath', There are only two special forms:
--
-- * @*@ matches an entire path component, excluding any separators.
--
-- * @\/\/@ matches an arbitrary number of path components.
--
-- Some examples that match:
--
-- @
-- \"\/\/*.c\" '?==' \"foo\/bar\/baz.c\"
-- \"*.c\" '?==' \"baz.c\"
-- \"\/\/*.c\" '?==' \"baz.c\"
-- \"test.c\" '?==' \"test.c\"
-- @
--
-- Examples that /don't/ match:
--
-- @
-- \"*.c\" '?==' \"foo\/bar.c\"
-- \"*\/*.c\" '?==' \"foo\/bar\/baz.c\"
-- @
--
-- An example that only matches on Windows:
--
-- @
-- \"foo\/bar\" '?==' \"foo\\\\bar\"
-- @
(?==) :: FilePattern -> FilePath -> Bool
(?==) p x = not $ null $ match (pattern $ lexer p) (True, x)
---------------------------------------------------------------------
-- DIRECTORY PATTERNS
-- | Given a pattern, return the directory that requires searching,
-- with 'True' if it requires a recursive search. Must be conservative.
-- Examples:
--
-- > directories1 "*.xml" == ("",False)
-- > directories1 "//*.xml" == ("",True)
-- > directories1 "foo//*.xml" == ("foo",True)
-- > directories1 "foo/bar/*.xml" == ("foo/bar",False)
-- > directories1 "*/bar/*.xml" == ("",True)
directories1 :: FilePattern -> (FilePath, Bool)
directories1 = first (intercalate "/") . f . lexer
where
f xs | (a@(_:_),b:bs) <- span isDull xs, b `elem` [Char '/',SlashSlash] =
if b == SlashSlash then ([map fromChar a],True) else first (map fromChar a:) $ f bs
| all (\x -> isDull x || x == Star) xs = ([],False)
| otherwise = ([], True)
-- | Given a set of patterns, produce a set of directories that require searching,
-- with 'True' if it requires a recursive search. Must be conservative. Examples:
--
-- > directories ["*.xml","//*.c"] == [("",True)]
-- > directories ["bar/*.xml","baz//*.c"] == [("bar",False),("baz",True)]
-- > directories ["bar/*.xml","baz//*.c"] == [("bar",False),("baz",True)]
directories :: [FilePattern] -> [(FilePath,Bool)]
directories ps = foldl f xs xs
where
xs = nub $ map directories1 ps
-- Eliminate anything which is a strict subset
f xs (x,True) = filter (\y -> not $ (x,False) == y || (x ++ "/") `isPrefixOf` fst y) xs
f xs _ = xs
---------------------------------------------------------------------
-- MULTIPATTERN COMPATIBLE SUBSTITUTIONS
-- | Do they have the same * and // counts in the same order
compatible :: [FilePattern] -> Bool
compatible [] = True
compatible (x:xs) = all ((==) (f x) . f) xs
where f = filter (not . isChar) . lexer
-- | Extract the items that match the wildcards. The pair must match with '?=='.
extract :: FilePattern -> FilePath -> [String]
extract p x = ms
where (ms,_,_):_ = match (pattern $ lexer p) (True,x)
-- | Given the result of 'extract', substitute it back in to a 'compatible' pattern.
--
-- > p '?==' x ==> substitute (extract p x) p == x
substitute :: [String] -> FilePattern -> FilePath
substitute ms p = f ms (lexer p)
where
f ms (Char p:ps) = p : f ms ps
f (m:ms) (_:ps) = m ++ f ms ps
f [] [] = []
f _ _ = error $ "Substitution failed into pattern " ++ show p ++ " with " ++ show (length ms) ++ " matches, namely " ++ show ms
| nh2/shake | Development/Shake/FilePattern.hs | bsd-3-clause | 5,466 | 16 | 15 | 1,212 | 1,753 | 984 | 769 | 69 | 4 |
Subsets and Splits