code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
{-# LANGUAGE TemplateHaskell #-} module Client.MenuLayerT where import Control.Lens (makeLenses) import Types makeLenses ''MenuLayerT newMenuLayerT :: MenuLayerT newMenuLayerT = MenuLayerT { _mlDraw = Nothing , _mlKey = Nothing }
ksaveljev/hake-2
src/Client/MenuLayerT.hs
Haskell
bsd-3-clause
267
module Proper.TestUtils(testFunction) where import Test.HUnit testFunction func cases = runTestTT $ makeTestCases func cases makeTestCases func cases = TestList $ map (\(input, expected) -> testCase func input expected) cases testCase func input expected = TestCase (assertEqual ("Input: " ++ show input) expected (func input))
dillonhuff/Proper
test/Proper/TestUtils.hs
Haskell
bsd-3-clause
335
main :: IO () main = putStrLn "Test suite not yet implemented."
denibertovic/watcher
test/Spec.hs
Haskell
bsd-3-clause
64
import Intake.Core import Intake.Job import System.Exit main = defaultMain' [ -- Run `intake run a` and capture its output as SHORT_ID and ID. defaultJob { jobCommand = "./dist/build/intake/intake" , jobArguments = words "run a" , jobStderr = Just "" , jobStdout = Just "{{SHORT_ID}} {{ID}}\n" } -- Wait a bit. , defaultJob { jobCommand = "sleep" , jobArguments = words "0.1" } -- Run `intake status $SHORT_ID` with the captured SHORT_ID. , defaultJob { jobCommand = "./dist/build/intake/intake" , jobArguments = words "status {{$SHORT_ID}}" , jobStderr = Just "" , jobStdout = Just "WCompleted\n" } -- Run `intake show $SHORT_ID` with the captured SHORT_ID. -- This checks the stdout by comparing the captured ID. , defaultJob { jobCommand = "./dist/build/intake/intake" , jobArguments = words "show {{$SHORT_ID}}" , jobStderr = Just "" , jobStdout = Just "workflow: Right a\n\ \id: {{$ID}}\n\ \arguments: []\n\ \state: #0 echo [\"a\"](Completed)\n\n" } ]
noteed/intake
tests/intake-run-00.hs
Haskell
bsd-3-clause
1,024
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE ParallelListComp #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} -- | Definition of the MonetDB5/SQL backend for DSH: SQL code generation and -- execution of SQL queries. module Database.DSH.Backend.Sql.M5 where import Data.Aeson import Database.Algebra.SQL.Dialect import Database.Algebra.SQL.Materialization.CTE import Database.Algebra.SQL.Util import Database.DSH.Backend.Sql.Common -------------------------------------------------------------------------------- -- | SQL code generated for MonetDB5/SQL newtype M5Code = M5Code { unM5 :: String } instance Show M5Code where show = unM5 instance SqlCode M5Code where genSqlCode dag = (M5Code <$> prelude, M5Code <$> queries) where (prelude, queries) = renderOutputDSHWith MonetDB materialize dag instance ToJSON M5Code where toJSON (M5Code sql) = toJSON sql -- | A data vector described by MonetDB5 SQL type M5Vector = SqlVector M5Code --------------------------------------------------------------------------------
ulricha/dsh-sql
src/Database/DSH/Backend/Sql/M5.hs
Haskell
bsd-3-clause
1,237
module Main where import Test.Framework import qualified TestTerm import qualified TestTheta import qualified TestASUP main :: IO () main = defaultMain tests tests :: [Test] tests = [ TestTerm.tests , TestTheta.tests , TestASUP.tests ]
projedi/type-inference-rank2
tests/TestMain.hs
Haskell
bsd-3-clause
264
module Arcade.Sequence ( Sequence(..) ) where import Data.Word -- wrapping 16 bit sequence numbers newtype Sequence = Sequence Word16 instance Eq Sequence where Sequence a == Sequence b = a == b instance Ord Sequence where compare (Sequence s1) (Sequence s2) = case compare s1 s2 of LT | s2 - s1 <= 32768 -> GT GT | s1 - s2 <= 32768 -> LT x -> x
ekmett/arcade
src/Arcade/Sequence.hs
Haskell
bsd-3-clause
370
-- Example of Container for Multiple Types {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} module Container4 where import Control.Applicative (Applicative, WrappedMonad (..)) import Control.Applicative ((<$>), (<*>)) import Data.Foldable (Foldable) import Data.Maybe (fromMaybe, listToMaybe, maybeToList) import Data.Traversable (Traversable, traverse) import qualified Data.Set as Set type family L p (t :: * -> *) class PackLift p where pup :: (forall a. a -> t a ) -> p -> L p t pdown :: (forall a. t a -> a ) -> L p t -> p class PackMap p where pmap :: (forall a. t a -> t' a) -> L p t -> L p t' pmapA :: Applicative f => (forall a. t a -> f (t' a)) -> L p t -> f (L p t') -- pmapM :: Monad m => -- (forall a. t a -> m (t' a)) -> L p t -> m (L p t') -- pmapM f = unwrapMonad . pmapA (WrapMonad . f) toList :: (forall a. t a -> t') -> L p t -> [t'] class (PackMap p, PackLift p) => Pack p newtype Pair a b = Pair ( a, b) deriving (Show, Eq) -- newtype Pair' a b t = Pair' (t a, t b) deriving (Show, Eq) type Pair' a b f = Pair (f a) (f b) type instance L (Pair a b) t = Pair (t a) (t b) instance PackLift (Pair a b) where pup f (Pair (a, b)) = Pair (f a, f b) pdown f (Pair (a, b)) = Pair (f a, f b) instance PackMap (Pair a b) where pmap f (Pair (a, b)) = Pair (f a, f b) pmapA f (Pair (a, b)) = (\x y -> Pair (x, y)) <$> (f a) <*> (f b) toList f (Pair (a, b)) = [f a, f b] testUp :: Pair' Int Bool Maybe testUp = pup Just (Pair (1 :: Int, True)) testDown :: Pair Int Bool testDown = pdown (head . maybeToList) (Pair (Just (1 :: Int), Just True)) -- NG: The type variable ‘p1’ is ambiguous -- testMap :: Pair' Int Bool [] -- testMap = pmap maybeToList (Pair (Just 1, Just True)) -- testMap = (pmap :: (Maybe a -> [a]) -> Pair' Int Bool Maybe -> Pair' Int Bool []) maybeToList (Pair (Just 1, Just True)) -- data Showable = forall a. Show a => S a data Showable = forall a. S a -- deriving instance Show Showable -- NG: The type variables ‘p0’, ‘t0’ are ambiguous -- testToList :: [Showable] -- testToList = toList S (Pair (Just (1 :: Int), Just True)) {- instance PackLift (a, b) ( a b) where pup f (Pair (a, b)) = Pair' (f a, f b) pdown f (Pair' (a, b)) = Pair (f a, f b) instance PackMap (Pair' a b) where pmap f (Pair' (a, b)) = Pair' (f a, f b) pmapA f (Pair' (a, b)) = (\x y -> Pair' (x, y)) <$> (f a) <*> (f b) toList f (Pair' (a, b)) = [f a, f b] -} newtype PTraversable t' v t = PTraversable { unPTraversable :: t' (t v) } deriving (Show, Eq) {- instance Traversable t' => P (PTraversable t' v) where pmapA f (PTraversable ts) = PTraversable <$> Traversable.traverse f ts fromContainer f (PTraversable ts) = Foldable.toList $ fmap f ts instance Traversable t' => ContainerLift (PTraversable t' v) (t' v) where pup f ts = PTraversable $ fmap f ts pdown f (PTraversable ts) = fmap f ts -}
notae/haskell-exercise
pack/Container4.hs
Haskell
bsd-3-clause
3,207
module Data.Int.Dom.Common ( Mask , mkMask , negative , zero , Depth , depth , Prefix , mkPrefix ) where import Control.Monad ((<=<)) import Data.Bits import Data.Function (on) import Data.Functor ((<$>)) import Data.Word (Word) import Prelude hiding (init, last) newtype Mask = Mask Int mkMask :: Prefix -> Prefix -> Mask mkMask = curry $ last . next 32 . next 16 . next 8 . next 4 . next 2 . next 1 . init where init = uncurry (xor `on` toWord) next = (.|.) <=< flip (.>>.) last = Mask . fromWord <$> (xor =<< (.>>. 1)) (.>>.) = shiftR {-# INLINE mkMask #-} negative :: Mask -> Bool negative (Mask m) = m < 0 {-# INLINE negative #-} zero :: Int -> Mask -> Bool zero i (Mask m) = toWord i .&. toWord m == 0 {-# INLINE zero #-} newtype Depth = Depth Mask instance Eq Depth where Depth (Mask m1) == Depth (Mask m2) = m1 == m2 Depth (Mask m1) /= Depth (Mask m2) = m1 /= m2 depth :: Mask -> Depth depth = Depth {-# INLINE depth #-} instance Ord Depth where Depth (Mask m1) <= Depth (Mask m2) = toWord m1 >= toWord m2 {-# INLINE (<=) #-} type Prefix = Int mkPrefix :: Int -> Mask -> Prefix mkPrefix i (Mask m) = fromWord $ toWord i .&. (complement (m' - 1) `xor` m') where m' = toWord m {-# INLINE mkPrefix #-} toWord :: Int -> Word toWord = fromIntegral {-# INLINE toWord #-} fromWord :: Word -> Int fromWord = fromIntegral {-# INLINE fromWord #-}
sonyandy/fd
src/Data/Int/Dom/Common.hs
Haskell
bsd-3-clause
1,456
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Pack2 where import Control.Applicative import Control.Monad import Data.Dynamic import Data.Foldable import Data.Functor.Identity import Data.Maybe import Data.Monoid import Data.Traversable -- -- New Pack -- class PackLift b p where pLiftUp :: Applicative f => b -> p f pLiftDown :: Applicative f => p f -> f b class PackMap p where pNTM :: Applicative f => (forall x. g x -> f (h x)) -> p g -> f (p h) pNT :: (forall x. g x -> h x) -> p g -> p h pNT f = runIdentity . pNTM (Identity . f) -- TBD: put x under constraints pToList :: Applicative f => (forall x. f x -> y) -> p f -> [y] pToList' :: (Applicative f, Typeable f) => p f -> [Dynamic] pFoldM :: Applicative f => (forall x. s -> f x -> s) -> s -> p f -> s type Pack b p = (PackLift b p, PackMap p) -- Instances for Traversable newtype WrappedTraversable t a f = WrapTraversable { unwrapTraversable :: t (f a) } deriving Show instance Traversable t => PackLift (t a) (WrappedTraversable t a) where pLiftUp = WrapTraversable . fmap pure pLiftDown (WrapTraversable t) = traverse id t instance (Traversable t, Typeable a) => PackMap (WrappedTraversable t a) where pNTM f (WrapTraversable t) = WrapTraversable <$> traverse f t pToList f (WrapTraversable t) = fmap f (toList t) pToList' (WrapTraversable t) = fmap toDyn (toList t) -- Instances for (a, b) newtype PairL a b f = PairL (f a, f b) deriving (Show, Eq) instance PackLift (a, b) (PairL a b) where pLiftUp (a, b) = PairL (pure a, pure b) pLiftDown (PairL (a, b)) = (,) <$> a <*> b instance (Typeable a, Typeable b) => PackMap (PairL a b) where pNTM f (PairL (a, b)) = PairL <$> ((,) <$> f a <*> f b) pToList f (PairL (a, b)) = [f a, f b] pToList' (PairL (a, b)) = [toDyn a, toDyn b] pFoldM f s0 (PairL (a, b)) = f (f s0 a) b pl0 :: (Int, Bool) pl0 = (1, True) pl1 :: PairL Int Bool [] pl1 = PairL ([1], [True]) pl2 :: PairL Int Bool [] pl2 = PairL ([1, 2], [True]) pl3 :: PairL Int Bool [] pl3 = PairL ([1, 2], [True, False]) {-| >>> testPLU PairL ([1],[True]) -} testPLU :: PairL Int Bool [] testPLU = pLiftUp pl0 {-| >>> testPLD [(1,True)] >>> testPLD2 [(1,True),(1,False),(2,True),(2,False)] -} testPLD :: [(Int, Bool)] testPLD = pLiftDown pl1 testPLD2 :: [(Int, Bool)] testPLD2 = pLiftDown pl3 {-| >>> testPNTM PairL (Just 1,Just True) -} testPNTM :: PairL Int Bool Maybe testPNTM = runIdentity $ pNTM (Identity . listToMaybe) pl1 {-| >>> testFM [1,2] -} testFM :: [Int] testFM = pFoldM f mempty pl2 where f s x = length x : s testPack :: Pack b p => b -> p [] testPack = pLiftUp -- -- Experimental code -- {- traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) usecase: forall a. t a -> t (Dom a) -- (1) Create domain with single value t (Dom a) -> m (t (Var a)) -- (2) Create new variables t (Var a) -> m (t (Dom a)) -- (3) Read values of variables t (Dom a) -> t (Maybe a) -- (4) Convert Domain to Maybe t (Maybe a) -> Maybe (t a) -- (5) Convert Maybe to single value -} -- single type: {-| >>> st5 $ st4 $ st1 [1,2,3] Just [1,2,3] >>> st45 $ st1 [1,2,3] Just [1,2,3] -} -- (1) st1 :: (Traversable t, Applicative f) => t a -> t (f a) st1 = runIdentity . traverse (Identity . pure) -- (2)(3) st2 :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b) st2 = traverse -- (4) st4 :: (Traversable t) => t [a] -> t (Maybe a) st4 = runIdentity . traverse (Identity . listToMaybe) -- (5) st5 :: (Traversable t) => t (Maybe a) -> Maybe (t a) st5 = traverse id -- (4)+(5) st45 :: (Traversable t) => t [a] -> Maybe (t a) st45 = traverse listToMaybe -- ex.: t = (a, b), f = [] {-| >>> plLiftDown' $ plTranslate' $ plLiftUp' (1,True) Just (1,True) >>> plLiftDown'' $ plLiftUp' (1,True) Just (1,True) -} -- (1) plLiftUp' :: (a, b) -> ([a], [b]) plLiftUp' (a, b) = ([a], [b]) -- (4) plTranslate' :: ([a], [b]) -> (Maybe a, Maybe b) plTranslate' (a, b) = (listToMaybe a, listToMaybe b) -- (5) plLiftDown' :: (Maybe a, Maybe b) -> Maybe (a, b) plLiftDown' (a, b) = (,) <$> a <*> b -- (4)+(5) plLiftDown'' :: ([a], [b]) -> Maybe (a, b) plLiftDown'' (a, b) = (,) <$> listToMaybe a <*> listToMaybe b {-| >>> pgLiftDown $ pgNT listToMaybe $ pgLiftUp (1,True) Just (1,True) >>> pgLiftDown $ pgNT' listToMaybe $ pgLiftUp (1,True) Just (1,True) >>> pgNTM (Just . listToMaybe) ([1,2],[True,False]) Just (Just 1,Just True) >>> runIdentity $ pgNTM (Identity . listToMaybe) ([1,2],[True,False]) (Just 1,Just True) -} -- (1) primitive pgLiftUp :: Applicative f => (a, b) -> (f a, f b) pgLiftUp (a, b) = (pure a, pure b) -- (2)(3) primitive pgNTM :: Applicative f => (forall x. g x -> f (h x)) -> (g a, g b) -> f (h a, h b) pgNTM f (a, b) = (,) <$> f a <*> f b -- (4) pgNT :: (forall x. f x -> g x) -> (f a, f b) -> (g a, g b) pgNT f (a, b) = (f a, f b) -- rewritten with primitive pgNT' :: (forall x. f x -> g x) -> (f a, f b) -> (g a, g b) pgNT' f = runIdentity . pgNTM (Identity . f) -- (5) primitive pgLiftDown :: Applicative f => (f a, f b) -> f (a, b) pgLiftDown (a, b) = (,) <$> a <*> b -- TBD: generalize on element type -- multi type: -- (1) -- mt1 :: (forall a. a -> f a) -> f a -- (forall a. f a -> g a) -> -- (forall a. f a -> a) -> t f -> f t -- (2)(3) primitive mNTM :: Applicative f => (forall x. g x -> f (h x)) -> t g -> f (t h) mNTM = undefined
notae/haskell-exercise
pack/Pack2.hs
Haskell
bsd-3-clause
5,650
-- example2 import Data.IORef import Control.Applicative import Control.Monad import Control.Exception (SomeException) import qualified Control.Exception as E import Control.Concurrent (threadDelay) import System.IO.Unsafe (unsafePerformIO) import System.Timeout (timeout) {-# NOINLINE numHandles #-} numHandles :: IORef Int numHandles = unsafePerformIO $ newIORef 0 {-# NOINLINE dataWritten #-} dataWritten :: IORef [String] dataWritten = unsafePerformIO $ newIORef [] test :: IO () -> IO () test action = do action `E.catch` \e -> do putStrLn $ "exception: " ++ show (e :: SomeException) readIORef numHandles >>= putStrLn . ("Number of open handles: " ++) . show readIORef dataWritten >>= putStrLn . ("Data writtern to file: " ++) . show data Handle = Handle (IORef (Maybe String)) openFile :: FilePath -> IO Handle openFile _ = do modifyIORef' numHandles succ Handle <$> newIORef Nothing hClose :: Handle -> IO () hClose h = hFlushFailing h `E.finally` modifyIORef numHandles pred hFlushFailing :: Handle -> IO () hFlushFailing _ = error "hFlush failed" hFlush :: Handle -> IO () hFlush (Handle ref) = do val <- readIORef ref case val of Just str -> modifyIORef dataWritten (str :) _ -> return () writeIORef ref Nothing hPutStr :: Handle -> String -> IO () hPutStr h@(Handle ref) str = do hFlush h writeIORef ref (Just str) bracket :: IO a -> (a -> IO ()) -> (a -> IO b) -> IO b bracket allocate release use = E.mask $ \restore -> do resource <- allocate restore (use resource) `E.finally` release resource example :: IO () example = void $ timeout (1 * 1000 * 1000) $ bracket (openFile "path") hClose $ \h -> do hPutStr h "Hello" hPutStr h "World" threadDelay (2 * 1000 * 1000) main :: IO () main = test example
Yuras/io-region
misc/imask/example2.hs
Haskell
bsd-3-clause
1,794
module PrettyPrinter where import Syntax import Text.PrettyPrint pprExpr :: CoreExpr -> Doc pprExpr (ENum n) = int n pprExpr (EVar v) = text v pprExpr (EBinApp binOp e1 e2) = hcat [ pprExpr e1 <+> text (show binOp) <+> pprExpr e2] pprExpr (ECase e alts) = empty --TODO pprExpr (EConstr n1 n2) = empty --TODO pprExpr (ELam vs e) = hcat [ text "\\" , foldl (\acc v -> acc <+> (text v)) empty vs , text " . " , pprExpr e ] pprExpr (EAp e1 e2) = hsep [pprExpr e1, pprExpr e2] pprExpr (ELet is_rec defns expr) = vcat [ text keyword , vcat (map pprDefn defns) , text "in" , pprExpr expr ] where keyword | is_rec = "letrec" | not is_rec = "let" pprDefn :: (Name, CoreExpr) -> Doc pprDefn (name, expr) = hsep [text name, text "=", pprExpr expr] pprScDefn :: CoreScDefn -> Doc pprScDefn (name, vars, expr) = hsep [ text name , foldl (\acc v -> acc <+> (text v)) empty vars , text "=" , pprExpr expr ] pprProg :: CoreProgram -> Doc pprProg scDefns = vcat (map pprScDefn scDefns) pprint :: CoreProgram -> IO () pprint = print . pprProg
MarkX95/TinyHask
PrettyPrinter.hs
Haskell
bsd-3-clause
1,145
module Network.TigHTTP.Token ( isTokenChar, isTextChar, isQdtextChar, ) where import Data.Char (isAscii) isCtl, isSeparator, isTokenChar, isTextChar, isQdtextChar :: Char -> Bool isCtl = (`elem` (['\0' .. '\31'] ++ "\DEL")) isSeparator = (`elem` "()<>@,;:\\\"/[]?={} \t") isTokenChar = (&&) <$> not . isCtl <*> not . isSeparator isTextChar = (&&) <$> isAscii <*> not . isCtl isQdtextChar = (&&) <$> isTextChar <*> (/= '"')
YoshikuniJujo/tighttp
src/Network/TigHTTP/Token.hs
Haskell
bsd-3-clause
433
-- | Render an abstract shell script as a bash script module Shell.Formatter.Bash ( runBash, bashFormatter ) where import qualified Text.PrettyPrint.Mainland as PP import qualified Shell.Diagnostic as D import qualified Shell.Formatter.Base as F import qualified Shell.Internal as I import qualified Shell.Optimize as O import qualified Shell.Render as R -- | A formatter for bash scripts bashFormatter :: F.Formatter bashFormatter = F.defaultFormatter { F.fmtPreamble = \_ -> preamble } preamble :: PP.Doc preamble = PP.stack [ PP.string "#!/bin/bash" , PP.string "set -e" , PP.string "set -u" , PP.line ] -- | Turn an abstract shell script specification into a bash script. runBash :: I.ShellM () -> IO (Maybe String, [D.Diagnostic]) runBash st = do shell <- I.flattenShell st let (sh, odiags) = O.optimize O.defaultOptimizer shell case R.renderScript bashFormatter sh of Left errs -> return (Nothing, errs ++ odiags) Right script -> return (Just script, odiags)
travitch/shellDSL
src/Shell/Formatter/Bash.hs
Haskell
bsd-3-clause
1,071
module Trainer.Internal where boxMueller :: Double -> Double -> Double -> Double -> Double boxMueller μ σ r1 r2 = μ + σ * sqrt (-2*log r1) * cos (2*pi*r2) positiveStdNormal :: Double -> Double -> Double -> Double positiveStdNormal hi r1 r2 = min hi (abs bm) where bm = boxMueller 0 (hi/25) r1 r2
epsilonhalbe/VocabuLambda
Trainer/Internal.hs
Haskell
bsd-3-clause
330
------------------------------------------------------------------------------ -- | -- Module : Data.Datamining.Clustering.Gsom -- Copyright : (c) 2009 Stephan Günther -- License : BSD3 -- -- Maintainer : gnn.github@gmail.com -- Stability : experimental -- Portability : portable -- -- The network created by the GSOM algorithm is layed out in two dimensions. -- Thus one needs to assign two dimensional coordinates to the nodes of the -- network and for a clustering to the clusters. -- -- The types defining these coordinates and the functions to handle them belong -- into this module. ------------------------------------------------------------------------------ module Data.Datamining.Clustering.Gsom.Coordinates where type Coordinates = (Int, Int) type Direction = Int type Directions = [Int] -- | The list of supported directions. Since we are only dealing with -- hexagonal lattices, there are only six possible directions. directions :: Directions directions = [0..5] -- | @'neighbour' location direction@ calculates the coordinates of -- the neighbour of node with location @location@ in direction -- @direction@. neighbour :: Coordinates -> Direction -> Coordinates neighbour coordinates direction | direction > 5 = error $ "in neighbour: direction to big " ++ show direction ++ " (not in [0,5])." | otherwise = map ((\p1 p2 -> (fst p1 + fst p2, snd p1 + snd p2)) coordinates) [(2, 0), (1, 1), (-1, 1), (-2, 0), (-1, -1), (1, -1)] !! direction -- | @'neighbourCoordinates' point@ calculates the list of -- coordinates which are directly adjacent to @point@. neighbourCoordinates :: Coordinates -> [Coordinates] neighbourCoordinates cs = map (neighbour cs) directions
gnn/hsgsom
Data/Datamining/Clustering/Gsom/coordinates.hs
Haskell
bsd-3-clause
1,733
{-# LANGUAGE PatternGuards #-} -- | -- Module : Scion.Types.Notes -- Copyright : (c) Thomas Schilling 2009 -- License : BSD-style -- -- Maintainer : nominolo@googlemail.com -- Stability : experimental -- Portability : portable -- -- Notes, i.e., warnings, errors, etc. -- module Scion.Types.Notes ( Location, LocSource(..), mkLocation, mkNoLoc , locSource, isValidLoc, noLocText, viewLoc , locStartCol, locEndCol, locStartLine, locEndLine , AbsFilePath(toFilePath), mkAbsFilePath , Note(..), NoteKind(..), Notes , ghcSpanToLocation, ghcErrMsgToNote, ghcWarnMsgToNote , ghcMessagesToNotes ) where import qualified ErrUtils as GHC ( ErrMsg(..), WarnMsg, Messages ) import qualified SrcLoc as GHC import qualified FastString as GHC ( unpackFS ) import qualified Outputable as GHC ( showSDoc, ppr, showSDocForUser ) import qualified Bag ( bagToList ) import qualified Data.MultiSet as MS import System.FilePath infixr 9 `thenCmp` -- * Notes -- | A note from the compiler or some other tool. data Note = Note { noteKind :: NoteKind , noteLoc :: Location , noteMessage :: String } deriving (Eq, Ord, Show) -- | Classifies the kind (or severity) of a note. data NoteKind = ErrorNote | WarningNote | InfoNote | OtherNote deriving (Eq, Ord, Show) type Notes = MS.MultiSet Note -- * Absolute File Paths -- | Represents a 'FilePath' which we know is absolute. -- -- Since relative 'FilePath's depend on the a current working directory we -- normalise all paths to absolute paths. Use 'mkAbsFilePath' to create -- absolute file paths. newtype AbsFilePath = AFP { toFilePath :: FilePath } deriving (Eq, Ord) instance Show AbsFilePath where show (AFP s) = show s -- | Create an absolute file path given a base directory. -- -- Throws an error if the first argument is not an absolute path. mkAbsFilePath :: FilePath -- ^ base directory (must be absolute) -> FilePath -- ^ absolute or relative -> AbsFilePath mkAbsFilePath baseDir dir | isAbsolute baseDir = AFP $ normalise $ baseDir </> dir | otherwise = error "mkAbsFilePath: first argument must be an absolute path" -- * Scion's 'Location' data type -- | Scion's type for source code locations (regions). -- -- We use a custom location type for two reasons: -- -- 1. We enforce the invariant, that the file path of the location is an -- absolute path. -- -- 2. Independent evolution from the GHC API. -- -- To save space, the 'Location' type is kept abstract and uses special -- cases for notes that span only one line or are only one character wide. -- Use 'mkLocation' and 'viewLoc' as well as the respective accessor -- functions to construct and destruct nodes. -- -- If no reasonable can be given, use the 'mkNoLoc' function, but be careful -- not to call 'viewLoc' or any other accessor function on such a -- 'Location'. -- data Location = LocOneLine { locSource :: LocSource, locLine :: {-# UNPACK #-} !Int, locSCol :: {-# UNPACK #-} !Int, locECol :: {-# UNPACK #-} !Int } | LocMultiLine { locSource :: LocSource, locSLine :: {-# UNPACK #-} !Int, locELine :: {-# UNPACK #-} !Int, locSCol :: {-# UNPACK #-} !Int, locECol :: {-# UNPACK #-} !Int } | LocPoint { locSource :: LocSource, locLine :: {-# UNPACK #-} !Int, locCol :: {-# UNPACK #-} !Int } | LocNone { noLocText :: String } deriving (Eq, Show) -- | The \"source\" of a location. data LocSource = FileSrc AbsFilePath -- ^ The location refers to a position in a file. | OtherSrc String -- ^ The location refers to something else, e.g., the command line, or -- stdin. deriving (Eq, Ord, Show) instance Ord Location where compare = cmpLoc -- | Construct a source code location from start and end point. -- -- If the start point is after the end point, they are swapped -- automatically. mkLocation :: LocSource -> Int -- ^ start line -> Int -- ^ start column -> Int -- ^ end line -> Int -- ^ end column -> Location mkLocation file l0 c0 l1 c1 | l0 > l1 = mkLocation file l1 c0 l0 c1 | l0 == l1 && c0 > c1 = mkLocation file l0 c1 l1 c0 | l0 == l1 = if c0 == c1 then LocPoint file l0 c0 else LocOneLine file l0 c0 c1 | otherwise = LocMultiLine file l0 l1 c0 c1 -- | Construct a source location that does not specify a region. The -- argument can be used to give some hint as to why there is no location -- available. (E.g., \"File not found\"). mkNoLoc :: String -> Location mkNoLoc msg = LocNone msg -- | Test whether a location is valid, i.e., not constructed with 'mkNoLoc'. isValidLoc :: Location -> Bool isValidLoc (LocNone _) = False isValidLoc _ = True noLocError :: String -> a noLocError f = error $ f ++ ": argument must not be a noLoc" -- | Return the start column. Only defined on valid locations. locStartCol :: Location -> Int locStartCol l@LocPoint{} = locCol l locStartCol LocNone{} = noLocError "locStartCol" locStartCol l = locSCol l -- | Return the end column. Only defined on valid locations. locEndCol :: Location -> Int locEndCol l@LocPoint{} = locCol l locEndCol LocNone{} = noLocError "locEndCol" locEndCol l = locECol l -- | Return the start line. Only defined on valid locations. locStartLine :: Location -> Int locStartLine l@LocMultiLine{} = locSLine l locStartLine LocNone{} = noLocError "locStartLine" locStartLine l = locLine l -- | Return the end line. Only defined on valid locations. locEndLine :: Location -> Int locEndLine l@LocMultiLine{} = locELine l locEndLine LocNone{} = noLocError "locEndLine" locEndLine l = locLine l {-# INLINE viewLoc #-} -- | View on a (valid) location. -- -- It holds the property: -- -- > prop_viewLoc_mkLoc s l0 c0 l1 c1 = -- > viewLoc (mkLocation s l0 c0 l1 c1) == (s, l0, c0, l1, c1) -- viewLoc :: Location -> (LocSource, Int, Int, Int, Int) -- ^ source, start line, start column, end line, end column. viewLoc l = (locSource l, locStartLine l, locStartCol l, locEndLine l, locEndCol l) -- | Comparison function for two 'Location's. cmpLoc :: Location -> Location -> Ordering cmpLoc LocNone{} _ = LT cmpLoc _ LocNone{} = GT cmpLoc l1 l2 = (f1 `compare` f2) `thenCmp` (sl1 `compare` sl2) `thenCmp` (sc1 `compare` sc2) `thenCmp` (el1 `compare` el2) `thenCmp` (ec1 `compare` ec2) where (f1, sl1, sc1, el1, ec1) = viewLoc l1 (f2, sl2, sc2, el2, ec2) = viewLoc l2 -- | Lexicographic composition two orderings. Compare using the first -- ordering, use the second to break ties. thenCmp :: Ordering -> Ordering -> Ordering thenCmp EQ x = x thenCmp x _ = x {-# INLINE thenCmp #-} -- * Converting from GHC types. -- | Convert a 'GHC.SrcSpan' to a 'Location'. -- -- The first argument is used to normalise relative source locations to an -- absolute file path. ghcSpanToLocation :: FilePath -- ^ Base directory -> GHC.SrcSpan -> Location ghcSpanToLocation baseDir sp | GHC.isGoodSrcSpan sp = mkLocation mkLocFile (GHC.srcSpanStartLine sp) (GHC.srcSpanStartCol sp) (GHC.srcSpanEndLine sp) (GHC.srcSpanEndCol sp) | otherwise = mkNoLoc (GHC.showSDoc (GHC.ppr sp)) where mkLocFile = case GHC.unpackFS (GHC.srcSpanFile sp) of s@('<':_) -> OtherSrc s p -> FileSrc $ mkAbsFilePath baseDir p ghcErrMsgToNote :: FilePath -> GHC.ErrMsg -> Note ghcErrMsgToNote = ghcMsgToNote ErrorNote ghcWarnMsgToNote :: FilePath -> GHC.WarnMsg -> Note ghcWarnMsgToNote = ghcMsgToNote WarningNote -- Note that we don *not* include the extra info, since that information is -- only useful in the case where we don not show the error location directly -- in the source. ghcMsgToNote :: NoteKind -> FilePath -> GHC.ErrMsg -> Note ghcMsgToNote note_kind base_dir msg = Note { noteLoc = ghcSpanToLocation base_dir loc , noteKind = note_kind , noteMessage = show_msg (GHC.errMsgShortDoc msg) } where loc | (s:_) <- GHC.errMsgSpans msg = s | otherwise = GHC.noSrcSpan unqual = GHC.errMsgContext msg show_msg = GHC.showSDocForUser unqual -- | Convert 'GHC.Messages' to 'Notes'. -- -- This will mix warnings and errors, but you can split them back up -- by filtering the 'Notes' based on the 'noteKind'. ghcMessagesToNotes :: FilePath -- ^ Base path for normalising paths. -- See 'mkAbsFilePath'. -> GHC.Messages -> Notes ghcMessagesToNotes base_dir (warns, errs) = MS.union (map_bag2ms (ghcWarnMsgToNote base_dir) warns) (map_bag2ms (ghcErrMsgToNote base_dir) errs) where map_bag2ms f = MS.fromList . map f . Bag.bagToList
nominolo/scion
lib/Scion/Types/Notes.hs
Haskell
bsd-3-clause
8,890
-------------------------------------------------------------------------------- -- -- Copyright (c) 2011 - 2014 Tad Doxsee -- All rights reserved. -- -- Author: Tad Doxsee -- -------------------------------------------------------------------------------- module Main where import RegTesterLib (CmdMaker, regTesterMain) main :: IO () main = regTesterMain mkCmd mkCmd :: CmdMaker mkCmd program auxDir stdInDir testOutDir _ = program ++ " " ++ auxDir ++ " " ++ stdInDir ++ " " ++ testOutDir
tdox/regTester
src/regTester2.hs
Haskell
bsd-3-clause
500
{-# LANGUAGE RecordWildCards #-} -- Chi square tests for random generators module MWC.ChiSquare ( tests ) where import Control.Applicative import Control.Monad import Data.Typeable import Data.Word import Data.List (find) import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Unboxed.Mutable as M import qualified System.Random.MWC as MWC import qualified System.Random.MWC.Distributions as MWC import qualified System.Random.MWC.CondensedTable as MWC import Statistics.Types import Statistics.Test.ChiSquared import Statistics.Distribution import Statistics.Distribution.Poisson import Statistics.Distribution.Binomial import Statistics.Distribution.Geometric import Test.HUnit hiding (Test) import Test.Framework import Test.Framework.Providers.HUnit ---------------------------------------------------------------- tests :: MWC.GenIO -> Test.Framework.Test tests g = testGroup "Chi squared tests" -- Word8 tests [ uniformRTest (0,255 :: Word8) g , uniformRTest (0,254 :: Word8) g , uniformRTest (0,129 :: Word8) g , uniformRTest (0,126 :: Word8) g , uniformRTest (0,10 :: Word8) g -- * Tables , ctableTest [1] g , ctableTest [0.5, 0.5] g , ctableTest [0.25, 0.25, 0.25, 0.25] g , ctableTest [0.25, 0.5, 0.25] g , ctableTest [1/3 , 1/3, 1/3] g , ctableTest [0.1, 0.9] g , ctableTest (replicate 10 0.1) g -- ** Poisson , poissonTest 0.2 g , poissonTest 1.32 g , poissonTest 6.8 g , poissonTest 100 g -- ** Binomial , binomialTest 4 0.5 g , binomialTest 10 0.1 g , binomialTest 10 0.6 g , binomialTest 10 0.8 g , binomialTest 100 0.3 g -- ** Geometric , geometricTest 0.1 g , geometricTest 0.5 g , geometricTest 0.9 g ] ---------------------------------------------------------------- -- | RNG and corresonding distribution data Generator = Generator { generator :: MWC.GenIO -> IO Int , probabilites :: U.Vector Double } -- | Apply chi square test for a distribution sampleTest :: String -- ^ Name of test -> Generator -- ^ Generator to test -> Int -- ^ N of events -> MWC.GenIO -- ^ PRNG state -> Test.Framework.Test sampleTest nm (Generator{..}) n g = testCase nm $ do let size = U.length $ probabilites h <- histogram (generator g) size n let w = U.map (* fromIntegral n) probabilites Just t = chi2test 0 $ U.zip h w case isSignificant (mkPValue 0.01) t of Significant -> assertFailure ("Significant: " ++ show t) NotSignificant -> return () {-# INLINE sampleTest #-} -- | Fill histogram using supplied generator histogram :: IO Int -- ^ Rangom generator -> Int -- ^ N of outcomes -> Int -- ^ N of events -> IO (U.Vector Int) histogram gen size n = do arr <- M.replicate size 0 replicateM_ n $ do i <- gen when (i < size) $ M.write arr i . (+1) =<< M.read arr i U.unsafeFreeze arr {-# INLINE histogram #-} -- | Test uniformR uniformRTest :: (MWC.Variate a, Typeable a, Show a, Integral a) => (a,a) -> MWC.GenIO -> Test.Framework.Test uniformRTest (a,b) = sampleTest ("uniformR: " ++ show (a,b) ++ " :: " ++ show (typeOf a)) gen (10^5) where n = fromIntegral b - fromIntegral a + 1 gen = Generator { generator = \g -> fromIntegral . subtract a <$> MWC.uniformR (a,b) g , probabilites = U.replicate n (1 / fromIntegral n) } {-# INLINE uniformRTest #-} -- | Test for condensed tables ctableTest :: [Double] -> MWC.GenIO -> Test.Framework.Test ctableTest ps = sampleTest ("condensedTable: " ++ show ps) gen (10^4) where gen = Generator { generator = MWC.genFromTable $ MWC.tableFromProbabilities $ U.fromList $ zip [0..] ps , probabilites = U.fromList ps } -- | Test for condensed table for poissson distribution poissonTest :: Double -> MWC.GenIO -> Test.Framework.Test poissonTest lam = sampleTest ("poissonTest: " ++ show lam) gen (10^4) where pois = poisson lam Just nMax = find (\n -> probability pois n < 2**(-33)) [floor lam ..] gen = Generator { generator = MWC.genFromTable (MWC.tablePoisson lam) , probabilites = U.generate nMax (probability pois) } -- | Test for condensed table for binomial distribution binomialTest :: Int -> Double -> MWC.GenIO -> Test.Framework.Test binomialTest n p = sampleTest ("binomialTest: " ++ show p ++ " " ++ show n) gen (10^4) where binom = binomial n p gen = Generator { generator = MWC.genFromTable (MWC.tableBinomial n p) , probabilites = U.generate (n+1) (probability binom) } -- | Test for geometric distribution geometricTest :: Double -> MWC.GenIO -> Test.Framework.Test geometricTest gd = sampleTest ("geometricTest: " ++ show gd) gen (10^4) where n = 1000 gen = Generator { generator = MWC.geometric1 gd , probabilites = U.generate (n+1) (probability $ geometric gd) }
bos/mwc-random
mwc-random-bench/test/MWC/ChiSquare.hs
Haskell
bsd-2-clause
5,175
{-# LANGUAGE TypeOperators, GADTs, KindSignatures, ConstraintKinds #-} {-# LANGUAGE FlexibleContexts, PatternGuards, ViewPatterns, ScopedTypeVariables #-} {-# LANGUAGE CPP #-} {-# OPTIONS_GHC -Wall #-} -- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP -- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP ---------------------------------------------------------------------- -- | -- Module : LambdaCCC.ToCircuit -- Copyright : (c) 2013 Tabula, Inc. -- LICENSE : BSD3 -- -- Maintainer : conal@tabula.com -- Stability : experimental -- -- Convert from CCC form to a circuit ---------------------------------------------------------------------- module LambdaCCC.ToCircuit ( expToCircuit, cccToCircuit ) where import Prelude hiding (id,(.),curry,uncurry) import Data.Constraint (Dict(..)) import Circat.Prim hiding (xor) import LambdaCCC.CCC import LambdaCCC.Lambda (E) import LambdaCCC.ToCCC (toCCC) import Circat.Circuit import Circat.Category import Circat.Classes expToCircuit :: E Prim (a -> b) -> (a :> b) expToCircuit = cccToCircuit . toCCC #define TS (tyPSource -> Dict) #define CP (cccPS -> (Dict, Dict)) #define TC (tyHasCond -> Dict) #define LS (litSS -> Dict) cccToCircuit :: (a :-> b) -> (a :> b) -- Category cccToCircuit Id = id cccToCircuit (g :. f) = cccToCircuit g . cccToCircuit f -- Primitives cccToCircuit (Prim p) = primToSource p cccToCircuit (Lit l@LS) = constC (eval l) -- Product cccToCircuit Exl = exl cccToCircuit Exr = exr cccToCircuit (f :&&& g) = cccToCircuit f &&& cccToCircuit g -- Coproduct cccToCircuit Inl = inl cccToCircuit Inr = inr -- cccToCircuit k@(f :||| g) = cccToCircuit f |||* cccToCircuit g -- Exponential cccToCircuit Apply = apply cccToCircuit (Curry h) = curry (cccToCircuit h) cccToCircuit (Uncurry h) = uncurry (cccToCircuit h) cccToCircuit ccc = error $ "cccToCircuit: not yet handled: " ++ show ccc #define TH (tyHasTy -> HasTy) -- TODO: I don't know whether to keep add. We'll probably want to build it from -- simpler pieces. -- -- TODO: Maybe implement all primitives (other than exl & exr) with namedC. I -- could even use this PrimC type in circat, though it'd be the first dependency -- of circat on lambda-ccc. {-------------------------------------------------------------------- Prim conversion --------------------------------------------------------------------} primToSource :: Prim t -> Pins t primToSource NotP = not primToSource AndP = curry and primToSource OrP = curry or primToSource XorP = curry xor primToSource ExlP = exl primToSource ExrP = exr primToSource PairP = curry id primToSource InlP = inl primToSource InrP = inr -- primToSource CondP = condC -- primToSource AddP = curry (namedC "add") primToSource p = error $ "primToSource: not yet handled: " ++ show p #if 0 -- Prove that IsSource (Pins a), IsSource (Pins b) cccPS :: (a :-> b) -> (PSourceJt a, PSourceJt b) cccPS = tyPSource2 . cccTys {-------------------------------------------------------------------- Proofs --------------------------------------------------------------------} type PSourceJt a = Dict (IsSourceP a) -- | Proof of @'IsSource' ('Pins' a)@ from @'Ty' a@ tyPSource :: Ty a -> PSourceJt a tyPSource Unit = Dict tyPSource Bool = Dict tyPSource (TS :* TS) = Dict -- still needed? tyPSource ty = error $ "tyPSource: Oops -- not yet handling " ++ show ty -- That product case gets used for my CRC example when I turn off the -- xor/constant rewrite rules. tyPSource2 :: (Ty a,Ty b) -> (PSourceJt a, PSourceJt b) tyPSource2 (a,b) = (tyPSource a,tyPSource b) -- tyPSource2 = tyPSource *** tyPSource -- | Proof of @'HasCond t@ from @'Ty' t@ tyHasCond :: Ty t -> Dict (HasCond t) tyHasCond Unit = Dict tyHasCond Bool = Dict tyHasCond (TC :* TC) = Dict tyHasCond (_ :+ _ ) = Dict tyHasCond (_ :=> TC) = Dict tyHasCond Int = error "tyHasCond: Int not yet handled." #endif
conal/lambda-ccc
src/LambdaCCC/Unused/ToCircuit.hs
Haskell
bsd-3-clause
4,036
{-# LANGUAGE TypeFamilies, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, RankNTypes, GADTs, ScopedTypeVariables, FunctionalDependencies, RecursiveDo, UndecidableInstances, GeneralizedNewtypeDeriving, StandaloneDeriving, EmptyDataDecls, NoMonomorphismRestriction, TypeOperators, DeriveDataTypeable, PackageImports, TemplateHaskell, LambdaCase, DataKinds, PolyKinds #-} module Reflex.Dynamic ( Dynamic -- Abstract so we can preserve the law that the current value is always equal to the most recent update , current , updated , constDyn , holdDyn , nubDyn , count , toggle , switchPromptlyDyn , tagDyn , attachDyn , attachDynWith , attachDynWithMaybe , mapDyn , forDyn , mapDynM , foldDyn , foldDynM , foldDynMaybe , foldDynMaybeM , combineDyn , collectDyn , mconcatDyn , distributeDMapOverDyn , joinDyn , joinDynThroughMap , traceDyn , traceDynWith , splitDyn , Demux , demux , getDemuxed -- Things that probably aren't very useful: , HList (..) , FHList (..) , distributeFHListOverDyn -- Unsafe , unsafeDynamic ) where import Prelude hiding (mapM, mapM_) import Reflex.Class import Data.Functor.Misc import Control.Monad hiding (mapM, mapM_, forM, forM_) import Control.Monad.Fix import Control.Monad.Identity hiding (mapM, mapM_, forM, forM_) import Data.These import Data.Traversable (mapM, forM) import Data.Align import Data.Map (Map) import qualified Data.Map as Map import Data.Dependent.Map (DMap) import qualified Data.Dependent.Map as DMap import Data.Dependent.Sum (DSum (..)) import Data.GADT.Compare (GCompare (..), GEq (..), (:~:) (..), GOrdering (..)) import Data.Monoid --import Data.HList (HList (..), hBuild) data HList (l::[*]) where HNil :: HList '[] HCons :: e -> HList l -> HList (e ': l) infixr 2 `HCons` type family HRevApp (l1 :: [k]) (l2 :: [k]) :: [k] type instance HRevApp '[] l = l type instance HRevApp (e ': l) l' = HRevApp l (e ': l') hRevApp :: HList l1 -> HList l2 -> HList (HRevApp l1 l2) hRevApp HNil l = l hRevApp (HCons x l) l' = hRevApp l (HCons x l') hReverse :: HList l -> HList (HRevApp l '[]) hReverse l = hRevApp l HNil hBuild :: (HBuild' '[] r) => r hBuild = hBuild' HNil class HBuild' l r where hBuild' :: HList l -> r instance (l' ~ HRevApp l '[]) => HBuild' l (HList l') where hBuild' l = hReverse l instance HBuild' (a ': l) r => HBuild' l (a->r) where hBuild' l x = hBuild' (HCons x l) -- | A container for a value that can change over time and allows notifications on changes. -- Basically a combination of a 'Behavior' and an 'Event', with a rule that the Behavior will -- change if and only if the Event fires. data Dynamic t a = Dynamic (Behavior t a) (Event t a) unsafeDynamic :: Behavior t a -> Event t a -> Dynamic t a unsafeDynamic = Dynamic -- | Extract the 'Behavior' of a 'Dynamic'. current :: Dynamic t a -> Behavior t a current (Dynamic b _) = b -- | Extract the 'Event' of the 'Dynamic'. updated :: Dynamic t a -> Event t a updated (Dynamic _ e) = e -- | 'Dynamic' with the constant supplied value. constDyn :: Reflex t => a -> Dynamic t a constDyn x = Dynamic (constant x) never -- | Create a 'Dynamic' using the initial value that changes every -- time the 'Event' occurs. holdDyn :: MonadHold t m => a -> Event t a -> m (Dynamic t a) holdDyn v0 e = do b <- hold v0 e return $ Dynamic b e -- | Create a new 'Dynamic' that only signals changes if the values -- actually changed. nubDyn :: (Reflex t, Eq a) => Dynamic t a -> Dynamic t a nubDyn d = let e' = attachWithMaybe (\x x' -> if x' == x then Nothing else Just x') (current d) (updated d) in Dynamic (current d) e' --TODO: Avoid invalidating the outgoing Behavior {- instance Reflex t => Functor (Dynamic t) where fmap f d = let e' = fmap f $ updated d eb' = push (\b' -> liftM Just $ constant b') e' b0 = fmap f $ current d -} -- | Map a function over a 'Dynamic'. mapDyn :: (Reflex t, MonadHold t m) => (a -> b) -> Dynamic t a -> m (Dynamic t b) mapDyn f = mapDynM $ return . f -- | Flipped version of 'mapDyn'. forDyn :: (Reflex t, MonadHold t m) => Dynamic t a -> (a -> b) -> m (Dynamic t b) forDyn = flip mapDyn -- | Map a monadic function over a 'Dynamic'. The only monadic action that the given function can -- perform is 'sample'. {-# INLINE mapDynM #-} mapDynM :: forall t m a b. (Reflex t, MonadHold t m) => (forall m'. MonadSample t m' => a -> m' b) -> Dynamic t a -> m (Dynamic t b) mapDynM f d = do let e' = push (liftM Just . f :: a -> PushM t (Maybe b)) $ updated d eb' = fmap constant e' v0 = pull $ f =<< sample (current d) bb' :: Behavior t (Behavior t b) <- hold v0 eb' let b' = pull $ sample =<< sample bb' return $ Dynamic b' e' -- | Create a 'Dynamic' using the initial value and change it each -- time the 'Event' occurs using a folding function on the previous -- value and the value of the 'Event'. foldDyn :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> b) -> b -> Event t a -> m (Dynamic t b) foldDyn f = foldDynMaybe $ \o v -> Just $ f o v -- | Create a 'Dynamic' using the initial value and change it each -- time the 'Event' occurs using a monadic folding function on the -- previous value and the value of the 'Event'. foldDynM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t b) -> b -> Event t a -> m (Dynamic t b) foldDynM f = foldDynMaybeM $ \o v -> liftM Just $ f o v foldDynMaybe :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> Maybe b) -> b -> Event t a -> m (Dynamic t b) foldDynMaybe f = foldDynMaybeM $ \o v -> return $ f o v foldDynMaybeM :: (Reflex t, MonadHold t m, MonadFix m) => (a -> b -> PushM t (Maybe b)) -> b -> Event t a -> m (Dynamic t b) foldDynMaybeM f z e = do rec let e' = flip push e $ \o -> do v <- sample b' f o v b' <- hold z e' return $ Dynamic b' e' -- | Create a new 'Dynamic' that counts the occurences of the 'Event'. count :: (Reflex t, MonadHold t m, MonadFix m, Num b) => Event t a -> m (Dynamic t b) count e = holdDyn 0 =<< zipListWithEvent const (iterate (+1) 1) e -- | Create a new 'Dynamic' using the initial value that flips its -- value every time the 'Event' occurs. toggle :: (Reflex t, MonadHold t m, MonadFix m) => Bool -> Event t a -> m (Dynamic t Bool) toggle = foldDyn (const not) -- | Switches to the new 'Event' whenever it receives one. Switching -- occurs *before* the inner 'Event' fires - so if the 'Dynamic' changes and both the old and new -- inner Events fire simultaneously, the output will fire with the value of the *new* 'Event'. switchPromptlyDyn :: forall t a. Reflex t => Dynamic t (Event t a) -> Event t a switchPromptlyDyn de = let eLag = switch $ current de eCoincidences = coincidence $ updated de in leftmost [eCoincidences, eLag] {- mergeEventsWith :: Reflex t m => (a -> a -> a) -> Event t a -> Event t a -> m (Event t a) mergeEventsWith f ea eb = mapE (mergeThese f) =<< alignEvents ea eb firstE :: (Reflex t m) => [Event t a] -> m (Event t a) firstE [] = return never firstE (h:t) = mergeEventsLeftBiased h =<< firstE t concatEventsWith :: (Reflex t m) => (a -> a -> a) -> [Event t a] -> m (Event t a) concatEventsWith _ [] = return never concatEventsWith _ [e] = return e concatEventsWith f es = mapEM (liftM (foldl1 f . map (\(Const2 _ :=> v) -> v) . DMap.toList) . sequenceDmap) <=< mergeEventDMap $ DMap.fromList $ map (\(k, v) -> WrapArg (Const2 k) :=> v) $ zip [0 :: Int ..] es --concatEventsWith f (h:t) = mergeEventsWith f h =<< concatEventsWith f t mconcatE :: (Reflex t m, Monoid a) => [Event t a] -> m (Event t a) mconcatE = concatEventsWith mappend -} -- | Split the 'Dynamic' into two 'Dynamic's, each taking the -- respective value of the tuple. splitDyn :: (Reflex t, MonadHold t m) => Dynamic t (a, b) -> m (Dynamic t a, Dynamic t b) splitDyn d = liftM2 (,) (mapDyn fst d) (mapDyn snd d) -- | Merge the 'Dynamic' values using their 'Monoid' instance. mconcatDyn :: forall t m a. (Reflex t, MonadHold t m, Monoid a) => [Dynamic t a] -> m (Dynamic t a) mconcatDyn es = do ddm :: Dynamic t (DMap (Const2 Int a)) <- distributeDMapOverDyn $ DMap.fromList $ map (\(k, v) -> WrapArg (Const2 k) :=> v) $ zip [0 :: Int ..] es mapDyn (mconcat . map (\(Const2 _ :=> v) -> v) . DMap.toList) ddm -- | Create a 'Dynamic' with a 'DMap' of values out of a 'DMap' of -- Dynamic values. distributeDMapOverDyn :: forall t m k. (Reflex t, MonadHold t m, GCompare k) => DMap (WrapArg (Dynamic t) k) -> m (Dynamic t (DMap k)) distributeDMapOverDyn dm = case DMap.toList dm of [] -> return $ constDyn DMap.empty [WrapArg k :=> v] -> mapDyn (DMap.singleton k) v _ -> do let edmPre = merge $ rewrapDMap updated dm edm :: Event t (DMap k) = flip push edmPre $ \o -> return . Just =<< do let f _ = \case This origDyn -> sample $ current origDyn That _ -> error "distributeDMapOverDyn: should be impossible to have an event occurring that is not present in the original DMap" These _ (Identity newVal) -> return newVal sequenceDmap $ combineDMapsWithKey f dm (wrapDMap Identity o) dm0 :: Behavior t (DMap k) = pull $ do liftM DMap.fromList $ forM (DMap.toList dm) $ \(WrapArg k :=> dv) -> liftM (k :=>) $ sample $ current dv bbdm :: Behavior t (Behavior t (DMap k)) <- hold dm0 $ fmap constant edm let bdm = pull $ sample =<< sample bbdm return $ Dynamic bdm edm -- | Merge two 'Dynamic's into a new one using the provided -- function. The new 'Dynamic' changes its value each time one of the -- original 'Dynamic's changes its value. combineDyn :: forall t m a b c. (Reflex t, MonadHold t m) => (a -> b -> c) -> Dynamic t a -> Dynamic t b -> m (Dynamic t c) combineDyn f da db = do let eab = align (updated da) (updated db) ec = flip push eab $ \o -> do (a, b) <- case o of This a -> do b <- sample $ current db return (a, b) That b -> do a <- sample $ current da return (a, b) These a b -> return (a, b) return $ Just $ f a b c0 :: Behavior t c = pull $ liftM2 f (sample $ current da) (sample $ current db) bbc :: Behavior t (Behavior t c) <- hold c0 $ fmap constant ec let bc :: Behavior t c = pull $ sample =<< sample bbc return $ Dynamic bc ec {- tagInnerDyn :: Reflex t => Event t (Dynamic t a) -> Event t a tagInnerDyn e = let eSlow = push (liftM Just . sample . current) e eFast = coincidence $ fmap updated e in leftmost [eFast, eSlow] -} -- | Join a nested 'Dynamic' into a new 'Dynamic' that has the value -- of the inner 'Dynamic'. joinDyn :: forall t a. (Reflex t) => Dynamic t (Dynamic t a) -> Dynamic t a joinDyn dd = let b' = pull $ sample . current =<< sample (current dd) eOuter :: Event t a = pushAlways (sample . current) $ updated dd eInner :: Event t a = switch $ fmap updated (current dd) eBoth :: Event t a = coincidence $ fmap updated (updated dd) e' = leftmost [eBoth, eOuter, eInner] in Dynamic b' e' --TODO: Generalize this to functors other than Maps -- | Combine a 'Dynamic' of a 'Map' of 'Dynamic's into a 'Dynamic' -- with the current values of the 'Dynamic's in a map. joinDynThroughMap :: forall t k a. (Reflex t, Ord k) => Dynamic t (Map k (Dynamic t a)) -> Dynamic t (Map k a) joinDynThroughMap dd = let b' = pull $ mapM (sample . current) =<< sample (current dd) eOuter :: Event t (Map k a) = pushAlways (mapM (sample . current)) $ updated dd eInner :: Event t (Map k a) = attachWith (flip Map.union) b' $ switch $ fmap (mergeMap . fmap updated) (current dd) --Note: the flip is important because Map.union is left-biased readNonFiring :: MonadSample t m => These (Dynamic t a) a -> m a readNonFiring = \case This d -> sample $ current d That a -> return a These _ a -> return a eBoth :: Event t (Map k a) = coincidence $ fmap (\m -> pushAlways (mapM readNonFiring . align m) $ mergeMap $ fmap updated m) (updated dd) e' = leftmost [eBoth, eOuter, eInner] in Dynamic b' e' -- | Print the value of the 'Dynamic' on each change and prefix it -- with the provided string. This should /only/ be used for debugging. -- -- Note: Just like Debug.Trace.trace, the value will only be shown if something -- else in the system is depending on it. traceDyn :: (Reflex t, Show a) => String -> Dynamic t a -> Dynamic t a traceDyn s = traceDynWith $ \x -> s <> ": " <> show x -- | Print the result of applying the provided function to the value -- of the 'Dynamic' on each change. This should /only/ be used for -- debugging. -- -- Note: Just like Debug.Trace.trace, the value will only be shown if something -- else in the system is depending on it. traceDynWith :: Reflex t => (a -> String) -> Dynamic t a -> Dynamic t a traceDynWith f d = let e' = traceEventWith f $ updated d in Dynamic (current d) e' -- | Replace the value of the 'Event' with the current value of the 'Dynamic' -- each time the 'Event' occurs. -- -- Note: `tagDyn d e` differs from `tag (current d) e` in the case that `e` is firing -- at the same time that `d` is changing. With `tagDyn d e`, the *new* value of `d` -- will replace the value of `e`, whereas with `tag (current d) e`, the *old* value -- will be used, since the 'Behavior' won't be updated until the end of the frame. -- Additionally, this means that the output 'Event' may not be used to directly change -- the input 'Dynamic', because that would mean its value depends on itself. When creating -- cyclic data flows, generally `tag (current d) e` is preferred. tagDyn :: Reflex t => Dynamic t a -> Event t b -> Event t a tagDyn = attachDynWith const -- | Attach the current value of the 'Dynamic' to the value of the -- 'Event' each time it occurs. -- -- Note: `attachDyn d` is not the same as `attach (current d)`. See 'tagDyn' for details. attachDyn :: Reflex t => Dynamic t a -> Event t b -> Event t (a, b) attachDyn = attachDynWith (,) -- | Combine the current value of the 'Dynamic' with the value of the -- 'Event' each time it occurs. -- -- Note: `attachDynWith f d` is not the same as `attachWith f (current d)`. See 'tagDyn' for details. attachDynWith :: Reflex t => (a -> b -> c) -> Dynamic t a -> Event t b -> Event t c attachDynWith f = attachDynWithMaybe $ \a b -> Just $ f a b -- | Create a new 'Event' by combining the value at each occurence -- with the current value of the 'Dynamic' value and possibly -- filtering if the combining function returns 'Nothing'. -- -- Note: `attachDynWithMaybe f d` is not the same as `attachWithMaybe f (current d)`. See 'tagDyn' for details. attachDynWithMaybe :: Reflex t => (a -> b -> Maybe c) -> Dynamic t a -> Event t b -> Event t c attachDynWithMaybe f d e = let e' = attach (current d) e in fforMaybe (align e' $ updated d) $ \case This (a, b) -> f a b -- Only the tagging event is firing, so use that These (_, b) a -> f a b -- Both events are firing, so use the newer value That _ -> Nothing -- The tagging event isn't firing, so don't fire -------------------------------------------------------------------------------- -- Demux -------------------------------------------------------------------------------- -- | Represents a time changing value together with an 'EventSelector' -- that can efficiently detect when the underlying Dynamic has a particular value. -- This is useful for representing data like the current selection of a long list. -- -- Semantically, -- > getDemuxed (demux d) k === mapDyn (== k) d -- However, the when getDemuxed is used multiple times, the complexity is only /O(log(n))/, -- rather than /O(n)/ for mapDyn. data Demux t k = Demux { demuxValue :: Behavior t k , demuxSelector :: EventSelector t (Const2 k Bool) } -- | Demultiplex an input value to a 'Demux' with many outputs. At any given time, whichever output is indicated by the given 'Dynamic' will be 'True'. demux :: (Reflex t, Ord k) => Dynamic t k -> Demux t k demux k = Demux (current k) (fan $ attachWith (\k0 k1 -> if k0 == k1 then DMap.empty else DMap.fromList [Const2 k0 :=> False, Const2 k1 :=> True]) (current k) (updated k)) --TODO: The pattern of using hold (sample b0) can be reused in various places as a safe way of building certain kinds of Dynamics; see if we can factor this out -- | Select a particular output of the 'Demux'; this is equivalent to (but much faster than) -- mapping over the original 'Dynamic' and checking whether it is equal to the given key. getDemuxed :: (Reflex t, MonadHold t m, Eq k) => Demux t k -> k -> m (Dynamic t Bool) getDemuxed d k = do let e = select (demuxSelector d) (Const2 k) bb <- hold (liftM (==k) $ sample $ demuxValue d) $ fmap return e let b = pull $ join $ sample bb return $ Dynamic b e -------------------------------------------------------------------------------- -- collectDyn -------------------------------------------------------------------------------- --TODO: This whole section is badly in need of cleanup data FHList f l where FHNil :: FHList f '[] FHCons :: f e -> FHList f l -> FHList f (e ': l) instance GEq (HListPtr l) where HHeadPtr `geq` HHeadPtr = Just Refl HHeadPtr `geq` HTailPtr _ = Nothing HTailPtr _ `geq` HHeadPtr = Nothing HTailPtr a `geq` HTailPtr b = a `geq` b instance GCompare (HListPtr l) where -- Warning: This ordering can't change, dmapTo*HList will break HHeadPtr `gcompare` HHeadPtr = GEQ HHeadPtr `gcompare` HTailPtr _ = GLT HTailPtr _ `gcompare` HHeadPtr = GGT HTailPtr a `gcompare` HTailPtr b = a `gcompare` b data HListPtr l a where HHeadPtr :: HListPtr (h ': t) h HTailPtr :: HListPtr t a -> HListPtr (h ': t) a fhlistToDMap :: forall f l. FHList f l -> DMap (WrapArg f (HListPtr l)) fhlistToDMap = DMap.fromList . go where go :: forall l'. FHList f l' -> [DSum (WrapArg f (HListPtr l'))] go = \case FHNil -> [] FHCons h t -> (WrapArg HHeadPtr :=> h) : map (\(WrapArg p :=> v) -> WrapArg (HTailPtr p) :=> v) (go t) class RebuildSortedHList l where rebuildSortedFHList :: [DSum (WrapArg f (HListPtr l))] -> FHList f l rebuildSortedHList :: [DSum (HListPtr l)] -> HList l instance RebuildSortedHList '[] where rebuildSortedFHList l = case l of [] -> FHNil _ : _ -> error "rebuildSortedFHList{'[]}: empty list expected" rebuildSortedHList l = case l of [] -> HNil _ : _ -> error "rebuildSortedHList{'[]}: empty list expected" instance RebuildSortedHList t => RebuildSortedHList (h ': t) where rebuildSortedFHList l = case l of ((WrapArg HHeadPtr :=> h) : t) -> FHCons h $ rebuildSortedFHList $ map (\(WrapArg (HTailPtr p) :=> v) -> WrapArg p :=> v) t _ -> error "rebuildSortedFHList{h':t}: non-empty list with HHeadPtr expected" rebuildSortedHList l = case l of ((HHeadPtr :=> h) : t) -> HCons h $ rebuildSortedHList $ map (\(HTailPtr p :=> v) -> p :=> v) t _ -> error "rebuildSortedHList{h':t}: non-empty list with HHeadPtr expected" dmapToHList :: forall l. RebuildSortedHList l => DMap (HListPtr l) -> HList l dmapToHList = rebuildSortedHList . DMap.toList distributeFHListOverDyn :: forall t m l. (Reflex t, MonadHold t m, RebuildSortedHList l) => FHList (Dynamic t) l -> m (Dynamic t (HList l)) distributeFHListOverDyn l = mapDyn dmapToHList =<< distributeDMapOverDyn (fhlistToDMap l) {- distributeFHListOverDyn l = do let ec = undefined c0 = pull $ sequenceFHList $ natMap (sample . current) l bbc <- hold c0 $ fmap constant ec let bc = pull $ sample =<< sample bbc return $ Dynamic bc ec -} class AllAreFunctors (f :: a -> *) (l :: [a]) where type FunctorList f l :: [*] toFHList :: HList (FunctorList f l) -> FHList f l fromFHList :: FHList f l -> HList (FunctorList f l) instance AllAreFunctors f '[] where type FunctorList f '[] = '[] toFHList l = case l of HNil -> FHNil _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139 fromFHList FHNil = HNil instance AllAreFunctors f t => AllAreFunctors f (h ': t) where type FunctorList f (h ': t) = f h ': FunctorList f t toFHList l = case l of a `HCons` b -> a `FHCons` toFHList b _ -> error "toFHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139 fromFHList (a `FHCons` b) = a `HCons` fromFHList b collectDyn :: ( RebuildSortedHList (HListElems b) , IsHList a, IsHList b , AllAreFunctors (Dynamic t) (HListElems b) , Reflex t, MonadHold t m , HListElems a ~ FunctorList (Dynamic t) (HListElems b) ) => a -> m (Dynamic t b) collectDyn ds = mapDyn fromHList =<< distributeFHListOverDyn (toFHList $ toHList ds) -- Poor man's Generic class IsHList a where type HListElems a :: [*] toHList :: a -> HList (HListElems a) fromHList :: HList (HListElems a) -> a instance IsHList (a, b) where type HListElems (a, b) = [a, b] toHList (a, b) = hBuild a b fromHList l = case l of a `HCons` b `HCons` HNil -> (a, b) _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139 instance IsHList (a, b, c, d) where type HListElems (a, b, c, d) = [a, b, c, d] toHList (a, b, c, d) = hBuild a b c d fromHList l = case l of a `HCons` b `HCons` c `HCons` d `HCons` HNil -> (a, b, c, d) _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139 instance IsHList (a, b, c, d, e, f) where type HListElems (a, b, c, d, e, f) = [a, b, c, d, e, f] toHList (a, b, c, d, e, f) = hBuild a b c d e f fromHList l = case l of a `HCons` b `HCons` c `HCons` d `HCons` e `HCons` f `HCons` HNil -> (a, b, c, d, e, f) _ -> error "fromHList: impossible" -- Otherwise, GHC complains of a non-exhaustive pattern match; see https://ghc.haskell.org/trac/ghc/ticket/4139
k0001/reflex
src/Reflex/Dynamic.hs
Haskell
bsd-3-clause
22,941
import qualified Data.Text.IO as T import qualified Data.Text as T import qualified Data.Text.Lazy.IO as TL import qualified Data.Text.Lazy as TL import Pipes import qualified Pipes.Text as TP import qualified Pipes.ByteString as BP import Pipes.Safe main = textaction big = "../../examples/txt/words2.txt" textaction = T.readFile big >>= T.putStrLn pipeaction = runEffect $ for ((TP.readFile big) >> return ()) (lift . T.putStrLn)
bitemyapp/text-pipes
bench/IO.hs
Haskell
bsd-3-clause
441
{-# LANGUAGE GADTs #-} module Syntax.Tree where -------------------------------------------------------------------------------- -- Identifiers -------------------------------------------------------------------------------- type Identifier = String type SnakeId = Identifier type CamelId = Identifier -- Used to refer to variables, functions, structs, etc. type VarName = SnakeId -- Represents how to 'reach' a variable, e.g. ["x", "m_x"] would be the -- variable m_x, via the object x. The code would be: x.m_x type VarPath = [VarName] -------------------------------------------------------------------------------- -- Types -------------------------------------------------------------------------------- -- Types associated with data stored in variables. data DataType = SymType | TapeType | CustomType StructName deriving (Eq, Show) -- Returns whether the data type is a custom type. Says nothing about which -- custom type it is. isCustomType :: DataType -> Bool isCustomType (CustomType _) = True isCustomType _ = False -- Types that have a data type, e.g. Symbol, Tape, Struct, etc. class Typed a where typeOf :: a -> DataType -------------------------------------------------------------------------------- -- Tape Symbols -------------------------------------------------------------------------------- -- Tape symbol, i.e. a symbol contained in a cell of the machine's tape. type TapeSymbol = Char -- Values that evaluate to tape symbols. data SymExpr = Read TapeExpr | SymLit TapeSymbol | SymVar VarPath deriving (Eq, Show) instance Typed SymExpr where typeOf _ = SymType -------------------------------------------------------------------------------- -- Tape -------------------------------------------------------------------------------- -- Values that evaluate to tape references. data TapeExpr = TapeLit String | TapeVar VarPath deriving (Eq, Show) instance Typed TapeExpr where typeOf _ = TapeType -------------------------------------------------------------------------------- -- Objects -------------------------------------------------------------------------------- -- Values that evaluate to structure instances. data ObjExpr = NewObj StructName [NewObjArg] | ObjVar StructName VarPath deriving (Eq, Show) instance Typed ObjExpr where typeOf (NewObj structName _) = CustomType structName typeOf (ObjVar structName _) = CustomType structName -------------------------------------------------------------------------------- -- Variables -------------------------------------------------------------------------------- -- Values that evaluate to either a symbol or tape. data AnyValExpr = S SymExpr | T TapeExpr | C ObjExpr deriving (Eq, Show) instance Typed AnyValExpr where typeOf (S s) = typeOf s typeOf (T t) = typeOf t typeOf (C c) = typeOf c -------------------------------------------------------------------------------- -- Functions -------------------------------------------------------------------------------- -- Name of a function. type FuncName = SnakeId -- Name of an argument to a function. type ArgName = SnakeId -- Argument supplied when defining a function. type FuncDeclArg = (ArgName, DataType) -- Argument supplied when invoking a function. type FuncCallArg = AnyValExpr -- Returns the type of an argument to a function invocation. argType :: FuncDeclArg -> DataType argType = snd -------------------------------------------------------------------------------- -- Structs -------------------------------------------------------------------------------- -- Name of a structure. type StructName = CamelId -- Variable contained within a struct. type StructMemberVar = (VarName, DataType) -- Argument supplied when creating an object. type NewObjArg = AnyValExpr -- Returns the type of the variable in the struct. memberVarType :: StructMemberVar -> DataType memberVarType = snd -------------------------------------------------------------------------------- -- Bexp -------------------------------------------------------------------------------- -- Syntax tree for boolean expressions. data Bexp = TRUE | FALSE | Not Bexp | And Bexp Bexp | Or Bexp Bexp | Eq SymExpr SymExpr | Le SymExpr SymExpr | Ne SymExpr SymExpr deriving (Eq, Show) -------------------------------------------------------------------------------- -- Stm -------------------------------------------------------------------------------- -- Syntax tree for statements. data Stm = MoveLeft TapeExpr | MoveRight TapeExpr | Write TapeExpr SymExpr | Accept | Reject | If Bexp Stm [(Bexp, Stm)] (Maybe Stm) | While Bexp Stm | VarDecl VarName AnyValExpr | FuncDecl FuncName [FuncDeclArg] Stm | Call FuncName [AnyValExpr] | StructDecl StructName [StructMemberVar] | Comp Stm Stm | Print SymExpr | PrintLn (Maybe SymExpr) | DebugPrintTape TapeExpr deriving (Eq, Show) -------------------------------------------------------------------------------- -- Program -------------------------------------------------------------------------------- -- Path of a Metal file to be imported. type ImportPath = String -- The contents of a metal file. type FileContents = String
BakerSmithA/Turing
src/Syntax/Tree.hs
Haskell
bsd-3-clause
5,552
import Control.Monad as CM(forM,filterM) yes = flip mapM
bitemyapp/apply-refact
tests/examples/Default123.hs
Haskell
bsd-3-clause
57
module B2 where data Data1 a = C1 a Int Int | C4 Float | C2 Int | C3 Float addedC4 = error "added C4 Float to Data1" g (C1 x y z) (C1 n m o) = y + m g (C4 a) b = addedC4 g a (C4 b) = addedC4 g (C2 x) (C2 y) = x - y g (C3 x) (C3 k) = 42
kmate/HaRe
old/testing/addCon/B2AST.hs
Haskell
bsd-3-clause
245
module Syntax (module S) where import BaseSyntax as S import SyntaxRec as S import SyntaxRecPretty as S
forste/haReFork
tools/base/syntax/Syntax.hs
Haskell
bsd-3-clause
106
module HAD.Y2014.M03.D13.Solution where import Control.Applicative -- | pairToList Trnsform a pair of same type elements in a list of two -- elements. -- -- Of course, the major challenge is to find a point free function -- (without lambda) -- -- prop> replicate 2 (x :: Int) == pairToList (x,x) -- -- prop> (\(f,s) -> [f,s]) x == pairToList x -- pairToList :: (a,a) -> [a] pairToList = (:) <$> fst <*> ((:[]) . snd)
1HaskellADay/1HAD
exercises/HAD/Y2014/M03/D13/Solution.hs
Haskell
mit
421
{-# LANGUAGE NoImplicitPrelude #-} -- | Description: interpret flags parsed by "IHaskell.Flags" module IHaskell.Convert.Args (ConvertSpec(..), fromJustConvertSpec, toConvertSpec) where import IHaskellPrelude import qualified Data.Text as T import qualified Data.Text.Lazy as LT import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Char8 as CBS import Control.Applicative ((<$>)) import Control.Monad.Identity (Identity(Identity)) import Data.Char (toLower) import Data.List (partition) import Data.Maybe (fromMaybe) import qualified Data.Text.Lazy as T (pack, Text) import IHaskell.Flags (Argument(..), LhsStyle, lhsStyleBird, NotebookFormat(..)) import System.FilePath ((<.>), dropExtension, takeExtension) import Text.Printf (printf) -- | ConvertSpec is the accumulator for command line arguments data ConvertSpec f = ConvertSpec { convertToIpynb :: f Bool , convertInput :: f FilePath , convertOutput :: f FilePath , convertLhsStyle :: f (LhsStyle LT.Text) , convertOverwriteFiles :: Bool } -- | Convert a possibly-incomplete specification for what to convert into one which can be executed. -- Calls error when data is missing. fromJustConvertSpec :: ConvertSpec Maybe -> ConvertSpec Identity fromJustConvertSpec convertSpec = convertSpec { convertToIpynb = Identity toIpynb , convertInput = Identity inputFile , convertOutput = Identity outputFile , convertLhsStyle = Identity $ fromMaybe (LT.pack <$> lhsStyleBird) (convertLhsStyle convertSpec) } where toIpynb = fromMaybe (error "Error: direction for conversion unknown") (convertToIpynb convertSpec) (inputFile, outputFile) = case (convertInput convertSpec, convertOutput convertSpec) of (Nothing, Nothing) -> error "Error: no files specified for conversion" (Just i, Nothing) | toIpynb -> (i, dropExtension i <.> "ipynb") | otherwise -> (i, dropExtension i <.> "lhs") (Nothing, Just o) | toIpynb -> (dropExtension o <.> "lhs", o) | otherwise -> (dropExtension o <.> "ipynb", o) (Just i, Just o) -> (i, o) -- | Does this @Argument@ explicitly request a file format? isFormatSpec :: Argument -> Bool isFormatSpec (ConvertToFormat _) = True isFormatSpec (ConvertFromFormat _) = True isFormatSpec _ = False toConvertSpec :: [Argument] -> ConvertSpec Maybe toConvertSpec args = mergeArgs otherArgs (mergeArgs formatSpecArgs initialConvertSpec) where (formatSpecArgs, otherArgs) = partition isFormatSpec args initialConvertSpec = ConvertSpec Nothing Nothing Nothing Nothing False mergeArgs :: [Argument] -> ConvertSpec Maybe -> ConvertSpec Maybe mergeArgs args initialConvertSpec = foldr mergeArg initialConvertSpec args mergeArg :: Argument -> ConvertSpec Maybe -> ConvertSpec Maybe mergeArg OverwriteFiles convertSpec = convertSpec { convertOverwriteFiles = True } mergeArg (ConvertLhsStyle lhsStyle) convertSpec | Just previousLhsStyle <- convertLhsStyle convertSpec, previousLhsStyle /= fmap LT.pack lhsStyle = error $ printf "Conflicting lhs styles requested: <%s> and <%s>" (show lhsStyle) (show previousLhsStyle) | otherwise = convertSpec { convertLhsStyle = Just (LT.pack <$> lhsStyle) } mergeArg (ConvertFrom inputFile) convertSpec | Just previousInputFile <- convertInput convertSpec, previousInputFile /= inputFile = error $ printf "Multiple input files specified: <%s> and <%s>" inputFile previousInputFile | otherwise = convertSpec { convertInput = Just inputFile , convertToIpynb = case (convertToIpynb convertSpec, fromExt inputFile) of (prev, Nothing) -> prev (prev@(Just _), _) -> prev (Nothing, format) -> fmap (== LhsMarkdown) format } mergeArg (ConvertTo outputFile) convertSpec | Just previousOutputFile <- convertOutput convertSpec, previousOutputFile /= outputFile = error $ printf "Multiple output files specified: <%s> and <%s>" outputFile previousOutputFile | otherwise = convertSpec { convertOutput = Just outputFile , convertToIpynb = case (convertToIpynb convertSpec, fromExt outputFile) of (prev, Nothing) -> prev (prev@(Just _), _) -> prev (Nothing, format) -> fmap (== IpynbFile) format } mergeArg unexpectedArg _ = error $ "IHaskell.Convert.mergeArg: impossible argument: " ++ show unexpectedArg -- | Guess the format based on the file extension. fromExt :: FilePath -> Maybe NotebookFormat fromExt s = case map toLower (takeExtension s) of ".lhs" -> Just LhsMarkdown ".ipynb" -> Just IpynbFile _ -> Nothing
artuuge/IHaskell
src/IHaskell/Convert/Args.hs
Haskell
mit
4,837
{- (c) The University of Glasgow 2006 (c) The AQUA Project, Glasgow University, 1993-1998 This is useful, general stuff for the Native Code Generator. Provide trees (of instructions), so that lists of instructions can be appended in linear time. -} {-# LANGUAGE CPP #-} module OrdList ( OrdList, nilOL, isNilOL, unitOL, appOL, consOL, snocOL, concatOL, lastOL, mapOL, fromOL, toOL, foldrOL, foldlOL ) where import Outputable #if __GLASGOW_HASKELL__ > 710 import Data.Semigroup ( Semigroup ) import qualified Data.Semigroup as Semigroup #endif infixl 5 `appOL` infixl 5 `snocOL` infixr 5 `consOL` data OrdList a = None | One a | Many [a] -- Invariant: non-empty | Cons a (OrdList a) | Snoc (OrdList a) a | Two (OrdList a) -- Invariant: non-empty (OrdList a) -- Invariant: non-empty instance Outputable a => Outputable (OrdList a) where ppr ol = ppr (fromOL ol) -- Convert to list and print that #if __GLASGOW_HASKELL__ > 710 instance Semigroup (OrdList a) where (<>) = appOL #endif instance Monoid (OrdList a) where mempty = nilOL mappend = appOL mconcat = concatOL nilOL :: OrdList a isNilOL :: OrdList a -> Bool unitOL :: a -> OrdList a snocOL :: OrdList a -> a -> OrdList a consOL :: a -> OrdList a -> OrdList a appOL :: OrdList a -> OrdList a -> OrdList a concatOL :: [OrdList a] -> OrdList a lastOL :: OrdList a -> a nilOL = None unitOL as = One as snocOL as b = Snoc as b consOL a bs = Cons a bs concatOL aas = foldr appOL None aas lastOL None = panic "lastOL" lastOL (One a) = a lastOL (Many as) = last as lastOL (Cons _ as) = lastOL as lastOL (Snoc _ a) = a lastOL (Two _ as) = lastOL as isNilOL None = True isNilOL _ = False None `appOL` b = b a `appOL` None = a One a `appOL` b = Cons a b a `appOL` One b = Snoc a b a `appOL` b = Two a b fromOL :: OrdList a -> [a] fromOL a = go a [] where go None acc = acc go (One a) acc = a : acc go (Cons a b) acc = a : go b acc go (Snoc a b) acc = go a (b:acc) go (Two a b) acc = go a (go b acc) go (Many xs) acc = xs ++ acc mapOL :: (a -> b) -> OrdList a -> OrdList b mapOL _ None = None mapOL f (One x) = One (f x) mapOL f (Cons x xs) = Cons (f x) (mapOL f xs) mapOL f (Snoc xs x) = Snoc (mapOL f xs) (f x) mapOL f (Two x y) = Two (mapOL f x) (mapOL f y) mapOL f (Many xs) = Many (map f xs) instance Functor OrdList where fmap = mapOL foldrOL :: (a->b->b) -> b -> OrdList a -> b foldrOL _ z None = z foldrOL k z (One x) = k x z foldrOL k z (Cons x xs) = k x (foldrOL k z xs) foldrOL k z (Snoc xs x) = foldrOL k (k x z) xs foldrOL k z (Two b1 b2) = foldrOL k (foldrOL k z b2) b1 foldrOL k z (Many xs) = foldr k z xs foldlOL :: (b->a->b) -> b -> OrdList a -> b foldlOL _ z None = z foldlOL k z (One x) = k z x foldlOL k z (Cons x xs) = foldlOL k (k z x) xs foldlOL k z (Snoc xs x) = k (foldlOL k z xs) x foldlOL k z (Two b1 b2) = foldlOL k (foldlOL k z b1) b2 foldlOL k z (Many xs) = foldl k z xs toOL :: [a] -> OrdList a toOL [] = None toOL xs = Many xs
tjakway/ghcjvm
compiler/utils/OrdList.hs
Haskell
bsd-3-clause
3,188
{-# OPTIONS_GHC -Wunused-binds #-} {-# LANGUAGE PatternSynonyms #-} module Foo (pattern P) where -- x is used!! x :: Int x = 0 pattern P :: Int pattern P <- _ where P = x
ezyang/ghc
testsuite/tests/rename/should_compile/T12548.hs
Haskell
bsd-3-clause
182
module TcFail209a where g :: ((Show a, Num a), Eq a) => a -> a g = undefined
urbanslug/ghc
testsuite/tests/typecheck/should_fail/tcfail209a.hs
Haskell
bsd-3-clause
78
module Cli.Cli (listen, prompt, say) where listen :: IO String listen = getLine prompt :: (Read a) => String -> IO a prompt s = putStr s >> getLine >>= return . read say :: String -> IO () say x = putStrLn x
korczis/skull-haskell
src/Lib/Cli/Cli.hs
Haskell
mit
211
-- ghci -- :load C:\Users\Thomas\Documents\GitHub\haskell.practice\PE\Problem0016.hs -- :r -- :set +s module Problem16 where import Data.Char twoToThePowerOf n = 2 ^ n sumOfDigits n = sum $ map digitToInt $ show n sumOfDigitsForTwoToThePowerOf n = sumOfDigits $ twoToThePowerOf n --Tests sumOfDigitsForTwoToThePowerOfTests = and [ sumOfDigitsForTwoToThePowerOf 2 == 4, sumOfDigitsForTwoToThePowerOf 15 == 26, sumOfDigitsForTwoToThePowerOf 45 == 62 ] sumOfDigitsTests = and [ sumOfDigits 10 == 1, sumOfDigits 5555555555 == 50 ] twoToThePowerOfTests = and [ twoToThePowerOf 2 == 4, twoToThePowerOf 15 == 32768, twoToThePowerOf 30 == 1073741824, twoToThePowerOf 35 == 34359738368, twoToThePowerOf 45 == 35184372088832 ] tests = and [ twoToThePowerOfTests, sumOfDigitsTests, sumOfDigitsForTwoToThePowerOfTests ] answer = sumOfDigitsForTwoToThePowerOf 1000
Sobieck00/practice
pe/nonvisualstudio/haskell/OldWork/Implementation/Problem0016.hs
Haskell
mit
965
module Euler.P002 (sumEvenFib, sumEvenFib') where -- Problem 2 -- -- Each new term in the Fibonacci sequence is generated by adding the previous -- two terms. By starting with 1 and 2, the first 10 terms will be: -- -- 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... -- -- By considering the terms in the Fibonacci sequence whose values do not -- exceed four million, find the sum of the even-valued terms. sumEvenFib :: Int -> Int sumEvenFib = sum . evenFib evenFib :: Int -> [Int] evenFib n = filter even $ takeWhile (<= n) $ map fib [1..] fib :: (Integral a) => a -> a fib 0 = 0 fib 1 = 1 fib n = fib (n - 1) + fib (n - 2) sumEvenFib' :: Int -> Int sumEvenFib' = sum . evenFib' evenFib' :: Int -> [Int] evenFib' n = filter even $ takeWhile (<= n) fib' fib' :: [Int] fib' = 0 : scanl (+) 1 fib'
arnau/haskell-euler
src/Euler/P002.hs
Haskell
mit
819
{- Copyright (c) 2015 Nils 'bash0r' Jonsson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} {- | Module : $Header$ Description : An expression in the PolyDSL language. Author : Nils 'bash0r' Jonsson Copyright : (c) 2015 Nils 'bash0r' Jonsson License : MIT Maintainer : aka.bash0r@gmail.com Stability : unstable Portability : non-portable (Portability is untested.) An expression in the PolyDSL language. -} module Language.PolyDSL.DOM.Expression ( Expression (..) ) where -- | A PolyDSL expression. data Expression -- | A numeric value in the PolyDSL language. = NumberLiteral Rational -- | A string value in the PolyDSL language. | StringLiteral String -- | A char value in the PolyDSL language. | CharLiteral Char -- | An identifier in the PolyDSL language. | Identifier String -- | A binary operator expression in the PolyDSL language. | BinaryExpression String Expression Expression -- | A function call expression in the PolyDSL language. | FunctionCall Expression Expression deriving (Show, Eq)
project-horizon/framework
src/lib/Language/PolyDSL/DOM/Expression.hs
Haskell
mit
2,058
-- Enumerator and iteratee -- ref: https://wiki.haskell.org/Enumerator_and_iteratee -- okmij: http://okmij.org/ftp/Haskell/Iteratee/describe.pdf -- An enumerator is something that knows how to generate a list -- An iteratee is something that does one step in processing another piece of the big list. -- foldl (+) 0 xs -- foldl : enumerator -- ((+), 0) iteratee -- Separation of concerns -- fold(enumerator) has the intimate knowledge of the collection and how to get to the next element -- iteratee knows what to do with the current element -- (+) not to care which collection the element from -- 0 unware of the collection -- F-algebra -- ((+), 0) is an F-algebra -- foldl (+) 0 is a catamorphism -- iteratee is an automaton -- From this point of view, the enumerator sends elements of a list sequentially, from head to tail, as input messages to the iteratee. If the iteratee finishes, it outputs an accumulator. If the iteratee continues, it outputs nothing (i.e., ()). -- a set of states of iteratee is divided into subsets "Done" and "Next". -- Done-state means that automaton finished consuming a list, i.e., the automaton is dead. -- Next-state means that you can give an input message and obtain the same automaton in a new state. data Iteratee i o = Done o | Next (i -> Iteratee i o) -- i is the type of the iteratee's input messages (or list elements)-- o is a type of the output message (an accumulator). -- Iteratee stores not an automaton, but an automaton in some state, an automaton with distinguished state. -- The distinct feature of iteratee is that it can say after which list element an iteratee finishes. An iteratee says this by sending "Done" to an enumerator. Then the enumerator can, for example, close a file or a socket (a stream) where a list of characters is read from. Lazy I/O, which uses lazy lists, closes a stream only when the stream is exhausted. -- The drawback is that an enumerator can not tell an iteratee that an input is exhausted — an Iteratee consumes only infinite lists. You can remedy this by assuming -- i == Maybe i' (That's just fix) -- sample enumerator that takes input messages from a file enumerator :: FilePath -> Iteratee (Maybe Char) o -> IO o enumerator file it = withFile file ReadMode $ \h -> fix (\rc it -> case it of Done o -> return o Next f -> do eof <- hIsEOF h case eof of False -> do c <- hGetChar h rc (f (Just c)) True -> rc (f Nothing) ) it -- 2. Functions -- pi-calculus notation -- Monadic parsing (it0 -> it1) -- You can compose iteratees sequentially in time. This is done by (>>). it0 >> it1 means that when it0 finishes, it1 starts. Generally speaking, Iteratee i is a Monad, and it works exactly like a monadic parser. {- s = state -} instance Functor (Iteratee input) where fmap f = fix $ \rc s -> case s of Done o -> Done (f o) Next g -> Next (rc . g) instance Monad (Iteratee input) where return = Done it0 >>= it1 = fix (\rc s -> case s of Done o -> it1 o Next g -> Next (rc . g) ) it0 -- Repetitive parsing (it1 | !it0) -- You can also compose iteratees sequentially in space. it0's output messages become it1's input messages, so it0 and it1 work in parallel. Their composition is denoted it1 . it0. If it0 finishes, it is resurrected to its original state. If it1 finishes, it1 . it0 finishes — The main feature here is that it0 is restarted, as this is used for repetitive parsing. arr0 f = Next $ \i -> Done (f i) instance Category Iteratee where id = arr0 id it1 . it0 = fix (\rc1 it1 -> case it1 of Done c -> Done c Next f1 -> fix (\rc0 it0 -> case it0 of Done b -> rc1 (f1 b) Next f0 -> Next (rc0 . f0) ) it0 ) it1 -- 3. Generalization -- You may note that Iteratee is a final coalgebra. Other kinds of automata can be described with other F-coalgebras. In practice such automata can handle network protocols or interactive user input. See for example papers by Bart Jacobs for theoretical discussion. {- type Iteratee el m a −− a processor of the stream of els −− in a monad m yielding the result of type a instance Monad m ⇒ Monad (Iteratee el m) instance MonadTrans (Iteratee el ) getchar :: Monad m ⇒ Iteratee el m (Maybe el) −− cf. IO.getChar, List . head count_i :: Monad m ⇒ Iteratee el m Int −− cf. List . length run :: Monad m ⇒ Iteratee el m a → m a −− extract Iteratee ’ s result −− A producer of the stream of els in a monad m type Enumerator el m a = Iteratee el m a → m (Iteratee el m a) enum file :: FilePath → Enumerator Char IO a −− Enumerator of a file −− A transformer of the stream of elo to the stream of eli −− (a producer of the stream eli and a consumer of the stream elo ) type Enumeratee elo eli m a = Iteratee eli m a → Iteratee elo m (Iteratee eli m a) en_filter :: Monad m ⇒ (el → Bool) → Enumeratee el el m a take :: Monad m ⇒ Int → Enumeratee el el m a −− cf. List . take enum_words :: Monad m ⇒ Enumeratee Char String m a −− cf. List.words −− Kleisli (monadic function) composition: composing enumerators (>>>) :: Monad m ⇒ (a → m b) → (b → m c) → (a → m c) −− Connecting producers with transformers (cf . (= )) infixr 1 . | −− right−associative (.|) :: Monad m ⇒ (Iteratee el m a → w) → Iteratee el m (Iteratee el ’ m a) → w −− Parallel composition of iteratees (cf . List . zip ) en_pair :: Monad m ⇒ Iteratee el m a → Iteratee el m b → Iteratee el m (a,b) -}
Airtnp/Freshman_Simple_Haskell_Lib
Idioms/Enumerator-Iteratee.hs
Haskell
mit
5,808
----------------------------------------------------------------------------- -- | -- Module : StandardLibrary -- Copyright : (c) University of Saskatchewan 2013 -- -- Maintainer : ivan.vendrov@usask.ca -- -- The Frabjous standard library -------------------------------------------------------------------------- module Frabjous.StdLib (Real, -- * Utility Functions clip, length, count, fraction, average, stepWire, -- * Random Numbers uniform, frequencies, draw, -- * Wire Combinators -- ** simple combinators constant, function, -- ** event combinators (<|>), edge, changed, andThen, never, after, for, delay, -- ** real numbers integrate, randomWalk, -- ** randomness noise, poisson, countingPoisson, rate, -- ** functions that take wires as parameters & analyze them somehow accumulate, countEvents, onChange, internalStateT, internalState, -- ** switches switch, stateDiagram, -- * Networks -- ** static networks emptyNetwork, randomNetwork, predicate, gridWithDiags, {- randomSymmetricNetwork, poissonSymmetricNetwork, -- ** dynamic networks memorylessSymmetric, randomSymmetric, poissonRandomSymmetric, distanceBased, -} -- ** auxiliary functions manhattan, euclidean, normed) where import Frabjous.StdLib.Internal hiding (edge) import qualified Frabjous.Compiler.Syntax as Syntax import Prelude hiding ((.), id, length, Real) import Control.Monad.Random hiding (uniform) import Data.Traversable as Traversable hiding (for) import Control.Wire (mkGen, mkState, (.), Wire, WireM, EventM, LastException, (<|>), after, delay, for, andThen, edge, changed) import qualified Control.Wire as Wire import Data.Monoid import Data.Tuple (swap) import Data.List hiding (length) import qualified Data.List import qualified Data.IntMap as IntMap type Real = Double -- -1. UTILITY FUNCTIONS -- | the function 'clip' keeps its value in the given closed interval clip (a,b) x = if x < a then a else if x > b then b else x -- | generalizes length to any numeric type, allowing one to elide 'fromIntegral' in code length :: (Num n) => [a] -> n length = fromIntegral . Data.List.length -- | counts the number of elements that satisfy the given predicate count :: (a -> Bool) -> [a] -> Integer count pred = length . filter pred -- | determines the fraction of elements satisfying the given predicate fraction :: (a -> Bool) -> [a] -> Double fraction pred l = fromIntegral (count pred l) / length l -- | finds the average of a list of numbers average :: [Double] -> Double average l = sum l / length l -- 0. RANDOM NUMBERS uniform :: MonadRandom m => (Double, Double) -> m Double uniform = getRandomR frequencies :: MonadRandom m => [(a, Double)] -> m a frequencies probs = let (vals, pdf) = unzip probs cdf = scanl1 (+) pdf in do p <- getRandom let Just idx = findIndex (>= p) cdf return (vals !! idx) draw :: MonadRandom m => Int -> m a -> m [a] draw n rand = Traversable.sequence (replicate n rand) stepWire :: Monad m => Wire.WireM m a b -> Wire.Time -> a -> m (Either LastException b, Wire.WireM m a b) stepWire = Wire.stepWire -- 1. WIRE COMBINATORS constant :: (Monad m) => b -> Wire e m a b constant = Wire.pure function :: (Monad m) => (a -> b) -> Wire e m a b function = Wire.arr never :: (Monad m, Monoid e) => Wire e m a b never = Wire.empty -- | draws a value from the given distribution at every timestep noise :: MonadRandom m => m a -> Wire LastException m input a noise distribution = mkGen $ \_ _ -> do val <- distribution return (Right val, noise distribution) -- | integrates its input with respect to time integrate :: Monad m => Double -> Wire e m Double Double integrate = internalStateT (\dt x -> (+ dt*x)) -- | performs a 1D random walk at the velocity specified by the given distribution randomWalk init distribution = integrate init . noise distribution -- | (TODO REFACTOR?) internalStateT applies the given transition function -- | to the timestep, input, and state at every step, then outputs the new state internalStateT :: (Double -> a -> s -> s) -- ^ the transition function -> s -- ^ the initial state -> Wire e m a s internalStateT transition init = mkState init $ \dt (x, state) -> let newState = transition dt x state in newState `seq` (Right newState, newState) -- | internalState applies the given transition function -- | to its input and state at every step, then outputs the state internalState transition init = internalStateT (const transition) init -- nonhomogenous poisson process rate :: MonadRandom m => Wire LastException m Double () rate = mkGen $ \dt lambda -> do e <- getRandom return (if e < 1 - exp (-dt * lambda) then Right () else Left mempty, rate) -- a poisson process with rate parameter lambda poisson :: MonadRandom m => Double -> Wire LastException m a () poisson lambda = rate . constant lambda -- a counting poisson process countingPoisson :: MonadRandom m => Double -> Wire LastException m a Int countingPoisson lambda = countEvents (poisson lambda) ----------------------------------------------------- -- Functions that take wires as parameters -- and analyze them somehow - ('higher order' wires) ----------------------------------------------------- -- | orElse is a synonym for <|> (acts like the first wire if it produces; otherwise, like the second) orElse :: Monad m => WireM m a b -> WireM m a b -> WireM m a b orElse = (<|>) -- | accumulates the output of a signal function by the given combining function, with the given starting state accumulate :: Monad m => (b -> a -> b) -> b -> Wire e m c a -> Wire e m c b accumulate binop init wire = Wire.hold init (Wire.accum binop init . wire) -- | count the number of events of an argument wire countEvents :: Monad m => Wire e m a b -> Wire e m a Int countEvents wire = accumulate (+) 0 (1 . wire) -- | produces when the argument wire changes output onChange :: (Eq b, Monad m) => WireM m a b -> EventM m a onChange wire = on (changed . wire) -- | produces when the argument wire produces on :: Monad m => WireM m a b -> EventM m a on wire = mkGen $ \dt x -> do (output, wire') <- stepWire wire dt x let output' = case output of Right _ -> Right x Left e -> Left e return (output', on wire') -- | whenever producer produces a wire, that wire is switched into (and starts at time 0) -- | (difference from Netwire is that there's no initial wire) switch producer = Wire.switch producer never -- statechart :: Wire a b -> Wire a (Wire a b) -> Wire a b -- statechart state transitions is a wire whose internal state will be the most recent -- value produced by transitions; and which is refreshed every time its internal state changes stateDiagram state transitions = switch (transitions . onChange state) `orElse` state -- 2. NETWORKS -- A) Library functions for creation pairs xs = [(u, v) | u <- xs, v <- xs, u < v] symmetrify edges = edges ++ map swap edges emptyNetwork :: (MonadRandom m) => [Int] -> [Int] -> m (Network e) emptyNetwork v1 v2 = return $ Network (Syntax.Many, Syntax.Many) v1 v2 [] randomNetwork :: (MonadRandom m) => Double -> [Int] -> [Int] -> m (Network ()) -- randomNetwork rng fraction size = a random network with the given integer vertices. -- each directed edge has a given probability of existing randomNetwork fraction vertices1 vertices2 = do randoms <- getRandoms let edges = map snd . filter ((<fraction) . fst) . zip randoms $ [(u,v) | u <- vertices1, v <- vertices2] return $ Network (Syntax.Many, Syntax.Many) vertices1 vertices2 (zipWith Edge edges (repeat ())) predicate :: (a -> a -> Bool) -> NetworkGenerator a () -- TODO generalize to any edge type predicate connected pop _ = let vertices = IntMap.toList pop edges = [(i1, i2) | (i1, v1) <- vertices, (i2, v2) <- vertices, i1 < i2, connected v1 v2] indices = IntMap.keys pop in return $ Network (Syntax.Many, Syntax.Many) indices indices (zipWith Edge edges (repeat ())) gridWithDiags :: Int -> [a -> Int] -> NetworkGenerator a () -- TODO generalize to any edge type gridWithDiags resolution coords = predicate connected where connected a1 a2 = let x = map ($a1) coords y = map ($a2) coords diffs = map abs $ zipWith (-) x y in all (<= resolution) diffs {- -- poissonSymmetricNetwork is like a random network but for a single population -- each UNDIRECTED edge has a "fraction" probability of existing poissonSymmetricNetwork fraction vertices _ = do randoms <- getRandoms let edges = map snd . filter ((<fraction) . fst) . zip randoms $ pairs vertices return $ fromEdges vertices vertices (symmetrify edges) -- | creates a random network with each link probability calculated using the -- | binary function prob randomSymmetricNetwork :: ((a,a) -> Double) -> NetworkGenerator a randomSymmetricNetwork prob pop _ = do randoms <- getRandoms let vertices = IntMap.toList pop edges' = map (snd . snd) . filter (\(r, (vs, _)) -> r < prob vs) . zip randoms $ [((v1, v2), (i1, i2)) | (i1, v1) <- vertices, (i2, v2) <- vertices, i1 < i2] edges = edges' ++ map swap edges' indices = map fst vertices return $ fromEdges indices indices edges -- B) dynamic networks -- converts a static network generator into a dynamic one by just applying it every step memorylessSymmetric :: NetworkGenerator a -> (model -> ReactiveOutput a) -> ModelWire model ManyToMany memorylessSymmetric staticCreator extractPop = helper where helper = mkGen $ \dt model -> do let v1 = collection . extractPop $ model network <- staticCreator v1 v1 return (Right network, helper) -- | have links between agents based on the given probability function randomSymmetric :: ((a,a) -> Double) -> (model -> ReactiveOutput a) -> ModelWire model ManyToMany randomSymmetric prob = memorylessSymmetric (randomSymmetricNetwork prob) poissonRandomSymmetric :: Double -> (model -> ReactiveOutput a) -> ModelWire model ManyToMany poissonRandomSymmetric prob = randomSymmetric (const prob) predicateDynamic pred = memorylessSymmetric (predicate pred) {- predicate :: (a -> a -> Bool) -> (model -> ReactiveOutput a) -> ModelWire model ManyToMany predicate connected extractPop = function helper where helper model = let pop = collection . extractPop $ model indices = IntMap.keys pop indexPairs = pairs indices withinDistance (i1, i2) = connected (pop IntMap.! i1) (pop IntMap.! i2) in fromEdges indices indices (symmetrify $ filter withinDistance indexPairs) -} distanceBased :: Num n => (a -> a -> n) -> (n -> Bool) -> (model -> ReactiveOutput a) -> ModelWire model ManyToMany distanceBased d pred = predicateDynamic (\ a b -> pred $ d a b) -} euclidean :: [a -> Double] -> a -> a -> Double euclidean = normed 2 manhattan :: Num n => [a -> n] -> a -> a -> n manhattan accessors p1 p2 = sum . map abs $ diffs accessors p1 p2 diffs accessors p1 p2 = let coords1 = map ($ p1) accessors coords2 = map ($ p2) accessors in zipWith (-) coords1 coords2 normed :: Double -> [a -> Double] -> a -> a -> Double normed p accessors p1 p2 = norm (diffs accessors p1 p2) where norm diffs = sum (map (**p) diffs) ** (1/p) {- -- sample dynamic network specifications : -- a. makes "v" a neighbour of "u" iff (pred u v) predicateNetwork :: (a -> a -> Bool) -> Vector a -> Vector (Vector a) predicateNetwork pred agents = map (\p -> filter (pred p) agents) agents -- b . makes u and v neighbours iff label u = label v equivalenceClass :: (Eq b) => (a :-> b) -> Vector a -> Vector (Vector a) equivalenceClass label = predicateNetwork ((==) `on` (get label)) -- c. makes person i belong to neighbourhood j of n iff i % n = j evenlyDistribute people nbhds = map (nbhds!) $ map (`mod` n) (fromList [0 .. nPeople-1]) where n = length nbhds nPeople = length people -}
ivendrov/frabjous2
src/Frabjous/StdLib.hs
Haskell
mit
12,883
{- Package for evaluating Scheme Expressions -} module Scheme.Eval ( -- module Scheme.Eval.LispError, module Scheme.Eval.Prim, module Scheme.Eval.EvalUtil, module Scheme.Eval.List, module Scheme.Eval.Comp, module Scheme.Eval.Unpack ) where import Text.ParserCombinators.Parsec hiding (spaces) import Control.Monad.Error import Scheme.Lex -- import Scheme.Eval.LispError import Scheme.Eval.Prim import Scheme.Eval.EvalUtil import Scheme.Eval.List import Scheme.Eval.Comp import Scheme.Eval.Unpack
johnellis1392/Haskell-Scheme
Scheme/Eval/Eval.hs
Haskell
mit
520
import Test.HUnit import System.Exit import Data.Set.Lazy tests = TestList [basic, fizzbuzztest, infinity] ---- BASIC ----- basic = TestList [noZero, oneToTen, noEleven] where toTenList = [1..10] toTenSet = fromList toTenList noZero = TestCase $ assertBool "Zero not in there" $not (member 0 toTenSet) oneToTen = TestCase $ assertBool "1 to 10 present in set." $ all (\i -> member i toTenSet) toTenList noEleven = TestCase $ assertBool "11 not in there" $not (member 11 toTenSet) ----- INFINITY---- evenNumberSet = fromList $ filter even [1..] infinity = TestList [ TestCase ( assertBool "Even numbers are in there " (all (\i -> member i evenNumberSet) [2,4,6,100,10^4])), TestCase ( assertBool "Odd numbers are in there " (all (\i ->not $ member i evenNumberSet) [1,3,5,99,10^4+1])) ] --- FizzBuzz --- isFizzBuzz x = x `mod` 7 == 0 || '7' `elem` show x fizzbuzzes = fromList $ filter isFizzBuzz [1..] fizzbuzztest = TestList[ TestCase ( assertBool "fizzes" (all (\i -> member i fizzbuzzes) [7,14,21,70,71,77])), TestCase ( assertBool "does not fizz" (all (\i -> not $ member i fizzbuzzes) [1,2,3,8,9,10,16,22,100])) ] main = do result <- runTestTT tests let allpassed = (errors result + failures result) == 0 if allpassed then exitSuccess else exitFailure
happyherp/lazyset
LazySetTest.hs
Haskell
mit
1,490
{-# LANGUAGE OverloadedStrings #-} module Codex.Config where import qualified Data.HashMap.Strict as HM import Snap.Util.FileServe(MimeMap, defaultMimeTypes) -- | custom mime type mapping mimeTypes :: MimeMap mimeTypes = HM.union defaultMimeTypes $ HM.fromList [(".mdown", "text/markdown"), (".md", "text/markdown"), (".tst", "text/plain"), (".cfg", "text/plain") ]
pbv/codex
src/Codex/Config.hs
Haskell
mit
452
-- | -- AST traversal extracting output types. module Hasql.TH.Extraction.OutputTypeList where import Hasql.TH.Prelude import PostgresqlSyntax.Ast foldable :: Foldable f => (a -> Either Text [Typename]) -> f a -> Either Text [Typename] foldable fn = fmap join . traverse fn . toList preparableStmt = \case SelectPreparableStmt a -> selectStmt a InsertPreparableStmt a -> insertStmt a UpdatePreparableStmt a -> updateStmt a DeletePreparableStmt a -> deleteStmt a -- * Insert insertStmt (InsertStmt a b c d e) = foldable returningClause e returningClause = targetList -- * Update updateStmt (UpdateStmt _ _ _ _ _ a) = foldable returningClause a -- * Delete deleteStmt (DeleteStmt _ _ _ _ a) = foldable returningClause a -- * Select selectStmt = \case Left a -> selectNoParens a Right a -> selectWithParens a selectNoParens (SelectNoParens _ a _ _ _) = selectClause a selectWithParens = \case NoParensSelectWithParens a -> selectNoParens a WithParensSelectWithParens a -> selectWithParens a selectClause = either simpleSelect selectWithParens simpleSelect = \case NormalSimpleSelect a _ _ _ _ _ _ -> foldable targeting a ValuesSimpleSelect a -> valuesClause a TableSimpleSelect _ -> Left "TABLE cannot be used as a final statement, since it's impossible to specify the output types" BinSimpleSelect _ a _ b -> do c <- selectClause a d <- selectClause b if c == d then return c else Left "Merged queries produce results of incompatible types" targeting = \case NormalTargeting a -> targetList a AllTargeting a -> foldable targetList a DistinctTargeting _ b -> targetList b targetList = foldable targetEl targetEl = \case AliasedExprTargetEl a _ -> aExpr a ImplicitlyAliasedExprTargetEl a _ -> aExpr a ExprTargetEl a -> aExpr a AsteriskTargetEl -> Left "Target of all fields is not allowed, \ \because it leaves the output types unspecified. \ \You have to be specific." valuesClause = foldable (foldable aExpr) aExpr = \case CExprAExpr a -> cExpr a TypecastAExpr _ a -> Right [a] a -> Left "Result expression is missing a typecast" cExpr = \case InParensCExpr a Nothing -> aExpr a a -> Left "Result expression is missing a typecast"
nikita-volkov/hasql-th
library/Hasql/TH/Extraction/OutputTypeList.hs
Haskell
mit
2,245
{-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-} -- | Reexports "Text.Read.Lex.Compat" -- from a globally unique namespace. module Text.Read.Lex.Compat.Repl.Batteries ( module Text.Read.Lex.Compat ) where import "this" Text.Read.Lex.Compat
haskell-compat/base-compat
base-compat-batteries/src/Text/Read/Lex/Compat/Repl/Batteries.hs
Haskell
mit
294
module OneDim where import Data.Bits import CellularAutomata2D import GUI initSpace1D :: Int -> [a] -> Torus (Maybe a) initSpace1D steps initialSpace1D = setCells emptySpace (zip fstRow $ map Just initialSpace1D) where emptySpace = initSpace (steps, length initialSpace1D) (const $ Nothing) fstRow = zip (repeat 0) [0..length initialSpace1D - 1] make1DRule :: Int -> ([a] -> a) -> Rule (Maybe a) make1DRule radius rule1D = Rule { ruleNeighborhoodDeltas = zip (repeat $ -1) [-radius..radius] , ruleFunction = \self maybeNeighborhood -> case self of Just state -> return (Just state) Nothing -> case sequence maybeNeighborhood of Just neighborhood -> return $ Just $ rule1D neighborhood Nothing -> return Nothing } instance Cell a => Cell (Maybe a) where getColor (Just s) = getColor s getColor Nothing = grey getSuccState = fmap getSuccState elementaryCellularAutomata :: Int -> Rule (Maybe Bool) elementaryCellularAutomata ruleNumber = make1DRule 1 (\[l, c, r] -> 0 /= (ruleNumber .&. (shiftL 1 (4 * boolToInt l + 2 * boolToInt c + boolToInt r)))) where boolToInt True = 1 boolToInt False = 0 singleCell :: Int -> [Bool] singleCell size = map isMidpoint [1..size] where isMidpoint = (== div size 2) main :: IO () main = runCellularAutomata2D (elementaryCellularAutomata 110) (initSpace1D 100 $ singleCell 100) >> return ()
orion-42/cellular-automata-2d
OneDim.hs
Haskell
mit
1,448
{- | Description : Truncation of floating-point significands Copyright : 2017 Andrew Dawson License : Apache-2.0 Tools for truncating the number of bits in the significand of floating-point numbers. The numbers can be represented in decimal, binary or hexadecimal. You can create additional representations by making instances of the 'Truncatable' typeclass. -} -- -- Copyright 2017 Andrew Dawson -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- module Truncate ( Truncatable(..) , TParser , WordF(..) , Binary(..) , Decimal(..) , Hexadecimal(..) , toBin , toDec , toHex , makeBin32 , makeBin64 , makeDec32 , makeDec64 , makeHex32 , makeHex64 ) where ------------------------------------------------------------------------ import Data.Binary.IEEE754 ( wordToFloat , floatToWord , wordToDouble , doubleToWord ) import Text.Read (readMaybe) ------------------------------------------------------------------------ import Truncate.Internal ------------------------------------------------------------------------ -- | A typeclass for things that can be represented as truncatable bits class Truncatable a where -- | Convert to a bits representation, either a 'WordF32' or 'WordF64'. makeBits :: a -> WordF -- | Convert from a bits representation which will be either a 'WordF32' -- or a 'WordF64'. fromBits :: WordF -> a -- | Truncation operator, truncates an instance to a specified number of -- bits in its significand. The truncation applies the IEEE round-to-nearest -- tie-to-even rounding specification. infixl 5 <# (<#) :: a -> Int -> a (<#) = (fromBits .) . truncateWord . makeBits -- | The same as '(<#)' with the arguments flipped. infixr 5 #> (#>) :: Int -> a -> a (#>)= flip (<#) -- | Convert from one 'Truncatable' instance to another. convert :: (Truncatable b) => a -> b convert = fromBits . makeBits ----------------------------------------------------------------------- -- | A function type for parsing 'Truncatable' types type TParser a = String -> Either String a ----------------------------------------------------------------------- -- | Truncatable floating-point numbers in binary representation. data Binary = Bin32 String | Bin64 String instance Truncatable Binary where makeBits (Bin32 b) = WordF32 $ binToWord b makeBits (Bin64 b) = WordF64 $ binToWord b fromBits (WordF32 b) = Bin32 (wordToBin b) fromBits (WordF64 b) = Bin64 (wordToBin b) instance Show Binary where show (Bin32 s) = zeroPad 32 s show (Bin64 s) = zeroPad 64 s instance Eq Binary where (Bin32 a) == (Bin32 b) = (zeroStrip a) == (zeroStrip b) (Bin64 a) == (Bin64 b) = (zeroStrip a) == (zeroStrip b) _ == _ = False -- | Convert a 'Truncatable' instance to 'Binary'. toBin :: (Truncatable a) => a -> Binary toBin = convert -- | Create a 'Bin32' from a string. The string should be a sequence of the -- characters @0@ and @1@ no longer than 32 characters in length. makeBin32 :: TParser Binary makeBin32 s | length s > 32 = Left $ tooManyDigits "binary" 32 | (not .validBin) s = Left $ invalidDigits "binary" 32 | otherwise = Right (Bin32 s) -- | Create a 'Bin64' from a string. The string should be a sequence of the -- characters @0@ and @1@ no longer than 64 characters in length. makeBin64 :: TParser Binary makeBin64 s | length s > 64 = Left $ tooManyDigits "binary" 64 | (not .validBin) s = Left $ invalidDigits "binary" 64 | otherwise = Right (Bin64 s) ----------------------------------------------------------------------- -- | Truncatable floating-point numbers in decimal representation. data Decimal = Dec32 Float | Dec64 Double deriving (Eq) instance Truncatable Decimal where makeBits (Dec32 f) = WordF32 (floatToWord f) makeBits (Dec64 f) = WordF64 (doubleToWord f) fromBits (WordF32 b) = Dec32 (wordToFloat b) fromBits (WordF64 b) = Dec64 (wordToDouble b) instance Show Decimal where show (Dec32 f) = show f show (Dec64 d) = show d -- | Convert a 'Truncatable' instance to 'Decimal'. toDec :: (Truncatable a) => a -> Decimal toDec = convert -- | Create a 'Dec32' from a string. The string can be anything that can be -- interpreted as a 32-bit 'Float' by 'read'. makeDec32 :: TParser Decimal makeDec32 s = case readMaybe s :: Maybe Float of Just f -> Right (Dec32 f) Nothing -> Left "Error: value is not a 32-bit decimal number" -- | Create a 'Dec64' from a string. The string can be anything that can be -- interpreted as a 64-bit 'Double' by 'read'. makeDec64 :: TParser Decimal makeDec64 s = case readMaybe s :: Maybe Double of Just f -> Right (Dec64 f) Nothing -> Left "Error: value is not a 64-bit decimal number" ----------------------------------------------------------------------- -- | Truncatable floating-point numbers in hexadecimal representation. data Hexadecimal = Hex32 String | Hex64 String instance Truncatable Hexadecimal where makeBits (Hex32 s) = WordF32 $ hexToWord s makeBits (Hex64 s) = WordF64 $ hexToWord s fromBits (WordF32 b) = Hex32 (wordToHex b) fromBits (WordF64 b) = Hex64 (wordToHex b) instance Show Hexadecimal where show (Hex32 s) = zeroPad 8 s show (Hex64 s) = zeroPad 16 s instance Eq Hexadecimal where (Hex32 a) == (Hex32 b) = (zeroStrip a) == (zeroStrip b) (Hex64 a) == (Hex64 b) = (zeroStrip a) == (zeroStrip b) _ == _ = False -- | Convert a 'Truncatable' instance to 'Hexadecimal'. toHex :: (Truncatable a) => a -> Hexadecimal toHex = convert -- | Create a 'Hex32' from a string. The string should be a sequence of the -- valid hexadecimal digits @0-9@ and @a-f@ no longer than 8 characters in length. makeHex32 :: TParser Hexadecimal makeHex32 s | length s > 8 = Left $ tooManyDigits "hexadecimal" 32 | (not . validHex) s = Left $ invalidDigits "hexadecimal" 32 | otherwise = Right (Hex32 s) -- | Create a 'Hex64' from a string. The string should be a sequence of the -- valid hexadecimal digits @0-9@ and @a-f@ no longer than 16 characters in length. makeHex64 :: TParser Hexadecimal makeHex64 s | length s > 16 = Left $ tooManyDigits "hexadecimal" 64 | (not . validHex) s = Left $ invalidDigits "hexadecimal" 64 | otherwise = Right (Hex64 s)
aopp-pred/fp-truncate
src/Truncate.hs
Haskell
apache-2.0
7,082
compress :: Eq a => [a] -> [a] compress [] = [] compress (x:xs) = compress' x xs where compress' x [] = [x] compress' y (x:xs) | y == x = compress' x xs | otherwise = y:(compress' x xs)
alephnil/h99
08.hs
Haskell
apache-2.0
232
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, TypeFamilies, TemplateHaskell, OverloadedStrings, InstanceSigs #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Types where import Control.Applicative ((<$>), pure, (<*>)) import Control.Monad (forM_, mzero) import Control.Monad.Reader (ask) import Control.Monad.State (get, put) import Data.Acid (Query, Update, makeAcidic) import Data.Aeson ((.:), (.=), object) import Data.Aeson.TH (deriveJSON, defaultOptions) import Data.Aeson.Types (FromJSON(..), ToJSON(..), Parser, Value(..)) import Data.Foldable (concat) import Data.SafeCopy (deriveSafeCopy, base) import Data.Time (UTCTime) import Data.Typeable (Typeable) import Network.URI (URI, URIAuth, parseURI) import Prelude hiding (concat) import qualified Data.Map as Map newtype Tag = Tag String deriving (Show, Typeable, Eq, Ord) data Link = Link { uri :: URI , tags :: [Tag] } deriving (Show, Typeable, Eq) data DateLink = DateLink { link :: Link , date :: UTCTime } deriving (Show, Typeable, Eq) -- Seems like a horrible hack, but let's make this work first -- before worrying about space/update efficiency. newtype Links = Links { getLinkMap :: Map.Map Tag [DateLink] } deriving (Show, Typeable) instance FromJSON Link where parseJSON :: Value -> Parser Link parseJSON (Object o) = Link <$> (maybe mzero return . parseURI =<< o .: "link") <*> o .: "tags" parseJSON _ = mzero instance ToJSON Link where toJSON (Link uri' tags') = object [ "uri" .= show uri' , "tags" .= tags' ] -- Orphan safecopy instances for URI-related things deriveSafeCopy 0 'base ''URI deriveSafeCopy 0 'base ''URIAuth deriveSafeCopy 0 'base ''Tag deriveSafeCopy 0 'base ''DateLink deriveSafeCopy 0 'base ''Link deriveSafeCopy 0 'base ''Links -- Orphan JSON instances for URI-related things deriveJSON defaultOptions ''URI deriveJSON defaultOptions ''URIAuth deriveJSON defaultOptions ''Tag deriveJSON defaultOptions ''DateLink getLinksByTag :: Tag -> Query Links [DateLink] getLinksByTag tag = concat . Map.lookup tag . getLinkMap <$> ask getLinks :: Query Links [DateLink] getLinks = concat . Map.elems . getLinkMap <$> ask postLink :: UTCTime -> Link -> Update Links () postLink now link' = forM_ (tags link') $ \t -> do let dateLink = DateLink link' now linkMap <- getLinkMap <$> get let newLinks = maybe (pure dateLink) (dateLink :) (Map.lookup t linkMap) put . Links $ Map.insert t newLinks linkMap makeAcidic ''Links ['getLinksByTag, 'getLinks, 'postLink]
passy/giflib-api
Types.hs
Haskell
apache-2.0
2,657
module Graphics.GL.Low.Common where import Graphics.GL import Graphics.GL.Low.Types import Graphics.GL.Low.Cube attachmentPointForImageFormat :: ImageFormat -> GLenum attachmentPointForImageFormat format = case format of RGB -> GL_COLOR_ATTACHMENT0 RGBA -> GL_COLOR_ATTACHMENT0 Alpha -> GL_COLOR_ATTACHMENT0 Luminance -> GL_COLOR_ATTACHMENT0 LuminanceAlpha -> GL_COLOR_ATTACHMENT0 Depth24 -> GL_DEPTH_ATTACHMENT Depth24Stencil8 -> GL_DEPTH_STENCIL_ATTACHMENT cubeSideCodes :: Cube GLenum cubeSideCodes = Cube { cubeLeft = GL_TEXTURE_CUBE_MAP_NEGATIVE_X , cubeRight = GL_TEXTURE_CUBE_MAP_POSITIVE_X , cubeTop = GL_TEXTURE_CUBE_MAP_POSITIVE_Y , cubeBottom = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y , cubeFront = GL_TEXTURE_CUBE_MAP_POSITIVE_Z , cubeBack = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z }
evanrinehart/lowgl
Graphics/GL/Low/Common.hs
Haskell
bsd-2-clause
865
{-# LANGUAGE TransformListComp #-} ----------------------------------------------------------------------------- -- | -- Module : Haddock.Backends.Html.Decl -- Copyright : (c) Simon Marlow 2003-2006, -- David Waern 2006-2009, -- Mark Lentczner 2010 -- License : BSD-like -- -- Maintainer : haddock@projects.haskell.org -- Stability : experimental -- Portability : portable ----------------------------------------------------------------------------- module Haddock.Backends.Xhtml.Decl ( ppDecl, ppTyName, ppTyFamHeader, ppTypeApp, tyvarNames ) where import Haddock.Backends.Xhtml.DocMarkup import Haddock.Backends.Xhtml.Layout import Haddock.Backends.Xhtml.Names import Haddock.Backends.Xhtml.Types import Haddock.Backends.Xhtml.Utils import Haddock.GhcUtils import Haddock.Types import Haddock.Doc (combineDocumentation) import Data.List ( intersperse, sort ) import qualified Data.Map as Map import Data.Maybe import Text.XHtml hiding ( name, title, p, quote ) import GHC import GHC.Exts import Name import BooleanFormula ppDecl :: Bool -> LinksInfo -> LHsDecl DocName -> DocForDecl DocName -> [DocInstance DocName] -> [(DocName, Fixity)] -> [(DocName, DocForDecl DocName)] -> Splice -> Unicode -> Qualification -> Html ppDecl summ links (L loc decl) (mbDoc, fnArgsDoc) instances fixities subdocs splice unicode qual = case decl of TyClD (FamDecl d) -> ppTyFam summ False links instances fixities loc mbDoc d splice unicode qual TyClD d@(DataDecl {}) -> ppDataDecl summ links instances fixities subdocs loc mbDoc d splice unicode qual TyClD d@(SynDecl {}) -> ppTySyn summ links fixities loc (mbDoc, fnArgsDoc) d splice unicode qual TyClD d@(ClassDecl {}) -> ppClassDecl summ links instances fixities loc mbDoc subdocs d splice unicode qual SigD (TypeSig lnames lty _) -> ppLFunSig summ links loc (mbDoc, fnArgsDoc) lnames lty fixities splice unicode qual SigD (PatSynSig lname qtvs prov req ty) -> ppLPatSig summ links loc (mbDoc, fnArgsDoc) lname qtvs prov req ty fixities splice unicode qual ForD d -> ppFor summ links loc (mbDoc, fnArgsDoc) d fixities splice unicode qual InstD _ -> noHtml _ -> error "declaration not supported by ppDecl" ppLFunSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName -> [Located DocName] -> LHsType DocName -> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html ppLFunSig summary links loc doc lnames lty fixities splice unicode qual = ppFunSig summary links loc doc (map unLoc lnames) (unLoc lty) fixities splice unicode qual ppFunSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName -> [DocName] -> HsType DocName -> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html ppFunSig summary links loc doc docnames typ fixities splice unicode qual = ppSigLike summary links loc mempty doc docnames fixities (typ, pp_typ) splice unicode qual where pp_typ = ppType unicode qual typ ppLPatSig :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName -> Located DocName -> (HsExplicitFlag, LHsTyVarBndrs DocName) -> LHsContext DocName -> LHsContext DocName -> LHsType DocName -> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html ppLPatSig summary links loc (doc, _argDocs) (L _ name) (expl, qtvs) lprov lreq typ fixities splice unicode qual | summary = pref1 | otherwise = topDeclElem links loc splice [name] (pref1 <+> ppFixities fixities qual) +++ docSection Nothing qual doc where pref1 = hsep [ keyword "pattern" , ppBinder summary occname , dcolon unicode , ppLTyVarBndrs expl qtvs unicode qual , cxt , ppLType unicode qual typ ] cxt = case (ppLContextMaybe lprov unicode qual, ppLContextMaybe lreq unicode qual) of (Nothing, Nothing) -> noHtml (Nothing, Just req) -> parens noHtml <+> darr <+> req <+> darr (Just prov, Nothing) -> prov <+> darr (Just prov, Just req) -> prov <+> darr <+> req <+> darr darr = darrow unicode occname = nameOccName . getName $ name ppSigLike :: Bool -> LinksInfo -> SrcSpan -> Html -> DocForDecl DocName -> [DocName] -> [(DocName, Fixity)] -> (HsType DocName, Html) -> Splice -> Unicode -> Qualification -> Html ppSigLike summary links loc leader doc docnames fixities (typ, pp_typ) splice unicode qual = ppTypeOrFunSig summary links loc docnames typ doc ( addFixities $ leader <+> ppTypeSig summary occnames pp_typ unicode , addFixities . concatHtml . punctuate comma $ map (ppBinder False) occnames , dcolon unicode ) splice unicode qual where occnames = map (nameOccName . getName) docnames addFixities html | summary = html | otherwise = html <+> ppFixities fixities qual ppTypeOrFunSig :: Bool -> LinksInfo -> SrcSpan -> [DocName] -> HsType DocName -> DocForDecl DocName -> (Html, Html, Html) -> Splice -> Unicode -> Qualification -> Html ppTypeOrFunSig summary links loc docnames typ (doc, argDocs) (pref1, pref2, sep) splice unicode qual | summary = pref1 | Map.null argDocs = topDeclElem links loc splice docnames pref1 +++ docSection curName qual doc | otherwise = topDeclElem links loc splice docnames pref2 +++ subArguments qual (do_args 0 sep typ) +++ docSection curName qual doc where curName = getName <$> listToMaybe docnames argDoc n = Map.lookup n argDocs do_largs n leader (L _ t) = do_args n leader t do_args :: Int -> Html -> HsType DocName -> [SubDecl] do_args n leader (HsForAllTy _ _ tvs lctxt ltype) = case unLoc lctxt of [] -> do_largs n leader' ltype _ -> (leader' <+> ppLContextNoArrow lctxt unicode qual, Nothing, []) : do_largs n (darrow unicode) ltype where leader' = leader <+> ppForAll tvs unicode qual do_args n leader (HsFunTy lt r) = (leader <+> ppLFunLhType unicode qual lt, argDoc n, []) : do_largs (n+1) (arrow unicode) r do_args n leader t = [(leader <+> ppType unicode qual t, argDoc n, [])] ppForAll :: LHsTyVarBndrs DocName -> Unicode -> Qualification -> Html ppForAll tvs unicode qual = case [ppKTv n k | L _ (KindedTyVar (L _ n) k) <- hsQTvBndrs tvs] of [] -> noHtml ts -> forallSymbol unicode <+> hsep ts +++ dot where ppKTv n k = parens $ ppTyName (getName n) <+> dcolon unicode <+> ppLKind unicode qual k ppFixities :: [(DocName, Fixity)] -> Qualification -> Html ppFixities [] _ = noHtml ppFixities fs qual = foldr1 (+++) (map ppFix uniq_fs) +++ rightEdge where ppFix (ns, p, d) = thespan ! [theclass "fixity"] << (toHtml d <+> toHtml (show p) <+> ppNames ns) ppDir InfixR = "infixr" ppDir InfixL = "infixl" ppDir InfixN = "infix" ppNames = case fs of _:[] -> const noHtml -- Don't display names for fixities on single names _ -> concatHtml . intersperse (stringToHtml ", ") . map (ppDocName qual Infix False) uniq_fs = [ (n, the p, the d') | (n, Fixity p d) <- fs , let d' = ppDir d , then group by Down (p,d') using groupWith ] rightEdge = thespan ! [theclass "rightedge"] << noHtml ppTyVars :: LHsTyVarBndrs DocName -> [Html] ppTyVars tvs = map ppTyName (tyvarNames tvs) tyvarNames :: LHsTyVarBndrs DocName -> [Name] tyvarNames = map getName . hsLTyVarNames ppFor :: Bool -> LinksInfo -> SrcSpan -> DocForDecl DocName -> ForeignDecl DocName -> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html ppFor summary links loc doc (ForeignImport (L _ name) (L _ typ) _ _) fixities splice unicode qual = ppFunSig summary links loc doc [name] typ fixities splice unicode qual ppFor _ _ _ _ _ _ _ _ _ = error "ppFor" -- we skip type patterns for now ppTySyn :: Bool -> LinksInfo -> [(DocName, Fixity)] -> SrcSpan -> DocForDecl DocName -> TyClDecl DocName -> Splice -> Unicode -> Qualification -> Html ppTySyn summary links fixities loc doc (SynDecl { tcdLName = L _ name, tcdTyVars = ltyvars , tcdRhs = ltype }) splice unicode qual = ppTypeOrFunSig summary links loc [name] (unLoc ltype) doc (full <+> fixs, hdr <+> fixs, spaceHtml +++ equals) splice unicode qual where hdr = hsep ([keyword "type", ppBinder summary occ] ++ ppTyVars ltyvars) full = hdr <+> equals <+> ppLType unicode qual ltype occ = nameOccName . getName $ name fixs | summary = noHtml | otherwise = ppFixities fixities qual ppTySyn _ _ _ _ _ _ _ _ _ = error "declaration not supported by ppTySyn" ppTypeSig :: Bool -> [OccName] -> Html -> Bool -> Html ppTypeSig summary nms pp_ty unicode = concatHtml htmlNames <+> dcolon unicode <+> pp_ty where htmlNames = intersperse (stringToHtml ", ") $ map (ppBinder summary) nms ppTyName :: Name -> Html ppTyName = ppName Prefix -------------------------------------------------------------------------------- -- * Type families -------------------------------------------------------------------------------- ppTyFamHeader :: Bool -> Bool -> FamilyDecl DocName -> Unicode -> Qualification -> Html ppTyFamHeader summary associated d@(FamilyDecl { fdInfo = info , fdKindSig = mkind }) unicode qual = (case info of OpenTypeFamily | associated -> keyword "type" | otherwise -> keyword "type family" DataFamily | associated -> keyword "data" | otherwise -> keyword "data family" ClosedTypeFamily _ -> keyword "type family" ) <+> ppFamDeclBinderWithVars summary d <+> (case mkind of Just kind -> dcolon unicode <+> ppLKind unicode qual kind Nothing -> noHtml ) ppTyFam :: Bool -> Bool -> LinksInfo -> [DocInstance DocName] -> [(DocName, Fixity)] -> SrcSpan -> Documentation DocName -> FamilyDecl DocName -> Splice -> Unicode -> Qualification -> Html ppTyFam summary associated links instances fixities loc doc decl splice unicode qual | summary = ppTyFamHeader True associated decl unicode qual | otherwise = header_ +++ docSection Nothing qual doc +++ instancesBit where docname = unLoc $ fdLName decl header_ = topDeclElem links loc splice [docname] $ ppTyFamHeader summary associated decl unicode qual <+> ppFixities fixities qual instancesBit | FamilyDecl { fdInfo = ClosedTypeFamily eqns } <- decl , not summary = subEquations qual $ map (ppTyFamEqn . unLoc) eqns | otherwise = ppInstances links instances docname unicode qual -- Individual equation of a closed type family ppTyFamEqn TyFamEqn { tfe_tycon = n, tfe_rhs = rhs , tfe_pats = HsWB { hswb_cts = ts }} = ( ppAppNameTypes (unLoc n) [] (map unLoc ts) unicode qual <+> equals <+> ppType unicode qual (unLoc rhs) , Nothing, [] ) -------------------------------------------------------------------------------- -- * Associated Types -------------------------------------------------------------------------------- ppAssocType :: Bool -> LinksInfo -> DocForDecl DocName -> LFamilyDecl DocName -> [(DocName, Fixity)] -> Splice -> Unicode -> Qualification -> Html ppAssocType summ links doc (L loc decl) fixities splice unicode qual = ppTyFam summ True links [] fixities loc (fst doc) decl splice unicode qual -------------------------------------------------------------------------------- -- * TyClDecl helpers -------------------------------------------------------------------------------- -- | Print a type family and its variables ppFamDeclBinderWithVars :: Bool -> FamilyDecl DocName -> Html ppFamDeclBinderWithVars summ (FamilyDecl { fdLName = lname, fdTyVars = tvs }) = ppAppDocNameNames summ (unLoc lname) (tyvarNames tvs) -- | Print a newtype / data binder and its variables ppDataBinderWithVars :: Bool -> TyClDecl DocName -> Html ppDataBinderWithVars summ decl = ppAppDocNameNames summ (tcdName decl) (tyvarNames $ tcdTyVars decl) -------------------------------------------------------------------------------- -- * Type applications -------------------------------------------------------------------------------- -- | Print an application of a DocName and two lists of HsTypes (kinds, types) ppAppNameTypes :: DocName -> [HsType DocName] -> [HsType DocName] -> Unicode -> Qualification -> Html ppAppNameTypes n ks ts unicode qual = ppTypeApp n ks ts (\p -> ppDocName qual p True) (ppParendType unicode qual) -- | Print an application of a DocName and a list of Names ppAppDocNameNames :: Bool -> DocName -> [Name] -> Html ppAppDocNameNames summ n ns = ppTypeApp n [] ns ppDN ppTyName where ppDN notation = ppBinderFixity notation summ . nameOccName . getName ppBinderFixity Infix = ppBinderInfix ppBinderFixity _ = ppBinder -- | General printing of type applications ppTypeApp :: DocName -> [a] -> [a] -> (Notation -> DocName -> Html) -> (a -> Html) -> Html ppTypeApp n [] (t1:t2:rest) ppDN ppT | operator, not . null $ rest = parens opApp <+> hsep (map ppT rest) | operator = opApp where operator = isNameSym . getName $ n opApp = ppT t1 <+> ppDN Infix n <+> ppT t2 ppTypeApp n ks ts ppDN ppT = ppDN Prefix n <+> hsep (map ppT $ ks ++ ts) ------------------------------------------------------------------------------- -- * Contexts ------------------------------------------------------------------------------- ppLContext, ppLContextNoArrow :: Located (HsContext DocName) -> Unicode -> Qualification -> Html ppLContext = ppContext . unLoc ppLContextNoArrow = ppContextNoArrow . unLoc ppLContextMaybe :: Located (HsContext DocName) -> Unicode -> Qualification -> Maybe Html ppLContextMaybe = ppContextNoLocsMaybe . map unLoc . unLoc ppContextNoArrow :: HsContext DocName -> Unicode -> Qualification -> Html ppContextNoArrow cxt unicode qual = fromMaybe noHtml $ ppContextNoLocsMaybe (map unLoc cxt) unicode qual ppContextNoLocs :: [HsType DocName] -> Unicode -> Qualification -> Html ppContextNoLocs cxt unicode qual = maybe noHtml (<+> darrow unicode) $ ppContextNoLocsMaybe cxt unicode qual ppContextNoLocsMaybe :: [HsType DocName] -> Unicode -> Qualification -> Maybe Html ppContextNoLocsMaybe [] _ _ = Nothing ppContextNoLocsMaybe cxt unicode qual = Just $ ppHsContext cxt unicode qual ppContext :: HsContext DocName -> Unicode -> Qualification -> Html ppContext cxt unicode qual = ppContextNoLocs (map unLoc cxt) unicode qual ppHsContext :: [HsType DocName] -> Unicode -> Qualification-> Html ppHsContext [] _ _ = noHtml ppHsContext [p] unicode qual = ppCtxType unicode qual p ppHsContext cxt unicode qual = parenList (map (ppType unicode qual) cxt) ------------------------------------------------------------------------------- -- * Class declarations ------------------------------------------------------------------------------- ppClassHdr :: Bool -> Located [LHsType DocName] -> DocName -> LHsTyVarBndrs DocName -> [Located ([Located DocName], [Located DocName])] -> Unicode -> Qualification -> Html ppClassHdr summ lctxt n tvs fds unicode qual = keyword "class" <+> (if not . null . unLoc $ lctxt then ppLContext lctxt unicode qual else noHtml) <+> ppAppDocNameNames summ n (tyvarNames tvs) <+> ppFds fds unicode qual ppFds :: [Located ([Located DocName], [Located DocName])] -> Unicode -> Qualification -> Html ppFds fds unicode qual = if null fds then noHtml else char '|' <+> hsep (punctuate comma (map (fundep . unLoc) fds)) where fundep (vars1,vars2) = ppVars vars1 <+> arrow unicode <+> ppVars vars2 ppVars = hsep . map ((ppDocName qual Prefix True) . unLoc) ppShortClassDecl :: Bool -> LinksInfo -> TyClDecl DocName -> SrcSpan -> [(DocName, DocForDecl DocName)] -> Splice -> Unicode -> Qualification -> Html ppShortClassDecl summary links (ClassDecl { tcdCtxt = lctxt, tcdLName = lname, tcdTyVars = tvs , tcdFDs = fds, tcdSigs = sigs, tcdATs = ats }) loc subdocs splice unicode qual = if not (any isVanillaLSig sigs) && null ats then (if summary then id else topDeclElem links loc splice [nm]) hdr else (if summary then id else topDeclElem links loc splice [nm]) (hdr <+> keyword "where") +++ shortSubDecls False ( [ ppAssocType summary links doc at [] splice unicode qual | at <- ats , let doc = lookupAnySubdoc (unL $ fdLName $ unL at) subdocs ] ++ -- ToDo: add associated type defaults [ ppFunSig summary links loc doc names typ [] splice unicode qual | L _ (TypeSig lnames (L _ typ) _) <- sigs , let doc = lookupAnySubdoc (head names) subdocs names = map unLoc lnames ] -- FIXME: is taking just the first name ok? Is it possible that -- there are different subdocs for different names in a single -- type signature? ) where hdr = ppClassHdr summary lctxt (unLoc lname) tvs fds unicode qual nm = unLoc lname ppShortClassDecl _ _ _ _ _ _ _ _ = error "declaration type not supported by ppShortClassDecl" ppClassDecl :: Bool -> LinksInfo -> [DocInstance DocName] -> [(DocName, Fixity)] -> SrcSpan -> Documentation DocName -> [(DocName, DocForDecl DocName)] -> TyClDecl DocName -> Splice -> Unicode -> Qualification -> Html ppClassDecl summary links instances fixities loc d subdocs decl@(ClassDecl { tcdCtxt = lctxt, tcdLName = lname, tcdTyVars = ltyvars , tcdFDs = lfds, tcdSigs = lsigs, tcdATs = ats }) splice unicode qual | summary = ppShortClassDecl summary links decl loc subdocs splice unicode qual | otherwise = classheader +++ docSection Nothing qual d +++ minimalBit +++ atBit +++ methodBit +++ instancesBit where classheader | any isVanillaLSig lsigs = topDeclElem links loc splice [nm] (hdr unicode qual <+> keyword "where" <+> fixs) | otherwise = topDeclElem links loc splice [nm] (hdr unicode qual <+> fixs) -- Only the fixity relevant to the class header fixs = ppFixities [ f | f@(n,_) <- fixities, n == unLoc lname ] qual nm = tcdName decl hdr = ppClassHdr summary lctxt (unLoc lname) ltyvars lfds -- ToDo: add assocatied typ defaults atBit = subAssociatedTypes [ ppAssocType summary links doc at subfixs splice unicode qual | at <- ats , let n = unL . fdLName $ unL at doc = lookupAnySubdoc (unL $ fdLName $ unL at) subdocs subfixs = [ f | f@(n',_) <- fixities, n == n' ] ] methodBit = subMethods [ ppFunSig summary links loc doc names typ subfixs splice unicode qual | L _ (TypeSig lnames (L _ typ) _) <- lsigs , let doc = lookupAnySubdoc (head names) subdocs subfixs = [ f | n <- names , f@(n',_) <- fixities , n == n' ] names = map unLoc lnames ] -- FIXME: is taking just the first name ok? Is it possible that -- there are different subdocs for different names in a single -- type signature? minimalBit = case [ s | L _ (MinimalSig _ s) <- lsigs ] of -- Miminal complete definition = every shown method And xs : _ | sort [getName n | Var (L _ n) <- xs] == sort [getName n | L _ (TypeSig ns _ _) <- lsigs, L _ n <- ns] -> noHtml -- Minimal complete definition = the only shown method Var (L _ n) : _ | [getName n] == [getName n' | L _ (TypeSig ns _ _) <- lsigs, L _ n' <- ns] -> noHtml -- Minimal complete definition = nothing And [] : _ -> subMinimal $ toHtml "Nothing" m : _ -> subMinimal $ ppMinimal False m _ -> noHtml ppMinimal _ (Var (L _ n)) = ppDocName qual Prefix True n ppMinimal _ (And fs) = foldr1 (\a b -> a+++", "+++b) $ map (ppMinimal True) fs ppMinimal p (Or fs) = wrap $ foldr1 (\a b -> a+++" | "+++b) $ map (ppMinimal False) fs where wrap | p = parens | otherwise = id instancesBit = ppInstances links instances nm unicode qual ppClassDecl _ _ _ _ _ _ _ _ _ _ _ = error "declaration type not supported by ppShortClassDecl" ppInstances :: LinksInfo -> [DocInstance DocName] -> DocName -> Unicode -> Qualification -> Html ppInstances links instances baseName unicode qual = subInstances qual instName links True baseName (map instDecl instances) -- force Splice = True to use line URLs where instName = getOccString $ getName baseName instDecl :: DocInstance DocName -> (SubDecl,SrcSpan) instDecl (L l inst, maybeDoc) = ((instHead inst, maybeDoc, []),l) instHead (n, ks, ts, ClassInst cs) = ppContextNoLocs cs unicode qual <+> ppAppNameTypes n ks ts unicode qual instHead (n, ks, ts, TypeInst rhs) = keyword "type" <+> ppAppNameTypes n ks ts unicode qual <+> maybe noHtml (\t -> equals <+> ppType unicode qual t) rhs instHead (n, ks, ts, DataInst dd) = keyword "data" <+> ppAppNameTypes n ks ts unicode qual <+> ppShortDataDecl False True dd unicode qual lookupAnySubdoc :: Eq id1 => id1 -> [(id1, DocForDecl id2)] -> DocForDecl id2 lookupAnySubdoc n = fromMaybe noDocForDecl . lookup n ------------------------------------------------------------------------------- -- * Data & newtype declarations ------------------------------------------------------------------------------- -- TODO: print contexts ppShortDataDecl :: Bool -> Bool -> TyClDecl DocName -> Unicode -> Qualification -> Html ppShortDataDecl summary dataInst dataDecl unicode qual | [] <- cons = dataHeader | [lcon] <- cons, ResTyH98 <- resTy, (cHead,cBody,cFoot) <- ppShortConstrParts summary dataInst (unLoc lcon) unicode qual = (dataHeader <+> equals <+> cHead) +++ cBody +++ cFoot | ResTyH98 <- resTy = dataHeader +++ shortSubDecls dataInst (zipWith doConstr ('=':repeat '|') cons) | otherwise = (dataHeader <+> keyword "where") +++ shortSubDecls dataInst (map doGADTConstr cons) where dataHeader | dataInst = noHtml | otherwise = ppDataHeader summary dataDecl unicode qual doConstr c con = toHtml [c] <+> ppShortConstr summary (unLoc con) unicode qual doGADTConstr con = ppShortConstr summary (unLoc con) unicode qual cons = dd_cons (tcdDataDefn dataDecl) resTy = (con_res . unLoc . head) cons ppDataDecl :: Bool -> LinksInfo -> [DocInstance DocName] -> [(DocName, Fixity)] -> [(DocName, DocForDecl DocName)] -> SrcSpan -> Documentation DocName -> TyClDecl DocName -> Splice -> Unicode -> Qualification -> Html ppDataDecl summary links instances fixities subdocs loc doc dataDecl splice unicode qual | summary = ppShortDataDecl summary False dataDecl unicode qual | otherwise = header_ +++ docSection Nothing qual doc +++ constrBit +++ instancesBit where docname = tcdName dataDecl cons = dd_cons (tcdDataDefn dataDecl) resTy = (con_res . unLoc . head) cons header_ = topDeclElem links loc splice [docname] $ ppDataHeader summary dataDecl unicode qual <+> whereBit <+> fix fix = ppFixities (filter (\(n,_) -> n == docname) fixities) qual whereBit | null cons = noHtml | otherwise = case resTy of ResTyGADT _ _ -> keyword "where" _ -> noHtml constrBit = subConstructors qual [ ppSideBySideConstr subdocs subfixs unicode qual c | c <- cons , let subfixs = filter (\(n,_) -> any (\cn -> cn == n) (map unLoc (con_names (unLoc c)))) fixities ] instancesBit = ppInstances links instances docname unicode qual ppShortConstr :: Bool -> ConDecl DocName -> Unicode -> Qualification -> Html ppShortConstr summary con unicode qual = cHead <+> cBody <+> cFoot where (cHead,cBody,cFoot) = ppShortConstrParts summary False con unicode qual -- returns three pieces: header, body, footer so that header & footer can be -- incorporated into the declaration ppShortConstrParts :: Bool -> Bool -> ConDecl DocName -> Unicode -> Qualification -> (Html, Html, Html) ppShortConstrParts summary dataInst con unicode qual = case con_res con of ResTyH98 -> case con_details con of PrefixCon args -> (header_ unicode qual +++ hsep (ppOcc : map (ppLParendType unicode qual) args), noHtml, noHtml) RecCon (L _ fields) -> (header_ unicode qual +++ ppOcc <+> char '{', doRecordFields fields, char '}') InfixCon arg1 arg2 -> (header_ unicode qual +++ hsep [ppLParendType unicode qual arg1, ppOccInfix, ppLParendType unicode qual arg2], noHtml, noHtml) ResTyGADT _ resTy -> case con_details con of -- prefix & infix could use hsConDeclArgTys if it seemed to -- simplify the code. PrefixCon args -> (doGADTCon args resTy, noHtml, noHtml) -- display GADT records with the new syntax, -- Constr :: (Context) => { field :: a, field2 :: b } -> Ty (a, b) -- (except each field gets its own line in docs, to match -- non-GADT records) RecCon (L _ fields) -> (ppOcc <+> dcolon unicode <+> ppForAllCon forall_ ltvs lcontext unicode qual <+> char '{', doRecordFields fields, char '}' <+> arrow unicode <+> ppLType unicode qual resTy) InfixCon arg1 arg2 -> (doGADTCon [arg1, arg2] resTy, noHtml, noHtml) where doRecordFields fields = shortSubDecls dataInst (map (ppShortField summary unicode qual) (map unLoc fields)) doGADTCon args resTy = ppOcc <+> dcolon unicode <+> hsep [ ppForAllCon forall_ ltvs lcontext unicode qual, ppLType unicode qual (foldr mkFunTy resTy args) ] header_ = ppConstrHdr forall_ tyVars context occ = map (nameOccName . getName . unLoc) $ con_names con ppOcc = case occ of [one] -> ppBinder summary one _ -> hsep (punctuate comma (map (ppBinder summary) occ)) ppOccInfix = case occ of [one] -> ppBinderInfix summary one _ -> hsep (punctuate comma (map (ppBinderInfix summary) occ)) ltvs = con_qvars con tyVars = tyvarNames ltvs lcontext = con_cxt con context = unLoc (con_cxt con) forall_ = con_explicit con mkFunTy a b = noLoc (HsFunTy a b) -- ppConstrHdr is for (non-GADT) existentials constructors' syntax ppConstrHdr :: HsExplicitFlag -> [Name] -> HsContext DocName -> Unicode -> Qualification -> Html ppConstrHdr forall_ tvs ctxt unicode qual = (if null tvs then noHtml else ppForall) +++ (if null ctxt then noHtml else ppContextNoArrow ctxt unicode qual <+> darrow unicode +++ toHtml " ") where ppForall = case forall_ of Explicit -> forallSymbol unicode <+> hsep (map (ppName Prefix) tvs) <+> toHtml ". " Qualified -> noHtml Implicit -> noHtml ppSideBySideConstr :: [(DocName, DocForDecl DocName)] -> [(DocName, Fixity)] -> Unicode -> Qualification -> LConDecl DocName -> SubDecl ppSideBySideConstr subdocs fixities unicode qual (L _ con) = (decl, mbDoc, fieldPart) where decl = case con_res con of ResTyH98 -> case con_details con of PrefixCon args -> hsep ((header_ +++ ppOcc) : map (ppLParendType unicode qual) args) <+> fixity RecCon _ -> header_ +++ ppOcc <+> fixity InfixCon arg1 arg2 -> hsep [header_ +++ ppLParendType unicode qual arg1, ppOccInfix, ppLParendType unicode qual arg2] <+> fixity ResTyGADT _ resTy -> case con_details con of -- prefix & infix could also use hsConDeclArgTys if it seemed to -- simplify the code. PrefixCon args -> doGADTCon args resTy cd@(RecCon _) -> doGADTCon (hsConDeclArgTys cd) resTy InfixCon arg1 arg2 -> doGADTCon [arg1, arg2] resTy fieldPart = case con_details con of RecCon (L _ fields) -> [doRecordFields fields] _ -> [] doRecordFields fields = subFields qual (map (ppSideBySideField subdocs unicode qual) (map unLoc fields)) doGADTCon :: [LHsType DocName] -> Located (HsType DocName) -> Html doGADTCon args resTy = ppOcc <+> dcolon unicode <+> hsep [ppForAllCon forall_ ltvs (con_cxt con) unicode qual, ppLType unicode qual (foldr mkFunTy resTy args) ] <+> fixity fixity = ppFixities fixities qual header_ = ppConstrHdr forall_ tyVars context unicode qual occ = map (nameOccName . getName . unLoc) $ con_names con ppOcc = case occ of [one] -> ppBinder False one _ -> hsep (punctuate comma (map (ppBinder False) occ)) ppOccInfix = case occ of [one] -> ppBinderInfix False one _ -> hsep (punctuate comma (map (ppBinderInfix False) occ)) ltvs = con_qvars con tyVars = tyvarNames (con_qvars con) context = unLoc (con_cxt con) forall_ = con_explicit con -- don't use "con_doc con", in case it's reconstructed from a .hi file, -- or also because we want Haddock to do the doc-parsing, not GHC. mbDoc = lookup (unLoc $ head $ con_names con) subdocs >>= combineDocumentation . fst mkFunTy a b = noLoc (HsFunTy a b) ppSideBySideField :: [(DocName, DocForDecl DocName)] -> Unicode -> Qualification -> ConDeclField DocName -> SubDecl ppSideBySideField subdocs unicode qual (ConDeclField names ltype _) = (hsep (punctuate comma (map ((ppBinder False) . nameOccName . getName . unL) names)) <+> dcolon unicode <+> ppLType unicode qual ltype, mbDoc, []) where -- don't use cd_fld_doc for same reason we don't use con_doc above -- Where there is more than one name, they all have the same documentation mbDoc = lookup (unL $ head names) subdocs >>= combineDocumentation . fst ppShortField :: Bool -> Unicode -> Qualification -> ConDeclField DocName -> Html ppShortField summary unicode qual (ConDeclField names ltype _) = hsep (punctuate comma (map ((ppBinder summary) . nameOccName . getName . unL) names)) <+> dcolon unicode <+> ppLType unicode qual ltype -- | Print the LHS of a data\/newtype declaration. -- Currently doesn't handle 'data instance' decls or kind signatures ppDataHeader :: Bool -> TyClDecl DocName -> Unicode -> Qualification -> Html ppDataHeader summary decl@(DataDecl { tcdDataDefn = HsDataDefn { dd_ND = nd , dd_ctxt = ctxt , dd_kindSig = ks } }) unicode qual = -- newtype or data (case nd of { NewType -> keyword "newtype"; DataType -> keyword "data" }) <+> -- context ppLContext ctxt unicode qual <+> -- T a b c ..., or a :+: b ppDataBinderWithVars summary decl <+> case ks of Nothing -> mempty Just (L _ x) -> dcolon unicode <+> ppKind unicode qual x ppDataHeader _ _ _ _ = error "ppDataHeader: illegal argument" -------------------------------------------------------------------------------- -- * Types and contexts -------------------------------------------------------------------------------- ppBang :: HsBang -> Html ppBang HsNoBang = noHtml ppBang _ = toHtml "!" -- Unpacked args is an implementation detail, -- so we just show the strictness annotation tupleParens :: HsTupleSort -> [Html] -> Html tupleParens HsUnboxedTuple = ubxParenList tupleParens _ = parenList -------------------------------------------------------------------------------- -- * Rendering of HsType -------------------------------------------------------------------------------- pREC_TOP, pREC_CTX, pREC_FUN, pREC_OP, pREC_CON :: Int pREC_TOP = 0 :: Int -- type in ParseIface.y in GHC pREC_CTX = 1 :: Int -- Used for single contexts, eg. ctx => type -- (as opposed to (ctx1, ctx2) => type) pREC_FUN = 2 :: Int -- btype in ParseIface.y in GHC -- Used for LH arg of (->) pREC_OP = 3 :: Int -- Used for arg of any infix operator -- (we don't keep their fixities around) pREC_CON = 4 :: Int -- Used for arg of type applicn: -- always parenthesise unless atomic maybeParen :: Int -- Precedence of context -> Int -- Precedence of top-level operator -> Html -> Html -- Wrap in parens if (ctxt >= op) maybeParen ctxt_prec op_prec p | ctxt_prec >= op_prec = parens p | otherwise = p ppLType, ppLParendType, ppLFunLhType :: Unicode -> Qualification -> Located (HsType DocName) -> Html ppLType unicode qual y = ppType unicode qual (unLoc y) ppLParendType unicode qual y = ppParendType unicode qual (unLoc y) ppLFunLhType unicode qual y = ppFunLhType unicode qual (unLoc y) ppType, ppCtxType, ppParendType, ppFunLhType :: Unicode -> Qualification -> HsType DocName -> Html ppType unicode qual ty = ppr_mono_ty pREC_TOP ty unicode qual ppCtxType unicode qual ty = ppr_mono_ty pREC_CTX ty unicode qual ppParendType unicode qual ty = ppr_mono_ty pREC_CON ty unicode qual ppFunLhType unicode qual ty = ppr_mono_ty pREC_FUN ty unicode qual ppLKind :: Unicode -> Qualification -> LHsKind DocName -> Html ppLKind unicode qual y = ppKind unicode qual (unLoc y) ppKind :: Unicode -> Qualification -> HsKind DocName -> Html ppKind unicode qual ki = ppr_mono_ty pREC_TOP ki unicode qual -- Drop top-level for-all type variables in user style -- since they are implicit in Haskell ppForAllCon :: HsExplicitFlag -> LHsTyVarBndrs DocName -> Located (HsContext DocName) -> Unicode -> Qualification -> Html ppForAllCon expl tvs cxt unicode qual = forall_part <+> ppLContext cxt unicode qual where forall_part = ppLTyVarBndrs expl tvs unicode qual ppLTyVarBndrs :: HsExplicitFlag -> LHsTyVarBndrs DocName -> Unicode -> Qualification -> Html ppLTyVarBndrs expl tvs unicode _qual | show_forall = hsep (forallSymbol unicode : ppTyVars tvs) +++ dot | otherwise = noHtml where show_forall = not (null (hsQTvBndrs tvs)) && is_explicit is_explicit = case expl of {Explicit -> True; Implicit -> False; Qualified -> False} ppr_mono_lty :: Int -> LHsType DocName -> Unicode -> Qualification -> Html ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty) ppr_mono_ty :: Int -> HsType DocName -> Unicode -> Qualification -> Html ppr_mono_ty ctxt_prec (HsForAllTy expl extra tvs ctxt ty) unicode qual = maybeParen ctxt_prec pREC_FUN $ ppForAllCon expl tvs ctxt' unicode qual <+> ppr_mono_lty pREC_TOP ty unicode qual where ctxt' = case extra of Just loc -> (++ [L loc HsWildcardTy]) `fmap` ctxt Nothing -> ctxt -- UnicodeSyntax alternatives ppr_mono_ty _ (HsTyVar name) True _ | getOccString (getName name) == "*" = toHtml "★" | getOccString (getName name) == "(->)" = toHtml "(→)" ppr_mono_ty _ (HsBangTy b ty) u q = ppBang b +++ ppLParendType u q ty ppr_mono_ty _ (HsTyVar name) _ q = ppDocName q Prefix True name ppr_mono_ty ctxt_prec (HsFunTy ty1 ty2) u q = ppr_fun_ty ctxt_prec ty1 ty2 u q ppr_mono_ty _ (HsTupleTy con tys) u q = tupleParens con (map (ppLType u q) tys) ppr_mono_ty _ (HsKindSig ty kind) u q = parens (ppr_mono_lty pREC_TOP ty u q <+> dcolon u <+> ppLKind u q kind) ppr_mono_ty _ (HsListTy ty) u q = brackets (ppr_mono_lty pREC_TOP ty u q) ppr_mono_ty _ (HsPArrTy ty) u q = pabrackets (ppr_mono_lty pREC_TOP ty u q) ppr_mono_ty ctxt_prec (HsIParamTy n ty) u q = maybeParen ctxt_prec pREC_CTX $ ppIPName n <+> dcolon u <+> ppr_mono_lty pREC_TOP ty u q ppr_mono_ty _ (HsSpliceTy {}) _ _ = error "ppr_mono_ty HsSpliceTy" ppr_mono_ty _ (HsQuasiQuoteTy {}) _ _ = error "ppr_mono_ty HsQuasiQuoteTy" ppr_mono_ty _ (HsRecTy {}) _ _ = error "ppr_mono_ty HsRecTy" ppr_mono_ty _ (HsCoreTy {}) _ _ = error "ppr_mono_ty HsCoreTy" ppr_mono_ty _ (HsExplicitListTy _ tys) u q = quote $ brackets $ hsep $ punctuate comma $ map (ppLType u q) tys ppr_mono_ty _ (HsExplicitTupleTy _ tys) u q = quote $ parenList $ map (ppLType u q) tys ppr_mono_ty _ (HsWrapTy {}) _ _ = error "ppr_mono_ty HsWrapTy" ppr_mono_ty ctxt_prec (HsEqTy ty1 ty2) unicode qual = maybeParen ctxt_prec pREC_CTX $ ppr_mono_lty pREC_OP ty1 unicode qual <+> char '~' <+> ppr_mono_lty pREC_OP ty2 unicode qual ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty) unicode qual = maybeParen ctxt_prec pREC_CON $ hsep [ppr_mono_lty pREC_FUN fun_ty unicode qual, ppr_mono_lty pREC_CON arg_ty unicode qual] ppr_mono_ty ctxt_prec (HsOpTy ty1 (_, op) ty2) unicode qual = maybeParen ctxt_prec pREC_FUN $ ppr_mono_lty pREC_OP ty1 unicode qual <+> ppr_op <+> ppr_mono_lty pREC_OP ty2 unicode qual where ppr_op = ppLDocName qual Infix op ppr_mono_ty ctxt_prec (HsParTy ty) unicode qual -- = parens (ppr_mono_lty pREC_TOP ty) = ppr_mono_lty ctxt_prec ty unicode qual ppr_mono_ty ctxt_prec (HsDocTy ty _) unicode qual = ppr_mono_lty ctxt_prec ty unicode qual ppr_mono_ty _ HsWildcardTy _ _ = char '_' ppr_mono_ty _ (HsNamedWildcardTy name) _ q = ppDocName q Prefix True name ppr_mono_ty _ (HsTyLit n) _ _ = ppr_tylit n ppr_tylit :: HsTyLit -> Html ppr_tylit (HsNumTy _ n) = toHtml (show n) ppr_tylit (HsStrTy _ s) = toHtml (show s) ppr_fun_ty :: Int -> LHsType DocName -> LHsType DocName -> Unicode -> Qualification -> Html ppr_fun_ty ctxt_prec ty1 ty2 unicode qual = let p1 = ppr_mono_lty pREC_FUN ty1 unicode qual p2 = ppr_mono_lty pREC_TOP ty2 unicode qual in maybeParen ctxt_prec pREC_FUN $ hsep [p1, arrow unicode <+> p2]
JPMoresmau/haddock
haddock-api/src/Haddock/Backends/Xhtml/Decl.hs
Haskell
bsd-2-clause
39,178
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QTcpServer_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:31 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Network.QTcpServer_h ( QhasPendingConnections_h(..) ,QnextPendingConnection_h(..) ) where import Foreign.C.Types import Qtc.Enums.Base import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Network_h import Qtc.ClassTypes.Network import Foreign.Marshal.Array instance QunSetUserMethod (QTcpServer ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QTcpServer_unSetUserMethod" qtc_QTcpServer_unSetUserMethod :: Ptr (TQTcpServer a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QTcpServerSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QTcpServer ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QTcpServerSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QTcpServer ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QTcpServerSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QTcpServer_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QTcpServer ()) (QTcpServer x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QTcpServer setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QTcpServer_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QTcpServer_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTcpServer_setUserMethod" qtc_QTcpServer_setUserMethod :: Ptr (TQTcpServer a) -> CInt -> Ptr (Ptr (TQTcpServer x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QTcpServer :: (Ptr (TQTcpServer x0) -> IO ()) -> IO (FunPtr (Ptr (TQTcpServer x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QTcpServer_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QTcpServerSc a) (QTcpServer x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QTcpServer setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QTcpServer_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QTcpServer_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QTcpServer ()) (QTcpServer x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QTcpServer setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QTcpServer_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QTcpServer_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTcpServer_setUserMethodVariant" qtc_QTcpServer_setUserMethodVariant :: Ptr (TQTcpServer a) -> CInt -> Ptr (Ptr (TQTcpServer x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QTcpServer :: (Ptr (TQTcpServer x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQTcpServer x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QTcpServer_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QTcpServerSc a) (QTcpServer x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QTcpServer setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QTcpServer_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QTcpServer_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QTcpServer ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QTcpServer_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QTcpServer_unSetHandler" qtc_QTcpServer_unSetHandler :: Ptr (TQTcpServer a) -> CWString -> IO (CBool) instance QunSetHandler (QTcpServerSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QTcpServer_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QTcpServer ()) (QTcpServer x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTcpServer1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTcpServer1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTcpServer_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qTcpServerFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTcpServer_setHandler1" qtc_QTcpServer_setHandler1 :: Ptr (TQTcpServer a) -> CWString -> Ptr (Ptr (TQTcpServer x0) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QTcpServer1 :: (Ptr (TQTcpServer x0) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTcpServer x0) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QTcpServer1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QTcpServerSc a) (QTcpServer x0 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTcpServer1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTcpServer1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTcpServer_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO (CBool) setHandlerWrapper x0 = do x0obj <- qTcpServerFromPtr x0 let rv = if (objectIsNull x0obj) then return False else _handler x0obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () class QhasPendingConnections_h x0 x1 where hasPendingConnections_h :: x0 -> x1 -> IO (Bool) instance QhasPendingConnections_h (QTcpServer ()) (()) where hasPendingConnections_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTcpServer_hasPendingConnections cobj_x0 foreign import ccall "qtc_QTcpServer_hasPendingConnections" qtc_QTcpServer_hasPendingConnections :: Ptr (TQTcpServer a) -> IO CBool instance QhasPendingConnections_h (QTcpServerSc a) (()) where hasPendingConnections_h x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTcpServer_hasPendingConnections cobj_x0 instance QsetHandler (QTcpServer ()) (QTcpServer x0 -> IO (QObject t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTcpServer2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTcpServer2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTcpServer_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO (Ptr (TQObject t0)) setHandlerWrapper x0 = do x0obj <- qTcpServerFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTcpServer_setHandler2" qtc_QTcpServer_setHandler2 :: Ptr (TQTcpServer a) -> CWString -> Ptr (Ptr (TQTcpServer x0) -> IO (Ptr (TQObject t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QTcpServer2 :: (Ptr (TQTcpServer x0) -> IO (Ptr (TQObject t0))) -> IO (FunPtr (Ptr (TQTcpServer x0) -> IO (Ptr (TQObject t0)))) foreign import ccall "wrapper" wrapSetHandler_QTcpServer2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QTcpServerSc a) (QTcpServer x0 -> IO (QObject t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTcpServer2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTcpServer2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTcpServer_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTcpServer x0) -> IO (Ptr (TQObject t0)) setHandlerWrapper x0 = do x0obj <- qTcpServerFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () class QnextPendingConnection_h x0 x1 where nextPendingConnection_h :: x0 -> x1 -> IO (QTcpSocket ()) instance QnextPendingConnection_h (QTcpServer ()) (()) where nextPendingConnection_h x0 () = withQTcpSocketResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTcpServer_nextPendingConnection cobj_x0 foreign import ccall "qtc_QTcpServer_nextPendingConnection" qtc_QTcpServer_nextPendingConnection :: Ptr (TQTcpServer a) -> IO (Ptr (TQTcpSocket ())) instance QnextPendingConnection_h (QTcpServerSc a) (()) where nextPendingConnection_h x0 () = withQTcpSocketResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTcpServer_nextPendingConnection cobj_x0 instance QsetHandler (QTcpServer ()) (QTcpServer x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTcpServer3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTcpServer3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTcpServer_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qTcpServerFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTcpServer_setHandler3" qtc_QTcpServer_setHandler3 :: Ptr (TQTcpServer a) -> CWString -> Ptr (Ptr (TQTcpServer x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QTcpServer3 :: (Ptr (TQTcpServer x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTcpServer x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QTcpServer3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QTcpServerSc a) (QTcpServer x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTcpServer3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTcpServer3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTcpServer_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qTcpServerFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QTcpServer ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTcpServer_event cobj_x0 cobj_x1 foreign import ccall "qtc_QTcpServer_event" qtc_QTcpServer_event :: Ptr (TQTcpServer a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QTcpServerSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTcpServer_event cobj_x0 cobj_x1 instance QsetHandler (QTcpServer ()) (QTcpServer x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTcpServer4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTcpServer4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTcpServer_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qTcpServerFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QTcpServer_setHandler4" qtc_QTcpServer_setHandler4 :: Ptr (TQTcpServer a) -> CWString -> Ptr (Ptr (TQTcpServer x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QTcpServer4 :: (Ptr (TQTcpServer x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTcpServer x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QTcpServer4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QTcpServerSc a) (QTcpServer x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QTcpServer4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QTcpServer4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QTcpServer_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQTcpServer x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qTcpServerFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QTcpServer ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTcpServer_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QTcpServer_eventFilter" qtc_QTcpServer_eventFilter :: Ptr (TQTcpServer a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QTcpServerSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTcpServer_eventFilter cobj_x0 cobj_x1 cobj_x2
keera-studios/hsQt
Qtc/Network/QTcpServer_h.hs
Haskell
bsd-2-clause
24,198
-- | Parser for ECMAScript 3. {-# LANGUAGE FlexibleContexts #-} module Language.ECMAScript3.Parser (parse , Parser , expression , statement , program , parseFromString , parseFromFile -- old and deprecated , parseScriptFromString , parseJavaScriptFromFile , parseScript , parseExpression , parseString , ParsedStatement , ParsedExpression , parseSimpleExpr' , parseBlockStmt , parseStatement , StatementParser , ExpressionParser , assignExpr , parseObjectLit ) where import Language.ECMAScript3.Lexer hiding (identifier) import qualified Language.ECMAScript3.Lexer as Lexer import Language.ECMAScript3.Parser.State import Language.ECMAScript3.Parser.Type import Language.ECMAScript3.Syntax hiding (pushLabel) import Language.ECMAScript3.Syntax.Annotations import Data.Default.Class import Text.Parsec hiding (parse) import Text.Parsec.Expr import Control.Monad(liftM,liftM2) import Control.Monad.Trans (MonadIO,liftIO) import Numeric(readDec,readOct,readHex, readFloat) import Data.Char import Control.Monad.Identity import Data.Maybe (isJust, isNothing, fromMaybe) import Control.Monad.Error.Class import Control.Applicative ((<$>), (<*>)) {-# DEPRECATED ParsedStatement, ParsedExpression, StatementParser, ExpressionParser "These type aliases will be hidden in the next version" #-} {-# DEPRECATED parseSimpleExpr', parseBlockStmt, parseObjectLit "These parsers will be hidden in the next version" #-} {-# DEPRECATED assignExpr, parseExpression "Use 'expression' instead" #-} {-# DEPRECATED parseStatement "Use 'statement' instead" #-} {-# DEPRECATED parseScript "Use 'program' instead" #-} {-# DEPRECATED parseScriptFromString, parseString "Use 'parseFromString' instead" #-} {-# DEPRECATED parseJavaScriptFromFile "Use 'parseFromFile' instead" #-} -- We parameterize the parse tree over source-locations. type ParsedStatement = Statement SourcePos type ParsedExpression = Expression SourcePos -- These parsers can store some arbitrary state type StatementParser s = Parser s ParsedStatement type ExpressionParser s = Parser s ParsedExpression initialParserState :: ParserState initialParserState = [] -- | checks if the label is not yet on the stack, if it is -- throws -- an error; otherwise it pushes it onto the stack pushLabel :: String -> Parser s () pushLabel lab = do labs <- getState pos <- getPosition if lab `elem` labs then fail $ "Duplicate label at " ++ show pos else putState (lab:labs) popLabel :: Parser s () popLabel = modifyState safeTail where safeTail [] = [] safeTail (_:xs) = xs clearLabels :: ParserState -> ParserState clearLabels _ = [] withFreshLabelStack :: Parser s a -> Parser s a withFreshLabelStack p = do oldState <- getState putState $ clearLabels oldState a <- p putState oldState return a identifier :: Stream s Identity Char => Parser s (Id SourcePos) identifier = liftM2 Id getPosition Lexer.identifier --{{{ Statements -- Keep in mind that Token.reserved parsers (exported from the lexer) do not -- consume any input on failure. Note that all statements (expect for labelled -- and expression statements) begin with a reserved-word. If we fail to parse -- this reserved-word, no input is consumed. Hence, we can have the massive or -- block that is parseExpression. Note that if the reserved-word is parsed, it -- must be whatever statement the reserved-word indicates. If we fail after the -- reserved-word, we truly have a syntax error. Since input has been consumed, -- <|> will not try its alternate in parseExpression, and we will fail. parseIfStmt:: Stream s Identity Char => StatementParser s parseIfStmt = do pos <- getPosition reserved "if" test <- parseParenExpr <?> "parenthesized test-expression in if statement" consequent <- parseStatement <?> "true-branch of if statement" optional semi -- TODO: in spec? ((do reserved "else" alternate <- parseStatement return $ IfStmt pos test consequent alternate) <|> return (IfSingleStmt pos test consequent)) parseSwitchStmt :: Stream s Identity Char => StatementParser s parseSwitchStmt = let parseDefault = do pos <- getPosition reserved "default" colon statements <- many parseStatement return (CaseDefault pos statements) parseCase = do pos <- getPosition reserved "case" condition <- parseListExpr colon actions <- many parseStatement return (CaseClause pos condition actions) isCaseDefault (CaseDefault _ _) = True isCaseDefault _ = False checkClauses cs = case filter isCaseDefault cs of (_:c:_) -> fail $ "duplicate default clause in switch statement at " ++ show (getAnnotation c) _ -> return () in do pos <- getPosition reserved "switch" test <- parseParenExpr clauses <- braces $ many $ parseDefault <|> parseCase checkClauses clauses return (SwitchStmt pos test clauses) parseWhileStmt:: Stream s Identity Char => StatementParser s parseWhileStmt = do pos <- getPosition reserved "while" test <- parseParenExpr <?> "parenthesized test-expression in while loop" body <- parseStatement return (WhileStmt pos test body) parseDoWhileStmt:: Stream s Identity Char => StatementParser s parseDoWhileStmt = do pos <- getPosition reserved "do" body <- parseStatement reserved "while" <?> "while at the end of a do block" test <- parseParenExpr <?> "parenthesized test-expression in do loop" optional semi return (DoWhileStmt pos body test) parseContinueStmt:: Stream s Identity Char => StatementParser s parseContinueStmt = do pos <- getPosition reserved "continue" pos' <- getPosition -- Ensure that the identifier is on the same line as 'continue.' id <- if sourceLine pos == sourceLine pos' then liftM Just identifier <|> return Nothing else return Nothing optional semi return $ ContinueStmt pos id parseBreakStmt:: Stream s Identity Char => StatementParser s parseBreakStmt = do pos <- getPosition reserved "break" pos' <- getPosition -- Ensure that the identifier is on the same line as 'break.' id <- if sourceLine pos == sourceLine pos' then liftM Just identifier <|> return Nothing else return Nothing optional semi return $ BreakStmt pos id parseBlockStmt:: Stream s Identity Char => StatementParser s parseBlockStmt = do pos <- getPosition statements <- braces (many parseStatement) return (BlockStmt pos statements) parseEmptyStmt:: Stream s Identity Char => StatementParser s parseEmptyStmt = do pos <- getPosition semi return (EmptyStmt pos) parseLabelledStmt:: Stream s Identity Char => StatementParser s parseLabelledStmt = do pos <- getPosition -- Lookahead for the colon. If we don't see it, we are parsing an identifier -- for an expression statement. label <- try (do label <- identifier colon return label) pushLabel $ unId label statement <- parseStatement popLabel return (LabelledStmt pos label statement) parseExpressionStmt:: Stream s Identity Char => StatementParser s parseExpressionStmt = do pos <- getPosition expr <- parseExpression -- TODO: spec 12.4? optional semi return $ ExprStmt pos expr parseForInStmt:: Stream s Identity Char => StatementParser s parseForInStmt = let parseInit = (reserved "var" >> liftM ForInVar identifier) <|> liftM ForInLVal lvalue in do pos <- getPosition -- Lookahead, so that we don't clash with parseForStmt (init,expr) <- try $ do reserved "for" parens $ do init <- parseInit reserved "in" expr <- parseExpression return (init,expr) body <- parseStatement return $ ForInStmt pos init expr body parseForStmt:: Stream s Identity Char => StatementParser s parseForStmt = let parseInit = (reserved "var" >> liftM VarInit (parseVarDecl `sepBy` comma)) <|> liftM ExprInit parseListExpr <|> return NoInit in do pos <- getPosition reserved "for" reservedOp "(" init <- parseInit semi test <- optionMaybe parseExpression semi iter <- optionMaybe parseExpression reservedOp ")" <?> "closing paren" stmt <- parseStatement return $ ForStmt pos init test iter stmt parseTryStmt:: Stream s Identity Char => StatementParser s parseTryStmt = let parseCatchClause = do pos <- getPosition reserved "catch" id <- parens identifier stmt <- parseStatement return $ CatchClause pos id stmt in do reserved "try" pos <- getPosition guarded <- parseStatement mCatch <- optionMaybe parseCatchClause mFinally <- optionMaybe $ reserved "finally" >> parseStatement -- the spec requires at least a catch or a finally block to -- be present if isJust mCatch || isJust mFinally then return $ TryStmt pos guarded mCatch mFinally else fail $ "A try statement should have at least a catch\ \ or a finally block, at " ++ show pos parseThrowStmt:: Stream s Identity Char => StatementParser s parseThrowStmt = do pos <- getPosition reserved "throw" expr <- parseExpression optional semi return (ThrowStmt pos expr) parseReturnStmt:: Stream s Identity Char => StatementParser s parseReturnStmt = do pos <- getPosition reserved "return" expr <- optionMaybe parseListExpr optional semi return (ReturnStmt pos expr) parseWithStmt:: Stream s Identity Char => StatementParser s parseWithStmt = do pos <- getPosition reserved "with" context <- parseParenExpr stmt <- parseStatement return (WithStmt pos context stmt) parseVarDecl :: Stream s Identity Char => Parser s (VarDecl SourcePos) parseVarDecl = do pos <- getPosition id <- identifier init <- (reservedOp "=" >> liftM Just assignExpr) <|> return Nothing return (VarDecl pos id init) parseVarDeclStmt:: Stream s Identity Char => StatementParser s parseVarDeclStmt = do pos <- getPosition reserved "var" decls <- parseVarDecl `sepBy` comma optional semi return (VarDeclStmt pos decls) parseFunctionStmt:: Stream s Identity Char => StatementParser s parseFunctionStmt = do pos <- getPosition name <- try (reserved "function" >> identifier) -- ambiguity with FuncExpr args <- parens (identifier `sepBy` comma) -- label sets don't cross function boundaries BlockStmt _ body <- withFreshLabelStack parseBlockStmt <?> "function body in { ... }" return (FunctionStmt pos name args body) parseStatement :: Stream s Identity Char => StatementParser s parseStatement = parseIfStmt <|> parseSwitchStmt <|> parseWhileStmt <|> parseDoWhileStmt <|> parseContinueStmt <|> parseBreakStmt <|> parseBlockStmt <|> parseEmptyStmt <|> parseForInStmt <|> parseForStmt <|> parseTryStmt <|> parseThrowStmt <|> parseReturnStmt <|> parseWithStmt <|> parseVarDeclStmt <|> parseFunctionStmt -- labelled, expression and the error message always go last, in this order <|> parseLabelledStmt <|> parseExpressionStmt <?> "statement" -- | The parser that parses a single ECMAScript statement statement :: Stream s Identity Char => Parser s (Statement SourcePos) statement = parseStatement --}}} --{{{ Expressions -- References used to construct this stuff: -- + http://developer.mozilla.org/en/docs/ -- Core_JavaScript_1.5_Reference:Operators:Operator_Precedence -- + http://www.mozilla.org/js/language/grammar14.html -- -- Aren't expression tables nice? Well, we can't quite use them, because of -- JavaScript's ternary (?:) operator. We have to use two expression tables. -- We use one expression table for the assignment operators that bind looser -- than ?: (assignTable). The terms of assignTable are ternary expressions -- (parseTernaryExpr). parseTernaryExpr left-factors the left-recursive -- production for ?:, and is defined over the second expression table, -- exprTable, which consists of operators that bind tighter than ?:. The terms -- of exprTable are atomic expressions, parenthesized expressions, functions and -- array references. --{{{ Primary expressions parseThisRef:: Stream s Identity Char => ExpressionParser s parseThisRef = do pos <- getPosition reserved "this" return (ThisRef pos) parseNullLit:: Stream s Identity Char => ExpressionParser s parseNullLit = do pos <- getPosition reserved "null" return (NullLit pos) parseBoolLit:: Stream s Identity Char => ExpressionParser s parseBoolLit = do pos <- getPosition let parseTrueLit = reserved "true" >> return (BoolLit pos True) parseFalseLit = reserved "false" >> return (BoolLit pos False) parseTrueLit <|> parseFalseLit parseVarRef:: Stream s Identity Char => ExpressionParser s parseVarRef = liftM2 VarRef getPosition identifier parseArrayLit:: Stream s Identity Char => ExpressionParser s parseArrayLit = liftM2 ArrayLit getPosition (squares (assignExpr `sepEndBy` comma)) parseFuncExpr :: Stream s Identity Char => ExpressionParser s parseFuncExpr = do pos <- getPosition reserved "function" name <- optionMaybe identifier args <- parens (identifier `sepBy` comma) -- labels don't cross function boundaries BlockStmt _ body <- withFreshLabelStack parseBlockStmt return $ FuncExpr pos name args body --{{{ parsing strings escapeChars = [('\'','\''),('\"','\"'),('\\','\\'),('b','\b'),('f','\f'),('n','\n'), ('r','\r'),('t','\t'),('v','\v'),('/','/'),(' ',' '),('0','\0')] allEscapes:: String allEscapes = map fst escapeChars parseEscapeChar :: Stream s Identity Char => Parser s Char parseEscapeChar = do c <- oneOf allEscapes let (Just c') = lookup c escapeChars -- will succeed due to line above return c' parseAsciiHexChar :: Stream s Identity Char => Parser s Char parseAsciiHexChar = do char 'x' d1 <- hexDigit d2 <- hexDigit return ((chr.fst.head.readHex) (d1:d2:"")) parseUnicodeHexChar :: Stream s Identity Char => Parser s Char parseUnicodeHexChar = do char 'u' liftM (chr.fst.head.readHex) (sequence [hexDigit,hexDigit,hexDigit,hexDigit]) isWhitespace ch = ch `elem` " \t" -- The endWith argument is either single-quote or double-quote, depending on how -- we opened the string. parseStringLit' endWith = (char endWith >> return "") <|> (do try (string "\\'") cs <- parseStringLit' endWith return $ "'" ++ cs) <|> (do char '\\' c <- parseEscapeChar <|> parseAsciiHexChar <|> parseUnicodeHexChar <|> char '\r' <|> char '\n' cs <- parseStringLit' endWith if c == '\r' || c == '\n' then return (c:dropWhile isWhitespace cs) else return (c:cs)) <|> liftM2 (:) anyChar (parseStringLit' endWith) parseStringLit:: Stream s Identity Char => ExpressionParser s parseStringLit = do pos <- getPosition -- parseStringLit' takes as an argument the quote-character that opened the -- string. str <- lexeme $ (char '\'' >>= parseStringLit') <|> (char '\"' >>= parseStringLit') -- CRUCIAL: Parsec.Token parsers expect to find their token on the first -- character, and read whitespaces beyond their tokens. Without 'lexeme' -- above, expressions like: -- var s = "string" ; -- do not parse. return $ StringLit pos str --}}} parseRegexpLit:: Stream s Identity Char => ExpressionParser s parseRegexpLit = do let parseFlags = do flags <- many (oneOf "mgi") return $ \f -> f ('g' `elem` flags) ('i' `elem` flags) let parseEscape :: Stream s Identity Char => Parser s Char parseEscape = char '\\' >> anyChar let parseChar :: Stream s Identity Char => Parser s Char parseChar = noneOf "/" let parseRe = (char '/' >> return "") <|> (do char '\\' ch <- anyChar -- TODO: too lenient rest <- parseRe return ('\\':ch:rest)) <|> liftM2 (:) anyChar parseRe pos <- getPosition char '/' notFollowedBy $ char '/' pat <- parseRe --many1 parseChar flags <- parseFlags spaces -- crucial for Parsec.Token parsers return $ flags (RegexpLit pos pat) parseObjectLit:: Stream s Identity Char => ExpressionParser s parseObjectLit = let parseProp = do -- Parses a string, identifier or integer as the property name. I -- apologize for the abstruse style, but it really does make the code -- much shorter. name <- liftM (\(StringLit p s) -> PropString p s) parseStringLit <|> liftM2 PropId getPosition identifier <|> liftM2 PropNum getPosition (parseNumber >>= toInt) colon val <- assignExpr return (name,val) toInt eid = case eid of Left i -> return $ fromIntegral i -- Note, the spec actually allows floats in property names. -- This is left for legacy reasons and will be fixed in 1.0 Right d-> unexpected "Floating point number in property name" in do pos <- getPosition props <- braces (parseProp `sepEndBy` comma) <?> "object literal" return $ ObjectLit pos props --{{{ Parsing numbers. From pg. 17-18 of ECMA-262. hex :: Stream s Identity Char => Parser s (Either Int Double) hex = do s <- hexIntLit Left <$> wrapReadS Numeric.readHex s decimal :: Stream s Identity Char => Parser s (Either Int Double) decimal = do (s, i) <- decLit if i then Left <$> wrapReadS readDec s else Right <$> wrapReadS readFloat s wrapReadS :: ReadS a -> String -> Parser s a wrapReadS r s = case r s of [(a, "")] -> return a _ -> fail "Bad parse: could not convert a string to a Haskell value" parseNumber:: Stream s Identity Char => Parser s (Either Int Double) parseNumber = hex <|> decimal parseNumLit:: Stream s Identity Char => ExpressionParser s parseNumLit = do pos <- getPosition eid <- lexeme $ parseNumber notFollowedBy identifierStart <?> "whitespace" return $ case eid of Left i -> IntLit pos i Right d-> NumLit pos d ------------------------------------------------------------------------------ -- Position Helper ------------------------------------------------------------------------------ withPos cstr p = do { pos <- getPosition; e <- p; return $ cstr pos e } ------------------------------------------------------------------------------- -- Compound Expression Parsers ------------------------------------------------------------------------------- dotRef e = (reservedOp "." >> withPos cstr identifier) <?> "property.ref" where cstr pos = DotRef pos e funcApp e = parens (withPos cstr (assignExpr `sepBy` comma)) <?>"(function application)" where cstr pos = CallExpr pos e bracketRef e = brackets (withPos cstr parseExpression) <?> "[property-ref]" where cstr pos = BracketRef pos e ------------------------------------------------------------------------------- -- Expression Parsers ------------------------------------------------------------------------------- parseParenExpr:: Stream s Identity Char => ExpressionParser s parseParenExpr = parens parseListExpr -- everything above expect functions parseExprForNew :: Stream s Identity Char => ExpressionParser s parseExprForNew = parseThisRef <|> parseNullLit <|> parseBoolLit <|> parseStringLit <|> parseArrayLit <|> parseParenExpr <|> parseNewExpr <|> parseNumLit <|> parseRegexpLit <|> parseObjectLit <|> parseVarRef -- all the expression parsers defined above parseSimpleExpr' :: Stream s Identity Char => ExpressionParser s parseSimpleExpr' = parseThisRef <|> parseNullLit <|> parseBoolLit <|> parseStringLit <|> parseArrayLit <|> parseParenExpr <|> parseFuncExpr <|> parseNumLit <|> parseRegexpLit <|> parseObjectLit <|> parseVarRef parseNewExpr :: Stream s Identity Char => ExpressionParser s parseNewExpr = (do pos <- getPosition reserved "new" constructor <- parseSimpleExprForNew Nothing -- right-associativity arguments <- try (parens (assignExpr `sepBy` comma)) <|> return [] return (NewExpr pos constructor arguments)) <|> parseSimpleExpr' parseSimpleExpr (Just e) = ((dotRef e <|> funcApp e <|> bracketRef e) >>= parseSimpleExpr . Just) <|> return e parseSimpleExpr Nothing = do e <- parseNewExpr <?> "expression (3)" parseSimpleExpr (Just e) parseSimpleExprForNew :: Stream s Identity Char =>(Maybe ParsedExpression) -> ExpressionParser s parseSimpleExprForNew (Just e) = ((dotRef e <|> bracketRef e) >>= parseSimpleExprForNew . Just) <|> return e parseSimpleExprForNew Nothing = do e <- parseNewExpr <?> "expression (3)" parseSimpleExprForNew (Just e) --}}} makeInfixExpr str constr = Infix parser AssocLeft where parser:: Stream s Identity Char => Parser s (Expression SourcePos -> Expression SourcePos -> Expression SourcePos) parser = do pos <- getPosition reservedOp str return (InfixExpr pos constr) -- points-free, returns a function -- apparently, expression tables can't handle immediately-nested prefixes parsePrefixedExpr :: Stream s Identity Char => ExpressionParser s parsePrefixedExpr = do pos <- getPosition op <- optionMaybe $ (reservedOp "!" >> return PrefixLNot) <|> (reservedOp "~" >> return PrefixBNot) <|> (try (lexeme $ char '-' >> notFollowedBy (char '-')) >> return PrefixMinus) <|> (try (lexeme $ char '+' >> notFollowedBy (char '+')) >> return PrefixPlus) <|> (reserved "typeof" >> return PrefixTypeof) <|> (reserved "void" >> return PrefixVoid) <|> (reserved "delete" >> return PrefixDelete) case op of Nothing -> unaryAssignExpr Just op -> do innerExpr <- parsePrefixedExpr return (PrefixExpr pos op innerExpr) exprTable:: Stream s Identity Char => [[Operator s ParserState Identity ParsedExpression]] exprTable = [ [ makeInfixExpr "*" OpMul , makeInfixExpr "/" OpDiv , makeInfixExpr "%" OpMod ] , [ makeInfixExpr "+" OpAdd , makeInfixExpr "-" OpSub ] , [ makeInfixExpr "<<" OpLShift , makeInfixExpr ">>" OpSpRShift , makeInfixExpr ">>>" OpZfRShift ] , [ makeInfixExpr "<" OpLT , makeInfixExpr "<=" OpLEq , makeInfixExpr ">" OpGT , makeInfixExpr ">=" OpGEq , makeInfixExpr "instanceof" OpInstanceof , makeInfixExpr "in" OpIn ] , [ makeInfixExpr "==" OpEq , makeInfixExpr "!=" OpNEq , makeInfixExpr "===" OpStrictEq , makeInfixExpr "!==" OpStrictNEq ] , [ makeInfixExpr "&" OpBAnd ] , [ makeInfixExpr "^" OpBXor ] , [ makeInfixExpr "|" OpBOr ] , [ makeInfixExpr "&&" OpLAnd ] , [ makeInfixExpr "||" OpLOr ] ] parseExpression' :: Stream s Identity Char => ExpressionParser s parseExpression' = buildExpressionParser exprTable parsePrefixedExpr <?> "simple expression" asLValue :: Stream s Identity Char => SourcePos -> Expression SourcePos -> Parser s (LValue SourcePos) asLValue p' e = case e of VarRef p (Id _ x) -> return (LVar p x) DotRef p e (Id _ x) -> return (LDot p e x) BracketRef p e1 e2 -> return (LBracket p e1 e2) otherwise -> fail $ "expected a left-value at " ++ show p' lvalue :: Stream s Identity Char => Parser s (LValue SourcePos) lvalue = do p <- getPosition e <- parseSimpleExpr Nothing asLValue p e unaryAssignExpr :: Stream s Identity Char => ExpressionParser s unaryAssignExpr = do p <- getPosition let prefixInc = do reservedOp "++" liftM (UnaryAssignExpr p PrefixInc) lvalue let prefixDec = do reservedOp "--" liftM (UnaryAssignExpr p PrefixDec) lvalue let postfixInc e = do reservedOp "++" liftM (UnaryAssignExpr p PostfixInc) (asLValue p e) let postfixDec e = do reservedOp "--" liftM (UnaryAssignExpr p PostfixDec) (asLValue p e) let other = do e <- parseSimpleExpr Nothing postfixInc e <|> postfixDec e <|> return e prefixInc <|> prefixDec <|> other parseTernaryExpr':: Stream s Identity Char => Parser s (ParsedExpression,ParsedExpression) parseTernaryExpr' = do reservedOp "?" l <- assignExpr colon r <- assignExpr return (l,r) parseTernaryExpr:: Stream s Identity Char => ExpressionParser s parseTernaryExpr = do e <- parseExpression' e' <- optionMaybe parseTernaryExpr' case e' of Nothing -> return e Just (l,r) -> do p <- getPosition return $ CondExpr p e l r assignOp :: Stream s Identity Char => Parser s AssignOp assignOp = (reservedOp "=" >> return OpAssign) <|>(reservedOp "+=" >> return OpAssignAdd) <|>(reservedOp "-=" >> return OpAssignSub) <|>(reservedOp "*=" >> return OpAssignMul) <|>(reservedOp "/=" >> return OpAssignDiv) <|>(reservedOp "%=" >> return OpAssignMod) <|>(reservedOp "<<=" >> return OpAssignLShift) <|>(reservedOp ">>=" >> return OpAssignSpRShift) <|>(reservedOp ">>>=" >> return OpAssignZfRShift) <|>(reservedOp "&=" >> return OpAssignBAnd) <|>(reservedOp "^=" >> return OpAssignBXor) <|>(reservedOp "|=" >> return OpAssignBOr) assignExpr :: Stream s Identity Char => ExpressionParser s assignExpr = do p <- getPosition lhs <- parseTernaryExpr let assign = do op <- assignOp lhs <- asLValue p lhs rhs <- assignExpr return (AssignExpr p op lhs rhs) assign <|> return lhs parseExpression:: Stream s Identity Char => ExpressionParser s parseExpression = parseListExpr -- | A parser that parses ECMAScript expressions expression :: Stream s Identity Char => Parser s (Expression SourcePos) expression = parseExpression parseListExpr :: Stream s Identity Char => ExpressionParser s parseListExpr = assignExpr `sepBy1` comma >>= \exprs -> case exprs of [expr] -> return expr es -> liftM2 ListExpr getPosition (return es) parseScript:: Stream s Identity Char => Parser s (JavaScript SourcePos) parseScript = do whiteSpace liftM2 Script getPosition (parseStatement `sepBy` whiteSpace) -- | A parser that parses an ECMAScript program. program :: Stream s Identity Char => Parser s (JavaScript SourcePos) program = parseScript -- | Parse from a stream given a parser, same as 'Text.Parsec.parse' -- in Parsec. We can use this to parse expressions or statements alone, -- not just whole programs. parse :: Stream s Identity Char => Parser s a -- ^ The parser to use -> SourceName -- ^ Name of the source file -> s -- ^ the stream to parse, usually a 'String' -> Either ParseError a parse p = runParser p initialParserState -- | A convenience function that takes a 'String' and tries to parse -- it as an ECMAScript program: -- -- > parseFromString = parse program "" parseFromString :: String -- ^ JavaScript source to parse -> Either ParseError (JavaScript SourcePos) parseFromString = parse program "" -- | A convenience function that takes a filename and tries to parse -- the file contents an ECMAScript program, it fails with an error -- message if it can't. parseFromFile :: (Error e, MonadIO m, MonadError e m) => String -- ^ file name -> m (JavaScript SourcePos) parseFromFile fname = liftIO (readFile fname) >>= \source -> case parse program fname source of Left err -> throwError $ strMsg $ show err Right js -> return js -- | Read a JavaScript program from file an parse it into a list of -- statements parseJavaScriptFromFile :: MonadIO m => String -- ^ file name -> m [Statement SourcePos] parseJavaScriptFromFile filename = do chars <- liftIO $ readFile filename case parse parseScript filename chars of Left err -> fail (show err) Right (Script _ stmts) -> return stmts -- | Parse a JavaScript program from a string parseScriptFromString :: String -- ^ source file name -> String -- ^ JavaScript source to parse -> Either ParseError (JavaScript SourcePos) parseScriptFromString = parse parseScript -- | Parse a JavaScript source string into a list of statements parseString :: String -- ^ JavaScript source -> [Statement SourcePos] parseString str = case parse parseScript "" str of Left err -> error (show err) Right (Script _ stmts) -> stmts
sinelaw/language-ecmascript
src/Language/ECMAScript3/Parser.hs
Haskell
bsd-3-clause
29,230
{-| Module : Idris.Error Description : Utilities to deal with error reporting. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE DeriveDataTypeable #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Error where import Prelude hiding (catch) import Idris.AbsSyntax import Idris.Delaborate import Idris.Core.Evaluate (ctxtAlist) import Idris.Core.TT import Idris.Core.Typecheck import Idris.Core.Constraints import Idris.Output import System.Console.Haskeline import System.Console.Haskeline.MonadException import Control.Monad (when) import Control.Monad.State.Strict import System.IO.Error(isUserError, ioeGetErrorString) import Data.Char import Data.List (intercalate, isPrefixOf) import qualified Data.Text as T import qualified Data.Set as S import Data.Typeable import qualified Data.Traversable as Traversable import qualified Data.Foldable as Foldable iucheck :: Idris () iucheck = do tit <- typeInType ist <- getIState let cs = idris_constraints ist logLvl 7 $ "ALL CONSTRAINTS: " ++ show (length (S.toList cs)) when (not tit) $ (tclift $ ucheck (idris_constraints ist)) `idrisCatch` (\e -> do let fc = getErrSpan e setErrSpan fc iWarn fc $ pprintErr ist e) showErr :: Err -> Idris String showErr e = getIState >>= return . flip pshow e report :: IOError -> String report e | isUserError e = ioeGetErrorString e | otherwise = show e idrisCatch :: Idris a -> (Err -> Idris a) -> Idris a idrisCatch = catchError setAndReport :: Err -> Idris () setAndReport e = do ist <- getIState case (unwrap e) of At fc e -> do setErrSpan fc iWarn fc $ pprintErr ist e _ -> do setErrSpan (getErrSpan e) iWarn emptyFC $ pprintErr ist e where unwrap (ProofSearchFail e) = e -- remove bookkeeping constructor unwrap e = e ifail :: String -> Idris a ifail = throwError . Msg ierror :: Err -> Idris a ierror = throwError tclift :: TC a -> Idris a tclift (OK v) = return v tclift (Error err@(At fc e)) = do setErrSpan fc; throwError err tclift (Error err@(UniverseError fc _ _ _ _)) = do setErrSpan fc; throwError err tclift (Error err) = throwError err tctry :: TC a -> TC a -> Idris a tctry tc1 tc2 = case tc1 of OK v -> return v Error err -> tclift tc2 getErrSpan :: Err -> FC getErrSpan (At fc _) = fc getErrSpan (UniverseError fc _ _ _ _) = fc getErrSpan _ = emptyFC -------------------------------------------------------------------- -- Specific warnings not included in elaborator -------------------------------------------------------------------- -- | Issue a warning on "with"-terms whose namespace is empty or nonexistent warnDisamb :: IState -> PTerm -> Idris () warnDisamb ist (PQuote _) = return () warnDisamb ist (PRef _ _ _) = return () warnDisamb ist (PInferRef _ _ _) = return () warnDisamb ist (PPatvar _ _) = return () warnDisamb ist (PLam _ _ _ t b) = warnDisamb ist t >> warnDisamb ist b warnDisamb ist (PPi _ _ _ t b) = warnDisamb ist t >> warnDisamb ist b warnDisamb ist (PLet _ _ _ x t b) = warnDisamb ist x >> warnDisamb ist t >> warnDisamb ist b warnDisamb ist (PTyped x t) = warnDisamb ist x >> warnDisamb ist t warnDisamb ist (PApp _ t args) = warnDisamb ist t >> mapM_ (warnDisamb ist . getTm) args warnDisamb ist (PWithApp _ t a) = warnDisamb ist t >> warnDisamb ist a warnDisamb ist (PAppBind _ f args) = warnDisamb ist f >> mapM_ (warnDisamb ist . getTm) args warnDisamb ist (PMatchApp _ _) = return () warnDisamb ist (PCase _ tm cases) = warnDisamb ist tm >> mapM_ (\(x,y)-> warnDisamb ist x >> warnDisamb ist y) cases warnDisamb ist (PIfThenElse _ c t f) = mapM_ (warnDisamb ist) [c, t, f] warnDisamb ist (PTrue _ _) = return () warnDisamb ist (PResolveTC _) = return () warnDisamb ist (PRewrite _ _ x y z) = warnDisamb ist x >> warnDisamb ist y >> Foldable.mapM_ (warnDisamb ist) z warnDisamb ist (PPair _ _ _ x y) = warnDisamb ist x >> warnDisamb ist y warnDisamb ist (PDPair _ _ _ x y z) = warnDisamb ist x >> warnDisamb ist y >> warnDisamb ist z warnDisamb ist (PAlternative _ _ tms) = mapM_ (warnDisamb ist) tms warnDisamb ist (PHidden tm) = warnDisamb ist tm warnDisamb ist (PType _) = return () warnDisamb ist (PUniverse _ _) = return () warnDisamb ist (PGoal _ x _ y) = warnDisamb ist x >> warnDisamb ist y warnDisamb ist (PConstant _ _) = return () warnDisamb ist Placeholder = return () warnDisamb ist (PDoBlock steps) = mapM_ wStep steps where wStep (DoExp _ x) = warnDisamb ist x wStep (DoBind _ _ _ x) = warnDisamb ist x wStep (DoBindP _ x y cs) = warnDisamb ist x >> warnDisamb ist y >> mapM_ (\(x,y) -> warnDisamb ist x >> warnDisamb ist y) cs wStep (DoLet _ _ _ x y) = warnDisamb ist x >> warnDisamb ist y wStep (DoLetP _ x y) = warnDisamb ist x >> warnDisamb ist y warnDisamb ist (PIdiom _ x) = warnDisamb ist x warnDisamb ist (PMetavar _ _) = return () warnDisamb ist (PProof tacs) = mapM_ (Foldable.mapM_ (warnDisamb ist)) tacs warnDisamb ist (PTactics tacs) = mapM_ (Foldable.mapM_ (warnDisamb ist)) tacs warnDisamb ist (PElabError _) = return () warnDisamb ist PImpossible = return () warnDisamb ist (PCoerced tm) = warnDisamb ist tm warnDisamb ist (PDisamb ds tm) = warnDisamb ist tm >> mapM_ warnEmpty ds where warnEmpty d = when (not (any (isIn d . fst) (ctxtAlist (tt_ctxt ist)))) $ ierror . Msg $ "Nothing found in namespace \"" ++ intercalate "." (map T.unpack . reverse $ d) ++ "\"." isIn d (NS _ ns) = isPrefixOf d ns isIn d _ = False warnDisamb ist (PUnifyLog tm) = warnDisamb ist tm warnDisamb ist (PNoImplicits tm) = warnDisamb ist tm warnDisamb ist (PQuasiquote tm goal) = warnDisamb ist tm >> Foldable.mapM_ (warnDisamb ist) goal warnDisamb ist (PUnquote tm) = warnDisamb ist tm warnDisamb ist (PQuoteName _ _ _) = return () warnDisamb ist (PAs _ _ tm) = warnDisamb ist tm warnDisamb ist (PAppImpl tm _) = warnDisamb ist tm warnDisamb ist (PRunElab _ tm _) = warnDisamb ist tm warnDisamb ist (PConstSugar _ tm) = warnDisamb ist tm
enolan/Idris-dev
src/Idris/Error.hs
Haskell
bsd-3-clause
6,583
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell, DeriveDataTypeable, PatternGuards, DeriveFunctor, DeriveFoldable, DeriveTraversable #-} -- Those extensions are required by the Uniplate instances. --{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} module Language.LaTeX.Types where import Prelude hiding (and, foldr, foldl, foldr1, foldl1, elem, concatMap, concat) import Data.Monoid (Monoid(..)) import Data.List (intercalate) import Data.Ratio ((%)) import Data.Foldable import Data.String (IsString(..)) -- import Data.Generics.PlateTypeable import Data.Data import Control.Applicative import Control.Arrow (second) import Control.Monad.Writer (Writer) import Control.Monad.Trans () import Control.Monad.Error data Document = Document { documentClass :: DocumentClss , documentPreamble :: PreambleItm , documentBody :: ParItm } deriving (Show, Eq, Typeable, Data) type LineNumber = Int type CharNumber = Int data Loc = Loc { locFile :: FilePath , locLine :: LineNumber , locChar :: CharNumber } deriving (Show, Eq, Typeable, Data) data Note = TextNote String | IntNote Int | LocNote Loc deriving (Show, Eq, Typeable, Data) data DocumentClassKind = Article | Book | Report | Letter | OtherDocumentClassKind String deriving (Show, Eq, Typeable, Data) data DocumentClss = DocClass { docClassKind :: DocumentClassKind , docClassOptions :: [AnyItm] } deriving (Show, Eq, Typeable, Data) data AnyItm = PreambleItm PreambleItm | LatexItm LatexItm | MathItm MathItm | ParItm ParItm | LocSpecs [LocSpec] | Key Key | PackageName PackageName | Coord Coord | Length LatexLength | SaveBin SaveBin deriving (Show, Eq, Typeable, Data) data PreambleItm = PreambleCmdArgs String [Arg AnyItm] | PreambleEnv String [Arg AnyItm] AnyItm | PreambleCast AnyItm | PreambleConcat [PreambleItm] | RawPreamble String | PreambleNote Key Note PreambleItm deriving (Show, Eq, Typeable, Data) instance Semigroup PreambleItm where PreambleConcat xs <> PreambleConcat ys = PreambleConcat (xs ++ ys) PreambleConcat xs <> y = PreambleConcat (xs ++ [y]) x <> PreambleConcat ys = PreambleConcat (x : ys) x <> y = PreambleConcat [x, y] instance Monoid PreambleItm where mempty = PreambleConcat [] data TexDcl = TexDcl { texDeclName :: String , texDeclArgs :: [Arg AnyItm] } deriving (Show, Eq, Typeable, Data) -- This is the subset of tex strings that fits in the LR mode. -- The distinction between the paragraph and the LR mode is always -- made explicit using the Para constructor. -- -- Modes: http://www.personal.ceu.hu/tex/modes.htm data LatexItm = LatexCmdArgs String [Arg LatexItm] | LatexCmdAnyArgs String [Arg AnyItm] | TexDecls [TexDcl] | TexCmdNoArg String | TexCmdArg String LatexItm | Environment String [Arg AnyItm] AnyItm | RawTex String | LatexCast AnyItm -- a cast from math induce $...$ | TexGroup LatexItm | LatexEmpty | LatexAppend LatexItm LatexItm | LatexNote Key Note LatexItm deriving (Show, Eq, Typeable, Data) appendAny :: AnyItm -> AnyItm -> Maybe AnyItm appendAny (PreambleItm x) (PreambleItm y) = Just $ PreambleItm (x `mappend` y) appendAny (LatexItm x) (LatexItm y) = Just $ LatexItm (x `mappend` y) appendAny (MathItm x) (MathItm y) = Just $ MathItm (x `mappend` y) appendAny (ParItm x) (ParItm y) = Just $ ParItm (x `mappend` y) appendAny (LocSpecs x) (LocSpecs y) = Just $ LocSpecs (x `mappend` y) -- this lengthy matching is to get a warning when we extend the AnyItm type appendAny PreambleItm{} _ = Nothing appendAny LatexItm{} _ = Nothing appendAny MathItm{} _ = Nothing appendAny ParItm{} _ = Nothing appendAny LocSpecs{} _ = Nothing appendAny Key{} _ = Nothing appendAny PackageName{} _ = Nothing appendAny Coord{} _ = Nothing appendAny Length{} _ = Nothing appendAny SaveBin{} _ = Nothing instance Semigroup LatexItm where RawTex xs <> RawTex ys = RawTex (xs ++ ys) LatexCast x <> LatexCast y | Just z <- appendAny x y = LatexCast z LatexEmpty <> x = x x <> LatexEmpty = x LatexAppend x y <> z = x <> (y <> z) -- TODO complexity issue? x <> LatexAppend y z = case x <> y of LatexAppend x' y' -> x' `LatexAppend` (y' <> z) -- TODO complexity issue? xy -> xy <> z x <> y = x `LatexAppend` y instance Monoid LatexItm where mempty = LatexEmpty -- LatexConcat [] {- LatexConcat xs `mappend` LatexConcat ys = LatexConcat (xs ++ ys) LatexConcat xs `mappend` y = LatexConcat (xs ++ [y]) x `mappend` LatexConcat ys = LatexConcat (x : ys) x `mappend` y = LatexConcat [x, y] -} instance IsString LatexItm where fromString s | null s = mempty | otherwise = f s where f = RawTex . concatMap rawhchar . intercalate "\n" . filter (not . null) . lines data Named a = Named String a deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable) data PackageAction = PackageDependency PackageName | ProvidePackage PackageName deriving (Show, Eq, Typeable, Data) data Arg a = NoArg | StarArg -- `*' | Mandatory [a] -- surrounded by `{' `}', separated by `,' | Optional [a] -- surrounded by `[' `]', separated by `,' or empty if null | NamedArgs [Named a] -- surrounded by `{' `}', separated by `=` and `,' | NamedOpts [Named a] -- surrounded by `[' `]', separated by `=' and `,' or empty if null | Coordinates a a -- surrounded by `(' `)', separated by ` ' | RawArg String | LiftArg a | PackageAction PackageAction deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable) data Star = Star | NoStar deriving (Show, Eq, Typeable, Data) instance Semigroup Star where NoStar <> x = x x <> _ = x instance Monoid Star where mempty = NoStar data Coord = MkCoord LatexLength LatexLength deriving (Show, Eq, Typeable, Data) newtype Percentage = Percentage { percentage :: Int } deriving (Eq,Show,Ord,Num) data ParItm = ParCmdArgs String [Arg AnyItm] | ParEnv String [Arg AnyItm] AnyItm | Tabular [RowSpec LatexItm] [Row LatexItm] | RawParMode String | ParCast AnyItm -- a cast from Math induce \[...\] | ParGroup ParItm -- check validity of this | ParConcat [ParItm] | ParNote Key Note ParItm deriving (Show, Eq, Typeable, Data) instance Semigroup ParItm where ParConcat xs <> ParConcat ys = ParConcat (xs ++ ys) ParConcat xs <> y = ParConcat (xs ++ [y]) x <> ParConcat ys = ParConcat (x : ys) x <> y = ParConcat [x, y] instance Monoid ParItm where mempty = ParConcat [] unParNote :: ParItm -> Maybe (Key, Note, ParItm) unParNote (ParNote k n p) = Just (k, n, p) unParNote _ = Nothing uncatParItm :: ParItm -> [ParItm] uncatParItm (ParConcat pars) = pars uncatParItm par = [par] newtype MathDcl = MathDcl String deriving (Show, Eq, Typeable, Data) data MathItm = MathDecls [MathDcl] | MathCmdArgs String [Arg AnyItm] | MathArray [RowSpec MathItm] [Row MathItm] | RawMath String | MathCast AnyItm | MathRat Rational | MathGroup MathItm | MathConcat [MathItm] | MathBinOp String MathItm MathItm | MathUnOp String MathItm | MathNote Key Note MathItm deriving (Show, Eq, Typeable, Data) instance Semigroup MathItm where MathConcat xs <> MathConcat ys = MathConcat (xs ++ ys) MathConcat xs <> y = MathConcat (xs ++ [y]) x <> MathConcat ys = MathConcat (x : ys) x <> y = MathConcat [x, y] instance Monoid MathItm where mempty = MathConcat [] instance Num MathItm where (+) = MathBinOp "+" (*) = MathBinOp "*" (-) = MathBinOp "-" negate = MathUnOp "-" abs x = MathCmdArgs "abs" [Mandatory [MathItm x]] -- TODO check signum = error "MathItm.signum is undefined" fromInteger = MathRat . (%1) instance Fractional MathItm where (/) = MathBinOp "/" fromRational = MathRat {- instance Real MathItm where toRational = error "MathItm.toRational is undefined" instance Integral MathItm where mod = MathBinOp "bmod" -- TODO quot, rem -} data TexUnit = Sp -- ^ Scalled point (1pt = 65536sp) | Pt -- ^ Point unit size (1pt = 0.351mm) | Bp -- ^ Big point (1in = 72bp), also PostScript point | Dd -- ^ Didôt point (1dd = 0.376mm) | Em -- ^ One em is about the width of the letter M in the current font | Ex -- ^ One ex is about the hoigh of the letter x in the current font | Cm -- ^ Centimeter unit size | Mm -- ^ Milimeter unit size (1mm = 2.845pt) | In -- ^ Inch unit size (1in = 72.27pt) | Pc -- ^ Picas (1pc = 12pt) | Cc -- ^ Cicero (1dd = 12dd = 4.531mm) | Mu -- ^ Math unit (18mu = 1em) deriving (Eq, Ord, Enum, Show, Typeable, Data) data LatexLength = LengthScaledBy Rational LatexLength | LengthCmdRatArg String Rational | LengthCmd String | LengthCst (Maybe TexUnit) Rational deriving (Show, Eq, Typeable, Data) lengthCst :: LatexLength -> Maybe (Maybe TexUnit, Rational) lengthCst (LengthScaledBy rat len) = second (rat *) <$> lengthCst len lengthCst (LengthCmdRatArg _ _) = Nothing lengthCst (LengthCmd _) = Nothing lengthCst (LengthCst mtu rat) = Just (mtu, rat) safeLengthOp :: String -> (Rational -> Rational -> Rational) -> LatexLength -> LatexLength -> LatexLength safeLengthOp _ op (LengthCst Nothing rx) (LengthCst munit ry) = LengthCst munit (op rx ry) safeLengthOp _ op (LengthCst (Just unit) rx) (LengthCst Nothing ry) = LengthCst (Just unit) (op rx ry) safeLengthOp op _ x y = error $ "LatexLength." ++ op ++ ": undefined on non constants terms (" ++ show x ++ op ++ show y ++ ")" scaleBy :: Rational -> LatexLength -> LatexLength scaleBy rx (LengthScaledBy ry l) = LengthScaledBy (rx * ry) l scaleBy rx (LengthCst munit ry) = LengthCst munit (rx * ry) scaleBy rx (LengthCmd cmd) = LengthScaledBy rx (LengthCmd cmd) scaleBy rx (LengthCmdRatArg cmd r) = LengthScaledBy rx (LengthCmdRatArg cmd r) instance Num LatexLength where LengthCst Nothing x * y = scaleBy x y x * LengthCst Nothing y = scaleBy y x x * y = safeLengthOp "*" (*) x y (+) = safeLengthOp "+" (+) (-) = safeLengthOp "-" (-) negate x = LengthCst Nothing (-1) * x abs = error "LatexLength.abs is undefined" signum = error "LatexLength.signum is undefined" fromInteger = LengthCst Nothing . (%1) instance Semigroup LatexLength where (<>) = (+) instance Monoid LatexLength where mempty = 0 instance Fractional LatexLength where x / LengthCst Nothing ry = scaleBy (1/ry) x x / y = safeLengthOp "/" (/) x y fromRational = LengthCst Nothing -- p{wd}, and *{num}{cols} are explicitly -- not supported, it seems much more natural and -- simple to obtain the same goals using standard -- programming uppon the rows and cells. data RowSpec a = Rc --- ^ Centered | Rl --- ^ Left | Rr --- ^ Right | Rvline --- ^ A vertical line | Rtext a --- ^ A fixed text column (@-expression in LaTeX parlance) deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable) {- instance Functor RowSpec where _ `fmap` Rc = Rc _ `fmap` Rl = Rl _ `fmap` Rr = Rr _ `fmap` Rvline = Rvline f `fmap` (Rtext x) = Rtext $ f x instance Foldable RowSpec where foldr _ z Rc = z foldr _ z Rl = z foldr _ z Rr = z foldr _ z Rvline = z foldr f z (Rtext x) = f x z instance Traversable RowSpec where sequenceA Rc = pure Rc sequenceA Rl = pure Rl sequenceA Rr = pure Rr sequenceA Rvline = pure Rvline sequenceA (Rtext x) = Rtext <$> x -} data LocSpec = Lh --- ^ Here | Lt --- ^ Top | Lb --- ^ Bottom | Lp --- ^ Page of floats: on a sperate page containing no text, --- only figures and tables. deriving (Show, Eq, Typeable, Data) locSpecChar :: LocSpec -> Char locSpecChar Lh = 'h' locSpecChar Lt = 't' locSpecChar Lb = 'b' locSpecChar Lp = 'p' data Pos = Centered -- ^ Centered (default). | FlushLeft -- ^ Flush left | FlushRight -- ^ Flush right | Stretch -- ^ Stretch (justify) across entire width; text must contain -- stretchable space for this to work. charPos :: Pos -> Char charPos Centered = 'c' charPos FlushLeft = 'l' charPos FlushRight = 'r' charPos Stretch = 's' -- TODO: add more paper sizes data LatexPaperSize = A4paper | OtherPaperSize String deriving (Show, Eq, Typeable, Data) {- NOTE: their is no handling of the \multicolumn command at the moment -} data Row cell = Cells [cell] | Hline | Cline Int Int deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable) {- instance Functor Row where f `fmap` Cells cs = Cells (fmap f cs) _ `fmap` Hline = Hline _ `fmap` Cline i j = Cline i j instance Foldable Row where foldr f z (Cells cs) = foldr f z cs foldr _ z Hline = z foldr _ z (Cline _ _) = z instance Traversable Row where sequenceA (Cells cs) = Cells <$> sequenceA cs sequenceA Hline = pure Hline sequenceA (Cline i j) = pure $ Cline i j -} data ListItm = ListItm { itemOptions :: [Arg LatexItm], itemContents :: ParItm } newtype PackageName = PkgName { getPkgName :: String } deriving (Ord, Eq, Show, Typeable, Data) newtype Key = MkKey { getKey :: String } deriving (Eq, Show, Typeable, Data) newtype SaveBin = UnsafeMakeSaveBin { unsafeGetSaveBin :: Int } deriving (Eq, Show, Typeable, Data) data LatexState = LS { freshSaveBin :: SaveBin } instance (Error a, Eq a, Show a, Num b) => Num (Either a b) where fromInteger = pure . fromInteger (+) = liftM2 (+) (-) = liftM2 (-) (*) = liftM2 (*) negate = liftM negate abs = liftM abs signum = liftM signum instance (Error a, Eq a, Show a, Fractional b) => Fractional (Either a b) where (/) = liftM2 (/) fromRational = pure . fromRational type ErrorMessage = String newtype LatexM a = LatexM { runLatexM :: Either ErrorMessage a } deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadError ErrorMessage, Show, Eq, Num, Fractional, Typeable, Data) instance Semigroup a => Semigroup (LatexM a) where (<>) = liftM2 (<>) -- sconcat = liftM sconcat . sequenceA instance Monoid a => Monoid (LatexM a) where mempty = pure mempty instance IsString a => IsString (LatexM a) where fromString = pure . fromString type TexDecl = LatexM TexDcl type LatexItem = LatexM LatexItm type ParItem = LatexM ParItm type MathDecl = LatexM MathDcl newtype AnyItem = AnyItem { anyItmM :: LatexM AnyItm } deriving (Eq, Show, Typeable, Data) newtype MathItem = MathItem { mathItmM :: LatexM MathItm } deriving (Semigroup, Monoid, Eq, Show, Num, Fractional, Typeable, Data) type ListItem = LatexM ListItm type PreambleItem = LatexM PreambleItm type DocumentClass = LatexM DocumentClss type TexDeclW = Writer TexDecl () type LatexItemW = Writer LatexItem () type ParItemW = Writer ParItem () type MathDeclW = Writer MathDecl () type MathItemW = Writer MathItem () type PreambleItemW = Writer PreambleItem () -- TODO: Maybe one should handle quotes in a less LaTeX -- way: provide a replacement for ``...'' and escape `'" -- -- NOTE: Don't confuse this function with ttchar -- NOTE: this raw Tex is ugly rawhchar :: Char -> String rawhchar '\\' = "\\textbackslash{}" rawhchar '<' = "\\textless{}" rawhchar '>' = "\\textgreater{}" rawhchar '|' = "\\textbar{}" rawhchar x | x `elem` "~^_#&{}$%" = ['\\',x,'{','}'] | x `elem` ":][" = ['{', x, '}'] -- '[' and ']' are escaped to avoid mess up optional args | otherwise = [x] -- | Type for encodings used in commands like. -- @\usepackage[utf8]{inputenc}@, that we can -- express as 'useInputenc' 'utf8'. newtype Encoding = Encoding { fromEncoding :: String } deriving (Eq,Ord,Show) -- instance (Integral a, Typeable a, Typeable b, PlateAll a b) => PlateAll (Ratio a) b where -- plateAll r = plate (%) |+ numerator r |+ denominator r {- $(derive makeUniplateTypeable ''SaveBin) $(derive makeUniplateTypeable ''PackageName) $(derive makeUniplateTypeable ''Loc) $(derive makeUniplateTypeable ''Note) $(derive makeUniplateTypeable ''Arg) $(derive makeUniplateTypeable ''Key) $(derive makeUniplateTypeable ''Row) $(derive makeUniplateTypeable ''RowSpec) $(derive makeUniplateTypeable ''LocSpec) $(derive makeUniplateTypeable ''LatexLength) $(derive makeUniplateTypeable ''Coord) $(derive makeUniplateTypeable ''DocumentClassKind) $(derive makeUniplateTypeable ''TexDcl) $(derive makeUniplateTypeable ''MathItm) $(derive makeUniplateTypeable ''MathDcl) $(derive makeUniplateTypeable ''ParItm) $(derive makeUniplateTypeable ''TexUnit) $(derive makeUniplateTypeable ''LatexItm) $(derive makeUniplateTypeable ''DocumentClass) $(derive makeUniplateTypeable ''PreambleItm) $(derive makeUniplateTypeable ''Document) -}
np/hlatex
Language/LaTeX/Types.hs
Haskell
bsd-3-clause
18,172
{-# LANGUAGE TypeFamilies, CPP, FlexibleInstances, FlexibleContexts, NamedFieldPuns, RecordWildCards, UndecidableInstances #-} {-# LANGUAGE MultiParamTypeClasses, UnboxedTuples, StandaloneDeriving, TypeSynonymInstances #-} {-# OPTIONS -funbox-strict-fields #-} module Data.TrieMap.Key () where import Data.TrieMap.Class import Data.TrieMap.TrieKey import Data.TrieMap.Representation.Class import Data.TrieMap.Modifiers import Prelude hiding (foldr, foldl, foldr1, foldl1, lookup) type RepMap k = TrieMap (Rep k) keyMap :: (Repr k, TrieKey (Rep k), Sized a) => TrieMap (Rep k) a -> TrieMap (Key k) a keyMap m = KeyMap (sizeM m) m #define KMAP(m) KeyMap{tMap = m} #define CONTEXT(cl) (Repr k, TrieKey (Rep k), cl (RepMap k)) instance CONTEXT(Foldable) => Foldable (TrieMap (Key k)) where foldMap f KMAP(m) = foldMap f m foldr f z KMAP(m) = foldr f z m foldl f z KMAP(m) = foldl f z m instance CONTEXT(Functor) => Functor (TrieMap (Key k)) where fmap f KeyMap{..} = KeyMap{sz, tMap = f <$> tMap} instance CONTEXT(Traversable) => Traversable (TrieMap (Key k)) where traverse f KeyMap{..} = KeyMap sz <$> traverse f tMap instance CONTEXT(Subset) => Subset (TrieMap (Key k)) where KMAP(m1) <=? KMAP(m2) = m1 <=? m2 instance (Repr k, TrieKey (Rep k), Buildable (RepMap k) (Rep k)) => Buildable (TrieMap (Key k)) (Key k) where type UStack (TrieMap (Key k)) = UMStack (Rep k) uFold = fmap keyMap . mapFoldlKeys keyRep . uFold type AStack (TrieMap (Key k)) = AMStack (Rep k) aFold = fmap keyMap . mapFoldlKeys keyRep . aFold type DAStack (TrieMap (Key k)) = DAMStack (Rep k) daFold = keyMap <$> mapFoldlKeys keyRep daFold #define SETOP(op) op f KMAP(m1) KMAP(m2) = keyMap (op f m1 m2) instance CONTEXT(SetOp) => SetOp (TrieMap (Key k)) where SETOP(union) SETOP(isect) SETOP(diff) instance CONTEXT(Project) => Project (TrieMap (Key k)) where mapMaybe f KMAP(m) = keyMap $ mapMaybe f m mapEither f KMAP(m) = both keyMap (mapEither f) m instance CONTEXT(Zippable) => Zippable (TrieMap (Key k)) where empty = KeyMap 0 empty clear (KeyHole hole) = keyMap (clear hole) assign a (KeyHole hole) = keyMap (assign a hole) #define SPLITOP(op) op (KeyHole hole) = keyMap (op hole) instance CONTEXT(Splittable) => Splittable (TrieMap (Key k)) where SPLITOP(before) SPLITOP(beforeWith a) SPLITOP(after) SPLITOP(afterWith a) instance CONTEXT(Indexable) => Indexable (TrieMap (Key k)) where index i KMAP(m) = case index i m of (# i', a, hole #) -> (# i', a, KeyHole hole #) instance TKey k => Searchable (TrieMap (Key k)) (Key k) where search k KMAP(m) = mapHole KeyHole (search (keyRep k) m) singleZip k = KeyHole (singleZip (keyRep k)) lookup k KMAP(m) = lookup (keyRep k) m insertWith f k a KMAP(m) = keyMap (insertWith f (keyRep k) a m) alter f k KMAP(m) = keyMap (alter f (keyRep k) m) instance CONTEXT(Alternatable) => Alternatable (TrieMap (Key k)) where alternate KMAP(m) = do (a, hole) <- alternate m return (a, KeyHole hole) data instance TrieMap (Key k) a = KeyMap {sz :: !Int, tMap :: !(TrieMap (Rep k) a)} newtype instance Zipper (TrieMap (Key k)) a = KeyHole (Hole (Rep k) a) -- | @'TrieMap' ('Key' k) a@ is a wrapper around a @TrieMap (Rep k) a@. instance TKey k => TrieKey (Key k) where getSimpleM KMAP(m) = getSimpleM m sizeM = sz unifierM (Key k1) (Key k2) a = KeyHole <$> unifierM (toRep k1) (toRep k2) a unifyM (Key k1) a1 (Key k2) a2 = keyMap <$> unifyM (toRep k1) a1 (toRep k2) a2 keyRep :: (Repr k, TrieKey (Rep k)) => Key k -> Rep k keyRep (Key k) = toRep k
lowasser/TrieMap
Data/TrieMap/Key.hs
Haskell
bsd-3-clause
3,563
{-# LANGUAGE OverloadedStrings #-} module Cauterize.Common.ParserUtils ( pSexp , parseBuiltInName , parseSchemaVersion , parseFormHash ) where import Text.Parsec import Text.Parsec.Text.Lazy import Cauterize.FormHash import Cauterize.Lexer import Control.Monad import Data.Word import qualified Data.Text.Lazy as T import Numeric import qualified Data.ByteString as BS import Cauterize.Common.Types parseManyStartingWith :: String -> String -> Parser T.Text parseManyStartingWith s r = lexeme $ do s' <- oneOf s r' <- many . oneOf $ r return $ s' `T.cons` T.pack r' parseSchemaVersion :: Parser T.Text parseSchemaVersion = parseManyStartingWith start rest where start = ['a'..'z'] ++ ['0'..'9'] rest = start ++ "_.-" parseFormHash :: Parser FormHash parseFormHash = pSexp "sha1" $ lexeme $ liftM (FormHash . BS.pack . hexStrToWord8s) $ count 40 $ oneOf (['a'..'f'] ++ ['0'..'9']) pSexp :: String -> Parser a -> Parser a pSexp n p = lexeme (parens $ reserved n >> p) hexStrToWord8s :: String -> [Word8] hexStrToWord8s (a:b:rs) = let w = (fst . head) $ readHex [a,b] rs' = hexStrToWord8s rs in w:rs' hexStrToWord8s [] = [] hexStrToWord8s _ = error "Must have even number of characters" parseBuiltInName :: Parser BuiltIn parseBuiltInName = lexeme $ liftM read $ choice names where names = map (try . string . show) bis bis = [minBound .. maxBound] :: [BuiltIn]
reiddraper/cauterize
src/Cauterize/Common/ParserUtils.hs
Haskell
bsd-3-clause
1,465
module Euler.E60 ( concatInts , remarkable , remarkableSet , addToRemarkableSet , solve , s ) where import Data.Monoid import Data.Maybe import Data.Numbers.Primes solve :: Int -> Int solve n = sum $ head $ dropWhile (\xs -> length xs < n) s s :: [[Int]] s = [] : concatMap (\p -> mapMaybe (addToRemarkableSet p) (takeWhile (f p) s)) primes where f _ [] = True f y (x:_) = x < y addToRemarkableSet :: Int -> [Int] -> Maybe [Int] addToRemarkableSet y [] = Just [y] addToRemarkableSet y (x:xs) | remarkableSet (x:xs) y = Just (y:x:xs) | otherwise = Nothing remarkableSet :: [Int] -> Int -> Bool remarkableSet xs y = all (== True) $ map (remarkable y) xs remarkable :: Int -> Int -> Bool remarkable x y = {-# SCC remarkable #-} isPrime (concatInts x y) && isPrime (concatInts y x) concatInts :: Int -> Int -> Int concatInts x y | x <= 0 || y <= 0 = error "Invalid arguments" | otherwise = read $ show x <> show y
lslah/euler
src/Euler/E60.hs
Haskell
bsd-3-clause
985
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ViewPatterns #-} -- | Build-specific types. module Stack.Types.Build (StackBuildException(..) ,FlagSource(..) ,UnusedFlags(..) ,InstallLocation(..) ,ModTime ,modTime ,Installed(..) ,PackageInstallInfo(..) ,Task(..) ,taskLocation ,LocalPackage(..) ,BaseConfigOpts(..) ,Plan(..) ,TestOpts(..) ,BenchmarkOpts(..) ,FileWatchOpts(..) ,BuildOpts(..) ,BuildSubset(..) ,defaultBuildOpts ,TaskType(..) ,TaskConfigOpts(..) ,ConfigCache(..) ,ConstructPlanException(..) ,configureOpts ,BadDependency(..) ,wantedLocalPackages ,FileCacheInfo (..) ,ConfigureOpts (..) ,PrecompiledCache (..)) where import Control.DeepSeq import Control.Exception import Data.Binary (getWord8, putWord8, gput, gget) import Data.Binary.VersionTagged import qualified Data.ByteString as S import Data.Char (isSpace) import Data.Data import Data.Hashable import Data.List (dropWhileEnd, nub, intercalate) import qualified Data.Map as Map import Data.Map.Strict (Map) import Data.Maybe import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8With) import Data.Text.Encoding.Error (lenientDecode) import Data.Time.Calendar import Data.Time.Clock import Distribution.System (Arch) import Distribution.Text (display) import GHC.Generics import Path (Path, Abs, File, Dir, mkRelDir, toFilePath, parseRelDir, (</>)) import Prelude import Stack.Types.FlagName import Stack.Types.GhcPkgId import Stack.Types.Compiler import Stack.Types.Config import Stack.Types.Package import Stack.Types.PackageIdentifier import Stack.Types.PackageName import Stack.Types.Version import System.Exit (ExitCode (ExitFailure)) import System.FilePath (dropTrailingPathSeparator, pathSeparator) ---------------------------------------------- -- Exceptions data StackBuildException = Couldn'tFindPkgId PackageName | CompilerVersionMismatch (Maybe (CompilerVersion, Arch)) (CompilerVersion, Arch) GHCVariant VersionCheck (Maybe (Path Abs File)) Text -- recommended resolution -- ^ Path to the stack.yaml file | Couldn'tParseTargets [Text] | UnknownTargets (Set PackageName) -- no known version (Map PackageName Version) -- not in snapshot, here's the most recent version in the index (Path Abs File) -- stack.yaml | TestSuiteFailure PackageIdentifier (Map Text (Maybe ExitCode)) (Maybe (Path Abs File)) S.ByteString | ConstructPlanExceptions [ConstructPlanException] (Path Abs File) -- stack.yaml | CabalExitedUnsuccessfully ExitCode PackageIdentifier (Path Abs File) -- cabal Executable [String] -- cabal arguments (Maybe (Path Abs File)) -- logfiles location S.ByteString -- log contents | ExecutionFailure [SomeException] | LocalPackageDoesn'tMatchTarget PackageName Version -- local version Version -- version specified on command line | NoSetupHsFound (Path Abs Dir) | InvalidFlagSpecification (Set UnusedFlags) | TargetParseException [Text] | DuplicateLocalPackageNames [(PackageName, [Path Abs Dir])] deriving Typeable data FlagSource = FSCommandLine | FSStackYaml deriving (Show, Eq, Ord) data UnusedFlags = UFNoPackage FlagSource PackageName | UFFlagsNotDefined FlagSource Package (Set FlagName) | UFSnapshot PackageName deriving (Show, Eq, Ord) instance Show StackBuildException where show (Couldn'tFindPkgId name) = ("After installing " <> packageNameString name <> ", the package id couldn't be found " <> "(via ghc-pkg describe " <> packageNameString name <> "). This shouldn't happen, " <> "please report as a bug") show (CompilerVersionMismatch mactual (expected, earch) ghcVariant check mstack resolution) = concat [ case mactual of Nothing -> "No compiler found, expected " Just (actual, arch) -> concat [ "Compiler version mismatched, found " , compilerVersionString actual , " (" , display arch , ")" , ", but expected " ] , case check of MatchMinor -> "minor version match with " MatchExact -> "exact version " NewerMinor -> "minor version match or newer with " , compilerVersionString expected , " (" , display earch , ghcVariantSuffix ghcVariant , ") (based on " , case mstack of Nothing -> "command line arguments" Just stack -> "resolver setting in " ++ toFilePath stack , ").\n" , T.unpack resolution ] show (Couldn'tParseTargets targets) = unlines $ "The following targets could not be parsed as package names or directories:" : map T.unpack targets show (UnknownTargets noKnown notInSnapshot stackYaml) = unlines $ noKnown' ++ notInSnapshot' where noKnown' | Set.null noKnown = [] | otherwise = return $ "The following target packages were not found: " ++ intercalate ", " (map packageNameString $ Set.toList noKnown) notInSnapshot' | Map.null notInSnapshot = [] | otherwise = "The following packages are not in your snapshot, but exist" : "in your package index. Recommended action: add them to your" : ("extra-deps in " ++ toFilePath stackYaml) : "(Note: these are the most recent versions," : "but there's no guarantee that they'll build together)." : "" : map (\(name, version) -> "- " ++ packageIdentifierString (PackageIdentifier name version)) (Map.toList notInSnapshot) show (TestSuiteFailure ident codes mlogFile bs) = unlines $ concat [ ["Test suite failure for package " ++ packageIdentifierString ident] , flip map (Map.toList codes) $ \(name, mcode) -> concat [ " " , T.unpack name , ": " , case mcode of Nothing -> " executable not found" Just ec -> " exited with: " ++ show ec ] , return $ case mlogFile of Nothing -> "Logs printed to console" -- TODO Should we load up the full error output and print it here? Just logFile -> "Full log available at " ++ toFilePath logFile , if S.null bs then [] else ["", "", doubleIndent $ T.unpack $ decodeUtf8With lenientDecode bs] ] where indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines doubleIndent = indent . indent show (ConstructPlanExceptions exceptions stackYaml) = "While constructing the BuildPlan the following exceptions were encountered:" ++ appendExceptions exceptions' ++ if Map.null extras then "" else (unlines $ ("\n\nRecommended action: try adding the following to your extra-deps in " ++ toFilePath stackYaml) : map (\(name, version) -> concat [ "- " , packageNameString name , "-" , versionString version ]) (Map.toList extras) ++ ["", "You may also want to try the 'stack solver' command"] ) where exceptions' = removeDuplicates exceptions appendExceptions = foldr (\e -> (++) ("\n\n--" ++ show e)) "" removeDuplicates = nub extras = Map.unions $ map getExtras exceptions' getExtras (DependencyCycleDetected _) = Map.empty getExtras (UnknownPackage _) = Map.empty getExtras (DependencyPlanFailures _ m) = Map.unions $ map go $ Map.toList m where go (name, (_range, Just version, NotInBuildPlan)) = Map.singleton name version go _ = Map.empty -- Supressing duplicate output show (CabalExitedUnsuccessfully exitCode taskProvides' execName fullArgs logFiles bs) = let fullCmd = (dropQuotes (toFilePath execName) ++ " " ++ (unwords fullArgs)) logLocations = maybe "" (\fp -> "\n Logs have been written to: " ++ toFilePath fp) logFiles in "\n-- While building package " ++ dropQuotes (show taskProvides') ++ " using:\n" ++ " " ++ fullCmd ++ "\n" ++ " Process exited with code: " ++ show exitCode ++ (if exitCode == ExitFailure (-9) then " (THIS MAY INDICATE OUT OF MEMORY)" else "") ++ logLocations ++ (if S.null bs then "" else "\n\n" ++ doubleIndent (T.unpack $ decodeUtf8With lenientDecode bs)) where -- appendLines = foldr (\pName-> (++) ("\n" ++ show pName)) "" indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines dropQuotes = filter ('\"' /=) doubleIndent = indent . indent show (ExecutionFailure es) = intercalate "\n\n" $ map show es show (LocalPackageDoesn'tMatchTarget name localV requestedV) = concat [ "Version for local package " , packageNameString name , " is " , versionString localV , ", but you asked for " , versionString requestedV , " on the command line" ] show (NoSetupHsFound dir) = "No Setup.hs or Setup.lhs file found in " ++ toFilePath dir show (InvalidFlagSpecification unused) = unlines $ "Invalid flag specification:" : map go (Set.toList unused) where showFlagSrc :: FlagSource -> String showFlagSrc FSCommandLine = " (specified on command line)" showFlagSrc FSStackYaml = " (specified in stack.yaml)" go :: UnusedFlags -> String go (UFNoPackage src name) = concat [ "- Package '" , packageNameString name , "' not found" , showFlagSrc src ] go (UFFlagsNotDefined src pkg flags) = concat [ "- Package '" , name , "' does not define the following flags" , showFlagSrc src , ":\n" , intercalate "\n" (map (\flag -> " " ++ flagNameString flag) (Set.toList flags)) , "\n- Flags defined by package '" ++ name ++ "':\n" , intercalate "\n" (map (\flag -> " " ++ name ++ ":" ++ flagNameString flag) (Set.toList pkgFlags)) ] where name = packageNameString (packageName pkg) pkgFlags = packageDefinedFlags pkg go (UFSnapshot name) = concat [ "- Attempted to set flag on snapshot package " , packageNameString name , ", please add to extra-deps" ] show (TargetParseException [err]) = "Error parsing targets: " ++ T.unpack err show (TargetParseException errs) = unlines $ "The following errors occurred while parsing the build targets:" : map (("- " ++) . T.unpack) errs show (DuplicateLocalPackageNames pairs) = concat $ "The same package name is used in multiple local packages\n" : map go pairs where go (name, dirs) = unlines $ "" : (packageNameString name ++ " used in:") : map goDir dirs goDir dir = "- " ++ toFilePath dir instance Exception StackBuildException data ConstructPlanException = DependencyCycleDetected [PackageName] | DependencyPlanFailures PackageIdentifier (Map PackageName (VersionRange, LatestVersion, BadDependency)) | UnknownPackage PackageName -- TODO perhaps this constructor will be removed, and BadDependency will handle it all -- ^ Recommend adding to extra-deps, give a helpful version number? deriving (Typeable, Eq) -- | For display purposes only, Nothing if package not found type LatestVersion = Maybe Version -- | Reason why a dependency was not used data BadDependency = NotInBuildPlan | Couldn'tResolveItsDependencies | DependencyMismatch Version deriving (Typeable, Eq) instance Show ConstructPlanException where show e = let details = case e of (DependencyCycleDetected pNames) -> "While checking call stack,\n" ++ " dependency cycle detected in packages:" ++ indent (appendLines pNames) (DependencyPlanFailures pIdent (Map.toList -> pDeps)) -> "Failure when adding dependencies:" ++ doubleIndent (appendDeps pDeps) ++ "\n" ++ " needed for package: " ++ packageIdentifierString pIdent (UnknownPackage pName) -> "While attempting to add dependency,\n" ++ " Could not find package " ++ show pName ++ " in known packages" in indent details where appendLines = foldr (\pName-> (++) ("\n" ++ show pName)) "" indent = dropWhileEnd isSpace . unlines . fmap (\line -> " " ++ line) . lines doubleIndent = indent . indent appendDeps = foldr (\dep-> (++) ("\n" ++ showDep dep)) "" showDep (name, (range, mlatest, badDep)) = concat [ show name , ": needed (" , display range , ")" , ", " , let latestStr = case mlatest of Nothing -> "" Just latest -> " (latest is " ++ versionString latest ++ ")" in case badDep of NotInBuildPlan -> "not present in build plan" ++ latestStr Couldn'tResolveItsDependencies -> "couldn't resolve its dependencies" DependencyMismatch version -> case mlatest of Just latest | latest == version -> versionString version ++ " found (latest version available)" _ -> versionString version ++ " found" ++ latestStr ] {- TODO Perhaps change the showDep function to look more like this: dropQuotes = filter ((/=) '\"') (VersionOutsideRange pName pIdentifier versionRange) -> "Exception: Stack.Build.VersionOutsideRange\n" ++ " While adding dependency for package " ++ show pName ++ ",\n" ++ " " ++ dropQuotes (show pIdentifier) ++ " was found to be outside its allowed version range.\n" ++ " Allowed version range is " ++ display versionRange ++ ",\n" ++ " should you correct the version range for " ++ dropQuotes (show pIdentifier) ++ ", found in [extra-deps] in the project's stack.yaml?" -} ---------------------------------------------- -- | Which subset of packages to build data BuildSubset = BSAll | BSOnlySnapshot -- ^ Only install packages in the snapshot database, skipping -- packages intended for the local database. | BSOnlyDependencies deriving Show -- | Configuration for building. data BuildOpts = BuildOpts {boptsTargets :: ![Text] ,boptsLibProfile :: !Bool ,boptsExeProfile :: !Bool ,boptsHaddock :: !Bool -- ^ Build haddocks? ,boptsHaddockDeps :: !(Maybe Bool) -- ^ Build haddocks for dependencies? ,boptsDryrun :: !Bool ,boptsGhcOptions :: ![Text] ,boptsFlags :: !(Map (Maybe PackageName) (Map FlagName Bool)) ,boptsInstallExes :: !Bool -- ^ Install executables to user path after building? ,boptsPreFetch :: !Bool -- ^ Fetch all packages immediately ,boptsBuildSubset :: !BuildSubset ,boptsFileWatch :: !FileWatchOpts -- ^ Watch files for changes and automatically rebuild ,boptsKeepGoing :: !(Maybe Bool) -- ^ Keep building/running after failure ,boptsForceDirty :: !Bool -- ^ Force treating all local packages as having dirty files ,boptsTests :: !Bool -- ^ Turn on tests for local targets ,boptsTestOpts :: !TestOpts -- ^ Additional test arguments ,boptsBenchmarks :: !Bool -- ^ Turn on benchmarks for local targets ,boptsBenchmarkOpts :: !BenchmarkOpts -- ^ Additional test arguments ,boptsExec :: ![(String, [String])] -- ^ Commands (with arguments) to run after a successful build ,boptsOnlyConfigure :: !Bool -- ^ Only perform the configure step when building ,boptsReconfigure :: !Bool -- ^ Perform the configure step even if already configured ,boptsCabalVerbose :: !Bool -- ^ Ask Cabal to be verbose in its builds } deriving (Show) defaultBuildOpts :: BuildOpts defaultBuildOpts = BuildOpts { boptsTargets = [] , boptsLibProfile = False , boptsExeProfile = False , boptsHaddock = False , boptsHaddockDeps = Nothing , boptsDryrun = False , boptsGhcOptions = [] , boptsFlags = Map.empty , boptsInstallExes = False , boptsPreFetch = False , boptsBuildSubset = BSAll , boptsFileWatch = NoFileWatch , boptsKeepGoing = Nothing , boptsForceDirty = False , boptsTests = False , boptsTestOpts = defaultTestOpts , boptsBenchmarks = False , boptsBenchmarkOpts = defaultBenchmarkOpts , boptsExec = [] , boptsOnlyConfigure = False , boptsReconfigure = False , boptsCabalVerbose = False } -- | Options for the 'FinalAction' 'DoTests' data TestOpts = TestOpts {toRerunTests :: !Bool -- ^ Whether successful tests will be run gain ,toAdditionalArgs :: ![String] -- ^ Arguments passed to the test program ,toCoverage :: !Bool -- ^ Generate a code coverage report ,toDisableRun :: !Bool -- ^ Disable running of tests } deriving (Eq,Show) defaultTestOpts :: TestOpts defaultTestOpts = TestOpts { toRerunTests = True , toAdditionalArgs = [] , toCoverage = False , toDisableRun = False } -- | Options for the 'FinalAction' 'DoBenchmarks' data BenchmarkOpts = BenchmarkOpts {beoAdditionalArgs :: !(Maybe String) -- ^ Arguments passed to the benchmark program ,beoDisableRun :: !Bool -- ^ Disable running of benchmarks } deriving (Eq,Show) defaultBenchmarkOpts :: BenchmarkOpts defaultBenchmarkOpts = BenchmarkOpts { beoAdditionalArgs = Nothing , beoDisableRun = False } data FileWatchOpts = NoFileWatch | FileWatch | FileWatchPoll deriving (Show,Eq) -- | Package dependency oracle. newtype PkgDepsOracle = PkgDeps PackageName deriving (Show,Typeable,Eq,Hashable,Binary,NFData) -- | Stored on disk to know whether the flags have changed or any -- files have changed. data ConfigCache = ConfigCache { configCacheOpts :: !ConfigureOpts -- ^ All options used for this package. , configCacheDeps :: !(Set GhcPkgId) -- ^ The GhcPkgIds of all of the dependencies. Since Cabal doesn't take -- the complete GhcPkgId (only a PackageIdentifier) in the configure -- options, just using the previous value is insufficient to know if -- dependencies have changed. , configCacheComponents :: !(Set S.ByteString) -- ^ The components to be built. It's a bit of a hack to include this in -- here, as it's not a configure option (just a build option), but this -- is a convenient way to force compilation when the components change. , configCacheHaddock :: !Bool -- ^ Are haddocks to be built? } deriving (Generic,Eq,Show) instance Binary ConfigCache where put x = do -- magic string putWord8 1 putWord8 3 putWord8 4 putWord8 8 gput $ from x get = do 1 <- getWord8 3 <- getWord8 4 <- getWord8 8 <- getWord8 fmap to gget instance NFData ConfigCache instance HasStructuralInfo ConfigCache instance HasSemanticVersion ConfigCache -- | A task to perform when building data Task = Task { taskProvides :: !PackageIdentifier -- ^ the package/version to be built , taskType :: !TaskType -- ^ the task type, telling us how to build this , taskConfigOpts :: !TaskConfigOpts , taskPresent :: !(Map PackageIdentifier GhcPkgId) -- ^ GhcPkgIds of already-installed dependencies } deriving Show -- | Given the IDs of any missing packages, produce the configure options data TaskConfigOpts = TaskConfigOpts { tcoMissing :: !(Set PackageIdentifier) -- ^ Dependencies for which we don't yet have an GhcPkgId , tcoOpts :: !(Map PackageIdentifier GhcPkgId -> ConfigureOpts) -- ^ Produce the list of options given the missing @GhcPkgId@s } instance Show TaskConfigOpts where show (TaskConfigOpts missing f) = concat [ "Missing: " , show missing , ". Without those: " , show $ f Map.empty ] -- | The type of a task, either building local code or something from the -- package index (upstream) data TaskType = TTLocal LocalPackage | TTUpstream Package InstallLocation deriving Show taskLocation :: Task -> InstallLocation taskLocation task = case taskType task of TTLocal _ -> Local TTUpstream _ loc -> loc -- | A complete plan of what needs to be built and how to do it data Plan = Plan { planTasks :: !(Map PackageName Task) , planFinals :: !(Map PackageName (Task, LocalPackageTB)) -- ^ Final actions to be taken (test, benchmark, etc) , planUnregisterLocal :: !(Map GhcPkgId (PackageIdentifier, Maybe Text)) -- ^ Text is reason we're unregistering, for display only , planInstallExes :: !(Map Text InstallLocation) -- ^ Executables that should be installed after successful building } deriving Show -- | Basic information used to calculate what the configure options are data BaseConfigOpts = BaseConfigOpts { bcoSnapDB :: !(Path Abs Dir) , bcoLocalDB :: !(Path Abs Dir) , bcoSnapInstallRoot :: !(Path Abs Dir) , bcoLocalInstallRoot :: !(Path Abs Dir) , bcoBuildOpts :: !BuildOpts } -- | Render a @BaseConfigOpts@ to an actual list of options configureOpts :: EnvConfig -> BaseConfigOpts -> Map PackageIdentifier GhcPkgId -- ^ dependencies -> Bool -- ^ wanted? -> InstallLocation -> Package -> ConfigureOpts configureOpts econfig bco deps wanted loc package = ConfigureOpts { coDirs = configureOptsDirs bco loc package , coNoDirs = configureOptsNoDir econfig bco deps wanted package } configureOptsDirs :: BaseConfigOpts -> InstallLocation -> Package -> [String] configureOptsDirs bco loc package = concat [ ["--user", "--package-db=clear", "--package-db=global"] , map (("--package-db=" ++) . toFilePath) $ case loc of Snap -> [bcoSnapDB bco] Local -> [bcoSnapDB bco, bcoLocalDB bco] , [ "--libdir=" ++ toFilePathNoTrailingSlash (installRoot </> $(mkRelDir "lib")) , "--bindir=" ++ toFilePathNoTrailingSlash (installRoot </> bindirSuffix) , "--datadir=" ++ toFilePathNoTrailingSlash (installRoot </> $(mkRelDir "share")) , "--libexecdir=" ++ toFilePathNoTrailingSlash (installRoot </> $(mkRelDir "libexec")) , "--sysconfdir=" ++ toFilePathNoTrailingSlash (installRoot </> $(mkRelDir "etc")) , "--docdir=" ++ toFilePathNoTrailingSlash docDir , "--htmldir=" ++ toFilePathNoTrailingSlash docDir , "--haddockdir=" ++ toFilePathNoTrailingSlash docDir] ] where toFilePathNoTrailingSlash = dropTrailingPathSeparator . toFilePath installRoot = case loc of Snap -> bcoSnapInstallRoot bco Local -> bcoLocalInstallRoot bco docDir = case pkgVerDir of Nothing -> installRoot </> docDirSuffix Just dir -> installRoot </> docDirSuffix </> dir pkgVerDir = parseRelDir (packageIdentifierString (PackageIdentifier (packageName package) (packageVersion package)) ++ [pathSeparator]) -- | Same as 'configureOpts', but does not include directory path options configureOptsNoDir :: EnvConfig -> BaseConfigOpts -> Map PackageIdentifier GhcPkgId -- ^ dependencies -> Bool -- ^ wanted? -> Package -> [String] configureOptsNoDir econfig bco deps wanted package = concat [ depOptions , ["--enable-library-profiling" | boptsLibProfile bopts || boptsExeProfile bopts] , ["--enable-executable-profiling" | boptsExeProfile bopts] , map (\(name,enabled) -> "-f" <> (if enabled then "" else "-") <> flagNameString name) (Map.toList (packageFlags package)) , concatMap (\x -> ["--ghc-options", T.unpack x]) allGhcOptions , map (("--extra-include-dirs=" ++) . T.unpack) (Set.toList (configExtraIncludeDirs config)) , map (("--extra-lib-dirs=" ++) . T.unpack) (Set.toList (configExtraLibDirs config)) , if whichCompiler (envConfigCompilerVersion econfig) == Ghcjs then ["--ghcjs"] else [] ] where config = getConfig econfig bopts = bcoBuildOpts bco depOptions = map (uncurry toDepOption) $ Map.toList deps where toDepOption = if envConfigCabalVersion econfig >= $(mkVersion "1.22") then toDepOption1_22 else toDepOption1_18 toDepOption1_22 ident gid = concat [ "--dependency=" , packageNameString $ packageIdentifierName ident , "=" , ghcPkgIdString gid ] toDepOption1_18 ident _gid = concat [ "--constraint=" , packageNameString name , "==" , versionString version ] where PackageIdentifier name version = ident ghcOptionsMap = configGhcOptions $ getConfig econfig allGhcOptions = concat [ fromMaybe [] $ Map.lookup Nothing ghcOptionsMap , fromMaybe [] $ Map.lookup (Just $ packageName package) ghcOptionsMap , if wanted then boptsGhcOptions bopts else [] ] -- | Get set of wanted package names from locals. wantedLocalPackages :: [LocalPackage] -> Set PackageName wantedLocalPackages = Set.fromList . map (packageName . lpPackage) . filter lpWanted -- | One-way conversion to serialized time. modTime :: UTCTime -> ModTime modTime x = ModTime ( toModifiedJulianDay (utctDay x) , toRational (utctDayTime x)) data Installed = Library PackageIdentifier GhcPkgId | Executable PackageIdentifier deriving (Show, Eq, Ord) -- | Configure options to be sent to Setup.hs configure data ConfigureOpts = ConfigureOpts { coDirs :: ![String] -- ^ Options related to various paths. We separate these out since they do -- not have an impact on the contents of the compiled binary for checking -- if we can use an existing precompiled cache. , coNoDirs :: ![String] } deriving (Show, Eq, Generic) instance Binary ConfigureOpts instance HasStructuralInfo ConfigureOpts instance NFData ConfigureOpts -- | Information on a compiled package: the library conf file (if relevant), -- and all of the executable paths. data PrecompiledCache = PrecompiledCache -- Use FilePath instead of Path Abs File for Binary instances { pcLibrary :: !(Maybe FilePath) -- ^ .conf file inside the package database , pcExes :: ![FilePath] -- ^ Full paths to executables } deriving (Show, Eq, Generic) instance Binary PrecompiledCache instance HasSemanticVersion PrecompiledCache instance HasStructuralInfo PrecompiledCache instance NFData PrecompiledCache
robstewart57/stack
src/Stack/Types/Build.hs
Haskell
bsd-3-clause
29,426
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.Histogram -- Copyright : (c) Sven Panne 2002-2013 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- This module corresponds to a part of section 3.6.1 (Pixel Storage Modes) of -- the OpenGL 2.1 specs. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.GL.PixelRectangles.Histogram ( Sink(..), histogram, Reset(..), getHistogram, resetHistogram, histogramRGBASizes, histogramLuminanceSize ) where import Foreign.Marshal.Utils import Graphics.Rendering.OpenGL.GL.Capability import Graphics.Rendering.OpenGL.GL.PeekPoke import Graphics.Rendering.OpenGL.GL.PixelData import Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable import Graphics.Rendering.OpenGL.GL.PixelRectangles.Reset import Graphics.Rendering.OpenGL.GL.PixelRectangles.Sink import Graphics.Rendering.OpenGL.GL.StateVar import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat import Graphics.Rendering.OpenGL.GL.VertexSpec import Graphics.Rendering.OpenGL.Raw -------------------------------------------------------------------------------- data HistogramTarget = Histogram | ProxyHistogram marshalHistogramTarget :: HistogramTarget -> GLenum marshalHistogramTarget x = case x of Histogram -> gl_HISTOGRAM ProxyHistogram -> gl_PROXY_HISTOGRAM proxyToHistogramTarget :: Proxy -> HistogramTarget proxyToHistogramTarget x = case x of NoProxy -> Histogram Proxy -> ProxyHistogram -------------------------------------------------------------------------------- histogram :: Proxy -> StateVar (Maybe (GLsizei, PixelInternalFormat, Sink)) histogram proxy = makeStateVarMaybe (return CapHistogram) (getHistogram' proxy) (setHistogram proxy) getHistogram' :: Proxy -> IO (GLsizei, PixelInternalFormat, Sink) getHistogram' proxy = do w <- getHistogramParameteri fromIntegral proxy HistogramWidth f <- getHistogramParameteri unmarshalPixelInternalFormat proxy HistogramFormat s <- getHistogramParameteri unmarshalSink proxy HistogramSink return (w, f, s) getHistogramParameteri :: (GLint -> a) -> Proxy -> GetHistogramParameterPName -> IO a getHistogramParameteri f proxy p = with 0 $ \buf -> do glGetHistogramParameteriv (marshalHistogramTarget (proxyToHistogramTarget proxy)) (marshalGetHistogramParameterPName p) buf peek1 f buf setHistogram :: Proxy -> (GLsizei, PixelInternalFormat, Sink) -> IO () setHistogram proxy (w, int, sink) = glHistogram (marshalHistogramTarget (proxyToHistogramTarget proxy)) w (marshalPixelInternalFormat' int) (marshalSink sink) -------------------------------------------------------------------------------- getHistogram :: Reset -> PixelData a -> IO () getHistogram reset pd = withPixelData pd $ glGetHistogram (marshalHistogramTarget Histogram) (marshalReset reset) -------------------------------------------------------------------------------- resetHistogram :: IO () resetHistogram = glResetHistogram (marshalHistogramTarget Histogram) -------------------------------------------------------------------------------- data GetHistogramParameterPName = HistogramWidth | HistogramFormat | HistogramRedSize | HistogramGreenSize | HistogramBlueSize | HistogramAlphaSize | HistogramLuminanceSize | HistogramSink marshalGetHistogramParameterPName :: GetHistogramParameterPName -> GLenum marshalGetHistogramParameterPName x = case x of HistogramWidth -> gl_HISTOGRAM_WIDTH HistogramFormat -> gl_HISTOGRAM_FORMAT HistogramRedSize -> gl_HISTOGRAM_RED_SIZE HistogramGreenSize -> gl_HISTOGRAM_GREEN_SIZE HistogramBlueSize -> gl_HISTOGRAM_BLUE_SIZE HistogramAlphaSize -> gl_HISTOGRAM_ALPHA_SIZE HistogramLuminanceSize -> gl_HISTOGRAM_LUMINANCE_SIZE HistogramSink -> gl_HISTOGRAM_SINK -------------------------------------------------------------------------------- histogramRGBASizes :: Proxy -> GettableStateVar (Color4 GLsizei) histogramRGBASizes proxy = makeGettableStateVar $ do r <- getHistogramParameteri fromIntegral proxy HistogramRedSize g <- getHistogramParameteri fromIntegral proxy HistogramGreenSize b <- getHistogramParameteri fromIntegral proxy HistogramBlueSize a <- getHistogramParameteri fromIntegral proxy HistogramAlphaSize return $ Color4 r g b a histogramLuminanceSize :: Proxy -> GettableStateVar GLsizei histogramLuminanceSize proxy = makeGettableStateVar $ getHistogramParameteri fromIntegral proxy HistogramLuminanceSize
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/PixelRectangles/Histogram.hs
Haskell
bsd-3-clause
4,803
-- | Module: Acme.LOLCAT -- Copyright: (c) 2013 Antonio Nikishaev -- License: BSD -- Maintainer: me@lelf.lu -- -- >>> (OH HAI I CAN HAZ ЙO? THXBYE <*> putStrLn) "LOL" == () -- LOL -- True {-# LANGUAGE Unsafe #-} module Acme.LOLCAT.IO (OH(..),HAI(..),I(..),CAN(..),HAZ(..), IO(..),ÏO(..),ЙО(..),ЙO(..),YO(..), (?),THXBYE(..)) where import Prelude hiding (IO) import System.IO.Unsafe (unsafePerformIO) data HAI a b c d e = HAI a b c d e data OH a b c d e = OH a b c d e data I = I data IO = IO data ÏO = ÏO data ЙО = ЙО data ЙO = ЙO data YO = YO data CAN = CAN data HAZ = HAZ data THXBYE = THXBYE _?_ = return unsafePerformIO
llelf/acme-lolcat
Acme/LOLCAT/IO.hs
Haskell
bsd-3-clause
711
module MaybeHero.World ( World , mkWorld , moveRoom , currentRoom , lookupRoom , lookupRoomStrict , rooms , roomDestinations , showCurrentInventory ) where import qualified Data.Map as Map import qualified Data.Maybe as Maybe import qualified Data.List as List import qualified MaybeHero.Room as Room import qualified MaybeHero.Inventory as I import qualified MaybeHero.GameObject as GO type RoomName = String type Inventory = [I.MoveableItem] data World = World (Map.Map RoomName Room.Room) RoomName Inventory mkWorld :: (Map.Map RoomName Room.Room) -> RoomName -> Inventory -> World mkWorld roomMap roomName inventory = World roomMap roomName inventory lookupRoomStrict :: String -> World -> Maybe Room.Room lookupRoomStrict s (World roomMap _ _) = Map.lookup s roomMap lookupRoom :: String -> World -> Room.Room lookupRoom s world = Maybe.maybe message id (lookupRoomStrict s world) where message = (error $ "Room does not exist for name " ++ s) moveRoom :: String -> World -> Maybe World moveRoom direction world@(World roomMap _ inventory) = do newRoomName <- Map.lookup direction $ Room.roomOrientation $ currentRoom world return $ World roomMap newRoomName inventory currentRoom :: World -> Room.Room currentRoom world@(World roomMap currentRoomName _) = lookupRoom currentRoomName world currentInventory :: World -> Inventory currentInventory (World _ _ inventory) = inventory showCurrentInventory :: World -> String showCurrentInventory = concat . List.intersperse ", " . map GO.objectName . currentInventory rooms :: World -> [Room.Room] rooms (World roomMap _ _) = Map.elems roomMap roomDestinations :: World -> [String] roomDestinations w = do room <- rooms w orientation <- Map.elems $ Room.roomOrientation room return orientation
gtrogers/maybe-hero
src/MaybeHero/World.hs
Haskell
bsd-3-clause
1,768
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE PolyKinds #-} {-# OPTIONS_HADDOCK not-home #-} module Servant.API.QueryParam (QueryFlag, QueryParam, QueryParams) where import Data.Typeable (Typeable) import GHC.TypeLits (Symbol) -- | Lookup the value associated to the @sym@ query string parameter -- and try to extract it as a value of type @a@. -- -- Example: -- -- >>> -- /books?author=<author name> -- >>> type MyApi = "books" :> QueryParam "author" Text :> Get '[JSON] [Book] data QueryParam (sym :: Symbol) a deriving Typeable -- | Lookup the values associated to the @sym@ query string parameter -- and try to extract it as a value of type @[a]@. This is typically -- meant to support query string parameters of the form -- @param[]=val1&param[]=val2@ and so on. Note that servant doesn't actually -- require the @[]@s and will fetch the values just fine with -- @param=val1&param=val2@, too. -- -- Example: -- -- >>> -- /books?authors[]=<author1>&authors[]=<author2>&... -- >>> type MyApi = "books" :> QueryParams "authors" Text :> Get '[JSON] [Book] data QueryParams (sym :: Symbol) a deriving Typeable -- | Lookup a potentially value-less query string parameter -- with boolean semantics. If the param @sym@ is there without any value, -- or if it's there with value "true" or "1", it's interpreted as 'True'. -- Otherwise, it's interpreted as 'False'. -- -- Example: -- -- >>> -- /books?published -- >>> type MyApi = "books" :> QueryFlag "published" :> Get '[JSON] [Book] data QueryFlag (sym :: Symbol) -- $setup -- >>> import Servant.API -- >>> import Data.Aeson -- >>> import Data.Text -- >>> data Book -- >>> instance ToJSON Book where { toJSON = undefined }
zerobuzz/servant
servant/src/Servant/API/QueryParam.hs
Haskell
bsd-3-clause
1,790
{-# LANGUAGE RecursiveDo #-} module Main where import Reflex import Reflex.Gloss.Scene import Reflex.Monad.Time import Reflex.Animation import Data.Foldable import Data.Traversable import Reflex.Monad import Graphics.Gloss import Widgets foldMerge :: MonadReflex t m => a -> [Event t (a -> a)] -> m (Dynamic t a) foldMerge initial events = foldDyn ($) initial (mergeWith (.) events) renderCanvas :: Vector -> [Picture] -> Picture renderCanvas (sx, sy) drawings = mconcat [ color black $ rectangleWire sx sy , mconcat drawings ] pen :: Reflex t => Vector -> Behavior t Color -> Scene t (Event t Picture) pen size currentCol = mdo start <- mouseDown LeftButton <$> targetRect (constant size) stop <- mouseUp LeftButton <$> targetWindow drawing <- widgetHold (return never) $ leftmost [ scrible stop <$ start , return never <$ stop ] return (switch (current drawing)) where scrible stop = do updates <- observe =<< localMouse points <- current <$> foldDyn (:) [] (clampSize <$> updates) let drawing = drawPath <$> points <*> currentCol render $ drawing return (tag drawing stop) clampSize (x, y) = (clamp (-w/2, w/2) x, clamp (-h/2, h/2) y) where (w, h) = size drawPath points c = color c $ line points palette :: Reflex t => [Color] -> Scene t (Behavior t Color) palette colors = do clicks <- forM indexed $ \(i, c) -> ith i $ do target <- targetRect (pure (30, 30)) render $ pure (drawColor c) (click, _) <- clicked LeftButton target return (c <$ click) currentCol <- hold (head colors) (leftmost clicks) render (drawSelected <$> currentCol) return currentCol where height = fromIntegral (length colors) * 40 + 50 ith i = translation (0, i * 40 - height/2) indexed = zip [1..] colors drawColor c = color c $ rectangleSolid 30 30 drawSelected c = translate 0 (-(height/2) - 25) $ color c $ rectangleSolid 40 40 canvas :: Reflex t => Vector -> Scene t () canvas size = do currentCol <- translation (200, 0) $ palette [black, red, green, blue] scribble <- pen size currentCol drawings <- current <$> foldDyn (:) [] scribble render $ renderCanvas <$> pure size <*> drawings widget :: Reflex t => Scene t () widget = canvas (300, 300) main = playSceneGraph display background frequency widget where display = InWindow "Scribble3" (600, 600) (0, 0) background = white frequency = 30
Saulzar/scribble
src/Scribble3.hs
Haskell
bsd-3-clause
2,557
-- | Multipart names. module Text.MultipartNames.MultipartName( MultipartName, mkMultipartName, mkMultipartNameFromWords, isLegalSegment, toSegments ) where -- import Control.Lens import Data.CaseInsensitive(CI) import qualified Data.CaseInsensitive as CI import Data.Char(isAscii, isLetter) -- | An opaque type that represents a multipart name. The initial -- character of each segment must be a cased letter. Currently, only -- ASCII letters are allowed as first characters of segments. newtype MultipartName = MultipartName [CI String] deriving (Eq, Ord, Show) -- | Returns the segments of the name toSegments :: MultipartName -> [CI String] toSegments (MultipartName ss) = ss -- | Creates a multipart name from its segments. mkMultipartName :: [String] -> MultipartName mkMultipartName ss | null ss = error "mkMultipartName []: argument cannot be null" | all isLegalSegment ss = MultipartName $ map CI.mk ss | otherwise = error msg where msg = "mkMultipartName " ++ show ss ++ ": all segments must start with a cased letter" -- | Creates a multipart name from words. Equivalent to -- @mkMultipartName . words@. mkMultipartNameFromWords :: String -> MultipartName mkMultipartNameFromWords = mkMultipartName . words -- | Is this string a legal segment for a 'MultipartName'? isLegalSegment :: String -> Bool isLegalSegment seg = case seg of [] -> False c : _ -> isAscii c && isLetter c
nedervold/multipart-names
src/Text/MultipartNames/MultipartName.hs
Haskell
bsd-3-clause
1,466
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.ES3Compatibility -- Copyright : (c) Sven Panne 2013 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- All raw functions, tokens and types from the ARB_ES3_compatibility extension, -- see <http://www.opengl.org/registry/specs/ARB/ES3_compatibility.txt>. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.ES3Compatibility ( -- * Tokens gl_COMPRESSED_RGB8_ETC2, gl_COMPRESSED_SRGB8_ETC2, gl_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, gl_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, gl_COMPRESSED_RGBA8_ETC2_EAC, gl_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, gl_COMPRESSED_R11_EAC, gl_COMPRESSED_SIGNED_R11_EAC, gl_COMPRESSED_RG11_EAC, gl_COMPRESSED_SIGNED_RG11_EAC, gl_PRIMITIVE_RESTART_FIXED_INDEX, gl_ANY_SAMPLES_PASSED_CONSERVATIVE, gl_MAX_ELEMENT_INDEX ) where import Graphics.Rendering.OpenGL.Raw.Core31.Types gl_COMPRESSED_RGB8_ETC2 :: GLenum gl_COMPRESSED_RGB8_ETC2 = 0x9274 gl_COMPRESSED_SRGB8_ETC2 :: GLenum gl_COMPRESSED_SRGB8_ETC2 = 0x9275 gl_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 :: GLenum gl_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276 gl_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 :: GLenum gl_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277 gl_COMPRESSED_RGBA8_ETC2_EAC :: GLenum gl_COMPRESSED_RGBA8_ETC2_EAC = 0x9278 gl_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC :: GLenum gl_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279 gl_COMPRESSED_R11_EAC :: GLenum gl_COMPRESSED_R11_EAC = 0x9270 gl_COMPRESSED_SIGNED_R11_EAC :: GLenum gl_COMPRESSED_SIGNED_R11_EAC = 0x9271 gl_COMPRESSED_RG11_EAC :: GLenum gl_COMPRESSED_RG11_EAC = 0x9272 gl_COMPRESSED_SIGNED_RG11_EAC :: GLenum gl_COMPRESSED_SIGNED_RG11_EAC = 0x9273 gl_PRIMITIVE_RESTART_FIXED_INDEX :: GLenum gl_PRIMITIVE_RESTART_FIXED_INDEX = 0x8D69 gl_ANY_SAMPLES_PASSED_CONSERVATIVE :: GLenum gl_ANY_SAMPLES_PASSED_CONSERVATIVE = 0x8D6A gl_MAX_ELEMENT_INDEX :: GLenum gl_MAX_ELEMENT_INDEX = 0x8D6B
mfpi/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/ES3Compatibility.hs
Haskell
bsd-3-clause
2,197
module Language.Xi.Base.Parser where
fizruk/xi-base
src/Language/Xi/Base/Parser.hs
Haskell
bsd-3-clause
37
module Parser.Internal where import Control.Applicative ( (<|>) ) import ASTree ( Number(..) , Expr(..) , LatCalError(..) ) import Text.ParserCombinators.ReadP ( ReadP , readP_to_S , optional , eof , char , munch , (<++) , chainl1 , string , between , skipSpaces , option , satisfy ) import Data.Char ( isDigit ) {- | Parse a latex expression string to either a parseerror or a latex - expression. -} parseString :: String -- ^ String to parse. -> Either LatCalError Expr parseString str = case readP_to_S parseExpr str of [(program, "")] -> Right program _ -> Left $ ParserError "Parse error" parseExpr :: ReadP Expr parseExpr = do expr <- token parseExpr0 eof return expr parseExpr0 :: ReadP Expr parseExpr0 = parseExpr1 `chainl1` plusminus where plusminus = plus <|> minus plus = infixOp "+" Sum minus = infixOp "-" Minus parseExpr1 :: ReadP Expr parseExpr1 = parseExpr2 `chainl1` mult where mult = mult1 <|> mult2 <|> mult3 mult1 = token (optional $ char '*') >> return Product mult2 = infixOp "\\cdot" Product mult3 = infixOp "\\times" Product parseExpr2 :: ReadP Expr parseExpr2 = parseExpr3 `chainl1` pow where pow = infixOp "^" Power parseExpr3 :: ReadP Expr parseExpr3 = fact <|> parseExpr4 <|> divi <|> binom <|> expo where divi = do _ <- string "\\frac" expr1 <- between (token $ char '{') (token $ char '}') parseExpr0 expr2 <- between (token $ char '{') (token $ char '}') parseExpr0 return $ Fraction expr1 expr2 fact = do expr <- token parseExpr4 _ <- char '!' return $ Factorial expr binom = do _ <- token $ string "\\binom" expr1 <- between (token $ char '{') (token $ char '}') parseExpr0 expr2 <- between (token $ char '{') (token $ char '}') parseExpr0 return $ Binomial expr1 expr2 expo = do _ <- token $ string "exp" expr <- between (token $ char '(') (token $ char ')') parseExpr0 return $ Power (Literal $ Real (exp 1)) expr parseExpr4 :: ReadP Expr parseExpr4 = real <++ whole <++ constant <++ bracket where real = token $ do skipSpaces minus <- option ' ' (char '-') first <- satisfy (`elem` ['0'..'9']) digits1 <- munch isDigit _ <- char '.' digits2 <- munch isDigit let int = Whole $ read (minus:first:digits1) frac = Real $ read ((minus:"0.") ++ digits2) return $ Literal (int + frac) whole = do skipSpaces minus <- option ' ' (char '-') first <- satisfy (`elem` ['0'..'9']) digits <- munch isDigit return $ Literal (Whole $ read (minus:first:digits)) bracket = bracket1 <|> bracket2 <|> bracket3 bracket1 = parseBracket (char '(') (char ')') bracket2 = parseBracket (string "\\left(") (string "\\right)") bracket3 = parseBracket (char '{') (char '}') parseBracket s e = between (token s) (token e) parseExpr0 constant = pi' <|> euler pi' = token (string "\\pi") >> return (Literal $ Real pi) euler = token (char 'e') >> return (Literal $ Real (exp 1)) infixOp :: String -> (a -> a -> a) -> ReadP (a -> a -> a) infixOp x f = token (string x) >> return f token :: ReadP a -> ReadP a token f = skipSpaces >> f >>= \v -> skipSpaces >> return v
bus000/latex-calculator
src/Parser/Internal.hs
Haskell
bsd-3-clause
3,436
{-# LANGUAGE TemplateHaskell #-} module Main where import qualified System.Exit as Exit import qualified TsParse as T main :: IO () main = T.runAllTests >>= \b -> if b then Exit.exitSuccess else Exit.exitFailure
massysett/tsparse
test-tsp.hs
Haskell
bsd-3-clause
217
-- | This module re-exports everything from 'Pos.Chain.Block.Logic.*'. module Pos.Chain.Block.Logic ( module Pos.Chain.Block.Logic.Integrity ) where import Pos.Chain.Block.Logic.Integrity
input-output-hk/pos-haskell-prototype
chain/src/Pos/Chain/Block/Logic.hs
Haskell
mit
213
module Interaction where import Logic import Browser -- | number of sentences type Window = Int type data DB = DB { retrieve :: Int -> Maybe Conversation, update :: Int -> Conversation -> DB, data Browsing = Browsing { browser :: Browser data State = State { conversations :: [(Int,Browsing)] } data Modify = Up Int | Down Int | Append String | Keep Int Bool | Refresh | Taint Int Int data Request = SetUser String | GetPage | GetConversation Int data Interaction a = Modification (Modify -> State -> State) | Interface (Request -> a
paolino/qrmaniacs
Interaction.hs
Haskell
mit
577
{- SockeyeSymbolTable.hs: Symbol Table for Sockeye Part of Sockeye Copyright (c) 2017, ETH Zurich. All rights reserved. This file is distributed under the terms in the attached LICENSE file. If you do not find this file, copies can be found by writing to: ETH Zurich D-INFK, CAB F.78, Universitaetstrasse 6, CH-8092 Zurich, Attn: Systems Group. -} module SockeyeSymbolTable ( module SockeyeSymbolTable , module SockeyeAST ) where import Data.Set (Set) import Data.Map (Map) import SockeyeASTMeta import SockeyeAST ( NaturalSet(NaturalSet) , NaturalRange(SingletonRange, LimitRange, BitsRange) , natRangeMeta, base, limit, bits , NaturalExpr(Addition, Subtraction, Multiplication, Slice, Concat, Variable, Literal) , natExprMeta, natExprOp1, natExprOp2, bitRange, varName, natural ) data Sockeye = Sockeye { entryPoint :: FilePath , files :: Map FilePath SockeyeFile } deriving (Show) data SockeyeFile = SockeyeFile { sockeyeFileMeta :: ASTMeta , modules :: Map String Module , types :: Map String NamedType } deriving (Show) instance MetaAST SockeyeFile where meta = sockeyeFileMeta data Module = Module { moduleMeta :: ASTMeta , parameters :: Map String ModuleParameter , parameterOrder :: [String] , constants :: Map String NamedConstant , inputPorts :: Set String , outputPorts :: Map String Node , instances :: Map String Instance , nodes :: Map String Node } | ImportedModule { moduleMeta :: ASTMeta , moduleFile :: !FilePath , origModName :: !String } deriving (Show) instance MetaAST Module where meta = moduleMeta data ModuleParameter = ModuleParameter { paramMeta :: ASTMeta , paramRange :: NaturalSet } deriving (Show) instance MetaAST ModuleParameter where meta = paramMeta data Instance = Instance { instMeta :: ASTMeta , instModule :: !String , instArrSize :: Maybe ArraySize } deriving (Show) instance MetaAST Instance where meta = instMeta data Node = Node { nodeMeta :: ASTMeta , nodeType :: NodeType , nodeArrSize :: Maybe ArraySize } deriving (Show) instance MetaAST Node where meta = nodeMeta data NodeType = NodeType { nodeTypeMeta :: ASTMeta , originDomain :: !Domain , originType :: EdgeType , targetDomain :: !Domain , targetType :: Maybe EdgeType } deriving (Show) instance MetaAST NodeType where meta = nodeTypeMeta data Domain = Memory | Interrupt | Power | Clock deriving (Eq, Show) data EdgeType = TypeLiteral { edgeTypeMeta :: ASTMeta , typeLiteral :: AddressType } | TypeName { edgeTypeMeta :: ASTMeta , typeRef :: !String } deriving (Show) instance MetaAST EdgeType where meta = edgeTypeMeta data NamedType = NamedType { namedTypeMeta :: ASTMeta , namedType :: AddressType } | ImportedType { namedTypeMeta :: ASTMeta , typeFile :: !FilePath , origTypeName :: !String } deriving (Show) instance MetaAST NamedType where meta = namedTypeMeta data NamedConstant = NamedConstant { namedConstMeta :: ASTMeta , namedConst :: !Integer } deriving (Show) instance MetaAST NamedConstant where meta = namedConstMeta data ArraySize = ArraySize ASTMeta [NaturalSet] deriving (Show) instance MetaAST ArraySize where meta (ArraySize m _) = m data AddressType = AddressType ASTMeta [NaturalSet] deriving (Show) instance MetaAST AddressType where meta (AddressType m _) = m
kishoredbn/barrelfish
tools/sockeye/SockeyeSymbolTable.hs
Haskell
mit
4,001
-- -- -- ----------------- -- Exercise 5.17. ----------------- -- -- -- module E'5'17 where -- GHCi> [2 .. 2] -- [2] -- [n .. n] results in the list [n]. -- GHCi> [2, 7 .. 4] -- [2] -- [2, 7 .. 4] results in the list [2]. -- GHCi> [2, 2 .. 2] -- [2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 -- ,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 -- ,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 -- ,2,2,2,2,2,2,2,2,2,2,2,2,2Interrupted. -- [n, n .. n] (ao.) results in an infinite calculation that has to be interrupted.
pascal-knodel/haskell-craft
_/links/E'5'17.hs
Haskell
mit
509
----------------------------------------------------------------------------- -- | -- Module : Control.Functor.Indexed -- Copyright : (C) 2008 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : portable -- ---------------------------------------------------------------------------- module Control.Functor.Indexed ( IxFunctor(..) , IxCopointed(..) , IxPointed(..) , IxApplicative(..) ) where class IxFunctor f where imap :: (a -> b) -> f j k a -> f j k b class IxPointed m => IxApplicative m where iap :: m i j (a -> b) -> m j k a -> m i k b class IxFunctor m => IxPointed m where ireturn :: a -> m i i a class IxFunctor w => IxCopointed w where iextract :: w i i a -> a {-# RULES "iextract/ireturn" iextract . ireturn = id #-}
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
Control/Functor/Indexed.hs
Haskell
apache-2.0
875
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="it-IT"> <title>Code Dx | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/codedx/src/main/javahelp/org/zaproxy/zap/extension/codedx/resources/help_it_IT/helpset_it_IT.hs
Haskell
apache-2.0
969
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="tr-TR"> <title>Pasif Tarama Kuralları - Beta | ZAP Uzantıları</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>İçindekiler</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>İçerik</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Arama</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favoriler</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/pscanrulesBeta/src/main/javahelp/org/zaproxy/zap/extension/pscanrulesBeta/resources/help_tr_TR/helpset_tr_TR.hs
Haskell
apache-2.0
1,002
{-# LANGUAGE ScopedTypeVariables #-} module Text.XmlHtml.TestCommon where import Control.Exception as E import System.IO.Unsafe import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit hiding (Test, Node) ------------------------------------------------------------------------------ -- | Tests a simple Bool property. testIt :: TestName -> Bool -> Test testIt name b = testCase name $ assertBool name b ------------------------------------------------------------------------------ -- Code adapted from ChasingBottoms. -- -- Adding an actual dependency isn't possible because Cabal refuses to build -- the package due to version conflicts. -- -- isBottom is impossible to write, but very useful! So we defy the -- impossible, and write it anyway. isBottom :: a -> Bool isBottom a = unsafePerformIO $ (E.evaluate a >> return False) `E.catches` [ E.Handler $ \ (_ :: PatternMatchFail) -> return True, E.Handler $ \ (_ :: ErrorCall) -> return True, E.Handler $ \ (_ :: NoMethodError) -> return True, E.Handler $ \ (_ :: RecConError) -> return True, E.Handler $ \ (_ :: RecUpdError) -> return True, E.Handler $ \ (_ :: RecSelError) -> return True ] ------------------------------------------------------------------------------ isLeft :: Either a b -> Bool isLeft = either (const True) (const False)
23Skidoo/xmlhtml
test/suite/Text/XmlHtml/TestCommon.hs
Haskell
bsd-3-clause
1,466
-- -- Data vault for metrics -- -- -- Copyright © 2013-2014 Anchor Systems, Pty Ltd and Others -- -- The code in this file, and the program it is a part of, is -- made available to you by its authors as open source software: -- you can redistribute it and/or modify it under the terms of -- the 3-clause BSD licence. -- {-# LANGUAGE OverloadedStrings #-} module Vaultaire.Types.ContentsResponse ( ContentsResponse(..), ) where import Control.Applicative ((<$>), (<*>)) import Control.Exception (SomeException (..)) import qualified Data.ByteString as S import Data.Packer (getBytes, getWord64LE, putBytes, putWord64LE, putWord8, runPacking, runUnpacking) import Test.QuickCheck import Vaultaire.Classes.WireFormat import Vaultaire.Types.Address import Vaultaire.Types.SourceDict data ContentsResponse = RandomAddress Address | InvalidContentsOrigin | ContentsListEntry Address SourceDict | EndOfContentsList | UpdateSuccess | RemoveSuccess deriving (Show, Eq) instance WireFormat ContentsResponse where fromWire bs | bs == "\x00" = Right InvalidContentsOrigin | bs == "\x03" = Right EndOfContentsList | bs == "\x04" = Right UpdateSuccess | bs == "\x05" = Right RemoveSuccess | S.take 1 bs == "\x01" = RandomAddress <$> fromWire (S.drop 1 bs) -- This relies on address being fixed-length when encoded | S.take 1 bs == "\x02" = do let body = S.drop 1 bs let unpacker = (,) <$> getBytes 8 <*> (getWord64LE >>= getBytes . fromIntegral) let (addr_bytes, dict_bytes ) = runUnpacking unpacker body ContentsListEntry <$> fromWire addr_bytes <*> fromWire dict_bytes | otherwise = Left $ SomeException $ userError "Invalid ContentsResponse packet" toWire InvalidContentsOrigin = "\x00" toWire (RandomAddress addr) = "\x01" `S.append` toWire addr toWire (ContentsListEntry addr dict) = let addr_bytes = toWire addr dict_bytes = toWire dict dict_len = S.length dict_bytes in runPacking (dict_len + 17) $ do putWord8 0x2 putBytes addr_bytes putWord64LE $ fromIntegral dict_len putBytes dict_bytes -- Be aware there is also case such that: -- toWire (ContentsListBypass addr b) = -- "\x02" ... -- so that raw encoded bytes stored on disk can be tunnelled through. See -- Vaultaire.Types.ContentsListBypass for details toWire EndOfContentsList = "\x03" toWire UpdateSuccess = "\x04" toWire RemoveSuccess = "\x05" instance Arbitrary ContentsResponse where arbitrary = oneof [ RandomAddress <$> arbitrary , ContentsListEntry <$> arbitrary <*> arbitrary , return EndOfContentsList , return UpdateSuccess , return RemoveSuccess ]
afcowie/vaultaire-common
lib/Vaultaire/Types/ContentsResponse.hs
Haskell
bsd-3-clause
3,024
module Main where import Graphics.X11.Turtle import Data.IORef import Control.Concurrent import Control.Monad import System.Environment import Text.XML.YJSVG import Data.Word main :: IO () main = do [fn, save] <- getArgs clr <- newIORef 0 bgclr <- newIORef 0 f <- openField t <- newTurtle f threadDelay 100000 height <- windowHeight t width <- windowWidth t clrT <- newTurtle f pensize clrT 10 hideturtle clrT penup clrT goto clrT (width / 2 - 10) (height / 2 - 10) pendown clrT shape t "turtle" shapesize t 2 2 pensize t 10 hideturtle t penup t readFile fn >>= runInputs t . read onclick f $ \b x y -> do case b of 1 -> goto t x y >> pendown t >> forward t 0 >> return True 3 -> clear t >> return True 2 -> modifyIORef bgclr (+ 1) >> readIORef bgclr >>= (\c -> bgcolor t c) . (colors !!) >> return True 4 -> goto t x y >> modifyIORef clr (+ 6) >> readIORef clr >>= (\c -> pencolor t c >> pencolor clrT c) . (colors !!) >> forward clrT 0 >> return True 5 -> goto t x y >> modifyIORef clr (+ 1) >> readIORef clr >>= (\c -> pencolor t c >> pencolor clrT c) . (colors !!) >> forward clrT 0 >> return True onrelease f $ \_ _ _ -> penup t>> return True onkeypress f $ \_ -> do {- print "hello" print $ head inputs print inputs print $ length inputs -} w <- windowWidth t h <- windowHeight t getSVG t >>= putStrLn . showSVG w h inputs <- inputs t when (read save) $ writeFile fn $ show $ drop 5 inputs return False ondrag f $ \bn x y -> case bn of 1 -> goto t x y _ -> return () waitField f colors :: [(Word8, Word8, Word8)] colors = cycle [ (255, 0, 0), (0, 255, 0), (255, 255, 0), (0, 0, 255), (128, 76, 0), (255, 255, 255), (0, 0, 0)]
YoshikuniJujo/wxturtle
tests/draw.hs
Haskell
bsd-3-clause
1,723
-- %************************************************************************ -- %* * -- The known-key names for Template Haskell -- %* * -- %************************************************************************ module THNames where import PrelNames( mk_known_key_name ) import Module( Module, mkModuleNameFS, mkModule, thUnitId ) import Name( Name ) import OccName( tcName, clsName, dataName, varName ) import RdrName( RdrName, nameRdrName ) import Unique import FastString -- To add a name, do three things -- -- 1) Allocate a key -- 2) Make a "Name" -- 3) Add the name to templateHaskellNames templateHaskellNames :: [Name] -- The names that are implicitly mentioned by ``bracket'' -- Should stay in sync with the import list of DsMeta templateHaskellNames = [ returnQName, bindQName, sequenceQName, newNameName, liftName, mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, mkNameSName, liftStringName, unTypeName, unTypeQName, unsafeTExpCoerceName, -- Lit charLName, stringLName, integerLName, intPrimLName, wordPrimLName, floatPrimLName, doublePrimLName, rationalLName, stringPrimLName, charPrimLName, -- Pat litPName, varPName, tupPName, unboxedTupPName, conPName, tildePName, bangPName, infixPName, asPName, wildPName, recPName, listPName, sigPName, viewPName, -- FieldPat fieldPatName, -- Match matchName, -- Clause clauseName, -- Exp varEName, conEName, litEName, appEName, infixEName, infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, unboxedTupEName, condEName, multiIfEName, letEName, caseEName, doEName, compEName, fromEName, fromThenEName, fromToEName, fromThenToEName, listEName, sigEName, recConEName, recUpdEName, staticEName, unboundVarEName, -- FieldExp fieldExpName, -- Body guardedBName, normalBName, -- Guard normalGEName, patGEName, -- Stmt bindSName, letSName, noBindSName, parSName, -- Dec funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, instanceDName, standaloneDerivDName, sigDName, forImpDName, pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName, defaultSigDName, dataFamilyDName, openTypeFamilyDName, closedTypeFamilyDName, dataInstDName, newtypeInstDName, tySynInstDName, infixLDName, infixRDName, infixNDName, roleAnnotDName, -- Cxt cxtName, -- Strict isStrictName, notStrictName, unpackedName, -- Con normalCName, recCName, infixCName, forallCName, -- StrictType strictTypeName, -- VarStrictType varStrictTypeName, -- Type forallTName, varTName, conTName, appTName, equalityTName, tupleTName, unboxedTupleTName, arrowTName, listTName, sigTName, litTName, promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName, wildCardTName, namedWildCardTName, -- TyLit numTyLitName, strTyLitName, -- TyVarBndr plainTVName, kindedTVName, -- Role nominalRName, representationalRName, phantomRName, inferRName, -- Kind varKName, conKName, tupleKName, arrowKName, listKName, appKName, starKName, constraintKName, -- FamilyResultSig noSigName, kindSigName, tyVarSigName, -- InjectivityAnn injectivityAnnName, -- Callconv cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName, -- Safety unsafeName, safeName, interruptibleName, -- Inline noInlineDataConName, inlineDataConName, inlinableDataConName, -- RuleMatch conLikeDataConName, funLikeDataConName, -- Phases allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName, -- TExp tExpDataConName, -- RuleBndr ruleVarName, typedRuleVarName, -- FunDep funDepName, -- FamFlavour typeFamName, dataFamName, -- TySynEqn tySynEqnName, -- AnnTarget valueAnnotationName, typeAnnotationName, moduleAnnotationName, -- The type classes liftClassName, -- And the tycons qTyConName, nameTyConName, patTyConName, fieldPatTyConName, matchQTyConName, clauseQTyConName, expQTyConName, fieldExpTyConName, predTyConName, stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, varStrictTypeQTyConName, typeQTyConName, expTyConName, decTyConName, typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, patQTyConName, fieldPatQTyConName, fieldExpQTyConName, funDepTyConName, predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName, tExpTyConName, injAnnTyConName, kindTyConName, -- Quasiquoting quoteDecName, quoteTypeName, quoteExpName, quotePatName] thSyn, thLib, qqLib :: Module thSyn = mkTHModule (fsLit "Language.Haskell.TH.Syntax") thLib = mkTHModule (fsLit "Language.Haskell.TH.Lib") qqLib = mkTHModule (fsLit "Language.Haskell.TH.Quote") mkTHModule :: FastString -> Module mkTHModule m = mkModule thUnitId (mkModuleNameFS m) libFun, libTc, thFun, thTc, thCls, thCon, qqFun :: FastString -> Unique -> Name libFun = mk_known_key_name OccName.varName thLib libTc = mk_known_key_name OccName.tcName thLib thFun = mk_known_key_name OccName.varName thSyn thTc = mk_known_key_name OccName.tcName thSyn thCls = mk_known_key_name OccName.clsName thSyn thCon = mk_known_key_name OccName.dataName thSyn qqFun = mk_known_key_name OccName.varName qqLib -------------------- TH.Syntax ----------------------- liftClassName :: Name liftClassName = thCls (fsLit "Lift") liftClassKey qTyConName, nameTyConName, fieldExpTyConName, patTyConName, fieldPatTyConName, expTyConName, decTyConName, typeTyConName, tyVarBndrTyConName, matchTyConName, clauseTyConName, funDepTyConName, predTyConName, tExpTyConName, injAnnTyConName, kindTyConName :: Name qTyConName = thTc (fsLit "Q") qTyConKey nameTyConName = thTc (fsLit "Name") nameTyConKey fieldExpTyConName = thTc (fsLit "FieldExp") fieldExpTyConKey patTyConName = thTc (fsLit "Pat") patTyConKey fieldPatTyConName = thTc (fsLit "FieldPat") fieldPatTyConKey expTyConName = thTc (fsLit "Exp") expTyConKey decTyConName = thTc (fsLit "Dec") decTyConKey typeTyConName = thTc (fsLit "Type") typeTyConKey tyVarBndrTyConName= thTc (fsLit "TyVarBndr") tyVarBndrTyConKey matchTyConName = thTc (fsLit "Match") matchTyConKey clauseTyConName = thTc (fsLit "Clause") clauseTyConKey funDepTyConName = thTc (fsLit "FunDep") funDepTyConKey predTyConName = thTc (fsLit "Pred") predTyConKey tExpTyConName = thTc (fsLit "TExp") tExpTyConKey injAnnTyConName = thTc (fsLit "InjectivityAnn") injAnnTyConKey kindTyConName = thTc (fsLit "Kind") kindTyConKey returnQName, bindQName, sequenceQName, newNameName, liftName, mkNameName, mkNameG_vName, mkNameG_dName, mkNameG_tcName, mkNameLName, mkNameSName, liftStringName, unTypeName, unTypeQName, unsafeTExpCoerceName :: Name returnQName = thFun (fsLit "returnQ") returnQIdKey bindQName = thFun (fsLit "bindQ") bindQIdKey sequenceQName = thFun (fsLit "sequenceQ") sequenceQIdKey newNameName = thFun (fsLit "newName") newNameIdKey liftName = thFun (fsLit "lift") liftIdKey liftStringName = thFun (fsLit "liftString") liftStringIdKey mkNameName = thFun (fsLit "mkName") mkNameIdKey mkNameG_vName = thFun (fsLit "mkNameG_v") mkNameG_vIdKey mkNameG_dName = thFun (fsLit "mkNameG_d") mkNameG_dIdKey mkNameG_tcName = thFun (fsLit "mkNameG_tc") mkNameG_tcIdKey mkNameLName = thFun (fsLit "mkNameL") mkNameLIdKey mkNameSName = thFun (fsLit "mkNameS") mkNameSIdKey unTypeName = thFun (fsLit "unType") unTypeIdKey unTypeQName = thFun (fsLit "unTypeQ") unTypeQIdKey unsafeTExpCoerceName = thFun (fsLit "unsafeTExpCoerce") unsafeTExpCoerceIdKey -------------------- TH.Lib ----------------------- -- data Lit = ... charLName, stringLName, integerLName, intPrimLName, wordPrimLName, floatPrimLName, doublePrimLName, rationalLName, stringPrimLName, charPrimLName :: Name charLName = libFun (fsLit "charL") charLIdKey stringLName = libFun (fsLit "stringL") stringLIdKey integerLName = libFun (fsLit "integerL") integerLIdKey intPrimLName = libFun (fsLit "intPrimL") intPrimLIdKey wordPrimLName = libFun (fsLit "wordPrimL") wordPrimLIdKey floatPrimLName = libFun (fsLit "floatPrimL") floatPrimLIdKey doublePrimLName = libFun (fsLit "doublePrimL") doublePrimLIdKey rationalLName = libFun (fsLit "rationalL") rationalLIdKey stringPrimLName = libFun (fsLit "stringPrimL") stringPrimLIdKey charPrimLName = libFun (fsLit "charPrimL") charPrimLIdKey -- data Pat = ... litPName, varPName, tupPName, unboxedTupPName, conPName, infixPName, tildePName, bangPName, asPName, wildPName, recPName, listPName, sigPName, viewPName :: Name litPName = libFun (fsLit "litP") litPIdKey varPName = libFun (fsLit "varP") varPIdKey tupPName = libFun (fsLit "tupP") tupPIdKey unboxedTupPName = libFun (fsLit "unboxedTupP") unboxedTupPIdKey conPName = libFun (fsLit "conP") conPIdKey infixPName = libFun (fsLit "infixP") infixPIdKey tildePName = libFun (fsLit "tildeP") tildePIdKey bangPName = libFun (fsLit "bangP") bangPIdKey asPName = libFun (fsLit "asP") asPIdKey wildPName = libFun (fsLit "wildP") wildPIdKey recPName = libFun (fsLit "recP") recPIdKey listPName = libFun (fsLit "listP") listPIdKey sigPName = libFun (fsLit "sigP") sigPIdKey viewPName = libFun (fsLit "viewP") viewPIdKey -- type FieldPat = ... fieldPatName :: Name fieldPatName = libFun (fsLit "fieldPat") fieldPatIdKey -- data Match = ... matchName :: Name matchName = libFun (fsLit "match") matchIdKey -- data Clause = ... clauseName :: Name clauseName = libFun (fsLit "clause") clauseIdKey -- data Exp = ... varEName, conEName, litEName, appEName, infixEName, infixAppName, sectionLName, sectionRName, lamEName, lamCaseEName, tupEName, unboxedTupEName, condEName, multiIfEName, letEName, caseEName, doEName, compEName, staticEName, unboundVarEName :: Name varEName = libFun (fsLit "varE") varEIdKey conEName = libFun (fsLit "conE") conEIdKey litEName = libFun (fsLit "litE") litEIdKey appEName = libFun (fsLit "appE") appEIdKey infixEName = libFun (fsLit "infixE") infixEIdKey infixAppName = libFun (fsLit "infixApp") infixAppIdKey sectionLName = libFun (fsLit "sectionL") sectionLIdKey sectionRName = libFun (fsLit "sectionR") sectionRIdKey lamEName = libFun (fsLit "lamE") lamEIdKey lamCaseEName = libFun (fsLit "lamCaseE") lamCaseEIdKey tupEName = libFun (fsLit "tupE") tupEIdKey unboxedTupEName = libFun (fsLit "unboxedTupE") unboxedTupEIdKey condEName = libFun (fsLit "condE") condEIdKey multiIfEName = libFun (fsLit "multiIfE") multiIfEIdKey letEName = libFun (fsLit "letE") letEIdKey caseEName = libFun (fsLit "caseE") caseEIdKey doEName = libFun (fsLit "doE") doEIdKey compEName = libFun (fsLit "compE") compEIdKey -- ArithSeq skips a level fromEName, fromThenEName, fromToEName, fromThenToEName :: Name fromEName = libFun (fsLit "fromE") fromEIdKey fromThenEName = libFun (fsLit "fromThenE") fromThenEIdKey fromToEName = libFun (fsLit "fromToE") fromToEIdKey fromThenToEName = libFun (fsLit "fromThenToE") fromThenToEIdKey -- end ArithSeq listEName, sigEName, recConEName, recUpdEName :: Name listEName = libFun (fsLit "listE") listEIdKey sigEName = libFun (fsLit "sigE") sigEIdKey recConEName = libFun (fsLit "recConE") recConEIdKey recUpdEName = libFun (fsLit "recUpdE") recUpdEIdKey staticEName = libFun (fsLit "staticE") staticEIdKey unboundVarEName = libFun (fsLit "unboundVarE") unboundVarEIdKey -- type FieldExp = ... fieldExpName :: Name fieldExpName = libFun (fsLit "fieldExp") fieldExpIdKey -- data Body = ... guardedBName, normalBName :: Name guardedBName = libFun (fsLit "guardedB") guardedBIdKey normalBName = libFun (fsLit "normalB") normalBIdKey -- data Guard = ... normalGEName, patGEName :: Name normalGEName = libFun (fsLit "normalGE") normalGEIdKey patGEName = libFun (fsLit "patGE") patGEIdKey -- data Stmt = ... bindSName, letSName, noBindSName, parSName :: Name bindSName = libFun (fsLit "bindS") bindSIdKey letSName = libFun (fsLit "letS") letSIdKey noBindSName = libFun (fsLit "noBindS") noBindSIdKey parSName = libFun (fsLit "parS") parSIdKey -- data Dec = ... funDName, valDName, dataDName, newtypeDName, tySynDName, classDName, instanceDName, sigDName, forImpDName, pragInlDName, pragSpecDName, pragSpecInlDName, pragSpecInstDName, pragRuleDName, pragAnnDName, standaloneDerivDName, defaultSigDName, dataInstDName, newtypeInstDName, tySynInstDName, dataFamilyDName, openTypeFamilyDName, closedTypeFamilyDName, infixLDName, infixRDName, infixNDName, roleAnnotDName :: Name funDName = libFun (fsLit "funD") funDIdKey valDName = libFun (fsLit "valD") valDIdKey dataDName = libFun (fsLit "dataD") dataDIdKey newtypeDName = libFun (fsLit "newtypeD") newtypeDIdKey tySynDName = libFun (fsLit "tySynD") tySynDIdKey classDName = libFun (fsLit "classD") classDIdKey instanceDName = libFun (fsLit "instanceD") instanceDIdKey standaloneDerivDName = libFun (fsLit "standaloneDerivD") standaloneDerivDIdKey sigDName = libFun (fsLit "sigD") sigDIdKey defaultSigDName = libFun (fsLit "defaultSigD") defaultSigDIdKey forImpDName = libFun (fsLit "forImpD") forImpDIdKey pragInlDName = libFun (fsLit "pragInlD") pragInlDIdKey pragSpecDName = libFun (fsLit "pragSpecD") pragSpecDIdKey pragSpecInlDName = libFun (fsLit "pragSpecInlD") pragSpecInlDIdKey pragSpecInstDName = libFun (fsLit "pragSpecInstD") pragSpecInstDIdKey pragRuleDName = libFun (fsLit "pragRuleD") pragRuleDIdKey pragAnnDName = libFun (fsLit "pragAnnD") pragAnnDIdKey dataInstDName = libFun (fsLit "dataInstD") dataInstDIdKey newtypeInstDName = libFun (fsLit "newtypeInstD") newtypeInstDIdKey tySynInstDName = libFun (fsLit "tySynInstD") tySynInstDIdKey openTypeFamilyDName = libFun (fsLit "openTypeFamilyD") openTypeFamilyDIdKey closedTypeFamilyDName= libFun (fsLit "closedTypeFamilyD") closedTypeFamilyDIdKey dataFamilyDName = libFun (fsLit "dataFamilyD") dataFamilyDIdKey infixLDName = libFun (fsLit "infixLD") infixLDIdKey infixRDName = libFun (fsLit "infixRD") infixRDIdKey infixNDName = libFun (fsLit "infixND") infixNDIdKey roleAnnotDName = libFun (fsLit "roleAnnotD") roleAnnotDIdKey -- type Ctxt = ... cxtName :: Name cxtName = libFun (fsLit "cxt") cxtIdKey -- data Strict = ... isStrictName, notStrictName, unpackedName :: Name isStrictName = libFun (fsLit "isStrict") isStrictKey notStrictName = libFun (fsLit "notStrict") notStrictKey unpackedName = libFun (fsLit "unpacked") unpackedKey -- data Con = ... normalCName, recCName, infixCName, forallCName :: Name normalCName = libFun (fsLit "normalC") normalCIdKey recCName = libFun (fsLit "recC") recCIdKey infixCName = libFun (fsLit "infixC") infixCIdKey forallCName = libFun (fsLit "forallC") forallCIdKey -- type StrictType = ... strictTypeName :: Name strictTypeName = libFun (fsLit "strictType") strictTKey -- type VarStrictType = ... varStrictTypeName :: Name varStrictTypeName = libFun (fsLit "varStrictType") varStrictTKey -- data Type = ... forallTName, varTName, conTName, tupleTName, unboxedTupleTName, arrowTName, listTName, appTName, sigTName, equalityTName, litTName, promotedTName, promotedTupleTName, promotedNilTName, promotedConsTName, wildCardTName, namedWildCardTName :: Name forallTName = libFun (fsLit "forallT") forallTIdKey varTName = libFun (fsLit "varT") varTIdKey conTName = libFun (fsLit "conT") conTIdKey tupleTName = libFun (fsLit "tupleT") tupleTIdKey unboxedTupleTName = libFun (fsLit "unboxedTupleT") unboxedTupleTIdKey arrowTName = libFun (fsLit "arrowT") arrowTIdKey listTName = libFun (fsLit "listT") listTIdKey appTName = libFun (fsLit "appT") appTIdKey sigTName = libFun (fsLit "sigT") sigTIdKey equalityTName = libFun (fsLit "equalityT") equalityTIdKey litTName = libFun (fsLit "litT") litTIdKey promotedTName = libFun (fsLit "promotedT") promotedTIdKey promotedTupleTName = libFun (fsLit "promotedTupleT") promotedTupleTIdKey promotedNilTName = libFun (fsLit "promotedNilT") promotedNilTIdKey promotedConsTName = libFun (fsLit "promotedConsT") promotedConsTIdKey wildCardTName = libFun (fsLit "wildCardT") wildCardTIdKey namedWildCardTName = libFun (fsLit "namedWildCardT") namedWildCardTIdKey -- data TyLit = ... numTyLitName, strTyLitName :: Name numTyLitName = libFun (fsLit "numTyLit") numTyLitIdKey strTyLitName = libFun (fsLit "strTyLit") strTyLitIdKey -- data TyVarBndr = ... plainTVName, kindedTVName :: Name plainTVName = libFun (fsLit "plainTV") plainTVIdKey kindedTVName = libFun (fsLit "kindedTV") kindedTVIdKey -- data Role = ... nominalRName, representationalRName, phantomRName, inferRName :: Name nominalRName = libFun (fsLit "nominalR") nominalRIdKey representationalRName = libFun (fsLit "representationalR") representationalRIdKey phantomRName = libFun (fsLit "phantomR") phantomRIdKey inferRName = libFun (fsLit "inferR") inferRIdKey -- data Kind = ... varKName, conKName, tupleKName, arrowKName, listKName, appKName, starKName, constraintKName :: Name varKName = libFun (fsLit "varK") varKIdKey conKName = libFun (fsLit "conK") conKIdKey tupleKName = libFun (fsLit "tupleK") tupleKIdKey arrowKName = libFun (fsLit "arrowK") arrowKIdKey listKName = libFun (fsLit "listK") listKIdKey appKName = libFun (fsLit "appK") appKIdKey starKName = libFun (fsLit "starK") starKIdKey constraintKName = libFun (fsLit "constraintK") constraintKIdKey -- data FamilyResultSig = ... noSigName, kindSigName, tyVarSigName :: Name noSigName = libFun (fsLit "noSig") noSigIdKey kindSigName = libFun (fsLit "kindSig") kindSigIdKey tyVarSigName = libFun (fsLit "tyVarSig") tyVarSigIdKey -- data InjectivityAnn = ... injectivityAnnName :: Name injectivityAnnName = libFun (fsLit "injectivityAnn") injectivityAnnIdKey -- data Callconv = ... cCallName, stdCallName, cApiCallName, primCallName, javaScriptCallName :: Name cCallName = libFun (fsLit "cCall") cCallIdKey stdCallName = libFun (fsLit "stdCall") stdCallIdKey cApiCallName = libFun (fsLit "cApi") cApiCallIdKey primCallName = libFun (fsLit "prim") primCallIdKey javaScriptCallName = libFun (fsLit "javaScript") javaScriptCallIdKey -- data Safety = ... unsafeName, safeName, interruptibleName :: Name unsafeName = libFun (fsLit "unsafe") unsafeIdKey safeName = libFun (fsLit "safe") safeIdKey interruptibleName = libFun (fsLit "interruptible") interruptibleIdKey -- newtype TExp a = ... tExpDataConName :: Name tExpDataConName = thCon (fsLit "TExp") tExpDataConKey -- data RuleBndr = ... ruleVarName, typedRuleVarName :: Name ruleVarName = libFun (fsLit ("ruleVar")) ruleVarIdKey typedRuleVarName = libFun (fsLit ("typedRuleVar")) typedRuleVarIdKey -- data FunDep = ... funDepName :: Name funDepName = libFun (fsLit "funDep") funDepIdKey -- data FamFlavour = ... typeFamName, dataFamName :: Name typeFamName = libFun (fsLit "typeFam") typeFamIdKey dataFamName = libFun (fsLit "dataFam") dataFamIdKey -- data TySynEqn = ... tySynEqnName :: Name tySynEqnName = libFun (fsLit "tySynEqn") tySynEqnIdKey -- data AnnTarget = ... valueAnnotationName, typeAnnotationName, moduleAnnotationName :: Name valueAnnotationName = libFun (fsLit "valueAnnotation") valueAnnotationIdKey typeAnnotationName = libFun (fsLit "typeAnnotation") typeAnnotationIdKey moduleAnnotationName = libFun (fsLit "moduleAnnotation") moduleAnnotationIdKey matchQTyConName, clauseQTyConName, expQTyConName, stmtQTyConName, decQTyConName, conQTyConName, strictTypeQTyConName, varStrictTypeQTyConName, typeQTyConName, fieldExpQTyConName, patQTyConName, fieldPatQTyConName, predQTyConName, decsQTyConName, ruleBndrQTyConName, tySynEqnQTyConName, roleTyConName :: Name matchQTyConName = libTc (fsLit "MatchQ") matchQTyConKey clauseQTyConName = libTc (fsLit "ClauseQ") clauseQTyConKey expQTyConName = libTc (fsLit "ExpQ") expQTyConKey stmtQTyConName = libTc (fsLit "StmtQ") stmtQTyConKey decQTyConName = libTc (fsLit "DecQ") decQTyConKey decsQTyConName = libTc (fsLit "DecsQ") decsQTyConKey -- Q [Dec] conQTyConName = libTc (fsLit "ConQ") conQTyConKey strictTypeQTyConName = libTc (fsLit "StrictTypeQ") strictTypeQTyConKey varStrictTypeQTyConName = libTc (fsLit "VarStrictTypeQ") varStrictTypeQTyConKey typeQTyConName = libTc (fsLit "TypeQ") typeQTyConKey fieldExpQTyConName = libTc (fsLit "FieldExpQ") fieldExpQTyConKey patQTyConName = libTc (fsLit "PatQ") patQTyConKey fieldPatQTyConName = libTc (fsLit "FieldPatQ") fieldPatQTyConKey predQTyConName = libTc (fsLit "PredQ") predQTyConKey ruleBndrQTyConName = libTc (fsLit "RuleBndrQ") ruleBndrQTyConKey tySynEqnQTyConName = libTc (fsLit "TySynEqnQ") tySynEqnQTyConKey roleTyConName = libTc (fsLit "Role") roleTyConKey -- quasiquoting quoteExpName, quotePatName, quoteDecName, quoteTypeName :: Name quoteExpName = qqFun (fsLit "quoteExp") quoteExpKey quotePatName = qqFun (fsLit "quotePat") quotePatKey quoteDecName = qqFun (fsLit "quoteDec") quoteDecKey quoteTypeName = qqFun (fsLit "quoteType") quoteTypeKey -- data Inline = ... noInlineDataConName, inlineDataConName, inlinableDataConName :: Name noInlineDataConName = thCon (fsLit "NoInline") noInlineDataConKey inlineDataConName = thCon (fsLit "Inline") inlineDataConKey inlinableDataConName = thCon (fsLit "Inlinable") inlinableDataConKey -- data RuleMatch = ... conLikeDataConName, funLikeDataConName :: Name conLikeDataConName = thCon (fsLit "ConLike") conLikeDataConKey funLikeDataConName = thCon (fsLit "FunLike") funLikeDataConKey -- data Phases = ... allPhasesDataConName, fromPhaseDataConName, beforePhaseDataConName :: Name allPhasesDataConName = thCon (fsLit "AllPhases") allPhasesDataConKey fromPhaseDataConName = thCon (fsLit "FromPhase") fromPhaseDataConKey beforePhaseDataConName = thCon (fsLit "BeforePhase") beforePhaseDataConKey {- ********************************************************************* * * Class keys * * ********************************************************************* -} -- ClassUniques available: 200-299 -- Check in PrelNames if you want to change this liftClassKey :: Unique liftClassKey = mkPreludeClassUnique 200 {- ********************************************************************* * * TyCon keys * * ********************************************************************* -} -- TyConUniques available: 200-299 -- Check in PrelNames if you want to change this expTyConKey, matchTyConKey, clauseTyConKey, qTyConKey, expQTyConKey, decQTyConKey, patTyConKey, matchQTyConKey, clauseQTyConKey, stmtQTyConKey, conQTyConKey, typeQTyConKey, typeTyConKey, tyVarBndrTyConKey, decTyConKey, varStrictTypeQTyConKey, strictTypeQTyConKey, fieldExpTyConKey, fieldPatTyConKey, nameTyConKey, patQTyConKey, fieldPatQTyConKey, fieldExpQTyConKey, funDepTyConKey, predTyConKey, predQTyConKey, decsQTyConKey, ruleBndrQTyConKey, tySynEqnQTyConKey, roleTyConKey, tExpTyConKey, injAnnTyConKey, kindTyConKey :: Unique expTyConKey = mkPreludeTyConUnique 200 matchTyConKey = mkPreludeTyConUnique 201 clauseTyConKey = mkPreludeTyConUnique 202 qTyConKey = mkPreludeTyConUnique 203 expQTyConKey = mkPreludeTyConUnique 204 decQTyConKey = mkPreludeTyConUnique 205 patTyConKey = mkPreludeTyConUnique 206 matchQTyConKey = mkPreludeTyConUnique 207 clauseQTyConKey = mkPreludeTyConUnique 208 stmtQTyConKey = mkPreludeTyConUnique 209 conQTyConKey = mkPreludeTyConUnique 210 typeQTyConKey = mkPreludeTyConUnique 211 typeTyConKey = mkPreludeTyConUnique 212 decTyConKey = mkPreludeTyConUnique 213 varStrictTypeQTyConKey = mkPreludeTyConUnique 214 strictTypeQTyConKey = mkPreludeTyConUnique 215 fieldExpTyConKey = mkPreludeTyConUnique 216 fieldPatTyConKey = mkPreludeTyConUnique 217 nameTyConKey = mkPreludeTyConUnique 218 patQTyConKey = mkPreludeTyConUnique 219 fieldPatQTyConKey = mkPreludeTyConUnique 220 fieldExpQTyConKey = mkPreludeTyConUnique 221 funDepTyConKey = mkPreludeTyConUnique 222 predTyConKey = mkPreludeTyConUnique 223 predQTyConKey = mkPreludeTyConUnique 224 tyVarBndrTyConKey = mkPreludeTyConUnique 225 decsQTyConKey = mkPreludeTyConUnique 226 ruleBndrQTyConKey = mkPreludeTyConUnique 227 tySynEqnQTyConKey = mkPreludeTyConUnique 228 roleTyConKey = mkPreludeTyConUnique 229 tExpTyConKey = mkPreludeTyConUnique 230 injAnnTyConKey = mkPreludeTyConUnique 231 kindTyConKey = mkPreludeTyConUnique 232 {- ********************************************************************* * * DataCon keys * * ********************************************************************* -} -- DataConUniques available: 100-150 -- If you want to change this, make sure you check in PrelNames -- data Inline = ... noInlineDataConKey, inlineDataConKey, inlinableDataConKey :: Unique noInlineDataConKey = mkPreludeDataConUnique 100 inlineDataConKey = mkPreludeDataConUnique 101 inlinableDataConKey = mkPreludeDataConUnique 102 -- data RuleMatch = ... conLikeDataConKey, funLikeDataConKey :: Unique conLikeDataConKey = mkPreludeDataConUnique 103 funLikeDataConKey = mkPreludeDataConUnique 104 -- data Phases = ... allPhasesDataConKey, fromPhaseDataConKey, beforePhaseDataConKey :: Unique allPhasesDataConKey = mkPreludeDataConUnique 105 fromPhaseDataConKey = mkPreludeDataConUnique 106 beforePhaseDataConKey = mkPreludeDataConUnique 107 -- newtype TExp a = ... tExpDataConKey :: Unique tExpDataConKey = mkPreludeDataConUnique 108 {- ********************************************************************* * * Id keys * * ********************************************************************* -} -- IdUniques available: 200-499 -- If you want to change this, make sure you check in PrelNames returnQIdKey, bindQIdKey, sequenceQIdKey, liftIdKey, newNameIdKey, mkNameIdKey, mkNameG_vIdKey, mkNameG_dIdKey, mkNameG_tcIdKey, mkNameLIdKey, mkNameSIdKey, unTypeIdKey, unTypeQIdKey, unsafeTExpCoerceIdKey :: Unique returnQIdKey = mkPreludeMiscIdUnique 200 bindQIdKey = mkPreludeMiscIdUnique 201 sequenceQIdKey = mkPreludeMiscIdUnique 202 liftIdKey = mkPreludeMiscIdUnique 203 newNameIdKey = mkPreludeMiscIdUnique 204 mkNameIdKey = mkPreludeMiscIdUnique 205 mkNameG_vIdKey = mkPreludeMiscIdUnique 206 mkNameG_dIdKey = mkPreludeMiscIdUnique 207 mkNameG_tcIdKey = mkPreludeMiscIdUnique 208 mkNameLIdKey = mkPreludeMiscIdUnique 209 mkNameSIdKey = mkPreludeMiscIdUnique 210 unTypeIdKey = mkPreludeMiscIdUnique 211 unTypeQIdKey = mkPreludeMiscIdUnique 212 unsafeTExpCoerceIdKey = mkPreludeMiscIdUnique 213 -- data Lit = ... charLIdKey, stringLIdKey, integerLIdKey, intPrimLIdKey, wordPrimLIdKey, floatPrimLIdKey, doublePrimLIdKey, rationalLIdKey, stringPrimLIdKey, charPrimLIdKey:: Unique charLIdKey = mkPreludeMiscIdUnique 220 stringLIdKey = mkPreludeMiscIdUnique 221 integerLIdKey = mkPreludeMiscIdUnique 222 intPrimLIdKey = mkPreludeMiscIdUnique 223 wordPrimLIdKey = mkPreludeMiscIdUnique 224 floatPrimLIdKey = mkPreludeMiscIdUnique 225 doublePrimLIdKey = mkPreludeMiscIdUnique 226 rationalLIdKey = mkPreludeMiscIdUnique 227 stringPrimLIdKey = mkPreludeMiscIdUnique 228 charPrimLIdKey = mkPreludeMiscIdUnique 229 liftStringIdKey :: Unique liftStringIdKey = mkPreludeMiscIdUnique 230 -- data Pat = ... litPIdKey, varPIdKey, tupPIdKey, unboxedTupPIdKey, conPIdKey, infixPIdKey, tildePIdKey, bangPIdKey, asPIdKey, wildPIdKey, recPIdKey, listPIdKey, sigPIdKey, viewPIdKey :: Unique litPIdKey = mkPreludeMiscIdUnique 240 varPIdKey = mkPreludeMiscIdUnique 241 tupPIdKey = mkPreludeMiscIdUnique 242 unboxedTupPIdKey = mkPreludeMiscIdUnique 243 conPIdKey = mkPreludeMiscIdUnique 244 infixPIdKey = mkPreludeMiscIdUnique 245 tildePIdKey = mkPreludeMiscIdUnique 246 bangPIdKey = mkPreludeMiscIdUnique 247 asPIdKey = mkPreludeMiscIdUnique 248 wildPIdKey = mkPreludeMiscIdUnique 249 recPIdKey = mkPreludeMiscIdUnique 250 listPIdKey = mkPreludeMiscIdUnique 251 sigPIdKey = mkPreludeMiscIdUnique 252 viewPIdKey = mkPreludeMiscIdUnique 253 -- type FieldPat = ... fieldPatIdKey :: Unique fieldPatIdKey = mkPreludeMiscIdUnique 260 -- data Match = ... matchIdKey :: Unique matchIdKey = mkPreludeMiscIdUnique 261 -- data Clause = ... clauseIdKey :: Unique clauseIdKey = mkPreludeMiscIdUnique 262 -- data Exp = ... varEIdKey, conEIdKey, litEIdKey, appEIdKey, infixEIdKey, infixAppIdKey, sectionLIdKey, sectionRIdKey, lamEIdKey, lamCaseEIdKey, tupEIdKey, unboxedTupEIdKey, condEIdKey, multiIfEIdKey, letEIdKey, caseEIdKey, doEIdKey, compEIdKey, fromEIdKey, fromThenEIdKey, fromToEIdKey, fromThenToEIdKey, listEIdKey, sigEIdKey, recConEIdKey, recUpdEIdKey, staticEIdKey, unboundVarEIdKey :: Unique varEIdKey = mkPreludeMiscIdUnique 270 conEIdKey = mkPreludeMiscIdUnique 271 litEIdKey = mkPreludeMiscIdUnique 272 appEIdKey = mkPreludeMiscIdUnique 273 infixEIdKey = mkPreludeMiscIdUnique 274 infixAppIdKey = mkPreludeMiscIdUnique 275 sectionLIdKey = mkPreludeMiscIdUnique 276 sectionRIdKey = mkPreludeMiscIdUnique 277 lamEIdKey = mkPreludeMiscIdUnique 278 lamCaseEIdKey = mkPreludeMiscIdUnique 279 tupEIdKey = mkPreludeMiscIdUnique 280 unboxedTupEIdKey = mkPreludeMiscIdUnique 281 condEIdKey = mkPreludeMiscIdUnique 282 multiIfEIdKey = mkPreludeMiscIdUnique 283 letEIdKey = mkPreludeMiscIdUnique 284 caseEIdKey = mkPreludeMiscIdUnique 285 doEIdKey = mkPreludeMiscIdUnique 286 compEIdKey = mkPreludeMiscIdUnique 287 fromEIdKey = mkPreludeMiscIdUnique 288 fromThenEIdKey = mkPreludeMiscIdUnique 289 fromToEIdKey = mkPreludeMiscIdUnique 290 fromThenToEIdKey = mkPreludeMiscIdUnique 291 listEIdKey = mkPreludeMiscIdUnique 292 sigEIdKey = mkPreludeMiscIdUnique 293 recConEIdKey = mkPreludeMiscIdUnique 294 recUpdEIdKey = mkPreludeMiscIdUnique 295 staticEIdKey = mkPreludeMiscIdUnique 296 unboundVarEIdKey = mkPreludeMiscIdUnique 297 -- type FieldExp = ... fieldExpIdKey :: Unique fieldExpIdKey = mkPreludeMiscIdUnique 310 -- data Body = ... guardedBIdKey, normalBIdKey :: Unique guardedBIdKey = mkPreludeMiscIdUnique 311 normalBIdKey = mkPreludeMiscIdUnique 312 -- data Guard = ... normalGEIdKey, patGEIdKey :: Unique normalGEIdKey = mkPreludeMiscIdUnique 313 patGEIdKey = mkPreludeMiscIdUnique 314 -- data Stmt = ... bindSIdKey, letSIdKey, noBindSIdKey, parSIdKey :: Unique bindSIdKey = mkPreludeMiscIdUnique 320 letSIdKey = mkPreludeMiscIdUnique 321 noBindSIdKey = mkPreludeMiscIdUnique 322 parSIdKey = mkPreludeMiscIdUnique 323 -- data Dec = ... funDIdKey, valDIdKey, dataDIdKey, newtypeDIdKey, tySynDIdKey, classDIdKey, instanceDIdKey, sigDIdKey, forImpDIdKey, pragInlDIdKey, pragSpecDIdKey, pragSpecInlDIdKey, pragSpecInstDIdKey, pragRuleDIdKey, pragAnnDIdKey, defaultSigDIdKey, dataFamilyDIdKey, openTypeFamilyDIdKey, closedTypeFamilyDIdKey, dataInstDIdKey, newtypeInstDIdKey, tySynInstDIdKey, standaloneDerivDIdKey, infixLDIdKey, infixRDIdKey, infixNDIdKey, roleAnnotDIdKey :: Unique funDIdKey = mkPreludeMiscIdUnique 330 valDIdKey = mkPreludeMiscIdUnique 331 dataDIdKey = mkPreludeMiscIdUnique 332 newtypeDIdKey = mkPreludeMiscIdUnique 333 tySynDIdKey = mkPreludeMiscIdUnique 334 classDIdKey = mkPreludeMiscIdUnique 335 instanceDIdKey = mkPreludeMiscIdUnique 336 sigDIdKey = mkPreludeMiscIdUnique 337 forImpDIdKey = mkPreludeMiscIdUnique 338 pragInlDIdKey = mkPreludeMiscIdUnique 339 pragSpecDIdKey = mkPreludeMiscIdUnique 340 pragSpecInlDIdKey = mkPreludeMiscIdUnique 341 pragSpecInstDIdKey = mkPreludeMiscIdUnique 342 pragRuleDIdKey = mkPreludeMiscIdUnique 343 pragAnnDIdKey = mkPreludeMiscIdUnique 344 dataFamilyDIdKey = mkPreludeMiscIdUnique 345 openTypeFamilyDIdKey = mkPreludeMiscIdUnique 346 dataInstDIdKey = mkPreludeMiscIdUnique 347 newtypeInstDIdKey = mkPreludeMiscIdUnique 348 tySynInstDIdKey = mkPreludeMiscIdUnique 349 closedTypeFamilyDIdKey = mkPreludeMiscIdUnique 350 infixLDIdKey = mkPreludeMiscIdUnique 352 infixRDIdKey = mkPreludeMiscIdUnique 353 infixNDIdKey = mkPreludeMiscIdUnique 354 roleAnnotDIdKey = mkPreludeMiscIdUnique 355 standaloneDerivDIdKey = mkPreludeMiscIdUnique 356 defaultSigDIdKey = mkPreludeMiscIdUnique 357 -- type Cxt = ... cxtIdKey :: Unique cxtIdKey = mkPreludeMiscIdUnique 360 -- data Strict = ... isStrictKey, notStrictKey, unpackedKey :: Unique isStrictKey = mkPreludeMiscIdUnique 363 notStrictKey = mkPreludeMiscIdUnique 364 unpackedKey = mkPreludeMiscIdUnique 365 -- data Con = ... normalCIdKey, recCIdKey, infixCIdKey, forallCIdKey :: Unique normalCIdKey = mkPreludeMiscIdUnique 370 recCIdKey = mkPreludeMiscIdUnique 371 infixCIdKey = mkPreludeMiscIdUnique 372 forallCIdKey = mkPreludeMiscIdUnique 373 -- type StrictType = ... strictTKey :: Unique strictTKey = mkPreludeMiscIdUnique 374 -- type VarStrictType = ... varStrictTKey :: Unique varStrictTKey = mkPreludeMiscIdUnique 375 -- data Type = ... forallTIdKey, varTIdKey, conTIdKey, tupleTIdKey, unboxedTupleTIdKey, arrowTIdKey, listTIdKey, appTIdKey, sigTIdKey, equalityTIdKey, litTIdKey, promotedTIdKey, promotedTupleTIdKey, promotedNilTIdKey, promotedConsTIdKey, wildCardTIdKey, namedWildCardTIdKey :: Unique forallTIdKey = mkPreludeMiscIdUnique 380 varTIdKey = mkPreludeMiscIdUnique 381 conTIdKey = mkPreludeMiscIdUnique 382 tupleTIdKey = mkPreludeMiscIdUnique 383 unboxedTupleTIdKey = mkPreludeMiscIdUnique 384 arrowTIdKey = mkPreludeMiscIdUnique 385 listTIdKey = mkPreludeMiscIdUnique 386 appTIdKey = mkPreludeMiscIdUnique 387 sigTIdKey = mkPreludeMiscIdUnique 388 equalityTIdKey = mkPreludeMiscIdUnique 389 litTIdKey = mkPreludeMiscIdUnique 390 promotedTIdKey = mkPreludeMiscIdUnique 391 promotedTupleTIdKey = mkPreludeMiscIdUnique 392 promotedNilTIdKey = mkPreludeMiscIdUnique 393 promotedConsTIdKey = mkPreludeMiscIdUnique 394 wildCardTIdKey = mkPreludeMiscIdUnique 395 namedWildCardTIdKey = mkPreludeMiscIdUnique 396 -- data TyLit = ... numTyLitIdKey, strTyLitIdKey :: Unique numTyLitIdKey = mkPreludeMiscIdUnique 400 strTyLitIdKey = mkPreludeMiscIdUnique 401 -- data TyVarBndr = ... plainTVIdKey, kindedTVIdKey :: Unique plainTVIdKey = mkPreludeMiscIdUnique 402 kindedTVIdKey = mkPreludeMiscIdUnique 403 -- data Role = ... nominalRIdKey, representationalRIdKey, phantomRIdKey, inferRIdKey :: Unique nominalRIdKey = mkPreludeMiscIdUnique 404 representationalRIdKey = mkPreludeMiscIdUnique 405 phantomRIdKey = mkPreludeMiscIdUnique 406 inferRIdKey = mkPreludeMiscIdUnique 407 -- data Kind = ... varKIdKey, conKIdKey, tupleKIdKey, arrowKIdKey, listKIdKey, appKIdKey, starKIdKey, constraintKIdKey :: Unique varKIdKey = mkPreludeMiscIdUnique 408 conKIdKey = mkPreludeMiscIdUnique 409 tupleKIdKey = mkPreludeMiscIdUnique 410 arrowKIdKey = mkPreludeMiscIdUnique 411 listKIdKey = mkPreludeMiscIdUnique 412 appKIdKey = mkPreludeMiscIdUnique 413 starKIdKey = mkPreludeMiscIdUnique 414 constraintKIdKey = mkPreludeMiscIdUnique 415 -- data FamilyResultSig = ... noSigIdKey, kindSigIdKey, tyVarSigIdKey :: Unique noSigIdKey = mkPreludeMiscIdUnique 416 kindSigIdKey = mkPreludeMiscIdUnique 417 tyVarSigIdKey = mkPreludeMiscIdUnique 418 -- data InjectivityAnn = ... injectivityAnnIdKey :: Unique injectivityAnnIdKey = mkPreludeMiscIdUnique 419 -- data Callconv = ... cCallIdKey, stdCallIdKey, cApiCallIdKey, primCallIdKey, javaScriptCallIdKey :: Unique cCallIdKey = mkPreludeMiscIdUnique 420 stdCallIdKey = mkPreludeMiscIdUnique 421 cApiCallIdKey = mkPreludeMiscIdUnique 422 primCallIdKey = mkPreludeMiscIdUnique 423 javaScriptCallIdKey = mkPreludeMiscIdUnique 424 -- data Safety = ... unsafeIdKey, safeIdKey, interruptibleIdKey :: Unique unsafeIdKey = mkPreludeMiscIdUnique 430 safeIdKey = mkPreludeMiscIdUnique 431 interruptibleIdKey = mkPreludeMiscIdUnique 432 -- data FunDep = ... funDepIdKey :: Unique funDepIdKey = mkPreludeMiscIdUnique 440 -- data FamFlavour = ... typeFamIdKey, dataFamIdKey :: Unique typeFamIdKey = mkPreludeMiscIdUnique 450 dataFamIdKey = mkPreludeMiscIdUnique 451 -- data TySynEqn = ... tySynEqnIdKey :: Unique tySynEqnIdKey = mkPreludeMiscIdUnique 460 -- quasiquoting quoteExpKey, quotePatKey, quoteDecKey, quoteTypeKey :: Unique quoteExpKey = mkPreludeMiscIdUnique 470 quotePatKey = mkPreludeMiscIdUnique 471 quoteDecKey = mkPreludeMiscIdUnique 472 quoteTypeKey = mkPreludeMiscIdUnique 473 -- data RuleBndr = ... ruleVarIdKey, typedRuleVarIdKey :: Unique ruleVarIdKey = mkPreludeMiscIdUnique 480 typedRuleVarIdKey = mkPreludeMiscIdUnique 481 -- data AnnTarget = ... valueAnnotationIdKey, typeAnnotationIdKey, moduleAnnotationIdKey :: Unique valueAnnotationIdKey = mkPreludeMiscIdUnique 490 typeAnnotationIdKey = mkPreludeMiscIdUnique 491 moduleAnnotationIdKey = mkPreludeMiscIdUnique 492 {- ************************************************************************ * * RdrNames * * ************************************************************************ -} lift_RDR, mkNameG_dRDR, mkNameG_vRDR :: RdrName lift_RDR = nameRdrName liftName mkNameG_dRDR = nameRdrName mkNameG_dName mkNameG_vRDR = nameRdrName mkNameG_vName -- data Exp = ... conE_RDR, litE_RDR, appE_RDR, infixApp_RDR :: RdrName conE_RDR = nameRdrName conEName litE_RDR = nameRdrName litEName appE_RDR = nameRdrName appEName infixApp_RDR = nameRdrName infixAppName -- data Lit = ... stringL_RDR, intPrimL_RDR, wordPrimL_RDR, floatPrimL_RDR, doublePrimL_RDR, stringPrimL_RDR, charPrimL_RDR :: RdrName stringL_RDR = nameRdrName stringLName intPrimL_RDR = nameRdrName intPrimLName wordPrimL_RDR = nameRdrName wordPrimLName floatPrimL_RDR = nameRdrName floatPrimLName doublePrimL_RDR = nameRdrName doublePrimLName stringPrimL_RDR = nameRdrName stringPrimLName charPrimL_RDR = nameRdrName charPrimLName
AlexanderPankiv/ghc
compiler/prelude/THNames.hs
Haskell
bsd-3-clause
41,406
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ur-PK"> <title>Call Home Add-On</title> <maps> <homeID>callhome</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/callhome/src/main/javahelp/org/zaproxy/addon/callhome/resources/help_ur_PK/helpset_ur_PK.hs
Haskell
apache-2.0
966
module Foo () where {-@ measure getfst :: (a, b) -> a getfst (x, y) = x @-} {-@ type Pair a b = {v0 : ({v:a | v = (getfst v0)}, b) | true } @-} {-@ type OPList a b = [(Pair a b)]<\h -> {v: (a, b) | (getfst v) >= (getfst h)}> @-} {-@ type OList a = [a]<\h -> {v: a | (v >= h)}> @-} {-@ getFsts :: OPList a b -> OList a @-} getFsts [] = [] getFsts ((x,_) : xs) = x : getFsts xs
ssaavedra/liquidhaskell
tests/pos/PairMeasure.hs
Haskell
bsd-3-clause
413
module Util.Http ( Links(..), httpGet, httpGetLink, httpPost, httpPostStatus, httpPut, httpDelete ) where import Import.NoFoundation hiding (responseBody, responseStatus, statusCode, checkStatus) import Data.Text (append) import qualified Data.ByteString.Lazy as L import Network.Wreq import Control.Lens data Links = Links { relNext :: Maybe Text, relPrev :: Maybe Text, relFirst :: Maybe Text, relLast :: Maybe Text } deriving (Show) toLinks :: Response body -> Links toLinks r = Links{ relNext=decodeUtf8 <$> (r ^? responseLink "rel" "next" . linkURL), relPrev=decodeUtf8 <$> (r ^? responseLink "rel" "prev" . linkURL), relFirst=decodeUtf8 <$> (r ^? responseLink "rel" "first" . linkURL), relLast=decodeUtf8 <$> (r ^? responseLink "rel" "last" . linkURL) } httpGet :: String -> Maybe Text -> IO L.ByteString httpGet url authToken = do r <- getWith (reqOptions authToken) url return $ r ^. responseBody httpGetLink :: String -> Maybe Text -> IO (L.ByteString, Links) httpGetLink url authToken = do r <- getWith (reqOptions authToken) url return $ (r ^. responseBody, toLinks r) httpPost :: String -> Maybe Text -> L.ByteString -> IO L.ByteString httpPost url authToken payload = do r <- postWith (reqOptions authToken) url payload return $ r ^. responseBody httpPostStatus :: String -> Maybe Text -> L.ByteString -> IO (Int, L.ByteString) httpPostStatus url authToken payload = do r <- postWith (reqOptionsNoCheck authToken) url payload return (r ^. responseStatus . statusCode, r ^. responseBody) httpPut :: String -> Maybe Text -> L.ByteString -> IO L.ByteString httpPut url authToken payload = do r <- putWith (reqOptions authToken) url payload return $ r ^. responseBody httpDelete :: String -> Maybe Text -> IO Int httpDelete url authToken = do r <- deleteWith (reqOptions authToken) url return $ r ^. responseStatus . statusCode reqOptionsNoCheck :: Maybe Text -> Options reqOptionsNoCheck authToken = (reqOptions authToken) & checkStatus .~ Just (\_ _ _ -> Nothing) reqOptions :: Maybe Text -> Options reqOptions Nothing = defaults & header "Content-type" .~ ["application/json"] reqOptions (Just authToken) = defaults & header "Authorization" .~ [authHeader authToken] & header "Content-type" .~ ["application/json"] authHeader :: Text -> ByteString authHeader = encodeUtf8 . append "Token "
vinnymac/glot-www
Util/Http.hs
Haskell
mit
2,470
module OpcodeTypes ( Bytecode(..) , oneOperandBytecodes , zeroOperandBytecodes , twoOperandBytecodes , varOperandBytecodes , extBytecodes , opcodeName ) where import qualified Story as S data Bytecode = OP2_1 | OP2_2 | OP2_3 | OP2_4 | OP2_5 | OP2_6 | OP2_7 | OP2_8 | OP2_9 | OP2_10 | OP2_11 | OP2_12 | OP2_13 | OP2_14 | OP2_15 | OP2_16 | OP2_17 | OP2_18 | OP2_19 | OP2_20 | OP2_21 | OP2_22 | OP2_23 | OP2_24 | OP2_25 | OP2_26 | OP2_27 | OP2_28 | OP1_128 | OP1_129 | OP1_130 | OP1_131 | OP1_132 | OP1_133 | OP1_134 | OP1_135 | OP1_136 | OP1_137 | OP1_138 | OP1_139 | OP1_140 | OP1_141 | OP1_142 | OP1_143 | OP0_176 | OP0_177 | OP0_178 | OP0_179 | OP0_180 | OP0_181 | OP0_182 | OP0_183 | OP0_184 | OP0_185 | OP0_186 | OP0_187 | OP0_188 | OP0_189 | OP0_190 | OP0_191 | VAR_224 | VAR_225 | VAR_226 | VAR_227 | VAR_228 | VAR_229 | VAR_230 | VAR_231 | VAR_232 | VAR_233 | VAR_234 | VAR_235 | VAR_236 | VAR_237 | VAR_238 | VAR_239 | VAR_240 | VAR_241 | VAR_242 | VAR_243 | VAR_244 | VAR_245 | VAR_246 | VAR_247 | VAR_248 | VAR_249 | VAR_250 | VAR_251 | VAR_252 | VAR_253 | VAR_254 | VAR_255 | EXT_0 | EXT_1 | EXT_2 | EXT_3 | EXT_4 | EXT_5 | EXT_6 | EXT_7 | EXT_8 | EXT_9 | EXT_10 | EXT_11 | EXT_12 | EXT_13 | EXT_14 | EXT_16 | EXT_17 | EXT_18 | EXT_19 | EXT_20 | EXT_21 | EXT_22 | EXT_23 | EXT_24 | EXT_25 | EXT_26 | EXT_27 | EXT_28 | EXT_29 | ILLEGAL deriving (Eq) --these lists are used to map from the opcode number to the opcode type oneOperandBytecodes :: [Bytecode] oneOperandBytecodes = [ OP1_128, OP1_129, OP1_130, OP1_131, OP1_132, OP1_133, OP1_134, OP1_135, OP1_136, OP1_137, OP1_138, OP1_139, OP1_140, OP1_141, OP1_142, OP1_143 ] zeroOperandBytecodes :: [Bytecode] zeroOperandBytecodes = [ OP0_176, OP0_177, OP0_178, OP0_179, OP0_180, OP0_181, OP0_182, OP0_183, OP0_184, OP0_185, OP0_186, OP0_187, OP0_188, OP0_189, OP0_190, OP0_191 ] twoOperandBytecodes :: [Bytecode] twoOperandBytecodes =[ ILLEGAL, OP2_1, OP2_2, OP2_3, OP2_4, OP2_5, OP2_6, OP2_7, OP2_8, OP2_9, OP2_10, OP2_11, OP2_12, OP2_13, OP2_14, OP2_15, OP2_16, OP2_17, OP2_18, OP2_19, OP2_20, OP2_21, OP2_22, OP2_23, OP2_24, OP2_25, OP2_26, OP2_27, OP2_28, ILLEGAL, ILLEGAL, ILLEGAL ] varOperandBytecodes :: [Bytecode] varOperandBytecodes = [ VAR_224, VAR_225, VAR_226, VAR_227, VAR_228, VAR_229, VAR_230, VAR_231, VAR_232, VAR_233, VAR_234, VAR_235, VAR_236, VAR_237, VAR_238, VAR_239, VAR_240, VAR_241, VAR_242, VAR_243, VAR_244, VAR_245, VAR_246, VAR_247, VAR_248, VAR_249, VAR_250, VAR_251, VAR_252, VAR_253, VAR_254, VAR_255 ] extBytecodes :: [Bytecode] extBytecodes = [ EXT_0, EXT_1, EXT_2, EXT_3, EXT_4, EXT_5, EXT_6, EXT_7, EXT_8, EXT_9, EXT_10, EXT_11, EXT_12, EXT_13, EXT_14, ILLEGAL, EXT_16, EXT_17, EXT_18, EXT_19, EXT_20, EXT_21, EXT_22, EXT_23, EXT_24, EXT_25, EXT_26, EXT_27, EXT_28, EXT_29, ILLEGAL, ILLEGAL ] opcodeName :: S.Story -> Bytecode -> String opcodeName story opcode = case opcode of ILLEGAL -> "ILLEGAL" OP2_1 -> "je" OP2_2 -> "jl" OP2_3 -> "jg" OP2_4 -> "dec_chk" OP2_5 -> "inc_chk" OP2_6 -> "jin" OP2_7 -> "test" OP2_8 -> "or" OP2_9 -> "and" OP2_10 -> "test_attr" OP2_11 -> "set_attr" OP2_12 -> "clear_attr" OP2_13 -> "store" OP2_14 -> "insert_obj" OP2_15 -> "loadw" OP2_16 -> "loadb" OP2_17 -> "get_prop" OP2_18 -> "get_prop_addr" OP2_19 -> "get_next_prop" OP2_20 -> "add" OP2_21 -> "sub" OP2_22 -> "mul" OP2_23 -> "div" OP2_24 -> "mod" OP2_25 -> "call_2s" OP2_26 -> "call_2n" OP2_27 -> "set_colour" OP2_28 -> "throw" OP1_128 -> "jz" OP1_129 -> "get_sibling" OP1_130 -> "get_child" OP1_131 -> "get_parent" OP1_132 -> "get_prop_len" OP1_133 -> "inc" OP1_134 -> "dec" OP1_135 -> "print_addr" OP1_136 -> "call_1s" OP1_137 -> "remove_obj" OP1_138 -> "print_obj" OP1_139 -> "ret" OP1_140 -> "jump" OP1_141 -> "print_paddr" OP1_142 -> "load" OP1_143 -> if S.isV4OrLower story then "not" else "call_1n" OP0_176 -> "rtrue" OP0_177 -> "rfalse" OP0_178 -> "print" OP0_179 -> "print_ret" OP0_180 -> "nop" OP0_181 -> "save" OP0_182 -> "restore" OP0_183 -> "restart" OP0_184 -> "ret_popped" OP0_185 -> if S.isV4OrLower story then "pop" else "catch" OP0_186 -> "quit" OP0_187 -> "new_line" OP0_188 -> "show_status" OP0_189 -> "verify" OP0_190 -> "EXTENDED" OP0_191 -> "piracy" VAR_224 -> if S.isV3OrLower story then "call" else "call_vs" VAR_225 -> "storew" VAR_226 -> "storeb" VAR_227 -> "put_prop" VAR_228 -> if S.isV4OrLower story then "sread" else "aread" VAR_229 -> "print_char" VAR_230 -> "print_num" VAR_231 -> "random" VAR_232 -> "push" VAR_233 -> "pull" VAR_234 -> "split_window" VAR_235 -> "set_window" VAR_236 -> "call_vs2" VAR_237 -> "erase_window" VAR_238 -> "erase_line" VAR_239 -> "set_cursor" VAR_240 -> "get_cursor" VAR_241 -> "set_text_style" VAR_242 -> "buffer_mode" VAR_243 -> "output_stream" VAR_244 -> "input_stream" VAR_245 -> "sound_effect" VAR_246 -> "read_char" VAR_247 -> "scan_table" VAR_248 -> "not" VAR_249 -> "call_vn" VAR_250 -> "call_vn2" VAR_251 -> "tokenise" VAR_252 -> "encode_text" VAR_253 -> "copy_table" VAR_254 -> "print_table" VAR_255 -> "check_arg_count" EXT_0 -> "save" EXT_1 -> "restore" EXT_2 -> "log_shift" EXT_3 -> "art_shift" EXT_4 -> "set_font" EXT_5 -> "draw_picture" EXT_6 -> "picture_data" EXT_7 -> "erase_picture" EXT_8 -> "set_margins" EXT_9 -> "save_undo" EXT_10 -> "restore_undo" EXT_11 -> "print_unicode" EXT_12 -> "check_unicode" EXT_13 -> "set_true_colour" EXT_14 -> "sound_data" EXT_16 -> "move_window" EXT_17 -> "window_size" EXT_18 -> "window_style" EXT_19 -> "get_wind_prop" EXT_20 -> "scroll_window" EXT_21 -> "pop_stack" EXT_22 -> "read_mouse" EXT_23 -> "mouse_window" EXT_24 -> "push_stack" EXT_25 -> "put_wind_prop" EXT_26 -> "print_form" EXT_27 -> "make_menu" EXT_28 -> "picture_table" EXT_29 -> "buffer_screen"
DylanSp/zmachine-interpreter
src/OpcodeTypes.hs
Haskell
mit
6,699
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE ViewPatterns #-} module Unison.Codebase.SqliteCodebase ( Unison.Codebase.SqliteCodebase.init, unsafeGetConnection, shutdownConnection, ) where import qualified Control.Concurrent import qualified Control.Exception import Control.Monad (filterM, unless, when, (>=>)) import Control.Monad.Except (ExceptT(ExceptT), MonadError (throwError), runExceptT) import qualified Control.Monad.Except as Except import Control.Monad.Extra (ifM, unlessM) import qualified Control.Monad.Extra as Monad import Control.Monad.Reader (ReaderT (runReaderT)) import Control.Monad.State (MonadState) import qualified Control.Monad.State as State import Control.Monad.Trans (MonadTrans (lift)) import Control.Monad.Trans.Maybe (MaybeT (MaybeT)) import Data.Bifunctor (Bifunctor (bimap, first), second) import qualified Data.Either.Combinators as Either import qualified Data.Char as Char import Data.Foldable (Foldable (toList), for_, traverse_) import Data.Functor (void, (<&>), ($>)) import qualified Data.List as List import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromJust) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Text.IO as TextIO import Data.Traversable (for) import Data.Word (Word64) import qualified Database.SQLite.Simple as Sqlite import GHC.Stack (HasCallStack) import qualified System.Console.ANSI as ANSI import System.FilePath ((</>)) import qualified System.FilePath as FilePath import U.Codebase.HashTags (CausalHash (CausalHash, unCausalHash)) import U.Codebase.Sqlite.Operations (EDB) import qualified U.Codebase.Reference as C.Reference import U.Codebase.Sqlite.Connection (Connection (Connection)) import qualified U.Codebase.Sqlite.Connection as Connection import qualified U.Codebase.Sqlite.JournalMode as JournalMode import qualified U.Codebase.Sqlite.ObjectType as OT import qualified U.Codebase.Sqlite.Operations as Ops import qualified U.Codebase.Sqlite.Queries as Q import qualified U.Codebase.Sqlite.Sync22 as Sync22 import qualified U.Codebase.Sync as Sync import qualified U.Codebase.WatchKind as WK import qualified U.Util.Cache as Cache import qualified U.Util.Hash as H2 import qualified U.Util.Monoid as Monoid import qualified U.Util.Set as Set import qualified Unison.Builtin as Builtins import Unison.Codebase (Codebase, CodebasePath) import qualified Unison.Codebase as Codebase1 import Unison.Codebase.Branch (Branch (..)) import qualified Unison.Codebase.Branch as Branch import qualified Unison.Codebase.Causal as Causal import Unison.Codebase.Editor.Git (gitIn, gitTextIn, pullBranch) import Unison.Codebase.Editor.RemoteRepo (ReadRemoteNamespace, WriteRepo (WriteGitRepo), writeToRead, printWriteRepo) import Unison.Codebase.GitError (GitError) import qualified Unison.Codebase.GitError as GitError import qualified Unison.Codebase.Init as Codebase import qualified Unison.Codebase.Init as Codebase1 import Unison.Codebase.Patch (Patch) import qualified Unison.Codebase.Reflog as Reflog import Unison.Codebase.ShortBranchHash (ShortBranchHash) import qualified Unison.Codebase.SqliteCodebase.Branch.Dependencies as BD import qualified Unison.Codebase.SqliteCodebase.Conversions as Cv import qualified Unison.Codebase.SqliteCodebase.SyncEphemeral as SyncEphemeral import Unison.Codebase.SyncMode (SyncMode) import qualified Unison.ConstructorType as CT import Unison.DataDeclaration (Decl) import qualified Unison.DataDeclaration as Decl import Unison.Hash (Hash) import Unison.Parser (Ann) import Unison.Prelude (MaybeT (runMaybeT), fromMaybe, isJust, trace, traceM) import Unison.Reference (Reference) import qualified Unison.Reference as Reference import qualified Unison.Referent as Referent import Unison.ShortHash (ShortHash) import qualified Unison.ShortHash as SH import qualified Unison.ShortHash as ShortHash import Unison.Symbol (Symbol) import Unison.Term (Term) import qualified Unison.Term as Term import Unison.Type (Type) import qualified Unison.Type as Type import qualified Unison.UnisonFile as UF import qualified Unison.Util.Pretty as P import U.Util.Timing (time) import UnliftIO (MonadIO, catchIO, finally, liftIO) import UnliftIO.Directory (canonicalizePath, createDirectoryIfMissing, doesDirectoryExist, doesFileExist) import UnliftIO.STM import U.Codebase.Sqlite.DbId (SchemaVersion(SchemaVersion)) import Control.Exception.Safe (MonadCatch) debug, debugProcessBranches, debugCommitFailedTransaction :: Bool debug = False debugProcessBranches = False debugCommitFailedTransaction = False codebasePath :: FilePath codebasePath = ".unison" </> "v2" </> "unison.sqlite3" v2dir :: FilePath -> FilePath v2dir root = root </> ".unison" </> "v2" init :: HasCallStack => (MonadIO m, MonadCatch m) => Codebase.Init m Symbol Ann init = Codebase.Init getCodebaseOrError createCodebaseOrError v2dir createCodebaseOrError :: (MonadIO m, MonadCatch m) => Codebase.DebugName -> CodebasePath -> m (Either Codebase1.CreateCodebaseError (m (), Codebase m Symbol Ann)) createCodebaseOrError debugName dir = do prettyDir <- P.string <$> canonicalizePath dir let convertError = \case CreateCodebaseAlreadyExists -> Codebase1.CreateCodebaseAlreadyExists CreateCodebaseUnknownSchemaVersion v -> Codebase1.CreateCodebaseOther $ prettyError v prettyError :: SchemaVersion -> Codebase1.Pretty prettyError v = P.wrap $ "I don't know how to handle " <> P.shown v <> "in" <> P.backticked' prettyDir "." Either.mapLeft convertError <$> createCodebaseOrError' debugName dir data CreateCodebaseError = CreateCodebaseAlreadyExists | CreateCodebaseUnknownSchemaVersion SchemaVersion deriving (Show) createCodebaseOrError' :: (MonadIO m, MonadCatch m) => Codebase.DebugName -> CodebasePath -> m (Either CreateCodebaseError (m (), Codebase m Symbol Ann)) createCodebaseOrError' debugName path = do ifM (doesFileExist $ path </> codebasePath) (pure $ Left CreateCodebaseAlreadyExists) do createDirectoryIfMissing True (path </> FilePath.takeDirectory codebasePath) liftIO $ Control.Exception.bracket (unsafeGetConnection (debugName ++ ".createSchema") path) shutdownConnection (runReaderT do Q.createSchema runExceptT (void . Ops.saveRootBranch $ Cv.causalbranch1to2 Branch.empty) >>= \case Left e -> error $ show e Right () -> pure () ) fmap (Either.mapLeft CreateCodebaseUnknownSchemaVersion) (sqliteCodebase debugName path) openOrCreateCodebaseConnection :: MonadIO m => Codebase.DebugName -> FilePath -> m Connection openOrCreateCodebaseConnection debugName path = do unlessM (doesFileExist $ path </> codebasePath) (initSchemaIfNotExist path) unsafeGetConnection debugName path -- get the codebase in dir getCodebaseOrError :: forall m. (MonadIO m, MonadCatch m) => Codebase.DebugName -> CodebasePath -> m (Either Codebase1.Pretty (m (), Codebase m Symbol Ann)) getCodebaseOrError debugName dir = do prettyDir <- liftIO $ P.string <$> canonicalizePath dir let prettyError v = P.wrap $ "I don't know how to handle " <> P.shown v <> "in" <> P.backticked' prettyDir "." doesFileExist (dir </> codebasePath) >>= \case -- If the codebase file doesn't exist, just return any string. The string is currently ignored (see -- Unison.Codebase.Init.getCodebaseOrExit). False -> pure (Left "codebase doesn't exist") True -> fmap (Either.mapLeft prettyError) (sqliteCodebase debugName dir) initSchemaIfNotExist :: MonadIO m => FilePath -> m () initSchemaIfNotExist path = liftIO do unlessM (doesDirectoryExist $ path </> FilePath.takeDirectory codebasePath) $ createDirectoryIfMissing True (path </> FilePath.takeDirectory codebasePath) unlessM (doesFileExist $ path </> codebasePath) $ Control.Exception.bracket (unsafeGetConnection "initSchemaIfNotExist" path) shutdownConnection (runReaderT Q.createSchema) -- checks if a db exists at `path` with the minimum schema codebaseExists :: MonadIO m => CodebasePath -> m Bool codebaseExists root = liftIO do Monad.when debug $ traceM $ "codebaseExists " ++ root Control.Exception.catch @Sqlite.SQLError ( sqliteCodebase "codebaseExists" root >>= \case Left _ -> pure False Right (close, _codebase) -> close $> True ) (const $ pure False) -- 1) buffer up the component -- 2) in the event that the component is complete, then what? -- * can write component provided all of its dependency components are complete. -- if dependency not complete, -- register yourself to be written when that dependency is complete -- an entry for a single hash data BufferEntry a = BufferEntry { -- First, you are waiting for the cycle to fill up with all elements -- Then, you check: are all dependencies of the cycle in the db? -- If yes: write yourself to database and trigger check of dependents -- If no: just wait, do nothing beComponentTargetSize :: Maybe Word64, beComponent :: Map Reference.Pos a, beMissingDependencies :: Set Hash, beWaitingDependents :: Set Hash } deriving (Eq, Show) prettyBufferEntry :: Show a => Hash -> BufferEntry a -> String prettyBufferEntry (h :: Hash) BufferEntry {..} = "BufferEntry " ++ show h ++ "\n" ++ " { beComponentTargetSize = " ++ show beComponentTargetSize ++ "\n" ++ " , beComponent = " ++ if Map.size beComponent < 2 then show $ Map.toList beComponent else mkString (Map.toList beComponent) (Just "\n [ ") " , " (Just "]\n") ++ " , beMissingDependencies =" ++ if Set.size beMissingDependencies < 2 then show $ Set.toList beMissingDependencies else mkString (Set.toList beMissingDependencies) (Just "\n [ ") " , " (Just "]\n") ++ " , beWaitingDependents =" ++ if Set.size beWaitingDependents < 2 then show $ Set.toList beWaitingDependents else mkString (Set.toList beWaitingDependents) (Just "\n [ ") " , " (Just "]\n") ++ " }" where mkString :: (Foldable f, Show a) => f a -> Maybe String -> String -> Maybe String -> String mkString as start middle end = fromMaybe "" start ++ List.intercalate middle (show <$> toList as) ++ fromMaybe "" end type TermBufferEntry = BufferEntry (Term Symbol Ann, Type Symbol Ann) type DeclBufferEntry = BufferEntry (Decl Symbol Ann) unsafeGetConnection :: MonadIO m => Codebase.DebugName -> CodebasePath -> m Connection unsafeGetConnection name root = do let path = root </> codebasePath Monad.when debug $ traceM $ "unsafeGetconnection " ++ name ++ " " ++ root ++ " -> " ++ path (Connection name path -> conn) <- liftIO $ Sqlite.open path runReaderT Q.setFlags conn pure conn shutdownConnection :: MonadIO m => Connection -> m () shutdownConnection conn = do Monad.when debug $ traceM $ "shutdown connection " ++ show conn liftIO $ Sqlite.close (Connection.underlying conn) sqliteCodebase :: (MonadIO m, MonadCatch m) => Codebase.DebugName -> CodebasePath -> m (Either SchemaVersion (m (), Codebase m Symbol Ann)) sqliteCodebase debugName root = do Monad.when debug $ traceM $ "sqliteCodebase " ++ debugName ++ " " ++ root conn <- unsafeGetConnection debugName root termCache <- Cache.semispaceCache 8192 -- pure Cache.nullCache -- to disable typeOfTermCache <- Cache.semispaceCache 8192 declCache <- Cache.semispaceCache 1024 runReaderT Q.schemaVersion conn >>= \case SchemaVersion 1 -> do rootBranchCache <- newTVarIO Nothing -- The v1 codebase interface has operations to read and write individual definitions -- whereas the v2 codebase writes them as complete components. These two fields buffer -- the individual definitions until a complete component has been written. termBuffer :: TVar (Map Hash TermBufferEntry) <- newTVarIO Map.empty declBuffer :: TVar (Map Hash DeclBufferEntry) <- newTVarIO Map.empty cycleLengthCache <- Cache.semispaceCache 8192 declTypeCache <- Cache.semispaceCache 2048 let getTerm :: MonadIO m => Reference.Id -> m (Maybe (Term Symbol Ann)) getTerm (Reference.Id h1@(Cv.hash1to2 -> h2) i _n) = runDB' conn do term2 <- Ops.loadTermByReference (C.Reference.Id h2 i) Cv.term2to1 h1 (getCycleLen "getTerm") getDeclType term2 getCycleLen :: EDB m => String -> Hash -> m Reference.Size getCycleLen source = Cache.apply cycleLengthCache \h -> (Ops.getCycleLen . Cv.hash1to2) h `Except.catchError` \case e@(Ops.DatabaseIntegrityError (Q.NoObjectForPrimaryHashId {})) -> pure . error $ show e ++ " in " ++ source e -> Except.throwError e getDeclType :: EDB m => C.Reference.Reference -> m CT.ConstructorType getDeclType = Cache.apply declTypeCache \case C.Reference.ReferenceBuiltin t -> let err = error $ "I don't know about the builtin type ##" ++ show t ++ ", but I've been asked for it's ConstructorType." in pure . fromMaybe err $ Map.lookup (Reference.Builtin t) Builtins.builtinConstructorType C.Reference.ReferenceDerived i -> getDeclTypeById i getDeclTypeById :: EDB m => C.Reference.Id -> m CT.ConstructorType getDeclTypeById = fmap Cv.decltype2to1 . Ops.getDeclTypeByReference getTypeOfTermImpl :: MonadIO m => Reference.Id -> m (Maybe (Type Symbol Ann)) getTypeOfTermImpl id | debug && trace ("getTypeOfTermImpl " ++ show id) False = undefined getTypeOfTermImpl (Reference.Id (Cv.hash1to2 -> h2) i _n) = runDB' conn do type2 <- Ops.loadTypeOfTermByTermReference (C.Reference.Id h2 i) Cv.ttype2to1 (getCycleLen "getTypeOfTermImpl") type2 getTypeDeclaration :: MonadIO m => Reference.Id -> m (Maybe (Decl Symbol Ann)) getTypeDeclaration (Reference.Id h1@(Cv.hash1to2 -> h2) i _n) = runDB' conn do decl2 <- Ops.loadDeclByReference (C.Reference.Id h2 i) Cv.decl2to1 h1 (getCycleLen "getTypeDeclaration") decl2 putTerm :: MonadIO m => Reference.Id -> Term Symbol Ann -> Type Symbol Ann -> m () putTerm id tm tp | debug && trace (show "SqliteCodebase.putTerm " ++ show id ++ " " ++ show tm ++ " " ++ show tp) False = undefined putTerm (Reference.Id h@(Cv.hash1to2 -> h2) i n') tm tp = runDB conn $ unlessM (Ops.objectExistsForHash h2 >>= if debug then \b -> do traceM $ "objectExistsForHash " ++ show h2 ++ " = " ++ show b; pure b else pure) ( withBuffer termBuffer h \be@(BufferEntry size comp missing waiting) -> do Monad.when debug $ traceM $ "adding to BufferEntry" ++ show be let size' = Just n' -- if size was previously set, it's expected to match size'. case size of Just n | n /= n' -> error $ "targetSize for term " ++ show h ++ " was " ++ show size ++ ", but now " ++ show size' _ -> pure () let comp' = Map.insert i (tm, tp) comp -- for the component element that's been passed in, add its dependencies to missing' missingTerms' <- filterM (fmap not . Ops.objectExistsForHash . Cv.hash1to2) [h | Reference.Derived h _i _n <- Set.toList $ Term.termDependencies tm] missingTypes' <- filterM (fmap not . Ops.objectExistsForHash . Cv.hash1to2) $ [h | Reference.Derived h _i _n <- Set.toList $ Term.typeDependencies tm] ++ [h | Reference.Derived h _i _n <- Set.toList $ Type.dependencies tp] let missing' = missing <> Set.fromList (missingTerms' <> missingTypes') -- notify each of the dependencies that h depends on them. traverse (addBufferDependent h termBuffer) missingTerms' traverse (addBufferDependent h declBuffer) missingTypes' putBuffer termBuffer h (BufferEntry size' comp' missing' waiting) tryFlushTermBuffer h ) putBuffer :: (MonadIO m, Show a) => TVar (Map Hash (BufferEntry a)) -> Hash -> BufferEntry a -> m () putBuffer tv h e = do Monad.when debug $ traceM $ "putBuffer " ++ prettyBufferEntry h e atomically $ modifyTVar tv (Map.insert h e) withBuffer :: (MonadIO m, Show a) => TVar (Map Hash (BufferEntry a)) -> Hash -> (BufferEntry a -> m b) -> m b withBuffer tv h f = do Monad.when debug $ readTVarIO tv >>= \tv -> traceM $ "tv = " ++ show tv Map.lookup h <$> readTVarIO tv >>= \case Just e -> do Monad.when debug $ traceM $ "SqliteCodebase.withBuffer " ++ prettyBufferEntry h e f e Nothing -> do Monad.when debug $ traceM $ "SqliteCodebase.with(new)Buffer " ++ show h f (BufferEntry Nothing Map.empty Set.empty Set.empty) removeBuffer :: (MonadIO m, Show a) => TVar (Map Hash (BufferEntry a)) -> Hash -> m () removeBuffer _tv h | debug && trace ("removeBuffer " ++ show h) False = undefined removeBuffer tv h = do Monad.when debug $ readTVarIO tv >>= \tv -> traceM $ "before delete: " ++ show tv atomically $ modifyTVar tv (Map.delete h) Monad.when debug $ readTVarIO tv >>= \tv -> traceM $ "after delete: " ++ show tv addBufferDependent :: (MonadIO m, Show a) => Hash -> TVar (Map Hash (BufferEntry a)) -> Hash -> m () addBufferDependent dependent tv dependency = withBuffer tv dependency \be -> do putBuffer tv dependency be {beWaitingDependents = Set.insert dependent $ beWaitingDependents be} tryFlushBuffer :: (EDB m, Show a) => TVar (Map Hash (BufferEntry a)) -> (H2.Hash -> [a] -> m ()) -> (Hash -> m ()) -> Hash -> m () tryFlushBuffer _ _ _ h | debug && trace ("tryFlushBuffer " ++ show h) False = undefined tryFlushBuffer buf saveComponent tryWaiting h@(Cv.hash1to2 -> h2) = -- skip if it has already been flushed unlessM (Ops.objectExistsForHash h2) $ withBuffer buf h try where try (BufferEntry size comp (Set.delete h -> missing) waiting) = case size of Just size -> do missing' <- filterM (fmap not . Ops.objectExistsForHash . Cv.hash1to2) (toList missing) Monad.when debug do traceM $ "tryFlushBuffer.missing' = " ++ show missing' traceM $ "tryFlushBuffer.size = " ++ show size traceM $ "tryFlushBuffer.length comp = " ++ show (length comp) if null missing' && size == fromIntegral (length comp) then do saveComponent h2 (toList comp) removeBuffer buf h Monad.when debug $ traceM $ "tryFlushBuffer.notify waiting " ++ show waiting traverse_ tryWaiting waiting else -- update putBuffer buf h $ BufferEntry (Just size) comp (Set.fromList missing') waiting Nothing -> -- it's never even been added, so there's nothing to do. pure () tryFlushTermBuffer :: EDB m => Hash -> m () tryFlushTermBuffer h | debug && trace ("tryFlushTermBuffer " ++ show h) False = undefined tryFlushTermBuffer h = tryFlushBuffer termBuffer ( \h2 -> void . Ops.saveTermComponent h2 . fmap (first (Cv.term1to2 h) . second Cv.ttype1to2) ) tryFlushTermBuffer h tryFlushDeclBuffer :: EDB m => Hash -> m () tryFlushDeclBuffer h | debug && trace ("tryFlushDeclBuffer " ++ show h) False = undefined tryFlushDeclBuffer h = tryFlushBuffer declBuffer (\h2 -> void . Ops.saveDeclComponent h2 . fmap (Cv.decl1to2 h)) (\h -> tryFlushTermBuffer h >> tryFlushDeclBuffer h) h putTypeDeclaration :: MonadIO m => Reference.Id -> Decl Symbol Ann -> m () putTypeDeclaration (Reference.Id h@(Cv.hash1to2 -> h2) i n') decl = runDB conn $ unlessM (Ops.objectExistsForHash h2) ( withBuffer declBuffer h \(BufferEntry size comp missing waiting) -> do let size' = Just n' case size of Just n | n /= n' -> error $ "targetSize for type " ++ show h ++ " was " ++ show size ++ ", but now " ++ show size' _ -> pure () let comp' = Map.insert i decl comp moreMissing <- filterM (fmap not . Ops.objectExistsForHash . Cv.hash1to2) $ [h | Reference.Derived h _i _n <- Set.toList $ Decl.declDependencies decl] let missing' = missing <> Set.fromList moreMissing traverse (addBufferDependent h declBuffer) moreMissing putBuffer declBuffer h (BufferEntry size' comp' missing' waiting) tryFlushDeclBuffer h ) getRootBranch :: MonadIO m => TVar (Maybe (Q.DataVersion, Branch m)) -> m (Either Codebase1.GetRootBranchError (Branch m)) getRootBranch rootBranchCache = readTVarIO rootBranchCache >>= \case Nothing -> forceReload Just (v, b) -> do -- check to see if root namespace hash has been externally modified -- and reload it if necessary v' <- runDB conn Ops.dataVersion if v == v' then pure (Right b) else do newRootHash <- runDB conn Ops.loadRootCausalHash if Branch.headHash b == Cv.branchHash2to1 newRootHash then pure (Right b) else do traceM $ "database was externally modified (" ++ show v ++ " -> " ++ show v' ++ ")" forceReload where forceReload = time "Get root branch" do b <- fmap (Either.mapLeft err) . runExceptT . flip runReaderT conn . fmap (Branch.transform (runDB conn)) $ Cv.causalbranch2to1 getCycleLen getDeclType =<< Ops.loadRootCausal v <- runDB conn Ops.dataVersion for_ b (atomically . writeTVar rootBranchCache . Just . (v,)) pure b err :: Ops.Error -> Codebase1.GetRootBranchError err = \case Ops.DatabaseIntegrityError Q.NoNamespaceRoot -> Codebase1.NoRootBranch Ops.DecodeError (Ops.ErrBranch oId) _bytes _msg -> Codebase1.CouldntParseRootBranch $ "Couldn't decode " ++ show oId ++ ": " ++ _msg Ops.ExpectedBranch ch _bh -> Codebase1.CouldntLoadRootBranch $ Cv.causalHash2to1 ch e -> error $ show e putRootBranch :: MonadIO m => TVar (Maybe (Q.DataVersion, Branch m)) -> Branch m -> m () putRootBranch rootBranchCache branch1 = do -- todo: check to see if root namespace hash has been externally modified -- and do something (merge?) it if necessary. But for now, we just overwrite it. runDB conn . void . Ops.saveRootBranch . Cv.causalbranch1to2 $ Branch.transform (lift . lift) branch1 atomically $ modifyTVar rootBranchCache (fmap . second $ const branch1) rootBranchUpdates :: MonadIO m => TVar (Maybe (Q.DataVersion, a)) -> m (IO (), IO (Set Branch.Hash)) rootBranchUpdates _rootBranchCache = do -- branchHeadChanges <- TQueue.newIO -- (cancelWatch, watcher) <- Watch.watchDirectory' (v2dir root) -- watcher1 <- -- liftIO . forkIO -- $ forever -- $ do -- -- void ignores the name and time of the changed file, -- -- and assume 'unison.sqlite3' has changed -- (filename, time) <- watcher -- traceM $ "SqliteCodebase.watcher " ++ show (filename, time) -- readTVarIO rootBranchCache >>= \case -- Nothing -> pure () -- Just (v, _) -> do -- -- this use of `conn` in a separate thread may be problematic. -- -- hopefully sqlite will produce an obvious error message if it is. -- v' <- runDB conn Ops.dataVersion -- if v /= v' then -- atomically -- . TQueue.enqueue branchHeadChanges =<< runDB conn Ops.loadRootCausalHash -- else pure () -- -- case hashFromFilePath filePath of -- -- Nothing -> failWith $ CantParseBranchHead filePath -- -- Just h -> -- -- atomically . TQueue.enqueue branchHeadChanges $ Branch.Hash h -- -- smooth out intermediate queue -- pure -- ( cancelWatch >> killThread watcher1 -- , Set.fromList <$> Watch.collectUntilPause branchHeadChanges 400000 -- ) pure (cleanup, liftIO newRootsDiscovered) where newRootsDiscovered = do Control.Concurrent.threadDelay maxBound -- hold off on returning pure mempty -- returning nothing cleanup = pure () -- if this blows up on cromulent hashes, then switch from `hashToHashId` -- to one that returns Maybe. getBranchForHash :: MonadIO m => Branch.Hash -> m (Maybe (Branch m)) getBranchForHash h = runDB conn do Ops.loadCausalBranchByCausalHash (Cv.branchHash1to2 h) >>= \case Just b -> pure . Just . Branch.transform (runDB conn) =<< Cv.causalbranch2to1 getCycleLen getDeclType b Nothing -> pure Nothing putBranch :: MonadIO m => Branch m -> m () putBranch = runDB conn . putBranch' isCausalHash :: MonadIO m => Branch.Hash -> m Bool isCausalHash = runDB conn . isCausalHash' getPatch :: MonadIO m => Branch.EditHash -> m (Maybe Patch) getPatch h = runDB conn . runMaybeT $ MaybeT (Ops.primaryHashToMaybePatchObjectId (Cv.patchHash1to2 h)) >>= Ops.loadPatchById >>= Cv.patch2to1 getCycleLen putPatch :: MonadIO m => Branch.EditHash -> Patch -> m () putPatch h p = runDB conn . void $ Ops.savePatch (Cv.patchHash1to2 h) (Cv.patch1to2 p) patchExists :: MonadIO m => Branch.EditHash -> m Bool patchExists = runDB conn . patchExists' dependentsImpl :: MonadIO m => Reference -> m (Set Reference.Id) dependentsImpl r = runDB conn $ Set.traverse (Cv.referenceid2to1 (getCycleLen "dependentsImpl")) =<< Ops.dependents (Cv.reference1to2 r) syncFromDirectory :: MonadIO m => Codebase1.CodebasePath -> SyncMode -> Branch m -> m () syncFromDirectory srcRoot _syncMode b = flip State.evalStateT emptySyncProgressState $ do srcConn <- unsafeGetConnection (debugName ++ ".sync.src") srcRoot syncInternal syncProgress srcConn conn $ Branch.transform lift b syncToDirectory :: MonadIO m => Codebase1.CodebasePath -> SyncMode -> Branch m -> m () syncToDirectory destRoot _syncMode b = flip State.evalStateT emptySyncProgressState $ do initSchemaIfNotExist destRoot destConn <- unsafeGetConnection (debugName ++ ".sync.dest") destRoot syncInternal syncProgress conn destConn $ Branch.transform lift b watches :: MonadIO m => UF.WatchKind -> m [Reference.Id] watches w = runDB conn $ Ops.listWatches (Cv.watchKind1to2 w) >>= traverse (Cv.referenceid2to1 (getCycleLen "watches")) getWatch :: MonadIO m => UF.WatchKind -> Reference.Id -> m (Maybe (Term Symbol Ann)) getWatch k r@(Reference.Id h _i _n) | elem k standardWatchKinds = runDB' conn $ Ops.loadWatch (Cv.watchKind1to2 k) (Cv.referenceid1to2 r) >>= Cv.term2to1 h (getCycleLen "getWatch") getDeclType getWatch _unknownKind _ = pure Nothing standardWatchKinds = [UF.RegularWatch, UF.TestWatch] putWatch :: MonadIO m => UF.WatchKind -> Reference.Id -> Term Symbol Ann -> m () putWatch k r@(Reference.Id h _i _n) tm | elem k standardWatchKinds = runDB conn $ Ops.saveWatch (Cv.watchKind1to2 k) (Cv.referenceid1to2 r) (Cv.term1to2 h tm) putWatch _unknownKind _ _ = pure () clearWatches :: MonadIO m => m () clearWatches = runDB conn Ops.clearWatches getReflog :: MonadIO m => m [Reflog.Entry] getReflog = liftIO $ ( do contents <- TextIO.readFile (reflogPath root) let lines = Text.lines contents let entries = parseEntry <$> lines pure entries ) `catchIO` const (pure []) where parseEntry t = fromMaybe (err t) (Reflog.fromText t) err t = error $ "I couldn't understand this line in " ++ reflogPath root ++ "\n\n" ++ Text.unpack t appendReflog :: MonadIO m => Text -> Branch m -> Branch m -> m () appendReflog reason old new = liftIO $ TextIO.appendFile (reflogPath root) (t <> "\n") where t = Reflog.toText $ Reflog.Entry (Branch.headHash old) (Branch.headHash new) reason reflogPath :: CodebasePath -> FilePath reflogPath root = root </> "reflog" termsOfTypeImpl :: MonadIO m => Reference -> m (Set Referent.Id) termsOfTypeImpl r = runDB conn $ Ops.termsHavingType (Cv.reference1to2 r) >>= Set.traverse (Cv.referentid2to1 (getCycleLen "termsOfTypeImpl") getDeclType) termsMentioningTypeImpl :: MonadIO m => Reference -> m (Set Referent.Id) termsMentioningTypeImpl r = runDB conn $ Ops.termsMentioningType (Cv.reference1to2 r) >>= Set.traverse (Cv.referentid2to1 (getCycleLen "termsMentioningTypeImpl") getDeclType) hashLength :: Applicative m => m Int hashLength = pure 10 branchHashLength :: Applicative m => m Int branchHashLength = pure 10 defnReferencesByPrefix :: MonadIO m => OT.ObjectType -> ShortHash -> m (Set Reference.Id) defnReferencesByPrefix _ (ShortHash.Builtin _) = pure mempty defnReferencesByPrefix ot (ShortHash.ShortHash prefix (fmap Cv.shortHashSuffix1to2 -> cycle) _cid) = Monoid.fromMaybe <$> runDB' conn do refs <- do Ops.componentReferencesByPrefix ot prefix cycle >>= traverse (C.Reference.idH Ops.loadHashByObjectId) >>= pure . Set.fromList Set.fromList <$> traverse (Cv.referenceid2to1 (getCycleLen "defnReferencesByPrefix")) (Set.toList refs) termReferencesByPrefix :: MonadIO m => ShortHash -> m (Set Reference.Id) termReferencesByPrefix = defnReferencesByPrefix OT.TermComponent declReferencesByPrefix :: MonadIO m => ShortHash -> m (Set Reference.Id) declReferencesByPrefix = defnReferencesByPrefix OT.DeclComponent referentsByPrefix :: MonadIO m => ShortHash -> m (Set Referent.Id) referentsByPrefix SH.Builtin {} = pure mempty referentsByPrefix (SH.ShortHash prefix (fmap Cv.shortHashSuffix1to2 -> cycle) cid) = runDB conn do termReferents <- Ops.termReferentsByPrefix prefix cycle >>= traverse (Cv.referentid2to1 (getCycleLen "referentsByPrefix") getDeclType) declReferents' <- Ops.declReferentsByPrefix prefix cycle (read . Text.unpack <$> cid) let declReferents = [ Referent.Con' (Reference.Id (Cv.hash2to1 h) pos len) (fromIntegral cid) (Cv.decltype2to1 ct) | (h, pos, len, ct, cids) <- declReferents', cid <- cids ] pure . Set.fromList $ termReferents <> declReferents branchHashesByPrefix :: MonadIO m => ShortBranchHash -> m (Set Branch.Hash) branchHashesByPrefix sh = runDB conn do -- given that a Branch is shallow, it's really `CausalHash` that you'd -- refer to to specify a full namespace w/ history. -- but do we want to be able to refer to a namespace without its history? cs <- Ops.causalHashesByPrefix (Cv.sbh1to2 sh) pure $ Set.map (Causal.RawHash . Cv.hash2to1 . unCausalHash) cs sqlLca :: MonadIO m => Branch.Hash -> Branch.Hash -> m (Maybe Branch.Hash) sqlLca h1 h2 = liftIO $ Control.Exception.bracket open close \(c1, c2) -> runDB conn . (fmap . fmap) Cv.causalHash2to1 $ Ops.lca (Cv.causalHash1to2 h1) (Cv.causalHash1to2 h2) c1 c2 where open = (,) <$> unsafeGetConnection (debugName ++ ".lca.left") root <*> unsafeGetConnection (debugName ++ ".lca.left") root close (c1, c2) = shutdownConnection c1 *> shutdownConnection c2 let finalizer :: MonadIO m => m () finalizer = do shutdownConnection conn decls <- readTVarIO declBuffer terms <- readTVarIO termBuffer let printBuffer header b = liftIO if b /= mempty then putStrLn header >> putStrLn "" >> print b else pure () printBuffer "Decls:" decls printBuffer "Terms:" terms pure . Right $ ( finalizer, let code = Codebase1.Codebase (Cache.applyDefined termCache getTerm) (Cache.applyDefined typeOfTermCache getTypeOfTermImpl) (Cache.applyDefined declCache getTypeDeclaration) putTerm putTypeDeclaration (getRootBranch rootBranchCache) (putRootBranch rootBranchCache) (rootBranchUpdates rootBranchCache) getBranchForHash putBranch isCausalHash getPatch putPatch patchExists dependentsImpl syncFromDirectory syncToDirectory viewRemoteBranch' (\b r _s -> pushGitRootBranch conn b r) watches getWatch putWatch clearWatches getReflog appendReflog termsOfTypeImpl termsMentioningTypeImpl hashLength termReferencesByPrefix declReferencesByPrefix referentsByPrefix branchHashLength branchHashesByPrefix (Just sqlLca) (Just \l r -> runDB conn $ fromJust <$> before l r) in code ) v -> shutdownConnection conn $> Left v -- well one or the other. :zany_face: the thinking being that they wouldn't hash-collide termExists', declExists' :: MonadIO m => Hash -> ReaderT Connection (ExceptT Ops.Error m) Bool termExists' = fmap isJust . Ops.primaryHashToMaybeObjectId . Cv.hash1to2 declExists' = termExists' patchExists' :: MonadIO m => Branch.EditHash -> ReaderT Connection (ExceptT Ops.Error m) Bool patchExists' h = fmap isJust $ Ops.primaryHashToMaybePatchObjectId (Cv.patchHash1to2 h) putBranch' :: MonadIO m => Branch m -> ReaderT Connection (ExceptT Ops.Error m) () putBranch' branch1 = void . Ops.saveBranch . Cv.causalbranch1to2 $ Branch.transform (lift . lift) branch1 isCausalHash' :: MonadIO m => Branch.Hash -> ReaderT Connection (ExceptT Ops.Error m) Bool isCausalHash' (Causal.RawHash h) = Q.loadHashIdByHash (Cv.hash1to2 h) >>= \case Nothing -> pure False Just hId -> Q.isCausalHash hId before :: MonadIO m => Branch.Hash -> Branch.Hash -> ReaderT Connection m (Maybe Bool) before h1 h2 = Ops.before (Cv.causalHash1to2 h1) (Cv.causalHash1to2 h2) syncInternal :: forall m. MonadIO m => Sync.Progress m Sync22.Entity -> Connection -> Connection -> Branch m -> m () syncInternal progress srcConn destConn b = time "syncInternal" do runDB srcConn $ Q.savepoint "sync" runDB destConn $ Q.savepoint "sync" result <- runExceptT do let syncEnv = Sync22.Env srcConn destConn (16 * 1024 * 1024) -- we want to use sync22 wherever possible -- so for each branch, we'll check if it exists in the destination branch -- or if it exists in the source branch, then we can sync22 it -- oh god but we have to figure out the dbid -- if it doesn't exist in the dest or source branch, -- then just use putBranch to the dest let se :: forall m a. Functor m => (ExceptT Sync22.Error m a -> ExceptT SyncEphemeral.Error m a) se = Except.withExceptT SyncEphemeral.Sync22Error let r :: forall m a. (ReaderT Sync22.Env m a -> m a) r = flip runReaderT syncEnv processBranches :: forall m. MonadIO m => Sync.Sync (ReaderT Sync22.Env (ExceptT Sync22.Error m)) Sync22.Entity -> Sync.Progress (ReaderT Sync22.Env (ExceptT Sync22.Error m)) Sync22.Entity -> [Entity m] -> ExceptT Sync22.Error m () processBranches _ _ [] = pure () processBranches sync progress (b0@(B h mb) : rest) = do when debugProcessBranches do traceM $ "processBranches " ++ show b0 traceM $ " queue: " ++ show rest ifM @(ExceptT Sync22.Error m) (lift . runDB destConn $ isCausalHash' h) do when debugProcessBranches $ traceM $ " " ++ show b0 ++ " already exists in dest db" processBranches sync progress rest do when debugProcessBranches $ traceM $ " " ++ show b0 ++ " doesn't exist in dest db" let h2 = CausalHash . Cv.hash1to2 $ Causal.unRawHash h lift (flip runReaderT srcConn (Q.loadCausalHashIdByCausalHash h2)) >>= \case Just chId -> do when debugProcessBranches $ traceM $ " " ++ show b0 ++ " exists in source db, so delegating to direct sync" r $ Sync.sync' sync progress [Sync22.C chId] processBranches sync progress rest Nothing -> lift mb >>= \b -> do when debugProcessBranches $ traceM $ " " ++ show b0 ++ " doesn't exist in either db, so delegating to Codebase.putBranch" let (branchDeps, BD.to' -> BD.Dependencies' es ts ds) = BD.fromBranch b when debugProcessBranches do traceM $ " branchDeps: " ++ show (fst <$> branchDeps) traceM $ " terms: " ++ show ts traceM $ " decls: " ++ show ds traceM $ " edits: " ++ show es (cs, es, ts, ds) <- lift $ runDB destConn do cs <- filterM (fmap not . isCausalHash' . fst) branchDeps es <- filterM (fmap not . patchExists') es ts <- filterM (fmap not . termExists') ts ds <- filterM (fmap not . declExists') ds pure (cs, es, ts, ds) if null cs && null es && null ts && null ds then do lift . runDB destConn $ putBranch' b processBranches @m sync progress rest else do let bs = map (uncurry B) cs os = map O (es <> ts <> ds) processBranches @m sync progress (os ++ bs ++ b0 : rest) processBranches sync progress (O h : rest) = do when debugProcessBranches $ traceM $ "processBranches O " ++ take 10 (show h) (runExceptT $ flip runReaderT srcConn (Q.expectHashIdByHash (Cv.hash1to2 h) >>= Q.expectObjectIdForAnyHashId)) >>= \case Left e -> error $ show e Right oId -> do r $ Sync.sync' sync progress [Sync22.O oId] processBranches sync progress rest sync <- se . r $ Sync22.sync22 let progress' = Sync.transformProgress (lift . lift) progress bHash = Branch.headHash b se $ time "SyncInternal.processBranches" $ processBranches sync progress' [B bHash (pure b)] testWatchRefs <- time "SyncInternal enumerate testWatches" $ lift . fmap concat $ for [WK.TestWatch] \wk -> fmap (Sync22.W wk) <$> flip runReaderT srcConn (Q.loadWatchesByWatchKind wk) se . r $ Sync.sync sync progress' testWatchRefs let onSuccess a = runDB destConn (Q.release "sync") *> pure a onFailure e = do if debugCommitFailedTransaction then runDB destConn (Q.release "sync") else runDB destConn (Q.rollbackRelease "sync") error (show e) runDB srcConn $ Q.rollbackRelease "sync" -- (we don't write to the src anyway) either onFailure onSuccess result runDB' :: MonadIO m => Connection -> MaybeT (ReaderT Connection (ExceptT Ops.Error m)) a -> m (Maybe a) runDB' conn = runDB conn . runMaybeT runDB :: MonadIO m => Connection -> ReaderT Connection (ExceptT Ops.Error m) a -> m a runDB conn = (runExceptT >=> err) . flip runReaderT conn where err = \case Left err -> error $ show err; Right a -> pure a data Entity m = B Branch.Hash (m (Branch m)) | O Hash instance Show (Entity m) where show (B h _) = "B " ++ take 10 (show h) show (O h) = "O " ++ take 10 (show h) data SyncProgressState = SyncProgressState { _needEntities :: Maybe (Set Sync22.Entity), _doneEntities :: Either Int (Set Sync22.Entity), _warnEntities :: Either Int (Set Sync22.Entity) } emptySyncProgressState :: SyncProgressState emptySyncProgressState = SyncProgressState (Just mempty) (Right mempty) (Right mempty) syncProgress :: MonadState SyncProgressState m => MonadIO m => Sync.Progress m Sync22.Entity syncProgress = Sync.Progress need done warn allDone where quiet = False maxTrackedHashCount = 1024 * 1024 size :: SyncProgressState -> Int size = \case SyncProgressState Nothing (Left i) (Left j) -> i + j SyncProgressState (Just need) (Right done) (Right warn) -> Set.size need + Set.size done + Set.size warn SyncProgressState _ _ _ -> undefined need, done, warn :: (MonadState SyncProgressState m, MonadIO m) => Sync22.Entity -> m () need h = do unless quiet $ Monad.whenM (State.gets size <&> (== 0)) $ liftIO $ putStr "\n" State.get >>= \case SyncProgressState Nothing Left {} Left {} -> pure () SyncProgressState (Just need) (Right done) (Right warn) -> if Set.size need + Set.size done + Set.size warn > maxTrackedHashCount then State.put $ SyncProgressState Nothing (Left $ Set.size done) (Left $ Set.size warn) else if Set.member h done || Set.member h warn then pure () else State.put $ SyncProgressState (Just $ Set.insert h need) (Right done) (Right warn) SyncProgressState _ _ _ -> undefined unless quiet printSynced done h = do unless quiet $ Monad.whenM (State.gets size <&> (== 0)) $ liftIO $ putStr "\n" State.get >>= \case SyncProgressState Nothing (Left done) warn -> State.put $ SyncProgressState Nothing (Left (done + 1)) warn SyncProgressState (Just need) (Right done) warn -> State.put $ SyncProgressState (Just $ Set.delete h need) (Right $ Set.insert h done) warn SyncProgressState _ _ _ -> undefined unless quiet printSynced warn h = do unless quiet $ Monad.whenM (State.gets size <&> (== 0)) $ liftIO $ putStr "\n" State.get >>= \case SyncProgressState Nothing done (Left warn) -> State.put $ SyncProgressState Nothing done (Left $ warn + 1) SyncProgressState (Just need) done (Right warn) -> State.put $ SyncProgressState (Just $ Set.delete h need) done (Right $ Set.insert h warn) SyncProgressState _ _ _ -> undefined unless quiet printSynced allDone = do State.get >>= liftIO . putStrLn . renderState (" " ++ "Done syncing ") printSynced :: (MonadState SyncProgressState m, MonadIO m) => m () printSynced = State.get >>= \s -> liftIO $ finally do ANSI.hideCursor; putStr . renderState (" " ++ "Synced ") $ s ANSI.showCursor renderState :: String -> SyncProgressState -> String renderState prefix = \case SyncProgressState Nothing (Left done) (Left warn) -> "\r" ++ prefix ++ show done ++ " entities" ++ if warn > 0 then " with " ++ show warn ++ " warnings." else "." SyncProgressState (Just _need) (Right done) (Right warn) -> "\r" ++ prefix ++ show (Set.size done + Set.size warn) ++ " entities" ++ if Set.size warn > 0 then " with " ++ show (Set.size warn) ++ " warnings." else "." SyncProgressState need done warn -> "invalid SyncProgressState " ++ show (fmap v need, bimap id v done, bimap id v warn) where v = const () viewRemoteBranch' :: forall m. (MonadIO m, MonadCatch m) => ReadRemoteNamespace -> m (Either GitError (m (), Branch m, CodebasePath)) viewRemoteBranch' (repo, sbh, path) = runExceptT do -- set up the cache dir remotePath <- time "Git fetch" $ pullBranch repo ifM (codebaseExists remotePath) do lift (sqliteCodebase "viewRemoteBranch.gitCache" remotePath) >>= \case Left sv -> ExceptT . pure . Left $ GitError.UnrecognizedSchemaVersion repo remotePath sv Right (closeCodebase, codebase) -> do -- try to load the requested branch from it branch <- time "Git fetch (sbh)" $ case sbh of -- no sub-branch was specified, so use the root. Nothing -> lift (time "Get remote root branch" $ Codebase1.getRootBranch codebase) >>= \case -- this NoRootBranch case should probably be an error too. Left Codebase1.NoRootBranch -> pure Branch.empty Left (Codebase1.CouldntLoadRootBranch h) -> throwError $ GitError.CouldntLoadRootBranch repo h Left (Codebase1.CouldntParseRootBranch s) -> throwError $ GitError.CouldntParseRootBranch repo s Right b -> pure b -- load from a specific `ShortBranchHash` Just sbh -> do branchCompletions <- lift $ Codebase1.branchHashesByPrefix codebase sbh case toList branchCompletions of [] -> throwError $ GitError.NoRemoteNamespaceWithHash repo sbh [h] -> lift (Codebase1.getBranchForHash codebase h) >>= \case Just b -> pure b Nothing -> throwError $ GitError.NoRemoteNamespaceWithHash repo sbh _ -> throwError $ GitError.RemoteNamespaceHashAmbiguous repo sbh branchCompletions pure (closeCodebase, Branch.getAt' path branch, remotePath) -- else there's no initialized codebase at this repo; we pretend there's an empty one. -- I'm thinking we should probably return an error value instead. (pure (pure (), Branch.empty, remotePath)) -- Given a branch that is "after" the existing root of a given git repo, -- stage and push the branch (as the new root) + dependencies to the repo. pushGitRootBranch :: (MonadIO m, MonadCatch m) => Connection -> Branch m -> WriteRepo -> m (Either GitError ()) pushGitRootBranch srcConn branch repo = runExceptT @GitError do -- pull the remote repo to the staging directory -- open a connection to the staging codebase -- create a savepoint on the staging codebase -- sync the branch to the staging codebase using `syncInternal`, which probably needs to be passed in instead of `syncToDirectory` -- do a `before` check on the staging codebase -- if it passes, then release the savepoint (commit it), clean up, and git-push the result -- if it fails, rollback to the savepoint and clean up. -- set up the cache dir remotePath <- time "Git fetch" $ pullBranch (writeToRead repo) destConn <- openOrCreateCodebaseConnection "push.dest" remotePath flip runReaderT destConn $ Q.savepoint "push" lift . flip State.execStateT emptySyncProgressState $ syncInternal syncProgress srcConn destConn (Branch.transform lift branch) flip runReaderT destConn do let newRootHash = Branch.headHash branch -- the call to runDB "handles" the possible DB error by bombing (fmap . fmap) Cv.branchHash2to1 (runDB destConn Ops.loadMaybeRootCausalHash) >>= \case Nothing -> do setRepoRoot newRootHash Q.release "push" Just oldRootHash -> do before oldRootHash newRootHash >>= \case Nothing -> error $ "I couldn't find the hash " ++ show newRootHash ++ " that I just synced to the cached copy of " ++ repoString ++ " in " ++ show remotePath ++ "." Just False -> do Q.rollbackRelease "push" throwError $ GitError.PushDestinationHasNewStuff repo Just True -> do setRepoRoot newRootHash Q.release "push" Q.setJournalMode JournalMode.DELETE liftIO do shutdownConnection destConn void $ push remotePath repo where repoString = Text.unpack $ printWriteRepo repo setRepoRoot :: Q.DB m => Branch.Hash -> m () setRepoRoot h = do let h2 = Cv.causalHash1to2 h err = error $ "Called SqliteCodebase.setNamespaceRoot on unknown causal hash " ++ show h2 chId <- fromMaybe err <$> Q.loadCausalHashIdByCausalHash h2 Q.setNamespaceRoot chId -- This function makes sure that the result of git status is valid. -- Valid lines are any of: -- -- ?? .unison/v2/unison.sqlite3 (initial commit to an empty repo) -- M .unison/v2/unison.sqlite3 (updating an existing repo) -- D .unison/v2/unison.sqlite3-wal (cleaning up the WAL from before bugfix) -- D .unison/v2/unison.sqlite3-shm (ditto) -- -- Invalid lines are like: -- -- ?? .unison/v2/unison.sqlite3-wal -- -- Which will only happen if the write-ahead log hasn't been -- fully folded into the unison.sqlite3 file. -- -- Returns `Just (hasDeleteWal, hasDeleteShm)` on success, -- `Nothing` otherwise. hasDeleteWal means there's the line: -- D .unison/v2/unison.sqlite3-wal -- and hasDeleteShm is `True` if there's the line: -- D .unison/v2/unison.sqlite3-shm -- parseStatus :: Text -> Maybe (Bool, Bool) parseStatus status = if all okLine statusLines then Just (hasDeleteWal, hasDeleteShm) else Nothing where statusLines = Text.unpack <$> Text.lines status t = dropWhile Char.isSpace okLine (t -> '?' : '?' : (t -> p)) | p == codebasePath = True okLine (t -> 'M' : (t -> p)) | p == codebasePath = True okLine line = isWalDelete line || isShmDelete line isWalDelete (t -> 'D' : (t -> p)) | p == codebasePath ++ "-wal" = True isWalDelete _ = False isShmDelete (t -> 'D' : (t -> p)) | p == codebasePath ++ "-wal" = True isShmDelete _ = False hasDeleteWal = any isWalDelete statusLines hasDeleteShm = any isShmDelete statusLines -- Commit our changes push :: CodebasePath -> WriteRepo -> IO Bool -- withIOError needs IO push remotePath (WriteGitRepo url) = time "SqliteCodebase.pushGitRootBranch.push" $ do -- has anything changed? -- note: -uall recursively shows status for all files in untracked directories -- we want this so that we see -- `?? .unison/v2/unison.sqlite3` and not -- `?? .unison/` status <- gitTextIn remotePath ["status", "--short", "-uall"] if Text.null status then pure False else case parseStatus status of Nothing -> error $ "An error occurred during push.\n" <> "I was expecting only to see .unison/v2/unison.sqlite3 modified, but saw:\n\n" <> Text.unpack status <> "\n\n" <> "Please visit https://github.com/unisonweb/unison/issues/2063\n" <> "and add any more details about how you encountered this!\n" Just (hasDeleteWal, hasDeleteShm) -> do -- Only stage files we're expecting; don't `git add --all .` -- which could accidentally commit some garbage gitIn remotePath ["add", ".unison/v2/unison.sqlite3"] when hasDeleteWal $ gitIn remotePath ["rm", ".unison/v2/unison.sqlite3-wal"] when hasDeleteShm $ gitIn remotePath ["rm", ".unison/v2/unison.sqlite3-shm"] gitIn remotePath ["commit", "-q", "-m", "Sync branch " <> Text.pack (show $ Branch.headHash branch)] -- Push our changes to the repo gitIn remotePath ["push", "--quiet", url] pure True
unisonweb/platform
parser-typechecker/src/Unison/Codebase/SqliteCodebase.hs
Haskell
mit
55,182
-- | Commit version. -- Adapted from Apia.Utils.CommitVersion.hs -- http://github.com/asr/apia. {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} -- The constructor @versionTagsq (see GHC ticket #2496) is deprecated -- (at least in GHC 8.0.1). See Issue #83. {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} module Athena.Utils.CommitVersion ( getVersion ) where ------------------------------------------------------------------------------ import Control.Exception ( IOException, try ) import Data.Version ( Version ( versionTags ) ) import System.Exit ( ExitCode ( ExitSuccess ) ) import System.Process ( readProcessWithExitCode ) ------------------------------------------------------------------------------ -- | If inside a `git` repository, then @'getVersion' x@ will return -- @x@ plus the hash of the top commit used for -- compilation. Otherwise, only @x@ will be returned. getVersion ∷ Version → IO Version getVersion version = do commit ∷ Maybe String ← commitInfo case commit of Nothing → return version Just rev → return $ gitVersion version rev tryIO ∷ IO a → IO (Either IOException a) tryIO = try commitInfo ∷ IO (Maybe String) commitInfo = do res ← tryIO $ readProcessWithExitCode "git" ["log", "--format=%h", "-n", "1"] "" case res of Right (ExitSuccess, hash, _) → do (_, _, _) ← readProcessWithExitCode "git" ["diff", "--quiet"] "" return $ Just (init hash) _ → return Nothing gitVersion ∷ Version → String → Version gitVersion version hash = version { versionTags = [take 7 hash] }
jonaprieto/athena
src/Athena/Utils/CommitVersion.hs
Haskell
mit
1,626
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} -- | Describes Rowling values, i.e., the entities which are produced by -- evaluating expressions, and passed as input to the evaluator. module Language.Rowling.Definitions.Values where import Data.Aeson (FromJSON(..), ToJSON(..), (.=), object) import qualified Data.Aeson as Aeson import Data.ContextStack import qualified Data.HashMap.Strict as H import Data.Scientific (isInteger, toRealFloat, fromFloatDigits) import qualified GHC.Exts as GHC import Language.Rowling.Common import Language.Rowling.Definitions.Expressions -- | The evaluated form of an `Expr`. data Value = VInt !Integer -- ^ An integer. | VFloat !Double -- ^ A floating-point number. | VString !Text -- ^ A string. | VBool !Bool -- ^ A boolean. | VArray !(Vector Value) -- ^ An array of values. | VTagged !Name !(Vector Value) -- ^ A tagged union, like `Either` or `List`. | VMaybe !(Maybe Value) -- ^ A maybe (using the Haskell type for efficiency) | VBuiltin !Builtin -- ^ A builtin function. | VRecord !(Record Value) -- ^ An instantiated Record. | VClosure !(Record Value) !Pattern !Expr -- ^ A closure. deriving (Show, Eq) -- | Looks up a field in a record. If the field doesn't exist, or the value -- isn't a record, an IO exception will be thrown. deref :: Name -> Value -> Value deref name (VRecord fields) = case H.lookup name fields of Nothing -> error $ "No field " <> show name Just val -> val deref _ _ = error "Not a record value" instance Render Value -- | The default value is an empty record, akin to @()@. instance Default Value where def = VRecord mempty -- | Makes creating string values more convenient. instance IsString Value where fromString = VString . fromString -- | Array values are lists, that contain values. instance IsList Value where type Item Value = Value fromList = VArray . GHC.fromList toList (VArray vs) = GHC.toList vs toList _ = error "Not a list value" -- | Values can be read out of JSON. Of course, closures and builtins -- can't be represented. instance FromJSON Value where parseJSON (Aeson.Object v) = VRecord <$> mapM parseJSON v parseJSON (Aeson.Array arr) = VArray <$> mapM parseJSON arr parseJSON (Aeson.String s) = return $ VString s parseJSON (Aeson.Bool b) = return $ VBool b parseJSON (Aeson.Number n) | isInteger n = return $ VInt (floor n) | otherwise = return $ VFloat $ toRealFloat n parseJSON _ = mzero -- | Most values have JSON representations. Where they don't, it's an error -- to try to serialize them to JSON. instance ToJSON Value where toJSON (VInt i) = Aeson.Number $ fromIntegral i toJSON (VFloat f) = Aeson.Number $ fromFloatDigits f toJSON (VString txt) = Aeson.String txt toJSON (VBool b) = Aeson.Bool b toJSON (VArray arr) = Aeson.Array $ map toJSON arr toJSON (VMaybe Nothing) = object ["@constructor" .= Aeson.String "None"] toJSON (VMaybe (Just v)) = object [ "@constructor" .= Aeson.String "Some", "@values" .= Aeson.Array [toJSON v] ] toJSON (VTagged name vals) = object ["@constructor" .= name, "@values" .= map toJSON vals] toJSON (VRecord rec) = Aeson.Object $ map toJSON rec toJSON v = errorC ["Can't serialize '", render v, "' to JSON"] -- | Matches a pattern against a value and either fails, or returns a map of -- name bindings. For example, matching the pattern @Just x@ against the value -- @VTagged "Just" (VInt 1)@ would return @[("x", VInt 1)]@. Matching the -- same pattern against @VFloat 2.3@ would return @Nothing@. patternMatch :: Pattern -> Value -> Maybe (Record Value) patternMatch p v = case (p, v) of -- Primitive literals just match if equal. (Constructors are literals). (Int n, VInt vn) | n == vn -> Just mempty (Float n, VFloat vn) | n == vn -> Just mempty (String (Plain s), VString vs) | s == vs -> Just mempty -- True and false are constructors, but use Haskell bools (Constructor "True", VBool True) -> Just mempty (Constructor "False", VBool False) -> Just mempty (Constructor "None", VMaybe Nothing) -> Just mempty (Apply (Constructor "Some") p, VMaybe (Just v)) -> patternMatch p v -- A variable can match with anything. (Variable name, v) -> Just [(name, v)] -- With a list expression, it matches if and only if all of them match. (List ps, VArray vs) -> matchVector ps vs (Record precord, VRecord vrecord) -> matchRecord precord vrecord -- For a compound expression, dive into it (see below). (compoundExpr, VTagged n' vs) -> case dive compoundExpr of Just (n, ps) | n == n' -> matchVector (fromList ps) vs otherwise -> Nothing -- Anything else is not a match. otherwise -> Nothing where matchRecord precord vrecord = loop mempty $ H.toList precord where loop bindings [] = Just bindings loop bindings ((key, pattern):rest) = case lookup key vrecord of -- Key doesn't exist, pattern match fails. Nothing -> Nothing Just val -> case patternMatch pattern val of -- Value doesn't pattern match with pattern, no match. Nothing -> Nothing Just bindings' -> loop (bindings' <> bindings) rest matchVector ps vs = case length ps == length vs of True -> concat <$> mapM (uncurry patternMatch) (zip ps vs) False -> Nothing -- "Dives" into a pattern and grabs the constructor name and patterns. -- Note that it's only going to return a @Just@ value if the "left most" -- expression in the pattern is a constructor. This prevents an pattern -- like @a b@ from matching against @Just 1@. dive = map (map reverse) . dive' where dive' (Constructor n) = Just (n, []) dive' (Apply p1 p2) = for (dive' p1) (\(name, ps) -> (name, p2:ps)) dive' _ = Nothing ------------------------------------------------------------------------------ -- * The Evaluator Monad -- Note: we have to put these definitions here because `Value`s need to be -- aware of the `Eval` type. ------------------------------------------------------------------------------ -- | An evaluation frame. It consists of the argument passed into the -- function currently being evaluated, and all of the variables in the -- current scope. data EvalFrame = EvalFrame { _fArgument :: Value, _fEnvironment :: Record Value } deriving (Show) -- | A frame is a key-value store where the internal dictionary is the -- environment. instance KeyValueStore EvalFrame where type LookupKey EvalFrame = Name type StoredValue EvalFrame = Value empty = def loadBindings bs f = f {_fEnvironment = bs <> _fEnvironment f} getValue name = lookup name . _fEnvironment putValue name val frame = frame {_fEnvironment = insertMap name val env} where env = _fEnvironment frame -- | The evaluator's state is a stack of evaluation frames. data EvalState = EvalState {_esStack :: [EvalFrame]} deriving (Show) -- | The evaluator state is a stack of `EvalFrame`s. instance Stack EvalState where type Frame EvalState = EvalFrame push frame state = state {_esStack = push frame $ _esStack state} pop state = (top, state {_esStack=rest}) where top:rest = _esStack state asList = _esStack modifyTop func state = state {_esStack=func top : rest} where top:rest = _esStack state -- | The default evaluation state is a stack with a single evaluation frame. instance Default EvalState where def = EvalState {_esStack = [def]} -- | The default evaluation frame just takes default arguments and -- environment. instance Default EvalFrame where def = EvalFrame {_fArgument = def, _fEnvironment = mempty} -- | The evaluator monad. type Eval = ReaderT () (StateT EvalState IO) -- | A built-in function. Allows us to write functions in Haskell and -- make them callable from inside the Rowling evaluator. data Builtin = Builtin Name (Value -> Eval Value) -- | All we show is the function's name, which is assumed to be unique. instance Show Builtin where show (Builtin n _) = "<BUILTIN " <> show n <> ">" -- | Builtins are considered equal if they have the same name. instance Eq Builtin where Builtin n1 _ == Builtin n2 _ = n1 == n2
thinkpad20/rowling
src/Language/Rowling/Definitions/Values.hs
Haskell
mit
8,495
module FrontEnd.TypeSynonyms ( removeSynonymsFromType, declsToTypeSynonyms, TypeSynonyms, restrictTypeSynonyms, expandTypeSyns, showSynonyms, showSynonym ) where import Control.Applicative(Applicative) import Control.Monad.Writer import Data.Binary import Data.List import qualified Data.Map as Map import qualified Data.Set as Set import Doc.DocLike import FrontEnd.HsSyn import FrontEnd.SrcLoc import FrontEnd.Syn.Traverse import FrontEnd.Warning import GenUtil import Name.Name import Support.FreeVars import Support.MapBinaryInstance import Util.HasSize import Util.UniqueMonad import qualified Util.Graph as G newtype TypeSynonyms = TypeSynonyms (Map.Map Name ([HsName], HsType, SrcLoc)) deriving(Monoid,HasSize) instance Binary TypeSynonyms where put (TypeSynonyms ts) = putMap ts get = fmap TypeSynonyms getMap restrictTypeSynonyms :: (Name -> Bool) -> TypeSynonyms -> TypeSynonyms restrictTypeSynonyms f (TypeSynonyms fm) = TypeSynonyms (Map.filterWithKey (\k _ -> f k) fm) showSynonym :: (DocLike d,Monad m) => (HsType -> d) -> Name -> TypeSynonyms -> m d showSynonym pprint n (TypeSynonyms m) = case Map.lookup n m of Just (ns, t, _) -> return $ hsep (tshow n:map tshow ns) <+> text "=" <+> pprint t Nothing -> fail "key not found" showSynonyms :: DocLike d => (HsType -> d) -> TypeSynonyms -> d showSynonyms pprint (TypeSynonyms m) = vcat (map f (Map.toList m)) where f (n,(ns,t,_)) = hsep (tshow n:map tshow ns) <+> text "=" <+> pprint t -- | convert a set of type synonym declarations to a synonym map used for efficient synonym -- expansion --declsToTypeSynonyms :: [HsDecl] -> TypeSynonyms --declsToTypeSynonyms ts = TypeSynonyms $ Map.fromList $ -- [ (toName TypeConstructor name,( args , quantifyHsType args (HsQualType [] t) , sl)) | (HsTypeDecl sl name args' t) <- ts, let args = [ n | ~(HsTyVar n) <- args'] ] -- ++ [ (toName TypeConstructor name,( args , HsTyAssoc, sl)) | (HsClassDecl _ _ ds) <- ts,(HsTypeDecl sl name args' _) <- ds, let args = [ n | ~(HsTyVar n) <- args'] ] -- | convert a set of type synonym declarations to a synonym map used for efficient synonym -- expansion, expanding out the body of synonyms along the way. declsToTypeSynonyms :: (Applicative m,MonadWarn m) => TypeSynonyms -> [HsDecl] -> m TypeSynonyms declsToTypeSynonyms tsin ds = f tsin gr [] where gr = G.scc $ G.newGraph [ (toName TypeConstructor name,( args , quantifyHsType args (HsQualType [] t) , sl)) | (HsTypeDecl sl name args' t) <- ds, let args = [ n | ~(HsTyVar n) <- args'] ] fst (Set.toList . freeVars . (\ (_,(_,t,_)) -> t)) f tsin (Right ns:xs) rs = do warn (head [ sl | (_,(_,_,sl)) <- ns]) TypeSynonymRecursive ("Recursive type synonyms:" <+> show (fsts ns)) f tsin xs rs f tsin (Left (n,(as,body,sl)):xs) rs = do body' <- evalTypeSyms sl tsin body f (tsInsert n (as,body',sl) tsin) xs ((n,(as,body',sl)):rs) f _ [] rs = return $ TypeSynonyms (Map.fromList rs) tsInsert x y (TypeSynonyms xs) = TypeSynonyms (Map.insert x y xs) removeSynonymsFromType :: (Applicative m,MonadSrcLoc m, MonadWarn m) => TypeSynonyms -> HsType -> m HsType removeSynonymsFromType syns t = do sl <- getSrcLoc evalTypeSyms sl syns t expandTypeSyns :: (TraverseHsOps a,MonadWarn m) => TypeSynonyms -> a -> m a expandTypeSyns syns m = runSLM (applyHsOps ops m) where ops = (hsOpsDefault ops) { opHsDecl, opHsType = removeSynonymsFromType syns } where opHsDecl td@HsTypeDecl {} = return td opHsDecl d = traverseHsOps ops d quantifyHsType :: [HsName] -> HsQualType -> HsType quantifyHsType inscope t | null vs, null (hsQualTypeContext t) = hsQualTypeType t | otherwise = HsTyForall vs t where vs = map g $ snub (execWriter (fv (hsQualTypeType t))) \\ inscope g n = hsTyVarBind { hsTyVarBindName = n } fv (HsTyVar v) = tell [v] fv (HsTyForall vs qt) = tell $ snub (execWriter (fv $ hsQualTypeType qt)) \\ map hsTyVarBindName vs fv (HsTyExists vs qt) = tell $ snub (execWriter (fv $ hsQualTypeType qt)) \\ map hsTyVarBindName vs fv x = traverseHsType (\x -> fv x >> return x) x >> return () evalTypeSyms :: (Applicative m,Monad m,MonadWarn m) => SrcLoc -> TypeSynonyms -> HsType -> m HsType evalTypeSyms sl (TypeSynonyms tmap) ot = execUniqT 1 (eval [] ot) where eval stack x@(HsTyCon n) | Just (args, t, sldef) <- Map.lookup (toName TypeConstructor n) tmap = do let excess = length stack - length args if (excess < 0) then do lift $ warn sl TypeSynonymPartialAp ("Partially applied typesym:" <+> show n <+> "need" <+> show (- excess) <+> "more arguments.") unwind x stack else case t of HsTyAssoc -> unwind x stack _ -> do st <- subst (Map.fromList [(a,s) | a <- args | s <- stack]) t eval (drop (length args) stack) st eval stack (HsTyApp t1 t2) = eval (t2:stack) t1 eval stack x = do t <- traverseHsType (eval []) x unwind t stack unwind t [] = return t unwind t (t1:rest) = do t1' <- eval [] t1 unwind (HsTyApp t t1') rest subst sm (HsTyForall vs t) = do ns <- mapM (const newUniq) vs let nvs = [ (hsTyVarBindName v,v { hsTyVarBindName = hsNameIdent_u ((show n ++ "00") ++) (hsTyVarBindName v)})| (n,v) <- zip ns vs ] nsm = Map.fromList [ (v,HsTyVar $ hsTyVarBindName t)| (v,t) <- nvs] `Map.union` sm t' <- substqt nsm t return $ HsTyForall (snds nvs) t' subst sm (HsTyExists vs t) = do ns <- mapM (const newUniq) vs let nvs = [ (hsTyVarBindName v,v { hsTyVarBindName = hsNameIdent_u ((show n ++ "00") ++) (hsTyVarBindName v)})| (n,v) <- zip ns vs ] nsm = Map.fromList [ (v,HsTyVar $ hsTyVarBindName t)| (v,t) <- nvs] `Map.union` sm t' <- substqt nsm t return $ HsTyExists (snds nvs) t' subst (sm::(Map.Map HsName HsType)) (HsTyVar n) | Just v <- Map.lookup n sm = return v subst sm t = traverseHsType (subst sm) t substqt sm qt@HsQualType { hsQualTypeContext = ps, hsQualTypeType = t } = do t' <- subst sm t let f (HsAsst c xs) = return (HsAsst c (map g xs)) f (HsAsstEq a b) = do a' <- subst sm a b' <- subst sm b return (HsAsstEq a' b') g n = case Map.lookup n sm of Just (HsTyVar n') -> n' ; _ -> n ps' <- mapM f ps -- = [ case Map.lookup n sm of Just (HsTyVar n') -> (c,n') ; _ -> (c,n) | (c,n) <- ps ] return qt { hsQualTypeType = t', hsQualTypeContext = ps' }
m-alvarez/jhc
src/FrontEnd/TypeSynonyms.hs
Haskell
mit
6,646
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module AI.Funn.CL.Batched.Param ( Param(..), reshape, split, appendD ) where import Control.Applicative import Control.Exception import Control.Monad import Control.Monad.IO.Class import Data.Foldable import Data.Monoid import Data.Proxy import Data.Traversable import GHC.TypeLits import System.IO.Unsafe import AI.Funn.CL.Blob (Blob, BlobT(Blob)) import qualified AI.Funn.CL.Blob as Blob import AI.Funn.CL.MonadCL import AI.Funn.CL.Tensor (Tensor) import qualified AI.Funn.CL.Tensor as T import qualified AI.Funn.CL.TensorLazy as TL import qualified AI.Funn.CL.LazyMem as LM import AI.Funn.Diff.Diff (Derivable(..)) import AI.Funn.Space newtype Param (ω :: Nat) (n :: Nat) = Param { getParam :: Tensor '[n] } instance Derivable (Param ω n) where type D (Param ω n) = TL.Tensor '[ω, n] instance (MonadIO m, KnownNat n) => Zero m (Param ω n) where zero = Param <$> zero instance (MonadIO m, KnownNat n) => Semi m (Param ω n) where plus (Param x) (Param y) = Param <$> plus x y instance (MonadIO m, KnownNat n) => Additive m (Param ω n) where plusm xs = Param <$> plusm (map getParam xs) instance (MonadIO m, KnownNat n) => Scale m Double (Param ω n) where scale x (Param xs) = Param <$> scale x xs instance (MonadIO m, KnownNat n) => VectorSpace m Double (Param ω n) where {} instance (MonadIO m, KnownNat n) => Inner m Double (Param ω n) where inner (Param x) (Param y) = inner x y instance (MonadIO m, KnownNat n) => Finite m Double (Param ω n) where getBasis (Param x) = getBasis x -- O(1) reshape :: (Prod ds ~ n) => Param ω n -> Tensor ds reshape (Param xs) = T.reshape xs -- O(1) split :: (KnownNat a, KnownNat b) => Param ω (a+b) -> (Param ω a, Param ω b) split (Param xs) = case T.split xs of (a, b) -> (Param a, Param b) -- O(ω) appendD :: forall ω a b. (KnownDimsF [ω, a, b]) => TL.Tensor [ω, a] -> TL.Tensor [ω, b] -> TL.Tensor [ω, a+b] appendD = TL.appendW
nshepperd/funn
AI/Funn/CL/Batched/Param.hs
Haskell
mit
2,439
import Data.List.Split (splitOn) import Data.List (sort) import Prelude hiding (readList) import Control.Applicative import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.Maybe import Data.Maybe part1 input = sum (map (\x -> part1helper $sort x) input) where part1helper [a,b,c] = 2*(a*b + a*c + b*c) + a*b part2 input = sum (map (\x -> part2helper $sort x) input) where part2helper [a,b,c] = 2*(a+b) + a*b*c readList :: IO [String] readList = fmap (fromMaybe []) $ runMaybeT $ many $ do l <- lift getLine guard $ not $ null l return l make_int dat = map (\x -> read x ::Int) (splitOn "x" dat) main = do input <- readList let split_data = map make_int input print split_data print $ part1 split_data print $ part2 split_data
jO-Osko/adventofcode2015
2015/problems/haskell/day2.hs
Haskell
mit
804
module CSPMTypeChecker.TCDependencies (Dependencies, dependencies, namesBoundByDecl, namesBoundByDecl', FreeVars, freeVars, prebindDataType) where import Data.List (nub, (\\)) import CSPMDataStructures import CSPMTypeChecker.TCMonad import Util -- This method heavily affects the DataType clause of typeCheckDecl. -- If any changes are made here changes will need to be made to typeCheckDecl -- too prebindDataType :: Decl -> TypeCheckMonad () prebindDataType (DataType n cs) = let prebindDataTypeClause (DataTypeClause n' es) = do fvs <- replicateM (length es) freshTypeVar setType n' (ForAll [] (TDatatypeClause n fvs)) clauseNames = [n' | DataTypeClause n' es <- map removeAnnotation cs] in do errorIfFalse (noDups clauseNames) (DuplicatedDefinitions clauseNames) mapM_ (prebindDataTypeClause . removeAnnotation) cs -- n is the set of all TDatatypeClause setType n (ForAll [] (TSet (TDatatypeClause n []))) class Dependencies a where dependencies :: a -> TypeCheckMonad [Name] dependencies xs = liftM nub (dependencies' xs) dependencies' :: a -> TypeCheckMonad [Name] instance Dependencies a => Dependencies [a] where dependencies' xs = concatMapM dependencies xs instance Dependencies a => Dependencies (Maybe a) where dependencies' (Just x) = dependencies' x dependencies' Nothing = return [] instance Dependencies a => Dependencies (Annotated b a) where dependencies' (Annotated _ _ inner) = dependencies inner instance Dependencies Pat where dependencies' (PVar n) = do res <- safeGetType n case res of Just (ForAll _ t) -> case t of -- See typeCheck (PVar) for a discussion of why -- we only do this TDatatypeClause n ts -> return [n] _ -> return [] Nothing -> return [] -- var is not bound dependencies' (PConcat p1 p2) = do fvs1 <- dependencies' p1 fvs2 <- dependencies' p2 return $ fvs1++fvs2 dependencies' (PDotApp p1 p2) = dependencies' [p1,p2] dependencies' (PList ps) = dependencies' ps dependencies' (PWildCard) = return [] dependencies' (PTuple ps) = dependencies' ps dependencies' (PSet ps) = dependencies' ps dependencies' (PParen p) = dependencies' p dependencies' (PLit l) = return [] dependencies' (PDoublePattern p1 p2) = do fvs1 <- dependencies' p1 fvs2 <- dependencies' p2 return $ fvs1++fvs2 instance Dependencies Exp where dependencies' (App e es) = dependencies' (e:es) dependencies' (BooleanBinaryOp _ e1 e2) = dependencies' [e1,e2] dependencies' (BooleanUnaryOp _ e) = dependencies' e dependencies' (Concat e1 e2) = dependencies' [e1,e2] dependencies' (DotApp e1 e2) = dependencies' [e1,e2] dependencies' (If e1 e2 e3) = dependencies' [e1,e2, e3] dependencies' (Lambda p e) = do fvsp <- freeVars p depsp <- dependencies p fvse <- dependencies e return $ (fvse \\ fvsp)++depsp dependencies' (Let ds e) = do fvsd <- dependencies ds newBoundVars <- liftM nub (concatMapM namesBoundByDecl ds) fvse <- dependencies e return $ nub (fvse++fvsd) \\ newBoundVars dependencies' (Lit _) = return [] dependencies' (List es) = dependencies es dependencies' (ListComp es stmts) = do fvStmts <- freeVars stmts depsStmts <- dependencies stmts fvses' <- dependencies es let fvse = nub (fvses'++depsStmts) return $ fvse \\ fvStmts dependencies' (ListEnumFrom e1) = dependencies' e1 dependencies' (ListEnumFromTo e1 e2) = dependencies' [e1,e2] dependencies' (ListLength e) = dependencies' e dependencies' (MathsBinaryOp _ e1 e2) = dependencies' [e1,e2] dependencies' (NegApp e) = dependencies' e dependencies' (Paren e) = dependencies' e dependencies' (Set es) = dependencies es dependencies' (SetComp es stmts) = do fvStmts <- freeVars stmts depsStmts <- dependencies stmts fvses' <- dependencies es let fvse = nub (fvses'++depsStmts) return $ fvse \\ fvStmts dependencies' (SetEnumComp es stmts) = do fvStmts <- freeVars stmts depsStmts <- dependencies stmts fvses' <- dependencies es let fvse = nub (fvses'++depsStmts) return $ fvse \\ fvStmts dependencies' (SetEnumFrom e1) = dependencies' e1 dependencies' (SetEnumFromTo e1 e2) = dependencies' [e1,e2] dependencies' (SetEnum es) = dependencies' es dependencies' (Tuple es) = dependencies' es dependencies' (Var (UnQual n)) = return [n] dependencies' (UserOperator n es) = dependencies' es dependencies' (ReplicatedUserOperator n es stmts) = do fvStmts <- freeVars stmts depsStmts <- dependencies stmts fvses' <- dependencies es let fvse = nub (fvses'++depsStmts) return $ fvse \\ fvStmts instance Dependencies Stmt where dependencies' (Generator p e) = do ds1 <- dependencies p ds2 <- dependencies e return $ ds1++ds2 dependencies' (Qualifier e) = dependencies e instance Dependencies Decl where dependencies' (FunBind n ms t) = do fvsms <- dependencies ms fvst <- dependencies t return $ fvsms++fvst dependencies' (PatBind p e) = do depsp <- dependencies p fvsp <- freeVars p depse <- dependencies e return $ depsp++depse dependencies' (Channel ns es) = dependencies es dependencies' (Assert e1 e2 m) = dependencies [e1, e2] dependencies' (DataType n cs) = dependencies [cs] dependencies' (External ns) = return [] dependencies' (Transparent ns) = return [] instance Dependencies Match where dependencies' (Match ps e) = do fvs1 <- freeVars ps depsPs <- dependencies ps fvs2 <- dependencies e return $ (fvs2 \\ fvs1) ++ depsPs instance Dependencies DataTypeClause where dependencies' (DataTypeClause n es) = dependencies es namesBoundByDecl :: AnDecl -> TypeCheckMonad [Name] namesBoundByDecl = namesBoundByDecl' . removeAnnotation namesBoundByDecl' (FunBind n ms t) = return [n] namesBoundByDecl' (PatBind p ms) = freeVars p namesBoundByDecl' (Channel ns es) = return ns namesBoundByDecl' (Assert e1 e2 m) = return [] namesBoundByDecl' (DataType n dcs) = let namesBoundByDtClause (DataTypeClause n _) = [n] in return $ n:concatMap (namesBoundByDtClause . removeAnnotation) dcs namesBoundByDecl' (External ns) = return ns namesBoundByDecl' (Transparent ns) = return ns class FreeVars a where freeVars :: a -> TypeCheckMonad [Name] freeVars = liftM nub . freeVars' freeVars' :: a -> TypeCheckMonad [Name] instance FreeVars a => FreeVars [a] where freeVars' xs = concatMapM freeVars' xs instance FreeVars a => FreeVars (Annotated b a) where freeVars' (Annotated _ _ inner) = freeVars inner instance FreeVars Pat where freeVars' (PVar n) = do res <- safeGetType n case res of Just (ForAll _ t) -> case t of -- See typeCheck (PVar) for a discussion of why -- we only do this TDatatypeClause n ts -> return [] _ -> return [n] Nothing -> return [n] -- var is not bound freeVars' (PConcat p1 p2) = do fvs1 <- freeVars' p1 fvs2 <- freeVars' p2 return $ fvs1++fvs2 freeVars' (PDotApp p1 p2) = freeVars' [p1,p2] freeVars' (PList ps) = freeVars' ps freeVars' (PWildCard) = return [] freeVars' (PTuple ps) = freeVars' ps freeVars' (PSet ps) = freeVars' ps freeVars' (PParen p) = freeVars' p freeVars' (PLit l) = return [] freeVars' (PDoublePattern p1 p2) = do fvs1 <- freeVars' p1 fvs2 <- freeVars' p2 return $ fvs1++fvs2 instance FreeVars Stmt where freeVars' (Qualifier e) = return [] freeVars' (Generator p e) = freeVars p
tomgr/tyger
src/CSPMTypeChecker/TCDependencies.hs
Haskell
mit
7,419
{-# LANGUAGE FlexibleContexts #-} module Errors ( AppError (..) , authenticationRequired , raiseAppError , resourceNotFound , serverError , badRequest ) where import Control.Monad.Except import qualified Data.ByteString.Lazy as BL import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TLE import Servant data AppError = ResourceNotFound | BadRequest T.Text | AuthenticationRequired | ServerError deriving (Show, Eq, Read) raiseAppError :: MonadError ServantErr m => AppError -> m a raiseAppError ResourceNotFound = throwError resourceNotFound raiseAppError (BadRequest errMsg) = throwError $ badRequest errMsg raiseAppError AuthenticationRequired = throwError authenticationRequired raiseAppError ServerError = throwError serverError authenticationRequired :: ServantErr authenticationRequired = err401 { errBody = "Authentication required" } resourceNotFound :: ServantErr resourceNotFound = err404 { errBody = "The request resource could not be found" } serverError :: ServantErr serverError = err500 { errBody = "Internal server error" } badRequest :: T.Text -> ServantErr badRequest msg = err400 { errBody = encode msg } encode :: T.Text -> BL.ByteString encode = TLE.encodeUtf8 . TL.fromStrict
gust/feature-creature
marketing-site/app/Errors.hs
Haskell
mit
1,337
{-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TemplateHaskell #-} module Db.Transaction ( Transaction'(Transaction) , NewTransaction , Transaction , transactionQuery , allTransactions , getTransaction , insertTransaction , transactionId , transactionDate , transactionAmount , transactionBalance , transactionType , transactionPlaceId , transactionAccountId ) where import BasePrelude hiding (optional) import Control.Lens import Data.Profunctor.Product.TH (makeAdaptorAndInstance) import Data.Text (Text) import Data.Time (Day) import Opaleye import Db.Internal data Transaction' a b c d e f g = Transaction { _transactionId :: a , _transactionDate :: b , _transactionAmount :: c , _transactionBalance :: d , _transactionType :: e , _transactionPlaceId :: f , _transactionAccountId :: g } deriving (Eq,Show) makeLenses ''Transaction' type Transaction = Transaction' Int Day Double Double Text (Maybe Int) Int type TransactionColumn = Transaction' (Column PGInt4) (Column PGDate) (Column PGFloat8) -- These should be non-floating point numbers (Column PGFloat8) -- but Opaleye doesn't support these yet. :( (Column PGText) (Column (Nullable PGInt4)) (Column PGInt4) makeAdaptorAndInstance "pTransaction" ''Transaction' type NewTransaction = Transaction' (Maybe Int) Day Double Double Text (Maybe Int) Int type NewTransactionColumn = Transaction' (Maybe (Column PGInt4)) (Column PGDate) (Column PGFloat8) (Column PGFloat8) (Column PGText) (Column (Nullable PGInt4)) (Column PGInt4) transactionTable :: Table NewTransactionColumn TransactionColumn transactionTable = Table "transaction" $ pTransaction Transaction { _transactionId = optional "id" , _transactionDate = required "date" , _transactionAmount = required "amount" , _transactionBalance = required "balance" , _transactionType = required "type" , _transactionPlaceId = required "place_id" , _transactionAccountId = required "account_id" } transactionQuery :: Query TransactionColumn transactionQuery = queryTable transactionTable allTransactions :: CanDb c e m => m [Transaction] allTransactions = liftQuery transactionQuery insertTransaction :: CanDb c e m => NewTransaction -> m Int insertTransaction = liftInsertReturningFirst transactionTable (view transactionId) . packNew getTransaction :: CanDb c e m => Int -> m (Maybe Transaction) getTransaction i = liftQueryFirst $ proc () -> do t <- transactionQuery -< () restrict -< t^.transactionId .== pgInt4 i returnA -< t packNew :: NewTransaction -> NewTransactionColumn packNew = pTransaction Transaction { _transactionId = fmap pgInt4 , _transactionDate = pgDay , _transactionAmount = pgDouble , _transactionBalance = pgDouble , _transactionType = pgStrictText , _transactionPlaceId = maybeToNullable . fmap pgInt4 , _transactionAccountId = pgInt4 }
benkolera/talk-stacking-your-monads
code-classy/src/Db/Transaction.hs
Haskell
mit
3,165
module Y2016.M12.D20.Exercise where -- below import available from 1HaskellADay git repository import Data.SymbolTable import Data.SymbolTable.Compiler import Data.SAIPE.USStates {-- So, yesterday, as you see from the import above, we enumerated the US States! YAY! *throws confetti NOW! Using the same data-set, stored at: Y2016/M12/D15/SAIPESNC_15DEC16_11_35_13_00.csv.gz let's enumerate the US Counties. A slight problem: the SymbolTable-type works with strings, SO you can enumerate the strings, sure. (I think any Ord-type should work, but hey.) ('but hey' is a perfect counter-argument to anything. Try it sometime.) Well you can do that. No problem. But how do you associate an atomic County symbol with its State? Today's Haskell problem. 1) create a complied symbol table of Data.SAIPE.USCounties, enumerated and indexible. --} usCountySymbols :: FilePath -> FilePath -> IO () usCountySymbols gzipSAIPEdata modul = undefined data USCounty = PlaceholderForCompiledUSCountyType -- see yesterday's exercise for guidance {-- Now, USState and USCounty and their associations are all deterministic (as we'd say in Prolog-parlance), so how do we do a lookup for the USState of a USCounty in a deterministic fashion? --} usStateFor :: USCounty -> USState usStateFor county = undefined -- 2) define usStateFor as above that guarantees to return a USState value -- (the correct one, at that) for the input USCounty value. -- hint: A USCounty's USState is a fact. No doubt.
geophf/1HaskellADay
exercises/HAD/Y2016/M12/D20/Exercise.hs
Haskell
mit
1,493
f x = if x < 10 then x else x*2
Bolt64/my_code
haskell/hello_haskell.hs
Haskell
mit
49
revList :: [a] -> [a] revList [] = [] revList (h:t) = revList t ++ [h] dropList :: Int -> [a] -> [a] dropList 0 list = list dropList _ [] = [] dropList n (h:t) = dropList (n-1) t fizzbuzz :: Int -> String fizzbuzz a | a `mod` 15 == 0 = "FizzBuzz" | a `mod` 3 == 0 = "Fizz" | a `mod` 5 == 0 = "Buzz" | otherwise = show a (|>) :: a -> (a -> b) -> b (|>) val func = func val quicksort :: (Ord a) => [a] -> [a] quicksort (x:xs) = [v | v <- xs, v <= x] ++ [x] ++ [v | v <- xs, v > x] zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c] zipWith' _ [] _ = [] zipWith' _ _ [] = [] zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys partition' :: (a -> Bool) -> [a] -> ([a],[a]) partition' f l = partition_' f ([],[]) l partition_' :: (a -> Bool) -> ([a],[a]) -> [a] -> ([a],[a]) partition_' f (h,t) [] = (h,t) partition_' f (h,t) (x:xs) | f(x) = partition_' f (h, x:t) xs | otherwise = partition_' f (x:h, t) xs -- -- Types -- Int -- Integer makes use unbounded list -- Char -- Bool -- Float -- Double -- Here Shape is the type and Circle and Rectange are the value constructors -- like Circle :: Float -> Float -> Float -> Shape -- Value Constructors are functions data Shape = Circle Float Float Float | Rectangle Float Float Float Float deriving (Show, Eq) area :: Shape -> Float area (Circle _ _ r) = 3.1415 * r * r area (Rectangle x1 y1 x2 y2) = abs (x1 - x2) * abs(y1 - y2) data Vector2D = Vector2D Float Float deriving (Show, Eq) add :: Vector2D -> Vector2D -> Vector2D add (Vector2D x1 y1) (Vector2D x2 y2) = Vector2D (x1+x2) (y1+y2) data MyBool = MyFalse | MyTrue deriving (Ord, Eq, Show) class YesNo a where yesno :: a -> MyBool instance YesNo Int where yesno 0 = MyFalse yesno _ = MyTrue instance YesNo [a] where yesno [] = MyFalse yesno _ = MyTrue instance YesNo MyBool where yesno = id data Optional a = Empty | Some a deriving (Show, Eq) instance Functor Optional where fmap f Empty = Empty fmap f (Some a) = Some $ f a rpn :: (Num a, Read a) => String -> a rpn exp = exp |> words |> foldl f [] |> head where f (x:y:ys) "*" = (x * y):ys f (x:y:ys) "+" = (x + y):ys f (x:y:ys) "-" = (y - x):ys f x num = (read num):x main = do print (revList [1,2,3,4,5]) print (dropList (-100) [1,2,3,4,5,6]) print (fizzbuzz 10) print (fizzbuzz 3) print (fizzbuzz 75) print (fizzbuzz 101) print (quicksort [23,5,34,78,9,10,20]) print (zipWith' (+) [1,2,3] [5,6,7]) print ( 3 |> (*3) |> (+10) |> \x -> x * x) print (partition' (>3) [1,2,3,4,5,6]) print $ area $ Rectangle 1 2 11 12 print $ yesno MyTrue print $ yesno (0::Int) print $ rpn "90 34 12 33 55 66 + * - + -"
anujjamwal/learning
Haskell/first.hs
Haskell
mit
2,734
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Text.Html.Nice.Internal where import Control.DeepSeq (NFData (..)) import Control.Monad import Control.Monad.Trans.Reader (ReaderT (..)) import Data.Bifunctor.TH import Data.Functor.Foldable.TH import Data.Functor.Identity import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Builder as TLB import qualified Data.Text.Lazy.Builder.Int as TLB import qualified Data.Text.Lazy.Builder.RealFloat as TLB import Data.Vector (Vector) import qualified Data.Vector as V import Data.Void import GHC.Generics (Generic) import qualified Text.Blaze as Blaze import qualified Text.Blaze.Internal as Blaze (textBuilder) import qualified Text.Blaze.Renderer.Text as Blaze type AttrName = Text data Attr a = (:=) { attrKey :: !AttrName , attrVal :: !Text } | (:-) { attrKey :: !AttrName , attrValHole :: a } deriving (Show, Eq, Functor, Foldable, Traversable) data IsEscaped = DoEscape | Don'tEscape deriving (Show, Eq) data SomeText = LazyT TL.Text | BuilderT TLB.Builder | StrictT !T.Text deriving (Show, Eq) -- | A very simple HTML DSL data Markup' a = Doctype | Node !Text !(Vector (Attr a)) (Markup' a) | VoidNode !Text !(Vector (Attr a)) | List [Markup' a] | Stream (Stream a) | Text !IsEscaped !SomeText | Hole !IsEscaped a | Precompiled !(FastMarkup a) | Empty deriving (Show, Eq, Functor, Foldable) {- , Traversable) -} data Stream a = forall s. ListS [s] !(FastMarkup (s -> a)) instance Show a => Show (Stream a) where show (ListS s f) = "(Stream (" ++ show (map (\a -> fmap ($ a) f) s) ++ "))" -- | Don't use this! It's a lie! instance Eq (Stream a) where _ == _ = True instance Functor Stream where fmap f (ListS l g) = ListS l (fmap (fmap f) g) instance Foldable Stream where foldMap f s = unstream (foldMap f) s mappend mempty instance NFData a => NFData (Stream a) where rnf (ListS !_ !s) = rnf s {-# INLINE unstream #-} unstream :: (FastMarkup a -> b) -> Stream a -> (b -> c -> c) -> c -> c unstream f (ListS l fm) cons nil = foldr (\x -> cons (f (fmap ($ x) fm))) nil l -------------------------------------------------------------------------------- -- Compiling data a :$ b = (:$) (FastMarkup (a -> b)) a deriving (Functor) infixl 0 :$ instance Show a => Show (a :$ b) where show (a :$ b) = '(':showsPrec 11 b (' ':':':'$':' ':showsPrec 11 (b <$ a) ")") data FastMarkup a = Bunch {-# UNPACK #-} !(Vector (FastMarkup a)) -- could unpack this manually but would then have to also write -- Show/Eq/Functor/Foldable manually | FStream !(Stream a) | FHole !IsEscaped !a | FLText TL.Text | FSText {-# UNPACK #-} !Text | FBuilder !TLB.Builder | FEmpty | FDeep (FastMarkup (FastMarkup a)) deriving (Show, Eq, Functor, Foldable, Generic) instance Monoid (FastMarkup a) where mempty = FBuilder mempty mappend a b = Bunch [a, b] instance NFData a => NFData (FastMarkup a) where rnf f = case f of Bunch v -> rnf v FStream s -> rnf s FLText t -> rnf t FSText t -> rnf t FHole !_ a -> rnf a _ -> () makeBaseFunctor ''Markup' deriveBifunctor ''Markup'F {-# INLINE plateFM #-} -- | Unlike 'plate', this uses 'Monad'. That's because 'traverse' over 'Vector' -- is really quite slow. plateFM :: Monad m => (FastMarkup a -> m (FastMarkup a)) -> FastMarkup a -> m (FastMarkup a) plateFM f x = case x of Bunch v -> Bunch <$> V.mapM f v _ -> pure x compileAttrs :: forall a. Vector (Attr a) -> (TLB.Builder, Vector (Attr a)) compileAttrs v = (static, dynAttrs) where isHoly :: Foldable f => f a -> Bool isHoly = foldr (\_ _ -> True) False staticAttrs :: Vector (Attr a) dynAttrs :: Vector (Attr a) (dynAttrs, staticAttrs) = case V.unstablePartition isHoly v of (dyn, stat) -> (dyn, stat) static :: TLB.Builder static = V.foldr (\((:=) key val) xs -> " " <> TLB.fromText key <> "=\"" <> escapeText val <> "\"" <> xs) mempty staticAttrs escapeText :: Text -> TLB.Builder escapeText = Blaze.renderMarkupBuilder . Blaze.text {-# INLINE escape #-} escape :: SomeText -> TLB.Builder escape st = case st of StrictT t -> Blaze.renderMarkupBuilder (Blaze.text t) LazyT t -> Blaze.renderMarkupBuilder (Blaze.lazyText t) BuilderT t -> Blaze.renderMarkupBuilder (Blaze.textBuilder t) toText :: TLB.Builder -> Text toText = TL.toStrict . TLB.toLazyText fastAttr :: Attr a -> FastMarkup a fastAttr ((:-) k v) = Bunch [FSText (" " <> k <> "=\""), FHole DoEscape v, FSText "\""] fastAttr _ = error "very bad" fast :: Markup' a -> FastMarkup a fast m = case m of Doctype -> FSText "<!DOCTYPE html>\n" Node t attrs m' -> case compileAttrs attrs of (staticAttrs, dynAttrs) -> case V.length dynAttrs of 0 -> Bunch [ FSText (T.concat ["<", t, toText staticAttrs, ">"]) , fast m' , FSText (T.concat ["</", t, ">"]) ] _ -> Bunch [ FBuilder ("<" <> TLB.fromText t <> staticAttrs) , Bunch (V.map fastAttr dynAttrs) , FSText ">" , fast m' , FSText ("</" <> t <> ">") ] VoidNode t attrs -> case compileAttrs attrs of (staticAttrs, dynAttrs) -> case V.length dynAttrs of 0 -> FSText (T.concat ["<", t, toText staticAttrs, " />"]) _ -> Bunch [ FBuilder ("<" <> TLB.fromText t <> staticAttrs) , Bunch (V.map fastAttr dynAttrs) , FSText " />" ] Text DoEscape t -> FBuilder (escape t) Text Don'tEscape t -> case t of StrictT a -> FSText a LazyT a -> FLText a BuilderT a -> FBuilder a List v -> Bunch (V.map fast (V.fromList v)) Hole e v -> FHole e v Stream a -> FStream a Empty -> FEmpty Precompiled fm -> fm -- | Look for an immediate string-like term and render that immediateRender :: FastMarkup a -> Maybe TLB.Builder immediateRender fm = case fm of FBuilder t -> Just t FSText t -> Just (TLB.fromText t) FLText t -> Just (TLB.fromLazyText t) FEmpty -> Just mempty _ -> Nothing -- | Flatten a vector of 'FastMarkup. String-like terms that are next to -- eachother should be combined munch :: Vector (FastMarkup a) -> Vector (FastMarkup a) munch v = V.fromList (go mempty 0) where len = V.length v go acc i | i < len = let e = V.unsafeIndex v i in case immediateRender e of Just b -> go (acc <> b) (i + 1) Nothing -> FBuilder acc : e : go mempty (i + 1) | otherwise = [FBuilder acc] -- | Recursively flatten 'FastMarkup' until doing so does nothing flatten :: FastMarkup a -> FastMarkup a flatten fm = case fm of FStream t -> FStream t -- ignore streams _ -> go where go = again $ case fm of Bunch v -> case V.length v of 0 -> FEmpty 1 -> V.head v _ -> Bunch (munch (V.concatMap (\x -> case x of Bunch v' -> v' FEmpty -> V.empty _ -> V.singleton (flatten x)) v)) _ -> runIdentity (plateFM (Identity . flatten) fm) again a -- Eq but ignore holes | (() <$ a) == (() <$ fm) = fm | otherwise = flatten a -- | Run all Text builders strictify :: FastMarkup a -> FastMarkup a strictify fm = case fm of FBuilder t -> FLText (TLB.toLazyText t) FLText t -> FLText t _ -> runIdentity (plateFM (Identity . strictify) fm) -- | Compile 'Markup''' compile_ :: Markup' a -> FastMarkup a compile_ = strictify . flatten . fast recompile :: FastMarkup a -> FastMarkup a recompile = strictify . flatten unlayer :: FastMarkup (FastMarkup a) -> FastMarkup a unlayer = FDeep -------------------------------------------------------------------------------- -- Rendering {-# SPECIALISE renderM :: (a -> Identity TLB.Builder) -> FastMarkup a -> Identity TLB.Builder #-} {-# INLINE renderM #-} -- | Render 'FastMarkup' renderM :: Monad m => (a -> m TLB.Builder) -> FastMarkup a -> m TLB.Builder renderM f = go where go fm = case fm of Bunch v -> V.foldM (\acc x -> mappend acc <$> go x) mempty v FBuilder t -> return t FSText t -> return (TLB.fromText t) FLText t -> return (TLB.fromLazyText t) FHole esc a -> case esc of DoEscape -> Blaze.renderMarkupBuilder . Blaze.textBuilder <$> f a Don'tEscape -> f a FStream str -> unstream go str (liftM2 mappend) (return mempty) FDeep a -> renderM go a _ -> return mempty {-# INLINE renderMs #-} -- | Render 'FastMarkup' by recursively rendering any sub-markup. renderMs :: Monad m => (a -> m (FastMarkup Void)) -> FastMarkup a -> m TLB.Builder renderMs f = renderM (f >=> renderMs (f . absurd)) {-# INLINE render #-} -- | Render 'FastMarkup' that has no holes. render :: FastMarkup Void -> TLB.Builder render = runIdentity . renderM absurd {-# INLINE r_ #-} r_ :: Render a Identity => a -> TLB.Builder r_ = runIdentity . r class Render a m where r :: a -> m TLB.Builder -- needs undecidableinstances ... instance (Render b m, m' ~ ReaderT a m) => Render (a -> b) m' where {-# INLINE r #-} r f = ReaderT (r . f) -- | Defer application of an argument to rendering instance (Monad m, Render b m) => Render (a :$ b) m where {-# INLINE r #-} r (b :$ a) = renderM (\f -> r (f a)) b instance Monad m => Render Void m where {-# INLINE r #-} r = return . absurd instance Monad m => Render TLB.Builder m where {-# INLINE r #-} r = return instance Monad m => Render T.Text m where {-# INLINE r #-} r = return . TLB.fromText instance Monad m => Render TL.Text m where {-# INLINE r #-} r = return . TLB.fromLazyText instance {-# OVERLAPPABLE #-} (Render a m, Monad m) => Render (FastMarkup a) m where {-# INLINE r #-} r = renderM r newtype RenderToFastMarkup a = RenderToFastMarkup { unToFastMarkup :: a } instance (ToFastMarkup a, Monad m) => Render (RenderToFastMarkup a) m where {-# INLINE r #-} r = r . (toFastMarkup :: a -> FastMarkup Void) . unToFastMarkup -------------------------------------------------------------------------------- class ToFastMarkup a where toFastMarkup :: a -> FastMarkup b instance ToFastMarkup (FastMarkup Void) where toFastMarkup = vacuous instance ToFastMarkup Text where {-# INLINE toFastMarkup #-} toFastMarkup = FSText instance ToFastMarkup TL.Text where {-# INLINE toFastMarkup #-} toFastMarkup = FLText instance ToFastMarkup TLB.Builder where {-# INLINE toFastMarkup #-} toFastMarkup = FBuilder newtype AsDecimal a = AsDecimal { asDecimal :: a } instance Integral a => ToFastMarkup (AsDecimal a) where {-# INLINE toFastMarkup #-} toFastMarkup = toFastMarkup . TLB.decimal . asDecimal newtype AsHex a = AsHex { asHex :: a } instance Integral a => ToFastMarkup (AsHex a) where {-# INLINE toFastMarkup #-} toFastMarkup = toFastMarkup . TLB.hexadecimal . asHex newtype AsRealFloat a = AsRealFloat { asRealFloat :: a } instance RealFloat a => ToFastMarkup (AsRealFloat a) where {-# INLINE toFastMarkup #-} toFastMarkup = toFastMarkup . TLB.realFloat . asRealFloat
TransportEngineering/nice-html
src/Text/Html/Nice/Internal.hs
Haskell
mit
12,438
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module BarthPar.Data where import Conduit import Control.Error import Control.Lens import qualified Data.Aeson as A import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.Char8 as L8 import Data.Csv import qualified Data.Csv as Csv import qualified Data.Vector as V import BarthPar.Lens import BarthPar.Parallel import BarthPar.Types splitTabs :: FromRecord a => L8.ByteString -> Either String (V.Vector a) splitTabs = traverse (Csv.runParser . parseRecord . V.fromList . fmap L8.toStrict . L8.split '\t') . V.fromList . L8.lines lazyWriteNetwork :: Int -> FilePath -> Network -> Script () lazyWriteNetwork chunkSize output n = runResourceT $ doc n $$ sinkFile output where doc Network{..} = do yield "{\"nodes\":" injectJsonArray $ smartMap chunkSize A.encode nodes yield ",\"links\":" injectJsonArray $ smartMap chunkSize A.encode links yield "}" injectJsonArray :: Monad m => [BL.ByteString] -> Source m BL.ByteString injectJsonArray [] = yield "[]" injectJsonArray (x:xs) = do yield "[" yield x mapM_ item xs yield "]" where item y = yield "," >> yield y {-# INLINE item #-} getWord :: InputRow -> Token getWord = view inputWord
erochest/barth-scrape
src/BarthPar/Data.hs
Haskell
apache-2.0
1,497
module Palindromes.A249642Spec (main, spec) where import Test.Hspec import Palindromes.A249642 (a249642) main :: IO () main = hspec spec spec :: Spec spec = describe "A249642" $ it "correctly computes the first 10 elements" $ take 10 (map a249642 [0..]) `shouldBe` expectedValue where expectedValue = [0,0,9,153,1449,13617,123129,1113273,10024569,90266553]
peterokagey/haskellOEIS
test/Palindromes/A249642Spec.hs
Haskell
apache-2.0
371
{-| Module : Text.ABNF.Document Description : Documents according to an ABNF definition Copyright : (c) Martin Zeller, 2016 License : BSD2 Maintainer : Martin Zeller <mz.bremerhaven@gmail.com> Stability : experimental Portability : non-portable -} module Text.ABNF.Document ( -- * Document types -- | Re-exported from "Text.ABNF.Document.Types" Document(..) -- * Reducing documents -- | Re-exported from "Text.ABNF.Document.Operations" -- -- In most cases, you don't want to work with the full tree of a 'Document'. -- You can use these cases to 'filterDocument' away any branches you do not -- need and 'squashDocumentOn' those, where you don't need it as -- fine-grained. -- -- This is incredibly useful if you have rules that parse single characters. , filterDocument , squashDocument , squashDocumentOn , lookupDocument , lookupDocument' , getContent -- * Parsing documents -- | Re-exported from "Text.ABNF.Document.Parser" , generateParser , parseDocument ) where import Text.ABNF.Document.Types ( Document(..) ) import Text.ABNF.Document.Operations ( filterDocument , squashDocument , squashDocumentOn , getContent , lookupDocument , lookupDocument' ) import Text.ABNF.Document.Parser ( generateParser , parseDocument )
Xandaros/abnf
src/Text/ABNF/Document.hs
Haskell
bsd-2-clause
1,662
module Main where import Criterion import Criterion.Main main :: IO () main = defaultMain [ env (return ()) $ \ ~() -> bgroup "\"oops\"" [bench "dummy" $ nf id ()] , env (return ()) $ \ ~() -> bgroup "'oops'" [bench "dummy" $ nf id ()] ]
bos/criterion
examples/Quotes.hs
Haskell
bsd-2-clause
266
module Database.Narc.Rewrite where import Data.Maybe (fromMaybe) import Database.Narc.AST import Database.Narc.Type import Database.Narc.Util (alistmap) -- | In @perhaps f x@, use @f@ to transform @x@, unless it declines by -- returning @Nothing@, in which case return @x@ unchanged. perhaps :: (a -> Maybe a) -> a -> a perhaps f x = fromMaybe x (f x) -- | Apply @f@ to each subterm of a given term, in a bottom-up fashion. bu :: (Term a -> Maybe (Term a)) -> Term a -> Term a bu f (Unit, d) = perhaps f (Unit, d) bu f (Bool b, d) = perhaps f (Bool b, d) bu f (Num n, d) = perhaps f (Num n, d) bu f (Var x, d) = perhaps f (Var x, d) bu f (Abs x n, d) = perhaps f (Abs x (bu f n), d) bu f (App l m, d) = perhaps f (App (bu f l) (bu f m), d) bu f (If c a b, d) = perhaps f (If (bu f c) (bu f a) (bu f b), d) bu f (Table tab fields, d) = perhaps f (Table tab fields, d) bu f (Singleton m, d) = perhaps f (Singleton (bu f m), d) bu f (Record fields, d) = perhaps f (Record (alistmap (bu f) fields), d) bu f (Project m a, d) = perhaps f (Project (bu f m) a, d) bu f (Comp x src body, d) = perhaps f (Comp x (bu f src) (bu f body), d) bu f (PrimApp fun args, d) = perhaps f (PrimApp fun args, d) bu f (Nil, d) = perhaps f (Nil, d) bu f (Union a b, d) = perhaps f (Union a b, d) -- | Small-step version of compilation: local rewrite rules applied -- willy-nilly. (Incomplete?) rw (Comp x (Singleton m, _) n, t) = Just (substTerm x m n) rw (App (Abs x n, st) m, t) = Just (substTerm x m n) rw (Project (Record fields, rect) fld, t) = lookup fld fields rw (Singleton (Var x, xT), t) = Nothing -- for now rw (Comp x (Nil, _) n, t) = Just (Nil, t) rw (Comp x m (Nil, _), t) = Just (Nil, t) rw (Comp x (Comp y l m, s) n, t) = if y `notElem` fvs n then Just (Comp y l (Comp x m n, t), t) else Nothing rw (Comp x (m1 `Union` m2, s) n, t) = Just ((Comp x m1 n, t) `Union` (Comp x m2 n, t), t) rw (Comp x m (n1 `Union` n2, _), t) = Just ((Comp x m n1, t) `Union` (Comp x m n2, t), t) rw (Comp x (If b m (Nil, _), _) n, t) = Just (Comp x m (If b n (Nil, t), t), t) rw (If (b, bTy) m n, t@(TList _, _)) | fst n /= Nil = Just((If (b,bTy) m (Nil, t), t) `Union` (If (PrimApp "not" [(b, bTy)], bTy) n (Nil, t), t), t) rw (If b (Nil, _) (Nil, _), t) = Just (Nil, t) rw (If b (Comp x m n, _) (Nil, _), t) = Just (Comp x m (If b n (Nil, t), t), t) rw (If b (m1 `Union` m2, _) (Nil, _), t) = Just ((If b m1 (Nil, t), t) `Union` (If b m2 (Nil, t), t), t) -- push App inside If -- push Project inside If -- push If inside Record -- rw (IsEmpty m, t) -- | lorob t = Nothing -- | otherwise = -- IsEmpty (Comp "x" m (Singleton (Unit, TUnit), TList Tunit), TList TUnit) rw _ = Nothing
ezrakilty/narc
Database/Narc/Rewrite.hs
Haskell
bsd-2-clause
2,786
import Types import Genetic import Runner import Control.Monad.State import Control.Lens import System.Random main = do -- Create a prog with some haskell code let prog = (def :: StateMachine) & code .~ (read "[+>++<].") -- Execute the prog let res = execState (exec 5000) prog -- Now we have access to everithing (strip state, code, output, etc.) showVm res -- Display the strip around the current position, the output, and -- the illness state (tell if the vm "crashed"). showVm res = do putStrLn . showStrip 5 $ (res ^. strip) putStrLn $ (res ^. output) putStrLn . show $ (res ^. illField) main' str = do -- Create a prog with some haskell code let prog = (def :: StateMachine) & code .~ (read str) -- Execute the prog let res = execState (exec 5000) prog -- Now we have access to everything (strip state, code, output, etc.) showVm res -- Generate a small sample of 50 instruction, and try to run it randomTry = do randLi <- sequence (take 100 $ repeat randomIO) :: IO [Sym] let vmState = (def :: StateMachine) & code .~ (Code randLi) let vm = execState (exec 800) vmState showVm $ vm return vm
Zenol/brainf_gen
Main.hs
Haskell
bsd-2-clause
1,212