code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
{-# LANGUAGE MultiParamTypeClasses #-} -- | -- Module : Simulation.Aivika.Experiment.Chart.DeviationChartView -- Copyright : Copyright (c) 2012-2017, David Sorokin <david.sorokin@gmail.com> -- License : BSD3 -- Maintainer : David Sorokin <david.sorokin@gmail.com> -- Stability : experimental -- Tested with: GHC 8.0.1 -- -- The module defines 'DeviationChartView' that plots the deviation chart using rule of 3-sigma. -- module Simulation.Aivika.Experiment.Chart.DeviationChartView (DeviationChartView(..), defaultDeviationChartView) where import Control.Monad import Control.Monad.Trans import Control.Concurrent.MVar import Control.Lens import qualified Data.Map as M import Data.IORef import Data.Maybe import Data.Either import Data.Monoid import Data.Array import Data.Array.IO.Safe import Data.Default.Class import System.IO import System.FilePath import Graphics.Rendering.Chart import Simulation.Aivika import Simulation.Aivika.Experiment import Simulation.Aivika.Experiment.Base import Simulation.Aivika.Experiment.Concurrent.MVar import Simulation.Aivika.Experiment.Chart.Types import Simulation.Aivika.Experiment.Chart.Utils (colourisePlotLines, colourisePlotFillBetween) -- | Defines the 'View' that plots the deviation chart in time points by the specified grid. data DeviationChartView = DeviationChartView { deviationChartTitle :: String, -- ^ This is a title used in HTML. deviationChartDescription :: String, -- ^ This is a description used in HTML. deviationChartWidth :: Int, -- ^ The width of the chart. deviationChartHeight :: Int, -- ^ The height of the chart. deviationChartGridSize :: Int, -- ^ The size of the grid, where the series data are collected. deviationChartFileName :: ExperimentFilePath, -- ^ It defines the file name with optional extension for each image to be saved. -- It may include special variable @$TITLE@. -- -- An example is -- -- @ -- deviationChartFileName = UniqueFilePath \"$TITLE\" -- @ deviationChartTransform :: ResultTransform, -- ^ The transform applied to the results before receiving series. deviationChartLeftYSeries :: ResultTransform, -- ^ It defines the series to be plotted basing on the left Y axis. deviationChartRightYSeries :: ResultTransform, -- ^ It defines the series to be plotted basing on the right Y axis. deviationChartPlotTitle :: String, -- ^ This is a title used in the chart. -- It may include special variable @$TITLE@. -- -- An example is -- -- @ -- deviationChartPlotTitle = \"$TITLE\" -- @ deviationChartPlotLines :: [PlotLines Double Double -> PlotLines Double Double], -- ^ Probably, an infinite sequence of plot -- transformations based on which the plot -- is constructed for each series. Generally, -- it may not coincide with a sequence of -- labels as one label may denote a whole list -- or an array of data providers. -- -- Here you can define a colour or style of -- the plot lines. deviationChartPlotFillBetween :: [PlotFillBetween Double Double -> PlotFillBetween Double Double], -- ^ Corresponds exactly to 'deviationChartPlotLines' -- but used for plotting the deviation areas -- by the rule of 3-sigma, while the former -- is used for plotting the trends of the -- random processes. deviationChartBottomAxis :: LayoutAxis Double -> LayoutAxis Double, -- ^ A transformation of the bottom axis, -- after title @time@ is added. deviationChartLayout :: LayoutLR Double Double Double -> LayoutLR Double Double Double -- ^ A transformation of the plot layout, -- where you can redefine the axes, for example. } -- | The default deviation chart view. defaultDeviationChartView :: DeviationChartView defaultDeviationChartView = DeviationChartView { deviationChartTitle = "Deviation Chart", deviationChartDescription = "It shows the Deviation chart by rule 3-sigma.", deviationChartWidth = 640, deviationChartHeight = 480, deviationChartGridSize = 2 * 640, deviationChartFileName = UniqueFilePath "DeviationChart", deviationChartTransform = id, deviationChartLeftYSeries = mempty, deviationChartRightYSeries = mempty, deviationChartPlotTitle = "$TITLE", deviationChartPlotLines = colourisePlotLines, deviationChartPlotFillBetween = colourisePlotFillBetween, deviationChartBottomAxis = id, deviationChartLayout = id } instance ChartRendering r => ExperimentView DeviationChartView (WebPageRenderer r) where outputView v = let reporter exp (WebPageRenderer renderer _) dir = do st <- newDeviationChart v exp renderer dir let context = WebPageContext $ WebPageWriter { reporterWriteTOCHtml = deviationChartTOCHtml st, reporterWriteHtml = deviationChartHtml st } return ExperimentReporter { reporterInitialise = return (), reporterFinalise = finaliseDeviationChart st, reporterSimulate = simulateDeviationChart st, reporterContext = context } in ExperimentGenerator { generateReporter = reporter } instance ChartRendering r => ExperimentView DeviationChartView (FileRenderer r) where outputView v = let reporter exp (FileRenderer renderer _) dir = do st <- newDeviationChart v exp renderer dir return ExperimentReporter { reporterInitialise = return (), reporterFinalise = finaliseDeviationChart st, reporterSimulate = simulateDeviationChart st, reporterContext = FileContext } in ExperimentGenerator { generateReporter = reporter } -- | The state of the view. data DeviationChartViewState r = DeviationChartViewState { deviationChartView :: DeviationChartView, deviationChartExperiment :: Experiment, deviationChartRenderer :: r, deviationChartDir :: FilePath, deviationChartFile :: IORef (Maybe FilePath), deviationChartResults :: MVar (Maybe DeviationChartResults) } -- | The deviation chart item. data DeviationChartResults = DeviationChartResults { deviationChartTimes :: IOArray Int Double, deviationChartNames :: [Either String String], deviationChartStats :: [MVar (IOArray Int (SamplingStats Double))] } -- | Create a new state of the view. newDeviationChart :: DeviationChartView -> Experiment -> r -> FilePath -> ExperimentWriter (DeviationChartViewState r) newDeviationChart view exp renderer dir = liftIO $ do f <- newIORef Nothing r <- newMVar Nothing return DeviationChartViewState { deviationChartView = view, deviationChartExperiment = exp, deviationChartRenderer = renderer, deviationChartDir = dir, deviationChartFile = f, deviationChartResults = r } -- | Create new chart results. newDeviationChartResults :: DeviationChartViewState r -> [Either String String] -> IO DeviationChartResults newDeviationChartResults st names = do let exp = deviationChartExperiment st view = deviationChartView st size = deviationChartGridSize view specs = experimentSpecs exp grid = timeGrid specs size bnds = (0, 1 + length grid) times <- liftIO $ newListArray bnds $ map snd grid stats <- forM names $ \_ -> liftIO $ newArray bnds emptySamplingStats >>= newMVar return DeviationChartResults { deviationChartTimes = times, deviationChartNames = names, deviationChartStats = stats } -- | Require to return unique chart results associated with the specified state. requireDeviationChartResults :: DeviationChartViewState r -> [Either String String] -> IO DeviationChartResults requireDeviationChartResults st names = maybePutMVar (deviationChartResults st) (newDeviationChartResults st names) $ \results -> if (names /= deviationChartNames results) then error "Series with different names are returned for different runs: requireDeviationChartResults" else return results -- | Simulate the specified series. simulateDeviationChart :: DeviationChartViewState r -> ExperimentData -> Composite () simulateDeviationChart st expdata = do let view = deviationChartView st loc = localisePathResultTitle $ experimentLocalisation $ deviationChartExperiment st rs1 = deviationChartLeftYSeries view $ deviationChartTransform view $ experimentResults expdata rs2 = deviationChartRightYSeries view $ deviationChartTransform view $ experimentResults expdata exts1 = resultsToDoubleStatsEitherValues rs1 exts2 = resultsToDoubleStatsEitherValues rs2 exts = exts1 ++ exts2 names1 = map (loc . resultValueIdPath) exts1 names2 = map (loc . resultValueIdPath) exts2 names = map Left names1 ++ map Right names2 signal <- liftEvent $ newSignalInTimeGrid $ deviationChartGridSize view hs <- forM exts $ \ext -> newSignalHistory $ flip mapSignalM signal $ \i -> resultValueData ext disposableComposite $ DisposableEvent $ do results <- liftIO $ requireDeviationChartResults st names let stats = deviationChartStats results forM_ (zip hs stats) $ \(h, stats') -> do (ts, xs) <- readSignalHistory h let (lo, hi) = bounds ts liftIO $ withMVar stats' $ \stats'' -> forM_ [lo..hi] $ \i -> do let x = xs ! i y <- readArray stats'' i let y' = combineSamplingStatsEither x y y' `seq` writeArray stats'' i y' -- | Plot the deviation chart after the simulation is complete. finaliseDeviationChart :: ChartRendering r => DeviationChartViewState r -> ExperimentWriter () finaliseDeviationChart st = do let view = deviationChartView st title = deviationChartTitle view plotTitle = deviationChartPlotTitle view plotTitle' = replace "$TITLE" title plotTitle width = deviationChartWidth view height = deviationChartHeight view plotLines = deviationChartPlotLines view plotFillBetween = deviationChartPlotFillBetween view plotBottomAxis = deviationChartBottomAxis view plotLayout = deviationChartLayout view renderer = deviationChartRenderer st file <- resolveFilePath (deviationChartDir st) $ mapFilePath (flip replaceExtension $ renderableChartExtension renderer) $ expandFilePath (deviationChartFileName view) $ M.fromList [("$TITLE", title)] results <- liftIO $ readMVar $ deviationChartResults st case results of Nothing -> return () Just results -> liftIO $ do let times = deviationChartTimes results names = deviationChartNames results stats = deviationChartStats results ps1 <- forM (zip3 names stats plotLines) $ \(name, stats', plotLines) -> do stats'' <- readMVar stats' xs <- getAssocs stats'' zs <- forM xs $ \(i, stats) -> do t <- readArray times i return (t, samplingStatsMean stats) let p = toPlot $ plotLines $ plot_lines_values .~ filterPlotLinesValues zs $ plot_lines_title .~ either id id name $ def case name of Left _ -> return $ Left p Right _ -> return $ Right p ps2 <- forM (zip3 names stats plotFillBetween) $ \(name, stats', plotFillBetween) -> do stats'' <- readMVar stats' xs <- getAssocs stats'' zs <- forM xs $ \(i, stats) -> do t <- readArray times i let mu = samplingStatsMean stats sigma = samplingStatsDeviation stats return (t, (mu - 3 * sigma, mu + 3 * sigma)) let p = toPlot $ plotFillBetween $ plot_fillbetween_values .~ filterPlotFillBetweenValues zs $ plot_fillbetween_title .~ either id id name $ def case name of Left _ -> return $ Left p Right _ -> return $ Right p let ps = join $ flip map (zip ps1 ps2) $ \(p1, p2) -> [p2, p1] axis = plotBottomAxis $ laxis_title .~ "time" $ def updateLeftAxis = if null $ lefts ps then layoutlr_left_axis_visibility .~ AxisVisibility False False False else id updateRightAxis = if null $ rights ps then layoutlr_right_axis_visibility .~ AxisVisibility False False False else id chart = plotLayout . renderingLayoutLR renderer . updateLeftAxis . updateRightAxis $ layoutlr_x_axis .~ axis $ layoutlr_title .~ plotTitle' $ layoutlr_plots .~ ps $ def renderChart renderer (width, height) file (toRenderable chart) when (experimentVerbose $ deviationChartExperiment st) $ putStr "Generated file " >> putStrLn file writeIORef (deviationChartFile st) $ Just file -- | Remove the NaN and inifity values. filterPlotLinesValues :: [(Double, Double)] -> [[(Double, Double)]] filterPlotLinesValues = filter (not . null) . divideBy (\(t, x) -> isNaN x || isInfinite x) -- | Remove the NaN and inifity values. filterPlotFillBetweenValues :: [(Double, (Double, Double))] -> [(Double, (Double, Double))] filterPlotFillBetweenValues = filter $ \(t, (x1, x2)) -> not $ isNaN x1 || isInfinite x1 || isNaN x2 || isInfinite x2 -- | Get the HTML code. deviationChartHtml :: DeviationChartViewState r -> Int -> HtmlWriter () deviationChartHtml st index = do header st index file <- liftIO $ readIORef (deviationChartFile st) case file of Nothing -> return () Just f -> writeHtmlParagraph $ writeHtmlImage (makeRelative (deviationChartDir st) f) header :: DeviationChartViewState r -> Int -> HtmlWriter () header st index = do writeHtmlHeader3WithId ("id" ++ show index) $ writeHtmlText (deviationChartTitle $ deviationChartView st) let description = deviationChartDescription $ deviationChartView st unless (null description) $ writeHtmlParagraph $ writeHtmlText description -- | Get the TOC item. deviationChartTOCHtml :: DeviationChartViewState r -> Int -> HtmlWriter () deviationChartTOCHtml st index = writeHtmlListItem $ writeHtmlLink ("#id" ++ show index) $ writeHtmlText (deviationChartTitle $ deviationChartView st)
dsorokin/aivika-experiment-chart
Simulation/Aivika/Experiment/Chart/DeviationChartView.hs
Haskell
bsd-3-clause
17,560
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 800 {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} #endif module Text.RE.TDFA.Text.Lazy ( -- * Tutorial -- $tutorial -- * The Match Operators (*=~) , (?=~) , (=~) , (=~~) -- * The Toolkit -- $toolkit , module Text.RE -- * The 'RE' Type -- $re , module Text.RE.TDFA.RE ) where import Prelude.Compat import qualified Data.Text.Lazy as TL import Data.Typeable import Text.Regex.Base import Text.RE import Text.RE.Internal.AddCaptureNames import Text.RE.TDFA.RE import qualified Text.Regex.TDFA as TDFA -- | find all matches in text (*=~) :: TL.Text -> RE -> Matches TL.Text (*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ match (reRegex rex) bs -- | find first match in text (?=~) :: TL.Text -> RE -> Match TL.Text (?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ match (reRegex rex) bs -- | the regex-base polymorphic match operator (=~) :: ( Typeable a , RegexContext TDFA.Regex TL.Text a , RegexMaker TDFA.Regex TDFA.CompOption TDFA.ExecOption String ) => TL.Text -> RE -> a (=~) bs rex = addCaptureNames (reCaptureNames rex) $ match (reRegex rex) bs -- | the regex-base monadic, polymorphic match operator (=~~) :: ( Monad m , Functor m , Typeable a , RegexContext TDFA.Regex TL.Text a , RegexMaker TDFA.Regex TDFA.CompOption TDFA.ExecOption String ) => TL.Text -> RE -> m a (=~~) bs rex = addCaptureNames (reCaptureNames rex) <$> matchM (reRegex rex) bs instance IsRegex RE TL.Text where matchOnce = flip (?=~) matchMany = flip (*=~) regexSource = reSource -- $tutorial -- We have a regex tutorial at <http://tutorial.regex.uk>. These API -- docs are mainly for reference. -- $toolkit -- -- Beyond the above match operators and the regular expression type -- below, "Text.RE" contains the toolkit for replacing captures, -- specifying options, etc. -- $re -- -- "Text.RE.TDFA.RE" contains the toolkit specific to the 'RE' type, -- the type generated by the gegex compiler.
cdornan/idiot
Text/RE/TDFA/Text/Lazy.hs
Haskell
bsd-3-clause
2,471
module Arhelk.Russian.Lemma.Data.Substantive where import Arhelk.Russian.Lemma.Data.Common import Lens.Simple import Data.Monoid import TextShow -- | Склонение. Describes declension of substantives data Declension = FirstDeclension | SecondDeclension | ThirdDeclension deriving (Eq, Ord, Enum, Show, Bounded) instance TextShow Declension where showb v = case v of FirstDeclension -> "I скл." SecondDeclension -> "II скл." ThirdDeclension -> "III скл." -- | Падеж. Grammatical case. data GrammarCase = Nominativus -- ^ Иминительный | Genitivus -- ^ Родительный | Dativus -- ^ Дательный | Accusativus -- ^ Винительный | Ablativus -- ^ Творительный | Praepositionalis -- ^ Предложный deriving (Eq, Ord, Enum, Show, Bounded) instance TextShow GrammarCase where showb v = case v of Nominativus -> "им. падеж" Genitivus -> "род. падеж" Dativus -> "дат. падеж" Accusativus -> "вин. падеж" Ablativus -> "твор. падеж" Praepositionalis -> "предл. падеж" -- | Имя нарицательное или собственное data Appellativity = AppellativeNoun -- ^ Нарицательное | ProperNoun -- ^ Собственное deriving (Eq, Ord, Enum, Show, Bounded) instance TextShow Appellativity where showb v = case v of AppellativeNoun -> "нариц." ProperNoun -> "собств." -- | Одушевленность data Animacy = AnimateNoun -- ^ Одушевленное | InanimateNoun -- ^ Неодушевленное deriving (Eq, Ord, Enum, Show, Bounded) instance TextShow Animacy where showb v = case v of AnimateNoun -> "одушвл." InanimateNoun -> "неодушвл." -- | Substantive morphological properties data SubstantiveProperties = SubstantiveProperties { _substAppellativity :: Maybe Appellativity , _substAnimacy :: Maybe Animacy , _substDeclension :: Maybe Declension , _substGender :: Maybe GrammarGender , _substQuantity :: Maybe GrammarQuantity , _substCase :: Maybe GrammarCase } deriving (Eq, Show) $(makeLenses ''SubstantiveProperties) instance Monoid SubstantiveProperties where mempty = SubstantiveProperties { _substAppellativity = Nothing , _substAnimacy = Nothing , _substDeclension = Nothing , _substGender = Nothing , _substQuantity = Nothing , _substCase = Nothing } mappend a b = SubstantiveProperties { _substAppellativity = getFirst $ First (_substAppellativity a) <> First (_substAppellativity b) , _substAnimacy = getFirst $ First (_substAnimacy a) <> First (_substAnimacy b) , _substDeclension = getFirst $ First (_substDeclension a) <> First (_substDeclension b) , _substGender = getFirst $ First (_substGender a) <> First (_substGender b) , _substQuantity = getFirst $ First (_substQuantity a) <> First (_substQuantity b) , _substCase = getFirst $ First (_substCase a) <> First (_substCase b) } instance TextShow SubstantiveProperties where showb SubstantiveProperties{..} = unwordsB [ maybe "" showb _substAppellativity , maybe "" showb _substAnimacy , maybe "" showb _substDeclension , maybe "" showb _substGender , maybe "" showb _substQuantity , maybe "" showb _substCase ]
Teaspot-Studio/arhelk-russian
src/Arhelk/Russian/Lemma/Data/Substantive.hs
Haskell
bsd-3-clause
3,365
-- The Timber compiler <timber-lang.org> -- -- Copyright 2008-2009 Johan Nordlander <nordland@csee.ltu.se> -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the names of the copyright holder and any identified -- contributors, nor the names of their affiliations, may be used to -- endorse or promote products derived from this software without -- specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE CONTRIBUTORS ``AS IS'' AND ANY EXPRESS -- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR -- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -- OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, -- STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN -- ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. module Lambdalift(lambdalift) where import Monad import Common import Kindle import PP lambdalift ds m = localStore (llModule ds m) data Env = Env { decls :: Decls, -- global type declarations thisSubst :: Map Name AType, -- thisVars :: [Name], -- variables reachable through "this" locals :: ATEnv, -- non-global value names in scope expansions :: Map Name ([Name],[Name]) -- non-global functions and their added type/term parameters } nullEnv = Env { decls = primDecls, thisSubst = [], thisVars = [], locals = [], expansions = [] } addDecls ds env = env { decls = ds ++ decls env } setThis vs xs env = env { thisSubst = vs `zip` map TThis [1..], thisVars = xs } addLocals te env = env { locals = te ++ prune (locals env) (dom te) } -- prune so that shadowed variables don't -- get lifted multiple times addExpansions exps env = env { expansions = exps ++ expansions env } findStructInstance env (Prim CLOS _) ts = (closBind ts, []) findStructInstance env n ts = (subst s te, [ t | (v,t) <- s, v `elem` vs' ]) where Struct vs te l = if isTuple n then tupleDecl n else lookup' (decls env) n s = vs `zip` ts vs' = equants l -- Convert a module llModule dsi (Module m ns es ds bs) = do bs <- mapM (llBind env0) bs s <- currentStore return (Module m ns es (ds ++ declsOfStore s) (bs ++ bindsOfStore s)) where env0 = addDecls (ds ++ dsi) nullEnv declsOfStore s = [ d | Left d <- s ] bindsOfStore s = [ b | Right b <- s ] -- Convert a binding llBind env (x, Fun vs t te c) = do c <- llCmd (addLocals te env) c return (x, Fun vs t te c) llBind env (x, Val t e) = do e <- llExp env e return (x, Val (mkT env t) e) {- Lambda-lifting a set of recursive bindings: \v -> letrec f r v x = ... r ... v ... letrec f x = ... r ... v ... g r v y = ... f r v e ... r = { a = ... g e ... } ==> in \v -> g y = ... f e ... letrec r = { a = ... g r v e ... } in f e in f r v e -} {- Closing a struct with function fields: \v -> \v -> { f x = ... v ... { f x = ... this.v ... w = ... v ... } ==> w = ... v ... v = v } -} -- Convert a command llCmd env (CBind r bs c) = do vals' <- mapM (llBind env') vals funs' <- mapM (llBind (setThis [] [] env')) funs store <- currentStore let fs = dom funs' `intersect` [ f | Right (f,_) <- store ] fs' <- mapM (newName . str) fs let s = fs `zip` fs' mapM_ liftFun (subst s funs') c' <- llCmd env2 c return (cBindR r (subst s vals') (subst s c')) where (vals,funs) = partition isVal bs free0 = evars funs free1 = free0 ++ concat [ xs | (f,(_,xs)) <- expansions env, f `elem` free0 ] fte = locals (if r then env1 else env) `restrict` free1 vs1 = concat [ vs | (f,(vs,_)) <- expansions env, f `elem` free0 ] fvs = nub (typevars funs ++ typevars fte ++ vs1) env1 = addLocals (mapSnd typeOf' vals) env env2 = addExpansions (dom funs `zip` repeat (fvs, dom fte)) env1 env' = if r then env2 else env liftFun (x, Fun vs t te c) = addToStore (Right (x, Fun (fvs++vs) t (fte++te) c)) llCmd env (CRet e) = liftM CRet (llExp env e) llCmd env (CRun e c) = liftM2 CRun (llExp env e) (llCmd env c) llCmd env (CUpd x e c) = liftM2 (CUpd x) (llExp env e) (llCmd env c) llCmd env (CUpdS e x e' c) = do e <- llExp env e liftM2 (CUpdS e x) (llExp env e') (llCmd env c) llCmd env (CUpdA e i e' c) = liftM4 CUpdA (llExp env e) (llExp env i) (llExp env e') (llCmd env c) llCmd env (CSwitch e alts) = liftM2 CSwitch (llExp env e) (mapM (llAlt env) alts) llCmd env (CSeq c c') = liftM2 CSeq (llCmd env c) (llCmd env c') llCmd env (CBreak) = return CBreak llCmd env (CRaise e) = liftM CRaise (llExp env e) llCmd env (CWhile e c c') = liftM3 CWhile (llExp env e) (llCmd env c) (llCmd env c') llCmd env (CCont) = return CCont -- Convert a switch alternative llAlt env (ACon x vs te c) = liftM (ACon x vs (mkT env te)) (llCmd (addLocals te env) c) llAlt env (ALit l c) = liftM (ALit l) (llCmd env c) llAlt env (AWild c) = liftM AWild (llCmd env c) -- Convert an expression llExp env (ECall x ts es) = do es <- mapM (llExp env) es case lookup x (expansions env) of Just (vs,xs) -> return (ECall x (mkT env (map tVar vs ++ ts)) (map (mkEVar env) xs ++ es)) Nothing -> return (ECall x (mkT env ts) es) llExp env ee@(ENew n ts0 bs) | null fte && null fvs = liftM (ENew n ts) (mapM (llBind env) bs) | otherwise = do n' <- getStructName (Struct tvs (te ++ mapSnd ValT fte) (Extends n ts tvs)) vals' <- mapM (llBind env) vals funs' <- mapM (llBind (setThis tvs (dom fte) env)) funs -- tr ("lift ENew: " ++ render (pr (TCon n ts)) ++ " fvs: " ++ show fvs ++ " new: " ++ show n') return (ECast (TCon n ts) (ENew n' (ts'++map close' fvs) (vals' ++ funs' ++ map close fte))) where ts = mkT env ts0 (vals,funs) = partition isVal bs free0 = evars funs free1 = free0 ++ concat [ xs | (f,(_,xs)) <- expansions env, f `elem` free0 ] fte = locals env `restrict` free1 vs1 = concat [ vs | (f,(vs,_)) <- expansions env, f `elem` free0 ] fvs = nub (typevars funs ++ typevars fte ++ vs1) tvs = take (length ts') abcSupply ++ fvs (te,ts') = findStructInstance env n ts close (x,t) = (x, Val (mkT env t) (mkEVar env x)) close' v = mkT env (tVar v) llExp env (EVar x) = return (mkEVar env x) llExp env (EThis) = return (EThis) llExp env (ELit l) = return (ELit l) llExp env (ESel e l) = liftM (flip ESel l) (llExp env e) llExp env (EEnter e f ts es) = do e <- llExp env e liftM (EEnter e f (mkT env ts)) (mapM (llExp env) es) llExp env (ECast t e) = liftM (ECast (mkT env t)) (llExp env e) mkEVar env x = if x `elem` thisVars env then ESel EThis x else EVar x mkT env t = subst (thisSubst env) t getStructName str = do s <- currentStore case findStruct str (declsOfStore s) of Just n -> return n Nothing -> do n <- newName typeSym addToStore (Left (n, str)) return n
mattias-lundell/timber-llvm
src/Lambdalift.hs
Haskell
bsd-3-clause
11,061
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} {-# LANGUAGE ConstraintKinds #-} module Fragment.Annotation.Rules.Type.Infer.SyntaxDirected ( AnnotationInferTypeContext , annotationInferTypeRules ) where import Rules.Type.Infer.SyntaxDirected import Fragment.Annotation.Ast.Term import Fragment.Annotation.Rules.Type.Infer.Common type AnnotationInferTypeContext e w s r m ki ty pt tm a = AsTmAnnotation ki ty pt tm annotationInferTypeRules :: AnnotationInferTypeContext e w s r m ki ty pt tm a => InferTypeInput e w s r m m ki ty pt tm a annotationInferTypeRules = let ah = AnnotationHelper expectType in inferTypeInput ah
dalaing/type-systems
src/Fragment/Annotation/Rules/Type/Infer/SyntaxDirected.hs
Haskell
bsd-3-clause
777
{-# LANGUAGE OverloadedStrings #-} -- | Find paths given the root directory of deployment. module Paths ( RootDir , incoming , angelConf , nginxConf , postgresConf ) where import Prelude () import Filesystem.Path.CurrentOS (FilePath, (</>)) type RootDir = FilePath incoming :: RootDir -> FilePath incoming = (</> "incoming") angelConf :: RootDir -> FilePath angelConf r = r </> "etc" </> "angel.conf" nginxConf :: FilePath nginxConf = "/etc/nginx/sites-enabled/yesod-deploy.conf" postgresConf :: RootDir -> FilePath postgresConf r = r </> "etc" </> "postgres.yaml"
yesodweb/deploy
src/Paths.hs
Haskell
bsd-3-clause
595
{-# language TemplateHaskell, GADTs #-} import Data.Function.Memoize import Control.Monad (forM_, when) import Test3Helper -- NonstandardParams is defined by: -- -- data NonstandardParams a b -- = NonstandardParams (a -> Bool) b -- -- This won’t compile because it needs addition typeclass constraints in -- the instance context: -- -- $(deriveMemoizable ''NonstandardParams) instance (Eq a, Enum a, Bounded a, Memoizable b) => Memoizable (NonstandardParams a b) where memoize = $(deriveMemoize ''NonstandardParams) applyToLength :: NonstandardParams Bool Int -> Bool applyToLength (NonstandardParams f z) = f (odd z) cases = [ (NonstandardParams id 5, True) , (NonstandardParams id 6, False) , (NonstandardParams not 5, False) , (NonstandardParams not 6, True) ] main :: IO () main = do let memoized = memoize applyToLength forM_ cases $ \(input, expected) -> do let actual = applyToLength input when (actual /= expected) $ fail $ "Test failed: got " ++ show actual ++ " when " ++ show expected ++ " expected."
tov/memoize
test/test3.hs
Haskell
bsd-3-clause
1,093
{-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -Wall #-} {-# OPTIONS_GHC -fno-warn-missing-methods #-} module HW06.HW06 where -- Exercise 1 ----------------------------------------- fib :: Integer -> Integer fib 0 = 0 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) fibs1 :: [Integer] fibs1 = fib `map` [0..] -- Exercise 2 ----------------------------------------- fibs2 :: [Integer] fibs2 = 0 : 1 : zipWith (+) fibs2 (tail fibs2) -- Exercise 3 ----------------------------------------- data Stream a = a `Cons` (Stream a) streamToList :: Stream a -> [a] streamToList (a `Cons` as) = a : streamToList as instance Show a => Show (Stream a) where show as = let asList = take 20 . streamToList $ as in "Stream " ++ show asList -- Exercise 4 ----------------------------------------- streamRepeat :: a -> Stream a streamRepeat a = Cons a $ streamRepeat a streamMap :: (a -> b) -> Stream a -> Stream b streamMap f (a `Cons` as) = f a `Cons` streamMap f as streamFromSeed :: (a -> a) -> a -> Stream a streamFromSeed g a = a `Cons` streamFromSeed g (g a) -- Exercise 5 ----------------------------------------- nats :: Stream Integer nats = streamFromSeed (+1) 0 interleaveStreams :: Stream a -> Stream a -> Stream a interleaveStreams (a `Cons` as) bs = a `Cons` interleaveStreams bs as ruler :: Stream Integer ruler = interleaveStreams zeros $ streamMap (+1) ruler where zeros = streamRepeat 0 -- Exercise 6 ----------------------------------------- x :: Stream Integer x = Cons 0 $ Cons 1 $ streamRepeat 0 instance Num (Stream Integer) where fromInteger n = Cons n $ streamRepeat 0 negate (a `Cons` as) = negate a `Cons` negate as (a `Cons` as) + (b `Cons` bs) = (a + b) `Cons` (as + bs) (a `Cons` as) * allB@(b `Cons` bs) = (a * b) `Cons` (streamMap (a*) bs + as * allB) instance Fractional (Stream Integer) where (a `Cons` as) / (b `Cons` bs) = q where q = (a `div` b) `Cons` streamMap (`div` b) (as - q * bs) fibs3 :: Stream Integer fibs3 = x / (1 - x - x * x) -- Exercise 7 ----------------------------------------- newtype Matrix = Matrix (Integer, Integer, Integer, Integer) instance Num Matrix where (Matrix (x1, x2, x3, x4)) * (Matrix (y1, y2, y3, y4)) = Matrix ( x1*y1 + x2*y3 , x1*y2 + x2*y4 , x3*y1 + x4*y3 , x3*y2 + x4*y4 ) fib4 :: Integer -> Integer fib4 0 = 0 fib4 n = let m = Matrix (1, 1, 1, 0) (Matrix (_, ans, _, _)) = m ^ n in ans
kemskems/cis194-spring13
src/HW06/HW06.hs
Haskell
bsd-3-clause
2,524
{-# language DataKinds #-} {-# language FlexibleInstances #-} import Control.Monad ( unless ) import qualified OpenCV as CV import OpenCV.TypeLevel import OpenCV.VideoIO.Types main :: IO () main = do cap <- CV.newVideoCapture -- Open the first available video capture device. Usually the -- webcam if run on a laptop. CV.exceptErrorIO $ CV.videoCaptureOpen cap $ CV.VideoDeviceSource 0 Nothing isOpened <- CV.videoCaptureIsOpened cap case isOpened of False -> putStrLn "Couldn't open video capture device" True -> do w <- CV.videoCaptureGetI cap VideoCapPropFrameWidth h <- CV.videoCaptureGetI cap VideoCapPropFrameHeight putStrLn $ "Video size: " ++ show w ++ " x " ++ show h CV.withWindow "video" $ \window -> do loop cap window where loop cap window = do _ok <- CV.videoCaptureGrab cap mbImg <- CV.videoCaptureRetrieve cap case mbImg of Just img -> do -- Assert that the retrieved frame is 2-dimensional. let img' :: CV.Mat ('S ['D, 'D]) 'D 'D img' = CV.exceptError $ CV.coerceMat img CV.imshow window img' key <- CV.waitKey 20 -- Loop unless the escape key is pressed. unless (key == 27) $ loop cap window -- Out of frames, stop looping. Nothing -> pure ()
lukexi/haskell-opencv
examples/src/videoio.hs
Haskell
bsd-3-clause
1,376
-- ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow, 2011 -- -- Generate code to initialise cost centres -- -- ----------------------------------------------------------------------------- module Eta.Profiling.ProfInit (profilingInitCode) where import Eta.Profiling.CostCentre -- import Eta.Main.DynFlags import Eta.Utils.Outputable -- import Eta.Utils.FastString import Eta.BasicTypes.Module -- ----------------------------------------------------------------------------- -- Initialising cost centres -- We must produce declarations for the cost-centres defined in this -- module; profilingInitCode :: Module -> CollectedCCs -> SDoc profilingInitCode _ (_, ___extern_CCs, _) = sdocWithDynFlags $ const empty -- if not (gopt Opt_SccProfilingOn dflags) -- then empty -- else vcat -- [ text "static void prof_init_" <> ppr this_mod -- <> text "(void) __attribute__((constructor));" -- , text "static void prof_init_" <> ppr this_mod <> text "(void)" -- , braces (vcat ( -- map emitRegisterCC local_CCs ++ -- map emitRegisterCCS singleton_CCSs -- )) -- ] -- where -- emitRegisterCC cc = -- ptext (sLit "extern CostCentre ") <> cc_lbl <> ptext (sLit "[];") $$ -- ptext (sLit "REGISTER_CC(") <> cc_lbl <> char ')' <> semi -- where cc_lbl = ppr (mkCCLabel cc) -- emitRegisterCCS ccs = -- ptext (sLit "extern CostCentreStack ") <> ccs_lbl <> ptext (sLit "[];") $$ -- ptext (sLit "REGISTER_CCS(") <> ccs_lbl <> char ')' <> semi -- where ccs_lbl = ppr (mkCCSLabel ccs)
rahulmutt/ghcvm
compiler/Eta/Profiling/ProfInit.hs
Haskell
bsd-3-clause
1,654
module Tests.TestSuiteTasty where import System.Exit (exitFailure) import System.Environment (lookupEnv) import qualified Tests.Parser as P import qualified Tests.TypeCheck as TC import qualified Tests.Simplify as S import qualified Tests.Disintegrate as D import qualified Tests.Sample as E import qualified Tests.RoundTrip as RT import Test.HUnit -- Tasty import Test.Tasty import Test.Tasty.HUnit.Adapter ( hUnitTestToTestTree ) import Test.Tasty.Runners.Html ( htmlRunner ) import Test.Tasty.Ingredients.Rerun ( rerunningTests ) import Test.Tasty.Ingredients.Basic ( consoleTestReporter, listingTests ) -- master test suite ignored :: Assertion ignored = putStrLn "Warning: maple tests will be ignored" simplifyTests :: Test -> Maybe String -> Test simplifyTests t env = case env of Just _ -> t Nothing -> test ignored allTests :: Maybe String -> TestTree allTests env = testGroup "hakaru" $ hUnitTestToTestTree $ test [ TestLabel "Parser" P.allTests , TestLabel "TypeCheck" TC.allTests , TestLabel "Simplify" (simplifyTests S.allTests env) , TestLabel "Disintegrate" D.allTests , TestLabel "Evaluate" E.allTests , TestLabel "RoundTrip" (simplifyTests RT.allTests env) ] hakaruRecipe = [ rerunningTests [ htmlRunner, consoleTestReporter ], listingTests ] main = (allTests <$> lookupEnv "LOCAL_MAPLE") >>= defaultMainWithIngredients hakaruRecipe
zachsully/hakaru
haskell/Tests/TestSuiteTasty.hs
Haskell
bsd-3-clause
1,465
{-| Instance status data collector. -} {- Copyright (C) 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.DataCollectors.InstStatus ( main , options , arguments , dcName , dcVersion , dcFormatVersion , dcCategory , dcKind , dcReport ) where import Control.Exception.Base import Data.List import Data.Maybe import qualified Data.Map as Map import Network.BSD (getHostName) import qualified Text.JSON as J import Ganeti.BasicTypes as BT import Ganeti.Confd.ClientFunctions import Ganeti.Common import qualified Ganeti.Constants as C import Ganeti.DataCollectors.CLI import Ganeti.DataCollectors.InstStatusTypes import Ganeti.DataCollectors.Types import Ganeti.Hypervisor.Xen import Ganeti.Hypervisor.Xen.Types import Ganeti.Logging import Ganeti.Objects import Ganeti.Path import Ganeti.Types import Ganeti.Utils -- | The name of this data collector. dcName :: String dcName = C.dataCollectorInstStatus -- | The version of this data collector. dcVersion :: DCVersion dcVersion = DCVerBuiltin -- | The version number for the data format of this data collector. dcFormatVersion :: Int dcFormatVersion = 1 -- | The category of this data collector. dcCategory :: Maybe DCCategory dcCategory = Just DCInstance -- | The kind of this data collector. dcKind :: DCKind dcKind = DCKStatus -- | The report of this data collector. dcReport :: IO DCReport dcReport = buildInstStatusReport Nothing Nothing -- * Command line options options :: IO [OptType] options = return [ oConfdAddr , oConfdPort ] -- | The list of arguments supported by the program. arguments :: [ArgCompletion] arguments = [] -- | Try to get the reason trail for an instance. In case it is not possible, -- log the failure and return an empty list instead. getReasonTrail :: String -> IO ReasonTrail getReasonTrail instanceName = do fileName <- getInstReasonFilename instanceName content <- try $ readFile fileName case content of Left e -> do logWarning $ "Unable to open the reason trail for instance " ++ instanceName ++ " expected at " ++ fileName ++ ": " ++ show (e :: IOException) return [] Right trailString -> case J.decode trailString of J.Ok t -> return t J.Error msg -> do logWarning $ "Unable to parse the reason trail: " ++ msg return [] -- | Determine the value of the status field for the report of one instance computeStatusField :: AdminState -> ActualState -> DCStatus computeStatusField AdminDown actualState = if actualState `notElem` [ActualShutdown, ActualDying] then DCStatus DCSCBad "The instance is not stopped as it should be" else DCStatus DCSCOk "" computeStatusField AdminUp ActualHung = DCStatus DCSCUnknown "Instance marked as running, but it appears to be hung" computeStatusField AdminUp actualState = if actualState `notElem` [ActualRunning, ActualBlocked] then DCStatus DCSCBad "The instance is not running as it should be" else DCStatus DCSCOk "" computeStatusField AdminOffline _ = -- FIXME: The "offline" status seems not to be used anywhere in the source -- code, but it is defined, so we have to consider it anyway here. DCStatus DCSCUnknown "The instance is marked as offline" -- Builds the status of an instance using runtime information about the Xen -- Domains, their uptime information and the static information provided by -- the ConfD server. buildStatus :: Map.Map String Domain -> Map.Map Int UptimeInfo -> RealInstanceData -> IO InstStatus buildStatus domains uptimes inst = do let name = realInstName inst currDomain = Map.lookup name domains idNum = fmap domId currDomain currUInfo = idNum >>= (`Map.lookup` uptimes) uptime = fmap uInfoUptime currUInfo adminState = realInstAdminState inst actualState = if adminState == AdminDown && isNothing currDomain then ActualShutdown else case currDomain of (Just dom@(Domain _ _ _ _ (Just isHung))) -> if isHung then ActualHung else domState dom _ -> ActualUnknown status = computeStatusField adminState actualState trail <- getReasonTrail name return $ InstStatus name (realInstUuid inst) adminState actualState uptime (realInstMtime inst) trail status -- | Compute the status code and message, given the current DRBD data -- The final state will have the code corresponding to the worst code of -- all the devices, and the error message given from the concatenation of the -- non-empty error messages. computeGlobalStatus :: [InstStatus] -> DCStatus computeGlobalStatus instStatusList = let dcstatuses = map iStatStatus instStatusList statuses = map (\s -> (dcStatusCode s, dcStatusMessage s)) dcstatuses (code, strList) = foldr mergeStatuses (DCSCOk, [""]) statuses in DCStatus code $ intercalate "\n" strList -- | Build the report of this data collector, containing all the information -- about the status of the instances. buildInstStatusReport :: Maybe String -> Maybe Int -> IO DCReport buildInstStatusReport srvAddr srvPort = do node <- getHostName answer <- runResultT $ getInstances node srvAddr srvPort inst <- exitIfBad "Can't get instance info from ConfD" answer d <- getInferredDomInfo let toReal (RealInstance i) = Just i toReal _ = Nothing reportData <- case d of BT.Ok domains -> do uptimes <- getUptimeInfo let primaryInst = mapMaybe toReal $ fst inst iStatus <- mapM (buildStatus domains uptimes) primaryInst let globalStatus = computeGlobalStatus iStatus return $ ReportData iStatus globalStatus BT.Bad m -> return . ReportData [] . DCStatus DCSCBad $ "Unable to receive the list of instances: " ++ m let jsonReport = J.showJSON reportData buildReport dcName dcVersion dcFormatVersion dcCategory dcKind jsonReport -- | Main function. main :: Options -> [String] -> IO () main opts _ = do report <- buildInstStatusReport (optConfdAddr opts) (optConfdPort opts) putStrLn $ J.encode report
apyrgio/ganeti
src/Ganeti/DataCollectors/InstStatus.hs
Haskell
bsd-2-clause
7,407
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="sq-AL"> <title>Active Scan Rules - Alpha | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/ascanrulesAlpha/src/main/javahelp/org/zaproxy/zap/extension/ascanrulesAlpha/resources/help_sq_AL/helpset_sq_AL.hs
Haskell
apache-2.0
986
-- This example demonstrates the peril of trying to benchmark a -- function that performs lazy I/O. import Criterion.Main main :: IO () main = defaultMain [ -- By using whnfIO, when the benchmark loop goes through an -- iteration, we inspect only the first constructor returned after -- the file is opened. Since the entire file must be read in -- order for it to be closed, this causes file handles to leak, -- and our benchmark will probably crash while running with an -- error like this: -- -- openFile: resource exhausted (Too many open files) bench "whnfIO readFile" $ whnfIO (readFile "BadReadFile.hs") ]
paulolieuthier/criterion
examples/BadReadFile.hs
Haskell
bsd-2-clause
653
module SchemeParse ( parseAtom {-, parseString-} , parseNumber , parseExpr , readExpr) where import Control.Monad import Text.ParserCombinators.Parsec hiding (spaces) import SchemeDef {-spaces :: Parser () spaces = skipMany1 space-} symbol :: Parser Char symbol = oneOf "!$%&|*+-/:<=>?@^_~" parseAtom :: Parser LispVal parseAtom = do first <- letter <|> symbol <|> char '#' rest <- many (letter <|> digit <|> symbol) let atom = first : rest return $ case atom of "#t" -> Bool True "#f" -> Bool False _ -> Atom atom {-parseString :: Parser LispVal parseString = do char '"' x <- many chars char '"' return $ String x where chars = escapedChar <|> noneOf "\"" escapedChar = char "\\" >> choice -} parseNumber :: Parser LispVal parseNumber = liftM (Number . read) $ many1 digit parseExpr :: Parser LispVal parseExpr = parseAtom {-<|> parseString-} <|> parseNumber readExpr :: String -> LispVal readExpr input = case parse parseExpr "lisp" input of Left err -> String $ "Parse error: " ++ show err Right val -> val
phlip9/scheme-interpreter
SchemeParse.hs
Haskell
mit
1,242
{- Counting Sundays Problem 19 You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? -} -- Some custom data types to help define the problem type Year = Int type Day = Int data Month = January | February | March | April | May | June | July | August | September | October | November | December deriving (Enum, Eq, Ord, Show) data Date = Date Year Month Day deriving (Eq, Ord, Show) data WeekDay = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Enum, Eq, Show) -- Quick check if a year is a leap year isLeapYear :: Year -> Bool isLeapYear y = y `mod` 400 == 0 || (y `mod` 4 == 0 && y `mod` 100 /= 0) -- Determine the next day of a given date next :: Date -> Date next (Date y m d) | m == December && d == 31 = Date (y+1) January 1 | d == 31 = Date y (succ m) 1 | m == February && d == 28 = if isLeapYear y then Date y February 29 else Date y March 1 | m == February && d == 29 = Date y March 1 | m `elem` [April, June, September, November] && d == 30 = Date y (succ m) 1 | otherwise = Date y m (d+1) -- The first known Monday given in the problem description initialMonday :: Date initialMonday = Date 1900 January 1 -- An infinite sequence of dates starting from initialMonday calendar :: [Date] calendar = iterate next initialMonday -- An infinite cycle of the days of the week weekdays :: [WeekDay] weekdays = cycle [Monday .. Sunday] -- Pairing the day of the week with an actual date beginning on a known Monday (see above) days :: [(WeekDay, Date)] days = zip weekdays calendar -- Filter the given period period :: [(WeekDay, Date)] period = dropWhile (\(w,d) -> d < (Date 1901 January 1)) (takeWhile (\(w,d) -> d <= (Date 2000 December 31)) days) -- Filter only the sundays that happened in the first of the month sundayFirsts :: [(WeekDay, Date)] sundayFirsts = filter (\(w,Date y m d) -> w == Sunday && d == 1) period -- Count them euler19 :: Int euler19 = length sundayFirsts
feliposz/project-euler-solutions
haskell/euler19.hs
Haskell
mit
2,405
module Main where {- pwr :: Integral a => a -> a -> a pwr b e = pwr' b b e pwr' :: Integral a => a -> a -> a -> a pwr' acc b 1 = acc pwr' acc b e = pwr' (acc*b) b (e-1) x % y | x < y = x | x == y = 0 | otherwise = (x - y) % y -} result :: (Enum a, RealFloat a) => a result = head [ a * b * sqrt (a * a + b * b) | a <- [1..998], b <- [1..998], a < b, a + b + sqrt (a * a + b * b) == 1000] main :: IO () main = print $ floor result
ron-wolf/haskeuler
src/09.hs
Haskell
mit
450
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.List.NonEmpty import Language.SAL main :: IO () main = putStrLn (renderSAL ctx) ctx :: Context ctx = Context "salctx" Nothing body where body = ContextBody (ModuleDecl salmod :| []) salmod :: ModuleDeclaration salmod = let ins = InputDecl $ VarDecls (VarDecl "x" (TyBasic INTEGER) :| []) outs = OutputDecl $ VarDecls (VarDecl "y" (TyBasic INTEGER) :| []) expr = InfixApp (NameExpr "x") "+" (NumLit 1) d1 = DefSimple (SimpleDefinition (LhsCurrent "y" []) (RhsExpr expr)) defs = DefDecl $ Definitions (d1 :| []) in ModuleDeclaration "salmod" Nothing $ BaseModule [ ins , outs , defs ]
GaloisInc/language-sal
examples/salmod.hs
Haskell
mit
769
module KMC.Syntax.ParserCombinators ( repetitions , delims , parens , brackets , braces , suppressDelims , parseTable , nonGroupParens , genParseTable ) where import Control.Applicative hiding (many) import Text.ParserCombinators.Parsec (choice, count, many, many1, optionMaybe, string, try) import KMC.Syntax.ParserTypes import Prelude -------------------------------------------------------------------------------- -- Various useful parser combinators. -------------------------------------------------------------------------------- -- | Automatically build a parse table from a data type that implements the Show -- type class. Takes a function that specifies how the parsers -- should behave as a function of their "Show value", a function to transform -- the parsed constructors, and a list of the constructors that should be -- made parsable by what "show" returns. genParseTable :: (Show a) => (String -> Parser String) -> (a -> b) -> [a] -> Parser b genParseTable p f = parseTable p f . map (\v -> (show v, v)) -- | Build a parser for a given table. The result of each parser -- is the value created by "valMod" applied to the right value in the tuple. parseTable :: (s -> Parser s) -> (a -> b) -> [(s, a)] -> Parser b parseTable parserMod valMod = choice . map (\(s,v) -> parserMod s >> return (valMod v)) -- | Given an ordering relation and an integer n, repeat the given parser either -- (== n) times, (<= n) times, or (>= n) times. Negative n are clamped to 0. repetitions :: Ordering -> Int -> Parser a -> Parser [a] repetitions o n = let n' = if n < 0 then 0 else n in case o of EQ -> count n' LT -> maximumRepetitions n' GT -> minimumRepetitions n' -- | Repeat parser minimum n times and collect the results. minimumRepetitions :: Int -> Parser a -> Parser [a] minimumRepetitions 0 p = many p minimumRepetitions 1 p = many1 p minimumRepetitions n p = do xs <- count n p xs' <- many p return (xs ++ xs') -- | Repeat parser maximum n times and collect the results. maximumRepetitions :: Int -> Parser a -> Parser [a] maximumRepetitions 0 _ = return [] maximumRepetitions 1 p = p >>= return . (:[]) maximumRepetitions n p = do x <- p mxs <- optionMaybe (maximumRepetitions (n - 1) p) case mxs of Nothing -> return [x] Just xs -> return (x:xs) -- | Build a parser that parses the given left- and right-delimiters around -- the provided parser p. delims :: String -> String -> Parser a -> Parser a delims left right p = try (string left) *> p <* (string right) -- | Put parentheses around parser parens :: Parser a -> Parser a parens = delims "(" ")" nonGroupParens :: Parser a -> Parser a nonGroupParens = delims "(?:" ")" -- | Put brackets around parser brackets :: Parser a -> Parser a brackets = delims "[" "]" -- | Put braces around parser braces :: Parser a -> Parser a braces = delims "{" "}" -- | Put "suppression delimiters" around parser suppressDelims :: Parser a -> Parser a suppressDelims = delims "$(" ")$"
diku-kmc/regexps-syntax
KMC/Syntax/ParserCombinators.hs
Haskell
mit
3,169
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-} module Y2018.M04.D09.Exercise where import Data.Aeson import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.SqlQQ {-- Okay, fam. We're going to wrap up our preparation for the data load by parsing tags into a tags lookup table. --} -- below imports available via 1HaskellADay git repository import Data.LookupTable import Store.SQL.Connection import Store.SQL.Util.Indexed import Store.SQL.Util.LookupTable tags :: FilePath tags = "Y2018/M04/D09/tags.json" data Tag = SomeStructureYouDeclare readTags :: FilePath -> IO [Tag] readTags json = undefined -- and then, into the database we go: tagStmt :: Query tagStmt = [sql|INSERT INTO tag VALUES (?,?)|] insertTags :: Connection -> LookupTable -> IO () insertTags conn = undefined
geophf/1HaskellADay
exercises/HAD/Y2018/M04/D09/Exercise.hs
Haskell
mit
804
{-# LANGUAGE FlexibleContexts , UndecidableSuperClasses #-} module MiniSequel.Mapper where import MiniSequel import MiniSequel.Expression ((=.), SequelExpression) import Database.HDBC import Data.Data import Data.Char (toUpper, toLower, isUpper) import Data.Maybe (fromJust) import qualified GHC.Generics as G import qualified Generics.SOP as SOP sequelValues :: (SOP.Generic a, SOP.All2 SequelValue (SOP.Code a)) => a -> [SequelExpression] sequelValues a = SOP.hcollapse (SOP.hcmap (Proxy :: Proxy SequelValue) (\ (SOP.I x) -> SOP.K (v x)) (SOP.from a)) class SequelMapper a where fromSqlRow :: [SqlValue] -> a create :: a -> SequelQuery createMulti :: [a] -> SequelQuery createMulti a = query where fields = fromJust . _colums . create . head $ a vals = map (head . fromJust . _values . create) a query = makeQuery tableName $ do insert fields values vals tableName = _from . create . head $ a snakeCase :: String -> String snakeCase = map toLower . concat . underscores . splitR isUpper where underscores :: [String] -> [String] underscores [] = [] underscores (h:t) = h : map ('_':) t splitR :: (Char -> Bool) -> String -> [String] splitR _ [] = [] splitR p s = let go :: Char -> String -> [String] go m s' = case break p s' of (b', []) -> [ m:b' ] (b', x:xs) -> ( m:b' ) : go x xs in case break p s of (b, []) -> [ b ] ([], h:t) -> go h t (b, h:t) -> b : go h t class (G.Generic a, Data a, SOP.Generic a, SOP.All2 SequelValue (SOP.Code a)) => SequelMapperUpdateable a where store :: a -> SequelQuery store a = query where key:fields = map (s.snakeCase) $ constrFields . toConstr $ a id : vals = sequelValues a query = undefined -- update set_fields $ -- where' (key =. id) $ -- from table_name table_name = ts $ snakeCase $ show $ toConstr a set_fields = zipWith (=.) fields vals
TachoMex/MiniSequel
src/MiniSequel/Mapper.hs
Haskell
mit
2,283
{-| Module: Y2015.D06 Description: Advent of Code Day 06 Solutions. License: MIT Maintainer: @tylerjl Solutions to the day 06 set of problems for <adventofcode.com>. -} module Y2015.D06 ( testA , testB , Instruction(..) , Range(..) , parseInstructions , configureGridA , configureGridB , lightSimulation ) where import Control.Applicative ((<|>)) import Data.List (foldl') import qualified Data.Array.Repa as R import Data.Array.Repa (Z(..), (:.)(..)) import qualified Text.Parsec as P import Text.Parsec.Char (char, endOfLine) import Text.Parsec.String (Parser) import Data.Vector.Unboxed.Base (Unbox) import Y2015.Util (regularParse, intParser) type Point = (Int, Int) -- |Represents a two-dimensional range of lights. data Range = Range Point Point deriving (Eq, Show) -- |Type of light grid instruction. data Instruction = On Range | Off Range | Toggle Range deriving (Show) size :: Int size = 1000 initialGrid :: R.Array R.U R.DIM2 Int initialGrid = R.fromListUnboxed (Z :. size :. size :: R.DIM2) (replicate (size * size) 0) instructionsParser :: Parser [Instruction] instructionsParser = P.many (instruction <* P.optional endOfLine) instruction :: Parser Instruction instruction = On <$> directive "turn on" <|> Off <$> directive "turn off" <|> Toggle <$> directive "toggle" directive :: String -> Parser Range directive s = P.skipMany1 (P.try (P.string s *> P.skipMany1 P.space)) *> range range :: Parser Range range = Range <$> point <* P.string " through " <*> point point :: Parser Point point = (,) <$> intParser <* char ',' <*> intParser -- |Folding function to aggregate computation for 'Instruction's per part -- |A spec. configureGridA :: R.Array R.U R.DIM2 Int -- ^ Light grid. -> Instruction -- ^ Operation 'Instruction'. -> R.Array R.U R.DIM2 Int -- ^ Resultant light grid. configureGridA a (On r) = switch a (const 1) r configureGridA a (Off r) = switch a (const 0) r configureGridA a (Toggle r) = switch a toggle r -- |Folding function to aggregate computation for 'Instruction's per part -- |B spec. configureGridB :: R.Array R.U R.DIM2 Int -- ^ Light grid. -> Instruction -- ^ Operation 'Instruction'. -> R.Array R.U R.DIM2 Int -- ^ Resultant light grid. configureGridB a (On r) = switch a (+ 1) r configureGridB a (Off r) = switch a dim r configureGridB a (Toggle r) = switch a (+ 2) r toggle :: Int -> Int toggle 1 = 0 toggle _ = 1 dim :: Int -> Int dim = max 0 . subtract 1 switch :: (R.Source r a, Unbox a) => R.Array r R.DIM2 a -> (a -> a) -> Range -> R.Array R.U R.DIM2 a switch a f r = R.computeS $ R.traverse a id (set f r) -- This is pretty confusing: -- Custom mapping function (set the lights) -- -> Range to apply the function upon -- -> Function to retrieve original elements from -- -> Original array constructor -- -> New (or unchanged) value set :: (a -> a) -> Range -> (R.DIM2 -> a) -> R.DIM2 -> a set f (Range (x', y') (x'', y'')) g (Z :. x :. y) | withinX && withinY = f orig | otherwise = orig where withinX = x >= x' && x <= x'' withinY = y >= y' && y <= y'' orig = g (Z :. x :. y) -- |Execute 'Instruction' and return number of lit lights per part A spec. testA :: Instruction -- ^ Given 'Instruction'. -> Int -- ^ Number of lit lights. testA = R.foldAllS (+) 0 . configureGridA initialGrid -- |Execute 'Instruction' and return number of lit lights per part B spec. testB :: Instruction -- ^ Given 'Instruction' -> Int -- ^ Number of lit lights. testB = R.foldAllS (+) 0 . configureGridB initialGrid -- |Parses a string into a list of 'Instruction's. parseInstructions :: String -- ^ Input string to parse. -> Either P.ParseError [Instruction] -- ^ Either an error or parsed structure. parseInstructions = regularParse instructionsParser -- |Run a light simulation lightSimulation :: (Monad m, Foldable t) => (R.Array R.U R.DIM2 Int -> a -> R.Array R.U R.DIM2 Int) -- ^ REPA Light grid -> t a -- ^ 'Instruction's -> m Int -- ^ Lit lights lightSimulation f = R.sumAllP . foldl' f initialGrid
tylerjl/adventofcode
src/Y2015/D06.hs
Haskell
mit
4,087
-- | In this module, we model an /elementary topos/ with Haskell types -- (see <https://en.wikipedia.org/wiki/Topos>). -- To be more precise, we model the "smallest elementary topos with a -- natural number object". Without such a natural number object, -- the resulting topos would be boring, consisting merely of the finite -- sets. By adding one infinite object, namely the natural numbers, we -- get access to all sorts of interesting objects - rational numbers, -- (constructible) real numbers, differentiable functions, a big chunk of -- all those objects that are studied in mathematics. module Protop.Core ( module Protop.Core.Compositions , module Protop.Core.Equalizers , module Protop.Core.Exponentials , module Protop.Core.Identities , module Protop.Core.Monos , module Protop.Core.Morphisms , module Protop.Core.Natural , module Protop.Core.Objects , module Protop.Core.Omega , module Protop.Core.Products , module Protop.Core.Proofs , module Protop.Core.Reflexivities , module Protop.Core.Setoids , module Protop.Core.Symmetries , module Protop.Core.Transitivities , module Protop.Core.Terminal ) where import Protop.Core.Compositions import Protop.Core.Equalizers import Protop.Core.Exponentials import Protop.Core.Identities import Protop.Core.Monos import Protop.Core.Morphisms import Protop.Core.Natural import Protop.Core.Objects import Protop.Core.Omega import Protop.Core.Products import Protop.Core.Proofs import Protop.Core.Reflexivities import Protop.Core.Setoids import Protop.Core.Symmetries import Protop.Core.Transitivities import Protop.Core.Terminal
brunjlar/protop
src/Protop/Core.hs
Haskell
mit
1,649
module Solidran.Hamm.DetailSpec (spec) where import Test.Hspec import Solidran.Hamm.Detail spec :: Spec spec = do describe "Solidran.Hamm.Detail" $ do describe "hammingDist" $ do it "should work in the given sample" $ do hammingDist "GAGCCTACTAACGGGAT" "CATCGTAATGACGGCCT" `shouldBe` 7 it "should work on empty strings" $ do hammingDist "" "" `shouldBe` 0 it "should work with any character" $ do hammingDist "333yg!.u=)8GYGU3¥~" "/^ayg?.u=)8gYGU3¥~" `shouldBe` 5 hammingDist "%&\"lqyYYUIhCDX%°" "%&'lqyYYUIhCDX%°" `shouldBe` 1
Jefffrey/Solidran
test/Solidran/Hamm/DetailSpec.hs
Haskell
mit
726
module System.Monitoring.Nrpe ( checkNRPE , liftNRPE , IONRPE , NRPE -- re-exports lower-level modules , module System.Monitoring.Nrpe.Protocol , module System.Monitoring.Nrpe.Nagios ) where import Data.ByteString (ByteString) import Control.Applicative ((<$>)) import System.Monitoring.Nrpe.Protocol (Service (..), Result, check) import System.Monitoring.Nrpe.Nagios (PluginOutput, parseOutput) type NRPE a = Result (Either String a) type IONRPE a = IO (NRPE a) -- Lifts a pure function into an IONRPE. liftNRPE :: (a -> b) -> IONRPE a -> IONRPE b liftNRPE = fmap . fmap . fmap -- Executes and parse an NRPE check result. checkNRPE :: Service -> ByteString -> IONRPE PluginOutput checkNRPE s x = fmap parseOutput <$> check s x
lucasdicioccio/nrpe
src/System/Monitoring/Nrpe.hs
Haskell
apache-2.0
752
{-# LANGUAGE ViewPatterns #-} module Language.K3.Codegen.CPP.Materialization.Common where import Control.Arrow import Data.Hashable import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Core.Expression import Language.K3.Core.Type rollLambdaChain :: K3 Expression -> ([(Identifier, K3 Expression)], K3 Expression) rollLambdaChain e@(tag &&& children -> (ELambda i, [f])) = let (ies, b) = rollLambdaChain f in ((i, e):ies, b) rollLambdaChain e = ([], e) rollAppChain :: K3 Expression -> (K3 Expression, [K3 Expression]) rollAppChain e@(tag &&& children -> (EOperate OApp, [f, x])) = let (f', xs) = rollAppChain f in (f', xs ++ [e]) rollAppChain e = (e, []) anon :: Int anon = hashJunctureName "!" anonS :: Identifier anonS = "!" hashJunctureName :: Identifier -> Int hashJunctureName = hash isNonScalarType :: K3 Type -> Bool isNonScalarType t = case t of (tag -> TString) -> True (tag &&& children -> (TTuple, cs)) -> any isNonScalarType cs (tag &&& children -> (TRecord _, cs)) -> any isNonScalarType cs (tag -> TCollection) -> True _ -> False
DaMSL/K3
src/Language/K3/Codegen/CPP/Materialization/Common.hs
Haskell
apache-2.0
1,095
{- Copyright 2015 Tristan Aubrey-Jones Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-| Copyright : (c) Tristan Aubrey-Jones, 2015 License : Apache-2 Maintainer : developer@flocc.net Stability : experimental For more information please see <http://www.flocc.net/> -} module Compiler.Back.TypeNames where import Compiler.Types2.TypeInfo (typeModeNames) import Compiler.Back.Graph import Compiler.Back.GenDecls import Data.Maybe (fromMaybe) import Data.List (stripPrefix) nameTy :: String -> LfTy nameTy n = (LfTy n []) namedTy :: String -> [Ty] -> LfTy namedTy n l = (LfTy n l) eqTys :: LfTy -> LfTy eqTys tin@(LfTy name l) = case (name, map (mapTree eqTys) l) of -- vectors ("LVec", [et]) -> namedTy "Vec" [et] -- maps ("VecMap", [Tup [kt, vt],_,_,_]) -> namedTy "Map" [kt, vt] ("LMap", [_,kt,vt,_]) -> namedTy "Map" [kt,vt] ("DMap", [_,kt,vt,_,_,_,_]) -> namedTy "Map" [kt, vt] -- Get rid of pointers ("Ptr", [(Lf t)]) -> t ("SPtr", [(Lf t)]) -> t -- everything else the same other -> tin -- |Returns true for all types that should be copied by -- |value rather than by pointer. copyByVal :: Ty -> Bool copyByVal ty = case ty of (Lf (LfTy "SPtr" [Lf (LfTy "VecMap" _)])) -> True (Lf (LfTy "DMap" l)) -> True _ -> False -- |Returns the value to use when creating a fresh instance of this -- |type. defaultInitializer :: Monad m => Ty -> Id -> GenM1 m Id defaultInitializer (Lf lfTy) tyId = case lfTy of (LfTy "SPtr" [Lf (LfTy "VecMap" _)]) -> return $ "new " ++ (init $ fromMaybe tyId $ stripPrefix "boost::shared_ptr<" tyId) (LfTy "DMap" l) -> return $ "new " ++ (init $ fromMaybe tyId $ stripPrefix "boost::shared_ptr<" tyId) other -> return "" defaultInitializer other tyId = return "" -- |getTypeName ty. Returns the C++ type -- |to use for ty, or Nothing if this type should not -- |be stored as a data structure. getTypeName :: Monad m => LfTy -> [Maybe Id] -> GenM1 m (Maybe Id) getTypeName lfTy children = case (lfTy, children) of -- mirrored type are themselves --(LfTy "Mirr" [ty], [tid]) -> return $ Just $ fromMaybe (error msg) tid -- distributed vector (LfTy "LVec" [et], [tid]) -> return $ Just $ "flocc::vec<" ++ (fromMaybe (error msg) tid) ++ " >" -- distributed maps {-(LfTy "DistMap" [kt, vt, kf, pf, nl], [ktid, vtid, _, _, _]) -> return $ Just $ "std::map<" ++ (fromMaybe (error msg) ktid) ++ ", " ++ (fromMaybe (error msg) vtid) ++ " >" (LfTy "DistHashMap" [kt, v2, kf, pf, nl], [ktid, vtid, _, _, _]) -> return $ Just $ "dense_hash_map<" ++ (fromMaybe (error msg) ktid) ++ ", " ++ (fromMaybe (error msg) vtid) ++ ", " ++ "hash<" ++ (fromMaybe (error msg) ktid) ++ " >, " ++ "eq" ++ (fromMaybe (error msg) ktid) ++ " >"-} (LfTy "VecMap" [kvt, pkt, Lf (LfTy "Null" []), projt], [kvtid, pktid, sktid, projtid]) -> -- vec map with null secondary key return $ Just $ "flocc::vecmap<" ++ (fromMaybe (error $ msg ++ "/elT/"++ (show kvt)) kvtid) ++ ", " ++ (fromMaybe (error $ msg ++ "/priKeyT/"++ (show pkt)) pktid) ++ ", " ++ "char, " ++ (fromMaybe (error $ msg ++ "/projFun/"++ (show projt)) projtid) ++ " >" (LfTy "VecMap" [kvt, pkt, skt, projt], [kvtid, pktid, sktid, projtid]) -> -- any other vecmap return $ Just $ "flocc::vecmap<" ++ (fromMaybe (error $ msg ++ "/elT/"++ (show kvt)) kvtid) ++ ", " ++ (fromMaybe (error $ msg ++ "/priKeyT/"++ (show pkt)) pktid) ++ ", " ++ (fromMaybe (error $ msg ++ "/secKeyT/"++ (show skt)) sktid) ++ ", " ++ (fromMaybe (error $ msg ++ "/projFun/"++ (show projt)) projtid) ++ " >" (LfTy "LMap" [(Lf (LfTy mode [])), kt, v2, sf], [_, ktid, vtid, _]) -> case mode of -- hash map "Hsh" -> return $ Just $ "google::dense_hash_map<" ++ (fromMaybe (error msg) ktid) ++ ", " ++ (fromMaybe "char" vtid) ++ ", " ++ "flocc::hasher<" ++ (fromMaybe (error msg) ktid) ++ " >, " ++ "flocc::eq<" ++ (fromMaybe (error msg) ktid) ++ " > >" (LfTy "MultiMap" [mmKt, kvt], [mmKtid, kvtid]) -> -- a std::multimap return $ Just $ "std::multimap<" ++ (fromMaybe (error msg) mmKtid) ++ ", " ++ (fromMaybe (error msg) kvtid) ++ " >" -- redistributer (LfTy "Reparter" [elT, outT], [elTid, outTid]) -> return $ Just $ "flocc::reparter<" ++ (fromMaybe (error msg) elTid) ++ ", " ++ (fromMaybe (error msg) outTid) ++ " >" -- iterators (LfTy "Iter" [colTy], [colTId]) -> return $ Just $ (fromMaybe (error msg) colTId) ++ "::iterator" (LfTy "ConstIter" [colTy], [colTId]) -> return $ Just $ (fromMaybe (error msg) colTId) ++ "::iterator" --"::const_iterator" (LfTy "IdxIter" [colTy], [colTId]) -> return $ Just $ (fromMaybe (error msg) colTId) ++ "::idx_iterator" -- pointers (LfTy "Ptr" [vTy], [vTId]) -> return $ Just $ (fromMaybe (error msg) vTId) ++ "*" (LfTy "SPtr" [vTy], [vTId]) -> return $ Just $ "boost::shared_ptr<" ++ (fromMaybe (error msg) vTId) ++ " >" -- distributed array {-(LfTy "DistArr" [idxTy, valty, layoutF, invLayoutF, partF, dims, mirrDims], [idxTid, valTid, _, _, _, _, _]) -> do -- get number of int's in flattened idxTy let flatIdxTy = flattenTree idxTy -- return template class return $ Just $ "SubArray<" ++ (fromMaybe (error msg) valTid) ++ ", " ++ (show $ length flatIdxTy) ++ ">" -- distributed array (LfTy "DistArrRoot" [idxTy, valty, layoutF, invLayoutF, partF, dims, mirrDims], [idxTid, valTid, _, _, _, _, _]) -> do -- get number of int's in flattened idxTy let flatIdxTy = flattenTree idxTy -- return template class return $ Just $ "RootArray<" ++ (fromMaybe (error msg) valTid) ++ ", " ++ (show $ length flatIdxTy) ++ ">" (LfTy "DistArr1D" [valTy, kf, vf, nl], [tid, _, _, _]) -> return $ Just $ "std::vector<" ++ (fromMaybe (error msg) tid) ++ " >"-} -- mpi datatype (LfTy "MPIType" [], _) -> return $ Just "MPI::Datatype" -- used for distribution meta-data, not actual data types {-(LfTy "NullFun" [], _) -> return Nothing (LfTy "NullDim" [], _) -> return Nothing (LfTy "MirrDims" [], _) -> return Nothing (LfTy "DimDists" _, _) -> return Nothing (LfTy "Fringe" [], _) -> return Nothing (LfTy "Mirr" [], _) -> return Nothing (LfTy ('P':'a':'r':'t':_) [], _) -> return Nothing -- from DistHistDemo (LfTy "AllNodes" [], _) -> return Nothing (LfTy "snd" [], _) -> return Nothing (LfTy "fst" [], _) -> return Nothing (LfTy "modN" l, _) -> return Nothing (LfTy "Snd" [], _) -> return Nothing (LfTy "Fst" [], _) -> return Nothing (LfTy "ModN" l, _) -> return Nothing-} -- functions (TODO create fun_class?) (FunTy graph, _) -> return Nothing -- type modes (LfTy name [], _) -> case elem name typeModeNames of True -> return Nothing False -> error $ "TypeNames:getTypeName: can't return type name for " ++ (show lfTy) _ -> error $ "TypeNames:getTypeName: can't return type name for " ++ (show lfTy) where msg = "getTypeName:couldn't generate type name for " ++ (show lfTy) -- TODO ADD CONSTRUCTORS TO SUBARRAY, SO WE CAN ALWAYS CREATE SUBARRAYS, AND THEY CAN -- CREATE NEW UNDERLYING ROOT ARRAYS, IF NONE IS GIVEN getMPITypeName :: Monad m => Ty -> Maybe Id -> GenM1 m (Maybe (Id, Code)) getMPITypeName ty idv = case ty of -- scalars Lf lty -> case lty of -- scalar types _ | ty == intTy -> return $ Just ("MPI::INT", "") _ | ty == uintTy -> return $ Just ("MPI::UNSIGNED", "") _ | ty == floatTy -> return $ Just ("MPI::DOUBLE", "") _ | ty == boolTy -> return $ Just ("MPI::C_BOOL", "") _ | ty == nullTy -> return $ Nothing -- structs (not needed as packed) -- TODO just use packed and size of struct -- arrays -- TODO generate data type for this collection -- other collections -- TODO just use n copies of struct mpi data type other -> error $ "cant generate mpi type for " ++ (show ty)
flocc-net/flocc
v0.1/Compiler/Back/TypeNames.hs
Haskell
apache-2.0
8,904
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QGraphicsItemGroup_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:25 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QGraphicsItemGroup_h where import Foreign.C.Types import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Enums.Gui.QGraphicsItem import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QGraphicsItemGroup ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QGraphicsItemGroup_unSetUserMethod" qtc_QGraphicsItemGroup_unSetUserMethod :: Ptr (TQGraphicsItemGroup a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QGraphicsItemGroupSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QGraphicsItemGroup ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QGraphicsItemGroupSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QGraphicsItemGroup ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QGraphicsItemGroupSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QGraphicsItemGroup_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QGraphicsItemGroup setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QGraphicsItemGroup_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QGraphicsItemGroup_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setUserMethod" qtc_QGraphicsItemGroup_setUserMethod :: Ptr (TQGraphicsItemGroup a) -> CInt -> Ptr (Ptr (TQGraphicsItemGroup x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsItemGroup :: (Ptr (TQGraphicsItemGroup x0) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QGraphicsItemGroup_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QGraphicsItemGroup setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QGraphicsItemGroup_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QGraphicsItemGroup_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QGraphicsItemGroup setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QGraphicsItemGroup_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QGraphicsItemGroup_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setUserMethodVariant" qtc_QGraphicsItemGroup_setUserMethodVariant :: Ptr (TQGraphicsItemGroup a) -> CInt -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsItemGroup :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QGraphicsItemGroup_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QGraphicsItemGroup setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QGraphicsItemGroup_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QGraphicsItemGroup_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QGraphicsItemGroup ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QGraphicsItemGroup_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QGraphicsItemGroup_unSetHandler" qtc_QGraphicsItemGroup_unSetHandler :: Ptr (TQGraphicsItemGroup a) -> CWString -> IO (CBool) instance QunSetHandler (QGraphicsItemGroupSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QGraphicsItemGroup_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> IO (QRectF t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQRectF t0)) setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler1" qtc_QGraphicsItemGroup_setHandler1 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQRectF t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup1 :: (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQRectF t0))) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQRectF t0)))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> IO (QRectF t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQRectF t0)) setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqqboundingRect_h (QGraphicsItemGroup ()) (()) where qqboundingRect_h x0 () = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_boundingRect cobj_x0 foreign import ccall "qtc_QGraphicsItemGroup_boundingRect" qtc_QGraphicsItemGroup_boundingRect :: Ptr (TQGraphicsItemGroup a) -> IO (Ptr (TQRectF ())) instance QqqboundingRect_h (QGraphicsItemGroupSc a) (()) where qqboundingRect_h x0 () = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_boundingRect cobj_x0 instance QqboundingRect_h (QGraphicsItemGroup ()) (()) where qboundingRect_h x0 () = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h foreign import ccall "qtc_QGraphicsItemGroup_boundingRect_qth" qtc_QGraphicsItemGroup_boundingRect_qth :: Ptr (TQGraphicsItemGroup a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO () instance QqboundingRect_h (QGraphicsItemGroupSc a) (()) where qboundingRect_h x0 () = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler2" qtc_QGraphicsItemGroup_setHandler2 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup2 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QObject t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- qObjectFromPtr x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler3" qtc_QGraphicsItemGroup_setHandler3 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup3 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QObject t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- qObjectFromPtr x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QisObscuredBy_h (QGraphicsItemGroup ()) ((QGraphicsItem t1)) where isObscuredBy_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_isObscuredBy cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_isObscuredBy" qtc_QGraphicsItemGroup_isObscuredBy :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsItem t1) -> IO CBool instance QisObscuredBy_h (QGraphicsItemGroupSc a) ((QGraphicsItem t1)) where isObscuredBy_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_isObscuredBy cobj_x0 cobj_x1 instance QisObscuredBy_h (QGraphicsItemGroup ()) ((QGraphicsTextItem t1)) where isObscuredBy_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_isObscuredBy_graphicstextitem cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_isObscuredBy_graphicstextitem" qtc_QGraphicsItemGroup_isObscuredBy_graphicstextitem :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool instance QisObscuredBy_h (QGraphicsItemGroupSc a) ((QGraphicsTextItem t1)) where isObscuredBy_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_isObscuredBy_graphicstextitem cobj_x0 cobj_x1 instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> IO (QPainterPath t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQPainterPath t0)) setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler4" qtc_QGraphicsItemGroup_setHandler4 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQPainterPath t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup4 :: (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQPainterPath t0))) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQPainterPath t0)))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> IO (QPainterPath t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (Ptr (TQPainterPath t0)) setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QopaqueArea_h (QGraphicsItemGroup ()) (()) where opaqueArea_h x0 () = withQPainterPathResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_opaqueArea cobj_x0 foreign import ccall "qtc_QGraphicsItemGroup_opaqueArea" qtc_QGraphicsItemGroup_opaqueArea :: Ptr (TQGraphicsItemGroup a) -> IO (Ptr (TQPainterPath ())) instance QopaqueArea_h (QGraphicsItemGroupSc a) (()) where opaqueArea_h x0 () = withQPainterPathResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_opaqueArea cobj_x0 instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO () setHandlerWrapper x0 x1 x2 x3 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 x2obj <- objectFromPtr_nf x2 x3obj <- qObjectFromPtr x3 if (objectIsNull x0obj) then return () else _handler x0obj x1obj x2obj x3obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler5" qtc_QGraphicsItemGroup_setHandler5 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup5 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QPainter t1 -> QStyleOption t2 -> QObject t3 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQObject t3) -> IO () setHandlerWrapper x0 x1 x2 x3 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 x2obj <- objectFromPtr_nf x2 x3obj <- qObjectFromPtr x3 if (objectIsNull x0obj) then return () else _handler x0obj x1obj x2obj x3obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qpaint_h (QGraphicsItemGroup ()) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where paint_h x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsItemGroup_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QGraphicsItemGroup_paint1" qtc_QGraphicsItemGroup_paint1 :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionGraphicsItem t2) -> Ptr (TQWidget t3) -> IO () instance Qpaint_h (QGraphicsItemGroupSc a) ((QPainter t1, QStyleOptionGraphicsItem t2, QWidget t3)) where paint_h x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QGraphicsItemGroup_paint1 cobj_x0 cobj_x1 cobj_x2 cobj_x3 instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler6" qtc_QGraphicsItemGroup_setHandler6 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup6 :: (Ptr (TQGraphicsItemGroup x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qqtype_h (QGraphicsItemGroup ()) (()) where qtype_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_type cobj_x0 foreign import ccall "qtc_QGraphicsItemGroup_type" qtc_QGraphicsItemGroup_type :: Ptr (TQGraphicsItemGroup a) -> IO CInt instance Qqtype_h (QGraphicsItemGroupSc a) (()) where qtype_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_type cobj_x0 instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 let x1int = fromCInt x1 if (objectIsNull x0obj) then return () else _handler x0obj x1int setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler7" qtc_QGraphicsItemGroup_setHandler7 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup7 :: (Ptr (TQGraphicsItemGroup x0) -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> CInt -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> Int -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CInt -> IO () setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 let x1int = fromCInt x1 if (objectIsNull x0obj) then return () else _handler x0obj x1int setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qadvance_h (QGraphicsItemGroup ()) ((Int)) where advance_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_advance cobj_x0 (toCInt x1) foreign import ccall "qtc_QGraphicsItemGroup_advance" qtc_QGraphicsItemGroup_advance :: Ptr (TQGraphicsItemGroup a) -> CInt -> IO () instance Qadvance_h (QGraphicsItemGroupSc a) ((Int)) where advance_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_advance cobj_x0 (toCInt x1) instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let x2enum = qEnum_fromInt $ fromCLong x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2enum rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler8" qtc_QGraphicsItemGroup_setHandler8 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup8 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> ItemSelectionMode -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> CLong -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let x2enum = qEnum_fromInt $ fromCLong x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2enum rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 x1obj <- qObjectFromPtr x1 let x2enum = qEnum_fromInt $ fromCLong x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2enum rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler9" qtc_QGraphicsItemGroup_setHandler9 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup9 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QObject t1 -> ItemSelectionMode -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> CLong -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 x1obj <- qObjectFromPtr x1 let x2enum = qEnum_fromInt $ fromCLong x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2enum rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QcollidesWithItem_h (QGraphicsItemGroup ()) ((QGraphicsItem t1)) where collidesWithItem_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithItem cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_collidesWithItem" qtc_QGraphicsItemGroup_collidesWithItem :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsItem t1) -> IO CBool instance QcollidesWithItem_h (QGraphicsItemGroupSc a) ((QGraphicsItem t1)) where collidesWithItem_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithItem cobj_x0 cobj_x1 instance QcollidesWithItem_h (QGraphicsItemGroup ()) ((QGraphicsItem t1, ItemSelectionMode)) where collidesWithItem_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QGraphicsItemGroup_collidesWithItem1" qtc_QGraphicsItemGroup_collidesWithItem1 :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsItem t1) -> CLong -> IO CBool instance QcollidesWithItem_h (QGraphicsItemGroupSc a) ((QGraphicsItem t1, ItemSelectionMode)) where collidesWithItem_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithItem1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) instance QcollidesWithItem_h (QGraphicsItemGroup ()) ((QGraphicsTextItem t1)) where collidesWithItem_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithItem_graphicstextitem cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_collidesWithItem_graphicstextitem" qtc_QGraphicsItemGroup_collidesWithItem_graphicstextitem :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsTextItem t1) -> IO CBool instance QcollidesWithItem_h (QGraphicsItemGroupSc a) ((QGraphicsTextItem t1)) where collidesWithItem_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithItem_graphicstextitem cobj_x0 cobj_x1 instance QcollidesWithItem_h (QGraphicsItemGroup ()) ((QGraphicsTextItem t1, ItemSelectionMode)) where collidesWithItem_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QGraphicsItemGroup_collidesWithItem1_graphicstextitem" qtc_QGraphicsItemGroup_collidesWithItem1_graphicstextitem :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsTextItem t1) -> CLong -> IO CBool instance QcollidesWithItem_h (QGraphicsItemGroupSc a) ((QGraphicsTextItem t1, ItemSelectionMode)) where collidesWithItem_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithItem1_graphicstextitem cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QPainterPath t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler10" qtc_QGraphicsItemGroup_setHandler10 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup10 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QPainterPath t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let x2enum = qEnum_fromInt $ fromCLong x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2enum rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler11" qtc_QGraphicsItemGroup_setHandler11 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup11 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QPainterPath t1 -> ItemSelectionMode -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup11 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup11_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPainterPath t1) -> CLong -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let x2enum = qEnum_fromInt $ fromCLong x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2enum rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QcollidesWithPath_h (QGraphicsItemGroup ()) ((QPainterPath t1)) where collidesWithPath_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithPath cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_collidesWithPath" qtc_QGraphicsItemGroup_collidesWithPath :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQPainterPath t1) -> IO CBool instance QcollidesWithPath_h (QGraphicsItemGroupSc a) ((QPainterPath t1)) where collidesWithPath_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithPath cobj_x0 cobj_x1 instance QcollidesWithPath_h (QGraphicsItemGroup ()) ((QPainterPath t1, ItemSelectionMode)) where collidesWithPath_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QGraphicsItemGroup_collidesWithPath1" qtc_QGraphicsItemGroup_collidesWithPath1 :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQPainterPath t1) -> CLong -> IO CBool instance QcollidesWithPath_h (QGraphicsItemGroupSc a) ((QPainterPath t1, ItemSelectionMode)) where collidesWithPath_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_collidesWithPath1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QPointF t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup12 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup12_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPointF t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler12" qtc_QGraphicsItemGroup_setHandler12 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup12 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPointF t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPointF t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QPointF t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup12 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup12_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQPointF t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qqcontains_h (QGraphicsItemGroup ()) ((PointF)) where qcontains_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QGraphicsItemGroup_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y foreign import ccall "qtc_QGraphicsItemGroup_contains_qth" qtc_QGraphicsItemGroup_contains_qth :: Ptr (TQGraphicsItemGroup a) -> CDouble -> CDouble -> IO CBool instance Qqcontains_h (QGraphicsItemGroupSc a) ((PointF)) where qcontains_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QGraphicsItemGroup_contains_qth cobj_x0 cpointf_x1_x cpointf_x1_y instance Qqqcontains_h (QGraphicsItemGroup ()) ((QPointF t1)) where qqcontains_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_contains cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_contains" qtc_QGraphicsItemGroup_contains :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQPointF t1) -> IO CBool instance Qqqcontains_h (QGraphicsItemGroupSc a) ((QPointF t1)) where qqcontains_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_contains cobj_x0 cobj_x1 instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup13 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup13_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler13" qtc_QGraphicsItemGroup_setHandler13 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup13 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup13 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup13_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QcontextMenuEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_contextMenuEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_contextMenuEvent" qtc_QGraphicsItemGroup_contextMenuEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneContextMenuEvent t1) -> IO () instance QcontextMenuEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_contextMenuEvent cobj_x0 cobj_x1 instance QdragEnterEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneDragDropEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_dragEnterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_dragEnterEvent" qtc_QGraphicsItemGroup_dragEnterEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO () instance QdragEnterEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneDragDropEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_dragEnterEvent cobj_x0 cobj_x1 instance QdragLeaveEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneDragDropEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_dragLeaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_dragLeaveEvent" qtc_QGraphicsItemGroup_dragLeaveEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO () instance QdragLeaveEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneDragDropEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_dragLeaveEvent cobj_x0 cobj_x1 instance QdragMoveEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneDragDropEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_dragMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_dragMoveEvent" qtc_QGraphicsItemGroup_dragMoveEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO () instance QdragMoveEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneDragDropEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_dragMoveEvent cobj_x0 cobj_x1 instance QdropEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneDragDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_dropEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_dropEvent" qtc_QGraphicsItemGroup_dropEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneDragDropEvent t1) -> IO () instance QdropEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneDragDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_dropEvent cobj_x0 cobj_x1 instance QfocusInEvent_h (QGraphicsItemGroup ()) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_focusInEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_focusInEvent" qtc_QGraphicsItemGroup_focusInEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent_h (QGraphicsItemGroupSc a) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_focusInEvent cobj_x0 cobj_x1 instance QfocusOutEvent_h (QGraphicsItemGroup ()) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_focusOutEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_focusOutEvent" qtc_QGraphicsItemGroup_focusOutEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent_h (QGraphicsItemGroupSc a) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_focusOutEvent cobj_x0 cobj_x1 instance QhoverEnterEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneHoverEvent t1)) where hoverEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_hoverEnterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_hoverEnterEvent" qtc_QGraphicsItemGroup_hoverEnterEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO () instance QhoverEnterEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneHoverEvent t1)) where hoverEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_hoverEnterEvent cobj_x0 cobj_x1 instance QhoverLeaveEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneHoverEvent t1)) where hoverLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_hoverLeaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_hoverLeaveEvent" qtc_QGraphicsItemGroup_hoverLeaveEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO () instance QhoverLeaveEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneHoverEvent t1)) where hoverLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_hoverLeaveEvent cobj_x0 cobj_x1 instance QhoverMoveEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneHoverEvent t1)) where hoverMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_hoverMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_hoverMoveEvent" qtc_QGraphicsItemGroup_hoverMoveEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneHoverEvent t1) -> IO () instance QhoverMoveEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneHoverEvent t1)) where hoverMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_hoverMoveEvent cobj_x0 cobj_x1 instance QinputMethodEvent_h (QGraphicsItemGroup ()) ((QInputMethodEvent t1)) where inputMethodEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_inputMethodEvent" qtc_QGraphicsItemGroup_inputMethodEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent_h (QGraphicsItemGroupSc a) ((QInputMethodEvent t1)) where inputMethodEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_inputMethodEvent cobj_x0 cobj_x1 instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup14 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup14_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 let x1enum = qEnum_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler14" qtc_QGraphicsItemGroup_setHandler14 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup14 :: (Ptr (TQGraphicsItemGroup x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> CLong -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup14 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup14_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 let x1enum = qEnum_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QinputMethodQuery_h (QGraphicsItemGroup ()) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QGraphicsItemGroup_inputMethodQuery" qtc_QGraphicsItemGroup_inputMethodQuery :: Ptr (TQGraphicsItemGroup a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery_h (QGraphicsItemGroupSc a) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup15 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup15_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 let x1enum = qEnum_fromInt $ fromCLong x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum x2obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler15" qtc_QGraphicsItemGroup_setHandler15 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup15 :: (Ptr (TQGraphicsItemGroup x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> GraphicsItemChange -> QVariant t2 -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup15 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup15_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 let x1enum = qEnum_fromInt $ fromCLong x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum x2obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QitemChange_h (QGraphicsItemGroup ()) ((GraphicsItemChange, QVariant t2)) where itemChange_h x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsItemGroup_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2 foreign import ccall "qtc_QGraphicsItemGroup_itemChange" qtc_QGraphicsItemGroup_itemChange :: Ptr (TQGraphicsItemGroup a) -> CLong -> Ptr (TQVariant t2) -> IO (Ptr (TQVariant ())) instance QitemChange_h (QGraphicsItemGroupSc a) ((GraphicsItemChange, QVariant t2)) where itemChange_h x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsItemGroup_itemChange cobj_x0 (toCLong $ qEnum_toInt x1) cobj_x2 instance QkeyPressEvent_h (QGraphicsItemGroup ()) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_keyPressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_keyPressEvent" qtc_QGraphicsItemGroup_keyPressEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent_h (QGraphicsItemGroupSc a) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_keyPressEvent cobj_x0 cobj_x1 instance QkeyReleaseEvent_h (QGraphicsItemGroup ()) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_keyReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_keyReleaseEvent" qtc_QGraphicsItemGroup_keyReleaseEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent_h (QGraphicsItemGroupSc a) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_keyReleaseEvent cobj_x0 cobj_x1 instance QmouseDoubleClickEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_mouseDoubleClickEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_mouseDoubleClickEvent" qtc_QGraphicsItemGroup_mouseDoubleClickEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO () instance QmouseDoubleClickEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_mouseDoubleClickEvent cobj_x0 cobj_x1 instance QmouseMoveEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_mouseMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_mouseMoveEvent" qtc_QGraphicsItemGroup_mouseMoveEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO () instance QmouseMoveEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_mouseMoveEvent cobj_x0 cobj_x1 instance QmousePressEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_mousePressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_mousePressEvent" qtc_QGraphicsItemGroup_mousePressEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO () instance QmousePressEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_mousePressEvent cobj_x0 cobj_x1 instance QmouseReleaseEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_mouseReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_mouseReleaseEvent" qtc_QGraphicsItemGroup_mouseReleaseEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneMouseEvent t1) -> IO () instance QmouseReleaseEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_mouseReleaseEvent cobj_x0 cobj_x1 instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup16 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup16_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler16" qtc_QGraphicsItemGroup_setHandler16 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup16 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup16 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup16_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsceneEvent_h (QGraphicsItemGroup ()) ((QEvent t1)) where sceneEvent_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_sceneEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_sceneEvent" qtc_QGraphicsItemGroup_sceneEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQEvent t1) -> IO CBool instance QsceneEvent_h (QGraphicsItemGroupSc a) ((QEvent t1)) where sceneEvent_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_sceneEvent cobj_x0 cobj_x1 instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup17 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup17_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler17" qtc_QGraphicsItemGroup_setHandler17 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup17 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QGraphicsItem t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup17 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup17_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetHandler (QGraphicsItemGroup ()) (QGraphicsItemGroup x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup18 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup18_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QGraphicsItemGroup_setHandler18" qtc_QGraphicsItemGroup_setHandler18 :: Ptr (TQGraphicsItemGroup a) -> CWString -> Ptr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup18 :: (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QGraphicsItemGroup18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QGraphicsItemGroupSc a) (QGraphicsItemGroup x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QGraphicsItemGroup18 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QGraphicsItemGroup18_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QGraphicsItemGroup_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQGraphicsItemGroup x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- objectFromPtr_nf x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsceneEventFilter_h (QGraphicsItemGroup ()) ((QGraphicsItem t1, QEvent t2)) where sceneEventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsItemGroup_sceneEventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QGraphicsItemGroup_sceneEventFilter" qtc_QGraphicsItemGroup_sceneEventFilter :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsItem t1) -> Ptr (TQEvent t2) -> IO CBool instance QsceneEventFilter_h (QGraphicsItemGroupSc a) ((QGraphicsItem t1, QEvent t2)) where sceneEventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsItemGroup_sceneEventFilter cobj_x0 cobj_x1 cobj_x2 instance QsceneEventFilter_h (QGraphicsItemGroup ()) ((QGraphicsTextItem t1, QEvent t2)) where sceneEventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsItemGroup_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QGraphicsItemGroup_sceneEventFilter_graphicstextitem" qtc_QGraphicsItemGroup_sceneEventFilter_graphicstextitem :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsTextItem t1) -> Ptr (TQEvent t2) -> IO CBool instance QsceneEventFilter_h (QGraphicsItemGroupSc a) ((QGraphicsTextItem t1, QEvent t2)) where sceneEventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QGraphicsItemGroup_sceneEventFilter_graphicstextitem cobj_x0 cobj_x1 cobj_x2 instance Qshape_h (QGraphicsItemGroup ()) (()) where shape_h x0 () = withQPainterPathResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_shape cobj_x0 foreign import ccall "qtc_QGraphicsItemGroup_shape" qtc_QGraphicsItemGroup_shape :: Ptr (TQGraphicsItemGroup a) -> IO (Ptr (TQPainterPath ())) instance Qshape_h (QGraphicsItemGroupSc a) (()) where shape_h x0 () = withQPainterPathResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QGraphicsItemGroup_shape cobj_x0 instance QwheelEvent_h (QGraphicsItemGroup ()) ((QGraphicsSceneWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_wheelEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QGraphicsItemGroup_wheelEvent" qtc_QGraphicsItemGroup_wheelEvent :: Ptr (TQGraphicsItemGroup a) -> Ptr (TQGraphicsSceneWheelEvent t1) -> IO () instance QwheelEvent_h (QGraphicsItemGroupSc a) ((QGraphicsSceneWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QGraphicsItemGroup_wheelEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QGraphicsItemGroup_h.hs
Haskell
bsd-2-clause
98,747
module Handler.View where import Import import Handler.Markdown (renderMarkdown) getViewR :: NoteId -> Handler RepHtml getViewR noteId = do note <- runDB $ get404 noteId defaultLayout $ do setTitle (toHtml $ noteTitle note) let markdown = renderMarkdown (unTextarea $ noteText note) $(widgetFile "view")
MasseR/introitu
Handler/View.hs
Haskell
bsd-2-clause
322
module Permutations where import Data.List (delete, nub) -- | List all permutations of a list (4 kyu) -- | Link: https://biturl.io/Permutations -- | My original solution permutations :: Eq a => [a] -> [[a]] permutations [] = [[]] permutations xs = nub [x : ys | x <- xs, ys <- permutations (delete x xs)]
Eugleo/Code-Wars
src/combinatorics-kata/Permutations.hs
Haskell
bsd-3-clause
308
{-# LANGUAGE OverloadedStrings #-} module Main ( main ) where import Control.Applicative ((<$>)) import Control.Monad (forever, mzero) import Control.Monad.Trans (liftIO) import Control.Monad.IO.Class (MonadIO) import Control.Concurrent (forkIO, ThreadId) import Data.Aeson (FromJSON (..), ToJSON (..), (.:), (.=)) import qualified Data.Aeson as A import qualified Data.Map as M import Data.Maybe (fromMaybe) import qualified Data.Text.IO as T import qualified Data.Text as T import qualified Data.ByteString.Lazy.Char8 as LBS import Data.Text (Text) import Data.List (isPrefixOf) import qualified Data.Vector as V import Data.Monoid ((<>)) import Control.Monad (when) import qualified Network.HTTP.Conduit as Http import qualified Network.URI as Uri import qualified Network.WebSockets as WS import System.Process (system) import System.Exit (ExitCode) import CmdArgs import Options.Applicative import Watch (monitor) import Chrome import Commands opts :: ParserInfo CmdArgs opts = info (helper <*> cmdArgs) (fullDesc <> progDesc "For WAI complaint haskell web applications" <> header "Reloader: Reload chrome tabs when files change locally." ) main :: IO () main = do CmdArgs shouldRestart website files <- execParser opts when shouldRestart (startChrome >> return ()) pages <- getChromiumPageInfo 9160 putStrLn "" >> putStrLn "pages:" print pages let (ci : _) = filter (\page -> isPrefixOf website (pageURL page)) pages putStrLn "" >> putStrLn "ci:" print ci -- putStrLn "" >> putStrLn "request" -- LBS.putStrLn $ A.encode $ searchName "remi" -- let (host, port, path) = parseUri (chromiumDebuggerUrl ci) WS.runClient host port path $ \conn -> do forkIO (monitor (const (WS.sendTextData conn $ A.encode reload)) >> return ()) WS.sendTextData conn $ A.encode reload forever $ do msg <- WS.receiveData conn liftIO $ do putStrLn "------------------\nresult:" T.putStrLn msg putStrLn "------------------" txt <- getLine let cmd = A.encode reload print cmd WS.sendTextData conn cmd
rvion/chrome-reloader
src/Main.hs
Haskell
bsd-3-clause
2,454
{- Copyright (c) 2014-2015, Johan Nordlander, Jonas Duregård, Michał Pałka, Patrik Jansson and Josef Svenningsson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Chalmers University of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Main where import ARSim -- | Just send 123 to the queue r1 :: PQ Int c -> RunM (StdRet ()) r1 pqe = do rte_send pqe (123::Int) -- | Provides a port (create it) and run r1 every 1.0 time units c1 :: AR c (PQ Int ()) c1 = do pqe <- providedQueueElement runnable Concurrent [Timed 1.0] (r1 pqe) return (seal pqe) -- | Just receive a value and do nothing with it r2 :: Valuable a => RQ a c -> RunM () r2 rqe = do Ok x <- rte_receive rqe; return () -- | Requires a port (parametrised over the port) and "runs" r2 c2 :: AR c (RQ Int ()) c2 = do rqe <- requiredQueueElement 10 -- Queue of size 10 runnable Concurrent [ReceiveQ rqe] (r2 rqe) return (seal rqe) -- | Connect c1 and c2 to create a program that sends and receives. test :: AR c () test = do pqe <- component c1 rqe <- component c2 connect pqe rqe -- | Run the simulation of this test program, showing a trace of the execution main = putTraceLabels $ fst $ (simulationHead test)
josefs/autosar
oldARSim/Main.hs
Haskell
bsd-3-clause
2,812
module HaskellCI.Config.Jobs where import HaskellCI.Prelude import qualified Distribution.Compat.CharParsing as C import qualified Distribution.Parsec as C import qualified Distribution.Pretty as C import qualified Text.PrettyPrint as PP -- | Jobs -- -- * @N:M@ - @N@ ghcs (cabal -j), @M@ threads (ghc -j) -- -- >>> let parseJobs = C.simpleParsec :: String -> Maybe Jobs -- >>> parseJobs "2:2" -- Just (BothJobs 2 2) -- -- >>> parseJobs ":2" -- Just (GhcJobs 2) -- -- >>> parseJobs "2" -- Just (CabalJobs 2) -- -- >>> parseJobs "garbage" -- Nothing -- data Jobs = CabalJobs Int | GhcJobs Int | BothJobs Int Int deriving (Show) cabalJobs :: Jobs -> Maybe Int cabalJobs (CabalJobs n) = Just n cabalJobs (GhcJobs _) = Nothing cabalJobs (BothJobs n _) = Just n ghcJobs :: Jobs -> Maybe Int ghcJobs (CabalJobs _) = Nothing ghcJobs (GhcJobs m) = Just m ghcJobs (BothJobs _ m) = Just m instance C.Parsec Jobs where parsec = ghc <|> rest where ghc = C.char ':' *> (GhcJobs <$> C.integral) rest = do n <- C.integral m' <- C.optional (C.char ':' *> C.integral) return $ case m' of Nothing -> CabalJobs n Just m -> BothJobs n m instance C.Pretty Jobs where pretty (BothJobs n m) = PP.int n PP.<> PP.colon PP.<> PP.int m pretty (CabalJobs n) = PP.int n pretty (GhcJobs m) = PP.colon PP.<> PP.int m
hvr/multi-ghc-travis
src/HaskellCI/Config/Jobs.hs
Haskell
bsd-3-clause
1,460
-- {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE ExplicitForAll #-} --{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} -- {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} --{-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE RankNTypes #-} --{-# LANGUAGE RebindableSyntax #-} --{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedLists #-} --{-# LANGUAGE NamedFieldPuns #-} module FV.Fit ( fit, kAddF, kAdd, ksm' , kChi2 ) where import Prelude.Extended --import qualified Data.Vector.Unboxed as A ( foldl, unzip, length ) import Data.Maybe ( Maybe (..), mapMaybe ) import Data.Cov import FV.Jacob as J import FV.Types ( VHMeas (..), HMeas (..), QMeas (..), XMeas (..) , XFit (..) , Prong (..), Chi2 (..) ) fit :: VHMeas -> Prong fit vhm = kSmooth vhm <<< kFilter $ vhm kFilter :: VHMeas -> XMeas kFilter VHMeas {vertex=v, helices=hl} = foldl kAdd v hl kAdd :: XMeas -> HMeas -> XMeas kAdd (XMeas v vv) (HMeas h hh w0) = kAdd' x_km1 p_k x_e q_e (Chi2 1e6) 0 where x_km1 = XMeas v (inv vv) p_k = HMeas h (inv hh) w0 x_e = v q_e = J.hv2q h v goodEnough :: Chi2 -> Chi2 -> Int -> Bool --goodEnough (Chi2 c0) (Chi2 c) i | i < 99 && trace ("." <> show i <> "|" <> to1fix (abs (c-c0)) <> " " <> to1fix c) false = undefined goodEnough (Chi2 c0) (Chi2 c) i = abs (c - c0) < chi2cut || i > iterMax where chi2cut = 0.5 iterMax = 99 :: Int -- | add a helix measurement to kalman filter, return updated vertex position -- | if we can't invert, don't update vertex kAdd' :: XMeas -> HMeas -> Vec3 -> Vec3 -> Chi2 -> Int -> XMeas --kAdd' (XMeas v0 uu0) (HMeas h gg w0) x_e q_e _ i | -- i == 0 && trace ("kadd'-->" <> show i <> "|" <> show v0 <> show h) false = undefined kAdd' (XMeas v0 uu0) (HMeas h gg w0) x_e q_e 𝜒2_0 iter = x_k where jj = J.expand x_e q_e Jacs {aajacs=aa, bbjacs=bb, h0jacs=h0} = jj aaT = tr aa bbT = tr bb x_k = case invMaybe (bb .*. gg) of Nothing -> XMeas v0 (inv uu0) `debug` "... can't invert in kAdd'" Just ww -> let gb = gg - gg .*. (bbT .*. ww) uu = uu0 + aa .*. gb cc = inv uu m = h - h0 v = cc *. (uu0 *. v0 + aaT *. gb *. m) dm = m - aa *. v q = ww *. (bbT *. gg *. dm) 𝜒2 = Chi2 $ (dm - bb *. q) .*. gg + (v - v0) .*. uu0 x_k' = if goodEnough 𝜒2_0 𝜒2 iter -- `debug` ("--> kAdd' chi2 is " <> show 𝜒2) then XMeas v cc else kAdd' (XMeas v0 uu0) (HMeas h gg w0) v q 𝜒2 (iter+1) in x_k' kAddF :: XFit -> HMeas -> XFit kAddF (XFit v vv _) (HMeas h hh _) = kAddF' v (inv vv) h (inv hh) v (J.hv2q h v) (Chi2 1e6) 0 kAddF' :: Vec3 -> Cov3 -> Vec5 -> Cov5 -> Vec3 -> Vec3 -> Chi2 -> Int -> XFit kAddF' v0 uu0 h gg x_e q_e 𝜒2_0 iter = x_k where jj = J.expand x_e q_e Jacs {aajacs=aa, bbjacs=bb, h0jacs=h0} = jj aaT = tr aa bbT = tr bb x_k = case invMaybe (bb .*. gg) of Nothing -> XFit v0 (inv uu0) (Chi2 1e6) `debug` "... can't invert in kAddF'" Just ww -> let gb = gg - gg .*. (bbT .*. ww) uu = uu0 + aa .*. gb cc = inv uu m = h - h0 v = cc *. (uu0 *. v0 + aaT *. gb *. m) dm = m - aa *. v q = ww *. (bbT *. gg *. dm) 𝜒2 = Chi2 $ (dm - bb *. q) .*. gg + (v - v0) .*. uu0 x_k' = if goodEnough 𝜒2_0 𝜒2 iter -- `debug` (printf "--> kAddF' chi2 is %9.1f, %9.1f" 𝜒2 (scalar $ sw (v-v0) uu0)) then XFit v cc 𝜒2 else kAddF' v0 uu0 h gg v q 𝜒2 (iter+1) in x_k' kSmooth :: VHMeas -> XMeas -> Prong --kSmooth vm v | trace ("kSmooth " <> (show <<< length <<< helices $ vm) <> ", vertex at " <> (show v) ) false = undefined kSmooth (VHMeas {vertex= v0, helices= hl}) v = pr' where (ql, chi2l) = unzip $ mapMaybe (ksm v) hl hl' = hl n = length hl n' = length ql n'' = if n == n' then n else n' `debug` "kSmooth killed helices" pr' = Prong { fitVertex= v, fitMomenta= ql, fitChi2s= chi2l, nProng= n'', measurements= VHMeas {vertex= v0, helices= hl'} } -- kalman smoother step: calculate 3-mom q and chi2 at kalman filter'ed vertex -- if we can't invert, return Nothing and this track will not be included ksm :: XMeas -> HMeas -> Maybe (QMeas, Chi2) ksm (XMeas x cc) (HMeas h hh w0) = do let jj = J.expand x (J.hv2q h x) Jacs {aajacs=aa, bbjacs=bb, h0jacs=h0} = jj gg = inv hh ww <- invMaybe (bb .*. gg) let p = h - h0 uu = inv cc aaT = tr aa bbT = tr bb dp = p - aa *. x q = ww *. (bbT *. gg *. dp) mee = (cc *. aaT) *. gg *. bb *. ww dd = ww + mee .*. uu r = p - aa *. x - bb *. q ch = r .*. gg gb = gg - gg .*. (bbT .*. ww) uu' = uu - aa .*. gb cx = if det uu' < 0.0 then 1000.0 `debug` ("--> ksm bad " <> show (det uu') <> show uu') else cx'' where cc' = inv uu' -- `debug` ("--> ksm " ++ show uu') x' = cc' *. (uu *. x - aaT *. gb *. p) dx = x - x' cx' = dx .*. uu' cx'' = if cx' < 0.0 then 2000.0 `debug` ("--> ksm chi2 is " <> show cx' <> ", " <> show ch <> ", " <> show (max cx' 0.0 + ch)) else cx' 𝜒2 = cx + ch pure (QMeas q dd w0, Chi2 𝜒2) ksm' :: XMeas -> Maybe HMeas -> Maybe (QMeas, Chi2) ksm' _ Nothing = Nothing ksm' xm (Just hm) = ksm xm hm -- calculate Chi2 of a new helix measurement using kalman filter -- if we can't invert, return 0.0 kChi2 :: XMeas -> HMeas -> Chi2 kChi2 (XMeas v vv) (HMeas h hh w0) = kChi2' x_km1 p_k x_e q_e (Chi2 1e6) 0 where x_km1 = XMeas v (inv vv) p_k = HMeas h (inv hh) w0 x_e = v q_e = J.hv2q h v kChi2' :: XMeas -> HMeas -> Vec3 -> Vec3 -> Chi2 -> Int -> Chi2 kChi2' (XMeas v0 uu0) (HMeas h gg w0) x_e q_e 𝜒2_0 iter = x_k where jj = J.expand x_e q_e Jacs {aajacs=aa, bbjacs=bb, h0jacs=h0} = jj aaT = tr aa bbT = tr bb x_k = case invMaybe (bb .*. gg) of Nothing -> Chi2 0.0 Just ww -> let gb = gg - gg .*. (bbT .*. ww) uu = uu0 + aa .*. gb cc = inv uu m = h - h0 v = cc *. (uu0 *. v0 + aaT *. gb *. m) dm = m - aa *. v q = ww *. bbT *. gg *. dm 𝜒2 = Chi2 $ (v - v0) .*. uu0 -- or shoud it use uu?? + sw (dm - bb * q) gg x_k' = if goodEnough 𝜒2_0 𝜒2 iter then 𝜒2 else kChi2' (XMeas v0 uu0) (HMeas h gg w0) v q 𝜒2 (iter+1) in x_k'
LATBauerdick/fv.hs
src/FV/Fit.hs
Haskell
bsd-3-clause
7,151
{-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module RegAlloc.Linear.FreeRegs ( FR(..), maxSpillSlots ) #include "HsVersions.h" where import Reg import RegClass import Panic import Platform -- ----------------------------------------------------------------------------- -- The free register set -- This needs to be *efficient* -- Here's an inefficient 'executable specification' of the FreeRegs data type: -- -- type FreeRegs = [RegNo] -- noFreeRegs = 0 -- releaseReg n f = if n `elem` f then f else (n : f) -- initFreeRegs = allocatableRegs -- getFreeRegs cls f = filter ( (==cls) . regClass . RealReg ) f -- allocateReg f r = filter (/= r) f import qualified RegAlloc.Linear.PPC.FreeRegs as PPC import qualified RegAlloc.Linear.SPARC.FreeRegs as SPARC import qualified RegAlloc.Linear.X86.FreeRegs as X86 import qualified PPC.Instr import qualified SPARC.Instr import qualified X86.Instr class Show freeRegs => FR freeRegs where frAllocateReg :: RealReg -> freeRegs -> freeRegs frGetFreeRegs :: Platform -> RegClass -> freeRegs -> [RealReg] frInitFreeRegs :: Platform -> freeRegs frReleaseReg :: RealReg -> freeRegs -> freeRegs instance FR X86.FreeRegs where frAllocateReg = X86.allocateReg frGetFreeRegs = X86.getFreeRegs frInitFreeRegs = X86.initFreeRegs frReleaseReg = X86.releaseReg instance FR PPC.FreeRegs where frAllocateReg = PPC.allocateReg frGetFreeRegs = \_ -> PPC.getFreeRegs frInitFreeRegs = \_ -> PPC.initFreeRegs frReleaseReg = PPC.releaseReg instance FR SPARC.FreeRegs where frAllocateReg = SPARC.allocateReg frGetFreeRegs = \_ -> SPARC.getFreeRegs frInitFreeRegs = \_ -> SPARC.initFreeRegs frReleaseReg = SPARC.releaseReg maxSpillSlots :: Platform -> Int maxSpillSlots platform = case platformArch platform of ArchX86 -> X86.Instr.maxSpillSlots True -- 32bit ArchX86_64 -> X86.Instr.maxSpillSlots False -- not 32bit ArchPPC -> PPC.Instr.maxSpillSlots ArchSPARC -> SPARC.Instr.maxSpillSlots ArchARM _ _ _ -> panic "maxSpillSlots ArchARM" ArchPPC_64 -> panic "maxSpillSlots ArchPPC_64" ArchUnknown -> panic "maxSpillSlots ArchUnknown"
nomeata/ghc
compiler/nativeGen/RegAlloc/Linear/FreeRegs.hs
Haskell
bsd-3-clause
2,590
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-@ LIQUID "--no-termination "@-} import LiquidHaskell import Language.Haskell.Liquid.Prelude import Prelude hiding (sum, length, (!!), Functor(..)) import qualified Prelude as P [lq| qualif Size(v:int, xs:a): v = (size xs) |] [lq| data List a = Nil | Cons (hd::a) (tl::(List a)) |] data List a = Nil | Cons a (List a) [lq| length :: xs:List a -> {v:Nat | v = (size xs)} |] length :: List a -> Int length Nil = 0 length (Cons x xs) = 1 + length xs [lq| (!!) :: xs:List a -> {v:Nat | v < (size xs)} -> a |] (!!) :: List a -> Int -> a Nil !! i = liquidError "impossible" (Cons x _) !! 0 = x (Cons x xs) !! i = xs !! (i - 1) [lq| class measure size :: forall a. a -> Int |] [lq| class Sized s where size :: forall a. x:s a -> {v:Nat | v = (size x)} |] class Sized s where size :: s a -> Int instance Sized List where [lq| instance measure size :: List a -> Int size (Nil) = 0 size (Cons x xs) = 1 + (size xs) |] size = length instance Sized [] where [lq| instance measure size :: [a] -> Int size ([]) = 0 size (x:xs) = 1 + (size xs) |] size [] = 0 size (x:xs) = 1 + size xs [lq| class (Sized s) => Indexable s where index :: forall a. x:s a -> {v:Nat | v < (size x)} -> a |] class (Sized s) => Indexable s where index :: s a -> Int -> a instance Indexable List where index = (!!) [lq| sum :: Indexable s => s Int -> Int |] sum :: Indexable s => s Int -> Int sum xs = go max 0 where max = size xs go (d::Int) i | i < max = index xs i + go (d-1) (i+1) | otherwise = 0 [lq| sumList :: List Int -> Int |] sumList :: List Int -> Int sumList xs = go max 0 where max = size xs go (d::Int) i | i < max = index xs i + go (d-1) (i+1) | otherwise = 0 [lq| x :: {v:List Int | (size v) = 3} |] x :: List Int x = 1 `Cons` (2 `Cons` (3 `Cons` Nil)) foo = liquidAssert $ size (Cons 1 Nil) == size [1]
spinda/liquidhaskell
tests/gsoc15/unknown/pos/Class.hs
Haskell
bsd-3-clause
2,007
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} -- | Provides operations for BitFields that are used in the protocol. module Network.BitTorrent.BitField ( BitField(..) , newBitField , get , set , completed , toPWP ) where import Control.DeepSeq import Data.Bits import Data.ByteString (ByteString) import Data.Foldable as Foldable import qualified Data.ByteString as B import Data.Monoid import Data.Word import GHC.Generics (Generic) import Network.BitTorrent.PWP import Network.BitTorrent.Utility -- | Holds the completion status of pieces. -- Works by using tightly packed bits to store this information efficiently. -- Can describe 8 piece statuses per byte. data BitField = BitField { raw :: !ByteString -- ^ Raw byte array. , length :: Word32 -- ^ Length of the bitfield. } deriving(Show, Eq, Generic, NFData) -- | /O(n)/ Creates a new bitfield with the specified length. -- Starts out with all pieces marked as unfinished. newBitField :: Word32 -> BitField newBitField len = BitField (B.replicate (fromIntegral byteLength) 0) len where byteLength = divideSize len 8 {-# INLINABLE newBitField #-} -- | /O(1)/ Get the status of a single piece. get :: BitField -> Word32 -> Bool get (BitField field _) ix = testBit word (7 - fromIntegral ix `rem` 8) where byteIx = fromIntegral $ ix `quot` 8 word = B.index field byteIx {-# INLINABLE get #-} -- | /O(n)/ Sets the status of a single piece by returning a new -- bitfield with the change applied. set :: BitField -> Word32 -- ^ Piece ID -> Bool -- ^ New status -> BitField set (BitField field len) ix val = (BitField $! updatedField) $! len where byteIx = fromIntegral ix `quot` 8 word = B.index field byteIx modifier True = setBit modifier False = clearBit updatedByte = modifier val word (7 - fromIntegral ix `rem` 8) updatedField = B.take byteIx field <> B.singleton updatedByte <> B.drop (byteIx + 1) field {-# INLINABLE set #-} -- | /O(n)/ Get the ratio of completed pieces. completed :: BitField -> Float -- ^ Result in range /[0;1]/ completed (BitField b len) = fromIntegral (Foldable.sum (popCount <$> B.unpack b)) / fromIntegral len {-# INLINABLE completed #-} -- | /O(1)/ Cast the BitField to a PWP message. toPWP :: BitField -> PWP toPWP (BitField raw _) = Bitfield raw {-# INLINABLE toPWP #-}
farnoy/torrent
src/Network/BitTorrent/BitField.hs
Haskell
bsd-3-clause
2,400
-- | contains a prettyprinter for the -- Template Haskell datatypes module Language.Haskell.TH.Ppr where -- All of the exports from this module should -- be "public" functions. The main module TH -- re-exports them all. import Text.PrettyPrint (render) import Language.Haskell.TH.PprLib import Language.Haskell.TH.Syntax import Data.Word ( Word8 ) import Data.Char ( toLower, chr, ord, isSymbol ) import GHC.Show ( showMultiLineString ) import Data.Ratio ( numerator, denominator ) nestDepth :: Int nestDepth = 4 type Precedence = Int appPrec, unopPrec, opPrec, noPrec :: Precedence appPrec = 3 -- Argument of a function application opPrec = 2 -- Argument of an infix operator unopPrec = 1 -- Argument of an unresolved infix operator noPrec = 0 -- Others parensIf :: Bool -> Doc -> Doc parensIf True d = parens d parensIf False d = d ------------------------------ pprint :: Ppr a => a -> String pprint x = render $ to_HPJ_Doc $ ppr x class Ppr a where ppr :: a -> Doc ppr_list :: [a] -> Doc ppr_list = vcat . map ppr instance Ppr a => Ppr [a] where ppr x = ppr_list x ------------------------------ instance Ppr Name where ppr v = pprName v ------------------------------ instance Ppr Info where ppr (TyConI d) = ppr d ppr (ClassI d is) = ppr d $$ vcat (map ppr is) ppr (FamilyI d is) = ppr d $$ vcat (map ppr is) ppr (PrimTyConI name arity is_unlifted) = text "Primitive" <+> (if is_unlifted then text "unlifted" else empty) <+> text "type constructor" <+> quotes (ppr name) <+> parens (text "arity" <+> int arity) ppr (ClassOpI v ty cls) = text "Class op from" <+> ppr cls <> colon <+> ppr_sig v ty ppr (DataConI v ty tc) = text "Constructor from" <+> ppr tc <> colon <+> ppr_sig v ty ppr (TyVarI v ty) = text "Type variable" <+> ppr v <+> equals <+> ppr ty ppr (VarI v ty mb_d) = vcat [ppr_sig v ty, case mb_d of { Nothing -> empty; Just d -> ppr d }] ppr_sig :: Name -> Type -> Doc ppr_sig v ty = pprName' Applied v <+> dcolon <+> ppr ty pprFixity :: Name -> Fixity -> Doc pprFixity _ f | f == defaultFixity = empty pprFixity v (Fixity i d) = ppr_fix d <+> int i <+> ppr v where ppr_fix InfixR = text "infixr" ppr_fix InfixL = text "infixl" ppr_fix InfixN = text "infix" ------------------------------ instance Ppr Module where ppr (Module pkg m) = text (pkgString pkg) <+> text (modString m) instance Ppr ModuleInfo where ppr (ModuleInfo imps) = text "Module" <+> vcat (map ppr imps) ------------------------------ instance Ppr Exp where ppr = pprExp noPrec pprPrefixOcc :: Name -> Doc -- Print operators with parens around them pprPrefixOcc n = parensIf (isSymOcc n) (ppr n) isSymOcc :: Name -> Bool isSymOcc n = case nameBase n of [] -> True -- Empty name; weird (c:_) -> isSymbolASCII c || (ord c > 0x7f && isSymbol c) -- c.f. OccName.startsVarSym in GHC itself isSymbolASCII :: Char -> Bool isSymbolASCII c = c `elem` "!#$%&*+./<=>?@\\^|~-" pprInfixExp :: Exp -> Doc pprInfixExp (VarE v) = pprName' Infix v pprInfixExp (ConE v) = pprName' Infix v pprInfixExp _ = text "<<Non-variable/constructor in infix context>>" pprExp :: Precedence -> Exp -> Doc pprExp _ (VarE v) = pprName' Applied v pprExp _ (ConE c) = pprName' Applied c pprExp i (LitE l) = pprLit i l pprExp i (AppE e1 e2) = parensIf (i >= appPrec) $ pprExp opPrec e1 <+> pprExp appPrec e2 pprExp _ (ParensE e) = parens (pprExp noPrec e) pprExp i (UInfixE e1 op e2) = parensIf (i > unopPrec) $ pprExp unopPrec e1 <+> pprInfixExp op <+> pprExp unopPrec e2 pprExp i (InfixE (Just e1) op (Just e2)) = parensIf (i >= opPrec) $ pprExp opPrec e1 <+> pprInfixExp op <+> pprExp opPrec e2 pprExp _ (InfixE me1 op me2) = parens $ pprMaybeExp noPrec me1 <+> pprInfixExp op <+> pprMaybeExp noPrec me2 pprExp i (LamE ps e) = parensIf (i > noPrec) $ char '\\' <> hsep (map (pprPat appPrec) ps) <+> text "->" <+> ppr e pprExp i (LamCaseE ms) = parensIf (i > noPrec) $ text "\\case" $$ nest nestDepth (ppr ms) pprExp _ (TupE es) = parens (commaSep es) pprExp _ (UnboxedTupE es) = hashParens (commaSep es) -- Nesting in Cond is to avoid potential problems in do statments pprExp i (CondE guard true false) = parensIf (i > noPrec) $ sep [text "if" <+> ppr guard, nest 1 $ text "then" <+> ppr true, nest 1 $ text "else" <+> ppr false] pprExp i (MultiIfE alts) = parensIf (i > noPrec) $ vcat $ case alts of [] -> [text "if {}"] (alt : alts') -> text "if" <+> pprGuarded arrow alt : map (nest 3 . pprGuarded arrow) alts' pprExp i (LetE ds_ e) = parensIf (i > noPrec) $ text "let" <+> pprDecs ds_ $$ text " in" <+> ppr e where pprDecs [] = empty pprDecs [d] = ppr d pprDecs ds = braces (semiSep ds) pprExp i (CaseE e ms) = parensIf (i > noPrec) $ text "case" <+> ppr e <+> text "of" $$ nest nestDepth (ppr ms) pprExp i (DoE ss_) = parensIf (i > noPrec) $ text "do" <+> pprStms ss_ where pprStms [] = empty pprStms [s] = ppr s pprStms ss = braces (semiSep ss) pprExp _ (CompE []) = text "<<Empty CompExp>>" -- This will probably break with fixity declarations - would need a ';' pprExp _ (CompE ss) = if null ss' -- If there are no statements in a list comprehension besides the last -- one, we simply treat it like a normal list. then text "[" <> ppr s <> text "]" else text "[" <> ppr s <+> text "|" <+> commaSep ss' <> text "]" where s = last ss ss' = init ss pprExp _ (ArithSeqE d) = ppr d pprExp _ (ListE es) = brackets (commaSep es) pprExp i (SigE e t) = parensIf (i > noPrec) $ ppr e <+> dcolon <+> ppr t pprExp _ (RecConE nm fs) = ppr nm <> braces (pprFields fs) pprExp _ (RecUpdE e fs) = pprExp appPrec e <> braces (pprFields fs) pprExp i (StaticE e) = parensIf (i >= appPrec) $ text "static"<+> pprExp appPrec e pprExp _ (UnboundVarE v) = pprName' Applied v pprFields :: [(Name,Exp)] -> Doc pprFields = sep . punctuate comma . map (\(s,e) -> ppr s <+> equals <+> ppr e) pprMaybeExp :: Precedence -> Maybe Exp -> Doc pprMaybeExp _ Nothing = empty pprMaybeExp i (Just e) = pprExp i e ------------------------------ instance Ppr Stmt where ppr (BindS p e) = ppr p <+> text "<-" <+> ppr e ppr (LetS ds) = text "let" <+> (braces (semiSep ds)) ppr (NoBindS e) = ppr e ppr (ParS sss) = sep $ punctuate (text "|") $ map commaSep sss ------------------------------ instance Ppr Match where ppr (Match p rhs ds) = ppr p <+> pprBody False rhs $$ where_clause ds ------------------------------ pprGuarded :: Doc -> (Guard, Exp) -> Doc pprGuarded eqDoc (guard, expr) = case guard of NormalG guardExpr -> char '|' <+> ppr guardExpr <+> eqDoc <+> ppr expr PatG stmts -> char '|' <+> vcat (punctuate comma $ map ppr stmts) $$ nest nestDepth (eqDoc <+> ppr expr) ------------------------------ pprBody :: Bool -> Body -> Doc pprBody eq body = case body of GuardedB xs -> nest nestDepth $ vcat $ map (pprGuarded eqDoc) xs NormalB e -> eqDoc <+> ppr e where eqDoc | eq = equals | otherwise = arrow ------------------------------ instance Ppr Lit where ppr = pprLit noPrec pprLit :: Precedence -> Lit -> Doc pprLit i (IntPrimL x) = parensIf (i > noPrec && x < 0) (integer x <> char '#') pprLit _ (WordPrimL x) = integer x <> text "##" pprLit i (FloatPrimL x) = parensIf (i > noPrec && x < 0) (float (fromRational x) <> char '#') pprLit i (DoublePrimL x) = parensIf (i > noPrec && x < 0) (double (fromRational x) <> text "##") pprLit i (IntegerL x) = parensIf (i > noPrec && x < 0) (integer x) pprLit _ (CharL c) = text (show c) pprLit _ (CharPrimL c) = text (show c) <> char '#' pprLit _ (StringL s) = pprString s pprLit _ (StringPrimL s) = pprString (bytesToString s) <> char '#' pprLit i (RationalL rat) = parensIf (i > noPrec) $ integer (numerator rat) <+> char '/' <+> integer (denominator rat) bytesToString :: [Word8] -> String bytesToString = map (chr . fromIntegral) pprString :: String -> Doc -- Print newlines as newlines with Haskell string escape notation, -- not as '\n'. For other non-printables use regular escape notation. pprString s = vcat (map text (showMultiLineString s)) ------------------------------ instance Ppr Pat where ppr = pprPat noPrec pprPat :: Precedence -> Pat -> Doc pprPat i (LitP l) = pprLit i l pprPat _ (VarP v) = pprName' Applied v pprPat _ (TupP ps) = parens (commaSep ps) pprPat _ (UnboxedTupP ps) = hashParens (commaSep ps) pprPat i (ConP s ps) = parensIf (i >= appPrec) $ pprName' Applied s <+> sep (map (pprPat appPrec) ps) pprPat _ (ParensP p) = parens $ pprPat noPrec p pprPat i (UInfixP p1 n p2) = parensIf (i > unopPrec) (pprPat unopPrec p1 <+> pprName' Infix n <+> pprPat unopPrec p2) pprPat i (InfixP p1 n p2) = parensIf (i >= opPrec) (pprPat opPrec p1 <+> pprName' Infix n <+> pprPat opPrec p2) pprPat i (TildeP p) = parensIf (i > noPrec) $ char '~' <> pprPat appPrec p pprPat i (BangP p) = parensIf (i > noPrec) $ char '!' <> pprPat appPrec p pprPat i (AsP v p) = parensIf (i > noPrec) $ ppr v <> text "@" <> pprPat appPrec p pprPat _ WildP = text "_" pprPat _ (RecP nm fs) = parens $ ppr nm <+> braces (sep $ punctuate comma $ map (\(s,p) -> ppr s <+> equals <+> ppr p) fs) pprPat _ (ListP ps) = brackets (commaSep ps) pprPat i (SigP p t) = parensIf (i > noPrec) $ ppr p <+> dcolon <+> ppr t pprPat _ (ViewP e p) = parens $ pprExp noPrec e <+> text "->" <+> pprPat noPrec p ------------------------------ instance Ppr Dec where ppr = ppr_dec True ppr_dec :: Bool -- declaration on the toplevel? -> Dec -> Doc ppr_dec _ (FunD f cs) = vcat $ map (\c -> pprPrefixOcc f <+> ppr c) cs ppr_dec _ (ValD p r ds) = ppr p <+> pprBody True r $$ where_clause ds ppr_dec _ (TySynD t xs rhs) = ppr_tySyn empty t (hsep (map ppr xs)) rhs ppr_dec _ (DataD ctxt t xs ksig cs decs) = ppr_data empty ctxt t (hsep (map ppr xs)) ksig cs decs ppr_dec _ (NewtypeD ctxt t xs ksig c decs) = ppr_newtype empty ctxt t (sep (map ppr xs)) ksig c decs ppr_dec _ (ClassD ctxt c xs fds ds) = text "class" <+> pprCxt ctxt <+> ppr c <+> hsep (map ppr xs) <+> ppr fds $$ where_clause ds ppr_dec _ (InstanceD o ctxt i ds) = text "instance" <+> maybe empty ppr_overlap o <+> pprCxt ctxt <+> ppr i $$ where_clause ds ppr_dec _ (SigD f t) = pprPrefixOcc f <+> dcolon <+> ppr t ppr_dec _ (ForeignD f) = ppr f ppr_dec _ (InfixD fx n) = pprFixity n fx ppr_dec _ (PragmaD p) = ppr p ppr_dec isTop (DataFamilyD tc tvs kind) = text "data" <+> maybeFamily <+> ppr tc <+> hsep (map ppr tvs) <+> maybeKind where maybeFamily | isTop = text "family" | otherwise = empty maybeKind | (Just k') <- kind = dcolon <+> ppr k' | otherwise = empty ppr_dec isTop (DataInstD ctxt tc tys ksig cs decs) = ppr_data maybeInst ctxt tc (sep (map pprParendType tys)) ksig cs decs where maybeInst | isTop = text "instance" | otherwise = empty ppr_dec isTop (NewtypeInstD ctxt tc tys ksig c decs) = ppr_newtype maybeInst ctxt tc (sep (map pprParendType tys)) ksig c decs where maybeInst | isTop = text "instance" | otherwise = empty ppr_dec isTop (TySynInstD tc (TySynEqn tys rhs)) = ppr_tySyn maybeInst tc (sep (map pprParendType tys)) rhs where maybeInst | isTop = text "instance" | otherwise = empty ppr_dec isTop (OpenTypeFamilyD tfhead) = text "type" <+> maybeFamily <+> ppr_tf_head tfhead where maybeFamily | isTop = text "family" | otherwise = empty ppr_dec _ (ClosedTypeFamilyD tfhead@(TypeFamilyHead tc _ _ _) eqns) = hang (text "type family" <+> ppr_tf_head tfhead <+> text "where") nestDepth (vcat (map ppr_eqn eqns)) where ppr_eqn (TySynEqn lhs rhs) = ppr tc <+> sep (map pprParendType lhs) <+> text "=" <+> ppr rhs ppr_dec _ (RoleAnnotD name roles) = hsep [ text "type role", ppr name ] <+> hsep (map ppr roles) ppr_dec _ (StandaloneDerivD cxt ty) = hsep [ text "deriving instance", pprCxt cxt, ppr ty ] ppr_dec _ (DefaultSigD n ty) = hsep [ text "default", pprPrefixOcc n, dcolon, ppr ty ] ppr_overlap :: Overlap -> Doc ppr_overlap o = text $ case o of Overlaps -> "{-# OVERLAPS #-}" Overlappable -> "{-# OVERLAPPABLE #-}" Overlapping -> "{-# OVERLAPPING #-}" Incoherent -> "{-# INCOHERENT #-}" ppr_data :: Doc -> Cxt -> Name -> Doc -> Maybe Kind -> [Con] -> Cxt -> Doc ppr_data maybeInst ctxt t argsDoc ksig cs decs = sep [text "data" <+> maybeInst <+> pprCxt ctxt <+> ppr t <+> argsDoc <+> ksigDoc <+> maybeWhere, nest nestDepth (sep (pref $ map ppr cs)), if null decs then empty else nest nestDepth $ text "deriving" <+> ppr_cxt_preds decs] where pref :: [Doc] -> [Doc] pref xs | isGadtDecl = xs pref [] = [] -- No constructors; can't happen in H98 pref (d:ds) = (char '=' <+> d):map (char '|' <+>) ds maybeWhere :: Doc maybeWhere | isGadtDecl = text "where" | otherwise = empty isGadtDecl :: Bool isGadtDecl = not (null cs) && all isGadtCon cs where isGadtCon (GadtC _ _ _ ) = True isGadtCon (RecGadtC _ _ _) = True isGadtCon (ForallC _ _ x ) = isGadtCon x isGadtCon _ = False ksigDoc = case ksig of Nothing -> empty Just k -> dcolon <+> ppr k ppr_newtype :: Doc -> Cxt -> Name -> Doc -> Maybe Kind -> Con -> Cxt -> Doc ppr_newtype maybeInst ctxt t argsDoc ksig c decs = sep [text "newtype" <+> maybeInst <+> pprCxt ctxt <+> ppr t <+> argsDoc <+> ksigDoc, nest 2 (char '=' <+> ppr c), if null decs then empty else nest nestDepth $ text "deriving" <+> ppr_cxt_preds decs] where ksigDoc = case ksig of Nothing -> empty Just k -> dcolon <+> ppr k ppr_tySyn :: Doc -> Name -> Doc -> Type -> Doc ppr_tySyn maybeInst t argsDoc rhs = text "type" <+> maybeInst <+> ppr t <+> argsDoc <+> text "=" <+> ppr rhs ppr_tf_head :: TypeFamilyHead -> Doc ppr_tf_head (TypeFamilyHead tc tvs res inj) = ppr tc <+> hsep (map ppr tvs) <+> ppr res <+> maybeInj where maybeInj | (Just inj') <- inj = ppr inj' | otherwise = empty ------------------------------ instance Ppr FunDep where ppr (FunDep xs ys) = hsep (map ppr xs) <+> text "->" <+> hsep (map ppr ys) ppr_list [] = empty ppr_list xs = char '|' <+> commaSep xs ------------------------------ instance Ppr FamFlavour where ppr DataFam = text "data" ppr TypeFam = text "type" ------------------------------ instance Ppr FamilyResultSig where ppr NoSig = empty ppr (KindSig k) = dcolon <+> ppr k ppr (TyVarSig bndr) = text "=" <+> ppr bndr ------------------------------ instance Ppr InjectivityAnn where ppr (InjectivityAnn lhs rhs) = char '|' <+> ppr lhs <+> text "->" <+> hsep (map ppr rhs) ------------------------------ instance Ppr Foreign where ppr (ImportF callconv safety impent as typ) = text "foreign import" <+> showtextl callconv <+> showtextl safety <+> text (show impent) <+> ppr as <+> dcolon <+> ppr typ ppr (ExportF callconv expent as typ) = text "foreign export" <+> showtextl callconv <+> text (show expent) <+> ppr as <+> dcolon <+> ppr typ ------------------------------ instance Ppr Pragma where ppr (InlineP n inline rm phases) = text "{-#" <+> ppr inline <+> ppr rm <+> ppr phases <+> ppr n <+> text "#-}" ppr (SpecialiseP n ty inline phases) = text "{-# SPECIALISE" <+> maybe empty ppr inline <+> ppr phases <+> sep [ ppr n <+> dcolon , nest 2 $ ppr ty ] <+> text "#-}" ppr (SpecialiseInstP inst) = text "{-# SPECIALISE instance" <+> ppr inst <+> text "#-}" ppr (RuleP n bndrs lhs rhs phases) = sep [ text "{-# RULES" <+> pprString n <+> ppr phases , nest 4 $ ppr_forall <+> ppr lhs , nest 4 $ char '=' <+> ppr rhs <+> text "#-}" ] where ppr_forall | null bndrs = empty | otherwise = text "forall" <+> fsep (map ppr bndrs) <+> char '.' ppr (AnnP tgt expr) = text "{-# ANN" <+> target1 tgt <+> ppr expr <+> text "#-}" where target1 ModuleAnnotation = text "module" target1 (TypeAnnotation t) = text "type" <+> ppr t target1 (ValueAnnotation v) = ppr v ppr (LineP line file) = text "{-# LINE" <+> int line <+> text (show file) <+> text "#-}" ------------------------------ instance Ppr Inline where ppr NoInline = text "NOINLINE" ppr Inline = text "INLINE" ppr Inlinable = text "INLINABLE" ------------------------------ instance Ppr RuleMatch where ppr ConLike = text "CONLIKE" ppr FunLike = empty ------------------------------ instance Ppr Phases where ppr AllPhases = empty ppr (FromPhase i) = brackets $ int i ppr (BeforePhase i) = brackets $ char '~' <> int i ------------------------------ instance Ppr RuleBndr where ppr (RuleVar n) = ppr n ppr (TypedRuleVar n ty) = parens $ ppr n <+> dcolon <+> ppr ty ------------------------------ instance Ppr Clause where ppr (Clause ps rhs ds) = hsep (map (pprPat appPrec) ps) <+> pprBody True rhs $$ where_clause ds ------------------------------ instance Ppr Con where ppr (NormalC c sts) = ppr c <+> sep (map pprBangType sts) ppr (RecC c vsts) = ppr c <+> braces (sep (punctuate comma $ map pprVarBangType vsts)) ppr (InfixC st1 c st2) = pprBangType st1 <+> pprName' Infix c <+> pprBangType st2 ppr (ForallC ns ctxt (GadtC c sts ty)) = commaSepApplied c <+> dcolon <+> pprForall ns ctxt <+> pprGadtRHS sts ty ppr (ForallC ns ctxt (RecGadtC c vsts ty)) = commaSepApplied c <+> dcolon <+> pprForall ns ctxt <+> pprRecFields vsts ty ppr (ForallC ns ctxt con) = pprForall ns ctxt <+> ppr con ppr (GadtC c sts ty) = commaSepApplied c <+> dcolon <+> pprGadtRHS sts ty ppr (RecGadtC c vsts ty) = commaSepApplied c <+> dcolon <+> pprRecFields vsts ty commaSepApplied :: [Name] -> Doc commaSepApplied = commaSepWith (pprName' Applied) pprForall :: [TyVarBndr] -> Cxt -> Doc pprForall ns ctxt = text "forall" <+> hsep (map ppr ns) <+> char '.' <+> pprCxt ctxt pprRecFields :: [(Name, Strict, Type)] -> Type -> Doc pprRecFields vsts ty = braces (sep (punctuate comma $ map pprVarBangType vsts)) <+> arrow <+> ppr ty pprGadtRHS :: [(Strict, Type)] -> Type -> Doc pprGadtRHS [] ty = ppr ty pprGadtRHS sts ty = sep (punctuate (space <> arrow) (map pprBangType sts)) <+> arrow <+> ppr ty ------------------------------ pprVarBangType :: VarBangType -> Doc -- Slight infelicity: with print non-atomic type with parens pprVarBangType (v, bang, t) = ppr v <+> dcolon <+> pprBangType (bang, t) ------------------------------ pprBangType :: BangType -> Doc -- Make sure we print -- -- Con {-# UNPACK #-} a -- -- rather than -- -- Con {-# UNPACK #-}a -- -- when there's no strictness annotation. If there is a strictness annotation, -- it's okay to not put a space between it and the type. pprBangType (bt@(Bang _ NoSourceStrictness), t) = ppr bt <+> pprParendType t pprBangType (bt, t) = ppr bt <> pprParendType t ------------------------------ instance Ppr Bang where ppr (Bang su ss) = ppr su <+> ppr ss ------------------------------ instance Ppr SourceUnpackedness where ppr NoSourceUnpackedness = empty ppr SourceNoUnpack = text "{-# NOUNPACK #-}" ppr SourceUnpack = text "{-# UNPACK #-}" ------------------------------ instance Ppr SourceStrictness where ppr NoSourceStrictness = empty ppr SourceLazy = char '~' ppr SourceStrict = char '!' ------------------------------ instance Ppr DecidedStrictness where ppr DecidedLazy = empty ppr DecidedStrict = char '!' ppr DecidedUnpack = text "{-# UNPACK #-} !" ------------------------------ {-# DEPRECATED pprVarStrictType "As of @template-haskell-2.11.0.0@, 'VarStrictType' has been replaced by 'VarBangType'. Please use 'pprVarBangType' instead." #-} pprVarStrictType :: (Name, Strict, Type) -> Doc pprVarStrictType = pprVarBangType ------------------------------ {-# DEPRECATED pprStrictType "As of @template-haskell-2.11.0.0@, 'StrictType' has been replaced by 'BangType'. Please use 'pprBangType' instead." #-} pprStrictType :: (Strict, Type) -> Doc pprStrictType = pprBangType ------------------------------ pprParendType :: Type -> Doc pprParendType (VarT v) = ppr v pprParendType (ConT c) = ppr c pprParendType (TupleT 0) = text "()" pprParendType (TupleT n) = parens (hcat (replicate (n-1) comma)) pprParendType (UnboxedTupleT n) = hashParens $ hcat $ replicate (n-1) comma pprParendType ArrowT = parens (text "->") pprParendType ListT = text "[]" pprParendType (LitT l) = pprTyLit l pprParendType (PromotedT c) = text "'" <> ppr c pprParendType (PromotedTupleT 0) = text "'()" pprParendType (PromotedTupleT n) = quoteParens (hcat (replicate (n-1) comma)) pprParendType PromotedNilT = text "'[]" pprParendType PromotedConsT = text "(':)" pprParendType StarT = char '*' pprParendType ConstraintT = text "Constraint" pprParendType (SigT ty k) = parens (ppr ty <+> text "::" <+> ppr k) pprParendType WildCardT = char '_' pprParendType (InfixT x n y) = parens (ppr x <+> pprName' Infix n <+> ppr y) pprParendType t@(UInfixT {}) = parens (pprUInfixT t) pprParendType (ParensT t) = ppr t pprParendType tuple | (TupleT n, args) <- split tuple , length args == n = parens (commaSep args) pprParendType other = parens (ppr other) pprUInfixT :: Type -> Doc pprUInfixT (UInfixT x n y) = pprUInfixT x <+> pprName' Infix n <+> pprUInfixT y pprUInfixT t = ppr t instance Ppr Type where ppr (ForallT tvars ctxt ty) = text "forall" <+> hsep (map ppr tvars) <+> text "." <+> sep [pprCxt ctxt, ppr ty] ppr ty = pprTyApp (split ty) -- Works, in a degnerate way, for SigT, and puts parens round (ty :: kind) -- See Note [Pretty-printing kind signatures] {- Note [Pretty-printing kind signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC's parser only recognises a kind signature in a type when there are parens around it. E.g. the parens are required here: f :: (Int :: *) type instance F Int = (Bool :: *) So we always print a SigT with parens (see Trac #10050). -} pprTyApp :: (Type, [Type]) -> Doc pprTyApp (ArrowT, [arg1,arg2]) = sep [pprFunArgType arg1 <+> text "->", ppr arg2] pprTyApp (EqualityT, [arg1, arg2]) = sep [pprFunArgType arg1 <+> text "~", ppr arg2] pprTyApp (ListT, [arg]) = brackets (ppr arg) pprTyApp (TupleT n, args) | length args == n = parens (commaSep args) pprTyApp (PromotedTupleT n, args) | length args == n = quoteParens (commaSep args) pprTyApp (fun, args) = pprParendType fun <+> sep (map pprParendType args) pprFunArgType :: Type -> Doc -- Should really use a precedence argument -- Everything except forall and (->) binds more tightly than (->) pprFunArgType ty@(ForallT {}) = parens (ppr ty) pprFunArgType ty@((ArrowT `AppT` _) `AppT` _) = parens (ppr ty) pprFunArgType ty@(SigT _ _) = parens (ppr ty) pprFunArgType ty = ppr ty split :: Type -> (Type, [Type]) -- Split into function and args split t = go t [] where go (AppT t1 t2) args = go t1 (t2:args) go ty args = (ty, args) pprTyLit :: TyLit -> Doc pprTyLit (NumTyLit n) = integer n pprTyLit (StrTyLit s) = text (show s) instance Ppr TyLit where ppr = pprTyLit ------------------------------ instance Ppr TyVarBndr where ppr (PlainTV nm) = ppr nm ppr (KindedTV nm k) = parens (ppr nm <+> dcolon <+> ppr k) instance Ppr Role where ppr NominalR = text "nominal" ppr RepresentationalR = text "representational" ppr PhantomR = text "phantom" ppr InferR = text "_" ------------------------------ pprCxt :: Cxt -> Doc pprCxt [] = empty pprCxt ts = ppr_cxt_preds ts <+> text "=>" ppr_cxt_preds :: Cxt -> Doc ppr_cxt_preds [] = empty ppr_cxt_preds [t] = ppr t ppr_cxt_preds ts = parens (commaSep ts) ------------------------------ instance Ppr Range where ppr = brackets . pprRange where pprRange :: Range -> Doc pprRange (FromR e) = ppr e <> text ".." pprRange (FromThenR e1 e2) = ppr e1 <> text "," <> ppr e2 <> text ".." pprRange (FromToR e1 e2) = ppr e1 <> text ".." <> ppr e2 pprRange (FromThenToR e1 e2 e3) = ppr e1 <> text "," <> ppr e2 <> text ".." <> ppr e3 ------------------------------ where_clause :: [Dec] -> Doc where_clause [] = empty where_clause ds = nest nestDepth $ text "where" <+> vcat (map (ppr_dec False) ds) showtextl :: Show a => a -> Doc showtextl = text . map toLower . show hashParens :: Doc -> Doc hashParens d = text "(# " <> d <> text " #)" quoteParens :: Doc -> Doc quoteParens d = text "'(" <> d <> text ")" ----------------------------- instance Ppr Loc where ppr (Loc { loc_module = md , loc_package = pkg , loc_start = (start_ln, start_col) , loc_end = (end_ln, end_col) }) = hcat [ text pkg, colon, text md, colon , parens $ int start_ln <> comma <> int start_col , text "-" , parens $ int end_ln <> comma <> int end_col ] -- Takes a list of printable things and prints them separated by commas followed -- by space. commaSep :: Ppr a => [a] -> Doc commaSep = commaSepWith ppr -- Takes a list of things and prints them with the given pretty-printing -- function, separated by commas followed by space. commaSepWith :: (a -> Doc) -> [a] -> Doc commaSepWith pprFun = sep . punctuate comma . map pprFun -- Takes a list of printable things and prints them separated by semicolons -- followed by space. semiSep :: Ppr a => [a] -> Doc semiSep = sep . punctuate semi . map ppr
GaloisInc/halvm-ghc
libraries/template-haskell/Language/Haskell/TH/Ppr.hs
Haskell
bsd-3-clause
28,065
{-# LANGUAGE CPP, BangPatterns #-} {-# OPTIONS -Wall #-} ----------------------------------------------------------------------------- -- | -- Module : Language.CFamily.Data.InputStream -- Copyright : (c) 2008,2011 Benedikt Huber -- License : BSD-style -- Maintainer : benedikt.huber@gmail.com -- Stability : experimental -- Portability : ghc -- -- Compile time input abstraction for the parser, relying on ByteString. -- The String interface only supports Latin-1 since alex-3, as alex now requires -- byte based access to the input stream. ------------------------------------------------------------------------------- module Language.CFamily.Data.InputStream ( InputStream, readInputStream,inputStreamToString,inputStreamFromString, takeByte, takeChar, inputStreamEmpty, takeChars, countLines, ) where import Data.Word #ifndef NO_BYTESTRING import Data.ByteString (ByteString) import qualified Data.ByteString as BSW import qualified Data.ByteString.Char8 as BSC #else import qualified Data.Char as Char #endif -- Generic InputStream stuff -- | read a file into an 'InputStream' readInputStream :: FilePath -> IO InputStream -- | convert 'InputStream' to 'String' inputStreamToString :: InputStream -> String {-# INLINE inputStreamToString #-} -- | convert a 'String' to an 'InputStream' inputStreamFromString :: String -> InputStream -- | @(b,is') = takeByte is@ reads and removes -- the first byte @b@ from the 'InputStream' @is@ takeByte :: InputStream -> (Word8, InputStream) {-# INLINE takeByte #-} -- | @(c,is') = takeChar is@ reads and removes -- the first character @c@ from the 'InputStream' @is@ takeChar :: InputStream -> (Char, InputStream) {-# INLINE takeChar #-} -- | return @True@ if the given input stream is empty inputStreamEmpty :: InputStream -> Bool {-# INLINE inputStreamEmpty #-} -- | @str = takeChars n is@ returns the first @n@ characters -- of the given input stream, without removing them takeChars :: Int -> InputStream -> [Char] {-# INLINE takeChars #-} -- | @countLines@ returns the number of text lines in the -- given 'InputStream' countLines :: InputStream -> Int #ifndef NO_BYTESTRING type InputStream = ByteString takeByte bs = BSW.head bs `seq` (BSW.head bs, BSW.tail bs) takeChar bs = BSC.head bs `seq` (BSC.head bs, BSC.tail bs) inputStreamEmpty = BSW.null #ifndef __HADDOCK__ takeChars !n bstr = BSC.unpack $ BSC.take n bstr --leaks #endif readInputStream = BSW.readFile inputStreamToString = BSC.unpack inputStreamFromString = BSC.pack countLines = length . BSC.lines #else type InputStream = String takeByte bs | Char.isLatin1 c = let b = fromIntegral (Char.ord c) in b `seq` (b, tail bs) | otherwise = error "takeByte: not a latin-1 character" where c = head bs takeChar bs = (head bs, tail bs) inputStreamEmpty = null takeChars n str = take n str readInputStream = readFile inputStreamToString = id inputStreamFromString = id countLines = length . lines #endif
micknelso/language-c
src/Language/CFamily/Data/InputStream.hs
Haskell
bsd-3-clause
2,994
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances, ViewPatterns #-} ----------------------------------------------------------------------------- -- | -- Module : Data.HyperDex.Client -- Copyright : (c) Aaron Friel 2013 -- License : BSD-style -- Maintainer : mayreply@aaronfriel.com -- Stability : maybe -- Portability : portable -- -- UTF8 String and Text support for HyperDex. -- -- A helper function to create attributes is exported. -- ----------------------------------------------------------------------------- module Database.HyperDex.Utf8 ( mkAttributeUtf8 , mkAttributeCheckUtf8 , mkMapAttributeUtf8 , mkMapAttributesFromMapUtf8 ) where import Database.HyperDex.Internal.Data.Attribute import Database.HyperDex.Internal.Data.AttributeCheck import Database.HyperDex.Internal.Data.MapAttribute import Database.HyperDex.Internal.Serialize import Database.HyperDex.Internal.Data.Hyperdex import Data.Serialize import Data.Text (Text) import qualified Data.Text as Text import Data.Text.Encoding import Data.Map (Map) instance HyperSerialize [Char] where getH = remaining >>= getByteString >>= return . Text.unpack . decodeUtf8 putH = putByteString . encodeUtf8 . Text.pack datatype = const HyperdatatypeString instance HyperSerialize Text where getH = remaining >>= getByteString >>= return . decodeUtf8 putH = putByteString . encodeUtf8 datatype = const HyperdatatypeString -- | Create an attribute using a name serialized as a UTF8 bytestring. mkAttributeUtf8 :: HyperSerialize a => Text -> a -> Attribute mkAttributeUtf8 (encodeUtf8 -> name) value = mkAttribute name value -- | Create an attribute using a name serialized as a UTF8 bytestring. mkAttributeCheckUtf8 :: HyperSerialize a => Text -> a -> Hyperpredicate -> AttributeCheck mkAttributeCheckUtf8 (encodeUtf8 -> name) = mkAttributeCheck name -- | Create an attribute using a name serialized as a UTF8 bytestring. mkMapAttributeUtf8 :: (HyperSerialize k, HyperSerialize v) => Text -> k -> v -> MapAttribute mkMapAttributeUtf8 (encodeUtf8 -> name) = mkMapAttribute name -- | Create an attribute using a name serialized as a UTF8 bytestring. mkMapAttributesFromMapUtf8 :: (HyperSerialize k, HyperSerialize v) => Text -> Map k v -> [MapAttribute] mkMapAttributesFromMapUtf8 = mkMapAttributesFromMap . encodeUtf8
AaronFriel/hyhac
src/Database/HyperDex/Utf8.hs
Haskell
bsd-3-clause
2,349
module Automata where import Sets -- Estrutura de um automato finito nao deterministico data Nfa a = NFA (Set a) (Set (Move a)) a (Set a) deriving (Eq, Show) -- data Move a = Move a Char a |Emove a a deriving (Eq, Ord, Show) startstate :: Nfa a -> a startstate (NFA s mov start final) = start states :: Nfa a -> Set a states (NFA s mov start final) = s moves :: Nfa a -> Set (Move a) moves (NFA s mov start final) = mov finishstates :: Nfa a -> Set a finishstates (NFA s mov start final) = final trans :: Ord a => Nfa a -> String -> Set a trans mach = foldl step startset where step set ch = onetrans mach ch set startset = closure mach (sing (startstate mach)) trans2 :: Ord a => Nfa a -> String -> [(String,Set a)] trans2 mach = transAux mach "" where transAux mach str [] = [(str,trans mach str)] transAux mach str (y:ys) = (str,trans mach str) : transAux mach (str ++ [y]) ys lastMatch :: Ord a => Nfa a -> String -> (String,Set a) lastMatch mach str = lastM where fim = finishstates mach matches = trans2 mach str notEmpty = filter (not . isEmpty . inter fim . snd) matches lastM = if null notEmpty then ("", empty) else last notEmpty onetrans :: Ord a => Nfa a -> Char -> Set a -> Set a onetrans mach c x = closure mach (onemove mach c x) onetrans2 :: Ord a => Nfa a -> Char -> Set a -> (Set a,Set a) onetrans2 mach@(NFA states moves start term) c x = (r,f) where r = closure mach (onemove mach c x) f = inter r term onemove :: Ord a => Nfa a -> Char -> Set a -> Set a onemove (NFA states moves start term) c x = makeSet [s | t <- flatten x, Move z d s <- flatten moves, z == t, c == d] closure :: Ord a => Nfa a -> Set a -> Set a closure (NFA states moves start term) = setlimit add where add stateset = stateset `union` makeSet accessible where accessible = [s | x <- flatten stateset, Emove y s <- flatten moves, y == x] printNfa :: (Show a) => Nfa a -> String printNfa (NFA states moves start finish) = "States:\t" ++ showStates (flatten states) ++ "\n" ++ "Moves:\n" ++ concatMap printMove (flatten moves) ++ "\n" ++ "Start:\t" ++ show start ++ "\n" ++ "Finish:\t" ++ showStates (flatten finish) ++ "\n" showStates :: (Show a) => [a] -> String showStates = concatMap ((++ " ") . show) printMove :: (Show a) => Move a -> String printMove (Move s1 c s2) = "\t" ++ show s1 ++ "----(" ++ [c] ++ ")---->" ++ show s2 ++ "\n" printMove (Emove s1 s2) = "\t" ++ show s1 ++ "----(@)---->" ++ show s2 ++ "\n"
arthurmgo/regex-ftc
src/Automata.hs
Haskell
bsd-3-clause
2,764
module DropNth where --(Problem 16) Drop every N'th element from a list. dropNth :: [a] -> Int -> [a] dropNth [] _ = [] dropNth y@(x:xs) n = (take (n - 1) y) ++ dropNth (drop 2 xs) n
michael-j-clark/hjs99
src/11to20/DropNth.hs
Haskell
bsd-3-clause
188
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ScopedTypeVariables #-} -- | See "Control.Monad.Ether.Reader". module Control.Monad.Ether.Implicit.Reader ( -- * MonadReader class MonadReader , local , ask , reader , asks -- * The Reader monad , Reader , runReader -- * The ReaderT monad transformer , ReaderT , readerT , runReaderT ) where import Data.Proxy import qualified Control.Monad.Ether.Reader as Explicit -- | See 'Control.Monad.Ether.Reader.ReaderT'. type ReaderT r = Explicit.ReaderT r r -- | See 'Control.Monad.Ether.Reader.Reader'. type Reader r = Explicit.Reader r r -- | See 'Control.Monad.Ether.Reader.readerT'. readerT :: (r -> m a) -> ReaderT r m a readerT = Explicit.readerT Proxy -- | See 'Control.Monad.Ether.Reader.runReaderT'. runReaderT :: ReaderT r m a -> r -> m a runReaderT = Explicit.runReaderT Proxy -- | See 'Control.Monad.Ether.Reader.runReader'. runReader :: Reader r a -> r -> a runReader = Explicit.runReader Proxy -- | See 'Control.Monad.Ether.Reader.MonadReader'. type MonadReader r = Explicit.MonadReader r r -- | See 'Control.Monad.Ether.Reader.local'. local :: forall m r a . MonadReader r m => (r -> r) -> m a -> m a local = Explicit.local (Proxy :: Proxy r) -- | See 'Control.Monad.Ether.Reader.ask'. ask :: forall m r . MonadReader r m => m r ask = Explicit.ask (Proxy :: Proxy r) -- | See 'Control.Monad.Ether.Reader.reader'. reader :: forall m r a . MonadReader r m => (r -> a) -> m a reader = Explicit.reader (Proxy :: Proxy r) -- | See 'Control.Monad.Ether.Reader.asks'. asks :: forall m r a . MonadReader r m => (r -> a) -> m a asks = Explicit.asks (Proxy :: Proxy r)
bitemyapp/ether
src/Control/Monad/Ether/Implicit/Reader.hs
Haskell
bsd-3-clause
1,690
{-# OPTIONS_GHC -fno-warn-orphans #-} module Data.MessagePack.Types.Instances () where import Data.Void (Void) import Data.MessagePack.Types.Class (MessagePack) import Data.MessagePack.Types.Generic () instance MessagePack a => MessagePack (Maybe a) instance (MessagePack a, MessagePack b) => MessagePack (Either a b) instance MessagePack Void
SX91/hs-msgpack-types
src/Data/MessagePack/Types/Instances.hs
Haskell
bsd-3-clause
403
{-# LANGUAGE DoRec #-} module LazyRec where import Control.Monad.Trans.Writer import Data.Maybe type Symbol = String type Line = Int type SymData = (Symbol, Line) type Stmt = (SymData, [String]) type Prog = [Stmt] prog :: Prog prog = [ (("alma", 1), ["korte", "alma"]) , (("korte", 2), ["szilva"]) , (("szilva", 3), ["alma"]) ] type Ref = (Symbol, SymData) refek :: Prog -> [Ref] refek stmts = let (allSyms, refs) = unzip $ map (stmtRefek allSyms) stmts in concat refs stmtRefek :: [SymData] -> Stmt -> (SymData, [Ref]) stmtRefek allSymData (symData, usedSyms) = let thisSym = fst symData addThisSym = map ((,) thisSym) refs = addThisSym $ catMaybes $ map resolveSym usedSyms in (symData, refs) where resolveSym s = listToMaybe $ filter (\sd -> fst sd == s) allSymData stmtRefekM :: [SymData] -> Stmt -> Writer [Ref] SymData stmtRefekM allSymData stmt = writer $ stmtRefek allSymData stmt refekM :: Prog -> [Ref] refekM stmts = let (allSyms, refs) = runWriter $ mapM (stmtRefekM allSyms) stmts in refs refekM2 :: Prog -> [Ref] refekM2 stmts = snd . runWriter $ do rec allSyms <- mapM (stmtRefekM allSyms) stmts return allSyms main = do --mapM_ print $ refek prog mapM_ print $ refekM2 prog
robinp/haskell-toys
src/Toys/LazyRec.hs
Haskell
bsd-3-clause
1,248
module Win32Font {- ( CharSet , PitchAndFamily , OutPrecision , ClipPrecision , FontQuality , FontWeight , createFont, deleteFont , StockFont, getStockFont , oEM_FIXED_FONT, aNSI_FIXED_FONT, aNSI_VAR_FONT, sYSTEM_FONT , dEVICE_DEFAULT_FONT, sYSTEM_FIXED_FONT ) where -} where import StdDIS import Win32Types import GDITypes ---------------------------------------------------------------- -- Types ---------------------------------------------------------------- type CharSet = UINT type PitchAndFamily = UINT type OutPrecision = UINT type ClipPrecision = UINT type FontQuality = UINT type FontWeight = Word32 type FaceName = String -- # A FaceName is a string no more that LF_FACESIZE in length -- # (including null terminator). -- %const Int LF_FACESIZE # == 32 -- %sentinel_array : FaceName : CHAR : char : $0 = '\0' : ('\0' == $0) : LF_FACESIZE ---------------------------------------------------------------- -- Constants ---------------------------------------------------------------- aNSI_CHARSET :: CharSet aNSI_CHARSET = unsafePerformIO( prim_Win32Font_cpp_aNSI_CHARSET >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_aNSI_CHARSET :: IO (Word32) dEFAULT_CHARSET :: CharSet dEFAULT_CHARSET = unsafePerformIO( prim_Win32Font_cpp_dEFAULT_CHARSET >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_dEFAULT_CHARSET :: IO (Word32) sYMBOL_CHARSET :: CharSet sYMBOL_CHARSET = unsafePerformIO( prim_Win32Font_cpp_sYMBOL_CHARSET >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_sYMBOL_CHARSET :: IO (Word32) sHIFTJIS_CHARSET :: CharSet sHIFTJIS_CHARSET = unsafePerformIO( prim_Win32Font_cpp_sHIFTJIS_CHARSET >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_sHIFTJIS_CHARSET :: IO (Word32) hANGEUL_CHARSET :: CharSet hANGEUL_CHARSET = unsafePerformIO( prim_Win32Font_cpp_hANGEUL_CHARSET >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_hANGEUL_CHARSET :: IO (Word32) cHINESEBIG5_CHARSET :: CharSet cHINESEBIG5_CHARSET = unsafePerformIO( prim_Win32Font_cpp_cHINESEBIG5_CHARSET >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_cHINESEBIG5_CHARSET :: IO (Word32) oEM_CHARSET :: CharSet oEM_CHARSET = unsafePerformIO( prim_Win32Font_cpp_oEM_CHARSET >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_oEM_CHARSET :: IO (Word32) dEFAULT_PITCH :: PitchAndFamily dEFAULT_PITCH = unsafePerformIO( prim_Win32Font_cpp_dEFAULT_PITCH >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_dEFAULT_PITCH :: IO (Word32) fIXED_PITCH :: PitchAndFamily fIXED_PITCH = unsafePerformIO( prim_Win32Font_cpp_fIXED_PITCH >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fIXED_PITCH :: IO (Word32) vARIABLE_PITCH :: PitchAndFamily vARIABLE_PITCH = unsafePerformIO( prim_Win32Font_cpp_vARIABLE_PITCH >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_vARIABLE_PITCH :: IO (Word32) fF_DONTCARE :: PitchAndFamily fF_DONTCARE = unsafePerformIO( prim_Win32Font_cpp_fF_DONTCARE >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fF_DONTCARE :: IO (Word32) fF_ROMAN :: PitchAndFamily fF_ROMAN = unsafePerformIO( prim_Win32Font_cpp_fF_ROMAN >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fF_ROMAN :: IO (Word32) fF_SWISS :: PitchAndFamily fF_SWISS = unsafePerformIO( prim_Win32Font_cpp_fF_SWISS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fF_SWISS :: IO (Word32) fF_MODERN :: PitchAndFamily fF_MODERN = unsafePerformIO( prim_Win32Font_cpp_fF_MODERN >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fF_MODERN :: IO (Word32) fF_SCRIPT :: PitchAndFamily fF_SCRIPT = unsafePerformIO( prim_Win32Font_cpp_fF_SCRIPT >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fF_SCRIPT :: IO (Word32) fF_DECORATIVE :: PitchAndFamily fF_DECORATIVE = unsafePerformIO( prim_Win32Font_cpp_fF_DECORATIVE >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fF_DECORATIVE :: IO (Word32) familyMask :: PitchAndFamily familyMask = unsafePerformIO( prim_Win32Font_cpp_familyMask >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_familyMask :: IO (Word32) pitchMask :: PitchAndFamily pitchMask = unsafePerformIO( prim_Win32Font_cpp_pitchMask >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_pitchMask :: IO (Word32) oUT_DEFAULT_PRECIS :: OutPrecision oUT_DEFAULT_PRECIS = unsafePerformIO( prim_Win32Font_cpp_oUT_DEFAULT_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_oUT_DEFAULT_PRECIS :: IO (Word32) oUT_STRING_PRECIS :: OutPrecision oUT_STRING_PRECIS = unsafePerformIO( prim_Win32Font_cpp_oUT_STRING_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_oUT_STRING_PRECIS :: IO (Word32) oUT_CHARACTER_PRECIS :: OutPrecision oUT_CHARACTER_PRECIS = unsafePerformIO( prim_Win32Font_cpp_oUT_CHARACTER_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_oUT_CHARACTER_PRECIS :: IO (Word32) oUT_STROKE_PRECIS :: OutPrecision oUT_STROKE_PRECIS = unsafePerformIO( prim_Win32Font_cpp_oUT_STROKE_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_oUT_STROKE_PRECIS :: IO (Word32) oUT_TT_PRECIS :: OutPrecision oUT_TT_PRECIS = unsafePerformIO( prim_Win32Font_cpp_oUT_TT_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_oUT_TT_PRECIS :: IO (Word32) oUT_DEVICE_PRECIS :: OutPrecision oUT_DEVICE_PRECIS = unsafePerformIO( prim_Win32Font_cpp_oUT_DEVICE_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_oUT_DEVICE_PRECIS :: IO (Word32) oUT_RASTER_PRECIS :: OutPrecision oUT_RASTER_PRECIS = unsafePerformIO( prim_Win32Font_cpp_oUT_RASTER_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_oUT_RASTER_PRECIS :: IO (Word32) oUT_TT_ONLY_PRECIS :: OutPrecision oUT_TT_ONLY_PRECIS = unsafePerformIO( prim_Win32Font_cpp_oUT_TT_ONLY_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_oUT_TT_ONLY_PRECIS :: IO (Word32) cLIP_DEFAULT_PRECIS :: ClipPrecision cLIP_DEFAULT_PRECIS = unsafePerformIO( prim_Win32Font_cpp_cLIP_DEFAULT_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_cLIP_DEFAULT_PRECIS :: IO (Word32) cLIP_CHARACTER_PRECIS :: ClipPrecision cLIP_CHARACTER_PRECIS = unsafePerformIO( prim_Win32Font_cpp_cLIP_CHARACTER_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_cLIP_CHARACTER_PRECIS :: IO (Word32) cLIP_STROKE_PRECIS :: ClipPrecision cLIP_STROKE_PRECIS = unsafePerformIO( prim_Win32Font_cpp_cLIP_STROKE_PRECIS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_cLIP_STROKE_PRECIS :: IO (Word32) cLIP_MASK :: ClipPrecision cLIP_MASK = unsafePerformIO( prim_Win32Font_cpp_cLIP_MASK >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_cLIP_MASK :: IO (Word32) cLIP_LH_ANGLES :: ClipPrecision cLIP_LH_ANGLES = unsafePerformIO( prim_Win32Font_cpp_cLIP_LH_ANGLES >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_cLIP_LH_ANGLES :: IO (Word32) cLIP_TT_ALWAYS :: ClipPrecision cLIP_TT_ALWAYS = unsafePerformIO( prim_Win32Font_cpp_cLIP_TT_ALWAYS >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_cLIP_TT_ALWAYS :: IO (Word32) cLIP_EMBEDDED :: ClipPrecision cLIP_EMBEDDED = unsafePerformIO( prim_Win32Font_cpp_cLIP_EMBEDDED >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_cLIP_EMBEDDED :: IO (Word32) dEFAULT_QUALITY :: FontQuality dEFAULT_QUALITY = unsafePerformIO( prim_Win32Font_cpp_dEFAULT_QUALITY >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_dEFAULT_QUALITY :: IO (Word32) dRAFT_QUALITY :: FontQuality dRAFT_QUALITY = unsafePerformIO( prim_Win32Font_cpp_dRAFT_QUALITY >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_dRAFT_QUALITY :: IO (Word32) pROOF_QUALITY :: FontQuality pROOF_QUALITY = unsafePerformIO( prim_Win32Font_cpp_pROOF_QUALITY >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_pROOF_QUALITY :: IO (Word32) fW_DONTCARE :: FontWeight fW_DONTCARE = unsafePerformIO( prim_Win32Font_cpp_fW_DONTCARE >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_DONTCARE :: IO (Word32) fW_THIN :: FontWeight fW_THIN = unsafePerformIO( prim_Win32Font_cpp_fW_THIN >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_THIN :: IO (Word32) fW_EXTRALIGHT :: FontWeight fW_EXTRALIGHT = unsafePerformIO( prim_Win32Font_cpp_fW_EXTRALIGHT >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_EXTRALIGHT :: IO (Word32) fW_LIGHT :: FontWeight fW_LIGHT = unsafePerformIO( prim_Win32Font_cpp_fW_LIGHT >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_LIGHT :: IO (Word32) fW_NORMAL :: FontWeight fW_NORMAL = unsafePerformIO( prim_Win32Font_cpp_fW_NORMAL >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_NORMAL :: IO (Word32) fW_MEDIUM :: FontWeight fW_MEDIUM = unsafePerformIO( prim_Win32Font_cpp_fW_MEDIUM >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_MEDIUM :: IO (Word32) fW_SEMIBOLD :: FontWeight fW_SEMIBOLD = unsafePerformIO( prim_Win32Font_cpp_fW_SEMIBOLD >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_SEMIBOLD :: IO (Word32) fW_BOLD :: FontWeight fW_BOLD = unsafePerformIO( prim_Win32Font_cpp_fW_BOLD >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_BOLD :: IO (Word32) fW_EXTRABOLD :: FontWeight fW_EXTRABOLD = unsafePerformIO( prim_Win32Font_cpp_fW_EXTRABOLD >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_EXTRABOLD :: IO (Word32) fW_HEAVY :: FontWeight fW_HEAVY = unsafePerformIO( prim_Win32Font_cpp_fW_HEAVY >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_HEAVY :: IO (Word32) fW_REGULAR :: FontWeight fW_REGULAR = unsafePerformIO( prim_Win32Font_cpp_fW_REGULAR >>= \ (res1) -> (return (res1))) primitive prim_Win32Font_cpp_fW_REGULAR :: IO (Word32) ---------------------------------------------------------------- -- Functions ---------------------------------------------------------------- createFont :: INT -> INT -> INT -> INT -> FontWeight -> Bool -> Bool -> Bool -> CharSet -> OutPrecision -> ClipPrecision -> FontQuality -> PitchAndFamily -> FaceName -> IO HFONT createFont gc_arg1 gc_arg2 gc_arg3 gc_arg4 arg5 gc_arg5 gc_arg6 gc_arg7 arg9 arg10 arg11 arg12 arg13 gc_arg8 = case ( fromIntegral gc_arg1) of { arg1 -> case ( fromIntegral gc_arg2) of { arg2 -> case ( fromIntegral gc_arg3) of { arg3 -> case ( fromIntegral gc_arg4) of { arg4 -> (marshall_bool_ gc_arg5) >>= \ (arg6) -> (marshall_bool_ gc_arg6) >>= \ (arg7) -> (marshall_bool_ gc_arg7) >>= \ (arg8) -> (marshall_string_ gc_arg8) >>= \ (arg14) -> prim_Win32Font_cpp_createFont arg1 arg2 arg3 arg4 arg5 arg6 arg7 arg8 arg9 arg10 arg11 arg12 arg13 arg14 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1))}}}} primitive prim_Win32Font_cpp_createFont :: Int -> Int -> Int -> Int -> Word32 -> Int -> Int -> Int -> Word32 -> Word32 -> Word32 -> Word32 -> Word32 -> Addr -> IO (Addr,Int,Addr) -- test :: IO () -- test = do -- f <- createFont_adr (100,100) 0 False False "Arial" -- putStrLn "Created first font" -- f <- createFont_adr (100,100) (-90) False False "Bogus" -- putStrLn "Created second font" -- -- createFont_adr (width, height) escapement bold italic family = -- createFont height width -- (round (escapement * 1800/pi)) -- 0 -- orientation -- weight -- italic False False -- italic, underline, strikeout -- aNSI_CHARSET -- oUT_DEFAULT_PRECIS -- cLIP_DEFAULT_PRECIS -- dEFAULT_QUALITY -- dEFAULT_PITCH -- family -- where -- weight | bold = fW_BOLD -- | otherwise = fW_NORMAL -- missing CreateFontIndirect from WinFonts.ss; GSL ??? deleteFont :: HFONT -> IO () deleteFont arg1 = prim_Win32Font_cpp_deleteFont arg1 primitive prim_Win32Font_cpp_deleteFont :: Addr -> IO () ---------------------------------------------------------------- type StockFont = WORD oEM_FIXED_FONT :: StockFont oEM_FIXED_FONT = unsafePerformIO( prim_Win32Font_cpp_oEM_FIXED_FONT >>= \ (res1) -> let gc_res1 = ( fromIntegral (res1)) in (return (gc_res1))) primitive prim_Win32Font_cpp_oEM_FIXED_FONT :: IO (Word32) aNSI_FIXED_FONT :: StockFont aNSI_FIXED_FONT = unsafePerformIO( prim_Win32Font_cpp_aNSI_FIXED_FONT >>= \ (res1) -> let gc_res1 = ( fromIntegral (res1)) in (return (gc_res1))) primitive prim_Win32Font_cpp_aNSI_FIXED_FONT :: IO (Word32) aNSI_VAR_FONT :: StockFont aNSI_VAR_FONT = unsafePerformIO( prim_Win32Font_cpp_aNSI_VAR_FONT >>= \ (res1) -> let gc_res1 = ( fromIntegral (res1)) in (return (gc_res1))) primitive prim_Win32Font_cpp_aNSI_VAR_FONT :: IO (Word32) sYSTEM_FONT :: StockFont sYSTEM_FONT = unsafePerformIO( prim_Win32Font_cpp_sYSTEM_FONT >>= \ (res1) -> let gc_res1 = ( fromIntegral (res1)) in (return (gc_res1))) primitive prim_Win32Font_cpp_sYSTEM_FONT :: IO (Word32) dEVICE_DEFAULT_FONT :: StockFont dEVICE_DEFAULT_FONT = unsafePerformIO( prim_Win32Font_cpp_dEVICE_DEFAULT_FONT >>= \ (res1) -> let gc_res1 = ( fromIntegral (res1)) in (return (gc_res1))) primitive prim_Win32Font_cpp_dEVICE_DEFAULT_FONT :: IO (Word32) sYSTEM_FIXED_FONT :: StockFont sYSTEM_FIXED_FONT = unsafePerformIO( prim_Win32Font_cpp_sYSTEM_FIXED_FONT >>= \ (res1) -> let gc_res1 = ( fromIntegral (res1)) in (return (gc_res1))) primitive prim_Win32Font_cpp_sYSTEM_FIXED_FONT :: IO (Word32) getStockFont :: StockFont -> IO HFONT getStockFont gc_arg1 = case ( fromIntegral gc_arg1) of { arg1 -> prim_Win32Font_cpp_getStockFont arg1 >>= \ (res1) -> (return (res1))} primitive prim_Win32Font_cpp_getStockFont :: Word32 -> IO (Addr) ---------------------------------------------------------------- -- End ---------------------------------------------------------------- needPrims_hugs 2
OS2World/DEV-UTIL-HUGS
libraries/win32/Win32Font.hs
Haskell
bsd-3-clause
14,409
module Simplify where import Prelude hiding (pi, abs) import Lang.LF import Terms import qualified Debug.Trace as Debug data BindData (γ :: Ctx *) where BindEmpty :: BindData E BindLetcont :: BindData γ -> LF γ TERM {- :: v ==> term -} -> BindData (γ ::> b) BindOpaque :: BindData γ -> BindData (γ ::> b) BindLetval :: BindData γ -> Bool -- Has at most one occurance? -> Bool -- Is cheap? -> LF γ TERM {- :: val -} -> BindData (γ ::> b) BindLetproj :: BindData γ -> Bool {- False = fst, True = snd -} -> LF γ TERM {- :: v -} -> BindData (γ ::> b) lookupContData :: BindData γ -> Var γ -> Maybe (LF γ TERM) lookupContData = go WeakRefl where go :: Weakening γ γ' -> BindData γ -> Var γ -> Maybe (LF γ' TERM) go w (BindLetcont bd _) (F v) = go (WeakRight w) bd v go w (BindOpaque bd) (F v) = go (WeakRight w) bd v go w (BindLetval bd _ _ _) (F v) = go (WeakRight w) bd v go w (BindLetproj bd _ _) (F v) = go (WeakRight w) bd v go w (BindLetcont _ v) B = Just (weaken (WeakRight w) v) go _ _ _ = Nothing lookupValData :: BindData γ -> Var γ -> Maybe (Bool, Bool, LF γ TERM) lookupValData = go WeakRefl where go :: Weakening γ γ' -> BindData γ -> Var γ -> Maybe (Bool, Bool, LF γ' TERM) go w (BindLetcont bd _) (F v) = go (WeakRight w) bd v go w (BindOpaque bd) (F v) = go (WeakRight w) bd v go w (BindLetval bd _ _ _) (F v) = go (WeakRight w) bd v go w (BindLetproj bd _ _) (F v) = go (WeakRight w) bd v go w (BindLetval _ lin cheap val) B = Just (lin, cheap, weaken (WeakRight w) val) go _ _ _ = Nothing lookupProjData :: BindData γ -> Var γ -> Maybe (Bool, LF γ TERM) lookupProjData = go WeakRefl where go :: Weakening γ γ' -> BindData γ -> Var γ -> Maybe (Bool, LF γ' TERM) go w (BindLetcont bd _) (F v) = go (WeakRight w) bd v go w (BindOpaque bd) (F v) = go (WeakRight w) bd v go w (BindLetval bd _ _ _) (F v) = go (WeakRight w) bd v go w (BindLetproj bd _ _) (F v) = go (WeakRight w) bd v go w (BindLetproj _ b v) B = Just (b, weaken (WeakRight w) v) go _ _ _ = Nothing dropData :: Var γ -> Int -> BindData γ -> BindData γ dropData v n bd | n <= 1 = bd | otherwise = go bd v where go :: BindData γ -> Var γ -> BindData γ go (BindLetcont bd k) (F v) = BindLetcont (go bd v) k go (BindOpaque bd) (F v) = BindOpaque (go bd v) go (BindLetval bd lin cheap val) (F v) = BindLetval (go bd v) lin cheap val go (BindLetproj bd x y) (F v) = BindLetproj (go bd v) x y go (BindLetcont bd _) B = BindOpaque bd go (BindLetval bd _ cheap val) B = BindLetval bd False cheap val go (BindLetproj bd _ _) B = BindOpaque bd go bd _ = bd newtype InlineHeuristic = InlineHeuristic { applyHeuristic :: forall γ. LF γ TERM -> Bool } simplifier :: forall γ . (LiftClosed γ , ?hyps :: H γ , ?soln :: LFSoln LF , ?ischeap :: InlineHeuristic ) => BindData γ -> LF γ TERM -> M (LF γ TERM) simplifier bd (termView -> VConst "letcont" [k,m]) = do -- first, simplify inside the bound continuation body k' <- case termView k of VLam nm x t km -> do q <- simplifier (BindOpaque bd) km mkLam nm x t q _ -> fail "simplifier: expected function in 'letcont'" case tryEtaCont k' of Just j -> Debug.trace "η-CONT" $ do j' <- j m' <- return m @@ return j' let bd' = case termView j' of VVar vj [] -> dropData vj (varCensus vj m') bd _ -> bd simplifier bd' m' _ -> do -- next, simplify inside the body of the 'letcont' case termView m of VLam nm x t m' -> do q <- if (varCensus x m' == 1) then do simplifier (BindLetcont bd k') m' else Debug.trace ("CONT multiple occur: " ++ show (varCensus x m')) $ simplifier (BindOpaque bd) m' -- DEAD-cont. remove dead code if the 'letcont' variable is now unused if freeVar x q then "letcont" @@ (return k') @@ (mkLam nm x t q) else Debug.trace "DEAD-CONT" $ strengthen q _ -> fail "simplifier: expected function in 'letcont' body" -- η-CONT rule. If the bound contnuation is just an η-expanded -- version of 'j', replace the bound variable in the body with 'j' -- and drop the 'letcont' where tryEtaCont :: LF γ TERM -> Maybe (M (LF γ TERM)) tryEtaCont (termView -> VLam _ x _ (termView -> VConst "enter" [ j, termView -> VVar x' []])) | x == x' = case termView j of VVar (F j') [] -> Just $ mkVar j' VConst c [] -> Just $ tmConst c _ -> Nothing tryEtaCont _ = Nothing simplifier bd (termView -> VConst "letval" [v0,m]) = do -- first simplify the value v <- simplifyVal bd v0 let hyps = ?hyps case termView v of -- η-FUN rule. If the bound value is just an η-expanded 'g', then replace -- the body of the let with 'g' and drop the let. VConst "lam" [termView -> VLam _ k _ (termView -> VLam _ x _ (termView -> VConst "app" [ termView -> VVar (F (F g)) [] , termView -> VVar (F k') [] , termView -> VVar x' [] ]))] | k == k', x == x' -> let ?hyps = hyps in Debug.trace "η-FUN" $ simplifier bd =<< (return m) @@ (var g) -- η-PAIR rule. If a pair is bound in a context where the components of the -- pair were previously projected from a pair variable, replace the reconstructed -- pair with the original variable. (NB: this rule is only valid for strict pairs) VConst "pair" [ termView -> VVar x [] , termView -> VVar y [] ] | Just (True, vx) <- lookupProjData bd x , Just (False,vy) <- lookupProjData bd y , alphaEq vx vy -> Debug.trace "η-PAIR" $ do m' <- return m @@ return vx let bd' = case termView vx of VVar vx' [] -> dropData vx' (varCensus vx' m') bd _ -> bd simplifier bd' m' -- η-UNIT rule. Replace every let-binding of tt with a distinguished -- variable standing for the constant unit value VConst "tt" [] -> Debug.trace "η-UNIT" $ do simplifier bd =<< (return m) @@ "tt_CAF" -- otherwise, recurse _ -> case termView m of VLam nm x t m' -> do q <- let bd' = BindLetval bd (varCensus x m' <= 1) (applyHeuristic ?ischeap v) v in simplifier bd' m' -- DEAD-val remove dead code if the 'letval' variable is now unused if freeVar x q then "letval" @@ return v @@ mkLam nm x t q else Debug.trace "DEAD-VAL" $ strengthen q _ -> fail "simplifier: expected function in 'letval'" simplifier bd (termView -> VConst "let_prj1" [v, m]) = do let bd' = BindLetproj bd False v case termView v of -- β-PAIR1 rule VVar v' [] | Just (_, _, termView -> VConst "pair" [x,_]) <- lookupValData bd v' -> Debug.trace "β-PAIR1" $ do m' <- return m @@ return x let bd' = case termView x of VVar x' [] -> dropData x' (varCensus x' m') bd _ -> bd simplifier bd' m' _ -> case termView m of VLam nm x t m' -> do q <- simplifier bd' m' -- DEAD-proj. remove dead code if the 'let_prj' variable is now unused if freeVar x q then "let_prj1" @@ return v @@ mkLam nm x t q else Debug.trace "DEAD-PROJ1" $ strengthen q _ -> fail "simplifier: expected function in 'let_prj1'" simplifier bd (termView -> VConst "let_prj2" [ v, m]) = do let bd' = BindLetproj bd True v case termView v of -- β-PAIR2 rule VVar v' [] | Just (_, _, termView -> VConst "pair" [_,y]) <- lookupValData bd v' -> Debug.trace "β-PAIR2" $ do m' <- return m @@ return y let bd' = case termView y of VVar y' [] -> dropData y' (varCensus y' m') bd _ -> bd simplifier bd' m' _ -> case termView m of VLam nm x t m' -> do q <- simplifier bd' m' -- DEAD-proj. remove dead code if the 'let_prj' variable is now unused if freeVar x q then "let_prj2" @@ return v @@ mkLam nm x t q else Debug.trace "DEAD-PROJ2" $ strengthen q _ -> fail "simplifier: expected function in 'let_prj2'" simplifier bd (termView -> VConst "enter" [termView -> VVar kv [], x]) | Just cont <- lookupContData bd kv = Debug.trace "β-CONT" $ do cont' <- return cont @@ return x let bd' = case termView x of VVar x' [] -> dropData x' (varCensus x' cont') bd _ -> bd simplifier bd' cont' simplifier bd (termView -> VConst "app" [ termView -> VVar f [], j, y]) | Just (lin, cheap, termView -> VConst "lam" [m]) <- lookupValData bd f , lin || cheap = Debug.trace "β-FUN" $ do m' <- return m @@ return j @@ return y let bd' = (case termView j of VVar j' [] -> dropData j' (varCensus j' m') _ -> id) $ (case termView y of VVar y' [] -> dropData y' (varCensus y' m') _ -> id) $ bd simplifier bd' m' simplifier bd m@(termView -> VConst "case" [e,l,r]) = do case termView e of VVar e' [] -- β-CASE rules. If we case on an 'inl' or 'inr' value, simply -- enter the correct continuation. | Just (_, _, termView -> VConst "inl" [x]) <- lookupValData bd e' -> Debug.trace "β-CASE-L" $ simplifier bd =<< "enter" @@ return l @@ return x | Just (_, _, termView -> VConst "inr" [x]) <- lookupValData bd e' -> Debug.trace "β-CASE-R" $ simplifier bd =<< "enter" @@ return r @@ return x _ -> case (termView l, termView r) of -- η-case rule. If the branches of a case simply reconstitute -- an either value and then enter the same continuation, we can skip -- the case and just enter the continuation. (NB: this rule is only valid -- for strict languages). (VVar l' [], VVar r' []) | Just lk <- lookupContData bd l' , Just rk <- lookupContData bd r' , Just k1 <- tryEtaCase "inl" lk , Just k2 <- tryEtaCase "inr" rk , k1 == k2 -> Debug.trace "η-CASE" simplifier bd =<< "enter" @@ var k1 @@ return e _ -> return m where tryEtaCase :: String -> LF γ TERM -> Maybe (Var γ) tryEtaCase con m = case termView m of VLam _ x _ (termView -> VConst "letval" [ termView -> VConst (CNm con') [termView -> VVar x' []] , termView -> VLam _ y _ (termView -> VConst "enter" [ termView -> VVar (F (F k)) [] , termView -> VVar y' [] ]) ]) | con == con', x == x', y == y' -> Just k _ -> Nothing -- No other rule applies, just return the term simplifier _ m = return m simplifyVal :: forall γ . (LiftClosed γ, ?hyps :: H γ , ?soln :: LFSoln LF , ?ischeap :: InlineHeuristic ) => BindData γ -> LF γ TERM -> M (LF γ TERM) -- Simplify inside the body of lambdas simplifyVal bd (termView -> VConst "lam" [termView -> VLam jnm j jt (termView -> VLam xnm x xt m) ]) = do let bd' = BindOpaque (BindOpaque bd) m' <- simplifier bd' m "lam" @@ (mkLam jnm j jt =<< mkLam xnm x xt m') -- otherwise return the term unchanged simplifyVal _ m = return m
robdockins/canonical-lf
toyml/Simplify.hs
Haskell
bsd-3-clause
13,373
module B1.Program.Chart.TaskManager ( TaskManager , newTaskManager ) where data TaskManager = TaskManager (IORef [IO ()]) newTaskManager :: IO TaskManager newTaskManager = do workQueue <- newIORef [] return $ TaskManager workQueue
madjestic/b1
src/B1/Program/Chart/ThreadManager.hs
Haskell
bsd-3-clause
244
{-# LANGUAGE FlexibleInstances,FlexibleContexts,MultiWayIf,CPP #-} module Herbie.MathInfo where import Class import DsBinds import DsMonad import ErrUtils import GhcPlugins hiding (trace) import Unique import MkId import PrelNames import UniqSupply import TcRnMonad import TcSimplify import Type import Control.Monad import Control.Monad.Except import Control.Monad.Trans import Data.Char import Data.List import Data.List.Split import Data.Maybe import Data.Ratio import Herbie.CoreManip import Herbie.MathExpr import Prelude import Show -- import Debug.Trace hiding (traceM) trace a b = b traceM a = return () -------------------------------------------------------------------------------- -- | The fields of this type correspond to the sections of a function type. -- -- Must satisfy the invariant that every class in "getCxt" has an associated dictionary in "getDicts". data ParamType = ParamType { getQuantifier :: [Var] , getCxt :: [Type] , getDicts :: [CoreExpr] , getParam :: Type } -- | This type is a simplified version of the CoreExpr type. -- It only supports math expressions. -- We first convert a CoreExpr into a MathInfo, -- perform all the manipulation on the MathExpr within the MathInfo, -- then use the information in MathInfo to convert the MathExpr back into a CoreExpr. data MathInfo = MathInfo { getMathExpr :: MathExpr , getParamType :: ParamType , getExprs :: [(String,Expr Var)] -- ^ the fst value is the unique name assigned to non-mathematical expressions -- the snd value is the expression } -- | Pretty print a math expression pprMathInfo :: MathInfo -> String pprMathInfo mathInfo = go 1 False $ getMathExpr mathInfo where isLitOrLeaf :: MathExpr -> Bool isLitOrLeaf (ELit _ ) = True isLitOrLeaf (ELeaf _) = True isLitOrLeaf _ = False go :: Int -> Bool -> MathExpr -> String go i b e = if b && not (isLitOrLeaf e) then "("++str++")" else str where str = case e of -- EMonOp "negate" l@(ELit _) -> "-"++go i False l EMonOp "negate" e1 -> "-"++go i False e1 EMonOp op e1 -> op++" "++go i True e1 EBinOp op e1 e2 -> if op `elem` fancyOps then op++" "++go i True e1++" "++go i True e2 else go i parens1 e1++" "++op++" "++go i parens2 e2 where parens1 = case e1 of -- (EBinOp op' _ _) -> op/=op' (EMonOp _ _) -> False _ -> True parens2 = case e2 of -- (EBinOp op' _ _) -> op/=op' || not (op `elem` commutativeOpList) (EMonOp _ _) -> False _ -> True ELit l -> if toRational (floor l) == l then if length (show (floor l :: Integer)) < 10 then show (floor l :: Integer) else show (fromRational l :: Double) else show (fromRational l :: Double) ELeaf l -> case lookup l $ getExprs mathInfo of Just (Var _) -> pprVariable l mathInfo Just _ -> pprExpr l mathInfo -- Just _ -> "???" EIf cond e1 e2 -> "if "++go i False cond++"\n" ++white++"then "++go (i+1) False e1++"\n" ++white++"else "++go (i+1) False e2 where white = replicate (4*i) ' ' -- | If there is no ambiguity, the variable is displayed without the unique. -- Otherwise, it is returned with the unique pprVariable :: String -> MathInfo -> String pprVariable var mathInfo = if length (filter (==pprvar) pprvars) > length (filter (==var) $ map fst $ getExprs mathInfo) then var else pprvar where pprvar = ppr var pprvars = map ppr $ map fst $ getExprs mathInfo ppr = concat . intersperse "_" . init . splitOn "_" -- | The names of expressions are long and awkward. -- This gives us a display-friendly version. pprExpr :: String -> MathInfo -> String pprExpr var mathInfo = "?"++show index where index = case findIndex (==var) notvars of Just x -> x notvars = map fst $ filter (\(v,e) -> case e of (Var _) -> False; otherwise -> True) $ getExprs mathInfo -- | If the given expression is a math expression, -- returns the type of the variable that the math expression operates on. varTypeIfValidExpr :: CoreExpr -> Maybe Type varTypeIfValidExpr e = case e of -- might be a binary math operation (App (App (App (App (Var v) (Type t)) _) _) _) -> if var2str v `elem` binOpList then if isValidType t then Just t else Nothing else Nothing -- might be a unary math operation (App (App (App (Var v) (Type t)) _) _) -> if var2str v `elem` monOpList then if isValidType t then Just t else Nothing else Nothing -- first function is anything else means that we're not a math expression _ -> Nothing where isValidType :: Type -> Bool isValidType t = isTyVarTy t || case splitTyConApp_maybe t of Nothing -> True Just (tyCon,_) -> tyCon == floatTyCon || tyCon == doubleTyCon -- | Converts a CoreExpr into a MathInfo mkMathInfo :: DynFlags -> [Var] -> Type -> Expr Var -> Maybe MathInfo mkMathInfo dflags dicts bndType e = case varTypeIfValidExpr e of Nothing -> Nothing Just t -> if mathExprDepth getMathExpr>1 || lispHasRepeatVars (mathExpr2lisp getMathExpr) then Just $ MathInfo getMathExpr ParamType { getQuantifier = quantifier , getCxt = cxt , getDicts = map Var dicts , getParam = t } exprs else Nothing where (getMathExpr,exprs) = go e [] -- this should never return Nothing if validExpr is not Nothing (quantifier,unquantified) = extractQuantifiers bndType (cxt,uncxt) = extractContext unquantified -- recursively converts the `Expr Var` into a MathExpr and a dictionary go :: Expr Var -> [(String,Expr Var)] -> (MathExpr ,[(String,Expr Var)] ) -- we need to special case the $ operator for when MathExpr is run before any rewrite rules go e@(App (App (App (App (Var v) (Type _)) (Type _)) a1) a2) exprs = if var2str v == "$" then go (App a1 a2) exprs else (ELeaf $ expr2str dflags e,[(expr2str dflags e,e)]) -- polymorphic literals created via fromInteger go e@(App (App (App (Var v) (Type _)) dict) (Lit l)) exprs = (ELit $ lit2rational l, exprs) -- polymorphic literals created via fromRational go e@(App (App (App (Var v) (Type _)) dict) (App (App (App (Var _) (Type _)) (Lit l1)) (Lit l2))) exprs = (ELit $ lit2rational l1 / lit2rational l2, exprs) -- non-polymorphic literals go e@(App (Var _) (Lit l)) exprs = (ELit $ lit2rational l, exprs) -- binary operators go e@(App (App (App (App (Var v) (Type _)) dict) a1) a2) exprs = if var2str v `elem` binOpList then let (a1',exprs1) = go a1 [] (a2',exprs2) = go a2 [] in ( EBinOp (var2str v) a1' a2' , exprs++exprs1++exprs2 ) else (ELeaf $ expr2str dflags e,[(expr2str dflags e,e)]) -- unary operators go e@(App (App (App (Var v) (Type _)) dict) a) exprs = if var2str v `elem` monOpList then let (a',exprs') = go a [] in ( EMonOp (var2str v) a' , exprs++exprs' ) else (ELeaf $ expr2str dflags e,(expr2str dflags e,e):exprs) -- everything else go e exprs = (ELeaf $ expr2str dflags e,[(expr2str dflags e,e)]) -- | Converts a MathInfo back into a CoreExpr mathInfo2expr :: ModGuts -> MathInfo -> ExceptT ExceptionType CoreM CoreExpr mathInfo2expr guts herbie = go (getMathExpr herbie) where pt = getParamType herbie -- binary operators go (EBinOp opstr a1 a2) = do a1' <- go a1 a2' <- go a2 f <- getDecoratedFunction guts opstr (getParam pt) (getDicts pt) return $ App (App f a1') a2' -- unary operators go (EMonOp opstr a) = do a' <- go a f <- getDecoratedFunction guts opstr (getParam pt) (getDicts pt) castToType (getDicts pt) (getParam pt) $ App f a' -- if statements go (EIf cond a1 a2) = do cond' <- go cond >>= castToType (getDicts pt) boolTy a1' <- go a1 a2' <- go a2 wildUniq <- getUniqueM let wildName = mkSystemName wildUniq (mkVarOcc "wild") wildVar = mkLocalVar VanillaId wildName boolTy vanillaIdInfo return $ Case cond' wildVar (getParam pt) [ (DataAlt falseDataCon, [], a2') , (DataAlt trueDataCon, [], a1') ] -- leaf is a numeric literal go (ELit r) = do fromRationalExpr <- getDecoratedFunction guts "fromRational" (getParam pt) (getDicts pt) integerTyCon <- lookupTyCon integerTyConName let integerTy = mkTyConTy integerTyCon ratioTyCon <- lookupTyCon ratioTyConName tmpUniq <- getUniqueM let tmpName = mkSystemName tmpUniq (mkVarOcc "a") tmpVar = mkTyVar tmpName liftedTypeKind tmpVarT = mkTyVarTy tmpVar ratioConTy = mkForAllTy tmpVar $ mkFunTys [tmpVarT,tmpVarT] $ mkAppTy (mkTyConTy ratioTyCon) tmpVarT ratioConVar = mkGlobalVar VanillaId ratioDataConName ratioConTy vanillaIdInfo return $ App fromRationalExpr (App (App (App (Var ratioConVar ) (Type integerTy) ) (Lit $ LitInteger (numerator r) integerTy) ) (Lit $ LitInteger (denominator r) integerTy) ) -- leaf is any other expression go (ELeaf str) = do dflags <- getDynFlags return $ case lookup str (getExprs herbie) of Just x -> x Nothing -> error $ "mathInfo2expr: var " ++ str ++ " not in scope" ++"; in scope vars="++show (nub $ map fst $ getExprs herbie)
mikeizbicki/HerbiePlugin
src/Herbie/MathInfo.hs
Haskell
bsd-3-clause
11,357
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Hakyll.Core.Rules.Tests ( tests ) where -------------------------------------------------------------------------------- import Data.IORef (IORef, newIORef, readIORef, writeIORef) import qualified Data.Map as M import qualified Data.Set as S import System.FilePath ((</>)) import Test.Framework (Test, testGroup) import Test.HUnit (Assertion, assert, (@=?)) -------------------------------------------------------------------------------- import Hakyll.Core.Compiler import Hakyll.Core.File import Hakyll.Core.Identifier import Hakyll.Core.Identifier.Pattern import Hakyll.Core.Routes import Hakyll.Core.Rules import Hakyll.Core.Rules.Internal import Hakyll.Web.Pandoc import TestSuite.Util -------------------------------------------------------------------------------- tests :: Test tests = testGroup "Hakyll.Core.Rules.Tests" $ fromAssertions "runRules" [case01] -------------------------------------------------------------------------------- case01 :: Assertion case01 = do ioref <- newIORef False store <- newTestStore provider <- newTestProvider store ruleSet <- runRules (rules01 ioref) provider let identifiers = S.fromList $ map fst $ rulesCompilers ruleSet routes = rulesRoutes ruleSet checkRoute ex i = runRoutes routes provider i >>= \(r, _) -> Just ex @=? r -- Test that we have some identifiers and that the routes work out S.fromList expected @=? identifiers checkRoute "example.html" "example.md" checkRoute "example.md" (sv "raw" "example.md") checkRoute "example.md" (sv "nav" "example.md") checkRoute "example.mv1" (sv "mv1" "example.md") checkRoute "example.mv2" (sv "mv2" "example.md") checkRoute "food/example.md" (sv "metadataMatch" "example.md") readIORef ioref >>= assert cleanTestEnv where sv g = setVersion (Just g) expected = [ "example.md" , sv "raw" "example.md" , sv "metadataMatch" "example.md" , sv "nav" "example.md" , sv "mv1" "example.md" , sv "mv2" "example.md" , "russian.md" , sv "raw" "russian.md" , sv "mv1" "russian.md" , sv "mv2" "russian.md" ] -------------------------------------------------------------------------------- rules01 :: IORef Bool -> Rules () rules01 ioref = do -- Compile some posts match "*.md" $ do route $ setExtension "html" compile pandocCompiler -- Yeah. I don't know how else to test this stuff? preprocess $ writeIORef ioref True -- Compile them, raw match "*.md" $ version "raw" $ do route idRoute compile getResourceString version "metadataMatch" $ matchMetadata "*.md" (\md -> M.lookup "subblog" md == Just "food") $ do route $ customRoute $ \id' -> "food" </> toFilePath id' compile getResourceString -- Regression test version "nav" $ match (fromList ["example.md"]) $ do route idRoute compile copyFileCompiler -- Another edge case: different versions in one match match "*.md" $ do version "mv1" $ do route $ setExtension "mv1" compile getResourceString version "mv2" $ do route $ setExtension "mv2" compile getResourceString
Minoru/hakyll
tests/Hakyll/Core/Rules/Tests.hs
Haskell
bsd-3-clause
3,836
{-# LANGUAGE TypeInType, ScopedTypeVariables, TypeOperators, GADTs #-} {-# OPTIONS_GHC -Wno-overlapping-patterns #-} -- don't want erroneous warning in test output -- if removing this doesn't change output, then -- remove it! module T13337 where import Data.Typeable import Data.Kind f :: forall k (a :: k). (Typeable k, Typeable a) => Proxy a -> Proxy Int f p = case eqT :: Maybe (k :~: Type) of Nothing -> Proxy Just Refl -> case eqT :: Maybe (a :~: Int) of Nothing -> Proxy Just Refl -> p
ezyang/ghc
testsuite/tests/typecheck/should_compile/T13337.hs
Haskell
bsd-3-clause
602
{-# LANGUAGE MagicHash, UnboxedTuples #-} module Main ( main ) where import GHC.Exts import GHC.Prim import GHC.ST main = putStr (test_sizeofArray ++ "\n" ++ test_sizeofMutableArray ++ "\n" ) test_sizeofArray :: String test_sizeofArray = flip shows "\n" $ runST $ ST $ \ s# -> go 0 [] s# where go i@(I# i#) acc s# | i < 1000 = case newArray# i# 0 s# of (# s2#, marr# #) -> case unsafeFreezeArray# marr# s2# of (# s3#, arr# #) -> case sizeofArray# arr# of j# -> go (i+1) ((I# j#):acc) s3# | otherwise = (# s#, reverse acc #) test_sizeofMutableArray :: String test_sizeofMutableArray = flip shows "\n" $ runST $ ST $ \ s# -> go 0 [] s# where go i@(I# i#) acc s# | i < 1000 = case newArray# i# 0 s# of (# s2#, marr# #) -> case sizeofMutableArray# marr# of j# -> go (i+1) ((I# j#):acc) s2# | otherwise = (# s#, reverse acc #)
hferreiro/replay
testsuite/tests/codeGen/should_run/cgrun065.hs
Haskell
bsd-3-clause
982
module Parse (parse, parseExpr, lexSynonym) where import Text.Parsec hiding (parse) import qualified Text.Parsec as P import Text.Parsec.String (Parser) import LambdaWithSynonyms (Expr'(..)) import Data.Functor ((<$>)) import Control.Arrow (left) import Control.Applicative ((<*)) parse :: String -> Either String Expr' parse = transformError . P.parse parseAllExpr "" transformError :: Either ParseError Expr' -> Either String Expr' transformError = left show parseAllExpr :: Parser Expr' parseAllExpr = parseExpr <* eof parseExpr :: Parser Expr' parseExpr = (parseLambdaOrName <|> withParens parseExpr) `chainl1` return Ap' parseLambdaOrName :: Parser Expr' parseLambdaOrName = parseLambda <|> parseName <|> parseSynonym parseLambda :: Parser Expr' parseLambda = do lexLambda names <- lexNames lexDot expr <- parseExpr return $ foldr L' expr names parseName :: Parser Expr' parseName = V' <$> lexName parseSynonym :: Parser Expr' parseSynonym = S' <$> lexSynonym --lexers lexLambda = char 'λ' <|> char '\\' lexDot = char '.' lexName = oneOf ['a'..'z'] lexNames = many1 lexName lexSynonym = oneOf $ ['A'..'Z'] ++ ['0'..'9'] --helpers withParens :: Parser a -> Parser a withParens = between (char '(') (char ')')
hughfdjackson/abattoir
src/Parse.hs
Haskell
mit
1,234
{-# OPTIONS -Wall #-} {-# LANGUAGE TupleSections #-} import qualified Data.List as List import qualified Data.Map.Strict as Map import qualified Data.Maybe as Maybe import Data.Set (Set) import qualified Data.Set as Set import Helpers.Function import Helpers.Grid (Grid, Point) import qualified Helpers.Grid as Grid main :: IO () main = do levels <- Grid.fromDigits <$> getContents let steps = iterate (step . fst) (levels, 0) let answer = Maybe.fromJust $ List.findIndex (Grid.all (== 0) . fst) steps print answer step :: Grid Int -> (Grid Int, Int) step startingLevels = step' (succ <$> startingLevels) Set.empty where step' :: Grid Int -> Set Point -> (Grid Int, Int) step' levels flashed = let updatedFlashed = Grid.pointsWhere (> 9) levels newFlashed = updatedFlashed Set.\\ flashed in if Set.size newFlashed == 0 then let updates = map (,0) (Set.toList flashed) in (levels Grid.// updates, Set.size flashed) else let updates = Set.toList newFlashed |> map (Map.fromSet (const 1) . (`Grid.neighboringPointsWithDiagonals` levels)) |> Map.unionsWith (+) in step' (Grid.updateWith (+) updates levels) updatedFlashed
SamirTalwar/advent-of-code
2021/AOC_11_2.hs
Haskell
mit
1,308
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE DeriveGeneric #-} -- | simple haskell interface for freetype2 -- -- for error codes: https://hackage.haskell.org/package/freetype2-0.1.1/src/include/freetype/fterrdef.h module Graphics.Font ( module Graphics.Font , module FontFace , module FontLibrary , module Graphics.Font.FontGlyph ) where import GHC.Generics import Data.Map.Strict hiding ( map ) import Data.Traversable ( sequenceA ) import Control.Applicative import Graphics.Font.FontLibrary as FontLibrary ( FontLibrary , withNewLibrary , makeLibrary , freeLibrary ) import Graphics.Font.FontFace as FontFace import Graphics.Font.FontGlyph import Graphics.Font.BitmapLoader import Codec.Picture pt :: Num a => a -> a pt = (*) 64 data FontDescriptor = FontDescriptor { charSize :: CharSize -- | pt (1/64 pixel) , deviceRes :: DeviceResolution -- | for dpi calculation } deriving ( Show, Eq, Ord, Generic ) data Font = Font { fontName :: !String , charMap :: !(Map Char FontGlyph) , fontDescr :: !FontDescriptor , fontFace :: !(FontFaceFPtr,FontFace) , fontLib :: !(FontLibrary) } data FontLoadMode = Gray8 | Monochrome deriving ( Show, Eq, Ord, Enum, Generic ) loadFont :: FontLibrary -> FilePath -> FontDescriptor -> IO Font loadFont flib fontfile descr@FontDescriptor{..} = do (fpt,face) <- newFontFace flib fontfile 0 setFaceCharSize fpt charSize deviceRes indices <- getAllFaceCharIndices fpt cMap <- fromList <$> mapM (toGlyph fpt) indices let fontName = familyName face ++ "-" ++ styleName face return $ Font fontName cMap descr (fpt,face) flib where toGlyph face (gindex, char) = (char,) <$> loadGlyph face gindex [LoadDefault] loadCharGlyph :: Font -> [LoadMode] -> Char -> IO FontGlyph loadCharGlyph Font{fontFace} mode c = getFaceGlyphIndex (fst fontFace) c >>= flip (loadGlyph (fst fontFace)) mode generateCharImg :: Font -> FontLoadMode -> Char -> IO (Image Pixel8) generateCharImg font mode char = case mode of Gray8 -> load grayLoader [LoadRender] Monochrome -> load monoLoader [LoadRender, LoadMonochrome] where load loader flags = loadFaceCharImage (fst $ fontFace font) char flags loader generateAllCharImgs :: Font -> FontLoadMode -> IO (Map Char (Image Pixel8)) generateAllCharImgs font mode = sequenceA $ mapWithKey (\c _ -> charImg c) (charMap font) where charImg = generateCharImg font mode
MaxDaten/typography-ft2
Graphics/Font.hs
Haskell
mit
2,801
-- A Gift Well Spent -- http://www.codewars.com/kata/54554846126a002d5b000854/ module Gift where buy :: (Num a, Eq a) => a -> [a] -> Maybe (Int, Int) buy c is = if null cs then Nothing else Just (head cs) where cs = [(i, j) | i<-[0..length is - 1], j <- drop i [1..length is - 1], is!!i + is!!j == c]
gafiatulin/codewars
src/7 kyu/Gift.hs
Haskell
mit
308
module Y2017.M07.D26.Exercise where import Control.Monad.State import Data.Map (Map) -- below import available via 1HaskellADay git repository import Relational.Scheme.Types {-- Unification and freshness for today. So, yesterday, we saw how to unify two atoms and how that reduced to lifting their equivalence into the monadic domain. Basically: unifying two ground terms is monadic guard. Fine. But what are the rules for unifying variables to ground terms? What are the rules for unifying variables to other variables, either of which may be bound or free? It turns out there are a lot of rules. And we're not even talking about the occurs-check, yet. So, like yesterday, where we broke it down: just unification on ground terms, let's continue to break down the problem into manageable pieces. There are many behaviors for unification with logic variables, so let's focus on one aspect of unification at a time. But even before that, we have to declare what a logic variable is. What is a logic variable? data LogicVariable = LV Sym Status deriving Eq The above is saying that a logic variable is named by its symbolic representation and its status. What is its symbolic representation, and what are the statii of a logic variable? Well, digging deeper, a logic variable is not an independent thing, like an atom, that can exist without some context. No, a logic variable exists in the (logic) universe in which it subsides. So, the above declaration is naïve. Really, a logic variable is a mapping from its symbolic representation to its status. Let's talk about the states of a logic variable. A logic variable exists in three states: free - it has not been bound to any value bound - it has been bound to a ground term (e.g.: an atomic value) linked - it has been linked to another logic variable in any state (of course, if the other logic variable is free, it, too becomes linked to the unifying logic variable). So, let's model the statii of a logic variable: --} data Status = Free | Linked { forward, back :: [Symbol] } | Bound Atom deriving (Eq, Show) -- (please ignore the Linked status for the time being) -- Okay, we know what an atom is (from the import). What's a symbol? type Symbol = String -- So we have the statii of logic variables. Now let's create the logic domain -- for logic variables type LogicDomain = Map Symbol Status -- and there you have it. Everything you need have logic variables. -- so: fresh. fresh :: MonadPlus m => Symbol -> StateT LogicDomain m () fresh sym = undefined {-- >>> runStateT (fresh "a") Map.empty ((),fromList [("a",Free)]) ... what happens when you declare an already existing variable 'fresh'? ... what should happen? --} -- which means everything that you do with logic variables include the domain -- ... including unification. So, let's get to it. -- What happens when an atom is unified to a variable? unifyAtom2LV :: MonadPlus m => Atom -> Symbol -> StateT LogicDomain m () unifyAtom2LV val var = undefined {-- So, what needs to happen is: If the logic variable is free, it needs to be bound to that value. If the logic variable is bound to a value, it needs to be equal to that value. ... we won't look at linked logic variables today. Question: What happens when a variable isn't in the domain? What should happen? --} -- What happens when a logic variable is unified to an atom? unifyLV2Atom :: MonadPlus m => Symbol -> Atom -> StateT LogicDomain m () unifyLV2Atom var val = undefined -- With the above definitions, unify the following: logicVars :: [Symbol] logicVars = words "a b c d" vals :: [Atom] vals = map read (words "5 #t #s Hi") {-- >>> vals [I 5,B True,L #s,S "Hi"] --} -- Now, with those unified variables (that is to say: keep the state active), -- unify a, b, c, d against the below newvals. What are your results? newvals :: [Atom] newvals = map read (words "5 True #u hi") {-- >>> newvals [I 5,S "True",L #u,S "hi"] --}
geophf/1HaskellADay
exercises/HAD/Y2017/M07/D26/Exercise.hs
Haskell
mit
3,957
{-# LANGUAGE DataKinds, MultiParamTypeClasses, FunctionalDependencies, TypeOperators, PolyKinds, TypeFamilies, FlexibleInstances, ScopedTypeVariables, UndecidableInstances, DefaultSignatures, FlexibleContexts #-} {-# OPTIONS_HADDOCK prune #-} module Data.MZip where import Data.MGeneric import Data.Unapply import Data.HList import Data.Proxy import Data.Nat import Unsafe.Coerce import Control.Applicative type family Dom (f :: *) where Dom (a -> b) = a type family Codom (f :: *) where Codom (a -> b) = b type family Doms (fs :: [*]) :: [*] where Doms '[] = '[] Doms ((a -> b) ': as) = a ': Doms as type family Codoms (fs :: [*]) :: [*] where Codoms '[] = '[] Codoms ((a -> b) ': as) = b ': Codoms as type family LCodoms (n :: Nat) (fs :: [*]) where LCodoms NZ fs = fs LCodoms (NS n) fs = LCodoms n (Codoms fs) type family ZipInput n f where ZipInput NZ a = Maybe a ZipInput (NS n) (a -> b) = a -> ZipInput n b type family ZipInputs n fs where ZipInputs n '[] = '[] ZipInputs n (f ': fs) = ZipInput n f ': ZipInputs n fs type family ZipWithType' (n :: Nat) (f :: k) (fs :: [*]) :: * where ZipWithType' NZ f fs = (f :$: fs) ZipWithType' (NS n) f fs = f :$: (Doms fs) -> ZipWithType' n f (Codoms fs) type family ZipWithType (n :: Nat) (f :: k) (fs :: [*]) :: * where ZipWithType NZ f fs = Maybe (f :$: fs) ZipWithType (NS n) f fs = f :$: (Doms fs) -> ZipWithType n f (Codoms fs) type family ZipWithTypeUn (n :: Nat) (f :: Un *) (fs :: [*]) :: * where ZipWithTypeUn NZ f fs = Maybe (In f fs) ZipWithTypeUn (NS n) f fs = In f (Doms fs) -> ZipWithTypeUn n f (Codoms fs) type family ZipWithTypeField (n :: Nat) (f :: Field *) (fs :: [*]) :: * where ZipWithTypeField NZ f fs = Maybe (InField f fs) ZipWithTypeField (NS n) f fs = InField f (Doms fs) -> ZipWithTypeField n f (Codoms fs) class MZipWithG n f rf fs where mzipWithPG :: Proxy n -> Proxy f -> Proxy rf -> Proxy fs -> ZipWithTypeUn n rf fs -> ZipWithType n f fs instance ( fs ~ Pars (f :$: fs) , rf ~ Rep (f :$: fs) , MGeneric (f :$: fs) ) => MZipWithG NZ f rf fs where mzipWithPG _ _ _ _ a = fmap to a instance ( MZipWithG n f rf (Codoms fs) , rf ~ Rep (f :$: Doms fs) , Doms fs ~ Pars (f :$: Doms fs) , MGeneric (f :$: Doms fs) ) => MZipWithG (NS n) f rf fs where mzipWithPG _ pf prf _ a b = mzipWithPG (Proxy :: Proxy n) pf prf (Proxy :: Proxy (Codoms fs)) (a (from b)) -- | class MZipWith (n :: Nat) (f :: k) (fs :: [*]) where -- | mzipWithP :: Proxy n -> Proxy f -> Proxy fs -> HList (ZipInputs n fs) -> ZipWithType n f fs default mzipWithP :: ( rf ~ Rep (f :$: LCodoms n fs) , MZipWithG n f rf fs , GMZipWith n rf fs ) => Proxy n -> Proxy f -> Proxy fs -> HList (ZipInputs n fs) -> ZipWithType n f fs mzipWithP pn pf pfs fs = mzipWithPG pn pf prf (Proxy :: Proxy fs) (mzipWithG pn prf pfs fs) where prf = Proxy :: Proxy (Rep (f :$: LCodoms n fs)) class (ZipInput n f ~ a) => ZipInputC n f a | n f -> a, a -> f instance ZipInputC NZ a (Maybe a) instance ZipInputC n b c => ZipInputC (NS n) (a -> b) (a -> c) class (ZipInputs n fs ~ a) => ZipInputsC n fs a | n fs -> a, a -> fs instance ZipInputsC n '[] '[] instance (ZipInputC n f c, ZipInputsC n fs b) => ZipInputsC n (f ': fs) (c ': b) class (ZipWithType n f fs ~ a) => ZipWithTypeC n f fs a | n f fs -> a, a -> n f fs instance Unapply a f fs => ZipWithTypeC NZ f fs (Maybe a) instance (Unapply a f (Doms fs), ZipWithTypeC n f (Codoms fs) b) => ZipWithTypeC (NS n) f fs (a -> b) -- | `mzipWith` zips n structures together if they have the same shape, or fails (with `Nothing`) if the shapes do not match. -- -- > mzipWith :: HList '[a11 -> ... -> an1 -> b1, ...] -> f a11 ... a1m -> f an1 ... anm -> f b1 ... bm mzipWith :: forall n f fs b. ( MZipWith n f fs , MakeZipInputs n fs , ZipWithTypeC n f fs b , ZipInputsC n fs (ZipInputs n fs) ) => HList fs -> b mzipWith fs = mzipWithP (Proxy :: Proxy n) (Proxy :: Proxy f) (Proxy :: Proxy fs) (makeZipInputs (Proxy :: Proxy n) fs) class MakeZipInput n f where makeZipInput :: Proxy n -> f -> ZipInput n f instance MakeZipInput NZ a where makeZipInput _ = Just instance MakeZipInput n b => MakeZipInput (NS n) (a -> b) where makeZipInput _ f a = makeZipInput (Proxy :: Proxy n) (f a) class MakeZipInputs n fs where makeZipInputs :: ZipInputsC n fs a => Proxy n -> HList fs -> HList a instance MakeZipInputs n '[] where makeZipInputs _ _ = HNil instance ( MakeZipInput n f , MakeZipInputs n fs , ZipInputsC n fs (ZipInputs n fs) ) => MakeZipInputs n (f ': fs) where makeZipInputs pn (HCons f fs) = HCons (makeZipInput pn f) (makeZipInputs pn fs) class GMZipWith (n :: Nat) (f :: Un *) (fs :: [*]) where mzipWithG :: Proxy n -> Proxy f -> Proxy fs -> HList (ZipInputs n fs) -> ZipWithTypeUn n f fs instance GMZipWith n UV fs where mzipWithG _ _ _ = undefined class GMTZipWith n fs where mzipWithGT :: Proxy n -> Proxy fs -> ZipWithTypeUn n UT fs instance GMTZipWith NZ fs where mzipWithGT _ _ = Just InT instance GMTZipWith n (Codoms fs) => GMTZipWith (NS n) fs where mzipWithGT _ pf _ = mzipWithGT (Proxy :: Proxy n) (Proxy :: Proxy (Codoms fs)) instance GMTZipWith n fs => GMZipWith n UT fs where mzipWithG _ _ _ _ = mzipWithGT (Proxy :: Proxy n) (Proxy :: Proxy fs) class GMZipWithFail n u fs where mzipWithFail :: Proxy n -> Proxy u -> Proxy fs -> ZipWithTypeUn n u fs instance GMZipWithFail NZ u fs where mzipWithFail _ _ _ = Nothing class GMLZipWith n u v fs where mzipWithGL :: Proxy n -> Proxy u -> Proxy v -> Proxy fs -> ZipWithTypeUn n u fs -> ZipWithTypeUn n (u :++: v) fs instance GMLZipWith NZ u v fs where mzipWithGL _ _ _ _ u = fmap InL u instance ( GMLZipWith n u v (Codoms fs) , GMZipWithFail n (u :++: v) (Codoms fs) ) => GMLZipWith (NS n) u v fs where mzipWithGL _ pu pv _ f (InL u) = mzipWithGL (Proxy :: Proxy n) pu pv (Proxy :: Proxy (Codoms fs)) (f u) mzipWithGL _ pu pv _ f (InR _) = mzipWithFail (Proxy :: Proxy n) (Proxy :: Proxy (u :++: v)) (Proxy :: Proxy (Codoms fs)) class GMRZipWith n u v fs where mzipWithGR :: Proxy n -> Proxy u -> Proxy v -> Proxy fs -> ZipWithTypeUn n v fs -> ZipWithTypeUn n (u :++: v) fs instance GMRZipWith NZ u v fs where mzipWithGR _ _ _ _ v = fmap InR v instance ( GMRZipWith n u v (Codoms fs) , GMZipWithFail n (u :++: v) (Codoms fs) ) => GMRZipWith (NS n) u v fs where mzipWithGR _ pu pv _ f (InR v) = mzipWithGR (Proxy :: Proxy n) pu pv (Proxy :: Proxy (Codoms fs)) (f v) mzipWithGR _ pu pv _ f (InL _) = mzipWithFail (Proxy :: Proxy n) (Proxy :: Proxy (u :++: v)) (Proxy :: Proxy (Codoms fs)) instance ( GMZipWith (NS n) u fs, GMZipWith (NS n) v fs , GMLZipWith n u v (Codoms fs), GMRZipWith n u v (Codoms fs) ) => GMZipWith (NS n) (u :++: v) fs where mzipWithG _ _ pf fs (InL u) = mzipWithGL (Proxy :: Proxy n) (Proxy :: Proxy u) (Proxy :: Proxy v) (Proxy :: Proxy (Codoms fs)) (mzipWithG (Proxy :: Proxy (NS n)) (Proxy :: Proxy u) pf fs u) mzipWithG _ _ pf fs (InR v) = mzipWithGR (Proxy :: Proxy n) (Proxy :: Proxy u) (Proxy :: Proxy v) (Proxy :: Proxy (Codoms fs)) (mzipWithG (Proxy :: Proxy (NS n)) (Proxy :: Proxy v) pf fs v) class GPiMZipWith n u v fs where mzipWithGPi :: Proxy n -> Proxy u -> Proxy v -> Proxy fs -> ZipWithTypeUn n u fs -> ZipWithTypeUn n v fs -> ZipWithTypeUn n (u :**: v) fs instance GPiMZipWith NZ u v fs where mzipWithGPi _ _ _ _ f g = (:*:) <$> f <*> g instance GPiMZipWith n u v (Codoms fs) => GPiMZipWith (NS n) u v fs where mzipWithGPi _ _ _ _ f g (u :*: v) = mzipWithGPi (Proxy :: Proxy n) (Proxy :: Proxy u) (Proxy :: Proxy v) (Proxy :: Proxy (Codoms fs)) (f u) (g v) instance (GMZipWith n u fs, GMZipWith n v fs, GPiMZipWith n u v fs) => GMZipWith n (u :**: v) fs where mzipWithG pn _ pf fs = mzipWithGPi pn (Proxy :: Proxy u) (Proxy :: Proxy v) pf (mzipWithG pn (Proxy :: Proxy u) pf fs) (mzipWithG pn (Proxy :: Proxy v) pf fs) class GMZipWithF n f fs where mzipWithGFF :: Proxy n -> Proxy f -> Proxy fs -> ZipWithTypeField n f fs -> ZipWithTypeUn n (UF f) fs instance GMZipWithF NZ f fs where mzipWithGFF _ _ _ f = fmap InF f instance GMZipWithF n f (Codoms fs) => GMZipWithF (NS n) f fs where mzipWithGFF _ pf _ f (InF b) = mzipWithGFF (Proxy:: Proxy n) pf (Proxy :: Proxy (Codoms fs)) (f b) instance (GFMZipWith n f fs, GMZipWithF n f fs) => GMZipWith n (UF f) fs where mzipWithG pn _ pf fs = mzipWithGFF pn (Proxy :: Proxy f) pf (mzipWithGF pn (Proxy :: Proxy f) pf fs) class GFMZipWith (n :: Nat) (f :: Field *) (fs :: [*]) where mzipWithGF :: Proxy n -> Proxy f -> Proxy fs -> HList (ZipInputs n fs) -> ZipWithTypeField n f fs -- instance GFMZipWith n (FK a) fs where -- mzipWithGF _ fs (InK a) = InK a class GFPMZipWith n m fs where mzipWithGFP :: Proxy n -> Proxy m -> Proxy fs -> (ZipInputs n fs :!: m) -> ZipWithTypeField n (FP m) fs instance (Maybe (fs :!: m) ~ (ZipInputs NZ fs :!: m)) => GFPMZipWith NZ m fs where mzipWithGFP _ _ _ a = fmap InP a instance ( (ZipInputs (NS n) fs :!: m) ~ (Doms fs :!: m -> ZipInputs n (Codoms fs) :!: m) , GFPMZipWith n m (Codoms fs) ) => GFPMZipWith (NS n) m fs where mzipWithGFP _ _ _ f (InP a) = mzipWithGFP (Proxy :: Proxy n) (Proxy :: Proxy m) (Proxy :: Proxy (Codoms fs)) (f a) instance (GFPMZipWith n m fs, HLookup m (ZipInputs n fs)) => GFMZipWith n (FP m) fs where mzipWithGF pn _ pf fs = mzipWithGFP (Proxy :: Proxy n) (Proxy :: Proxy m) pf (hlookup (Proxy :: Proxy m) (Proxy :: Proxy (ZipInputs n fs)) fs) -- type family NId n a where -- NId NZ a = a -- NId (NS n) a = a -> NId n a type family ExpandFieldFunction (n :: Nat) (f :: [Field *]) (ps :: [*]) :: [*] where ExpandFieldFunction n '[] ps = '[] --ExpandFieldFunction n (FK a ': fs) ps = NId n a ': ExpandFieldFunction fs vfs ps vs ExpandFieldFunction n (FP m ': fs) ps = (ps :!: m) ': ExpandFieldFunction n fs ps ExpandFieldFunction n ((f :@: as) ': fs) ps = ZipWithType' n f (ExpandFieldFunction n as ps) ': ExpandFieldFunction n fs ps class AdaptFieldFunction (n :: Nat) (f :: [Field *]) (ps :: [*]) where adaptFieldFunction :: Proxy n -> Proxy f -> Proxy ps -> HList (ZipInputs n ps) -> HList (ZipInputs n (ExpandFieldFunction n f ps)) instance AdaptFieldFunction n '[] ps where adaptFieldFunction _ _ _ fs = HNil instance ( HLookup m (ZipInputs n ps) , ZipInput n (ps :!: m) ~ (ZipInputs n ps :!: m) , AdaptFieldFunction n as ps ) => AdaptFieldFunction n (FP m ': as) ps where adaptFieldFunction _ _ pf fs = HCons (hlookup (Proxy :: Proxy m) (Proxy :: Proxy (ZipInputs n ps)) fs) (adaptFieldFunction (Proxy :: Proxy n) (Proxy :: Proxy as) pf fs) instance ( MZipWith n f (ExpandFieldFunction n bs ps) , ZipInput n (ZipWithType' n f (ExpandFieldFunction n bs ps)) ~ ZipWithType n f (ExpandFieldFunction n bs ps) , AdaptFieldFunction n bs ps , AdaptFieldFunction n as ps ) => AdaptFieldFunction n ((f :@: bs) ': as) ps where adaptFieldFunction pn _ pfs fs = HCons (mzipWithP pn pf (Proxy :: Proxy (ExpandFieldFunction n bs ps)) (adaptFieldFunction pn pb pfs fs)) (adaptFieldFunction pn (Proxy :: Proxy as) pfs fs) where pf = Proxy :: Proxy f pb = Proxy :: Proxy bs class GFAMZipWith n f as fs where mzipWithGFA :: Proxy n -> Proxy f -> Proxy as -> Proxy fs -> ZipWithType n f (ExpandFieldFunction n as fs) -> ZipWithTypeField n (f :@: as) fs instance (ExpandFields as fs ~ ExpandFieldFunction NZ as fs) => GFAMZipWith NZ f as fs where mzipWithGFA _ _ _ _ (Just a) = Just (InA a) mzipWithGFA _ _ _ _ Nothing = Nothing instance ( ExpandFieldFunction n as (Codoms fs) ~ Codoms (ExpandFieldFunction (NS n) as fs) , Doms (ExpandFieldFunction (NS n) as fs) ~ ExpandFields as (Doms fs) , GFAMZipWith n f as (Codoms fs) ) => GFAMZipWith (NS n) f as fs where mzipWithGFA _ pf pa _ a (InA b) = mzipWithGFA (Proxy :: Proxy n) pf pa (Proxy :: Proxy (Codoms fs)) (a (unsafeCoerce b)) instance ( GFAMZipWith n f as fs , MZipWith n f (ExpandFieldFunction n as fs) , AdaptFieldFunction n as fs ) => GFMZipWith n (f :@: as) fs where mzipWithGF pn _ pfs fs = mzipWithGFA pn pf pa pfs (mzipWithP pn pf (Proxy :: Proxy (ExpandFieldFunction n as fs)) (adaptFieldFunction pn pa pfs fs)) where pf = Proxy :: Proxy f pa = Proxy :: Proxy as
RafaelBocquet/haskell-mgeneric
src/Data/MZip.hs
Haskell
mit
12,658
{-# LANGUAGE TypeFamilies, QuasiQuotes, TemplateHaskell, MultiParamTypeClasses, OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module YesodCoreTest.ErrorHandling ( errorHandlingTest , Widget ) where import Yesod.Core import Test.Hspec import Network.Wai import Network.Wai.Test import Text.Hamlet (hamlet) import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Char8 as S8 import Control.Exception (SomeException, try) data App = App mkYesod "App" [parseRoutes| / HomeR GET /not_found NotFoundR POST /first_thing FirstThingR POST /after_runRequestBody AfterRunRequestBodyR POST /error-in-body ErrorInBodyR GET /error-in-body-noeval ErrorInBodyNoEvalR GET |] instance Yesod App getHomeR :: Handler RepHtml getHomeR = do $logDebug "Testing logging" defaultLayout $ toWidget [hamlet| $doctype 5 <html> <body> <form method=post action=@{NotFoundR}> <input type=submit value="Not found"> <form method=post action=@{FirstThingR}> <input type=submit value="Error is thrown first thing in handler"> <form method=post action=@{AfterRunRequestBodyR}> <input type=submit value="BUGGY: Error thrown after runRequestBody"> |] postNotFoundR, postFirstThingR, postAfterRunRequestBodyR :: Handler RepHtml postNotFoundR = do (_, _files) <- runRequestBody _ <- notFound getHomeR postFirstThingR = do _ <- error "There was an error 3.14159" getHomeR postAfterRunRequestBodyR = do x <- runRequestBody _ <- error $ show $ fst x getHomeR getErrorInBodyR :: Handler RepHtml getErrorInBodyR = do let foo = error "error in body 19328" :: String defaultLayout [whamlet|#{foo}|] getErrorInBodyNoEvalR :: Handler (DontFullyEvaluate RepHtml) getErrorInBodyNoEvalR = fmap DontFullyEvaluate getErrorInBodyR errorHandlingTest :: Spec errorHandlingTest = describe "Test.ErrorHandling" $ do it "says not found" caseNotFound it "says 'There was an error' before runRequestBody" caseBefore it "says 'There was an error' after runRequestBody" caseAfter it "error in body == 500" caseErrorInBody it "error in body, no eval == 200" caseErrorInBodyNoEval runner :: Session () -> IO () runner f = toWaiApp App >>= runSession f caseNotFound :: IO () caseNotFound = runner $ do res <- request defaultRequest { pathInfo = ["not_found"] , requestMethod = "POST" } assertStatus 404 res assertBodyContains "Not Found" res caseBefore :: IO () caseBefore = runner $ do res <- request defaultRequest { pathInfo = ["first_thing"] , requestMethod = "POST" } assertStatus 500 res assertBodyContains "There was an error 3.14159" res caseAfter :: IO () caseAfter = runner $ do let content = "foo=bar&baz=bin12345" res <- srequest SRequest { simpleRequest = defaultRequest { pathInfo = ["after_runRequestBody"] , requestMethod = "POST" , requestHeaders = [ ("content-type", "application/x-www-form-urlencoded") , ("content-length", S8.pack $ show $ L.length content) ] } , simpleRequestBody = content } assertStatus 500 res assertBodyContains "bin12345" res caseErrorInBody :: IO () caseErrorInBody = runner $ do res <- request defaultRequest { pathInfo = ["error-in-body"] } assertStatus 500 res assertBodyContains "error in body 19328" res caseErrorInBodyNoEval :: IO () caseErrorInBodyNoEval = do eres <- try $ runner $ do _ <- request defaultRequest { pathInfo = ["error-in-body-noeval"] } return () case eres of Left (_ :: SomeException) -> return () Right _ -> error "Expected an exception"
piyush-kurur/yesod
yesod-core/test/YesodCoreTest/ErrorHandling.hs
Haskell
mit
3,811
-- | -- Module: Math.NumberTheory.Primes.Testing.Probabilistic -- Copyright: (c) 2011 Daniel Fischer, 2017 Andrew Lelechenko -- Licence: MIT -- Maintainer: Daniel Fischer <daniel.is.fischer@googlemail.com> -- -- Probabilistic primality tests, Miller-Rabin and Baillie-PSW. {-# LANGUAGE BangPatterns #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE ScopedTypeVariables #-} module Math.NumberTheory.Primes.Testing.Probabilistic ( isPrime , millerRabinV , bailliePSW , isStrongFermatPP , isFermatPP , lucasTest ) where import Data.Bits import Data.Mod import Data.Proxy import GHC.Base import GHC.Integer.GMP.Internals import GHC.TypeNats (KnownNat, SomeNat(..), someNatVal) import Math.NumberTheory.Moduli.JacobiSymbol import Math.NumberTheory.Utils import Math.NumberTheory.Roots -- | @isPrime n@ tests whether @n@ is a prime (negative or positive). -- It is a combination of trial division and Baillie-PSW test. -- -- If @isPrime n@ returns @False@ then @n@ is definitely composite. -- There is a theoretical possibility that @isPrime n@ is @True@, -- but in fact @n@ is not prime. However, no such numbers are known -- and none exist below @2^64@. If you have found one, please report it, -- because it is a major discovery. isPrime :: Integer -> Bool isPrime n | n < 0 = isPrime (-n) | n < 2 = False | n < 4 = True | otherwise = millerRabinV 0 n -- trial division test && bailliePSW n -- | Miller-Rabin probabilistic primality test. It consists of the trial -- division test and several rounds of the strong Fermat test with different -- bases. The choice of trial divisors and bases are -- implementation details and may change in future silently. -- -- First argument stands for the number of rounds of strong Fermat test. -- If it is 0, only trial division test is performed. -- -- If @millerRabinV k n@ returns @False@ then @n@ is definitely composite. -- Otherwise @n@ may appear composite with probability @1/4^k@. millerRabinV :: Int -> Integer -> Bool millerRabinV (I# k) n = case testPrimeInteger n k of 0# -> False _ -> True -- | @'isStrongFermatPP' n b@ tests whether non-negative @n@ is -- a strong Fermat probable prime for base @b@. -- -- Apart from primes, also some composite numbers have the tested -- property, but those are rare. Very rare are composite numbers -- having the property for many bases, so testing a large prime -- candidate with several bases can identify composite numbers -- with high probability. An odd number @n > 3@ is prime if and -- only if @'isStrongFermatPP' n b@ holds for all @b@ with -- @2 <= b <= (n-1)/2@, but of course checking all those bases -- would be less efficient than trial division, so one normally -- checks only a relatively small number of bases, depending on -- the desired degree of certainty. The probability that a randomly -- chosen base doesn't identify a composite number @n@ is less than -- @1/4@, so five to ten tests give a reasonable level of certainty -- in general. -- -- Please consult <https://miller-rabin.appspot.com Deterministic variants of the Miller-Rabin primality test> -- for the best choice of bases. isStrongFermatPP :: Integer -> Integer -> Bool isStrongFermatPP n b | n < 0 = error "isStrongFermatPP: negative argument" | n <= 1 = False | n == 2 = True | otherwise = case someNatVal (fromInteger n) of SomeNat (_ :: Proxy t) -> isStrongFermatPPMod (fromInteger b :: Mod t) isStrongFermatPPMod :: KnownNat n => Mod n -> Bool isStrongFermatPPMod b = b == 0 || a == 1 || go t a where m = -1 (t, u) = shiftToOddCount $ unMod m a = b ^% u go 0 _ = False go k x = x == m || go (k - 1) (x * x) -- | @'isFermatPP' n b@ tests whether @n@ is a Fermat probable prime -- for the base @b@, that is, whether @b^(n-1) `mod` n == 1@. -- This is a weaker but simpler condition. However, more is lost -- in strength than is gained in simplicity, so for primality testing, -- the strong check should be used. The remarks about -- the choice of bases to test from @'isStrongFermatPP'@ apply -- with the modification that if @a@ and @b@ are Fermat bases -- for @n@, then @a*b@ /always/ is a Fermat base for @n@ too. -- A /Charmichael number/ is a composite number @n@ which is a -- Fermat probable prime for all bases @b@ coprime to @n@. By the -- above, only primes @p <= n/2@ not dividing @n@ need to be tested -- to identify Carmichael numbers (however, testing all those -- primes would be less efficient than determining Carmichaelness -- from the prime factorisation; but testing an appropriate number -- of prime bases is reasonable to find out whether it's worth the -- effort to undertake the prime factorisation). isFermatPP :: Integer -> Integer -> Bool isFermatPP n b = case someNatVal (fromInteger n) of SomeNat (_ :: Proxy t) -> (fromInteger b :: Mod t) ^% (n-1) == 1 -- | Primality test after Baillie, Pomerance, Selfridge and Wagstaff. -- The Baillie-PSW test consists of a strong Fermat probable primality -- test followed by a (strong) Lucas primality test. This implementation -- assumes that the number @n@ to test is odd and larger than @3@. -- Even and small numbers have to be handled before. Also, before -- applying this test, trial division by small primes should be performed -- to identify many composites cheaply (although the Baillie-PSW test is -- rather fast, about the same speed as a strong Fermat test for four or -- five bases usually, it is, for large numbers, much more costly than -- trial division by small primes, the primes less than @1000@, say, so -- eliminating numbers with small prime factors beforehand is more efficient). -- -- The Baillie-PSW test is very reliable, so far no composite numbers -- passing it are known, and it is known (Gilchrist 2010) that no -- Baillie-PSW pseudoprimes exist below @2^64@. However, a heuristic argument -- by Pomerance indicates that there are likely infinitely many Baillie-PSW -- pseudoprimes. On the other hand, according to -- <http://mathworld.wolfram.com/Baillie-PSWPrimalityTest.html> there is -- reason to believe that there are none with less than several -- thousand digits, so that for most use cases the test can be -- considered definitive. bailliePSW :: Integer -> Bool bailliePSW n = isStrongFermatPP n 2 && lucasTest n -- precondition: n odd, > 3 (no small prime factors, typically large) -- | The Lucas-Selfridge test, including square-check, but without -- the Fermat test. For package-internal use only. lucasTest :: Integer -> Bool lucasTest n | isSquare n || d == 0 = False | d == 1 = True | otherwise = uo == 0 || go t vo qo where d = find True 5 find !pos cd = case jacobi (n `rem` cd) cd of MinusOne -> if pos then cd else (-cd) Zero -> if cd == n then 1 else 0 One -> find (not pos) (cd+2) q = (1-d) `quot` 4 (t,o) = shiftToOddCount (n+1) (uo, vo, qo) = testLucas n q o go 0 _ _ = False go s vn qn = vn == 0 || go (s-1) ((vn*vn-2*qn) `rem` n) ((qn*qn) `rem` n) -- n odd positive, n > abs q, index odd testLucas :: Integer -> Integer -> Integer -> (Integer, Integer, Integer) testLucas n q (S# i#) = look (finiteBitSize (0 :: Word) - 2) where j = I# i# look k | testBit j k = go (k-1) 1 1 1 q | otherwise = look (k-1) go k un un1 vn qn | k < 0 = (un, vn, qn) | testBit j k = go (k-1) u2n1 u2n2 v2n1 q2n1 | otherwise = go (k-1) u2n u2n1 v2n q2n where u2n = (un*vn) `rem` n u2n1 = (un1*vn-qn) `rem` n u2n2 = ((un1-q*un)*vn-qn) `rem` n v2n = (vn*vn-2*qn) `rem` n v2n1 = ((un1 - (2*q)*un)*vn-qn) `rem` n q2n = (qn*qn) `rem` n q2n1 = (qn*qn*q) `rem` n testLucas n q (Jp# bn#) = test (s# -# 1#) where s# = sizeofBigNat# bn# test j# = case indexBigNat# bn# j# of 0## -> test (j# -# 1#) w# -> look (j# -# 1#) (W# w#) (finiteBitSize (0 :: Word) - 1) look j# w i | testBit w i = go j# w (i - 1) 1 1 1 q | otherwise = look j# w (i-1) go k# w i un un1 vn qn | i < 0 = if isTrue# (k# <# 0#) then (un,vn,qn) else go (k# -# 1#) (W# (indexBigNat# bn# k#)) (finiteBitSize (0 :: Word) - 1) un un1 vn qn | testBit w i = go k# w (i-1) u2n1 u2n2 v2n1 q2n1 | otherwise = go k# w (i-1) u2n u2n1 v2n q2n where u2n = (un*vn) `rem` n u2n1 = (un1*vn-qn) `rem` n u2n2 = ((un1-q*un)*vn-qn) `rem` n v2n = (vn*vn-2*qn) `rem` n v2n1 = ((un1 - (2*q)*un)*vn-qn) `rem` n q2n = (qn*qn) `rem` n q2n1 = (qn*qn*q) `rem` n -- Listed as a precondition of lucasTest testLucas _ _ _ = error "lucasTest: negative argument"
cartazio/arithmoi
Math/NumberTheory/Primes/Testing/Probabilistic.hs
Haskell
mit
9,084
import Data.List import Data.List.Split import Data.Maybe import System.IO import Data.Char import qualified AStar main = do contents <- readFile "day11input.txt" let result = compute $ lines contents print result type Pair = (Int, Int) -- (Floor of microchip, Floor of generator) type State = (Int, [Pair]) -- (Floor of elevator, List of Pairs) compute :: [String] -> Int compute input = cost where Just (cost, path) = AStar.search initState isGoalState nextStates heuristic initState = generateInitialState input isGoalState :: State -> Bool isGoalState (_, pairs) = and $ map (\(i,j) -> i == 3 && j == 3) pairs nextStates :: State -> [(State, Int)] nextStates (elev, pairs) = map (\s -> (sortState s, 1)) validStates where validStates = filter validState newStates newStates = concat $ map (makeMove (elev, pairs)) ranges ranges = filter (\x -> length x < 3) seq seq = tail $ subsequences $ elemIndices elev $ unPairList pairs unPairList :: [(a,a)] -> [a] unPairList [] = [] unPairList ((x, y):xs) = x : y : unPairList xs makeMove :: State -> [Int] -> [State] makeMove (elev, pairs) moves = [moveUp] ++ [moveDown] where moveUp = (elev + 1, foldl (move elev True) pairs moves) moveDown = (elev - 1, foldl (move elev False) pairs moves) move :: Int -> Bool -> [Pair] -> Int -> [Pair] move floor up ((m,g):pairs) i | i == 0 = (newElem m, g) : pairs | i == 1 = (m, newElem g) : pairs | otherwise = (m, g) : move floor up pairs (i - 2) where newElem n = if up then n + 1 else n - 1 validState :: State -> Bool validState state@(elev, pairs) = elev > -1 && elev < 4 && unfriedState pairs pairs unfriedState :: [Pair] -> [Pair] -> Bool unfriedState _ [] = True unfriedState originalPairs ((m,g):pairs) | m == g = rest | otherwise = isNothing (find (\(a, b) -> b == m) (delete (m,g) originalPairs)) && rest where rest = unfriedState originalPairs pairs heuristic :: State -> Int heuristic (_, pairs) = sum $ map (\(i, j) -> 3 - i + 3 - j) pairs sortState :: State -> State sortState (elev, pairs) = (elev, sort pairs) generateInitialState :: [String] -> State generateInitialState input = (0, sort $ state ++ newElems) where newElems = [(0,0),(0,0)] state = collate . concat $ map (\i -> generateFloor i $ parsedInput !! i) [0 .. length parsedInput - 1] generateFloor i floor = map (\word -> (takeWhile (/= '-') word, "compatible" `isInfixOf` word, i)) floor parsedInput = map (concat . tail . splitWhen (== "a") . drop 4 . filter validWord . words) input validWord x = and $ map (\w -> not $ isPrefixOf w x) ["and", "generator", "microchip"] collate :: [(String, Bool, Int)] -> [Pair] collate [] = [] collate ((x, b, i):xs) = pair : collate (delete other xs) where pair = if b then (i,i') else (i',i) Just other@(_,_,i') = find (\(x',_,_) -> x == x') xs
aBhallo/AoC2016
Day 11/day11part2.hs
Haskell
mit
3,004
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.Delete where import Data.Maybe import qualified Data.Map as M import qualified Data.Text as T import Text.Parsec import Text.Parsec.Error import qualified Text.BibTeX.Parse as BibP import qualified Text.BibTeX.Format as BibF import Yesod.Markdown import Import import Barch.Adaptors import Barch.UploadUtils import Barch.Widgets (fullReferenceView) import Handler.Edit getDeleteR :: ReferenceId->Handler Html getDeleteR refid = do dbRef <- runDB $ get refid (formWidget, formEnctype) <- generateFormPost $ editReferenceForm dbRef let submission = Nothing :: Maybe Text handlerName = "getDeleteR" :: Text fieldText = "" :: Text parsed = Nothing reference = Nothing parseErrors = [] haveErrors = False defaultLayout $ do aDomId <- newIdent setTitle "Barch: Delete" $(widgetFile "delete") postDeleteR :: ReferenceId->Handler Html postDeleteR refid = do dbRef <- runDB $ get refid let handlerName = "postDeleteR" :: Text reference = Nothing parseErrors = [] haveErrors = False (editFormWidget, editFormEnctype) <- generateFormPost $ editReferenceForm dbRef files <- referenceFiles refid _ <- mapM deleteFile (entityKey <$> files) _ <- runDB $ delete refid defaultLayout $ do aDomId <- newIdent setTitle "Barch: Delete" $(widgetFile "edit")
klarh/barch
Handler/Delete.hs
Haskell
mit
1,469
module Language.Binal.Verifier where import Control.Applicative import Control.Monad import Control.Monad.State import Control.Lens import qualified Data.Maybe as Maybe import qualified Data.List as List import qualified Data.HashSet as HashSet import qualified Data.HashMap.Strict as HashMap import Language.Binal.Types import qualified Language.Binal.Util as Util examineFormOfParams :: AST -> [SyntaxError] examineFormOfParams lit@(Lit _ _) = examineForms lit examineFormOfParams (List [] _) = [] examineFormOfParams (List [_] pos) = [UnexpectedArity 2 1 pos] examineFormOfParams (List xs _) = concatMap examineFormOfParams xs -- 特殊形式が妥当か検査する examineForms :: AST -> [SyntaxError] examineForms (Lit lit pos) = do case Util.extractSym lit of Just s -> do if HashSet.member s Util.keywords then [KeywordUsedAsVariable s pos] else [] Nothing -> [] examineForms (List [] pos) = [UnexpectedArity 1 0 pos] examineForms (List xs pos) = do let instr = xs !! 0 case instr of Lit (SymLit "^") _ -> do if length xs /= 3 then [UnexpectedArity 3 (length xs) pos] else do let params = xs !! 1 let body = xs !! 2 examineFormOfParams params ++ examineForms body Lit (SymLit "seq") _ -> do if length xs == 1 then [UnexpectedArity 2 (length xs) pos] else concatMap examineForms (tail xs) Lit (SymLit "let") _ -> do if length xs /= 3 then [UnexpectedArity 3 (length xs) pos] else do let pattern = xs !! 1 let body = xs !! 2 examineFormOfParams pattern ++ examineForms body Lit (SymLit "letrec") _ -> do if length xs /= 3 then [UnexpectedArity 3 (length xs) pos] else do let pattern = xs !! 1 let body = xs !! 2 examineFormOfParams pattern ++ examineForms body Lit (SymLit "match") _ -> do if length xs < 3 then [UnexpectedArity 3 (length xs) pos] else concatMap examineForms (tail xs) Lit (SymLit "cond") _ -> do if odd (length xs) then [UnexpectedArity (length xs + 1) (length xs) pos] else concatMap examineForms (tail xs) Lit (SymLit "object") _ -> do if odd (length (tail xs)) then [UnexpectedArity (length (tail xs) + 1) (length (tail xs)) pos] else do let symbols = Maybe.catMaybes (map (\(x,i) -> if even i then Just x else Nothing) (zip (tail xs) ([0..] :: [Int]))) let exprs = Maybe.catMaybes (map (\(x,i) -> if odd i then Just x else Nothing) (zip (tail xs) ([0..] :: [Int]))) let r1 = concatMap (\x -> case x of Lit (SymLit _) _ -> [] _ -> [Malformed (Util.whereIsAST x)]) symbols r1 ++ concatMap examineForms exprs Lit (SymLit ".") _ -> do if length xs /= 3 then [UnexpectedArity 3 (length xs) pos] else case xs !! 2 of Lit (SymLit _) _ -> examineForms (xs !! 1) _ -> Malformed (Util.whereIsAST (xs !! 2)) : examineForms (xs !! 1) Lit (SymLit ":=") _ -> do let ex1 it@(Lit (SymLit _) _) = examineForms it ex1 (Lit _ pos1) = [Malformed pos1] ex1 it@(List [] _) = examineForms it ex1 (List ys pos1) = do let instr1 = ys !! 0 case instr1 of Lit (SymLit ".") _ -> do if length ys /= 3 then [UnexpectedArity 3 (length ys) pos1] else case ys !! 2 of Lit (SymLit _) _ -> ex1 (ys !! 1) _ -> Malformed (Util.whereIsAST (ys !! 2)) : ex1 (ys !! 1) _ -> [Malformed pos1] if length xs /= 3 then [UnexpectedArity 3 (length xs) pos] else ex1 (xs !! 1) ++ examineForms (xs !! 2) Lit (SymLit "assume") _ -> do if length xs /= 2 then [UnexpectedArity 2 (length xs) pos] else case xs !! 1 of Lit (SymLit _) _ -> [] _ -> [Malformed (Util.whereIsAST (xs !! 1))] _ -> concatMap examineForms xs examineNames' :: AST -> State (HashSet.HashSet String) [NotInScope] examineNames' (Lit (SymLit s) pos) = do env <- get if HashSet.member s env then return [] else return [NotInScope s pos] examineNames' (Lit (StrLit _) _) = return [] examineNames' (Lit (NumLit _) _) = return [] examineNames' (Lit (BoolLit _) _) = return [] examineNames' (List [] _) = return [] examineNames' (List xs _) = do env <- get let instr = xs !! 0 case instr of Lit (SymLit "^") _ -> do let params = xs !! 1 let body = xs !! 2 let env' = foldr HashSet.insert env (Util.flatSymbols params) put env' r <- examineNames' body put env return r Lit (SymLit "seq") _ -> do rs <- mapM examineNames' (tail xs) return (concat rs) Lit (SymLit "let") _ -> do let pattern = xs !! 1 let body = xs !! 2 r <- examineNames' body let env' = foldr HashSet.insert env (Util.flatSymbols pattern) put env' return r Lit (SymLit "letrec") _ -> do let pattern = xs !! 1 let body = xs !! 2 let env' = foldr HashSet.insert env (Util.flatSymbols pattern) put env' examineNames' body Lit (SymLit "match") _ -> do rs <- mapM examineNames' (tail xs) return (concat rs) Lit (SymLit "cond") _ -> do rs <- mapM examineNames' (tail xs) return (concat rs) Lit (SymLit "object") _ -> do let exprs = Maybe.catMaybes (map (\(x,i) -> if odd i then Just x else Nothing) (zip (tail xs) ([0..] :: [Int]))) rs <- mapM examineNames' exprs return (concat rs) Lit (SymLit ".") _ -> do examineNames' (xs !! 1) Lit (SymLit ":=") _ -> do rs <- mapM examineNames' (tail xs) return (concat rs) Lit (SymLit "assume") _ -> do let Lit (SymLit s) _ = xs !! 1 let env' = HashSet.insert s env put env' return [] _ -> do rs <- mapM examineNames' xs return (concat rs) examineNames :: AST -> [NotInScope] examineNames ast = evalState (examineNames' ast) Util.primitives gensym :: TypeInferer Variable gensym = do var <- uses _2 head _2 %= tail return var makePoly :: TypedAST -> TypeInferer () makePoly (TyLit _ ty1 _) = Util.traverseVarTyM (\ty -> case ty of VarTy i -> _4 %= HashSet.insert i _ -> return ()) ty1 makePoly (TyList (TyLit (SymLit "^") _ _:_) ty1 _) = Util.traverseVarTyM (\ty -> case ty of VarTy i -> _4 %= HashSet.insert i _ -> return ()) ty1 makePoly _ = return () freshPoly' :: TyKind -> StateT (HashMap.HashMap Variable Variable) (State (TypeEnv, [Variable], [Constraint], PolyEnv)) TyKind freshPoly' (VarTy i) = do isPoly <- lift (uses _4 (HashSet.member i)) if isPoly then do polys <- get case HashMap.lookup i polys of Just poly -> return (VarTy poly) Nothing -> do var <- lift gensym modify (HashMap.insert i var) return (VarTy var) else return (VarTy i) freshPoly' (RecTy i ty) = do VarTy i' <- freshPoly' (VarTy i) ty' <- freshPoly' ty return (RecTy i' ty') freshPoly' SymTy = return SymTy freshPoly' StrTy = return StrTy freshPoly' NumTy = return NumTy freshPoly' BoolTy = return BoolTy freshPoly' (ArrTy x y) = ArrTy <$> freshPoly' x <*> freshPoly' y freshPoly' (ListTy tys) = ListTy <$> mapM freshPoly' tys freshPoly' (EitherTy tys) = EitherTy <$> mapM freshPoly' tys freshPoly' (ObjectTy i xs) = do xs' <- mapM (\(key, val) -> do { x <- freshPoly' val ; return (key, x) }) (HashMap.toList xs) return (ObjectTy i (HashMap.fromList xs')) freshPoly' (MutableTy ty) = MutableTy <$> freshPoly' ty freshPoly :: TyKind -> TypeInferer TyKind freshPoly ty = evalStateT (freshPoly' ty) HashMap.empty unifyEnv :: TypeInferer () unifyEnv = do env <- use _1 constraints <- use _3 _1 .= HashMap.map (unify (reverse constraints)) env inferTypeOfParams :: AST -> TypeInferer TypedAST inferTypeOfParams x@(Lit _ _) = inferType' x inferTypeOfParams (List xs pos) = do xs' <- mapM inferTypeOfParams xs let ty = ListTy (map Util.typeof xs') return (TyList xs' ty pos) inferType' :: AST -> TypeInferer TypedAST inferType' (Lit lit@(SymLit "true") pos) = return (TyLit lit BoolTy pos) inferType' (Lit lit@(SymLit "false") pos) = return (TyLit lit BoolTy pos) inferType' (Lit lit@(SymLit s) pos) = do env <- use _1 ty <- freshPoly (Maybe.fromJust (HashMap.lookup s env)) return (TyLit lit ty pos) inferType' (Lit lit@(StrLit _) pos) = return (TyLit lit StrTy pos) inferType' (Lit lit@(NumLit _) pos) = return (TyLit lit NumTy pos) inferType' (Lit lit@(BoolLit _) pos) = return (TyLit lit BoolTy pos) inferType' (List xs pos) = do let instr = xs !! 0 case instr of Lit (SymLit "^") pos1 -> do let params = xs !! 1 let body = xs !! 2 let syms = Util.flatSymbols params env <- use _1 forM_ syms $ \sym -> do var <- gensym _1 %= HashMap.insert sym (VarTy var) typedBody <- inferType' body typedParams <- inferTypeOfParams params _1 .= env unifyEnv constraints <- use _3 let unifiedBody = Util.mapTyKind (unify (reverse constraints)) typedBody let unifiedParams = Util.mapTyKind (unify (reverse constraints)) typedParams return (TyList [TyLit (SymLit "^") SymTy pos1, unifiedParams, unifiedBody] (ArrTy (Util.typeof unifiedParams) (Util.typeof unifiedBody)) pos) Lit (SymLit "seq") pos1 -> do xs' <- mapM inferType' (tail xs) return (TyList (TyLit (SymLit "seq") SymTy pos1:xs') (Util.typeof (last xs')) pos) Lit (SymLit "let") pos1 -> do let pattern = xs !! 1 let body = xs !! 2 let syms = Util.flatSymbols pattern typedBody <- inferType' body makePoly typedBody forM_ syms $ \sym -> do var <- gensym _1 %= HashMap.insert sym (VarTy var) typedPattern <- inferTypeOfParams pattern let bodyTy = Util.typeof typedBody let patTy = Util.typeof typedPattern let absurd = UnexpectedType bodyTy patTy (Util.whereIs typedPattern) _3 %= (Subtype bodyTy patTy absurd :) unifyEnv constraints <- use _3 let unifiedPattern = Util.mapTyKind (unify (reverse constraints)) typedPattern return (TyList [TyLit (SymLit "let") SymTy pos1, unifiedPattern, typedBody] (ListTy []) pos) Lit (SymLit "letrec") pos1 -> do let pattern = xs !! 1 let body = xs !! 2 let syms = Util.flatSymbols pattern forM_ syms $ \sym -> do var <- gensym _1 %= HashMap.insert sym (VarTy var) typedBody <- inferType' body typedPattern <- inferTypeOfParams pattern let bodyTy = Util.typeof typedBody let patTy = Util.typeof typedPattern let absurd = UnexpectedType bodyTy patTy (Util.whereIs typedPattern) _3 %= (Subtype bodyTy patTy absurd :) unifyEnv constraints <- use _3 let unifiedBody = Util.mapTyKind (unify (reverse constraints)) typedBody let unifiedPattern = Util.mapTyKind (unify (reverse constraints)) typedPattern makePoly unifiedBody return (TyList [TyLit (SymLit "letrec") SymTy pos1, unifiedPattern, unifiedBody] (ListTy []) pos) Lit (SymLit "match") pos1 -> do expr <- inferType' (xs !! 1) patterns <- mapM inferType' (drop 2 xs) syms <- mapM (\_ -> (,) <$> gensym <*> gensym) patterns forM_ (zip patterns syms) $ \(pat, (x, y)) -> do let patTy = Util.typeof pat let expected = ArrTy (VarTy x) (VarTy y) _3 %= (Subtype patTy expected (UnexpectedType expected patTy (Util.whereIs pat)) :) let exprTy = Util.typeof expr let srcTys = map (\(x, _) -> VarTy x) syms let expected = EitherTy srcTys let retTy = EitherTy (map (\(_, y) -> VarTy y) syms) _3 %= (Subtype exprTy expected (UnexpectedType expected exprTy (Util.whereIs expr)) :) unifyEnv constraints <- use _3 env <- use _1 _1 .= HashMap.map (Util.flatEitherTy (negate 1)) env let unifiedExpr = Util.mapTyKind (Util.flatEitherTy (negate 1) . unify (reverse constraints)) expr let unifiedPatterns = map (Util.mapTyKind (Util.flatEitherTy (negate 1) . unify (reverse constraints))) patterns return (TyList (TyLit (SymLit "match") SymTy pos1:unifiedExpr:unifiedPatterns) (Util.flatEitherTy (negate 1) (unify (reverse constraints) retTy)) pos) Lit (SymLit "cond") pos1 -> do exprs <- mapM inferType' (tail xs) let conds = Maybe.catMaybes (map (\(x,i) -> if even i then Just x else Nothing) (zip (init exprs) ([0..] :: [Int]))) let thenClauses = Maybe.catMaybes (map (\(x,i) -> if odd i then Just x else Nothing) (zip exprs ([0..] :: [Int]))) let elseClause = last exprs forM_ conds $ \cond -> do let ty = Util.typeof cond _3 %= (Subtype ty BoolTy (UnexpectedType BoolTy ty (Util.whereIs cond)) :) unifyEnv constraints <- use _3 let retTy = Util.flatEitherTy (negate 1) (EitherTy (map Util.typeof thenClauses ++ [Util.typeof elseClause])) return (Util.mapTyKind (unify (reverse constraints)) (TyList (TyLit (SymLit "cond") SymTy pos1:exprs) retTy pos)) Lit (SymLit "object") pos1 -> do let symbols = Maybe.catMaybes (map (\(x,i) -> if even i then Just x else Nothing) (zip (tail xs) ([0..] :: [Int]))) let exprs = Maybe.catMaybes (map (\(x,i) -> if odd i then Just x else Nothing) (zip (tail xs) ([0..] :: [Int]))) let propertyNames = Maybe.catMaybes (map (\x -> case x of Lit (SymLit s) _ -> Just s _ -> Nothing) symbols) typedExprs <- mapM inferType' exprs let tys = map Util.typeof typedExprs i <- gensym let ty = ObjectTy (HashSet.singleton i) (HashMap.fromList (zip propertyNames tys)) return (TyList (TyLit (SymLit "object") SymTy pos1:concatMap (\(k1, (k,v)) -> [TyLit (SymLit k) SymTy (Util.whereIsAST k1),v]) (zip symbols (zip propertyNames typedExprs))) ty pos) Lit (SymLit ".") pos1 -> do let Lit (SymLit propertyName) pos2 = xs !! 2 let expr = xs !! 1 typedExpr <- inferType' expr let exprTy = Util.typeof typedExpr i <- gensym x <- gensym let typedProp = TyLit (SymLit propertyName) (VarTy x) pos2 let expected = ObjectTy (HashSet.singleton i) (HashMap.singleton propertyName (VarTy x)) _3 %= (Equal expected exprTy (UnexpectedType expected exprTy (Util.whereIs typedExpr)) :) unifyEnv constraints <- use _3 let unifiedExpr = Util.mapTyKind (unify (reverse constraints)) typedExpr let unifiedProp = Util.mapTyKind (unify (reverse constraints)) typedProp return (Util.mapTyKind (unify (reverse constraints)) (TyList [TyLit (SymLit ".") SymTy pos1, unifiedExpr, unifiedProp] (VarTy x) pos)) Lit (SymLit ":=") pos1 -> do left <- inferType' (xs !! 1) right <- inferType' (xs !! 2) let leftTy = Util.typeof left let expected = MutableTy (Util.typeof right) _3 %= (Subtype expected leftTy (UnexpectedType expected leftTy (Util.whereIs left)) :) unifyEnv constraints <- use _3 return (Util.mapTyKind (unify (reverse constraints)) (TyList [TyLit (SymLit ":=") SymTy pos1, left, right] (ListTy []) pos)) Lit (SymLit "assume") pos1 -> do let Lit (SymLit sym) pos2 = xs !! 1 var <- gensym _1 %= HashMap.insert sym (VarTy var) return (TyList [ TyLit (SymLit "assume") SymTy pos1, TyLit (SymLit sym) (VarTy var) pos2 ] (ListTy []) pos) _ -> do let func = head xs let args = tail xs typedFunc <- inferType' func typedArgs <- mapM inferType' args let funcTy = Util.typeof typedFunc let argsTy = Util.flatListTy (ListTy (map Util.typeof typedArgs)) x <- gensym let expected = ArrTy argsTy (VarTy x) _3 %= (Subtype funcTy expected (UnexpectedType expected funcTy (Util.whereIs typedFunc)) :) unifyEnv constraints <- use _3 let unifiedFunc = Util.mapTyKind (unify (reverse constraints)) typedFunc let unifiedArgs = map (Util.mapTyKind (unify (reverse constraints))) typedArgs return (Util.mapTyKind (unify (reverse constraints)) (TyList (unifiedFunc:unifiedArgs) (VarTy x) pos)) inferType :: AST -> ([Absurd], TypedAST) inferType ast = do let (typedAST, (_, _, constraints, _)) = runState (inferType' ast) (Util.initialTypeEnv, Util.initialVarList, [], Util.initialPolyEnv) let absurds = cantUnify (reverse constraints) (List.nub absurds, Util.mapTyKind (unify (reverse constraints) . Util.flatListTy) typedAST) subst :: Variable -> TyKind -> TyKind -> TyKind subst i x y@(VarTy j) | i == j = x | otherwise = y subst i x (RecTy j ty) | i == j = RecTy j ty | otherwise = RecTy j (subst i x ty) subst _ _ SymTy = SymTy subst _ _ StrTy = StrTy subst _ _ NumTy = NumTy subst _ _ BoolTy = BoolTy subst i x (ArrTy y z) = ArrTy (subst i x y) (subst i x z) subst i x (ListTy xs) = ListTy (map (subst i x) xs) subst i x (EitherTy xs) = EitherTy (map (subst i x) xs) subst i x@(ObjectTy j ys) (ObjectTy k xs) | HashSet.member i k = ObjectTy (HashSet.union j k) (HashMap.union xs ys) | otherwise = ObjectTy k (HashMap.map (subst i x) xs) subst i x (ObjectTy j xs) = ObjectTy j (HashMap.map (subst i x) xs) subst i x (MutableTy ty) = MutableTy (subst i x ty) substConstraint :: Variable -> TyKind -> Constraint -> Constraint substConstraint i y (Equal ty1 ty2 absurd) = Equal (subst i y ty1) (subst i y ty2) (substAbsurd i y absurd) substConstraint i y (Subtype ty1 ty2 absurd) = Subtype (subst i y ty1) (subst i y ty2) (substAbsurd i y absurd) substAbsurd :: Variable -> TyKind -> Absurd -> Absurd substAbsurd i y (UnexpectedType ty1 ty2 pos) = UnexpectedType (subst i y ty1) (subst i y ty2) pos unify :: [Constraint] -> TyKind -> TyKind unify = snd . unify' cantUnify :: [Constraint] -> [Absurd] cantUnify = fst . unify' unify' :: [Constraint] -> ([Absurd], TyKind -> TyKind) unify' [] = ([], id) unify' (Subtype s t absurd:c) | s == t = unify' c | otherwise = do let tmp1 = Util.extractVarTy s let tmp2 = Util.extractVarTy t let i = Maybe.fromJust tmp1 let j = Maybe.fromJust tmp2 if Maybe.isJust tmp1 then do let t' = Util.flatEitherTy i t if not (elem i (Util.freeVariables t')) then do let (absurds, substitution) = unify' (map (substConstraint i t') c) (absurds, substitution . subst i t') else do let (absurds, substitution) = unify' (map (substConstraint i (RecTy i t')) c) (absurds, substitution . subst i (RecTy i t')) else if Maybe.isJust tmp2 then do let s' = Util.flatEitherTy j s if not (elem j (Util.freeVariables s')) then do let (absurds, substitution) = unify' (map (substConstraint j s') c) (absurds, substitution . subst j s') else do let (absurds, substitution) = unify' (map (substConstraint j (RecTy j s')) c) (absurds, substitution . subst j (RecTy j s')) else case (s, t) of (ArrTy s1 s2, ArrTy t1 t2) -> unify' (Subtype t1 s1 absurd:Subtype s2 t2 absurd:c) (RecTy _ s1, RecTy _ t1) -> do unify' (Subtype s1 t1 absurd:c) (MutableTy s1, MutableTy t1) -> unify' (Subtype s1 t1 absurd:c) (EitherTy ss, _) -> do let results = map (\s1 -> unify' [Subtype s1 t absurd]) ss if all (\(absurds, _) -> null absurds) results then do let substitution = foldr (\(_, substitution1) substitution2 -> substitution1 . substitution2) id results let (absurds, substitution1) = unify' c (absurds, substitution1 . substitution) else do let (absurds, substitution) = unify' c let (absurds1, substitution1) = head results (absurds ++ absurds1, substitution . substitution1) (_, EitherTy ts) -> do let results = map (\t1 -> unify' (Subtype s t1 absurd:c)) ts let r = foldl1 (\(absurds1, substitution1) (absurds2, substitution2) -> case absurds1 of [] -> (absurds1, substitution1) _ -> (absurds2, substitution2)) results case fst r of [] -> r _ -> head results (RecTy k s1, _) -> unify' (Subtype (subst k s s1) t absurd:c) (_, RecTy k t1) -> unify' (Subtype s (subst k t t1) absurd:c) (ListTy [], _) -> do let (absurds, substitution) = unify' c (absurd:absurds, substitution) (_, ListTy []) -> do let (absurds, substitution) = unify' c (absurd:absurds, substitution) (ListTy xs, ListTy ys) | length xs == length ys -> unify' (map (\(a,b) -> Subtype a b absurd) (zip xs ys) ++ c) | length xs < length ys -> do let len = length xs - 1 let xs1 = take len xs let ys1 = take len ys let xs2 = last xs let ys2 = ListTy (drop len ys) unify' (map (\(a,b) -> Subtype a b absurd) (zip xs1 ys1) ++ [Subtype xs2 ys2 absurd] ++ c) | length xs > length ys -> do let len = length ys - 1 let xs1 = take len xs let ys1 = take len ys let xs2 = ListTy (drop len xs) let ys2 = last ys unify' (map (\(a,b) -> Subtype a b absurd) (zip xs1 ys1) ++ [Subtype xs2 ys2 absurd] ++ c) (ObjectTy _ xs, ObjectTy _ ys) -> do let xKeys = HashMap.keys xs let yKeys = HashMap.keys ys if all (\x -> elem x xKeys) yKeys then do let c' = map (\key -> Subtype (Maybe.fromJust (HashMap.lookup key xs)) (Maybe.fromJust (HashMap.lookup key ys)) absurd) yKeys unify' (c'++c) else do let (absurds, substitution) = unify' c (absurd:absurds, substitution) _ -> do unify' (Equal s t absurd:c) unify' (Equal s t absurd:c) | s == t = unify' c | otherwise = do let tmp1 = Util.extractVarTy s let tmp2 = Util.extractVarTy t let i = Maybe.fromJust tmp1 let j = Maybe.fromJust tmp2 if Maybe.isJust tmp1 then do let t' = Util.flatEitherTy i t if not (elem i (Util.freeVariables t')) then do let (absurds, substitution) = unify' (map (substConstraint i t') c) (absurds, substitution . subst i t') else do let (absurds, substitution) = unify' (map (substConstraint i (RecTy i t')) c) (absurds, substitution . subst i (RecTy i t')) else if Maybe.isJust tmp2 then do let s' = Util.flatEitherTy j s if not (elem j (Util.freeVariables s')) then do let (absurds, substitution) = unify' (map (substConstraint j s') c) (absurds, substitution . subst j s') else do let (absurds, substitution) = unify' (map (substConstraint j (RecTy j s')) c) (absurds, substitution . subst j (RecTy j s')) else case (s, t) of (ArrTy s1 s2, ArrTy t1 t2) -> unify' (Equal t1 s1 absurd:Equal s2 t2 absurd:c) (ListTy [], _) -> do let (absurds, substitution) = unify' c (absurd:absurds, substitution) (_, ListTy []) -> do let (absurds, substitution) = unify' c (absurd:absurds, substitution) (ListTy xs, ListTy ys) | length xs == length ys -> unify' (map (\(a,b) -> Equal a b absurd) (zip xs ys) ++ c) | length xs < length ys -> do let len = length xs - 1 let xs1 = take len xs let ys1 = take len ys let xs2 = last xs let ys2 = ListTy (drop len ys) unify' (map (\(a,b) -> Equal a b absurd) (zip xs1 ys1) ++ [Equal xs2 ys2 absurd] ++ c) | length xs > length ys -> do let len = length ys - 1 let xs1 = take len xs let ys1 = take len ys let xs2 = ListTy (drop len xs) let ys2 = last ys unify' (map (\(a,b) -> Equal a b absurd) (zip xs1 ys1) ++ [Equal xs2 ys2 absurd] ++ c) (ObjectTy k xs, ObjectTy l ys) -> do let xKeys = HashMap.keys xs let yKeys = HashMap.keys ys if any (\x -> elem x yKeys) xKeys then do unify' (Subtype s t absurd:c) else do let (absurds, substitution) = unify' c (absurds, substitution . foldl (\f v -> subst v t . f) id (HashSet.toList k) . foldl (\f v -> subst v s . f) id (HashSet.toList l)) (RecTy _ s1, RecTy _ t1) -> do unify' (Equal s1 t1 absurd:c) _ -> do let (absurds, substitution) = unify' c (absurd:absurds, substitution)
pasberth/binal1
Language/Binal/Verifier.hs
Haskell
mit
26,883
-------------------------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} import Data.Monoid (mappend) import Hakyll -------------------------------------------------------------------------------- main :: IO () main = hakyll $ do match "images/*" $ do route idRoute compile copyFileCompiler match "css/*" $ do route idRoute compile compressCssCompiler match (fromList ["about.rst", "contact.markdown"]) $ do route $ setExtension "html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/default.html" defaultContext >>= relativizeUrls match "posts/*" $ do route $ setExtension "html" compile $ pandocCompiler >>= loadAndApplyTemplate "templates/post.html" postCtx >>= loadAndApplyTemplate "templates/default.html" postCtx >>= relativizeUrls create ["archive.html"] $ do route idRoute compile $ do posts <- recentFirst =<< loadAll "posts/*" let archiveCtx = listField "posts" postCtx (return posts) `mappend` constField "title" "Archives" `mappend` defaultContext makeItem "" >>= loadAndApplyTemplate "templates/archive.html" archiveCtx >>= loadAndApplyTemplate "templates/default.html" archiveCtx >>= relativizeUrls match "index.html" $ do route idRoute compile $ do posts <- fmap (take 10).recentFirst =<< loadAll "posts/*" let indexCtx = listField "posts" postCtx (return posts) `mappend` constField "title" "Home" `mappend` defaultContext getResourceBody >>= applyAsTemplate indexCtx >>= loadAndApplyTemplate "templates/default.html" indexCtx >>= relativizeUrls match "templates/*" $ compile templateCompiler -------------------------------------------------------------------------------- postCtx :: Context String postCtx = dateField "date" "%B %e, %Y" `mappend` defaultContext
prannayk/Hakyll-Blog
site.hs
Haskell
mit
2,284
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module LambdaCmsOrg.Tutorial.Foundation where import Control.Arrow ((&&&)) import Data.Text (Text) import Network.Wai (requestMethod) import Yesod import LambdaCms.Core import LambdaCmsOrg.Tutorial.Message (TutorialMessage, defaultMessage, englishMessage) import qualified LambdaCmsOrg.Tutorial.Message as Msg import LambdaCmsOrg.Tutorial.Models data TutorialAdmin = TutorialAdmin mkYesodSubData "TutorialAdmin" $(parseRoutesFile "config/routes") instance LambdaCmsOrgTutorial master => RenderMessage master TutorialMessage where renderMessage = renderTutorialMessage type TutorialHandler a = forall master. LambdaCmsOrgTutorial master => HandlerT TutorialAdmin (HandlerT master IO) a type TutorialForm x = forall master. LambdaCmsOrgTutorial master => Html -> MForm (HandlerT master IO) (FormResult x, WidgetT master IO ()) class LambdaCmsAdmin master => LambdaCmsOrgTutorial master where tutorialR :: Route TutorialAdmin -> Route master renderTutorialMessage :: master -> [Text] -> TutorialMessage -> Text renderTutorialMessage m (lang:langs) = do case (lang `elem` (renderLanguages m), lang) of (True, "en") -> englishMessage _ -> renderTutorialMessage m langs renderTutorialMessage _ _ = defaultMessage defaultTutorialAdminMenu :: LambdaCmsOrgTutorial master => (Route TutorialAdmin -> Route master) -> [AdminMenuItem master] defaultTutorialAdminMenu tp = [ MenuItem (SomeMessage Msg.MenuTutorial) (tp TutorialAdminIndexR) "book" ] instance LambdaCmsOrgTutorial master => LambdaCmsLoggable master Tutorial where logMessage y "POST" = translateTutorialLogs y Msg.LogCreatedTutorial logMessage y "PATCH" = translateTutorialLogs y Msg.LogUpdatedTutorial logMessage y "DELETE" = translateTutorialLogs y Msg.LogDeletedTutorial logMessage _ _ = const [] translateTutorialLogs :: forall b master. ( LambdaCmsOrgTutorial master , RenderMessage master b ) => master -> (Text -> b) -> Tutorial -> [(Text, Text)] translateTutorialLogs y msg e = map (id &&& messageFor) $ renderLanguages y where messageFor lang = renderMessage y [lang] . msg $ tutorialTitle e logTutorial :: LambdaCmsOrgTutorial master => Tutorial -> HandlerT master IO [(Text, Text)] logTutorial tutorial = do y <- getYesod method <- waiRequest >>= return . requestMethod return $ logMessage y method tutorial
lambdacms/lambdacms.org
lambdacmsorg-tutorial/LambdaCmsOrg/Tutorial/Foundation.hs
Haskell
mit
3,035
module Main where -- import Control.Monad ( (<<) ) import System( getArgs ) import System.IO( stderr, hPutStrLn ) import System.Process( runCommand, waitForProcess) import Data.List( nub, sort, isPrefixOf ) main = do args <- getArgs if (length args >= 2) then do let file = head args let current_word = (head . tail) args procHandle <- runCommand $ command file exitcode <- waitForProcess procHandle text <- readFile "/tmp/textmatetags" mapM_ (putStrLn) $ sort . nub . filter (isPrefixOf current_word) $ map (head . words) (lines text) else hPutStrLn stderr "Provide a haskell file and a current word!" where command file = "echo \":ctags /tmp/textmatetags\" | ghci " ++ file ++" &> /tmp/runtags"
spockz/Haskell-Code-Completion-for-TextMate
Main.hs
Haskell
mit
904
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StaticPointers #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE BangPatterns #-} module Driver ( tests ) where import Test.Framework (Test, testGroup) import Test.HUnit hiding (Test) import Test.Framework.Providers.HUnit (testCase) import CodeWorld import CodeWorld.Driver import CodeWorld.Event import CodeWorld.CanvasM import System.Mem.StableName import Control.Concurrent import GHC.Prim tests :: Test tests = testGroup "Driver" [ testCase "toState preserves identity" $ do let wrapped = wrappedInitial 42 let target = toState id wrapped assertBool "" $ identical wrapped target , testCase "wrappedStep preserves identity" $ do -- Expected failure: See https://github.com/google/codeworld/issues/681 let wrapped = wrappedInitial 42 let target = wrappedStep (const id) 1 wrapped assertBool "" $ not $ identical wrapped target , testCase "wrapping of shared identity is shared (events)" $ do -- Expected failure: See https://github.com/google/codeworld/issues/681 let wrapped = wrappedInitial 42 let target = wrappedEvent (const []) (const id) (const id) (TimePassing 0) wrapped assertBool "" $ not $ identical wrapped target ]
pranjaltale16/codeworld
codeworld-api/test/Driver.hs
Haskell
apache-2.0
1,290
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE ScopedTypeVariables #-} -- :script test/Spark/Core/Internal/PathsSpec.hs module Spark.Core.Internal.PathsSpec where import Test.Hspec import qualified Data.Map.Strict as M import qualified Data.Set as S import qualified Data.ByteString.Char8 as C8 import qualified Data.Text as T import Spark.Core.StructuresInternal import Spark.Core.Functions import Spark.Core.Dataset import Spark.Core.Internal.Paths import Spark.Core.Internal.DAGStructures import Spark.Core.Internal.DAGFunctions import Spark.Core.Internal.ComputeDag import Spark.Core.Internal.PathsUntyped import Spark.Core.Internal.Utilities import Spark.Core.Internal.DatasetFunctions import Spark.Core.Internal.DatasetStructures data MyV = MyV { mvId :: VertexId, mvLogical :: [MyV], mvParents :: [MyV] } deriving (Eq) instance Show MyV where show v = "MyV(" ++ (C8.unpack . unVertexId . mvId $ v) ++ ")" assignPaths :: UntypedNode -> [UntypedNode] assignPaths n = let cgt = buildCGraph n :: DagTry (ComputeDag UntypedNode NodeEdge) cg = forceRight cgt acgt = assignPathsUntyped cg ncg = forceRight acgt in graphDataLexico . tieNodes $ ncg instance GraphVertexOperations MyV where vertexToId = mvId expandVertexAsVertices = mvParents myv :: String -> [MyV] -> [MyV] -> MyV myv s logical inner = MyV (VertexId (C8.pack s)) logical inner myvToVertex :: MyV -> Vertex MyV myvToVertex x = Vertex (mvId x) x buildScopes :: [MyV] -> Scopes buildScopes l = iGetScopes0 l' fun where l' = myvToVertex <$> l fun vx = ParentSplit { psLogical = myvToVertex <$> (mvLogical . vertexData $ vx), psInner = myvToVertex <$> (mvParents . vertexData $ vx) } simple :: [(Maybe String, [String])] -> Scopes simple [] = M.empty simple ((ms, ss) : t) = let key = VertexId . C8.pack <$> ms vals = VertexId . C8.pack <$> ss new = M.singleton key (S.fromList vals) in mergeScopes new (simple t) gatherings :: [(String, [[String]])] -> M.Map VertexId [[VertexId]] gatherings [] = M.empty gatherings ((key, paths) : t) = let k = VertexId . C8.pack $ key ps = (VertexId . C8.pack <$>) <$> paths new = M.singleton k ps in M.unionWith (++) new (gatherings t) gatherPaths' :: [MyV] -> M.Map VertexId [[VertexId]] gatherPaths' = gatherPaths . buildScopes spec :: Spec spec = do describe "Tests on paths" $ do it "nothing" $ do buildScopes [] `shouldBe` simple [] it "no parent" $ do let v0 = myv "v0" [] [] let res = [ (Nothing, ["v0"]), (Just "v0", []) ] buildScopes [v0] `shouldBe` simple res it "one logical parent" $ do let v0 = myv "v0" [] [] let v1 = myv "v1" [v0] [] let res = [ (Nothing, ["v0", "v1"]) , (Just "v1", []) , (Just "v0", []) ] buildScopes [v1, v0] `shouldBe` simple res it "one inner parent" $ do let v0 = myv "v0" [] [] let v1 = myv "v1" [] [v0] let res = [ (Nothing, ["v1"]) , (Just "v1", ["v0"]) , (Just "v0", []) ] buildScopes [v1, v0] `shouldBe` simple res it "logical scoping over a parent" $ do let v0 = myv "v0" [] [] let v1 = myv "v1" [v0] [] let v2 = myv "v2" [v0] [v1] let res = [ (Nothing, ["v0", "v2"]) , (Just "v0", []) , (Just "v1", []) , (Just "v2", ["v1"]) ] buildScopes [v2] `shouldBe` simple res it "common ancestor" $ do let top = myv "top" [] [] let inner = myv "inner" [top] [] let v1 = myv "v1" [top] [inner] let v2 = myv "v2" [top] [inner] let res = [ (Nothing, ["top", "v1", "v2"]) , (Just "inner", []) , (Just "top", []) , (Just "v1", ["inner"]) , (Just "v2", ["inner"]) ] buildScopes [v1, v2] `shouldBe` simple res it "common ancestor, unbalanced" $ do let top = myv "top" [] [] let inner = myv "inner" [top] [] let v1 = myv "v1" [top] [inner] let v2 = myv "v2" [] [inner] let res = [ (Nothing, ["top", "v1", "v2"]) , (Just "inner", []) , (Just "top", []) , (Just "v1", ["inner"]) , (Just "v2", ["inner", "top"]) ] buildScopes [v1, v2] `shouldBe` simple res describe "Path gatherings" $ do it "nothing" $ do gatherPaths' [] `shouldBe` gatherings [] it "no parent" $ do let v0 = myv "v0" [] [] let res = [("v0", [[]])] gatherPaths' [v0] `shouldBe` gatherings res it "one logical parent" $ do let v0 = myv "v0" [] [] let v1 = myv "v1" [v0] [] let res = [ ("v1", [[]]) , ("v0", [[]])] gatherPaths' [v1] `shouldBe` gatherings res it "one inner parent" $ do let v0 = myv "v0" [] [] let v1 = myv "v1" [] [v0] let res = [ ("v1", [[]]) , ("v0", [["v1"]])] gatherPaths' [v1] `shouldBe` gatherings res it "logical scoping over a parent" $ do let v0 = myv "v0" [] [] let v1 = myv "v1" [v0] [] let v2 = myv "v2" [v0] [v1] let res = [ ("v0", [[]]) , ("v1", [["v2"]]) , ("v2", [[]]) ] gatherPaths' [v2] `shouldBe` gatherings res it "common ancestor" $ do let top = myv "top" [] [] let inner = myv "inner" [top] [] let v1 = myv "v1" [top] [inner] let v2 = myv "v2" [top] [inner] let res = [ ("inner", [["v1"], ["v2"]]) , ("top", [[]]) , ("v1", [[]]) , ("v2", [[]]) ] gatherPaths' [v1, v2] `shouldBe` gatherings res describe "Real paths" $ do it "simple test" $ do let c0 = constant (1 :: Int) @@ "c0" let c1 = identity c0 @@ "c1" let c2 = identity c1 `logicalParents` [untyped c0] @@ "c2" nodeId <$> nodeParents c1 `shouldBe` [nodeId c0] nodeId <$> nodeParents c2 `shouldBe` [nodeId c1] let withParents = T.unpack . catNodePath . nodePath <$> assignPaths (untyped c2) withParents `shouldBe` ["c0", "c2/c1", "c2"] it "simple test 2" $ do let ds = dataset ([1 ,2, 3, 4]::[Int]) @@ "ds" let c = count ds @@ "c" let c2 = (c + (identity c @@ "id")) `logicalParents` [untyped ds] @@ "c2" let withParents = T.unpack . catNodePath . nodePath <$> assignPaths (untyped c2) withParents `shouldBe` ["ds", "c2/c","c2/id","c2"]
krapsh/kraps-haskell
test/Spark/Core/Internal/PathsSpec.hs
Haskell
apache-2.0
6,446
module NLP.TAG.Vanilla.SubtreeSharing.Tests where import Control.Applicative ((<$>)) import qualified Data.Set as S import Test.Tasty (TestTree, testGroup) -- , localOptions) import Test.HUnit (Assertion, (@?=)) import Test.Tasty.HUnit (testCase) import NLP.TAG.Vanilla.Tree (Tree (..), AuxTree (..)) import NLP.TAG.Vanilla.Earley.Basic (recognize, recognizeFrom) import NLP.TAG.Vanilla.Rule (Rule) import qualified NLP.TAG.Vanilla.Rule as R import NLP.TAG.Vanilla.SubtreeSharing (compile) --------------------------------------------------------------------- -- Prerequisites --------------------------------------------------------------------- type Tr = Tree String String type AuxTr = AuxTree String String type Rl = Rule String String --------------------------------------------------------------------- -- Grammar 1 --------------------------------------------------------------------- tree1 :: Tr tree1 = INode "S" [ abc , INode "D" [ abc , INode "E" [] ] ] where abc = INode "A" [ INode "B" [] , INode "C" [] ] tree2 :: Tr tree2 = INode "S" [ INode "D" [ abc , INode "E" [] ] , abc ] where abc = INode "A" [ INode "B" [] , INode "C" [] ] tree3 :: Tr tree3 = INode "D" [ abc , INode "E" [] ] where abc = INode "A" [ INode "B" [] , INode "C" [] ] mkGram1 :: IO (S.Set Rl) mkGram1 = compile (map Left [tree1, tree2, tree3]) --------------------------------------------------------------------- -- Grammar 2 --------------------------------------------------------------------- aux1 :: AuxTr aux1 = AuxTree (INode "A" [ INode "B" [] , INode "C" [ INode "A" [] , INode "D" [] ] ]) [1, 0] aux2 :: AuxTr aux2 = AuxTree (INode "A" [ INode "C" [ INode "A" [] , INode "D" [] ] , INode "B" [] ]) [0, 0] aux3 :: Tr aux3 = INode "A" [ INode "B" [] , INode "C" [ INode "A" [] , INode "D" [] ] ] -- | Note: tree identical to `aux3`! aux4 :: Tr aux4 = INode "A" [ INode "B" [] , INode "C" [ INode "A" [] , INode "D" [] ] ] mkGram2 :: IO (S.Set Rl) mkGram2 = compile $ (map Left [aux3, aux4]) ++ (map Right [aux1, aux2]) --------------------------------------------------------------------- -- Tests --------------------------------------------------------------------- tests :: TestTree tests = testGroup "NLP.TAG.Vanilla.SubtreeSharing" [ testCase "Subtree Sharing (Initial)" testShareInit , testCase "Subtree Sharing (Auxiliary)" testShareAux ] testShareInit :: Assertion testShareInit = do gram <- mkGram1 S.size gram @?= 5 testShareAux :: Assertion testShareAux = do gram <- mkGram2 S.size gram @?= 5 localTest :: Assertion localTest = do gram <- mkGram1 mapM_ print $ S.toList gram -- --------------------------------------------------------------------- -- -- Utils -- --------------------------------------------------------------------- -- -- -- (@@?=) :: (Show a, Eq a) => IO a -> a -> Assertion -- mx @@?= y = do -- x <- mx -- x @?= y
kawu/tag-vanilla
src/NLP/TAG/Vanilla/SubtreeSharing/Tests.hs
Haskell
bsd-2-clause
3,252
{-# LANGUAGE OverloadedStrings #-} module Radiation.Parsers.Internal.CStyle where import Data.Attoparsec.ByteString.Char8 as BP import Data.Attoparsec.ByteString.Lazy as Lazy import qualified Data.Attoparsec.ByteString as BB import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Char8 as BSC import qualified Data.Char as C import Control.Applicative import Control.Monad import Data.Monoid (mappend) import My.Utils import Debug.Trace spaced :: Parser BS.ByteString -> Parser BS.ByteString spaced p = skipSpace *> p <* skipSpace attribute :: Parser BS.ByteString attribute = do string "__attribute__" skipSpace balancedParens removePattern :: Parser BS.ByteString -> Parser BS.ByteString removePattern pattern = BS.concat <$> many ((pattern >> return BS.empty) <|> (BS.singleton <$> BB.anyWord8)) subparse :: Parser a -> BS.ByteString -> Parser a subparse myParser bs = case parseOnly myParser bs of Left err -> fail err Right map -> return map (+>) :: Parser BS.ByteString -> Parser BS.ByteString -> Parser BS.ByteString (+>) p1 p2 = BS.append <$> p1 <*> p2 {- Take an identifier from the parser -} identifier :: Parser BS.ByteString identifier = skipSpace *> BP.takeWhile1 isIdentifierChar <* skipSpace notIdentifier :: Parser BS.ByteString notIdentifier = skipSpace *> BP.takeWhile1 (\c -> not (isIdentifierChar c || isSpace c)) <* skipSpace isIdentifierChar :: Char -> Bool isIdentifierChar ch = C.isDigit ch || C.isAlpha ch || ch == '_' between :: Char -> Char -> Parser BS.ByteString between open close = skipSpace *> char open *> (between open close <|> BP.takeWhile sat) <* char close where sat ch = ch /= open && ch /= close nextToken :: Parser BS.ByteString nextToken = identifier <|> notIdentifier token :: BS.ByteString -> Parser BS.ByteString token str = do tkn <- nextToken if tkn == str then return str else fail "Could not match token" balanced :: Char -> Char -> Parser BS.ByteString balanced c1 c2 = let looseBalanced :: BS.ByteString -> Int -> Parser BS.ByteString looseBalanced cur 0 = return cur looseBalanced cur n = do rest <- BP.takeWhile (\ch -> ch /= c1 && ch /= c2) ch <- char c1 <|> char c2 let cur' = cur `mappend` rest `mappend` BSC.singleton ch case () of () | ch == c1 -> looseBalanced cur' (n + 1) | ch == c2 -> looseBalanced cur' (n - 1) | otherwise -> looseBalanced cur' n in BP.char c1 >> looseBalanced (BSC.singleton c1) 1 balancedParens :: Parser BS.ByteString balancedParens = balanced '(' ')' body :: Parser BS.ByteString body = balanced '{' '}' parens :: Parser BS.ByteString parens = between '(' ')' nextWord :: BS.ByteString -> Parser BS.ByteString nextWord str = BP.takeWhile C.isSpace +> string str primitive :: Parser BS.ByteString primitive = skipSpace *> choice [integral, floating] -- >>= (\bs -> if BS.null bs then fail "" else return bs) where integral = option "" (option "" (string "un") +> nextWord "signed") +> choice (map nextWord ["int","char"]) floating = string "float" data CTypeHeader = CTypeHeader (Maybe (BS.ByteString,BS.ByteString)) {- Parses a type in C. Tries to do all possibilities, including - anonymous structures, but alas it proves difficult -} ctype :: Parser CTypeHeader ctype = (<|>) (primitive $> CTypeHeader Nothing) $ do typeoftype <- optional (choice $ fmap string ["struct","enum","union"]) id1 <- (body $> Nothing) <|> (Just <$> (identifier <* body)) identifier `mplus` (BSC.pack <$> many (skipSpace *> char '*' <* skipSpace)) return $ CTypeHeader ((,) <$> typeoftype <*> id1) {- Parses C++ types. These inculde the apersaned for - references -} cpptype :: Parser BS.ByteString cpptype = identifier `mplus` (BSC.pack <$> many (skipSpace *> (char '*' <|> char '&') <* skipSpace))
jrahm/Radiation
src/Radiation/Parsers/Internal/CStyle.hs
Haskell
bsd-2-clause
4,032
-- | The Ox monad facilitates writing functional expressions over the -- input sentence with arbitrary type of sentence token. module Control.Monad.Ox ( -- * Types Ox , Id -- * Functions , save , saves , when , whenJT , group -- * Ox monad execution , execOx -- * Utilities , atWith , atsWith ) where import Control.Applicative ((<$>), (<*), (*>)) import Control.Arrow (first) import Control.Monad.State hiding (when) import Control.Monad.Writer hiding (when) import Data.Maybe (maybeToList) import qualified Data.Vector as V -- | Observation type identifier. It consists of a list of -- integers, each integer representing a state of the Ox -- monad on the particular level. type Id = [Int] -- | Increment the integer component of the top-most level. inc :: Id -> Id inc [] = error "incId: null id" inc (x:xs) = x+1 : xs -- | Push new value to the Id stack. grow :: Id -> Id grow xs = 1 : xs -- | Pop value from the stack. shrink :: Id -> Id shrink [] = error "shrink: null id" shrink (_:xs) = xs -- | Set the top-most component to the given value. getTop :: Id -> Int getTop [] = error "getTop: null id" getTop (x:_) = x -- | Set the top-most component to the given value. setTop :: Int -> Id -> Id setTop _ [] = error "setTop: null id" setTop x (_:xs) = x:xs -- | The Ox is a monad stack with observation type identifier handled by -- the state monad and the resulting observation values paired with identifiers -- printed using the writer monad. type Ox o a = WriterT [(Id, o)] (State Id) a -- | Retrieve the current identifier value. getId :: Ox o Id getId = lift get {-# INLINE getId #-} -- | Set the new identifier value. setId :: Id -> Ox o () setId = lift . put {-# INLINE setId #-} -- | Update the current identifier of the Ox monad. updateId :: (Id -> Id) -> Ox o () updateId f = do i <- getId setId (f i) -- | Increase the current identifier of the Ox monad. incId :: Ox o () incId = updateId inc -- | Perform the identifier-dependent action and increase the identifier. withId :: (Id -> Ox o a) -> Ox o a withId act = do x <- act =<< getId incId return x -- | Perform the Ox action on the lower level. below :: Ox o a -> Ox o a below act = updateId grow *> act <* updateId shrink -- | Save observation values in the writer monad of the Ox stack. saves :: [o] -> Ox o () saves xs = withId $ \i -> tell [(i, x) | x <- xs] -- | Save the observation value. save :: Maybe o -> Ox o () save = saves . maybeToList -- | Perform the Ox action only when the 'cond' is True. It works like -- the standard 'Control.Monad.when' function but also changes the current -- identifier value. when :: Bool -> Ox o a -> Ox o (Maybe a) when cond act = do x <- case cond of False -> return Nothing True -> Just <$> below act incId return x -- | Perform the action only when the given condition is equal to Just True. whenJT :: Maybe Bool -> Ox o a -> Ox o (Maybe a) whenJT cond = when (justTrue cond) where justTrue Nothing = False justTrue (Just x) = x -- | Make all embedded observations to be indistinguishable with respect -- to their top-most identifier components. -- TODO: Perhaps should set only the current level, not the deeper ones. group :: Ox o a -> Ox o a group act = do i <- getId let top = getTop i x <- censor (map . first . setTop $ top) act setId (inc i) return x -- | Execute the Ox monad and retrieve the saved (with the 'save' and -- 'saves' functions) results. execOx :: Ox o a -> [(Id, o)] execOx ox = (map (first reverse) . fst) (runState (execWriterT ox) [1]) ------------------------------ -- Utilities ------------------------------ -- | Value of the 't -> a' function with respect to the given sentence -- and sentence position. Return Nothing if the position is out of -- bounds. atWith :: V.Vector a -> (a -> b) -> Int -> Maybe b atWith xs f k = if k < 0 || k >= V.length xs then Nothing else Just $ f (xs V.! k) -- | Value of the 't -> [a]' function with respect to the given sentence -- and sentence position. Return empty list if the position is out of -- bounds. atsWith :: V.Vector a -> (a -> [b]) -> Int -> [b] atsWith xs f k = if k < 0 || k >= V.length xs then [] else f (xs V.! k)
kawu/monad-ox
Control/Monad/Ox.hs
Haskell
bsd-2-clause
4,293
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} module Tap ( Tap (..) , TapRoute (..) , resourcesTap , Handler , Widget , module Yesod.Core , module Settings , StaticRoute (..) , lift , liftIO ) where import Tap.Redis import Yesod.Core import Yesod.Helpers.Static import qualified Settings import System.Directory import qualified Data.ByteString.Lazy as L import Settings (hamletFile, cassiusFile, luciusFile, juliusFile, widgetFile) import StaticFiles import Control.Monad (unless) import Control.Monad.Trans.Class (lift) import Control.Monad.IO.Class (liftIO) import qualified Data.Text as T import qualified Data.Sequence as Seq import qualified Data.ByteString as B -- | The site argument for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data Tap = Tap { getStatic :: Static -- ^ Settings for static file serving. , getMessages :: AtomicMessageStore } -- | A useful synonym; most of the handler functions in your application -- will need to be of this type. type Handler = GHandler Tap Tap -- | A useful synonym; most of the widgets functions in your application -- will need to be of this type. type Widget = GWidget Tap Tap -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://docs.yesodweb.com/book/web-routes-quasi/ -- -- This function does three things: -- -- * Creates the route datatype TapRoute. Every valid URL in your -- application can be represented as a value of this type. -- * Creates the associated type: -- type instance Route Tap = TapRoute -- * Creates the value resourcesTap which contains information on the -- resources declared below. This is used in Controller.hs by the call to -- mkYesodDispatch -- -- What this function does *not* do is create a YesodSite instance for -- Tap. Creating that instance requires all of the handler functions -- for our application to be in scope. However, the handler functions -- usually require access to the TapRoute datatype. Therefore, we -- split these actions into two functions and place them in separate files. mkYesodData "Tap" $(parseRoutesFile "config/routes") -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod Tap where approot _ = Settings.approot defaultLayout widget = do mmsg <- getMessage pc <- widgetToPageContent $ do widget addCassius $(Settings.cassiusFile "default-layout") hamletToRepHtml $(Settings.hamletFile "default-layout") -- This is done to provide an optimization for serving static files from -- a separate domain. Please see the staticroot setting in Settings.hs urlRenderOverride a (StaticR s) = Just $ uncurry (joinPath a Settings.staticroot) $ renderRoute s urlRenderOverride _ _ = Nothing -- This function creates static content files in the static folder -- and names them based on a hash of their content. This allows -- expiration dates to be set far in the future without worry of -- users receiving stale content. addStaticContent ext' _ content = do let fn = base64md5 content ++ '.' : T.unpack ext' let statictmp = Settings.staticdir ++ "/tmp/" liftIO $ createDirectoryIfMissing True statictmp let fn' = statictmp ++ fn exists <- liftIO $ doesFileExist fn' unless exists $ liftIO $ L.writeFile fn' content return $ Just $ Right (StaticR $ StaticRoute ["tmp", T.pack fn] [], [])
KirinDave/redis-conduit
Tap.hs
Haskell
bsd-2-clause
3,858
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QTextDocument_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:28 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QTextDocument_h ( QcreateObject_h(..) ) where import Foreign.C.Types import Qtc.Enums.Base import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QTextDocument ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTextDocument_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QTextDocument_unSetUserMethod" qtc_QTextDocument_unSetUserMethod :: Ptr (TQTextDocument a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QTextDocumentSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTextDocument_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QTextDocument ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTextDocument_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QTextDocumentSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTextDocument_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QTextDocument ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTextDocument_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QTextDocumentSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTextDocument_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QTextDocument ()) (QTextDocument x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QTextDocument setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QTextDocument_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QTextDocument_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQTextDocument x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTextDocument_setUserMethod" qtc_QTextDocument_setUserMethod :: Ptr (TQTextDocument a) -> CInt -> Ptr (Ptr (TQTextDocument x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QTextDocument :: (Ptr (TQTextDocument x0) -> IO ()) -> IO (FunPtr (Ptr (TQTextDocument x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QTextDocument_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QTextDocumentSc a) (QTextDocument x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QTextDocument setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QTextDocument_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QTextDocument_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQTextDocument x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QTextDocument ()) (QTextDocument x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QTextDocument setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QTextDocument_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QTextDocument_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQTextDocument x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTextDocument_setUserMethodVariant" qtc_QTextDocument_setUserMethodVariant :: Ptr (TQTextDocument a) -> CInt -> Ptr (Ptr (TQTextDocument x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QTextDocument :: (Ptr (TQTextDocument x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQTextDocument x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QTextDocument_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QTextDocumentSc a) (QTextDocument x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QTextDocument setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QTextDocument_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QTextDocument_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQTextDocument x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QTextDocument ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QTextDocument_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QTextDocument_unSetHandler" qtc_QTextDocument_unSetHandler :: Ptr (TQTextDocument a) -> CWString -> IO (CBool) instance QunSetHandler (QTextDocumentSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QTextDocument_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QTextDocument ()) (QTextDocument x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTextDocument1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTextDocument1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTextDocument_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTextDocument x0) -> IO () setHandlerWrapper x0 = do x0obj <- qTextDocumentFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTextDocument_setHandler1" qtc_QTextDocument_setHandler1 :: Ptr (TQTextDocument a) -> CWString -> Ptr (Ptr (TQTextDocument x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QTextDocument1 :: (Ptr (TQTextDocument x0) -> IO ()) -> IO (FunPtr (Ptr (TQTextDocument x0) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QTextDocument1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QTextDocumentSc a) (QTextDocument x0 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTextDocument1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTextDocument1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTextDocument_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTextDocument x0) -> IO () setHandlerWrapper x0 = do x0obj <- qTextDocumentFromPtr x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qclear_h (QTextDocument ()) (()) where clear_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_clear cobj_x0 foreign import ccall "qtc_QTextDocument_clear" qtc_QTextDocument_clear :: Ptr (TQTextDocument a) -> IO () instance Qclear_h (QTextDocumentSc a) (()) where clear_h x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextDocument_clear cobj_x0 instance QsetHandler (QTextDocument ()) (QTextDocument x0 -> QTextFormat t1 -> IO (QObject t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTextDocument2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTextDocument2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTextDocument_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTextDocument x0) -> Ptr (TQTextFormat t1) -> IO (Ptr (TQObject t0)) setHandlerWrapper x0 x1 = do x0obj <- qTextDocumentFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTextDocument_setHandler2" qtc_QTextDocument_setHandler2 :: Ptr (TQTextDocument a) -> CWString -> Ptr (Ptr (TQTextDocument x0) -> Ptr (TQTextFormat t1) -> IO (Ptr (TQObject t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QTextDocument2 :: (Ptr (TQTextDocument x0) -> Ptr (TQTextFormat t1) -> IO (Ptr (TQObject t0))) -> IO (FunPtr (Ptr (TQTextDocument x0) -> Ptr (TQTextFormat t1) -> IO (Ptr (TQObject t0)))) foreign import ccall "wrapper" wrapSetHandler_QTextDocument2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QTextDocumentSc a) (QTextDocument x0 -> QTextFormat t1 -> IO (QObject t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTextDocument2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTextDocument2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTextDocument_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTextDocument x0) -> Ptr (TQTextFormat t1) -> IO (Ptr (TQObject t0)) setHandlerWrapper x0 x1 = do x0obj <- qTextDocumentFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () class QcreateObject_h x0 x1 where createObject_h :: x0 -> x1 -> IO (QTextObject ()) instance QcreateObject_h (QTextDocument ()) ((QTextFormat t1)) where createObject_h x0 (x1) = withQTextObjectResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_createObject cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_createObject" qtc_QTextDocument_createObject :: Ptr (TQTextDocument a) -> Ptr (TQTextFormat t1) -> IO (Ptr (TQTextObject ())) instance QcreateObject_h (QTextDocumentSc a) ((QTextFormat t1)) where createObject_h x0 (x1) = withQTextObjectResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_createObject cobj_x0 cobj_x1 instance QsetHandler (QTextDocument ()) (QTextDocument x0 -> Int -> QUrl t2 -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTextDocument3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTextDocument3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTextDocument_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTextDocument x0) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 x2 = do x0obj <- qTextDocumentFromPtr x0 let x1int = fromCInt x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int x2obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTextDocument_setHandler3" qtc_QTextDocument_setHandler3 :: Ptr (TQTextDocument a) -> CWString -> Ptr (Ptr (TQTextDocument x0) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QTextDocument3 :: (Ptr (TQTextDocument x0) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQTextDocument x0) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QTextDocument3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QTextDocumentSc a) (QTextDocument x0 -> Int -> QUrl t2 -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTextDocument3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTextDocument3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTextDocument_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTextDocument x0) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 x2 = do x0obj <- qTextDocumentFromPtr x0 let x1int = fromCInt x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1int x2obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QloadResource_h (QTextDocument ()) ((Int, QUrl t2)) where loadResource_h x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_loadResource cobj_x0 (toCInt x1) cobj_x2 foreign import ccall "qtc_QTextDocument_loadResource" qtc_QTextDocument_loadResource :: Ptr (TQTextDocument a) -> CInt -> Ptr (TQUrl t2) -> IO (Ptr (TQVariant ())) instance QloadResource_h (QTextDocumentSc a) ((Int, QUrl t2)) where loadResource_h x0 (x1, x2) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_loadResource cobj_x0 (toCInt x1) cobj_x2 instance QsetHandler (QTextDocument ()) (QTextDocument x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTextDocument4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTextDocument4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTextDocument_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTextDocument x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qTextDocumentFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTextDocument_setHandler4" qtc_QTextDocument_setHandler4 :: Ptr (TQTextDocument a) -> CWString -> Ptr (Ptr (TQTextDocument x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QTextDocument4 :: (Ptr (TQTextDocument x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTextDocument x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QTextDocument4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QTextDocumentSc a) (QTextDocument x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTextDocument4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTextDocument4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTextDocument_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTextDocument x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qTextDocumentFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QTextDocument ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_event cobj_x0 cobj_x1 foreign import ccall "qtc_QTextDocument_event" qtc_QTextDocument_event :: Ptr (TQTextDocument a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QTextDocumentSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextDocument_event cobj_x0 cobj_x1 instance QsetHandler (QTextDocument ()) (QTextDocument x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTextDocument5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTextDocument5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTextDocument_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTextDocument x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qTextDocumentFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTextDocument_setHandler5" qtc_QTextDocument_setHandler5 :: Ptr (TQTextDocument a) -> CWString -> Ptr (Ptr (TQTextDocument x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QTextDocument5 :: (Ptr (TQTextDocument x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTextDocument x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QTextDocument5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QTextDocumentSc a) (QTextDocument x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTextDocument5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTextDocument5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTextDocument_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTextDocument x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qTextDocumentFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QTextDocument ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QTextDocument_eventFilter" qtc_QTextDocument_eventFilter :: Ptr (TQTextDocument a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QTextDocumentSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextDocument_eventFilter cobj_x0 cobj_x1 cobj_x2
keera-studios/hsQt
Qtc/Gui/QTextDocument_h.hs
Haskell
bsd-2-clause
28,767
module NametableSpec where import Test.Hspec import Test.QuickCheck import Test.QuickCheck.Monadic import Test.Test import Grin.Nametable import Grin.Pretty runTests :: IO () runTests = hspec spec spec :: Spec spec = do describe "Property" $ do it "restore . convert == id" $ property $ forAll genProg $ \p -> let p' = restore $ convert p in (PP p') `shouldBe` (PP p)
andorp/grin
grin/test/NametableSpec.hs
Haskell
bsd-3-clause
400
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} module TitleScene ( titleScene ) where import GameEngine.Scene import GameEngine.Sprite import GameEngine.Sprite.Label import GameEngine.Sprite.Colored import Control.Lens import Control.Monad (when) import Control.Monad.IO.Class import Control.Monad.State import Control.Monad.Except import Data.Color.Names import qualified Graphics.UI.GLFW as GLFW import System.Random data SceneState = SceneState { _title1 :: LabelSprite , _title2 :: LabelSprite , _enterKeyPressed :: Bool } makeLenses ''SceneState titleScene :: Scene () titleScene = do s <- liftIO $ initialSceneState makeScene s sceneGen initialSceneState :: IO SceneState initialSceneState = do freeSans <- loadFont "font/FreeSans.ttf" return $ SceneState { _title1 = configureSprite $ do text .= "Snake Game Haskell" color .= white font .= freeSans scale .= 2 position.x .= 120 position.y .= 240 , _title2 = configureSprite $ do text .= "Press enter" color .= white font .= freeSans scale .= 1.5 position.x .= 240 position.y .= 180 , _enterKeyPressed = False } sceneGen :: SceneGen SceneState () sceneGen = SceneGen { keyHandler = keyHandler' , stepHandler = stepHandler' , drawHandler = drawHandler' } keyHandler' :: GLFW.Key -> GLFW.KeyState -> GLFW.ModifierKeys -> StateT SceneState IO () keyHandler' key _ _ = case key of GLFW.Key'Enter -> enterKeyPressed .= True _ -> return () stepHandler' :: Double -> ExceptT () (StateT SceneState IO) () stepHandler' dt = do gameStart <- use enterKeyPressed when gameStart $ exitScene () drawHandler' :: (Int, Int) -> SceneState -> IO () drawHandler' (w, h) state = do let draw = drawInWindow w h draw $ state ^. title1 draw $ state ^. title2
lotz84/SnakeGameHaskell
src/TitleScene.hs
Haskell
bsd-3-clause
2,381
import Language.Haskell.TH putLeftRight :: Int -> ExpQ -> ExpQ putLeftRight 0 ex = leftE `appE` ex putLeftRight n ex = rightE `appE` putLeftRight (n - 1) ex rightE, leftE :: ExpQ rightE = conE $ mkName "Right" leftE = conE $ mkName "Left" reduce :: Either Int (Either String (Either Char ())) -> Either Int (Either String Char) reduce (Right (Right (Left c))) = Right $ Right c reduce (Right (Left s)) = Right $ Left s reduce (Left i) = Left i data DotList x = x :-: (Either (DotList x) x) deriving Show
YoshikuniJujo/papillon
test/templateHaskell/leftRight.hs
Haskell
bsd-3-clause
509
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} module Rules.Kind.Infer.SyntaxDirected ( IKSyntax ) where import Control.Monad (unless) import Control.Monad.Except (MonadError) import Control.Monad.Error.Lens (throwing) import Data.List.NonEmpty (NonEmpty(..)) import Ast.Error.Common import Data.Functor.Rec import Rules.Kind.Infer.Common data IKSyntax instance MkInferKind IKSyntax where type MkInferKindConstraint e w s r m ki ty a IKSyntax = ( Eq a , EqRec ki , MonadError e m , AsUnknownKindError e , AsUnexpectedKind e ki a , AsExpectedKindEq e ki a , AsExpectedKindAllEq e ki a ) type InferKindMonad m ki a IKSyntax = m type MkInferKindErrorList ki ty a IKSyntax = '[] type MkInferKindWarningList ki ty a IKSyntax = '[] mkCheckKind m ki ty a i = mkCheckKind' i (expectKind m ki ty a i) expectKind _ _ _ _ _ e@(ExpectedKind ki1) a@(ActualKind ki2) = unless (ki1 == ki2) $ throwing _UnexpectedKind (e, a) expectKindEq _ _ _ _ _ ki1 ki2 = unless (ki1 == ki2) $ throwing _ExpectedKindEq (ki1, ki2) expectKindAllEq _ _ _ _ _ (ki :| kis) = do unless (all (== ki) kis) $ throwing _ExpectedKindAllEq (ki :| kis) return ki prepareInferKind pm pki pty pa pi ki = let i = mkInferKind . kriInferRules $ ki c = mkCheckKind pm pki pty pa pi i in InferKindOutput i c
dalaing/type-systems
src/Rules/Kind/Infer/SyntaxDirected.hs
Haskell
bsd-3-clause
1,701
{-# LANGUAGE GADTs, MultiParamTypeClasses, FlexibleInstances, Rank2Types, PolyKinds, UndecidableInstances #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.Indexed.Free -- Copyright : (C) 2013 Fumiaki Kinoshita -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Fumiaki Kinoshita <fumiexcel@gmail.com> -- Stability : provisional -- Portability : non-portable -- ---------------------------------------------------------------------------- module Control.Monad.Indexed.Free (IxFree(..), hoistIxFree, module Control.Monad.Indexed.Free.Class) where import Control.Applicative import Control.Monad.Indexed import Control.Monad.Indexed.Free.Class data IxFree f i j x where Pure :: a -> IxFree f i i a Free :: f i j (IxFree f j k a) -> IxFree f i k a instance IxFunctor f => IxFunctor (IxFree f) where imap f (Pure a) = Pure (f a) imap f (Free w) = Free (imap (imap f) w) instance IxFunctor f => IxPointed (IxFree f) where ireturn = Pure instance IxFunctor f => IxApplicative (IxFree f) where iap (Pure a) (Pure b) = Pure (a b) iap (Pure a) (Free fb) = Free (imap a `imap` fb) iap (Free fa) mb = Free $ imap (`iap` mb) fa instance IxFunctor f => IxMonad (IxFree f) where ibind k (Pure a) = k a ibind k (Free fm) = Free $ imap (ibind k) fm instance IxFunctor f => IxMonadFree f (IxFree f) where iwrap = Free instance IxFunctor f => Functor (IxFree f i i) where fmap = imap instance IxFunctor f => Applicative (IxFree f i i) where pure = ireturn (<*>) = iap instance IxFunctor f => Monad (IxFree f i i) where return = ireturn (>>=) = (>>>=) hoistIxFree :: (IxFunctor g, IxMonadFree g m) => (forall i j x. f i j x -> g i j x) -> IxFree f i j a -> m i j a hoistIxFree _ (Pure a) = ireturn a hoistIxFree f (Free fm) = iwrap $ imap (hoistIxFree f) $ f fm
fumieval/indexed-free
Control/Monad/Indexed/Free.hs
Haskell
bsd-3-clause
1,914
{-# LANGUAGE TypeFamilies, TypeOperators, TupleSections #-} {-# OPTIONS_GHC -Wall #-} ---------------------------------------------------------------------- -- | -- Module : FunctorCombo.Holey -- Copyright : (c) Conal Elliott 2010 -- License : BSD3 -- -- Maintainer : conal@conal.net -- Stability : experimental -- -- Filling and extracting derivatives (one-hole contexts) -- Variation on Holey, integrating 'Der' ---------------------------------------------------------------------- module FunctorCombo.DHoley (Holey(..), fill) where import Control.Arrow (first,second) import FunctorCombo.Functor {-------------------------------------------------------------------- Extraction --------------------------------------------------------------------} -- | Location, i.e., one-hole context and a value for the hole. type Loc f a = (Der f a, a) -- | Alternative interface for 'fillC'. fill :: Holey f => Loc f a -> f a fill = uncurry fillC class Functor f => Holey f where -- | Derivative, i.e., one-hole context type Der f :: * -> * -- | Fill a hole fillC :: Der f a -> a -> f a -- | All extractions extract :: f a -> f (Loc f a) -- The Functor constraint simplifies several signatures below. instance Holey (Const x) where type Der (Const x) = Void fillC = voidF extract (Const x) = Const x instance Holey Id where type Der Id = Unit fillC (Const ()) = Id extract (Id a) = Id (Const (), a) instance (Holey f, Holey g) => Holey (f :+: g) where type Der (f :+: g) = Der f :+: Der g fillC (InL df) = InL . fillC df fillC (InR df) = InR . fillC df extract (InL fa) = InL ((fmap.first) InL (extract fa)) extract (InR ga) = InR ((fmap.first) InR (extract ga)) {- InL fa :: (f :+: g) a fa :: f a extract fa :: f (Loc f a) extract fa :: f (Der f a, a) (fmap.first) InL (extract fa) :: f ((Der f :+: Der g) a, a) (fmap.first) InL (extract fa) :: f ((Der (f :+: g) a), a) InL ((fmap.first) InL (extract fa)) :: (f :+: g) ((Der (f :+: g) a), a) -} -- Der (f :*: g) = Der f :*: g :+: f :*: Der g instance (Holey f, Holey g) => Holey (f :*: g) where type Der (f :*: g) = Der f :*: g :+: f :*: Der g fillC (InL (dfa :*: ga)) = (:*: ga) . fillC dfa fillC (InR ( fa :*: dga)) = (fa :*:) . fillC dga extract (fa :*: ga) = (fmap.first) (InL . (:*: ga)) (extract fa) :*: (fmap.first) (InR . (fa :*:)) (extract ga) {- fa :*: ga :: (f :*: g) a fa :: f a extract fa :: f (Loc f a) (fmap.first) (:*: ga) (extract fa) :: f ((Der f :*: g) a, a) (fmap.first) (InL . (:*: ga)) (extract fa) :: f (((Der f :*: g) :+: (f :*: Der g)) a, a) (fmap.first) (InL . (:*: ga)) (extract fa) :: f ((Der (f :*: g)) a, a) (fmap.first) (InR . (fa :*:)) (extract ga) :: g ((Der (f :*: g)) a, a) (fmap.first) (InL . (:*: ga)) (extract fa) :*: (fmap.first) (InR . (fa :*:)) (extract ga) :: (f :*: g) (Der (f :*: g) a, a) -} -- type instance Der (g :. f) = Der g :. f :*: Der f {- lassoc :: (p,(q,r)) -> ((p,q),r) lassoc (p,(q,r)) = ((p,q),r) squishP :: Functor f => (a, f b) -> f (a,b) squishP (a,fb) = fmap (a,) fb tweak1 :: Functor f => (dg (fa), f (dfa, a)) -> f ((dg (fa), dfa), a) tweak1 = fmap lassoc . squishP chainRule :: (dg (f a), df a) -> ((dg :. f) :*: df) a chainRule (dgfa, dfa) = O dgfa :*: dfa tweak2 :: Functor f => (dg (f a), f (df a, a)) -> f (((dg :. f) :*: df) a, a) tweak2 = (fmap.first) chainRule . tweak1 -} -- Sjoerd Visscher wrote <http://conal.net/blog/posts/another-angle-on-zippers/#comment-51328>: -- At first it was a bit disappointing that extract is so complicated for -- functor composition, but I played a bit with the code and tweak2 can be -- simplified (if I didn't make a mistake) to: -- tweak2 (dgfa, fl) = (fmap.first) (O dgfa :*:) fl -- It's interesting that (tweak2 . second extract) is very much like down! -- Probably because Fix f is like repeated functor composition of f. tweak2 :: Functor f => (dg (f a), f (df a, a)) -> f (((dg :. f) :*: df) a, a) tweak2 (dgfa, fl) = (fmap.first) (O dgfa :*:) fl -- And more specifically, -- -- tweak2 :: Functor f => (Der g (f a), f (Loc f a)) -> f (((Der g :. f) :*: Der f) a, a) -- tweak2 :: Functor f => (Der g (f a), f (Loc f a)) -> f (Der (g :. f) a, a) -- tweak2 :: Functor f => (Der g (f a), f (Loc f a)) -> f (Loc (g :. f) a) {- (dg fa, f (dfa,a)) f (dg fa, (df,a)) f ((dg fa, dfa), a) -} extractGF :: (Holey f, Holey g) => g (f a) -> g (f (Loc (g :. f) a)) extractGF = fmap (tweak2 . second extract) . extract {- gfa :: g (f a) extract gfa :: g (Der g (f a), f a) fmap (second extract) (extract gfa) :: g (Der g (f a), f (Loc f a)) fmap (tweak2 . second extract) (extract gfa) :: g (f (Loc (g :. f)) a) -} -- Der (g :. f) = Der g :. f :*: Der f instance (Holey f, Holey g) => Holey (g :. f) where type Der (g :. f) = Der g :. f :*: Der f fillC (O dgfa :*: dfa) = O. fillC dgfa . fillC dfa extract = inO extractGF -- extract (O gfa) = O (extractGF gfa) {- O dgfa :*: dfa :: Der (g :. f) a O dgfa :*: dfa :: (Der g :. f :*: Der f) a dgfa :: Der g (f a) dfa :: Der f a fillC dfa a :: f a fillC dgfa (fillC dfa a) :: g (f a) O (fillC dgfa (fillC dfa a)) :: (g :. f) a -}
conal/functor-combo
src/FunctorCombo/DHoley.hs
Haskell
bsd-3-clause
5,280
{-# LANGUAGE OverloadedStrings , FlexibleContexts #-} module Application where import Template.Main (htmlLight, page) import Application.Types (MonadApp) import Network.Wai.Trans (ApplicationT, MiddlewareT) import Network.Wai (pathInfo) import Network.Wai.Middleware.ContentType import Network.Wai.Middleware.Verbs (get) import Network.HTTP.Types (status200, status404) import Web.Page.Lucid (template) import Web.Routes.Nested (RouterT, route, matchHere, match, matchAny, action) import Lucid server :: MonadApp m => MiddlewareT m server = route routes where routes :: MonadApp m => RouterT (MiddlewareT m) sec m () routes = do matchHere $ action $ get $ htmlLight status200 $ template page $ p_ "Sup!" matchAny $ action $ get $ htmlLight status404 $ template page $ p_ "404 d:" defApp :: MonadApp m => ApplicationT m defApp _ respond = respond $ textOnly "404 d:" status404 []
Debatable-Online/backend
src/Application.hs
Haskell
bsd-3-clause
917
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Handles @deriving@ clauses on @data@ declarations. -} {-# LANGUAGE CPP #-} module TcDeriv ( tcDeriving, DerivInfo(..), mkDerivInfos ) where #include "HsVersions.h" import HsSyn import DynFlags import TcRnMonad import FamInst import TcErrors( reportAllUnsolved ) import TcValidity( validDerivPred ) import TcClassDcl( tcATDefault, tcMkDeclCtxt ) import TcEnv import TcGenDeriv -- Deriv stuff import TcGenGenerics import InstEnv import Inst import FamInstEnv import TcHsType import TcMType import TcSimplify import TcUnify( buildImplicationFor ) import LoadIface( loadInterfaceForName ) import Module( getModule ) import RnNames( extendGlobalRdrEnvRn ) import RnBinds import RnEnv import RnSource ( addTcgDUs ) import HscTypes import Avail import Unify( tcUnifyTy ) import Class import Type import ErrUtils import DataCon import Maybes import RdrName import Name import NameSet import TyCon import TcType import Var import VarEnv import VarSet import PrelNames import THNames ( liftClassKey ) import SrcLoc import Util import Outputable import FastString import Bag import Pair import qualified GHC.LanguageExtensions as LangExt import Control.Monad import Data.List {- ************************************************************************ * * Overview * * ************************************************************************ Overall plan ~~~~~~~~~~~~ 1. Convert the decls (i.e. data/newtype deriving clauses, plus standalone deriving) to [EarlyDerivSpec] 2. Infer the missing contexts for the InferTheta's 3. Add the derived bindings, generating InstInfos -} -- DerivSpec is purely local to this module data DerivSpec theta = DS { ds_loc :: SrcSpan , ds_name :: Name -- DFun name , ds_tvs :: [TyVar] , ds_theta :: theta , ds_cls :: Class , ds_tys :: [Type] , ds_tc :: TyCon , ds_overlap :: Maybe OverlapMode , ds_newtype :: Maybe Type } -- The newtype rep type -- This spec implies a dfun declaration of the form -- df :: forall tvs. theta => C tys -- The Name is the name for the DFun we'll build -- The tyvars bind all the variables in the theta -- For type families, the tycon in -- in ds_tys is the *family* tycon -- in ds_tc is the *representation* type -- For non-family tycons, both are the same -- the theta is either the given and final theta, in standalone deriving, -- or the not-yet-simplified list of constraints together with their origin -- ds_newtype = Just rep_ty <=> Generalised Newtype Deriving (GND) -- Nothing <=> Vanilla deriving {- Example: newtype instance T [a] = MkT (Tree a) deriving( C s ) ==> axiom T [a] = :RTList a axiom :RTList a = Tree a DS { ds_tvs = [a,s], ds_cls = C, ds_tys = [s, T [a]] , ds_tc = :RTList, ds_newtype = Just (Tree a) } -} type DerivContext = Maybe ThetaType -- Nothing <=> Vanilla deriving; infer the context of the instance decl -- Just theta <=> Standalone deriving: context supplied by programmer data PredOrigin = PredOrigin PredType CtOrigin TypeOrKind type ThetaOrigin = [PredOrigin] mkPredOrigin :: CtOrigin -> TypeOrKind -> PredType -> PredOrigin mkPredOrigin origin t_or_k pred = PredOrigin pred origin t_or_k mkThetaOrigin :: CtOrigin -> TypeOrKind -> ThetaType -> ThetaOrigin mkThetaOrigin origin t_or_k = map (mkPredOrigin origin t_or_k) data EarlyDerivSpec = InferTheta (DerivSpec ThetaOrigin) | GivenTheta (DerivSpec ThetaType) -- InferTheta ds => the context for the instance should be inferred -- In this case ds_theta is the list of all the constraints -- needed, such as (Eq [a], Eq a), together with a suitable CtLoc -- to get good error messages. -- The inference process is to reduce this to a -- simpler form (e.g. Eq a) -- -- GivenTheta ds => the exact context for the instance is supplied -- by the programmer; it is ds_theta -- See Note [Inferring the instance context] earlyDSLoc :: EarlyDerivSpec -> SrcSpan earlyDSLoc (InferTheta spec) = ds_loc spec earlyDSLoc (GivenTheta spec) = ds_loc spec splitEarlyDerivSpec :: [EarlyDerivSpec] -> ([DerivSpec ThetaOrigin], [DerivSpec ThetaType]) splitEarlyDerivSpec [] = ([],[]) splitEarlyDerivSpec (InferTheta spec : specs) = case splitEarlyDerivSpec specs of (is, gs) -> (spec : is, gs) splitEarlyDerivSpec (GivenTheta spec : specs) = case splitEarlyDerivSpec specs of (is, gs) -> (is, spec : gs) pprDerivSpec :: Outputable theta => DerivSpec theta -> SDoc pprDerivSpec (DS { ds_loc = l, ds_name = n, ds_tvs = tvs, ds_cls = c, ds_tys = tys, ds_theta = rhs }) = hang (text "DerivSpec") 2 (vcat [ text "ds_loc =" <+> ppr l , text "ds_name =" <+> ppr n , text "ds_tvs =" <+> ppr tvs , text "ds_cls =" <+> ppr c , text "ds_tys =" <+> ppr tys , text "ds_theta =" <+> ppr rhs ]) instance Outputable theta => Outputable (DerivSpec theta) where ppr = pprDerivSpec instance Outputable EarlyDerivSpec where ppr (InferTheta spec) = ppr spec <+> text "(Infer)" ppr (GivenTheta spec) = ppr spec <+> text "(Given)" instance Outputable PredOrigin where ppr (PredOrigin ty _ _) = ppr ty -- The origin is not so interesting when debugging {- Note [Inferring the instance context] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are two sorts of 'deriving': * InferTheta: the deriving clause for a data type data T a = T1 a deriving( Eq ) Here we must infer an instance context, and generate instance declaration instance Eq a => Eq (T a) where ... * CheckTheta: standalone deriving deriving instance Eq a => Eq (T a) Here we only need to fill in the bindings; the instance context is user-supplied For a deriving clause (InferTheta) we must figure out the instance context (inferConstraints). Suppose we are inferring the instance context for C t1 .. tn (T s1 .. sm) There are two cases * (T s1 .. sm) :: * (the normal case) Then we behave like Eq and guess (C t1 .. tn t) for each data constructor arg of type t. More details below. * (T s1 .. sm) :: * -> * (the functor-like case) Then we behave like Functor. In both cases we produce a bunch of un-simplified constraints and them simplify them in simplifyInstanceContexts; see Note [Simplifying the instance context]. Note [Data decl contexts] ~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data (RealFloat a) => Complex a = !a :+ !a deriving( Read ) We will need an instance decl like: instance (Read a, RealFloat a) => Read (Complex a) where ... The RealFloat in the context is because the read method for Complex is bound to construct a Complex, and doing that requires that the argument type is in RealFloat. But this ain't true for Show, Eq, Ord, etc, since they don't construct a Complex; they only take them apart. Our approach: identify the offending classes, and add the data type context to the instance decl. The "offending classes" are Read, Enum? FURTHER NOTE ADDED March 2002. In fact, Haskell98 now requires that pattern matching against a constructor from a data type with a context gives rise to the constraints for that context -- or at least the thinned version. So now all classes are "offending". Note [Newtype deriving] ~~~~~~~~~~~~~~~~~~~~~~~ Consider this: class C a b instance C [a] Char newtype T = T Char deriving( C [a] ) Notice the free 'a' in the deriving. We have to fill this out to newtype T = T Char deriving( forall a. C [a] ) And then translate it to: instance C [a] Char => C [a] T where ... Note [Newtype deriving superclasses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ (See also Trac #1220 for an interesting exchange on newtype deriving and superclasses.) The 'tys' here come from the partial application in the deriving clause. The last arg is the new instance type. We must pass the superclasses; the newtype might be an instance of them in a different way than the representation type E.g. newtype Foo a = Foo a deriving( Show, Num, Eq ) Then the Show instance is not done via Coercible; it shows Foo 3 as "Foo 3" The Num instance is derived via Coercible, but the Show superclass dictionary must the Show instance for Foo, *not* the Show dictionary gotten from the Num dictionary. So we must build a whole new dictionary not just use the Num one. The instance we want is something like: instance (Num a, Show (Foo a), Eq (Foo a)) => Num (Foo a) where (+) = ((+)@a) ...etc... There may be a coercion needed which we get from the tycon for the newtype when the dict is constructed in TcInstDcls.tcInstDecl2 Note [Unused constructors and deriving clauses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See Trac #3221. Consider data T = T1 | T2 deriving( Show ) Are T1 and T2 unused? Well, no: the deriving clause expands to mention both of them. So we gather defs/uses from deriving just like anything else. -} -- | Stuff needed to process a `deriving` clause data DerivInfo = DerivInfo { di_rep_tc :: TyCon -- ^ The data tycon for normal datatypes, -- or the *representation* tycon for data families , di_preds :: [LHsSigType Name] , di_ctxt :: SDoc -- ^ error context } -- | Extract `deriving` clauses of proper data type (skips data families) mkDerivInfos :: [TyClGroup Name] -> TcM [DerivInfo] mkDerivInfos tycls = concatMapM mk_derivs tycls where mk_derivs (TyClGroup { group_tyclds = decls }) = concatMapM (mk_deriv . unLoc) decls mk_deriv decl@(DataDecl { tcdLName = L _ data_name , tcdDataDefn = HsDataDefn { dd_derivs = Just (L _ preds) } }) = do { tycon <- tcLookupTyCon data_name ; return [DerivInfo { di_rep_tc = tycon, di_preds = preds , di_ctxt = tcMkDeclCtxt decl }] } mk_deriv _ = return [] {- ************************************************************************ * * \subsection[TcDeriv-driver]{Top-level function for \tr{derivings}} * * ************************************************************************ -} tcDeriving :: [DerivInfo] -- All `deriving` clauses -> [LDerivDecl Name] -- All stand-alone deriving declarations -> TcM (TcGblEnv, Bag (InstInfo Name), HsValBinds Name) tcDeriving deriv_infos deriv_decls = recoverM (do { g <- getGblEnv ; return (g, emptyBag, emptyValBindsOut)}) $ do { -- Fish the "deriving"-related information out of the TcEnv -- And make the necessary "equations". is_boot <- tcIsHsBootOrSig ; traceTc "tcDeriving" (ppr is_boot) ; early_specs <- makeDerivSpecs is_boot deriv_infos deriv_decls ; traceTc "tcDeriving 1" (ppr early_specs) ; let (infer_specs, given_specs) = splitEarlyDerivSpec early_specs ; insts1 <- mapM genInst given_specs -- the stand-alone derived instances (@insts1@) are used when inferring -- the contexts for "deriving" clauses' instances (@infer_specs@) ; final_specs <- extendLocalInstEnv (map (iSpec . fstOf3) insts1) $ simplifyInstanceContexts infer_specs ; insts2 <- mapM genInst final_specs ; let (inst_infos, deriv_stuff, maybe_fvs) = unzip3 (insts1 ++ insts2) ; loc <- getSrcSpanM ; let (binds, famInsts, extraInstances) = genAuxBinds loc (unionManyBags deriv_stuff) ; dflags <- getDynFlags ; (inst_info, rn_binds, rn_dus) <- renameDeriv is_boot (inst_infos ++ (bagToList extraInstances)) binds ; unless (isEmptyBag inst_info) $ liftIO (dumpIfSet_dyn dflags Opt_D_dump_deriv "Derived instances" (ddump_deriving inst_info rn_binds famInsts)) ; gbl_env <- tcExtendLocalFamInstEnv (bagToList famInsts) $ tcExtendLocalInstEnv (map iSpec (bagToList inst_info)) getGblEnv ; let all_dus = rn_dus `plusDU` usesOnly (mkFVs $ catMaybes maybe_fvs) ; return (addTcgDUs gbl_env all_dus, inst_info, rn_binds) } where ddump_deriving :: Bag (InstInfo Name) -> HsValBinds Name -> Bag FamInst -- ^ Rep type family instances -> SDoc ddump_deriving inst_infos extra_binds repFamInsts = hang (text "Derived instances:") 2 (vcat (map (\i -> pprInstInfoDetails i $$ text "") (bagToList inst_infos)) $$ ppr extra_binds) $$ hangP "GHC.Generics representation types:" (vcat (map pprRepTy (bagToList repFamInsts))) hangP s x = text "" $$ hang (ptext (sLit s)) 2 x -- Prints the representable type family instance pprRepTy :: FamInst -> SDoc pprRepTy fi@(FamInst { fi_tys = lhs }) = text "type" <+> ppr (mkTyConApp (famInstTyCon fi) lhs) <+> equals <+> ppr rhs where rhs = famInstRHS fi renameDeriv :: Bool -> [InstInfo RdrName] -> Bag (LHsBind RdrName, LSig RdrName) -> TcM (Bag (InstInfo Name), HsValBinds Name, DefUses) renameDeriv is_boot inst_infos bagBinds | is_boot -- If we are compiling a hs-boot file, don't generate any derived bindings -- The inst-info bindings will all be empty, but it's easier to -- just use rn_inst_info to change the type appropriately = do { (rn_inst_infos, fvs) <- mapAndUnzipM rn_inst_info inst_infos ; return ( listToBag rn_inst_infos , emptyValBindsOut, usesOnly (plusFVs fvs)) } | otherwise = discardWarnings $ -- Discard warnings about unused bindings etc setXOptM LangExt.EmptyCase $ -- Derived decls (for empty types) can have -- case x of {} setXOptM LangExt.ScopedTypeVariables $ -- Derived decls (for newtype-deriving) can setXOptM LangExt.KindSignatures $ -- used ScopedTypeVariables & KindSignatures do { -- Bring the extra deriving stuff into scope -- before renaming the instances themselves ; traceTc "rnd" (vcat (map (\i -> pprInstInfoDetails i $$ text "") inst_infos)) ; (aux_binds, aux_sigs) <- mapAndUnzipBagM return bagBinds ; let aux_val_binds = ValBindsIn aux_binds (bagToList aux_sigs) ; rn_aux_lhs <- rnTopBindsLHS emptyFsEnv aux_val_binds ; let bndrs = collectHsValBinders rn_aux_lhs ; envs <- extendGlobalRdrEnvRn (map avail bndrs) emptyFsEnv ; ; setEnvs envs $ do { (rn_aux, dus_aux) <- rnValBindsRHS (TopSigCtxt (mkNameSet bndrs)) rn_aux_lhs ; (rn_inst_infos, fvs_insts) <- mapAndUnzipM rn_inst_info inst_infos ; return (listToBag rn_inst_infos, rn_aux, dus_aux `plusDU` usesOnly (plusFVs fvs_insts)) } } where rn_inst_info :: InstInfo RdrName -> TcM (InstInfo Name, FreeVars) rn_inst_info inst_info@(InstInfo { iSpec = inst , iBinds = InstBindings { ib_binds = binds , ib_tyvars = tyvars , ib_pragmas = sigs , ib_extensions = exts -- Only for type-checking , ib_derived = sa } }) = ASSERT( null sigs ) bindLocalNamesFV tyvars $ do { (rn_binds,_, fvs) <- rnMethodBinds False (is_cls_nm inst) [] binds [] ; let binds' = InstBindings { ib_binds = rn_binds , ib_tyvars = tyvars , ib_pragmas = [] , ib_extensions = exts , ib_derived = sa } ; return (inst_info { iBinds = binds' }, fvs) } {- Note [Newtype deriving and unused constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this (see Trac #1954): module Bug(P) where newtype P a = MkP (IO a) deriving Monad If you compile with -Wunused-binds you do not expect the warning "Defined but not used: data consructor MkP". Yet the newtype deriving code does not explicitly mention MkP, but it should behave as if you had written instance Monad P where return x = MkP (return x) ...etc... So we want to signal a user of the data constructor 'MkP'. This is the reason behind the (Maybe Name) part of the return type of genInst. Note [Why we don't pass rep_tc into deriveTyData] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Down in the bowels of mkEqnHelp, we need to convert the fam_tc back into the rep_tc by means of a lookup. And yet we have the rep_tc right here! Why look it up again? Answer: it's just easier this way. We drop some number of arguments from the end of the datatype definition in deriveTyData. The arguments are dropped from the fam_tc. This action may drop a *different* number of arguments passed to the rep_tc, depending on how many free variables, etc., the dropped patterns have. Also, this technique carries over the kind substitution from deriveTyData nicely. ************************************************************************ * * From HsSyn to DerivSpec * * ************************************************************************ @makeDerivSpecs@ fishes around to find the info about needed derived instances. -} makeDerivSpecs :: Bool -> [DerivInfo] -> [LDerivDecl Name] -> TcM [EarlyDerivSpec] makeDerivSpecs is_boot deriv_infos deriv_decls = do { eqns1 <- concatMapM (recoverM (return []) . deriveDerivInfo) deriv_infos ; eqns2 <- concatMapM (recoverM (return []) . deriveStandalone) deriv_decls ; let eqns = eqns1 ++ eqns2 ; if is_boot then -- No 'deriving' at all in hs-boot files do { unless (null eqns) (add_deriv_err (head eqns)) ; return [] } else return eqns } where add_deriv_err eqn = setSrcSpan (earlyDSLoc eqn) $ addErr (hang (text "Deriving not permitted in hs-boot file") 2 (text "Use an instance declaration instead")) ------------------------------------------------------------------ -- | Process a `deriving` clause deriveDerivInfo :: DerivInfo -> TcM [EarlyDerivSpec] deriveDerivInfo (DerivInfo { di_rep_tc = rep_tc, di_preds = preds , di_ctxt = err_ctxt }) = addErrCtxt err_ctxt $ concatMapM (deriveTyData tvs tc tys) preds where tvs = tyConTyVars rep_tc (tc, tys) = case tyConFamInstSig_maybe rep_tc of -- data family: Just (fam_tc, pats, _) -> (fam_tc, pats) -- NB: deriveTyData wants the *user-specified* -- name. See Note [Why we don't pass rep_tc into deriveTyData] _ -> (rep_tc, mkTyVarTys tvs) -- datatype ------------------------------------------------------------------ deriveStandalone :: LDerivDecl Name -> TcM [EarlyDerivSpec] -- Standalone deriving declarations -- e.g. deriving instance Show a => Show (T a) -- Rather like tcLocalInstDecl deriveStandalone (L loc (DerivDecl deriv_ty overlap_mode)) = setSrcSpan loc $ addErrCtxt (standaloneCtxt deriv_ty) $ do { traceTc "Standalone deriving decl for" (ppr deriv_ty) ; (tvs, theta, cls, inst_tys) <- tcHsClsInstType TcType.InstDeclCtxt deriv_ty ; traceTc "Standalone deriving;" $ vcat [ text "tvs:" <+> ppr tvs , text "theta:" <+> ppr theta , text "cls:" <+> ppr cls , text "tys:" <+> ppr inst_tys ] -- C.f. TcInstDcls.tcLocalInstDecl1 ; checkTc (not (null inst_tys)) derivingNullaryErr ; let cls_tys = take (length inst_tys - 1) inst_tys inst_ty = last inst_tys ; traceTc "Standalone deriving:" $ vcat [ text "class:" <+> ppr cls , text "class types:" <+> ppr cls_tys , text "type:" <+> ppr inst_ty ] ; case tcSplitTyConApp_maybe inst_ty of Just (tc, tc_args) | className cls == typeableClassName -> do warnUselessTypeable return [] | isAlgTyCon tc || isDataFamilyTyCon tc -- All other classes -> do { spec <- mkEqnHelp (fmap unLoc overlap_mode) tvs cls cls_tys tc tc_args (Just theta) ; return [spec] } _ -> -- Complain about functions, primitive types, etc, failWithTc $ derivingThingErr False cls cls_tys inst_ty $ text "The last argument of the instance must be a data or newtype application" } warnUselessTypeable :: TcM () warnUselessTypeable = do { warn <- woptM Opt_WarnDerivingTypeable ; when warn $ addWarnTc (Reason Opt_WarnDerivingTypeable) $ text "Deriving" <+> quotes (ppr typeableClassName) <+> text "has no effect: all types now auto-derive Typeable" } ------------------------------------------------------------------ deriveTyData :: [TyVar] -> TyCon -> [Type] -- LHS of data or data instance -- Can be a data instance, hence [Type] args -> LHsSigType Name -- The deriving predicate -> TcM [EarlyDerivSpec] -- The deriving clause of a data or newtype declaration -- I.e. not standalone deriving deriveTyData tvs tc tc_args deriv_pred = setSrcSpan (getLoc (hsSigType deriv_pred)) $ -- Use loc of the 'deriving' item do { (deriv_tvs, cls, cls_tys, cls_arg_kind) <- tcExtendTyVarEnv tvs $ tcHsDeriv deriv_pred -- Deriving preds may (now) mention -- the type variables for the type constructor, hence tcExtendTyVarenv -- The "deriv_pred" is a LHsType to take account of the fact that for -- newtype deriving we allow deriving (forall a. C [a]). -- Typeable is special, because Typeable :: forall k. k -> Constraint -- so the argument kind 'k' is not decomposable by splitKindFunTys -- as is the case for all other derivable type classes ; if className cls == typeableClassName then do warnUselessTypeable return [] else do { -- Given data T a b c = ... deriving( C d ), -- we want to drop type variables from T so that (C d (T a)) is well-kinded let (arg_kinds, _) = splitFunTys cls_arg_kind n_args_to_drop = length arg_kinds n_args_to_keep = tyConArity tc - n_args_to_drop (tc_args_to_keep, args_to_drop) = splitAt n_args_to_keep tc_args inst_ty_kind = typeKind (mkTyConApp tc tc_args_to_keep) -- Use exactTyCoVarsOfTypes, not tyCoVarsOfTypes, so that we -- don't mistakenly grab a type variable mentioned in a type -- synonym that drops it. -- See Note [Eta-reducing type synonyms]. dropped_tvs = exactTyCoVarsOfTypes args_to_drop -- Match up the kinds, and apply the resulting kind substitution -- to the types. See Note [Unify kinds in deriving] -- We are assuming the tycon tyvars and the class tyvars are distinct mb_match = tcUnifyTy inst_ty_kind cls_arg_kind Just kind_subst = mb_match all_tkvs = varSetElemsWellScoped $ mkVarSet deriv_tvs `unionVarSet` tyCoVarsOfTypes tc_args_to_keep unmapped_tkvs = filter (`notElemTCvSubst` kind_subst) all_tkvs (subst, tkvs) = mapAccumL substTyVarBndr kind_subst unmapped_tkvs final_tc_args = substTys subst tc_args_to_keep final_cls_tys = substTys subst cls_tys ; traceTc "derivTyData1" (vcat [ pprTvBndrs tvs, ppr tc, ppr tc_args, ppr deriv_pred , pprTvBndrs (tyCoVarsOfTypesList tc_args) , ppr n_args_to_keep, ppr n_args_to_drop , ppr inst_ty_kind, ppr cls_arg_kind, ppr mb_match , ppr final_tc_args, ppr final_cls_tys ]) -- Check that the result really is well-kinded ; checkTc (n_args_to_keep >= 0 && isJust mb_match) (derivingKindErr tc cls cls_tys cls_arg_kind) ; traceTc "derivTyData2" (vcat [ ppr tkvs ]) ; checkTc (allDistinctTyVars args_to_drop && -- (a) and (b) not (any (`elemVarSet` dropped_tvs) tkvs)) -- (c) (derivingEtaErr cls final_cls_tys (mkTyConApp tc final_tc_args)) -- Check that -- (a) The args to drop are all type variables; eg reject: -- data instance T a Int = .... deriving( Monad ) -- (b) The args to drop are all *distinct* type variables; eg reject: -- class C (a :: * -> * -> *) where ... -- data instance T a a = ... deriving( C ) -- (c) The type class args, or remaining tycon args, -- do not mention any of the dropped type variables -- newtype T a s = ... deriving( ST s ) -- newtype instance K a a = ... deriving( Monad ) ; spec <- mkEqnHelp Nothing tkvs cls final_cls_tys tc final_tc_args Nothing ; traceTc "derivTyData" (ppr spec) ; return [spec] } } {- Note [Unify kinds in deriving] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider (Trac #8534) data T a b = MkT a deriving( Functor ) -- where Functor :: (*->*) -> Constraint So T :: forall k. * -> k -> *. We want to get instance Functor (T * (a:*)) where ... Notice the '*' argument to T. Moreover, as well as instantiating T's kind arguments, we may need to instantiate C's kind args. Consider (Trac #8865): newtype T a b = MkT (Either a b) deriving( Category ) where Category :: forall k. (k -> k -> *) -> Constraint We need to generate the instance instance Category * (Either a) where ... Notice the '*' argument to Category. So we need to * drop arguments from (T a b) to match the number of arrows in the (last argument of the) class; * and then *unify* kind of the remaining type against the expected kind, to figure out how to instantiate C's and T's kind arguments. In the two examples, * we unify kind-of( T k (a:k) ) ~ kind-of( Functor ) i.e. (k -> *) ~ (* -> *) to find k:=*. yielding k:=* * we unify kind-of( Either ) ~ kind-of( Category ) i.e. (* -> * -> *) ~ (k -> k -> k) yielding k:=* Now we get a kind substitution. We then need to: 1. Remove the substituted-out kind variables from the quantified kind vars 2. Apply the substitution to the kinds of quantified *type* vars (and extend the substitution to reflect this change) 3. Apply that extended substitution to the non-dropped args (types and kinds) of the type and class Forgetting step (2) caused Trac #8893: data V a = V [a] deriving Functor data P (x::k->*) (a:k) = P (x a) deriving Functor data C (x::k->*) (a:k) = C (V (P x a)) deriving Functor When deriving Functor for P, we unify k to *, but we then want an instance $df :: forall (x:*->*). Functor x => Functor (P * (x:*->*)) and similarly for C. Notice the modified kind of x, both at binding and occurrence sites. Note [Eta-reducing type synonyms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ One can instantiate a type in a data family instance with a type synonym that mentions other type variables: type Const a b = a data family Fam (f :: * -> *) (a :: *) newtype instance Fam f (Const a f) = Fam (f a) deriving Functor With -XTypeInType, it is also possible to define kind synonyms, and they can mention other types in a datatype declaration. For example, type Const a b = a newtype T f (a :: Const * f) = T (f a) deriving Functor When deriving, we need to perform eta-reduction analysis to ensure that none of the eta-reduced type variables are mentioned elsewhere in the declaration. But we need to be careful, because if we don't expand through the Const type synonym, we will mistakenly believe that f is an eta-reduced type variable and fail to derive Functor, even though the code above is correct (see Trac #11416, where this was first noticed). For this reason, we call exactTyCoVarsOfTypes on the eta-reduced types so that we only consider the type variables that remain after expanding through type synonyms. -} mkEqnHelp :: Maybe OverlapMode -> [TyVar] -> Class -> [Type] -> TyCon -> [Type] -> DerivContext -- Just => context supplied (standalone deriving) -- Nothing => context inferred (deriving on data decl) -> TcRn EarlyDerivSpec -- Make the EarlyDerivSpec for an instance -- forall tvs. theta => cls (tys ++ [ty]) -- where the 'theta' is optional (that's the Maybe part) -- Assumes that this declaration is well-kinded mkEqnHelp overlap_mode tvs cls cls_tys tycon tc_args mtheta = do { -- Find the instance of a data family -- Note [Looking up family instances for deriving] fam_envs <- tcGetFamInstEnvs ; let (rep_tc, rep_tc_args, _co) = tcLookupDataFamInst fam_envs tycon tc_args -- If it's still a data family, the lookup failed; i.e no instance exists ; when (isDataFamilyTyCon rep_tc) (bale_out (text "No family instance for" <+> quotes (pprTypeApp tycon tc_args))) -- For standalone deriving (mtheta /= Nothing), -- check that all the data constructors are in scope. ; rdr_env <- getGlobalRdrEnv ; let data_con_names = map dataConName (tyConDataCons rep_tc) hidden_data_cons = not (isWiredInName (tyConName rep_tc)) && (isAbstractTyCon rep_tc || any not_in_scope data_con_names) not_in_scope dc = null (lookupGRE_Name rdr_env dc) ; addUsedDataCons rdr_env rep_tc ; unless (isNothing mtheta || not hidden_data_cons) (bale_out (derivingHiddenErr tycon)) ; dflags <- getDynFlags ; if isDataTyCon rep_tc then mkDataTypeEqn dflags overlap_mode tvs cls cls_tys tycon tc_args rep_tc rep_tc_args mtheta else mkNewTypeEqn dflags overlap_mode tvs cls cls_tys tycon tc_args rep_tc rep_tc_args mtheta } where bale_out msg = failWithTc (derivingThingErr False cls cls_tys (mkTyConApp tycon tc_args) msg) {- Note [Looking up family instances for deriving] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tcLookupFamInstExact is an auxiliary lookup wrapper which requires that looked-up family instances exist. If called with a vanilla tycon, the old type application is simply returned. If we have data instance F () = ... deriving Eq data instance F () = ... deriving Eq then tcLookupFamInstExact will be confused by the two matches; but that can't happen because tcInstDecls1 doesn't call tcDeriving if there are any overlaps. There are two other things that might go wrong with the lookup. First, we might see a standalone deriving clause deriving Eq (F ()) when there is no data instance F () in scope. Note that it's OK to have data instance F [a] = ... deriving Eq (F [(a,b)]) where the match is not exact; the same holds for ordinary data types with standalone deriving declarations. Note [Deriving, type families, and partial applications] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When there are no type families, it's quite easy: newtype S a = MkS [a] -- :CoS :: S ~ [] -- Eta-reduced instance Eq [a] => Eq (S a) -- by coercion sym (Eq (:CoS a)) : Eq [a] ~ Eq (S a) instance Monad [] => Monad S -- by coercion sym (Monad :CoS) : Monad [] ~ Monad S When type familes are involved it's trickier: data family T a b newtype instance T Int a = MkT [a] deriving( Eq, Monad ) -- :RT is the representation type for (T Int a) -- :Co:RT :: :RT ~ [] -- Eta-reduced! -- :CoF:RT a :: T Int a ~ :RT a -- Also eta-reduced! instance Eq [a] => Eq (T Int a) -- easy by coercion -- d1 :: Eq [a] -- d2 :: Eq (T Int a) = d1 |> Eq (sym (:Co:RT a ; :coF:RT a)) instance Monad [] => Monad (T Int) -- only if we can eta reduce??? -- d1 :: Monad [] -- d2 :: Monad (T Int) = d1 |> Monad (sym (:Co:RT ; :coF:RT)) Note the need for the eta-reduced rule axioms. After all, we can write it out instance Monad [] => Monad (T Int) -- only if we can eta reduce??? return x = MkT [x] ... etc ... See Note [Eta reduction for data families] in FamInstEnv %************************************************************************ %* * Deriving data types * * ************************************************************************ -} mkDataTypeEqn :: DynFlags -> Maybe OverlapMode -> [TyVar] -- Universally quantified type variables in the instance -> Class -- Class for which we need to derive an instance -> [Type] -- Other parameters to the class except the last -> TyCon -- Type constructor for which the instance is requested -- (last parameter to the type class) -> [Type] -- Parameters to the type constructor -> TyCon -- rep of the above (for type families) -> [Type] -- rep of the above -> DerivContext -- Context of the instance, for standalone deriving -> TcRn EarlyDerivSpec -- Return 'Nothing' if error mkDataTypeEqn dflags overlap_mode tvs cls cls_tys tycon tc_args rep_tc rep_tc_args mtheta = case checkSideConditions dflags mtheta cls cls_tys rep_tc rep_tc_args of -- NB: pass the *representation* tycon to checkSideConditions NonDerivableClass msg -> bale_out (nonStdErr cls $$ msg) DerivableClassError msg -> bale_out msg CanDerive -> go_for_it DerivableViaInstance -> go_for_it where go_for_it = mk_data_eqn overlap_mode tvs cls cls_tys tycon tc_args rep_tc rep_tc_args mtheta bale_out msg = failWithTc (derivingThingErr False cls cls_tys (mkTyConApp tycon tc_args) msg) mk_data_eqn :: Maybe OverlapMode -> [TyVar] -> Class -> [Type] -> TyCon -> [TcType] -> TyCon -> [TcType] -> DerivContext -> TcM EarlyDerivSpec mk_data_eqn overlap_mode tvs cls cls_tys tycon tc_args rep_tc rep_tc_args mtheta = do loc <- getSrcSpanM dfun_name <- newDFunName' cls tycon case mtheta of Nothing -> do --Infer context inferred_constraints <- inferConstraints cls cls_tys inst_ty rep_tc rep_tc_args return $ InferTheta $ DS { ds_loc = loc , ds_name = dfun_name, ds_tvs = tvs , ds_cls = cls, ds_tys = inst_tys , ds_tc = rep_tc , ds_theta = inferred_constraints , ds_overlap = overlap_mode , ds_newtype = Nothing } Just theta -> do -- Specified context return $ GivenTheta $ DS { ds_loc = loc , ds_name = dfun_name, ds_tvs = tvs , ds_cls = cls, ds_tys = inst_tys , ds_tc = rep_tc , ds_theta = theta , ds_overlap = overlap_mode , ds_newtype = Nothing } where inst_ty = mkTyConApp tycon tc_args inst_tys = cls_tys ++ [inst_ty] ---------------------- inferConstraints :: Class -> [TcType] -> TcType -> TyCon -> [TcType] -> TcM ThetaOrigin -- inferConstraints figures out the constraints needed for the -- instance declaration generated by a 'deriving' clause on a -- data type declaration. -- See Note [Inferring the instance context] -- e.g. inferConstraints -- C Int (T [a]) -- Class and inst_tys -- :RTList a -- Rep tycon and its arg tys -- where T [a] ~R :RTList a -- -- Generate a sufficiently large set of constraints that typechecking the -- generated method definitions should succeed. This set will be simplified -- before being used in the instance declaration inferConstraints main_cls cls_tys inst_ty rep_tc rep_tc_args | main_cls `hasKey` genClassKey -- Generic constraints are easy = return [] | main_cls `hasKey` gen1ClassKey -- Gen1 needs Functor = ASSERT( length rep_tc_tvs > 0 ) -- See Note [Getting base classes] ASSERT( null cls_tys ) do { functorClass <- tcLookupClass functorClassName ; return (con_arg_constraints (get_gen1_constraints functorClass)) } | otherwise -- The others are a bit more complicated = ASSERT2( equalLength rep_tc_tvs all_rep_tc_args , ppr main_cls <+> ppr rep_tc $$ ppr rep_tc_tvs $$ ppr all_rep_tc_args ) do { traceTc "inferConstraints" (vcat [ppr main_cls <+> ppr inst_tys, ppr arg_constraints]) ; return (stupid_constraints ++ extra_constraints ++ sc_constraints ++ arg_constraints) } where tc_binders = tyConBinders rep_tc choose_level bndr | isNamedBinder bndr = KindLevel | otherwise = TypeLevel t_or_ks = map choose_level tc_binders ++ repeat TypeLevel -- want to report *kind* errors when possible arg_constraints = con_arg_constraints get_std_constrained_tys -- Constraints arising from the arguments of each constructor con_arg_constraints :: (CtOrigin -> TypeOrKind -> Type -> [PredOrigin]) -> [PredOrigin] con_arg_constraints get_arg_constraints = [ pred | data_con <- tyConDataCons rep_tc , (arg_n, arg_t_or_k, arg_ty) <- zip3 [1..] t_or_ks $ dataConInstOrigArgTys data_con all_rep_tc_args , not (isUnliftedType arg_ty) , let orig = DerivOriginDC data_con arg_n , pred <- get_arg_constraints orig arg_t_or_k arg_ty ] -- No constraints for unlifted types -- See Note [Deriving and unboxed types] -- is_functor_like: see Note [Inferring the instance context] is_functor_like = typeKind inst_ty `tcEqKind` typeToTypeKind get_gen1_constraints functor_cls orig t_or_k ty = mk_functor_like_constraints orig t_or_k functor_cls $ get_gen1_constrained_tys last_tv ty get_std_constrained_tys :: CtOrigin -> TypeOrKind -> Type -> [PredOrigin] get_std_constrained_tys orig t_or_k ty | is_functor_like = mk_functor_like_constraints orig t_or_k main_cls $ deepSubtypesContaining last_tv ty | otherwise = [mk_cls_pred orig t_or_k main_cls ty] mk_functor_like_constraints :: CtOrigin -> TypeOrKind -> Class -> [Type] -> [PredOrigin] -- 'cls' is usually main_cls (Functor or Traversable etc), but if -- main_cls = Generic1, then 'cls' can be Functor; see get_gen1_constraints -- -- For each type, generate two constraints: (cls ty, kind(ty) ~ (*->*)) -- The second constraint checks that the first is well-kinded. -- Lacking that, as Trac #10561 showed, we can just generate an -- ill-kinded instance. mk_functor_like_constraints orig t_or_k cls tys = [ pred_o | ty <- tys , pred_o <- [ mk_cls_pred orig t_or_k cls ty , mkPredOrigin orig KindLevel (mkPrimEqPred (typeKind ty) typeToTypeKind) ] ] rep_tc_tvs = tyConTyVars rep_tc last_tv = last rep_tc_tvs all_rep_tc_args | is_functor_like = rep_tc_args ++ [mkTyVarTy last_tv] | otherwise = rep_tc_args -- Constraints arising from superclasses -- See Note [Superclasses of derived instance] cls_tvs = classTyVars main_cls inst_tys = cls_tys ++ [inst_ty] sc_constraints = ASSERT2( equalLength cls_tvs inst_tys, ppr main_cls <+> ppr rep_tc) mkThetaOrigin DerivOrigin TypeLevel $ substTheta cls_subst (classSCTheta main_cls) cls_subst = ASSERT( equalLength cls_tvs inst_tys ) zipTvSubst cls_tvs inst_tys -- Stupid constraints stupid_constraints = mkThetaOrigin DerivOrigin TypeLevel $ substTheta tc_subst (tyConStupidTheta rep_tc) tc_subst = ASSERT( equalLength rep_tc_tvs all_rep_tc_args ) zipTvSubst rep_tc_tvs all_rep_tc_args -- Extra Data constraints -- The Data class (only) requires that for -- instance (...) => Data (T t1 t2) -- IF t1:*, t2:* -- THEN (Data t1, Data t2) are among the (...) constraints -- Reason: when the IF holds, we generate a method -- dataCast2 f = gcast2 f -- and we need the Data constraints to typecheck the method extra_constraints | main_cls `hasKey` dataClassKey , all (isLiftedTypeKind . typeKind) rep_tc_args = [ mk_cls_pred DerivOrigin t_or_k main_cls ty | (t_or_k, ty) <- zip t_or_ks rep_tc_args] | otherwise = [] mk_cls_pred orig t_or_k cls ty -- Don't forget to apply to cls_tys too -- In the awkward Generic1 casde, cls_tys is empty = mkPredOrigin orig t_or_k (mkClassPred cls (cls_tys ++ [ty])) {- Note [Getting base classes] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Functor and Typeable are defined in package 'base', and that is not available when compiling 'ghc-prim'. So we must be careful that 'deriving' for stuff in ghc-prim does not use Functor or Typeable implicitly via these lookups. Note [Deriving and unboxed types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We have some special hacks to support things like data T = MkT Int# deriving ( Show ) Specifically, we use TcGenDeriv.box to box the Int# into an Int (which we know how to show), and append a '#'. Parenthesis are not required for unboxed values (`MkT -3#` is a valid expression). Note [Deriving any class] ~~~~~~~~~~~~~~~~~~~~~~~~~ Classic uses of a deriving clause, or a standalone-deriving declaration, are for: * a built-in class like Eq or Show, for which GHC knows how to generate the instance code * a newtype, via the mechanism enabled by GeneralizedNewtypeDeriving The DeriveAnyClass extension adds a third way to derive instances, based on empty instance declarations. The canonical use case is in combination with GHC.Generics and default method signatures. These allow us to have instance declarations being empty, but still useful, e.g. data T a = ...blah..blah... deriving( Generic ) instance C a => C (T a) -- No 'where' clause where C is some "random" user-defined class. This boilerplate code can be replaced by the more compact data T a = ...blah..blah... deriving( Generic, C ) if DeriveAnyClass is enabled. This is not restricted to Generics; any class can be derived, simply giving rise to an empty instance. Unfortunately, it is not clear how to determine the context (in case of standard deriving; in standalone deriving, the user provides the context). GHC uses the same heuristic for figuring out the class context that it uses for Eq in the case of *-kinded classes, and for Functor in the case of * -> *-kinded classes. That may not be optimal or even wrong. But in such cases, standalone deriving can still be used. -} ------------------------------------------------------------------ -- Check side conditions that dis-allow derivability for particular classes -- This is *apart* from the newtype-deriving mechanism -- -- Here we get the representation tycon in case of family instances as it has -- the data constructors - but we need to be careful to fall back to the -- family tycon (with indexes) in error messages. data DerivStatus = CanDerive -- Standard class, can derive | DerivableClassError SDoc -- Standard class, but can't do it | DerivableViaInstance -- See Note [Deriving any class] | NonDerivableClass SDoc -- Non-standard class -- A "standard" class is one defined in the Haskell report which GHC knows how -- to generate code for, such as Eq, Ord, Ix, etc. checkSideConditions :: DynFlags -> DerivContext -> Class -> [TcType] -> TyCon -> [Type] -- tycon and its parameters -> DerivStatus checkSideConditions dflags mtheta cls cls_tys rep_tc rep_tc_args | Just cond <- sideConditions mtheta cls = case (cond (dflags, rep_tc, rep_tc_args)) of NotValid err -> DerivableClassError err -- Class-specific error IsValid | null cls_tys -> CanDerive -- All derivable classes are unary, so -- cls_tys (the type args other than last) -- should be null | otherwise -> DerivableClassError (classArgsErr cls cls_tys) -- e.g. deriving( Eq s ) | Just err <- canDeriveAnyClass dflags rep_tc cls = NonDerivableClass err -- DeriveAnyClass does not work | otherwise = DerivableViaInstance -- DeriveAnyClass should work classArgsErr :: Class -> [Type] -> SDoc classArgsErr cls cls_tys = quotes (ppr (mkClassPred cls cls_tys)) <+> text "is not a class" nonStdErr :: Class -> SDoc nonStdErr cls = quotes (ppr cls) <+> text "is not a standard derivable class (Eq, Show, etc.)" sideConditions :: DerivContext -> Class -> Maybe Condition -- Side conditions for classes that GHC knows about, -- that is, "deriviable classes" -- Returns Nothing for a non-derivable class sideConditions mtheta cls | cls_key == eqClassKey = Just (cond_std `andCond` cond_args cls) | cls_key == ordClassKey = Just (cond_std `andCond` cond_args cls) | cls_key == showClassKey = Just (cond_std `andCond` cond_args cls) | cls_key == readClassKey = Just (cond_std `andCond` cond_args cls) | cls_key == enumClassKey = Just (cond_std `andCond` cond_isEnumeration) | cls_key == ixClassKey = Just (cond_std `andCond` cond_enumOrProduct cls) | cls_key == boundedClassKey = Just (cond_std `andCond` cond_enumOrProduct cls) | cls_key == dataClassKey = Just (checkFlag LangExt.DeriveDataTypeable `andCond` cond_std `andCond` cond_args cls) | cls_key == functorClassKey = Just (checkFlag LangExt.DeriveFunctor `andCond` cond_vanilla `andCond` cond_functorOK True False) | cls_key == foldableClassKey = Just (checkFlag LangExt.DeriveFoldable `andCond` cond_vanilla `andCond` cond_functorOK False True) -- Functor/Fold/Trav works ok -- for rank-n types | cls_key == traversableClassKey = Just (checkFlag LangExt.DeriveTraversable `andCond` cond_vanilla `andCond` cond_functorOK False False) | cls_key == genClassKey = Just (checkFlag LangExt.DeriveGeneric `andCond` cond_vanilla `andCond` cond_RepresentableOk) | cls_key == gen1ClassKey = Just (checkFlag LangExt.DeriveGeneric `andCond` cond_vanilla `andCond` cond_Representable1Ok) | cls_key == liftClassKey = Just (checkFlag LangExt.DeriveLift `andCond` cond_vanilla `andCond` cond_args cls) | otherwise = Nothing where cls_key = getUnique cls cond_std = cond_stdOK mtheta False -- Vanilla data constructors, at least one, -- and monotype arguments cond_vanilla = cond_stdOK mtheta True -- Vanilla data constructors but -- allow no data cons or polytype arguments canDeriveAnyClass :: DynFlags -> TyCon -> Class -> Maybe SDoc -- Nothing: we can (try to) derive it via an empty instance declaration -- Just s: we can't, reason s -- Precondition: the class is not one of the standard ones canDeriveAnyClass dflags _tycon clas | not (xopt LangExt.DeriveAnyClass dflags) = Just (text "Try enabling DeriveAnyClass") | not (any (target_kind `tcEqKind`) [ liftedTypeKind, typeToTypeKind ]) = Just (text "The last argument of class" <+> quotes (ppr clas) <+> text "does not have kind * or (* -> *)") | otherwise = Nothing -- OK! where -- We are making an instance (C t1 .. tn (T s1 .. sm)) -- and we can only do so if the kind of C's last argument -- is * or (* -> *). Because only then can we make a reasonable -- guess at the instance context target_kind = tyVarKind (last (classTyVars clas)) typeToTypeKind :: Kind typeToTypeKind = liftedTypeKind `mkFunTy` liftedTypeKind type Condition = (DynFlags, TyCon, [Type]) -> Validity -- first Bool is whether or not we are allowed to derive Data and Typeable -- second Bool is whether or not we are allowed to derive Functor -- TyCon is the *representation* tycon if the data type is an indexed one -- [Type] are the type arguments to the (representation) TyCon -- Nothing => OK orCond :: Condition -> Condition -> Condition orCond c1 c2 tc = case (c1 tc, c2 tc) of (IsValid, _) -> IsValid -- c1 succeeds (_, IsValid) -> IsValid -- c21 succeeds (NotValid x, NotValid y) -> NotValid (x $$ text " or" $$ y) -- Both fail andCond :: Condition -> Condition -> Condition andCond c1 c2 tc = c1 tc `andValid` c2 tc cond_stdOK :: DerivContext -- Says whether this is standalone deriving or not; -- if standalone, we just say "yes, go for it" -> Bool -- True <=> permissive: allow higher rank -- args and no data constructors -> Condition cond_stdOK (Just _) _ _ = IsValid -- Don't check these conservative conditions for -- standalone deriving; just generate the code -- and let the typechecker handle the result cond_stdOK Nothing permissive (_, rep_tc, _) | null data_cons , not permissive = NotValid (no_cons_why rep_tc $$ suggestion) | not (null con_whys) = NotValid (vcat con_whys $$ suggestion) | otherwise = IsValid where suggestion = text "Possible fix: use a standalone deriving declaration instead" data_cons = tyConDataCons rep_tc con_whys = getInvalids (map check_con data_cons) check_con :: DataCon -> Validity check_con con | not (isVanillaDataCon con) = NotValid (badCon con (text "has existentials or constraints in its type")) | not (permissive || all isTauTy (dataConOrigArgTys con)) = NotValid (badCon con (text "has a higher-rank type")) | otherwise = IsValid no_cons_why :: TyCon -> SDoc no_cons_why rep_tc = quotes (pprSourceTyCon rep_tc) <+> text "must have at least one data constructor" cond_RepresentableOk :: Condition cond_RepresentableOk (dflags, tc, tc_args) = canDoGenerics dflags tc tc_args cond_Representable1Ok :: Condition cond_Representable1Ok (dflags, tc, tc_args) = canDoGenerics1 dflags tc tc_args cond_enumOrProduct :: Class -> Condition cond_enumOrProduct cls = cond_isEnumeration `orCond` (cond_isProduct `andCond` cond_args cls) cond_args :: Class -> Condition -- For some classes (eg Eq, Ord) we allow unlifted arg types -- by generating specialised code. For others (eg Data) we don't. cond_args cls (_, tc, _) = case bad_args of [] -> IsValid (ty:_) -> NotValid (hang (text "Don't know how to derive" <+> quotes (ppr cls)) 2 (text "for type" <+> quotes (ppr ty))) where bad_args = [ arg_ty | con <- tyConDataCons tc , arg_ty <- dataConOrigArgTys con , isUnliftedType arg_ty , not (ok_ty arg_ty) ] cls_key = classKey cls ok_ty arg_ty | cls_key == eqClassKey = check_in arg_ty ordOpTbl | cls_key == ordClassKey = check_in arg_ty ordOpTbl | cls_key == showClassKey = check_in arg_ty boxConTbl | cls_key == liftClassKey = check_in arg_ty litConTbl | otherwise = False -- Read, Ix etc check_in :: Type -> [(Type,a)] -> Bool check_in arg_ty tbl = any (eqType arg_ty . fst) tbl cond_isEnumeration :: Condition cond_isEnumeration (_, rep_tc, _) | isEnumerationTyCon rep_tc = IsValid | otherwise = NotValid why where why = sep [ quotes (pprSourceTyCon rep_tc) <+> text "must be an enumeration type" , text "(an enumeration consists of one or more nullary, non-GADT constructors)" ] -- See Note [Enumeration types] in TyCon cond_isProduct :: Condition cond_isProduct (_, rep_tc, _) | isProductTyCon rep_tc = IsValid | otherwise = NotValid why where why = quotes (pprSourceTyCon rep_tc) <+> text "must have precisely one constructor" cond_functorOK :: Bool -> Bool -> Condition -- OK for Functor/Foldable/Traversable class -- Currently: (a) at least one argument -- (b) don't use argument contravariantly -- (c) don't use argument in the wrong place, e.g. data T a = T (X a a) -- (d) optionally: don't use function types -- (e) no "stupid context" on data type cond_functorOK allowFunctions allowExQuantifiedLastTyVar (_, rep_tc, _) | null tc_tvs = NotValid (text "Data type" <+> quotes (ppr rep_tc) <+> text "must have some type parameters") | not (null bad_stupid_theta) = NotValid (text "Data type" <+> quotes (ppr rep_tc) <+> text "must not have a class context:" <+> pprTheta bad_stupid_theta) | otherwise = allValid (map check_con data_cons) where tc_tvs = tyConTyVars rep_tc Just (_, last_tv) = snocView tc_tvs bad_stupid_theta = filter is_bad (tyConStupidTheta rep_tc) is_bad pred = last_tv `elemVarSet` tyCoVarsOfType pred data_cons = tyConDataCons rep_tc check_con con = allValid (check_universal con : foldDataConArgs (ft_check con) con) check_universal :: DataCon -> Validity check_universal con | allowExQuantifiedLastTyVar = IsValid -- See Note [DeriveFoldable with ExistentialQuantification] -- in TcGenDeriv | Just tv <- getTyVar_maybe (last (tyConAppArgs (dataConOrigResTy con))) , tv `elem` dataConUnivTyVars con , not (tv `elemVarSet` tyCoVarsOfTypes (dataConTheta con)) = IsValid -- See Note [Check that the type variable is truly universal] | otherwise = NotValid (badCon con existential) ft_check :: DataCon -> FFoldType Validity ft_check con = FT { ft_triv = IsValid, ft_var = IsValid , ft_co_var = NotValid (badCon con covariant) , ft_fun = \x y -> if allowFunctions then x `andValid` y else NotValid (badCon con functions) , ft_tup = \_ xs -> allValid xs , ft_ty_app = \_ x -> x , ft_bad_app = NotValid (badCon con wrong_arg) , ft_forall = \_ x -> x } existential = text "must be truly polymorphic in the last argument of the data type" covariant = text "must not use the type variable in a function argument" functions = text "must not contain function types" wrong_arg = text "must use the type variable only as the last argument of a data type" checkFlag :: LangExt.Extension -> Condition checkFlag flag (dflags, _, _) | xopt flag dflags = IsValid | otherwise = NotValid why where why = text "You need " <> text flag_str <+> text "to derive an instance for this class" flag_str = case [ flagSpecName f | f <- xFlags , flagSpecFlag f == flag ] of [s] -> s other -> pprPanic "checkFlag" (ppr other) std_class_via_coercible :: Class -> Bool -- These standard classes can be derived for a newtype -- using the coercible trick *even if no -XGeneralizedNewtypeDeriving -- because giving so gives the same results as generating the boilerplate std_class_via_coercible clas = classKey clas `elem` [eqClassKey, ordClassKey, ixClassKey, boundedClassKey] -- Not Read/Show/Lift because they respect the type -- Not Enum, because newtypes are never in Enum non_coercible_class :: Class -> Bool -- *Never* derive Read, Show, Typeable, Data, Generic, Generic1, Lift -- by Coercible, even with -XGeneralizedNewtypeDeriving -- Also, avoid Traversable, as the Coercible-derived instance and the "normal"-derived -- instance behave differently if there's a non-lawful Applicative out there. -- Besides, with roles, Coercible-deriving Traversable is ill-roled. non_coercible_class cls = classKey cls `elem` ([ readClassKey, showClassKey, dataClassKey , genClassKey, gen1ClassKey, typeableClassKey , traversableClassKey, liftClassKey ]) badCon :: DataCon -> SDoc -> SDoc badCon con msg = text "Constructor" <+> quotes (ppr con) <+> msg {- Note [Check that the type variable is truly universal] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ For Functor and Traversable instances, we must check that the *last argument* of the type constructor is used truly universally quantified. Example data T a b where T1 :: a -> b -> T a b -- Fine! Vanilla H-98 T2 :: b -> c -> T a b -- Fine! Existential c, but we can still map over 'b' T3 :: b -> T Int b -- Fine! Constraint 'a', but 'b' is still polymorphic T4 :: Ord b => b -> T a b -- No! 'b' is constrained T5 :: b -> T b b -- No! 'b' is constrained T6 :: T a (b,b) -- No! 'b' is constrained Notice that only the first of these constructors is vanilla H-98. We only need to take care about the last argument (b in this case). See Trac #8678. Eg. for T1-T3 we can write fmap f (T1 a b) = T1 a (f b) fmap f (T2 b c) = T2 (f b) c fmap f (T3 x) = T3 (f x) We need not perform these checks for Foldable instances, however, since functions in Foldable can only consume existentially quantified type variables, rather than produce them (as is the case in Functor and Traversable functions.) As a result, T can have a derived Foldable instance: foldr f z (T1 a b) = f b z foldr f z (T2 b c) = f b z foldr f z (T3 x) = f x z foldr f z (T4 x) = f x z foldr f z (T5 x) = f x z foldr _ z T6 = z See Note [DeriveFoldable with ExistentialQuantification] in TcGenDeriv. Note [Superclasses of derived instance] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In general, a derived instance decl needs the superclasses of the derived class too. So if we have data T a = ...deriving( Ord ) then the initial context for Ord (T a) should include Eq (T a). Often this is redundant; we'll also generate an Ord constraint for each constructor argument, and that will probably generate enough constraints to make the Eq (T a) constraint be satisfied too. But not always; consider: data S a = S instance Eq (S a) instance Ord (S a) data T a = MkT (S a) deriving( Ord ) instance Num a => Eq (T a) The derived instance for (Ord (T a)) must have a (Num a) constraint! Similarly consider: data T a = MkT deriving( Data, Typeable ) Here there *is* no argument field, but we must nevertheless generate a context for the Data instances: instance Typable a => Data (T a) where ... ************************************************************************ * * Deriving newtypes * * ************************************************************************ -} mkNewTypeEqn :: DynFlags -> Maybe OverlapMode -> [TyVar] -> Class -> [Type] -> TyCon -> [Type] -> TyCon -> [Type] -> DerivContext -> TcRn EarlyDerivSpec mkNewTypeEqn dflags overlap_mode tvs cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta -- Want: instance (...) => cls (cls_tys ++ [tycon tc_args]) where ... | ASSERT( length cls_tys + 1 == classArity cls ) might_derive_via_coercible && ((newtype_deriving && not deriveAnyClass) || std_class_via_coercible cls) = do traceTc "newtype deriving:" (ppr tycon <+> ppr rep_tys <+> ppr all_preds) dfun_name <- newDFunName' cls tycon loc <- getSrcSpanM case mtheta of Just theta -> return $ GivenTheta $ DS { ds_loc = loc , ds_name = dfun_name, ds_tvs = varSetElemsWellScoped dfun_tvs , ds_cls = cls, ds_tys = inst_tys , ds_tc = rep_tycon , ds_theta = theta , ds_overlap = overlap_mode , ds_newtype = Just rep_inst_ty } Nothing -> return $ InferTheta $ DS { ds_loc = loc , ds_name = dfun_name, ds_tvs = varSetElemsWellScoped dfun_tvs , ds_cls = cls, ds_tys = inst_tys , ds_tc = rep_tycon , ds_theta = all_preds , ds_overlap = overlap_mode , ds_newtype = Just rep_inst_ty } | otherwise = case checkSideConditions dflags mtheta cls cls_tys rep_tycon rep_tc_args of -- Error with standard class DerivableClassError msg | might_derive_via_coercible -> bale_out (msg $$ suggest_gnd) | otherwise -> bale_out msg -- Must use newtype deriving or DeriveAnyClass NonDerivableClass _msg -- Too hard, even with newtype deriving | newtype_deriving -> bale_out cant_derive_err -- Try newtype deriving! -- Here we suggest GeneralizedNewtypeDeriving even in cases where it may -- not be applicable. See Trac #9600. | otherwise -> bale_out (non_std $$ suggest_gnd) -- CanDerive/DerivableViaInstance _ -> do when (newtype_deriving && deriveAnyClass) $ addWarnTc NoReason (sep [ text "Both DeriveAnyClass and GeneralizedNewtypeDeriving are enabled" , text "Defaulting to the DeriveAnyClass strategy for instantiating" <+> ppr cls ]) go_for_it where newtype_deriving = xopt LangExt.GeneralizedNewtypeDeriving dflags deriveAnyClass = xopt LangExt.DeriveAnyClass dflags go_for_it = mk_data_eqn overlap_mode tvs cls cls_tys tycon tc_args rep_tycon rep_tc_args mtheta bale_out = bale_out' newtype_deriving bale_out' b = failWithTc . derivingThingErr b cls cls_tys inst_ty non_std = nonStdErr cls suggest_gnd = text "Try GeneralizedNewtypeDeriving for GHC's newtype-deriving extension" -- Here is the plan for newtype derivings. We see -- newtype T a1...an = MkT (t ak+1...an) deriving (.., C s1 .. sm, ...) -- where t is a type, -- ak+1...an is a suffix of a1..an, and are all tyars -- ak+1...an do not occur free in t, nor in the s1..sm -- (C s1 ... sm) is a *partial applications* of class C -- with the last parameter missing -- (T a1 .. ak) matches the kind of C's last argument -- (and hence so does t) -- The latter kind-check has been done by deriveTyData already, -- and tc_args are already trimmed -- -- We generate the instance -- instance forall ({a1..ak} u fvs(s1..sm)). -- C s1 .. sm t => C s1 .. sm (T a1...ak) -- where T a1...ap is the partial application of -- the LHS of the correct kind and p >= k -- -- NB: the variables below are: -- tc_tvs = [a1, ..., an] -- tyvars_to_keep = [a1, ..., ak] -- rep_ty = t ak .. an -- deriv_tvs = fvs(s1..sm) \ tc_tvs -- tys = [s1, ..., sm] -- rep_fn' = t -- -- Running example: newtype T s a = MkT (ST s a) deriving( Monad ) -- We generate the instance -- instance Monad (ST s) => Monad (T s) where nt_eta_arity = newTyConEtadArity rep_tycon -- For newtype T a b = MkT (S a a b), the TyCon machinery already -- eta-reduces the representation type, so we know that -- T a ~ S a a -- That's convenient here, because we may have to apply -- it to fewer than its original complement of arguments -- Note [Newtype representation] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Need newTyConRhs (*not* a recursive representation finder) -- to get the representation type. For example -- newtype B = MkB Int -- newtype A = MkA B deriving( Num ) -- We want the Num instance of B, *not* the Num instance of Int, -- when making the Num instance of A! rep_inst_ty = newTyConInstRhs rep_tycon rep_tc_args rep_tys = cls_tys ++ [rep_inst_ty] rep_pred = mkClassPred cls rep_tys rep_pred_o = mkPredOrigin DerivOrigin TypeLevel rep_pred -- rep_pred is the representation dictionary, from where -- we are gong to get all the methods for the newtype -- dictionary -- Next we figure out what superclass dictionaries to use -- See Note [Newtype deriving superclasses] above cls_tyvars = classTyVars cls dfun_tvs = tyCoVarsOfTypes inst_tys inst_ty = mkTyConApp tycon tc_args inst_tys = cls_tys ++ [inst_ty] sc_theta = mkThetaOrigin DerivOrigin TypeLevel $ substTheta (zipTvSubst cls_tyvars inst_tys) $ classSCTheta cls -- Next we collect Coercible constraints between -- the Class method types, instantiated with the representation and the -- newtype type; precisely the constraints required for the -- calls to coercible that we are going to generate. coercible_constraints = [ let (Pair t1 t2) = mkCoerceClassMethEqn cls (varSetElemsWellScoped dfun_tvs) inst_tys rep_inst_ty meth in mkPredOrigin (DerivOriginCoerce meth t1 t2) TypeLevel (mkReprPrimEqPred t1 t2) | meth <- classMethods cls ] -- If there are no tyvars, there's no need -- to abstract over the dictionaries we need -- Example: newtype T = MkT Int deriving( C ) -- We get the derived instance -- instance C T -- rather than -- instance C Int => C T all_preds = rep_pred_o : coercible_constraints ++ sc_theta -- NB: rep_pred comes first ------------------------------------------------------------------- -- Figuring out whether we can only do this newtype-deriving thing -- See Note [Determining whether newtype-deriving is appropriate] might_derive_via_coercible = not (non_coercible_class cls) && eta_ok && ats_ok -- && not (isRecursiveTyCon tycon) -- Note [Recursive newtypes] -- Check that eta reduction is OK eta_ok = nt_eta_arity <= length rep_tc_args -- The newtype can be eta-reduced to match the number -- of type argument actually supplied -- newtype T a b = MkT (S [a] b) deriving( Monad ) -- Here the 'b' must be the same in the rep type (S [a] b) -- And the [a] must not mention 'b'. That's all handled -- by nt_eta_rity. ats_ok = null (classATs cls) -- No associated types for the class, because we don't -- currently generate type 'instance' decls; and cannot do -- so for 'data' instance decls cant_derive_err = vcat [ ppUnless eta_ok eta_msg , ppUnless ats_ok ats_msg ] eta_msg = text "cannot eta-reduce the representation type enough" ats_msg = text "the class has associated types" {- Note [Recursive newtypes] ~~~~~~~~~~~~~~~~~~~~~~~~~ Newtype deriving works fine, even if the newtype is recursive. e.g. newtype S1 = S1 [T1 ()] newtype T1 a = T1 (StateT S1 IO a ) deriving( Monad ) Remember, too, that type families are currently (conservatively) given a recursive flag, so this also allows newtype deriving to work for type famillies. We used to exclude recursive types, because we had a rather simple minded way of generating the instance decl: newtype A = MkA [A] instance Eq [A] => Eq A -- Makes typechecker loop! But now we require a simple context, so it's ok. Note [Determining whether newtype-deriving is appropriate] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we see newtype NT = MkNT Foo deriving C we have to decide how to perform the deriving. Do we do newtype deriving, or do we do normal deriving? In general, we prefer to do newtype deriving wherever possible. So, we try newtype deriving unless there's a glaring reason not to. Note that newtype deriving might fail, even after we commit to it. This is because the derived instance uses `coerce`, which must satisfy its `Coercible` constraint. This is different than other deriving scenarios, where we're sure that the resulting instance will type-check. ************************************************************************ * * Finding the fixed point of deriving equations * * ************************************************************************ Note [Simplifying the instance context] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T a b = C1 (Foo a) (Bar b) | C2 Int (T b a) | C3 (T a a) deriving (Eq) We want to come up with an instance declaration of the form instance (Ping a, Pong b, ...) => Eq (T a b) where x == y = ... It is pretty easy, albeit tedious, to fill in the code "...". The trick is to figure out what the context for the instance decl is, namely Ping, Pong and friends. Let's call the context reqd for the T instance of class C at types (a,b, ...) C (T a b). Thus: Eq (T a b) = (Ping a, Pong b, ...) Now we can get a (recursive) equation from the data decl. This part is done by inferConstraints. Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1 u Eq (T b a) u Eq Int -- From C2 u Eq (T a a) -- From C3 Foo and Bar may have explicit instances for Eq, in which case we can just substitute for them. Alternatively, either or both may have their Eq instances given by deriving clauses, in which case they form part of the system of equations. Now all we need do is simplify and solve the equations, iterating to find the least fixpoint. This is done by simplifyInstanceConstraints. Notice that the order of the arguments can switch around, as here in the recursive calls to T. Let's suppose Eq (Foo a) = Eq a, and Eq (Bar b) = Ping b. We start with: Eq (T a b) = {} -- The empty set Next iteration: Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1 u Eq (T b a) u Eq Int -- From C2 u Eq (T a a) -- From C3 After simplification: = Eq a u Ping b u {} u {} u {} = Eq a u Ping b Next iteration: Eq (T a b) = Eq (Foo a) u Eq (Bar b) -- From C1 u Eq (T b a) u Eq Int -- From C2 u Eq (T a a) -- From C3 After simplification: = Eq a u Ping b u (Eq b u Ping a) u (Eq a u Ping a) = Eq a u Ping b u Eq b u Ping a The next iteration gives the same result, so this is the fixpoint. We need to make a canonical form of the RHS to ensure convergence. We do this by simplifying the RHS to a form in which - the classes constrain only tyvars - the list is sorted by tyvar (major key) and then class (minor key) - no duplicates, of course -} simplifyInstanceContexts :: [DerivSpec ThetaOrigin] -> TcM [DerivSpec ThetaType] -- Used only for deriving clauses (InferTheta) -- not for standalone deriving -- See Note [Simplifying the instance context] simplifyInstanceContexts [] = return [] simplifyInstanceContexts infer_specs = do { traceTc "simplifyInstanceContexts" $ vcat (map pprDerivSpec infer_specs) ; iterate_deriv 1 initial_solutions } where ------------------------------------------------------------------ -- The initial solutions for the equations claim that each -- instance has an empty context; this solution is certainly -- in canonical form. initial_solutions :: [ThetaType] initial_solutions = [ [] | _ <- infer_specs ] ------------------------------------------------------------------ -- iterate_deriv calculates the next batch of solutions, -- compares it with the current one; finishes if they are the -- same, otherwise recurses with the new solutions. -- It fails if any iteration fails iterate_deriv :: Int -> [ThetaType] -> TcM [DerivSpec ThetaType] iterate_deriv n current_solns | n > 20 -- Looks as if we are in an infinite loop -- This can happen if we have -XUndecidableInstances -- (See TcSimplify.tcSimplifyDeriv.) = pprPanic "solveDerivEqns: probable loop" (vcat (map pprDerivSpec infer_specs) $$ ppr current_solns) | otherwise = do { -- Extend the inst info from the explicit instance decls -- with the current set of solutions, and simplify each RHS inst_specs <- zipWithM newDerivClsInst current_solns infer_specs ; new_solns <- checkNoErrs $ extendLocalInstEnv inst_specs $ mapM gen_soln infer_specs ; if (current_solns `eqSolution` new_solns) then return [ spec { ds_theta = soln } | (spec, soln) <- zip infer_specs current_solns ] else iterate_deriv (n+1) new_solns } eqSolution = eqListBy (eqListBy eqType) ------------------------------------------------------------------ gen_soln :: DerivSpec ThetaOrigin -> TcM ThetaType gen_soln (DS { ds_loc = loc, ds_tvs = tyvars , ds_cls = clas, ds_tys = inst_tys, ds_theta = deriv_rhs }) = setSrcSpan loc $ addErrCtxt (derivInstCtxt the_pred) $ do { theta <- simplifyDeriv the_pred tyvars deriv_rhs -- checkValidInstance tyvars theta clas inst_tys -- Not necessary; see Note [Exotic derived instance contexts] ; traceTc "TcDeriv" (ppr deriv_rhs $$ ppr theta) -- Claim: the result instance declaration is guaranteed valid -- Hence no need to call: -- checkValidInstance tyvars theta clas inst_tys ; return (sortBy cmpType theta) } -- Canonicalise before returning the solution where the_pred = mkClassPred clas inst_tys ------------------------------------------------------------------ newDerivClsInst :: ThetaType -> DerivSpec theta -> TcM ClsInst newDerivClsInst theta (DS { ds_name = dfun_name, ds_overlap = overlap_mode , ds_tvs = tvs, ds_cls = clas, ds_tys = tys }) = newClsInst overlap_mode dfun_name tvs theta clas tys extendLocalInstEnv :: [ClsInst] -> TcM a -> TcM a -- Add new locally-defined instances; don't bother to check -- for functional dependency errors -- that'll happen in TcInstDcls extendLocalInstEnv dfuns thing_inside = do { env <- getGblEnv ; let inst_env' = extendInstEnvList (tcg_inst_env env) dfuns env' = env { tcg_inst_env = inst_env' } ; setGblEnv env' thing_inside } {- *********************************************************************************** * * * Simplify derived constraints * * *********************************************************************************** -} simplifyDeriv :: PredType -> [TyVar] -> ThetaOrigin -- Wanted -> TcM ThetaType -- Needed -- Given instance (wanted) => C inst_ty -- Simplify 'wanted' as much as possibles -- Fail if not possible simplifyDeriv pred tvs theta = do { (skol_subst, tvs_skols) <- tcInstSkolTyVars tvs -- Skolemize -- The constraint solving machinery -- expects *TcTyVars* not TyVars. -- We use *non-overlappable* (vanilla) skolems -- See Note [Overlap and deriving] ; let skol_set = mkVarSet tvs_skols skol_info = DerivSkol pred doc = text "deriving" <+> parens (ppr pred) mk_ct (PredOrigin t o t_or_k) = newWanted o (Just t_or_k) (substTy skol_subst t) ; (wanted, tclvl) <- pushTcLevelM (mapM mk_ct theta) ; traceTc "simplifyDeriv" $ vcat [ pprTvBndrs tvs $$ ppr theta $$ ppr wanted, doc ] ; residual_wanted <- simplifyWantedsTcM wanted -- Result is zonked ; let residual_simple = wc_simple residual_wanted (good, bad) = partitionBagWith get_good residual_simple unsolved = residual_wanted { wc_simple = bad } -- See Note [Exotic derived instance contexts] get_good :: Ct -> Either PredType Ct get_good ct | validDerivPred skol_set p , isWantedCt ct = Left p -- NB: residual_wanted may contain unsolved -- Derived and we stick them into the bad set -- so that reportUnsolved may decide what to do with them | otherwise = Right ct where p = ctPred ct ; traceTc "simplifyDeriv 2" $ vcat [ ppr tvs_skols, ppr residual_simple, ppr good, ppr bad ] -- If we are deferring type errors, simply ignore any insoluble -- constraints. They'll come up again when we typecheck the -- generated instance declaration ; defer <- goptM Opt_DeferTypeErrors ; (implic, _) <- buildImplicationFor tclvl skol_info tvs_skols [] unsolved -- The buildImplicationFor is just to bind the skolems, -- in case they are mentioned in error messages -- See Trac #11347 ; unless defer (reportAllUnsolved (mkImplicWC implic)) ; let min_theta = mkMinimalBySCs (bagToList good) subst_skol = zipTvSubst tvs_skols $ mkTyVarTys tvs -- The reverse substitution (sigh) ; return (substTheta subst_skol min_theta) } {- Note [Overlap and deriving] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider some overlapping instances: data Show a => Show [a] where .. data Show [Char] where ... Now a data type with deriving: data T a = MkT [a] deriving( Show ) We want to get the derived instance instance Show [a] => Show (T a) where... and NOT instance Show a => Show (T a) where... so that the (Show (T Char)) instance does the Right Thing It's very like the situation when we're inferring the type of a function f x = show [x] and we want to infer f :: Show [a] => a -> String BOTTOM LINE: use vanilla, non-overlappable skolems when inferring the context for the derived instance. Hence tcInstSkolTyVars not tcInstSuperSkolTyVars Note [Exotic derived instance contexts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In a 'derived' instance declaration, we *infer* the context. It's a bit unclear what rules we should apply for this; the Haskell report is silent. Obviously, constraints like (Eq a) are fine, but what about data T f a = MkT (f a) deriving( Eq ) where we'd get an Eq (f a) constraint. That's probably fine too. One could go further: consider data T a b c = MkT (Foo a b c) deriving( Eq ) instance (C Int a, Eq b, Eq c) => Eq (Foo a b c) Notice that this instance (just) satisfies the Paterson termination conditions. Then we *could* derive an instance decl like this: instance (C Int a, Eq b, Eq c) => Eq (T a b c) even though there is no instance for (C Int a), because there just *might* be an instance for, say, (C Int Bool) at a site where we need the equality instance for T's. However, this seems pretty exotic, and it's quite tricky to allow this, and yet give sensible error messages in the (much more common) case where we really want that instance decl for C. So for now we simply require that the derived instance context should have only type-variable constraints. Here is another example: data Fix f = In (f (Fix f)) deriving( Eq ) Here, if we are prepared to allow -XUndecidableInstances we could derive the instance instance Eq (f (Fix f)) => Eq (Fix f) but this is so delicate that I don't think it should happen inside 'deriving'. If you want this, write it yourself! NB: if you want to lift this condition, make sure you still meet the termination conditions! If not, the deriving mechanism generates larger and larger constraints. Example: data Succ a = S a data Seq a = Cons a (Seq (Succ a)) | Nil deriving Show Note the lack of a Show instance for Succ. First we'll generate instance (Show (Succ a), Show a) => Show (Seq a) and then instance (Show (Succ (Succ a)), Show (Succ a), Show a) => Show (Seq a) and so on. Instead we want to complain of no instance for (Show (Succ a)). The bottom line ~~~~~~~~~~~~~~~ Allow constraints which consist only of type variables, with no repeats. ************************************************************************ * * \subsection[TcDeriv-normal-binds]{Bindings for the various classes} * * ************************************************************************ After all the trouble to figure out the required context for the derived instance declarations, all that's left is to chug along to produce them. They will then be shoved into @tcInstDecls2@, which will do all its usual business. There are lots of possibilities for code to generate. Here are various general remarks. PRINCIPLES: \begin{itemize} \item We want derived instances of @Eq@ and @Ord@ (both v common) to be ``you-couldn't-do-better-by-hand'' efficient. \item Deriving @Show@---also pretty common--- should also be reasonable good code. \item Deriving for the other classes isn't that common or that big a deal. \end{itemize} PRAGMATICS: \begin{itemize} \item Deriving @Ord@ is done mostly with the 1.3 @compare@ method. \item Deriving @Eq@ also uses @compare@, if we're deriving @Ord@, too. \item We {\em normally} generate code only for the non-defaulted methods; there are some exceptions for @Eq@ and (especially) @Ord@... \item Sometimes we use a @_con2tag_<tycon>@ function, which returns a data constructor's numeric (@Int#@) tag. These are generated by @gen_tag_n_con_binds@, and the heuristic for deciding if one of these is around is given by @hasCon2TagFun@. The examples under the different sections below will make this clearer. \item Much less often (really just for deriving @Ix@), we use a @_tag2con_<tycon>@ function. See the examples. \item We use the renamer!!! Reason: we're supposed to be producing @LHsBinds Name@ for the methods, but that means producing correctly-uniquified code on the fly. This is entirely possible (the @TcM@ monad has a @UniqueSupply@), but it is painful. So, instead, we produce @MonoBinds RdrName@ then heave 'em through the renamer. What a great hack! \end{itemize} -} -- Generate the InstInfo for the required instance paired with the -- *representation* tycon for that instance, -- plus any auxiliary bindings required -- -- Representation tycons differ from the tycon in the instance signature in -- case of instances for indexed families. -- genInst :: DerivSpec ThetaType -> TcM (InstInfo RdrName, BagDerivStuff, Maybe Name) genInst spec@(DS { ds_tvs = tvs, ds_tc = rep_tycon , ds_theta = theta, ds_newtype = is_newtype, ds_tys = tys , ds_name = dfun_name, ds_cls = clas, ds_loc = loc }) | Just rhs_ty <- is_newtype -- See Note [Bindings for Generalised Newtype Deriving] = do { inst_spec <- newDerivClsInst theta spec ; traceTc "genInst/is_newtype" (vcat [ppr loc, ppr clas, ppr tvs, ppr tys, ppr rhs_ty]) ; return ( InstInfo { iSpec = inst_spec , iBinds = InstBindings { ib_binds = gen_Newtype_binds loc clas tvs tys rhs_ty , ib_tyvars = map Var.varName tvs -- Scope over bindings , ib_pragmas = [] , ib_extensions = [ LangExt.ImpredicativeTypes , LangExt.RankNTypes ] , ib_derived = True } } , emptyBag , Just $ getName $ head $ tyConDataCons rep_tycon ) } -- See Note [Newtype deriving and unused constructors] | otherwise = do { (meth_binds, deriv_stuff) <- genDerivStuff loc clas dfun_name rep_tycon tys tvs ; inst_spec <- newDerivClsInst theta spec ; traceTc "newder" (ppr inst_spec) ; let inst_info = InstInfo { iSpec = inst_spec , iBinds = InstBindings { ib_binds = meth_binds , ib_tyvars = map Var.varName tvs , ib_pragmas = [] , ib_extensions = [] , ib_derived = True } } ; return ( inst_info, deriv_stuff, Nothing ) } -- Generate the bindings needed for a derived class that isn't handled by -- -XGeneralizedNewtypeDeriving. genDerivStuff :: SrcSpan -> Class -> Name -> TyCon -> [Type] -> [TyVar] -> TcM (LHsBinds RdrName, BagDerivStuff) genDerivStuff loc clas dfun_name tycon inst_tys tyvars -- Special case for DeriveGeneric | let ck = classKey clas , ck `elem` [genClassKey, gen1ClassKey] = let gk = if ck == genClassKey then Gen0 else Gen1 -- TODO NSF: correctly identify when we're building Both instead of One in do (binds, faminst) <- gen_Generic_binds gk tycon (nameModule dfun_name) return (binds, unitBag (DerivFamInst faminst)) -- Not deriving Generic(1), so we first check if the compiler has built-in -- support for deriving the class in question. | otherwise = do { dflags <- getDynFlags ; fix_env <- getDataConFixityFun tycon ; case hasBuiltinDeriving dflags fix_env clas of Just gen_fn -> return (gen_fn loc tycon) Nothing -> genDerivAnyClass dflags } where genDerivAnyClass :: DynFlags -> TcM (LHsBinds RdrName, BagDerivStuff) genDerivAnyClass dflags = do { -- If there isn't compiler support for deriving the class, our last -- resort is -XDeriveAnyClass (since -XGeneralizedNewtypeDeriving -- fell through). let mini_env = mkVarEnv (classTyVars clas `zip` inst_tys) mini_subst = mkTvSubst (mkInScopeSet (mkVarSet tyvars)) mini_env ; tyfam_insts <- ASSERT2( isNothing (canDeriveAnyClass dflags tycon clas) , ppr "genDerivStuff: bad derived class" <+> ppr clas ) mapM (tcATDefault False loc mini_subst emptyNameSet) (classATItems clas) ; return ( emptyBag -- No method bindings are needed... , listToBag (map DerivFamInst (concat tyfam_insts)) -- ...but we may need to generate binding for associated type -- family default instances. -- See Note [DeriveAnyClass and default family instances] ) } getDataConFixityFun :: TyCon -> TcM (Name -> Fixity) -- If the TyCon is locally defined, we want the local fixity env; -- but if it is imported (which happens for standalone deriving) -- we need to get the fixity env from the interface file -- c.f. RnEnv.lookupFixity, and Trac #9830 getDataConFixityFun tc = do { this_mod <- getModule ; if nameIsLocalOrFrom this_mod name then do { fix_env <- getFixityEnv ; return (lookupFixity fix_env) } else do { iface <- loadInterfaceForName doc name -- Should already be loaded! ; return (mi_fix iface . nameOccName) } } where name = tyConName tc doc = text "Data con fixities for" <+> ppr name {- Note [Bindings for Generalised Newtype Deriving] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider class Eq a => C a where f :: a -> a newtype N a = MkN [a] deriving( C ) instance Eq (N a) where ... The 'deriving C' clause generates, in effect instance (C [a], Eq a) => C (N a) where f = coerce (f :: [a] -> [a]) This generates a cast for each method, but allows the superclasse to be worked out in the usual way. In this case the superclass (Eq (N a)) will be solved by the explicit Eq (N a) instance. We do *not* create the superclasses by casting the superclass dictionaries for the representation type. See the paper "Safe zero-cost coercions for Hsakell". Note [DeriveAnyClass and default family instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When a class has a associated type family with a default instance, e.g.: class C a where type T a type T a = Char then there are a couple of scenarios in which a user would expect T a to default to Char. One is when an instance declaration for C is given without an implementation for T: instance C Int Another scenario in which this can occur is when the -XDeriveAnyClass extension is used: data Example = Example deriving (C, Generic) In the latter case, we must take care to check if C has any associated type families with default instances, because -XDeriveAnyClass will never provide an implementation for them. We "fill in" the default instances using the tcATDefault function from TcClsDcl (which is also used in TcInstDcls to handle the empty instance declaration case). ************************************************************************ * * \subsection[TcDeriv-taggery-Names]{What con2tag/tag2con functions are available?} * * ************************************************************************ -} derivingNullaryErr :: MsgDoc derivingNullaryErr = text "Cannot derive instances for nullary classes" derivingKindErr :: TyCon -> Class -> [Type] -> Kind -> MsgDoc derivingKindErr tc cls cls_tys cls_kind = hang (text "Cannot derive well-kinded instance of form" <+> quotes (pprClassPred cls cls_tys <+> parens (ppr tc <+> text "..."))) 2 (text "Class" <+> quotes (ppr cls) <+> text "expects an argument of kind" <+> quotes (pprKind cls_kind)) derivingEtaErr :: Class -> [Type] -> Type -> MsgDoc derivingEtaErr cls cls_tys inst_ty = sep [text "Cannot eta-reduce to an instance of form", nest 2 (text "instance (...) =>" <+> pprClassPred cls (cls_tys ++ [inst_ty]))] derivingThingErr :: Bool -> Class -> [Type] -> Type -> MsgDoc -> MsgDoc derivingThingErr newtype_deriving clas tys ty why = sep [(hang (text "Can't make a derived instance of") 2 (quotes (ppr pred)) $$ nest 2 extra) <> colon, nest 2 why] where extra | newtype_deriving = text "(even with cunning GeneralizedNewtypeDeriving)" | otherwise = Outputable.empty pred = mkClassPred clas (tys ++ [ty]) derivingHiddenErr :: TyCon -> SDoc derivingHiddenErr tc = hang (text "The data constructors of" <+> quotes (ppr tc) <+> ptext (sLit "are not all in scope")) 2 (text "so you cannot derive an instance for it") standaloneCtxt :: LHsSigType Name -> SDoc standaloneCtxt ty = hang (text "In the stand-alone deriving instance for") 2 (quotes (ppr ty)) derivInstCtxt :: PredType -> MsgDoc derivInstCtxt pred = text "When deriving the instance for" <+> parens (ppr pred)
mcschroeder/ghc
compiler/typecheck/TcDeriv.hs
Haskell
bsd-3-clause
96,356
module Test where import Data.List main :: IO () main = return () f::(Ord b, Show b, Eq a) => b -> a f = undefined
sebastiaanvisser/ghc-goals
tests/Test.hs
Haskell
bsd-3-clause
120
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 TcSplice: Template Haskell splices -} {-# LANGUAGE CPP, FlexibleInstances, MagicHash, ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module TcSplice( -- These functions are defined in stage1 and stage2 -- The raise civilised errors in stage1 tcSpliceExpr, tcTypedBracket, tcUntypedBracket, -- runQuasiQuoteExpr, runQuasiQuotePat, -- runQuasiQuoteDecl, runQuasiQuoteType, runAnnotation, #ifdef GHCI -- These ones are defined only in stage2, and are -- called only in stage2 (ie GHCI is on) runMetaE, runMetaP, runMetaT, runMetaD, runQuasi, tcTopSpliceExpr, lookupThName_maybe, defaultRunMeta, runMeta' #endif ) where #include "HsVersions.h" import HsSyn import Annotations import Name import TcRnMonad import TcType #ifdef GHCI import HscMain -- These imports are the reason that TcSplice -- is very high up the module hierarchy import RnSplice( traceSplice, SpliceInfo(..) ) import RdrName import HscTypes import Convert import RnExpr import RnEnv import RnTypes import TcExpr import TcHsSyn import TcSimplify import TcUnify import Type import Kind import NameSet import TcEnv import TcMType import TcHsType import TcIface import TypeRep import FamInst import FamInstEnv import InstEnv import NameEnv import PrelNames import OccName import Hooks import Var import Module import LoadIface import Class import Inst import TyCon import CoAxiom import PatSyn ( patSynName ) import ConLike import DataCon import TcEvidence( TcEvBinds(..) ) import Id import IdInfo import DsExpr import DsMonad import Serialized import ErrUtils import SrcLoc import Util import Data.List ( mapAccumL ) import Unique import VarSet ( isEmptyVarSet ) import Data.Maybe import BasicTypes hiding( SuccessFlag(..) ) import Maybes( MaybeErr(..) ) import DynFlags import Panic import Lexeme import FastString import Outputable import DsMeta import qualified Language.Haskell.TH as TH -- THSyntax gives access to internal functions and data types import qualified Language.Haskell.TH.Syntax as TH -- Because GHC.Desugar might not be in the base library of the bootstrapping compiler import GHC.Desugar ( AnnotationWrapper(..) ) import qualified Data.Map as Map import Data.Dynamic ( fromDynamic, toDyn ) import Data.Typeable ( typeOf ) import Data.Data (Data) import GHC.Exts ( unsafeCoerce# ) #endif {- ************************************************************************ * * \subsection{Main interface + stubs for the non-GHCI case * * ************************************************************************ -} tcTypedBracket :: HsBracket Name -> TcRhoType -> TcM (HsExpr TcId) tcUntypedBracket :: HsBracket Name -> [PendingRnSplice] -> TcRhoType -> TcM (HsExpr TcId) tcSpliceExpr :: HsSplice Name -> TcRhoType -> TcM (HsExpr TcId) -- None of these functions add constraints to the LIE -- runQuasiQuoteExpr :: HsQuasiQuote RdrName -> RnM (LHsExpr RdrName) -- runQuasiQuotePat :: HsQuasiQuote RdrName -> RnM (LPat RdrName) -- runQuasiQuoteType :: HsQuasiQuote RdrName -> RnM (LHsType RdrName) -- runQuasiQuoteDecl :: HsQuasiQuote RdrName -> RnM [LHsDecl RdrName] runAnnotation :: CoreAnnTarget -> LHsExpr Name -> TcM Annotation #ifndef GHCI tcTypedBracket x _ = failTH x "Template Haskell bracket" tcUntypedBracket x _ _ = failTH x "Template Haskell bracket" tcSpliceExpr e _ = failTH e "Template Haskell splice" -- runQuasiQuoteExpr q = failTH q "quasiquote" -- runQuasiQuotePat q = failTH q "pattern quasiquote" -- runQuasiQuoteType q = failTH q "type quasiquote" -- runQuasiQuoteDecl q = failTH q "declaration quasiquote" runAnnotation _ q = failTH q "annotation" #else -- The whole of the rest of the file is the else-branch (ie stage2 only) {- Note [How top-level splices are handled] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Top-level splices (those not inside a [| .. |] quotation bracket) are handled very straightforwardly: 1. tcTopSpliceExpr: typecheck the body e of the splice $(e) 2. runMetaT: desugar, compile, run it, and convert result back to HsSyn RdrName (of the appropriate flavour, eg HsType RdrName, HsExpr RdrName etc) 3. treat the result as if that's what you saw in the first place e.g for HsType, rename and kind-check for HsExpr, rename and type-check (The last step is different for decls, because they can *only* be top-level: we return the result of step 2.) Note [How brackets and nested splices are handled] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Nested splices (those inside a [| .. |] quotation bracket), are treated quite differently. Remember, there are two forms of bracket typed [|| e ||] and untyped [| e |] The life cycle of a typed bracket: * Starts as HsBracket * When renaming: * Set the ThStage to (Brack s RnPendingTyped) * Rename the body * Result is still a HsBracket * When typechecking: * Set the ThStage to (Brack s (TcPending ps_var lie_var)) * Typecheck the body, and throw away the elaborated result * Nested splices (which must be typed) are typechecked, and the results accumulated in ps_var; their constraints accumulate in lie_var * Result is a HsTcBracketOut rn_brack pending_splices where rn_brack is the incoming renamed bracket The life cycle of a un-typed bracket: * Starts as HsBracket * When renaming: * Set the ThStage to (Brack s (RnPendingUntyped ps_var)) * Rename the body * Nested splices (which must be untyped) are renamed, and the results accumulated in ps_var * Result is still (HsRnBracketOut rn_body pending_splices) * When typechecking a HsRnBracketOut * Typecheck the pending_splices individually * Ignore the body of the bracket; just check that the context expects a bracket of that type (e.g. a [p| pat |] bracket should be in a context needing a (Q Pat) * Result is a HsTcBracketOut rn_brack pending_splices where rn_brack is the incoming renamed bracket In both cases, desugaring happens like this: * HsTcBracketOut is desugared by DsMeta.dsBracket. It a) Extends the ds_meta environment with the PendingSplices attached to the bracket b) Converts the quoted (HsExpr Name) to a CoreExpr that, when run, will produce a suitable TH expression/type/decl. This is why we leave the *renamed* expression attached to the bracket: the quoted expression should not be decorated with all the goop added by the type checker * Each splice carries a unique Name, called a "splice point", thus ${n}(e). The name is initialised to an (Unqual "splice") when the splice is created; the renamer gives it a unique. * When DsMeta (used to desugar the body of the bracket) comes across a splice, it looks up the splice's Name, n, in the ds_meta envt, to find an (HsExpr Id) that should be substituted for the splice; it just desugars it to get a CoreExpr (DsMeta.repSplice). Example: Source: f = [| Just $(g 3) |] The [| |] part is a HsBracket Typechecked: f = [| Just ${s7}(g 3) |]{s7 = g Int 3} The [| |] part is a HsBracketOut, containing *renamed* (not typechecked) expression The "s7" is the "splice point"; the (g Int 3) part is a typechecked expression Desugared: f = do { s7 <- g Int 3 ; return (ConE "Data.Maybe.Just" s7) } Note [Template Haskell state diagram] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here are the ThStages, s, their corresponding level numbers (the result of (thLevel s)), and their state transitions. The top level of the program is stage Comp: Start here | V ----------- $ ------------ $ | Comp | ---------> | Splice | -----| | 1 | | 0 | <----| ----------- ------------ ^ | ^ | $ | | [||] $ | | [||] | v | v -------------- ---------------- | Brack Comp | | Brack Splice | | 2 | | 1 | -------------- ---------------- * Normal top-level declarations start in state Comp (which has level 1). Annotations start in state Splice, since they are treated very like a splice (only without a '$') * Code compiled in state Splice (and only such code) will be *run at compile time*, with the result replacing the splice * The original paper used level -1 instead of 0, etc. * The original paper did not allow a splice within a splice, but there is no reason not to. This is the $ transition in the top right. Note [Template Haskell levels] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Imported things are impLevel (= 0) * However things at level 0 are not *necessarily* imported. eg $( \b -> ... ) here b is bound at level 0 * In GHCi, variables bound by a previous command are treated as impLevel, because we have bytecode for them. * Variables are bound at the "current level" * The current level starts off at outerLevel (= 1) * The level is decremented by splicing $(..) incremented by brackets [| |] incremented by name-quoting 'f When a variable is used, we compare bind: binding level, and use: current level at usage site Generally bind > use Always error (bound later than used) [| \x -> $(f x) |] bind = use Always OK (bound same stage as used) [| \x -> $(f [| x |]) |] bind < use Inside brackets, it depends Inside splice, OK Inside neither, OK For (bind < use) inside brackets, there are three cases: - Imported things OK f = [| map |] - Top-level things OK g = [| f |] - Non-top-level Only if there is a liftable instance h = \(x:Int) -> [| x |] To track top-level-ness we use the ThBindEnv in TcLclEnv For example: f = ... g1 = $(map ...) is OK g2 = $(f ...) is not OK; because we havn't compiled f yet ************************************************************************ * * \subsection{Quoting an expression} * * ************************************************************************ -} -- See Note [How brackets and nested splices are handled] -- tcTypedBracket :: HsBracket Name -> TcRhoType -> TcM (HsExpr TcId) tcTypedBracket brack@(TExpBr expr) res_ty = addErrCtxt (quotationCtxtDoc brack) $ do { cur_stage <- getStage ; ps_ref <- newMutVar [] ; lie_var <- getConstraintVar -- Any constraints arising from nested splices -- should get thrown into the constraint set -- from outside the bracket -- Typecheck expr to make sure it is valid, -- Throw away the typechecked expression but return its type. -- We'll typecheck it again when we splice it in somewhere ; (_tc_expr, expr_ty) <- setStage (Brack cur_stage (TcPending ps_ref lie_var)) $ tcInferRhoNC expr -- NC for no context; tcBracket does that ; meta_ty <- tcTExpTy expr_ty ; co <- unifyType meta_ty res_ty ; ps' <- readMutVar ps_ref ; texpco <- tcLookupId unsafeTExpCoerceName ; return (mkHsWrapCo co (unLoc (mkHsApp (nlHsTyApp texpco [expr_ty]) (noLoc (HsTcBracketOut brack ps'))))) } tcTypedBracket other_brack _ = pprPanic "tcTypedBracket" (ppr other_brack) -- tcUntypedBracket :: HsBracket Name -> [PendingRnSplice] -> TcRhoType -> TcM (HsExpr TcId) tcUntypedBracket brack ps res_ty = do { traceTc "tc_bracket untyped" (ppr brack $$ ppr ps) ; ps' <- mapM tcPendingSplice ps ; meta_ty <- tcBrackTy brack ; co <- unifyType meta_ty res_ty ; traceTc "tc_bracket done untyped" (ppr meta_ty) ; return (mkHsWrapCo co (HsTcBracketOut brack ps')) } --------------- tcBrackTy :: HsBracket Name -> TcM TcType tcBrackTy (VarBr _ _) = tcMetaTy nameTyConName -- Result type is Var (not Q-monadic) tcBrackTy (ExpBr _) = tcMetaTy expQTyConName -- Result type is ExpQ (= Q Exp) tcBrackTy (TypBr _) = tcMetaTy typeQTyConName -- Result type is Type (= Q Typ) tcBrackTy (DecBrG _) = tcMetaTy decsQTyConName -- Result type is Q [Dec] tcBrackTy (PatBr _) = tcMetaTy patQTyConName -- Result type is PatQ (= Q Pat) tcBrackTy (DecBrL _) = panic "tcBrackTy: Unexpected DecBrL" tcBrackTy (TExpBr _) = panic "tcUntypedBracket: Unexpected TExpBr" --------------- tcPendingSplice :: PendingRnSplice -> TcM PendingTcSplice tcPendingSplice (PendingRnSplice flavour splice_name expr) = do { res_ty <- tcMetaTy meta_ty_name ; expr' <- tcMonoExpr expr res_ty ; return (PendingTcSplice splice_name expr') } where meta_ty_name = case flavour of UntypedExpSplice -> expQTyConName UntypedPatSplice -> patQTyConName UntypedTypeSplice -> typeQTyConName UntypedDeclSplice -> decsQTyConName --------------- -- Takes a type tau and returns the type Q (TExp tau) tcTExpTy :: TcType -> TcM TcType tcTExpTy tau = do { q <- tcLookupTyCon qTyConName ; texp <- tcLookupTyCon tExpTyConName ; return (mkTyConApp q [mkTyConApp texp [tau]]) } {- ************************************************************************ * * \subsection{Splicing an expression} * * ************************************************************************ -} tcSpliceExpr splice@(HsTypedSplice name expr) res_ty = addErrCtxt (spliceCtxtDoc splice) $ setSrcSpan (getLoc expr) $ do { stage <- getStage ; case stage of Splice {} -> tcTopSplice expr res_ty Comp -> tcTopSplice expr res_ty Brack pop_stage pend -> tcNestedSplice pop_stage pend name expr res_ty } tcSpliceExpr splice _ = pprPanic "tcSpliceExpr" (ppr splice) tcNestedSplice :: ThStage -> PendingStuff -> Name -> LHsExpr Name -> TcRhoType -> TcM (HsExpr Id) -- See Note [How brackets and nested splices are handled] -- A splice inside brackets tcNestedSplice pop_stage (TcPending ps_var lie_var) splice_name expr res_ty = do { meta_exp_ty <- tcTExpTy res_ty ; expr' <- setStage pop_stage $ setConstraintVar lie_var $ tcMonoExpr expr meta_exp_ty ; untypeq <- tcLookupId unTypeQName ; let expr'' = mkHsApp (nlHsTyApp untypeq [res_ty]) expr' ; ps <- readMutVar ps_var ; writeMutVar ps_var (PendingTcSplice splice_name expr'' : ps) -- The returned expression is ignored; it's in the pending splices ; return (panic "tcSpliceExpr") } tcNestedSplice _ _ splice_name _ _ = pprPanic "tcNestedSplice: rename stage found" (ppr splice_name) tcTopSplice :: LHsExpr Name -> TcRhoType -> TcM (HsExpr Id) tcTopSplice expr res_ty = do { -- Typecheck the expression, -- making sure it has type Q (T res_ty) meta_exp_ty <- tcTExpTy res_ty ; zonked_q_expr <- tcTopSpliceExpr True $ tcMonoExpr expr meta_exp_ty -- Run the expression ; expr2 <- runMetaE zonked_q_expr ; traceSplice (SpliceInfo { spliceDescription = "expression" , spliceIsDecl = False , spliceSource = Just expr , spliceGenerated = ppr expr2 }) -- Rename and typecheck the spliced-in expression, -- making sure it has type res_ty -- These steps should never fail; this is a *typed* splice ; addErrCtxt (spliceResultDoc expr) $ do { (exp3, _fvs) <- rnLExpr expr2 ; exp4 <- tcMonoExpr exp3 res_ty ; return (unLoc exp4) } } {- ************************************************************************ * * \subsection{Error messages} * * ************************************************************************ -} quotationCtxtDoc :: HsBracket Name -> SDoc quotationCtxtDoc br_body = hang (ptext (sLit "In the Template Haskell quotation")) 2 (ppr br_body) spliceCtxtDoc :: HsSplice Name -> SDoc spliceCtxtDoc splice = hang (ptext (sLit "In the Template Haskell splice")) 2 (pprSplice splice) spliceResultDoc :: LHsExpr Name -> SDoc spliceResultDoc expr = sep [ ptext (sLit "In the result of the splice:") , nest 2 (char '$' <> pprParendExpr expr) , ptext (sLit "To see what the splice expanded to, use -ddump-splices")] ------------------- tcTopSpliceExpr :: Bool -> TcM (LHsExpr Id) -> TcM (LHsExpr Id) -- Note [How top-level splices are handled] -- Type check an expression that is the body of a top-level splice -- (the caller will compile and run it) -- Note that set the level to Splice, regardless of the original level, -- before typechecking the expression. For example: -- f x = $( ...$(g 3) ... ) -- The recursive call to tcMonoExpr will simply expand the -- inner escape before dealing with the outer one tcTopSpliceExpr isTypedSplice tc_action = checkNoErrs $ -- checkNoErrs: must not try to run the thing -- if the type checker fails! unsetGOptM Opt_DeferTypeErrors $ -- Don't defer type errors. Not only are we -- going to run this code, but we do an unsafe -- coerce, so we get a seg-fault if, say we -- splice a type into a place where an expression -- is expected (Trac #7276) setStage (Splice isTypedSplice) $ do { -- Typecheck the expression (expr', lie) <- captureConstraints tc_action -- Solve the constraints ; const_binds <- simplifyTop lie -- Zonk it and tie the knot of dictionary bindings ; zonkTopLExpr (mkHsDictLet (EvBinds const_binds) expr') } {- ************************************************************************ * * Annotations * * ************************************************************************ -} runAnnotation target expr = do -- Find the classes we want instances for in order to call toAnnotationWrapper loc <- getSrcSpanM data_class <- tcLookupClass dataClassName to_annotation_wrapper_id <- tcLookupId toAnnotationWrapperName -- Check the instances we require live in another module (we want to execute it..) -- and check identifiers live in other modules using TH stage checks. tcSimplifyStagedExpr -- also resolves the LIE constraints to detect e.g. instance ambiguity zonked_wrapped_expr' <- tcTopSpliceExpr False $ do { (expr', expr_ty) <- tcInferRhoNC expr -- We manually wrap the typechecked expression in a call to toAnnotationWrapper -- By instantiating the call >here< it gets registered in the -- LIE consulted by tcTopSpliceExpr -- and hence ensures the appropriate dictionary is bound by const_binds ; wrapper <- instCall AnnOrigin [expr_ty] [mkClassPred data_class [expr_ty]] ; let specialised_to_annotation_wrapper_expr = L loc (HsWrap wrapper (HsVar to_annotation_wrapper_id)) ; return (L loc (HsApp specialised_to_annotation_wrapper_expr expr')) } -- Run the appropriately wrapped expression to get the value of -- the annotation and its dictionaries. The return value is of -- type AnnotationWrapper by construction, so this conversion is -- safe serialized <- runMetaAW zonked_wrapped_expr' return Annotation { ann_target = target, ann_value = serialized } convertAnnotationWrapper :: AnnotationWrapper -> Either MsgDoc Serialized convertAnnotationWrapper annotation_wrapper = Right $ case annotation_wrapper of AnnotationWrapper value | let serialized = toSerialized serializeWithData value -> -- Got the value and dictionaries: build the serialized value and -- call it a day. We ensure that we seq the entire serialized value -- in order that any errors in the user-written code for the -- annotation are exposed at this point. This is also why we are -- doing all this stuff inside the context of runMeta: it has the -- facilities to deal with user error in a meta-level expression seqSerialized serialized `seq` serialized {- ************************************************************************ * * \subsection{Running an expression} * * ************************************************************************ -} runQuasi :: TH.Q a -> TcM a runQuasi act = TH.runQ act runQResult :: (a -> String) -> (SrcSpan -> a -> b) -> SrcSpan -> TH.Q a -> TcM b runQResult show_th f expr_span hval = do { th_result <- TH.runQ hval ; traceTc "Got TH result:" (text (show_th th_result)) ; return (f expr_span th_result) } ----------------- runMeta :: (MetaHook TcM -> LHsExpr Id -> TcM hs_syn) -> LHsExpr Id -> TcM hs_syn runMeta unwrap e = do { h <- getHooked runMetaHook defaultRunMeta ; unwrap h e } defaultRunMeta :: MetaHook TcM defaultRunMeta (MetaE r) = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsExpr) defaultRunMeta (MetaP r) = fmap r . runMeta' True ppr (runQResult TH.pprint convertToPat) defaultRunMeta (MetaT r) = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsType) defaultRunMeta (MetaD r) = fmap r . runMeta' True ppr (runQResult TH.pprint convertToHsDecls) defaultRunMeta (MetaAW r) = fmap r . runMeta' False (const empty) (const (return . convertAnnotationWrapper)) -- We turn off showing the code in meta-level exceptions because doing so exposes -- the toAnnotationWrapper function that we slap around the users code ---------------- runMetaAW :: LHsExpr Id -- Of type AnnotationWrapper -> TcM Serialized runMetaAW = runMeta metaRequestAW runMetaE :: LHsExpr Id -- Of type (Q Exp) -> TcM (LHsExpr RdrName) runMetaE = runMeta metaRequestE runMetaP :: LHsExpr Id -- Of type (Q Pat) -> TcM (LPat RdrName) runMetaP = runMeta metaRequestP runMetaT :: LHsExpr Id -- Of type (Q Type) -> TcM (LHsType RdrName) runMetaT = runMeta metaRequestT runMetaD :: LHsExpr Id -- Of type Q [Dec] -> TcM [LHsDecl RdrName] runMetaD = runMeta metaRequestD --------------- runMeta' :: Bool -- Whether code should be printed in the exception message -> (hs_syn -> SDoc) -- how to print the code -> (SrcSpan -> x -> TcM (Either MsgDoc hs_syn)) -- How to run x -> LHsExpr Id -- Of type x; typically x = Q TH.Exp, or something like that -> TcM hs_syn -- Of type t runMeta' show_code ppr_hs run_and_convert expr = do { traceTc "About to run" (ppr expr) ; recordThSpliceUse -- seems to be the best place to do this, -- we catch all kinds of splices and annotations. -- Check that we've had no errors of any sort so far. -- For example, if we found an error in an earlier defn f, but -- recovered giving it type f :: forall a.a, it'd be very dodgy -- to carry ont. Mind you, the staging restrictions mean we won't -- actually run f, but it still seems wrong. And, more concretely, -- see Trac #5358 for an example that fell over when trying to -- reify a function with a "?" kind in it. (These don't occur -- in type-correct programs. ; failIfErrsM -- Desugar ; ds_expr <- initDsTc (dsLExpr expr) -- Compile and link it; might fail if linking fails ; hsc_env <- getTopEnv ; src_span <- getSrcSpanM ; traceTc "About to run (desugared)" (ppr ds_expr) ; either_hval <- tryM $ liftIO $ HscMain.hscCompileCoreExpr hsc_env src_span ds_expr ; case either_hval of { Left exn -> fail_with_exn "compile and link" exn ; Right hval -> do { -- Coerce it to Q t, and run it -- Running might fail if it throws an exception of any kind (hence tryAllM) -- including, say, a pattern-match exception in the code we are running -- -- We also do the TH -> HS syntax conversion inside the same -- exception-cacthing thing so that if there are any lurking -- exceptions in the data structure returned by hval, we'll -- encounter them inside the try -- -- See Note [Exceptions in TH] let expr_span = getLoc expr ; either_tval <- tryAllM $ setSrcSpan expr_span $ -- Set the span so that qLocation can -- see where this splice is do { mb_result <- run_and_convert expr_span (unsafeCoerce# hval) ; case mb_result of Left err -> failWithTc err Right result -> do { traceTc "Got HsSyn result:" (ppr_hs result) ; return $! result } } ; case either_tval of Right v -> return v Left se -> case fromException se of Just IOEnvFailure -> failM -- Error already in Tc monad _ -> fail_with_exn "run" se -- Exception }}} where -- see Note [Concealed TH exceptions] fail_with_exn phase exn = do exn_msg <- liftIO $ Panic.safeShowException exn let msg = vcat [text "Exception when trying to" <+> text phase <+> text "compile-time code:", nest 2 (text exn_msg), if show_code then text "Code:" <+> ppr expr else empty] failWithTc msg {- Note [Exceptions in TH] ~~~~~~~~~~~~~~~~~~~~~~~ Supppose we have something like this $( f 4 ) where f :: Int -> Q [Dec] f n | n>3 = fail "Too many declarations" | otherwise = ... The 'fail' is a user-generated failure, and should be displayed as a perfectly ordinary compiler error message, not a panic or anything like that. Here's how it's processed: * 'fail' is the monad fail. The monad instance for Q in TH.Syntax effectively transforms (fail s) to qReport True s >> fail where 'qReport' comes from the Quasi class and fail from its monad superclass. * The TcM monad is an instance of Quasi (see TcSplice), and it implements (qReport True s) by using addErr to add an error message to the bag of errors. The 'fail' in TcM raises an IOEnvFailure exception * 'qReport' forces the message to ensure any exception hidden in unevaluated thunk doesn't get into the bag of errors. Otherwise the following splice will triger panic (Trac #8987): $(fail undefined) See also Note [Concealed TH exceptions] * So, when running a splice, we catch all exceptions; then for - an IOEnvFailure exception, we assume the error is already in the error-bag (above) - other errors, we add an error to the bag and then fail Note [Concealed TH exceptions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When displaying the error message contained in an exception originated from TH code, we need to make sure that the error message itself does not contain an exception. For example, when executing the following splice: $( error ("foo " ++ error "bar") ) the message for the outer exception is a thunk which will throw the inner exception when evaluated. For this reason, we display the message of a TH exception using the 'safeShowException' function, which recursively catches any exception thrown when showing an error message. To call runQ in the Tc monad, we need to make TcM an instance of Quasi: -} instance TH.Quasi (IOEnv (Env TcGblEnv TcLclEnv)) where qNewName s = do { u <- newUnique ; let i = getKey u ; return (TH.mkNameU s i) } -- 'msg' is forced to ensure exceptions don't escape, -- see Note [Exceptions in TH] qReport True msg = seqList msg $ addErr (text msg) qReport False msg = seqList msg $ addWarn (text msg) qLocation = do { m <- getModule ; l <- getSrcSpanM ; r <- case l of UnhelpfulSpan _ -> pprPanic "qLocation: Unhelpful location" (ppr l) RealSrcSpan s -> return s ; return (TH.Loc { TH.loc_filename = unpackFS (srcSpanFile r) , TH.loc_module = moduleNameString (moduleName m) , TH.loc_package = packageKeyString (modulePackageKey m) , TH.loc_start = (srcSpanStartLine r, srcSpanStartCol r) , TH.loc_end = (srcSpanEndLine r, srcSpanEndCol r) }) } qLookupName = lookupName qReify = reify qReifyInstances = reifyInstances qReifyRoles = reifyRoles qReifyAnnotations = reifyAnnotations qReifyModule = reifyModule -- For qRecover, discard error messages if -- the recovery action is chosen. Otherwise -- we'll only fail higher up. c.f. tryTcLIE_ qRecover recover main = do { (msgs, mb_res) <- tryTcErrs main ; case mb_res of Just val -> do { addMessages msgs -- There might be warnings ; return val } Nothing -> recover -- Discard all msgs } qRunIO io = liftIO io qAddDependentFile fp = do ref <- fmap tcg_dependent_files getGblEnv dep_files <- readTcRef ref writeTcRef ref (fp:dep_files) qAddTopDecls thds = do l <- getSrcSpanM let either_hval = convertToHsDecls l thds ds <- case either_hval of Left exn -> pprPanic "qAddTopDecls: can't convert top-level declarations" exn Right ds -> return ds mapM_ (checkTopDecl . unLoc) ds th_topdecls_var <- fmap tcg_th_topdecls getGblEnv updTcRef th_topdecls_var (\topds -> ds ++ topds) where checkTopDecl :: HsDecl RdrName -> TcM () checkTopDecl (ValD binds) = mapM_ bindName (collectHsBindBinders binds) checkTopDecl (SigD _) = return () checkTopDecl (ForD (ForeignImport (L _ name) _ _ _)) = bindName name checkTopDecl _ = addErr $ text "Only function, value, and foreign import declarations may be added with addTopDecl" bindName :: RdrName -> TcM () bindName (Exact n) = do { th_topnames_var <- fmap tcg_th_topnames getGblEnv ; updTcRef th_topnames_var (\ns -> extendNameSet ns n) } bindName name = addErr $ hang (ptext (sLit "The binder") <+> quotes (ppr name) <+> ptext (sLit "is not a NameU.")) 2 (text "Probable cause: you used mkName instead of newName to generate a binding.") qAddModFinalizer fin = do th_modfinalizers_var <- fmap tcg_th_modfinalizers getGblEnv updTcRef th_modfinalizers_var (\fins -> fin:fins) qGetQ = do th_state_var <- fmap tcg_th_state getGblEnv th_state <- readTcRef th_state_var let x = Map.lookup (typeOf x) th_state >>= fromDynamic return x qPutQ x = do th_state_var <- fmap tcg_th_state getGblEnv updTcRef th_state_var (\m -> Map.insert (typeOf x) (toDyn x) m) {- ************************************************************************ * * Instance Testing * * ************************************************************************ -} reifyInstances :: TH.Name -> [TH.Type] -> TcM [TH.Dec] reifyInstances th_nm th_tys = addErrCtxt (ptext (sLit "In the argument of reifyInstances:") <+> ppr_th th_nm <+> sep (map ppr_th th_tys)) $ do { loc <- getSrcSpanM ; rdr_ty <- cvt loc (mkThAppTs (TH.ConT th_nm) th_tys) -- #9262 says to bring vars into scope, like in HsForAllTy case -- of rnHsTyKi ; let (kvs, tvs) = extractHsTyRdrTyVars rdr_ty tv_bndrs = userHsTyVarBndrs loc tvs hs_tvbs = mkHsQTvs tv_bndrs -- Rename to HsType Name ; ((rn_tvbs, rn_ty), _fvs) <- bindHsTyVars doc Nothing kvs hs_tvbs $ \ rn_tvbs -> do { (rn_ty, fvs) <- rnLHsType doc rdr_ty ; return ((rn_tvbs, rn_ty), fvs) } ; (ty, _kind) <- tcHsTyVarBndrs rn_tvbs $ \ _tvs -> tcLHsType rn_ty ; ty <- zonkTcTypeToType emptyZonkEnv ty -- Substitute out the meta type variables -- In particular, the type might have kind -- variables inside it (Trac #7477) ; traceTc "reifyInstances" (ppr ty $$ ppr (typeKind ty)) ; case splitTyConApp_maybe ty of -- This expands any type synonyms Just (tc, tys) -- See Trac #7910 | Just cls <- tyConClass_maybe tc -> do { inst_envs <- tcGetInstEnvs ; let (matches, unifies, _) = lookupInstEnv inst_envs cls tys ; traceTc "reifyInstances1" (ppr matches) ; reifyClassInstances cls (map fst matches ++ unifies) } | isOpenFamilyTyCon tc -> do { inst_envs <- tcGetFamInstEnvs ; let matches = lookupFamInstEnv inst_envs tc tys ; traceTc "reifyInstances2" (ppr matches) ; reifyFamilyInstances tc (map fim_instance matches) } _ -> bale_out (hang (ptext (sLit "reifyInstances:") <+> quotes (ppr ty)) 2 (ptext (sLit "is not a class constraint or type family application"))) } where doc = ClassInstanceCtx bale_out msg = failWithTc msg cvt :: SrcSpan -> TH.Type -> TcM (LHsType RdrName) cvt loc th_ty = case convertToHsType loc th_ty of Left msg -> failWithTc msg Right ty -> return ty {- ************************************************************************ * * Reification * * ************************************************************************ -} lookupName :: Bool -- True <=> type namespace -- False <=> value namespace -> String -> TcM (Maybe TH.Name) lookupName is_type_name s = do { lcl_env <- getLocalRdrEnv ; case lookupLocalRdrEnv lcl_env rdr_name of Just n -> return (Just (reifyName n)) Nothing -> do { mb_nm <- lookupGlobalOccRn_maybe rdr_name ; return (fmap reifyName mb_nm) } } where th_name = TH.mkName s -- Parses M.x into a base of 'x' and a module of 'M' occ_fs :: FastString occ_fs = mkFastString (TH.nameBase th_name) occ :: OccName occ | is_type_name = if isLexCon occ_fs then mkTcOccFS occ_fs else mkTyVarOccFS occ_fs | otherwise = if isLexCon occ_fs then mkDataOccFS occ_fs else mkVarOccFS occ_fs rdr_name = case TH.nameModule th_name of Nothing -> mkRdrUnqual occ Just mod -> mkRdrQual (mkModuleName mod) occ getThing :: TH.Name -> TcM TcTyThing getThing th_name = do { name <- lookupThName th_name ; traceIf (text "reify" <+> text (show th_name) <+> brackets (ppr_ns th_name) <+> ppr name) ; tcLookupTh name } -- ToDo: this tcLookup could fail, which would give a -- rather unhelpful error message where ppr_ns (TH.Name _ (TH.NameG TH.DataName _pkg _mod)) = text "data" ppr_ns (TH.Name _ (TH.NameG TH.TcClsName _pkg _mod)) = text "tc" ppr_ns (TH.Name _ (TH.NameG TH.VarName _pkg _mod)) = text "var" ppr_ns _ = panic "reify/ppr_ns" reify :: TH.Name -> TcM TH.Info reify th_name = do { traceTc "reify 1" (text (TH.showName th_name)) ; thing <- getThing th_name ; traceTc "reify 2" (ppr thing) ; reifyThing thing } lookupThName :: TH.Name -> TcM Name lookupThName th_name = do mb_name <- lookupThName_maybe th_name case mb_name of Nothing -> failWithTc (notInScope th_name) Just name -> return name lookupThName_maybe :: TH.Name -> TcM (Maybe Name) lookupThName_maybe th_name = do { names <- mapMaybeM lookup (thRdrNameGuesses th_name) -- Pick the first that works -- E.g. reify (mkName "A") will pick the class A in preference to the data constructor A ; return (listToMaybe names) } where lookup rdr_name = do { -- Repeat much of lookupOccRn, becase we want -- to report errors in a TH-relevant way ; rdr_env <- getLocalRdrEnv ; case lookupLocalRdrEnv rdr_env rdr_name of Just name -> return (Just name) Nothing -> lookupGlobalOccRn_maybe rdr_name } tcLookupTh :: Name -> TcM TcTyThing -- This is a specialised version of TcEnv.tcLookup; specialised mainly in that -- it gives a reify-related error message on failure, whereas in the normal -- tcLookup, failure is a bug. tcLookupTh name = do { (gbl_env, lcl_env) <- getEnvs ; case lookupNameEnv (tcl_env lcl_env) name of { Just thing -> return thing; Nothing -> case lookupNameEnv (tcg_type_env gbl_env) name of { Just thing -> return (AGlobal thing); Nothing -> if nameIsLocalOrFrom (tcg_mod gbl_env) name then -- It's defined in this module failWithTc (notInEnv name) else do { mb_thing <- tcLookupImported_maybe name ; case mb_thing of Succeeded thing -> return (AGlobal thing) Failed msg -> failWithTc msg }}}} notInScope :: TH.Name -> SDoc notInScope th_name = quotes (text (TH.pprint th_name)) <+> ptext (sLit "is not in scope at a reify") -- Ugh! Rather an indirect way to display the name notInEnv :: Name -> SDoc notInEnv name = quotes (ppr name) <+> ptext (sLit "is not in the type environment at a reify") ------------------------------ reifyRoles :: TH.Name -> TcM [TH.Role] reifyRoles th_name = do { thing <- getThing th_name ; case thing of AGlobal (ATyCon tc) -> return (map reify_role (tyConRoles tc)) _ -> failWithTc (ptext (sLit "No roles associated with") <+> (ppr thing)) } where reify_role Nominal = TH.NominalR reify_role Representational = TH.RepresentationalR reify_role Phantom = TH.PhantomR ------------------------------ reifyThing :: TcTyThing -> TcM TH.Info -- The only reason this is monadic is for error reporting, -- which in turn is mainly for the case when TH can't express -- some random GHC extension reifyThing (AGlobal (AnId id)) = do { ty <- reifyType (idType id) ; fix <- reifyFixity (idName id) ; let v = reifyName id ; case idDetails id of ClassOpId cls -> return (TH.ClassOpI v ty (reifyName cls) fix) _ -> return (TH.VarI v ty Nothing fix) } reifyThing (AGlobal (ATyCon tc)) = reifyTyCon tc reifyThing (AGlobal (AConLike (RealDataCon dc))) = do { let name = dataConName dc ; ty <- reifyType (idType (dataConWrapId dc)) ; fix <- reifyFixity name ; return (TH.DataConI (reifyName name) ty (reifyName (dataConOrigTyCon dc)) fix) } reifyThing (AGlobal (AConLike (PatSynCon ps))) = noTH (sLit "pattern synonyms") (ppr $ patSynName ps) reifyThing (ATcId {tct_id = id}) = do { ty1 <- zonkTcType (idType id) -- Make use of all the info we have, even -- though it may be incomplete ; ty2 <- reifyType ty1 ; fix <- reifyFixity (idName id) ; return (TH.VarI (reifyName id) ty2 Nothing fix) } reifyThing (ATyVar tv tv1) = do { ty1 <- zonkTcTyVar tv1 ; ty2 <- reifyType ty1 ; return (TH.TyVarI (reifyName tv) ty2) } reifyThing thing = pprPanic "reifyThing" (pprTcTyThingCategory thing) ------------------------------------------- reifyAxBranch :: CoAxBranch -> TcM TH.TySynEqn reifyAxBranch (CoAxBranch { cab_lhs = args, cab_rhs = rhs }) -- remove kind patterns (#8884) = do { args' <- mapM reifyType (filter (not . isKind) args) ; rhs' <- reifyType rhs ; return (TH.TySynEqn args' rhs') } reifyTyCon :: TyCon -> TcM TH.Info reifyTyCon tc | Just cls <- tyConClass_maybe tc = reifyClass cls | isFunTyCon tc = return (TH.PrimTyConI (reifyName tc) 2 False) | isPrimTyCon tc = return (TH.PrimTyConI (reifyName tc) (tyConArity tc) (isUnLiftedTyCon tc)) | isFamilyTyCon tc = do { let tvs = tyConTyVars tc kind = tyConKind tc -- we need the *result kind* (see #8884) (kvs, mono_kind) = splitForAllTys kind -- tyConArity includes *kind* params (_, res_kind) = splitKindFunTysN (tyConArity tc - length kvs) mono_kind ; kind' <- fmap Just (reifyKind res_kind) ; tvs' <- reifyTyVars tvs ; flav' <- reifyFamFlavour tc ; case flav' of { Left flav -> -- open type/data family do { fam_envs <- tcGetFamInstEnvs ; instances <- reifyFamilyInstances tc (familyInstances fam_envs tc) ; return (TH.FamilyI (TH.FamilyD flav (reifyName tc) tvs' kind') instances) } ; Right eqns -> -- closed type family return (TH.FamilyI (TH.ClosedTypeFamilyD (reifyName tc) tvs' kind' eqns) []) } } | Just (tvs, rhs) <- synTyConDefn_maybe tc -- Vanilla type synonym = do { rhs' <- reifyType rhs ; tvs' <- reifyTyVars tvs ; return (TH.TyConI (TH.TySynD (reifyName tc) tvs' rhs')) } | otherwise = do { cxt <- reifyCxt (tyConStupidTheta tc) ; let tvs = tyConTyVars tc ; cons <- mapM (reifyDataCon (mkTyVarTys tvs)) (tyConDataCons tc) ; r_tvs <- reifyTyVars tvs ; let name = reifyName tc deriv = [] -- Don't know about deriving decl | isNewTyCon tc = TH.NewtypeD cxt name r_tvs (head cons) deriv | otherwise = TH.DataD cxt name r_tvs cons deriv ; return (TH.TyConI decl) } reifyDataCon :: [Type] -> DataCon -> TcM TH.Con -- For GADTs etc, see Note [Reifying data constructors] reifyDataCon tys dc = do { let (tvs, theta, arg_tys, _) = dataConSig dc subst = mkTopTvSubst (tvs `zip` tys) -- Dicard ex_tvs (subst', ex_tvs') = mapAccumL substTyVarBndr subst (dropList tys tvs) theta' = substTheta subst' theta arg_tys' = substTys subst' arg_tys stricts = map reifyStrict (dataConSrcBangs dc) fields = dataConFieldLabels dc name = reifyName dc ; r_arg_tys <- reifyTypes arg_tys' ; let main_con | not (null fields) = TH.RecC name (zip3 (map reifyName fields) stricts r_arg_tys) | dataConIsInfix dc = ASSERT( length arg_tys == 2 ) TH.InfixC (s1,r_a1) name (s2,r_a2) | otherwise = TH.NormalC name (stricts `zip` r_arg_tys) [r_a1, r_a2] = r_arg_tys [s1, s2] = stricts ; ASSERT( length arg_tys == length stricts ) if null ex_tvs' && null theta then return main_con else do { cxt <- reifyCxt theta' ; ex_tvs'' <- reifyTyVars ex_tvs' ; return (TH.ForallC ex_tvs'' cxt main_con) } } ------------------------------ reifyClass :: Class -> TcM TH.Info reifyClass cls = do { cxt <- reifyCxt theta ; inst_envs <- tcGetInstEnvs ; insts <- reifyClassInstances cls (InstEnv.classInstances inst_envs cls) ; ops <- concatMapM reify_op op_stuff ; tvs' <- reifyTyVars tvs ; let dec = TH.ClassD cxt (reifyName cls) tvs' fds' ops ; return (TH.ClassI dec insts ) } where (tvs, fds, theta, _, _, op_stuff) = classExtraBigSig cls fds' = map reifyFunDep fds reify_op (op, def_meth) = do { ty <- reifyType (idType op) ; let nm' = reifyName op ; case def_meth of GenDefMeth gdm_nm -> do { gdm_id <- tcLookupId gdm_nm ; gdm_ty <- reifyType (idType gdm_id) ; return [TH.SigD nm' ty, TH.DefaultSigD nm' gdm_ty] } _ -> return [TH.SigD nm' ty] } ------------------------------ -- | Annotate (with TH.SigT) a type if the first parameter is True -- and if the type contains a free variable. -- This is used to annotate type patterns for poly-kinded tyvars in -- reifying class and type instances. See #8953 and th/T8953. annotThType :: Bool -- True <=> annotate -> TypeRep.Type -> TH.Type -> TcM TH.Type -- tiny optimization: if the type is annotated, don't annotate again. annotThType _ _ th_ty@(TH.SigT {}) = return th_ty annotThType True ty th_ty | not $ isEmptyVarSet $ tyVarsOfType ty = do { let ki = typeKind ty ; th_ki <- reifyKind ki ; return (TH.SigT th_ty th_ki) } annotThType _ _ th_ty = return th_ty -- | For every *type* variable (not *kind* variable) in the input, -- report whether or not the tv is poly-kinded. This is used to eventually -- feed into 'annotThType'. mkIsPolyTvs :: [TyVar] -> [Bool] mkIsPolyTvs tvs = [ is_poly_tv tv | tv <- tvs , not (isKindVar tv) ] where is_poly_tv tv = not $ isEmptyVarSet $ tyVarsOfType $ tyVarKind tv ------------------------------ reifyClassInstances :: Class -> [ClsInst] -> TcM [TH.Dec] reifyClassInstances cls insts = mapM (reifyClassInstance (mkIsPolyTvs tvs)) insts where tvs = classTyVars cls reifyClassInstance :: [Bool] -- True <=> the corresponding tv is poly-kinded -- this list contains flags only for *type* -- variables, not *kind* variables -> ClsInst -> TcM TH.Dec reifyClassInstance is_poly_tvs i = do { cxt <- reifyCxt theta ; let types_only = filterOut isKind types ; thtypes <- reifyTypes types_only ; annot_thtypes <- zipWith3M annotThType is_poly_tvs types_only thtypes ; let head_ty = mkThAppTs (TH.ConT (reifyName cls)) annot_thtypes ; return $ (TH.InstanceD cxt head_ty []) } where (_tvs, theta, cls, types) = tcSplitDFunTy (idType dfun) dfun = instanceDFunId i ------------------------------ reifyFamilyInstances :: TyCon -> [FamInst] -> TcM [TH.Dec] reifyFamilyInstances fam_tc fam_insts = mapM (reifyFamilyInstance (mkIsPolyTvs fam_tvs)) fam_insts where fam_tvs = tyConTyVars fam_tc reifyFamilyInstance :: [Bool] -- True <=> the corresponding tv is poly-kinded -- this list contains flags only for *type* -- variables, not *kind* variables -> FamInst -> TcM TH.Dec reifyFamilyInstance is_poly_tvs (FamInst { fi_flavor = flavor , fi_fam = fam , fi_tys = lhs , fi_rhs = rhs }) = case flavor of SynFamilyInst -> -- remove kind patterns (#8884) do { let lhs_types_only = filterOut isKind lhs ; th_lhs <- reifyTypes lhs_types_only ; annot_th_lhs <- zipWith3M annotThType is_poly_tvs lhs_types_only th_lhs ; th_rhs <- reifyType rhs ; return (TH.TySynInstD (reifyName fam) (TH.TySynEqn annot_th_lhs th_rhs)) } DataFamilyInst rep_tc -> do { let tvs = tyConTyVars rep_tc fam' = reifyName fam -- eta-expand lhs types, because sometimes data/newtype -- instances are eta-reduced; See Trac #9692 -- See Note [Eta reduction for data family axioms] -- in TcInstDcls (_rep_tc, rep_tc_args) = splitTyConApp rhs etad_tyvars = dropList rep_tc_args tvs eta_expanded_lhs = lhs `chkAppend` mkTyVarTys etad_tyvars ; cons <- mapM (reifyDataCon (mkTyVarTys tvs)) (tyConDataCons rep_tc) ; let types_only = filterOut isKind eta_expanded_lhs ; th_tys <- reifyTypes types_only ; annot_th_tys <- zipWith3M annotThType is_poly_tvs types_only th_tys ; return (if isNewTyCon rep_tc then TH.NewtypeInstD [] fam' annot_th_tys (head cons) [] else TH.DataInstD [] fam' annot_th_tys cons []) } ------------------------------ reifyType :: TypeRep.Type -> TcM TH.Type -- Monadic only because of failure reifyType ty@(ForAllTy _ _) = reify_for_all ty reifyType (LitTy t) = do { r <- reifyTyLit t; return (TH.LitT r) } reifyType (TyVarTy tv) = return (TH.VarT (reifyName tv)) reifyType (TyConApp tc tys) = reify_tc_app tc tys -- Do not expand type synonyms here reifyType (AppTy t1 t2) = do { [r1,r2] <- reifyTypes [t1,t2] ; return (r1 `TH.AppT` r2) } reifyType ty@(FunTy t1 t2) | isPredTy t1 = reify_for_all ty -- Types like ((?x::Int) => Char -> Char) | otherwise = do { [r1,r2] <- reifyTypes [t1,t2] ; return (TH.ArrowT `TH.AppT` r1 `TH.AppT` r2) } reify_for_all :: TypeRep.Type -> TcM TH.Type reify_for_all ty = do { cxt' <- reifyCxt cxt; ; tau' <- reifyType tau ; tvs' <- reifyTyVars tvs ; return (TH.ForallT tvs' cxt' tau') } where (tvs, cxt, tau) = tcSplitSigmaTy ty reifyTyLit :: TypeRep.TyLit -> TcM TH.TyLit reifyTyLit (NumTyLit n) = return (TH.NumTyLit n) reifyTyLit (StrTyLit s) = return (TH.StrTyLit (unpackFS s)) reifyTypes :: [Type] -> TcM [TH.Type] reifyTypes = mapM reifyType reifyKind :: Kind -> TcM TH.Kind reifyKind ki = do { let (kis, ki') = splitKindFunTys ki ; ki'_rep <- reifyNonArrowKind ki' ; kis_rep <- mapM reifyKind kis ; return (foldr (TH.AppT . TH.AppT TH.ArrowT) ki'_rep kis_rep) } where reifyNonArrowKind k | isLiftedTypeKind k = return TH.StarT | isConstraintKind k = return TH.ConstraintT reifyNonArrowKind (TyVarTy v) = return (TH.VarT (reifyName v)) reifyNonArrowKind (ForAllTy _ k) = reifyKind k reifyNonArrowKind (TyConApp kc kis) = reify_kc_app kc kis reifyNonArrowKind (AppTy k1 k2) = do { k1' <- reifyKind k1 ; k2' <- reifyKind k2 ; return (TH.AppT k1' k2') } reifyNonArrowKind k = noTH (sLit "this kind") (ppr k) reify_kc_app :: TyCon -> [TypeRep.Kind] -> TcM TH.Kind reify_kc_app kc kis = fmap (mkThAppTs r_kc) (mapM reifyKind kis) where r_kc | Just tc <- isPromotedTyCon_maybe kc , isTupleTyCon tc = TH.TupleT (tyConArity kc) | kc `hasKey` listTyConKey = TH.ListT | otherwise = TH.ConT (reifyName kc) reifyCxt :: [PredType] -> TcM [TH.Pred] reifyCxt = mapM reifyPred reifyFunDep :: ([TyVar], [TyVar]) -> TH.FunDep reifyFunDep (xs, ys) = TH.FunDep (map reifyName xs) (map reifyName ys) reifyFamFlavour :: TyCon -> TcM (Either TH.FamFlavour [TH.TySynEqn]) reifyFamFlavour tc | isOpenTypeFamilyTyCon tc = return $ Left TH.TypeFam | isDataFamilyTyCon tc = return $ Left TH.DataFam -- this doesn't really handle abstract closed families, but let's not worry -- about that now | Just ax <- isClosedSynFamilyTyCon_maybe tc = do { eqns <- brListMapM reifyAxBranch $ coAxiomBranches ax ; return $ Right eqns } | otherwise = panic "TcSplice.reifyFamFlavour: not a type family" reifyTyVars :: [TyVar] -> TcM [TH.TyVarBndr] reifyTyVars tvs = mapM reify_tv $ filter isTypeVar tvs where -- even if the kind is *, we need to include a kind annotation, -- in case a poly-kind would be inferred without the annotation. -- See #8953 or test th/T8953 reify_tv tv = TH.KindedTV name <$> reifyKind kind where kind = tyVarKind tv name = reifyName tv {- Note [Kind annotations on TyConApps] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A poly-kinded tycon sometimes needs a kind annotation to be unambiguous. For example: type family F a :: k type instance F Int = (Proxy :: * -> *) type instance F Bool = (Proxy :: (* -> *) -> *) It's hard to figure out where these annotations should appear, so we do this: Suppose the tycon is applied to n arguments. We strip off the first n arguments of the tycon's kind. If there are any variables left in the result kind, we put on a kind annotation. But we must be slightly careful: it's possible that the tycon's kind will have fewer than n arguments, in the case that the concrete application instantiates a result kind variable with an arrow kind. So, if we run out of arguments, we conservatively put on a kind annotation anyway. This should be a rare case, indeed. Here is an example: data T1 :: k1 -> k2 -> * data T2 :: k1 -> k2 -> * type family G (a :: k) :: k type instance G T1 = T2 type instance F Char = (G T1 Bool :: (* -> *) -> *) -- F from above Here G's kind is (forall k. k -> k), and the desugared RHS of that last instance of F is (G (* -> (* -> *) -> *) (T1 * (* -> *)) Bool). According to the algoritm above, there are 3 arguments to G so we should peel off 3 arguments in G's kind. But G's kind has only two arguments. This is the rare special case, and we conservatively choose to put the annotation in. See #8953 and test th/T8953. -} reify_tc_app :: TyCon -> [TypeRep.Type] -> TcM TH.Type reify_tc_app tc tys = do { tys' <- reifyTypes (removeKinds tc_kind tys) ; maybe_sig_t (mkThAppTs r_tc tys') } where arity = tyConArity tc tc_kind = tyConKind tc r_tc | isTupleTyCon tc = if isPromotedDataCon tc then TH.PromotedTupleT arity else TH.TupleT arity | tc `hasKey` listTyConKey = TH.ListT | tc `hasKey` nilDataConKey = TH.PromotedNilT | tc `hasKey` consDataConKey = TH.PromotedConsT | tc `hasKey` eqTyConKey = TH.EqualityT | otherwise = TH.ConT (reifyName tc) -- See Note [Kind annotations on TyConApps] maybe_sig_t th_type | needs_kind_sig = do { let full_kind = typeKind (mkTyConApp tc tys) ; th_full_kind <- reifyKind full_kind ; return (TH.SigT th_type th_full_kind) } | otherwise = return th_type needs_kind_sig | Just result_ki <- peel_off_n_args tc_kind (length tys) = not $ isEmptyVarSet $ kiVarsOfKind result_ki | otherwise = True peel_off_n_args :: Kind -> Arity -> Maybe Kind peel_off_n_args k 0 = Just k peel_off_n_args k n | Just (_, res_k) <- splitForAllTy_maybe k = peel_off_n_args res_k (n-1) | Just (_, res_k) <- splitFunTy_maybe k = peel_off_n_args res_k (n-1) | otherwise = Nothing removeKinds :: Kind -> [TypeRep.Type] -> [TypeRep.Type] removeKinds (FunTy k1 k2) (h:t) | isSuperKind k1 = removeKinds k2 t | otherwise = h : removeKinds k2 t removeKinds (ForAllTy v k) (h:t) | isSuperKind (varType v) = removeKinds k t | otherwise = h : removeKinds k t removeKinds _ tys = tys reifyPred :: TypeRep.PredType -> TcM TH.Pred reifyPred ty -- We could reify the implicit paramter as a class but it seems -- nicer to support them properly... | isIPPred ty = noTH (sLit "implicit parameters") (ppr ty) | otherwise = reifyType ty ------------------------------ reifyName :: NamedThing n => n -> TH.Name reifyName thing | isExternalName name = mk_varg pkg_str mod_str occ_str | otherwise = TH.mkNameU occ_str (getKey (getUnique name)) -- Many of the things we reify have local bindings, and -- NameL's aren't supposed to appear in binding positions, so -- we use NameU. When/if we start to reify nested things, that -- have free variables, we may need to generate NameL's for them. where name = getName thing mod = ASSERT( isExternalName name ) nameModule name pkg_str = packageKeyString (modulePackageKey mod) mod_str = moduleNameString (moduleName mod) occ_str = occNameString occ occ = nameOccName name mk_varg | OccName.isDataOcc occ = TH.mkNameG_d | OccName.isVarOcc occ = TH.mkNameG_v | OccName.isTcOcc occ = TH.mkNameG_tc | otherwise = pprPanic "reifyName" (ppr name) ------------------------------ reifyFixity :: Name -> TcM TH.Fixity reifyFixity name = do { fix <- lookupFixityRn name ; return (conv_fix fix) } where conv_fix (BasicTypes.Fixity i d) = TH.Fixity i (conv_dir d) conv_dir BasicTypes.InfixR = TH.InfixR conv_dir BasicTypes.InfixL = TH.InfixL conv_dir BasicTypes.InfixN = TH.InfixN reifyStrict :: DataCon.HsSrcBang -> TH.Strict reifyStrict HsNoBang = TH.NotStrict reifyStrict (HsSrcBang _ _ False) = TH.NotStrict reifyStrict (HsSrcBang _ (Just True) True) = TH.Unpacked reifyStrict (HsSrcBang _ _ True) = TH.IsStrict reifyStrict HsStrict = TH.IsStrict reifyStrict (HsUnpack {}) = TH.Unpacked ------------------------------ lookupThAnnLookup :: TH.AnnLookup -> TcM CoreAnnTarget lookupThAnnLookup (TH.AnnLookupName th_nm) = fmap NamedTarget (lookupThName th_nm) lookupThAnnLookup (TH.AnnLookupModule (TH.Module pn mn)) = return $ ModuleTarget $ mkModule (stringToPackageKey $ TH.pkgString pn) (mkModuleName $ TH.modString mn) reifyAnnotations :: Data a => TH.AnnLookup -> TcM [a] reifyAnnotations th_name = do { name <- lookupThAnnLookup th_name ; topEnv <- getTopEnv ; epsHptAnns <- liftIO $ prepareAnnotations topEnv Nothing ; tcg <- getGblEnv ; let selectedEpsHptAnns = findAnns deserializeWithData epsHptAnns name ; let selectedTcgAnns = findAnns deserializeWithData (tcg_ann_env tcg) name ; return (selectedEpsHptAnns ++ selectedTcgAnns) } ------------------------------ modToTHMod :: Module -> TH.Module modToTHMod m = TH.Module (TH.PkgName $ packageKeyString $ modulePackageKey m) (TH.ModName $ moduleNameString $ moduleName m) reifyModule :: TH.Module -> TcM TH.ModuleInfo reifyModule (TH.Module (TH.PkgName pkgString) (TH.ModName mString)) = do this_mod <- getModule let reifMod = mkModule (stringToPackageKey pkgString) (mkModuleName mString) if (reifMod == this_mod) then reifyThisModule else reifyFromIface reifMod where reifyThisModule = do usages <- fmap (map modToTHMod . moduleEnvKeys . imp_mods) getImports return $ TH.ModuleInfo usages reifyFromIface reifMod = do iface <- loadInterfaceForModule (ptext (sLit "reifying module from TH for") <+> ppr reifMod) reifMod let usages = [modToTHMod m | usage <- mi_usages iface, Just m <- [usageToModule (modulePackageKey reifMod) usage] ] return $ TH.ModuleInfo usages usageToModule :: PackageKey -> Usage -> Maybe Module usageToModule _ (UsageFile {}) = Nothing usageToModule this_pkg (UsageHomeModule { usg_mod_name = mn }) = Just $ mkModule this_pkg mn usageToModule _ (UsagePackageModule { usg_mod = m }) = Just m ------------------------------ mkThAppTs :: TH.Type -> [TH.Type] -> TH.Type mkThAppTs fun_ty arg_tys = foldl TH.AppT fun_ty arg_tys noTH :: LitString -> SDoc -> TcM a noTH s d = failWithTc (hsep [ptext (sLit "Can't represent") <+> ptext s <+> ptext (sLit "in Template Haskell:"), nest 2 d]) ppr_th :: TH.Ppr a => a -> SDoc ppr_th x = text (TH.pprint x) {- Note [Reifying data constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Template Haskell syntax is rich enough to express even GADTs, provided we do so in the equality-predicate form. So a GADT like data T a where MkT1 :: a -> T [a] MkT2 :: T Int will appear in TH syntax like this data T a = forall b. (a ~ [b]) => MkT1 b | (a ~ Int) => MkT2 -} #endif /* GHCI */
gcampax/ghc
compiler/typecheck/TcSplice.hs
Haskell
bsd-3-clause
63,028
module Main where import System.Environment import Server main :: IO () main = do args <- getArgs if length args /= 1 then putStr help else case args of [cfg] -> startServer cfg _ -> putStr help -- | Help message help :: String help = "Students Big Brother Server v0.1.0 \n\ \Usage: \n\ \ students-big-brother-server <server_config.json>\n"
geo2a/students-big-brother
students-big-brother-server/app/Main.hs
Haskell
bsd-3-clause
385
{-# LANGUAGE TemplateHaskell #-} module Client.CEntityT where import Control.Lens (makeLenses) import Linear (V3(..)) import Game.EntityStateT import Types makeLenses ''CEntityT newCEntityT :: CEntityT newCEntityT = CEntityT { _ceBaseline = newEntityStateT Nothing , _ceCurrent = newEntityStateT Nothing , _cePrev = newEntityStateT Nothing , _ceServerFrame = 0 , _ceTrailCount = 0 , _ceLerpOrigin = V3 0 0 0 , _ceFlyStopTime = 0 }
ksaveljev/hake-2
src/Client/CEntityT.hs
Haskell
bsd-3-clause
539
{-| Module : $Header$ Description : Adapter for communicating with Slack via the webhook based Events API Copyright : (c) Justus Adam, 2016 License : BSD3 Maintainer : dev@justus.science Stability : experimental Portability : POSIX See http://marvin.readthedocs.io/en/latest/adapters.html#events-api for documentation about this adapter. -} module Marvin.Adapter.Slack.EventsAPI ( SlackAdapter, EventsAPI , SlackUserId, SlackChannelId , MkSlack , SlackRemoteFile(..), SlackLocalFile(..) , HasTitle(..), HasPublicPermalink(..), HasEditable(..), HasPublic(..), HasUser(..), HasPrivateUrl(..), HasComment(..) ) where import Control.Concurrent.Async.Lifted import Control.Concurrent.Chan.Lifted import Control.Monad import Control.Monad.IO.Class import Control.Monad.Logger import Data.Aeson import Data.Aeson.Types import Data.Maybe (fromMaybe) import qualified Data.Text as T import qualified Data.Text.Lazy as L import qualified Data.Text.Lazy.Encoding as L import Lens.Micro.Platform import Marvin.Adapter import Marvin.Adapter.Slack.Internal.Common import Marvin.Adapter.Slack.Internal.Types import Marvin.Interpolate.All import Network.HTTP.Types import Network.Wai import Network.Wai.Handler.Warp import Network.Wai.Handler.WarpTLS import Network.Wreq eventAPIeventParser :: Value -> Parser (T.Text, Either L.Text (InternalType EventsAPI)) eventAPIeventParser = withObject "expected object" $ \o -> do token <- o .: "token" type_ <- o .: "type" (token,) <$> case (type_ :: T.Text) of "url_verification" -> Left <$> o .: "challenge" "event_callback" -> Right <$> (o .: "event" >>= eventParser) _ -> fail "unknown wrapper event type" runEventReceiver :: Chan (InternalType EventsAPI) -> AdapterM (SlackAdapter EventsAPI) () runEventReceiver evChan = do useTLS <- fromMaybe True <$> lookupFromAdapterConfig "use-tls" server <- if useTLS then do certfile <- requireFromAdapterConfig "certfile" keyfile <- requireFromAdapterConfig "keyfile" return $ runTLS $ tlsSettings certfile keyfile else return runSettings port <- fromMaybe 7000 <$> lookupFromAdapterConfig "port" expectedToken <- requireFromAdapterConfig "token" let warpSet = setPort port defaultSettings logFn <- askLoggerIO liftIO $ server warpSet $ \req resp -> flip runLoggingT logFn $ let respond status rheaders body = liftIO $ resp $ responseLBS status rheaders body in if requestMethod req == methodPost then do bod <- liftIO $ lazyRequestBody req case eitherDecode bod >>= parseEither eventAPIeventParser of Left err -> do logErrorN $(isT "Unreadable JSON event: '#{err}'") respond notAcceptable406 [] "" Right (token,_) | token /= expectedToken -> do logErrorN $(isT "Recieved incorrect token: '#{token}'") respond unauthorized401 [] "" Right (_, Left challenge) -> do logInfoN $(isT "Recieved challenge event: '#{challenge}'") respond ok200 [] (L.encodeUtf8 challenge) Right (_, Right ev) -> do writeChan evChan ev respond ok200 [] "" else respond methodNotAllowed405 [] "" sendMessageLoop :: AdapterM (SlackAdapter EventsAPI) () sendMessageLoop = do outChan <- view (adapter.outChannel) forever $ do (SlackChannelId chan, msg) <- readChan outChan either (\err -> logErrorN $(isT "Sending message failed: #{err}")) (const $ return ()) =<< execAPIMethod (const $ return ()) "chat.postMessage" [ "channel" := chan , "text" := msg ] -- | Recieve events as a server via HTTP webhook data EventsAPI instance MkSlack EventsAPI where mkAdapterId = "slack-events" initIOConnections inChan = do a <- async $ runEventReceiver inChan link a sendMessageLoop
JustusAdam/marvin
src/Marvin/Adapter/Slack/EventsAPI.hs
Haskell
bsd-3-clause
4,540
{-# LANGUAGE OverloadedStrings #-} module Image_Loader where import Graphics.Blank import Wiki -- (578,400) main :: IO () main = do blankCanvas 3000 $ \ context -> do url1 <- staticURL context "type/jpeg" "images/Haskell.jpg" url2 <- staticURL context "type/jpeg" "images/House.jpg" send context $ do img1 <- newImage url1 img2 <- newImage url2 drawImage(img1,[69,50,97,129]) drawImage(img2,[200,50]) wiki $ snapShot context "images/Image_Loader.png" wiki $ close context
ku-fpg/blank-canvas
wiki-suite/Image_Loader.hs
Haskell
bsd-3-clause
584
#!/usr/bin/runghc import Distribution.Simple main = defaultMain
baldo/derive-trie
Setup.hs
Haskell
bsd-3-clause
65
module Deflisp.Core.Show where import Deflisp.Core.Types import Debug.Trace import qualified Data.Map as Map instance Show LispFunk where show (LibraryFunction name _) = "library function: " ++ name show (VarArgFunction _ _ _ _) = "vararg function" show (UserFunction _ _ _) = "user function" show (Macros _ _) = "macros" show (VariadicMacros _ _ _) = "variadic macros" instance Show LispExpression where show (LispNumber n) = show n show (LispSymbol n) = n show (LispKeyword n) = n show (ReservedKeyword n) = show n show (LispList n) = "(" ++ (unwords (map show n)) ++ ")" show (LispMap n) = "(" ++ (unwords (map show (Map.toList n))) ++ ")" show (LispVector n) = "[" ++ (unwords (map show n)) ++ "]" show (LispString n) = n show (LispBool n) = show n show (LispFunction a) = show a show (LispNil) = "nil" show (LispIO _) = "io" -- show a | (trace a) False = undefined -- instance Show (IO LispExpression) where -- show (IO (LispNumber n)) = show n -- instance Eq LispExpression where -- (LispNumber a) == (LispNumber b) = a == b -- (LispBool a) == (LispBool b) = a == b -- (LispSymbol a) == (LispSymbol b) = a == b -- (LispList a) == (LispList b) = a == b -- (LispVector a) == (LispVector b) = a == b -- (LispString a) == (LispString b) = a == b -- LispNil == LispNil = True -- _ == _ = False
ifesdjeen/deflisp
src/DefLisp/Core/Show.hs
Haskell
bsd-3-clause
1,361
module Language ( initialInterpreterState , parse , interpret , setInterpreterVariables , updateSystemVars , module Language.Ast ) where import Control.Monad ( forM_ ) import Control.Monad.Trans ( liftIO ) import qualified Data.Map.Strict as M import Lens.Simple ( set ) import Gfx.Context ( GfxContext ) import Language.Ast ( Identifier , Program , Value(..) ) import Language.Ast.Transformers ( transform ) import Language.Interpreter ( interpretLanguage ) import Language.Interpreter.StdLib ( addStdLib ) import qualified Language.Interpreter.Types as LT import Language.Interpreter.Types ( InterpreterState , externals , getGlobalNames , gfxContext , runInterpreterM , setGlobal , setSystemVars , systemVars ) import Language.Parser ( parseProgram ) import Language.Parser.Errors ( ParserError ) import Logging ( logInfo ) parse :: String -> Either ParserError Program parse = parseProgram initialInterpreterState :: [(Identifier, Value)] -> [(FilePath, Program)] -> GfxContext -> IO InterpreterState initialInterpreterState systemVariables userCode ctx = let langState = set gfxContext ctx LT.empty setup = do setSystemVars systemVariables addStdLib globals <- getGlobalNames mapM (load globals) userCode in snd <$> runInterpreterM setup langState where load globals (fp, code) = do liftIO $ logInfo ("Loading " ++ fp) interpretLanguage $ transform globals code updateSystemVars :: [(Identifier, Value)] -> InterpreterState -> InterpreterState updateSystemVars newSysVars = set systemVars (M.fromList newSysVars) setInterpreterVariables :: [(Identifier, Value)] -> M.Map String Value -> InterpreterState -> IO InterpreterState setInterpreterVariables globals externalVars is = let setVars = forM_ globals (uncurry setGlobal) in do (_, newState) <- runInterpreterM setVars is return $ set externals externalVars newState interpret :: InterpreterState -> Program -> IO (Either String Value, InterpreterState) interpret initialState program = let run = do globals <- getGlobalNames interpretLanguage (transform globals program) in runInterpreterM run initialState
rumblesan/improviz
src/Language.hs
Haskell
bsd-3-clause
3,026
module System.Build.Access.Version where class Version r where setVersion :: r -> r unsetVersion :: r -> r
tonymorris/lastik
System/Build/Access/Version.hs
Haskell
bsd-3-clause
130
{-# LANGUAGE JavaScriptFFI #-} module GHCJS.Three.HasName (HasName(..) ) where import GHCJS.Types import GHCJS.Three.Monad import Data.JSString (pack, unpack) -- | get name foreign import javascript unsafe "($1)['name']" thr_getName :: JSVal -> Three JSString -- | set name foreign import javascript unsafe "($2)['name'] = $1" thr_setName :: JSString -> JSVal -> Three () class ThreeJSVal o => HasName o where getName :: o -> Three String getName o = unpack <$> thr_getName (toJSVal o) setName :: String -> o -> Three () setName n o = thr_setName (pack n) (toJSVal o)
manyoo/ghcjs-three
src/GHCJS/Three/HasName.hs
Haskell
bsd-3-clause
605
{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.Equality -- Copyright : (C) 2012-14 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : Rank2Types -- ---------------------------------------------------------------------------- module Control.Lens.Equality ( -- * Type Equality Equality, Equality' , AnEquality, AnEquality' , runEq , substEq , mapEq , fromEq , simply -- * Implementation Details , Identical(..) ) where import Control.Lens.Type import Data.Functor.Identity #ifdef HLINT {-# ANN module "HLint: ignore Use id" #-} {-# ANN module "HLint: ignore Eta reduce" #-} #endif -- $setup -- >>> import Control.Lens ----------------------------------------------------------------------------- -- Equality ----------------------------------------------------------------------------- -- | Provides witness that @(s ~ a, b ~ t)@ holds. data Identical a b s t where Identical :: Identical a b a b -- | When you see this as an argument to a function, it expects an 'Equality'. type AnEquality s t a b = Identical a (Identity b) a (Identity b) -> Identical a (Identity b) s (Identity t) -- | A 'Simple' 'AnEquality'. type AnEquality' s a = AnEquality s s a a -- | Extract a witness of type 'Equality'. runEq :: AnEquality s t a b -> Identical s t a b runEq l = case l Identical of Identical -> Identical {-# INLINE runEq #-} -- | Substituting types with 'Equality'. substEq :: AnEquality s t a b -> ((s ~ a, t ~ b) => r) -> r substEq l = case runEq l of Identical -> \r -> r {-# INLINE substEq #-} -- | We can use 'Equality' to do substitution into anything. mapEq :: AnEquality s t a b -> f s -> f a mapEq l r = substEq l r {-# INLINE mapEq #-} -- | 'Equality' is symmetric. fromEq :: AnEquality s t a b -> Equality b a t s fromEq l = substEq l id {-# INLINE fromEq #-} -- | This is an adverb that can be used to modify many other 'Lens' combinators to make them require -- simple lenses, simple traversals, simple prisms or simple isos as input. simply :: (Optic' p f s a -> r) -> Optic' p f s a -> r simply = id {-# INLINE simply #-}
hvr/lens
src/Control/Lens/Equality.hs
Haskell
bsd-3-clause
2,358
module Distribution.Client.Dependency.Modular ( modularResolver, SolverConfig(..)) where -- Here, we try to map between the external epm solver -- interface and the internal interface that the solver actually -- expects. There are a number of type conversions to perform: we -- have to convert the package indices to the uniform index used -- by the solver; we also have to convert the initial constraints; -- and finally, we have to convert back the resulting install -- plan. import Data.Map as M ( fromListWith ) import Distribution.Client.Dependency.Modular.Assignment ( Assignment, toCPs ) import Distribution.Client.Dependency.Modular.Dependency ( RevDepMap ) import Distribution.Client.Dependency.Modular.ConfiguredConversion ( convCP ) import Distribution.Client.Dependency.Modular.IndexConversion ( convPIs ) import Distribution.Client.Dependency.Modular.Log ( logToProgress ) import Distribution.Client.Dependency.Modular.Package ( PN ) import Distribution.Client.Dependency.Modular.Solver ( SolverConfig(..), solve ) import Distribution.Client.Dependency.Types ( DependencyResolver, PackageConstraint(..) ) import Distribution.Client.InstallPlan ( PlanPackage ) import Distribution.System ( Platform(..) ) -- | Ties the two worlds together: classic epm vs. the modular -- solver. Performs the necessary translations before and after. modularResolver :: SolverConfig -> DependencyResolver modularResolver sc (Platform arch os) cinfo iidx sidx pprefs pcs pns = fmap (uncurry postprocess) $ -- convert install plan logToProgress (maxBackjumps sc) $ -- convert log format into progress format solve sc idx pprefs gcs pns where -- Indices have to be converted into solver-specific uniform index. idx = convPIs os arch cinfo (shadowPkgs sc) (strongFlags sc) iidx sidx -- Constraints have to be converted into a finite map indexed by PN. gcs = M.fromListWith (++) (map (\ pc -> (pcName pc, [pc])) pcs) -- Results have to be converted into an install plan. postprocess :: Assignment -> RevDepMap -> [PlanPackage] postprocess a rdm = map (convCP iidx sidx) (toCPs a rdm) -- Helper function to extract the PN from a constraint. pcName :: PackageConstraint -> PN pcName (PackageConstraintVersion pn _) = pn pcName (PackageConstraintInstalled pn ) = pn pcName (PackageConstraintSource pn ) = pn pcName (PackageConstraintFlags pn _) = pn pcName (PackageConstraintStanzas pn _) = pn
typelead/epm
epm/Distribution/Client/Dependency/Modular.hs
Haskell
bsd-3-clause
2,611
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-2006 \section[RnEnv]{Environment manipulation for the renamer monad} -} {-# LANGUAGE CPP, MultiWayIf #-} module RnEnv ( newTopSrcBinder, lookupLocatedTopBndrRn, lookupTopBndrRn, lookupLocatedOccRn, lookupOccRn, lookupOccRn_maybe, lookupLocalOccRn_maybe, lookupInfoOccRn, lookupLocalOccThLvl_maybe, lookupTypeOccRn, lookupKindOccRn, lookupGlobalOccRn, lookupGlobalOccRnExport, lookupGlobalOccRn_maybe, lookupOccRn_overloaded, lookupGlobalOccRn_overloaded, reportUnboundName, unknownNameSuggestions, addNameClashErrRn, HsSigCtxt(..), lookupLocalTcNames, lookupSigOccRn, lookupSigCtxtOccRn, lookupFixityRn, lookupFixityRn_help, lookupFieldFixityRn, lookupTyFixityRn, lookupInstDeclBndr, lookupRecFieldOcc, lookupFamInstName, lookupConstructorFields, lookupSyntaxName, lookupSyntaxNames, lookupIfThenElse, lookupGreAvailRn, getLookupOccRn,mkUnboundName, mkUnboundNameRdr, isUnboundName, addUsedGRE, addUsedGREs, addUsedDataCons, newLocalBndrRn, newLocalBndrsRn, bindLocalNames, bindLocalNamesFV, MiniFixityEnv, addLocalFixities, bindLocatedLocalsFV, bindLocatedLocalsRn, extendTyVarEnvFVRn, -- Role annotations RoleAnnotEnv, emptyRoleAnnotEnv, mkRoleAnnotEnv, lookupRoleAnnot, getRoleAnnots, checkDupRdrNames, checkShadowedRdrNames, checkDupNames, checkDupAndShadowedNames, dupNamesErr, checkTupSize, addFvRn, mapFvRn, mapMaybeFvRn, mapFvRnCPS, warnUnusedMatches, warnUnusedTypePatterns, warnUnusedTopBinds, warnUnusedLocalBinds, mkFieldEnv, dataTcOccs, kindSigErr, perhapsForallMsg, unknownSubordinateErr, HsDocContext(..), pprHsDocContext, inHsDocContext, withHsDocContext ) where #include "HsVersions.h" import LoadIface ( loadInterfaceForName, loadSrcInterface_maybe ) import IfaceEnv import HsSyn import RdrName import HscTypes import TcEnv import TcRnMonad import RdrHsSyn ( setRdrNameSpace ) import TysWiredIn ( starKindTyConName, unicodeStarKindTyConName ) import Name import NameSet import NameEnv import Avail import Module import ConLike import DataCon import TyCon import PrelNames ( mkUnboundName, isUnboundName, rOOT_MAIN, forall_tv_RDR ) import ErrUtils ( MsgDoc ) import BasicTypes ( Fixity(..), FixityDirection(..), minPrecedence, defaultFixity ) import SrcLoc import Outputable import Util import Maybes import BasicTypes ( TopLevelFlag(..) ) import ListSetOps ( removeDups ) import DynFlags import FastString import Control.Monad import Data.List import Data.Function ( on ) import ListSetOps ( minusList ) import Constants ( mAX_TUPLE_SIZE ) import qualified GHC.LanguageExtensions as LangExt {- ********************************************************* * * Source-code binders * * ********************************************************* Note [Signature lazy interface loading] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GHC's lazy interface loading can be a bit confusing, so this Note is an empirical description of what happens in one interesting case. When compiling a signature module against an its implementation, we do NOT load interface files associated with its names until after the type checking phase. For example: module ASig where data T f :: T -> T Suppose we compile this with -sig-of "A is ASig": module B where data T = T f T = T module A(module B) where import B During type checking, we'll load A.hi because we need to know what the RdrEnv for the module is, but we DO NOT load the interface for B.hi! It's wholly unnecessary: our local definition 'data T' in ASig is all the information we need to finish type checking. This is contrast to type checking of ordinary Haskell files, in which we would not have the local definition "data T" and would need to consult B.hi immediately. (Also, this situation never occurs for hs-boot files, since you're not allowed to reexport from another module.) After type checking, we then check that the types we provided are consistent with the backing implementation (in checkHiBootOrHsigIface). At this point, B.hi is loaded, because we need something to compare against. I discovered this behavior when trying to figure out why type class instances for Data.Map weren't in the EPS when I was type checking a test very much like ASig (sigof02dm): the associated interface hadn't been loaded yet! (The larger issue is a moot point, since an instance declared in a signature can never be a duplicate.) This behavior might change in the future. Consider this alternate module B: module B where {-# DEPRECATED T, f "Don't use" #-} data T = T f T = T One might conceivably want to report deprecation warnings when compiling ASig with -sig-of B, in which case we need to look at B.hi to find the deprecation warnings during renaming. At the moment, you don't get any warning until you use the identifier further downstream. This would require adjusting addUsedGRE so that during signature compilation, we do not report deprecation warnings for LocalDef. See also Note [Handling of deprecations] -} newTopSrcBinder :: Located RdrName -> RnM Name newTopSrcBinder (L loc rdr_name) | Just name <- isExact_maybe rdr_name = -- This is here to catch -- (a) Exact-name binders created by Template Haskell -- (b) The PrelBase defn of (say) [] and similar, for which -- the parser reads the special syntax and returns an Exact RdrName -- We are at a binding site for the name, so check first that it -- the current module is the correct one; otherwise GHC can get -- very confused indeed. This test rejects code like -- data T = (,) Int Int -- unless we are in GHC.Tup if isExternalName name then do { this_mod <- getModule ; unless (this_mod == nameModule name) (addErrAt loc (badOrigBinding rdr_name)) ; return name } else -- See Note [Binders in Template Haskell] in Convert.hs do { this_mod <- getModule ; externaliseName this_mod name } | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { this_mod <- getModule ; unless (rdr_mod == this_mod || rdr_mod == rOOT_MAIN) (addErrAt loc (badOrigBinding rdr_name)) -- When reading External Core we get Orig names as binders, -- but they should agree with the module gotten from the monad -- -- We can get built-in syntax showing up here too, sadly. If you type -- data T = (,,,) -- the constructor is parsed as a type, and then RdrHsSyn.tyConToDataCon -- uses setRdrNameSpace to make it into a data constructors. At that point -- the nice Exact name for the TyCon gets swizzled to an Orig name. -- Hence the badOrigBinding error message. -- -- Except for the ":Main.main = ..." definition inserted into -- the Main module; ugh! -- Because of this latter case, we call newGlobalBinder with a module from -- the RdrName, not from the environment. In principle, it'd be fine to -- have an arbitrary mixture of external core definitions in a single module, -- (apart from module-initialisation issues, perhaps). ; newGlobalBinder rdr_mod rdr_occ loc } | otherwise = do { unless (not (isQual rdr_name)) (addErrAt loc (badQualBndrErr rdr_name)) -- Binders should not be qualified; if they are, and with a different -- module name, we we get a confusing "M.T is not in scope" error later ; stage <- getStage ; env <- getGblEnv ; if isBrackStage stage then -- We are inside a TH bracket, so make an *Internal* name -- See Note [Top-level Names in Template Haskell decl quotes] in RnNames do { uniq <- newUnique ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) } else case tcg_impl_rdr_env env of Just gr -> -- We're compiling --sig-of, so resolve with respect to this -- module. -- See Note [Signature parameters in TcGblEnv and DynFlags] do { case lookupGlobalRdrEnv gr (rdrNameOcc rdr_name) of -- Be sure to override the loc so that we get accurate -- information later [GRE{ gre_name = n }] -> do -- NB: Just adding this line will not work: -- addUsedGRE True gre -- see Note [Signature lazy interface loading] for -- more details. return (setNameLoc n loc) _ -> do { -- NB: cannot use reportUnboundName rdr_name -- because it looks up in the wrong RdrEnv -- ToDo: more helpful error messages ; addErr (unknownNameErr (pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name))) rdr_name) ; return (mkUnboundNameRdr rdr_name) } } Nothing -> -- Normal case do { this_mod <- getModule ; traceRn (text "newTopSrcBinder" <+> (ppr this_mod $$ ppr rdr_name $$ ppr loc)) ; newGlobalBinder this_mod (rdrNameOcc rdr_name) loc } } {- ********************************************************* * * Source code occurrences * * ********************************************************* Looking up a name in the RnEnv. Note [Type and class operator definitions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We want to reject all of these unless we have -XTypeOperators (Trac #3265) data a :*: b = ... class a :*: b where ... data (:*:) a b = .... class (:*:) a b where ... The latter two mean that we are not just looking for a *syntactically-infix* declaration, but one that uses an operator OccName. We use OccName.isSymOcc to detect that case, which isn't terribly efficient, but there seems to be no better way. -} lookupTopBndrRn :: RdrName -> RnM Name lookupTopBndrRn n = do nopt <- lookupTopBndrRn_maybe n case nopt of Just n' -> return n' Nothing -> do traceRn $ (text "lookupTopBndrRn fail" <+> ppr n) unboundName WL_LocalTop n lookupLocatedTopBndrRn :: Located RdrName -> RnM (Located Name) lookupLocatedTopBndrRn = wrapLocM lookupTopBndrRn lookupTopBndrRn_maybe :: RdrName -> RnM (Maybe Name) -- Look up a top-level source-code binder. We may be looking up an unqualified 'f', -- and there may be several imported 'f's too, which must not confuse us. -- For example, this is OK: -- import Foo( f ) -- infix 9 f -- The 'f' here does not need to be qualified -- f x = x -- Nor here, of course -- So we have to filter out the non-local ones. -- -- A separate function (importsFromLocalDecls) reports duplicate top level -- decls, so here it's safe just to choose an arbitrary one. -- -- There should never be a qualified name in a binding position in Haskell, -- but there can be if we have read in an external-Core file. -- The Haskell parser checks for the illegal qualified name in Haskell -- source files, so we don't need to do so here. lookupTopBndrRn_maybe rdr_name | Just name <- isExact_maybe rdr_name = do { name' <- lookupExactOcc name; return (Just name') } | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name -- This deals with the case of derived bindings, where -- we don't bother to call newTopSrcBinder first -- We assume there is no "parent" name = do { loc <- getSrcSpanM ; n <- newGlobalBinder rdr_mod rdr_occ loc ; return (Just n)} | otherwise = do { -- Check for operators in type or class declarations -- See Note [Type and class operator definitions] let occ = rdrNameOcc rdr_name ; when (isTcOcc occ && isSymOcc occ) (do { op_ok <- xoptM LangExt.TypeOperators ; unless op_ok (addErr (opDeclErr rdr_name)) }) ; env <- getGlobalRdrEnv ; case filter isLocalGRE (lookupGRE_RdrName rdr_name env) of [gre] -> return (Just (gre_name gre)) _ -> return Nothing -- Ambiguous (can't happen) or unbound } ----------------------------------------------- -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames]. -- This adds an error if the name cannot be found. lookupExactOcc :: Name -> RnM Name lookupExactOcc name = do { result <- lookupExactOcc_either name ; case result of Left err -> do { addErr err ; return name } Right name' -> return name' } -- | Lookup an @Exact@ @RdrName@. See Note [Looking up Exact RdrNames]. -- This never adds an error, but it may return one. lookupExactOcc_either :: Name -> RnM (Either MsgDoc Name) -- See Note [Looking up Exact RdrNames] lookupExactOcc_either name | Just thing <- wiredInNameTyThing_maybe name , Just tycon <- case thing of ATyCon tc -> Just tc AConLike (RealDataCon dc) -> Just (dataConTyCon dc) _ -> Nothing , isTupleTyCon tycon = do { checkTupSize (tyConArity tycon) ; return (Right name) } | isExternalName name = return (Right name) | otherwise = do { env <- getGlobalRdrEnv ; let -- See Note [Splicing Exact names] main_occ = nameOccName name demoted_occs = case demoteOccName main_occ of Just occ -> [occ] Nothing -> [] gres = [ gre | occ <- main_occ : demoted_occs , gre <- lookupGlobalRdrEnv env occ , gre_name gre == name ] ; case gres of [gre] -> return (Right (gre_name gre)) [] -> -- See Note [Splicing Exact names] do { lcl_env <- getLocalRdrEnv ; if name `inLocalRdrEnvScope` lcl_env then return (Right name) else #ifdef GHCI do { th_topnames_var <- fmap tcg_th_topnames getGblEnv ; th_topnames <- readTcRef th_topnames_var ; if name `elemNameSet` th_topnames then return (Right name) else return (Left exact_nm_err) } #else /* !GHCI */ return (Left exact_nm_err) #endif /* !GHCI */ } gres -> return (Left (sameNameErr gres)) -- Ugh! See Note [Template Haskell ambiguity] } where exact_nm_err = hang (text "The exact Name" <+> quotes (ppr name) <+> ptext (sLit "is not in scope")) 2 (vcat [ text "Probable cause: you used a unique Template Haskell name (NameU), " , text "perhaps via newName, but did not bind it" , text "If that's it, then -ddump-splices might be useful" ]) sameNameErr :: [GlobalRdrElt] -> MsgDoc sameNameErr [] = panic "addSameNameErr: empty list" sameNameErr gres@(_ : _) = hang (text "Same exact name in multiple name-spaces:") 2 (vcat (map pp_one sorted_names) $$ th_hint) where sorted_names = sortWith nameSrcLoc (map gre_name gres) pp_one name = hang (pprNameSpace (occNameSpace (getOccName name)) <+> quotes (ppr name) <> comma) 2 (text "declared at:" <+> ppr (nameSrcLoc name)) th_hint = vcat [ text "Probable cause: you bound a unique Template Haskell name (NameU)," , text "perhaps via newName, in different name-spaces." , text "If that's it, then -ddump-splices might be useful" ] ----------------------------------------------- lookupInstDeclBndr :: Name -> SDoc -> RdrName -> RnM Name -- This is called on the method name on the left-hand side of an -- instance declaration binding. eg. instance Functor T where -- fmap = ... -- ^^^^ called on this -- Regardless of how many unqualified fmaps are in scope, we want -- the one that comes from the Functor class. -- -- Furthermore, note that we take no account of whether the -- name is only in scope qualified. I.e. even if method op is -- in scope as M.op, we still allow plain 'op' on the LHS of -- an instance decl -- -- The "what" parameter says "method" or "associated type", -- depending on what we are looking up lookupInstDeclBndr cls what rdr = do { when (isQual rdr) (addErr (badQualBndrErr rdr)) -- In an instance decl you aren't allowed -- to use a qualified name for the method -- (Although it'd make perfect sense.) ; mb_name <- lookupSubBndrOcc False -- False => we don't give deprecated -- warnings when a deprecated class -- method is defined. We only warn -- when it's used cls doc rdr ; case mb_name of Left err -> do { addErr err; return (mkUnboundNameRdr rdr) } Right nm -> return nm } where doc = what <+> text "of class" <+> quotes (ppr cls) ----------------------------------------------- lookupFamInstName :: Maybe Name -> Located RdrName -> RnM (Located Name) -- Used for TyData and TySynonym family instances only, -- See Note [Family instance binders] lookupFamInstName (Just cls) tc_rdr -- Associated type; c.f RnBinds.rnMethodBind = wrapLocM (lookupInstDeclBndr cls (text "associated type")) tc_rdr lookupFamInstName Nothing tc_rdr -- Family instance; tc_rdr is an *occurrence* = lookupLocatedOccRn tc_rdr ----------------------------------------------- lookupConstructorFields :: Name -> RnM [FieldLabel] -- Look up the fields of a given constructor -- * For constructors from this module, use the record field env, -- which is itself gathered from the (as yet un-typechecked) -- data type decls -- -- * For constructors from imported modules, use the *type* environment -- since imported modles are already compiled, the info is conveniently -- right there lookupConstructorFields con_name = do { this_mod <- getModule ; if nameIsLocalOrFrom this_mod con_name then do { field_env <- getRecFieldEnv ; traceTc "lookupCF" (ppr con_name $$ ppr (lookupNameEnv field_env con_name) $$ ppr field_env) ; return (lookupNameEnv field_env con_name `orElse` []) } else do { con <- tcLookupDataCon con_name ; traceTc "lookupCF 2" (ppr con) ; return (dataConFieldLabels con) } } ----------------------------------------------- -- Used for record construction and pattern matching -- When the -XDisambiguateRecordFields flag is on, take account of the -- constructor name to disambiguate which field to use; it's just the -- same as for instance decls -- -- NB: Consider this: -- module Foo where { data R = R { fld :: Int } } -- module Odd where { import Foo; fld x = x { fld = 3 } } -- Arguably this should work, because the reference to 'fld' is -- unambiguous because there is only one field id 'fld' in scope. -- But currently it's rejected. lookupRecFieldOcc :: Maybe Name -- Nothing => just look it up as usual -- Just tycon => use tycon to disambiguate -> SDoc -> RdrName -> RnM Name lookupRecFieldOcc parent doc rdr_name | Just tc_name <- parent = do { mb_name <- lookupSubBndrOcc True tc_name doc rdr_name ; case mb_name of Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) } Right n -> return n } | otherwise = lookupGlobalOccRn rdr_name lookupSubBndrOcc :: Bool -> Name -- Parent -> SDoc -> RdrName -> RnM (Either MsgDoc Name) -- Find all the things the rdr-name maps to -- and pick the one with the right parent namep lookupSubBndrOcc warn_if_deprec the_parent doc rdr_name | Just n <- isExact_maybe rdr_name -- This happens in derived code = do { n <- lookupExactOcc n ; return (Right n) } | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { n <- lookupOrig rdr_mod rdr_occ ; return (Right n) } | isUnboundName the_parent -- Avoid an error cascade from malformed decls: -- instance Int where { foo = e } -- We have already generated an error in rnLHsInstDecl = return (Right (mkUnboundNameRdr rdr_name)) | otherwise = do { env <- getGlobalRdrEnv ; let gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name) -- NB: lookupGlobalRdrEnv, not lookupGRE_RdrName! -- The latter does pickGREs, but we want to allow 'x' -- even if only 'M.x' is in scope ; traceRn (text "lookupSubBndrOcc" <+> vcat [ppr the_parent, ppr rdr_name, ppr gres, ppr (pick_gres rdr_name gres)]) ; case pick_gres rdr_name gres of (gre:_) -> do { addUsedGRE warn_if_deprec gre -- Add a usage; this is an *occurrence* site -- Note [Usage for sub-bndrs] ; return (Right (gre_name gre)) } -- If there is more than one local GRE for the -- same OccName 'f', that will be reported separately -- as a duplicate top-level binding for 'f' [] -> do { ns <- lookupQualifiedNameGHCi rdr_name ; case ns of (n:_) -> return (Right n) -- Unlikely to be more than one...? [] -> return (Left (unknownSubordinateErr doc rdr_name)) } } where -- If Parent = NoParent, just do a normal lookup -- If Parent = Parent p then find all GREs that -- (a) have parent p -- (b) for Unqual, are in scope qualified or unqualified -- for Qual, are in scope with that qualification pick_gres rdr_name gres | isUnqual rdr_name = filter right_parent gres | otherwise = filter right_parent (pickGREs rdr_name gres) right_parent (GRE { gre_par = p }) | ParentIs parent <- p = parent == the_parent | FldParent { par_is = parent } <- p = parent == the_parent | otherwise = False {- Note [Family instance binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data family F a data instance F T = X1 | X2 The 'data instance' decl has an *occurrence* of F (and T), and *binds* X1 and X2. (This is unlike a normal data type declaration which would bind F too.) So we want an AvailTC F [X1,X2]. Now consider a similar pair: class C a where data G a instance C S where data G S = Y1 | Y2 The 'data G S' *binds* Y1 and Y2, and has an *occurrence* of G. But there is a small complication: in an instance decl, we don't use qualified names on the LHS; instead we use the class to disambiguate. Thus: module M where import Blib( G ) class C a where data G a instance C S where data G S = Y1 | Y2 Even though there are two G's in scope (M.G and Blib.G), the occurrence of 'G' in the 'instance C S' decl is unambiguous, because C has only one associated type called G. This is exactly what happens for methods, and it is only consistent to do the same thing for types. That's the role of the function lookupTcdName; the (Maybe Name) give the class of the encloseing instance decl, if any. Note [Looking up Exact RdrNames] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Exact RdrNames are generated by Template Haskell. See Note [Binders in Template Haskell] in Convert. For data types and classes have Exact system Names in the binding positions for constructors, TyCons etc. For example [d| data T = MkT Int |] when we splice in and Convert to HsSyn RdrName, we'll get data (Exact (system Name "T")) = (Exact (system Name "MkT")) ... These System names are generated by Convert.thRdrName But, constructors and the like need External Names, not System Names! So we do the following * In RnEnv.newTopSrcBinder we spot Exact RdrNames that wrap a non-External Name, and make an External name for it. This is the name that goes in the GlobalRdrEnv * When looking up an occurrence of an Exact name, done in RnEnv.lookupExactOcc, we find the Name with the right unique in the GlobalRdrEnv, and use the one from the envt -- it will be an External Name in the case of the data type/constructor above. * Exact names are also use for purely local binders generated by TH, such as \x_33. x_33 Both binder and occurrence are Exact RdrNames. The occurrence gets looked up in the LocalRdrEnv by RnEnv.lookupOccRn, and misses, because lookupLocalRdrEnv always returns Nothing for an Exact Name. Now we fall through to lookupExactOcc, which will find the Name is not in the GlobalRdrEnv, so we just use the Exact supplied Name. Note [Splicing Exact names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider the splice $(do { x <- newName "x"; return (VarE x) }) This will generate a (HsExpr RdrName) term that mentions the Exact RdrName "x_56" (or whatever), but does not bind it. So when looking such Exact names we want to check that it's in scope, otherwise the type checker will get confused. To do this we need to keep track of all the Names in scope, and the LocalRdrEnv does just that; we consult it with RdrName.inLocalRdrEnvScope. There is another wrinkle. With TH and -XDataKinds, consider $( [d| data Nat = Zero data T = MkT (Proxy 'Zero) |] ) After splicing, but before renaming we get this: data Nat_77{tc} = Zero_78{d} data T_79{tc} = MkT_80{d} (Proxy 'Zero_78{tc}) |] ) The occurrence of 'Zero in the data type for T has the right unique, but it has a TcClsName name-space in its OccName. (This is set by the ctxt_ns argument of Convert.thRdrName.) When we check that is in scope in the GlobalRdrEnv, we need to look up the DataName namespace too. (An alternative would be to make the GlobalRdrEnv also have a Name -> GRE mapping.) Note [Template Haskell ambiguity] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The GlobalRdrEnv invariant says that if occ -> [gre1, ..., gren] then the gres have distinct Names (INVARIANT 1 of GlobalRdrEnv). This is guaranteed by extendGlobalRdrEnvRn (the dups check in add_gre). So how can we get multiple gres in lookupExactOcc_maybe? Because in TH we might use the same TH NameU in two different name spaces. eg (Trac #7241): $(newName "Foo" >>= \o -> return [DataD [] o [] [RecC o []] [''Show]]) Here we generate a type constructor and data constructor with the same unique, but differnt name spaces. It'd be nicer to rule this out in extendGlobalRdrEnvRn, but that would mean looking up the OccName in every name-space, just in case, and that seems a bit brutal. So it's just done here on lookup. But we might need to revisit that choice. Note [Usage for sub-bndrs] ~~~~~~~~~~~~~~~~~~~~~~~~~~ If you have this import qualified M( C( f ) ) instance M.C T where f x = x then is the qualified import M.f used? Obviously yes. But the RdrName used in the instance decl is unqualified. In effect, we fill in the qualification by looking for f's whose class is M.C But when adding to the UsedRdrNames we must make that qualification explicit (saying "used M.f"), otherwise we get "Redundant import of M.f". So we make up a suitable (fake) RdrName. But be careful import qualifed M import M( C(f) ) instance C T where f x = x Here we want to record a use of 'f', not of 'M.f', otherwise we'll miss the fact that the qualified import is redundant. -------------------------------------------------- -- Occurrences -------------------------------------------------- -} getLookupOccRn :: RnM (Name -> Maybe Name) getLookupOccRn = do local_env <- getLocalRdrEnv return (lookupLocalRdrOcc local_env . nameOccName) mkUnboundNameRdr :: RdrName -> Name mkUnboundNameRdr rdr = mkUnboundName (rdrNameOcc rdr) lookupLocatedOccRn :: Located RdrName -> RnM (Located Name) lookupLocatedOccRn = wrapLocM lookupOccRn lookupLocalOccRn_maybe :: RdrName -> RnM (Maybe Name) -- Just look in the local environment lookupLocalOccRn_maybe rdr_name = do { local_env <- getLocalRdrEnv ; return (lookupLocalRdrEnv local_env rdr_name) } lookupLocalOccThLvl_maybe :: Name -> RnM (Maybe (TopLevelFlag, ThLevel)) -- Just look in the local environment lookupLocalOccThLvl_maybe name = do { lcl_env <- getLclEnv ; return (lookupNameEnv (tcl_th_bndrs lcl_env) name) } -- lookupOccRn looks up an occurrence of a RdrName lookupOccRn :: RdrName -> RnM Name lookupOccRn rdr_name = do { mb_name <- lookupOccRn_maybe rdr_name ; case mb_name of Just name -> return name Nothing -> reportUnboundName rdr_name } lookupKindOccRn :: RdrName -> RnM Name -- Looking up a name occurring in a kind lookupKindOccRn rdr_name = do { typeintype <- xoptM LangExt.TypeInType ; if | typeintype -> lookupTypeOccRn rdr_name -- With -XNoTypeInType, treat any usage of * in kinds as in scope -- this is a dirty hack, but then again so was the old * kind. | is_star rdr_name -> return starKindTyConName | is_uni_star rdr_name -> return unicodeStarKindTyConName | otherwise -> lookupOccRn rdr_name } -- lookupPromotedOccRn looks up an optionally promoted RdrName. lookupTypeOccRn :: RdrName -> RnM Name -- see Note [Demotion] lookupTypeOccRn rdr_name = do { mb_name <- lookupOccRn_maybe rdr_name ; case mb_name of { Just name -> return name ; Nothing -> do { dflags <- getDynFlags ; lookup_demoted rdr_name dflags } } } lookup_demoted :: RdrName -> DynFlags -> RnM Name lookup_demoted rdr_name dflags | Just demoted_rdr <- demoteRdrName rdr_name -- Maybe it's the name of a *data* constructor = do { data_kinds <- xoptM LangExt.DataKinds ; mb_demoted_name <- lookupOccRn_maybe demoted_rdr ; case mb_demoted_name of Nothing -> unboundNameX WL_Any rdr_name star_info Just demoted_name | data_kinds -> do { whenWOptM Opt_WarnUntickedPromotedConstructors $ addWarn (Reason Opt_WarnUntickedPromotedConstructors) (untickedPromConstrWarn demoted_name) ; return demoted_name } | otherwise -> unboundNameX WL_Any rdr_name suggest_dk } | otherwise = reportUnboundName rdr_name where suggest_dk = text "A data constructor of that name is in scope; did you mean DataKinds?" untickedPromConstrWarn name = text "Unticked promoted constructor" <> colon <+> quotes (ppr name) <> dot $$ hsep [ text "Use" , quotes (char '\'' <> ppr name) , text "instead of" , quotes (ppr name) <> dot ] star_info | is_star rdr_name || is_uni_star rdr_name = if xopt LangExt.TypeInType dflags then text "NB: With TypeInType, you must import" <+> ppr rdr_name <+> text "from Data.Kind" else empty | otherwise = empty is_star, is_uni_star :: RdrName -> Bool is_star = (fsLit "*" ==) . occNameFS . rdrNameOcc is_uni_star = (fsLit "★" ==) . occNameFS . rdrNameOcc {- Note [Demotion] ~~~~~~~~~~~~~~~ When the user writes: data Nat = Zero | Succ Nat foo :: f Zero -> Int 'Zero' in the type signature of 'foo' is parsed as: HsTyVar ("Zero", TcClsName) When the renamer hits this occurrence of 'Zero' it's going to realise that it's not in scope. But because it is renaming a type, it knows that 'Zero' might be a promoted data constructor, so it will demote its namespace to DataName and do a second lookup. The final result (after the renamer) will be: HsTyVar ("Zero", DataName) -} -- Use this version to get tracing -- -- lookupOccRn_maybe, lookupOccRn_maybe' :: RdrName -> RnM (Maybe Name) -- lookupOccRn_maybe rdr_name -- = do { mb_res <- lookupOccRn_maybe' rdr_name -- ; gbl_rdr_env <- getGlobalRdrEnv -- ; local_rdr_env <- getLocalRdrEnv -- ; traceRn $ text "lookupOccRn_maybe" <+> -- vcat [ ppr rdr_name <+> ppr (getUnique (rdrNameOcc rdr_name)) -- , ppr mb_res -- , text "Lcl env" <+> ppr local_rdr_env -- , text "Gbl env" <+> ppr [ (getUnique (nameOccName (gre_name (head gres'))),gres') | gres <- occEnvElts gbl_rdr_env -- , let gres' = filter isLocalGRE gres, not (null gres') ] ] -- ; return mb_res } lookupOccRn_maybe :: RdrName -> RnM (Maybe Name) -- lookupOccRn looks up an occurrence of a RdrName lookupOccRn_maybe rdr_name = do { local_env <- getLocalRdrEnv ; case lookupLocalRdrEnv local_env rdr_name of { Just name -> return (Just name) ; Nothing -> do ; lookupGlobalOccRn_maybe rdr_name } } lookupGlobalOccRn_maybe :: RdrName -> RnM (Maybe Name) -- Looks up a RdrName occurrence in the top-level -- environment, including using lookupQualifiedNameGHCi -- for the GHCi case -- No filter function; does not report an error on failure -- Uses addUsedRdrName to record use and deprecations lookupGlobalOccRn_maybe rdr_name | Just n <- isExact_maybe rdr_name -- This happens in derived code = do { n' <- lookupExactOcc n; return (Just n') } | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { n <- lookupOrig rdr_mod rdr_occ ; return (Just n) } | otherwise = do { mb_gre <- lookupGreRn_maybe rdr_name ; case mb_gre of { Just gre -> return (Just (gre_name gre)) ; Nothing -> do { ns <- lookupQualifiedNameGHCi rdr_name -- This test is not expensive, -- and only happens for failed lookups ; case ns of (n:_) -> return (Just n) -- Unlikely to be more than one...? [] -> return Nothing } } } lookupGlobalOccRn :: RdrName -> RnM Name -- lookupGlobalOccRn is like lookupOccRn, except that it looks in the global -- environment. Adds an error message if the RdrName is not in scope. lookupGlobalOccRn rdr_name = do { mb_name <- lookupGlobalOccRn_maybe rdr_name ; case mb_name of Just n -> return n Nothing -> do { traceRn (text "lookupGlobalOccRn" <+> ppr rdr_name) ; unboundName WL_Global rdr_name } } -- like lookupGlobalOccRn but suggests adding 'type' keyword -- to export type constructors mistaken for data constructors lookupGlobalOccRnExport :: RdrName -> RnM Name lookupGlobalOccRnExport rdr_name = do { mb_name <- lookupGlobalOccRn_maybe rdr_name ; case mb_name of Just n -> return n Nothing -> do { env <- getGlobalRdrEnv ; let tycon = setOccNameSpace tcClsName (rdrNameOcc rdr_name) msg = case lookupOccEnv env tycon of Just (gre : _) -> make_msg gre _ -> Outputable.empty make_msg gre = hang (hsep [text "Note: use", quotes (text "type"), text "keyword to export type constructor", quotes (ppr (gre_name gre))]) 2 (vcat [pprNameProvenance gre, text "(requires TypeOperators extension)"]) ; unboundNameX WL_Global rdr_name msg } } lookupInfoOccRn :: RdrName -> RnM [Name] -- lookupInfoOccRn is intended for use in GHCi's ":info" command -- It finds all the GREs that RdrName could mean, not complaining -- about ambiguity, but rather returning them all -- C.f. Trac #9881 lookupInfoOccRn rdr_name | Just n <- isExact_maybe rdr_name -- e.g. (->) = return [n] | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { n <- lookupOrig rdr_mod rdr_occ ; return [n] } | otherwise = do { rdr_env <- getGlobalRdrEnv ; let ns = map gre_name (lookupGRE_RdrName rdr_name rdr_env) ; qual_ns <- lookupQualifiedNameGHCi rdr_name ; return (ns ++ (qual_ns `minusList` ns)) } -- | Like 'lookupOccRn_maybe', but with a more informative result if -- the 'RdrName' happens to be a record selector: -- -- * Nothing -> name not in scope (no error reported) -- * Just (Left x) -> name uniquely refers to x, -- or there is a name clash (reported) -- * Just (Right xs) -> name refers to one or more record selectors; -- if overload_ok was False, this list will be -- a singleton. lookupOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [FieldOcc Name])) lookupOccRn_overloaded overload_ok rdr_name = do { local_env <- getLocalRdrEnv ; case lookupLocalRdrEnv local_env rdr_name of { Just name -> return (Just (Left name)) ; Nothing -> do { mb_name <- lookupGlobalOccRn_overloaded overload_ok rdr_name ; case mb_name of { Just name -> return (Just name) ; Nothing -> do { ns <- lookupQualifiedNameGHCi rdr_name -- This test is not expensive, -- and only happens for failed lookups ; case ns of (n:_) -> return $ Just $ Left n -- Unlikely to be more than one...? [] -> return Nothing } } } } } lookupGlobalOccRn_overloaded :: Bool -> RdrName -> RnM (Maybe (Either Name [FieldOcc Name])) lookupGlobalOccRn_overloaded overload_ok rdr_name | Just n <- isExact_maybe rdr_name -- This happens in derived code = do { n' <- lookupExactOcc n; return (Just (Left n')) } | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { n <- lookupOrig rdr_mod rdr_occ ; return (Just (Left n)) } | otherwise = do { env <- getGlobalRdrEnv ; case lookupGRE_RdrName rdr_name env of [] -> return Nothing [gre] | isRecFldGRE gre -> do { addUsedGRE True gre ; let fld_occ :: FieldOcc Name fld_occ = FieldOcc (noLoc rdr_name) (gre_name gre) ; return (Just (Right [fld_occ])) } | otherwise -> do { addUsedGRE True gre ; return (Just (Left (gre_name gre))) } gres | all isRecFldGRE gres && overload_ok -- Don't record usage for ambiguous selectors -- until we know which is meant -> return (Just (Right (map (FieldOcc (noLoc rdr_name) . gre_name) gres))) gres -> do { addNameClashErrRn rdr_name gres ; return (Just (Left (gre_name (head gres)))) } } -------------------------------------------------- -- Lookup in the Global RdrEnv of the module -------------------------------------------------- lookupGreRn_maybe :: RdrName -> RnM (Maybe GlobalRdrElt) -- Look up the RdrName in the GlobalRdrEnv -- Exactly one binding: records it as "used", return (Just gre) -- No bindings: return Nothing -- Many bindings: report "ambiguous", return an arbitrary (Just gre) -- (This API is a bit strange; lookupGRERn2_maybe is simpler. -- But it works and I don't want to fiddle too much.) -- Uses addUsedRdrName to record use and deprecations lookupGreRn_maybe rdr_name = do { env <- getGlobalRdrEnv ; case lookupGRE_RdrName rdr_name env of [] -> return Nothing [gre] -> do { addUsedGRE True gre ; return (Just gre) } gres -> do { addNameClashErrRn rdr_name gres ; traceRn (text "name clash" <+> (ppr rdr_name $$ ppr gres $$ ppr env)) ; return (Just (head gres)) } } lookupGreRn2_maybe :: RdrName -> RnM (Maybe GlobalRdrElt) -- Look up the RdrName in the GlobalRdrEnv -- Exactly one binding: record it as "used", return (Just gre) -- No bindings: report "not in scope", return Nothing -- Many bindings: report "ambiguous", return Nothing -- Uses addUsedRdrName to record use and deprecations lookupGreRn2_maybe rdr_name = do { env <- getGlobalRdrEnv ; case lookupGRE_RdrName rdr_name env of [] -> do { _ <- unboundName WL_Global rdr_name ; return Nothing } [gre] -> do { addUsedGRE True gre ; return (Just gre) } gres -> do { addNameClashErrRn rdr_name gres ; traceRn (text "name clash" <+> (ppr rdr_name $$ ppr gres $$ ppr env)) ; return Nothing } } lookupGreAvailRn :: RdrName -> RnM (Name, AvailInfo) -- Used in export lists -- If not found or ambiguous, add error message, and fake with UnboundName -- Uses addUsedRdrName to record use and deprecations lookupGreAvailRn rdr_name = do { mb_gre <- lookupGreRn2_maybe rdr_name ; case mb_gre of { Just gre -> return (gre_name gre, availFromGRE gre) ; Nothing -> do { traceRn (text "lookupGreRn" <+> ppr rdr_name) ; let name = mkUnboundNameRdr rdr_name ; return (name, avail name) } } } {- ********************************************************* * * Deprecations * * ********************************************************* Note [Handling of deprecations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * We report deprecations at each *occurrence* of the deprecated thing (see Trac #5867) * We do not report deprecations for locally-defined names. For a start, we may be exporting a deprecated thing. Also we may use a deprecated thing in the defn of another deprecated things. We may even use a deprecated thing in the defn of a non-deprecated thing, when changing a module's interface. * addUsedGREs: we do not report deprecations for sub-binders: - the ".." completion for records - the ".." in an export item 'T(..)' - the things exported by a module export 'module M' -} addUsedDataCons :: GlobalRdrEnv -> TyCon -> RnM () -- Remember use of in-scope data constructors (Trac #7969) addUsedDataCons rdr_env tycon = addUsedGREs [ gre | dc <- tyConDataCons tycon , gre : _ <- [lookupGRE_Name rdr_env (dataConName dc) ] ] addUsedGRE :: Bool -> GlobalRdrElt -> RnM () -- Called for both local and imported things -- Add usage *and* warn if deprecated addUsedGRE warn_if_deprec gre = do { when warn_if_deprec (warnIfDeprecated gre) ; unless (isLocalGRE gre) $ do { env <- getGblEnv ; traceRn (text "addUsedGRE" <+> ppr gre) ; updMutVar (tcg_used_gres env) (gre :) } } addUsedGREs :: [GlobalRdrElt] -> RnM () -- Record uses of any *imported* GREs -- Used for recording used sub-bndrs -- NB: no call to warnIfDeprecated; see Note [Handling of deprecations] addUsedGREs gres | null imp_gres = return () | otherwise = do { env <- getGblEnv ; traceRn (text "addUsedGREs" <+> ppr imp_gres) ; updMutVar (tcg_used_gres env) (imp_gres ++) } where imp_gres = filterOut isLocalGRE gres warnIfDeprecated :: GlobalRdrElt -> RnM () warnIfDeprecated gre@(GRE { gre_name = name, gre_imp = iss }) | (imp_spec : _) <- iss = do { dflags <- getDynFlags ; this_mod <- getModule ; when (wopt Opt_WarnWarningsDeprecations dflags && not (nameIsLocalOrFrom this_mod name)) $ -- See Note [Handling of deprecations] do { iface <- loadInterfaceForName doc name ; case lookupImpDeprec iface gre of Just txt -> addWarn (Reason Opt_WarnWarningsDeprecations) (mk_msg imp_spec txt) Nothing -> return () } } | otherwise = return () where occ = greOccName gre name_mod = ASSERT2( isExternalName name, ppr name ) nameModule name doc = text "The name" <+> quotes (ppr occ) <+> ptext (sLit "is mentioned explicitly") mk_msg imp_spec txt = sep [ sep [ text "In the use of" <+> pprNonVarNameSpace (occNameSpace occ) <+> quotes (ppr occ) , parens imp_msg <> colon ] , ppr txt ] where imp_mod = importSpecModule imp_spec imp_msg = text "imported from" <+> ppr imp_mod <> extra extra | imp_mod == moduleName name_mod = Outputable.empty | otherwise = text ", but defined in" <+> ppr name_mod lookupImpDeprec :: ModIface -> GlobalRdrElt -> Maybe WarningTxt lookupImpDeprec iface gre = mi_warn_fn iface (greOccName gre) `mplus` -- Bleat if the thing, case gre_par gre of -- or its parent, is warn'd ParentIs p -> mi_warn_fn iface (nameOccName p) FldParent { par_is = p } -> mi_warn_fn iface (nameOccName p) NoParent -> Nothing PatternSynonym -> Nothing {- Note [Used names with interface not loaded] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's (just) possible to find a used Name whose interface hasn't been loaded: a) It might be a WiredInName; in that case we may not load its interface (although we could). b) It might be GHC.Real.fromRational, or GHC.Num.fromInteger These are seen as "used" by the renamer (if -XRebindableSyntax) is on), but the typechecker may discard their uses if in fact the in-scope fromRational is GHC.Read.fromRational, (see tcPat.tcOverloadedLit), and the typechecker sees that the type is fixed, say, to GHC.Base.Float (see Inst.lookupSimpleInst). In that obscure case it won't force the interface in. In both cases we simply don't permit deprecations; this is, after all, wired-in stuff. ********************************************************* * * GHCi support * * ********************************************************* A qualified name on the command line can refer to any module at all: we try to load the interface if we don't already have it, just as if there was an "import qualified M" declaration for every module. If we fail we just return Nothing, rather than bleating about "attempting to use module ‘D’ (./D.hs) which is not loaded" which is what loadSrcInterface does. Note [Safe Haskell and GHCi] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We DONT do this Safe Haskell as we need to check imports. We can and should instead check the qualified import but at the moment this requires some refactoring so leave as a TODO -} lookupQualifiedNameGHCi :: RdrName -> RnM [Name] lookupQualifiedNameGHCi rdr_name = -- We want to behave as we would for a source file import here, -- and respect hiddenness of modules/packages, hence loadSrcInterface. do { dflags <- getDynFlags ; is_ghci <- getIsGHCi ; go_for_it dflags is_ghci } where go_for_it dflags is_ghci | Just (mod,occ) <- isQual_maybe rdr_name , is_ghci , gopt Opt_ImplicitImportQualified dflags -- Enables this GHCi behaviour , not (safeDirectImpsReq dflags) -- See Note [Safe Haskell and GHCi] = do { res <- loadSrcInterface_maybe doc mod False Nothing ; case res of Succeeded iface -> return [ name | avail <- mi_exports iface , name <- availNames avail , nameOccName name == occ ] _ -> -- Either we couldn't load the interface, or -- we could but we didn't find the name in it do { traceRn (text "lookupQualifiedNameGHCi" <+> ppr rdr_name) ; return [] } } | otherwise = do { traceRn (text "lookupQualifedNameGHCi: off" <+> ppr rdr_name) ; return [] } doc = text "Need to find" <+> ppr rdr_name {- Note [Looking up signature names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ lookupSigOccRn is used for type signatures and pragmas Is this valid? module A import M( f ) f :: Int -> Int f x = x It's clear that the 'f' in the signature must refer to A.f The Haskell98 report does not stipulate this, but it will! So we must treat the 'f' in the signature in the same way as the binding occurrence of 'f', using lookupBndrRn However, consider this case: import M( f ) f :: Int -> Int g x = x We don't want to say 'f' is out of scope; instead, we want to return the imported 'f', so that later on the reanamer will correctly report "misplaced type sig". Note [Signatures for top level things] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ data HsSigCtxt = ... | TopSigCtxt NameSet | .... * The NameSet says what is bound in this group of bindings. We can't use isLocalGRE from the GlobalRdrEnv, because of this: f x = x $( ...some TH splice... ) f :: Int -> Int When we encounter the signature for 'f', the binding for 'f' will be in the GlobalRdrEnv, and will be a LocalDef. Yet the signature is mis-placed * For type signatures the NameSet should be the names bound by the value bindings; for fixity declarations, the NameSet should also include class sigs and record selectors infix 3 `f` -- Yes, ok f :: C a => a -> a -- No, not ok class C a where f :: a -> a -} data HsSigCtxt = TopSigCtxt NameSet -- At top level, binding these names -- See Note [Signatures for top level things] | LocalBindCtxt NameSet -- In a local binding, binding these names | ClsDeclCtxt Name -- Class decl for this class | InstDeclCtxt NameSet -- Instance decl whose user-written method -- bindings are for these methods | HsBootCtxt NameSet -- Top level of a hs-boot file, binding these names | RoleAnnotCtxt NameSet -- A role annotation, with the names of all types -- in the group lookupSigOccRn :: HsSigCtxt -> Sig RdrName -> Located RdrName -> RnM (Located Name) lookupSigOccRn ctxt sig = lookupSigCtxtOccRn ctxt (hsSigDoc sig) -- | Lookup a name in relation to the names in a 'HsSigCtxt' lookupSigCtxtOccRn :: HsSigCtxt -> SDoc -- ^ description of thing we're looking up, -- like "type family" -> Located RdrName -> RnM (Located Name) lookupSigCtxtOccRn ctxt what = wrapLocM $ \ rdr_name -> do { mb_name <- lookupBindGroupOcc ctxt what rdr_name ; case mb_name of Left err -> do { addErr err; return (mkUnboundNameRdr rdr_name) } Right name -> return name } lookupBindGroupOcc :: HsSigCtxt -> SDoc -> RdrName -> RnM (Either MsgDoc Name) -- Looks up the RdrName, expecting it to resolve to one of the -- bound names passed in. If not, return an appropriate error message -- -- See Note [Looking up signature names] lookupBindGroupOcc ctxt what rdr_name | Just n <- isExact_maybe rdr_name = lookupExactOcc_either n -- allow for the possibility of missing Exacts; -- see Note [dataTcOccs and Exact Names] -- Maybe we should check the side conditions -- but it's a pain, and Exact things only show -- up when you know what you are doing | Just (rdr_mod, rdr_occ) <- isOrig_maybe rdr_name = do { n' <- lookupOrig rdr_mod rdr_occ ; return (Right n') } | otherwise = case ctxt of HsBootCtxt ns -> lookup_top (`elemNameSet` ns) TopSigCtxt ns -> lookup_top (`elemNameSet` ns) RoleAnnotCtxt ns -> lookup_top (`elemNameSet` ns) LocalBindCtxt ns -> lookup_group ns ClsDeclCtxt cls -> lookup_cls_op cls InstDeclCtxt ns -> lookup_top (`elemNameSet` ns) where lookup_cls_op cls = lookupSubBndrOcc True cls doc rdr_name where doc = text "method of class" <+> quotes (ppr cls) lookup_top keep_me = do { env <- getGlobalRdrEnv ; let all_gres = lookupGlobalRdrEnv env (rdrNameOcc rdr_name) ; case filter (keep_me . gre_name) all_gres of [] | null all_gres -> bale_out_with Outputable.empty | otherwise -> bale_out_with local_msg (gre:_) -> return (Right (gre_name gre)) } lookup_group bound_names -- Look in the local envt (not top level) = do { local_env <- getLocalRdrEnv ; case lookupLocalRdrEnv local_env rdr_name of Just n | n `elemNameSet` bound_names -> return (Right n) | otherwise -> bale_out_with local_msg Nothing -> bale_out_with Outputable.empty } bale_out_with msg = return (Left (sep [ text "The" <+> what <+> text "for" <+> quotes (ppr rdr_name) , nest 2 $ text "lacks an accompanying binding"] $$ nest 2 msg)) local_msg = parens $ text "The" <+> what <+> ptext (sLit "must be given where") <+> quotes (ppr rdr_name) <+> text "is declared" --------------- lookupLocalTcNames :: HsSigCtxt -> SDoc -> RdrName -> RnM [(RdrName, Name)] -- GHC extension: look up both the tycon and data con or variable. -- Used for top-level fixity signatures and deprecations. -- Complain if neither is in scope. -- See Note [Fixity signature lookup] lookupLocalTcNames ctxt what rdr_name = do { mb_gres <- mapM lookup (dataTcOccs rdr_name) ; let (errs, names) = splitEithers mb_gres ; when (null names) $ addErr (head errs) -- Bleat about one only ; return names } where lookup rdr = do { name <- lookupBindGroupOcc ctxt what rdr ; return (fmap ((,) rdr) name) } dataTcOccs :: RdrName -> [RdrName] -- Return both the given name and the same name promoted to the TcClsName -- namespace. This is useful when we aren't sure which we are looking at. -- See also Note [dataTcOccs and Exact Names] dataTcOccs rdr_name | isDataOcc occ || isVarOcc occ = [rdr_name, rdr_name_tc] | otherwise = [rdr_name] where occ = rdrNameOcc rdr_name rdr_name_tc = setRdrNameSpace rdr_name tcName {- Note [dataTcOccs and Exact Names] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Exact RdrNames can occur in code generated by Template Haskell, and generally those references are, well, exact. However, the TH `Name` type isn't expressive enough to always track the correct namespace information, so we sometimes get the right Unique but wrong namespace. Thus, we still have to do the double-lookup for Exact RdrNames. There is also an awkward situation for built-in syntax. Example in GHCi :info [] This parses as the Exact RdrName for nilDataCon, but we also want the list type constructor. Note that setRdrNameSpace on an Exact name requires the Name to be External, which it always is for built in syntax. ********************************************************* * * Fixities * * ********************************************************* Note [Fixity signature lookup] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A fixity declaration like infixr 2 ? can refer to a value-level operator, e.g.: (?) :: String -> String -> String or a type-level operator, like: data (?) a b = A a | B b so we extend the lookup of the reader name '?' to the TcClsName namespace, as well as the original namespace. The extended lookup is also used in other places, like resolution of deprecation declarations, and lookup of names in GHCi. -} -------------------------------- type MiniFixityEnv = FastStringEnv (Located Fixity) -- Mini fixity env for the names we're about -- to bind, in a single binding group -- -- It is keyed by the *FastString*, not the *OccName*, because -- the single fixity decl infix 3 T -- affects both the data constructor T and the type constrctor T -- -- We keep the location so that if we find -- a duplicate, we can report it sensibly -------------------------------- -- Used for nested fixity decls to bind names along with their fixities. -- the fixities are given as a UFM from an OccName's FastString to a fixity decl addLocalFixities :: MiniFixityEnv -> [Name] -> RnM a -> RnM a addLocalFixities mini_fix_env names thing_inside = extendFixityEnv (mapMaybe find_fixity names) thing_inside where find_fixity name = case lookupFsEnv mini_fix_env (occNameFS occ) of Just (L _ fix) -> Just (name, FixItem occ fix) Nothing -> Nothing where occ = nameOccName name {- -------------------------------- lookupFixity is a bit strange. * Nested local fixity decls are put in the local fixity env, which we find with getFixtyEnv * Imported fixities are found in the HIT or PIT * Top-level fixity decls in this module may be for Names that are either Global (constructors, class operations) or Local/Exported (everything else) (See notes with RnNames.getLocalDeclBinders for why we have this split.) We put them all in the local fixity environment -} lookupFixityRn :: Name -> RnM Fixity lookupFixityRn name = lookupFixityRn' name (nameOccName name) lookupFixityRn' :: Name -> OccName -> RnM Fixity lookupFixityRn' name = fmap snd . lookupFixityRn_help' name -- | 'lookupFixityRn_help' returns @(True, fixity)@ if it finds a 'Fixity' -- in a local environment or from an interface file. Otherwise, it returns -- @(False, fixity)@ (e.g., for unbound 'Name's or 'Name's without -- user-supplied fixity declarations). lookupFixityRn_help :: Name -> RnM (Bool, Fixity) lookupFixityRn_help name = lookupFixityRn_help' name (nameOccName name) lookupFixityRn_help' :: Name -> OccName -> RnM (Bool, Fixity) lookupFixityRn_help' name occ | isUnboundName name = return (False, Fixity (show minPrecedence) minPrecedence InfixL) -- Minimise errors from ubound names; eg -- a>0 `foo` b>0 -- where 'foo' is not in scope, should not give an error (Trac #7937) | otherwise = do { local_fix_env <- getFixityEnv ; case lookupNameEnv local_fix_env name of { Just (FixItem _ fix) -> return (True, fix) ; Nothing -> do { this_mod <- getModule ; if nameIsLocalOrFrom this_mod name -- Local (and interactive) names are all in the -- fixity env, and don't have entries in the HPT then return (False, defaultFixity) else lookup_imported } } } where lookup_imported -- For imported names, we have to get their fixities by doing a -- loadInterfaceForName, and consulting the Ifaces that comes back -- from that, because the interface file for the Name might not -- have been loaded yet. Why not? Suppose you import module A, -- which exports a function 'f', thus; -- module CurrentModule where -- import A( f ) -- module A( f ) where -- import B( f ) -- Then B isn't loaded right away (after all, it's possible that -- nothing from B will be used). When we come across a use of -- 'f', we need to know its fixity, and it's then, and only -- then, that we load B.hi. That is what's happening here. -- -- loadInterfaceForName will find B.hi even if B is a hidden module, -- and that's what we want. = do { iface <- loadInterfaceForName doc name ; let mb_fix = mi_fix_fn iface occ ; let msg = case mb_fix of Nothing -> text "looking up name" <+> ppr name <+> text "in iface, but found no fixity for it." <+> text "Using default fixity instead." Just f -> text "looking up name in iface and found:" <+> vcat [ppr name, ppr f] ; traceRn (text "lookupFixityRn_either:" <+> msg) ; return (maybe (False, defaultFixity) (\f -> (True, f)) mb_fix) } doc = text "Checking fixity for" <+> ppr name --------------- lookupTyFixityRn :: Located Name -> RnM Fixity lookupTyFixityRn (L _ n) = lookupFixityRn n -- | Look up the fixity of a (possibly ambiguous) occurrence of a record field -- selector. We use 'lookupFixityRn'' so that we can specifiy the 'OccName' as -- the field label, which might be different to the 'OccName' of the selector -- 'Name' if @DuplicateRecordFields@ is in use (Trac #1173). If there are -- multiple possible selectors with different fixities, generate an error. lookupFieldFixityRn :: AmbiguousFieldOcc Name -> RnM Fixity lookupFieldFixityRn (Unambiguous (L _ rdr) n) = lookupFixityRn' n (rdrNameOcc rdr) lookupFieldFixityRn (Ambiguous (L _ rdr) _) = get_ambiguous_fixity rdr where get_ambiguous_fixity :: RdrName -> RnM Fixity get_ambiguous_fixity rdr_name = do traceRn $ text "get_ambiguous_fixity" <+> ppr rdr_name rdr_env <- getGlobalRdrEnv let elts = lookupGRE_RdrName rdr_name rdr_env fixities <- groupBy ((==) `on` snd) . zip elts <$> mapM lookup_gre_fixity elts case fixities of -- There should always be at least one fixity. -- Something's very wrong if there are no fixity candidates, so panic [] -> panic "get_ambiguous_fixity: no candidates for a given RdrName" [ (_, fix):_ ] -> return fix ambigs -> addErr (ambiguous_fixity_err rdr_name ambigs) >> return (Fixity(show minPrecedence) minPrecedence InfixL) lookup_gre_fixity gre = lookupFixityRn' (gre_name gre) (greOccName gre) ambiguous_fixity_err rn ambigs = vcat [ text "Ambiguous fixity for record field" <+> quotes (ppr rn) , hang (text "Conflicts: ") 2 . vcat . map format_ambig $ concat ambigs ] format_ambig (elt, fix) = hang (ppr fix) 2 (pprNameProvenance elt) {- ********************************************************************* * * Role annotations * * ********************************************************************* -} type RoleAnnotEnv = NameEnv (LRoleAnnotDecl Name) mkRoleAnnotEnv :: [LRoleAnnotDecl Name] -> RoleAnnotEnv mkRoleAnnotEnv role_annot_decls = mkNameEnv [ (name, ra_decl) | ra_decl <- role_annot_decls , let name = roleAnnotDeclName (unLoc ra_decl) , not (isUnboundName name) ] -- Some of the role annots will be unbound; -- we don't wish to include these emptyRoleAnnotEnv :: RoleAnnotEnv emptyRoleAnnotEnv = emptyNameEnv lookupRoleAnnot :: RoleAnnotEnv -> Name -> Maybe (LRoleAnnotDecl Name) lookupRoleAnnot = lookupNameEnv getRoleAnnots :: [Name] -> RoleAnnotEnv -> ([LRoleAnnotDecl Name], RoleAnnotEnv) getRoleAnnots bndrs role_env = ( mapMaybe (lookupRoleAnnot role_env) bndrs , delListFromNameEnv role_env bndrs ) {- ************************************************************************ * * Rebindable names Dealing with rebindable syntax is driven by the Opt_RebindableSyntax dynamic flag. In "deriving" code we don't want to use rebindable syntax so we switch off the flag locally * * ************************************************************************ Haskell 98 says that when you say "3" you get the "fromInteger" from the Standard Prelude, regardless of what is in scope. However, to experiment with having a language that is less coupled to the standard prelude, we're trying a non-standard extension that instead gives you whatever "Prelude.fromInteger" happens to be in scope. Then you can import Prelude () import MyPrelude as Prelude to get the desired effect. At the moment this just happens for * fromInteger, fromRational on literals (in expressions and patterns) * negate (in expressions) * minus (arising from n+k patterns) * "do" notation We store the relevant Name in the HsSyn tree, in * HsIntegral/HsFractional/HsIsString * NegApp * NPlusKPat * HsDo respectively. Initially, we just store the "standard" name (PrelNames.fromIntegralName, fromRationalName etc), but the renamer changes this to the appropriate user name if Opt_NoImplicitPrelude is on. That is what lookupSyntaxName does. We treat the orignal (standard) names as free-vars too, because the type checker checks the type of the user thing against the type of the standard thing. -} lookupIfThenElse :: RnM (Maybe (SyntaxExpr Name), FreeVars) -- Different to lookupSyntaxName because in the non-rebindable -- case we desugar directly rather than calling an existing function -- Hence the (Maybe (SyntaxExpr Name)) return type lookupIfThenElse = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return (Nothing, emptyFVs) else do { ite <- lookupOccRn (mkVarUnqual (fsLit "ifThenElse")) ; return ( Just (mkRnSyntaxExpr ite) , unitFV ite ) } } lookupSyntaxName :: Name -- The standard name -> RnM (SyntaxExpr Name, FreeVars) -- Possibly a non-standard name lookupSyntaxName std_name = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return (mkRnSyntaxExpr std_name, emptyFVs) else -- Get the similarly named thing from the local environment do { usr_name <- lookupOccRn (mkRdrUnqual (nameOccName std_name)) ; return (mkRnSyntaxExpr usr_name, unitFV usr_name) } } lookupSyntaxNames :: [Name] -- Standard names -> RnM ([HsExpr Name], FreeVars) -- See comments with HsExpr.ReboundNames -- this works with CmdTop, which wants HsExprs, not SyntaxExprs lookupSyntaxNames std_names = do { rebindable_on <- xoptM LangExt.RebindableSyntax ; if not rebindable_on then return (map (HsVar . noLoc) std_names, emptyFVs) else do { usr_names <- mapM (lookupOccRn . mkRdrUnqual . nameOccName) std_names ; return (map (HsVar . noLoc) usr_names, mkFVs usr_names) } } {- ********************************************************* * * \subsection{Binding} * * ********************************************************* -} newLocalBndrRn :: Located RdrName -> RnM Name -- Used for non-top-level binders. These should -- never be qualified. newLocalBndrRn (L loc rdr_name) | Just name <- isExact_maybe rdr_name = return name -- This happens in code generated by Template Haskell -- See Note [Binders in Template Haskell] in Convert.hs | otherwise = do { unless (isUnqual rdr_name) (addErrAt loc (badQualBndrErr rdr_name)) ; uniq <- newUnique ; return (mkInternalName uniq (rdrNameOcc rdr_name) loc) } newLocalBndrsRn :: [Located RdrName] -> RnM [Name] newLocalBndrsRn = mapM newLocalBndrRn --------------------- bindLocatedLocalsRn :: [Located RdrName] -> ([Name] -> RnM a) -> RnM a bindLocatedLocalsRn rdr_names_w_loc enclosed_scope = do { checkDupRdrNames rdr_names_w_loc ; checkShadowedRdrNames rdr_names_w_loc -- Make fresh Names and extend the environment ; names <- newLocalBndrsRn rdr_names_w_loc ; bindLocalNames names (enclosed_scope names) } bindLocalNames :: [Name] -> RnM a -> RnM a bindLocalNames names enclosed_scope = do { lcl_env <- getLclEnv ; let th_level = thLevel (tcl_th_ctxt lcl_env) th_bndrs' = extendNameEnvList (tcl_th_bndrs lcl_env) [ (n, (NotTopLevel, th_level)) | n <- names ] rdr_env' = extendLocalRdrEnvList (tcl_rdr lcl_env) names ; setLclEnv (lcl_env { tcl_th_bndrs = th_bndrs' , tcl_rdr = rdr_env' }) enclosed_scope } bindLocalNamesFV :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars) bindLocalNamesFV names enclosed_scope = do { (result, fvs) <- bindLocalNames names enclosed_scope ; return (result, delFVs names fvs) } ------------------------------------- -- binLocalsFVRn is the same as bindLocalsRn -- except that it deals with free vars bindLocatedLocalsFV :: [Located RdrName] -> ([Name] -> RnM (a,FreeVars)) -> RnM (a, FreeVars) bindLocatedLocalsFV rdr_names enclosed_scope = bindLocatedLocalsRn rdr_names $ \ names -> do (thing, fvs) <- enclosed_scope names return (thing, delFVs names fvs) ------------------------------------- extendTyVarEnvFVRn :: [Name] -> RnM (a, FreeVars) -> RnM (a, FreeVars) -- This function is used only in rnSourceDecl on InstDecl extendTyVarEnvFVRn tyvars thing_inside = bindLocalNamesFV tyvars thing_inside ------------------------------------- checkDupRdrNames :: [Located RdrName] -> RnM () -- Check for duplicated names in a binding group checkDupRdrNames rdr_names_w_loc = mapM_ (dupNamesErr getLoc) dups where (_, dups) = removeDups (\n1 n2 -> unLoc n1 `compare` unLoc n2) rdr_names_w_loc checkDupNames :: [Name] -> RnM () -- Check for duplicated names in a binding group checkDupNames names = check_dup_names (filterOut isSystemName names) -- See Note [Binders in Template Haskell] in Convert check_dup_names :: [Name] -> RnM () check_dup_names names = mapM_ (dupNamesErr nameSrcSpan) dups where (_, dups) = removeDups (\n1 n2 -> nameOccName n1 `compare` nameOccName n2) names --------------------- checkShadowedRdrNames :: [Located RdrName] -> RnM () checkShadowedRdrNames loc_rdr_names = do { envs <- getRdrEnvs ; checkShadowedOccs envs get_loc_occ filtered_rdrs } where filtered_rdrs = filterOut (isExact . unLoc) loc_rdr_names -- See Note [Binders in Template Haskell] in Convert get_loc_occ (L loc rdr) = (loc,rdrNameOcc rdr) checkDupAndShadowedNames :: (GlobalRdrEnv, LocalRdrEnv) -> [Name] -> RnM () checkDupAndShadowedNames envs names = do { check_dup_names filtered_names ; checkShadowedOccs envs get_loc_occ filtered_names } where filtered_names = filterOut isSystemName names -- See Note [Binders in Template Haskell] in Convert get_loc_occ name = (nameSrcSpan name, nameOccName name) ------------------------------------- checkShadowedOccs :: (GlobalRdrEnv, LocalRdrEnv) -> (a -> (SrcSpan, OccName)) -> [a] -> RnM () checkShadowedOccs (global_env,local_env) get_loc_occ ns = whenWOptM Opt_WarnNameShadowing $ do { traceRn (text "shadow" <+> ppr (map get_loc_occ ns)) ; mapM_ check_shadow ns } where check_shadow n | startsWithUnderscore occ = return () -- Do not report shadowing for "_x" -- See Trac #3262 | Just n <- mb_local = complain [text "bound at" <+> ppr (nameSrcLoc n)] | otherwise = do { gres' <- filterM is_shadowed_gre gres ; complain (map pprNameProvenance gres') } where (loc,occ) = get_loc_occ n mb_local = lookupLocalRdrOcc local_env occ gres = lookupGRE_RdrName (mkRdrUnqual occ) global_env -- Make an Unqualified RdrName and look that up, so that -- we don't find any GREs that are in scope qualified-only complain [] = return () complain pp_locs = addWarnAt (Reason Opt_WarnNameShadowing) loc (shadowedNameWarn occ pp_locs) is_shadowed_gre :: GlobalRdrElt -> RnM Bool -- Returns False for record selectors that are shadowed, when -- punning or wild-cards are on (cf Trac #2723) is_shadowed_gre gre | isRecFldGRE gre = do { dflags <- getDynFlags ; return $ not (xopt LangExt.RecordPuns dflags || xopt LangExt.RecordWildCards dflags) } is_shadowed_gre _other = return True {- ************************************************************************ * * What to do when a lookup fails * * ************************************************************************ -} data WhereLooking = WL_Any -- Any binding | WL_Global -- Any top-level binding (local or imported) | WL_LocalTop -- Any top-level binding in this module reportUnboundName :: RdrName -> RnM Name reportUnboundName rdr = unboundName WL_Any rdr unboundName :: WhereLooking -> RdrName -> RnM Name unboundName wl rdr = unboundNameX wl rdr Outputable.empty unboundNameX :: WhereLooking -> RdrName -> SDoc -> RnM Name unboundNameX where_look rdr_name extra = do { dflags <- getDynFlags ; let show_helpful_errors = gopt Opt_HelpfulErrors dflags what = pprNonVarNameSpace (occNameSpace (rdrNameOcc rdr_name)) err = unknownNameErr what rdr_name $$ extra ; if not show_helpful_errors then addErr err else do { local_env <- getLocalRdrEnv ; global_env <- getGlobalRdrEnv ; impInfo <- getImports ; let suggestions = unknownNameSuggestions_ where_look dflags global_env local_env impInfo rdr_name ; addErr (err $$ suggestions) } ; return (mkUnboundNameRdr rdr_name) } unknownNameErr :: SDoc -> RdrName -> SDoc unknownNameErr what rdr_name = vcat [ hang (text "Not in scope:") 2 (what <+> quotes (ppr rdr_name)) , extra ] where extra | rdr_name == forall_tv_RDR = perhapsForallMsg | otherwise = Outputable.empty type HowInScope = Either SrcSpan ImpDeclSpec -- Left loc => locally bound at loc -- Right ispec => imported as specified by ispec -- | Called from the typechecker (TcErrors) when we find an unbound variable unknownNameSuggestions :: DynFlags -> GlobalRdrEnv -> LocalRdrEnv -> ImportAvails -> RdrName -> SDoc unknownNameSuggestions = unknownNameSuggestions_ WL_Any unknownNameSuggestions_ :: WhereLooking -> DynFlags -> GlobalRdrEnv -> LocalRdrEnv -> ImportAvails -> RdrName -> SDoc unknownNameSuggestions_ where_look dflags global_env local_env imports tried_rdr_name = similarNameSuggestions where_look dflags global_env local_env tried_rdr_name $$ importSuggestions dflags imports tried_rdr_name similarNameSuggestions :: WhereLooking -> DynFlags -> GlobalRdrEnv -> LocalRdrEnv -> RdrName -> SDoc similarNameSuggestions where_look dflags global_env local_env tried_rdr_name = case suggest of [] -> Outputable.empty [p] -> perhaps <+> pp_item p ps -> sep [ perhaps <+> text "one of these:" , nest 2 (pprWithCommas pp_item ps) ] where all_possibilities :: [(String, (RdrName, HowInScope))] all_possibilities = [ (showPpr dflags r, (r, Left loc)) | (r,loc) <- local_possibilities local_env ] ++ [ (showPpr dflags r, rp) | (r, rp) <- global_possibilities global_env ] suggest = fuzzyLookup (showPpr dflags tried_rdr_name) all_possibilities perhaps = text "Perhaps you meant" pp_item :: (RdrName, HowInScope) -> SDoc pp_item (rdr, Left loc) = pp_ns rdr <+> quotes (ppr rdr) <+> loc' -- Locally defined where loc' = case loc of UnhelpfulSpan l -> parens (ppr l) RealSrcSpan l -> parens (text "line" <+> int (srcSpanStartLine l)) pp_item (rdr, Right is) = pp_ns rdr <+> quotes (ppr rdr) <+> -- Imported parens (text "imported from" <+> ppr (is_mod is)) pp_ns :: RdrName -> SDoc pp_ns rdr | ns /= tried_ns = pprNameSpace ns | otherwise = Outputable.empty where ns = rdrNameSpace rdr tried_occ = rdrNameOcc tried_rdr_name tried_is_sym = isSymOcc tried_occ tried_ns = occNameSpace tried_occ tried_is_qual = isQual tried_rdr_name correct_name_space occ = nameSpacesRelated (occNameSpace occ) tried_ns && isSymOcc occ == tried_is_sym -- Treat operator and non-operators as non-matching -- This heuristic avoids things like -- Not in scope 'f'; perhaps you meant '+' (from Prelude) local_ok = case where_look of { WL_Any -> True; _ -> False } local_possibilities :: LocalRdrEnv -> [(RdrName, SrcSpan)] local_possibilities env | tried_is_qual = [] | not local_ok = [] | otherwise = [ (mkRdrUnqual occ, nameSrcSpan name) | name <- localRdrEnvElts env , let occ = nameOccName name , correct_name_space occ] gre_ok :: GlobalRdrElt -> Bool gre_ok = case where_look of WL_LocalTop -> isLocalGRE _ -> \_ -> True global_possibilities :: GlobalRdrEnv -> [(RdrName, (RdrName, HowInScope))] global_possibilities global_env | tried_is_qual = [ (rdr_qual, (rdr_qual, how)) | gre <- globalRdrEnvElts global_env , gre_ok gre , let name = gre_name gre occ = nameOccName name , correct_name_space occ , (mod, how) <- quals_in_scope gre , let rdr_qual = mkRdrQual mod occ ] | otherwise = [ (rdr_unqual, pair) | gre <- globalRdrEnvElts global_env , gre_ok gre , let name = gre_name gre occ = nameOccName name rdr_unqual = mkRdrUnqual occ , correct_name_space occ , pair <- case (unquals_in_scope gre, quals_only gre) of (how:_, _) -> [ (rdr_unqual, how) ] ([], pr:_) -> [ pr ] -- See Note [Only-quals] ([], []) -> [] ] -- Note [Only-quals] -- The second alternative returns those names with the same -- OccName as the one we tried, but live in *qualified* imports -- e.g. if you have: -- -- > import qualified Data.Map as Map -- > foo :: Map -- -- then we suggest @Map.Map@. -------------------- unquals_in_scope :: GlobalRdrElt -> [HowInScope] unquals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is }) | lcl = [ Left (nameSrcSpan n) ] | otherwise = [ Right ispec | i <- is, let ispec = is_decl i , not (is_qual ispec) ] -------------------- quals_in_scope :: GlobalRdrElt -> [(ModuleName, HowInScope)] -- Ones for which the qualified version is in scope quals_in_scope (GRE { gre_name = n, gre_lcl = lcl, gre_imp = is }) | lcl = case nameModule_maybe n of Nothing -> [] Just m -> [(moduleName m, Left (nameSrcSpan n))] | otherwise = [ (is_as ispec, Right ispec) | i <- is, let ispec = is_decl i ] -------------------- quals_only :: GlobalRdrElt -> [(RdrName, HowInScope)] -- Ones for which *only* the qualified version is in scope quals_only (GRE { gre_name = n, gre_imp = is }) = [ (mkRdrQual (is_as ispec) (nameOccName n), Right ispec) | i <- is, let ispec = is_decl i, is_qual ispec ] -- | Generate helpful suggestions if a qualified name Mod.foo is not in scope. importSuggestions :: DynFlags -> ImportAvails -> RdrName -> SDoc importSuggestions _dflags imports rdr_name | not (isQual rdr_name || isUnqual rdr_name) = Outputable.empty | null interesting_imports , Just name <- mod_name = hsep [ text "No module named" , quotes (ppr name) , text "is imported." ] | is_qualified , null helpful_imports , [(mod,_)] <- interesting_imports = hsep [ text "Module" , quotes (ppr mod) , text "does not export" , quotes (ppr occ_name) <> dot ] | is_qualified , null helpful_imports , mods <- map fst interesting_imports = hsep [ text "Neither" , quotedListWithNor (map ppr mods) , text "exports" , quotes (ppr occ_name) <> dot ] | [(mod,imv)] <- helpful_imports_non_hiding = fsep [ text "Perhaps you want to add" , quotes (ppr occ_name) , text "to the import list" , text "in the import of" , quotes (ppr mod) , parens (ppr (imv_span imv)) <> dot ] | not (null helpful_imports_non_hiding) = fsep [ text "Perhaps you want to add" , quotes (ppr occ_name) , text "to one of these import lists:" ] $$ nest 2 (vcat [ quotes (ppr mod) <+> parens (ppr (imv_span imv)) | (mod,imv) <- helpful_imports_non_hiding ]) | [(mod,imv)] <- helpful_imports_hiding = fsep [ text "Perhaps you want to remove" , quotes (ppr occ_name) , text "from the explicit hiding list" , text "in the import of" , quotes (ppr mod) , parens (ppr (imv_span imv)) <> dot ] | not (null helpful_imports_hiding) = fsep [ text "Perhaps you want to remove" , quotes (ppr occ_name) , text "from the hiding clauses" , text "in one of these imports:" ] $$ nest 2 (vcat [ quotes (ppr mod) <+> parens (ppr (imv_span imv)) | (mod,imv) <- helpful_imports_hiding ]) | otherwise = Outputable.empty where is_qualified = isQual rdr_name (mod_name, occ_name) = case rdr_name of Unqual occ_name -> (Nothing, occ_name) Qual mod_name occ_name -> (Just mod_name, occ_name) _ -> error "importSuggestions: dead code" -- What import statements provide "Mod" at all -- or, if this is an unqualified name, are not qualified imports interesting_imports = [ (mod, imp) | (mod, mod_imports) <- moduleEnvToList (imp_mods imports) , Just imp <- return $ pick mod_imports ] -- We want to keep only one for each original module; preferably one with an -- explicit import list (for no particularly good reason) pick :: [ImportedModsVal] -> Maybe ImportedModsVal pick = listToMaybe . sortBy (compare `on` prefer) . filter select where select imv = case mod_name of Just name -> imv_name imv == name Nothing -> not (imv_qualified imv) prefer imv = (imv_is_hiding imv, imv_span imv) -- Which of these would export a 'foo' -- (all of these are restricted imports, because if they were not, we -- wouldn't have an out-of-scope error in the first place) helpful_imports = filter helpful interesting_imports where helpful (_,imv) = not . null $ lookupGlobalRdrEnv (imv_all_exports imv) occ_name -- Which of these do that because of an explicit hiding list resp. an -- explicit import list (helpful_imports_hiding, helpful_imports_non_hiding) = partition (imv_is_hiding . snd) helpful_imports {- ************************************************************************ * * \subsection{Free variable manipulation} * * ************************************************************************ -} -- A useful utility addFvRn :: FreeVars -> RnM (thing, FreeVars) -> RnM (thing, FreeVars) addFvRn fvs1 thing_inside = do { (res, fvs2) <- thing_inside ; return (res, fvs1 `plusFV` fvs2) } mapFvRn :: (a -> RnM (b, FreeVars)) -> [a] -> RnM ([b], FreeVars) mapFvRn f xs = do stuff <- mapM f xs case unzip stuff of (ys, fvs_s) -> return (ys, plusFVs fvs_s) mapMaybeFvRn :: (a -> RnM (b, FreeVars)) -> Maybe a -> RnM (Maybe b, FreeVars) mapMaybeFvRn _ Nothing = return (Nothing, emptyFVs) mapMaybeFvRn f (Just x) = do { (y, fvs) <- f x; return (Just y, fvs) } -- because some of the rename functions are CPSed: -- maps the function across the list from left to right; -- collects all the free vars into one set mapFvRnCPS :: (a -> (b -> RnM c) -> RnM c) -> [a] -> ([b] -> RnM c) -> RnM c mapFvRnCPS _ [] cont = cont [] mapFvRnCPS f (x:xs) cont = f x $ \ x' -> mapFvRnCPS f xs $ \ xs' -> cont (x':xs') {- ************************************************************************ * * \subsection{Envt utility functions} * * ************************************************************************ -} warnUnusedTopBinds :: [GlobalRdrElt] -> RnM () warnUnusedTopBinds gres = whenWOptM Opt_WarnUnusedTopBinds $ do env <- getGblEnv let isBoot = tcg_src env == HsBootFile let noParent gre = case gre_par gre of NoParent -> True PatternSynonym -> True _ -> False -- Don't warn about unused bindings with parents in -- .hs-boot files, as you are sometimes required to give -- unused bindings (trac #3449). -- HOWEVER, in a signature file, you are never obligated to put a -- definition in the main text. Thus, if you define something -- and forget to export it, we really DO want to warn. gres' = if isBoot then filter noParent gres else gres warnUnusedGREs gres' warnUnusedLocalBinds, warnUnusedMatches, warnUnusedTypePatterns :: [Name] -> FreeVars -> RnM () warnUnusedLocalBinds = check_unused Opt_WarnUnusedLocalBinds warnUnusedMatches = check_unused Opt_WarnUnusedMatches warnUnusedTypePatterns = check_unused Opt_WarnUnusedTypePatterns check_unused :: WarningFlag -> [Name] -> FreeVars -> RnM () check_unused flag bound_names used_names = whenWOptM flag (warnUnused flag (filterOut (`elemNameSet` used_names) bound_names)) ------------------------- -- Helpers warnUnusedGREs :: [GlobalRdrElt] -> RnM () warnUnusedGREs gres = mapM_ warnUnusedGRE gres warnUnused :: WarningFlag -> [Name] -> RnM () warnUnused flag names = do fld_env <- mkFieldEnv <$> getGlobalRdrEnv mapM_ (warnUnused1 flag fld_env) names warnUnused1 :: WarningFlag -> NameEnv (FieldLabelString, Name) -> Name -> RnM () warnUnused1 flag fld_env name = when (reportable name) $ addUnusedWarning flag occ (nameSrcSpan name) (text "Defined but not used") where occ = case lookupNameEnv fld_env name of Just (fl, _) -> mkVarOccFS fl Nothing -> nameOccName name warnUnusedGRE :: GlobalRdrElt -> RnM () warnUnusedGRE gre@(GRE { gre_name = name, gre_lcl = lcl, gre_imp = is }) | lcl = do fld_env <- mkFieldEnv <$> getGlobalRdrEnv warnUnused1 Opt_WarnUnusedTopBinds fld_env name | otherwise = when (reportable name) (mapM_ warn is) where occ = greOccName gre warn spec = addUnusedWarning Opt_WarnUnusedTopBinds occ span msg where span = importSpecLoc spec pp_mod = quotes (ppr (importSpecModule spec)) msg = text "Imported from" <+> pp_mod <+> ptext (sLit "but not used") -- | Make a map from selector names to field labels and parent tycon -- names, to be used when reporting unused record fields. mkFieldEnv :: GlobalRdrEnv -> NameEnv (FieldLabelString, Name) mkFieldEnv rdr_env = mkNameEnv [ (gre_name gre, (lbl, par_is (gre_par gre))) | gres <- occEnvElts rdr_env , gre <- gres , Just lbl <- [greLabel gre] ] reportable :: Name -> Bool reportable name | isWiredInName name = False -- Don't report unused wired-in names -- Otherwise we get a zillion warnings -- from Data.Tuple | otherwise = not (startsWithUnderscore (nameOccName name)) addUnusedWarning :: WarningFlag -> OccName -> SrcSpan -> SDoc -> RnM () addUnusedWarning flag occ span msg = addWarnAt (Reason flag) span $ sep [msg <> colon, nest 2 $ pprNonVarNameSpace (occNameSpace occ) <+> quotes (ppr occ)] addNameClashErrRn :: RdrName -> [GlobalRdrElt] -> RnM () addNameClashErrRn rdr_name gres | all isLocalGRE gres && not (all isRecFldGRE gres) -- If there are two or more *local* defns, we'll have reported = return () -- that already, and we don't want an error cascade | otherwise = addErr (vcat [text "Ambiguous occurrence" <+> quotes (ppr rdr_name), text "It could refer to" <+> vcat (msg1 : msgs)]) where (np1:nps) = gres msg1 = ptext (sLit "either") <+> mk_ref np1 msgs = [text " or" <+> mk_ref np | np <- nps] mk_ref gre = sep [nom <> comma, pprNameProvenance gre] where nom = case gre_par gre of FldParent { par_lbl = Just lbl } -> text "the field" <+> quotes (ppr lbl) _ -> quotes (ppr (gre_name gre)) shadowedNameWarn :: OccName -> [SDoc] -> SDoc shadowedNameWarn occ shadowed_locs = sep [text "This binding for" <+> quotes (ppr occ) <+> text "shadows the existing binding" <> plural shadowed_locs, nest 2 (vcat shadowed_locs)] perhapsForallMsg :: SDoc perhapsForallMsg = vcat [ text "Perhaps you intended to use ExplicitForAll or similar flag" , text "to enable explicit-forall syntax: forall <tvs>. <type>"] unknownSubordinateErr :: SDoc -> RdrName -> SDoc unknownSubordinateErr doc op -- Doc is "method of class" or -- "field of constructor" = quotes (ppr op) <+> text "is not a (visible)" <+> doc badOrigBinding :: RdrName -> SDoc badOrigBinding name = text "Illegal binding of built-in syntax:" <+> ppr (rdrNameOcc name) -- The rdrNameOcc is because we don't want to print Prelude.(,) dupNamesErr :: Outputable n => (n -> SrcSpan) -> [n] -> RnM () dupNamesErr get_loc names = addErrAt big_loc $ vcat [text "Conflicting definitions for" <+> quotes (ppr (head names)), locations] where locs = map get_loc names big_loc = foldr1 combineSrcSpans locs locations = text "Bound at:" <+> vcat (map ppr (sort locs)) kindSigErr :: Outputable a => a -> SDoc kindSigErr thing = hang (text "Illegal kind signature for" <+> quotes (ppr thing)) 2 (text "Perhaps you intended to use KindSignatures") badQualBndrErr :: RdrName -> SDoc badQualBndrErr rdr_name = text "Qualified name in binding position:" <+> ppr rdr_name opDeclErr :: RdrName -> SDoc opDeclErr n = hang (text "Illegal declaration of a type or class operator" <+> quotes (ppr n)) 2 (text "Use TypeOperators to declare operators in type and declarations") checkTupSize :: Int -> RnM () checkTupSize tup_size | tup_size <= mAX_TUPLE_SIZE = return () | otherwise = addErr (sep [text "A" <+> int tup_size <> ptext (sLit "-tuple is too large for GHC"), nest 2 (parens (text "max size is" <+> int mAX_TUPLE_SIZE)), nest 2 (text "Workaround: use nested tuples or define a data type")]) {- ************************************************************************ * * \subsection{Contexts for renaming errors} * * ************************************************************************ -} -- AZ:TODO: Change these all to be Name instead of RdrName. -- Merge TcType.UserTypeContext in to it. data HsDocContext = TypeSigCtx SDoc | PatCtx | SpecInstSigCtx | DefaultDeclCtx | ForeignDeclCtx (Located RdrName) | DerivDeclCtx | RuleCtx FastString | TyDataCtx (Located RdrName) | TySynCtx (Located RdrName) | TyFamilyCtx (Located RdrName) | FamPatCtx (Located RdrName) -- The patterns of a type/data family instance | ConDeclCtx [Located Name] | ClassDeclCtx (Located RdrName) | ExprWithTySigCtx | TypBrCtx | HsTypeCtx | GHCiCtx | SpliceTypeCtx (LHsType RdrName) | ClassInstanceCtx | VectDeclCtx (Located RdrName) | GenericCtx SDoc -- Maybe we want to use this more! withHsDocContext :: HsDocContext -> SDoc -> SDoc withHsDocContext ctxt doc = doc $$ inHsDocContext ctxt inHsDocContext :: HsDocContext -> SDoc inHsDocContext ctxt = text "In" <+> pprHsDocContext ctxt pprHsDocContext :: HsDocContext -> SDoc pprHsDocContext (GenericCtx doc) = doc pprHsDocContext (TypeSigCtx doc) = text "the type signature for" <+> doc pprHsDocContext PatCtx = text "a pattern type-signature" pprHsDocContext SpecInstSigCtx = text "a SPECIALISE instance pragma" pprHsDocContext DefaultDeclCtx = text "a `default' declaration" pprHsDocContext DerivDeclCtx = text "a deriving declaration" pprHsDocContext (RuleCtx name) = text "the transformation rule" <+> ftext name pprHsDocContext (TyDataCtx tycon) = text "the data type declaration for" <+> quotes (ppr tycon) pprHsDocContext (FamPatCtx tycon) = text "a type pattern of family instance for" <+> quotes (ppr tycon) pprHsDocContext (TySynCtx name) = text "the declaration for type synonym" <+> quotes (ppr name) pprHsDocContext (TyFamilyCtx name) = text "the declaration for type family" <+> quotes (ppr name) pprHsDocContext (ClassDeclCtx name) = text "the declaration for class" <+> quotes (ppr name) pprHsDocContext ExprWithTySigCtx = text "an expression type signature" pprHsDocContext TypBrCtx = text "a Template-Haskell quoted type" pprHsDocContext HsTypeCtx = text "a type argument" pprHsDocContext GHCiCtx = text "GHCi input" pprHsDocContext (SpliceTypeCtx hs_ty) = text "the spliced type" <+> quotes (ppr hs_ty) pprHsDocContext ClassInstanceCtx = text "TcSplice.reifyInstances" pprHsDocContext (ForeignDeclCtx name) = text "the foreign declaration for" <+> quotes (ppr name) pprHsDocContext (ConDeclCtx [name]) = text "the definition of data constructor" <+> quotes (ppr name) pprHsDocContext (ConDeclCtx names) = text "the definition of data constructors" <+> interpp'SP names pprHsDocContext (VectDeclCtx tycon) = text "the VECTORISE pragma for type constructor" <+> quotes (ppr tycon)
tjakway/ghcjvm
compiler/rename/RnEnv.hs
Haskell
bsd-3-clause
97,750
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} module Test.Pos.Chain.Txp.Bi ( tests ) where import Universum import qualified Data.Map as M import Data.Typeable (typeRep) import Hedgehog (Gen, Property) import qualified Hedgehog as H import qualified Hedgehog.Gen as Gen import Pos.Binary.Class (Bi, Case (..), LengthOf, SizeOverride (..), szCases) import Pos.Chain.Txp (Tx (..), TxAux (..), TxIn (..), TxInWitness (..), TxOut (..), TxOutAux (..), TxSigData (..)) import Pos.Core.Attributes (Attributes (..), mkAttributes) import Pos.Core.Common (AddrAttributes (..), Script (..)) import Pos.Crypto (ProtocolMagic (..), ProtocolMagicId (..), RequiresNetworkMagic (..), SignTag (..), Signature, sign) import Test.Pos.Binary.Helpers (SizeTestConfig (..), scfg, sizeTest) import Test.Pos.Binary.Helpers.GoldenRoundTrip (goldenTestBi, roundTripsBiBuildable, roundTripsBiShow) import Test.Pos.Chain.Txp.Example (exampleHashTx, exampleRedeemSignature, exampleTxId, exampleTxInList, exampleTxInUnknown, exampleTxInUtxo, exampleTxOut, exampleTxOutList, exampleTxProof, exampleTxSig, exampleTxSigData, exampleTxWitness) import Test.Pos.Chain.Txp.Gen (genTx, genTxAttributes, genTxAux, genTxHash, genTxId, genTxIn, genTxInList, genTxInWitness, genTxOut, genTxOutAux, genTxOutList, genTxPayload, genTxProof, genTxSig, genTxSigData, genTxWitness) import Test.Pos.Core.ExampleHelpers (examplePublicKey, exampleRedeemPublicKey, exampleSecretKey, feedPM) import Test.Pos.Util.Golden (discoverGolden, eachOf) import Test.Pos.Util.Tripping (discoverRoundTrip) -------------------------------------------------------------------------------- -- Tx -------------------------------------------------------------------------------- golden_Tx :: Property golden_Tx = goldenTestBi tx "test/golden/bi/txp/Tx" where tx = UnsafeTx exampleTxInList exampleTxOutList (mkAttributes ()) roundTripTx :: Property roundTripTx = eachOf 50 genTx roundTripsBiBuildable -------------------------------------------------------------------------------- -- TxAttributes -------------------------------------------------------------------------------- golden_TxAttributes :: Property golden_TxAttributes = goldenTestBi txA "test/golden/bi/txp/TxAttributes" where txA = mkAttributes () roundTripTxAttributes :: Property roundTripTxAttributes = eachOf 10 genTxAttributes roundTripsBiBuildable -------------------------------------------------------------------------------- -- TxAux -------------------------------------------------------------------------------- roundTripTxAux :: Property roundTripTxAux = eachOf 100 (feedPM genTxAux) roundTripsBiBuildable -------------------------------------------------------------------------------- -- Tx Hash -------------------------------------------------------------------------------- golden_HashTx :: Property golden_HashTx = goldenTestBi exampleHashTx "test/golden/bi/txp/HashTx" roundTripHashTx :: Property roundTripHashTx = eachOf 50 genTxHash roundTripsBiBuildable -------------------------------------------------------------------------------- -- TxIn -------------------------------------------------------------------------------- golden_TxInUtxo :: Property golden_TxInUtxo = goldenTestBi exampleTxInUtxo "test/golden/bi/txp/TxIn_Utxo" golden_TxInUnknown :: Property golden_TxInUnknown = goldenTestBi exampleTxInUnknown "test/golden/bi/txp/TxIn_Unknown" roundTripTxIn :: Property roundTripTxIn = eachOf 100 genTxIn roundTripsBiBuildable -------------------------------------------------------------------------------- -- TxId -------------------------------------------------------------------------------- golden_TxId :: Property golden_TxId = goldenTestBi exampleTxId "test/golden/bi/txp/TxId" roundTripTxId :: Property roundTripTxId = eachOf 50 genTxId roundTripsBiBuildable -------------------------------------------------------------------------------- -- TxInList -------------------------------------------------------------------------------- golden_TxInList :: Property golden_TxInList = goldenTestBi exampleTxInList "test/golden/bi/txp/TxInList" roundTripTxInList :: Property roundTripTxInList = eachOf 50 genTxInList roundTripsBiShow -------------------------------------------------------------------------------- -- TxInWitness -------------------------------------------------------------------------------- golden_PkWitness :: Property golden_PkWitness = goldenTestBi pkWitness "test/golden/bi/txp/TxInWitness_PkWitness" where pkWitness = PkWitness examplePublicKey exampleTxSig golden_ScriptWitness :: Property golden_ScriptWitness = goldenTestBi scriptWitness "test/golden/bi/txp/TxInWitness_ScriptWitness" where scriptWitness = ScriptWitness validatorScript redeemerScript validatorScript = Script 47 "serialized script" redeemerScript = Script 47 "serialized script" golden_RedeemWitness :: Property golden_RedeemWitness = goldenTestBi redeemWitness "test/golden/bi/txp/TxInWitness_RedeemWitness" where redeemWitness = RedeemWitness exampleRedeemPublicKey exampleRedeemSignature golden_UnknownWitnessType :: Property golden_UnknownWitnessType = goldenTestBi unkWitType "test/golden/bi/txp/TxInWitness_UnknownWitnessType" where unkWitType = UnknownWitnessType 47 "forty seven" roundTripTxInWitness :: Property roundTripTxInWitness = eachOf 50 (feedPM genTxInWitness) roundTripsBiBuildable -------------------------------------------------------------------------------- -- TxOutList -------------------------------------------------------------------------------- golden_TxOutList :: Property golden_TxOutList = goldenTestBi exampleTxOutList "test/golden/bi/txp/TxOutList" roundTripTxOutList :: Property roundTripTxOutList = eachOf 50 genTxOutList roundTripsBiShow -------------------------------------------------------------------------------- -- TxOut -------------------------------------------------------------------------------- golden_TxOut :: Property golden_TxOut = goldenTestBi exampleTxOut "test/golden/bi/txp/TxOut" roundTripTxOut :: Property roundTripTxOut = eachOf 50 genTxOut roundTripsBiBuildable -------------------------------------------------------------------------------- -- TxOutAux -------------------------------------------------------------------------------- golden_TxOutAux :: Property golden_TxOutAux = goldenTestBi txOutAux "test/golden/bi/txp/TxOutAux" where txOutAux = TxOutAux exampleTxOut roundTripTxOutAux :: Property roundTripTxOutAux = eachOf 50 genTxOutAux roundTripsBiBuildable -------------------------------------------------------------------------------- -- TxPayload -------------------------------------------------------------------------------- roundTripTxPayload :: Property roundTripTxPayload = eachOf 50 (feedPM genTxPayload) roundTripsBiShow -------------------------------------------------------------------------------- -- TxProof -------------------------------------------------------------------------------- golden_TxProof :: Property golden_TxProof = goldenTestBi exampleTxProof "test/golden/bi/txp/TxProof" roundTripTxProof :: Property roundTripTxProof = eachOf 50 (feedPM genTxProof) roundTripsBiBuildable -------------------------------------------------------------------------------- -- TxSig -------------------------------------------------------------------------------- golden_TxSig :: Property golden_TxSig = goldenTestBi txSigGold "test/golden/bi/txp/TxSig" where txSigGold = sign pm SignForTestingOnly exampleSecretKey exampleTxSigData pm = ProtocolMagic { getProtocolMagicId = ProtocolMagicId 0 , getRequiresNetworkMagic = RequiresNoMagic } roundTripTxSig :: Property roundTripTxSig = eachOf 50 (feedPM genTxSig) roundTripsBiBuildable -------------------------------------------------------------------------------- -- TxSigData -------------------------------------------------------------------------------- golden_TxSigData :: Property golden_TxSigData = goldenTestBi exampleTxSigData "test/golden/bi/txp/TxSigData" roundTripTxSigData :: Property roundTripTxSigData = eachOf 50 genTxSigData roundTripsBiShow -------------------------------------------------------------------------------- -- TxWitness -------------------------------------------------------------------------------- golden_TxWitness :: Property golden_TxWitness = goldenTestBi exampleTxWitness "test/golden/bi/txp/TxWitness" roundTripTxWitness :: Property roundTripTxWitness = eachOf 20 (feedPM genTxWitness) roundTripsBiShow sizeEstimates :: H.Group sizeEstimates = let check :: (Show a, Bi a) => Gen a -> Property check g = sizeTest $ scfg { gen = g } pm = ProtocolMagic { getProtocolMagicId = ProtocolMagicId 0 , getRequiresNetworkMagic = RequiresNoMagic } knownTxIn (TxInUnknown _ _) = False knownTxIn _ = True -- Explicit bounds for types, based on the generators from Gen. attrUnitSize = (typeRep (Proxy @(Attributes ())) , SizeConstant 1) attrAddrSize = (typeRep (Proxy @(Attributes AddrAttributes)), SizeConstant (szCases [ Case "min" 1, Case "max" 1024 ])) txSigSize = (typeRep (Proxy @(Signature TxSigData)) , SizeConstant 66) scriptSize = (typeRep (Proxy @Script), SizeConstant $ szCases [ Case "loScript" 1 , Case "hiScript" 255 ]) in H.Group "Encoded size bounds for core types." [ ("TxId" , check genTxId) , ("Tx" , sizeTest $ scfg { gen = genTx , addlCtx = M.fromList [ attrUnitSize, attrAddrSize ] , computedCtx = \tx -> M.fromList [ (typeRep (Proxy @(LengthOf [TxIn])), SizeConstant (fromIntegral $ length $ _txInputs tx)) , (typeRep (Proxy @(LengthOf [TxOut])), SizeConstant (fromIntegral $ length $ _txOutputs tx)) ] }) , ("TxIn" , check (Gen.filter knownTxIn genTxIn)) , ("TxOut" , sizeTest $ scfg { gen = genTxOut , addlCtx = M.fromList [ attrAddrSize ] }) , ("TxAux" , sizeTest $ scfg { gen = genTxAux pm , addlCtx = M.fromList [ attrUnitSize , attrAddrSize , scriptSize , txSigSize ] , computedCtx = \(TxAux tx witness) -> M.fromList [ (typeRep (Proxy @(LengthOf [TxIn])), SizeConstant (fromIntegral $ length $ _txInputs tx)) , (typeRep (Proxy @(LengthOf (Vector TxInWitness))), SizeConstant (fromIntegral $ length witness)) , (typeRep (Proxy @(LengthOf [TxOut])), SizeConstant (fromIntegral $ length $ _txOutputs tx)) ] }) , ("TxInWitness" , sizeTest $ scfg { gen = genTxInWitness pm , addlCtx = M.fromList [ txSigSize, scriptSize ] }) , ("TxSigData" , check genTxSigData) , ("Signature TxSigData" , sizeTest $ scfg { gen = genTxSig pm , addlCtx = M.fromList [ txSigSize ] }) ] ----------------------------------------------------------------------- -- Main test export ----------------------------------------------------------------------- tests :: IO Bool tests = and <$> sequence [ H.checkSequential $$discoverGolden , H.checkParallel $$discoverRoundTrip , H.checkParallel sizeEstimates ]
input-output-hk/pos-haskell-prototype
chain/test/Test/Pos/Chain/Txp/Bi.hs
Haskell
mit
12,445
module Examples.UsablePath ( upExamples ) where import Utils import Algebra.Matrix import Algebra.Semiring import Algebra.Optimum import Policy.UsablePath upExamples :: Int -> Matrix UsablePath upExamples 0 = M (toArray 5 [(U 0), (U 0), (U 0), (U 1), (U 0) ,(U 0), (U 0), (U 0), (U 1), (U 0) ,(U 0), (U 0), (U 0), (U 0), (U 1) ,(U 1), (U 1), (U 0), (U 0), (U 0) ,(U 0), (U 0), (U 1), (U 0), (U 0)]) upExamples 1 = M (toArray 5 [(U 0), (U 0), (U 0), (U 1), (U 0) ,(U 1), (U 0), (U 1), (U 0), (U 0) ,(U 0), (U 0), (U 0), (U 1), (U 1) ,(U 0), (U 0), (U 0), (U 0), (U 1) ,(U 0), (U 1), (U 0), (U 0), (U 0)]) upExamples 2 = M (toArray 7 [(U 0), (U 0), (U 0), (U 0), (U 0), (U 0), (U 0) ,(U 1), (U 0), (U 0), (U 1), (U 1), (U 0), (U 0) ,(U 0), (U 0), (U 0), (U 0), (U 0), (U 0), (U 0) ,(U 0), (U 1), (U 1), (U 0), (U 1), (U 1), (U 0) ,(U 0), (U 0), (U 0), (U 0), (U 0), (U 0), (U 0) ,(U 0), (U 0), (U 1), (U 1), (U 0), (U 0), (U 1) ,(U 0), (U 0), (U 0), (U 0), (U 1), (U 1), (U 0)]) upExamples 3 = M (toArray 7 [(U 0), (U 1), (U 1), (U 0), (U 0), (U 0), (U 0) ,(U 0), (U 0), (U 0), (U 0), (U 0), (U 0), (U 0) ,(U 1), (U 0), (U 0), (U 1), (U 0), (U 1), (U 0) ,(U 0), (U 0), (U 0), (U 0), (U 0), (U 0), (U 0) ,(U 0), (U 1), (U 0), (U 1), (U 0), (U 0), (U 1) ,(U 0), (U 0), (U 1), (U 1), (U 0), (U 0), (U 1) ,(U 0), (U 0), (U 0), (U 0), (U 0), (U 0), (U 0)]) upExamples _ = error "Undefined example of Usable"
sdynerow/Semirings-Library
haskell/Examples/UsablePath.hs
Haskell
apache-2.0
1,609
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="pl-PL"> <title>Customizable HTML Report</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Zawartość</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Szukaj</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Ulubione</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/customreport/src/main/javahelp/org/zaproxy/zap/extension/customreport/resources/help_pl_PL/helpset_pl_PL.hs
Haskell
apache-2.0
973
module HermBanded where import Driver import Monadic import qualified Test.QuickCheck.BLAS as Test import Data.Matrix.Herm import Data.Matrix.Banded import Data.Vector.Dense import Data.Vector.Dense.ST import Data.Matrix.Dense.ST import Test.Matrix.Herm.Banded type V = Vector E type B = Banded E type HB = Herm Banded E prop_herm_apply (HermBandedMV (h :: HB) a x) = h <*> x ~== a <*> x prop_herm_sapply k (HermBandedMV (h :: HB) a x) = sapplyVector k h x ~== sapplyVector k a x prop_herm_herm_apply (HermBandedMV (h :: HB) a x) = herm h <*> x ~== h <*> x prop_doSapplyAddVector alpha beta (HermBandedMV (a :: HB) _ x) = monadicST $ do forAllM (Test.vector (numRows a)) $ \y -> do y' <- run $ (unsafeThawVector y :: ST s (STVector s E)) y'' <- run $ freezeVector y' run $ doSApplyAddVector alpha a x beta y' assert $ y ~== a <*> (alpha *> x) + (beta *> y'') prop_herm_applyMatrix (HermBandedMM (h :: HB) a b) = h <**> b ~== a <**> b prop_herm_sapplyMatrix k (HermBandedMM (h :: HB) a b) = sapplyMatrix k h b ~== sapplyMatrix k a b prop_herm_herm_applyMatrix (HermBandedMM (h :: HB) _ b) = herm h <**> b ~== h <**> b prop_doSapplyAddMatrix alpha beta (HermBandedMM (a :: HB) _ b) = monadicST $ do forAllM (Test.matrix (numRows a, numCols b)) $ \c -> do c' <- run $ unsafeThawMatrix c c'' <- run $ freezeMatrix c' run $ doSApplyAddMatrix alpha a b beta c' assert $ c ~== a <**> (alpha *> b) + (beta *> c'') tests_HermBanded = [ testProperty "herm apply" prop_herm_apply , testProperty "herm sapply" prop_herm_sapply , testProperty "herm herm apply" prop_herm_herm_apply , testProperty "doSApplyAddVector" prop_doSapplyAddVector , testProperty "herm applyMatrix" prop_herm_applyMatrix , testProperty "herm sapplyMatrix" prop_herm_sapplyMatrix , testProperty "herm herm applyMatrix" prop_herm_herm_applyMatrix , testProperty "doSApplyAddMatrix" prop_doSapplyAddMatrix ]
patperry/hs-linear-algebra
tests-old/HermBanded.hs
Haskell
bsd-3-clause
2,038
{-# LANGUAGE Rank2Types, FlexibleContexts #-} module Tests.Utils where import Data.Word import Control.Monad.ST import Foreign.C.Error import System.Directory import System.IO import System.IO.Unsafe (unsafePerformIO) import System.FilePath import Test.QuickCheck hiding (numTests) import Test.QuickCheck.Monadic import qualified Data.ByteString as BS import qualified Data.Map as M import Halfs.BlockMap import Halfs.Classes import Halfs.CoreAPI (mount, newfs, unmount) import Halfs.Directory import Halfs.Errors import Halfs.HalfsState import Halfs.Monad import Halfs.MonadUtils import Halfs.Protection import Halfs.SuperBlock import Halfs.Utils (divCeil, withDHLock) import System.Device.BlockDevice import System.Device.File import System.Device.Memory import System.Device.ST import Tests.Instances import Tests.Types -- import Debug.Trace type DevCtor = BDGeom -> IO (Maybe (BlockDevice IO)) type HalfsM b r l m a = HalfsT HalfsError (Maybe (HalfsState b r l m)) m a -------------------------------------------------------------------------------- -- Utility functions fileDev :: DevCtor fileDev g = withFileStore True ("./pseudo.dsk") (bdgSecSz g) (bdgSecCnt g) (`newFileBlockDevice` (bdgSecSz g)) memDev :: DevCtor memDev g = newMemoryBlockDevice (bdgSecCnt g) (bdgSecSz g) -- | Create an STArray-backed block device. This function transforms -- the ST-based block device to an IO block device for interface -- consistency within this module. staDev :: DevCtor staDev g = stToIO (newSTBlockDevice (bdgSecCnt g) (bdgSecSz g)) >>= return . maybe Nothing (\dev -> Just BlockDevice { bdBlockSize = bdBlockSize dev , bdNumBlocks = bdNumBlocks dev , bdReadBlock = \i -> stToIO $ bdReadBlock dev i , bdWriteBlock = \i v -> stToIO $ bdWriteBlock dev i v , bdFlush = stToIO $ bdFlush dev , bdShutdown = stToIO $ bdShutdown dev }) rescaledDev :: BDGeom -- ^ geometry for underlying device -> BDGeom -- ^ new device geometry -> DevCtor -- ^ ctor for underlying device -> IO (Maybe (BlockDevice IO)) rescaledDev oldG newG ctor = maybe (fail "Invalid BlockDevice") (newRescaledBlockDevice (bdgSecSz newG)) `fmap` ctor oldG monadicBCMIOProp :: PropertyM (BCM IO) a -> Property monadicBCMIOProp = monadic (unsafePerformIO . runBCM) withFileStore :: Bool -> FilePath -> Word64 -> Word64 -> (FilePath -> IO a) -> IO a withFileStore temp fp secSize secCnt act = do (fname, h) <- if temp then openBinaryTempFile (let d = takeDirectory "." in if null d then "." else d) (takeFileName fp) else (,) fp `fmap` openBinaryFile fp ReadWriteMode let chunkSz = 2^(20::Int) (numChunks, numBytes) = fromIntegral (secSize * secCnt) `divMod` chunkSz chunk = BS.replicate chunkSz 0 replicateM_ numChunks (BS.hPut h chunk) BS.hPut h (BS.replicate numBytes 0) hClose h rslt <- act fname when temp $ removeFile fname return rslt whenDev :: (Monad m) => (a -> m b) -> (a -> m ()) -> Maybe a -> m b whenDev act cleanup = maybe (fail "Invalid BlockDevice") $ \x -> do y <- act x cleanup x return y mkMemDevExec :: forall m. Bool -> String -> Int -> String -> (BDGeom -> BlockDevice IO -> PropertyM IO m) -> (Args, Property) mkMemDevExec quick pfx = let numTests n = (,) $ if quick then stdArgs{maxSuccess = n} else stdArgs doProp = (`whenDev` run . bdShutdown) in \n s pr -> numTests n $ label (pfx ++ ": " ++ s) $ monadicIO $ forAllM arbBDGeom $ \g -> run (memDev g) >>= doProp (pr g) mkNewFS :: HalfsCapable b t r l m => BlockDevice m -> PropertyM m (Either HalfsError SuperBlock) mkNewFS dev = runHNoEnv $ newfs dev rootUser rootGroup rootDirPerms mountOK :: HalfsCapable b t r l m => BlockDevice m -> PropertyM m (HalfsState b r l m) mountOK dev = do runHNoEnv (defaultMount dev) >>= either (fail . (++) "Unexpected mount failure: " . show) return unmountOK :: HalfsCapable b t r l m => HalfsState b r l m -> PropertyM m () unmountOK fs = runH fs unmount >>= either (fail . (++) "Unexpected unmount failure: " . show) (const $ return ()) sreadRef :: HalfsCapable b t r l m => r a -> PropertyM m a sreadRef = ($!) (run . readRef) runH :: HalfsCapable b t r l m => HalfsState b r l m -> HalfsM b r l m a -> PropertyM m (Either HalfsError a) runH fs = run . runHalfs fs runHNoEnv :: HalfsCapable b t r l m => HalfsM b r l m a -> PropertyM m (Either HalfsError a) runHNoEnv = run . runHalfsNoEnv execE :: (Monad m ,Show a) => String -> String -> m (Either a b) -> PropertyM m b execE nm descrip act = run act >>= \ea -> case ea of Left e -> fail $ "Unexpected error in " ++ nm ++ " (" ++ descrip ++ "): " ++ show e Right x -> return x execH :: Monad m => String -> env -> String -> HalfsT HalfsError (Maybe env) m b -> PropertyM m b execH nm env descrip = execE nm descrip . runHalfs env execHNoEnv :: Monad m => String -> String -> HalfsT HalfsError (Maybe env) m b -> PropertyM m b execHNoEnv nm descrip = execE nm descrip . runHalfsNoEnv expectErr :: HalfsCapable b t r l m => (HalfsError -> Bool) -> String -> HalfsM b r l m a -> HalfsState b r l m -> PropertyM m () expectErr expectedP rsn act fs = runH fs act >>= \e -> case e of Left err | expectedP err -> return () Left err -> unexpectedErr err Right _ -> fail rsn unexpectedErr :: (Monad m, Show a) => a -> PropertyM m () unexpectedErr = fail . (++) "Expected failure, but not: " . show expectErrno :: Monad m => Errno -> Either HalfsError a -> PropertyM m () expectErrno e (Left (HE_ErrnoAnnotated _ errno)) = assert (errno == e) expectErrno _ _ = assert False checkFileStat :: (HalfsCapable b t r l m, Integral a) => FileStat t -> a -- expected filesize -> FileType -- expected filetype -> FileMode -- expected filemode -> UserID -- expected userid -> GroupID -- expected groupid -> a -- expected allocated block count -> (t -> Bool) -- access time predicate -> (t -> Bool) -- modification time predicate -> (t -> Bool) -- status change time predicate -> PropertyM m () checkFileStat st expFileSz expFileTy expMode expUsr expGrp expNumBlocks accessp modifyp changep = do mapM_ assert [ fsSize st == fromIntegral expFileSz , fsType st == expFileTy , fsMode st == expMode , fsUID st == expUsr , fsGID st == expGrp , fsNumBlocks st == fromIntegral expNumBlocks , accessp (fsAccessTime st) , modifyp (fsModifyTime st) , changep (fsChangeTime st) ] assertMsg :: Monad m => String -> String -> Bool -> PropertyM m () assertMsg _ _ True = return () assertMsg ctx dtls False = do fail $ "(" ++ ctx ++ ": " ++ dtls ++ ")" -- Using the current allocation scheme and inode/cont distinction, -- determine how many blocks (of the given size, in bytes) are required -- to store the given data size, in bytes. calcExpBlockCount :: Integral a => Word64 -- block size -> Word64 -- addresses (#blocks) per inode -> Word64 -- addresses (#blocks) per cont -> a -- data size -> a -- expected number of blocks calcExpBlockCount bs api apc dataSz = fromIntegral $ if dsz > bpi then 1 -- inode block + api -- number of blocks in full inode + (dsz - bpi) `divCeil` bpc -- number of blocks required for conts + (dsz - bpi) `divCeil` bs -- number of blocks rquired for data else 1 -- inode block + (dsz `divCeil` bs) -- number of blocks required for data where dsz = fromIntegral dataSz bpi = api * bs bpc = apc * bs defaultUser :: UserID defaultUser = rootUser defaultGroup :: GroupID defaultGroup = rootGroup rootDirPerms, defaultDirPerms, defaultFilePerms :: FileMode rootDirPerms = FileMode [Read,Write,Execute] [] [] defaultDirPerms = FileMode [Read,Write,Execute] [Read, Execute] [Read, Execute] defaultFilePerms = FileMode [Read,Write] [Read] [Read] defaultMount :: HalfsCapable b t r l m => BlockDevice m -> HalfsM b r l m (HalfsState b r l m) defaultMount dev = mount dev defaultUser defaultGroup defaultDirPerms -------------------------------------------------------------------------------- -- Block utilization checking combinators rscUtil :: HalfsCapable b t r l m => (Word64 -> Word64 -> Bool) -- ^ predicate on after/before block cnts -> HalfsState b r l m -- ^ the filesystem state -> PropertyM m a -- ^ the action to check -> PropertyM m () rscUtil p fs act = do b <- getFree fs; _ <- act; a <- getFree fs; assert (p a b) where getFree = sreadRef . bmNumFree . hsBlockMap blocksUnallocd :: HalfsCapable b t r l m => Word64 -- ^ expected #blocks unallocated -> HalfsState b r l m -- ^ the filesystem state -> PropertyM m a -- ^ the action to check -> PropertyM m () blocksUnallocd x = rscUtil (\a b -> a >= b && a - b == x) blocksAllocd :: HalfsCapable b t r l m => Word64 -- ^ expected #blocks unallocated -> HalfsState b r l m -- ^ the filesystem state -> PropertyM m a -- ^ the action to check -> PropertyM m () blocksAllocd x = rscUtil (\a b -> b >= a && b - a == x) zeroOrMoreBlocksAllocd :: HalfsCapable b t r l m => HalfsState b r l m -- ^ the filesystem state -> PropertyM m a -- ^ the action to check -> PropertyM m () zeroOrMoreBlocksAllocd = rscUtil (<=) -------------------------------------------------------------------------------- -- Debugging helpers dumpfs :: HalfsCapable b t r l m => HalfsM b r l m String dumpfs = do sbRef <- hasks hsSuperBlock dump <- dumpfs' 2 "/\n" =<< rootDir `fmap` readRef sbRef return $ "=== fs dump begin ===\n" ++ dump ++ "=== fs dump end ===\n" where dumpfs' i ipfx inr = do contents <- withDirectory inr $ \dh -> do withDHLock dh $ readRef (dhContents dh) foldM (\dumpAcc (path, dirEnt) -> do sub <- if deType dirEnt == Directory && path /= "." && path /= ".." then dumpfs' (i+2) "" (deInode dirEnt) else return "" return $ dumpAcc ++ replicate i ' ' ++ path ++ let inr' = deInode dirEnt in case deType dirEnt of RegularFile -> " (" ++ show inr' ++ ") (file)\n" Directory -> " (" ++ show inr' ++ ") (directory)\n" ++ sub Symlink -> " (" ++ show inr' ++ ") (symlink)\n" _ -> error "unknown file type" ) ipfx (M.toList contents)
hackern/halfs
test/src/Tests/Utils.hs
Haskell
bsd-3-clause
11,787