code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE FlexibleContexts #-} module Exp.Roll where import Autolib.Exp import Autolib.NFA import Autolib.Exp.Some import Exp.Property roll :: NFAC c Int => [ Property c ] -> IO ( RX c, NFA c Int ) roll props = do let [ alpha ] = do Alphabet alpha <- props ; return alpha let [ s ] = do Max_Size s <- props ; return s nontrivial alpha ( s `div` 2 )
marcellussiegburg/autotool
collection/src/Exp/Roll.hs
gpl-2.0
389
0
13
108
154
77
77
13
1
-- The error screen, showing a current error condition (such as a parse error after reloading the journal) {-# LANGUAGE OverloadedStrings, FlexibleContexts, RecordWildCards #-} module Hledger.UI.ErrorScreen (errorScreen ,uiCheckBalanceAssertions ,uiReloadJournal ,uiReloadJournalIfChanged ) where import Brick -- import Brick.Widgets.Border (borderAttr) import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.Monoid import Data.Time.Calendar (Day) import Graphics.Vty (Event(..),Key(..)) import Text.Megaparsec.Compat import Hledger.Cli hiding (progname,prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.Editor errorScreen :: Screen errorScreen = ErrorScreen{ sInit = esInit ,sDraw = esDraw ,sHandle = esHandle ,esError = "" } esInit :: Day -> Bool -> UIState -> UIState esInit _ _ ui@UIState{aScreen=ErrorScreen{}} = ui esInit _ _ _ = error "init function called with wrong screen type, should not happen" esDraw :: UIState -> [Widget Name] esDraw UIState{aopts=UIOpts{cliopts_=copts@CliOpts{}} ,aScreen=ErrorScreen{..} ,aMode=mode} = case mode of Help -> [helpDialog copts, maincontent] -- Minibuffer e -> [minibuffer e, maincontent] _ -> [maincontent] where maincontent = Widget Greedy Greedy $ do render $ defaultLayout toplabel bottomlabel $ withAttr "error" $ str $ esError where toplabel = withAttr ("border" <> "bold") (str "Oops. Please fix this problem then press g to reload") -- <+> (if ignore_assertions_ copts then withAttr (borderAttr <> "query") (str " ignoring") else str " not ignoring") bottomlabel = case mode of -- Minibuffer ed -> minibuffer ed _ -> quickhelp where quickhelp = borderKeysStr [ ("h", "help") ,("ESC", "cancel/top") ,("E", "editor") ,("g", "reload") ,("q", "quit") ] esDraw _ = error "draw function called with wrong screen type, should not happen" esHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) esHandle ui@UIState{ aScreen=ErrorScreen{..} ,aopts=UIOpts{cliopts_=copts} ,ajournal=j ,aMode=mode } ev = case mode of Help -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui _ -> helpHandle ui ev _ -> do d <- liftIO getCurrentDay case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui VtyEvent (EvKey KEsc []) -> continue $ uiCheckBalanceAssertions d $ resetScreens d ui VtyEvent (EvKey (KChar c) []) | c `elem` ['h','?'] -> continue $ setMode Help ui VtyEvent (EvKey (KChar 'E') []) -> suspendAndResume $ void (runEditor pos f) >> uiReloadJournalIfChanged copts d j (popScreen ui) where (pos,f) = case parsewithString hledgerparseerrorpositionp esError of Right (f,l,c) -> (Just (l, Just c),f) Left _ -> (endPos, journalFilePath j) e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> liftIO (uiReloadJournal copts d (popScreen ui)) >>= continue . uiCheckBalanceAssertions d -- (ej, _) <- liftIO $ journalReloadIfChanged copts d j -- case ej of -- Left err -> continue ui{aScreen=s{esError=err}} -- show latest parse error -- Right j' -> continue $ regenerateScreens j' d $ popScreen ui -- return to previous screen, and reload it VtyEvent (EvKey (KChar 'I') []) -> continue $ uiCheckBalanceAssertions d (popScreen $ toggleIgnoreBalanceAssertions ui) _ -> continue ui esHandle _ _ = error "event handler called with wrong screen type, should not happen" -- | Parse the file name, line and column number from a hledger parse error message, if possible. -- Temporary, we should keep the original parse error location. XXX hledgerparseerrorpositionp :: ParsecT MPErr String t (String, Int, Int) hledgerparseerrorpositionp = do anyChar `manyTill` char '"' f <- anyChar `manyTill` (oneOf ['"','\n']) string " (line " l <- read <$> some digitChar string ", column " c <- read <$> some digitChar return (f, l, c) -- Unconditionally reload the journal, regenerating the current screen -- and all previous screens in the history. -- If reloading fails, enter the error screen, or if we're already -- on the error screen, update the error displayed. -- The provided CliOpts are used for reloading, and then saved -- in the UIState if reloading is successful (otherwise the -- ui state keeps its old cli opts.) -- Defined here so it can reference the error screen. uiReloadJournal :: CliOpts -> Day -> UIState -> IO UIState uiReloadJournal copts d ui = do ej <- journalReload copts return $ case ej of Right j -> regenerateScreens j d ui{aopts=(aopts ui){cliopts_=copts}} Left err -> case ui of UIState{aScreen=s@ErrorScreen{}} -> ui{aScreen=s{esError=err}} _ -> screenEnter d errorScreen{esError=err} ui -- Like uiReloadJournal, but does not bother re-parsing the journal if -- the file(s) have not changed since last loaded. Always regenerates -- the current and previous screens though, since opts or date may have changed. uiReloadJournalIfChanged :: CliOpts -> Day -> Journal -> UIState -> IO UIState uiReloadJournalIfChanged copts d j ui = do (ej, _changed) <- journalReloadIfChanged copts d j return $ case ej of Right j' -> regenerateScreens j' d ui{aopts=(aopts ui){cliopts_=copts}} Left err -> case ui of UIState{aScreen=s@ErrorScreen{}} -> ui{aScreen=s{esError=err}} _ -> screenEnter d errorScreen{esError=err} ui -- Re-check any balance assertions in the current journal, and if any -- fail, enter (or update) the error screen. Or if balance assertions -- are disabled, do nothing. uiCheckBalanceAssertions :: Day -> UIState -> UIState uiCheckBalanceAssertions d ui@UIState{aopts=UIOpts{cliopts_=copts}, ajournal=j} | ignore_assertions_ $ inputopts_ copts = ui | otherwise = case journalCheckBalanceAssertions j of Right _ -> ui Left err -> case ui of UIState{aScreen=s@ErrorScreen{}} -> ui{aScreen=s{esError=err}} _ -> screenEnter d errorScreen{esError=err} ui
ony/hledger
hledger-ui/Hledger/UI/ErrorScreen.hs
gpl-3.0
6,585
0
22
1,660
1,668
890
778
112
10
-- This file is part of seismic_repa. -- -- seismic_repa is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- seismic_repa is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with seismic_repa. If not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE PackageImports, BangPatterns, PatternGuards #-} {-# OPTIONS -Wall -fno-warn-missing-signatures -fno-warn-incomplete-patterns #-} import Seismic import System.Environment import Data.Time(getCurrentTime, diffUTCTime) -- import Data.Array.Repa.IO.Binary(writeArrayToStorableFile) main :: IO () main = do args <- getArgs case args of [t, x, y] -> go (read t::Int) (read x::Int) (read y::Int) _ -> print usage go !t !x !y = do let !mat = genMatrices x y let !pulse = genSeismicPulseVector t start <- getCurrentTime let !res = doNTimes mat pulse t 0 end <- getCurrentTime print $ diffUTCTime end start -- writeArrayToStorableFile "out_image_repa.bin" res return () usage :: String usage = "Usage: seismic_repa timeSteps xDim yDim"
agremm/Seismic
repa/Main.hs
gpl-3.0
1,486
0
12
280
236
121
115
21
2
module SequenceSpec(main,spec) where import Test.Hspec import qualified Data.Sequence as S import Data.Sequence ( ViewL((:<)), ViewR ((:>)) ) main :: IO () main = hspec spec exampleSeq :: S.Seq Int exampleSeq = S.fromList [1..10] spec :: Spec spec = describe "A Sequence" $ do it "can be queried for the left head" $ do let x :< _ = S.viewl exampleSeq x `shouldBe` 1 it "can be queried for the right head" $ do let _ :> x = S.viewr exampleSeq x `shouldBe` 10
svenkeidel/gnome-citadel
test/SequenceSpec.hs
gpl-3.0
484
0
15
108
186
100
86
16
1
{-# LANGUAGE NoImplicitPrelude, CPP, RecordWildCards #-} module Graphics.UI.Bottle.MainLoop ( AnimConfig (..) , mainLoopAnim , mainLoopImage , mainLoopWidget ) where import Prelude.Compat import Control.Concurrent (ThreadId, threadDelay, killThread, myThreadId) import Control.Concurrent.STM.TVar import Control.Concurrent.Utils (forkIOUnmasked) import Control.Exception (bracket, onException) import Control.Lens (Lens') import Control.Lens.Operators import Control.Monad (void, when, unless, forever) import qualified Control.Monad.STM as STM import Data.IORef import Data.MRUMemo (memoIO) import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import qualified Data.Monoid as Monoid import Data.Time.Clock (NominalDiffTime, UTCTime, getCurrentTime, addUTCTime, diffUTCTime) import Data.Vector.Vector2 (Vector2(..)) import Graphics.DrawingCombinators ((%%)) import Graphics.DrawingCombinators.Utils (Image) import qualified Graphics.DrawingCombinators.Utils as DrawUtils import Graphics.Rendering.OpenGL.GL (($=)) import qualified Graphics.Rendering.OpenGL.GL as GL import Graphics.UI.Bottle.Animation (AnimId) import qualified Graphics.UI.Bottle.Animation as Anim import qualified Graphics.UI.Bottle.EventMap as E import Graphics.UI.Bottle.Widget (Widget) import qualified Graphics.UI.Bottle.Widget as Widget import qualified Graphics.UI.GLFW as GLFW import Graphics.UI.GLFW.Events (KeyEvent, Event(..), Result(..), eventLoop) data AnimConfig = AnimConfig { acTimePeriod :: NominalDiffTime , acRemainingRatioInPeriod :: Anim.R } data EventResult = ERNone | ERRefresh | ERQuit deriving (Eq, Ord, Show) instance Monoid EventResult where mempty = ERNone mappend = max data ImageHandlers = ImageHandlers { imageEventHandler :: KeyEvent -> IO () , imageUpdate :: IO (Maybe Image) , imageRefresh :: IO Image } windowSize :: GLFW.Window -> IO Widget.Size windowSize win = do (x, y) <- GLFW.getFramebufferSize win return $ fromIntegral <$> Vector2 x y mainLoopImage :: GLFW.Window -> (Widget.Size -> ImageHandlers) -> IO () mainLoopImage win imageHandlers = eventLoop win handleEvents where handleEvent handlers (EventKey keyEvent) = do imageEventHandler handlers keyEvent return ERNone handleEvent _ EventWindowClose = return ERQuit handleEvent _ EventWindowRefresh = return ERRefresh handleEvents events = do winSize <- windowSize win let handlers = imageHandlers winSize eventResult <- mconcat <$> traverse (handleEvent handlers) events case eventResult of ERQuit -> return ResultQuit ERRefresh -> imageRefresh handlers >>= draw winSize ERNone -> imageUpdate handlers >>= maybe delay (draw winSize) delay = do -- TODO: If we can verify that there's sync-to-vblank, we -- need no sleep here threadDelay 10000 return ResultNone draw winSize@(Vector2 winSizeX winSizeY) image = do GL.viewport $= (GL.Position 0 0, GL.Size (round winSizeX) (round winSizeY)) image & (DrawUtils.translate (Vector2 (-1) 1) <> DrawUtils.scale (Vector2 (2/winSizeX) (-2/winSizeY)) %%) & let Vector2 glPixelRatioX glPixelRatioY = winSize / 2 -- GL range is -1..1 in DrawUtils.clearRenderSized (glPixelRatioX, glPixelRatioY) return ResultDidDraw data AnimHandlers = AnimHandlers { animTickHandler :: IO (Maybe (Monoid.Endo AnimId)) , animEventHandler :: KeyEvent -> IO (Maybe (Monoid.Endo AnimId)) , animMakeFrame :: IO Anim.Frame } data IsAnimating = Animating NominalDiffTime -- Current animation speed half-life | FinalFrame | NotAnimating deriving Eq asyncKillThread :: ThreadId -> IO () asyncKillThread = void . forkIOUnmasked . killThread withForkedIO :: IO () -> IO a -> IO a withForkedIO action = bracket (forkIOUnmasked action) asyncKillThread . const -- Animation thread will have not only the cur frame, but the dest -- frame in its mutable current state (to update it asynchronously) -- Worker thread receives events, ticks (which may be lost), handles them, responds to animation thread -- Animation thread sends events, ticks to worker thread. Samples results from worker thread, applies them to the cur state data AnimState = AnimState { _asIsAnimating :: !IsAnimating , _asCurTime :: !UTCTime , _asCurFrame :: !Anim.Frame , _asDestFrame :: !Anim.Frame } asIsAnimating :: Lens' AnimState IsAnimating asIsAnimating f AnimState {..} = f _asIsAnimating <&> \_asIsAnimating -> AnimState {..} asCurFrame :: Lens' AnimState Anim.Frame asCurFrame f AnimState {..} = f _asCurFrame <&> \_asCurFrame -> AnimState {..} asCurTime :: Lens' AnimState UTCTime asCurTime f AnimState {..} = f _asCurTime <&> \_asCurTime -> AnimState {..} asDestFrame :: Lens' AnimState Anim.Frame asDestFrame f AnimState {..} = f _asDestFrame <&> \_asDestFrame -> AnimState {..} data ThreadSyncVar = ThreadSyncVar { _tsvHaveTicks :: Bool , _tsvRefreshRequested :: Bool , _tsvWinSize :: Widget.Size , _tsvReversedEvents :: [KeyEvent] } initialAnimState :: Anim.Frame -> IO AnimState initialAnimState initialFrame = do curTime <- getCurrentTime return AnimState { _asIsAnimating = NotAnimating , _asCurTime = curTime , _asCurFrame = initialFrame , _asDestFrame = initialFrame } tsvHaveTicks :: Lens' ThreadSyncVar Bool tsvHaveTicks f ThreadSyncVar {..} = f _tsvHaveTicks <&> \_tsvHaveTicks -> ThreadSyncVar {..} tsvRefreshRequested :: Lens' ThreadSyncVar Bool tsvRefreshRequested f ThreadSyncVar {..} = f _tsvRefreshRequested <&> \_tsvRefreshRequested -> ThreadSyncVar {..} tsvWinSize :: Lens' ThreadSyncVar Widget.Size tsvWinSize f ThreadSyncVar {..} = f _tsvWinSize <&> \_tsvWinSize -> ThreadSyncVar {..} tsvReversedEvents :: Lens' ThreadSyncVar [KeyEvent] tsvReversedEvents f ThreadSyncVar {..} = f _tsvReversedEvents <&> \_tsvReversedEvents -> ThreadSyncVar {..} atomicModifyIORef_ :: IORef a -> (a -> a) -> IO () atomicModifyIORef_ ioref f = atomicModifyIORef ioref (flip (,) () . f) killSelfOnError :: IO a -> IO (IO a) killSelfOnError action = do selfId <- myThreadId return $ action `onException` asyncKillThread selfId desiredFrameRate :: Num a => a desiredFrameRate = 60 mainLoopAnim :: GLFW.Window -> IO AnimConfig -> (Widget.Size -> AnimHandlers) -> IO () mainLoopAnim win getAnimationConfig animHandlers = do initialWinSize <- windowSize win frameStateVar <- animMakeFrame (animHandlers initialWinSize) >>= initialAnimState >>= newIORef eventTVar <- STM.atomically $ newTVar ThreadSyncVar { _tsvHaveTicks = False , _tsvRefreshRequested = False , _tsvWinSize = initialWinSize , _tsvReversedEvents = [] } eventHandler <- killSelfOnError (eventHandlerThread frameStateVar eventTVar getAnimationConfig animHandlers) withForkedIO eventHandler $ mainLoopAnimThread frameStateVar eventTVar win waitForEvent :: TVar ThreadSyncVar -> IO ThreadSyncVar waitForEvent eventTVar = do tsv <- readTVar eventTVar when (not (tsv ^. tsvHaveTicks) && not (tsv ^. tsvRefreshRequested) && null (tsv ^. tsvReversedEvents)) $ STM.retry tsv & tsvHaveTicks .~ False & tsvRefreshRequested .~ False & tsvReversedEvents .~ [] & writeTVar eventTVar return tsv & STM.atomically eventHandlerThread :: IORef AnimState -> TVar ThreadSyncVar -> IO AnimConfig -> (Widget.Size -> AnimHandlers) -> IO () eventHandlerThread frameStateVar eventTVar getAnimationConfig animHandlers = forever $ do tsv <- waitForEvent eventTVar userEventTime <- getCurrentTime let handlers = animHandlers (tsv ^. tsvWinSize) eventResults <- mapM (animEventHandler handlers) $ reverse (tsv ^. tsvReversedEvents) tickResult <- if tsv ^. tsvHaveTicks then animTickHandler handlers else return Nothing case (tsv ^. tsvRefreshRequested, mconcat (tickResult : eventResults)) of (False, Nothing) -> return () (_, mMapping) -> do destFrame <- animMakeFrame handlers AnimConfig timePeriod ratio <- getAnimationConfig curTime <- getCurrentTime let timeRemaining = max 0 $ diffUTCTime (addUTCTime timePeriod userEventTime) curTime let animationHalfLife = timeRemaining / realToFrac (logBase 0.5 ratio) atomicModifyIORef_ frameStateVar $ \oldFrameState -> oldFrameState & asIsAnimating .~ Animating animationHalfLife & asDestFrame .~ destFrame -- retroactively pretend animation started at -- user event time to make the -- animation-until-dest-frame last the same -- amount of time no matter how long it took -- to handle the event: & asCurTime .~ addUTCTime (-1.0 / desiredFrameRate) curTime & asCurFrame %~ Anim.mapIdentities (Monoid.appEndo (fromMaybe mempty mMapping)) mainLoopAnimThread :: IORef AnimState -> TVar ThreadSyncVar -> GLFW.Window -> IO () mainLoopAnimThread frameStateVar eventTVar win = mainLoopImage win $ \size -> ImageHandlers { imageEventHandler = \event -> updateTVar $ tsvReversedEvents %~ (event :) , imageRefresh = do updateTVar (tsvRefreshRequested .~ True) updateFrameState size <&> _asCurFrame <&> Anim.draw , imageUpdate = updateFrameState size <&> frameStateResult } where updateTVar = STM.atomically . modifyTVar eventTVar tick size = updateTVar $ (tsvHaveTicks .~ True) . (tsvWinSize .~ size) updateFrameState size = do tick size curTime <- getCurrentTime atomicModifyIORef frameStateVar $ \(AnimState prevAnimating prevTime prevFrame destFrame) -> let notAnimating = AnimState NotAnimating curTime destFrame destFrame newAnimState = case prevAnimating of Animating animationHalfLife -> case Anim.nextFrame progress destFrame prevFrame of Nothing -> AnimState FinalFrame curTime destFrame destFrame Just newFrame -> AnimState (Animating animationHalfLife) curTime newFrame destFrame where elapsed = curTime `diffUTCTime` prevTime progress = 1 - 0.5 ** (realToFrac elapsed / realToFrac animationHalfLife) FinalFrame -> notAnimating NotAnimating -> notAnimating in (newAnimState, newAnimState) frameStateResult (AnimState isAnimating _ frame _) = case isAnimating of Animating _ -> Just $ Anim.draw frame FinalFrame -> Just $ Anim.draw frame NotAnimating -> Nothing mainLoopWidget :: GLFW.Window -> IO Bool -> (Widget.Size -> IO (Widget IO)) -> IO AnimConfig -> IO () mainLoopWidget win widgetTickHandler mkWidgetUnmemod getAnimationConfig = do mkWidgetRef <- newIORef =<< memoIO mkWidgetUnmemod let newWidget = writeIORef mkWidgetRef =<< memoIO mkWidgetUnmemod getWidget size = ($ size) =<< readIORef mkWidgetRef mainLoopAnim win getAnimationConfig $ \size -> AnimHandlers { animTickHandler = do anyUpdate <- widgetTickHandler when anyUpdate newWidget widget <- getWidget size tickResults <- sequenceA (widget ^. Widget.eventMap . E.emTickHandlers) unless (null tickResults) newWidget return $ case (tickResults, anyUpdate) of ([], False) -> Nothing _ -> Just . mconcat $ map (^. Widget.eAnimIdMapping) tickResults , animEventHandler = \event -> do widget <- getWidget size mAnimIdMapping <- widget ^. Widget.eventMap & E.lookup event & sequenceA & (fmap . fmap) (^. Widget.eAnimIdMapping) case mAnimIdMapping of Nothing -> return () Just _ -> newWidget return mAnimIdMapping , animMakeFrame = getWidget size <&> (^. Widget.animFrame) }
rvion/lamdu
bottlelib/Graphics/UI/Bottle/MainLoop.hs
gpl-3.0
13,867
0
23
4,493
3,210
1,668
1,542
-1
-1
{-# LANGUAGE NoMonomorphismRestriction#-} {-# LANGUAGE NoImplicitPrelude #-} module Bamboo.Helper where import Bamboo.Helper.ByteString import Bamboo.Helper.PreludeEnv hiding (at) import Bamboo.Helper.Translation import Bamboo.Type import Bamboo.Type.Reader import Bamboo.Type.StaticWidget hiding (name, body, reader) import Control.Monad (liftM2, when) import Data.Default import Data.Maybe import Hack.Contrib.Utils (script_name) import Hack (Env) import System.Directory import System.FilePath.Posix hiding ((<.>)) import System.IO as IO import Text.XHtml.Strict hiding (p, meta, body, select, name) import qualified Bamboo.Type.Theme as Theme import qualified Prelude as P import qualified Text.XHtml.Strict as Html gt :: (Ord a) => a -> a -> Bool gt = (P.>) ffmap :: (Functor f, Functor f1) => (a -> b) -> f1 (f a) -> f1 (f b) ffmap f = fmap (fmap f) (^^) :: (Functor f, Functor f1) => f1 (f a) -> (a -> b) -> f1 (f b) (^^) x f = fmap (fmap f) x whenM :: (Monad m) => m Bool -> m () -> m () whenM b x = b >>= flip when x parse_config :: String -> IO Assoc parse_config x = do s <- read_file x s .filter_comment .lines.map strip .map (split "\\s*=\\s*") .map fill_snd_blank .map tuple2 .return where fill_snd_blank [y] = [y,""] fill_snd_blank xs = xs write_config :: FilePath -> Assoc -> IO () write_config s xs = xs.map(\(x, y) -> x ++ " = " ++ y) .join "\n" .write_file s -- html empty_html :: Html empty_html = toHtml "" -- generic show_data :: (Show a) => a -> [Char] show_data = show > snake_case ifM :: (Monad m) => m Bool -> m b -> m b -> m b ifM p t f = p >>= (\p' -> if p' then t else f) parse_boolean :: String -> Bool parse_boolean = belongs_to ["true", "1", "y", "yes", "yeah"] mkdir :: String -> IO () mkdir = u2b > createDirectory -- type SC = String -> String type SIO = String -> IO () take_directory :: SC take_directory = u2b > takeDirectory > b2u with_file :: String -> IOMode -> (Handle -> IO a) -> IO a with_file s m f = IO.withFile (s.u2b) m f id_to_type :: SC id_to_type x = x.split "/" .first id_to_resource :: SC id_to_resource x = x.split "/" .tail.join "/" read_data :: (Read a) => String -> a read_data s = s.camel_case.read read_data_list :: (Read a) => [String] -> [a] read_data_list xs = xs.map read_data take_extension :: SC take_extension = takeExtension -- > split "\\." > last take_known_extension :: SC take_known_extension s | ext.belongs_to exts = ext | otherwise = "" where ext = s.take_extension exts = readers.only_snd.join' drop_known_extension :: SC drop_known_extension s | s.take_extension.belongs_to exts = dropExtension s | otherwise = s where exts = readers.only_snd.join' remove_trailing_slash :: SC remove_trailing_slash s = if s.last.is '/' then s.init else s -- config parse_list :: String -> [String] parse_list s = s.split "," .map strip .reject null static_config :: Config static_config = purify $ do return def >>= set_blog_title ( for_s BlogTitle ) >>= set_blog_subtitle ( for_s BlogSubtitle ) >>= set_host_name ( for_s HostName ) >>= set_author_email ( for_s AuthorEmail ) >>= set_per_page ( for_i PerPage ) >>= set_navigation ( for_l Navigation ^^ (home_nav :) ) >>= set_bamboo_url ( for_s BambooUrl ) >>= set_sidebar ( for_l Sidebar >>= load_sidebar ) >>= set_footer ( for_s Footer >>= load_footer ) >>= set_favicon ( for_s Favicon ) >>= set_analytics_account_id ( for_s AnalyticsAccountId ) >>= set_extensions ( for_l Extensions ^^ read_data_list ) >>= set_theme_config ( for_s Theme >>= get_theme_config ) >>= set_post_date_format ( for_s PostDateFormat ) >>= set_comment_date_format ( for_s CommentDateFormat ) >>= set_url_date_format ( for_s UrlDateFormat ) >>= set_url_date_matcher ( for_s UrlDateMatcher ) >>= set_url_title_subs ( for_s UrlTitleSubs ^^ (as_l > read) ) >>= set_url_date_title_seperator ( for_s UrlDateTitleSeperator ) >>= set_cut ( for_s Cut ) >>= set_summary_for_root ( for_b SummaryForRoot ) >>= set_summary_for_tag ( for_b SummaryForTag ) >>= set_summary_for_rss ( for_b SummaryForRss ) >>= set_picture_prefix ( for_s PicturePrefix ) >>= set_number_of_latest_posts ( for_i NumberOfLatestPosts ) >>= set_use_cache ( for_b UseCache ) where user_config = parse_config $ def.config_uri for x = user_config ^ lookup (x.show_data) for_s = for for_i = for > (^^ read) for_l = for > (^^ parse_list) for_b = for > (^^ parse_boolean) load_widget x = do exists <- x.file_exist if exists then do w <- read_static_widget def x return $ (Just w) else return Nothing load_sidebar_item = (def.footer_uri / ) > load_widget load_sidebar Nothing = return Nothing load_sidebar (Just xs) = xs . mapM load_sidebar_item ^ filter isJust ^ map fromJust ^ Just load_footer Nothing = return Nothing load_footer (Just s) = (def.footer_uri / s) .load_widget ^ Just as_l s = "[" ++ s ++ "]" get_theme_config Nothing = return Nothing get_theme_config (Just user_theme_name) = do let user_theme_uri = (def.theme_uri / user_theme_name) ++ ".txt" exists <- user_theme_uri.file_exist if exists then parse_config user_theme_uri ^ (("name", user_theme_name) : ) ^ to_theme ^ Just else return Nothing -- helper c (Just _) _ y = y c Nothing x _ = x p = fromJust r = return set_analytics_account_id v' x = v' >>= \v -> r $ c v x $ x { analytics_account_id = p v} set_author_email v' x = v' >>= \v -> r $ c v x $ x { author_email = p v} set_bamboo_url v' x = v' >>= \v -> r $ c v x $ x { bamboo_url = p v} set_blog_subtitle v' x = v' >>= \v -> r $ c v x $ x { blog_subtitle = p v} set_blog_title v' x = v' >>= \v -> r $ c v x $ x { blog_title = p v} set_comment_date_format v' x = v' >>= \v -> r $ c v x $ x { comment_date_format = p v} set_cut v' x = v' >>= \v -> r $ c v x $ x { cut = p v} set_extensions v' x = v' >>= \v -> r $ c v x $ x { extensions = p v} set_favicon v' x = v' >>= \v -> r $ c v x $ x { favicon = p v} set_footer v' x = v' >>= \v -> r $ c v x $ x { footer = p v} set_host_name v' x = v' >>= \v -> r $ c v x $ x { host_name = p v} set_navigation v' x = v' >>= \v -> r $ c v x $ x { navigation = p v} set_number_of_latest_posts v' x = v' >>= \v -> r $ c v x $ x { number_of_latest_posts = p v} set_per_page v' x = v' >>= \v -> r $ c v x $ x { per_page = p v} set_picture_prefix v' x = v' >>= \v -> r $ c v x $ x { picture_prefix = p v} set_post_date_format v' x = v' >>= \v -> r $ c v x $ x { post_date_format = p v} set_sidebar v' x = v' >>= \v -> r $ c v x $ x { sidebar = p v} set_summary_for_root v' x = v' >>= \v -> r $ c v x $ x { summary_for_root = p v} set_summary_for_rss v' x = v' >>= \v -> r $ c v x $ x { summary_for_rss = p v} set_summary_for_tag v' x = v' >>= \v -> r $ c v x $ x { summary_for_tag = p v} set_theme_config v' x = v' >>= \v -> r $ c v x $ x { theme_config = p v} set_url_date_format v' x = v' >>= \v -> r $ c v x $ x { url_date_format = p v} set_url_date_matcher v' x = v' >>= \v -> r $ c v x $ x { url_date_matcher = p v} set_url_date_title_seperator v' x = v' >>= \v -> r $ c v x $ x { url_date_title_seperator = p v} set_url_title_subs v' x = v' >>= \v -> r $ c v x $ x { url_title_subs = p v} set_use_cache v' x = v' >>= \v -> r $ c v x $ x { use_cache = p v} db_uri :: Config -> String flat_uri :: Config -> String public_uri :: Config -> String image_uri :: Config -> String config_uri :: Config -> String sidebar_uri :: Config -> String footer_uri :: Config -> String post_uri :: Config -> String tag_uri :: Config -> String comment_uri :: Config -> String theme_uri :: Config -> String album_uri :: Config -> String topic_uri :: Config -> String stat_uri :: Config -> String cache_uri :: Config -> String db_uri x = x.db_id flat_uri x = x.db_uri / x.flat_id public_uri x = x.db_uri / x.public_id image_uri x = x.public_uri / x.image_id config_uri x = x.flat_uri / x.config_id / x.config_file_id sidebar_uri x = x.flat_uri / x.config_id / x.sidebar_id footer_uri x = x.flat_uri / x.config_id post_uri x = x.flat_uri / x.post_id tag_uri x = x.flat_uri / x.tag_id comment_uri x = x.flat_uri / x.comment_id theme_uri x = x.flat_uri / x.config_id / x.theme_id album_uri x = x.image_uri / x.album_id topic_uri x = x.flat_uri / x.topic_id stat_uri x = x.flat_uri / x.stat_id cache_uri x = x.flat_uri / x.cache_id -- Widget read_static_widget :: Reader -> String -> IO StaticWidget read_static_widget user_reader s = liftM2 (StaticWidget name) body (return reader) where body = s.read_bytestring reader = s.take_extension.guess_reader.fromMaybe user_reader name = s.takeFileName.drop_known_extension -- Theme to_theme :: Assoc -> Theme.ThemeConfig to_theme xs = Theme.ThemeConfig { Theme.name = at Theme.Name , Theme.css = at Theme.Css .css_list , Theme.js = at Theme.Js .js_list } where at s = xs.lookup (s.show_data) .fromJust css_list s = s.parse_list.map (\x -> "theme/" ++ at Theme.Name ++ "/css/" ++ x ++ ".css") js_list s = s.parse_list.map (\x -> "theme/" ++ at Theme.Name ++ "/js/" ++ x ++ ".js") slashed_script_name :: Env -> String slashed_script_name env = "/" / env.script_name
nfjinjing/bamboo
src/Bamboo/Helper.hs
gpl-3.0
11,030
16
34
3,759
3,708
1,921
1,787
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.SQL.Instances.ResetSSLConfig -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes all client certificates and generates a new server SSL -- certificate for the instance. -- -- /See:/ <https://developers.google.com/cloud-sql/ Cloud SQL Admin API Reference> for @sql.instances.resetSslConfig@. module Network.Google.Resource.SQL.Instances.ResetSSLConfig ( -- * REST Resource InstancesResetSSLConfigResource -- * Creating a Request , instancesResetSSLConfig , InstancesResetSSLConfig -- * Request Lenses , irscXgafv , irscUploadProtocol , irscProject , irscAccessToken , irscUploadType , irscCallback , irscInstance ) where import Network.Google.Prelude import Network.Google.SQLAdmin.Types -- | A resource alias for @sql.instances.resetSslConfig@ method which the -- 'InstancesResetSSLConfig' request conforms to. type InstancesResetSSLConfigResource = "v1" :> "projects" :> Capture "project" Text :> "instances" :> Capture "instance" Text :> "resetSslConfig" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Post '[JSON] Operation -- | Deletes all client certificates and generates a new server SSL -- certificate for the instance. -- -- /See:/ 'instancesResetSSLConfig' smart constructor. data InstancesResetSSLConfig = InstancesResetSSLConfig' { _irscXgafv :: !(Maybe Xgafv) , _irscUploadProtocol :: !(Maybe Text) , _irscProject :: !Text , _irscAccessToken :: !(Maybe Text) , _irscUploadType :: !(Maybe Text) , _irscCallback :: !(Maybe Text) , _irscInstance :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'InstancesResetSSLConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'irscXgafv' -- -- * 'irscUploadProtocol' -- -- * 'irscProject' -- -- * 'irscAccessToken' -- -- * 'irscUploadType' -- -- * 'irscCallback' -- -- * 'irscInstance' instancesResetSSLConfig :: Text -- ^ 'irscProject' -> Text -- ^ 'irscInstance' -> InstancesResetSSLConfig instancesResetSSLConfig pIrscProject_ pIrscInstance_ = InstancesResetSSLConfig' { _irscXgafv = Nothing , _irscUploadProtocol = Nothing , _irscProject = pIrscProject_ , _irscAccessToken = Nothing , _irscUploadType = Nothing , _irscCallback = Nothing , _irscInstance = pIrscInstance_ } -- | V1 error format. irscXgafv :: Lens' InstancesResetSSLConfig (Maybe Xgafv) irscXgafv = lens _irscXgafv (\ s a -> s{_irscXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). irscUploadProtocol :: Lens' InstancesResetSSLConfig (Maybe Text) irscUploadProtocol = lens _irscUploadProtocol (\ s a -> s{_irscUploadProtocol = a}) -- | Project ID of the project that contains the instance. irscProject :: Lens' InstancesResetSSLConfig Text irscProject = lens _irscProject (\ s a -> s{_irscProject = a}) -- | OAuth access token. irscAccessToken :: Lens' InstancesResetSSLConfig (Maybe Text) irscAccessToken = lens _irscAccessToken (\ s a -> s{_irscAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). irscUploadType :: Lens' InstancesResetSSLConfig (Maybe Text) irscUploadType = lens _irscUploadType (\ s a -> s{_irscUploadType = a}) -- | JSONP irscCallback :: Lens' InstancesResetSSLConfig (Maybe Text) irscCallback = lens _irscCallback (\ s a -> s{_irscCallback = a}) -- | Cloud SQL instance ID. This does not include the project ID. irscInstance :: Lens' InstancesResetSSLConfig Text irscInstance = lens _irscInstance (\ s a -> s{_irscInstance = a}) instance GoogleRequest InstancesResetSSLConfig where type Rs InstancesResetSSLConfig = Operation type Scopes InstancesResetSSLConfig = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/sqlservice.admin"] requestClient InstancesResetSSLConfig'{..} = go _irscProject _irscInstance _irscXgafv _irscUploadProtocol _irscAccessToken _irscUploadType _irscCallback (Just AltJSON) sQLAdminService where go = buildClient (Proxy :: Proxy InstancesResetSSLConfigResource) mempty
brendanhay/gogol
gogol-sqladmin/gen/Network/Google/Resource/SQL/Instances/ResetSSLConfig.hs
mpl-2.0
5,404
0
19
1,255
786
458
328
117
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.AndroidPublisher.Types.Sum -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.AndroidPublisher.Types.Sum where import Network.Google.Prelude data EditsImagesDeleteallImageType = FeatureGraphic -- ^ @featureGraphic@ | Icon -- ^ @icon@ | PhoneScreenshots -- ^ @phoneScreenshots@ | PromoGraphic -- ^ @promoGraphic@ | SevenInchScreenshots -- ^ @sevenInchScreenshots@ | TenInchScreenshots -- ^ @tenInchScreenshots@ | TvBanner -- ^ @tvBanner@ | TvScreenshots -- ^ @tvScreenshots@ | WearScreenshots -- ^ @wearScreenshots@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsImagesDeleteallImageType instance FromHttpApiData EditsImagesDeleteallImageType where parseQueryParam = \case "featureGraphic" -> Right FeatureGraphic "icon" -> Right Icon "phoneScreenshots" -> Right PhoneScreenshots "promoGraphic" -> Right PromoGraphic "sevenInchScreenshots" -> Right SevenInchScreenshots "tenInchScreenshots" -> Right TenInchScreenshots "tvBanner" -> Right TvBanner "tvScreenshots" -> Right TvScreenshots "wearScreenshots" -> Right WearScreenshots x -> Left ("Unable to parse EditsImagesDeleteallImageType from: " <> x) instance ToHttpApiData EditsImagesDeleteallImageType where toQueryParam = \case FeatureGraphic -> "featureGraphic" Icon -> "icon" PhoneScreenshots -> "phoneScreenshots" PromoGraphic -> "promoGraphic" SevenInchScreenshots -> "sevenInchScreenshots" TenInchScreenshots -> "tenInchScreenshots" TvBanner -> "tvBanner" TvScreenshots -> "tvScreenshots" WearScreenshots -> "wearScreenshots" instance FromJSON EditsImagesDeleteallImageType where parseJSON = parseJSONText "EditsImagesDeleteallImageType" instance ToJSON EditsImagesDeleteallImageType where toJSON = toJSONText -- | The track type to read or modify. data EditsTracksPatchTrack = Alpha -- ^ @alpha@ | Beta -- ^ @beta@ | Production -- ^ @production@ | Rollout -- ^ @rollout@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsTracksPatchTrack instance FromHttpApiData EditsTracksPatchTrack where parseQueryParam = \case "alpha" -> Right Alpha "beta" -> Right Beta "production" -> Right Production "rollout" -> Right Rollout x -> Left ("Unable to parse EditsTracksPatchTrack from: " <> x) instance ToHttpApiData EditsTracksPatchTrack where toQueryParam = \case Alpha -> "alpha" Beta -> "beta" Production -> "production" Rollout -> "rollout" instance FromJSON EditsTracksPatchTrack where parseJSON = parseJSONText "EditsTracksPatchTrack" instance ToJSON EditsTracksPatchTrack where toJSON = toJSONText -- | The track type to read or modify. data EditsTracksGetTrack = ETGTAlpha -- ^ @alpha@ | ETGTBeta -- ^ @beta@ | ETGTProduction -- ^ @production@ | ETGTRollout -- ^ @rollout@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsTracksGetTrack instance FromHttpApiData EditsTracksGetTrack where parseQueryParam = \case "alpha" -> Right ETGTAlpha "beta" -> Right ETGTBeta "production" -> Right ETGTProduction "rollout" -> Right ETGTRollout x -> Left ("Unable to parse EditsTracksGetTrack from: " <> x) instance ToHttpApiData EditsTracksGetTrack where toQueryParam = \case ETGTAlpha -> "alpha" ETGTBeta -> "beta" ETGTProduction -> "production" ETGTRollout -> "rollout" instance FromJSON EditsTracksGetTrack where parseJSON = parseJSONText "EditsTracksGetTrack" instance ToJSON EditsTracksGetTrack where toJSON = toJSONText -- | The track type to read or modify. data EditsTracksUpdateTrack = ETUTAlpha -- ^ @alpha@ | ETUTBeta -- ^ @beta@ | ETUTProduction -- ^ @production@ | ETUTRollout -- ^ @rollout@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsTracksUpdateTrack instance FromHttpApiData EditsTracksUpdateTrack where parseQueryParam = \case "alpha" -> Right ETUTAlpha "beta" -> Right ETUTBeta "production" -> Right ETUTProduction "rollout" -> Right ETUTRollout x -> Left ("Unable to parse EditsTracksUpdateTrack from: " <> x) instance ToHttpApiData EditsTracksUpdateTrack where toQueryParam = \case ETUTAlpha -> "alpha" ETUTBeta -> "beta" ETUTProduction -> "production" ETUTRollout -> "rollout" instance FromJSON EditsTracksUpdateTrack where parseJSON = parseJSONText "EditsTracksUpdateTrack" instance ToJSON EditsTracksUpdateTrack where toJSON = toJSONText data EditsImagesListImageType = EILITFeatureGraphic -- ^ @featureGraphic@ | EILITIcon -- ^ @icon@ | EILITPhoneScreenshots -- ^ @phoneScreenshots@ | EILITPromoGraphic -- ^ @promoGraphic@ | EILITSevenInchScreenshots -- ^ @sevenInchScreenshots@ | EILITTenInchScreenshots -- ^ @tenInchScreenshots@ | EILITTvBanner -- ^ @tvBanner@ | EILITTvScreenshots -- ^ @tvScreenshots@ | EILITWearScreenshots -- ^ @wearScreenshots@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsImagesListImageType instance FromHttpApiData EditsImagesListImageType where parseQueryParam = \case "featureGraphic" -> Right EILITFeatureGraphic "icon" -> Right EILITIcon "phoneScreenshots" -> Right EILITPhoneScreenshots "promoGraphic" -> Right EILITPromoGraphic "sevenInchScreenshots" -> Right EILITSevenInchScreenshots "tenInchScreenshots" -> Right EILITTenInchScreenshots "tvBanner" -> Right EILITTvBanner "tvScreenshots" -> Right EILITTvScreenshots "wearScreenshots" -> Right EILITWearScreenshots x -> Left ("Unable to parse EditsImagesListImageType from: " <> x) instance ToHttpApiData EditsImagesListImageType where toQueryParam = \case EILITFeatureGraphic -> "featureGraphic" EILITIcon -> "icon" EILITPhoneScreenshots -> "phoneScreenshots" EILITPromoGraphic -> "promoGraphic" EILITSevenInchScreenshots -> "sevenInchScreenshots" EILITTenInchScreenshots -> "tenInchScreenshots" EILITTvBanner -> "tvBanner" EILITTvScreenshots -> "tvScreenshots" EILITWearScreenshots -> "wearScreenshots" instance FromJSON EditsImagesListImageType where parseJSON = parseJSONText "EditsImagesListImageType" instance ToJSON EditsImagesListImageType where toJSON = toJSONText data EditsTestersPatchTrack = ETPTAlpha -- ^ @alpha@ | ETPTBeta -- ^ @beta@ | ETPTProduction -- ^ @production@ | ETPTRollout -- ^ @rollout@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsTestersPatchTrack instance FromHttpApiData EditsTestersPatchTrack where parseQueryParam = \case "alpha" -> Right ETPTAlpha "beta" -> Right ETPTBeta "production" -> Right ETPTProduction "rollout" -> Right ETPTRollout x -> Left ("Unable to parse EditsTestersPatchTrack from: " <> x) instance ToHttpApiData EditsTestersPatchTrack where toQueryParam = \case ETPTAlpha -> "alpha" ETPTBeta -> "beta" ETPTProduction -> "production" ETPTRollout -> "rollout" instance FromJSON EditsTestersPatchTrack where parseJSON = parseJSONText "EditsTestersPatchTrack" instance ToJSON EditsTestersPatchTrack where toJSON = toJSONText data EditsTestersGetTrack = EAlpha -- ^ @alpha@ | EBeta -- ^ @beta@ | EProduction -- ^ @production@ | ERollout -- ^ @rollout@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsTestersGetTrack instance FromHttpApiData EditsTestersGetTrack where parseQueryParam = \case "alpha" -> Right EAlpha "beta" -> Right EBeta "production" -> Right EProduction "rollout" -> Right ERollout x -> Left ("Unable to parse EditsTestersGetTrack from: " <> x) instance ToHttpApiData EditsTestersGetTrack where toQueryParam = \case EAlpha -> "alpha" EBeta -> "beta" EProduction -> "production" ERollout -> "rollout" instance FromJSON EditsTestersGetTrack where parseJSON = parseJSONText "EditsTestersGetTrack" instance ToJSON EditsTestersGetTrack where toJSON = toJSONText data EditsImagesUploadImageType = EIUITFeatureGraphic -- ^ @featureGraphic@ | EIUITIcon -- ^ @icon@ | EIUITPhoneScreenshots -- ^ @phoneScreenshots@ | EIUITPromoGraphic -- ^ @promoGraphic@ | EIUITSevenInchScreenshots -- ^ @sevenInchScreenshots@ | EIUITTenInchScreenshots -- ^ @tenInchScreenshots@ | EIUITTvBanner -- ^ @tvBanner@ | EIUITTvScreenshots -- ^ @tvScreenshots@ | EIUITWearScreenshots -- ^ @wearScreenshots@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsImagesUploadImageType instance FromHttpApiData EditsImagesUploadImageType where parseQueryParam = \case "featureGraphic" -> Right EIUITFeatureGraphic "icon" -> Right EIUITIcon "phoneScreenshots" -> Right EIUITPhoneScreenshots "promoGraphic" -> Right EIUITPromoGraphic "sevenInchScreenshots" -> Right EIUITSevenInchScreenshots "tenInchScreenshots" -> Right EIUITTenInchScreenshots "tvBanner" -> Right EIUITTvBanner "tvScreenshots" -> Right EIUITTvScreenshots "wearScreenshots" -> Right EIUITWearScreenshots x -> Left ("Unable to parse EditsImagesUploadImageType from: " <> x) instance ToHttpApiData EditsImagesUploadImageType where toQueryParam = \case EIUITFeatureGraphic -> "featureGraphic" EIUITIcon -> "icon" EIUITPhoneScreenshots -> "phoneScreenshots" EIUITPromoGraphic -> "promoGraphic" EIUITSevenInchScreenshots -> "sevenInchScreenshots" EIUITTenInchScreenshots -> "tenInchScreenshots" EIUITTvBanner -> "tvBanner" EIUITTvScreenshots -> "tvScreenshots" EIUITWearScreenshots -> "wearScreenshots" instance FromJSON EditsImagesUploadImageType where parseJSON = parseJSONText "EditsImagesUploadImageType" instance ToJSON EditsImagesUploadImageType where toJSON = toJSONText data EditsDeobfuscationFilesUploadDeobfuscationFileType = Proguard -- ^ @proguard@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsDeobfuscationFilesUploadDeobfuscationFileType instance FromHttpApiData EditsDeobfuscationFilesUploadDeobfuscationFileType where parseQueryParam = \case "proguard" -> Right Proguard x -> Left ("Unable to parse EditsDeobfuscationFilesUploadDeobfuscationFileType from: " <> x) instance ToHttpApiData EditsDeobfuscationFilesUploadDeobfuscationFileType where toQueryParam = \case Proguard -> "proguard" instance FromJSON EditsDeobfuscationFilesUploadDeobfuscationFileType where parseJSON = parseJSONText "EditsDeobfuscationFilesUploadDeobfuscationFileType" instance ToJSON EditsDeobfuscationFilesUploadDeobfuscationFileType where toJSON = toJSONText data EditsExpansionFilesUploadExpansionFileType = Main -- ^ @main@ | Patch' -- ^ @patch@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsExpansionFilesUploadExpansionFileType instance FromHttpApiData EditsExpansionFilesUploadExpansionFileType where parseQueryParam = \case "main" -> Right Main "patch" -> Right Patch' x -> Left ("Unable to parse EditsExpansionFilesUploadExpansionFileType from: " <> x) instance ToHttpApiData EditsExpansionFilesUploadExpansionFileType where toQueryParam = \case Main -> "main" Patch' -> "patch" instance FromJSON EditsExpansionFilesUploadExpansionFileType where parseJSON = parseJSONText "EditsExpansionFilesUploadExpansionFileType" instance ToJSON EditsExpansionFilesUploadExpansionFileType where toJSON = toJSONText data EditsExpansionFilesGetExpansionFileType = EEFGEFTMain -- ^ @main@ | EEFGEFTPatch' -- ^ @patch@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsExpansionFilesGetExpansionFileType instance FromHttpApiData EditsExpansionFilesGetExpansionFileType where parseQueryParam = \case "main" -> Right EEFGEFTMain "patch" -> Right EEFGEFTPatch' x -> Left ("Unable to parse EditsExpansionFilesGetExpansionFileType from: " <> x) instance ToHttpApiData EditsExpansionFilesGetExpansionFileType where toQueryParam = \case EEFGEFTMain -> "main" EEFGEFTPatch' -> "patch" instance FromJSON EditsExpansionFilesGetExpansionFileType where parseJSON = parseJSONText "EditsExpansionFilesGetExpansionFileType" instance ToJSON EditsExpansionFilesGetExpansionFileType where toJSON = toJSONText data EditsExpansionFilesPatchExpansionFileType = EEFPEFTMain -- ^ @main@ | EEFPEFTPatch' -- ^ @patch@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsExpansionFilesPatchExpansionFileType instance FromHttpApiData EditsExpansionFilesPatchExpansionFileType where parseQueryParam = \case "main" -> Right EEFPEFTMain "patch" -> Right EEFPEFTPatch' x -> Left ("Unable to parse EditsExpansionFilesPatchExpansionFileType from: " <> x) instance ToHttpApiData EditsExpansionFilesPatchExpansionFileType where toQueryParam = \case EEFPEFTMain -> "main" EEFPEFTPatch' -> "patch" instance FromJSON EditsExpansionFilesPatchExpansionFileType where parseJSON = parseJSONText "EditsExpansionFilesPatchExpansionFileType" instance ToJSON EditsExpansionFilesPatchExpansionFileType where toJSON = toJSONText data EditsExpansionFilesUpdateExpansionFileType = EEFUEFTMain -- ^ @main@ | EEFUEFTPatch' -- ^ @patch@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsExpansionFilesUpdateExpansionFileType instance FromHttpApiData EditsExpansionFilesUpdateExpansionFileType where parseQueryParam = \case "main" -> Right EEFUEFTMain "patch" -> Right EEFUEFTPatch' x -> Left ("Unable to parse EditsExpansionFilesUpdateExpansionFileType from: " <> x) instance ToHttpApiData EditsExpansionFilesUpdateExpansionFileType where toQueryParam = \case EEFUEFTMain -> "main" EEFUEFTPatch' -> "patch" instance FromJSON EditsExpansionFilesUpdateExpansionFileType where parseJSON = parseJSONText "EditsExpansionFilesUpdateExpansionFileType" instance ToJSON EditsExpansionFilesUpdateExpansionFileType where toJSON = toJSONText data EditsImagesDeleteImageType = EIDITFeatureGraphic -- ^ @featureGraphic@ | EIDITIcon -- ^ @icon@ | EIDITPhoneScreenshots -- ^ @phoneScreenshots@ | EIDITPromoGraphic -- ^ @promoGraphic@ | EIDITSevenInchScreenshots -- ^ @sevenInchScreenshots@ | EIDITTenInchScreenshots -- ^ @tenInchScreenshots@ | EIDITTvBanner -- ^ @tvBanner@ | EIDITTvScreenshots -- ^ @tvScreenshots@ | EIDITWearScreenshots -- ^ @wearScreenshots@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsImagesDeleteImageType instance FromHttpApiData EditsImagesDeleteImageType where parseQueryParam = \case "featureGraphic" -> Right EIDITFeatureGraphic "icon" -> Right EIDITIcon "phoneScreenshots" -> Right EIDITPhoneScreenshots "promoGraphic" -> Right EIDITPromoGraphic "sevenInchScreenshots" -> Right EIDITSevenInchScreenshots "tenInchScreenshots" -> Right EIDITTenInchScreenshots "tvBanner" -> Right EIDITTvBanner "tvScreenshots" -> Right EIDITTvScreenshots "wearScreenshots" -> Right EIDITWearScreenshots x -> Left ("Unable to parse EditsImagesDeleteImageType from: " <> x) instance ToHttpApiData EditsImagesDeleteImageType where toQueryParam = \case EIDITFeatureGraphic -> "featureGraphic" EIDITIcon -> "icon" EIDITPhoneScreenshots -> "phoneScreenshots" EIDITPromoGraphic -> "promoGraphic" EIDITSevenInchScreenshots -> "sevenInchScreenshots" EIDITTenInchScreenshots -> "tenInchScreenshots" EIDITTvBanner -> "tvBanner" EIDITTvScreenshots -> "tvScreenshots" EIDITWearScreenshots -> "wearScreenshots" instance FromJSON EditsImagesDeleteImageType where parseJSON = parseJSONText "EditsImagesDeleteImageType" instance ToJSON EditsImagesDeleteImageType where toJSON = toJSONText data EditsTestersUpdateTrack = EDIAlpha -- ^ @alpha@ | EDIBeta -- ^ @beta@ | EDIProduction -- ^ @production@ | EDIRollout -- ^ @rollout@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EditsTestersUpdateTrack instance FromHttpApiData EditsTestersUpdateTrack where parseQueryParam = \case "alpha" -> Right EDIAlpha "beta" -> Right EDIBeta "production" -> Right EDIProduction "rollout" -> Right EDIRollout x -> Left ("Unable to parse EditsTestersUpdateTrack from: " <> x) instance ToHttpApiData EditsTestersUpdateTrack where toQueryParam = \case EDIAlpha -> "alpha" EDIBeta -> "beta" EDIProduction -> "production" EDIRollout -> "rollout" instance FromJSON EditsTestersUpdateTrack where parseJSON = parseJSONText "EditsTestersUpdateTrack" instance ToJSON EditsTestersUpdateTrack where toJSON = toJSONText
rueshyna/gogol
gogol-android-publisher/gen/Network/Google/AndroidPublisher/Types/Sum.hs
mpl-2.0
18,599
0
11
4,108
3,158
1,648
1,510
395
0
{-# LANGUAGE TemplateHaskell #-} module HQueries.TH( deriveQType , deriveQKey , makeQLenses ) where import Language.Haskell.TH import HQueries.Internal import Data.Text (Text) import qualified Data.Text as T import qualified Data.String.Utils as SU import Data.Maybe import Control.Lens con2ArgTypes :: Con -> [Type] con2ArgTypes (NormalC _ subs) = map (\(_,x) -> x) subs con2ArgTypes (RecC _ subs) = map (\(_,_,x) -> x) subs con2ArgNames :: Con -> Maybe [Name] con2ArgNames (RecC _ subs) = Just $ map (\(x,_,_) -> x) subs con2ArgNames _ = Nothing con2Vars :: String -> Con -> Q [Name] con2Vars z c = mapM (\_ -> newName z) (con2ArgTypes c) con2Name :: Con -> Name con2Name (NormalC name _) = name con2Name (RecC name _) = name con2clause_toQuery :: Con -> ClauseQ con2clause_toQuery c = do vars <- con2Vars "x" c let n = con2Name c clause [conP n (map varP vars)] (normalB $ appE (conE 'ASTProdTypeLit) (listE $ map (\x -> [|QueryObj (toQuery $(varE x))|]) vars) ) [] con2clause_parseQueryRes :: Con -> ClauseQ con2clause_parseQueryRes c = do bs <- newName "bs" xs <- con2Vars "x" c rs <- con2Vars "r" c let n = con2Name c let l = zip3 xs rs (bs:(init rs)) clause [varP bs] (normalB $ letE (map (\(x,r,last) -> valD (tupP [varP x, varP r]) (normalB [|parseQueryRes $(varE last)|]) []) l) [|($(applyArgs (conE n) (map varE xs)), $(varE (last rs)))|] ) [] type2QTypeRep :: Type -> ExpQ -- QTypeRep type2QTypeRep (ConT x) | x == ''Integer = [|QTypeRepInt|] type2QTypeRep (ConT x) | x == ''Text = [|QTypeRepText|] nameExp :: Name -> ExpQ nameExp n = [| T.pack $(return $ LitE $ StringL $ showName n)|] con2clause_getQTypeRep :: Name -> Con -> ClauseQ con2clause_getQTypeRep tyName c = let tname = nameExp tyName cname = nameExp $ con2Name c names = case con2ArgNames c of Nothing -> [|Nothing|] Just names -> [|Just $ map T.pack $(return $ ListE $ (map (LitE . StringL . showName) names))|] in clause [wildP] (normalB $ [|QTypeRepProd (QTypeRepProdHead $tname $cname) $names $(listE $ map type2QTypeRep $ con2ArgTypes c )|]) [] applyArgs :: ExpQ -> [ExpQ] -> ExpQ applyArgs f args = foldr (\a l -> appE l a) f args makeQLensesAux :: Name -> [(Name, Type, Int)] -> DecsQ makeQLensesAux n l = concat `fmap` mapM (makeQLens n) l makeLensQName :: Name -> Name makeLensQName n = mkName $ (tail $ showName n) ++ "Q" makeQLens :: Name -> (Name, Type, Int) -> DecsQ makeQLens n (cn, ctp, pos) = do let ln = makeLensQName cn body <- [|lens (ASTProjection pos) undefined|] return $ [ SigD ln (AppT (AppT (ConT ''Lens') (AppT (ConT ''Query) $ ConT n)) (AppT (ConT ''Query) ctp)) , ValD (VarP ln) (NormalB (body)) []] makeQLenses :: Name -> DecsQ makeQLenses tyName = do (TyConI tpDec) <- reify tyName case tpDec of (DataD _ _ [] [con] _) -> makeQLensesAux (tyName) $ zip3 (fromJust $ con2ArgNames con) (con2ArgTypes con) [1..] deriveQKey :: Name -> DecsQ deriveQKey tyName = do let txtName = ''Text (TyConI (NewtypeD [] _ [] (NormalC consName [(NotStrict, (ConT txtName))]) [])) <- reify tyName x <- newName "x" iDec <- instanceD (return []) (appT (conT ''QKey) (conT tyName)) [ funD 'key2text [ clause [conP consName [varP x]] (normalB $ varE x) [] ], funD 'text2key [ clause [varP x] (normalB $ appE (conE consName) (varE x)) [] ] ] qtDec <- deriveQType tyName return $ qtDec ++ [iDec] deriveQType :: Name -> DecsQ deriveQType tyName = do (TyConI tpDec) <- reify tyName let tname = nameExp tyName x <- newName "x" iDec <- case tpDec of (DataD _ _ [] [con] _) -> instanceD (return []) (appT (conT ''QType) (conT tyName) ) [ funD 'toQuery [ con2clause_toQuery con ], funD 'parseQueryRes [ con2clause_parseQueryRes con ], funD 'getQTypeRep [ con2clause_getQTypeRep tyName con ] ] (NewtypeD [] _ [] (NormalC conName [(NotStrict, (ConT conType))]) []) -> instanceD (return []) (appT (conT ''QType) (conT tyName) ) [ funD 'toQuery [ clause [conP conName [varP x]] (normalB $ [|ASTNewTypeLit $ toQuery $(varE x)|]) [] ], funD 'parseQueryRes [ clause [varP x] (normalB [|let (a,b) = parseQueryRes $(varE x) in ( $(conE conName) a, b)|]) [] ], funD 'getQTypeRep [ clause [wildP] (normalB $ [|QTypeRepNewType $tname $(type2QTypeRep $ ConT conType)|]) [] ] ] return [iDec] showName :: Name -> String showName n = last $ SU.split "." $ show n
premium-minds/h-queries
HQueries/TH.hs
lgpl-3.0
5,387
0
19
1,887
1,878
978
900
125
2
{-# LANGUAGE CPP,NamedFieldPuns, RecordWildCards #-} -- #define RCS_DEBUG module StearnsWharf.Steel.HatProfiles where import StearnsWharf.Common (BeamTypeId) import qualified StearnsWharf.Profiles as P import qualified StearnsWharf.Steel.HUP as H import qualified StearnsWharf.Steel.Plates as Pl data HatProfile -- | Hatteprofil m/ HUP og gj.gående bunnplate = HatProfileA { hup :: H.HUP, plate :: Pl.Plate } -- | Norsk Stålforbund utviklet to-/ensidig hatteprofil -- eks. tosidig: THP 250 x 6 - 200 x 30 - 462 x 15 -- eks. ensidig: EHP 250 x 6 - 200 x 30 - 352 x 15 | TEHP { topPl :: Pl.Plate, -- ^ Topplate webPl :: Pl.Plate, -- ^ Stegplater, behandles som to stk selv om angitt som en botPl :: Pl.Plate -- ^ Bunnplate } deriving Show createTEHP :: Double -- ^ Høyde for hatten over bunnplate [mm] -> Double -- ^ Tykkelse for stegplater [mm] -> Double -- ^ Bredde for topplate [mm] -> Double -- ^ Tykkelse for topplate [mm] -> Double -- ^ Bredde for bunnplate [mm] -> Double -- ^ Tykkelse for bunnplate [mm] -> HatProfile createTEHP h tw bo to bu tu = TEHP topP webP botP where topP = Pl.Plate bo to webP = Pl.Plate tw (h - tw) -- ^ h - tw pga geometri avslutning m/ kilsveis (se bilde div/THP.png) botP = Pl.Plate bu tu instance P.Profile HatProfile where sigma hp m = m / (1000.0 * (P.sectionModulus hp)) tau profile shr = (3.0*shr) / (2000.0 * (P.area profile)) area TEHP { topPl,webPl,botPl } = (P.area topPl) + (2*(P.area webPl)) + (P.area botPl) area HatProfileA { hup,plate } = (P.area hup) + (P.area plate) emodulus hp = 200000.0 sectionModulus hat@HatProfileA { hup, plate } = sam / y where sam = P.secondAreaMoment hat y = max c cy cy = hh + ph - c c = P.centroid hat hh = (H.h hup) / 1000.0 ph = (Pl.h plate) / 1000.0 sectionModulus hat@TEHP { .. } = sam / y where sam = P.secondAreaMoment hat cc = P.centroid hat hh = totalHeight hat y | hh / 2.0 > cc = hh - cc | otherwise = cc secondAreaMoment hat@(HatProfileA { hup, plate }) = huI + plateI + cenHupI + cenPlateI where huI = P.secondAreaMoment hup plateI = P.secondAreaMoment plate c = P.centroid hat cenHup = P.centroid hup cenPlate = P.centroid plate cenHupI = (P.area hup) * ((c - cenHup)**2) cenPlateI = P.area plate * ((c - cenPlate)**2) secondAreaMoment hat@TEHP { .. } = ii + (at*dt*dt) + (ab*db*db) + (aw*dw*dw) where ii = (P.secondAreaMoment topPl) + ((P.secondAreaMoment webPl)*2.0) + (P.secondAreaMoment botPl) hb = (Pl.h botPl) / 1000.0 -- hw = (Pl.h webPl) / 1000.0 hw = webHeight hat at = P.area topPl aw = 2.0 * (P.area webPl) ab = P.area botPl cc = P.centroid hat dt = hb + hw - cc - (P.centroid topPl) -- ^ distance form centroid top to main centroid dw = (P.centroid webPl) + hb - cc -- ^ distance form centroid web to main centroid db = cc - (P.centroid botPl) -- ^ distance form centroid bottom to main centroid centroid hat@HatProfileA { hup,plate } = (pca + huca) / (P.area hat) where pc = P.centroid plate huc = (P.centroid hup) + ((Pl.h plate) / 1000.0) pca = pc * (P.area plate) huca = huc * (P.area hup) centroid hat@TEHP { .. } = ((ct*at) + (cw*aw) + (cb*ab)) / area where hb = (Pl.h botPl) / 1000.0 hw = webHeight hat ct = hw + hb - (P.centroid topPl) cw = (P.centroid webPl) + ((Pl.h botPl) / 2000.0) cb = P.centroid botPl at = P.area topPl aw = 2.0 * (P.area webPl) ab = P.area botPl area = at + aw + ab -- | Total høyde for profilet totalHeight :: HatProfile -> Double totalHeight TEHP { webPl,botPl } = (Pl.h webPl + Pl.h botPl) / 1000.0 -- | Total høyde på "hatten" over bunnplaten webHeight :: HatProfile -> Double webHeight TEHP { webPl } = (Pl.h webPl + Pl.b webPl) / 1000.0
baalbek/stearnswharf
src/StearnsWharf/Steel/HatProfiles.hs
lgpl-3.0
4,526
0
14
1,605
1,376
740
636
84
1
-- http://blog.tmorris.net/posts/20-intermediate-haskell-exercises/index.html class Fluffy f where furry :: (a -> b) -> f a -> f b -- Exercise 1 -- Relative Difficulty: 1 instance Fluffy [] where furry = map -- Exercise 2 -- Relative Difficulty: 1 instance Fluffy Maybe where furry _ Nothing = Nothing furry f (Just a) = Just (f a) -- Exercise 3 -- Relative Difficulty: 5 instance Fluffy ((->) t) where furry = (.) newtype EitherLeft b a = EitherLeft (Either a b) deriving (Show) newtype EitherRight a b = EitherRight (Either a b) -- Exercise 4 -- Relative Difficulty: 5 instance Fluffy (EitherLeft t) where furry _ (EitherLeft (Right b)) = EitherLeft (Right b) furry f (EitherLeft (Left a)) = EitherLeft (Left (f a)) -- Exercise 5 -- Relative Difficulty: 5 instance Fluffy (EitherRight t) where furry f (EitherRight (Right b)) = EitherRight (Right (f b)) furry _ (EitherRight (Left a)) = EitherRight (Left a) class Misty m where banana :: (a -> m b) -> m a -> m b unicorn :: a -> m a -- Exercise 6 -- Relative Difficulty: 3 -- (use banana and/or unicorn) furry' :: (a -> b) -> m a -> m b furry' f = banana (unicorn . f) -- Exercise 7 -- Relative Difficulty: 2 instance Misty [] where banana f xs = concat $ map f xs unicorn = (:[]) -- Exercise 8 -- Relative Difficulty: 2 instance Misty Maybe where banana _ Nothing = Nothing banana f (Just a) = f a unicorn = Just -- Exercise 9 -- Relative Difficulty: 6 instance Misty ((->) t) where banana f a = \r -> f (a r) r unicorn = const -- Exercise 10 -- Relative Difficulty: 6 instance Misty (EitherLeft t) where banana _ (EitherLeft (Right b)) = (EitherLeft (Right b)) banana f (EitherLeft (Left a)) = f a unicorn = EitherLeft . Left -- Exercise 11 -- Relative Difficulty: 6 instance Misty (EitherRight t) where banana _ (EitherRight (Left b)) = (EitherRight (Left b)) banana f (EitherRight (Right a)) = f a unicorn = EitherRight . Right -- Exercise 12 -- Relative Difficulty: 3 jellybean :: (Misty m) => m (m a) -> m a jellybean = banana id -- Exercise 13 -- Relative Difficulty: 6 apple :: (Misty m) => m a -> m (a -> b) -> m b apple a f = banana (\a' -> banana (\f' -> unicorn (f' a')) f) a -- Exercise 14 -- Relative Difficulty: 6 moppy :: (Misty m) => [a] -> (a -> m b) -> m [b] moppy a f = foldr k (unicorn []) (map f a) where k m m' = banana (\x -> banana (\xs -> unicorn (x:xs)) m') m -- Exercise 15 -- Relative Difficulty: 6 -- (bonus: use moppy) sausage :: (Misty m) => [m a] -> m [a] sausage a = moppy a id -- Exercise 16 -- Relative Difficulty: 6 -- (bonus: use apple + furry') banana2 :: (Misty m) => (a -> b -> c) -> m a -> m b -> m c banana2 f a b = apple b (furry' f a) -- Exercise 17 -- Relative Difficulty: 6 -- (bonus: use apple + banana2) banana3 :: (Misty m) => (a -> b -> c -> d) -> m a -> m b -> m c -> m d banana3 f a b c = apple c (banana2 f a b) -- Exercise 18 -- Relative Difficulty: 6 -- (bonus: use apple + banana3) banana4 :: (Misty m) => (a -> b -> c -> d -> e) -> m a -> m b -> m c -> m d -> m e banana4 f a b c d = apple d (banana3 f a b c) newtype State s a = State { state :: (s -> (s, a)) } -- Exercise 19 -- Relative Difficulty: 9 instance Fluffy (State s) where furry f s = State $ \t -> let (q, a) = state s t in (q, f a) -- Exercise 20 -- Relative Difficulty: 10 instance Misty (State s) where banana f s = State $ \x -> let (q, a) = state s x in state (f a) q unicorn a = State $ \s -> (s, a)
jstolarek/sandbox
haskell/20.intermediate.haskell.exercises.hs
unlicense
3,535
0
15
867
1,486
777
709
64
1
{-# LANGUAGE OverloadedStrings #-} module CountdownGame.State ( State (..) , Round (..) , initState , setAttempt , takeSnapshot , initialCompletions , completions )where import Data.Text (Text, pack) import qualified Data.Map.Strict as M import Countdown.Game (Attempt, attempt, Challange, Player, PlayerId, playerId, score, availableNumbers) import qualified Countdown.Completion as CC import CountdownGame.References import CountdownGame.State.Definitions (State (..), Round (..)) import CountdownGame.State.Snapshots (takeSnapshot) import CountdownGame.Database (setPlayerScore, createPool) initialCompletions :: State -> IO [(Text, (CC.Input, CC.Expression))] initialCompletions state = do rd <- readRef id $ currentRound state case rd of Nothing -> return [] Just rd' -> do let nrs = availableNumbers $ challange rd' return $ map (\ (i,e) -> (pack (show i), (i,e))) $CC.start nrs completions :: State -> (CC.Input, CC.Expression) -> IO [(Text, (CC.Input, CC.Expression))] completions state inp = do rd <- readRef id $ currentRound state case rd of Nothing -> return [] Just rd' -> do let nrs = availableNumbers $ challange rd' return $ map (\ (i,e) -> (pack (show i), (i,e))) $ CC.next nrs inp setAttempt :: State -> Player -> Text -> IO (Maybe Attempt) setAttempt state p txt = do rd <- readRef id $ currentRound state case rd of Just rd' -> do let ch = challange rd' cId = databaseKey rd' at <- modifyRef (attempt ch txt p) $ playerAttempts state setPlayerScore cId (playerId p) (score at) return $ Just at Nothing -> return Nothing initState :: Int -> IO State initState nrPoolCons = do emptyR <- emptyRoundState emptyP <- emptyChallange noGuesses <- createRef M.empty pool <- createPool nrPoolCons return $ State emptyR emptyP noGuesses pool emptyRoundState :: IO (Reference (Maybe Round)) emptyRoundState = createRef Nothing emptyChallange :: IO (Reference (Maybe Challange)) emptyChallange = createRef Nothing
CarstenKoenig/DOS2015
CountdownGame/src/web/CountdownGame/State.hs
unlicense
2,097
0
20
457
761
396
365
55
2
{-# LANGUAGE PolyKinds #-} module Data.Container.Type where import Prelude --type family In (a :: a) (cont :: c) :: Bool --type instance In a '[] = False --type instance In a '[] = False type family In a lst where In a (a ': ls) = True In a (l ': ls) = In a ls In a '[] = False
wdanilo/container
src/Data/Container/Type.hs
apache-2.0
300
0
8
83
79
46
33
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Refile where import Control.Applicative import qualified Data.Text as T import System.Directory import System.FilePath import Data.RDF import Util import Import fileByDate :: FilePath -> FilePath -> IO () fileByDate directoryRoot f = do putStrLn f tris <- readFileMeta f case query tris Nothing (Just . unode $ "meta:creation-date") Nothing of [] -> return () (tri:_) -> case object tri of LNode l -> case dirByDate <$> (parse8601 . T.unpack . lText $ l) of Nothing -> return () Just dir -> do let dirPath = directoryRoot </> dir createDirectoryIfMissing True dirPath renameFile f (dirPath </> takeFileName f) example :: FilePath -> IO () example fromDir = do files <- getDirectoryContents fromDir mapM_ (fileByDate "photos" . (fromDir </>)) $ filter (matchExtension ".jpg") files
bergey/metastic
src/Refile.hs
bsd-2-clause
904
0
21
207
303
150
153
26
3
{-| Module : Idris.Core.Evaluate Description : Evaluate Idris expressions. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE BangPatterns, DeriveGeneric, FlexibleInstances, MultiParamTypeClasses, PatternGuards #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Core.Evaluate(normalise, normaliseTrace, normaliseC, normaliseAll, normaliseBlocking, toValue, quoteTerm, rt_simplify, simplify, inlineSmall, specialise, unfold, convEq, convEq', Def(..), CaseInfo(..), CaseDefs(..), Accessibility(..), Injectivity, Totality(..), PReason(..), MetaInformation(..), Context, initContext, ctxtAlist, next_tvar, addToCtxt, setAccess, setInjective, setTotal, setRigCount, setMetaInformation, addCtxtDef, addTyDecl, addDatatype, addCasedef, simplifyCasedef, addOperator, lookupNames, lookupTyName, lookupTyNameExact, lookupTy, lookupTyExact, lookupP, lookupP_all, lookupDef, lookupNameDef, lookupDefExact, lookupDefAcc, lookupDefAccExact, lookupVal, mapDefCtxt, tcReducible, lookupTotal, lookupTotalExact, lookupInjectiveExact, lookupRigCount, lookupRigCountExact, lookupNameTotal, lookupMetaInformation, lookupTyEnv, isTCDict, isCanonical, isDConName, canBeDConName, isTConName, isConName, isFnName, Value(..), Quote(..), initEval, uniqueNameCtxt, uniqueBindersCtxt, definitions, isUniverse, linearCheck, linearCheckArg) where import Idris.Core.CaseTree import Idris.Core.TT import Control.Applicative hiding (Const) import Control.Monad.State import Data.Binary hiding (get, put) import qualified Data.Binary as B import Data.Maybe (listToMaybe) import Debug.Trace import GHC.Generics (Generic) data EvalState = ES { limited :: [(Name, Int)], nexthole :: Int, blocking :: Bool } deriving Show type Eval a = State EvalState a data EvalOpt = Spec | Simplify Bool -- ^ whether to expand lets or not | AtREPL | RunTT | Unfold deriving (Show, Eq) initEval = ES [] 0 False -- VALUES (as HOAS) --------------------------------------------------------- -- | A HOAS representation of values data Value = VP NameType Name Value | VV Int -- True for Bool indicates safe to reduce | VBind Bool Name (Binder Value) (Value -> Eval Value) -- For frozen let bindings when simplifying | VBLet Int Name Value Value Value | VApp Value Value | VType UExp | VUType Universe | VErased | VImpossible | VConstant Const | VProj Value Int -- | VLazy Env [Value] Term | VTmp Int canonical :: Value -> Bool canonical (VP (DCon _ _ _) _ _) = True canonical (VApp f a) = canonical f canonical (VConstant _) = True canonical (VType _) = True canonical (VUType _) = True canonical VErased = True canonical _ = False instance Show Value where show x = show $ evalState (quote 100 x) initEval instance Show (a -> b) where show x = "<<fn>>" -- THE EVALUATOR ------------------------------------------------------------ -- The environment is assumed to be "locally named" - i.e., not de Bruijn -- indexed. -- i.e. it's an intermediate environment that we have while type checking or -- while building a proof. -- | Normalise fully type checked terms (so, assume all names/let bindings resolved) normaliseC :: Context -> Env -> TT Name -> TT Name normaliseC ctxt env t = evalState (do val <- eval False ctxt [] (map finalEntry env) t [] quote 0 val) initEval -- | Normalise everything, whether abstract, private or public normaliseAll :: Context -> Env -> TT Name -> TT Name normaliseAll ctxt env t = evalState (do val <- eval False ctxt [] (map finalEntry env) t [AtREPL] quote 0 val) initEval -- | As normaliseAll, but with an explicit list of names *not* to reduce normaliseBlocking :: Context -> Env -> [Name] -> TT Name -> TT Name normaliseBlocking ctxt env blocked t = evalState (do val <- eval False ctxt (map (\n -> (n, 0)) blocked) (map finalEntry env) t [AtREPL] quote 0 val) initEval normalise :: Context -> Env -> TT Name -> TT Name normalise = normaliseTrace False normaliseTrace :: Bool -> Context -> Env -> TT Name -> TT Name normaliseTrace tr ctxt env t = evalState (do val <- eval tr ctxt [] (map finalEntry env) (finalise t) [] quote 0 val) initEval toValue :: Context -> Env -> TT Name -> Value toValue ctxt env t = evalState (eval False ctxt [] (map finalEntry env) t []) initEval quoteTerm :: Value -> TT Name quoteTerm val = evalState (quote 0 val) initEval -- Return a specialised name, and an updated list of reductions available, -- so that the caller can tell how much specialisation was achieved. specialise :: Context -> Env -> [(Name, Int)] -> TT Name -> (TT Name, [(Name, Int)]) specialise ctxt env limits t = let (tm, st) = runState (do val <- eval False ctxt [] (map finalEntry env) (finalise t) [Spec] quote 0 val) (initEval { limited = limits }) in (tm, limited st) -- | Like normalise, but we only reduce functions that are marked as okay to -- inline, and lets simplify :: Context -> Env -> TT Name -> TT Name simplify ctxt env t = evalState (do val <- eval False ctxt [(sUN "lazy", 0), (sUN "force", 0), (sUN "Force", 0), (sUN "assert_smaller", 0), (sUN "assert_total", 0), (sUN "par", 0), (sUN "prim__syntactic_eq", 0), (sUN "fork", 0)] (map finalEntry env) (finalise t) [Simplify True] quote 0 val) initEval -- | Like simplify, but we only reduce functions that are marked as okay to -- inline, and don't reduce lets inlineSmall :: Context -> Env -> TT Name -> TT Name inlineSmall ctxt env t = evalState (do val <- eval False ctxt [] (map finalEntry env) (finalise t) [Simplify False] quote 0 val) initEval -- | Simplify for run-time (i.e. basic inlining) rt_simplify :: Context -> Env -> TT Name -> TT Name rt_simplify ctxt env t = evalState (do val <- eval False ctxt [(sUN "lazy", 0), (sUN "force", 0), (sUN "Force", 0), (sUN "par", 0), (sUN "prim__syntactic_eq", 0), (sUN "prim_fork", 0)] (map finalEntry env) (finalise t) [RunTT] quote 0 val) initEval -- | Unfold the given names in a term, the given number of times in a stack. -- Preserves 'let'. -- This is primarily to support inlining of the given names, and can also -- help with partial evaluation by allowing a rescursive definition to be -- unfolded once only. -- Specifically used to unfold definitions using interfaces before going to -- the totality checker (otherwise mutually recursive definitions in -- implementations will not work...) unfold :: Context -> Env -> [(Name, Int)] -> TT Name -> TT Name unfold ctxt env ns t = evalState (do val <- eval False ctxt ns (map finalEntry env) (finalise t) [Unfold] quote 0 val) initEval -- unbindEnv env (quote 0 (eval ctxt (bindEnv env t))) finalEntry :: (Name, RigCount, Binder (TT Name)) -> (Name, RigCount, Binder (TT Name)) finalEntry (n, r, b) = (n, r, fmap finalise b) bindEnv :: EnvTT n -> TT n -> TT n bindEnv [] tm = tm bindEnv ((n, r, Let t v):bs) tm = Bind n (NLet t v) (bindEnv bs tm) bindEnv ((n, r, b):bs) tm = Bind n b (bindEnv bs tm) unbindEnv :: EnvTT n -> TT n -> TT n unbindEnv [] tm = tm unbindEnv (_:bs) (Bind n b sc) = unbindEnv bs sc unbindEnv env tm = error "Impossible case occurred: couldn't unbind env." usable :: Bool -- specialising -> Bool -- unfolding only -> Int -- Reduction depth limit (when simplifying/at REPL) -> Name -> [(Name, Int)] -> Eval (Bool, [(Name, Int)]) -- usable _ _ ns@((MN 0 "STOP", _) : _) = return (False, ns) usable False uf depthlimit n [] = return (True, []) usable True uf depthlimit n ns = do ES ls num b <- get if b then return (False, ns) else case lookup n ls of Just 0 -> return (False, ns) Just i -> return (True, ns) _ -> return (False, ns) usable False uf depthlimit n ns = case lookup n ns of Just 0 -> return (False, ns) Just i -> return $ (True, (n, abs (i-1)) : filter (\ (n', _) -> n/=n') ns) _ -> return $ if uf then (False, ns) else (True, (n, depthlimit) : filter (\ (n', _) -> n/=n') ns) fnCount :: Int -> Name -> Eval () fnCount inc n = do ES ls num b <- get case lookup n ls of Just i -> do put $ ES ((n, (i - inc)) : filter (\ (n', _) -> n/=n') ls) num b _ -> return () setBlock :: Bool -> Eval () setBlock b = do ES ls num _ <- get put (ES ls num b) deduct = fnCount 1 reinstate = fnCount (-1) -- | Evaluate in a context of locally named things (i.e. not de Bruijn indexed, -- such as we might have during construction of a proof) -- The (Name, Int) pair in the arguments is the maximum depth of unfolding of -- a name. The corresponding pair in the state is the maximum number of -- unfoldings overall. eval :: Bool -> Context -> [(Name, Int)] -> Env -> TT Name -> [EvalOpt] -> Eval Value eval traceon ctxt ntimes genv tm opts = ev ntimes [] True [] tm where spec = Spec `elem` opts simpl = Simplify True `elem` opts || Simplify False `elem` opts simpl_inline = Simplify False `elem` opts runtime = RunTT `elem` opts atRepl = AtREPL `elem` opts unfold = Unfold `elem` opts noFree = all canonical . map snd -- returns 'True' if the function should block -- normal evaluation should return false blockSimplify (CaseInfo inl always dict) n stk | runtime = if always then False else not (inl || dict) || elem n stk | simpl = (not inl || elem n stk) || (n == sUN "prim__syntactic_eq") | otherwise = False getCases cd | simpl = cases_compiletime cd | runtime = cases_runtime cd | otherwise = cases_compiletime cd ev ntimes stk top env (P _ n ty) | Just (Let t v) <- lookupBinder n genv = ev ntimes stk top env v ev ntimes_in stk top env (P Ref n ty) = do let limit = if simpl then 100 else 10000 (u, ntimes) <- usable spec unfold limit n ntimes_in let red = u && (tcReducible n ctxt || spec || (atRepl && noFree env) || runtime || unfold || sUN "assert_total" `elem` stk) if red then do let val = lookupDefAccExact n (spec || unfold || (atRepl && noFree env) || runtime) ctxt case val of Just (Function _ tm, Public) -> ev ntimes (n:stk) True env tm Just (TyDecl nt ty, _) -> do vty <- ev ntimes stk True env ty return $ VP nt n vty Just (CaseOp ci _ _ _ _ cd, acc) | (acc == Public || acc == Hidden) && -- || sUN "assert_total" `elem` stk) && null (fst (cases_compiletime cd)) -> -- unoptimised version let (ns, tree) = getCases cd in if blockSimplify ci n stk then liftM (VP Ref n) (ev ntimes stk top env ty) else -- traceWhen runtime (show (n, ns, tree)) $ do c <- evCase ntimes n (n:stk) top env ns [] tree case c of (Nothing, _) -> liftM (VP Ref n) (ev ntimes stk top env ty) (Just v, _) -> return v _ -> liftM (VP Ref n) (ev ntimes stk top env ty) else liftM (VP Ref n) (ev ntimes stk top env ty) ev ntimes stk top env (P nt n ty) = liftM (VP nt n) (ev ntimes stk top env ty) ev ntimes stk top env (V i) | i < length env && i >= 0 = return $ snd (env !! i) | otherwise = return $ VV i ev ntimes stk top env (Bind n (Let t v) sc) | (not (runtime || simpl_inline || unfold)) || occurrences n sc < 2 = do v' <- ev ntimes stk top env v --(finalise v) sc' <- ev ntimes stk top ((n, v') : env) sc wknV (-1) sc' | otherwise = do t' <- ev ntimes stk top env t v' <- ev ntimes stk top env v --(finalise v) -- use Tmp as a placeholder, then make it a variable reference -- again when evaluation finished hs <- get let vd = nexthole hs put (hs { nexthole = vd + 1 }) sc' <- ev ntimes stk top ((n, VP Bound (sMN vd "vlet") VErased) : env) sc return $ VBLet vd n t' v' sc' ev ntimes stk top env (Bind n (NLet t v) sc) = do t' <- ev ntimes stk top env (finalise t) v' <- ev ntimes stk top env (finalise v) sc' <- ev ntimes stk top ((n, v') : env) sc return $ VBind True n (Let t' v') (\x -> return sc') ev ntimes stk top env (Bind n b sc) = do b' <- vbind env b let n' = uniqueName n (map fstEnv genv ++ map fst env) return $ VBind True -- (vinstances 0 sc < 2) n' b' (\x -> ev ntimes stk False ((n', x):env) sc) where vbind env t = fmapMB (\tm -> ev ntimes stk top env (finalise tm)) t -- block reduction immediately under codata (and not forced) ev ntimes stk top env (App _ (App _ (App _ d@(P _ (UN dly) _) l@(P _ (UN lco) _)) t) arg) | dly == txt "Delay" && lco == txt "Infinite" && not (unfold || simpl) = do let (f, _) = unApply arg let ntimes' = case f of P _ fn _ -> (fn, 0) : ntimes _ -> ntimes when spec $ setBlock True d' <- ev ntimes' stk False env d l' <- ev ntimes' stk False env l t' <- ev ntimes' stk False env t arg' <- ev ntimes' stk False env arg when spec $ setBlock False evApply ntimes' stk top env [l',t',arg'] d' -- Treat "assert_total" specially, as long as it's defined! ev ntimes stk top env (App _ (App _ (P _ n@(UN at) _) _) arg) | Just (CaseOp _ _ _ _ _ _, _) <- lookupDefAccExact n (spec || (atRepl && noFree env)|| runtime) ctxt, at == txt "assert_total" && not (simpl || unfold) = ev ntimes (n : stk) top env arg ev ntimes stk top env (App _ f a) = do f' <- ev ntimes stk False env f a' <- ev ntimes stk False env a evApply ntimes stk top env [a'] f' ev ntimes stk top env (Proj t i) = do -- evaluate dictionaries if it means the projection works t' <- ev ntimes stk top env t -- tfull' <- reapply ntimes stk top env t' [] return (doProj t' (getValArgs t')) where doProj t' (VP (DCon _ _ _) _ _, args) | i >= 0 && i < length args = args!!i doProj t' _ = VProj t' i ev ntimes stk top env (Constant c) = return $ VConstant c ev ntimes stk top env Erased = return VErased ev ntimes stk top env Impossible = return VImpossible ev ntimes stk top env (Inferred tm) = ev ntimes stk top env tm ev ntimes stk top env (TType i) = return $ VType i ev ntimes stk top env (UType u) = return $ VUType u evApply ntimes stk top env args (VApp f a) = evApply ntimes stk top env (a:args) f evApply ntimes stk top env args f = apply ntimes stk top env f args reapply ntimes stk top env f@(VP Ref n ty) args = let val = lookupDefAccExact n (spec || (atRepl && noFree env) || runtime) ctxt in case val of Just (CaseOp ci _ _ _ _ cd, acc) -> let (ns, tree) = getCases cd in do c <- evCase ntimes n (n:stk) top env ns args tree case c of (Nothing, _) -> return $ unload env (VP Ref n ty) args (Just v, rest) -> evApply ntimes stk top env rest v _ -> case args of (a : as) -> return $ unload env f (a : as) [] -> return f reapply ntimes stk top env (VApp f a) args = reapply ntimes stk top env f (a : args) reapply ntimes stk top env v args = return v apply ntimes stk top env (VBind True n (Lam _ t) sc) (a:as) = do a' <- sc a app <- apply ntimes stk top env a' as wknV 1 app apply ntimes_in stk top env f@(VP Ref n ty) args = do let limit = if simpl then 100 else 10000 (u, ntimes) <- usable spec unfold limit n ntimes_in let red = u && (tcReducible n ctxt || spec || (atRepl && noFree env) || unfold || runtime || sUN "assert_total" `elem` stk) if red then do let val = lookupDefAccExact n (spec || unfold || (atRepl && noFree env) || runtime) ctxt case val of Just (CaseOp ci _ _ _ _ cd, acc) | acc == Public || acc == Hidden -> -- unoptimised version let (ns, tree) = getCases cd in if blockSimplify ci n stk then return $ unload env (VP Ref n ty) args else -- traceWhen runtime (show (n, ns, tree)) $ do c <- evCase ntimes n (n:stk) top env ns args tree case c of (Nothing, _) -> return $ unload env (VP Ref n ty) args (Just v, rest) -> evApply ntimes stk top env rest v Just (Operator _ i op, _) -> if (i <= length args) then case op (take i args) of Nothing -> return $ unload env (VP Ref n ty) args Just v -> evApply ntimes stk top env (drop i args) v else return $ unload env (VP Ref n ty) args _ -> case args of [] -> return f _ -> return $ unload env f args else case args of (a : as) -> return $ unload env f (a:as) [] -> return f apply ntimes stk top env f (a:as) = return $ unload env f (a:as) apply ntimes stk top env f [] = return f -- specApply stk env f@(VP Ref n ty) args -- = case lookupCtxt n statics of -- [as] -> if or as -- then trace (show (n, map fst (filter (\ (_, s) -> s) (zip args as)))) $ -- return $ unload env f args -- else return $ unload env f args -- _ -> return $ unload env f args -- specApply stk env f args = return $ unload env f args unload :: [(Name, Value)] -> Value -> [Value] -> Value unload env f [] = f unload env f (a:as) = unload env (VApp f a) as evCase ntimes n stk top env ns args tree | length ns <= length args = do let args' = take (length ns) args let rest = drop (length ns) args when spec $ deduct n t <- evTree ntimes stk top env (zip ns args') tree when spec $ case t of Nothing -> reinstate n -- Blocked, count n again Just _ -> return () -- (zipWith (\n , t) -> (n, t)) ns args') tree return (t, rest) | otherwise = return (Nothing, args) evTree :: [(Name, Int)] -> [Name] -> Bool -> [(Name, Value)] -> [(Name, Value)] -> SC -> Eval (Maybe Value) evTree ntimes stk top env amap (UnmatchedCase str) = return Nothing evTree ntimes stk top env amap (STerm tm) = do let etm = pToVs (map fst amap) tm etm' <- ev ntimes stk (not (conHeaded tm)) (amap ++ env) etm return $ Just etm' evTree ntimes stk top env amap (ProjCase t alts) = do t' <- ev ntimes stk top env t doCase ntimes stk top env amap t' alts evTree ntimes stk top env amap (Case _ n alts) = case lookup n amap of Just v -> doCase ntimes stk top env amap v alts _ -> return Nothing evTree ntimes stk top env amap ImpossibleCase = return Nothing doCase ntimes stk top env amap v alts = do c <- chooseAlt env v (getValArgs v) alts amap case c of Just (altmap, sc) -> evTree ntimes stk top env altmap sc _ -> do c' <- chooseAlt' ntimes stk env v (getValArgs v) alts amap case c' of Just (altmap, sc) -> evTree ntimes stk top env altmap sc _ -> return Nothing conHeaded tm@(App _ _ _) | (P (DCon _ _ _) _ _, args) <- unApply tm = True conHeaded t = False chooseAlt' ntimes stk env _ (f, args) alts amap = do f' <- apply ntimes stk True env f args chooseAlt env f' (getValArgs f') alts amap chooseAlt :: [(Name, Value)] -> Value -> (Value, [Value]) -> [CaseAlt] -> [(Name, Value)] -> Eval (Maybe ([(Name, Value)], SC)) chooseAlt env _ (VP (DCon i a _) _ _, args) alts amap | Just (ns, sc) <- findTag i alts = return $ Just (updateAmap (zip ns args) amap, sc) | Just v <- findDefault alts = return $ Just (amap, v) chooseAlt env _ (VP (TCon i a) _ _, args) alts amap | Just (ns, sc) <- findTag i alts = return $ Just (updateAmap (zip ns args) amap, sc) | Just v <- findDefault alts = return $ Just (amap, v) chooseAlt env _ (VConstant c, []) alts amap | Just v <- findConst c alts = return $ Just (amap, v) | Just (n', sub, sc) <- findSuc c alts = return $ Just (updateAmap [(n',sub)] amap, sc) | Just v <- findDefault alts = return $ Just (amap, v) chooseAlt env _ (VP _ n _, args) alts amap | Just (ns, sc) <- findFn n alts = return $ Just (updateAmap (zip ns args) amap, sc) chooseAlt env _ (VBind _ _ (Pi _ i s k) t, []) alts amap | Just (ns, sc) <- findFn (sUN "->") alts = do t' <- t (VV 0) -- we know it's not in scope or it's not a pattern return $ Just (updateAmap (zip ns [s, t']) amap, sc) chooseAlt _ _ _ alts amap | Just v <- findDefault alts = if (any fnCase alts) then return $ Just (amap, v) else return Nothing | otherwise = return Nothing fnCase (FnCase _ _ _) = True fnCase _ = False -- Replace old variable names in the map with new matches -- (This is possibly unnecessary since we make unique names and don't -- allow repeated variables...?) updateAmap newm amap = newm ++ filter (\ (x, _) -> not (elem x (map fst newm))) amap findTag i [] = Nothing findTag i (ConCase n j ns sc : xs) | i == j = Just (ns, sc) findTag i (_ : xs) = findTag i xs findFn fn [] = Nothing findFn fn (FnCase n ns sc : xs) | fn == n = Just (ns, sc) findFn fn (_ : xs) = findFn fn xs findDefault [] = Nothing findDefault (DefaultCase sc : xs) = Just sc findDefault (_ : xs) = findDefault xs findSuc c [] = Nothing findSuc (BI val) (SucCase n sc : _) | val /= 0 = Just (n, VConstant (BI (val - 1)), sc) findSuc c (_ : xs) = findSuc c xs findConst c [] = Nothing findConst c (ConstCase c' v : xs) | c == c' = Just v findConst (AType (ATInt ITNative)) (ConCase n 1 [] v : xs) = Just v findConst (AType ATFloat) (ConCase n 2 [] v : xs) = Just v findConst (AType (ATInt ITChar)) (ConCase n 3 [] v : xs) = Just v findConst StrType (ConCase n 4 [] v : xs) = Just v findConst (AType (ATInt ITBig)) (ConCase n 6 [] v : xs) = Just v findConst (AType (ATInt (ITFixed ity))) (ConCase n tag [] v : xs) | tag == 7 + fromEnum ity = Just v findConst c (_ : xs) = findConst c xs getValArgs tm = getValArgs' tm [] getValArgs' (VApp f a) as = getValArgs' f (a:as) getValArgs' f as = (f, as) -- tmpToV i vd (VLetHole j) | vd == j = return $ VV i -- tmpToV i vd (VP nt n v) = liftM (VP nt n) (tmpToV i vd v) -- tmpToV i vd (VBind n b sc) = do b' <- fmapMB (tmpToV i vd) b -- let sc' = \x -> do x' <- sc x -- tmpToV (i + 1) vd x' -- return (VBind n b' sc') -- tmpToV i vd (VApp f a) = liftM2 VApp (tmpToV i vd f) (tmpToV i vd a) -- tmpToV i vd x = return x instance Eq Value where (==) x y = getTT x == getTT y where getTT v = evalState (quote 0 v) initEval class Quote a where quote :: Int -> a -> Eval (TT Name) instance Quote Value where quote i (VP nt n v) = liftM (P nt n) (quote i v) quote i (VV x) = return $ V x quote i (VBind _ n b sc) = do sc' <- sc (VTmp i) b' <- quoteB b liftM (Bind n b') (quote (i+1) sc') where quoteB t = fmapMB (quote i) t quote i (VBLet vd n t v sc) = do sc' <- quote i sc t' <- quote i t v' <- quote i v let sc'' = pToV (sMN vd "vlet") (addBinder sc') return (Bind n (Let t' v') sc'') quote i (VApp f a) = liftM2 (App MaybeHoles) (quote i f) (quote i a) quote i (VType u) = return (TType u) quote i (VUType u) = return (UType u) quote i VErased = return Erased quote i VImpossible = return Impossible quote i (VProj v j) = do v' <- quote i v return (Proj v' j) quote i (VConstant c) = return $ Constant c quote i (VTmp x) = return $ V (i - x - 1) wknV :: Int -> Value -> Eval Value wknV i (VV x) | x >= i = return $ VV (x - 1) wknV i (VBind red n b sc) = do b' <- fmapMB (wknV i) b return $ VBind red n b' (\x -> do x' <- sc x wknV (i + 1) x') wknV i (VApp f a) = liftM2 VApp (wknV i f) (wknV i a) wknV i t = return t isUniverse :: Term -> Bool isUniverse (TType _) = True isUniverse (UType _) = True isUniverse _ = False isUsableUniverse :: Term -> Bool isUsableUniverse (UType NullType) = False isUsableUniverse x = isUniverse x convEq' ctxt hs x y = evalStateT (convEq ctxt hs x y) (0, []) convEq :: Context -> [Name] -> TT Name -> TT Name -> StateT UCs TC Bool convEq ctxt holes topx topy = ceq [] topx topy where ceq :: [(Name, Name)] -> TT Name -> TT Name -> StateT UCs TC Bool ceq ps (P xt x _) (P yt y _) | x `elem` holes || y `elem` holes = return True | x == y || (x, y) `elem` ps || (y,x) `elem` ps = return True | otherwise = sameDefs ps x y ceq ps x (Bind n (Lam _ t) (App _ y (V 0))) = ceq ps x (substV (P Bound n t) y) ceq ps (Bind n (Lam _ t) (App _ x (V 0))) y = ceq ps (substV (P Bound n t) x) y ceq ps x (Bind n (Lam _ t) (App _ y (P Bound n' _))) | n == n' = ceq ps x y ceq ps (Bind n (Lam _ t) (App _ x (P Bound n' _))) y | n == n' = ceq ps x y ceq ps (Bind n (PVar _ t) sc) y = ceq ps sc y ceq ps x (Bind n (PVar _ t) sc) = ceq ps x sc ceq ps (Bind n (PVTy t) sc) y = ceq ps sc y ceq ps x (Bind n (PVTy t) sc) = ceq ps x sc ceq ps (V x) (V y) = return (x == y) ceq ps (V x) (P _ y _) | x >= 0 && length ps > x = return (fst (ps!!x) == y) | otherwise = return False ceq ps (P _ x _) (V y) | y >= 0 && length ps > y = return (x == snd (ps!!y)) | otherwise = return False ceq ps (Bind n xb xs) (Bind n' yb ys) = liftM2 (&&) (ceqB ps xb yb) (ceq ((n,n'):ps) xs ys) where ceqB ps (Let v t) (Let v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t') ceqB ps (Guess v t) (Guess v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t') ceqB ps (Pi r i v t) (Pi r' i' v' t') = liftM2 (&&) (ceq ps v v') (ceq ps t t') ceqB ps b b' = ceq ps (binderTy b) (binderTy b') -- Special case for 'case' blocks - size of scope causes complications, -- we only want to check the blocks themselves are valid and identical -- in the current scope. So, just check the bodies, and the additional -- arguments the case blocks are applied to. ceq ps x@(App _ _ _) y@(App _ _ _) | (P _ cx _, xargs) <- unApply x, (P _ cy _, yargs) <- unApply y, caseName cx && caseName cy = sameCase ps cx cy xargs yargs ceq ps (App _ fx ax) (App _ fy ay) = liftM2 (&&) (ceq ps fx fy) (ceq ps ax ay) ceq ps (Constant x) (Constant y) = return (x == y) ceq ps (TType x) (TType y) | x == y = return True ceq ps (TType (UVal 0)) (TType y) = return True ceq ps (TType x) (TType y) = do (v, cs) <- get put (v, ULE x y : cs) return True ceq ps (UType AllTypes) x = return (isUsableUniverse x) ceq ps x (UType AllTypes) = return (isUsableUniverse x) ceq ps (UType u) (UType v) = return (u == v) ceq ps Erased _ = return True ceq ps _ Erased = return True ceq ps x y = return False caseeq ps (Case _ n cs) (Case _ n' cs') = caseeqA ((n,n'):ps) cs cs' where caseeqA ps (ConCase x i as sc : rest) (ConCase x' i' as' sc' : rest') = do q1 <- caseeq (zip as as' ++ ps) sc sc' q2 <- caseeqA ps rest rest' return $ x == x' && i == i' && q1 && q2 caseeqA ps (ConstCase x sc : rest) (ConstCase x' sc' : rest') = do q1 <- caseeq ps sc sc' q2 <- caseeqA ps rest rest' return $ x == x' && q1 && q2 caseeqA ps (DefaultCase sc : rest) (DefaultCase sc' : rest') = liftM2 (&&) (caseeq ps sc sc') (caseeqA ps rest rest') caseeqA ps [] [] = return True caseeqA ps _ _ = return False caseeq ps (STerm x) (STerm y) = ceq ps x y caseeq ps (UnmatchedCase _) (UnmatchedCase _) = return True caseeq ps _ _ = return False sameDefs ps x y = case (lookupDef x ctxt, lookupDef y ctxt) of ([Function _ xdef], [Function _ ydef]) -> ceq ((x,y):ps) xdef ydef ([CaseOp _ _ _ _ _ xd], [CaseOp _ _ _ _ _ yd]) -> let (_, xdef) = cases_compiletime xd (_, ydef) = cases_compiletime yd in caseeq ((x,y):ps) xdef ydef _ -> return False sameCase :: [(Name, Name)] -> Name -> Name -> [Term] -> [Term] -> StateT UCs TC Bool sameCase ps x y xargs yargs = case (lookupDef x ctxt, lookupDef y ctxt) of ([Function _ xdef], [Function _ ydef]) -> ceq ((x,y):ps) xdef ydef ([CaseOp _ _ _ _ _ xd], [CaseOp _ _ _ _ _ yd]) -> let (xin, xdef) = cases_compiletime xd (yin, ydef) = cases_compiletime yd in do liftM2 (&&) (do ok <- zipWithM (ceq ps) (drop (length xin) xargs) (drop (length yin) yargs) return (and ok)) (caseeq ((x,y):ps) xdef ydef) _ -> return False -- SPECIALISATION ----------------------------------------------------------- -- We need too much control to be able to do this by tweaking the main -- evaluator spec :: Context -> Ctxt [Bool] -> Env -> TT Name -> Eval (TT Name) spec ctxt statics genv tm = error "spec undefined" -- CONTEXTS ----------------------------------------------------------------- {-| A definition is either a simple function (just an expression with a type), a constant, which could be a data or type constructor, an axiom or as an yet undefined function, or an Operator. An Operator is a function which explains how to reduce. A CaseOp is a function defined by a simple case tree -} data Def = Function !Type !Term | TyDecl NameType !Type | Operator Type Int ([Value] -> Maybe Value) | CaseOp CaseInfo !Type ![(Type, Bool)] -- argument types, whether canonical ![Either Term (Term, Term)] -- original definition ![([Name], Term, Term)] -- simplified for totality check definition !CaseDefs deriving Generic -- [Name] SC -- Compile time case definition -- [Name] SC -- Run time cae definitions data CaseDefs = CaseDefs { cases_compiletime :: !([Name], SC), cases_runtime :: !([Name], SC) } deriving Generic data CaseInfo = CaseInfo { case_inlinable :: Bool, -- decided by machine case_alwaysinline :: Bool, -- decided by %inline flag tc_dictionary :: Bool } deriving Generic {-! deriving instance Binary Def !-} {-! deriving instance Binary CaseInfo !-} {-! deriving instance Binary CaseDefs !-} instance Show Def where show (Function ty tm) = "Function: " ++ show (ty, tm) show (TyDecl nt ty) = "TyDecl: " ++ show nt ++ " " ++ show ty show (Operator ty _ _) = "Operator: " ++ show ty show (CaseOp (CaseInfo inlc inla inlr) ty atys ps_in ps cd) = let (ns, sc) = cases_compiletime cd (ns', sc') = cases_runtime cd in "Case: " ++ show ty ++ " " ++ show ps ++ "\n" ++ "COMPILE TIME:\n\n" ++ show ns ++ " " ++ show sc ++ "\n\n" ++ "RUN TIME:\n\n" ++ show ns' ++ " " ++ show sc' ++ "\n\n" ++ if inlc then "Inlinable" else "Not inlinable" ++ if inla then " Aggressively\n" else "\n" ------- -- Hidden => Programs can't access the name at all -- Public => Programs can access the name and use at will -- Frozen => Programs can access the name, which doesn't reduce -- Private => Programs can't access the name, doesn't reduce internally data Accessibility = Hidden | Public | Frozen | Private deriving (Eq, Ord, Generic) instance Show Accessibility where show Public = "public export" show Frozen = "export" show Private = "private" show Hidden = "hidden" type Injectivity = Bool -- | The result of totality checking data Totality = Total [Int] -- ^ well-founded arguments | Productive -- ^ productive | Partial PReason | Unchecked | Generated deriving (Eq, Generic) -- | Reasons why a function may not be total data PReason = Other [Name] | Itself | NotCovering | NotPositive | UseUndef Name | ExternalIO | BelieveMe | Mutual [Name] | NotProductive deriving (Show, Eq, Generic) instance Show Totality where show (Total args)= "Total" -- ++ show args ++ " decreasing arguments" show Productive = "Productive" -- ++ show args ++ " decreasing arguments" show Unchecked = "not yet checked for totality" show (Partial Itself) = "possibly not total as it is not well founded" show (Partial NotCovering) = "not total as there are missing cases" show (Partial NotPositive) = "not strictly positive" show (Partial ExternalIO) = "an external IO primitive" show (Partial NotProductive) = "not productive" show (Partial BelieveMe) = "not total due to use of believe_me in proof" show (Partial (Other ns)) = "possibly not total due to: " ++ showSep ", " (map show ns) show (Partial (Mutual ns)) = "possibly not total due to recursive path " ++ showSep " --> " (map show ns) show (Partial (UseUndef n)) = "possibly not total because it uses the undefined name " ++ show n show Generated = "auto-generated" {-! deriving instance Binary Accessibility !-} {-! deriving instance Binary Totality !-} {-! deriving instance Binary PReason !-} -- Possible attached meta-information for a definition in context data MetaInformation = EmptyMI -- ^ No meta-information | DataMI [Int] -- ^ Meta information for a data declaration with position of parameters deriving (Eq, Show, Generic) -- | Contexts used for global definitions and for proof state. They contain -- universe constraints and existing definitions. -- Also store maximum RigCount of the name (can't bind a name at multiplicity -- 1 in a RigW, for example) data Context = MkContext { next_tvar :: Int, definitions :: Ctxt (Def, RigCount, Injectivity, Accessibility, Totality, MetaInformation) } deriving (Show, Generic) -- | The initial empty context initContext = MkContext 0 emptyContext mapDefCtxt :: (Def -> Def) -> Context -> Context mapDefCtxt f (MkContext t !defs) = MkContext t (mapCtxt f' defs) where f' (!d, r, i, a, t, m) = f' (f d, r, i, a, t, m) -- | Get the definitions from a context ctxtAlist :: Context -> [(Name, Def)] ctxtAlist ctxt = map (\(n, (d, r, i, a, t, m)) -> (n, d)) $ toAlist (definitions ctxt) veval ctxt env t = evalState (eval False ctxt [] env t []) initEval addToCtxt :: Name -> Term -> Type -> Context -> Context addToCtxt n tm ty uctxt = let ctxt = definitions uctxt !ctxt' = addDef n (Function ty tm, RigW, False, Public, Unchecked, EmptyMI) ctxt in uctxt { definitions = ctxt' } setAccess :: Name -> Accessibility -> Context -> Context setAccess n a uctxt = let ctxt = definitions uctxt !ctxt' = updateDef n (\ (d, r, i, _, t, m) -> (d, r, i, a, t, m)) ctxt in uctxt { definitions = ctxt' } setInjective :: Name -> Injectivity -> Context -> Context setInjective n i uctxt = let ctxt = definitions uctxt !ctxt' = updateDef n (\ (d, r, _, a, t, m) -> (d, r, i, a, t, m)) ctxt in uctxt { definitions = ctxt' } setTotal :: Name -> Totality -> Context -> Context setTotal n t uctxt = let ctxt = definitions uctxt !ctxt' = updateDef n (\ (d, r, i, a, _, m) -> (d, r, i, a, t, m)) ctxt in uctxt { definitions = ctxt' } setRigCount :: Name -> RigCount -> Context -> Context setRigCount n rc uctxt = let ctxt = definitions uctxt !ctxt' = updateDef n (\ (d, _, i, a, t, m) -> (d, rc, i, a, t, m)) ctxt in uctxt { definitions = ctxt' } setMetaInformation :: Name -> MetaInformation -> Context -> Context setMetaInformation n m uctxt = let ctxt = definitions uctxt !ctxt' = updateDef n (\ (d, r, i, a, t, _) -> (d, r, i, a, t, m)) ctxt in uctxt { definitions = ctxt' } addCtxtDef :: Name -> Def -> Context -> Context addCtxtDef n d c = let ctxt = definitions c !ctxt' = addDef n (d, RigW, False, Public, Unchecked, EmptyMI) $! ctxt in c { definitions = ctxt' } addTyDecl :: Name -> NameType -> Type -> Context -> Context addTyDecl n nt ty uctxt = let ctxt = definitions uctxt !ctxt' = addDef n (TyDecl nt ty, RigW, False, Public, Unchecked, EmptyMI) ctxt in uctxt { definitions = ctxt' } addDatatype :: Datatype Name -> Context -> Context addDatatype (Data n tag ty unique cons) uctxt = let ctxt = definitions uctxt ty' = normalise uctxt [] ty !ctxt' = addCons 0 cons (addDef n (TyDecl (TCon tag (arity ty')) ty, RigW, True, Public, Unchecked, EmptyMI) ctxt) in uctxt { definitions = ctxt' } where addCons tag [] ctxt = ctxt addCons tag ((n, ty) : cons) ctxt = let ty' = normalise uctxt [] ty in addCons (tag+1) cons (addDef n (TyDecl (DCon tag (arity ty') unique) ty, RigW, True, Public, Unchecked, EmptyMI) ctxt) -- FIXME: Too many arguments! Refactor all these Bools. -- -- Issue #1724 on the issue tracker. -- https://github.com/idris-lang/Idris-dev/issues/1724 addCasedef :: Name -> ErasureInfo -> CaseInfo -> Bool -> SC -> -- default case Bool -> Bool -> [(Type, Bool)] -> -- argument types, whether canonical [Int] -> -- inaccessible arguments [Either Term (Term, Term)] -> [([Name], Term, Term)] -> -- compile time [([Name], Term, Term)] -> -- run time Type -> Context -> TC Context addCasedef n ei ci@(CaseInfo inline alwaysInline tcdict) tcase covering reflect asserted argtys inacc ps_in ps_ct ps_rt ty uctxt = do let ctxt = definitions uctxt access = case lookupDefAcc n False uctxt of [(_, acc)] -> acc _ -> Public compileTime <- simpleCase tcase covering reflect CompileTime emptyFC inacc argtys ps_ct ei runtime <- simpleCase tcase covering reflect RunTime emptyFC inacc argtys ps_rt ei ctxt' <- case (compileTime, runtime) of ( CaseDef args_ct sc_ct _, CaseDef args_rt sc_rt _) -> let inl = alwaysInline -- tcdict inlc = (inl || small n args_ct sc_ct) && (not asserted) inlr = inl || small n args_rt sc_rt cdef = CaseDefs (args_ct, sc_ct) (args_rt, sc_rt) op = (CaseOp (ci { case_inlinable = inlc }) ty argtys ps_in ps_ct cdef, RigW, False, access, Unchecked, EmptyMI) in return $ addDef n op ctxt -- other -> tfail (Msg $ "Error adding case def: " ++ show other) return uctxt { definitions = ctxt' } -- simplify a definition by inlining -- (Note: This used to be for totality checking, and now it's actually a -- no-op, but I'm keeping it here because I'll be putting it back with some -- more carefully controlled inlining at some stage. --- EB) simplifyCasedef :: Name -> ErasureInfo -> Context -> TC Context simplifyCasedef n ei uctxt = do let ctxt = definitions uctxt ctxt' <- case lookupCtxt n ctxt of [(CaseOp ci ty atys [] ps _, rc, inj, acc, tot, metainf)] -> return ctxt -- nothing to simplify (or already done...) [(CaseOp ci ty atys ps_in ps cd, rc, inj, acc, tot, metainf)] -> do let ps_in' = map simpl ps_in pdef = map debind ps_in' CaseDef args sc _ <- simpleCase False (STerm Erased) False CompileTime emptyFC [] atys pdef ei return $ addDef n (CaseOp ci ty atys ps_in' ps (cd { cases_compiletime = (args, sc) }), rc, inj, acc, tot, metainf) ctxt _ -> return ctxt return uctxt { definitions = ctxt' } where depat acc (Bind n (PVar _ t) sc) = depat (n : acc) (instantiate (P Bound n t) sc) depat acc x = (acc, x) debind (Right (x, y)) = let (vs, x') = depat [] x (_, y') = depat [] y in (vs, x', y') debind (Left x) = let (vs, x') = depat [] x in (vs, x', Impossible) simpl (Right (x, y)) = Right (x, y) -- inline uctxt [] y) simpl t = t addOperator :: Name -> Type -> Int -> ([Value] -> Maybe Value) -> Context -> Context addOperator n ty a op uctxt = let ctxt = definitions uctxt ctxt' = addDef n (Operator ty a op, RigW, False, Public, Unchecked, EmptyMI) ctxt in uctxt { definitions = ctxt' } tfst (a, _, _, _, _, _) = a lookupNames :: Name -> Context -> [Name] lookupNames n ctxt = let ns = lookupCtxtName n (definitions ctxt) in map fst ns -- | Get the list of pairs of fully-qualified names and their types that match some name lookupTyName :: Name -> Context -> [(Name, Type)] lookupTyName n ctxt = do (name, def) <- lookupCtxtName n (definitions ctxt) ty <- case tfst def of (Function ty _) -> return ty (TyDecl _ ty) -> return ty (Operator ty _ _) -> return ty (CaseOp _ ty _ _ _ _) -> return ty return (name, ty) -- | Get the pair of a fully-qualified name and its type, if there is a unique one matching the name used as a key. lookupTyNameExact :: Name -> Context -> Maybe (Name, Type) lookupTyNameExact n ctxt = listToMaybe [ (nm, v) | (nm, v) <- lookupTyName n ctxt, nm == n ] -- | Get the types that match some name lookupTy :: Name -> Context -> [Type] lookupTy n ctxt = map snd (lookupTyName n ctxt) -- | Get the single type that matches some name precisely lookupTyExact :: Name -> Context -> Maybe Type lookupTyExact n ctxt = fmap snd (lookupTyNameExact n ctxt) -- | Return true if the given type is a concrete type familyor primitive -- False it it's a function to compute a type or a variable isCanonical :: Type -> Context -> Bool isCanonical t ctxt = case unApply t of (P _ n _, _) -> isConName n ctxt (Constant _, _) -> True _ -> False isConName :: Name -> Context -> Bool isConName n ctxt = isTConName n ctxt || isDConName n ctxt isTConName :: Name -> Context -> Bool isTConName n ctxt = case lookupDefExact n ctxt of Just (TyDecl (TCon _ _) _) -> True _ -> False -- | Check whether a resolved name is certainly a data constructor isDConName :: Name -> Context -> Bool isDConName n ctxt = case lookupDefExact n ctxt of Just (TyDecl (DCon _ _ _) _) -> True _ -> False -- | Check whether any overloading of a name is a data constructor canBeDConName :: Name -> Context -> Bool canBeDConName n ctxt = or $ do def <- lookupCtxt n (definitions ctxt) case tfst def of (TyDecl (DCon _ _ _) _) -> return True _ -> return False isFnName :: Name -> Context -> Bool isFnName n ctxt = case lookupDefExact n ctxt of Just (Function _ _) -> True Just (Operator _ _ _) -> True Just (CaseOp _ _ _ _ _ _) -> True _ -> False isTCDict :: Name -> Context -> Bool isTCDict n ctxt = case lookupDefExact n ctxt of Just (Function _ _) -> False Just (Operator _ _ _) -> False Just (CaseOp ci _ _ _ _ _) -> tc_dictionary ci _ -> False lookupP :: Name -> Context -> [Term] lookupP = lookupP_all False False lookupP_all :: Bool -> Bool -> Name -> Context -> [Term] lookupP_all all exact n ctxt = do (n', def) <- names p <- case def of (Function ty tm, _, inj, a, _, _) -> return (P Ref n' ty, a) (TyDecl nt ty, _, _, a, _, _) -> return (P nt n' ty, a) (CaseOp _ ty _ _ _ _, _, inj, a, _, _) -> return (P Ref n' ty, a) (Operator ty _ _, _, inj, a, _, _) -> return (P Ref n' ty, a) case snd p of Hidden -> if all then return (fst p) else [] Private -> if all then return (fst p) else [] _ -> return (fst p) where names = let ns = lookupCtxtName n (definitions ctxt) in if exact then filter (\ (n', d) -> n' == n) ns else ns lookupDefExact :: Name -> Context -> Maybe Def lookupDefExact n ctxt = tfst <$> lookupCtxtExact n (definitions ctxt) lookupDef :: Name -> Context -> [Def] lookupDef n ctxt = tfst <$> lookupCtxt n (definitions ctxt) lookupNameDef :: Name -> Context -> [(Name, Def)] lookupNameDef n ctxt = mapSnd tfst $ lookupCtxtName n (definitions ctxt) where mapSnd f [] = [] mapSnd f ((x,y):xys) = (x, f y) : mapSnd f xys lookupDefAcc :: Name -> Bool -> Context -> [(Def, Accessibility)] lookupDefAcc n mkpublic ctxt = map mkp $ lookupCtxt n (definitions ctxt) -- io_bind a special case for REPL prettiness where mkp (d, _, inj, a, _, _) = if mkpublic && (not (n == sUN "io_bind" || n == sUN "io_pure")) then (d, Public) else (d, a) lookupDefAccExact :: Name -> Bool -> Context -> Maybe (Def, Accessibility) lookupDefAccExact n mkpublic ctxt = fmap mkp $ lookupCtxtExact n (definitions ctxt) -- io_bind a special case for REPL prettiness where mkp (d, _, inj, a, _, _) = if mkpublic && (not (n == sUN "io_bind" || n == sUN "io_pure")) then (d, Public) else (d, a) lookupTotal :: Name -> Context -> [Totality] lookupTotal n ctxt = map mkt $ lookupCtxt n (definitions ctxt) where mkt (d, _, inj, a, t, m) = t lookupTotalExact :: Name -> Context -> Maybe Totality lookupTotalExact n ctxt = fmap mkt $ lookupCtxtExact n (definitions ctxt) where mkt (d, _, inj, a, t, m) = t lookupRigCount :: Name -> Context -> [Totality] lookupRigCount n ctxt = map mkt $ lookupCtxt n (definitions ctxt) where mkt (d, _, inj, a, t, m) = t lookupRigCountExact :: Name -> Context -> Maybe RigCount lookupRigCountExact n ctxt = fmap mkt $ lookupCtxtExact n (definitions ctxt) where mkt (d, rc, inj, a, t, m) = rc lookupInjectiveExact :: Name -> Context -> Maybe Injectivity lookupInjectiveExact n ctxt = fmap mkt $ lookupCtxtExact n (definitions ctxt) where mkt (d, _, inj, a, t, m) = inj -- Assume type is at least in whnfArgs form linearCheck :: Context -> Type -> TC () linearCheck ctxt t = checkArgs t where checkArgs (Bind n (Pi RigW _ ty _) sc) = do linearCheckArg ctxt ty checkArgs (substV (P Bound n Erased) sc) checkArgs (Bind n (Pi _ _ _ _) sc) = checkArgs (substV (P Bound n Erased) sc) checkArgs _ = return () linearCheckArg :: Context -> Type -> TC () linearCheckArg ctxt ty = mapM_ checkNameOK (allTTNames ty) where checkNameOK f = case lookupRigCountExact f ctxt of Just Rig1 -> tfail $ Msg $ show f ++ " can only appear in a linear binding" _ -> return () checkArgs (Bind n (Pi RigW _ ty _) sc) = do mapM_ checkNameOK (allTTNames ty) checkArgs (substV (P Bound n Erased) sc) checkArgs (Bind n (Pi _ _ _ _) sc) = checkArgs (substV (P Bound n Erased) sc) checkArgs _ = return () -- Check if a name is reducible in the type checker. Partial definitions -- are not reducible (so treated as a constant) tcReducible :: Name -> Context -> Bool tcReducible n ctxt = case lookupTotalExact n ctxt of Nothing -> True Just (Partial _) -> False _ -> True lookupMetaInformation :: Name -> Context -> [MetaInformation] lookupMetaInformation n ctxt = map mkm $ lookupCtxt n (definitions ctxt) where mkm (d, _, inj, a, t, m) = m lookupNameTotal :: Name -> Context -> [(Name, Totality)] lookupNameTotal n = map (\(n, (_, _, _, _, t, _)) -> (n, t)) . lookupCtxtName n . definitions lookupVal :: Name -> Context -> [Value] lookupVal n ctxt = do def <- lookupCtxt n (definitions ctxt) case tfst def of (Function _ htm) -> return (veval ctxt [] htm) (TyDecl nt ty) -> return (VP nt n (veval ctxt [] ty)) _ -> [] lookupTyEnv :: Name -> Env -> Maybe (Int, RigCount, Type) lookupTyEnv n env = li n 0 env where li n i [] = Nothing li n i ((x, r, b): xs) | n == x = Just (i, r, binderTy b) | otherwise = li n (i+1) xs -- | Create a unique name given context and other existing names uniqueNameCtxt :: Context -> Name -> [Name] -> Name uniqueNameCtxt ctxt n hs | n `elem` hs = uniqueNameCtxt ctxt (nextName n) hs | [_] <- lookupTy n ctxt = uniqueNameCtxt ctxt (nextName n) hs | otherwise = n uniqueBindersCtxt :: Context -> [Name] -> TT Name -> TT Name uniqueBindersCtxt ctxt ns (Bind n b sc) = let n' = uniqueNameCtxt ctxt n ns in Bind n' (fmap (uniqueBindersCtxt ctxt (n':ns)) b) (uniqueBindersCtxt ctxt ns sc) uniqueBindersCtxt ctxt ns (App s f a) = App s (uniqueBindersCtxt ctxt ns f) (uniqueBindersCtxt ctxt ns a) uniqueBindersCtxt ctxt ns t = t
bravit/Idris-dev
src/Idris/Core/Evaluate.hs
bsd-3-clause
54,891
0
27
19,907
19,129
9,789
9,340
961
80
{- | Module : Distribution.NixOS.Derivation.Meta License : BSD3 Maintainer : nix-dev@cs.uu.nl Stability : provisional Portability : portable A representation of the @meta@ section used in Nix expressions. A detailed description can be found in section 4, \"Meta-attributes\", of the Nixpkgs manual at <http://nixos.org/nixpkgs/docs.html>. -} module Distribution.NixOS.Derivation.Meta ( Meta(..) , module Distribution.NixOS.Derivation.License ) where import Distribution.NixOS.PrettyPrinting import Distribution.NixOS.Derivation.License import Distribution.Text -- | A representation of the @meta@ section used in Nix expressions. -- -- > > putStrLn (display (Meta "http://example.org" "an example package" (Unknown Nothing) -- > > ["stdenv.lib.platforms."++x | x<-["unix","cygwin"]] -- > > ["stdenv.lib.maintainers."++x | x<-["joe","jane"]])) -- > meta = { -- > homepage = "http://example.org"; -- > description = "an example package"; -- > license = "unknown"; -- > platforms = -- > stdenv.lib.platforms.unix ++ stdenv.lib.platforms.cygwin; -- > maintainers = [ stdenv.lib.maintainers.joe stdenv.lib.maintainers.jane ]; -- > }; -- -- Note that the "Text" instance definition provides pretty-printing, -- but no parsing as of now! data Meta = Meta { homepage :: String -- ^ URL of the package homepage , description :: String -- ^ short description of the package , license :: License -- ^ licensing terms , platforms :: [String] -- ^ list of supported platforms from @pkgs\/lib\/platforms.nix@ , maintainers :: [String] -- ^ list of maintainers from @pkgs\/lib\/maintainers.nix@ } deriving (Show, Eq, Ord) instance Text Meta where disp = renderMeta parse = error "parsing Distribution.NixOS.Derivation.Cabal.Meta is not supported yet" renderMeta :: Meta -> Doc renderMeta meta = vcat [ text "meta" <+> equals <+> lbrace , nest 2 $ vcat [ onlyIf (homepage meta) $ attr "homepage" $ string (homepage meta) , onlyIf (description meta) $ attr "description" $ string (description meta) , attr "license" $ disp (license meta) , onlyIf (platforms meta) $ sep [ text "platforms" <+> equals , nest 2 ((fsep $ punctuate (text " ++") $ map text (platforms meta))) <> semi ] , listattr "maintainers" (maintainers meta) ] , rbrace <> semi ]
shlevy/nixos-types
src/Distribution/NixOS/Derivation/Meta.hs
bsd-3-clause
2,440
0
21
533
372
210
162
28
1
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module PeerTrader.Database where import Control.Monad.Logger import Control.Monad.Reader import Control.Monad.Trans.Control import Data.Aeson import qualified Data.HashMap.Strict as H import qualified Data.Vector as V import Database.Groundhog.Core import Database.Groundhog.Generic import qualified Database.Groundhog.Postgresql.Array as P import Database.Groundhog.Utils.Postgresql (intToKey, keyToInt) instance ToJSON a => ToJSON (P.Array a) where toJSON (P.Array x) = toJSON x instance FromJSON a => FromJSON (P.Array a) where parseJSON (Array x) = fmap P.Array $ mapM parseJSON $ V.toList x parseJSON _ = return $ P.Array [] data Entity a = Entity { key :: !Int , entity :: !a } deriving (Show, Eq) instance Functor Entity where fmap f (Entity k v) = Entity k (f v) selectEntity :: (PersistBackend m, Projection constr b, ProjectionDb constr (PhantomDb m), ProjectionRestriction constr (RestrictionHolder v c), HasSelectOptions opts (PhantomDb m) (RestrictionHolder v c), EntityConstr v c, AutoKey v ~ Key b a, PrimitivePersistField (Key b a)) => constr -- ^ The constructor type for the object being queried -> opts -- ^ Same as the opts argument to groundhog's select funciton -> m [Entity b] selectEntity constructor cond = do res <- project (AutoKeyField, constructor) cond return $ map (\(k, v) -> Entity (keyToInt k) v) res replaceEntity :: (PersistEntity a, PersistBackend m, PrimitivePersistField (Key a BackendSpecific)) => Entity a -> m () replaceEntity (Entity k v) = replace (intToKey k) v instance ToJSON a => ToJSON (Entity a) where toJSON (Entity k e) = case toJSON e of Object x -> Object $ H.insert "id" (toJSON k) x x -> x instance FromJSON a => FromJSON (Entity a) where parseJSON o@(Object x) = Entity <$> x .: "id" <*> parseJSON o parseJSON x = fail $ "Could not parse Entity JSON: " ++ show x runDb :: (ConnectionManager cm conn, MonadBaseControl IO m, MonadIO m, MonadReader cm m) => DbPersist conn (NoLoggingT m) a -> m a runDb f = ask >>= runDbConn f
WraithM/peertrader-backend
src/PeerTrader/Database.hs
bsd-3-clause
2,592
0
13
737
775
403
372
62
1
module Main where import Test.Tasty import Test.Tasty.Runners.Html import AgentsetBuilding -- import Interaction -- import RandomOrderInitialization import Agentsets -- import Layouts -- import Repeat import AnyAll -- import Let -- import ReporterTasks import Ask -- import Links -- import ResizeWorld import BooleanOperators -- import Lists -- import RGB import Breeds -- import Math -- import Run import CanMove -- import Member -- import SelfMyself -- import CommandTasks -- import MinMaxNOf -- import Sort import ComparingAgents -- import MoveTo -- import StackTraces import ControlStructures -- import Neighbors -- import Stop -- import DeadTurtles -- import NoAgents -- import Sum -- import Diffuse -- import Nsum -- import Ticks -- import Distance -- import Observer -- import Tie -- import Equality -- import OneOf -- import Tilt -- import Errors -- import Patch import Timer -- import Face -- import PatchAhead -- import Turtles -- import File -- import PatchAt -- import TurtlesHere -- import Generator -- import PatchSize -- import TurtlesOn -- import HubNet -- import Perspective -- import TypeChecking -- import ImportPatchesAndDrawing -- import Plot -- import UpAndDownhill -- import ImportWorld -- import Predicates -- import UserReporters -- import InCone -- import Procedures -- import WithLocalRandomness -- import Initialization -- import Random -- import Word -- import InRadius -- import RandomCors main :: IO () main = defaultMainWithIngredients (htmlRunner:defaultIngredients)( localOption (mkTimeout 1000000) $ -- timeouts any test at 1s testGroup "hlogo" [ testGroup "agentsetbuildingTestGroup" agentsetbuildingTestGroup -- interactionTestGroup, randomOrderInitializationTestGroup, , testGroup "agentsetsTestGroup" agentsetsTestGroup -- layoutsTestGroup, repeatTestGroup, , testGroup "anyallTestGroup" anyallTestGroup -- letTestGroup, reportertasksTestGroup, -- , testGroup "askTestGroup" askTestGroup -- linksTestGroup, resizeworldTestGroup, , testGroup "booleanoperatorsTestGroup" booleanoperatorsTestGroup -- listsTestGroup, rgbTestGroup, , testGroup "breedsTestGroup" breedsTestGroup -- mathTestGroup, runTestGroup, , testGroup "canmoveTestGroup" canmoveTestGroup -- memberTestGroup, selfmyselfTestGroup, -- commandtasksTestGroup, minmaxnofTestGroup, sortTestGroup, , testGroup "comparingagentsTestGroup" comparingagentsTestGroup-- movetoTestGroup, stacktracesTestGroup, , testGroup "controlstructuresTestGroup" controlstructuresTestGroup --, neighborsTestGroup, stopTestGroup, -- deadturtlesTestGroup, noagentsTestGroup, sumTestGroup, -- diffuseTestGroup, nsumTestGroup, ticksTestGroup, -- distanceTestGroup, observerTestGroup, tieTestGroup, -- equalityTestGroup, oneofTestGroup, tiltTestGroup, , testGroup "timerTestGroup" timerTestGroup -- errorsTestGroup, patchTestGroup, , -- faceTestGroup, patchaheadTestGroup, turtlesTestGroup, -- fileTestGroup, patchatTestGroup, turtleshereTestGroup, -- generatorTestGroup, patchsizeTestGroup, turtlesonTestGroup, -- hubnetTestGroup, perspectiveTestGroup, typecheckingTestGroup, -- importpatchesanddrawingTestGroup, plotTestGroup, upanddownhillTestGroup, -- importworldTestGroup, predicatesTestGroup, userreportersTestGroup, -- inconeTestGroup, proceduresTestGroup, withlocalrandomnessTestGroup, -- initializationTestGroup, randomTestGroup, wordTestGroup, -- inradiusTestGroup, randomcorsTestGroup ])
bezirg/hlogo
tests/unit.hs
bsd-3-clause
4,110
0
10
1,095
252
177
75
27
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Prelude hiding (readFile, drop) import Control.Monad import Control.Monad.IO.Class import Control.Exception import Foreign.C.Types import System.Random import Numeric.LinearAlgebra import Numeric.LinearAlgebra.Data import SDL import Debug.Trace import qualified Linear import Data.List.Split (chunksOf) import Neural import MNIST -- Generates a layer with a given number of neurons with inputCount weights. -- Weights are randomised between 0 and 1. genLayer :: Int -> Int -> IO Layer genLayer neurons inputCount = do weights <- replicateM (neurons * inputCount) (randomRIO (-0.2, 0.2) :: IO R) biases <- replicateM (neurons) (randomRIO (-0.2, 0.2) :: IO R) return $ Layer (matrix inputCount weights) (vector biases) -- Generates a network with the specified number of neurons in each layer, -- and the number of inputs to the network. -- Initialised with random weights and biases as in genLayer. genNetwork :: [Int] -> Int -> IO Network genNetwork layers inputCount = sequence . map (uncurry genLayer) $ layerDefs where -- Layer definitions in the form (neuronCount, inputCount) layerDefs = zip layers (inputCount:layers) -- A test network testNetwork :: IO Network testNetwork = do l1 <- genLayer 5 3 l2 <- genLayer 5 5 l3 <- genLayer 1 5 return [l1, l2, l3] -- Another test network testNetwork2 :: Network testNetwork2 = [hiddenLayer, outputLayer] where hiddenLayer = Layer (matrix 2 [0.15, 0.2, 0.25, 0.3]) (vector [0.35, 0.35]) outputLayer = Layer (matrix 2 [0.4, 0.45, 0.5, 0.55]) (vector [0.6, 0.6]) -- Test inputs for testNetwork2 testInputs = vector [0.05, 0.1] -- Training data for testInputs trainingData = vector [0.01, 0.99] -- Train neural network trainNet = do (imageCount, width, height, imageData) <- readMNISTImages "train-images-idx3-ubyte" (labelCount, labels) <- readMNISTLabels "train-labels-idx1-ubyte" let image = head imageData let input = vector (map fromIntegral image) let correctNumber = fromIntegral . head $ labels let training = vector $ map (\i -> if i == correctNumber then 1.0 else 0.0) [1..10] hiddenLayer <- genLayer 20 (width * height) outputLayer <- genLayer 10 20 let initialNetwork = [hiddenLayer, outputLayer] let loop net i err = case i > 1000 || err < 0.1 of True -> net False -> trace (show $ sumElements (last error)) $ loop nextNet (i+1) (sumElements (last error)) where output = evalNetwork net input error = evalNetworkError net output input training nextNet = gradientDescent net input (map fst output) error 0.1 let trainedNet = loop initialNetwork 0 1000 return (input, initialNetwork, trainedNet, training) -- Train neural network trainNetM = do (imageCount, width, height, imageData) <- readMNISTImages "train-images-idx3-ubyte" (labelCount, labels) <- readMNISTLabels "train-labels-idx1-ubyte" let image = head imageData let input = fromRows [vector (map fromIntegral image)] let correctNumber = fromIntegral . head $ labels let training = fromRows [vector $ map (\i -> if i == correctNumber then 1.0 else 0.0) [1..10]] hiddenLayer <- genLayer 20 (width * height) outputLayer <- genLayer 10 20 let initialNetwork = [hiddenLayer, outputLayer] let loop net i err = case i > 100000 || err < 0.1 of True -> net False -> trace (show $ sumElements (last error)) $ loop nextNet (i+1) (sumElements (last error)) where output = evalNetworkM net input error = evalNetworkErrorM net output input training nextNet = gradientDescentM net input (map fst output) error 0.1 let trainedNet = loop initialNetwork 0 1000 return (input, initialNetwork, trainedNet, training) -- Make a window and show MNIST image window image width height = do initializeAll window <- createWindow "SDL Application" defaultWindow renderer <- createRenderer window (-1) defaultRenderer -- Convert to sdl texture texture <- loadTextureMNIST renderer width height image SDL.rendererDrawColor renderer $= Linear.V4 255 255 255 255 SDL.clear renderer copy renderer texture Nothing Nothing present renderer let loop = do pollEvents keyState <- getKeyboardState case keyState ScancodeEscape of True -> (return ()) :: IO () False -> loop loop destroyTexture texture destroyRenderer renderer destroyWindow window -- Train a network using a given set of inputs and training values for the given -- number of epochs using the given learning rate. trainNetwork :: Network -> [Vector R] -> [Vector R] -> Int -> Int -> R -> Network trainNetwork initialNet input trainingValues epochs batchSize learnRate = train initialNet 0 where train net epoch = case epoch >= epochs of True -> net False -> train nextNet (epoch + 1) where --inputBatch = fromRows input --trainingBatch = fromRows trainingValues inputBatches = map fromRows . chunksOf batchSize $ input trainingBatches = map fromRows . chunksOf batchSize $ trainingValues nextNet = foldl runBatch net (zip inputBatches trainingBatches) --nextNet = net runBatch network (inputBatch, trainingBatch) = gradientDescentM net inputBatch (map fst output) error learnRate where output = evalNetworkM net inputBatch error = evalNetworkErrorM net output inputBatch trainingBatch toOutput = \n -> vector . map (\x -> if n == x then 1.0 else 0.0) $ [0..9] fromOutput :: Vector R -> Int fromOutput v = guess where list = zip [0..] . toList $ v possibles = filter ((>=0.5) . snd) list guess = case length possibles of 0 -> -1 1 -> fst . head $ possibles _ -> -2 runTest :: Network -> ([CUChar], Int) -> Bool runTest network (image, label) = guess == label where output = fst . last $ evalNetwork network $ vector . map fromIntegral $ image guess = fromOutput output --runTest :: Network -> ([CUChar], Int) -> IO () --runTest network (image, label) = do -- let output = fst . last $ evalNetwork network $ vector . map fromIntegral $ image -- let guess = fromOutput output -- let expected = label -- putStr "Guess: " -- putStr . show $ guess -- putStr ",\tExpected: " -- putStr . show $ label -- putStr $ if guess == expected then ".\tCorrect! " else ".\tINCORRECT!" -- putStrLn "" main = do (trainingImageCount, trainingWidth, trainingHeight, trainingImageData) <- readMNISTImages "train-images-idx3-ubyte" (trainingLabelCount, trainingLabels) <- readMNISTLabels "train-labels-idx1-ubyte" (testImageCount, testWidth, testHeight, testImageData) <- readMNISTImages "t10k-images-idx3-ubyte" (testLabelCount, testLabels) <- readMNISTLabels "t10k-labels-idx1-ubyte" assert (trainingWidth == testWidth && trainingHeight == testHeight) (return ()) let input = take 60000 . map (vector . map fromIntegral) $ trainingImageData let trainingData = take 60000 . map toOutput $ trainingLabels initialNetwork <- genNetwork [20,10] (trainingWidth * trainingHeight) let trainedNetwork = trainNetwork initialNetwork input trainingData 2 10 3.0 let testImage = head testImageData let testInput = vector . map fromIntegral $ testImage let testOutput = head testLabels --toOutput $ head testLabels --window testImage testWidth testHeight --let output = fst . last $ evalNetwork trainedNetwork testInput --let filteredOutput = map (>=0.5) . toList $ output --print $ fromOutput output --print $ testOutput let tests = map (runTest trainedNetwork) $ zip testImageData testLabels let success = length . filter (==True) $ tests let total = length tests putStr . show $ success putStr "/" putStrLn . show $ total --flip mapM_ (take 100 $ zip testImageData testLabels) runTest -- where -- runTest (imageData, label) = output -- where -- output2 = evalNetwork trainedNetwork -- output = putStrLn "test" -- --let output = evalNetwork trainedNetwork (vector . map fromIntegral $ imageData) -- --in do -- -- putStr "Guess: " -- -- putStr . show . fromOutput $ output
Catchouli/neuron
src/Main.hs
bsd-3-clause
8,402
0
19
1,926
2,245
1,148
1,097
140
3
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1998 \section[TyCoRep]{Type and Coercion - friends' interface} Note [The Type-related module hierarchy] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Class CoAxiom TyCon imports Class, CoAxiom TyCoRep imports Class, CoAxiom, TyCon TysPrim imports TyCoRep ( including mkTyConTy ) Kind imports TysPrim ( mainly for primitive kinds ) Type imports Kind Coercion imports Type -} -- We expose the relevant stuff from this module via the Type module {-# OPTIONS_HADDOCK hide #-} {-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable, MultiWayIf #-} {-# LANGUAGE ImplicitParams #-} module TyCoRep ( TyThing(..), pprTyThingCategory, pprShortTyThing, -- * Types Type(..), TyLit(..), KindOrType, Kind, PredType, ThetaType, -- Synonyms ArgFlag(..), -- * Coercions Coercion(..), LeftOrRight(..), UnivCoProvenance(..), CoercionHole(..), CoercionN, CoercionR, CoercionP, KindCoercion, -- * Functions over types mkTyConTy, mkTyVarTy, mkTyVarTys, mkFunTy, mkFunTys, mkForAllTy, mkForAllTys, mkPiTy, mkPiTys, isLiftedTypeKind, isUnliftedTypeKind, isCoercionType, isRuntimeRepTy, isRuntimeRepVar, isRuntimeRepKindedTy, dropRuntimeRepArgs, sameVis, -- * Functions over binders TyBinder(..), TyVarBinder, binderVar, binderVars, binderKind, binderArgFlag, delBinderVar, isInvisibleArgFlag, isVisibleArgFlag, isInvisibleBinder, isVisibleBinder, -- * Functions over coercions pickLR, -- * Pretty-printing pprType, pprParendType, pprTypeApp, pprTvBndr, pprTvBndrs, pprSigmaType, pprTheta, pprForAll, pprForAllImplicit, pprUserForAll, pprThetaArrowTy, pprClassPred, pprKind, pprParendKind, pprTyLit, TyPrec(..), maybeParen, pprTcAppCo, pprTcAppTy, pprPrefixApp, pprArrowChain, ppr_type, pprDataCons, ppSuggestExplicitKinds, -- * Free variables tyCoVarsOfType, tyCoVarsOfTypeDSet, tyCoVarsOfTypes, tyCoVarsOfTypesDSet, tyCoFVsBndr, tyCoFVsOfType, tyCoVarsOfTypeList, tyCoFVsOfTypes, tyCoVarsOfTypesList, closeOverKindsDSet, closeOverKindsFV, closeOverKindsList, coVarsOfType, coVarsOfTypes, coVarsOfCo, coVarsOfCos, tyCoVarsOfCo, tyCoVarsOfCos, tyCoVarsOfCoDSet, tyCoFVsOfCo, tyCoFVsOfCos, tyCoVarsOfCoList, tyCoVarsOfProv, closeOverKinds, -- * Substitutions TCvSubst(..), TvSubstEnv, CvSubstEnv, emptyTvSubstEnv, emptyCvSubstEnv, composeTCvSubstEnv, composeTCvSubst, emptyTCvSubst, mkEmptyTCvSubst, isEmptyTCvSubst, mkTCvSubst, mkTvSubst, getTvSubstEnv, getCvSubstEnv, getTCvInScope, getTCvSubstRangeFVs, isInScope, notElemTCvSubst, setTvSubstEnv, setCvSubstEnv, zapTCvSubst, extendTCvInScope, extendTCvInScopeList, extendTCvInScopeSet, extendTCvSubst, extendCvSubst, extendCvSubstWithClone, extendTvSubst, extendTvSubstBinder, extendTvSubstWithClone, extendTvSubstList, extendTvSubstAndInScope, unionTCvSubst, zipTyEnv, zipCoEnv, mkTyCoInScopeSet, zipTvSubst, zipCvSubst, mkTvSubstPrs, substTyWith, substTyWithCoVars, substTysWith, substTysWithCoVars, substCoWith, substTy, substTyAddInScope, substTyUnchecked, substTysUnchecked, substThetaUnchecked, substTyWithUnchecked, substCoUnchecked, substCoWithUnchecked, substTyWithInScope, substTys, substTheta, lookupTyVar, substTyVarBndr, substCo, substCos, substCoVar, substCoVars, lookupCoVar, substCoVarBndr, cloneTyVarBndr, cloneTyVarBndrs, substTyVar, substTyVars, substForAllCoBndr, substTyVarBndrCallback, substForAllCoBndrCallback, substCoVarBndrCallback, -- * Tidying type related things up for printing tidyType, tidyTypes, tidyOpenType, tidyOpenTypes, tidyOpenKind, tidyTyCoVarBndr, tidyTyCoVarBndrs, tidyFreeTyCoVars, tidyOpenTyCoVar, tidyOpenTyCoVars, tidyTyVarOcc, tidyTopType, tidyKind, tidyCo, tidyCos, tidyTyVarBinder, tidyTyVarBinders ) where #include "HsVersions.h" import {-# SOURCE #-} DataCon( dataConTyCon, dataConFullSig , dataConUnivTyVarBinders, dataConExTyVarBinders , DataCon, filterEqSpec ) import {-# SOURCE #-} Type( isPredTy, isCoercionTy, mkAppTy , tyCoVarsOfTypesWellScoped , partitionInvisibles, coreView, typeKind , eqType ) -- Transitively pulls in a LOT of stuff, better to break the loop import {-# SOURCE #-} Coercion import {-# SOURCE #-} ConLike ( ConLike(..), conLikeName ) import {-# SOURCE #-} TysWiredIn ( ptrRepLiftedTy ) -- friends: import Var import VarEnv import VarSet import Name hiding ( varName ) import BasicTypes import TyCon import Class import CoAxiom import FV -- others import PrelNames import Binary import Outputable import DynFlags import StaticFlags ( opt_PprStyle_Debug ) import FastString import Pair import UniqSupply import Util import UniqFM -- libraries import qualified Data.Data as Data hiding ( TyCon ) import Data.List import Data.IORef ( IORef ) -- for CoercionHole #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) import GHC.Stack (CallStack) #endif {- %************************************************************************ %* * TyThing %* * %************************************************************************ Despite the fact that DataCon has to be imported via a hi-boot route, this module seems the right place for TyThing, because it's needed for funTyCon and all the types in TysPrim. It is also SOURCE-imported into Name.hs Note [ATyCon for classes] ~~~~~~~~~~~~~~~~~~~~~~~~~ Both classes and type constructors are represented in the type environment as ATyCon. You can tell the difference, and get to the class, with isClassTyCon :: TyCon -> Bool tyConClass_maybe :: TyCon -> Maybe Class The Class and its associated TyCon have the same Name. -} -- | A global typecheckable-thing, essentially anything that has a name. -- Not to be confused with a 'TcTyThing', which is also a typecheckable -- thing but in the *local* context. See 'TcEnv' for how to retrieve -- a 'TyThing' given a 'Name'. data TyThing = AnId Id | AConLike ConLike | ATyCon TyCon -- TyCons and classes; see Note [ATyCon for classes] | ACoAxiom (CoAxiom Branched) instance Outputable TyThing where ppr = pprShortTyThing instance NamedThing TyThing where -- Can't put this with the type getName (AnId id) = getName id -- decl, because the DataCon instance getName (ATyCon tc) = getName tc -- isn't visible there getName (ACoAxiom cc) = getName cc getName (AConLike cl) = conLikeName cl pprShortTyThing :: TyThing -> SDoc -- c.f. PprTyThing.pprTyThing, which prints all the details pprShortTyThing thing = pprTyThingCategory thing <+> quotes (ppr (getName thing)) pprTyThingCategory :: TyThing -> SDoc pprTyThingCategory (ATyCon tc) | isClassTyCon tc = text "Class" | otherwise = text "Type constructor" pprTyThingCategory (ACoAxiom _) = text "Coercion axiom" pprTyThingCategory (AnId _) = text "Identifier" pprTyThingCategory (AConLike (RealDataCon _)) = text "Data constructor" pprTyThingCategory (AConLike (PatSynCon _)) = text "Pattern synonym" {- ********************************************************************** * * Type * * ********************************************************************** -} -- | The key representation of types within the compiler type KindOrType = Type -- See Note [Arguments to type constructors] -- | The key type representing kinds in the compiler. type Kind = Type -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data Type -- See Note [Non-trivial definitional equality] = TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable) | AppTy -- See Note [AppTy rep] Type Type -- ^ Type application to something other than a 'TyCon'. Parameters: -- -- 1) Function: must /not/ be a 'TyConApp', -- must be another 'AppTy', or 'TyVarTy' -- -- 2) Argument type | TyConApp -- See Note [AppTy rep] TyCon [KindOrType] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms. -- Invariant: saturated applications of 'FunTyCon' must -- use 'FunTy' and saturated synonyms must use their own -- constructors. However, /unsaturated/ 'FunTyCon's -- do appear as 'TyConApp's. -- Parameters: -- -- 1) Type constructor being applied to. -- -- 2) Type arguments. Might not have enough type arguments -- here to saturate the constructor. -- Even type synonyms are not necessarily saturated; -- for example unsaturated type synonyms -- can appear as the right hand side of a type synonym. | ForAllTy {-# UNPACK #-} !TyVarBinder Type -- ^ A Π type. | FunTy Type Type -- ^ t1 -> t2 Very common, so an important special case | LitTy TyLit -- ^ Type literals are similar to type constructors. | CastTy Type KindCoercion -- ^ A kind cast. The coercion is always nominal. -- INVARIANT: The cast is never refl. -- INVARIANT: The cast is "pushed down" as far as it -- can go. See Note [Pushing down casts] | CoercionTy Coercion -- ^ Injection of a Coercion into a type -- This should only ever be used in the RHS of an AppTy, -- in the list of a TyConApp, when applying a promoted -- GADT data constructor deriving Data.Data -- NOTE: Other parts of the code assume that type literals do not contain -- types or type variables. data TyLit = NumTyLit Integer | StrTyLit FastString deriving (Eq, Ord, Data.Data) {- Note [The kind invariant] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The kinds # UnliftedTypeKind OpenKind super-kind of *, # can never appear under an arrow or type constructor in a kind; they can only be at the top level of a kind. It follows that primitive TyCons, which have a naughty pseudo-kind State# :: * -> # must always be saturated, so that we can never get a type whose kind has a UnliftedTypeKind or ArgTypeKind underneath an arrow. Nor can we abstract over a type variable with any of these kinds. k :: = kk | # | ArgKind | (#) | OpenKind kk :: = * | kk -> kk | T kk1 ... kkn So a type variable can only be abstracted kk. Note [AppTy rep] ~~~~~~~~~~~~~~~~ Types of the form 'f a' must be of kind *, not #, so we are guaranteed that they are represented by pointers. The reason is that f must have kind (kk -> kk) and kk cannot be unlifted; see Note [The kind invariant] in TyCoRep. Note [Arguments to type constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Because of kind polymorphism, in addition to type application we now have kind instantiation. We reuse the same notations to do so. For example: Just (* -> *) Maybe Right * Nat Zero are represented by: TyConApp (PromotedDataCon Just) [* -> *, Maybe] TyConApp (PromotedDataCon Right) [*, Nat, (PromotedDataCon Zero)] Important note: Nat is used as a *kind* and not as a type. This can be confusing, since type-level Nat and kind-level Nat are identical. We use the kind of (PromotedDataCon Right) to know if its arguments are kinds or types. This kind instantiation only happens in TyConApp currently. Note [Pushing down casts] ~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have (a :: k1 -> *), (b :: k1), and (co :: * ~ q). The type (a b |> co) is `eqType` to ((a |> co') b), where co' = (->) <k1> co. Thus, to make this visible to functions that inspect types, we always push down coercions, preferring the second form. Note that this also applies to TyConApps! Note [Non-trivial definitional equality] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Is Int |> <*> the same as Int? YES! In order to reduce headaches, we decide that any reflexive casts in types are just ignored. More generally, the `eqType` function, which defines Core's type equality relation, ignores casts and coercion arguments, as long as the two types have the same kind. This allows us to be a little sloppier in keeping track of coercions, which is a good thing. It also means that eqType does not depend on eqCoercion, which is also a good thing. Why is this sensible? That is, why is something different than α-equivalence appropriate for the implementation of eqType? Anything smaller than ~ and homogeneous is an appropriate definition for equality. The type safety of FC depends only on ~. Let's say η : τ ~ σ. Any expression of type τ can be transmuted to one of type σ at any point by casting. The same is true of types of type τ. So in some sense, τ and σ are interchangeable. But let's be more precise. If we examine the typing rules of FC (say, those in http://www.cis.upenn.edu/~eir/papers/2015/equalities/equalities-extended.pdf) there are several places where the same metavariable is used in two different premises to a rule. (For example, see Ty_App.) There is an implicit equality check here. What definition of equality should we use? By convention, we use α-equivalence. Take any rule with one (or more) of these implicit equality checks. Then there is an admissible rule that uses ~ instead of the implicit check, adding in casts as appropriate. The only problem here is that ~ is heterogeneous. To make the kinds work out in the admissible rule that uses ~, it is necessary to homogenize the coercions. That is, if we have η : (τ : κ1) ~ (σ : κ2), then we don't use η; we use η |> kind η, which is homogeneous. The effect of this all is that eqType, the implementation of the implicit equality check, can use any homogeneous relation that is smaller than ~, as those rules must also be admissible. What would go wrong if we insisted on the casts matching? See the beginning of Section 8 in the unpublished paper above. Theoretically, nothing at all goes wrong. But in practical terms, getting the coercions right proved to be nightmarish. And types would explode: during kind-checking, we often produce reflexive kind coercions. When we try to cast by these, mkCastTy just discards them. But if we used an eqType that distinguished between Int and Int |> <*>, then we couldn't discard -- the output of kind-checking would be enormous, and we would need enormous casts with lots of CoherenceCo's to straighten them out. Would anything go wrong if eqType respected type families? No, not at all. But that makes eqType rather hard to implement. Thus, the guideline for eqType is that it should be the largest easy-to-implement relation that is still smaller than ~ and homogeneous. The precise choice of relation is somewhat incidental, as long as the smart constructors and destructors in Type respect whatever relation is chosen. Another helpful principle with eqType is this: ** If (t1 eqType t2) then I can replace t1 by t2 anywhere. ** This principle also tells us that eqType must relate only types with the same kinds. -} {- ********************************************************************** * * TyBinder and ArgFlag * * ********************************************************************** -} -- | A 'TyBinder' represents an argument to a function. TyBinders can be dependent -- ('Named') or nondependent ('Anon'). They may also be visible or not. -- See Note [TyBinders] data TyBinder = Named TyVarBinder | Anon Type -- Visibility is determined by the type (Constraint vs. *) deriving Data.Data -- | Remove the binder's variable from the set, if the binder has -- a variable. delBinderVar :: VarSet -> TyVarBinder -> VarSet delBinderVar vars (TvBndr tv _) = vars `delVarSet` tv -- | Does this binder bind an invisible argument? isInvisibleBinder :: TyBinder -> Bool isInvisibleBinder (Named (TvBndr _ vis)) = isInvisibleArgFlag vis isInvisibleBinder (Anon ty) = isPredTy ty -- | Does this binder bind a visible argument? isVisibleBinder :: TyBinder -> Bool isVisibleBinder = not . isInvisibleBinder {- Note [TyBinders] ~~~~~~~~~~~~~~~~~~~ A ForAllTy contains a TyVarBinder. But a type can be decomposed to a telescope consisting of a [TyBinder] A TyBinder represents the type of binders -- that is, the type of an argument to a Pi-type. GHC Core currently supports two different Pi-types: * A non-dependent function, written with ->, e.g. ty1 -> ty2 represented as FunTy ty1 ty2 * A dependent compile-time-only polytype, written with forall, e.g. forall (a:*). ty represented as ForAllTy (TvBndr a v) ty Both Pi-types classify terms/types that take an argument. In other words, if `x` is either a function or a polytype, `x arg` makes sense (for an appropriate `arg`). It is thus often convenient to group Pi-types together. This is ForAllTy. The two constructors for TyBinder sort out the two different possibilities. `Named` builds a polytype, while `Anon` builds an ordinary function. (ForAllTy (Anon arg) res used to be called FunTy arg res.) Note [TyBinders and ArgFlags] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ A ForAllTy contains a TyVarBinder. Each TyVarBinder is equipped with a ArgFlag, which says whether or not arguments for this binder should be visible (explicit) in source Haskell. ----------------------------------------------------------------------- Occurrences look like this TyBinder GHC displays type as in Haskell souce code ----------------------------------------------------------------------- In the type of a term Anon: f :: type -> type Arg required: f x Named Inferred: f :: forall {a}. type Arg not allowed: f Named Specified: f :: forall a. type Arg optional: f or f @Int Named Required: Illegal: See Note [No Required TyBinder in terms] In the kind of a type Anon: T :: kind -> kind Required: T * Named Inferred: T :: forall {k}. kind Arg not allowed: T Named Specified: T :: forall k. kind Arg not allowed[1]: T Named Required: T :: forall k -> kind Required: T * ------------------------------------------------------------------------ [1] In types, in the Specified case, it would make sense to allow optional kind applications, thus (T @*), but we have not yet implemented that ---- Examples of where the different visiblities come from ----- In term declarations: * Inferred. Function defn, with no signature: f1 x = x We infer f1 :: forall {a}. a -> a, with 'a' Inferred It's Inferred because it doesn't appear in any user-written signature for f1 * Specified. Function defn, with signature (implicit forall): f2 :: a -> a; f2 x = x So f2 gets the type f2 :: forall a. a->a, with 'a' Specified even though 'a' is not bound in the source code by an explicit forall * Specified. Function defn, with signature (explicit forall): f3 :: forall a. a -> a; f3 x = x So f3 gets the type f3 :: forall a. a->a, with 'a' Specified * Inferred/Specified. Function signature with inferred kind polymorphism. f4 :: a b -> Int So 'f4' gets the type f4 :: forall {k} (a:k->*) (b:k). a b -> Int Here 'k' is Inferred (it's not mentioned in the type), but 'a' and 'b' are Specified. * Specified. Function signature with explicit kind polymorphism f5 :: a (b :: k) -> Int This time 'k' is Specified, because it is mentioned explicitly, so we get f5 :: forall (k:*) (a:k->*) (b:k). a b -> Int * Similarly pattern synonyms: Inferred - from inferred types (e.g. no pattern type signature) - or from inferred kind polymorphism In type declarations: * Inferred (k) data T1 a b = MkT1 (a b) Here T1's kind is T1 :: forall {k:*}. (k->*) -> k -> * The kind variable 'k' is Inferred, since it is not mentioned Note that 'a' and 'b' correspond to /Anon/ TyBinders in T1's kind, and Anon binders don't have a visibility flag. (Or you could think of Anon having an implicit Required flag.) * Specified (k) data T2 (a::k->*) b = MkT (a b) Here T's kind is T :: forall (k:*). (k->*) -> k -> * The kind variable 'k' is Specified, since it is mentioned in the signature. * Required (k) data T k (a::k->*) b = MkT (a b) Here T's kind is T :: forall k:* -> (k->*) -> k -> * The kind is Required, since it bound in a positional way in T's declaration Every use of T must be explicitly applied to a kind * Inferred (k1), Specified (k) data T a b (c :: k) = MkT (a b) (Proxy c) Here T's kind is T :: forall {k1:*} (k:*). (k1->*) -> k1 -> k -> * So 'k' is Specified, because it appears explicitly, but 'k1' is Inferred, because it does not ---- Printing ----- We print forall types with enough syntax to tell you their visiblity flag. But this is not source Haskell, and these types may not all be parsable. Specified: a list of Specified binders is written between `forall` and `.`: const :: forall a b. a -> b -> a Inferred: with -fprint-explicit-foralls, Inferred binders are written in braces: f :: forall {k} (a:k). S k a -> Int Otherwise, they are printed like Specified binders. Required: binders are put between `forall` and `->`: T :: forall k -> * ---- Other points ----- * In classic Haskell, all named binders (that is, the type variables in a polymorphic function type f :: forall a. a -> a) have been Inferred. * Inferred variables correspond to "generalized" variables from the Visible Type Applications paper (ESOP'16). Note [No Required TyBinder in terms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't allow Required foralls for term variables, including pattern synonyms and data constructors. Why? Because then an application would need a /compulsory/ type argument (possibly without an "@"?), thus (f Int); and we don't have concrete syntax for that. We could change this decision, but Required, Named TyBinders are rare anyway. (Most are Anons.) -} {- ********************************************************************** * * PredType * * ********************************************************************** -} -- | A type of the form @p@ of kind @Constraint@ represents a value whose type is -- the Haskell predicate @p@, where a predicate is what occurs before -- the @=>@ in a Haskell type. -- -- We use 'PredType' as documentation to mark those types that we guarantee to have -- this kind. -- -- It can be expanded into its representation, but: -- -- * The type checker must treat it as opaque -- -- * The rest of the compiler treats it as transparent -- -- Consider these examples: -- -- > f :: (Eq a) => a -> Int -- > g :: (?x :: Int -> Int) => a -> Int -- > h :: (r\l) => {r} => {l::Int | r} -- -- Here the @Eq a@ and @?x :: Int -> Int@ and @r\l@ are all called \"predicates\" type PredType = Type -- | A collection of 'PredType's type ThetaType = [PredType] {- (We don't support TREX records yet, but the setup is designed to expand to allow them.) A Haskell qualified type, such as that for f,g,h above, is represented using * a FunTy for the double arrow * with a type of kind Constraint as the function argument The predicate really does turn into a real extra argument to the function. If the argument has type (p :: Constraint) then the predicate p is represented by evidence of type p. %************************************************************************ %* * Simple constructors %* * %************************************************************************ These functions are here so that they can be used by TysPrim, which in turn is imported by Type -} -- named with "Only" to prevent naive use of mkTyVarTy mkTyVarTy :: TyVar -> Type mkTyVarTy v = ASSERT2( isTyVar v, ppr v <+> dcolon <+> ppr (tyVarKind v) ) TyVarTy v mkTyVarTys :: [TyVar] -> [Type] mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy infixr 3 `mkFunTy` -- Associates to the right -- | Make an arrow type mkFunTy :: Type -> Type -> Type mkFunTy arg res = FunTy arg res -- | Make nested arrow types mkFunTys :: [Type] -> Type -> Type mkFunTys tys ty = foldr mkFunTy ty tys mkForAllTy :: TyVar -> ArgFlag -> Type -> Type mkForAllTy tv vis ty = ForAllTy (TvBndr tv vis) ty -- | Wraps foralls over the type using the provided 'TyVar's from left to right mkForAllTys :: [TyVarBinder] -> Type -> Type mkForAllTys tyvars ty = foldr ForAllTy ty tyvars mkPiTy :: TyBinder -> Type -> Type mkPiTy (Anon ty1) ty2 = FunTy ty1 ty2 mkPiTy (Named tvb) ty = ForAllTy tvb ty mkPiTys :: [TyBinder] -> Type -> Type mkPiTys tbs ty = foldr mkPiTy ty tbs -- | Does this type classify a core (unlifted) Coercion? -- At either role nominal or reprsentational -- (t1 ~# t2) or (t1 ~R# t2) isCoercionType :: Type -> Bool isCoercionType (TyConApp tc tys) | (tc `hasKey` eqPrimTyConKey) || (tc `hasKey` eqReprPrimTyConKey) , length tys == 4 = True isCoercionType _ = False -- | Create the plain type constructor type which has been applied to no type arguments at all. mkTyConTy :: TyCon -> Type mkTyConTy tycon = TyConApp tycon [] {- Some basic functions, put here to break loops eg with the pretty printer -} -- | This version considers Constraint to be distinct from *. isLiftedTypeKind :: Kind -> Bool isLiftedTypeKind ki | Just ki' <- coreView ki = isLiftedTypeKind ki' isLiftedTypeKind (TyConApp tc [TyConApp ptr_rep []]) = tc `hasKey` tYPETyConKey && ptr_rep `hasKey` ptrRepLiftedDataConKey isLiftedTypeKind _ = False isUnliftedTypeKind :: Kind -> Bool isUnliftedTypeKind ki | Just ki' <- coreView ki = isUnliftedTypeKind ki' isUnliftedTypeKind (TyConApp tc [TyConApp ptr_rep []]) | tc `hasKey` tYPETyConKey , ptr_rep `hasKey` ptrRepLiftedDataConKey = False isUnliftedTypeKind (TyConApp tc [arg]) = tc `hasKey` tYPETyConKey && isEmptyVarSet (tyCoVarsOfType arg) -- all other possibilities are unlifted isUnliftedTypeKind _ = False -- | Is this the type 'RuntimeRep'? isRuntimeRepTy :: Type -> Bool isRuntimeRepTy ty | Just ty' <- coreView ty = isRuntimeRepTy ty' isRuntimeRepTy (TyConApp tc []) = tc `hasKey` runtimeRepTyConKey isRuntimeRepTy _ = False -- | Is this a type of kind RuntimeRep? (e.g. PtrRep) isRuntimeRepKindedTy :: Type -> Bool isRuntimeRepKindedTy = isRuntimeRepTy . typeKind -- | Is a tyvar of type 'RuntimeRep'? isRuntimeRepVar :: TyVar -> Bool isRuntimeRepVar = isRuntimeRepTy . tyVarKind -- | Drops prefix of RuntimeRep constructors in 'TyConApp's. Useful for e.g. -- dropping 'PtrRep arguments of unboxed tuple TyCon applications: -- -- dropRuntimeRepArgs [ 'PtrRepLifted, 'PtrRepUnlifted -- , String, Int# ] == [String, Int#] -- dropRuntimeRepArgs :: [Type] -> [Type] dropRuntimeRepArgs = dropWhile isRuntimeRepKindedTy {- %************************************************************************ %* * Coercions %* * %************************************************************************ -} -- | A 'Coercion' is concrete evidence of the equality/convertibility -- of two types. -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data Coercion -- Each constructor has a "role signature", indicating the way roles are -- propagated through coercions. -- - P, N, and R stand for coercions of the given role -- - e stands for a coercion of a specific unknown role -- (think "role polymorphism") -- - "e" stands for an explicit role parameter indicating role e. -- - _ stands for a parameter that is not a Role or Coercion. -- These ones mirror the shape of types = -- Refl :: "e" -> _ -> e Refl Role Type -- See Note [Refl invariant] -- Invariant: applications of (Refl T) to a bunch of identity coercions -- always show up as Refl. -- For example (Refl T) (Refl a) (Refl b) shows up as (Refl (T a b)). -- Applications of (Refl T) to some coercions, at least one of -- which is NOT the identity, show up as TyConAppCo. -- (They may not be fully saturated however.) -- ConAppCo coercions (like all coercions other than Refl) -- are NEVER the identity. -- Use (Refl Representational _), not (SubCo (Refl Nominal _)) -- These ones simply lift the correspondingly-named -- Type constructors into Coercions -- TyConAppCo :: "e" -> _ -> ?? -> e -- See Note [TyConAppCo roles] | TyConAppCo Role TyCon [Coercion] -- lift TyConApp -- The TyCon is never a synonym; -- we expand synonyms eagerly -- But it can be a type function | AppCo Coercion CoercionN -- lift AppTy -- AppCo :: e -> N -> e -- See Note [Forall coercions] | ForAllCo TyVar KindCoercion Coercion -- ForAllCo :: _ -> N -> e -> e -- These are special | CoVarCo CoVar -- :: _ -> (N or R) -- result role depends on the tycon of the variable's type -- AxiomInstCo :: e -> _ -> [N] -> e | AxiomInstCo (CoAxiom Branched) BranchIndex [Coercion] -- See also [CoAxiom index] -- The coercion arguments always *precisely* saturate -- arity of (that branch of) the CoAxiom. If there are -- any left over, we use AppCo. -- See [Coercion axioms applied to coercions] | UnivCo UnivCoProvenance Role Type Type -- :: _ -> "e" -> _ -> _ -> e | SymCo Coercion -- :: e -> e | TransCo Coercion Coercion -- :: e -> e -> e -- The number coercions should match exactly the expectations -- of the CoAxiomRule (i.e., the rule is fully saturated). | AxiomRuleCo CoAxiomRule [Coercion] | NthCo Int Coercion -- Zero-indexed; decomposes (T t0 ... tn) -- :: _ -> e -> ?? (inverse of TyConAppCo, see Note [TyConAppCo roles]) -- Using NthCo on a ForAllCo gives an N coercion always -- See Note [NthCo and newtypes] | LRCo LeftOrRight CoercionN -- Decomposes (t_left t_right) -- :: _ -> N -> N | InstCo Coercion CoercionN -- :: e -> N -> e -- See Note [InstCo roles] -- Coherence applies a coercion to the left-hand type of another coercion -- See Note [Coherence] | CoherenceCo Coercion KindCoercion -- :: e -> N -> e -- Extract a kind coercion from a (heterogeneous) type coercion -- NB: all kind coercions are Nominal | KindCo Coercion -- :: e -> N | SubCo CoercionN -- Turns a ~N into a ~R -- :: N -> R deriving Data.Data type CoercionN = Coercion -- always nominal type CoercionR = Coercion -- always representational type CoercionP = Coercion -- always phantom type KindCoercion = CoercionN -- always nominal -- If you edit this type, you may need to update the GHC formalism -- See Note [GHC Formalism] in coreSyn/CoreLint.hs data LeftOrRight = CLeft | CRight deriving( Eq, Data.Data ) instance Binary LeftOrRight where put_ bh CLeft = putByte bh 0 put_ bh CRight = putByte bh 1 get bh = do { h <- getByte bh ; case h of 0 -> return CLeft _ -> return CRight } pickLR :: LeftOrRight -> (a,a) -> a pickLR CLeft (l,_) = l pickLR CRight (_,r) = r {- Note [Refl invariant] ~~~~~~~~~~~~~~~~~~~~~ Invariant 1: Coercions have the following invariant Refl is always lifted as far as possible. You might think that a consequencs is: Every identity coercions has Refl at the root But that's not quite true because of coercion variables. Consider g where g :: Int~Int Left h where h :: Maybe Int ~ Maybe Int etc. So the consequence is only true of coercions that have no coercion variables. Note [Coercion axioms applied to coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The reason coercion axioms can be applied to coercions and not just types is to allow for better optimization. There are some cases where we need to be able to "push transitivity inside" an axiom in order to expose further opportunities for optimization. For example, suppose we have C a : t[a] ~ F a g : b ~ c and we want to optimize sym (C b) ; t[g] ; C c which has the kind F b ~ F c (stopping through t[b] and t[c] along the way). We'd like to optimize this to just F g -- but how? The key is that we need to allow axioms to be instantiated by *coercions*, not just by types. Then we can (in certain cases) push transitivity inside the axiom instantiations, and then react opposite-polarity instantiations of the same axiom. In this case, e.g., we match t[g] against the LHS of (C c)'s kind, to obtain the substitution a |-> g (note this operation is sort of the dual of lifting!) and hence end up with C g : t[b] ~ F c which indeed has the same kind as t[g] ; C c. Now we have sym (C b) ; C g which can be optimized to F g. Note [CoAxiom index] ~~~~~~~~~~~~~~~~~~~~ A CoAxiom has 1 or more branches. Each branch has contains a list of the free type variables in that branch, the LHS type patterns, and the RHS type for that branch. When we apply an axiom to a list of coercions, we must choose which branch of the axiom we wish to use, as the different branches may have different numbers of free type variables. (The number of type patterns is always the same among branches, but that doesn't quite concern us here.) The Int in the AxiomInstCo constructor is the 0-indexed number of the chosen branch. Note [Forall coercions] ~~~~~~~~~~~~~~~~~~~~~~~ Constructing coercions between forall-types can be a bit tricky, because the kinds of the bound tyvars can be different. The typing rule is: kind_co : k1 ~ k2 tv1:k1 |- co : t1 ~ t2 ------------------------------------------------------------------- ForAllCo tv1 kind_co co : all tv1:k1. t1 ~ all tv1:k2. (t2[tv1 |-> tv1 |> sym kind_co]) First, the TyVar stored in a ForAllCo is really an optimisation: this field should be a Name, as its kind is redundant. Thinking of the field as a Name is helpful in understanding what a ForAllCo means. The idea is that kind_co gives the two kinds of the tyvar. See how, in the conclusion, tv1 is assigned kind k1 on the left but kind k2 on the right. Of course, a type variable can't have different kinds at the same time. So, we arbitrarily prefer the first kind when using tv1 in the inner coercion co, which shows that t1 equals t2. The last wrinkle is that we need to fix the kinds in the conclusion. In t2, tv1 is assumed to have kind k1, but it has kind k2 in the conclusion of the rule. So we do a kind-fixing substitution, replacing (tv1:k1) with (tv1:k2) |> sym kind_co. This substitution is slightly bizarre, because it mentions the same name with different kinds, but it *is* well-kinded, noting that `(tv1:k2) |> sym kind_co` has kind k1. This all really would work storing just a Name in the ForAllCo. But we can't add Names to, e.g., VarSets, and there generally is just an impedence mismatch in a bunch of places. So we use tv1. When we need tv2, we can use setTyVarKind. Note [Coherence] ~~~~~~~~~~~~~~~~ The Coherence typing rule is thus: g1 : s ~ t s : k1 g2 : k1 ~ k2 ------------------------------------ CoherenceCo g1 g2 : (s |> g2) ~ t While this looks (and is) unsymmetric, a combination of other coercion combinators can make the symmetric version. For role information, see Note [Roles and kind coercions]. Note [Predicate coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have g :: a~b How can we coerce between types ([c]~a) => [a] -> c and ([c]~b) => [b] -> c where the equality predicate *itself* differs? Answer: we simply treat (~) as an ordinary type constructor, so these types really look like ((~) [c] a) -> [a] -> c ((~) [c] b) -> [b] -> c So the coercion between the two is obviously ((~) [c] g) -> [g] -> c Another way to see this to say that we simply collapse predicates to their representation type (see Type.coreView and Type.predTypeRep). This collapse is done by mkPredCo; there is no PredCo constructor in Coercion. This is important because we need Nth to work on predicates too: Nth 1 ((~) [c] g) = g See Simplify.simplCoercionF, which generates such selections. Note [Roles] ~~~~~~~~~~~~ Roles are a solution to the GeneralizedNewtypeDeriving problem, articulated in Trac #1496. The full story is in docs/core-spec/core-spec.pdf. Also, see http://ghc.haskell.org/trac/ghc/wiki/RolesImplementation Here is one way to phrase the problem: Given: newtype Age = MkAge Int type family F x type instance F Age = Bool type instance F Int = Char This compiles down to: axAge :: Age ~ Int axF1 :: F Age ~ Bool axF2 :: F Int ~ Char Then, we can make: (sym (axF1) ; F axAge ; axF2) :: Bool ~ Char Yikes! The solution is _roles_, as articulated in "Generative Type Abstraction and Type-level Computation" (POPL 2010), available at http://www.seas.upenn.edu/~sweirich/papers/popl163af-weirich.pdf The specification for roles has evolved somewhat since that paper. For the current full details, see the documentation in docs/core-spec. Here are some highlights. We label every equality with a notion of type equivalence, of which there are three options: Nominal, Representational, and Phantom. A ground type is nominally equivalent only with itself. A newtype (which is considered a ground type in Haskell) is representationally equivalent to its representation. Anything is "phantomly" equivalent to anything else. We use "N", "R", and "P" to denote the equivalences. The axioms above would be: axAge :: Age ~R Int axF1 :: F Age ~N Bool axF2 :: F Age ~N Char Then, because transitivity applies only to coercions proving the same notion of equivalence, the above construction is impossible. However, there is still an escape hatch: we know that any two types that are nominally equivalent are representationally equivalent as well. This is what the form SubCo proves -- it "demotes" a nominal equivalence into a representational equivalence. So, it would seem the following is possible: sub (sym axF1) ; F axAge ; sub axF2 :: Bool ~R Char -- WRONG What saves us here is that the arguments to a type function F, lifted into a coercion, *must* prove nominal equivalence. So, (F axAge) is ill-formed, and we are safe. Roles are attached to parameters to TyCons. When lifting a TyCon into a coercion (through TyConAppCo), we need to ensure that the arguments to the TyCon respect their roles. For example: data T a b = MkT a (F b) If we know that a1 ~R a2, then we know (T a1 b) ~R (T a2 b). But, if we know that b1 ~R b2, we know nothing about (T a b1) and (T a b2)! This is because the type function F branches on b's *name*, not representation. So, we say that 'a' has role Representational and 'b' has role Nominal. The third role, Phantom, is for parameters not used in the type's definition. Given the following definition data Q a = MkQ Int the Phantom role allows us to say that (Q Bool) ~R (Q Char), because we can construct the coercion Bool ~P Char (using UnivCo). See the paper cited above for more examples and information. Note [TyConAppCo roles] ~~~~~~~~~~~~~~~~~~~~~~~ The TyConAppCo constructor has a role parameter, indicating the role at which the coercion proves equality. The choice of this parameter affects the required roles of the arguments of the TyConAppCo. To help explain it, assume the following definition: type instance F Int = Bool -- Axiom axF : F Int ~N Bool newtype Age = MkAge Int -- Axiom axAge : Age ~R Int data Foo a = MkFoo a -- Role on Foo's parameter is Representational TyConAppCo Nominal Foo axF : Foo (F Int) ~N Foo Bool For (TyConAppCo Nominal) all arguments must have role Nominal. Why? So that Foo Age ~N Foo Int does *not* hold. TyConAppCo Representational Foo (SubCo axF) : Foo (F Int) ~R Foo Bool TyConAppCo Representational Foo axAge : Foo Age ~R Foo Int For (TyConAppCo Representational), all arguments must have the roles corresponding to the result of tyConRoles on the TyCon. This is the whole point of having roles on the TyCon to begin with. So, we can have Foo Age ~R Foo Int, if Foo's parameter has role R. If a Representational TyConAppCo is over-saturated (which is otherwise fine), the spill-over arguments must all be at Nominal. This corresponds to the behavior for AppCo. TyConAppCo Phantom Foo (UnivCo Phantom Int Bool) : Foo Int ~P Foo Bool All arguments must have role Phantom. This one isn't strictly necessary for soundness, but this choice removes ambiguity. The rules here dictate the roles of the parameters to mkTyConAppCo (should be checked by Lint). Note [NthCo and newtypes] ~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have newtype N a = MkN Int type role N representational This yields axiom NTCo:N :: forall a. N a ~R Int We can then build co :: forall a b. N a ~R N b co = NTCo:N a ; sym (NTCo:N b) for any `a` and `b`. Because of the role annotation on N, if we use NthCo, we'll get out a representational coercion. That is: NthCo 0 co :: forall a b. a ~R b Yikes! Clearly, this is terrible. The solution is simple: forbid NthCo to be used on newtypes if the internal coercion is representational. This is not just some corner case discovered by a segfault somewhere; it was discovered in the proof of soundness of roles and described in the "Safe Coercions" paper (ICFP '14). Note [InstCo roles] ~~~~~~~~~~~~~~~~~~~ Here is (essentially) the typing rule for InstCo: g :: (forall a. t1) ~r (forall a. t2) w :: s1 ~N s2 ------------------------------- InstCo InstCo g w :: (t1 [a |-> s1]) ~r (t2 [a |-> s2]) Note that the Coercion w *must* be nominal. This is necessary because the variable a might be used in a "nominal position" (that is, a place where role inference would require a nominal role) in t1 or t2. If we allowed w to be representational, we could get bogus equalities. A more nuanced treatment might be able to relax this condition somewhat, by checking if t1 and/or t2 use their bound variables in nominal ways. If not, having w be representational is OK. %************************************************************************ %* * UnivCoProvenance %* * %************************************************************************ A UnivCo is a coercion whose proof does not directly express its role and kind (indeed for some UnivCos, like UnsafeCoerceProv, there /is/ no proof). The different kinds of UnivCo are described by UnivCoProvenance. Really each is entirely separate, but they all share the need to represent their role and kind, which is done in the UnivCo constructor. -} -- | For simplicity, we have just one UnivCo that represents a coercion from -- some type to some other type, with (in general) no restrictions on the -- type. The UnivCoProvenance specifies more exactly what the coercion really -- is and why a program should (or shouldn't!) trust the coercion. -- It is reasonable to consider each constructor of 'UnivCoProvenance' -- as a totally independent coercion form; their only commonality is -- that they don't tell you what types they coercion between. (That info -- is in the 'UnivCo' constructor of 'Coercion'. data UnivCoProvenance = UnsafeCoerceProv -- ^ From @unsafeCoerce#@. These are unsound. | PhantomProv KindCoercion -- ^ See Note [Phantom coercions]. Only in Phantom -- roled coercions | ProofIrrelProv KindCoercion -- ^ From the fact that any two coercions are -- considered equivalent. See Note [ProofIrrelProv]. -- Can be used in Nominal or Representational coercions | PluginProv String -- ^ From a plugin, which asserts that this coercion -- is sound. The string is for the use of the plugin. | HoleProv CoercionHole -- ^ See Note [Coercion holes] deriving Data.Data instance Outputable UnivCoProvenance where ppr UnsafeCoerceProv = text "(unsafeCoerce#)" ppr (PhantomProv _) = text "(phantom)" ppr (ProofIrrelProv _) = text "(proof irrel.)" ppr (PluginProv str) = parens (text "plugin" <+> brackets (text str)) ppr (HoleProv hole) = parens (text "hole" <> ppr hole) -- | A coercion to be filled in by the type-checker. See Note [Coercion holes] data CoercionHole = CoercionHole { chUnique :: Unique -- ^ used only for debugging , chCoercion :: IORef (Maybe Coercion) } instance Data.Data CoercionHole where -- don't traverse? toConstr _ = abstractConstr "CoercionHole" gunfold _ _ = error "gunfold" dataTypeOf _ = mkNoRepType "CoercionHole" instance Outputable CoercionHole where ppr (CoercionHole u _) = braces (ppr u) {- Note [Phantom coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T a = T1 | T2 Then we have T s ~R T t for any old s,t. The witness for this is (TyConAppCo T Rep co), where (co :: s ~P t) is a phantom coercion built with PhantomProv. The role of the UnivCo is always Phantom. The Coercion stored is the (nominal) kind coercion between the types kind(s) ~N kind (t) Note [Coercion holes] ~~~~~~~~~~~~~~~~~~~~~~~~ During typechecking, constraint solving for type classes works by - Generate an evidence Id, d7 :: Num a - Wrap it in a Wanted constraint, [W] d7 :: Num a - Use the evidence Id where the evidence is needed - Solve the constraint later - When solved, add an enclosing let-binding let d7 = .... in .... which actually binds d7 to the (Num a) evidence For equality constraints we use a different strategy. See Note [The equality types story] in TysPrim for background on equality constraints. - For boxed equality constraints, (t1 ~N t2) and (t1 ~R t2), it's just like type classes above. (Indeed, boxed equality constraints *are* classes.) - But for /unboxed/ equality constraints (t1 ~R# t2) and (t1 ~N# t2) we use a different plan For unboxed equalities: - Generate a CoercionHole, a mutable variable just like a unification variable - Wrap the CoercionHole in a Wanted constraint; see TcRnTypes.TcEvDest - Use the CoercionHole in a Coercion, via HoleProv - Solve the constraint later - When solved, fill in the CoercionHole by side effect, instead of doing the let-binding thing The main reason for all this is that there may be no good place to let-bind the evidence for unboxed equalities: - We emit constraints for kind coercions, to be used to cast a type's kind. These coercions then must be used in types. Because they might appear in a top-level type, there is no place to bind these (unlifted) coercions in the usual way. - A coercion for (forall a. t1) ~ forall a. t2) will look like forall a. (coercion for t1~t2) But the coercion for (t1~t2) may mention 'a', and we don't have let-bindings within coercions. We could add them, but coercion holes are easier. Other notes about HoleCo: * INVARIANT: CoercionHole and HoleProv are used only during type checking, and should never appear in Core. Just like unification variables; a Type can contain a TcTyVar, but only during type checking. If, one day, we use type-level information to separate out forms that can appear during type-checking vs forms that can appear in core proper, holes in Core will be ruled out. * The Unique carried with a coercion hole is used solely for debugging. * Coercion holes can be compared for equality only like other coercions: only by looking at the types coerced. * We don't use holes for other evidence because other evidence wants to be /shared/. But coercions are entirely erased, so there's little benefit to sharing. Note [ProofIrrelProv] ~~~~~~~~~~~~~~~~~~~~~ A ProofIrrelProv is a coercion between coercions. For example: data G a where MkG :: G Bool In core, we get G :: * -> * MkG :: forall (a :: *). (a ~ Bool) -> G a Now, consider 'MkG -- that is, MkG used in a type -- and suppose we want a proof that ('MkG co1 a1) ~ ('MkG co2 a2). This will have to be TyConAppCo Nominal MkG [co3, co4] where co3 :: co1 ~ co2 co4 :: a1 ~ a2 Note that co1 :: a1 ~ Bool co2 :: a2 ~ Bool Here, co3 = UnivCo (ProofIrrelProv co5) Nominal (CoercionTy co1) (CoercionTy co2) where co5 :: (a1 ~ Bool) ~ (a2 ~ Bool) co5 = TyConAppCo Nominal (~) [<*>, <*>, co4, <Bool>] %************************************************************************ %* * Free variables of types and coercions %* * %************************************************************************ -} {- Note [Free variables of types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The family of functions tyCoVarsOfType, tyCoVarsOfTypes etc, returns a VarSet that is closed over the types of its variables. More precisely, if S = tyCoVarsOfType( t ) and (a:k) is in S then tyCoVarsOftype( k ) is a subset of S Example: The tyCoVars of this ((a:* -> k) Int) is {a, k}. We could /not/ close over the kinds of the variable occurrences, and instead do so at call sites, but it seems that we always want to do so, so it's easiest to do it here. -} -- | Returns free variables of a type, including kind variables as -- a non-deterministic set. For type synonyms it does /not/ expand the -- synonym. tyCoVarsOfType :: Type -> TyCoVarSet -- See Note [Free variables of types] tyCoVarsOfType ty = fvVarSet $ tyCoFVsOfType ty -- | `tyVarsOfType` that returns free variables of a type in a deterministic -- set. For explanation of why using `VarSet` is not deterministic see -- Note [Deterministic FV] in FV. tyCoVarsOfTypeDSet :: Type -> DTyCoVarSet -- See Note [Free variables of types] tyCoVarsOfTypeDSet ty = fvDVarSet $ tyCoFVsOfType ty -- | `tyVarsOfType` that returns free variables of a type in deterministic -- order. For explanation of why using `VarSet` is not deterministic see -- Note [Deterministic FV] in FV. tyCoVarsOfTypeList :: Type -> [TyCoVar] -- See Note [Free variables of types] tyCoVarsOfTypeList ty = fvVarList $ tyCoFVsOfType ty -- | The worker for `tyVarsOfType` and `tyVarsOfTypeList`. -- The previous implementation used `unionVarSet` which is O(n+m) and can -- make the function quadratic. -- It's exported, so that it can be composed with -- other functions that compute free variables. -- See Note [FV naming conventions] in FV. -- -- Eta-expanded because that makes it run faster (apparently) -- See Note [FV eta expansion] in FV for explanation. tyCoFVsOfType :: Type -> FV -- See Note [Free variables of types] tyCoFVsOfType (TyVarTy v) a b c = (unitFV v `unionFV` tyCoFVsOfType (tyVarKind v)) a b c tyCoFVsOfType (TyConApp _ tys) a b c = tyCoFVsOfTypes tys a b c tyCoFVsOfType (LitTy {}) a b c = emptyFV a b c tyCoFVsOfType (AppTy fun arg) a b c = (tyCoFVsOfType fun `unionFV` tyCoFVsOfType arg) a b c tyCoFVsOfType (FunTy arg res) a b c = (tyCoFVsOfType arg `unionFV` tyCoFVsOfType res) a b c tyCoFVsOfType (ForAllTy bndr ty) a b c = tyCoFVsBndr bndr (tyCoFVsOfType ty) a b c tyCoFVsOfType (CastTy ty co) a b c = (tyCoFVsOfType ty `unionFV` tyCoFVsOfCo co) a b c tyCoFVsOfType (CoercionTy co) a b c = tyCoFVsOfCo co a b c tyCoFVsBndr :: TyVarBinder -> FV -> FV -- Free vars of (forall b. <thing with fvs>) tyCoFVsBndr (TvBndr tv _) fvs = (delFV tv fvs) `unionFV` tyCoFVsOfType (tyVarKind tv) -- | Returns free variables of types, including kind variables as -- a non-deterministic set. For type synonyms it does /not/ expand the -- synonym. tyCoVarsOfTypes :: [Type] -> TyCoVarSet -- See Note [Free variables of types] tyCoVarsOfTypes tys = fvVarSet $ tyCoFVsOfTypes tys -- | Returns free variables of types, including kind variables as -- a non-deterministic set. For type synonyms it does /not/ expand the -- synonym. tyCoVarsOfTypesSet :: TyVarEnv Type -> TyCoVarSet -- See Note [Free variables of types] tyCoVarsOfTypesSet tys = fvVarSet $ tyCoFVsOfTypes $ nonDetEltsUFM tys -- It's OK to use nonDetEltsUFM here because we immediately forget the -- ordering by returning a set -- | Returns free variables of types, including kind variables as -- a deterministic set. For type synonyms it does /not/ expand the -- synonym. tyCoVarsOfTypesDSet :: [Type] -> DTyCoVarSet -- See Note [Free variables of types] tyCoVarsOfTypesDSet tys = fvDVarSet $ tyCoFVsOfTypes tys -- | Returns free variables of types, including kind variables as -- a deterministically ordered list. For type synonyms it does /not/ expand the -- synonym. tyCoVarsOfTypesList :: [Type] -> [TyCoVar] -- See Note [Free variables of types] tyCoVarsOfTypesList tys = fvVarList $ tyCoFVsOfTypes tys tyCoFVsOfTypes :: [Type] -> FV -- See Note [Free variables of types] tyCoFVsOfTypes (ty:tys) fv_cand in_scope acc = (tyCoFVsOfType ty `unionFV` tyCoFVsOfTypes tys) fv_cand in_scope acc tyCoFVsOfTypes [] fv_cand in_scope acc = emptyFV fv_cand in_scope acc tyCoVarsOfCo :: Coercion -> TyCoVarSet -- See Note [Free variables of types] tyCoVarsOfCo co = fvVarSet $ tyCoFVsOfCo co -- | Get a deterministic set of the vars free in a coercion tyCoVarsOfCoDSet :: Coercion -> DTyCoVarSet -- See Note [Free variables of types] tyCoVarsOfCoDSet co = fvDVarSet $ tyCoFVsOfCo co tyCoVarsOfCoList :: Coercion -> [TyCoVar] -- See Note [Free variables of types] tyCoVarsOfCoList co = fvVarList $ tyCoFVsOfCo co tyCoFVsOfCo :: Coercion -> FV -- Extracts type and coercion variables from a coercion -- See Note [Free variables of types] tyCoFVsOfCo (Refl _ ty) fv_cand in_scope acc = tyCoFVsOfType ty fv_cand in_scope acc tyCoFVsOfCo (TyConAppCo _ _ cos) fv_cand in_scope acc = tyCoFVsOfCos cos fv_cand in_scope acc tyCoFVsOfCo (AppCo co arg) fv_cand in_scope acc = (tyCoFVsOfCo co `unionFV` tyCoFVsOfCo arg) fv_cand in_scope acc tyCoFVsOfCo (ForAllCo tv kind_co co) fv_cand in_scope acc = (delFV tv (tyCoFVsOfCo co) `unionFV` tyCoFVsOfCo kind_co) fv_cand in_scope acc tyCoFVsOfCo (CoVarCo v) fv_cand in_scope acc = (unitFV v `unionFV` tyCoFVsOfType (varType v)) fv_cand in_scope acc tyCoFVsOfCo (AxiomInstCo _ _ cos) fv_cand in_scope acc = tyCoFVsOfCos cos fv_cand in_scope acc tyCoFVsOfCo (UnivCo p _ t1 t2) fv_cand in_scope acc = (tyCoFVsOfProv p `unionFV` tyCoFVsOfType t1 `unionFV` tyCoFVsOfType t2) fv_cand in_scope acc tyCoFVsOfCo (SymCo co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfCo (TransCo co1 co2) fv_cand in_scope acc = (tyCoFVsOfCo co1 `unionFV` tyCoFVsOfCo co2) fv_cand in_scope acc tyCoFVsOfCo (NthCo _ co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfCo (LRCo _ co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfCo (InstCo co arg) fv_cand in_scope acc = (tyCoFVsOfCo co `unionFV` tyCoFVsOfCo arg) fv_cand in_scope acc tyCoFVsOfCo (CoherenceCo c1 c2) fv_cand in_scope acc = (tyCoFVsOfCo c1 `unionFV` tyCoFVsOfCo c2) fv_cand in_scope acc tyCoFVsOfCo (KindCo co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfCo (SubCo co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfCo (AxiomRuleCo _ cs) fv_cand in_scope acc = tyCoFVsOfCos cs fv_cand in_scope acc tyCoVarsOfProv :: UnivCoProvenance -> TyCoVarSet tyCoVarsOfProv prov = fvVarSet $ tyCoFVsOfProv prov tyCoFVsOfProv :: UnivCoProvenance -> FV tyCoFVsOfProv UnsafeCoerceProv fv_cand in_scope acc = emptyFV fv_cand in_scope acc tyCoFVsOfProv (PhantomProv co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfProv (ProofIrrelProv co) fv_cand in_scope acc = tyCoFVsOfCo co fv_cand in_scope acc tyCoFVsOfProv (PluginProv _) fv_cand in_scope acc = emptyFV fv_cand in_scope acc tyCoFVsOfProv (HoleProv _) fv_cand in_scope acc = emptyFV fv_cand in_scope acc tyCoVarsOfCos :: [Coercion] -> TyCoVarSet tyCoVarsOfCos cos = fvVarSet $ tyCoFVsOfCos cos tyCoVarsOfCosSet :: CoVarEnv Coercion -> TyCoVarSet tyCoVarsOfCosSet cos = fvVarSet $ tyCoFVsOfCos $ nonDetEltsUFM cos -- It's OK to use nonDetEltsUFM here because we immediately forget the -- ordering by returning a set tyCoFVsOfCos :: [Coercion] -> FV tyCoFVsOfCos [] fv_cand in_scope acc = emptyFV fv_cand in_scope acc tyCoFVsOfCos (co:cos) fv_cand in_scope acc = (tyCoFVsOfCo co `unionFV` tyCoFVsOfCos cos) fv_cand in_scope acc coVarsOfType :: Type -> CoVarSet coVarsOfType (TyVarTy v) = coVarsOfType (tyVarKind v) coVarsOfType (TyConApp _ tys) = coVarsOfTypes tys coVarsOfType (LitTy {}) = emptyVarSet coVarsOfType (AppTy fun arg) = coVarsOfType fun `unionVarSet` coVarsOfType arg coVarsOfType (FunTy arg res) = coVarsOfType arg `unionVarSet` coVarsOfType res coVarsOfType (ForAllTy (TvBndr tv _) ty) = (coVarsOfType ty `delVarSet` tv) `unionVarSet` coVarsOfType (tyVarKind tv) coVarsOfType (CastTy ty co) = coVarsOfType ty `unionVarSet` coVarsOfCo co coVarsOfType (CoercionTy co) = coVarsOfCo co coVarsOfTypes :: [Type] -> TyCoVarSet coVarsOfTypes tys = mapUnionVarSet coVarsOfType tys coVarsOfCo :: Coercion -> CoVarSet -- Extract *coercion* variables only. Tiresome to repeat the code, but easy. coVarsOfCo (Refl _ ty) = coVarsOfType ty coVarsOfCo (TyConAppCo _ _ args) = coVarsOfCos args coVarsOfCo (AppCo co arg) = coVarsOfCo co `unionVarSet` coVarsOfCo arg coVarsOfCo (ForAllCo tv kind_co co) = coVarsOfCo co `delVarSet` tv `unionVarSet` coVarsOfCo kind_co coVarsOfCo (CoVarCo v) = unitVarSet v `unionVarSet` coVarsOfType (varType v) coVarsOfCo (AxiomInstCo _ _ args) = coVarsOfCos args coVarsOfCo (UnivCo p _ t1 t2) = coVarsOfProv p `unionVarSet` coVarsOfTypes [t1, t2] coVarsOfCo (SymCo co) = coVarsOfCo co coVarsOfCo (TransCo co1 co2) = coVarsOfCo co1 `unionVarSet` coVarsOfCo co2 coVarsOfCo (NthCo _ co) = coVarsOfCo co coVarsOfCo (LRCo _ co) = coVarsOfCo co coVarsOfCo (InstCo co arg) = coVarsOfCo co `unionVarSet` coVarsOfCo arg coVarsOfCo (CoherenceCo c1 c2) = coVarsOfCos [c1, c2] coVarsOfCo (KindCo co) = coVarsOfCo co coVarsOfCo (SubCo co) = coVarsOfCo co coVarsOfCo (AxiomRuleCo _ cs) = coVarsOfCos cs coVarsOfProv :: UnivCoProvenance -> CoVarSet coVarsOfProv UnsafeCoerceProv = emptyVarSet coVarsOfProv (PhantomProv co) = coVarsOfCo co coVarsOfProv (ProofIrrelProv co) = coVarsOfCo co coVarsOfProv (PluginProv _) = emptyVarSet coVarsOfProv (HoleProv _) = emptyVarSet coVarsOfCos :: [Coercion] -> CoVarSet coVarsOfCos cos = mapUnionVarSet coVarsOfCo cos -- | Add the kind variables free in the kinds of the tyvars in the given set. -- Returns a non-deterministic set. closeOverKinds :: TyVarSet -> TyVarSet closeOverKinds = fvVarSet . closeOverKindsFV . nonDetEltsUFM -- It's OK to use nonDetEltsUFM here because we immediately forget -- about the ordering by returning a set. -- | Given a list of tyvars returns a deterministic FV computation that -- returns the given tyvars with the kind variables free in the kinds of the -- given tyvars. closeOverKindsFV :: [TyVar] -> FV closeOverKindsFV tvs = mapUnionFV (tyCoFVsOfType . tyVarKind) tvs `unionFV` mkFVs tvs -- | Add the kind variables free in the kinds of the tyvars in the given set. -- Returns a deterministically ordered list. closeOverKindsList :: [TyVar] -> [TyVar] closeOverKindsList tvs = fvVarList $ closeOverKindsFV tvs -- | Add the kind variables free in the kinds of the tyvars in the given set. -- Returns a deterministic set. closeOverKindsDSet :: DTyVarSet -> DTyVarSet closeOverKindsDSet = fvDVarSet . closeOverKindsFV . dVarSetElems {- %************************************************************************ %* * Substitutions Data type defined here to avoid unnecessary mutual recursion %* * %************************************************************************ -} -- | Type & coercion substitution -- -- #tcvsubst_invariant# -- The following invariants must hold of a 'TCvSubst': -- -- 1. The in-scope set is needed /only/ to -- guide the generation of fresh uniques -- -- 2. In particular, the /kind/ of the type variables in -- the in-scope set is not relevant -- -- 3. The substitution is only applied ONCE! This is because -- in general such application will not reach a fixed point. data TCvSubst = TCvSubst InScopeSet -- The in-scope type and kind variables TvSubstEnv -- Substitutes both type and kind variables CvSubstEnv -- Substitutes coercion variables -- See Note [Apply Once] -- and Note [Extending the TvSubstEnv] -- and Note [Substituting types and coercions] -- and Note [The substitution invariant] -- | A substitution of 'Type's for 'TyVar's -- and 'Kind's for 'KindVar's type TvSubstEnv = TyVarEnv Type -- A TvSubstEnv is used both inside a TCvSubst (with the apply-once -- invariant discussed in Note [Apply Once]), and also independently -- in the middle of matching, and unification (see Types.Unify) -- So you have to look at the context to know if it's idempotent or -- apply-once or whatever -- | A substitution of 'Coercion's for 'CoVar's type CvSubstEnv = CoVarEnv Coercion {- Note [Apply Once] ~~~~~~~~~~~~~~~~~ We use TCvSubsts to instantiate things, and we might instantiate forall a b. ty \with the types [a, b], or [b, a]. So the substitution might go [a->b, b->a]. A similar situation arises in Core when we find a beta redex like (/\ a /\ b -> e) b a Then we also end up with a substitution that permutes type variables. Other variations happen to; for example [a -> (a, b)]. **************************************************** *** So a TCvSubst must be applied precisely once *** **************************************************** A TCvSubst is not idempotent, but, unlike the non-idempotent substitution we use during unifications, it must not be repeatedly applied. Note [Extending the TvSubstEnv] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See #tcvsubst_invariant# for the invariants that must hold. This invariant allows a short-cut when the subst envs are empty: if the TvSubstEnv and CvSubstEnv are empty --- i.e. (isEmptyTCvSubst subst) holds --- then (substTy subst ty) does nothing. For example, consider: (/\a. /\b:(a~Int). ...b..) Int We substitute Int for 'a'. The Unique of 'b' does not change, but nevertheless we add 'b' to the TvSubstEnv, because b's kind does change This invariant has several crucial consequences: * In substTyVarBndr, we need extend the TvSubstEnv - if the unique has changed - or if the kind has changed * In substTyVar, we do not need to consult the in-scope set; the TvSubstEnv is enough * In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty Note [Substituting types and coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Types and coercions are mutually recursive, and either may have variables "belonging" to the other. Thus, every time we wish to substitute in a type, we may also need to substitute in a coercion, and vice versa. However, the constructor used to create type variables is distinct from that of coercion variables, so we carry two VarEnvs in a TCvSubst. Note that it would be possible to use the CoercionTy constructor to combine these environments, but that seems like a false economy. Note that the TvSubstEnv should *never* map a CoVar (built with the Id constructor) and the CvSubstEnv should *never* map a TyVar. Furthermore, the range of the TvSubstEnv should *never* include a type headed with CoercionTy. Note [The substitution invariant] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When calling (substTy subst ty) it should be the case that the in-scope set in the substitution is a superset of both: * The free vars of the range of the substitution * The free vars of ty minus the domain of the substitution If we want to substitute [a -> ty1, b -> ty2] I used to think it was enough to generate an in-scope set that includes fv(ty1,ty2). But that's not enough; we really should also take the free vars of the type we are substituting into! Example: (forall b. (a,b,x)) [a -> List b] Then if we use the in-scope set {b}, there is a danger we will rename the forall'd variable to 'x' by mistake, getting this: (forall x. (List b, x, x)) Breaking this invariant caused the bug from #11371. -} emptyTvSubstEnv :: TvSubstEnv emptyTvSubstEnv = emptyVarEnv emptyCvSubstEnv :: CvSubstEnv emptyCvSubstEnv = emptyVarEnv composeTCvSubstEnv :: InScopeSet -> (TvSubstEnv, CvSubstEnv) -> (TvSubstEnv, CvSubstEnv) -> (TvSubstEnv, CvSubstEnv) -- ^ @(compose env1 env2)(x)@ is @env1(env2(x))@; i.e. apply @env2@ then @env1@. -- It assumes that both are idempotent. -- Typically, @env1@ is the refinement to a base substitution @env2@ composeTCvSubstEnv in_scope (tenv1, cenv1) (tenv2, cenv2) = ( tenv1 `plusVarEnv` mapVarEnv (substTy subst1) tenv2 , cenv1 `plusVarEnv` mapVarEnv (substCo subst1) cenv2 ) -- First apply env1 to the range of env2 -- Then combine the two, making sure that env1 loses if -- both bind the same variable; that's why env1 is the -- *left* argument to plusVarEnv, because the right arg wins where subst1 = TCvSubst in_scope tenv1 cenv1 -- | Composes two substitutions, applying the second one provided first, -- like in function composition. composeTCvSubst :: TCvSubst -> TCvSubst -> TCvSubst composeTCvSubst (TCvSubst is1 tenv1 cenv1) (TCvSubst is2 tenv2 cenv2) = TCvSubst is3 tenv3 cenv3 where is3 = is1 `unionInScope` is2 (tenv3, cenv3) = composeTCvSubstEnv is3 (tenv1, cenv1) (tenv2, cenv2) emptyTCvSubst :: TCvSubst emptyTCvSubst = TCvSubst emptyInScopeSet emptyTvSubstEnv emptyCvSubstEnv mkEmptyTCvSubst :: InScopeSet -> TCvSubst mkEmptyTCvSubst is = TCvSubst is emptyTvSubstEnv emptyCvSubstEnv isEmptyTCvSubst :: TCvSubst -> Bool -- See Note [Extending the TvSubstEnv] isEmptyTCvSubst (TCvSubst _ tenv cenv) = isEmptyVarEnv tenv && isEmptyVarEnv cenv mkTCvSubst :: InScopeSet -> (TvSubstEnv, CvSubstEnv) -> TCvSubst mkTCvSubst in_scope (tenv, cenv) = TCvSubst in_scope tenv cenv mkTvSubst :: InScopeSet -> TvSubstEnv -> TCvSubst -- ^ Make a TCvSubst with specified tyvar subst and empty covar subst mkTvSubst in_scope tenv = TCvSubst in_scope tenv emptyCvSubstEnv getTvSubstEnv :: TCvSubst -> TvSubstEnv getTvSubstEnv (TCvSubst _ env _) = env getCvSubstEnv :: TCvSubst -> CvSubstEnv getCvSubstEnv (TCvSubst _ _ env) = env getTCvInScope :: TCvSubst -> InScopeSet getTCvInScope (TCvSubst in_scope _ _) = in_scope -- | Returns the free variables of the types in the range of a substitution as -- a non-deterministic set. getTCvSubstRangeFVs :: TCvSubst -> VarSet getTCvSubstRangeFVs (TCvSubst _ tenv cenv) = unionVarSet tenvFVs cenvFVs where tenvFVs = tyCoVarsOfTypesSet tenv cenvFVs = tyCoVarsOfCosSet cenv isInScope :: Var -> TCvSubst -> Bool isInScope v (TCvSubst in_scope _ _) = v `elemInScopeSet` in_scope notElemTCvSubst :: Var -> TCvSubst -> Bool notElemTCvSubst v (TCvSubst _ tenv cenv) | isTyVar v = not (v `elemVarEnv` tenv) | otherwise = not (v `elemVarEnv` cenv) setTvSubstEnv :: TCvSubst -> TvSubstEnv -> TCvSubst setTvSubstEnv (TCvSubst in_scope _ cenv) tenv = TCvSubst in_scope tenv cenv setCvSubstEnv :: TCvSubst -> CvSubstEnv -> TCvSubst setCvSubstEnv (TCvSubst in_scope tenv _) cenv = TCvSubst in_scope tenv cenv zapTCvSubst :: TCvSubst -> TCvSubst zapTCvSubst (TCvSubst in_scope _ _) = TCvSubst in_scope emptyVarEnv emptyVarEnv extendTCvInScope :: TCvSubst -> Var -> TCvSubst extendTCvInScope (TCvSubst in_scope tenv cenv) var = TCvSubst (extendInScopeSet in_scope var) tenv cenv extendTCvInScopeList :: TCvSubst -> [Var] -> TCvSubst extendTCvInScopeList (TCvSubst in_scope tenv cenv) vars = TCvSubst (extendInScopeSetList in_scope vars) tenv cenv extendTCvInScopeSet :: TCvSubst -> VarSet -> TCvSubst extendTCvInScopeSet (TCvSubst in_scope tenv cenv) vars = TCvSubst (extendInScopeSetSet in_scope vars) tenv cenv extendTCvSubst :: TCvSubst -> TyCoVar -> Type -> TCvSubst extendTCvSubst subst v ty | isTyVar v = extendTvSubst subst v ty | CoercionTy co <- ty = extendCvSubst subst v co | otherwise = pprPanic "extendTCvSubst" (ppr v <+> text "|->" <+> ppr ty) extendTvSubst :: TCvSubst -> TyVar -> Type -> TCvSubst extendTvSubst (TCvSubst in_scope tenv cenv) tv ty = TCvSubst in_scope (extendVarEnv tenv tv ty) cenv extendTvSubstBinder :: TCvSubst -> TyBinder -> Type -> TCvSubst extendTvSubstBinder subst (Named bndr) ty = extendTvSubst subst (binderVar bndr) ty extendTvSubstBinder subst (Anon _) _ = subst extendTvSubstWithClone :: TCvSubst -> TyVar -> TyVar -> TCvSubst -- Adds a new tv -> tv mapping, /and/ extends the in-scope set extendTvSubstWithClone (TCvSubst in_scope tenv cenv) tv tv' = TCvSubst (extendInScopeSetSet in_scope new_in_scope) (extendVarEnv tenv tv (mkTyVarTy tv')) cenv where new_in_scope = tyCoVarsOfType (tyVarKind tv') `extendVarSet` tv' extendCvSubst :: TCvSubst -> CoVar -> Coercion -> TCvSubst extendCvSubst (TCvSubst in_scope tenv cenv) v co = TCvSubst in_scope tenv (extendVarEnv cenv v co) extendCvSubstWithClone :: TCvSubst -> CoVar -> CoVar -> TCvSubst extendCvSubstWithClone (TCvSubst in_scope tenv cenv) cv cv' = TCvSubst (extendInScopeSetSet in_scope new_in_scope) tenv (extendVarEnv cenv cv (mkCoVarCo cv')) where new_in_scope = tyCoVarsOfType (varType cv') `extendVarSet` cv' extendTvSubstAndInScope :: TCvSubst -> TyVar -> Type -> TCvSubst -- Also extends the in-scope set extendTvSubstAndInScope (TCvSubst in_scope tenv cenv) tv ty = TCvSubst (in_scope `extendInScopeSetSet` tyCoVarsOfType ty) (extendVarEnv tenv tv ty) cenv extendTvSubstList :: TCvSubst -> [Var] -> [Type] -> TCvSubst extendTvSubstList subst tvs tys = foldl2 extendTvSubst subst tvs tys unionTCvSubst :: TCvSubst -> TCvSubst -> TCvSubst -- Works when the ranges are disjoint unionTCvSubst (TCvSubst in_scope1 tenv1 cenv1) (TCvSubst in_scope2 tenv2 cenv2) = ASSERT( not (tenv1 `intersectsVarEnv` tenv2) && not (cenv1 `intersectsVarEnv` cenv2) ) TCvSubst (in_scope1 `unionInScope` in_scope2) (tenv1 `plusVarEnv` tenv2) (cenv1 `plusVarEnv` cenv2) -- mkTvSubstPrs and zipTvSubst generate the in-scope set from -- the types given; but it's just a thunk so with a bit of luck -- it'll never be evaluated -- | Generates an in-scope set from the free variables in a list of types -- and a list of coercions mkTyCoInScopeSet :: [Type] -> [Coercion] -> InScopeSet mkTyCoInScopeSet tys cos = mkInScopeSet (tyCoVarsOfTypes tys `unionVarSet` tyCoVarsOfCos cos) -- | Generates the in-scope set for the 'TCvSubst' from the types in the incoming -- environment. No CoVars, please! zipTvSubst :: [TyVar] -> [Type] -> TCvSubst zipTvSubst tvs tys | debugIsOn , not (all isTyVar tvs) || length tvs /= length tys = pprTrace "zipTvSubst" (ppr tvs $$ ppr tys) emptyTCvSubst | otherwise = mkTvSubst (mkInScopeSet (tyCoVarsOfTypes tys)) tenv where tenv = zipTyEnv tvs tys -- | Generates the in-scope set for the 'TCvSubst' from the types in the incoming -- environment. No TyVars, please! zipCvSubst :: [CoVar] -> [Coercion] -> TCvSubst zipCvSubst cvs cos | debugIsOn , not (all isCoVar cvs) || length cvs /= length cos = pprTrace "zipCvSubst" (ppr cvs $$ ppr cos) emptyTCvSubst | otherwise = TCvSubst (mkInScopeSet (tyCoVarsOfCos cos)) emptyTvSubstEnv cenv where cenv = zipCoEnv cvs cos -- | Generates the in-scope set for the 'TCvSubst' from the types in the -- incoming environment. No CoVars, please! mkTvSubstPrs :: [(TyVar, Type)] -> TCvSubst mkTvSubstPrs prs = ASSERT2( onlyTyVarsAndNoCoercionTy, text "prs" <+> ppr prs ) mkTvSubst in_scope tenv where tenv = mkVarEnv prs in_scope = mkInScopeSet $ tyCoVarsOfTypes $ map snd prs onlyTyVarsAndNoCoercionTy = and [ isTyVar tv && not (isCoercionTy ty) | (tv, ty) <- prs ] zipTyEnv :: [TyVar] -> [Type] -> TvSubstEnv zipTyEnv tyvars tys = ASSERT( all (not . isCoercionTy) tys ) mkVarEnv (zipEqual "zipTyEnv" tyvars tys) -- There used to be a special case for when -- ty == TyVarTy tv -- (a not-uncommon case) in which case the substitution was dropped. -- But the type-tidier changes the print-name of a type variable without -- changing the unique, and that led to a bug. Why? Pre-tidying, we had -- a type {Foo t}, where Foo is a one-method class. So Foo is really a newtype. -- And it happened that t was the type variable of the class. Post-tiding, -- it got turned into {Foo t2}. The ext-core printer expanded this using -- sourceTypeRep, but that said "Oh, t == t2" because they have the same unique, -- and so generated a rep type mentioning t not t2. -- -- Simplest fix is to nuke the "optimisation" zipCoEnv :: [CoVar] -> [Coercion] -> CvSubstEnv zipCoEnv cvs cos = mkVarEnv (zipEqual "zipCoEnv" cvs cos) instance Outputable TCvSubst where ppr (TCvSubst ins tenv cenv) = brackets $ sep[ text "TCvSubst", nest 2 (text "In scope:" <+> ppr ins), nest 2 (text "Type env:" <+> ppr tenv), nest 2 (text "Co env:" <+> ppr cenv) ] {- %************************************************************************ %* * Performing type or kind substitutions %* * %************************************************************************ Note [Sym and ForAllCo] ~~~~~~~~~~~~~~~~~~~~~~~ In OptCoercion, we try to push "sym" out to the leaves of a coercion. But, how do we push sym into a ForAllCo? It's a little ugly. Here is the typing rule: h : k1 ~# k2 (tv : k1) |- g : ty1 ~# ty2 ---------------------------- ForAllCo tv h g : (ForAllTy (tv : k1) ty1) ~# (ForAllTy (tv : k2) (ty2[tv |-> tv |> sym h])) Here is what we want: ForAllCo tv h' g' : (ForAllTy (tv : k2) (ty2[tv |-> tv |> sym h])) ~# (ForAllTy (tv : k1) ty1) Because the kinds of the type variables to the right of the colon are the kinds coerced by h', we know (h' : k2 ~# k1). Thus, (h' = sym h). Now, we can rewrite ty1 to be (ty1[tv |-> tv |> sym h' |> h']). We thus want ForAllCo tv h' g' : (ForAllTy (tv : k2) (ty2[tv |-> tv |> h'])) ~# (ForAllTy (tv : k1) (ty1[tv |-> tv |> h'][tv |-> tv |> sym h'])) We thus see that we want g' : ty2[tv |-> tv |> h'] ~# ty1[tv |-> tv |> h'] and thus g' = sym (g[tv |-> tv |> h']). Putting it all together, we get this: sym (ForAllCo tv h g) ==> ForAllCo tv (sym h) (sym g[tv |-> tv |> sym h]) -} -- | Type substitution, see 'zipTvSubst' substTyWith :: -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) (?callStack :: CallStack) => #endif [TyVar] -> [Type] -> Type -> Type -- Works only if the domain of the substitution is a -- superset of the type being substituted into substTyWith tvs tys = ASSERT( length tvs == length tys ) substTy (zipTvSubst tvs tys) -- | Type substitution, see 'zipTvSubst'. Disables sanity checks. -- The problems that the sanity checks in substTy catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substTyUnchecked to -- substTy and remove this function. Please don't use in new code. substTyWithUnchecked :: [TyVar] -> [Type] -> Type -> Type substTyWithUnchecked tvs tys = ASSERT( length tvs == length tys ) substTyUnchecked (zipTvSubst tvs tys) -- | Substitute tyvars within a type using a known 'InScopeSet'. -- Pre-condition: the 'in_scope' set should satisfy Note [The substitution -- invariant]; specifically it should include the free vars of 'tys', -- and of 'ty' minus the domain of the subst. substTyWithInScope :: InScopeSet -> [TyVar] -> [Type] -> Type -> Type substTyWithInScope in_scope tvs tys ty = ASSERT( length tvs == length tys ) substTy (mkTvSubst in_scope tenv) ty where tenv = zipTyEnv tvs tys -- | Coercion substitution, see 'zipTvSubst' substCoWith :: -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) (?callStack :: CallStack) => #endif [TyVar] -> [Type] -> Coercion -> Coercion substCoWith tvs tys = ASSERT( length tvs == length tys ) substCo (zipTvSubst tvs tys) -- | Coercion substitution, see 'zipTvSubst'. Disables sanity checks. -- The problems that the sanity checks in substCo catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substCoUnchecked to -- substCo and remove this function. Please don't use in new code. substCoWithUnchecked :: [TyVar] -> [Type] -> Coercion -> Coercion substCoWithUnchecked tvs tys = ASSERT( length tvs == length tys ) substCoUnchecked (zipTvSubst tvs tys) -- | Substitute covars within a type substTyWithCoVars :: [CoVar] -> [Coercion] -> Type -> Type substTyWithCoVars cvs cos = substTy (zipCvSubst cvs cos) -- | Type substitution, see 'zipTvSubst' substTysWith :: [TyVar] -> [Type] -> [Type] -> [Type] substTysWith tvs tys = ASSERT( length tvs == length tys ) substTys (zipTvSubst tvs tys) -- | Type substitution, see 'zipTvSubst' substTysWithCoVars :: [CoVar] -> [Coercion] -> [Type] -> [Type] substTysWithCoVars cvs cos = ASSERT( length cvs == length cos ) substTys (zipCvSubst cvs cos) -- | Substitute within a 'Type' after adding the free variables of the type -- to the in-scope set. This is useful for the case when the free variables -- aren't already in the in-scope set or easily available. -- See also Note [The substitution invariant]. substTyAddInScope :: TCvSubst -> Type -> Type substTyAddInScope subst ty = substTy (extendTCvInScopeSet subst $ tyCoVarsOfType ty) ty -- | When calling `substTy` it should be the case that the in-scope set in -- the substitution is a superset of the free vars of the range of the -- substitution. -- See also Note [The substitution invariant]. isValidTCvSubst :: TCvSubst -> Bool isValidTCvSubst (TCvSubst in_scope tenv cenv) = (tenvFVs `varSetInScope` in_scope) && (cenvFVs `varSetInScope` in_scope) where tenvFVs = tyCoVarsOfTypesSet tenv cenvFVs = tyCoVarsOfCosSet cenv -- | This checks if the substitution satisfies the invariant from -- Note [The substitution invariant]. checkValidSubst :: #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) (?callStack :: CallStack) => #endif TCvSubst -> [Type] -> [Coercion] -> a -> a checkValidSubst subst@(TCvSubst in_scope tenv cenv) tys cos a = ASSERT2( isValidTCvSubst subst, text "in_scope" <+> ppr in_scope $$ text "tenv" <+> ppr tenv $$ text "tenvFVs" <+> ppr (tyCoVarsOfTypesSet tenv) $$ text "cenv" <+> ppr cenv $$ text "cenvFVs" <+> ppr (tyCoVarsOfCosSet cenv) $$ text "tys" <+> ppr tys $$ text "cos" <+> ppr cos ) ASSERT2( tysCosFVsInScope, text "in_scope" <+> ppr in_scope $$ text "tenv" <+> ppr tenv $$ text "cenv" <+> ppr cenv $$ text "tys" <+> ppr tys $$ text "cos" <+> ppr cos $$ text "needInScope" <+> ppr needInScope ) a where substDomain = nonDetKeysUFM tenv ++ nonDetKeysUFM cenv -- It's OK to use nonDetKeysUFM here, because we only use this list to -- remove some elements from a set needInScope = (tyCoVarsOfTypes tys `unionVarSet` tyCoVarsOfCos cos) `delListFromUFM_Directly` substDomain tysCosFVsInScope = needInScope `varSetInScope` in_scope -- | Substitute within a 'Type' -- The substitution has to satisfy the invariants described in -- Note [The substitution invariant]. substTy :: -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) (?callStack :: CallStack) => #endif TCvSubst -> Type -> Type substTy subst ty | isEmptyTCvSubst subst = ty | otherwise = checkValidSubst subst [ty] [] $ subst_ty subst ty -- | Substitute within a 'Type' disabling the sanity checks. -- The problems that the sanity checks in substTy catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substTyUnchecked to -- substTy and remove this function. Please don't use in new code. substTyUnchecked :: TCvSubst -> Type -> Type substTyUnchecked subst ty | isEmptyTCvSubst subst = ty | otherwise = subst_ty subst ty -- | Substitute within several 'Type's -- The substitution has to satisfy the invariants described in -- Note [The substitution invariant]. substTys :: -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) (?callStack :: CallStack) => #endif TCvSubst -> [Type] -> [Type] substTys subst tys | isEmptyTCvSubst subst = tys | otherwise = checkValidSubst subst tys [] $ map (subst_ty subst) tys -- | Substitute within several 'Type's disabling the sanity checks. -- The problems that the sanity checks in substTys catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substTysUnchecked to -- substTys and remove this function. Please don't use in new code. substTysUnchecked :: TCvSubst -> [Type] -> [Type] substTysUnchecked subst tys | isEmptyTCvSubst subst = tys | otherwise = map (subst_ty subst) tys -- | Substitute within a 'ThetaType' -- The substitution has to satisfy the invariants described in -- Note [The substitution invariant]. substTheta :: -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) (?callStack :: CallStack) => #endif TCvSubst -> ThetaType -> ThetaType substTheta = substTys -- | Substitute within a 'ThetaType' disabling the sanity checks. -- The problems that the sanity checks in substTys catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substThetaUnchecked to -- substTheta and remove this function. Please don't use in new code. substThetaUnchecked :: TCvSubst -> ThetaType -> ThetaType substThetaUnchecked = substTysUnchecked subst_ty :: TCvSubst -> Type -> Type -- subst_ty is the main workhorse for type substitution -- -- Note that the in_scope set is poked only if we hit a forall -- so it may often never be fully computed subst_ty subst ty = go ty where go (TyVarTy tv) = substTyVar subst tv go (AppTy fun arg) = mkAppTy (go fun) $! (go arg) -- The mkAppTy smart constructor is important -- we might be replacing (a Int), represented with App -- by [Int], represented with TyConApp go (TyConApp tc tys) = let args = map go tys in args `seqList` TyConApp tc args go (FunTy arg res) = (FunTy $! go arg) $! go res go (ForAllTy (TvBndr tv vis) ty) = case substTyVarBndrUnchecked subst tv of (subst', tv') -> (ForAllTy $! ((TvBndr $! tv') vis)) $! (subst_ty subst' ty) go (LitTy n) = LitTy $! n go (CastTy ty co) = (CastTy $! (go ty)) $! (subst_co subst co) go (CoercionTy co) = CoercionTy $! (subst_co subst co) substTyVar :: TCvSubst -> TyVar -> Type substTyVar (TCvSubst _ tenv _) tv = ASSERT( isTyVar tv ) case lookupVarEnv tenv tv of Just ty -> ty Nothing -> TyVarTy tv substTyVars :: TCvSubst -> [TyVar] -> [Type] substTyVars subst = map $ substTyVar subst lookupTyVar :: TCvSubst -> TyVar -> Maybe Type -- See Note [Extending the TCvSubst] lookupTyVar (TCvSubst _ tenv _) tv = ASSERT( isTyVar tv ) lookupVarEnv tenv tv -- | Substitute within a 'Coercion' -- The substitution has to satisfy the invariants described in -- Note [The substitution invariant]. substCo :: -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) (?callStack :: CallStack) => #endif TCvSubst -> Coercion -> Coercion substCo subst co | isEmptyTCvSubst subst = co | otherwise = checkValidSubst subst [] [co] $ subst_co subst co -- | Substitute within a 'Coercion' disabling sanity checks. -- The problems that the sanity checks in substCo catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substCoUnchecked to -- substCo and remove this function. Please don't use in new code. substCoUnchecked :: TCvSubst -> Coercion -> Coercion substCoUnchecked subst co | isEmptyTCvSubst subst = co | otherwise = subst_co subst co -- | Substitute within several 'Coercion's -- The substitution has to satisfy the invariants described in -- Note [The substitution invariant]. substCos :: -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) (?callStack :: CallStack) => #endif TCvSubst -> [Coercion] -> [Coercion] substCos subst cos | isEmptyTCvSubst subst = cos | otherwise = checkValidSubst subst [] cos $ map (subst_co subst) cos subst_co :: TCvSubst -> Coercion -> Coercion subst_co subst co = go co where go_ty :: Type -> Type go_ty = subst_ty subst go :: Coercion -> Coercion go (Refl r ty) = mkReflCo r $! go_ty ty go (TyConAppCo r tc args)= let args' = map go args in args' `seqList` mkTyConAppCo r tc args' go (AppCo co arg) = (mkAppCo $! go co) $! go arg go (ForAllCo tv kind_co co) = case substForAllCoBndrUnchecked subst tv kind_co of { (subst', tv', kind_co') -> ((mkForAllCo $! tv') $! kind_co') $! subst_co subst' co } go (CoVarCo cv) = substCoVar subst cv go (AxiomInstCo con ind cos) = mkAxiomInstCo con ind $! map go cos go (UnivCo p r t1 t2) = (((mkUnivCo $! go_prov p) $! r) $! (go_ty t1)) $! (go_ty t2) go (SymCo co) = mkSymCo $! (go co) go (TransCo co1 co2) = (mkTransCo $! (go co1)) $! (go co2) go (NthCo d co) = mkNthCo d $! (go co) go (LRCo lr co) = mkLRCo lr $! (go co) go (InstCo co arg) = (mkInstCo $! (go co)) $! go arg go (CoherenceCo co1 co2) = (mkCoherenceCo $! (go co1)) $! (go co2) go (KindCo co) = mkKindCo $! (go co) go (SubCo co) = mkSubCo $! (go co) go (AxiomRuleCo c cs) = let cs1 = map go cs in cs1 `seqList` AxiomRuleCo c cs1 go_prov UnsafeCoerceProv = UnsafeCoerceProv go_prov (PhantomProv kco) = PhantomProv (go kco) go_prov (ProofIrrelProv kco) = ProofIrrelProv (go kco) go_prov p@(PluginProv _) = p go_prov p@(HoleProv _) = p -- NB: this last case is a little suspicious, but we need it. Originally, -- there was a panic here, but it triggered from deeplySkolemise. Because -- we only skolemise tyvars that are manually bound, this operation makes -- sense, even over a coercion with holes. substForAllCoBndr :: TCvSubst -> TyVar -> Coercion -> (TCvSubst, TyVar, Coercion) substForAllCoBndr subst = substForAllCoBndrCallback False (substCo subst) subst -- | Like 'substForAllCoBndr', but disables sanity checks. -- The problems that the sanity checks in substCo catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substCoUnchecked to -- substCo and remove this function. Please don't use in new code. substForAllCoBndrUnchecked :: TCvSubst -> TyVar -> Coercion -> (TCvSubst, TyVar, Coercion) substForAllCoBndrUnchecked subst = substForAllCoBndrCallback False (substCoUnchecked subst) subst -- See Note [Sym and ForAllCo] substForAllCoBndrCallback :: Bool -- apply sym to binder? -> (Coercion -> Coercion) -- transformation to kind co -> TCvSubst -> TyVar -> Coercion -> (TCvSubst, TyVar, Coercion) substForAllCoBndrCallback sym sco (TCvSubst in_scope tenv cenv) old_var old_kind_co = ( TCvSubst (in_scope `extendInScopeSet` new_var) new_env cenv , new_var, new_kind_co ) where new_env | no_change && not sym = delVarEnv tenv old_var | sym = extendVarEnv tenv old_var $ TyVarTy new_var `CastTy` new_kind_co | otherwise = extendVarEnv tenv old_var (TyVarTy new_var) no_kind_change = isEmptyVarSet (tyCoVarsOfCo old_kind_co) no_change = no_kind_change && (new_var == old_var) new_kind_co | no_kind_change = old_kind_co | otherwise = sco old_kind_co Pair new_ki1 _ = coercionKind new_kind_co new_var = uniqAway in_scope (setTyVarKind old_var new_ki1) substCoVar :: TCvSubst -> CoVar -> Coercion substCoVar (TCvSubst _ _ cenv) cv = case lookupVarEnv cenv cv of Just co -> co Nothing -> CoVarCo cv substCoVars :: TCvSubst -> [CoVar] -> [Coercion] substCoVars subst cvs = map (substCoVar subst) cvs lookupCoVar :: TCvSubst -> Var -> Maybe Coercion lookupCoVar (TCvSubst _ _ cenv) v = lookupVarEnv cenv v substTyVarBndr :: -- CallStack wasn't present in GHC 7.10.1, disable callstacks in stage 1 #if MIN_VERSION_GLASGOW_HASKELL(7,10,2,0) (?callStack :: CallStack) => #endif TCvSubst -> TyVar -> (TCvSubst, TyVar) substTyVarBndr = substTyVarBndrCallback substTy -- | Like 'substTyVarBndr' but disables sanity checks. -- The problems that the sanity checks in substTy catch are described in -- Note [The substitution invariant]. -- The goal of #11371 is to migrate all the calls of substTyUnchecked to -- substTy and remove this function. Please don't use in new code. substTyVarBndrUnchecked :: TCvSubst -> TyVar -> (TCvSubst, TyVar) substTyVarBndrUnchecked = substTyVarBndrCallback substTyUnchecked -- | Substitute a tyvar in a binding position, returning an -- extended subst and a new tyvar. substTyVarBndrCallback :: (TCvSubst -> Type -> Type) -- ^ the subst function -> TCvSubst -> TyVar -> (TCvSubst, TyVar) substTyVarBndrCallback subst_fn subst@(TCvSubst in_scope tenv cenv) old_var = ASSERT2( _no_capture, pprTvBndr old_var $$ pprTvBndr new_var $$ ppr subst ) ASSERT( isTyVar old_var ) (TCvSubst (in_scope `extendInScopeSet` new_var) new_env cenv, new_var) where new_env | no_change = delVarEnv tenv old_var | otherwise = extendVarEnv tenv old_var (TyVarTy new_var) _no_capture = not (new_var `elemVarSet` tyCoVarsOfTypesSet tenv) -- Assertion check that we are not capturing something in the substitution old_ki = tyVarKind old_var no_kind_change = isEmptyVarSet (tyCoVarsOfType old_ki) -- verify that kind is closed no_change = no_kind_change && (new_var == old_var) -- no_change means that the new_var is identical in -- all respects to the old_var (same unique, same kind) -- See Note [Extending the TCvSubst] -- -- In that case we don't need to extend the substitution -- to map old to new. But instead we must zap any -- current substitution for the variable. For example: -- (\x.e) with id_subst = [x |-> e'] -- Here we must simply zap the substitution for x new_var | no_kind_change = uniqAway in_scope old_var | otherwise = uniqAway in_scope $ setTyVarKind old_var (subst_fn subst old_ki) -- The uniqAway part makes sure the new variable is not already in scope substCoVarBndr :: TCvSubst -> CoVar -> (TCvSubst, CoVar) substCoVarBndr = substCoVarBndrCallback False substTy substCoVarBndrCallback :: Bool -- apply "sym" to the covar? -> (TCvSubst -> Type -> Type) -> TCvSubst -> CoVar -> (TCvSubst, CoVar) substCoVarBndrCallback sym subst_fun subst@(TCvSubst in_scope tenv cenv) old_var = ASSERT( isCoVar old_var ) (TCvSubst (in_scope `extendInScopeSet` new_var) tenv new_cenv, new_var) where -- When we substitute (co :: t1 ~ t2) we may get the identity (co :: t ~ t) -- In that case, mkCoVarCo will return a ReflCoercion, and -- we want to substitute that (not new_var) for old_var new_co = (if sym then mkSymCo else id) $ mkCoVarCo new_var no_kind_change = isEmptyVarSet (tyCoVarsOfTypes [t1, t2]) no_change = new_var == old_var && not (isReflCo new_co) && no_kind_change new_cenv | no_change = delVarEnv cenv old_var | otherwise = extendVarEnv cenv old_var new_co new_var = uniqAway in_scope subst_old_var subst_old_var = mkCoVar (varName old_var) new_var_type (_, _, t1, t2, role) = coVarKindsTypesRole old_var t1' = subst_fun subst t1 t2' = subst_fun subst t2 new_var_type = uncurry (mkCoercionType role) (if sym then (t2', t1') else (t1', t2')) -- It's important to do the substitution for coercions, -- because they can have free type variables cloneTyVarBndr :: TCvSubst -> TyVar -> Unique -> (TCvSubst, TyVar) cloneTyVarBndr subst@(TCvSubst in_scope tv_env cv_env) tv uniq = ASSERT2( isTyVar tv, ppr tv ) -- I think it's only called on TyVars (TCvSubst (extendInScopeSet in_scope tv') (extendVarEnv tv_env tv (mkTyVarTy tv')) cv_env, tv') where old_ki = tyVarKind tv no_kind_change = isEmptyVarSet (tyCoVarsOfType old_ki) -- verify that kind is closed tv1 | no_kind_change = tv | otherwise = setTyVarKind tv (substTy subst old_ki) tv' = setVarUnique tv1 uniq cloneTyVarBndrs :: TCvSubst -> [TyVar] -> UniqSupply -> (TCvSubst, [TyVar]) cloneTyVarBndrs subst [] _usupply = (subst, []) cloneTyVarBndrs subst (t:ts) usupply = (subst'', tv:tvs) where (uniq, usupply') = takeUniqFromSupply usupply (subst' , tv ) = cloneTyVarBndr subst t uniq (subst'', tvs) = cloneTyVarBndrs subst' ts usupply' {- %************************************************************************ %* * Pretty-printing types Defined very early because of debug printing in assertions %* * %************************************************************************ @pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is defined to use this. @pprParendType@ is the same, except it puts parens around the type, except for the atomic cases. @pprParendType@ works just by setting the initial context precedence very high. Note [Precedence in types] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't keep the fixity of type operators in the operator. So the pretty printer operates the following precedene structre: Type constructor application binds more tightly than Operator applications which bind more tightly than Function arrow So we might see a :+: T b -> c meaning (a :+: (T b)) -> c Maybe operator applications should bind a bit less tightly? Anyway, that's the current story, and it is used consistently for Type and HsType -} data TyPrec -- See Note [Prededence in types] = TopPrec -- No parens | FunPrec -- Function args; no parens for tycon apps | TyOpPrec -- Infix operator | TyConPrec -- Tycon args; no parens for atomic deriving( Eq, Ord ) maybeParen :: TyPrec -> TyPrec -> SDoc -> SDoc maybeParen ctxt_prec inner_prec pretty | ctxt_prec < inner_prec = pretty | otherwise = parens pretty ------------------ {- Note [Defaulting RuntimeRep variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RuntimeRep variables are considered by many (most?) users to be little more than syntactic noise. When the notion was introduced there was a signficant and understandable push-back from those with pedagogy in mind, which argued that RuntimeRep variables would throw a wrench into nearly any teach approach since they appear in even the lowly ($) function's type, ($) :: forall (w :: RuntimeRep) a (b :: TYPE w). (a -> b) -> a -> b which is significantly less readable than its non RuntimeRep-polymorphic type of ($) :: (a -> b) -> a -> b Moreover, unboxed types don't appear all that often in run-of-the-mill Haskell programs, so it makes little sense to make all users pay this syntactic overhead. For this reason it was decided that we would hide RuntimeRep variables for now (see #11549). We do this by defaulting all type variables of kind RuntimeRep to PtrLiftedRep. This is done in a pass right before pretty-printing (defaultRuntimeRepVars, controlled by -fprint-explicit-runtime-reps) -} -- | Default 'RuntimeRep' variables to 'LiftedPtr'. e.g. -- -- @ -- ($) :: forall (r :: GHC.Types.RuntimeRep) a (b :: TYPE r). -- (a -> b) -> a -> b -- @ -- -- turns in to, -- -- @ ($) :: forall a (b :: *). (a -> b) -> a -> b @ -- -- We do this to prevent RuntimeRep variables from incurring a significant -- syntactic overhead in otherwise simple type signatures (e.g. ($)). See -- Note [Defaulting RuntimeRep variables] and #11549 for further discussion. -- defaultRuntimeRepVars :: Type -> Type defaultRuntimeRepVars = defaultRuntimeRepVars' emptyVarSet defaultRuntimeRepVars' :: TyVarSet -- ^ the binders which we should default -> Type -> Type -- TODO: Eventually we should just eliminate the Type pretty-printer -- entirely and simply use IfaceType; this task is tracked as #11660. defaultRuntimeRepVars' subs (ForAllTy (TvBndr var vis) ty) | isRuntimeRepVar var = let subs' = extendVarSet subs var in defaultRuntimeRepVars' subs' ty | otherwise = let var' = var { varType = defaultRuntimeRepVars' subs (varType var) } in ForAllTy (TvBndr var' vis) (defaultRuntimeRepVars' subs ty) defaultRuntimeRepVars' subs (FunTy kind ty) = FunTy (defaultRuntimeRepVars' subs kind) (defaultRuntimeRepVars' subs ty) defaultRuntimeRepVars' subs (TyVarTy var) | var `elemVarSet` subs = ptrRepLiftedTy defaultRuntimeRepVars' subs (TyConApp tc args) = TyConApp tc $ map (defaultRuntimeRepVars' subs) args defaultRuntimeRepVars' subs (AppTy x y) = defaultRuntimeRepVars' subs x `AppTy` defaultRuntimeRepVars' subs y defaultRuntimeRepVars' subs (CastTy ty co) = CastTy (defaultRuntimeRepVars' subs ty) co defaultRuntimeRepVars' _ other = other eliminateRuntimeRep :: (Type -> SDoc) -> Type -> SDoc eliminateRuntimeRep f ty = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitRuntimeReps dflags then f ty else f (defaultRuntimeRepVars ty) pprType, pprParendType :: Type -> SDoc pprType ty = eliminateRuntimeRep (ppr_type TopPrec) ty pprParendType ty = eliminateRuntimeRep (ppr_type TyConPrec) ty pprTyLit :: TyLit -> SDoc pprTyLit = ppr_tylit TopPrec pprKind, pprParendKind :: Kind -> SDoc pprKind = pprType pprParendKind = pprParendType ------------ pprClassPred :: Class -> [Type] -> SDoc pprClassPred clas tys = pprTypeApp (classTyCon clas) tys ------------ pprTheta :: ThetaType -> SDoc pprTheta [pred] = ppr_type TopPrec pred -- I'm in two minds about this pprTheta theta = parens (sep (punctuate comma (map (ppr_type TopPrec) theta))) pprThetaArrowTy :: ThetaType -> SDoc pprThetaArrowTy [] = empty pprThetaArrowTy [pred] = ppr_type TyOpPrec pred <+> darrow -- TyOpPrec: Num a => a -> a does not need parens -- bug (a :~: b) => a -> b currently does -- Trac # 9658 pprThetaArrowTy preds = parens (fsep (punctuate comma (map (ppr_type TopPrec) preds))) <+> darrow -- Notice 'fsep' here rather that 'sep', so that -- type contexts don't get displayed in a giant column -- Rather than -- instance (Eq a, -- Eq b, -- Eq c, -- Eq d, -- Eq e, -- Eq f, -- Eq g, -- Eq h, -- Eq i, -- Eq j, -- Eq k, -- Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) -- we get -- -- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, -- Eq j, Eq k, Eq l) => -- Eq (a, b, c, d, e, f, g, h, i, j, k, l) ------------------ instance Outputable Type where ppr ty = pprType ty instance Outputable TyLit where ppr = pprTyLit ------------------ -- OK, here's the main printer ppr_type :: TyPrec -> Type -> SDoc ppr_type _ (TyVarTy tv) = ppr_tvar tv ppr_type p (TyConApp tc tys) = pprTyTcApp p tc tys ppr_type p (LitTy l) = ppr_tylit p l ppr_type p ty@(ForAllTy {}) = ppr_forall_type p ty ppr_type p ty@(FunTy {}) = ppr_forall_type p ty ppr_type p (AppTy t1 t2) = if_print_coercions ppr_app_ty (case split_app_tys t1 [t2] of (CastTy head _, args) -> ppr_type p (mk_app_tys head args) _ -> ppr_app_ty) where ppr_app_ty = maybeParen p TyConPrec $ ppr_type FunPrec t1 <+> ppr_type TyConPrec t2 split_app_tys (AppTy ty1 ty2) args = split_app_tys ty1 (ty2:args) split_app_tys head args = (head, args) mk_app_tys (TyConApp tc tys1) tys2 = TyConApp tc (tys1 ++ tys2) mk_app_tys ty1 tys2 = foldl AppTy ty1 tys2 ppr_type p (CastTy ty co) = if_print_coercions (parens (ppr_type TopPrec ty <+> text "|>" <+> ppr co)) (ppr_type p ty) ppr_type _ (CoercionTy co) = if_print_coercions (parens (ppr co)) (text "<>") ppr_forall_type :: TyPrec -> Type -> SDoc -- Used for types starting with ForAllTy or FunTy ppr_forall_type p ty = maybeParen p FunPrec $ sdocWithDynFlags $ \dflags -> ppr_sigma_type dflags True ty -- True <=> we always print the foralls on *nested* quantifiers -- Opt_PrintExplicitForalls only affects top-level quantifiers ppr_tvar :: TyVar -> SDoc ppr_tvar tv -- Note [Infix type variables] = parenSymOcc (getOccName tv) (ppr tv) ppr_tylit :: TyPrec -> TyLit -> SDoc ppr_tylit _ tl = case tl of NumTyLit n -> integer n StrTyLit s -> text (show s) if_print_coercions :: SDoc -- if printing coercions -> SDoc -- otherwise -> SDoc if_print_coercions yes no = sdocWithDynFlags $ \dflags -> getPprStyle $ \style -> if gopt Opt_PrintExplicitCoercions dflags || dumpStyle style || debugStyle style then yes else no ------------------- ppr_sigma_type :: DynFlags -> Bool -- ^ True <=> Show the foralls unconditionally -> Type -> SDoc -- Used for types starting with ForAllTy or FunTy -- Suppose we have (forall a. Show a => forall b. a -> b). When we're not -- printing foralls, we want to drop both the (forall a) and the (forall b). -- This logic does so. ppr_sigma_type dflags False orig_ty | not (gopt Opt_PrintExplicitForalls dflags) , all (isEmptyVarSet . tyCoVarsOfType . tyVarKind) tv_bndrs -- See Note [When to print foralls] = sep [ pprThetaArrowTy theta , pprArrowChain TopPrec (ppr_fun_tail tau) ] where (tv_bndrs, theta, tau) = split [] [] orig_ty split :: [TyVar] -> [PredType] -> Type -> ([TyVar], [PredType], Type) split bndr_acc theta_acc (ForAllTy (TvBndr tv vis) ty) | isInvisibleArgFlag vis = split (tv : bndr_acc) theta_acc ty split bndr_acc theta_acc (FunTy ty1 ty2) | isPredTy ty1 = split bndr_acc (ty1 : theta_acc) ty2 split bndr_acc theta_acc ty = (reverse bndr_acc, reverse theta_acc, ty) ppr_sigma_type _ _ ty = sep [ pprForAll bndrs , pprThetaArrowTy ctxt , pprArrowChain TopPrec (ppr_fun_tail tau) ] where (bndrs, rho) = split1 [] ty (ctxt, tau) = split2 [] rho split1 bndrs (ForAllTy bndr ty) = split1 (bndr:bndrs) ty split1 bndrs ty = (reverse bndrs, ty) split2 ps (FunTy ty1 ty2) | isPredTy ty1 = split2 (ty1:ps) ty2 split2 ps ty = (reverse ps, ty) -- We don't want to lose synonyms, so we mustn't use splitFunTys here. ppr_fun_tail :: Type -> [SDoc] ppr_fun_tail (FunTy ty1 ty2) | not (isPredTy ty1) = ppr_type FunPrec ty1 : ppr_fun_tail ty2 ppr_fun_tail other_ty = [ppr_type TopPrec other_ty] pprSigmaType :: Type -> SDoc pprSigmaType ty = sdocWithDynFlags $ \dflags -> eliminateRuntimeRep (ppr_sigma_type dflags False) ty pprUserForAll :: [TyVarBinder] -> SDoc -- Print a user-level forall; see Note [When to print foralls] pprUserForAll bndrs = sdocWithDynFlags $ \dflags -> ppWhen (any bndr_has_kind_var bndrs || gopt Opt_PrintExplicitForalls dflags) $ pprForAll bndrs where bndr_has_kind_var bndr = not (isEmptyVarSet (tyCoVarsOfType (binderKind bndr))) pprForAllImplicit :: [TyVar] -> SDoc pprForAllImplicit tvs = pprForAll [ TvBndr tv Specified | tv <- tvs ] -- | Render the "forall ... ." or "forall ... ->" bit of a type. -- Do not pass in anonymous binders! pprForAll :: [TyVarBinder] -> SDoc pprForAll [] = empty pprForAll bndrs@(TvBndr _ vis : _) = add_separator (forAllLit <+> doc) <+> pprForAll bndrs' where (bndrs', doc) = ppr_tv_bndrs bndrs vis add_separator stuff = case vis of Required -> stuff <+> arrow _inv -> stuff <> dot pprTvBndrs :: [TyVar] -> SDoc pprTvBndrs tvs = sep (map pprTvBndr tvs) -- | Render the ... in @(forall ... .)@ or @(forall ... ->)@. -- Returns both the list of not-yet-rendered binders and the doc. ppr_tv_bndrs :: [TyVarBinder] -> ArgFlag -- ^ visibility of the first binder in the list -> ([TyVarBinder], SDoc) ppr_tv_bndrs all_bndrs@(TvBndr tv vis : bndrs) vis1 | vis `sameVis` vis1 = let (bndrs', doc) = ppr_tv_bndrs bndrs vis1 pp_tv = sdocWithDynFlags $ \dflags -> if Inferred == vis && gopt Opt_PrintExplicitForalls dflags then braces (pprTvBndrNoParens tv) else pprTvBndr tv in (bndrs', pp_tv <+> doc) | otherwise = (all_bndrs, empty) ppr_tv_bndrs [] _ = ([], empty) pprTvBndr :: TyVar -> SDoc pprTvBndr tv | isLiftedTypeKind kind = ppr_tvar tv | otherwise = parens (ppr_tvar tv <+> dcolon <+> pprKind kind) where kind = tyVarKind tv pprTvBndrNoParens :: TyVar -> SDoc pprTvBndrNoParens tv | isLiftedTypeKind kind = ppr_tvar tv | otherwise = ppr_tvar tv <+> dcolon <+> pprKind kind where kind = tyVarKind tv instance Outputable TyBinder where ppr (Anon ty) = text "[anon]" <+> ppr ty ppr (Named (TvBndr v Required)) = ppr v ppr (Named (TvBndr v Specified)) = char '@' <> ppr v ppr (Named (TvBndr v Inferred)) = braces (ppr v) ----------------- instance Outputable Coercion where -- defined here to avoid orphans ppr = pprCo instance Outputable LeftOrRight where ppr CLeft = text "Left" ppr CRight = text "Right" {- Note [When to print foralls] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mostly we want to print top-level foralls when (and only when) the user specifies -fprint-explicit-foralls. But when kind polymorphism is at work, that suppresses too much information; see Trac #9018. So I'm trying out this rule: print explicit foralls if a) User specifies -fprint-explicit-foralls, or b) Any of the quantified type variables has a kind that mentions a kind variable This catches common situations, such as a type siguature f :: m a which means f :: forall k. forall (m :: k->*) (a :: k). m a We really want to see both the "forall k" and the kind signatures on m and a. The latter comes from pprTvBndr. Note [Infix type variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ With TypeOperators you can say f :: (a ~> b) -> b and the (~>) is considered a type variable. However, the type pretty-printer in this module will just see (a ~> b) as App (App (TyVarTy "~>") (TyVarTy "a")) (TyVarTy "b") So it'll print the type in prefix form. To avoid confusion we must remember to parenthesise the operator, thus (~>) a b -> b See Trac #2766. -} pprDataCons :: TyCon -> SDoc pprDataCons = sepWithVBars . fmap pprDataConWithArgs . tyConDataCons where sepWithVBars [] = empty sepWithVBars docs = sep (punctuate (space <> vbar) docs) pprDataConWithArgs :: DataCon -> SDoc pprDataConWithArgs dc = sep [forAllDoc, thetaDoc, ppr dc <+> argsDoc] where (_univ_tvs, _ex_tvs, eq_spec, theta, arg_tys, _res_ty) = dataConFullSig dc univ_bndrs = dataConUnivTyVarBinders dc ex_bndrs = dataConExTyVarBinders dc forAllDoc = pprUserForAll $ (filterEqSpec eq_spec univ_bndrs ++ ex_bndrs) thetaDoc = pprThetaArrowTy theta argsDoc = hsep (fmap pprParendType arg_tys) pprTypeApp :: TyCon -> [Type] -> SDoc pprTypeApp tc tys = pprTyTcApp TopPrec tc tys -- We have to use ppr on the TyCon (not its name) -- so that we get promotion quotes in the right place pprTyTcApp :: TyPrec -> TyCon -> [Type] -> SDoc -- Used for types only; so that we can make a -- special case for type-level lists pprTyTcApp p tc tys | tc `hasKey` ipClassKey , [LitTy (StrTyLit n),ty] <- tys = maybeParen p FunPrec $ char '?' <> ftext n <> text "::" <> ppr_type TopPrec ty | tc `hasKey` consDataConKey , [_kind,ty1,ty2] <- tys = sdocWithDynFlags $ \dflags -> if gopt Opt_PrintExplicitKinds dflags then ppr_deflt else pprTyList p ty1 ty2 | not opt_PprStyle_Debug , tc `hasKey` errorMessageTypeErrorFamKey = text "(TypeError ...)" -- Suppress detail unles you _really_ want to see | tc `hasKey` tYPETyConKey , [TyConApp ptr_rep []] <- tys , ptr_rep `hasKey` ptrRepLiftedDataConKey = unicodeSyntax (char '★') (char '*') | tc `hasKey` tYPETyConKey , [TyConApp ptr_rep []] <- tys , ptr_rep `hasKey` ptrRepUnliftedDataConKey = char '#' | otherwise = ppr_deflt where ppr_deflt = pprTcAppTy p ppr_type tc tys pprTcAppTy :: TyPrec -> (TyPrec -> Type -> SDoc) -> TyCon -> [Type] -> SDoc pprTcAppTy p pp tc tys = getPprStyle $ \style -> pprTcApp style id p pp tc tys pprTcAppCo :: TyPrec -> (TyPrec -> Coercion -> SDoc) -> TyCon -> [Coercion] -> SDoc pprTcAppCo p pp tc cos = getPprStyle $ \style -> pprTcApp style (pFst . coercionKind) p pp tc cos pprTcApp :: PprStyle -> (a -> Type) -> TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> SDoc -- Used for both types and coercions, hence polymorphism pprTcApp _ _ _ pp tc [ty] | tc `hasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp TopPrec ty) | tc `hasKey` parrTyConKey = pprPromotionQuote tc <> paBrackets (pp TopPrec ty) pprTcApp style to_type p pp tc tys | not (debugStyle style) , Just sort <- tyConTuple_maybe tc , let arity = tyConArity tc , arity == length tys , let num_to_drop = case sort of UnboxedTuple -> arity `div` 2 _ -> 0 = pprTupleApp p pp tc sort (drop num_to_drop tys) | not (debugStyle style) , Just dc <- isPromotedDataCon_maybe tc , let dc_tc = dataConTyCon dc , Just tup_sort <- tyConTuple_maybe dc_tc , let arity = tyConArity dc_tc -- E.g. 3 for (,,) k1 k2 k3 t1 t2 t3 ty_args = drop arity tys -- Drop the kind args , ty_args `lengthIs` arity -- Result is saturated = pprPromotionQuote tc <> (tupleParens tup_sort $ pprWithCommas (pp TopPrec) ty_args) | otherwise = sdocWithDynFlags $ \dflags -> pprTcApp_help to_type p pp tc tys dflags style where pprTupleApp :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> TupleSort -> [a] -> SDoc -- Print a saturated tuple pprTupleApp p pp tc sort tys | null tys , ConstraintTuple <- sort = if opt_PprStyle_Debug then text "(%%)" else maybeParen p FunPrec $ text "() :: Constraint" | otherwise = pprPromotionQuote tc <> tupleParens sort (pprWithCommas (pp TopPrec) tys) pprTcApp_help :: (a -> Type) -> TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> DynFlags -> PprStyle -> SDoc -- This one has accss to the DynFlags pprTcApp_help to_type p pp tc tys dflags style | not (isSymOcc (nameOccName tc_name)) -- Print prefix = pprPrefixApp p pp_tc (map (pp TyConPrec) tys_wo_kinds) | Just args <- mb_saturated_equality = print_equality args -- So we have an operator symbol of some kind | [ty1,ty2] <- tys_wo_kinds -- Infix, two arguments; -- we know nothing of precedence though = pprInfixApp p pp pp_tc ty1 ty2 | tc_name `hasKey` starKindTyConKey || tc_name `hasKey` unicodeStarKindTyConKey || tc_name `hasKey` unliftedTypeKindTyConKey = pp_tc -- Do not wrap *, # in parens | otherwise -- Unsaturated operator = pprPrefixApp p (parens (pp_tc)) (map (pp TyConPrec) tys_wo_kinds) where tc_name = tyConName tc pp_tc = ppr tc tys_wo_kinds = suppressInvisibles to_type dflags tc tys mb_saturated_equality | hetero_eq_tc , [k1, k2, t1, t2] <- tys = Just (k1, k2, t1, t2) | homo_eq_tc , [k, t1, t2] <- tys -- we must have (~) = Just (k, k, t1, t2) | otherwise = Nothing homo_eq_tc = tc `hasKey` eqTyConKey -- ~ hetero_eq_tc = tc `hasKey` eqPrimTyConKey -- ~# || tc `hasKey` eqReprPrimTyConKey -- ~R# || tc `hasKey` heqTyConKey -- ~~ -- This is all a bit ad-hoc, trying to print out the best representation -- of equalities. If you see a better design, go for it. print_equality (ki1, ki2, ty1, ty2) | print_eqs = ppr_infix_eq pp_tc | hetero_eq_tc , print_kinds || not (to_type ki1 `eqType` to_type ki2) = ppr_infix_eq $ if tc `hasKey` eqPrimTyConKey then text "~~" else pp_tc | otherwise = if tc `hasKey` eqReprPrimTyConKey then text "Coercible" <+> (sep [ pp TyConPrec ty1 , pp TyConPrec ty2 ]) else sep [pp TyOpPrec ty1, text "~", pp TyOpPrec ty2] where ppr_infix_eq eq_op = sep [ parens (pp TyOpPrec ty1 <+> dcolon <+> pp TyOpPrec ki1) , eq_op , parens (pp TyOpPrec ty2 <+> dcolon <+> pp TyOpPrec ki2)] print_kinds = gopt Opt_PrintExplicitKinds dflags print_eqs = gopt Opt_PrintEqualityRelations dflags || dumpStyle style || debugStyle style ------------------ -- | Given a 'TyCon',and the args to which it is applied, -- suppress the args that are implicit suppressInvisibles :: (a -> Type) -> DynFlags -> TyCon -> [a] -> [a] suppressInvisibles to_type dflags tc xs | gopt Opt_PrintExplicitKinds dflags = xs | otherwise = snd $ partitionInvisibles tc to_type xs ---------------- pprTyList :: TyPrec -> Type -> Type -> SDoc -- Given a type-level list (t1 ': t2), see if we can print -- it in list notation [t1, ...]. pprTyList p ty1 ty2 = case gather ty2 of (arg_tys, Nothing) -> char '\'' <> brackets (fsep (punctuate comma (map (ppr_type TopPrec) (ty1:arg_tys)))) (arg_tys, Just tl) -> maybeParen p FunPrec $ hang (ppr_type FunPrec ty1) 2 (fsep [ colon <+> ppr_type FunPrec ty | ty <- arg_tys ++ [tl]]) where gather :: Type -> ([Type], Maybe Type) -- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn] -- = (tys, Just tl) means ty is of form t1:t2:...tn:tl gather (TyConApp tc tys) | tc `hasKey` consDataConKey , [_kind, ty1,ty2] <- tys , (args, tl) <- gather ty2 = (ty1:args, tl) | tc `hasKey` nilDataConKey = ([], Nothing) gather ty = ([], Just ty) ---------------- pprInfixApp :: TyPrec -> (TyPrec -> a -> SDoc) -> SDoc -> a -> a -> SDoc pprInfixApp p pp pp_tc ty1 ty2 = maybeParen p TyOpPrec $ sep [pp TyOpPrec ty1, pprInfixVar True pp_tc <+> pp TyOpPrec ty2] pprPrefixApp :: TyPrec -> SDoc -> [SDoc] -> SDoc pprPrefixApp p pp_fun pp_tys | null pp_tys = pp_fun | otherwise = maybeParen p TyConPrec $ hang pp_fun 2 (sep pp_tys) ---------------- pprArrowChain :: TyPrec -> [SDoc] -> SDoc -- pprArrowChain p [a,b,c] generates a -> b -> c pprArrowChain _ [] = empty pprArrowChain p (arg:args) = maybeParen p FunPrec $ sep [arg, sep (map (arrow <+>) args)] ppSuggestExplicitKinds :: SDoc -- Print a helpful suggstion about -fprint-explicit-kinds, -- if it is not already on ppSuggestExplicitKinds = sdocWithDynFlags $ \ dflags -> ppUnless (gopt Opt_PrintExplicitKinds dflags) $ text "Use -fprint-explicit-kinds to see the kind arguments" {- %************************************************************************ %* * \subsection{TidyType} %* * %************************************************************************ -} -- | This tidies up a type for printing in an error message, or in -- an interface file. -- -- It doesn't change the uniques at all, just the print names. tidyTyCoVarBndrs :: TidyEnv -> [TyCoVar] -> (TidyEnv, [TyCoVar]) tidyTyCoVarBndrs (occ_env, subst) tvs = mapAccumL tidyTyCoVarBndr tidy_env' tvs where -- Seed the occ_env with clashes among the names, see -- Node [Tidying multiple names at once] in OccName -- Se still go through tidyTyCoVarBndr so that each kind variable is tidied -- with the correct tidy_env occs = map getHelpfulOccName tvs tidy_env' = (avoidClashesOccEnv occ_env occs, subst) tidyTyCoVarBndr :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar) tidyTyCoVarBndr tidy_env@(occ_env, subst) tyvar = case tidyOccName occ_env (getHelpfulOccName tyvar) of (occ_env', occ') -> ((occ_env', subst'), tyvar') where subst' = extendVarEnv subst tyvar tyvar' tyvar' = setTyVarKind (setTyVarName tyvar name') kind' kind' = tidyKind tidy_env (tyVarKind tyvar) name' = tidyNameOcc name occ' name = tyVarName tyvar getHelpfulOccName :: TyCoVar -> OccName getHelpfulOccName tyvar = occ1 where name = tyVarName tyvar occ = getOccName name -- System Names are for unification variables; -- when we tidy them we give them a trailing "0" (or 1 etc) -- so that they don't take precedence for the un-modified name -- Plus, indicating a unification variable in this way is a -- helpful clue for users occ1 | isSystemName name = if isTyVar tyvar then mkTyVarOcc (occNameString occ ++ "0") else mkVarOcc (occNameString occ ++ "0") | otherwise = occ tidyTyVarBinder :: TidyEnv -> TyVarBndr TyVar vis -> (TidyEnv, TyVarBndr TyVar vis) tidyTyVarBinder tidy_env (TvBndr tv vis) = (tidy_env', TvBndr tv' vis) where (tidy_env', tv') = tidyTyCoVarBndr tidy_env tv tidyTyVarBinders :: TidyEnv -> [TyVarBndr TyVar vis] -> (TidyEnv, [TyVarBndr TyVar vis]) tidyTyVarBinders = mapAccumL tidyTyVarBinder --------------- tidyFreeTyCoVars :: TidyEnv -> [TyCoVar] -> TidyEnv -- ^ Add the free 'TyVar's to the env in tidy form, -- so that we can tidy the type they are free in tidyFreeTyCoVars (full_occ_env, var_env) tyvars = fst (tidyOpenTyCoVars (full_occ_env, var_env) tyvars) --------------- tidyOpenTyCoVars :: TidyEnv -> [TyCoVar] -> (TidyEnv, [TyCoVar]) tidyOpenTyCoVars env tyvars = mapAccumL tidyOpenTyCoVar env tyvars --------------- tidyOpenTyCoVar :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar) -- ^ Treat a new 'TyCoVar' as a binder, and give it a fresh tidy name -- using the environment if one has not already been allocated. See -- also 'tidyTyCoVarBndr' tidyOpenTyCoVar env@(_, subst) tyvar = case lookupVarEnv subst tyvar of Just tyvar' -> (env, tyvar') -- Already substituted Nothing -> let env' = tidyFreeTyCoVars env (tyCoVarsOfTypeList (tyVarKind tyvar)) in tidyTyCoVarBndr env' tyvar -- Treat it as a binder --------------- tidyTyVarOcc :: TidyEnv -> TyVar -> TyVar tidyTyVarOcc env@(_, subst) tv = case lookupVarEnv subst tv of Nothing -> updateTyVarKind (tidyType env) tv Just tv' -> tv' --------------- tidyTypes :: TidyEnv -> [Type] -> [Type] tidyTypes env tys = map (tidyType env) tys --------------- tidyType :: TidyEnv -> Type -> Type tidyType _ (LitTy n) = LitTy n tidyType env (TyVarTy tv) = TyVarTy (tidyTyVarOcc env tv) tidyType env (TyConApp tycon tys) = let args = tidyTypes env tys in args `seqList` TyConApp tycon args tidyType env (AppTy fun arg) = (AppTy $! (tidyType env fun)) $! (tidyType env arg) tidyType env (FunTy fun arg) = (FunTy $! (tidyType env fun)) $! (tidyType env arg) tidyType env (ty@(ForAllTy{})) = mkForAllTys' (zip tvs' vis) $! tidyType env' body_ty where (tvs, vis, body_ty) = splitForAllTys' ty (env', tvs') = tidyTyCoVarBndrs env tvs tidyType env (CastTy ty co) = (CastTy $! tidyType env ty) $! (tidyCo env co) tidyType env (CoercionTy co) = CoercionTy $! (tidyCo env co) -- The following two functions differ from mkForAllTys and splitForAllTys in that -- they expect/preserve the ArgFlag argument. Thes belong to types/Type.hs, but -- how should they be named? mkForAllTys' :: [(TyVar, ArgFlag)] -> Type -> Type mkForAllTys' tvvs ty = foldr strictMkForAllTy ty tvvs where strictMkForAllTy (tv,vis) ty = (ForAllTy $! ((TvBndr $! tv) $! vis)) $! ty splitForAllTys' :: Type -> ([TyVar], [ArgFlag], Type) splitForAllTys' ty = go ty [] [] where go (ForAllTy (TvBndr tv vis) ty) tvs viss = go ty (tv:tvs) (vis:viss) go ty tvs viss = (reverse tvs, reverse viss, ty) --------------- -- | Grabs the free type variables, tidies them -- and then uses 'tidyType' to work over the type itself tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type]) tidyOpenTypes env tys = (env', tidyTypes (trimmed_occ_env, var_env) tys) where (env'@(_, var_env), tvs') = tidyOpenTyCoVars env $ tyCoVarsOfTypesWellScoped tys trimmed_occ_env = initTidyOccEnv (map getOccName tvs') -- The idea here was that we restrict the new TidyEnv to the -- _free_ vars of the types, so that we don't gratuitously rename -- the _bound_ variables of the types. --------------- tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type) tidyOpenType env ty = let (env', [ty']) = tidyOpenTypes env [ty] in (env', ty') --------------- -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment) tidyTopType :: Type -> Type tidyTopType ty = tidyType emptyTidyEnv ty --------------- tidyOpenKind :: TidyEnv -> Kind -> (TidyEnv, Kind) tidyOpenKind = tidyOpenType tidyKind :: TidyEnv -> Kind -> Kind tidyKind = tidyType ---------------- tidyCo :: TidyEnv -> Coercion -> Coercion tidyCo env@(_, subst) co = go co where go (Refl r ty) = Refl r (tidyType env ty) go (TyConAppCo r tc cos) = let args = map go cos in args `seqList` TyConAppCo r tc args go (AppCo co1 co2) = (AppCo $! go co1) $! go co2 go (ForAllCo tv h co) = ((ForAllCo $! tvp) $! (go h)) $! (tidyCo envp co) where (envp, tvp) = tidyTyCoVarBndr env tv -- the case above duplicates a bit of work in tidying h and the kind -- of tv. But the alternative is to use coercionKind, which seems worse. go (CoVarCo cv) = case lookupVarEnv subst cv of Nothing -> CoVarCo cv Just cv' -> CoVarCo cv' go (AxiomInstCo con ind cos) = let args = map go cos in args `seqList` AxiomInstCo con ind args go (UnivCo p r t1 t2) = (((UnivCo $! (go_prov p)) $! r) $! tidyType env t1) $! tidyType env t2 go (SymCo co) = SymCo $! go co go (TransCo co1 co2) = (TransCo $! go co1) $! go co2 go (NthCo d co) = NthCo d $! go co go (LRCo lr co) = LRCo lr $! go co go (InstCo co ty) = (InstCo $! go co) $! go ty go (CoherenceCo co1 co2) = (CoherenceCo $! go co1) $! go co2 go (KindCo co) = KindCo $! go co go (SubCo co) = SubCo $! go co go (AxiomRuleCo ax cos) = let cos1 = tidyCos env cos in cos1 `seqList` AxiomRuleCo ax cos1 go_prov UnsafeCoerceProv = UnsafeCoerceProv go_prov (PhantomProv co) = PhantomProv (go co) go_prov (ProofIrrelProv co) = ProofIrrelProv (go co) go_prov p@(PluginProv _) = p go_prov p@(HoleProv _) = p tidyCos :: TidyEnv -> [Coercion] -> [Coercion] tidyCos env = map (tidyCo env)
vTurbine/ghc
compiler/types/TyCoRep.hs
bsd-3-clause
128,802
20
20
31,433
19,652
10,432
9,220
-1
-1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor, TypeSynonymInstances, PatternGuards, CPP #-} module Idris.AbsSyntaxTree where import Core.TT import Core.Evaluate import Core.Elaborate hiding (Tactic(..)) import Core.Typecheck import IRTS.Lang import IRTS.CodegenCommon import Util.Pretty import Util.DynamicLinker import Paths_idris import System.Console.Haskeline import Control.Monad.Trans.State.Strict import Data.List import Data.Char import Data.Either import Debug.Trace data IOption = IOption { opt_logLevel :: Int, opt_typecase :: Bool, opt_typeintype :: Bool, opt_coverage :: Bool, opt_showimp :: Bool, opt_errContext :: Bool, opt_repl :: Bool, opt_verbose :: Bool, opt_quiet :: Bool, opt_codegen :: Codegen, opt_outputTy :: OutputType, opt_ibcsubdir :: FilePath, opt_importdirs :: [FilePath], opt_triple :: String, opt_cpu :: String, opt_optLevel :: Int, opt_cmdline :: [Opt] -- remember whole command line } deriving (Show, Eq) defaultOpts = IOption { opt_logLevel = 0 , opt_typecase = False , opt_typeintype = False , opt_coverage = True , opt_showimp = False , opt_errContext = False , opt_repl = True , opt_verbose = True , opt_quiet = False , opt_codegen = ViaC , opt_outputTy = Executable , opt_ibcsubdir = "" , opt_importdirs = [] , opt_triple = "" , opt_cpu = "" , opt_optLevel = 2 , opt_cmdline = [] } data LanguageExt = TypeProviders deriving (Show, Eq, Read, Ord) -- | The output mode in use data OutputMode = RawOutput | IdeSlave Integer deriving Show -- TODO: Add 'module data' to IState, which can be saved out and reloaded quickly (i.e -- without typechecking). -- This will include all the functions and data declarations, plus fixity declarations -- and syntax macros. -- | The global state used in the Idris monad data IState = IState { tt_ctxt :: Context, -- ^ All the currently defined names and their terms idris_constraints :: [(UConstraint, FC)], -- ^ A list of universe constraints and their corresponding source locations idris_infixes :: [FixDecl], -- ^ Currently defined infix operators idris_implicits :: Ctxt [PArg], idris_statics :: Ctxt [Bool], idris_classes :: Ctxt ClassInfo, idris_dsls :: Ctxt DSL, idris_optimisation :: Ctxt OptInfo, idris_datatypes :: Ctxt TypeInfo, idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported -- ^ list of lhs/rhs, and a list of missing clauses idris_flags :: Ctxt [FnOpt], idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos idris_calledgraph :: Ctxt [Name], idris_docstrings :: Ctxt String, idris_totcheck :: [(FC, Name)], idris_log :: String, idris_options :: IOption, idris_name :: Int, idris_metavars :: [Name], -- ^ The currently defined but not proven metavariables idris_coercions :: [Name], idris_transforms :: [(Term, Term)], syntax_rules :: [Syntax], syntax_keywords :: [String], imported :: [FilePath], -- ^ The imported modules idris_scprims :: [(Name, (Int, PrimFn))], idris_objs :: [(Codegen, FilePath)], idris_libs :: [(Codegen, String)], idris_hdrs :: [(Codegen, String)], proof_list :: [(Name, [String])], errLine :: Maybe Int, lastParse :: Maybe Name, indent_stack :: [Int], brace_stack :: [Maybe Int], hide_list :: [(Name, Maybe Accessibility)], default_access :: Accessibility, default_total :: Bool, ibc_write :: [IBCWrite], compiled_so :: Maybe String, idris_dynamic_libs :: [DynamicLib], idris_language_extensions :: [LanguageExt], idris_outputmode :: OutputMode } data SizeChange = Smaller | Same | Bigger | Unknown deriving (Show, Eq) {-! deriving instance Binary SizeChange !-} type SCGEntry = (Name, [Maybe (Int, SizeChange)]) data CGInfo = CGInfo { argsdef :: [Name], calls :: [(Name, [[Name]])], scg :: [SCGEntry], argsused :: [Name], unusedpos :: [Int] } deriving Show {-! deriving instance Binary CGInfo !-} primDefs = [UN "unsafePerformIO", UN "mkLazyForeign", UN "mkForeign", UN "FalseElim"] -- information that needs writing for the current module's .ibc file data IBCWrite = IBCFix FixDecl | IBCImp Name | IBCStatic Name | IBCClass Name | IBCInstance Bool Name Name | IBCDSL Name | IBCData Name | IBCOpt Name | IBCSyntax Syntax | IBCKeyword String | IBCImport FilePath | IBCObj Codegen FilePath | IBCLib Codegen String | IBCDyLib String | IBCHeader Codegen String | IBCAccess Name Accessibility | IBCTotal Name Totality | IBCFlags Name [FnOpt] | IBCTrans (Term, Term) | IBCCG Name | IBCDoc Name | IBCCoercion Name | IBCDef Name -- i.e. main context deriving Show idrisInit = IState initContext [] [] emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext [] "" defaultOpts 6 [] [] [] [] [] [] [] [] [] [] [] Nothing Nothing [] [] [] Hidden False [] Nothing [] [] RawOutput -- | The monad for the main REPL - reading and processing files and updating -- global state (hence the IO inner monad). --type Idris = WriterT [Either String (IO ())] (State IState a)) type Idris = StateT IState IO -- Commands in the REPL data Codegen = ViaC | ViaJava | ViaNode | ViaJavaScript | ViaLLVM #ifdef CLASH | ViaCLaSH #endif | Bytecode deriving (Show, Eq) -- | REPL commands data Command = Quit | Help | Eval PTerm | Check PTerm | DocStr Name | TotCheck Name | Reload | Load FilePath | ChangeDirectory FilePath | ModImport String | Edit | Compile Codegen String | Execute | ExecVal PTerm | Metavars | Prove Name | AddProof (Maybe Name) | RmProof Name | ShowProof Name | Proofs | Universes | TTShell | LogLvl Int | Spec PTerm | HNF PTerm | Defn Name | Info Name | Missing Name | DynamicLink FilePath | ListDynamic | Pattelab PTerm | DebugInfo Name | Search PTerm | SetOpt Opt | UnsetOpt Opt | NOP data Opt = Filename String | Ver | Usage | Quiet | Ideslave | ShowLibs | ShowLibdir | ShowIncs | NoPrelude | NoREPL | OLogging Int | Output String | TypeCase | TypeInType | DefaultTotal | DefaultPartial | WarnPartial | NoCoverage | ErrContext | ShowImpl | Verbose | IBCSubDir String | ImportDir String | PkgBuild String | PkgInstall String | PkgClean String | WarnOnly | Pkg String | BCAsm String | DumpDefun String | DumpCases String | FOVM String | UseCodegen Codegen | OutputTy OutputType | Extension LanguageExt | InterpretScript String | TargetTriple String | TargetCPU String | OptLevel Int deriving (Show, Eq) -- Parsed declarations data Fixity = Infixl { prec :: Int } | Infixr { prec :: Int } | InfixN { prec :: Int } | PrefixN { prec :: Int } deriving Eq {-! deriving instance Binary Fixity !-} instance Show Fixity where show (Infixl i) = "infixl " ++ show i show (Infixr i) = "infixr " ++ show i show (InfixN i) = "infix " ++ show i show (PrefixN i) = "prefix " ++ show i data FixDecl = Fix Fixity String deriving Eq instance Show FixDecl where show (Fix f s) = show f ++ " " ++ s {-! deriving instance Binary FixDecl !-} instance Ord FixDecl where compare (Fix x _) (Fix y _) = compare (prec x) (prec y) data Static = Static | Dynamic deriving (Show, Eq) {-! deriving instance Binary Static !-} -- Mark bindings with their explicitness, and laziness data Plicity = Imp { plazy :: Bool, pstatic :: Static, pdocstr :: String } | Exp { plazy :: Bool, pstatic :: Static, pdocstr :: String } | Constraint { plazy :: Bool, pstatic :: Static, pdocstr :: String } | TacImp { plazy :: Bool, pstatic :: Static, pscript :: PTerm, pdocstr :: String } deriving (Show, Eq) {-! deriving instance Binary Plicity !-} impl = Imp False Dynamic "" expl = Exp False Dynamic "" constraint = Constraint False Dynamic "" tacimpl t = TacImp False Dynamic t "" data FnOpt = Inlinable -- always evaluate when simplifying | TotalFn | PartialFn | Coinductive | AssertTotal | Dictionary -- type class dictionary, eval only when -- a function argument, and further evaluation resutls | Implicit -- implicit coercion | CExport String -- export, with a C name | Reflection -- a reflecting function, compile-time only | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names deriving (Show, Eq) {-! deriving instance Binary FnOpt !-} type FnOpts = [FnOpt] inlinable :: FnOpts -> Bool inlinable = elem Inlinable dictionary :: FnOpts -> Bool dictionary = elem Dictionary -- | Top-level declarations such as compiler directives, definitions, -- datatypes and typeclasses. data PDecl' t = PFix FC Fixity [String] -- ^ Fixity declaration | PTy String SyntaxInfo FC FnOpts Name t -- ^ Type declaration | PPostulate String SyntaxInfo FC FnOpts Name t -- ^ Postulate | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause | PCAF FC Name t -- ^ Top level constant | PData String SyntaxInfo FC Bool (PData' t) -- ^ Data declaration. The Bool argument is True for codata. | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block | PNamespace String [PDecl' t] -- ^ New namespace | PRecord String SyntaxInfo FC Name t String Name t -- ^ Record declaration | PClass String SyntaxInfo FC [t] -- constraints Name [(Name, t)] -- parameters [PDecl' t] -- declarations -- ^ Type class: arguments are documentation, syntax info, source location, constraints, -- class name, parameters, method declarations | PInstance SyntaxInfo FC [t] -- constraints Name -- class [t] -- parameters t -- full instance type (Maybe Name) -- explicit name [PDecl' t] -- ^ Instance declaration: arguments are syntax info, source location, constraints, -- class name, parameters, full instance type, optional explicit name, and definitions | PDSL Name (DSL' t) -- ^ DSL declaration | PSyntax FC Syntax -- ^ Syntax definition | PMutual FC [PDecl' t] -- ^ Mutual block | PDirective (Idris ()) -- ^ Compiler directive. The parser inserts the corresponding action in the Idris monad. | PProvider SyntaxInfo FC Name t t -- ^ Type provider. The first t is the type, the second is the term | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If -- bool is True, lhs and rhs must be convertible deriving Functor {-! deriving instance Binary PDecl' !-} -- | One clause of a top-level definition. Term arguments to constructors are: -- -- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause) -- -- 2. The list of patterns -- -- 3. The right-hand side -- -- 4. The where block (PDecl' t) data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition. | PWith FC Name t [t] t [PDecl' t] | PClauseR FC [t] t [PDecl' t] | PWithR FC [t] t [PDecl' t] deriving Functor {-! deriving instance Binary PClause' !-} -- | Data declaration data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype d_tcon :: t, -- ^ Type constructor d_cons :: [(String, Name, t, FC)] -- ^ Constructors } -- ^ Data declaration | PLaterdecl { d_name :: Name, d_tcon :: t } -- ^ "Placeholder" for data whose constructors are defined later deriving Functor {-! deriving instance Binary PData' !-} -- Handy to get a free function for applying PTerm -> PTerm functions -- across a program, by deriving Functor type PDecl = PDecl' PTerm type PData = PData' PTerm type PClause = PClause' PTerm -- get all the names declared in a decl declared :: PDecl -> [Name] declared (PFix _ _ _) = [] declared (PTy _ _ _ _ n t) = [n] declared (PPostulate _ _ _ _ n t) = [n] declared (PClauses _ _ n _) = [] -- not a declaration declared (PCAF _ n _) = [n] declared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts where fstt (_, a, _, _) = a declared (PData _ _ _ _ (PLaterdecl n _)) = [n] declared (PParams _ _ ds) = concatMap declared ds declared (PNamespace _ ds) = concatMap declared ds declared (PRecord _ _ _ n _ _ c _) = [n, c] declared (PClass _ _ _ _ n _ ms) = n : concatMap declared ms declared (PInstance _ _ _ _ _ _ _ _) = [] declared (PDSL n _) = [n] declared (PSyntax _ _) = [] declared (PMutual _ ds) = concatMap declared ds declared (PDirective _) = [] -- get the names declared, not counting nested parameter blocks tldeclared :: PDecl -> [Name] tldeclared (PFix _ _ _) = [] tldeclared (PTy _ _ _ _ n t) = [n] tldeclared (PPostulate _ _ _ _ n t) = [n] tldeclared (PClauses _ _ n _) = [] -- not a declaration tldeclared (PRecord _ _ _ n _ _ c _) = [n, c] tldeclared (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts where fstt (_, a, _, _) = a tldeclared (PParams _ _ ds) = [] tldeclared (PMutual _ ds) = concatMap tldeclared ds tldeclared (PNamespace _ ds) = concatMap tldeclared ds tldeclared (PClass _ _ _ _ n _ ms) = concatMap tldeclared ms tldeclared (PInstance _ _ _ _ _ _ _ _) = [] tldeclared _ = [] defined :: PDecl -> [Name] defined (PFix _ _ _) = [] defined (PTy _ _ _ _ n t) = [] defined (PPostulate _ _ _ _ n t) = [] defined (PClauses _ _ n _) = [n] -- not a declaration defined (PCAF _ n _) = [n] defined (PData _ _ _ _ (PDatadecl n _ ts)) = n : map fstt ts where fstt (_, a, _, _) = a defined (PData _ _ _ _ (PLaterdecl n _)) = [] defined (PParams _ _ ds) = concatMap defined ds defined (PNamespace _ ds) = concatMap defined ds defined (PRecord _ _ _ n _ _ c _) = [n, c] defined (PClass _ _ _ _ n _ ms) = n : concatMap defined ms defined (PInstance _ _ _ _ _ _ _ _) = [] defined (PDSL n _) = [n] defined (PSyntax _ _) = [] defined (PMutual _ ds) = concatMap defined ds defined (PDirective _) = [] --defined _ = [] updateN :: [(Name, Name)] -> Name -> Name updateN ns n | Just n' <- lookup n ns = n' updateN _ n = n updateNs :: [(Name, Name)] -> PTerm -> PTerm updateNs [] t = t updateNs ns t = mapPT updateRef t where updateRef (PRef fc f) = PRef fc (updateN ns f) updateRef t = t -- updateDNs :: [(Name, Name)] -> PDecl -> PDecl -- updateDNs [] t = t -- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t -- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c) -- where updateCNs ns (PClause n l ts r ds) -- = PClause (updateN ns n) (fmap (updateNs ns) l) -- (map (fmap (updateNs ns)) ts) -- (fmap (updateNs ns) r) -- (map (updateDNs ns) ds) -- updateDNs ns c = c -- | High level language terms data PTerm = PQuote Raw | PRef FC Name | PInferRef FC Name -- ^ A name to be defined later | PPatvar FC Name | PLam Name PTerm PTerm | PPi Plicity Name PTerm PTerm | PLet Name PTerm PTerm PTerm | PTyped PTerm PTerm -- ^ Term with explicit type | PApp FC PTerm [PArg] | PMatchApp FC Name -- ^ Make an application by type matching | PCase FC PTerm [(PTerm, PTerm)] | PTrue FC | PFalse FC | PRefl FC PTerm | PResolveTC FC | PEq FC PTerm PTerm | PRewrite FC PTerm PTerm (Maybe PTerm) | PPair FC PTerm PTerm | PDPair FC PTerm PTerm PTerm | PAlternative Bool [PTerm] -- True if only one may work | PHidden PTerm -- ^ Irrelevant or hidden pattern | PType | PGoal FC PTerm Name PTerm | PConstant Const | Placeholder | PDoBlock [PDo] | PIdiom FC PTerm | PReturn FC | PMetavar Name | PProof [PTactic] -- ^ Proof script | PTactics [PTactic] -- ^ As PProof, but no auto solving | PElabError Err -- ^ Error to report on elaboration | PImpossible -- ^ Special case for declaring when an LHS can't typecheck | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice | PUnifyLog PTerm -- ^ dump a trace of unifications when building term deriving Eq {-! deriving instance Binary PTerm !-} mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm mapPT f t = f (mpt t) where mpt (PLam n t s) = PLam n (mapPT f t) (mapPT f s) mpt (PPi p n t s) = PPi p n (mapPT f t) (mapPT f s) mpt (PLet n ty v s) = PLet n (mapPT f ty) (mapPT f v) (mapPT f s) mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s) (fmap (mapPT f) g) mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as) mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os) mpt (PEq fc l r) = PEq fc (mapPT f l) (mapPT f r) mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r) mpt (PPair fc l r) = PPair fc (mapPT f l) (mapPT f r) mpt (PDPair fc l t r) = PDPair fc (mapPT f l) (mapPT f t) (mapPT f r) mpt (PAlternative a as) = PAlternative a (map (mapPT f) as) mpt (PHidden t) = PHidden (mapPT f t) mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds) mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts) mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts) mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm) mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc) mpt x = x data PTactic' t = Intro [Name] | Intros | Focus Name | Refine Name [Bool] | Rewrite t | Equiv t | MatchRefine Name | LetTac Name t | LetTacTy Name t t | Exact t | Compute | Trivial | Solve | Attack | ProofState | ProofTerm | Undo | Try (PTactic' t) (PTactic' t) | TSeq (PTactic' t) (PTactic' t) | ApplyTactic t -- see Language.Reflection module | Reflect t | Fill t | GoalType String (PTactic' t) | Qed | Abandon deriving (Show, Eq, Functor) {-! deriving instance Binary PTactic' !-} instance Sized a => Sized (PTactic' a) where size (Intro nms) = 1 + size nms size Intros = 1 size (Focus nm) = 1 + size nm size (Refine nm bs) = 1 + size nm + length bs size (Rewrite t) = 1 + size t size (LetTac nm t) = 1 + size nm + size t size (Exact t) = 1 + size t size Compute = 1 size Trivial = 1 size Solve = 1 size Attack = 1 size ProofState = 1 size ProofTerm = 1 size Undo = 1 size (Try l r) = 1 + size l + size r size (TSeq l r) = 1 + size l + size r size (ApplyTactic t) = 1 + size t size (Reflect t) = 1 + size t size (Fill t) = 1 + size t size Qed = 1 size Abandon = 1 type PTactic = PTactic' PTerm data PDo' t = DoExp FC t | DoBind FC Name t | DoBindP FC t t | DoLet FC Name t t | DoLetP FC t t deriving (Eq, Functor) {-! deriving instance Binary PDo' !-} instance Sized a => Sized (PDo' a) where size (DoExp fc t) = 1 + size fc + size t size (DoBind fc nm t) = 1 + size fc + size nm + size t size (DoBindP fc l r) = 1 + size fc + size l + size r size (DoLet fc nm l r) = 1 + size fc + size nm + size l + size r size (DoLetP fc l r) = 1 + size fc + size l + size r type PDo = PDo' PTerm -- The priority gives a hint as to elaboration order. Best to elaborate -- things early which will help give a more concrete type to other -- variables, e.g. a before (interpTy a). -- TODO: priority no longer serves any purpose, drop it! data PArg' t = PImp { priority :: Int, lazyarg :: Bool, pname :: Name, getTm :: t, pargdoc :: String } | PExp { priority :: Int, lazyarg :: Bool, getTm :: t, pargdoc :: String } | PConstraint { priority :: Int, lazyarg :: Bool, getTm :: t, pargdoc :: String } | PTacImplicit { priority :: Int, lazyarg :: Bool, pname :: Name, getScript :: t, getTm :: t, pargdoc :: String } deriving (Show, Eq, Functor) instance Sized a => Sized (PArg' a) where size (PImp p l nm trm _) = 1 + size nm + size trm size (PExp p l trm _) = 1 + size trm size (PConstraint p l trm _) = 1 + size trm size (PTacImplicit p l nm scr trm _) = 1 + size nm + size scr + size trm {-! deriving instance Binary PArg' !-} pimp n t = PImp 0 True n t "" pexp t = PExp 0 False t "" pconst t = PConstraint 0 False t "" ptacimp n s t = PTacImplicit 0 True n s t "" type PArg = PArg' PTerm -- Type class data data ClassInfo = CI { instanceName :: Name, class_methods :: [(Name, (FnOpts, PTerm))], class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl class_params :: [Name], class_instances :: [Name] } deriving Show {-! deriving instance Binary ClassInfo !-} data OptInfo = Optimise { collapsible :: Bool, forceable :: [Int], -- argument positions recursive :: [Int] } deriving Show {-! deriving instance Binary OptInfo !-} data TypeInfo = TI { con_names :: [Name], codata :: Bool, param_pos :: [Int] } deriving Show {-! deriving instance Binary TypeInfo !-} -- Syntactic sugar info data DSL' t = DSL { dsl_bind :: t, dsl_return :: t, dsl_apply :: t, dsl_pure :: t, dsl_var :: Maybe t, index_first :: Maybe t, index_next :: Maybe t, dsl_lambda :: Maybe t, dsl_let :: Maybe t } deriving (Show, Functor) {-! deriving instance Binary DSL' !-} type DSL = DSL' PTerm data SynContext = PatternSyntax | TermSyntax | AnySyntax deriving Show {-! deriving instance Binary SynContext !-} data Syntax = Rule [SSymbol] PTerm SynContext deriving Show {-! deriving instance Binary Syntax !-} data SSymbol = Keyword Name | Symbol String | Binding Name | Expr Name | SimpleExpr Name deriving Show {-! deriving instance Binary SSymbol !-} initDSL = DSL (PRef f (UN ">>=")) (PRef f (UN "return")) (PRef f (UN "<$>")) (PRef f (UN "pure")) Nothing Nothing Nothing Nothing Nothing where f = FC "(builtin)" 0 data Using = UImplicit Name PTerm | UConstraint Name [Name] deriving (Show, Eq) {-! deriving instance Binary Using !-} data SyntaxInfo = Syn { using :: [Using], syn_params :: [(Name, PTerm)], syn_namespace :: [String], no_imp :: [Name], decoration :: Name -> Name, inPattern :: Bool, implicitAllowed :: Bool, dsl_info :: DSL } deriving Show {-! deriving instance Binary SyntaxInfo !-} defaultSyntax = Syn [] [] [] [] id False False initDSL expandNS :: SyntaxInfo -> Name -> Name expandNS syn n@(NS _ _) = n expandNS syn n = case syn_namespace syn of [] -> n xs -> NS n xs --- Pretty printing declarations and terms instance Show PTerm where show tm = showImp False tm instance Pretty PTerm where pretty = prettyImp False instance Show PDecl where show d = showDeclImp False d instance Show PClause where show c = showCImp True c instance Show PData where show d = showDImp False d showDeclImp _ (PFix _ f ops) = show f ++ " " ++ showSep ", " ops showDeclImp t (PTy _ _ _ _ n ty) = show n ++ " : " ++ showImp t ty showDeclImp t (PPostulate _ _ _ _ n ty) = show n ++ " : " ++ showImp t ty showDeclImp _ (PClauses _ _ n c) = showSep "\n" (map show c) showDeclImp _ (PData _ _ _ _ d) = show d showDeclImp _ (PParams f ns ps) = "parameters " ++ show ns ++ "\n" ++ showSep "\n" (map show ps) showCImp :: Bool -> PClause -> String showCImp impl (PClause _ n l ws r w) = showImp impl l ++ showWs ws ++ " = " ++ showImp impl r ++ " where " ++ show w where showWs [] = "" showWs (x : xs) = " | " ++ showImp impl x ++ showWs xs showCImp impl (PWith _ n l ws r w) = showImp impl l ++ showWs ws ++ " with " ++ showImp impl r ++ " { " ++ show w ++ " } " where showWs [] = "" showWs (x : xs) = " | " ++ showImp impl x ++ showWs xs showDImp :: Bool -> PData -> String showDImp impl (PDatadecl n ty cons) = "data " ++ show n ++ " : " ++ showImp impl ty ++ " where\n\t" ++ showSep "\n\t| " (map (\ (_, n, t, _) -> show n ++ " : " ++ showImp impl t) cons) getImps :: [PArg] -> [(Name, PTerm)] getImps [] = [] getImps (PImp _ _ n tm _ : xs) = (n, tm) : getImps xs getImps (_ : xs) = getImps xs getExps :: [PArg] -> [PTerm] getExps [] = [] getExps (PExp _ _ tm _ : xs) = tm : getExps xs getExps (_ : xs) = getExps xs getConsts :: [PArg] -> [PTerm] getConsts [] = [] getConsts (PConstraint _ _ tm _ : xs) = tm : getConsts xs getConsts (_ : xs) = getConsts xs getAll :: [PArg] -> [PTerm] getAll = map getTm prettyImp :: Bool -> PTerm -> Doc prettyImp impl = prettySe 10 where prettySe p (PQuote r) = if size r > breakingSize then text "![" $$ pretty r <> text "]" else text "![" <> pretty r <> text "]" prettySe p (PPatvar fc n) = pretty n prettySe p (PRef fc n) = if impl then pretty n else prettyBasic n where prettyBasic n@(UN _) = pretty n prettyBasic (MN _ s) = text s prettyBasic (NS n s) = (foldr (<>) empty (intersperse (text ".") (map text $ reverse s))) <> prettyBasic n prettySe p (PLam n ty sc) = bracket p 2 $ if size sc > breakingSize then text "λ" <> pretty n <+> text "=>" $+$ pretty sc else text "λ" <> pretty n <+> text "=>" <+> pretty sc prettySe p (PLet n ty v sc) = bracket p 2 $ if size sc > breakingSize then text "let" <+> pretty n <+> text "=" <+> prettySe 10 v <+> text "in" $+$ nest nestingSize (prettySe 10 sc) else text "let" <+> pretty n <+> text "=" <+> prettySe 10 v <+> text "in" <+> prettySe 10 sc prettySe p (PPi (Exp l s _) n ty sc) | n `elem` allNamesIn sc || impl = let open = if l then text "|" <> lparen else lparen in bracket p 2 $ if size sc > breakingSize then open <> pretty n <+> colon <+> prettySe 10 ty <> rparen <+> st <+> text "->" $+$ prettySe 10 sc else open <> pretty n <+> colon <+> prettySe 10 ty <> rparen <+> st <+> text "->" <+> prettySe 10 sc | otherwise = bracket p 2 $ if size sc > breakingSize then prettySe 0 ty <+> st <+> text "->" $+$ prettySe 10 sc else prettySe 0 ty <+> st <+> text "->" <+> prettySe 10 sc where st = case s of Static -> text "[static]" _ -> empty prettySe p (PPi (Imp l s _) n ty sc) | impl = let open = if l then text "|" <> lbrace else lbrace in bracket p 2 $ if size sc > breakingSize then open <> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+> st <+> text "->" <+> prettySe 10 sc else open <> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+> st <+> text "->" <+> prettySe 10 sc | otherwise = prettySe 10 sc where st = case s of Static -> text $ "[static]" _ -> empty prettySe p (PPi (Constraint _ _ _) n ty sc) = bracket p 2 $ if size sc > breakingSize then prettySe 10 ty <+> text "=>" <+> prettySe 10 sc else prettySe 10 ty <+> text "=>" $+$ prettySe 10 sc prettySe p (PPi (TacImp _ _ s _) n ty sc) = bracket p 2 $ if size sc > breakingSize then lbrace <> text "tacimp" <+> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+> text "->" $+$ prettySe 10 sc else lbrace <> text "tacimp" <+> pretty n <+> colon <+> prettySe 10 ty <> rbrace <+> text "->" <+> prettySe 10 sc prettySe p (PApp _ (PRef _ f) []) | not impl = pretty f prettySe p (PApp _ (PRef _ op@(UN (f:_))) args) | length (getExps args) == 2 && (not impl) && (not $ isAlpha f) = let [l, r] = getExps args in bracket p 1 $ if size r > breakingSize then prettySe 1 l <+> pretty op $+$ prettySe 0 r else prettySe 1 l <+> pretty op <+> prettySe 0 r prettySe p (PApp _ f as) = let args = getExps as in bracket p 1 $ prettySe 1 f <+> if impl then foldl' fS empty as -- foldr (<+>) empty $ map prettyArgS as else foldl' fSe empty args -- foldr (<+>) empty $ map prettyArgSe args where fS l r = if size r > breakingSize then l $+$ nest nestingSize (prettyArgS r) else l <+> prettyArgS r fSe l r = if size r > breakingSize then l $+$ nest nestingSize (prettyArgSe r) else l <+> prettyArgSe r prettySe p (PCase _ scr opts) = text "case" <+> prettySe 10 scr <+> text "of" $+$ nest nestingSize prettyBody where prettyBody = foldr ($$) empty $ intersperse (text "|") $ map sc opts sc (l, r) = prettySe 10 l <+> text "=>" <+> prettySe 10 r prettySe p (PHidden tm) = text "." <> prettySe 0 tm prettySe p (PRefl _ _) = text "refl" prettySe p (PResolveTC _) = text "resolvetc" prettySe p (PTrue _) = text "()" prettySe p (PFalse _) = text "_|_" prettySe p (PEq _ l r) = bracket p 2 $ if size r > breakingSize then prettySe 10 l <+> text "=" $$ nest nestingSize (prettySe 10 r) else prettySe 10 l <+> text "=" <+> prettySe 10 r prettySe p (PRewrite _ l r _) = bracket p 2 $ if size r > breakingSize then text "rewrite" <+> prettySe 10 l <+> text "in" $$ nest nestingSize (prettySe 10 r) else text "rewrite" <+> prettySe 10 l <+> text "in" <+> prettySe 10 r prettySe p (PTyped l r) = lparen <> prettySe 10 l <+> colon <+> prettySe 10 r <> rparen prettySe p (PPair _ l r) = if size r > breakingSize then lparen <> prettySe 10 l <> text "," $+$ prettySe 10 r <> rparen else lparen <> prettySe 10 l <> text "," <+> prettySe 10 r <> rparen prettySe p (PDPair _ l t r) = if size r > breakingSize then lparen <> prettySe 10 l <+> text "**" $+$ prettySe 10 r <> rparen else lparen <> prettySe 10 l <+> text "**" <+> prettySe 10 r <> rparen prettySe p (PAlternative a as) = lparen <> text "|" <> prettyAs <> text "|" <> rparen where prettyAs = foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (prettySe 10) as prettySe p PType = text "Type" prettySe p (PConstant c) = pretty c -- XXX: add pretty for tactics prettySe p (PProof ts) = text "proof" <+> lbrace $+$ nest nestingSize (text . show $ ts) $+$ rbrace prettySe p (PTactics ts) = text "tactics" <+> lbrace $+$ nest nestingSize (text . show $ ts) $+$ rbrace prettySe p (PMetavar n) = text "?" <> pretty n prettySe p (PReturn f) = text "return" prettySe p PImpossible = text "impossible" prettySe p Placeholder = text "_" prettySe p (PDoBlock _) = text "do block pretty not implemented" prettySe p (PElabError s) = pretty s prettySe p _ = text "test" prettyArgS (PImp _ _ n tm _) = prettyArgSi (n, tm) prettyArgS (PExp _ _ tm _) = prettyArgSe tm prettyArgS (PConstraint _ _ tm _) = prettyArgSc tm prettyArgS (PTacImplicit _ _ n _ tm _) = prettyArgSti (n, tm) prettyArgSe arg = prettySe 0 arg prettyArgSi (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe 10 val <> rbrace prettyArgSc val = lbrace <> lbrace <> prettySe 10 val <> rbrace <> rbrace prettyArgSti (n, val) = lbrace <> text "auto" <+> pretty n <+> text "=" <+> prettySe 10 val <> rbrace bracket outer inner doc | inner > outer = lparen <> doc <> rparen | otherwise = doc showImp :: Bool -> PTerm -> String showImp impl tm = se 10 tm where se p (PQuote r) = "![" ++ show r ++ "]" se p (PPatvar fc n) = if impl then show n ++ "[p]" else show n se p (PInferRef fc n) = "!" ++ show n -- ++ "[" ++ show fc ++ "]" se p (PRef fc n) = if impl then show n -- ++ "[" ++ show fc ++ "]" else showbasic n where showbasic n@(UN _) = show n showbasic (MN _ s) = s showbasic (NS n s) = showSep "." (reverse s) ++ "." ++ showbasic n se p (PLam n ty sc) = bracket p 2 $ "\\ " ++ show n ++ (if impl then " : " ++ se 10 ty else "") ++ " => " ++ se 10 sc se p (PLet n ty v sc) = bracket p 2 $ "let " ++ show n ++ " = " ++ se 10 v ++ " in " ++ se 10 sc se p (PPi (Exp l s _) n ty sc) | n `elem` allNamesIn sc || impl = bracket p 2 $ (if l then "|(" else "(") ++ show n ++ " : " ++ se 10 ty ++ ") " ++ st ++ "-> " ++ se 10 sc | otherwise = bracket p 2 $ se 0 ty ++ " " ++ st ++ "-> " ++ se 10 sc where st = case s of Static -> "[static] " _ -> "" se p (PPi (Imp l s _) n ty sc) | impl = bracket p 2 $ (if l then "|{" else "{") ++ show n ++ " : " ++ se 10 ty ++ "} " ++ st ++ "-> " ++ se 10 sc | otherwise = se 10 sc where st = case s of Static -> "[static] " _ -> "" se p (PPi (Constraint _ _ _) n ty sc) = bracket p 2 $ se 10 ty ++ " => " ++ se 10 sc se p (PPi (TacImp _ _ s _) n ty sc) = bracket p 2 $ "{tacimp " ++ show n ++ " : " ++ se 10 ty ++ "} -> " ++ se 10 sc se p e | Just str <- slist p e = str | Just num <- snat p e = show num se p (PMatchApp _ f) = "match " ++ show f se p (PApp _ (PRef _ f) []) | not impl = show f se p (PApp _ (PRef _ op@(UN (f:_))) args) | length (getExps args) == 2 && not impl && not (isAlpha f) = let [l, r] = getExps args in bracket p 1 $ se 1 l ++ " " ++ show op ++ " " ++ se 0 r se p (PApp _ f as) = let args = getExps as in bracket p 1 $ se 1 f ++ if impl then concatMap sArg as else concatMap seArg args se p (PCase _ scr opts) = "case " ++ se 10 scr ++ " of " ++ showSep " | " (map sc opts) where sc (l, r) = se 10 l ++ " => " ++ se 10 r se p (PHidden tm) = "." ++ se 0 tm se p (PRefl _ t) | not impl = "refl" | otherwise = "refl {" ++ se 10 t ++ "}" se p (PResolveTC _) = "resolvetc" se p (PTrue _) = "()" se p (PFalse _) = "_|_" se p (PEq _ l r) = bracket p 2 $ se 10 l ++ " = " ++ se 10 r se p (PRewrite _ l r _) = bracket p 2 $ "rewrite " ++ se 10 l ++ " in " ++ se 10 r se p (PTyped l r) = "(" ++ se 10 l ++ " : " ++ se 10 r ++ ")" se p (PPair _ l r) = "(" ++ se 10 l ++ ", " ++ se 10 r ++ ")" se p (PDPair _ l t r) = "(" ++ se 10 l ++ " ** " ++ se 10 r ++ ")" se p (PAlternative a as) = "(|" ++ showSep " , " (map (se 10) as) ++ "|)" se p PType = "Type" se p (PConstant c) = show c se p (PProof ts) = "proof { " ++ show ts ++ "}" se p (PTactics ts) = "tactics { " ++ show ts ++ "}" se p (PMetavar n) = "?" ++ show n se p (PReturn f) = "return" se p PImpossible = "impossible" se p Placeholder = "_" se p (PDoBlock _) = "do block show not implemented" se p (PElabError s) = show s se p (PCoerced t) = se p t se p (PUnifyLog t) = "%unifyLog " ++ se p t se p (PGoal f t n sc) = "quoteGoal " ++ show n ++ " by " ++ se 10 t ++ " in " ++ se 10 sc -- se p x = "Not implemented" slist' p (PApp _ (PRef _ nil) _) | nsroot nil == UN "Nil" = Just [] slist' p (PApp _ (PRef _ cons) args) | nsroot cons == UN "::", (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args, all isImp imps, Just tl' <- slist' p tl = Just (hd:tl') where isImp (PImp {}) = True isImp _ = False slist' _ _ = Nothing slist p e | Just es <- slist' p e = Just $ case es of [] -> "[]" [x] -> "[" ++ se p x ++ "]" xs -> "[" ++ intercalate "," (map (se p) xs) ++ "]" slist _ _ = Nothing -- since Prelude is always imported, S & Z are unqualified iff they're the -- Nat ones. snat p (PRef _ o) | show o == (natns++"Z") || show o == "Z" = Just 0 snat p (PApp _ s [PExp {getTm=n}]) | show s == (natns++"S") || show s == "S", Just n' <- snat p n = Just $ 1 + n' snat _ _ = Nothing natns = "Prelude.Nat." sArg (PImp _ _ n tm _) = siArg (n, tm) sArg (PExp _ _ tm _) = seArg tm sArg (PConstraint _ _ tm _) = scArg tm sArg (PTacImplicit _ _ n _ tm _) = stiArg (n, tm) seArg arg = " " ++ se 0 arg siArg (n, val) = " {" ++ show n ++ " = " ++ se 10 val ++ "}" scArg val = " {{" ++ se 10 val ++ "}}" stiArg (n, val) = " {auto " ++ show n ++ " = " ++ se 10 val ++ "}" bracket outer inner str | inner > outer = "(" ++ str ++ ")" | otherwise = str instance Sized PTerm where size (PQuote rawTerm) = size rawTerm size (PRef fc name) = size name size (PLam name ty bdy) = 1 + size ty + size bdy size (PPi plicity name ty bdy) = 1 + size ty + size bdy size (PLet name ty def bdy) = 1 + size ty + size def + size bdy size (PTyped trm ty) = 1 + size trm + size ty size (PApp fc name args) = 1 + size args size (PCase fc trm bdy) = 1 + size trm + size bdy size (PTrue fc) = 1 size (PFalse fc) = 1 size (PRefl fc _) = 1 size (PResolveTC fc) = 1 size (PEq fc left right) = 1 + size left + size right size (PRewrite fc left right _) = 1 + size left + size right size (PPair fc left right) = 1 + size left + size right size (PDPair fs left ty right) = 1 + size left + size ty + size right size (PAlternative a alts) = 1 + size alts size (PHidden hidden) = size hidden size (PUnifyLog tm) = size tm size PType = 1 size (PConstant const) = 1 + size const size Placeholder = 1 size (PDoBlock dos) = 1 + size dos size (PIdiom fc term) = 1 + size term size (PReturn fc) = 1 size (PMetavar name) = 1 size (PProof tactics) = size tactics size (PElabError err) = size err size PImpossible = 1 getPArity :: PTerm -> Int getPArity (PPi _ _ _ sc) = 1 + getPArity sc getPArity _ = 0 -- Return all names, free or globally bound, in the given term. allNamesIn :: PTerm -> [Name] allNamesIn tm = nub $ ni [] tm where ni env (PRef _ n) | not (n `elem` env) = [n] ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os) ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc ni env (PHidden tm) = ni env tm ni env (PEq _ l r) = ni env l ++ ni env r ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ l r) = ni env l ++ ni env r ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative a ls) = concatMap (ni env) ls ni env (PUnifyLog tm) = ni env tm ni env _ = [] -- Return names which are free in the given term. namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name] namesIn uvars ist tm = nub $ ni [] tm where ni env (PRef _ n) | not (n `elem` env) = case lookupTy n (tt_ctxt ist) of [] -> [n] _ -> if n `elem` (map fst uvars) then [n] else [] ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os) ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc ni env (PEq _ l r) = ni env l ++ ni env r ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ l r) = ni env l ++ ni env r ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative a as) = concatMap (ni env) as ni env (PHidden tm) = ni env tm ni env (PUnifyLog tm) = ni env tm ni env _ = [] -- Return which of the given names are used in the given term. usedNamesIn :: [Name] -> IState -> PTerm -> [Name] usedNamesIn vars ist tm = nub $ ni [] tm where ni env (PRef _ n) | n `elem` vars && not (n `elem` env) = case lookupTy n (tt_ctxt ist) of [] -> [n] _ -> [] ni env (PApp _ f as) = ni env f ++ concatMap (ni env) (map getTm as) ni env (PCase _ c os) = ni env c ++ concatMap (ni env) (map snd os) ni env (PLam n ty sc) = ni env ty ++ ni (n:env) sc ni env (PPi _ n ty sc) = ni env ty ++ ni (n:env) sc ni env (PEq _ l r) = ni env l ++ ni env r ni env (PRewrite _ l r _) = ni env l ++ ni env r ni env (PTyped l r) = ni env l ++ ni env r ni env (PPair _ l r) = ni env l ++ ni env r ni env (PDPair _ (PRef _ n) t r) = ni env t ++ ni (n:env) r ni env (PDPair _ l t r) = ni env l ++ ni env t ++ ni env r ni env (PAlternative a as) = concatMap (ni env) as ni env (PHidden tm) = ni env tm ni env (PUnifyLog tm) = ni env tm ni env _ = []
christiaanb/Idris-dev
src/Idris/AbsSyntaxTree.hs
bsd-3-clause
45,732
0
19
16,719
16,086
8,291
7,795
975
61
module Helpers ( isSubsetOf , none , remove , unions , andThen , return , guard ) where import Prelude hiding (return) import Data.Set (Set) import qualified Data.Set as Set -- |Checks whether a set is a subset of the other set. isSubsetOf :: Ord a => Set a -> Set a -> Bool isSubsetOf first second = first `Set.intersection` second == first -- |Determines whether no element of the structure satisfies the predicate. none :: Foldable t => (a -> Bool) -> t a -> Bool none predicate = not . any predicate -- |Filter all elements that do not satisfy the predicate. remove :: Ord a => (a -> Bool) -> Set a -> Set a remove predicate = Set.filter (not. predicate) unions :: Ord a => Set (Set a) -> Set a unions = Set.foldl Set.union Set.empty return :: a -> Set a return = Set.singleton andThen :: (Ord a, Ord b) => Set a -> (a -> Set b) -> Set b andThen monad f = (unions . Set.map f) monad guard :: Bool -> Set () guard True = Set.singleton () guard False = Set.empty
jakubriha/automata
src/Helpers.hs
bsd-3-clause
1,002
0
10
227
374
195
179
32
1
{-| Module : Reactive.DOM.Widget.Common Description : Various useful widgets Copyright : (c) Alexander Vieth, 2016 Licence : BSD3 Maintainer : aovieth@gmail.com Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE RankNTypes #-} module Reactive.DOM.Widget.Common where import qualified Data.Text as T import Reactive.DOM.Node import Reactive.DOM.Children.Static import Reactive.DOM.Children.NodeList import Reactive.DOM.Children.Single import Reactive.Banana.Combinators import Reactive.Banana.Frameworks import Reactive.Sequence import Data.Profunctor varyingText :: OpenWidget (Sequence T.Text) () varyingText = widget $ \(~(seqnc, _)) -> do let ~(initial, rest) = runSequence seqnc pure ((), children (Single (textChild initial)) (pure . Single . textChild <$> rest)) constantText :: OpenWidget T.Text () constantText = lmap always varyingText div :: OpenWidget s t -> Widget "div" s t div = id a :: OpenWidget s t -> Widget "a" s t a = id link :: OpenWidget s t -> Widget "a" (s, T.Text) t link w = pullthrough (a (lmap fst w)) `modifyr` setHref where setHref = modifier $ \((_, href), t) -> do attributes' (always [Set (makeAttributes [("href", href)])]) pure t p :: OpenWidget s t -> Widget "p" s t p = id span :: OpenWidget s t -> Widget "span" s t span = id button :: OpenWidget s t -> Widget "button" s t button = id input :: OpenWidget s t -> Widget "input" s t input = id form :: OpenWidget s t -> Widget "form" s t form = id hr :: Widget "hr" () () hr = trivialWidget br :: Widget "br" () () br = trivialWidget -- | A button which shows text and gives a click event. simpleButton :: Widget "button" T.Text (Event ()) simpleButton = button constantText `modifyr` modifier (const (event Click)) -- | The text displayed here is not determined by children, but by the value -- property, so it can be played with through the Modification interface. textInput :: Widget "input" () (Event T.Text) textInput = input trivialWidget `modifyr` modifier (const (event Input)) textInputVarying :: Widget "input" (Sequence T.Text) (Event T.Text) textInputVarying = pullthrough (input (lmap (const ()) trivialWidget)) `modifyr` setup where setup = modifier $ \(s, t) -> setInputValue s t >> event Input setInputValue :: Sequence T.Text -> () -> ElementBuilder "input" () setInputValue seqnc _ = do -- Each text gets its own Properties, and we're careful to unset the -- previous one. let uniqueProperties = setValue <$> seqnc let ~(initial, _) = runSequence uniqueProperties changes <- sequenceChanges uniqueProperties properties' ([Set initial] |> (unsetSet <$> changes)) pure () where setValue :: T.Text -> Properties setValue txt = makeProperties [("value", txt)] unsetSet :: (Properties, Properties) -> [Action Properties] unsetSet (old, new) = [Unset old, Set new] -- | Same as textInput but we set the type attribute to password for you. passwordInput :: Widget "input" () (Event T.Text) passwordInput = textInput `modifyr` modifier setPasswordType where setPasswordType event = attributes (always (Set attrs)) >> pure event attrs = makeAttributes [("type", "password")] passwordInputVarying :: Widget "input" (Sequence T.Text) (Event T.Text) passwordInputVarying = pullthrough (input (lmap (const ()) trivialWidget)) `modifyr` setup where attrs = makeAttributes [("type", "password")] setup = modifier $ \(s, t) -> do attributes (always (Set attrs)) setInputValue s t event Input
avieth/reactive-dom
Reactive/DOM/Widget/Common.hs
bsd-3-clause
3,635
0
19
692
1,174
616
558
71
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} module Servant.API.ResponseHeadersSpec where import Test.Hspec import Servant.API.Header import Servant.API.ResponseHeaders spec :: Spec spec = describe "Servant.API.ResponseHeaders" $ do describe "addHeader" $ do it "adds a header to a value" $ do let val = addHeader "hi" 5 :: Headers '[Header "test" String] Int getHeaders val `shouldBe` [("test", "hi")] it "maintains the value" $ do let val = addHeader "hi" 5 :: Headers '[Header "test" String] Int getResponse val `shouldBe` 5 it "adds headers to the front of the list" $ do let val = addHeader 10 $ addHeader "b" 5 :: Headers '[Header "first" Int, Header "second" String] Int getHeaders val `shouldBe` [("first", "10"), ("second", "b")] describe "noHeader" $ do it "does not add a header" $ do let val = noHeader 5 :: Headers '[Header "test" Int] Int getHeaders val `shouldBe` []
zerobuzz/servant
servant/test/Servant/API/ResponseHeadersSpec.hs
bsd-3-clause
975
0
20
217
321
160
161
22
1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} module Language.KansasLava.Signal.Utils ( splitByte , debounce , nary , divideClk , counter , rotatorL , fromUnsigned , toUnsigned , parity , whenEnabled ) where import Language.KansasLava import Data.Sized.Matrix as Matrix import Data.Sized.Unsigned as Unsigned import Data.Bits splitByte :: (sig ~ Signal c) => sig (Unsigned X8) -> (sig (Unsigned X4), sig (Unsigned X4)) splitByte sig = (hi, lo) where mtx = fromUnsigned sig hi = toUnsigned . flip cropAt 4 $ mtx lo = toUnsigned . flip cropAt 0 $ mtx debounce :: forall c sig n. (Clock c, sig ~ Signal c, Size n) => Witness n -> sig Bool -> (sig Bool, sig Bool, sig Bool) debounce _ button = runRTL $ do -- Based on http://www.fpga4fun.com/Debouncer2.html counter <- newReg (0 :: Unsigned n) let counter_max = reg counter .==. maxBound toggle <- newReg False let idle = reg toggle ./=. button down = bitNot (reg toggle) .&&. bitNot idle .&&. counter_max up = reg toggle .&&. bitNot idle .&&. counter_max CASE [ IF idle $ do counter := 0 , OTHERWISE $ do counter := reg counter + 1 WHEN counter_max $ do toggle := bitNot (reg toggle) ] return (up, down, reg toggle) nary :: forall a clk sig n. (Clock clk, sig ~ Signal clk, Rep a, Size n, Rep n) => sig n -> Matrix n (sig a) -> sig a nary sel inps = pack inps .!. sel divideClk :: forall c sig ix. (Clock c, sig ~ Signal c, Size ix) => Witness ix -> sig Bool divideClk _ = counter high .==. (0 :: sig (Unsigned ix)) counter :: (Rep a, Num a, Bounded a, Eq a, Clock c, sig ~ Signal c) => sig Bool -> sig a counter inc = loop where reg = register 0 loop reg' = mux (reg .==. maxBound) (reg + 1, 0) loop = mux inc (reg, reg') rotatorL :: (Clock c, sig ~ Signal c, Size ix, Integral ix) => sig Bool -> Matrix ix (sig Bool) rotatorL step = fromUnsigned loop where reg = register 1 loop loop = mux step (reg, rotateL reg 1) fromUnsigned :: (sig ~ Signal c, Size ix) => sig (Unsigned ix) -> Matrix ix (sig Bool) fromUnsigned = unpack . coerce Unsigned.toMatrix toUnsigned :: (sig ~ Signal c, Size ix) => Matrix ix (sig Bool) -> sig (Unsigned ix) toUnsigned = coerce Unsigned.fromMatrix . pack parity :: forall clk n. (Clock clk, Size n, Rep n, Integral n, Enum n) => Signal clk (Unsigned n) -> Signal clk Bool parity x = foldr xor2 low $ map (testABit x . pureS) [minBound .. maxBound :: n] whenEnabled :: (Clock clk, Rep a) => Signal clk (Enabled a) -> (Signal clk a -> RTL s clk ()) -> RTL s clk () whenEnabled sig = CASE . return . match sig
gergoerdi/kansas-lava-papilio
src/Language/KansasLava/Signal/Utils.hs
bsd-3-clause
2,818
0
19
794
1,173
596
577
63
1
module UU.UUAGC (uuagc, uuagcMain, compile, module Options) where import Ag (uuagcLib, uuagcExe, compile) import Options import System.Exit (ExitCode(..)) uuagc :: [String] -> FilePath -> IO (ExitCode, [FilePath]) uuagc = uuagcLib uuagcMain :: IO () uuagcMain = uuagcExe
norm2782/uuagc
src/UU/UUAGC.hs
bsd-3-clause
274
0
9
40
100
61
39
8
1
{-# LANGUAGE OverloadedStrings #-} module VForth.LocationSpec where import qualified Data.Text as T import Data.Text.Arbitrary import TextShow import Data.Char(isSpace) import Test.Hspec import Test.QuickCheck import VForth newtype TestableLocation = TestableLocation Location instance Arbitrary TestableLocation where arbitrary = TestableLocation <$> ( newLocation <$> arbitrary <*> arbitrary ) instance Show TestableLocation where show (TestableLocation l) = "Location { title=\"" ++ show (title l) ++ "\", description=\"" ++ show (description l) ++ "\" }" newLocation :: Text -> Text -> Location newLocation titleText descText = Location { title = titleText , description = descText } spec :: Spec spec = do describe "Location Display" $ do it "Show puts title before dashes before a description" $ do showt (newLocation "My Title" "The complete description.") `shouldBe` "My Title\n--------\nThe complete description." it "Title should be included in showable output" $ property $ \(TestableLocation l) -> title l `T.isInfixOf` showt l it "Description should be included in showable output" $ property $ \(TestableLocation l) -> description l `T.isInfixOf` showt l it "Showable output is never blank" $ property $ \(TestableLocation l) -> (not . T.null . title $ l) && (not . T.null . description $ l) ==> any (not . isSpace) (T.unpack (showt l))
budgefeeney/ventureforth
chap4/test/VForth/LocationSpec.hs
bsd-3-clause
1,438
0
18
284
397
208
189
32
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE GADTs #-} module Test.IO.Tinfoil.Signing.Ed25519.Internal where import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.Text as T import Disorder.Core.IO (testIO) import Disorder.Core.Property (failWith) import P import System.IO import Test.QuickCheck import Test.QuickCheck.Instances () import Tinfoil.Data import Tinfoil.Signing.Ed25519.Internal prop_genKeyPair_len :: Property prop_genKeyPair_len = testIO $ do (PKey_Ed25519 pk, SKey_Ed25519 sk) <- genKeyPair pure $ (BS.length pk, BS.length sk) === (pubKeyLen, secKeyLen) prop_genKeyPair :: Property prop_genKeyPair = testIO $ do (pk1, sk1) <- genKeyPair (pk2, sk2) <- genKeyPair pure $ (pk1 == pk2, sk1 == sk2) === (False, False) -- Roundtrip test on the raw bindings. prop_signMessage' :: ByteString -> Property prop_signMessage' msg = testIO $ do (pk, sk) <- genKeyPair pure $ case signMessage' sk msg of Nothing' -> failWith $ "Unexpected failure signing: " <> T.pack (show msg) Just' sig -> (verifyMessage' pk sig msg) === Verified return [] tests :: IO Bool tests = $forAllProperties $ quickCheckWithResult (stdArgs { maxSuccess = 1000 } )
ambiata/tinfoil
test/Test/IO/Tinfoil/Signing/Ed25519/Internal.hs
bsd-3-clause
1,392
0
15
303
372
208
164
36
2
{-# LANGUAGE FlexibleInstances, GADTs, MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Matrix.ReflectorBase -- Copyright : Copyright (c) , Patrick Perry <patperry@stanford.edu> -- License : BSD3 -- Maintainer : Patrick Perry <patperry@stanford.edu> -- Stability : experimental -- module Data.Matrix.ReflectorBase where import Control.Monad import Control.Monad.Interleave import Control.Monad.ST import Foreign import Unsafe.Coerce import Data.Elem.BLAS import Data.Elem.LAPACK.C import Data.Vector.Dense import Data.Vector.Dense.ST( runSTVector ) import Data.Vector.Dense.Class import Data.Matrix.Dense.Class import Data.Matrix.Dense.ST( runSTMatrix ) import Data.Matrix.Class import Data.Tensor.Class import Data.Tensor.Class.MTensor( unsafeReadElem, unsafeWriteElem, unsafeModifyElem ) import Unsafe.BLAS( IOVector(..), IMatrix(..), MMatrix(..), ISolve(..), MSolve(..), unsafePerformIOWithVector, unsafeIOVectorToVector, unsafeSubvectorView, unsafeCopyVector, unsafeAxpyVector, unsafeGetDot, unsafeSubmatrixView, unsafeRowView, unsafeCopyMatrix, unsafeRank1UpdateMatrix, unsafeGetSSolveVector, unsafeGetSSolveMatrix ) -- | An elementary Housholder reflector. data Reflector nn e where Reflector :: (BLAS1 e) => Vector n e -> e -> Reflector (n,n) e coerceReflector :: Reflector np e -> Reflector np' e coerceReflector = unsafeCoerce {-# INLINE coerceReflector #-} hermReflector :: Reflector (n,p) e -> Reflector (p,n) e hermReflector (Reflector v tau) = Reflector v (conjugate tau) unsafeDoSApplyReflectorVector_ :: (WriteVector x m, BLAS1 e) => e -> Reflector (n,n) e -> x n e -> m () unsafeDoSApplyReflectorVector_ k (Reflector v tau) x | n == 0 = return () | n == 1 = unsafeModifyElem x 0 (\e -> (1-tau)*(k*e)) | otherwise = let x2 = unsafeSubvectorView x 1 (n-1) in do scaleBy k x x1 <- unsafeReadElem x 0 vx2 <- unsafeGetDot v x2 let alpha = -tau*(x1 + vx2) unsafeWriteElem x 0 (x1 + alpha) unsafeAxpyVector alpha v x2 where n = dim x {-# INLINE unsafeDoSApplyReflectorVector_ #-} unsafeDoSApplyReflectorMatrix_ :: (WriteMatrix a m, BLAS3 e) => e -> Reflector (n,n) e -> a (n,p) e -> m () unsafeDoSApplyReflectorMatrix_ k (Reflector v tau) a | n == 0 = return () | n == 1 = scaleBy ((1-tau)*k) a | otherwise = let a1 = unsafeRowView a 0 a2 = unsafeSubmatrixView a (1,0) (n-1,p) in do scaleBy k a z <- newCopyVector (conj a1) unsafeDoSApplyAddVector 1 (herm a2) v 1 z unsafeAxpyVector (-tau) (conj z) a1 unsafeRank1UpdateMatrix a2 (-tau) v z where (n,p) = shape a {-# INLINE unsafeDoSApplyReflectorMatrix_ #-} unsafeGetSApplyReflectorVector :: (ReadVector x m, WriteVector y m, BLAS1 e) => e -> Reflector (n,p) e -> x p e -> m (y n e) unsafeGetSApplyReflectorVector k r x = do x' <- newCopyVector x unsafeDoSApplyReflectorVector_ k (unsafeCoerce r) x' return $ unsafeCoerce x' unsafeGetSApplyReflectorMatrix :: (ReadMatrix a m, WriteMatrix b m, BLAS3 e) => e -> Reflector (n,p) e -> a (p,q) e -> m (b (n,q) e) unsafeGetSApplyReflectorMatrix k r a = do a' <- newCopyMatrix a unsafeDoSApplyReflectorMatrix_ k (unsafeCoerce r) a' return $ unsafeCoerce a' {-# INLINE unsafeGetSApplyReflectorMatrix #-} unsafeGetColReflector :: (WriteVector x m) => Reflector (n,p) e -> Int -> m (x n e) unsafeGetColReflector r@(Reflector _ _) j = do e <- newBasisVector (numRows r) j unsafeDoSApplyReflectorVector_ 1 (unsafeCoerce r) e return e {-# INLINE unsafeGetColReflector #-} -- | Compute an elementary reflector @H@ such that @H' x = beta e_1@. The -- reflector H is represented as @H = I - tau (1; v) (1; v)'@. The function -- sets the first element of @x@ to @beta@, sets the rest of the components -- to @v@, and returns @tau@. The function returns the resulting reflector, -- along with the value @beta@. Note that this is a destructive operation -- and that the returned object assumes ownership of the memory in @x@. setReflector :: (WriteVector x m, LAPACK e) => x n e -> m (Reflector (n,n) e, e) setReflector x | dim x == 0 = fail $ "setReflector <vector of dim 0>: dimension must be positive." setReflector x = unsafePerformIOWithVector x $ \(IOVector c n f p inc) -> let p1 = p `advancePtr` inc v = unsafeIOVectorToVector $ IOVector NoConj (n-1) f p1 inc in do when (c == Conj) $ doConjVector (IOVector c n f p inc) tau <- larfg n p p1 inc beta <- peek p touchForeignPtr f return $ (Reflector v tau, beta) {-# INLINE setReflector #-} -- | Get an elementary reflector @H@ that transforms the vector @x@ to be -- parallel with the first basis vector, along with value @(H' x)_1@. getReflector :: (ReadVector x m, LAPACK e) => x n e -> m (Reflector (n,n) e, e) getReflector x = unsafePerformIOWithVector x $ \x' -> do y <- newCopyVector x' setReflector y {-# INLINE getReflector #-} -- | Get an elementary reflector @H@ that transforms the vector @x@ to be -- parallel with the first basis vector, along with value @(H' x)_1@. reflector :: (LAPACK e) => Vector n e -> (Reflector (n,n) e, e) reflector x = runST $ getReflector x {-# INLINE reflector #-} instance Shaped Reflector (Int,Int) where shape (Reflector v _) = (n,n) where n = 1 + dim v {-# INLINE shape #-} bounds a = ((0,0),(n-1,n-1)) where (n,_) = shape a {-# INLINE bounds #-} instance MatrixShaped Reflector where instance HasHerm Reflector where herm = hermReflector {-# INLINE herm #-} instance IMatrix Reflector where unsafeSApplyVector alpha a x = runSTVector $ unsafeGetSApplyVector alpha a x {-# INLINE unsafeSApplyVector #-} unsafeSApplyMatrix alpha a b = runSTMatrix $ unsafeGetSApplyMatrix alpha a b {-# INLINE unsafeSApplyMatrix #-} unsafeCol a j = runSTVector $ unsafeGetCol a j {-# INLINE unsafeCol #-} unsafeRow a i = runSTVector $ unsafeGetRow a i {-# INLINE unsafeRow #-} instance (MonadInterleave m) => MMatrix Reflector m where unsafeGetSApplyVector = unsafeGetSApplyReflectorVector {-# INLINE unsafeGetSApplyVector #-} unsafeGetSApplyMatrix = unsafeGetSApplyReflectorMatrix {-# INLINE unsafeGetSApplyMatrix #-} unsafeDoSApplyVector_ = unsafeDoSApplyReflectorVector_ {-# INLINE unsafeDoSApplyVector_ #-} unsafeDoSApplyMatrix_ = unsafeDoSApplyReflectorMatrix_ {-# INLINE unsafeDoSApplyMatrix_ #-} unsafeGetCol = unsafeGetColReflector {-# INLINE unsafeGetCol #-} instance ISolve Reflector where unsafeSSolveVector alpha a x = runSTVector $ unsafeGetSSolveVector alpha a x {-# INLINE unsafeSSolveVector #-} unsafeSSolveMatrix alpha a b = runSTMatrix $ unsafeGetSSolveMatrix alpha a b {-# INLINE unsafeSSolveMatrix #-} instance (MonadInterleave m) => MSolve Reflector m where unsafeDoSSolveVector alpha a x y = do unsafeCopyVector (coerceVector y) x unsafeDoSApplyVector_ alpha (coerceReflector $ herm a) (coerceVector y) {-# INLINE unsafeDoSSolveVector #-} unsafeDoSSolveMatrix alpha a b c = do unsafeCopyMatrix (coerceMatrix c) b unsafeDoSApplyMatrix_ alpha (coerceReflector $ herm a) (coerceMatrix c) {-# INLINE unsafeDoSSolveMatrix #-}
patperry/lapack
lib/Data/Matrix/ReflectorBase.hs
bsd-3-clause
7,812
0
15
1,934
2,082
1,089
993
154
1
{-# LANGUAGE BangPatterns, CPP, MultiParamTypeClasses, TypeFamilies, FlexibleContexts #-} #if __GLASGOW_HASKELL__ >= 707 {-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-} #endif {-# OPTIONS_HADDOCK hide #-} -- | -- Module : Data.Vector.Unboxed.Base -- Copyright : (c) Roman Leshchinskiy 2009-2010 -- License : BSD-style -- -- Maintainer : Roman Leshchinskiy <rl@cse.unsw.edu.au> -- Stability : experimental -- Portability : non-portable -- -- Adaptive unboxed vectors: basic implementation -- module Data.Vector.Unboxed.Base ( MVector(..), IOVector, STVector, Vector(..), Unbox ) where import qualified Data.Vector.Generic as G import qualified Data.Vector.Generic.Mutable as M import qualified Data.Vector.Primitive as P import Control.DeepSeq ( NFData(rnf) ) import Control.Monad.Primitive import Control.Monad ( liftM ) import Data.Word ( Word8, Word16, Word32, Word64 ) import Data.Int ( Int8, Int16, Int32, Int64 ) import Data.Complex #if !MIN_VERSION_base(4,8,0) import Data.Word ( Word ) #endif #if __GLASGOW_HASKELL__ >= 707 import Data.Typeable ( Typeable ) #else import Data.Typeable ( Typeable1(..), Typeable2(..), mkTyConApp, mkTyCon3 ) #endif import Data.Data ( Data(..) ) -- Data.Vector.Internal.Check is unused #define NOT_VECTOR_MODULE #include "vector.h" data family MVector s a data family Vector a type IOVector = MVector RealWorld type STVector s = MVector s type instance G.Mutable Vector = MVector class (G.Vector Vector a, M.MVector MVector a) => Unbox a instance NFData (Vector a) where rnf !_ = () instance NFData (MVector s a) where rnf !_ = () -- ----------------- -- Data and Typeable -- ----------------- #if __GLASGOW_HASKELL__ >= 707 deriving instance Typeable Vector deriving instance Typeable MVector #else vectorTyCon = mkTyCon3 "vector" instance Typeable1 Vector where typeOf1 _ = mkTyConApp (vectorTyCon "Data.Vector.Unboxed" "Vector") [] instance Typeable2 MVector where typeOf2 _ = mkTyConApp (vectorTyCon "Data.Vector.Unboxed.Mutable" "MVector") [] #endif instance (Data a, Unbox a) => Data (Vector a) where gfoldl = G.gfoldl toConstr _ = error "toConstr" gunfold _ _ = error "gunfold" dataTypeOf _ = G.mkType "Data.Vector.Unboxed.Vector" dataCast1 = G.dataCast -- ---- -- Unit -- ---- newtype instance MVector s () = MV_Unit Int newtype instance Vector () = V_Unit Int instance Unbox () instance M.MVector MVector () where {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicOverlaps #-} {-# INLINE basicUnsafeNew #-} {-# INLINE basicInitialize #-} {-# INLINE basicUnsafeRead #-} {-# INLINE basicUnsafeWrite #-} {-# INLINE basicClear #-} {-# INLINE basicSet #-} {-# INLINE basicUnsafeCopy #-} {-# INLINE basicUnsafeGrow #-} basicLength (MV_Unit n) = n basicUnsafeSlice _ m (MV_Unit _) = MV_Unit m basicOverlaps _ _ = False basicUnsafeNew n = return (MV_Unit n) -- Nothing to initialize basicInitialize _ = return () basicUnsafeRead (MV_Unit _) _ = return () basicUnsafeWrite (MV_Unit _) _ () = return () basicClear _ = return () basicSet (MV_Unit _) () = return () basicUnsafeCopy (MV_Unit _) (MV_Unit _) = return () basicUnsafeGrow (MV_Unit n) m = return $ MV_Unit (n+m) instance G.Vector Vector () where {-# INLINE basicUnsafeFreeze #-} basicUnsafeFreeze (MV_Unit n) = return $ V_Unit n {-# INLINE basicUnsafeThaw #-} basicUnsafeThaw (V_Unit n) = return $ MV_Unit n {-# INLINE basicLength #-} basicLength (V_Unit n) = n {-# INLINE basicUnsafeSlice #-} basicUnsafeSlice _ m (V_Unit _) = V_Unit m {-# INLINE basicUnsafeIndexM #-} basicUnsafeIndexM (V_Unit _) _ = return () {-# INLINE basicUnsafeCopy #-} basicUnsafeCopy (MV_Unit _) (V_Unit _) = return () {-# INLINE elemseq #-} elemseq _ = seq -- --------------- -- Primitive types -- --------------- #define primMVector(ty,con) \ instance M.MVector MVector ty where { \ {-# INLINE basicLength #-} \ ; {-# INLINE basicUnsafeSlice #-} \ ; {-# INLINE basicOverlaps #-} \ ; {-# INLINE basicUnsafeNew #-} \ ; {-# INLINE basicInitialize #-} \ ; {-# INLINE basicUnsafeReplicate #-} \ ; {-# INLINE basicUnsafeRead #-} \ ; {-# INLINE basicUnsafeWrite #-} \ ; {-# INLINE basicClear #-} \ ; {-# INLINE basicSet #-} \ ; {-# INLINE basicUnsafeCopy #-} \ ; {-# INLINE basicUnsafeGrow #-} \ ; basicLength (con v) = M.basicLength v \ ; basicUnsafeSlice i n (con v) = con $ M.basicUnsafeSlice i n v \ ; basicOverlaps (con v1) (con v2) = M.basicOverlaps v1 v2 \ ; basicUnsafeNew n = con `liftM` M.basicUnsafeNew n \ ; basicInitialize (con v) = M.basicInitialize v \ ; basicUnsafeReplicate n x = con `liftM` M.basicUnsafeReplicate n x \ ; basicUnsafeRead (con v) i = M.basicUnsafeRead v i \ ; basicUnsafeWrite (con v) i x = M.basicUnsafeWrite v i x \ ; basicClear (con v) = M.basicClear v \ ; basicSet (con v) x = M.basicSet v x \ ; basicUnsafeCopy (con v1) (con v2) = M.basicUnsafeCopy v1 v2 \ ; basicUnsafeMove (con v1) (con v2) = M.basicUnsafeMove v1 v2 \ ; basicUnsafeGrow (con v) n = con `liftM` M.basicUnsafeGrow v n } #define primVector(ty,con,mcon) \ instance G.Vector Vector ty where { \ {-# INLINE basicUnsafeFreeze #-} \ ; {-# INLINE basicUnsafeThaw #-} \ ; {-# INLINE basicLength #-} \ ; {-# INLINE basicUnsafeSlice #-} \ ; {-# INLINE basicUnsafeIndexM #-} \ ; {-# INLINE elemseq #-} \ ; basicUnsafeFreeze (mcon v) = con `liftM` G.basicUnsafeFreeze v \ ; basicUnsafeThaw (con v) = mcon `liftM` G.basicUnsafeThaw v \ ; basicLength (con v) = G.basicLength v \ ; basicUnsafeSlice i n (con v) = con $ G.basicUnsafeSlice i n v \ ; basicUnsafeIndexM (con v) i = G.basicUnsafeIndexM v i \ ; basicUnsafeCopy (mcon mv) (con v) = G.basicUnsafeCopy mv v \ ; elemseq _ = seq } newtype instance MVector s Int = MV_Int (P.MVector s Int) newtype instance Vector Int = V_Int (P.Vector Int) instance Unbox Int primMVector(Int, MV_Int) primVector(Int, V_Int, MV_Int) newtype instance MVector s Int8 = MV_Int8 (P.MVector s Int8) newtype instance Vector Int8 = V_Int8 (P.Vector Int8) instance Unbox Int8 primMVector(Int8, MV_Int8) primVector(Int8, V_Int8, MV_Int8) newtype instance MVector s Int16 = MV_Int16 (P.MVector s Int16) newtype instance Vector Int16 = V_Int16 (P.Vector Int16) instance Unbox Int16 primMVector(Int16, MV_Int16) primVector(Int16, V_Int16, MV_Int16) newtype instance MVector s Int32 = MV_Int32 (P.MVector s Int32) newtype instance Vector Int32 = V_Int32 (P.Vector Int32) instance Unbox Int32 primMVector(Int32, MV_Int32) primVector(Int32, V_Int32, MV_Int32) newtype instance MVector s Int64 = MV_Int64 (P.MVector s Int64) newtype instance Vector Int64 = V_Int64 (P.Vector Int64) instance Unbox Int64 primMVector(Int64, MV_Int64) primVector(Int64, V_Int64, MV_Int64) newtype instance MVector s Word = MV_Word (P.MVector s Word) newtype instance Vector Word = V_Word (P.Vector Word) instance Unbox Word primMVector(Word, MV_Word) primVector(Word, V_Word, MV_Word) newtype instance MVector s Word8 = MV_Word8 (P.MVector s Word8) newtype instance Vector Word8 = V_Word8 (P.Vector Word8) instance Unbox Word8 primMVector(Word8, MV_Word8) primVector(Word8, V_Word8, MV_Word8) newtype instance MVector s Word16 = MV_Word16 (P.MVector s Word16) newtype instance Vector Word16 = V_Word16 (P.Vector Word16) instance Unbox Word16 primMVector(Word16, MV_Word16) primVector(Word16, V_Word16, MV_Word16) newtype instance MVector s Word32 = MV_Word32 (P.MVector s Word32) newtype instance Vector Word32 = V_Word32 (P.Vector Word32) instance Unbox Word32 primMVector(Word32, MV_Word32) primVector(Word32, V_Word32, MV_Word32) newtype instance MVector s Word64 = MV_Word64 (P.MVector s Word64) newtype instance Vector Word64 = V_Word64 (P.Vector Word64) instance Unbox Word64 primMVector(Word64, MV_Word64) primVector(Word64, V_Word64, MV_Word64) newtype instance MVector s Float = MV_Float (P.MVector s Float) newtype instance Vector Float = V_Float (P.Vector Float) instance Unbox Float primMVector(Float, MV_Float) primVector(Float, V_Float, MV_Float) newtype instance MVector s Double = MV_Double (P.MVector s Double) newtype instance Vector Double = V_Double (P.Vector Double) instance Unbox Double primMVector(Double, MV_Double) primVector(Double, V_Double, MV_Double) newtype instance MVector s Char = MV_Char (P.MVector s Char) newtype instance Vector Char = V_Char (P.Vector Char) instance Unbox Char primMVector(Char, MV_Char) primVector(Char, V_Char, MV_Char) -- ---- -- Bool -- ---- fromBool :: Bool -> Word8 {-# INLINE fromBool #-} fromBool True = 1 fromBool False = 0 toBool :: Word8 -> Bool {-# INLINE toBool #-} toBool 0 = False toBool _ = True newtype instance MVector s Bool = MV_Bool (P.MVector s Word8) newtype instance Vector Bool = V_Bool (P.Vector Word8) instance Unbox Bool instance M.MVector MVector Bool where {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicOverlaps #-} {-# INLINE basicUnsafeNew #-} {-# INLINE basicInitialize #-} {-# INLINE basicUnsafeReplicate #-} {-# INLINE basicUnsafeRead #-} {-# INLINE basicUnsafeWrite #-} {-# INLINE basicClear #-} {-# INLINE basicSet #-} {-# INLINE basicUnsafeCopy #-} {-# INLINE basicUnsafeGrow #-} basicLength (MV_Bool v) = M.basicLength v basicUnsafeSlice i n (MV_Bool v) = MV_Bool $ M.basicUnsafeSlice i n v basicOverlaps (MV_Bool v1) (MV_Bool v2) = M.basicOverlaps v1 v2 basicUnsafeNew n = MV_Bool `liftM` M.basicUnsafeNew n basicInitialize (MV_Bool v) = M.basicInitialize v basicUnsafeReplicate n x = MV_Bool `liftM` M.basicUnsafeReplicate n (fromBool x) basicUnsafeRead (MV_Bool v) i = toBool `liftM` M.basicUnsafeRead v i basicUnsafeWrite (MV_Bool v) i x = M.basicUnsafeWrite v i (fromBool x) basicClear (MV_Bool v) = M.basicClear v basicSet (MV_Bool v) x = M.basicSet v (fromBool x) basicUnsafeCopy (MV_Bool v1) (MV_Bool v2) = M.basicUnsafeCopy v1 v2 basicUnsafeMove (MV_Bool v1) (MV_Bool v2) = M.basicUnsafeMove v1 v2 basicUnsafeGrow (MV_Bool v) n = MV_Bool `liftM` M.basicUnsafeGrow v n instance G.Vector Vector Bool where {-# INLINE basicUnsafeFreeze #-} {-# INLINE basicUnsafeThaw #-} {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicUnsafeIndexM #-} {-# INLINE elemseq #-} basicUnsafeFreeze (MV_Bool v) = V_Bool `liftM` G.basicUnsafeFreeze v basicUnsafeThaw (V_Bool v) = MV_Bool `liftM` G.basicUnsafeThaw v basicLength (V_Bool v) = G.basicLength v basicUnsafeSlice i n (V_Bool v) = V_Bool $ G.basicUnsafeSlice i n v basicUnsafeIndexM (V_Bool v) i = toBool `liftM` G.basicUnsafeIndexM v i basicUnsafeCopy (MV_Bool mv) (V_Bool v) = G.basicUnsafeCopy mv v elemseq _ = seq -- ------- -- Complex -- ------- newtype instance MVector s (Complex a) = MV_Complex (MVector s (a,a)) newtype instance Vector (Complex a) = V_Complex (Vector (a,a)) instance (RealFloat a, Unbox a) => Unbox (Complex a) instance (RealFloat a, Unbox a) => M.MVector MVector (Complex a) where {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicOverlaps #-} {-# INLINE basicUnsafeNew #-} {-# INLINE basicInitialize #-} {-# INLINE basicUnsafeReplicate #-} {-# INLINE basicUnsafeRead #-} {-# INLINE basicUnsafeWrite #-} {-# INLINE basicClear #-} {-# INLINE basicSet #-} {-# INLINE basicUnsafeCopy #-} {-# INLINE basicUnsafeGrow #-} basicLength (MV_Complex v) = M.basicLength v basicUnsafeSlice i n (MV_Complex v) = MV_Complex $ M.basicUnsafeSlice i n v basicOverlaps (MV_Complex v1) (MV_Complex v2) = M.basicOverlaps v1 v2 basicUnsafeNew n = MV_Complex `liftM` M.basicUnsafeNew n basicInitialize (MV_Complex v) = M.basicInitialize v basicUnsafeReplicate n (x :+ y) = MV_Complex `liftM` M.basicUnsafeReplicate n (x,y) basicUnsafeRead (MV_Complex v) i = uncurry (:+) `liftM` M.basicUnsafeRead v i basicUnsafeWrite (MV_Complex v) i (x :+ y) = M.basicUnsafeWrite v i (x,y) basicClear (MV_Complex v) = M.basicClear v basicSet (MV_Complex v) (x :+ y) = M.basicSet v (x,y) basicUnsafeCopy (MV_Complex v1) (MV_Complex v2) = M.basicUnsafeCopy v1 v2 basicUnsafeMove (MV_Complex v1) (MV_Complex v2) = M.basicUnsafeMove v1 v2 basicUnsafeGrow (MV_Complex v) n = MV_Complex `liftM` M.basicUnsafeGrow v n instance (RealFloat a, Unbox a) => G.Vector Vector (Complex a) where {-# INLINE basicUnsafeFreeze #-} {-# INLINE basicUnsafeThaw #-} {-# INLINE basicLength #-} {-# INLINE basicUnsafeSlice #-} {-# INLINE basicUnsafeIndexM #-} {-# INLINE elemseq #-} basicUnsafeFreeze (MV_Complex v) = V_Complex `liftM` G.basicUnsafeFreeze v basicUnsafeThaw (V_Complex v) = MV_Complex `liftM` G.basicUnsafeThaw v basicLength (V_Complex v) = G.basicLength v basicUnsafeSlice i n (V_Complex v) = V_Complex $ G.basicUnsafeSlice i n v basicUnsafeIndexM (V_Complex v) i = uncurry (:+) `liftM` G.basicUnsafeIndexM v i basicUnsafeCopy (MV_Complex mv) (V_Complex v) = G.basicUnsafeCopy mv v elemseq _ (x :+ y) z = G.elemseq (undefined :: Vector a) x $ G.elemseq (undefined :: Vector a) y z -- ------ -- Tuples -- ------ #define DEFINE_INSTANCES #include "unbox-tuple-instances"
sergv/vector
Data/Vector/Unboxed/Base.hs
bsd-3-clause
14,519
0
9
3,602
3,335
1,767
1,568
-1
-1
module Database.HypherGraph.Utils ( stats ) where -- stats :: IO Int stats = undefined
tolysz/hypergraph-store
src/Database/HypherGraph/Utils.hs
bsd-3-clause
93
0
4
20
18
12
6
3
1
import Computation import Control.Applicative import Control.Monad import Data.Char import Implementation.Cryptodev import Parser import PPrint import SuiteB import System.Environment import System.Exit import System.IO import Test.AES import Transducer main = getArgs >>= mapM_ (runAndReport . checkRoundtrip) runAndReport = runComputation >=> either (hPutStrLn stderr) (\_ -> return ()) readFile' = reifyIOException "Couldn't open" . readFile writeFile' = (reifyIOException "Couldn't open" .) . writeFile parseVectors' f s = case parseVectors s of (v, []) -> return v (_, e:_) -> throwError $ f ++ "\n" ++ show e processFile :: FilePath -> Computation IO () processFile f = do s <- readFile' f v <- parseVectors' f s v' <- runTransformer test implementation v writeFile' (f ++ ".out") (pprint v') normalizeNewlines ('\r':'\n':rest) = '\n':normalizeNewlines rest normalizeNewlines (c:rest) = c:normalizeNewlines rest normalizeNewlines [] = [] normalizeRepeats (x:y:rest) | isSpace x && isSpace y && x == y = normalizeRepeats (y:rest) normalizeRepeats (c:rest) = c:normalizeRepeats rest normalizeRepeats [] = [] normalizeEndlineSpace (' ':xs) = case span (==' ') xs of (ws, '\n':rest) -> '\n':normalizeEndlineSpace rest (ws, rest) -> " " ++ ws ++ normalizeEndlineSpace rest normalizeEndlineSpace (x:xs) = x : normalizeEndlineSpace xs normalizeEndlineSpace [] = [] -- TODO: move this closer and closer to id normalize = normalizeEndlineSpace . normalizeNewlines closeEnough a b = normalize a == normalize b checkRoundtrip :: FilePath -> Computation IO () checkRoundtrip f = do s <- readFile' f s' <- pprint <$> parseVectors' f s unless (closeEnough s s') $ do writeFile' "out" s' throwError $ f ++ "\n\tdoesn't roundtrip; output written to out" checkParse :: FilePath -> Computation IO () checkParse f = readFile' f >>= parseVectors' f >> return ()
GaloisInc/hacrypto
calf/bin/Main.hs
bsd-3-clause
1,883
9
11
307
702
350
352
48
2
{-# LANGUAGE PatternGuards, ViewPatterns, NamedFieldPuns #-} module Converter ( convert ) where import Parse import Smart (TaskChan, restart, interp) import Result (hasError) import Html import Lang import Args import Hash import qualified Language.Haskell.Exts.Pretty as HPty import qualified Language.Haskell.Exts.Syntax as HSyn import Text.XHtml.Strict hiding (lang) import Text.Pandoc import System.Process (readProcessWithExitCode) import System.Cmd import System.FilePath import System.Exit import System.Directory (getTemporaryDirectory, getModificationTime, doesFileExist, getTemporaryDirectory, createDirectoryIfMissing) --import Data.Time (diffUTCTime) import Control.Monad import Data.List import Data.Char hiding (Format) ---------------------------------- convert :: TaskChan -> Args -> String -> IO () convert ghci args@(Args {magicname, sourcedir, gendir, recompilecmd, verbose}) what = do whenOutOfDate () output input $ do whenOutOfDate () object input $ do when (verbose > 0) $ putStrLn $ object ++ " is out of date, regenerating" -- x <- system $ recompilecmd ++ " " ++ input let (ghc:args) = words recompilecmd -- !!! (x, out, err) <- readProcessWithExitCode ghc (args ++ [input]) "" if x == ExitSuccess then do restart ghci return () else fail $ unlines [unwords [recompilecmd, input], show x, out, err] when (verbose > 0) $ putStrLn $ output ++ " is out of date, regenerating" mainParse HaskellMode input >>= extract HaskellMode (verbose > 0) ghci args what where input = sourcedir </> what <.> "lhs" output = gendir </> what <.> "xml" object = sourcedir </> what <.> "o" extract :: ParseMode -> Bool -> TaskChan -> Args -> Language -> Doc -> IO () extract mode verbose ghci (Args {lang, templatedir, sourcedir, exercisedir, gendir, magicname}) what (Doc meta modu ss) = do writeEx (what <.> ext) [showEnv mode $ importsHiding []] ss' <- zipWithM processBlock [1..] $ preprocessForSlides ss ht <- readFile' $ templatedir </> lang' ++ ".template" putStrLn $ "Lang is:" ++ lang' writeFile' (gendir </> what <.> "xml") $ flip writeHtmlString (Pandoc meta $ concat ss') $ def { writerStandalone = True , writerTableOfContents = True , writerSectionDivs = True , writerTemplate = ht } where ext = case mode of HaskellMode -> "hs" lang' = case span (/= '_') . reverse $ what of (l, "") -> lang (l, _) | length l > 2 -> lang (x, _) -> reverse x writeEx f l = writeFile' (exercisedir </> f) $ intercalate delim l writeFile' f s = do when verbose $ putStrLn $ f ++ " is written." createDirectoryIfMissing True (dropFileName f) writeFile f s readFile' f = do when verbose $ putStrLn $ f ++ " is to read..." readFile f system' s = do when verbose $ putStrLn $ "executing " ++ s system s importsHiding funnames = case modu of HaskellModule (HSyn.Module loc (HSyn.ModuleName modname) directives _ _ imps _) -> HPty.prettyPrint $ HSyn.Module loc (HSyn.ModuleName "") directives Nothing Nothing ([mkImport modname funnames, mkImport_ ('X':magicname) modname] ++ imps) [] -- _ -> error "error in Converter.extract" mkCodeBlock l = [ CodeBlock ("", ["haskell"], []) $ intercalate "\n" l | not $ null l ] ---------------------------- -- todo: processBlock :: Int -> BBlock -> IO (Either Html [Block]) -- hogy a hibákhoz lehessen rendes html oldalt generálni -- vagy a Resulthoz jobb show-t írni processBlock :: Int -> BBlock -> IO [Block] processBlock _ (Exercise visihidden _ _ funnames is) | null funnames || null is = return $ mkCodeBlock $ visihidden processBlock _ (Exercise _ visi hidden funnames is) = do let i = show $ mkHash $ unlines funnames j = "_j" ++ i fn = what ++ "_" ++ i <.> ext (static_, inForm, rows) = if null hidden then ([], visi, length visi) else (visi, [], 2 + length hidden) writeEx fn [ showEnv mode $ importsHiding funnames ++ "\n" ++ unlines static_ , unlines $ hidden, show $ map parseQuickCheck is, j, i , show funnames ] return $ mkCodeBlock static_ ++ showBlockSimple lang' fn i rows (intercalate "\n" inForm) processBlock ii (OneLineExercise 'H' correct exp) = return [] processBlock ii (OneLineExercise p correct exp) = do let m5 = mkHash $ show ii ++ exp i = show m5 fn = what ++ (if p == 'R' then "_" ++ i else "") <.> ext act = getOne "eval" fn i i when (p == 'R') $ writeEx fn [showEnv mode $ importsHiding [], "\n" ++ magicname ++ " = " ++ exp] when verbose $ putStrLn $ "interpreting " ++ exp result <- if p `elem` ['F', 'R'] then return Nothing else do result <- interp False m5 lang' ghci (exercisedir </> fn) exp Nothing when (correct == hasError [result]) $ error $ translate lang' "Erroneous evaluation" ++ ": " ++ exp ++ " ; " ++ showHtmlFragment (renderResult result) return $ Just result return [rawHtml $ showHtmlFragment $ showInterpreter lang' 60 act i p exp result] processBlock _ (Text (CodeBlock ("",[t],[]) l)) | t `elem` ["dot","neato","twopi","circo","fdp","dfdp","latex"] = do tmpdir <- getTemporaryDirectory let i = show $ mkHash $ t ++ l fn = what ++ i imgname = takeFileName fn <.> "png" outfile = gendir </> fn <.> "png" tmpfile = tmpdir </> takeFileName fn <.> if t=="latex" then "tex" else t writeFile' tmpfile $ unlines $ case t of "latex" -> [ "\\documentclass{article}" , "\\usepackage{ucs}" , "\\usepackage[utf8x]{inputenc}" , "\\usepackage{amsmath}" , "\\pagestyle{empty}" -- , "\\newcommand{\\cfrac}[2]{\\displaystyle\\frac{#1}{#2}}" , "\\begin{document}" , "$$", l, "$$" , "\\end{document}" ] _ -> ["digraph G {", l, "}"] createDirectoryIfMissing True (dropFileName outfile) x <- system' $ unwords $ case t of "latex" -> [ "(", "cd", dropFileName tmpfile, "&&" , "latex -halt-on-error", takeFileName tmpfile, "2>&1 >/dev/null", ")" , "&&", "(", "dvipng -D 150 -T tight", "-o", outfile , replaceExtension tmpfile "dvi", "2>&1 >/dev/null",")"] _ -> [ t, "-Tpng", "-o", outfile, tmpfile, "2>&1 >/dev/null" ] if x == ExitSuccess then return [Para [Image ("", [], []) [Str imgname] (imgname, "")]] else fail $ "processDot " ++ tmpfile ++ "; " ++ show x processBlock _ (Text l) = return [l] --------------------------------- preprocessForSlides :: [BBlock] -> [BBlock] preprocessForSlides x = case span (not . isLim) x of (a, []) -> a (a, b) -> a ++ case span (not . isHeader) b of (c, d) -> [Text $ rawHtml "<div class=\"handout\">"] ++ c ++ [Text $ rawHtml "</div>"] ++ preprocessForSlides d where isLim (Text HorizontalRule) = True isLim _ = False isHeader (Text (Header {})) = True isHeader _ = False ------------------------------------ rawHtml :: String -> Block rawHtml x = RawBlock (Format "html") x showBlockSimple :: Language -> String -> String -> Int -> String -> [Block] showBlockSimple lang fn i rows_ cont = (:[]) $ rawHtml $ showHtmlFragment $ indent $ [ form ! [ theclass $ if null cont then "interpreter" else "resetinterpreter" , action $ getOne "check" fn i i ] <<[ textarea ! [ cols "80" , rows $ show rows_ , identifier $ "tarea" ++ i ] << cont , br , input ! [thetype "submit", value $ translate lang "Check"] ] , thediv ! [theclass "answer", identifier $ "res" ++ i] << "" ] ----------------- showEnv :: ParseMode -> String -> String showEnv HaskellMode prelude = "{-# LINE 1 \"testenv\" #-}\n" ++ prelude ++ "\n{-# LINE 1 \"input\" #-}\n" mkImport :: String -> [Name] -> HSyn.ImportDecl mkImport m d = HSyn.ImportDecl { HSyn.importLoc = undefined , HSyn.importModule = HSyn.ModuleName m , HSyn.importQualified = False , HSyn.importSrc = False , HSyn.importPkg = Nothing , HSyn.importAs = Nothing , HSyn.importSpecs = Just (True, map (HSyn.IVar . mkName) d) , HSyn.importSafe = False } mkName :: String -> HSyn.Name mkName n@(c:_) | isLetter c = HSyn.Ident n mkName n = HSyn.Symbol n mkImport_ :: String -> String -> HSyn.ImportDecl mkImport_ magic m = (mkImport m []) { HSyn.importQualified = True, HSyn.importAs = Just $ HSyn.ModuleName magic } ------------------ whenOutOfDate :: b -> FilePath -> FilePath -> IO b -> IO b whenOutOfDate def x src m = do a <- modTime x b <- modTime src case (a, b) of (Nothing, Just _) -> m (Just t1, Just t2) | t1 < t2 -> m _ -> return def where modTime f = do a <- doesFileExist f if a then fmap Just $ getModificationTime f else return Nothing --------------------
pgj/ActiveHs
Converter.hs
bsd-3-clause
9,925
0
23
3,164
3,075
1,604
1,471
201
15
import XMonad import XMonad.Hooks.DynamicLog (dynamicLogWithPP, xmobarPP, ppOutput, ppCurrent, ppVisible, ppHidden, ppHiddenNoWindows, ppTitle, ppLayout, ppSep, ppOrder, ppExtras, xmobarColor, wrap, shorten, xmobar) import XMonad.Actions.SpawnOn import XMonad.Layout.NoBorders (smartBorders) import XMonad.Layout.Named import XMonad.Operations (refresh) import XMonad.Hooks.ManageDocks (avoidStruts, manageDocks, docks) import XMonad.Util.Run (spawnPipe) import qualified XMonad.StackSet as W import XMonad.Actions.CycleWS import XMonad.Actions.Submap import XMonad.Util.NamedScratchpad import XMonad.Actions.DynamicWorkspaces import XMonad.Prompt import Control.Monad import Data.Map (union, fromList) import Data.Maybe (isNothing) import System.IO (hPutStrLn) myWorkspaces = map show [1..9] mySP = ["NSP"] myKeys conf@(XConfig {modMask = modm}) = fromList $ [ ((modm, xK_z), spawn "slock") -- keybindings for workspaces , ((modm, xK_a), toggleSkip mySP) , ((modm, xK_s), swapNextScreen >> nextScreen) , ((modm, xK_Right), moveTo Next (WSIs $ allWS [notSP, hiddenWS])) , ((modm, xK_Left), moveTo Prev (WSIs $ allWS [notSP, hiddenWS])) , ((modm .|. shiftMask, xK_Right), shiftTo Next (WSIs notSP) >> moveTo Next (WSIs notSP)) , ((modm .|. shiftMask, xK_Left), shiftTo Prev (WSIs notSP) >> moveTo Prev (WSIs notSP)) , ((modm, xK_f), moveTo Next (WSIs $ allWS [notSP, emptyWS])) , ((modm .|. shiftMask, xK_f), shiftTo Next (WSIs $ allWS [notSP, emptyWS])) -- keybindings for stacked workspaces , ((modm, xK_grave), submap . fromList $ [ ((modm, xK_grave), selectWorkspace defaultXPConfig) , ((modm, xK_Tab), withWorkspace defaultXPConfig (\t -> (windows . W.shift $ t) >> (windows . W.view $ t))) , ((modm, xK_r), removeEmptyWorkspace >> moveTo Next (WSIs $ allWS [notSP, hiddenWS])) ]) , ((modm, xK_c), namedScratchpadAction myScratchpads "term") , ((0 , 0x1008FF11), spawn "amixer set Master 2-") , ((modm, xK_d ), spawn "amixer set Master 2-") , ((0 , 0x1008FF13), spawn "amixer set Master 2+") , ((modm, xK_u ), spawn "amixer set Master 2+") , ((0 , 0x1008FF12), spawn "bash ~/.xmonad/volume_mute_toggle.sh") , ((0 , 0x1008FFA9), spawn "touchpad-toggle") , ((0 , 0x1008FF02), spawn "xbacklight +10") , ((0 , 0x1008FF03), spawn "xbacklight -10") ] where toggleSkip :: [WorkspaceId] -> X () toggleSkip skips = do hs <- gets (flip skipTags skips . W.hidden . windowset) unless (null hs) (windows . W.view . W.tag $ head hs) hiddenWS :: X (WindowSpace -> Bool) hiddenWS = do hs <- gets (map W.tag . W.hidden . windowset) return (\ws -> W.tag ws `elem` hs) emptyWS :: X (WindowSpace -> Bool) emptyWS = return (isNothing . W.stack) notSP :: X (WindowSpace -> Bool) notSP = return ((`notElem` mySP) . W.tag) allWS :: [X (WindowSpace -> Bool)] -> X (WindowSpace -> Bool) allWS = (liftM foldPreds) . (mapM id) where foldPreds :: [a -> Bool] -> (a -> Bool) foldPreds (p:tail) = (\v -> (p v) && (foldPreds tail) v) foldPreds [] = (\x -> True) myScratchpads = [ NS "term" spawnTerm findTerm myFloat ] where spawnTerm = "gnome-terminal --hide-menubar --role=scratchpad" role = stringProperty "WM_WINDOW_ROLE" findTerm = role =? "scratchpad" myFloat = customFloating $ W.RationalRect l t w h where h = 0.25 -- terminal height w = 0.75 -- terminal width t = 1 - h - h/2 -- distance from top edge l = (1 - w)/2 -- distance from left edge myFocusedBorderColor = "#0080FF" myNormalBorderColor = "#753200" myStartupHook :: X () myStartupHook = do spawnOn "1" "/home/mark/.xmonad/startup.sh" myLogHook proc = dynamicLogWithPP $ xmobarPP { ppOutput = hPutStrLn proc , ppSep = " " , ppOrder = (\(ws:l:t:e:_) -> [l ++ e, ws, t]) , ppCurrent = currentStyle , ppVisible = visibleStyle , ppHidden = hiddenStyle . noScratchPad , ppHiddenNoWindows = hiddenNoWinStyle . noScratchPad , ppTitle = titleStyle , ppLayout = (xmobarColor "#404040" "#202020") . (wrap "[" "") . (\layout -> case layout of "Tall" -> "|" "Mirror Tall" -> "-" "LaTeX" -> "L" -- "ThreeCol" -> "3Col" -- "Mirror ThreeCol" -> "Mirror 3Col" "Full" -> "#" x -> "Error parsing (see xmonad.hs): " ++ x ) , ppExtras = [logTitles] } where currentStyle = xmobarColor "yellow" "" visibleStyle = xmobarColor "#717700" "" hiddenStyle = xmobarColor "grey" "" hiddenNoWinStyle = xmobarColor "#202020" "" titleStyle = xmobarColor "#008000" "" . shorten 130 . filterCurly filterCurly = filter (not . isCurly) isCurly x = x == '{' || x == '}' logTitles = do winset <- gets windowset let numWins = length $ W.index winset let color = xmobarColor "#7a0000" "#202020" let sep = xmobarColor "#404040" "#202020" "]" return $ Just $ color $ show numWins ++ sep noScratchPad ws = if ws `elem` mySP then "" else ws myLayoutHook = avoidStruts $ smartBorders $ -- (tiled ||| Mirror tiled ||| threeCol ||| Mirror threeCol ||| Full) -- (tiled ||| Mirror tiled ||| latexTiled ||| Full) (tiled ||| Mirror tiled ||| latexTiled ||| Full) where tiled = Tall nmaster delta ratio latexTiled = named "LaTeX" (Tall nmaster delta latexRatio) nmaster = 1 delta = 3/100 ratio = 1/2 latexRatio = 63/100 myManageHook = manageDocks <+> manageHook defaultConfig <+> namedScratchpadManageHook myScratchpads myConfig logHandle = defaultConfig { -- automount, desktop background, systray startupHook = myStartupHook, -- terminal terminal = "/usr/bin/konsole", -- workspace names workspaces = myWorkspaces, -- keyBindings modMask = mod4Mask, -- use the windows key for mod key keys = \c -> myKeys c `union` keys defaultConfig c, -- xmobar logHook = myLogHook logHandle, manageHook = myManageHook, layoutHook = myLayoutHook, -- window border color focusedBorderColor = myFocusedBorderColor, normalBorderColor = myNormalBorderColor } main = do xmobar <- spawnPipe "xmobar" xmonad $ docks $ myConfig xmobar
mark-i-m/dotfilesvm
wm/.xmonad/xmonad.hs
mit
6,631
12
18
1,784
2,034
1,131
903
136
6
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} module Coinbase.Exchange.Private ( getAccountList , getAccount , getAccountLedger , getAccountHolds , createOrder , cancelOrder , cancelAllOrders , getOrderList , getOrder , getFills , createTransfer , createCryptoWithdrawal , createReport , getReportStatus , module Coinbase.Exchange.Types.Private ) where import Control.Monad.Except import Control.Monad.Reader import Control.Monad.Trans.Resource import Data.Char import Data.List import qualified Data.Text as T import Data.UUID import Coinbase.Exchange.Rest import Coinbase.Exchange.Types import Coinbase.Exchange.Types.Core import Coinbase.Exchange.Types.Private -- Accounts getAccountList :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => m [Account] getAccountList = coinbaseGet True "/accounts" voidBody getAccount :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => AccountId -> m Account getAccount (AccountId i) = coinbaseGet True ("/accounts/" ++ toString i) voidBody getAccountLedger :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => AccountId -> m [Entry] getAccountLedger (AccountId i) = coinbaseGet True ("/accounts/" ++ toString i ++ "/ledger") voidBody getAccountHolds :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => AccountId -> m [Hold] getAccountHolds (AccountId i) = coinbaseGet True ("/accounts/" ++ toString i ++ "/holds") voidBody -- Orders createOrder :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => NewOrder -> m OrderId createOrder = liftM ocId . coinbasePost True "/orders" . Just cancelOrder :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => OrderId -> m () cancelOrder (OrderId o) = coinbaseDeleteDiscardBody True ("/orders/" ++ toString o) voidBody cancelAllOrders :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => Maybe ProductId -> m [OrderId] cancelAllOrders prodId = coinbaseDelete True ("/orders" ++ opt prodId) voidBody where opt Nothing = "" opt (Just id) = "?product_id=" ++ T.unpack (unProductId id) getOrderList :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => [OrderStatus] -> m [Order] getOrderList os = coinbaseGet True ("/orders?" ++ query os) voidBody where query [] = "status=open&status=pending&status=active" query xs = intercalate "&" $ map (\x -> "status=" ++ map toLower (show x)) xs getOrder :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => OrderId -> m Order getOrder (OrderId o) = coinbaseGet True ("/orders/" ++ toString o) voidBody -- Fills getFills :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => Maybe OrderId -> Maybe ProductId -> m [Fill] getFills moid mpid = coinbaseGet True ("/fills?" ++ oid ++ "&" ++ pid) voidBody where oid = case moid of Just v -> "order_id=" ++ toString (unOrderId v) Nothing -> "" pid = case mpid of Just v -> "product_id=" ++ T.unpack (unProductId v) Nothing -> "" -- Transfers createTransfer :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => TransferToCoinbase -> m TransferToCoinbaseResponse createTransfer = coinbasePost True "/transfers" . Just createCryptoWithdrawal :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => CryptoWithdrawal -> m CryptoWithdrawalResp createCryptoWithdrawal = coinbasePost True "/withdrawals/crypto" . Just -- Reports createReport :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => ReportRequest -> m ReportInfo createReport = coinbasePost True "/reports" . Just getReportStatus :: (MonadResource m, MonadReader ExchangeConf m, MonadError ExchangeFailure m) => ReportId -> m ReportInfo getReportStatus (ReportId r) = coinbaseGet True ("/reports/" ++ toString r) voidBody
AndrewRademacher/coinbase-exchange
src/Coinbase/Exchange/Private.hs
mit
4,477
0
14
1,013
1,208
633
575
82
3
{-# OPTIONS -fglasgow-exts #-} module Baum.RedBlack ( make_quiz ) where -- $Id$ import Baum.RedBlack.Type import Baum.RedBlack.Ops import Baum.RedBlack.Show import qualified Baum.Such.Class as C import qualified Baum.Such.Central import qualified Tree as T import Autolib.ToDoc import Inter.Types import Data.Typeable instance C.Such RedBlackTree where empty = Empty isEmpty = isLeaf contains = contains insert = rbInsert delete = error "Delete für RedBlackTree nicht implementiert" equal = (==) contents = contents instance Show a => T.ToTree ( RedBlackTree a ) where toTree = toTree . fmap show toTreeNode = toTreeNode . fmap show data SuchbaumRedBlack = SuchbaumRedBlack deriving ( Eq, Ord, Show, Read, Typeable ) instance C.Tag SuchbaumRedBlack RedBlackTree Int where tag = SuchbaumRedBlack make_quiz :: Make make_quiz = Baum.Such.Central.make_quiz SuchbaumRedBlack
florianpilz/autotool
src/Baum/RedBlack.hs
gpl-2.0
914
0
7
160
231
135
96
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.CloudWatch.ListMetrics -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns a list of valid metrics stored for the AWS account owner. -- Returned metrics can be used with GetMetricStatistics to obtain -- statistical data for a given metric. -- -- /See:/ <http://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_ListMetrics.html AWS API Reference> for ListMetrics. -- -- This operation returns paginated results. module Network.AWS.CloudWatch.ListMetrics ( -- * Creating a Request listMetrics , ListMetrics -- * Request Lenses , lmMetricName , lmNamespace , lmNextToken , lmDimensions -- * Destructuring the Response , listMetricsResponse , ListMetricsResponse -- * Response Lenses , lmrsMetrics , lmrsNextToken , lmrsResponseStatus ) where import Network.AWS.CloudWatch.Types import Network.AWS.CloudWatch.Types.Product import Network.AWS.Pager import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'listMetrics' smart constructor. data ListMetrics = ListMetrics' { _lmMetricName :: !(Maybe Text) , _lmNamespace :: !(Maybe Text) , _lmNextToken :: !(Maybe Text) , _lmDimensions :: !(Maybe [DimensionFilter]) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListMetrics' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lmMetricName' -- -- * 'lmNamespace' -- -- * 'lmNextToken' -- -- * 'lmDimensions' listMetrics :: ListMetrics listMetrics = ListMetrics' { _lmMetricName = Nothing , _lmNamespace = Nothing , _lmNextToken = Nothing , _lmDimensions = Nothing } -- | The name of the metric to filter against. lmMetricName :: Lens' ListMetrics (Maybe Text) lmMetricName = lens _lmMetricName (\ s a -> s{_lmMetricName = a}); -- | The namespace to filter against. lmNamespace :: Lens' ListMetrics (Maybe Text) lmNamespace = lens _lmNamespace (\ s a -> s{_lmNamespace = a}); -- | The token returned by a previous call to indicate that there is more -- data available. lmNextToken :: Lens' ListMetrics (Maybe Text) lmNextToken = lens _lmNextToken (\ s a -> s{_lmNextToken = a}); -- | A list of dimensions to filter against. lmDimensions :: Lens' ListMetrics [DimensionFilter] lmDimensions = lens _lmDimensions (\ s a -> s{_lmDimensions = a}) . _Default . _Coerce; instance AWSPager ListMetrics where page rq rs | stop (rs ^. lmrsNextToken) = Nothing | stop (rs ^. lmrsMetrics) = Nothing | otherwise = Just $ rq & lmNextToken .~ rs ^. lmrsNextToken instance AWSRequest ListMetrics where type Rs ListMetrics = ListMetricsResponse request = postQuery cloudWatch response = receiveXMLWrapper "ListMetricsResult" (\ s h x -> ListMetricsResponse' <$> (x .@? "Metrics" .!@ mempty >>= may (parseXMLList "member")) <*> (x .@? "NextToken") <*> (pure (fromEnum s))) instance ToHeaders ListMetrics where toHeaders = const mempty instance ToPath ListMetrics where toPath = const "/" instance ToQuery ListMetrics where toQuery ListMetrics'{..} = mconcat ["Action" =: ("ListMetrics" :: ByteString), "Version" =: ("2010-08-01" :: ByteString), "MetricName" =: _lmMetricName, "Namespace" =: _lmNamespace, "NextToken" =: _lmNextToken, "Dimensions" =: toQuery (toQueryList "member" <$> _lmDimensions)] -- | The output for the ListMetrics action. -- -- /See:/ 'listMetricsResponse' smart constructor. data ListMetricsResponse = ListMetricsResponse' { _lmrsMetrics :: !(Maybe [Metric]) , _lmrsNextToken :: !(Maybe Text) , _lmrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'ListMetricsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lmrsMetrics' -- -- * 'lmrsNextToken' -- -- * 'lmrsResponseStatus' listMetricsResponse :: Int -- ^ 'lmrsResponseStatus' -> ListMetricsResponse listMetricsResponse pResponseStatus_ = ListMetricsResponse' { _lmrsMetrics = Nothing , _lmrsNextToken = Nothing , _lmrsResponseStatus = pResponseStatus_ } -- | A list of metrics used to generate statistics for an AWS account. lmrsMetrics :: Lens' ListMetricsResponse [Metric] lmrsMetrics = lens _lmrsMetrics (\ s a -> s{_lmrsMetrics = a}) . _Default . _Coerce; -- | A string that marks the start of the next batch of returned results. lmrsNextToken :: Lens' ListMetricsResponse (Maybe Text) lmrsNextToken = lens _lmrsNextToken (\ s a -> s{_lmrsNextToken = a}); -- | The response status code. lmrsResponseStatus :: Lens' ListMetricsResponse Int lmrsResponseStatus = lens _lmrsResponseStatus (\ s a -> s{_lmrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-cloudwatch/gen/Network/AWS/CloudWatch/ListMetrics.hs
mpl-2.0
5,778
0
16
1,339
1,002
584
418
113
1
module GameServer.Clients.Messages where import Data.Aeson import Data.Text (Text) import GameServer.Utils import GHC.Generics import GHC.Natural data Message = ListGames | NewGame { numHumans :: Natural, numRobots :: Natural } | JoinGame { playerKey :: Id, gameId :: Id } | Action { payload :: Text } | Bye deriving stock (Eq, Show, Read, Generic) deriving anyclass( ToJSON, FromJSON) newtype CommandError = CommandError { reason :: Text } deriving newtype (Eq, Show, ToJSON, FromJSON) data Result = PlayerRegistered { playerKey :: Id, gameId :: Id } | NewGameStarted { gameId :: Id } | GameStarts { gameId :: Id } | GamesList [GameDescription] | InputRequired { payload :: Text } | ErrorMessage { error :: Text } deriving (Show, Read, Generic, ToJSON, FromJSON) data GameDescription = GameDescription { gameDescId :: Id , descNumberOfHumans :: Natural , descNumberOfRobots :: Natural , descRegisteredHumans :: [Id] , descLive :: Bool } deriving (Show, Read, Eq, Generic, ToJSON, FromJSON)
abailly/hsgames
game-server/src/GameServer/Clients/Messages.hs
apache-2.0
1,068
0
9
230
325
195
130
-1
-1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : Qtc.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:01:40 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc ( module Qtc.Core , module Qtc.Gui , module Qtc.Network , module Qtc.Opengl , module Qtc.Tools , module Qtc.Script ) where import Qtc.Core import Qtc.Gui import Qtc.Opengl import Qtc.Network import Qtc.Tools import Qtc.Script
uduki/hsQt
Qtc.hs
bsd-2-clause
661
0
5
126
76
50
26
14
0
-- The @FamInst@ type: family instance heads {-# LANGUAGE GADTs, CPP #-} module ETA.TypeCheck.FamInst ( FamInstEnvs, tcGetFamInstEnvs, checkFamInstConsistency, tcExtendLocalFamInstEnv, tcLookupFamInst, tcLookupDataFamInst, tcLookupDataFamInst_maybe, tcInstNewTyCon_maybe, tcTopNormaliseNewTypeTF_maybe, newFamInst ) where import ETA.Main.HscTypes import ETA.Types.FamInstEnv import ETA.Types.InstEnv( roughMatchTcs ) import ETA.Types.Coercion hiding ( substTy ) import ETA.TypeCheck.TcEvidence import ETA.Iface.LoadIface import ETA.TypeCheck.TcRnMonad import ETA.Types.TyCon import ETA.Types.CoAxiom import ETA.Main.DynFlags import ETA.BasicTypes.Module import ETA.Utils.Outputable import ETA.Utils.UniqFM import ETA.Utils.FastString import ETA.Utils.Util import ETA.BasicTypes.RdrName import ETA.BasicTypes.DataCon ( dataConName ) import ETA.Utils.Maybes import ETA.TypeCheck.TcMType import ETA.TypeCheck.TcType import ETA.BasicTypes.Name import Control.Monad import Data.Map (Map) import qualified Data.Map as Map import Control.Arrow ( first, second ) #include "HsVersions.h" {- ************************************************************************ * * Making a FamInst * * ************************************************************************ -} -- All type variables in a FamInst must be fresh. This function -- creates the fresh variables and applies the necessary substitution -- It is defined here to avoid a dependency from FamInstEnv on the monad -- code. newFamInst :: FamFlavor -> CoAxiom Unbranched -> TcRnIf gbl lcl FamInst -- Freshen the type variables of the FamInst branches -- Called from the vectoriser monad too, hence the rather general type newFamInst flavor axiom@(CoAxiom { co_ax_branches = FirstBranch branch , co_ax_tc = fam_tc }) | CoAxBranch { cab_tvs = tvs , cab_lhs = lhs , cab_rhs = rhs } <- branch = do { (subst, tvs') <- freshenTyVarBndrs tvs ; return (FamInst { fi_fam = tyConName fam_tc , fi_flavor = flavor , fi_tcs = roughMatchTcs lhs , fi_tvs = tvs' , fi_tys = substTys subst lhs , fi_rhs = substTy subst rhs , fi_axiom = axiom }) } {- ************************************************************************ * * Optimised overlap checking for family instances * * ************************************************************************ For any two family instance modules that we import directly or indirectly, we check whether the instances in the two modules are consistent, *unless* we can be certain that the instances of the two modules have already been checked for consistency during the compilation of modules that we import. Why do we need to check? Consider module X1 where module X2 where data T1 data T2 type instance F T1 b = Int type instance F a T2 = Char f1 :: F T1 a -> Int f2 :: Char -> F a T2 f1 x = x f2 x = x Now if we import both X1 and X2 we could make (f2 . f1) :: Int -> Char. Notice that neither instance is an orphan. How do we know which pairs of modules have already been checked? Any pair of modules where both modules occur in the `HscTypes.dep_finsts' set (of the `HscTypes.Dependencies') of one of our directly imported modules must have already been checked. Everything else, we check now. (So that we can be certain that the modules in our `HscTypes.dep_finsts' are consistent.) -} -- The optimisation of overlap tests is based on determining pairs of modules -- whose family instances need to be checked for consistency. -- data ModulePair = ModulePair Module Module -- canonical order of the components of a module pair -- canon :: ModulePair -> (Module, Module) canon (ModulePair m1 m2) | m1 < m2 = (m1, m2) | otherwise = (m2, m1) instance Eq ModulePair where mp1 == mp2 = canon mp1 == canon mp2 instance Ord ModulePair where mp1 `compare` mp2 = canon mp1 `compare` canon mp2 instance Outputable ModulePair where ppr (ModulePair m1 m2) = angleBrackets (ppr m1 <> comma <+> ppr m2) -- Sets of module pairs -- type ModulePairSet = Map ModulePair () listToSet :: [ModulePair] -> ModulePairSet listToSet l = Map.fromList (zip l (repeat ())) checkFamInstConsistency :: [Module] -> [Module] -> TcM () checkFamInstConsistency famInstMods directlyImpMods = do { dflags <- getDynFlags ; (eps, hpt) <- getEpsAndHpt ; let { -- Fetch the iface of a given module. Must succeed as -- all directly imported modules must already have been loaded. modIface mod = case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of Nothing -> panic "FamInst.checkFamInstConsistency" Just iface -> iface ; hmiModule = mi_module . hm_iface ; hmiFamInstEnv = extendFamInstEnvList emptyFamInstEnv . md_fam_insts . hm_details ; hpt_fam_insts = mkModuleEnv [ (hmiModule hmi, hmiFamInstEnv hmi) | hmi <- eltsUFM hpt] ; groups = map (dep_finsts . mi_deps . modIface) directlyImpMods ; okPairs = listToSet $ concatMap allPairs groups -- instances of okPairs are consistent ; criticalPairs = listToSet $ allPairs famInstMods -- all pairs that we need to consider ; toCheckPairs = Map.keys $ criticalPairs `Map.difference` okPairs -- the difference gives us the pairs we need to check now } ; mapM_ (check hpt_fam_insts) toCheckPairs } where allPairs [] = [] allPairs (m:ms) = map (ModulePair m) ms ++ allPairs ms check hpt_fam_insts (ModulePair m1 m2) = do { env1 <- getFamInsts hpt_fam_insts m1 ; env2 <- getFamInsts hpt_fam_insts m2 ; mapM_ (checkForConflicts (emptyFamInstEnv, env2)) (famInstEnvElts env1) } getFamInsts :: ModuleEnv FamInstEnv -> Module -> TcM FamInstEnv getFamInsts hpt_fam_insts mod | Just env <- lookupModuleEnv hpt_fam_insts mod = return env | otherwise = do { _ <- initIfaceTcRn (loadSysInterface doc mod) ; eps <- getEps ; return (expectJust "checkFamInstConsistency" $ lookupModuleEnv (eps_mod_fam_inst_env eps) mod) } where doc = ppr mod <+> ptext (sLit "is a family-instance module") {- ************************************************************************ * * Lookup * * ************************************************************************ Look up the instance tycon of a family instance. The match may be ambiguous (as we know that overlapping instances have identical right-hand sides under overlapping substitutions - see 'FamInstEnv.lookupFamInstEnvConflicts'). However, the type arguments used for matching must be equal to or be more specific than those of the family instance declaration. We pick one of the matches in case of ambiguity; as the right-hand sides are identical under the match substitution, the choice does not matter. Return the instance tycon and its type instance. For example, if we have tcLookupFamInst 'T' '[Int]' yields (':R42T', 'Int') then we have a coercion (ie, type instance of family instance coercion) :Co:R42T Int :: T [Int] ~ :R42T Int which implies that :R42T was declared as 'data instance T [a]'. -} tcLookupFamInst :: FamInstEnvs -> TyCon -> [Type] -> Maybe FamInstMatch tcLookupFamInst fam_envs tycon tys | not (isOpenFamilyTyCon tycon) = Nothing | otherwise = case lookupFamInstEnv fam_envs tycon tys of match : _ -> Just match [] -> Nothing -- | If @co :: T ts ~ rep_ty@ then: -- -- > instNewTyCon_maybe T ts = Just (rep_ty, co) -- -- Checks for a newtype, and for being saturated -- Just like Coercion.instNewTyCon_maybe, but returns a TcCoercion tcInstNewTyCon_maybe :: TyCon -> [TcType] -> Maybe (TcType, TcCoercion) tcInstNewTyCon_maybe tc tys = fmap (second TcCoercion) $ instNewTyCon_maybe tc tys -- | Like 'tcLookupDataFamInst_maybe', but returns the arguments back if -- there is no data family to unwrap. tcLookupDataFamInst :: FamInstEnvs -> TyCon -> [TcType] -> (TyCon, [TcType], TcCoercion) tcLookupDataFamInst fam_inst_envs tc tc_args | Just (rep_tc, rep_args, co) <- tcLookupDataFamInst_maybe fam_inst_envs tc tc_args = (rep_tc, rep_args, TcCoercion co) | otherwise = (tc, tc_args, mkTcRepReflCo (mkTyConApp tc tc_args)) tcLookupDataFamInst_maybe :: FamInstEnvs -> TyCon -> [TcType] -> Maybe (TyCon, [TcType], Coercion) -- ^ Converts a data family type (eg F [a]) to its representation type (eg FList a) -- and returns a coercion between the two: co :: F [a] ~R FList a tcLookupDataFamInst_maybe fam_inst_envs tc tc_args | isDataFamilyTyCon tc , match : _ <- lookupFamInstEnv fam_inst_envs tc tc_args , FamInstMatch { fim_instance = rep_fam , fim_tys = rep_args } <- match , let co_tc = famInstAxiom rep_fam rep_tc = dataFamInstRepTyCon rep_fam co = mkUnbranchedAxInstCo Representational co_tc rep_args = Just (rep_tc, rep_args, co) | otherwise = Nothing -- | Get rid of top-level newtypes, potentially looking through newtype -- instances. Only unwraps newtypes that are in scope. This is used -- for solving for `Coercible` in the solver. This version is careful -- not to unwrap data/newtype instances if it can't continue unwrapping. -- Such care is necessary for proper error messages. -- -- Does not look through type families. Does not normalise arguments to a -- tycon. -- -- Always produces a representational coercion. tcTopNormaliseNewTypeTF_maybe :: FamInstEnvs -> GlobalRdrEnv -> Type -> Maybe (TcCoercion, Type) tcTopNormaliseNewTypeTF_maybe faminsts rdr_env ty -- cf. FamInstEnv.topNormaliseType_maybe and Coercion.topNormaliseNewType_maybe = fmap (first TcCoercion) $ topNormaliseTypeX_maybe stepper ty where stepper = unwrap_newtype `composeSteppers` \ rec_nts tc tys -> case tcLookupDataFamInst_maybe faminsts tc tys of Just (tc', tys', co) -> modifyStepResultCo (co `mkTransCo`) (unwrap_newtype rec_nts tc' tys') Nothing -> NS_Done unwrap_newtype rec_nts tc tys | data_cons_in_scope tc = unwrapNewTypeStepper rec_nts tc tys | otherwise = NS_Done data_cons_in_scope :: TyCon -> Bool data_cons_in_scope tc = isWiredInName (tyConName tc) || (not (isAbstractTyCon tc) && all in_scope data_con_names) where data_con_names = map dataConName (tyConDataCons tc) in_scope dc = not $ null $ lookupGRE_Name rdr_env dc {- ************************************************************************ * * Extending the family instance environment * * ************************************************************************ -} -- Add new locally-defined family instances tcExtendLocalFamInstEnv :: [FamInst] -> TcM a -> TcM a tcExtendLocalFamInstEnv fam_insts thing_inside = do { env <- getGblEnv ; (inst_env', fam_insts') <- foldlM addLocalFamInst (tcg_fam_inst_env env, tcg_fam_insts env) fam_insts ; let env' = env { tcg_fam_insts = fam_insts' , tcg_fam_inst_env = inst_env' } ; setGblEnv env' thing_inside } -- Check that the proposed new instance is OK, -- and then add it to the home inst env -- This must be lazy in the fam_inst arguments, see Note [Lazy axiom match] -- in FamInstEnv.lhs addLocalFamInst :: (FamInstEnv,[FamInst]) -> FamInst -> TcM (FamInstEnv, [FamInst]) addLocalFamInst (home_fie, my_fis) fam_inst -- home_fie includes home package and this module -- my_fies is just the ones from this module = do { traceTc "addLocalFamInst" (ppr fam_inst) ; isGHCi <- getIsGHCi ; mod <- getModule ; traceTc "alfi" (ppr mod $$ ppr isGHCi) -- In GHCi, we *override* any identical instances -- that are also defined in the interactive context -- See Note [Override identical instances in GHCi] in HscTypes ; let home_fie' | isGHCi = deleteFromFamInstEnv home_fie fam_inst | otherwise = home_fie -- Load imported instances, so that we report -- overlaps correctly ; eps <- getEps ; let inst_envs = (eps_fam_inst_env eps, home_fie') home_fie'' = extendFamInstEnv home_fie fam_inst -- Check for conflicting instance decls ; no_conflict <- checkForConflicts inst_envs fam_inst ; if no_conflict then return (home_fie'', fam_inst : my_fis) else return (home_fie, my_fis) } {- ************************************************************************ * * Checking an instance against conflicts with an instance env * * ************************************************************************ Check whether a single family instance conflicts with those in two instance environments (one for the EPS and one for the HPT). -} checkForConflicts :: FamInstEnvs -> FamInst -> TcM Bool checkForConflicts inst_envs fam_inst = do { let conflicts = lookupFamInstEnvConflicts inst_envs fam_inst no_conflicts = null conflicts ; traceTc "checkForConflicts" $ vcat [ ppr (map fim_instance conflicts) , ppr fam_inst -- , ppr inst_envs ] ; unless no_conflicts $ conflictInstErr fam_inst conflicts ; return no_conflicts } conflictInstErr :: FamInst -> [FamInstMatch] -> TcRn () conflictInstErr fam_inst conflictingMatch | (FamInstMatch { fim_instance = confInst }) : _ <- conflictingMatch = addFamInstsErr (ptext (sLit "Conflicting family instance declarations:")) [fam_inst, confInst] | otherwise = panic "conflictInstErr" addFamInstsErr :: SDoc -> [FamInst] -> TcRn () addFamInstsErr herald insts = ASSERT( not (null insts) ) setSrcSpan srcSpan $ addErr $ hang herald 2 (vcat [ pprCoAxBranchHdr (famInstAxiom fi) 0 | fi <- sorted ]) where getSpan = getSrcLoc . famInstAxiom sorted = sortWith getSpan insts fi1 = head sorted srcSpan = coAxBranchSpan (coAxiomSingleBranch (famInstAxiom fi1)) -- The sortWith just arranges that instances are dislayed in order -- of source location, which reduced wobbling in error messages, -- and is better for users tcGetFamInstEnvs :: TcM FamInstEnvs -- Gets both the external-package inst-env -- and the home-pkg inst env (includes module being compiled) tcGetFamInstEnvs = do { eps <- getEps; env <- getGblEnv ; return (eps_fam_inst_env eps, tcg_fam_inst_env env) }
pparkkin/eta
compiler/ETA/TypeCheck/FamInst.hs
bsd-3-clause
16,102
0
14
4,693
2,591
1,383
1,208
209
3
{-# LANGUAGE TemplateHaskell #-} module Bead.View.Translation.Entries where import Bead.View.Translation.Base $(generateTranslationEntries labels)
pgj/bead
src/Bead/View/Translation/Entries.hs
bsd-3-clause
149
0
7
13
26
16
10
4
0
module NestedImporting2.A where import Prelude r :: Double r = 1
beni55/fay
tests/NestedImporting2/A.hs
bsd-3-clause
67
0
4
13
19
12
7
4
1
{-# LANGUAGE ForeignFunctionInterface #-} module Test.TestFormat where import Data.Time import Data.Time.Clock.POSIX import Data.Char import Foreign import Foreign.C import Control.Exception; import Test.TestUtil {- size_t format_time ( char *s, size_t maxsize, const char *format, int isdst,int gmtoff,time_t t); -} foreign import ccall unsafe "TestFormatStuff.h format_time" format_time :: CString -> CSize -> CString -> CInt -> CInt -> CString -> CTime -> IO CSize withBuffer :: Int -> (CString -> IO CSize) -> IO String withBuffer n f = withArray (replicate n 0) (\buffer -> do len <- f buffer peekCStringLen (buffer,fromIntegral len) ) unixFormatTime :: String -> TimeZone -> UTCTime -> IO String unixFormatTime fmt zone time = withCString fmt (\pfmt -> withCString (timeZoneName zone) (\pzonename -> withBuffer 100 (\buffer -> format_time buffer 100 pfmt (if timeZoneSummerOnly zone then 1 else 0) (fromIntegral (timeZoneMinutes zone * 60)) pzonename (fromInteger (truncate (utcTimeToPOSIXSeconds time))) ) )) locale :: TimeLocale locale = defaultTimeLocale {dateTimeFmt = "%a %b %e %H:%M:%S %Y"} zones :: [TimeZone] zones = [utc,TimeZone 87 True "Fenwickian Daylight Time"] baseTime0 :: UTCTime baseTime0 = localTimeToUTC utc (LocalTime (fromGregorian 1970 01 01) midnight) baseTime1 :: UTCTime baseTime1 = localTimeToUTC utc (LocalTime (fromGregorian 2000 01 01) midnight) getDay :: Integer -> UTCTime getDay day = addUTCTime ((fromInteger day) * posixDayLength) baseTime1 getYearP1 :: Integer -> UTCTime getYearP1 year = localTimeToUTC utc (LocalTime (fromGregorian year 01 01) midnight) getYearP2 :: Integer -> UTCTime getYearP2 year = localTimeToUTC utc (LocalTime (fromGregorian year 02 04) midnight) getYearP3 :: Integer -> UTCTime getYearP3 year = localTimeToUTC utc (LocalTime (fromGregorian year 03 04) midnight) getYearP4 :: Integer -> UTCTime getYearP4 year = localTimeToUTC utc (LocalTime (fromGregorian year 12 31) midnight) years :: [Integer] years = [999,1000,1899,1900,1901] ++ [1980..2000] ++ [9999,10000] times :: [UTCTime] times = [baseTime0] ++ (fmap getDay [0..23]) ++ (fmap getDay [0..100]) ++ (fmap getYearP1 years) ++ (fmap getYearP2 years) ++ (fmap getYearP3 years) ++ (fmap getYearP4 years) padN :: Int -> Char -> String -> String padN n _ s | n <= (length s) = s padN n c s = (replicate (n - length s) c) ++ s unixWorkarounds :: String -> String -> String unixWorkarounds "%_Y" s = padN 4 ' ' s unixWorkarounds "%0Y" s = padN 4 '0' s unixWorkarounds "%_C" s = padN 2 ' ' s unixWorkarounds "%0C" s = padN 2 '0' s unixWorkarounds "%_G" s = padN 4 ' ' s unixWorkarounds "%0G" s = padN 4 '0' s unixWorkarounds "%_f" s = padN 2 ' ' s unixWorkarounds "%0f" s = padN 2 '0' s unixWorkarounds _ s = s compareFormat :: String -> (String -> String) -> String -> TimeZone -> UTCTime -> Test compareFormat testname modUnix fmt zone time = let ctime = utcToZonedTime zone time haskellText = formatTime locale fmt ctime in ioTest (testname ++ ": " ++ (show fmt) ++ " of " ++ (show ctime)) $ do unixText <- unixFormatTime fmt zone time let expectedText = unixWorkarounds fmt (modUnix unixText) return $ diff expectedText haskellText -- as found in http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html -- plus FgGklz -- f not supported -- P not always supported -- s time-zone dependent chars :: [Char] chars = "aAbBcCdDeFgGhHIjklmMnprRStTuUVwWxXyYzZ%" -- as found in "man strftime" on a glibc system. '#' is different, though modifiers :: [Char] modifiers = "_-0^" formats :: [String] formats = ["%G-W%V-%u","%U-%w","%W-%u"] ++ (fmap (\char -> '%':char:[]) chars) ++ (concat (fmap (\char -> fmap (\modifier -> '%':modifier:char:[]) modifiers) chars)) hashformats :: [String] hashformats = (fmap (\char -> '%':'#':char:[]) chars) somestrings :: [String] somestrings = ["", " ", "-", "\n"] getBottom :: a -> IO (Maybe Control.Exception.SomeException); getBottom a = Control.Exception.catch (seq a (return Nothing)) (return . Just); safeString :: String -> IO String safeString s = do msx <- getBottom s case msx of Just sx -> return (show sx) Nothing -> case s of (c:cc) -> do mcx <- getBottom c case mcx of Just cx -> return (show cx) Nothing -> do ss <- safeString cc return (c:ss) [] -> return "" compareExpected :: (Eq t,Show t,ParseTime t) => String -> String -> String -> Maybe t -> Test compareExpected testname fmt str expected = ioTest (testname ++ ": " ++ (show fmt) ++ " on " ++ (show str)) $ do let found = parseTimeM False defaultTimeLocale fmt str mex <- getBottom found case mex of Just ex -> return $ Fail $ unwords [ "Exception: expected" , show expected ++ ", caught", show ex] Nothing -> return $ diff expected found class (ParseTime t) => TestParse t where expectedParse :: String -> String -> Maybe t expectedParse "%Z" "" = Just (buildTime defaultTimeLocale []) expectedParse "%_Z" "" = Just (buildTime defaultTimeLocale []) expectedParse "%-Z" "" = Just (buildTime defaultTimeLocale []) expectedParse "%0Z" "" = Just (buildTime defaultTimeLocale []) expectedParse _ _ = Nothing instance TestParse Day instance TestParse TimeOfDay instance TestParse LocalTime instance TestParse TimeZone instance TestParse ZonedTime instance TestParse UTCTime checkParse :: String -> String -> [Test] checkParse fmt str = [ compareExpected "Day" fmt str (expectedParse fmt str :: Maybe Day) , compareExpected "TimeOfDay" fmt str (expectedParse fmt str :: Maybe TimeOfDay) , compareExpected "LocalTime" fmt str (expectedParse fmt str :: Maybe LocalTime) , compareExpected "TimeZone" fmt str (expectedParse fmt str :: Maybe TimeZone) , compareExpected "UTCTime" fmt str (expectedParse fmt str :: Maybe UTCTime) ] testCheckParse :: [Test] testCheckParse = concatMap (\fmt -> concatMap (\str -> checkParse fmt str) somestrings) formats testCompareFormat :: [Test] testCompareFormat = concatMap (\fmt -> concatMap (\time -> fmap (\zone -> compareFormat "compare format" id fmt zone time) zones) times) formats testCompareHashFormat :: [Test] testCompareHashFormat = concatMap (\fmt -> concatMap (\time -> fmap (\zone -> compareFormat "compare hashformat" (fmap toLower) fmt zone time) zones) times) hashformats testFormats :: [Test] testFormats = [ testGroup "checkParse" testCheckParse, testGroup "compare format" testCompareFormat, testGroup "compare hashformat" testCompareHashFormat ] testFormat :: Test testFormat = testGroup "testFormat" testFormats
bergmark/time
test/Test/TestFormat.hs
bsd-3-clause
6,668
16
22
1,251
2,341
1,201
1,140
133
4
{-# LANGUAGE OverloadedStrings #-} {-| Parser for the output of the @xm list --long@ command of Xen -} {- 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.Hypervisor.Xen.XmParser ( xmListParser , lispConfigParser , xmUptimeParser , uptimeLineParser ) where import Control.Applicative import Control.Monad import qualified Data.Attoparsec.Combinator as AC import qualified Data.Attoparsec.Text as A import Data.Attoparsec.Text (Parser) import Data.Char import Data.List import Data.Text (unpack) import qualified Data.Map as Map import Ganeti.BasicTypes import Ganeti.Hypervisor.Xen.Types -- | A parser for parsing generic config files written in the (LISP-like) -- format that is the output of the @xm list --long@ command. -- This parser only takes care of the syntactic parse, but does not care -- about the semantics. -- Note: parsing the double requires checking for the next character in order -- to prevent string like "9a" to be recognized as the number 9. lispConfigParser :: Parser LispConfig lispConfigParser = A.skipSpace *> ( listConfigP <|> doubleP <|> stringP ) <* A.skipSpace where listConfigP = LCList <$> (A.char '(' *> liftA2 (++) (many middleP) (((:[]) <$> finalP) <|> (rparen *> pure []))) doubleP = LCDouble <$> A.rational <* A.skipSpace <* A.endOfInput innerDoubleP = LCDouble <$> A.rational stringP = LCString . unpack <$> A.takeWhile1 (not . (\c -> isSpace c || c `elem` ("()" :: String))) wspace = AC.many1 A.space rparen = A.skipSpace *> A.char ')' finalP = listConfigP <* rparen <|> innerDoubleP <* rparen <|> stringP <* rparen middleP = listConfigP <* wspace <|> innerDoubleP <* wspace <|> stringP <* wspace -- | Find a configuration having the given string as its first element, -- from a list of configurations. findConf :: String -> [LispConfig] -> Result LispConfig findConf key configs = case find (isNamed key) configs of (Just c) -> Ok c _ -> Bad "Configuration not found" -- | Get the value of of a configuration having the given string as its -- first element. -- The value is the content of the configuration, discarding the name itself. getValue :: (FromLispConfig a) => String -> [LispConfig] -> Result a getValue key configs = findConf key configs >>= fromLispConfig -- | Extract the values of a configuration containing a list of them. extractValues :: LispConfig -> Result [LispConfig] extractValues c = tail `fmap` fromLispConfig c -- | Verify whether the given configuration has a certain name or not.fmap -- The name of a configuration is its first parameter, if it is a string. isNamed :: String -> LispConfig -> Bool isNamed key (LCList (LCString x:_)) = x == key isNamed _ _ = False -- | Parser for recognising the current state of a Xen domain. parseState :: String -> ActualState parseState s = case s of "r-----" -> ActualRunning "-b----" -> ActualBlocked "--p---" -> ActualPaused "---s--" -> ActualShutdown "----c-" -> ActualCrashed "-----d" -> ActualDying _ -> ActualUnknown -- | Extract the configuration data of a Xen domain from a generic LispConfig -- data structure. Fail if the LispConfig does not represent a domain. getDomainConfig :: LispConfig -> Result Domain getDomainConfig configData = do domainConf <- if isNamed "domain" configData then extractValues configData else Bad $ "Not a domain configuration: " ++ show configData domid <- getValue "domid" domainConf name <- getValue "name" domainConf cpuTime <- getValue "cpu_time" domainConf state <- getValue "state" domainConf let actualState = parseState state return $ Domain domid name cpuTime actualState Nothing -- | A parser for parsing the output of the @xm list --long@ command. -- It adds the semantic layer on top of lispConfigParser. -- It returns a map of domains, with their name as the key. -- FIXME: This is efficient under the assumption that only a few fields of the -- domain configuration are actually needed. If many of them are required, a -- parser able to directly extract the domain config would actually be better. xmListParser :: Parser (Map.Map String Domain) xmListParser = do configs <- lispConfigParser `AC.manyTill` A.endOfInput let domains = map getDomainConfig configs foldResult m (Ok val) = Ok $ Map.insert (domName val) val m foldResult _ (Bad msg) = Bad msg case foldM foldResult Map.empty domains of Ok d -> return d Bad msg -> fail msg -- | A parser for parsing the output of the @xm uptime@ command. xmUptimeParser :: Parser (Map.Map Int UptimeInfo) xmUptimeParser = do _ <- headerParser uptimes <- uptimeLineParser `AC.manyTill` A.endOfInput return $ Map.fromList [(uInfoID u, u) | u <- uptimes] where headerParser = A.string "Name" <* A.skipSpace <* A.string "ID" <* A.skipSpace <* A.string "Uptime" <* A.skipSpace -- | A helper for parsing a single line of the @xm uptime@ output. uptimeLineParser :: Parser UptimeInfo uptimeLineParser = do name <- A.takeTill isSpace <* A.skipSpace idNum <- A.decimal <* A.skipSpace uptime <- A.takeTill (`elem` ("\n\r" :: String)) <* A.skipSpace return . UptimeInfo (unpack name) idNum $ unpack uptime
leshchevds/ganeti
src/Ganeti/Hypervisor/Xen/XmParser.hs
bsd-2-clause
6,612
0
16
1,342
1,170
615
555
95
7
module Constructor where -- Should be able to rename AType to MyType, as they are in different name -- spaces data MyType = AType Int | YourType Bool foo :: MyType -> Bool foo (AType i) = i > 0 foo (YourType b) = b
RefactoringTools/HaRe
test/testdata/Renaming/Constructor.hs
bsd-3-clause
219
0
7
49
61
34
27
5
1
{-# LANGUAGE MultiParamTypeClasses, GADTs, RankNTypes, ConstraintKinds, QuantifiedConstraints, UndecidableInstances #-} module T15359a where class C a b class a ~ b => D a b data Dict c where Dict :: c => Dict c foo :: (forall a b. C a b => D a b) => Dict (C a b) -> a -> b foo Dict x = x
sdiehl/ghc
testsuite/tests/quantified-constraints/T15359a.hs
bsd-3-clause
321
0
9
92
110
57
53
-1
-1
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ConstraintKinds #-} module T4175 where import GHC.Exts type family A a b type instance A Int Int = () type instance A (Maybe a) a = a type instance A (B a) b = () data family B a data instance B () = MkB class C a where type D a b instance C Int where type D Int () = String instance C () where type D () () = Bool type family E a where E () = Bool E Int = String class Z a class F (a :: Constraint) instance F (Z a) class G (a :: * -> *) instance G B
urbanslug/ghc
testsuite/tests/ghci/scripts/T4175.hs
bsd-3-clause
526
0
8
145
231
127
104
-1
-1
{-# LANGUAGE GADTs, DataKinds, KindSignatures, FlexibleInstances #-} module T8537 where import Data.Functor data Nat = S !Nat | Z infixr 3 :* data Shape (rank :: Nat) a where Nil :: Shape Z a (:*) :: !(a) -> !(Shape r a ) -> Shape (S r) a instance Functor (Shape Z) where fmap = \ f Nil -> Nil {-# INLINABLE fmap #-} {-# SPECIALIZE fmap :: (Int ->Int )-> (Shape Z Int)-> (Shape Z Int) #-}
siddhanathan/ghc
testsuite/tests/simplCore/should_compile/T8537.hs
bsd-3-clause
422
0
10
110
116
67
49
17
0
{-# LANGUAGE DeriveDataTypeable, NoImplicitPrelude, FlexibleContexts #-} {-# OPTIONS_GHC -Wall #-} module LLVM.General.Util.Internal.Diagnostic ( LLVMError(..), llvmErrorFunctionName, llvmErrorString, errorToIO, diagToIO, catchInternal, catchCaller, catchCallerError, catchCallerDiag, module LLVM.General.Diagnostic ) where import ClassyPrelude import Control.Exception.Lifted(catches, Handler(..)) import Control.Monad.Trans.Control(MonadBaseControl(..)) import Control.Monad.Trans.Error(ErrorT(..)) import Language.Haskell.TH(Name) import LLVM.General.Diagnostic data LLVMError = LLVMError Name String | LLVMInternalError Name String | LLVMDiagnostic Name Diagnostic deriving (Eq,Ord,Show,Typeable) instance Exception LLVMError llvmErrorFunctionName :: LLVMError -> Name llvmErrorFunctionName (LLVMError funcName _) = funcName llvmErrorFunctionName (LLVMInternalError funcName _) = funcName llvmErrorFunctionName (LLVMDiagnostic funcName _) = funcName llvmErrorString :: LLVMError -> String llvmErrorString (LLVMError _ str) = str llvmErrorString (LLVMInternalError _ str) = str llvmErrorString (LLVMDiagnostic _ diag) = diagnosticDisplay diag errorToIO :: Name -> ErrorT String IO a -> IO a errorToIO funcName m = do result <- catchInternal funcName $ runErrorT m case result of Left str -> throwIO (LLVMError funcName str) Right x -> return x diagToIO :: Name -> ErrorT (Either String Diagnostic) IO a -> IO a diagToIO funcName m = do result <- catchInternal funcName $ runErrorT m case result of Left (Left str) -> throwIO (LLVMError funcName str) Left (Right diag) -> throwIO (LLVMDiagnostic funcName diag) Right x -> return x catchInternal :: (MonadBaseControl IO m) => Name -> m a -> m a catchInternal funcName m = catch m catcher where catcher e = if isUserError e then throwIO (LLVMInternalError funcName (ioeGetErrorString e)) else throwIO e newtype AntiCatch = AntiCatch IOError deriving (Show,Typeable) instance Exception AntiCatch catchCaller :: (MonadBaseControl IO m) => Name -> ((a -> m b) -> m b) -> (a -> m b) -> m b catchCaller funcName f g = catches (f g') [Handler catcherA, Handler catcherB] where g' x = catch (g x) (throwIO . AntiCatch) catcherA (AntiCatch e) = throwIO e catcherB e = if isUserError e then throwIO (LLVMInternalError funcName (ioeGetErrorString e)) else throwIO e catchCallerError :: (MonadBaseControl IO m) => Name -> ((a -> m b) -> ErrorT String m b) -> (a -> m b) -> m b catchCallerError funcName f g = catchCaller funcName f' g where f' g' = do result <- (runErrorT . f) g' case result of Left str -> throwIO (LLVMError funcName str) Right x -> return x catchCallerDiag :: (MonadBaseControl IO m) => Name -> ((a -> m b) -> ErrorT (Either String Diagnostic) m b) -> (a -> m b) -> m b catchCallerDiag funcName f g = catchCaller funcName f' g where f' g' = do result <- (runErrorT . f) g' case result of Left (Left str) -> throwIO (LLVMError funcName str) Left (Right diag) -> throwIO (LLVMDiagnostic funcName diag) Right x -> return x
dfoxfranke/llvm-general-util
LLVM/General/Util/Internal/Diagnostic.hs
mit
3,552
0
14
1,008
1,139
576
563
88
3
{-# LANGUAGE OverloadedStrings #-} module Guguk.Phonetics where import qualified Data.Text as T import qualified Data.List as L type IPASymbol = T.Text type SurfaceForm = T.Text -- Vowel types data VowelOpenness = Close | NearClose | CloseMid | Mid | OpenMid | NearOpen | Open deriving (Show, Eq) data VowelLocation = Front | NearFront | Central | NearBack | Back deriving (Show, Eq) data VowelRoundedness = Rounded | Unrounded | Nonrounded deriving (Show, Eq) data VowelLength = Long | NormalLength deriving (Show, Eq) data Vowel = Vowel IPASymbol VowelOpenness VowelLocation VowelRoundedness VowelLength deriving (Show, Eq) -- Consonant types -- | AlveolarLateralV means Velarized AlveolarLateral. data ConsonantPlace = Labial | Bilabial | Dental | Labiodental | Alveolar | PostAlveolar | PalatoAlveolar | AlveolarLateral | AlveolarLateralV | Palatal | Velar | Glottal deriving (Show, Eq) data ConsonantManner = Nasal | Stop | Affricate | Fricative | Approximant | Flap | Sibilant deriving (Show, Eq) data ConsonantVoice = Voiced | Voiceless deriving (Show, Eq) data Consonant = Consonant IPASymbol ConsonantVoice ConsonantPlace ConsonantManner deriving (Show, Eq) -- Phoneme types data Phoneme = VowelPhoneme SurfaceForm Vowel | ConsonantPhoneme SurfaceForm Consonant deriving (Show, Eq) turkishPhonemes :: [Phoneme] turkishPhonemes = [ -- Vowels VowelPhoneme "a" (Vowel "ɑ" Open Back Unrounded NormalLength) , VowelPhoneme "a" (Vowel "a" Open Front Unrounded NormalLength) , VowelPhoneme "e" (Vowel "e" CloseMid Front Unrounded NormalLength) , VowelPhoneme "e" (Vowel "ɛ" OpenMid Front Unrounded NormalLength) , VowelPhoneme "e" (Vowel "æ" NearOpen Front Unrounded NormalLength) , VowelPhoneme "ı" (Vowel "ɯ" Close Back Unrounded NormalLength) , VowelPhoneme "i" (Vowel "i" Close Front Unrounded NormalLength) , VowelPhoneme "o" (Vowel "o" CloseMid Back Rounded NormalLength) , VowelPhoneme "ö" (Vowel "ø" CloseMid Front Rounded NormalLength) , VowelPhoneme "u" (Vowel "u" Close Back Rounded NormalLength) , VowelPhoneme "ü" (Vowel "y" Close Front Rounded NormalLength) -- Long Vowels , VowelPhoneme "â" (Vowel "aː" Open Back Unrounded Long) , VowelPhoneme "î" (Vowel "iː" Close Front Unrounded Long) , VowelPhoneme "û" (Vowel "uː" Close Back Rounded Long) -- Consonants , ConsonantPhoneme "b" (Consonant "b" Voiced Bilabial Stop) , ConsonantPhoneme "c" (Consonant "d͡ʒ" Voiced PalatoAlveolar Affricate) , ConsonantPhoneme "ç" (Consonant "t͡ʃ" Voiceless PalatoAlveolar Affricate) , ConsonantPhoneme "d" (Consonant "d̪" Voiced Dental Stop) , ConsonantPhoneme "f" (Consonant "f" Voiceless Labiodental Fricative) , ConsonantPhoneme "g" (Consonant "ɡ" Voiced Velar Stop) , ConsonantPhoneme "g" (Consonant "ɟ" Voiced Palatal Stop) , ConsonantPhoneme "ğ" (Consonant "ɣ" Voiced Velar Fricative) , ConsonantPhoneme "h" (Consonant "h" Voiceless Glottal Fricative) , ConsonantPhoneme "j" (Consonant "ʒ" Voiced PalatoAlveolar Sibilant) , ConsonantPhoneme "k" (Consonant "k" Voiceless Velar Stop) , ConsonantPhoneme "k" (Consonant "c" Voiceless Palatal Stop) , ConsonantPhoneme "l" (Consonant "l" Voiced AlveolarLateral Approximant) , ConsonantPhoneme "l" (Consonant "ɫ" Voiced AlveolarLateralV Approximant) , ConsonantPhoneme "m" (Consonant "m" Voiced Bilabial Nasal) , ConsonantPhoneme "n" (Consonant "n" Voiced Alveolar Nasal) , ConsonantPhoneme "p" (Consonant "p" Voiceless Bilabial Stop) , ConsonantPhoneme "r" (Consonant "ɾ" Voiced Alveolar Flap) , ConsonantPhoneme "s" (Consonant "s" Voiceless Alveolar Fricative) , ConsonantPhoneme "ş" (Consonant "ʃ" Voiceless PalatoAlveolar Fricative) , ConsonantPhoneme "t" (Consonant "t̪" Voiceless Dental Stop) , ConsonantPhoneme "v" (Consonant "v" Voiced Labiodental Fricative) , ConsonantPhoneme "y" (Consonant "j" Voiced Palatal Approximant) , ConsonantPhoneme "z" (Consonant "z" Voiced Alveolar Sibilant) ] -- Phoneme general functions getSurfaceForm :: Phoneme -> SurfaceForm getSurfaceForm (VowelPhoneme x _) = x getSurfaceForm (ConsonantPhoneme x _) = x getIPASymbol :: Phoneme -> IPASymbol getIPASymbol (VowelPhoneme _ (Vowel x _ _ _ _)) = x getIPASymbol (ConsonantPhoneme _ (Consonant x _ _ _ )) = x getBySurfaceForm :: SurfaceForm -> [Phoneme] getBySurfaceForm sf = L.filter ((== sf) . getSurfaceForm) turkishPhonemes getByIPASymbol :: IPASymbol -> Maybe Phoneme getByIPASymbol ipa = L.find ((== ipa) . getIPASymbol) turkishPhonemes -- Vowel specific functions vowelTypeError :: String vowelTypeError = "Cannot get vowel-specific feature of a consonant" isVowel :: Phoneme -> Bool isVowel (VowelPhoneme _ _) = True isVowel _ = False vowelOpenness :: Phoneme -> VowelOpenness vowelOpenness (VowelPhoneme _ (Vowel _ x _ _ _)) = x vowelOpenness _ = error vowelTypeError vowelLocation :: Phoneme -> VowelLocation vowelLocation (VowelPhoneme _ (Vowel _ _ x _ _)) = x vowelLocation _ = error vowelTypeError vowelRoundedness :: Phoneme -> VowelRoundedness vowelRoundedness (VowelPhoneme _ (Vowel _ _ _ x _)) = x vowelRoundedness _ = error vowelTypeError vowelLength :: Phoneme -> VowelLength vowelLength (VowelPhoneme _ (Vowel _ _ _ _ x)) = x vowelLength _ = error vowelTypeError -- Consonant specific functions consonantTypeError :: String consonantTypeError = "Cannot get consonant-specific feature of a vowel" isConsonant :: Phoneme -> Bool isConsonant (ConsonantPhoneme _ _) = True isConsonant _ = False consonantVoice :: Phoneme -> ConsonantVoice consonantVoice (ConsonantPhoneme _ (Consonant _ x _ _)) = x consonantVoice _ = error consonantTypeError consonantPlace :: Phoneme -> ConsonantPlace consonantPlace (ConsonantPhoneme _ (Consonant _ _ x _)) = x consonantPlace _ = error consonantTypeError consonantManner :: Phoneme -> ConsonantManner consonantManner (ConsonantPhoneme _ (Consonant _ _ _ x)) = x consonantManner _ = error consonantTypeError
joom/Guguk
src/Guguk/Phonetics.hs
mit
6,769
0
9
1,743
1,766
930
836
115
1
module Nauva.View.Terms.Generator (main) where import Data.List (sort, nub) import Data.Char (toUpper) sanitize :: String -> String sanitize str = removeDash str ++ "_" where removeDash ('-' : x : xs) = toUpper x : removeDash xs removeDash (x : xs) = x : removeDash xs removeDash [] = [] exportList :: [String] -> String exportList [] = error "exportList without functions." exportList (f:functions) = unlines $ [ "module Nauva.View.Terms" , " ( " ++ f ] ++ map (" , " ++) functions ++ [ " ) where"] makeVoidTerm :: String -> String makeVoidTerm tag = unlines [ function ++ " :: [Attribute] -> Element" , function ++ " = with (ENode \"" ++ tag ++ "\" [] [])" , "{-# INLINE " ++ function ++ " #-}" ] where function = sanitize tag makeTerm :: String -> String makeTerm tag = unlines [ function ++ " :: Term arg res => arg -> res" , function ++ " = term \"" ++ tag ++ "\"" , "{-# INLINE " ++ function ++ " #-}" ] where function = sanitize tag makeAttributeTerm :: String -> String makeAttributeTerm tag = unlines [ function ++ " :: Term arg res => arg -> res" , function ++ " = term \"" ++ tag ++ "\"" , "{-# INLINE " ++ function ++ " #-}" ] where function = sanitize tag -- For distinction between void and normal elements, please refer to -- https://www.w3.org/TR/html5/syntax.html#elements-0 voidElements :: [String] voidElements = [ "area" , "base" , "br" , "col" , "embed" , "hr" , "img" , "input" , "keygen" , "link" , "meta" , "param" , "source" , "track" , "wbr" ] normalElements :: [String] normalElements = [ "a" , "blockquote" , "button" , "circle" , "code" , "div" , "em" , "h1" , "h2" , "h3" , "h4" , "h5" , "h6" , "i" , "li" , "p" , "path" , "pre" , "rect" , "section" , "span" , "strong" , "style" , "svg" , "title" , "ul" , "ol" , "value" ] attributes :: [String] attributes = [ "className" , "cx" , "cy" , "d" , "fill" , "height" , "href" , "r" , "ref" , "rel" , "src" , "stroke" , "strokeWidth" , "type" , "viewBox" , "width" , "x" , "y" ] terms :: [String] terms = nub $ sort $ voidElements ++ normalElements ++ attributes main :: IO () main = do putStr $ removeTrailingNewlines $ unlines [ "{-# LANGUAGE OverloadedStrings #-}" , "{-# LANGUAGE TypeFamilies #-}" , "" , exportList (map sanitize terms) , "" , "import Nauva.Internal.Types" , "import Nauva.View.Types" , "" , "" , unlines $ map makeVoidTerm (nub $ sort $ voidElements) , "" , unlines $ map makeTerm (nub $ sort $ normalElements) , "" , unlines $ map makeAttributeTerm (nub $ sort $ attributes) ] where removeTrailingNewlines = reverse . drop 2 . reverse
wereHamster/nauva
pkg/hs/nauva/src/Nauva/View/Terms.Generator.hs
mit
3,080
0
14
1,026
801
456
345
121
3
{-# LANGUAGE OverloadedStrings, RankNTypes, FlexibleContexts #-} module FTag (module FTag.Data, module FTag) where import Database.Persist import Database.Persist.Sqlite import Data.Text hiding (map) import Control.Exception import Control.Monad.IO.Class import Data.Maybe (catMaybes) import Data.List (nub) import Control.Monad.Trans.Reader import Env import Env.Paths import FTag.Data import FTag.Sort import FTag.AtomicSets import qualified FTag.DB as DB import FTag.DB.Errors (silentFail) import qualified FTag.Expr as E runFTag :: (MonadIO m) => FTEnv -> FTag a -> m a runFTag e a = runReaderT a e testFTag :: (MonadIO m) => [(TagN, Text, Maybe Text)] -> DBAction a -> m a testFTag t a = runFTag testEnv $ runInDB $ DB.setupDB >> setupTest >> a where setupTest = do mapM_ DB.addFile $ nub $ map (\(_, fn, _) -> StorFileN fn) $ t mapM_ DB.addTag $ nub $ map (\(tn, _, _) -> tn) $ t mapM_ (\(tn, fn, v) -> DB.tagFile tn (StorFileN fn) v) t testEnv = FTEnv False ":memory:" ":memory:" ":memory:" init :: FTag () init = runInDB $ DB.setupDB >> DB.addTag "last_added" -- Functions for adding and removing tags addTag :: [TagN] -> FTag () addTag = runInDB . mapM_ (silentFail . DB.addTag) removeTag :: [TagN] -> FTag () removeTag = runInDB . mapM_ (silentFail . DB.removeTag) listTags :: FTag [TagN] listTags = runInDB $ DB.listTags renameTag :: TagN -> TagN -> FTag () renameTag o n = runInDB $ DB.renameTag o n -- Functions for adding and removing files assertFileExists :: UserFileN -> FTag () assertFileExists n = do exists <- liftIO $ pathExists $ unU n if exists then return () else throw . FTNoSuchFile <$> toStor n addFile :: [UserFileN] -> FTag () addFile fs = mapM_ assertFileExists fs >> mapM toStor fs >>= runInDB . mapM_ (silentFail . DB.addFile) removeFile :: [UserFileN] -> FTag () removeFile fs = mapM toStor fs >>= runInDB . mapM_ (silentFail . DB.removeFile) listFiles :: FTag [UserFileN] listFiles = runInDB DB.listFiles >>= mapM toUser renameFile :: UserFileN -> UserFileN -> FTag () renameFile o n = do assertFileExists n so <- toStor o sn <- toStor n runInDB (DB.renameFile so sn) -- Functions for tagging and untagging mTagFile :: [(TagN, Maybe Text)] -> [UserFileN] -> FTag () mTagFile ts fs = do fss <- mapM toStor fs runInDB $ mapM_ (\f -> mapM_ (\(t, v) -> silentFail $ DB.tagFile t f v) ts) fss mUntagFile :: [TagN] -> [UserFileN] -> FTag () mUntagFile ts fs = do fss <- mapM toStor fs runInDB $ mapM_ (\f -> mapM_ (\t -> silentFail $ DB.untagFile t f) ts) fss listTagsVals :: UserFileN -> FTag [Text] listTagsVals f = map pp <$> listTagsAndVals f where pp (t, Nothing) = t pp (t, Just v) = t `append` "=" `append` v listTagsAndVals :: UserFileN -> FTag [(TagN, Maybe Text)] listTagsAndVals f = toStor f >>= runInDB . DB.tagsValsForFile removeAllTags :: UserFileN -> FTag () removeAllTags f = do fs <- toStor f runInDB $ DB.tagsForFile fs >>= mapM_ (flip DB.untagFile fs) untagAll :: TagN -> FTag () untagAll t = runInDB $ DB.filesForTag t >>= mapM_ (DB.untagFile t) -- Functions to list expressions lsExpr :: Text -> [TagN] -> FTag [UserFileN] lsExpr e s = E.resolve (E.parse e) >>= sortByTags s >>= mapM toUser listVals :: TagN -> (Maybe Text) -> FTag [Text] listVals t Nothing = runInDB $ DB.listVals t listVals t (Just e) = nub . catMaybes . map maybeVal <$> (E.resolve (E.parse e) >>= mapM (testFile (UASByName t))) -- Functions to add and remove presets addPreset :: Text -> Text -> FTag () addPreset n e = E.exprToStor (E.parse e) >>= runInDB . DB.addPreset n removePreset :: Text -> FTag () removePreset = runInDB . DB.removePreset
chrys-h/ftag
src/FTag.hs
mit
3,692
0
16
732
1,510
777
733
85
2
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.BeforeLoadEvent (js_getUrl, getUrl, BeforeLoadEvent, castToBeforeLoadEvent, gTypeBeforeLoadEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"url\"]" js_getUrl :: BeforeLoadEvent -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/BeforeLoadEvent.url Mozilla BeforeLoadEvent.url documentation> getUrl :: (MonadIO m, FromJSString result) => BeforeLoadEvent -> m result getUrl self = liftIO (fromJSString <$> (js_getUrl (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/BeforeLoadEvent.hs
mit
1,341
6
10
158
365
233
132
23
1
-- Point in Polygon -- http://www.codewars.com/kata/530265044b7e23379d00076a/ module PointInPolygon where type Point = (Double, Double) pointInPoly :: [Point] -> Point -> Bool pointInPoly poly point = odd . length . filter (intersect (point, 1, 0)) . zip poly $ (tail poly ++ [head poly]) where intersect ((px, py), dx, dy) ((ax, ay), (bx, by)) = (dx*l /= dy*m) && t1 >= 0 && t2 >= 0 && t2 <= 1 where t1 = (m*k - n*l)/(dy*m - dx*l) t2 = (dx*k - dy*n)/(dy*m - dx*l) m = bx - ax n = ax - px l = by - ay k = ay - py
gafiatulin/codewars
src/3 kyu/PointInPolygon.hs
mit
634
0
16
225
297
165
132
11
1
-- | Defining a `KVMap` data structure, which is a string -> string -- mapping that is text encoded in a simple format. module Data.KVMap where import ClassyPrelude import qualified Data.Text as T import qualified Data.HashMap.Strict as H import Data.Attoparsec.ByteString.Lazy (Parser) import Data.Attoparsec.ByteString.Char8 (char, notChar, space, endOfLine, many1) -- | Some nix cache information comes in a line-separated "Key: Value" -- format. Here we represent that as a map. newtype KVMap = KVMap (HashMap Text Text) deriving (Show, Eq, Generic) -- | Class for things which can be represented in KVMaps. class FromKVMap t where fromKVMap :: KVMap -> Either String t -- | KVMaps can be parsed from text. parseKVMap :: Parser KVMap parseKVMap = do many $ endOfLine <|> (space >> return ()) keysVals <- many $ do key <- many1 $ notChar ':' char ':' >> many space val <- many1 $ notChar '\n' many $ endOfLine <|> (space >> return ()) return (T.pack key, T.pack val) return $ KVMap $ H.fromList keysVals
adnelson/nix-binary-cache
src/Data/KVMap.hs
mit
1,082
0
15
241
271
145
126
21
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.Window ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Window #else module Graphics.UI.Gtk.WebKit.DOM.Window #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Window #else import Graphics.UI.Gtk.WebKit.DOM.Window #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/Window.hs
mit
395
0
5
39
31
24
7
4
0
{-# LANGUAGE AutoDeriveTypeable, DeriveDataTypeable, DeriveGeneric, DeriveAnyClass, DeriveFunctor, DeriveFoldable, DeriveTraversable #-} {-# LANGUAGE TemplateHaskell, LambdaCase, TypeFamilies #-} module Data.Sexp where import Derive.List (deriveList) import Control.Lens (Plated (..)) import Data.Foldable (Foldable (..)) import Data.Data (Data) import GHC.Generics (Generic) import GHC.Exts (IsString (..)) import Data.Void (Void) {- | a heterogenous list. a <http://en.wikipedia.org/wiki/Common_Lisp#The_function_namespace Lisp-2> S-expression, where: * @f@ is the function namespace * @a@ is the atom namespace you could define @type Lisp1 a = Sexp a a@. with some caveats: * @f@ is ignored by 'Monad'ic methods like 'joinSexp' * @plate@ doesn't reach the @f@, even when @f ~ a@, as the 'Plated' instance is manual, not automatic via @Data@. the 'List' case is just a specialized @'Sexp' ()@, but easier to work with than: * @Sexp (Maybe f) [Sexp f a]@ (where Nothing would represent 'List') * forcing each concrete @f@ to hold a unit case (which would represent 'List') examples: >>> 'toList' (List [Atom "f",Atom "x",List [Atom "g",Atom "y"],Atom "z"]) ["f","x","g","y","z"] >>> :{ let doubleSexp e = do x <- e listSexp [x,x] :} >>> doubleSexp (List [Atom "f", Sexp () [Atom "a", Atom "b"]]) List [List [Atom "f",Atom "f"],Sexp () [List [Atom "a",Atom "a"],List [Atom "b",Atom "b"]]] -} data Sexp f a = Atom a | List [Sexp f a] | Sexp f [Sexp f a] deriving (Show,Read,Eq,Ord,Functor,Foldable,Traversable,Data,Generic) {-| isomorphic to: @ data Sexp_ a = Atom_ a | List_ [Sexp_ a] @ when you only care about lists (e.g. to interface with other s-expression libraries). -} type Sexp_ = Sexp Void {-| @ data ByteSexp = Atom ByteString | List [ByteSexp] bytesexp2sexp :: ByteSexp -> 'Sexp_' ByteString bytesexp2sexp = 'toSexp' $ \case Atom s -> Left s List es -> Right es @ -} toSexp :: (r -> Either a [r]) -> (r -> Sexp_ a) toSexp f = go where go r = case f r of Left a -> Atom a Right rs -> List (map go rs) -- | default instance via the 'Monad' subclass. instance Applicative (Sexp f) where pure = return (<*>) f x = f >>= (\g -> x >>= (return.g)) {- | definitions: @ 'return' = 'pureSexp' '(>>=)' = 'bindSexp' @ proofs of laws: * left-inverse(1): @join . return = id@ @ join (return m) joinSexp (pureSexp m) joinSexp (Atom m) m @ * left-inverse(2): @join . fmap return = id@ (the Sexp case is elided, the steps being identical to the List case) @ join (fmap return m) joinSexp (fmap pureSexp m) joinSexp (fmap Atom m) -- case analysis case m of Atom x -> joinSexp (Atom (Atom x)) -- by definition of joinSexp Atom x List ms -> joinSexp (List (fmap (fmap Atom) ms) -- by definition of joinSexp List (fmap joinSexp (fmap (fmap Atom) ms)) -- functor composition List (fmap (joinSexp . fmap Atom) ms) List (fmap (join . fmap return) ms) -- by induction List (fmap id ms) -- functor identity List ms -- both cases are identity m @ where: @ fmap f = \case Atom x -> f x List ms -> List (fmap (fmap f) ms) join = \case Atom x -> x List ms -> List (fmap joinSexp ms) @ * associativity(3): @join . join = join . fmap join@ @ TODO @ -} instance Monad (Sexp f) where return = pure (>>=) = bindSexp -- TODO laws, verified as @QuickCheck@ properties: instance Plated (Sexp f a) where plate f = \case Atom a -> Atom <$> pure a List ps -> List <$> traverse f ps Sexp g ps -> Sexp g <$> traverse f ps {-| >>> :set -XOverloadedStrings >>> "x" :: Sexp f String Atom "x" -} instance (IsString a) => IsString (Sexp f a) where fromString = Atom . fromString {-| @pureSexp = 'Atom'@ -} pureSexp :: a -> Sexp f a pureSexp = Atom {-# INLINE pureSexp #-} bindSexp :: Sexp f a -> (a -> Sexp f b) -> Sexp f b bindSexp s f = (joinSexp . fmap f) s {-# INLINE bindSexp #-} {-| -} joinSexp :: Sexp f (Sexp f a) -> Sexp f a joinSexp = \case Atom e -> e List ess -> List (joinSexp <$> ess) Sexp f ess -> Sexp f (joinSexp <$> ess) {-# INLINEABLE joinSexp #-} -- to hit the Atom I hope. deriveList ''Sexp 'List {-| refines any Sexp to a list, which can be given to the 'List'. -} toSexpList :: Sexp f a -> [Sexp f a] {-| >>> appendSexp (Atom "f") (List [Atom "x"]) List [Atom "f",Atom "x"] -} appendSexp :: Sexp f a -> Sexp f a -> Sexp f a {-| @emptySexp = 'List' []@ -} emptySexp :: Sexp f a {-| fold over an sexp. i.e. strictly evaluate a sexp ("all the way") to an atom, within any monadic context. -} evalSexp :: (Monad m) => ([a] -> m a) -> ([a] -> g -> m a) -> Sexp g a -> m a evalSexp list apply = \case Atom a -> pure a List es -> list =<< traverse go es Sexp g es -> (flip apply) g =<< traverse go es where go = evalSexp list apply {-| >>> data ArithFunc = Add | Multiply | Negate deriving Show >>> let badArith = Sexp Negate [Atom 1, Atom 2, Atom 3] :: Sexp ArithFunc Integer >>> let goodArith = Sexp Add [Sexp Multiply [], Sexp Negate [Atom (10::Integer)], Sexp Multiply [Atom 2, Atom 3, Atom 4]] >>> :set -XLambdaCase >>> :{ let evalArith = \case Add -> \case xs -> Just [sum xs] Multiply -> \case xs -> Just [product xs] Negate -> \case [x] -> Just [negate x] _ -> Nothing :} >>> evalSplatSexp (flip evalArith) (fmap (:[]) badArith) -- wrong arity Nothing >>> evalSplatSexp (flip evalArith) (fmap (:[]) goodArith) -- (+ (*) (- 10) (* 2 3 4)) Just [15] specializing, as above, @(m ~ Maybe)@, @(b ~ [Integer])@, @(g ~ ArithFunc)@: @evalSplatSexp :: ([Integer] -> ArithFunc -> Maybe [Integer]) -> (Sexp ArithFunc [Integer] -> Maybe [Integer])@ @evalSplatSexp apply = 'evalSexp' ('pure'.'fold') (apply.'fold')@ -} evalSplatSexp :: (Monad m, Monoid b) => (b -> g -> m b) -> (Sexp g b -> m b) evalSplatSexp apply = evalSexp (pure.fold) (apply.fold) {-# INLINE evalSplatSexp #-} {-| when a Sexp\'s atoms are 'Monoid'al ("list-like"), after evaluating some expressions into atoms, we can "splat" them back together. @splatList@ takes: * an evaluator @eval@ * and a list of s-expressions @es@ to evaluate in sequence. -} splatSexpList :: (Applicative m, Monoid b) => (Sexp g b -> m b) -> [Sexp g b] -> m b splatSexpList eval = fmap fold . traverse eval {-# INLINE splatSexpList #-} {-| inject a list of atoms. >>> listSexp [1,2,3] List [Atom 1,Atom 2,Atom 3] -} listSexp :: [a] -> Sexp f a listSexp = List . map Atom {-# INLINE listSexp #-} -- data SexpF f a r -- = AtomF a -- | FuncF (f r) -- | ListF [r] -- deriving (Show,Read,Eq,Ord,Functor,Data,Generic) -- type Sexp' a = Fix (SexpF a) {- helper when converting from other sexp types, like from a parsing library. @Either Bytestring [Bytestring]@ is isomorphic to: e.g. the @atto-lisp@ package defines: @ data Lisp = Symbol Text -- ^ A symbol (including keyword) | String Text -- ^ A string. | Number Number -- ^ A number | List [Lisp] -- ^ A proper list: @(foo x 42)@ | DotList [Lisp] Lisp -- ^ A list with a non-nil tail: @(foo x -- . 42)@. The list argument must be -- non-empty and the tail must be non-'nil'. @ we can define: @ type AttoLispSexp = Sexp AttoLispFunc AttoLispAtom data AttoLispAtom = SymbolAtom Text | StringAtom Text | NumberAtom Number TODO data AttoLispFunc r = DotListFunc [r] r @ -} -- fromSexp :: -> -- fromSexp = -- toSexp :: -> -- toSexp =
sboosali/s-expression
sources/Data/Sexp.hs
mit
7,867
0
12
2,077
1,054
555
499
64
3
{-# htermination keysFM_GE :: FiniteMap Char b -> Char -> [Char] #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_keysFM_GE_3.hs
mit
86
0
3
14
5
3
2
1
0
{-# LANGUAGE TemplateHaskell #-} module UnitTest.RequestParse.AccountUnlinking where import Data.Aeson (Value) import Data.Yaml.TH (decodeFile) import Test.Tasty as Tasty import Web.Facebook.Messenger import UnitTest.Internal ----------------------- -- ACCOUNT UNLINKING -- ----------------------- accountUnlinkVal :: Value accountUnlinkVal = $$(decodeFile "test/json/request/account_unlinking.json") accountUnlinkTest :: TestTree accountUnlinkTest = parseTest "Account Unlinking Request" accountUnlinkVal $ AccountUnlinkRequest $ PSID "PSID"
Vlix/facebookmessenger
test/UnitTest/RequestParse/AccountUnlinking.hs
mit
568
0
7
74
93
56
37
-1
-1
module ObjCSyntax where data Interface = Interface Name [Property] [Method] data Property = Property [PropertyModifier] Type Name data PropertyModifier = Nonatomic | Strong | Weak | Copy data Implementation = Implementation Name [Method] data Method = Method ClassOrInstance ReturnType MethodName Body data ClassOrInstance = Class | Instance data MethodName = SimpleName String | NameWithArguments [Argument] data Argument = Argument String Type String data Type = Scalar String | Id | Pointer Type | QualifiedWithProtocols Type [String] | Void | InstanceType deriving (Eq, Show) type Name = String type Body = [Statement] data Statement = IfStatement Expression Body | AssignmentStatement Expression AssignmentType Expression | ReturnStatement Expression | EmptyStatement data Expression = Other String | VariableExpr String | PropertyExpr Expression Expression | NotExpr Expression | MessageExpr Expression Selector [Expression] | CastExpr Type Expression | VarExpr Type Expression | IVarExpr Expression Expression | OperatorExpr Expression Operator Expression | AtExpr Expression type Operator = String data Selector = SelectorNoArgument String | SelectorWithArguments [String] data AssignmentType = Equals type ReturnType = Type -- Convenience constructors
chriseidhof/objc-value-objects
ObjCSyntax.hs
mit
1,550
0
7
459
321
189
132
38
0
{-# OPTIONS -Wall #-} import Data.Functor (($>)) import Data.Set (Set) import qualified Data.Set as Set import Helpers.Parse import Text.Parsec type Input = [([Set Segment], [Set Segment])] data Segment = A | B | C | D | E | F | G deriving (Eq, Ord, Show) main :: IO () main = do input <- parseInput let outputValues = concatMap snd input let answer = sum $ map (`countOfSize` outputValues) [2, 4, 3, 7] print answer countOfSize :: Int -> [Set Segment] -> Int countOfSize n = length . filter (\segments -> Set.size segments == n) parseInput :: IO Input parseInput = parseLinesIO $ do signalPatterns <- filter (not . Set.null) <$> sepBy segments (string " ") _ <- string "| " outputValue <- sepBy segments (string " ") return (signalPatterns, outputValue) where segments = Set.fromList <$> many segment segment = choice [ char 'a' $> A, char 'b' $> B, char 'c' $> C, char 'd' $> D, char 'e' $> E, char 'f' $> F, char 'g' $> G ]
SamirTalwar/advent-of-code
2021/AOC_08_1.hs
mit
1,043
0
13
288
423
223
200
33
1
import Data.Numbers.Primes (primes) tenThousandFirstPrime :: Integer tenThousandFirstPrime = primes !! 10000 -- tenThousandFirstPrime == 104743
samidarko/euler
problem007.hs
mit
147
0
5
18
27
16
11
3
1
module Feature.Common.Util where import ClassyPrelude orThrow :: Monad m => m (Maybe a) -> e -> m (Either e a) orThrow action e = maybe (Left e) Right <$> action
eckyputrady/haskell-scotty-realworld-example-app
src/Feature/Common/Util.hs
mit
165
0
10
33
75
38
37
5
1
sumsqr :: Int -> Int sumsqr n = sum [x^2 | x <- [1..n]] sumsqr' :: Int -> Int sumsqr' n = sum (map (\x -> x * x) [1..n]) sumsqr'' :: Int -> Int sumsqr'' n = foldl (\acc x -> acc + x^2) 0 [1..n] main = do print $ sumsqr 100 print $ sumsqr' 100 print $ sumsqr'' 100
fabioyamate/programming-in-haskell
ch05/ex01.hs
mit
279
0
10
77
168
85
83
10
1
module Logic where import Control.Monad import Data.List import qualified Data.Map as M import Data.Ord import System.Exit import System.IO import System.Process import Text.Printf import TimeAccounting data Cell = Unknown | Revealed Int | Flagged deriving Show showCell Unknown = "." showCell Flagged = "#" showCell (Revealed 0) = "_" showCell (Revealed n) = show n revealed Unknown = False revealed (Revealed _) = True revealed Flagged = True revealedToN Unknown = error "revealedToN" revealedToN Flagged = (-1) revealedToN (Revealed n) = n type Board = M.Map (Int,Int) Cell boardToDzn :: Board -> String boardToDzn board = concatMap (++"\n") items where clues = M.filter revealed board nclues = M.size clues cluestrings = map (\ ((x,y),cell) -> printf "%d,%d,%d" x y (revealedToN cell)) (M.toList clues) items = [ printf "width = %d;" (fst (fst (M.findMax board)) + 1) , printf "height = %d;" (snd (fst (M.findMax board)) + 1) , printf "nclues = %d;" nclues , "clues = [| " ++ intercalate " | " cluestrings ++ " |];" ] possibleGuesses :: Board -> [ ((Int,Int), Bool) ] possibleGuesses board = (filter ((/=0) . revealedNeighbours) guesses) where cells = M.filter (not . revealed) board guesses = concatMap (\ ((x,y),Unknown) -> [ ((x,y),True), ((x,y),False) ]) (M.toList cells) revealedNeighbours ((x,y),b) = length (filter g [(x+i,y+j) | i <- [-1,0,1], j <- [-1,0,1]]) unrevealedNeighbours ((x,y),b) = length (filter f [(x+i,y+j) | i <- [-1,0,1], j <- [-1,0,1]]) f (x,y) = case M.lookup (x,y) board of Nothing -> False Just Unknown -> True _ -> False g (x,y) = case M.lookup (x,y) board of Nothing -> False Just (Revealed _) -> True _ -> False testGuess :: Account -> Board -> ((Int,Int), Bool) -> IO Bool testGuess account board ((x,y),b) = do withFile "gecode-input" WriteMode $ \h -> do hPutStrLn h "0" hPutStrLn h (show (fst (fst (M.findMax board)) + 1)) hPutStrLn h (show (snd (fst (M.findMax board)) + 1)) hPrintf h "%d %d %d\n" x y (fromEnum b) let clues = M.filter revealed board nclues = M.size clues mapM_ (\ ((xx,yy),cell) -> hPrintf h "%d %d %d\n" xx yy (revealedToN cell)) (M.toList clues) r <- accountAction account "gecode" $ system "./mines-solve < gecode-input" return (r == ExitFailure 1) propagate :: Account -> Board -> IO [ ((Int,Int), Bool) ] propagate account board = do withFile "gecode-prop-input" WriteMode $ \h -> do hPutStrLn h "1" hPutStrLn h (show (fst (fst (M.findMax board)) + 1)) hPutStrLn h (show (snd (fst (M.findMax board)) + 1)) let clues = M.filter revealed board nclues = M.size clues mapM_ (\ ((xx,yy),cell) -> hPrintf h "%d %d %d\n" xx yy (revealedToN cell)) (M.toList clues) r <- accountAction account "gecode-prop" $ system "./mines-solve < gecode-prop-input > gecode-prop-output" c <- liftM lines (readFile "gecode-prop-output") when ((head c) == "failed") (error "propagation failed!") let output = map specialRead (tail c) usefulOutput = filter ((/= -1) . snd) output novelOutput = filter ( \((x,y),_) -> isUnknown (x,y) board ) usefulOutput return (map (\((x,y),b) -> ((x,y), not (toEnum b))) novelOutput) specialRead :: String -> ((Int,Int),Int) specialRead s = let [a,b,c] = map read $ words s in ((a,b),c) isUnknown (x,y) board = case M.lookup (x,y) board of Nothing -> True Just Unknown -> True _ -> False
cmears/mines-solver
Logic.hs
mit
3,730
0
21
999
1,661
878
783
87
5
import Test.Hspec import Test.QuickCheck import Control.Exception (evaluate) main :: IO () main = hspec $ do describe "Prelude.head" $ do it "returns the first element of a list" $ do head [23 ..] `shouldBe` (23 :: Int) it "returns the first element of an *arbitrary* list" $ property $ \x xs -> head (x:xs) == (x :: Int) it "throws an exception if used with an empty list" $ do evaluate (head []) `shouldThrow` anyException
manuel-io/snake
spec/Spec.hs
mit
464
0
18
114
153
78
75
12
1
module LexML.Linker.RegrasSTF ( pSTF ) where import Data.Char import Data.Maybe import Control.Monad import Control.Monad.Trans import Control.Monad.Except import Control.Monad.Identity import Control.Monad.State import LexML.Linker.Decorator (DecorationMap, addURN) import Data.Typeable import LexML.Linker.LexerPrim (Token, TokenData(..), tokenDataLength) import LexML.URN.Utils import LexML.URN.Types import qualified Data.Map as M import Text.Parsec import Text.Parsec.Prim import Text.Parsec.Pos (newPos) import LexML.URN.Types import LexML.URN.Show import qualified LexML.URN.Atalhos as U import LexML.Linker.ParserBase import Prelude hiding (log) import qualified LexML.Linker.Municipios as M import qualified LexML.Linker.Estados as E import System.Log.Logger --pSTF :: ParseCase2 --pSTF = fail "failed" type SelectF = URNLexML -> URNLexML data Norma = Lei | LeiComplementar | LeiDelegada | Decreto | DecretoLei | ProjetoLei | ProjetoLeiComplementar | MedidaProvisoria | Regimento | Resolucao log :: String -> LinkerParserMonad () log = logRegras log'' :: String -> LinkerParserMonad () log'' msg = do lh <- try (eof >> return Nothing) <|> (lookAhead anyToken >>= return . Just) log $ msg ++ " (lh: " ++ show lh ++ ")" pSTF :: ParseCase2 pSTF = constanteI "leg" >>= pSTF' pSTF' :: Pos -> ParseCase2 pSTF' initial = do hifen >> choice [ constantes [ "FED", "***" ] >> pEsferaFederal , constantes [ "EST" ] >> pEsferaEstadual , constantes [ "MUN" ] >> pEsferaMunicipal , constantes [ "DIS" ] >> pEsferaDistrital ] where pEsferaFederal :: ParseCase2 pEsferaFederal = choice [ pLei Nothing (Just $ A_Convencionada $ AC_Federal) ] pEsferaEstadual :: ParseCase2 pEsferaEstadual = fail "not implemented" pEsferaMunicipal :: ParseCase2 pEsferaMunicipal = fail "not implemented" pEsferaDistrital :: ParseCase2 pEsferaDistrital = fail "not implemented" pLei :: (Maybe DetalhamentoLocal) -> (Maybe Autoridade) -> ParseCase2 pLei detLocal (Just autoridade) = do tipoNorma <- choice [ constanteI t >> return c | (t,c) <- [ ("lei",["lei"]) , ("lcp",["lei","complementar"]) , ("ldl",["lei","delegada"]) , ("mpr",["medida","provisoria"]) , ("dec",["decreto"]) , ("del",["decreto","lei"]) ] ] hifen (_,num) <- pNumeroNorma constanteI "ano" hifen (final,ano) <- pAnoLei return $ [(initial,final, U.selecionaLocal (Local Brasil detLocal) . U.selecionaNorma'' tipoNorma num ano Nothing Nothing Nothing (Just autoridade))] where pAnoLei = pAnoLei1 <|> pAnoLei2 pAnoLei1 = do hifen (p,n) <- numero let n' = if n < 100 then n+1900 else n return (p, fromInteger n) pAnoLei2 = do (p,n) <- numero return (p, fromInteger n) pLei _ _ = fail "not implemented" pNumeroNorma :: LinkerParserMonad (Pos,[Integer]) pNumeroNorma = do (p,n) <- numero return (p, [n]) numero :: LinkerParserMonad (Pos,Integer) numero = lToken f where f (Numero n _) = Just n f _ = Nothing
lexml/lexml-linker
src/main/haskell/LexML/Linker/RegrasSTF.hs
gpl-2.0
3,271
0
16
819
990
557
433
86
4
ver 0 b c = b + 1 ver a 0 c = ver (a-1) c c ver a b c = ver (a-1) (ver a (b-1) c) c
btrzcinski/synacor-challenge
hs/ver.hs
gpl-2.0
85
0
9
30
86
43
43
3
1
{-# LANGUAGE ScopedTypeVariables #-} module Robots3.Solver where -- $Id$ import Robots3.Config import Robots3.Data import Robots3.Move import Robots3.Final import Robots3.Hull import Robots3.Nice import Robots3.Final import Robots3.Examples import Autolib.Schichten import Data.Maybe import Autolib.Set import Autolib.ToDoc import Autolib.Reporter ( export ) import Control.Monad ( guard ) nachfolger :: Config -> [ Config ] nachfolger k = do ( z, k' ) <- znachfolger k return k' znachfolger :: Config -> [ ( Zug, Config ) ] znachfolger k = do let ( t, _ :: Doc ) = export $ valid k guard $ isJust t r <- robots k d <- richtungen let z = Zug { robot = name r, richtung = d } k' <- maybeToList $ execute k z guard $ covered k' return ( z, k' ) reachables :: Config -> [[ Config ]] reachables k = map setToList $ schichten ( mkSet . nachfolger ) k solutions :: Config -> [ ((Int, Int), [[Zug]]) ] solutions k = do (d, ps) <- zip [0 :: Int ..] $ schichten ( mkSet . nachfolger ) k let out = do p <- setToList ps let ( t, _ :: Doc ) = export $ final p guard $ isJust t return $ reverse $ geschichte p return $ (( d, length out), filter (not . null) out) solutions' :: Int -> Config -> [ ((Int, Int), [[Zug]]) ] solutions' sw k = do (d, ps) <- zip [0 :: Int ..] $ takeWhile ( \ zss -> cardinality zss < sw ) $ schichten ( mkSet . nachfolger ) k let out = do p <- setToList ps let ( t, _ :: Doc ) = export $ final p guard $ isJust t return $ reverse $ geschichte p return $ (( d, length out), filter (not . null) out) solve :: Config -> IO () solve k = sequence_ $ map ( print . toDoc ) $ solutions k shortest :: Config -> [[Zug]] shortest k = take 1 $ do ( _ , zss ) <- solutions k zss shortest' :: Int -> Config -> [[Zug]] shortest' sw k = take 1 $ do ( _ , zss ) <- solutions' sw k zss vorganger :: Config -> [ Config ] vorganger c = do r <- robots c d <- richtungen let z = Zug { robot = name r, richtung = d } reverse_executes c z ancestors :: Config -> [[Config]] ancestors c = map setToList $ schichten ( mkSet . vorganger ) c ---------------------------------------------------- ex :: Config ex = Robots3.Config.make [ Robot { name = "A", position = Position {x= -2, y = -2 } } , Robot { name = "B", position = Position {x= 2, y = 3 } } , Robot { name = "C", position = Position {x= -2, y = 1 } } , Robot { name = "D", position = Position {x= 2, y = 0 } } , Robot { name = "E", position = Position {x= -3, y = 1 } } ] [ Position {x= 0, y =0 } ]
Erdwolf/autotool-bonn
src/Robots3/Solver.hs
gpl-2.0
2,702
38
20
772
1,137
616
521
77
1
-- quadratic-to-qubezier.hs import System.Environment (getArgs) -- | Converts y = Ax^2 + Bx + C to QBezier notation. quadToQbez :: Float -- ^ Coefficient of x^2. -> Float -- ^ Coefficient of x. -> Float -- ^ Constant term. -> [(Float, Float)] -- ^ Curve in QBez notation. quadToQbez a b c = [(x0, y0), (x1, y1), (x2, y2)] where x0 = -b / (2 * a) - 1 y0 = f x0 x1 = -b / (2 * a) y1 = f x0 + f' x0 x2 = -b / (2 * a) + 1 y2 = f x2 f x = a * x^2 + b * x + c f' x = 2 * a * x + b -- | Converts two points with derivative to QBezier notation. splineToQbez :: (Float, Float, Float) -- ^ First point, with slope -> (Float, Float, Float) -- ^ Second point, with slope -> [(Float, Float)] -- ^ Curve in QBez notation. splineToQbez (x0,y0,s0) (x2,y2,s2) = [(x0,y0),(x1,y1),(x2,y2)] where x1 = (s0 * x0 - s2 * x2 - y0 + y2) / (s0 - s2) y1 = s0 * (x1 - x0) + y0 -- | Console wrapper for quadToQbez. main :: IO () main = print . unQuadToQbez . toTuple . map read =<< getArgs where unQuadToQbez = uncurry . uncurry $ quadToQbez toTuple (a:b:c:[]) = ((a, b), c)
friedbrice/Haskell
quadratic-to-qubezier.hs
gpl-2.0
1,217
3
11
401
484
269
215
24
1
{- | Module : $Id: h2hf.hs 18342 2013-11-29 02:57:59Z sternk $ Description : a test driver for Haskell to Isabelle HOLCF translations Copyright : (c) Christian Maeder, Uni Bremen 2002-2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : experimental Portability : non-portable(uses programatica) test translation from Haskell to Isabelle -} module Main where import System.Environment import Data.Char import Text.ParserCombinators.Parsec import Common.Result import Common.AnnoState import Common.AS_Annotation import Common.GlobalAnnotations import Common.ExtSign import Comorphisms.Hs2HOLCF import Isabelle.IsaPrint import Isabelle.IsaSign as IsaSign import Haskell.HatAna as HatAna import Haskell.HatParser pickParser :: (Continuity, Bool) -> AParser () (IsaSign.Sign, [Named IsaSign.Sentence]) pickParser c = do b <- hatParser let res@(Result _ m) = do (_, ExtSign sig _, sens) <- hatAna (b, HatAna.emptySign, emptyGlobalAnnos) uncurry transTheory c sig sens case m of Nothing -> fail $ show res Just x -> return x main :: IO () main = do let err = "command line input error: first argument must be" ++ " either h (HOL), hc (HOLCF), mh (HOL with theory morphisms)," ++ " mhc (HOLCF with theory morphisms)." l <- getArgs case l of [] -> putStrLn err c : fs -> let elm = elem $ map toLower c in mapM_ (process (if elm ["h", "hol"] then (NotCont, False) else if elm ["hc", "holcf"] then (IsCont True, False) else if elm ["mh", "mhol"] then (NotCont, True) else if elm ["mhc", "mholcf"] then (IsCont True, True) else error err)) fs process :: (Continuity, Bool) -> FilePath -> IO () process c fn = do putStrLn $ "translating " ++ show fn ++ " to " ++ case c of (IsCont _, False) -> "HOLCF" (NotCont, False) -> "HOL" (IsCont _, True) -> "HOLCF with theory morphisms" (NotCont, True) -> "HOL with theory morphisms" s <- readFile fn case runParser (pickParser c) (emptyAnnos ()) fn s of Right (sig, hs) -> do let tn = takeWhile (/= '.') (reverse . takeWhile (/= '/') $ reverse fn) ++ "_" ++ case c of (IsCont _, False) -> "hc" (NotCont, False) -> "h" (IsCont _, True) -> "mhc" (NotCont, True) -> "mh" nsig = sig {theoryName = tn} doc = printIsaTheory tn nsig hs thyFile = tn ++ ".thy" putStrLn $ "writing " ++ show thyFile writeFile thyFile (shows doc "\n") Left err -> print err
nevrenato/HetsAlloy
Haskell/h2hf.hs
gpl-2.0
2,772
0
22
830
780
410
370
62
8
module Main where import Control.Monad import Control.Concurrent import Control.Concurrent.STM main = do shared <- atomically $ newTVar 0 before <- atomRead shared putStrLn $ "Before: " ++ show before forkIO $ 25 `timesDo` (dispVar shared >> milliSleep 20) forkIO $ 10 `timesDo` (appV ((+) 2) shared >> milliSleep 50) forkIO $ 20 `timesDo` (appV pred shared >> milliSleep 25) milliSleep 800 after <- atomRead shared putStrLn $ "After: " ++ show after where timesDo = replicateM_ milliSleep = threadDelay . (*) 1000 atomRead = atomically . readTVar dispVar x = atomRead x >>= print appV fn x = atomically $ readTVar x >>= writeTVar x . fn
tormeh/uniproject
haskell/stm.hs
gpl-2.0
730
0
12
199
256
127
129
18
1
module Problem001 (answer) where answer :: Int answer = sum $ filter (\x -> x `mod` 3 == 0 || x `mod` 5 == 0) [1..999]
geekingfrog/project-euler
Problem001.hs
gpl-3.0
120
0
13
27
65
38
27
3
1
module HakeModule ( targets , moreFile , deps ) where import Control.Arrow targetDependPairs :: [ (String, [ String ]) ] targetDependPairs = [ (firstSampleXhtml , firstSampleXhtmlMoreFile ) , (useRuleXhtml , useRuleXhtmlMoreFile ) , (useDefaultXhtml , useDefaultXhtmlMoreFile ) , (useAddDepsXhtml , useAddDepsXhtmlMoreFile ) , (useRuleSSXhtml , useRuleSSXhtmlMoreFile ) , (useRuleVXhtml , useRuleVXhtmlMoreFile ) , (useGetValsXhtml , useGetValsXhtmlMoreFile ) , (fileAgainXhtml , fileAgainXhtmlMoreFile ) , (useGetNewersXhtml , useGetNewersXhtmlMoreFile ) , (useHakefileIsXhtml , useHakefileIsXhtmlMoreFile) , (useDelRulesXhtml , useDelRulesXhtmlMoreFile ) , (useModuleXhtml , useModuleXhtmlMoreFile ) , ("use_f_option.xhtml" , [ "myHakefile.hs_use_f_option" ] ) ] targets :: [ String ] targets = map fst targetDependPairs moreFile :: [ String ] moreFile = concatMap snd targetDependPairs deps :: [ (String, [String]) ] deps = map (second ("Variables.hs":)) targetDependPairs firstSampleXhtml, useRuleXhtml, useDefaultXhtml, useAddDepsXhtml :: String firstSampleXhtml = "first_sample.xhtml" useRuleXhtml = "use_rule.xhtml" useDefaultXhtml = "use_default.xhtml" useAddDepsXhtml = "use_addDeps.xhtml" useRuleSSXhtml = "use_ruleSS.xhtml" useRuleVXhtml = "use_ruleV.xhtml" useGetValsXhtml = "use_getVals.xhtml" fileAgainXhtml = "file_again.xhtml" useGetNewersXhtml = "use_getNewers.xhtml" useHakefileIsXhtml = "use_hakefileIs.xhtml" useDelRulesXhtml = "use_delRules.xhtml" useModuleXhtml = "use_module.xhtml" firstSampleXhtmlMoreFile, useRuleXhtmlMoreFile, useDefaultXhtmlMoreFile :: [ String ] firstSampleXhtmlMoreFile = [ "Hakefile_first_sample" ] useRuleXhtmlMoreFile = [ "Hakefile_use_rule" , "Hakefile_use_rule_FunSetRaw" ] useDefaultXhtmlMoreFile = [ "Hakefile_use_default" ] useAddDepsXhtmlMoreFile = [ "Hakefile_use_addDeps" ] useRuleSSXhtmlMoreFile = [ "Hakefile_use_ruleSS" ] useRuleVXhtmlMoreFile = [ "Hakefile_use_ruleV" ] useGetValsXhtmlMoreFile = [ "Hakefile_use_getVals" ] fileAgainXhtmlMoreFile = [ "Hakefile_file_again" ] useGetNewersXhtmlMoreFile = [ "Hakefile_use_getNewers" ] useHakefileIsXhtmlMoreFile = [ "Hakefile_use_hakefileIs" ] ++ moreMoreFile useDelRulesXhtmlMoreFile = [ "Hakefile_use_delRules" ] useModuleXhtmlMoreFile = [ "Hakefile_use_module" ] ++ moreMoreFile2 moreMoreFile = [ "hakeMain.hs_use_hakefileIs", "Variables.hs_use_hakefileIs" ] moreMoreFile2 = [ "Variables.hs_use_module" ]
YoshikuniJujo/hake_haskell
web_page/short_tutorial/HakeModule.hs
gpl-3.0
2,605
0
8
437
444
281
163
54
1
module Main where import Application.PVP2LibLinear.ArgsParser as AP import Application.PVP2LibLinear.Conduit import Application.PVP2LibLinear.Utility import Classifier.LibLinear import Control.Monad as M import Data.Conduit import Data.Conduit.List as CL import Data.List as L import PetaVision.Data.Pooling import PetaVision.PVPFile.IO import PetaVision.Utility.Parallel as PA import Prelude as P import System.Environment import Control.Monad.Trans.Resource main = do args <- getArgs if null args then error "run with --help to see options." else return () params <- parseArgs args header <- M.mapM (readPVPHeader . P.head) (pvpFile params) let source = P.map (\filePath -> (sequenceSources . P.map pvpFileSource $ filePath) =$= CL.concat) (pvpFile params) dims = dimOffset header if poolingFlag params then do putStrLn $ "Using CPU for " ++ show (poolingType params) ++ " Pooling" runResourceT $ sequenceSources (P.zipWith (\s offset -> s =$= poolVecConduit (ParallelParams (AP.numThread params) (AP.batchSize params)) (poolingType params) (poolingSize params) offset) source (snd . unzip $ dims)) $$ concatPooledConduit =$ predictConduit =$= mergeSource (sequenceSources (if L.isSuffixOf ".pvp" . L.head . labelFile $ params then (P.map pvpLabelSource $ labelFile params) else (P.map labelSource $ labelFile params)) =$= CL.concat) =$= predict (modelName params) "result.txt" else runResourceT $ sequenceSources source $$ concatConduit (snd . unzip $ dims) =$= predictConduit =$= mergeSource (sequenceSources (if L.isSuffixOf ".pvp" . L.head . labelFile $ params then (P.map pvpLabelSource $ labelFile params) else (P.map labelSource $ labelFile params)) =$= CL.concat) =$= predict (modelName params) "result.txt"
XinhuaZhang/PetaVisionHaskell
Application/PVP2LibLinear/Test.hs
gpl-3.0
2,857
0
26
1,358
581
303
278
64
5
module Util where import Data.List import qualified Data.Map as Map import Data.Maybe (fromMaybe) import System.Info (os) joinWith :: String -> [String] -> String joinWith = intercalate joinWithSpace :: [String] -> String joinWithSpace = unwords joinWithComma :: [String] -> String joinWithComma = intercalate", " joinWithUnderscore :: [String] -> String joinWithUnderscore = intercalate"_" joinWithPeriod :: [String] -> String joinWithPeriod = intercalate"." pairwise :: Show a => [a] -> [(a, a)] pairwise [] = [] pairwise (x : y : xs) = (x, y) : pairwise xs pairwise leftover = error ("An uneven number of forms sent to pairwise: " ++ show leftover) compilerError :: String -> a compilerError msg = error ("Internal compiler error: " ++ msg) -- | Unwraps a Maybe value a to Right a, or returns a default value (Left b) if it was Nothing. toEither :: Maybe a -> b -> Either b a toEither a b = case a of Just ok -> Right ok Nothing -> Left b replaceChars :: Map.Map Char String -> String -> String replaceChars dict = concatMap replacer where replacer c = fromMaybe [c] (Map.lookup c dict) addIfNotPresent :: Eq a => a -> [a] -> [a] addIfNotPresent x xs = if x `elem` xs then xs else xs ++ [x] remove :: (a -> Bool) -> [a] -> [a] remove f = filter (not . f) enumerate :: Int -> String enumerate 0 = "first" enumerate 1 = "second" enumerate 2 = "third" enumerate 3 = "fourth" enumerate 4 = "fifth" enumerate 5 = "sixth" enumerate 6 = "seventh" enumerate n = show n ++ ":th" data Platform = Linux | MacOS | Windows deriving (Show, Eq) platform :: Platform platform = case os of "linux" -> Linux "darwin" -> MacOS "mingw32" -> Windows
eriksvedang/Carp
src/Util.hs
mpl-2.0
1,710
0
10
371
608
325
283
51
3
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} -- Module : Khan.Model.SSH -- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : experimental -- Portability : non-portable (GHC extensions) module Khan.Model.SSH ( Mode (..) , execSCP , execSSH , wait ) where import qualified Data.Text as Text import qualified Filesystem.Path.CurrentOS as Path import Khan.Internal import Khan.Prelude import System.Process (callCommand) data Mode = Upload !FilePath !FilePath | Download !FilePath !FilePath deriving (Show) execSCP :: MonadIO m => Mode -> Text -> Text -> FilePath -> [String] -> m () execSCP mode addr user key xs = exec "scp" (as ++ xs) where as = map Text.unpack $ ident : case mode of Upload s d -> [toTextIgnore s, remote d] Download s d -> [remote s, toTextIgnore d] remote = mappend (user <> "@" <> addr <> ":") . toTextIgnore ident = "-i" <> toTextIgnore key execSSH :: MonadIO m => Text -> Text -> FilePath -> [String] -> m () execSSH addr user key xs = exec "ssh" (args addr user key xs) wait :: MonadIO m => Int -> Text -> Text -> FilePath -> m Bool wait s addr user key = do say "Waiting {} seconds for SSH connectivity on {}" [show s, Text.unpack addr] liftIO (go s) where delay = 20 go n | n <= 0 = return False | otherwise = do say "Waiting {} seconds..." [delay] delaySeconds delay e <- runEitherT . sync $ exec "ssh" xs either (const . go $ n - delay) (return . const True) e xs = args addr user key [ "-q" , "-o" , "BatchMode=yes" , "-o" , "StrictHostKeyChecking=no" , "exit" ] exec :: MonadIO m => String -> [String] -> m () exec run xs = let cmd = unwords (run : xs) in log "{}" [cmd] >> liftIO (callCommand cmd) args :: Text -> Text -> FilePath -> [String] -> [String] args addr user key = mappend [ "-i" <> Path.encodeString key , Text.unpack $ user <> "@" <> addr ]
brendanhay/khan
khan/Khan/Model/SSH.hs
mpl-2.0
2,552
0
14
834
717
370
347
67
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.SQL.Instances.StartReplica -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Starts the replication in the read replica instance. -- -- /See:/ <https://developers.google.com/cloud-sql/ Cloud SQL Admin API Reference> for @sql.instances.startReplica@. module Network.Google.Resource.SQL.Instances.StartReplica ( -- * REST Resource InstancesStartReplicaResource -- * Creating a Request , instancesStartReplica , InstancesStartReplica -- * Request Lenses , insXgafv , insUploadProtocol , insProject , insAccessToken , insUploadType , insCallback , insInstance ) where import Network.Google.Prelude import Network.Google.SQLAdmin.Types -- | A resource alias for @sql.instances.startReplica@ method which the -- 'InstancesStartReplica' request conforms to. type InstancesStartReplicaResource = "v1" :> "projects" :> Capture "project" Text :> "instances" :> Capture "instance" Text :> "startReplica" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Post '[JSON] Operation -- | Starts the replication in the read replica instance. -- -- /See:/ 'instancesStartReplica' smart constructor. data InstancesStartReplica = InstancesStartReplica' { _insXgafv :: !(Maybe Xgafv) , _insUploadProtocol :: !(Maybe Text) , _insProject :: !Text , _insAccessToken :: !(Maybe Text) , _insUploadType :: !(Maybe Text) , _insCallback :: !(Maybe Text) , _insInstance :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'InstancesStartReplica' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'insXgafv' -- -- * 'insUploadProtocol' -- -- * 'insProject' -- -- * 'insAccessToken' -- -- * 'insUploadType' -- -- * 'insCallback' -- -- * 'insInstance' instancesStartReplica :: Text -- ^ 'insProject' -> Text -- ^ 'insInstance' -> InstancesStartReplica instancesStartReplica pInsProject_ pInsInstance_ = InstancesStartReplica' { _insXgafv = Nothing , _insUploadProtocol = Nothing , _insProject = pInsProject_ , _insAccessToken = Nothing , _insUploadType = Nothing , _insCallback = Nothing , _insInstance = pInsInstance_ } -- | V1 error format. insXgafv :: Lens' InstancesStartReplica (Maybe Xgafv) insXgafv = lens _insXgafv (\ s a -> s{_insXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). insUploadProtocol :: Lens' InstancesStartReplica (Maybe Text) insUploadProtocol = lens _insUploadProtocol (\ s a -> s{_insUploadProtocol = a}) -- | ID of the project that contains the read replica. insProject :: Lens' InstancesStartReplica Text insProject = lens _insProject (\ s a -> s{_insProject = a}) -- | OAuth access token. insAccessToken :: Lens' InstancesStartReplica (Maybe Text) insAccessToken = lens _insAccessToken (\ s a -> s{_insAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). insUploadType :: Lens' InstancesStartReplica (Maybe Text) insUploadType = lens _insUploadType (\ s a -> s{_insUploadType = a}) -- | JSONP insCallback :: Lens' InstancesStartReplica (Maybe Text) insCallback = lens _insCallback (\ s a -> s{_insCallback = a}) -- | Cloud SQL read replica instance name. insInstance :: Lens' InstancesStartReplica Text insInstance = lens _insInstance (\ s a -> s{_insInstance = a}) instance GoogleRequest InstancesStartReplica where type Rs InstancesStartReplica = Operation type Scopes InstancesStartReplica = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/sqlservice.admin"] requestClient InstancesStartReplica'{..} = go _insProject _insInstance _insXgafv _insUploadProtocol _insAccessToken _insUploadType _insCallback (Just AltJSON) sQLAdminService where go = buildClient (Proxy :: Proxy InstancesStartReplicaResource) mempty
brendanhay/gogol
gogol-sqladmin/gen/Network/Google/Resource/SQL/Instances/StartReplica.hs
mpl-2.0
5,160
0
19
1,234
784
456
328
116
1
module CCAR.Model.ProjectWorkbench( querySupportedScripts , queryActiveWorkbenches , manageWorkbench , executeWorkbench , testExecuteScript )where import CCAR.Main.DBUtils import GHC.Generics import Data.Aeson as J import Yesod.Core import Control.Monad.IO.Class(liftIO) import Control.Concurrent import Control.Concurrent.STM.Lifted import Control.Concurrent.Async import Control.Exception import qualified Data.Map as IMap import Control.Exception import Control.Monad import Control.Monad.Logger(runStderrLoggingT) import Network.WebSockets.Connection as WSConn import Data.Text as T import Data.Text.Lazy as L import Data.HashMap.Lazy as LH (HashMap, lookup, member) import Database.Persist.Postgresql as DB import Data.Aeson.Encode as En import Data.Text.Lazy.Encoding as E import Data.Aeson as J import Data.HashMap.Lazy as LH (HashMap, lookup) import Control.Applicative as Appl import Data.Aeson.Encode as En import Data.Aeson.Types as AeTypes(Result(..), parse) import GHC.Generics import GHC.IO.Exception import Data.Data import Data.Monoid (mappend) import Data.Typeable import System.IO import System.Locale as Locale import Data.Time import Data.UUID.V1 import Data.UUID as UUID import qualified CCAR.Main.EnumeratedTypes as EnTypes import qualified CCAR.Main.GroupCommunication as GC import CCAR.Main.Util as Util import CCAR.Command.ApplicationError import Database.Persist.Postgresql as Postgresql -- For haskell shell import HSH import System.IO(openFile, writeFile, IOMode(..)) import System.Log.Logger as Logger data CRUD = Create | Read | WrkBench_Update | Delete deriving(Show, Read, Eq, Data, Generic, Typeable) instance ToJSON CRUD instance FromJSON CRUD data QuerySupportedScript = QuerySupportedScript { nickName :: T.Text , commandType :: T.Text , scriptTypes :: [EnTypes.SupportedScript] } deriving (Show, Read, Data, Typeable, Generic) {-- All of the database entities have 2 faces: the one that -- yesod/db layer needs and the other that interfaces with the -- external interfaces. -- Unique project id is the uuid that uniquely identifies the -- project workbench. Trying to relate objects by their unique -- keys is not convenient in the presence of nesting. For example, -- company -> project-> workbench. --} data ProjectWorkbenchT = ProjectWorkbenchT { crudType :: CRUD , workbenchId :: T.Text , uniqueProjectId :: T.Text , scriptType :: EnTypes.SupportedScript , scriptSummary :: T.Text , scriptData :: T.Text , numberOfCores :: Int , scriptDataPath :: Maybe T.Text , jobStartDate :: Maybe UTCTime , jobEndDate :: Maybe UTCTime , workbenchCommandType :: T.Text } deriving(Show, Read, Eq, Data, Generic, Typeable) dto :: CRUD -> T.Text -> ProjectWorkbench -> ProjectWorkbenchT dto c pid p@(ProjectWorkbench _ w s ssummary sdata cores sdPath jobStartDate jobEndDate) = ProjectWorkbenchT c w pid s ssummary (sdata) cores sdPath (jobStartDate) (jobEndDate) "ManageWorkbench" process :: ProjectWorkbenchT -> IO (Either T.Text ProjectWorkbench) process r@(ProjectWorkbenchT cType wId uniqueProjedtId scriptType scriptSummary scriptData numberOfCores scriptDataPath jobStartDate jobEndData wcType ) = case cType of Create -> insertWorkbench r Read -> readWorkbench r WrkBench_Update -> updateWorkbench r Delete -> deleteWorkbench r deleteWorkbench :: ProjectWorkbenchT -> IO (Either T.Text ProjectWorkbench) deleteWorkbench w@(ProjectWorkbenchT cType wId uniqueProjedtId scriptType scriptSummary scriptData numberOfCores scriptDataPath jobStartDate jobEndDate wcType) = dbOps $ do workbench <- getBy $ UniqueWorkbench wId case workbench of Just (Entity k v) -> do Postgresql.delete k liftIO $ return $ Right v Nothing -> liftIO $ return $ Left $ "Workbench not found to delete " `mappend` wId updateWorkbench :: ProjectWorkbenchT -> IO (Either T.Text ProjectWorkbench) updateWorkbench w@(ProjectWorkbenchT cType wId uniqueProjedtId scriptType scriptSummary scriptData numberOfCores scriptDataPath jobStartDate jobEndDate wcType) = dbOps $ do workbench <- getBy $ UniqueWorkbench wId case workbench of Just (Entity k v) -> do Postgresql.replace k rep liftIO $ return $ Right rep where rep = (ProjectWorkbench (projectWorkbenchProject v) wId scriptType scriptSummary scriptData numberOfCores scriptDataPath jobStartDate jobEndDate) Nothing -> liftIO $ return $ Left $ "Workbench not found " `mappend` wId readWorkbench :: ProjectWorkbenchT -> IO (Either T.Text ProjectWorkbench) readWorkbench wT@(ProjectWorkbenchT cType wId uniqueProjedtId scriptType scriptSummary scriptData numberOfCores scriptDataPath jobStartDate jobEndDate wcType) = dbOps $ do workbench <- getBy $ UniqueWorkbench wId case workbench of Just (Entity kWork w) -> return $ Right w Nothing -> return $ Left $ "Reading workbench " `mappend` wId insertWorkbench :: ProjectWorkbenchT -> IO (Either T.Text ProjectWorkbench) insertWorkbench w@(ProjectWorkbenchT cType wId uniqueProjectId scriptType scriptSummary scriptData numberOfCores scriptDataPath jobStartDate jobEndDate wcType ) = do uuidM <- nextUUID case uuidM of Just uuid -> do dbOps $ do project <- getBy $ UniqueProject uniqueProjectId case project of Just (Entity prKey project) -> do -- We need to address the -- case where the insert may fail -- due to unique workbench id. wid <- insert $ ProjectWorkbench prKey uuidAsString scriptType scriptSummary scriptData numberOfCores scriptDataPath jobStartDate jobEndDate resP <- get wid case resP of Just r -> liftIO $ return $ Right r Nothing -> liftIO $ return $ Left $ "Entity not found " `mappend` uuidAsString Nothing -> liftIO $ return $ Left ("Project " `mappend` uuidAsString `mappend` " not found" :: T.Text) where uuidAsString = T.pack $ UUID.toString uuid Nothing -> return $ Left ("UUID generated too quickly") data QueryAllWorkbenches = QueryAllWorkbenches { qaNickName :: T.Text , qaCommandType :: T.Text , projectId :: T.Text , workbenches :: [ProjectWorkbenchT] }deriving (Show, Eq, Data, Generic, Typeable) instance ToJSON QueryAllWorkbenches where toJSON p@(QueryAllWorkbenches n c pid workbenches) = object [ "nickName" .= n , "commandType" .= c , "projectId" .= pid , "workbenches" .= workbenches ] instance FromJSON QueryAllWorkbenches where parseJSON (Object a ) = QueryAllWorkbenches <$> (a .: "nickName") <*> (a .: "commandType") <*> (a .: "projectId") <*> (a .: "workbenches") parseJSON _ = Appl.empty instance ToJSON QuerySupportedScript instance FromJSON QuerySupportedScript instance ToJSON ProjectWorkbenchT where toJSON p@(ProjectWorkbenchT c wid pid stype sSummary sdata n sdp jsd jen wcType ) = object [ "crudType" .= c , "workbenchId" .= wid , "uniqueProjectId" .= pid , "scriptType" .= stype , "scriptSummary" .= sSummary , "scriptData" .= sdata , "numberOfCores" .= n , "scriptDataPath" .= sdp , "jobStartDate" .= jsd , "jobEndDate" .= jen , "commandType" .= wcType ] {-- data ProjectWorkbenchT = ProjectWorkbenchT { crudType :: CRUD , workbenchId :: T.Text , uniqueProjectId :: T.Text , scriptType :: EnTypes.SupportedScript , scriptSummary :: T.Text , scriptData :: T.Text , numberOfCores :: Int , scriptDataPath :: Maybe T.Text , jobStartDate :: Maybe UTCTime , jobEndDate :: Maybe UTCTime , workbenchCommandType :: T.Text } deriving(Show, Read, Eq, Data, Generic, Typeable) --} instance FromJSON ProjectWorkbenchT where parseJSON (Object a ) = ProjectWorkbenchT <$> (a .: "crudType") <*> (a .: "workbenchId") <*> (a .: "uniqueProjectId") <*> (a .: "scriptType") <*> (a .: "scriptSummary") <*> (a .: "scriptData") <*> (a .: "numberOfCores") <*> (a .: "scriptDataPath") <*> (a .: "jobStartDate") <*> (a .: "jobEndDate") <*> (a .: "commandType") parseJSON _ = Appl.empty -- The project uuid (not the internal database id) selectActiveWorkbenches aProjectId = dbOps $ do project <- getBy $ UniqueProject aProjectId case project of Just (Entity k v) -> selectList [ProjectWorkbenchProject ==. k] [LimitTo 50] -- Nothing -> ?? {--Review comments: should these queries that dont depend on the database be in a separate module. Maintaining it as part of the module help reduce namespace issues. --} querySupportedScripts :: T.Text -> Value -> IO(GC.DestinationType, T.Text) querySupportedScripts n (Object a) = return(GC.Reply, Util.serialize $ QuerySupportedScript n "QuerySupportedScripts" EnTypes.getSupportedScripts) queryActiveWorkbenches aValue@(Object a) = do case (fromJSON aValue) of Success (QueryAllWorkbenches n c pid ws) -> do activeW <- selectActiveWorkbenches pid activeWE <- mapM (\x@(Entity k v) -> return $ dto Read pid v) activeW return (GC.Reply, serialize $ QueryAllWorkbenches n c pid activeWE) Error errorMsg -> return (GC.Reply, serialize $ appError $ "Error processing query active workbenches " ++ errorMsg) manageWorkbench :: Value -> IO (GC.DestinationType, T.Text) manageWorkbench aValue@(Object a) = do case (fromJSON aValue) of Success r -> do res <- process r case res of Right wbR@(ProjectWorkbench project workbenchId scriptType scriptSummary scriptData numberOfCores scriptDataPath jobStartDate jobEndDate) -> return (GC.Reply, serialize r { workbenchId = workbenchId , scriptType = scriptType , scriptData = scriptData , scriptSummary = scriptSummary , numberOfCores = numberOfCores , scriptDataPath = scriptDataPath , jobStartDate = jobStartDate , jobEndDate = jobEndDate }) -- If things work, return the original value? Left f -> return (GC.Reply, serialize $ appError $ "Error processing manageWorkbench " ++ (T.unpack f)) Error errorMsg -> return (GC.Reply, serialize $ appError $ "Error in manageworkbench " ++ errorMsg) -- To not having carry the id around. -- need a readerT unknownId = "REPLACE_ME" data ExecuteWorkbench = ExecuteWorkbench { executeWorkbenchId :: T.Text , executeWorkbenchCommandType :: T.Text , scriptResult :: T.Text }deriving (Show, Read, Eq, Data, Generic, Typeable) instance ToJSON ExecuteWorkbench instance FromJSON ExecuteWorkbench type ScriptContent = T.Text type WorkbenchIdText = T.Text iModuleName :: String iModuleName = "CCAR.Model.ProjectWorkbench" getScriptDetails :: WorkbenchIdText -> IO (EnTypes.SupportedScript, ScriptContent, Int) getScriptDetails anId = dbOps $ do workbench <- getBy $ UniqueWorkbench anId case workbench of Just (Entity k v@(ProjectWorkbench p w' sT' ss' sD n' sdp' js' je')) -> return $ (sT', sD, n') formatTimestamp = formatTime Locale.defaultTimeLocale "%D_%T" type Core = Int executeScript :: T.Text -> EnTypes.SupportedScript -> T.Text -> T.Text -> Core -> IO ExecuteWorkbench executeScript nn EnTypes.UnsupportedScriptType scriptId scriptData nCores = return $ ExecuteWorkbench unknownId "ExecuteWorkbench" $ " Unsupported type " `mappend` T.pack (show EnTypes.UnsupportedScriptType) executeScript nickName EnTypes.RScript scriptUUID scriptData nCores = do timeStamp <- Data.Time.getCurrentTime Logger.debugM iModuleName $ "Reading script file " ++ (scriptFileName timeStamp) bR <- bracket(openFile (scriptFileName timeStamp) WriteMode) hClose $ \h -> do hPutStr h (T.unpack scriptData) Logger.debugM iModuleName $ "Bracket returned " `mappend` (show bR) createDir <- tryEC $ run $ ("mkdir -p " ++ "./" ++ (T.unpack nickName)):: IO (Either ExitCode String) case createDir of Right str -> do result <- tryEC $ run $ T.unpack $ "mpiexec -np " `mappend` (T.pack $ show nCores) `mappend` " " `mappend` "Rscript " `mappend` (T.pack (scriptFileName timeStamp)) Logger.infoM iModuleName $ "Completed processing the job " `mappend` (scriptFileName timeStamp) case result of Right str -> return $ ExecuteWorkbench scriptUUID "ExecuteWorkbench" $ T.pack str Left code -> return $ ExecuteWorkbench unknownId "ExecuteWorkbench" $ T.pack $ show code Left code -> return $ ExecuteWorkbench unknownId "ExecuteWorkbench" $ T.pack $ show code where scriptFileName timeStamp= ("." ++ "/" ++ ("workbench_data") ++ "/" ++ (T.unpack scriptUUID) ++ ".r") executeWorkbench :: Value -> IO (GC.DestinationType, T.Text) executeWorkbench aValue@(Object a) = case (fromJSON aValue) of Success r@(ExecuteWorkbench wId cType _ ) -> do (sType, sContent, cores) <- getScriptDetails wId case nickName of Just (String nn) -> do result <- executeScript nn sType wId sContent cores return (GC.Reply, serialize $ (Right $ result {executeWorkbenchId = wId , executeWorkbenchCommandType = cType} :: Either T.Text ExecuteWorkbench)) Error errorMsg -> return (GC.Reply , serialize $ appError $ "Error processing executeWorkbench " ++ errorMsg) where nickName = LH.lookup "nickName" a {-- Tests --} testExecuteScript = do x <- executeScript "test_nick_name" EnTypes.RScript "test_uuid" "#This is a comment" 1 return x
asm-products/ccar-websockets
CCAR/Model/ProjectWorkbench.hs
agpl-3.0
14,069
283
26
3,246
3,883
2,056
1,827
354
4
-- C->Haskell Compiler: C attribute definitions and manipulation routines -- -- Author : Manuel M. T. Chakravarty -- Created: 12 August 99 -- -- Version $Revision: 1.1 $ from $Date: 2004/11/21 21:05:27 $ -- -- Copyright (c) [1999..2001] Manuel M. T. Chakravarty -- -- This file is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This file is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- --- DESCRIPTION --------------------------------------------------------------- -- -- This module provides the attributed version of the C structure tree. -- -- * C has several name spaces of which two are represented in this module: -- - `CObj' in `defObjsAC': The name space of objects, functions, typedef -- names, and enum constants. -- - `CTag' in `defTagsAC': The name space of tags of structures, unions, -- and enumerations. -- -- * The final state of the names spaces are preserved in the attributed -- structure tree. This allows further fast lookups for globally defined -- identifiers after the name anaysis is over. -- -- * In addition to the name spaces, the attribute structure tree contains -- a ident-definition table, which for attribute handles of identifiers -- refers to the identifiers definition. These are only used in usage -- occurences, except for one exception: The tag identifiers in forward -- definitions of structures or enums get a reference to the corresponding -- full definition - see `CTrav' for full details. -- -- * We maintain a shadow definition table, it can be populated with aliases -- to other objects and maps identifiers to identifiers. It is populated by -- using the `applyPrefix' function. When looksup performed via the shadow -- variant of a lookup function, shadow aliases are also considered, but -- they are used only if no normal entry for the identifiers is present. -- -- * Only ranges delimited by a block open a new range for tags (see -- `enterNewObjRangeC' and `leaveObjRangeC'). -- --- DOCU ---------------------------------------------------------------------- -- -- language: Haskell 98 -- --- TODO ---------------------------------------------------------------------- -- module CAttrs (-- attributed C -- AttrC, attrC, getCHeader, enterNewRangeC, enterNewObjRangeC, leaveRangeC, leaveObjRangeC, addDefObjC, lookupDefObjC, lookupDefObjCShadow, addDefTagC, lookupDefTagC, lookupDefTagCShadow, applyPrefix, getDefOfIdentC, setDefOfIdentC, updDefOfIdentC, freezeDefOfIdentsAttrC, softenDefOfIdentsAttrC, -- -- C objects -- CObj(..), CTag(..), CDef(..)) where import Char (toUpper) import List (isPrefixOf) import Maybe (mapMaybe) import Position (Position, Pos(posOf), nopos, dontCarePos, builtinPos) import Errors (interr) import Idents (Ident, getIdentAttrs, identToLexeme, onlyPosIdent) import Attributes (Attr(..), AttrTable, getAttr, setAttr, updAttr, newAttrTable, freezeAttrTable, softenAttrTable) import NameSpaces (NameSpace, nameSpace, enterNewRange, leaveRange, defLocal, defGlobal, find, nameSpaceToList) import Binary (Binary(..), putByte, getByte) import CAST -- attributed C structure tree -- --------------------------- -- C unit together with the attributes relevant to the outside world -- (EXPORTED ABSTRACT) -- data AttrC = AttrC { headerAC :: CHeader, -- raw header defObjsAC :: CObjNS, -- defined objects defTagsAC :: CTagNS, -- defined tags shadowsAC :: CShadowNS, -- shadow definitions (prefix) defsAC :: CDefTable -- ident-def associations } -- make an attribute structure tree from a raw one (EXPORTED) -- attrC :: CHeader -> AttrC attrC header = AttrC { headerAC = header, defObjsAC = cObjNS, defTagsAC = cTagNS, shadowsAC = cShadowNS, defsAC = cDefTable } -- extract the raw structure tree from an attributes one (EXPORTED) -- getCHeader :: AttrC -> CHeader getCHeader = headerAC -- the name space operations -- -- enter a new range (EXPORTED) -- enterNewRangeC :: AttrC -> AttrC enterNewRangeC ac = ac { defObjsAC = enterNewRange . defObjsAC $ ac, defTagsAC = enterNewRange . defTagsAC $ ac } -- enter a new range, only for objects (EXPORTED) -- enterNewObjRangeC :: AttrC -> AttrC enterNewObjRangeC ac = ac { defObjsAC = enterNewRange . defObjsAC $ ac } -- leave the current range (EXPORTED) -- leaveRangeC :: AttrC -> AttrC leaveRangeC ac = ac { defObjsAC = fst . leaveRange . defObjsAC $ ac, defTagsAC = fst . leaveRange . defTagsAC $ ac } -- leave the current range, only for objects (EXPORTED) -- leaveObjRangeC :: AttrC -> AttrC leaveObjRangeC ac = ac { defObjsAC = fst . leaveRange . defObjsAC $ ac } -- add another definitions to the object name space (EXPORTED) -- -- * if a definition of the same name was already present, it is returned -- addDefObjC :: AttrC -> Ident -> CObj -> (AttrC, Maybe CObj) addDefObjC ac ide obj = let om = defObjsAC ac (ac', obj') = defLocal om ide obj in (ac {defObjsAC = ac'}, obj') -- lookup an identifier in the object name space (EXPORTED) -- lookupDefObjC :: AttrC -> Ident -> Maybe CObj lookupDefObjC ac ide = find (defObjsAC ac) ide -- lookup an identifier in the object name space; if nothing found, try -- whether there is a shadow identifier that matches (EXPORTED) -- -- * the returned identifier is the _real_ identifier of the object -- lookupDefObjCShadow :: AttrC -> Ident -> Maybe (CObj, Ident) lookupDefObjCShadow ac ide = case lookupDefObjC ac ide of Just obj -> Just (obj, ide) Nothing -> case find (shadowsAC ac) ide of Nothing -> Nothing Just ide' -> case lookupDefObjC ac ide' of Just obj -> Just (obj, ide') Nothing -> Nothing -- add another definition to the tag name space (EXPORTED) -- -- * if a definition of the same name was already present, it is returned -- addDefTagC :: AttrC -> Ident -> CTag -> (AttrC, Maybe CTag) addDefTagC ac ide obj = let tm = defTagsAC ac (ac', obj') = defLocal tm ide obj in (ac {defTagsAC = ac'}, obj') -- lookup an identifier in the tag name space (EXPORTED) -- lookupDefTagC :: AttrC -> Ident -> Maybe CTag lookupDefTagC ac ide = find (defTagsAC ac) ide -- lookup an identifier in the tag name space; if nothing found, try -- whether there is a shadow identifier that matches (EXPORTED) -- -- * the returned identifier is the _real_ identifier of the tag -- lookupDefTagCShadow :: AttrC -> Ident -> Maybe (CTag, Ident) lookupDefTagCShadow ac ide = case lookupDefTagC ac ide of Just tag -> Just (tag, ide) Nothing -> case find (shadowsAC ac) ide of Nothing -> Nothing Just ide' -> case lookupDefTagC ac ide' of Just tag -> Just (tag, ide') Nothing -> Nothing -- enrich the shadow name space with identifiers obtained by dropping -- the given prefix from the identifiers already in the object or tag name -- space (EXPORTED) -- -- * in case of a collisions, a random entry is selected -- -- * case is not relevant in the prefix and underscores between the prefix and -- the stem of an identifier are also dropped -- applyPrefix :: AttrC -> String -> AttrC applyPrefix ac prefix = let shadows = shadowsAC ac names = map fst (nameSpaceToList (defObjsAC ac)) ++ map fst (nameSpaceToList (defTagsAC ac)) newShadows = mapMaybe (strip prefix) names in ac {shadowsAC = foldl define shadows newShadows} where strip prefix ide = case eat prefix (identToLexeme ide) of Nothing -> Nothing Just "" -> Nothing Just newName -> Just (onlyPosIdent (posOf ide) newName, ide) -- eat [] ('_':cs) = eat [] cs eat [] cs = Just cs eat (p:prefix) (c:cs) | toUpper p == toUpper c = eat prefix cs | otherwise = Nothing eat _ _ = Nothing -- define ns (ide, def) = fst (defGlobal ns ide def) -- the attribute table operations on the attributes -- -- get the definition associated with the given identifier (EXPORTED) -- getDefOfIdentC :: AttrC -> Ident -> CDef getDefOfIdentC ac = getAttr (defsAC ac) . getIdentAttrs setDefOfIdentC :: AttrC -> Ident -> CDef -> AttrC setDefOfIdentC ac id def = let tot' = setAttr (defsAC ac) (getIdentAttrs id) def in ac {defsAC = tot'} updDefOfIdentC :: AttrC -> Ident -> CDef -> AttrC updDefOfIdentC ac id def = let tot' = updAttr (defsAC ac) (getIdentAttrs id) def in ac {defsAC = tot'} freezeDefOfIdentsAttrC :: AttrC -> AttrC freezeDefOfIdentsAttrC ac = ac {defsAC = freezeAttrTable (defsAC ac)} softenDefOfIdentsAttrC :: AttrC -> AttrC softenDefOfIdentsAttrC ac = ac {defsAC = softenAttrTable (defsAC ac)} -- C objects including operations -- ------------------------------ -- C objects data definition (EXPORTED) -- data CObj = TypeCO CDecl -- typedef declaration | ObjCO CDecl -- object or function declaration | EnumCO Ident CEnum -- enumerator | BuiltinCO -- builtin object -- two C objects are equal iff they are defined by the same structure -- tree node (i.e., the two nodes referenced have the same attribute -- identifier) -- instance Eq CObj where (TypeCO decl1 ) == (TypeCO decl2 ) = decl1 == decl2 (ObjCO decl1 ) == (ObjCO decl2 ) = decl1 == decl2 (EnumCO ide1 enum1) == (EnumCO ide2 enum2) = ide1 == ide2 && enum1 == enum2 _ == _ = False instance Pos CObj where posOf (TypeCO def ) = posOf def posOf (ObjCO def ) = posOf def posOf (EnumCO ide _) = posOf ide posOf (BuiltinCO ) = builtinPos -- C tagged objects including operations -- ------------------------------------- -- C tagged objects data definition (EXPORTED) -- data CTag = StructUnionCT CStructUnion -- toplevel struct-union declaration | EnumCT CEnum -- toplevel enum declaration -- two C tag objects are equal iff they are defined by the same structure -- tree node (i.e., the two nodes referenced have the same attribute -- identifier) -- instance Eq CTag where (StructUnionCT struct1) == (StructUnionCT struct2) = struct1 == struct2 (EnumCT enum1 ) == (EnumCT enum2 ) = enum1 == enum2 _ == _ = False instance Pos CTag where posOf (StructUnionCT def) = posOf def posOf (EnumCT def) = posOf def -- C general definition -- -------------------- -- C general definition (EXPORTED) -- data CDef = UndefCD -- undefined object | DontCareCD -- don't care object | ObjCD CObj -- C object | TagCD CTag -- C tag -- two C definitions are equal iff they are defined by the same structure -- tree node (i.e., the two nodes referenced have the same attribute -- identifier), but don't care objects are equal to everything and undefined -- objects may not be compared -- instance Eq CDef where (ObjCD obj1) == (ObjCD obj2) = obj1 == obj2 (TagCD tag1) == (TagCD tag2) = tag1 == tag2 DontCareCD == _ = True _ == DontCareCD = True UndefCD == _ = interr "CAttrs: Attempt to compare an undefined C definition!" _ == UndefCD = interr "CAttrs: Attempt to compare an undefined C definition!" _ == _ = False instance Attr CDef where undef = UndefCD dontCare = DontCareCD isUndef UndefCD = True isUndef _ = False isDontCare DontCareCD = True isDontCare _ = False instance Pos CDef where posOf UndefCD = nopos posOf DontCareCD = dontCarePos posOf (ObjCD obj) = posOf obj posOf (TagCD tag) = posOf tag -- object tables (internal use only) -- --------------------------------- -- the object name space -- type CObjNS = NameSpace CObj -- creating a new object name space -- cObjNS :: CObjNS cObjNS = nameSpace -- the tag name space -- type CTagNS = NameSpace CTag -- creating a new tag name space -- cTagNS :: CTagNS cTagNS = nameSpace -- the shadow name space -- type CShadowNS = NameSpace Ident -- creating a shadow name space -- cShadowNS :: CShadowNS cShadowNS = nameSpace -- the general definition table -- type CDefTable = AttrTable CDef -- creating a new definition table -- cDefTable :: CDefTable cDefTable = newAttrTable "C General Definition Table for Idents" {-! for AttrC derive : GhcBinary !-} {-! for CObj derive : GhcBinary !-} {-! for CTag derive : GhcBinary !-} {-! for CDef derive : GhcBinary !-} {-* Generated by DrIFT : Look, but Don't Touch. *-} instance Binary AttrC where put_ bh (AttrC aa ab ac ad ae) = do -- put_ bh aa put_ bh ab put_ bh ac put_ bh ad put_ bh ae get bh = do -- aa <- get bh ab <- get bh ac <- get bh ad <- get bh ae <- get bh return (AttrC (error "AttrC.headerAC should not be needed") ab ac ad ae) instance Binary CObj where put_ bh (TypeCO aa) = do putByte bh 0 put_ bh aa put_ bh (ObjCO ab) = do putByte bh 1 put_ bh ab put_ bh (EnumCO ac ad) = do putByte bh 2 put_ bh ac put_ bh ad put_ bh BuiltinCO = do putByte bh 3 get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (TypeCO aa) 1 -> do ab <- get bh return (ObjCO ab) 2 -> do ac <- get bh ad <- get bh return (EnumCO ac ad) 3 -> do return BuiltinCO instance Binary CTag where put_ bh (StructUnionCT aa) = do putByte bh 0 put_ bh aa put_ bh (EnumCT ab) = do putByte bh 1 put_ bh ab get bh = do h <- getByte bh case h of 0 -> do aa <- get bh return (StructUnionCT aa) 1 -> do ab <- get bh return (EnumCT ab) instance Binary CDef where put_ bh UndefCD = do putByte bh 0 put_ bh DontCareCD = do putByte bh 1 put_ bh (ObjCD aa) = do putByte bh 2 put_ bh aa put_ bh (TagCD ab) = do putByte bh 3 put_ bh ab get bh = do h <- getByte bh case h of 0 -> do return UndefCD 1 -> do return DontCareCD 2 -> do aa <- get bh return (ObjCD aa) 3 -> do ab <- get bh return (TagCD ab)
thiagoarrais/gtk2hs
tools/c2hs/c/CAttrs.hs
lgpl-2.1
15,404
106
15
4,418
3,277
1,741
1,536
-1
-1
-- | -- Module: SwiftNav.SBP.GnssSignal -- Copyright: Copyright (C) 2015 Swift Navigation, Inc. -- License: LGPL-3 -- Maintainer: Mark Fine <dev@swiftnav.com> -- Stability: experimental -- Portability: portable -- -- Struct to represent a signal (constellation, band, satellite identifier) module SwiftNav.SBP.GnssSignal where import BasicPrelude import Control.Lens import Control.Monad.Loops import Data.Aeson.TH (deriveJSON, defaultOptions, fieldLabelModifier) import Data.Binary import Data.Binary.Get import Data.Binary.IEEE754 import Data.Binary.Put import Data.ByteString import Data.ByteString.Lazy hiding ( ByteString ) import Data.Int import Data.Word import SwiftNav.SBP.Encoding import SwiftNav.SBP.TH import SwiftNav.SBP.Types -- | SBPGnssSignal. -- -- Signal identifier containing constellation, band, and satellite identifier data SBPGnssSignal = SBPGnssSignal { _sBPGnssSignal_sat :: Word16 -- ^ Constellation-specific satellite identifier , _sBPGnssSignal_band :: Word8 -- ^ Signal band , _sBPGnssSignal_constellation :: Word8 -- ^ Constellation to which the satellite belongs } deriving ( Show, Read, Eq ) instance Binary SBPGnssSignal where get = do _sBPGnssSignal_sat <- getWord16le _sBPGnssSignal_band <- getWord8 _sBPGnssSignal_constellation <- getWord8 return SBPGnssSignal {..} put SBPGnssSignal {..} = do putWord16le _sBPGnssSignal_sat putWord8 _sBPGnssSignal_band putWord8 _sBPGnssSignal_constellation $(deriveJSON defaultOptions {fieldLabelModifier = fromMaybe "_sBPGnssSignal_" . stripPrefix "_sBPGnssSignal_"} ''SBPGnssSignal) $(makeLenses ''SBPGnssSignal)
mookerji/libsbp
haskell/src/SwiftNav/SBP/GnssSignal.hs
lgpl-3.0
1,685
0
11
272
284
163
121
-1
-1
{-# LANGUAGE TypeOperators, TypeFamilies, DataKinds #-} module Example.Pass.Typecheck where import Data.Generics.Fixplate import Data.OpenRecords import Example.Ast data Type = TInt | TBool deriving (Eq) instance Show Type where show TInt = "Int" show TBool = "Bool" type' :: Label "type'" type' = Label :: Label "type'" -- quote at end to avoid conflict with the "type" keyword inferType :: (r0 :\ "type'", (r1 :! "type'") ~ Type, ("type'" ::= Type :| r0) ~ r1) => AnnExpr r0 -> AnnExpr r1 inferType = cata attachType attachType :: ((r1 :! "type'") ~ Type, ("type'" ::= Type :| r0) ~ r1) => Ann Expr (Rec r0) (AnnExpr r1) -> AnnExpr ("type'" ::= Type :| r0) attachType (Ann r (LBool b)) = fixAnn (type' := TBool .| r) $ LBool b attachType (Ann r (LInt i)) = fixAnn (type' := TInt .| r) $ LInt i attachType (Ann r (Add e1 e2)) | exprType e1 == TInt && sameType e1 e2 = fixAnn (type' := TInt .| r) $ Add e1 e2 | otherwise = error "addition error: one of the summands was not of type Int" attachType (Ann r (If e1 e2 e3)) | exprType e1 /= TBool = error "If expr has non-boolean conditional" | not (sameType e2 e3) = error "then and else clause has differing types" | otherwise = fixAnn (type' := exprType e2 .| r) $ If e1 e2 e3 attachType (Ann r (Cmp e1 e2)) | not (sameType e1 e2) = error "attempts to compare differernt types" | otherwise = fixAnn (type' := TBool .| r) $ Cmp e1 e2 attachType (Ann r (Not e)) | exprType e /= TBool = error "Expression for not is not a boolean" | otherwise = fixAnn (type' := TBool .| r) $ Not e sameType :: (r :! "type'") ~ Type => AnnExpr r -> AnnExpr r -> Bool sameType a b = exprType a == exprType b exprType :: ((r :! "type'") ~ Type) => Mu (Ann f (Rec r)) -> Type exprType x = attr (unFix x) .! type'
hyPiRion/hs-playground
trex-ann/Example/Pass/Typecheck.hs
unlicense
1,851
0
11
451
765
375
390
-1
-1
module Lib ( go ) where go :: IO () go = putStrLn "Nothing successfully completed."
aztecrex/haskell-sample
src/Lib.hs
unlicense
95
0
6
27
27
15
12
4
1
module HelperSequences.A220096Spec (main, spec) where import Test.Hspec import HelperSequences.A220096 (a220096) main :: IO () main = hspec spec spec :: Spec spec = describe "A220096" $ it "correctly computes the first 20 elements" $ take 20 (map a220096 [1..]) `shouldBe` expectedValue where expectedValue = [0,1,2,2,4,3,6,4,3,5,10,6,12,7,5,8,16,9,18,10]
peterokagey/haskellOEIS
test/HelperSequences/A220096Spec.hs
apache-2.0
370
0
10
59
160
95
65
10
1
{-# LANGUAGE OverloadedStrings #-} -- | Internal doc. module Database.CouchDB.Conduit.Internal.Doc ( couchRev, couchRev', couchDelete, couchGetWith, couchPutWith, couchPutWith_, couchPutWith' ) where import Prelude import Control.Monad (void) import Control.Exception.Lifted (catch, throw) import Data.Maybe (fromJust) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.Text.Encoding as TE import qualified Data.Aeson as A import Data.Conduit (($$+-)) import qualified Data.Conduit.Attoparsec as CA import qualified Network.HTTP.Conduit as H import Network.HTTP.Types as HT import Database.CouchDB.Conduit.Internal.Connection import Database.CouchDB.Conduit.LowLevel (couch, protect') import Database.CouchDB.Conduit.Internal.Parser ------------------------------------------------------------------------------ -- Type-independent methods ------------------------------------------------------------------------------ -- | Get Revision of a document. couchRev :: MonadCouch m => Path -- ^ Correct 'Path' with escaped fragments. -> m Revision couchRev p = do response <- couch HT.methodHead p [] [] (H.RequestBodyBS B.empty) protect' return $ peekRev (H.responseHeaders response) where peekRev = B.tail . B.init . fromJust . lookup "Etag" -- | Brain-free version of 'couchRev'. If document absent, -- just return 'B.empty'. couchRev' :: MonadCouch m => Path -- ^ Correct 'Path' with escaped fragments. -> m Revision couchRev' p = catch (couchRev p) handler404 where handler404 (CouchHttpError 404 _) = return B.empty handler404 e = throw e -- | Delete the given revision of the object. couchDelete :: MonadCouch m => Path -- ^ Correct 'Path' with escaped fragments. -> Revision -- ^ Revision -> m () couchDelete p r = void $ couch methodDelete p [] [("rev", Just r)] (H.RequestBodyBS B.empty) protect' ------------------------------------------------------------------------------ -- with converter ------------------------------------------------------------------------------ -- | Load CouchDB document and parse it with given parser. couchGetWith :: MonadCouch m => (A.Value -> A.Result a) -- ^ Parser -> Path -- ^ Correct 'Path' with escaped fragments. -> Query -- ^ Query -> m (Revision, a) couchGetWith f p q = do response <- couch HT.methodGet p [] q (H.RequestBodyBS B.empty) protect' j <- (H.responseBody response) $$+- CA.sinkParser A.json A.String r <- either throw return $ extractField "_rev" j o <- jsonToTypeWith f j return (TE.encodeUtf8 r, o) -- | Put document, with given encoder couchPutWith :: MonadCouch m => (a -> BL.ByteString) -- ^ Encoder -> Path -- ^ Correct 'Path' with escaped fragments. -> Revision -- ^ Document revision. For new docs provide -- ^ empty string. -> Query -- ^ Query arguments. -> a -- ^ The object to store. -> m Revision couchPutWith f p r q val = do response <- couch HT.methodPut p (ifMatch r) q (H.RequestBodyLBS $ f val) protect' j <- (H.responseBody response) $$+- CA.sinkParser A.json either throw return $ extractRev j where ifMatch "" = [] ifMatch rv = [("If-Match", rv)] -- | \"Don't care\" version of version of 'couchPutWith'. Stores -- document only if it not exists. couchPutWith_ :: MonadCouch m => (a -> BL.ByteString) -- ^ Encoder -> Path -- ^ Correct 'Path' with escaped fragments. -> HT.Query -- ^ Query arguments. -> a -- ^ The object to store. -> m Revision couchPutWith_ f p q val = do rev <- couchRev' p if rev == "" then couchPutWith f p "" q val else return rev -- | Brute force version of 'couchPutWith'. couchPutWith' :: MonadCouch m => (a -> BL.ByteString) -- ^ Encoder -> Path -- ^ Correct 'Path' with escaped fragments. -> HT.Query -- ^ Query arguments. -> a -- ^ The object to store. -> m Revision couchPutWith' f p q val = do rev <- couchRev' p couchPutWith f p rev q val
akaspin/couchdb-conduit
src/Database/CouchDB/Conduit/Internal/Doc.hs
bsd-2-clause
4,799
0
11
1,556
984
531
453
95
2
module Main where import Position import Data.IORef import Data.Char import Control.Concurrent import Control.Monad import TerminalStuff import Map import Move import Monster import Player import State import Ray import Data.Maybe import System.IO import System.IO.Unsafe import Vision import Vision.DDA -- import UI.NCurses -- TODO: Use proper state. IORef is frowned upon! shouldQuit :: IORef Bool {-# NOINLINE shouldQuit #-} shouldQuit = unsafePerformIO (newIORef False) display_map :: GameMap -> IO () display_map m = do mapM_ putStrLn m drawPlayer :: Position -> IO () drawPlayer (x, y) = do setCursor (x+1) (y+1) putStr $ colorChr '@' putStr clrReset drawMonsters :: [Monster] -> IO () drawMonsters [] = return () drawMonsters (m:ms) = do drawMonster m drawMonsters ms drawMonster :: Monster -> IO () drawMonster m = do map <- readIORef State.map p <- readIORef State.player when (isVisible map (position p) (position m)) $ do let (x, y) = position m setCursor (x+1) (y+1) putStr $ colorChr 'X' putStr clrReset printSeparator :: IO () printSeparator = do w <- consoleWidth let s = "=" putStr $ concat [s | x <- [0..w]] printStat :: Show a => Position -> String -> a -> IO () printStat (x, y) title var = do setCursor x y putStr $ title ++ ": " putStr $ show var drawHud :: Position -> IO () drawHud pos = do h <- consoleHeight let top = h - 1 setCursor 0 top printSeparator p <- readIORef State.player printStat (0, top + 1) "Pos" $ position p printStat (20, top + 1) "HP" $ health p setCursor 40 (top - 2) drawLog drawLog :: IO () drawLog = do h <- consoleHeight w <- consoleWidth let bw = 40 let top = h - 4 let left = w - bw + 1 -- Draw box let space = [' ' | x <- [0..bw]] let line = ['=' | x <- [0..bw]] setCursor (left - 1) (top - 1) printIndentedLn (left - 2) $ "=" ++ line printIndentedLn (left - 2) $ "|" ++ space printIndentedLn (left - 2) $ "|" ++ space printIndentedLn (left - 2) $ "|" ++ space printIndentedLn (left - 2) $ "|" ++ space printIndentedLn (left - 2) $ "|" ++ space setCursor left top log <- readIORef gameLog let lines = take 5 log mapM_ (printIndentedLn left) lines printIndentedLn :: Int -> String -> IO () printIndentedLn x s = do setCursorX x putStr s nextLine draw :: [String] -> Position -> IO () draw m pos = do setCursor 0 0 display_map m drawPlayer pos ms <- readIORef monsters drawMonsters ms drawHud pos setCursor 0 35 hFlush stdout keyPressed :: Char -> IO () keyPressed 'q' = writeIORef shouldQuit True keyPressed '1' = moveRel (-1, 1) keyPressed '2' = moveRel (0, 1) keyPressed '3' = moveRel (1, 1) keyPressed '4' = moveRel (-1, 0) keyPressed '5' = moveRel (0, 0) keyPressed '6' = moveRel (1, 0) keyPressed '7' = moveRel (-1, -1) keyPressed '8' = moveRel (0, -1) keyPressed '9' = moveRel (1, -1) keyPressed _ = return() main :: IO () main = do hideCursor cls let ms = [Monster "Troll" 20 (19, 9) 5] writeIORef monsters ms map <- loadMap "map.txt" writeIORef State.map map hSetBuffering stdin NoBuffering hSetEcho stdin False playGame map showCursor showTrace :: [Position] -> IO () showTrace [] = return () showTrace (p:ps) = do let (x, y) = p setCursor (x+1) (y+1) putStr "#" showTrace ps playGame map = do handleAI p <- readIORef player let pos = Player.position p let coloredMap = colorMap $ computeVisible map pos draw coloredMap pos hFlush stdout a <- getHiddenChar cls setCursor 0 45 if ord a == 0x1B then do handleControlSequence else if a == '\224' then do -- Windows is special ... a <- getHiddenChar winSpecialKeyPressed a else do keyPressed a sq <- readIORef shouldQuit if not sq then playGame map else return () handleAI :: IO () handleAI = do p <- readIORef player ms <- readIORef monsters map <- readIORef State.map let newMonsters = doMonsterStuff ms map p writeIORef monsters newMonsters return () doMonsterStuff :: [Monster] -> GameMap -> Player -> [Monster] doMonsterStuff [] _ _ = [] doMonsterStuff (m:ms) map p = [handleMonster m map p] ++ (doMonsterStuff ms map p) handleControlSequence :: IO () handleControlSequence = do a <- getHiddenChar _hcs1 a _hcs1 :: Char -> IO () _hcs1 ('[') = do b <- getHiddenChar specialKeyPressed b _hcs1 a = do putStrLn "Not proper sequence. Expected '[', got " print a return () winSpecialKeyPressed :: Char -> IO () winSpecialKeyPressed 'H' = specialKeyPressed 'A' winSpecialKeyPressed 'P' = specialKeyPressed 'B' winSpecialKeyPressed 'M' = specialKeyPressed 'C' winSpecialKeyPressed 'K' = specialKeyPressed 'D' winSpecialKeyPressed x = specialKeyPressed x specialKeyPressed :: Char -> IO () specialKeyPressed 'A' = moveRel (0, -1) specialKeyPressed 'B' = moveRel (0, 1) specialKeyPressed 'C' = moveRel (1, 0) specialKeyPressed 'D' = moveRel (-1, 0) specialKeyPressed x = print x
CheeseSucker/haskell-roguelike
src/roguelike.hs
bsd-2-clause
5,171
0
13
1,306
2,090
997
1,093
185
4
{-# LANGUAGE RankNTypes, BangPatterns, DeriveDataTypeable, StandaloneDeriving #-} {-# OPTIONS -W #-} module Language.Hakaru.Types where import Data.Dynamic import System.Random -- Basic types for conditioning and conditioned sampler data Density a = Lebesgue !a | Discrete !a deriving Typeable type Cond = Maybe Dynamic fromDiscrete :: Density t -> t fromDiscrete (Discrete a) = a fromDiscrete _ = error "got a non-discrete sampler" fromLebesgue :: Density t -> t fromLebesgue (Lebesgue a) = a fromLebesgue _ = error "got a discrete sampler" fromDensity :: Density t -> t fromDensity (Discrete a) = a fromDensity (Lebesgue a) = a type LogLikelihood = Double data Dist a = Dist {logDensity :: Density a -> LogLikelihood, distSample :: forall g. RandomGen g => g -> (Density a, g)} deriving instance Typeable1 Dist
zaxtax/hakaru-old
Language/Hakaru/Types.hs
bsd-3-clause
896
0
13
210
231
124
107
25
1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {- | Module : Control.Monad.Error.Class Copyright : (c) Michael Weber <michael.weber@post.rwth-aachen.de> 2001, (c) Jeff Newbern 2003-2006, (c) Andriy Palamarchuk 2006 (c) Edward Kmett 2012 License : BSD-style (see the file LICENSE) Maintainer : libraries@haskell.org Stability : experimental Portability : non-portable (multi-parameter type classes) [Computation type:] Computations which may fail or throw exceptions. [Binding strategy:] Failure records information about the cause\/location of the failure. Failure values bypass the bound function, other values are used as inputs to the bound function. [Useful for:] Building computations from sequences of functions that may fail or using exception handling to structure error handling. [Zero and plus:] Zero is represented by an empty error and the plus operation executes its second argument if the first fails. [Example type:] @'Either' 'String' a@ The Error monad (also called the Exception monad). -} {- Rendered by Michael Weber <mailto:michael.weber@post.rwth-aachen.de>, inspired by the Haskell Monad Template Library from Andy Gill (<http://web.cecs.pdx.edu/~andy/>) -} module Control.Monad.Error.Class ( MonadError(..), liftEither, tryError, withError, handleError, mapError, ) where import qualified Control.Exception import Control.Monad.Trans.Except (Except, ExceptT) import qualified Control.Monad.Trans.Except as ExceptT (throwE, catchE) import Control.Monad.Trans.Identity as Identity import Control.Monad.Trans.Maybe as Maybe import Control.Monad.Trans.Reader as Reader import Control.Monad.Trans.RWS.Lazy as LazyRWS import Control.Monad.Trans.RWS.Strict as StrictRWS import Control.Monad.Trans.State.Lazy as LazyState import Control.Monad.Trans.State.Strict as StrictState import Control.Monad.Trans.Writer.Lazy as LazyWriter import Control.Monad.Trans.Writer.Strict as StrictWriter #if MIN_VERSION_transformers(0,5,3) import Control.Monad.Trans.Accum as Accum #endif #if MIN_VERSION_transformers(0,5,6) import Control.Monad.Trans.RWS.CPS as CPSRWS import Control.Monad.Trans.Writer.CPS as CPSWriter #endif import Control.Monad.Trans.Class (lift) import Control.Exception (IOException, catch, ioError) import Control.Monad #if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 707 import Control.Monad.Instances () #endif import Data.Monoid import Prelude (Either(..), Maybe(..), either, flip, (.), IO) {- | The strategy of combining computations that can throw exceptions by bypassing bound functions from the point an exception is thrown to the point that it is handled. Is parameterized over the type of error information and the monad type constructor. It is common to use @'Either' String@ as the monad type constructor for an error monad in which error descriptions take the form of strings. In that case and many other common cases the resulting monad is already defined as an instance of the 'MonadError' class. You can also define your own error type and\/or use a monad type constructor other than @'Either' 'String'@ or @'Either' 'IOError'@. In these cases you will have to explicitly define instances of the 'MonadError' class. (If you are using the deprecated "Control.Monad.Error" or "Control.Monad.Trans.Error", you may also have to define an 'Error' instance.) -} class (Monad m) => MonadError e m | m -> e where -- | Is used within a monadic computation to begin exception processing. throwError :: e -> m a {- | A handler function to handle previous errors and return to normal execution. A common idiom is: > do { action1; action2; action3 } `catchError` handler where the @action@ functions can call 'throwError'. Note that @handler@ and the do-block must have the same return type. -} catchError :: m a -> (e -> m a) -> m a #if __GLASGOW_HASKELL__ >= 707 {-# MINIMAL throwError, catchError #-} #endif {- | Lifts an @'Either' e@ into any @'MonadError' e@. > do { val <- liftEither =<< action1; action2 } where @action1@ returns an 'Either' to represent errors. @since 2.2.2 -} liftEither :: MonadError e m => Either e a -> m a liftEither = either throwError return instance MonadError IOException IO where throwError = ioError catchError = catch {- | @since 2.2.2 -} instance MonadError () Maybe where throwError () = Nothing catchError Nothing f = f () catchError x _ = x -- --------------------------------------------------------------------------- -- Our parameterizable error monad instance MonadError e (Either e) where throwError = Left Left l `catchError` h = h l Right r `catchError` _ = Right r {- | @since 2.2 -} instance Monad m => MonadError e (ExceptT e m) where throwError = ExceptT.throwE catchError = ExceptT.catchE -- --------------------------------------------------------------------------- -- Instances for other mtl transformers -- -- All of these instances need UndecidableInstances, -- because they do not satisfy the coverage condition. instance MonadError e m => MonadError e (IdentityT m) where throwError = lift . throwError catchError = Identity.liftCatch catchError instance MonadError e m => MonadError e (MaybeT m) where throwError = lift . throwError catchError = Maybe.liftCatch catchError instance MonadError e m => MonadError e (ReaderT r m) where throwError = lift . throwError catchError = Reader.liftCatch catchError instance (Monoid w, MonadError e m) => MonadError e (LazyRWS.RWST r w s m) where throwError = lift . throwError catchError = LazyRWS.liftCatch catchError instance (Monoid w, MonadError e m) => MonadError e (StrictRWS.RWST r w s m) where throwError = lift . throwError catchError = StrictRWS.liftCatch catchError instance MonadError e m => MonadError e (LazyState.StateT s m) where throwError = lift . throwError catchError = LazyState.liftCatch catchError instance MonadError e m => MonadError e (StrictState.StateT s m) where throwError = lift . throwError catchError = StrictState.liftCatch catchError instance (Monoid w, MonadError e m) => MonadError e (LazyWriter.WriterT w m) where throwError = lift . throwError catchError = LazyWriter.liftCatch catchError instance (Monoid w, MonadError e m) => MonadError e (StrictWriter.WriterT w m) where throwError = lift . throwError catchError = StrictWriter.liftCatch catchError #if MIN_VERSION_transformers(0,5,6) -- | @since 2.3 instance (Monoid w, MonadError e m) => MonadError e (CPSRWS.RWST r w s m) where throwError = lift . throwError catchError = CPSRWS.liftCatch catchError -- | @since 2.3 instance (Monoid w, MonadError e m) => MonadError e (CPSWriter.WriterT w m) where throwError = lift . throwError catchError = CPSWriter.liftCatch catchError #endif #if MIN_VERSION_transformers(0,5,3) -- | @since 2.3 instance ( Monoid w , MonadError e m #if !MIN_VERSION_base(4,8,0) , Functor m #endif ) => MonadError e (AccumT w m) where throwError = lift . throwError catchError = Accum.liftCatch catchError #endif -- | 'MonadError' analogue to the 'Control.Exception.try' function. tryError :: MonadError e m => m a -> m (Either e a) tryError action = (liftM Right action) `catchError` (return . Left) -- | 'MonadError' analogue to the 'withExceptT' function. -- Modify the value (but not the type) of an error. The type is -- fixed because of the functional dependency @m -> e@. If you need -- to change the type of @e@ use 'mapError'. withError :: MonadError e m => (e -> e) -> m a -> m a withError f action = tryError action >>= either (throwError . f) return -- | As 'handle' is flipped 'Control.Exception.catch', 'handleError' -- is flipped 'catchError'. handleError :: MonadError e m => (e -> m a) -> m a -> m a handleError = flip catchError -- | 'MonadError' analogue of the 'mapExceptT' function. The -- computation is unwrapped, a function is applied to the @Either@, and -- the result is lifted into the second 'MonadError' instance. mapError :: (MonadError e m, MonadError e' n) => (m (Either e a) -> n (Either e' b)) -> m a -> n b mapError f action = f (tryError action) >>= liftEither
ekmett/mtl
Control/Monad/Error/Class.hs
bsd-3-clause
8,435
0
11
1,527
1,483
831
652
83
1
module PathFinder.Interface ( search2d , search2d' , searchGraphMatrix , graph ) where import PathFinder.Core ( pathFinderSearch , PathFinderState ) import PathFinder.Types import PathFinder.Configs import Control.Lens.Operators import Control.Lens (_Just, _1) import Linear.V2 (V2) import Data.Monoid ( Sum(getSum) ) search2d' :: (Ord d, Floating d) => V2 d -> V2 d -> (V2 d -> Bool) -> Maybe (Path d (V2 d)) search2d' start end blocked = fst $ search2d start end blocked search2d :: (Ord d, Floating d) => V2 d -> V2 d -> (V2 d -> Bool) -> (Maybe (Path d (V2 d)), PathFinderState (V2 d) (Sum d)) search2d start end blocked = pathFinderSearch cfg start & _1 . _Just . pathCost %~ getSum where cfg = searchIn2d end & canBeWalked %~ \prevBlock x -> prevBlock x || blocked x searchGraphMatrix :: Integral i => i -> i -> [[Maybe i]] -> Maybe (Path i i) searchGraphMatrix start end matrix = fst (pathFinderSearch cfg start) & _Just . pathCost %~ getSum where cfg = searchInMatrix end matrix graph :: [[Maybe Int]] graph = [ [Nothing, Just 4, Just 2, Nothing, Just 6, Nothing, Nothing, Nothing] , Just 4 : replicate 7 Nothing , Just 2 : replicate 7 Nothing , replicate 7 Nothing ++ [Just 5] , Just 6 : replicate 6 Nothing ++ [Just 5] , replicate 6 Nothing ++ [Just 2, Just 9] , replicate 5 Nothing ++ [Just 2, Nothing, Nothing] , [Nothing, Nothing, Nothing, Just 5, Just 5, Just 9, Nothing, Nothing] ]
markus1189/pathfinder
src/PathFinder/Interface.hs
bsd-3-clause
1,720
0
14
571
633
332
301
-1
-1
{-# LANGUAGE RecordWildCards #-} module Leash.AMQP ( subscribe -- * Network.AMQP re-exports , AMQPException , Connection , Message(..) , Envelope , closeConnection ) where import Network.AMQP import Bark.Types import qualified Data.ByteString.Char8 as B subscribe :: URI -> Host -> Service -> Category -> Severity -> ((Message, Envelope) -> IO ()) -> IO Connection subscribe URI{..} host serv cat sev callback = do conn <- openConnection uriHost uriVHost uriUser uriPass chan <- openChannel conn _ <- declareQueue chan opts _ <- bindQueue chan queue exchange key _ <- consumeMsgs chan queue NoAck callback return conn where queue = "" exchange = B.unpack serv key = publishKey host cat sev opts = newQueue { queueName = queue , queueAutoDelete = True , queueDurable = False }
brendanhay/amqp-bark
leash/src/Leash/AMQP.hs
bsd-3-clause
993
0
14
341
255
136
119
31
1
{-# LANGUAGE CPP, RankNTypes, GADTs #-} #if __GLASGOW_HASKELL__ >= 800 #define TheExc TypeError #else #define TheExc ErrorCall #endif module Test.ShouldNotTypecheck (shouldNotTypecheck) where import Control.DeepSeq (force, NFData) import Control.Exception (evaluate, try, throwIO, TheExc(..)) import Data.List (isSuffixOf, isInfixOf) import Test.HUnit.Lang (Assertion, assertFailure) {-| Takes one argument, an expression that should not typecheck. It will fail the test if the expression does typecheck. Requires Deferred Type Errors to be enabled for the file it is called in. See the <https://github.com/CRogers/should-not-typecheck#should-not-typecheck- README> for examples and more information. -} #if __GLASGOW_HASKELL__ >= 800 shouldNotTypecheck :: NFData a => (() ~ () => a) -> Assertion #else shouldNotTypecheck :: NFData a => a -> Assertion #endif -- The type for GHC-8.0.1 is a hack, see https://github.com/CRogers/should-not-typecheck/pull/6#issuecomment-211520177 shouldNotTypecheck a = do result <- try (evaluate $ force a) case result of Right _ -> assertFailure "Expected expression to not compile but it did compile" Left e@(TheExc msg) -> case isSuffixOf "(deferred type error)" msg of True -> case isInfixOf "No instance for" msg && isInfixOf "NFData" msg of True -> assertFailure $ "Make sure the expression has an NFData instance! See docs at https://github.com/CRogers/should-not-typecheck#nfdata-a-constraint. Full error:\n" ++ msg False -> return () False -> throwIO e
CRogers/should-not-typecheck
src/Test/ShouldNotTypecheck.hs
bsd-3-clause
1,546
0
17
251
248
134
114
16
4
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeFamilies #-} -------------------------------------------------------------------- -- | -- Module : The Connection type class -- Copyright : (C) Marek Kidon 2016 -- License : BSD-style (see the file LICENSE) -- Maintainer : Marek 'Tr1p0d' Kidon <marek.kidon@itcommunity.cz> -- Stability : experimental -- Portability : non-portable -- -- This is the Connection type class. -------------------------------------------------------------------- module Network.Connections.Class.Connection where import Control.Monad.Catch (MonadThrow) import Control.Monad.IO.Class (MonadIO) import qualified Control.Monad.TaggedException as E (Throws) import Data.Proxy (Proxy) import qualified Network.Connections.Class.Transport as T ( ConnectionAccessor , ClientSettings , Transport , ServerSettings ) type OnConnectErrorHandler c m = E.Throws (EstablishConnectionError c) m (T.ConnectionAccessor c) -> m (T.ConnectionAccessor c) type OnCloseErrorHandler c m = E.Throws (CloseConnectionError c) m () -> m () class T.Transport c => ClientConnection c where type EstablishConnectionError c :: [*] establishConnection :: (MonadIO m, MonadThrow m) => Proxy c -> T.ClientSettings c -> E.Throws (EstablishConnectionError c) m (T.ConnectionAccessor c) type CloseConnectionError c :: [*] closeConnection :: (MonadIO m, MonadThrow m) => Proxy c -> T.ConnectionAccessor c -> E.Throws (CloseConnectionError c) m () class T.Transport c => ServerConnection c where type EstablishServerError c :: [*] establishServer :: (MonadIO m, MonadThrow m) => Proxy c -> T.ServerSettings c -> E.Throws (EstablishServerError c) m (T.ConnectionAccessor c) type CloseServerError c :: [*] closeServer :: (MonadIO m, MonadThrow m) => Proxy c -> T.ConnectionAccessor c -> E.Throws (CloseServerError c) m ()
Tr1p0d/connections
src/Network/Connections/Class/Connection.hs
bsd-3-clause
2,097
0
13
458
474
265
209
46
0
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric, FlexibleInstances, GADTs, GeneralizedNewtypeDeriving, StandaloneDeriving, NoImplicitPrelude #-} module Types where import BasePrelude import qualified Data.Map as Map import Data.Text import Test.QuickCheck (Property, counterexample) data Foo = Foo { fooInt :: Int , fooDouble :: Double , fooTuple :: (String, Text, Int) -- This definition causes an infinite loop in genericTo and genericFrom! -- , fooMap :: Map.Map String Foo , fooMap :: Map.Map String (Text,Int) } deriving (Show, Typeable, Data) data UFoo = UFoo { _UFooInt :: Int , uFooInt :: Int } deriving (Show, Eq, Data, Typeable) -- This type is needed because allSameEncoders in Properties.hs fails with -- Map (toEncoding and toJson output fields in different order but it's -- okay). data MapLessFoo = MapLessFoo { mapLessFooInt :: Int , mapLessFooDouble :: Double , mapLessFooTuple :: (String, Text, Int) } deriving (Show, Typeable, Data) data OneConstructor = OneConstructor deriving (Show, Eq, Typeable, Data) data Product2 a b = Product2 a b deriving (Show, Eq, Typeable, Data) data Product6 a b c d e f = Product6 a b c d e f deriving (Show, Eq, Typeable, Data) data Sum4 a b c d = Alt1 a | Alt2 b | Alt3 c | Alt4 d deriving (Show, Eq, Typeable, Data) class ApproxEq a where (=~) :: a -> a -> Bool newtype Approx a = Approx { fromApprox :: a } deriving (Show, Data, Typeable, ApproxEq, Num) instance (ApproxEq a) => Eq (Approx a) where Approx a == Approx b = a =~ b data Nullary = C1 | C2 | C3 deriving (Eq, Show) data SomeType a = Nullary | Unary Int | Product String (Maybe Char) a | Record { testOne :: Double , testTwo :: Maybe Bool , testThree :: Maybe a } deriving (Eq, Show) data GADT a where GADT :: { gadt :: String } -> GADT String deriving Typeable deriving instance Data (GADT String) deriving instance Eq (GADT a) deriving instance Show (GADT a) deriving instance Generic Foo deriving instance Generic UFoo deriving instance Generic OneConstructor deriving instance Generic (Product2 a b) deriving instance Generic (Product6 a b c d e f) deriving instance Generic (Sum4 a b c d) deriving instance Generic (Approx a) deriving instance Generic Nullary deriving instance Generic (SomeType a) failure :: Show a => String -> String -> a -> Property failure func msg v = counterexample (func ++ " failed: " ++ msg ++ ", " ++ show v) False
aelve/json-x
tests/Types.hs
bsd-3-clause
2,695
1
11
740
797
446
351
-1
-1
module DoubledWordsSpec (main, spec) where import Test.Hspec import DoubledWords ( OurWord(..) , WordInfo(..) , doubledWords , keepOnlyLatestDuplicates ) main :: IO () main = hspec spec spec :: Spec spec = do describe "DoubledWords" $ do describe "doubledWords" $ do it "reports nothing when there are no doubled words" $ do doubledWords "hello world" `shouldBe` [] it "gives the furthest down line numbers for a doubled word" $ do doubledWords "hello\nhello\nhello" `shouldBe` [ WordInfo 3 (OurWord "hello") ] it "handles a realistic stream of different doubled words" $ do doubledWords "hello\nhello\n hello\n world\nthere here here" `shouldBe` [ WordInfo 3 (OurWord "hello") , WordInfo 5 (OurWord "here") ] describe "keepOnlyLatestDuplicates" $ do it "ignores non-duplicates" $ do keepOnlyLatestDuplicates [ WordInfo 1 (OurWord "hello") ] `shouldBe` [] it "keeps only latest duplicates" $ do keepOnlyLatestDuplicates [ WordInfo 1 (OurWord "hello") , WordInfo 2 (OurWord "hello") , WordInfo 3 (OurWord "hello") ] `shouldBe` [ WordInfo 3 (OurWord "hello") ]
FranklinChen/doubled-words-haskell
test/DoubledWordsSpec.hs
bsd-3-clause
1,317
0
21
414
326
163
163
33
1
module Main where import System.Environment (getArgs) import Anatomy.Builder main :: IO () main = do args <- getArgs case args of [fn, "-o", out] -> buildFile fn out [fn] -> buildFile fn "." _ -> putStrLn . unlines $ [ "usage:" , "anatomy FILENAME\t\tbuild FILENAME, outputting documents to ." , "anatomy FILENAME -o DIRNAME\tbuild FILENAME, outputting documents to DIRNAME" ]
vito/atomo-anatomy
src/Main.hs
bsd-3-clause
462
0
11
145
105
57
48
13
3
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | Create new a new project directory populated with a basic working -- project. module Stack.New ( new , NewOpts(..) , defaultTemplateName , templateNameArgument , getTemplates , TemplateName , listTemplates) where import Control.Applicative import Control.Monad import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader import Control.Monad.Trans.Writer.Strict import Data.Aeson import Data.Aeson.Types import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as L8 import Data.Conduit import Data.Foldable (asum) import qualified Data.HashMap.Strict as HM import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe) import Data.Maybe.Extra (mapMaybeM) import Data.Monoid import Data.Set (Set) import qualified Data.Set as S import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Data.Text.Lazy as LT import Data.Time.Calendar import Data.Time.Clock import Data.Typeable import qualified Data.Yaml as Yaml import Network.HTTP.Client.Conduit hiding (path) import Network.HTTP.Download import Network.HTTP.Types.Status import Path import Path.IO import Prelude import Stack.Constants import Stack.Types import Stack.Types.TemplateName import System.Process.Run import Text.Hastache import Text.Hastache.Context import Text.Printf import Text.ProjectTemplate -------------------------------------------------------------------------------- -- Main project creation -- | Options for creating a new project. data NewOpts = NewOpts { newOptsProjectName :: PackageName -- ^ Name of the project to create. , newOptsCreateBare :: Bool -- ^ Whether to create the project without a directory. , newOptsTemplate :: Maybe TemplateName -- ^ Name of the template to use. , newOptsNonceParams :: Map Text Text -- ^ Nonce parameters specified just for this invocation. } -- | Create a new project with the given options. new :: (HasConfig r, MonadReader r m, MonadLogger m, MonadCatch m, MonadThrow m, MonadIO m, HasHttpManager r, Functor m, Applicative m) => NewOpts -> Bool -> m (Path Abs Dir) new opts forceOverwrite = do pwd <- getCurrentDir absDir <- if bare then return pwd else do relDir <- parseRelDir (packageNameString project) liftM (pwd </>) (return relDir) exists <- doesDirExist absDir configTemplate <- configDefaultTemplate <$> asks getConfig let template = fromMaybe defaultTemplateName $ asum [ cliOptionTemplate , configTemplate ] if exists && not bare then throwM (AlreadyExists absDir) else do templateText <- loadTemplate template (logUsing absDir template) files <- applyTemplate project template (newOptsNonceParams opts) absDir templateText when (not forceOverwrite && bare) $ checkForOverwrite (M.keys files) writeTemplateFiles files runTemplateInits absDir return absDir where cliOptionTemplate = newOptsTemplate opts project = newOptsProjectName opts bare = newOptsCreateBare opts logUsing absDir template templateFrom = let loading = case templateFrom of LocalTemp -> "Loading local" RemoteTemp -> "Downloading" in $logInfo (loading <> " template \"" <> templateName template <> "\" to create project \"" <> packageNameText project <> "\" in " <> if bare then "the current directory" else T.pack (toFilePath (dirname absDir)) <> " ...") data TemplateFrom = LocalTemp | RemoteTemp -- | Download and read in a template's text content. loadTemplate :: forall m r. (HasConfig r, HasHttpManager r, MonadReader r m, MonadIO m, MonadThrow m, MonadCatch m, MonadLogger m, Functor m, Applicative m) => TemplateName -> (TemplateFrom -> m ()) -> m Text loadTemplate name logIt = do templateDir <- templatesDir <$> asks getConfig case templatePath name of AbsPath absFile -> logIt LocalTemp >> loadLocalFile absFile UrlPath s -> do let req = fromMaybe (error "impossible happened: already valid \ \URL couldn't be parsed") (parseUrl s) rel = fromMaybe backupUrlRelPath (parseRelFile s) downloadTemplate req (templateDir </> rel) RelPath relFile -> catch (loadLocalFile relFile <* logIt LocalTemp) (\(e :: NewException) -> case relRequest relFile of Just req -> downloadTemplate req (templateDir </> relFile) Nothing -> throwM e ) where loadLocalFile :: Path b File -> m Text loadLocalFile path = do $logDebug ("Opening local template: \"" <> T.pack (toFilePath path) <> "\"") exists <- doesFileExist path if exists then liftIO (T.readFile (toFilePath path)) else throwM (FailedToLoadTemplate name (toFilePath path)) relRequest :: MonadThrow n => Path Rel File -> n Request relRequest rel = parseUrl (defaultTemplateUrl <> "/" <> toFilePath rel) downloadTemplate :: Request -> Path Abs File -> m Text downloadTemplate req path = do logIt RemoteTemp _ <- catch (redownload req path) (throwM . FailedToDownloadTemplate name) loadLocalFile path backupUrlRelPath = $(mkRelFile "downloaded.template.file.hsfiles") -- | Apply and unpack a template into a directory. applyTemplate :: (MonadIO m, MonadThrow m, MonadCatch m, MonadReader r m, HasConfig r, MonadLogger m) => PackageName -> TemplateName -> Map Text Text -> Path Abs Dir -> Text -> m (Map (Path Abs File) LB.ByteString) applyTemplate project template nonceParams dir templateText = do config <- asks getConfig currentYear <- do now <- liftIO getCurrentTime (year, _, _) <- return $ toGregorian . utctDay $ now return $ T.pack . show $ year let context = M.union (M.union nonceParams extraParams) configParams where extraParams = M.fromList [ ("name", packageNameText project) , ("year", currentYear) ] configParams = configTemplateParams config (applied,missingKeys) <- runWriterT (hastacheStr defaultConfig { muEscapeFunc = id } templateText (mkStrContextM (contextFunction context))) unless (S.null missingKeys) ($logInfo ("\n" <> T.pack (show (MissingParameters project template missingKeys (configUserConfigPath config))) <> "\n")) files :: Map FilePath LB.ByteString <- catch (execWriterT $ yield (T.encodeUtf8 (LT.toStrict applied)) $$ unpackTemplate receiveMem id ) (\(e :: ProjectTemplateException) -> throwM (InvalidTemplate template (show e))) when (M.null files) $ throwM (InvalidTemplate template "Template does not contain any files") let isPkgSpec f = ".cabal" `isSuffixOf` f || f == "package.yaml" unless (any isPkgSpec . M.keys $ files) $ throwM (InvalidTemplate template "Template does not contain a .cabal \ \or package.yaml file") liftM M.fromList (mapM (\(fp,bytes) -> do path <- parseRelFile fp return (dir </> path, bytes)) (M.toList files)) where -- | Does a lookup in the context and returns a moustache value, -- on the side, writes out a set of keys that were requested but -- not found. contextFunction :: Monad m => Map Text Text -> String -> WriterT (Set String) m (MuType (WriterT (Set String) m)) contextFunction context key = case M.lookup (T.pack key) context of Nothing -> do tell (S.singleton key) return MuNothing Just value -> return (MuVariable value) -- | Check if we're going to overwrite any existing files. checkForOverwrite :: (MonadIO m, MonadThrow m) => [Path Abs File] -> m () checkForOverwrite files = do overwrites <- filterM doesFileExist files unless (null overwrites) $ throwM (AttemptedOverwrites overwrites) -- | Write files to the new project directory. writeTemplateFiles :: MonadIO m => Map (Path Abs File) LB.ByteString -> m () writeTemplateFiles files = forM_ (M.toList files) (\(fp,bytes) -> do ensureDir (parent fp) liftIO (LB.writeFile (toFilePath fp) bytes)) -- | Run any initialization functions, such as Git. runTemplateInits :: (MonadIO m, MonadReader r m, HasConfig r, MonadLogger m, MonadCatch m) => Path Abs Dir -> m () runTemplateInits dir = do menv <- getMinimalEnvOverride config <- asks getConfig case configScmInit config of Nothing -> return () Just Git -> catch (callProcess $ Cmd (Just dir) "git" menv ["init"]) (\(_ :: ProcessExitedUnsuccessfully) -> $logInfo "git init failed to run, ignoring ...") -- | Display the set of templates accompanied with description if available. listTemplates :: (MonadIO m, MonadThrow m, MonadReader r m, HasHttpManager r, MonadCatch m, MonadLogger m) => m () listTemplates = do templates <- getTemplates templateInfo <- getTemplateInfo if not . M.null $ templateInfo then do let keySizes = map (T.length . templateName) $ S.toList templates padWidth = show $ maximum keySizes outputfmt = "%-" <> padWidth <> "s %s\n" headerfmt = "%-" <> padWidth <> "s %s\n" liftIO $ printf headerfmt ("Template"::String) ("Description"::String) forM_ (S.toList templates) (\x -> do let name = templateName x desc = fromMaybe "" $ liftM (mappend "- ") (M.lookup name templateInfo >>= description) liftIO $ printf outputfmt (T.unpack name) (T.unpack desc)) else mapM_ (liftIO . T.putStrLn . templateName) (S.toList templates) -- | Get the set of templates. getTemplates :: (MonadIO m, MonadThrow m, MonadReader r m, HasHttpManager r, MonadCatch m) => m (Set TemplateName) getTemplates = do req <- liftM addHeaders (parseUrl defaultTemplatesList) resp <- catch (httpLbs req) (throwM . FailedToDownloadTemplates) case statusCode (responseStatus resp) of 200 -> case eitherDecode (responseBody resp) >>= parseEither parseTemplateSet of Left err -> throwM (BadTemplatesJSON err (responseBody resp)) Right value -> return value code -> throwM (BadTemplatesResponse code) getTemplateInfo :: (MonadIO m, MonadThrow m, MonadReader r m, HasHttpManager r, MonadCatch m, MonadLogger m) => m (Map Text TemplateInfo) getTemplateInfo = do req <- liftM addHeaders (parseUrl defaultTemplateInfoUrl) resp <- catch (liftM Right $ httpLbs req) (\(ex :: HttpException) -> return . Left $ "Failed to download template info. The HTTP error was: " <> show ex) case resp >>= is200 of Left err -> do liftIO . putStrLn $ err return M.empty Right resp' -> case Yaml.decodeEither (LB.toStrict $ responseBody resp') :: Either String Object of Left err -> throwM $ BadTemplateInfo err Right o -> return (M.mapMaybe (Yaml.parseMaybe Yaml.parseJSON) (M.fromList . HM.toList $ o) :: Map Text TemplateInfo) where is200 resp = if statusCode (responseStatus resp) == 200 then return resp else Left $ "Unexpected status code while retrieving templates info: " <> show (statusCode $ responseStatus resp) addHeaders :: Request -> Request addHeaders req = req { requestHeaders = [ ("User-Agent", "The Haskell Stack") , ("Accept", "application/vnd.github.v3+json")] <> requestHeaders req } -- | Parser the set of templates from the JSON. parseTemplateSet :: Value -> Parser (Set TemplateName) parseTemplateSet a = do xs <- parseJSON a fmap S.fromList (mapMaybeM parseTemplate xs) where parseTemplate v = do o <- parseJSON v name <- o .: "name" if ".hsfiles" `isSuffixOf` name then case parseTemplateNameFromString name of Left{} -> fail ("Unable to parse template name from " <> name) Right template -> return (Just template) else return Nothing -------------------------------------------------------------------------------- -- Defaults -- | The default template name you can use if you don't have one. defaultTemplateName :: TemplateName defaultTemplateName = $(mkTemplateName "new-template") -- | Default web root URL to download from. defaultTemplateUrl :: String defaultTemplateUrl = "https://raw.githubusercontent.com/commercialhaskell/stack-templates/master" -- | Default web URL to get a yaml file containing template metadata. defaultTemplateInfoUrl :: String defaultTemplateInfoUrl = "https://raw.githubusercontent.com/commercialhaskell/stack-templates/master/template-info.yaml" -- | Default web URL to list the repo contents. defaultTemplatesList :: String defaultTemplatesList = "https://api.github.com/repos/commercialhaskell/stack-templates/contents/" -------------------------------------------------------------------------------- -- Exceptions -- | Exception that might occur when making a new project. data NewException = FailedToLoadTemplate !TemplateName !FilePath | FailedToDownloadTemplate !TemplateName !DownloadException | FailedToDownloadTemplates !HttpException | BadTemplatesResponse !Int | BadTemplatesJSON !String !LB.ByteString | AlreadyExists !(Path Abs Dir) | MissingParameters !PackageName !TemplateName !(Set String) !(Path Abs File) | InvalidTemplate !TemplateName !String | AttemptedOverwrites [Path Abs File] | FailedToDownloadTemplateInfo !HttpException | BadTemplateInfo !String | BadTemplateInfoResponse !Int deriving (Typeable) instance Exception NewException instance Show NewException where show (FailedToLoadTemplate name path) = "Failed to load download template " <> T.unpack (templateName name) <> " from " <> path show (FailedToDownloadTemplate name (RedownloadFailed _ _ resp)) = case statusCode (responseStatus resp) of 404 -> "That template doesn't exist. Run `stack templates' to see a list of available templates." code -> "Failed to download template " <> T.unpack (templateName name) <> ": unknown reason, status code was: " <> show code show (FailedToDownloadTemplate name _) = "Failed to download template " <> T.unpack (templateName name) <> ", reason unknown." show (AlreadyExists path) = "Directory " <> toFilePath path <> " already exists. Aborting." show (FailedToDownloadTemplates ex) = "Failed to download templates. The HTTP error was: " <> show ex show (BadTemplatesResponse code) = "Unexpected status code while retrieving templates list: " <> show code show (BadTemplatesJSON err bytes) = "Github returned some JSON that couldn't be parsed: " <> err <> "\n\n" <> L8.unpack bytes show (MissingParameters name template missingKeys userConfigPath) = intercalate "\n" [ "The following parameters were needed by the template but not provided: " <> intercalate ", " (S.toList missingKeys) , "You can provide them in " <> toFilePath userConfigPath <> ", like this:" , "templates:" , " params:" , intercalate "\n" (map (\key -> " " <> key <> ": value") (S.toList missingKeys)) , "Or you can pass each one as parameters like this:" , "stack new " <> packageNameString name <> " " <> T.unpack (templateName template) <> " " <> unwords (map (\key -> "-p \"" <> key <> ":value\"") (S.toList missingKeys))] show (InvalidTemplate name why) = "The template \"" <> T.unpack (templateName name) <> "\" is invalid and could not be used. " <> "The error was: \"" <> why <> "\"" show (AttemptedOverwrites fps) = "The template would create the following files, but they already exist:\n" <> unlines (map ((" " ++) . toFilePath) fps) <> "Use --force to ignore this, and overwite these files." show (FailedToDownloadTemplateInfo ex) = "Failed to download templates info. The HTTP error was: " <> show ex show (BadTemplateInfo err) = "Template info couldn't be parsed: " <> err show (BadTemplateInfoResponse code) = "Unexpected status code while retrieving templates info: " <> show code
phadej/stack
src/Stack/New.hs
bsd-3-clause
18,577
0
23
5,715
4,333
2,193
2,140
423
5
module Test.Sandbox.Compose.Template ( applyTemplate ) where import qualified Text.Hastache as H import qualified Text.Hastache.Context as H import qualified Data.Text.Lazy as TL import qualified Data.Text as T import qualified Data.Map as M applyTemplate :: H.MuVar a => [(String, a)] -> String -> IO String applyTemplate keyValues template = do str' <- H.hastacheStr H.defaultConfig (H.encodeStr template) (H.mkStrContext context') return $ T.unpack $ TL.toStrict str' where context' :: Monad m => String -> H.MuType m context' str' = case M.lookup str' (M.fromList (map (\(k,v) -> (k,H.MuVariable v)) keyValues)) of Just val -> val Nothing -> H.MuVariable ("{{"++str'++"}}")
junjihashimoto/test-sandbox-compose
Test/Sandbox/Compose/Template.hs
bsd-3-clause
768
0
17
184
265
146
119
21
2
{-# LANGUAGE BangPatterns #-} module RandomSkewHeapSpec where import Data.List (group, sort) import Test.Hspec import qualified RandomSkewHeap as P spec :: Spec spec = do describe "base priority queue" $ do it "queues entries based on weight" $ do let q = P.enqueue 5 1 5 $ P.enqueue 3 101 3 $ P.enqueue 1 201 1 P.empty xs = enqdeq q 1000 let [x201,x101,x1] = map length (group (sort xs)) x201 `shouldSatisfy` (\x -> 640 <= x && x <= 690) x101 `shouldSatisfy` (\x -> 310 <= x && x <= 360) x1 `shouldSatisfy` (\x -> 1 <= x && x <= 10) enqdeq :: P.PriorityQueue Int -> Int -> [Int] enqdeq pq num = loop pq num [] where loop _ 0 ks = ks loop !q !n ks = case P.dequeue q of Nothing -> error "enqdeq" Just (k,w,v,q') -> loop (P.enqueue k w v q') (n - 1) (k:ks)
kazu-yamamoto/http2
bench-priority/test/RandomSkewHeapSpec.hs
bsd-3-clause
932
0
20
327
382
198
184
23
3
-- | -- This module export Text, ByteString, LText, and LByteString -- module Prelude.Bitpacked.Types ( Text , ByteString , LText , LByteString ) where import Data.Text (Text) import Data.ByteString (ByteString) import qualified Data.Text.Lazy as LazyText import qualified Data.ByteString.Lazy as LazyByteString type LText = LazyText.Text type LByteString = LazyByteString.ByteString
andrewthad/lens-prelude
src/Prelude/Bitpacked/Types.hs
bsd-3-clause
398
0
5
62
78
53
25
11
0
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE ParallelArrays, MagicHash #-} {-# OPTIONS_GHC -funbox-strict-fields #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.PArr -- Copyright : (c) 2001-2011 The Data Parallel Haskell team -- License : see libraries/base/LICENSE -- -- Maintainer : cvs-ghc@haskell.org -- Stability : internal -- Portability : non-portable (GHC Extensions) -- -- BIG UGLY HACK: The desugarer special cases this module. Despite the uses of '-XParallelArrays', -- the desugarer does not load 'Data.Array.Parallel' into its global state. (Hence, -- the present module may not use any other piece of '-XParallelArray' syntax.) -- -- This will be cleaned up when we change the internal represention of '[::]' to not -- rely on a wired-in type constructor. module GHC.PArr where import GHC.Base -- Representation of parallel arrays -- -- Vanilla representation of parallel Haskell based on standard GHC arrays that is used if the -- vectorised is /not/ used. -- -- NB: This definition *must* be kept in sync with `TysWiredIn.parrTyCon'! -- data [::] e = PArr !Int (Array# e) type PArr = [::] -- this synonym is to get access to '[::]' without using the special syntax
jstolarek/ghc
libraries/base/GHC/PArr.hs
bsd-3-clause
1,386
4
7
283
65
54
11
-1
-1