code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Graphics.Quad( remapCoords , transformedQuad , screenQuad ) where import Data.Vec import Graphics.GPipe -- | Coordinates transformation from viewport system to specified local. This function maps points in particular -- region into texture coordinates. remapCoords :: Vec2 Float -> Vec2 Float -> Vec2 (Shader t Float) -> Vec2 (Shader t Float) remapCoords (ox:.oy:.()) (sx:.sy:.()) (ux:.uy:.()) = ux':.uy':.() where ux' = (ux - toGPU ox) / toGPU sx uy' = (uy - toGPU oy) / toGPU sy -- | Some trivial transformations for viewport quad. transformedQuad :: Float -> PrimitiveStream Triangle (Vec4 (Vertex Float), Vec2 (Vertex Float)) transformedQuad d = fmap homonize $ screenQuad d where homonize :: (Vec3 (Vertex Float), Vec2 (Vertex Float)) -> (Vec4 (Vertex Float), Vec2 (Vertex Float)) homonize (v,uv) = (homPoint v :: Vec4 (Vertex Float), uv) -- | Quad that covers all window screenQuad :: Float -> PrimitiveStream Triangle (Vec3 (Vertex Float), Vec2 (Vertex Float)) screenQuad d = toGPUStream TriangleList $ zip vecs uvs where vecs = [(-1):.(-1):.d:.(), 1:.1:.d:.(), (-1):.1:.d:.(), (-1):.(-1):.d:.(), 1:.(-1):.d:.(), 1:.1:.d:.()] uvs = [0:.1:.(), 1:.0:.(), 0:.0:.(), 0:.1:.(), 1:.1:.(), 1:.0:.()]
NCrashed/sinister
src/client/Graphics/Quad.hs
mit
1,354
0
12
322
613
322
291
18
1
import GenPw import System.Random import Control.Monad main :: IO () main = liftM (genPw 8) getStdGen >>= putStrLn
dex/genpw
Main.hs
mit
117
0
8
20
44
23
21
5
1
{-# LANGUAGE NoMonomorphismRestriction #-} module Plugins.Gallery.Gallery.Manual10 where import Diagrams.Prelude import Graphics.Rendering.Diagrams.Points example = stroke (star (StarSkip 2) (regPoly 8 1)) ||| strutX 1 ||| stroke (star (StarSkip 3) (regPoly 8 1))
andrey013/pluginstest
Plugins/Gallery/Gallery/Manual10.hs
mit
288
0
11
55
87
47
40
7
1
{-# LANGUAGE TypeOperators #-} module Lib ( Grid, makeGrid, gridFrom ) where import Data.Array.Repa import Data.Array.Repa.Index (DIM2, ix2) import Data.Ownership type Grid a = Array U DIM2 a makeGrid :: Int -> Int -> Grid Ownership makeGrid w h = gridFrom w h $ replicate (w * h) Nil {-# INLINE makeGrid #-} gridFrom :: Int -> Int -> [Ownership] -> Grid Ownership gridFrom w h = fromListUnboxed (ix2 w h) {-# INLINE gridFrom #-}
range12/gobang
src/Lib.hs
mit
468
0
8
113
149
83
66
16
1
-- | This module containts the Oden AST - the representation of the syntax. {-# LANGUAGE LambdaCase #-} module Oden.Syntax where import Oden.Identifier import Oden.SourceInfo import Oden.Type.Signature data NameBinding = NameBinding SourceInfo Identifier deriving (Show, Eq, Ord) data LetPair = LetPair SourceInfo NameBinding Expr deriving (Show, Eq, Ord) data FieldInitializer = FieldInitializer SourceInfo Identifier Expr deriving (Show, Eq, Ord) data BinaryOperator = Add | Subtract | Multiply | Divide | EqualTo | NotEqualTo | MonoidApply | LessThan | GreaterThan | LessThanEqual | GreaterThanEqual | And | Or deriving (Show, Eq, Ord) data UnaryOperator = Negate | Not deriving (Show, Eq, Ord) data Expr = Symbol SourceInfo Identifier | Subscript SourceInfo Expr [Subscript] | UnaryOp SourceInfo UnaryOperator Expr | BinaryOp SourceInfo BinaryOperator Expr Expr | Application SourceInfo Expr [Expr] | Fn SourceInfo [NameBinding] Expr | Let SourceInfo [LetPair] Expr | Literal SourceInfo Literal | If SourceInfo Expr Expr Expr | Slice SourceInfo [Expr] | Tuple SourceInfo Expr Expr [Expr] | Block SourceInfo [Expr] | RecordInitializer SourceInfo [FieldInitializer] | MemberAccess SourceInfo Expr Expr | ProtocolMethodReference SourceInfo Expr Expr deriving (Show, Eq, Ord) instance HasSourceInfo Expr where getSourceInfo = \case Symbol si _ -> si Subscript si _ _ -> si UnaryOp si _ _ -> si BinaryOp si _ _ _ -> si Application si _ _ -> si Fn si _ _ -> si Let si _ _ -> si Literal si _ -> si If si _ _ _ -> si Slice si _ -> si Tuple si _ _ _ -> si Block si _ -> si RecordInitializer si _ -> si MemberAccess si _ _ -> si ProtocolMethodReference si _ _ -> si setSourceInfo si = \case Symbol _ i -> Symbol si i Subscript _ s i -> Subscript si s i UnaryOp _ o r -> UnaryOp si o r BinaryOp _ p l r -> BinaryOp si p l r Application _ f a -> Application si f a Fn _ n b -> Fn si n b Let _ p b -> Let si p b Literal _ l -> Literal si l If _ c t e -> If si c t e Slice _ e -> Slice si e Tuple _ f s r -> Tuple si f s r Block _ e -> Block si e RecordInitializer _ fs -> RecordInitializer si fs MemberAccess _ pkgAlias name -> MemberAccess si pkgAlias name ProtocolMethodReference _ protocol method -> ProtocolMethodReference si protocol method data Subscript = Singular Expr | RangeTo Expr | RangeFrom Expr | Range Expr Expr deriving (Show, Eq, Ord) data Literal = Int Integer | Float Double | Bool Bool | String String | Unit deriving (Show, Eq, Ord) type PackageName = [String] data PackageDeclaration = PackageDeclaration SourceInfo PackageName deriving (Show, Eq, Ord) data RecordFieldExpr = RecordFieldExpr SourceInfo Identifier SignatureExpr deriving (Show, Eq, Ord) data Definition = ValueDefinition SourceInfo Identifier Expr | FnDefinition SourceInfo Identifier [NameBinding] Expr deriving (Show, Eq, Ord) data TopLevel = ImportDeclaration SourceInfo [String] | ImportForeignDeclaration SourceInfo String | TypeSignatureDeclaration SourceInfo Identifier TypeSignature | TopLevelDefinition Definition -- TODO: Add support for type parameters | TypeDefinition SourceInfo Identifier SignatureExpr | ProtocolDefinition SourceInfo Identifier SignatureVarBinding [ProtocolMethodSignature] | Implementation SourceInfo TypeSignature [Definition] deriving (Show, Eq, Ord) data Package = Package PackageDeclaration [TopLevel] deriving (Show, Eq, Ord)
oden-lang/oden
src/Oden/Syntax.hs
mit
4,519
0
9
1,722
1,174
611
563
113
0
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-} module Event where import DateTime import Data.Aeson.TH import Data.Aeson data Event = Event { start :: DateTime , end :: Maybe DateTime , description :: String } deriving (Show,Eq) instance ToJSON Event where toJSON (Event s Nothing d) = object [ "start" .= s, "description" .= d] toJSON (Event s (Just e) d) = object [ "start" .= s, "description" .= d ,"end" .= e] $(deriveFromJSON defaultOptions ''Event)
edwardwas/haskcal
src/Event.hs
mit
475
4
10
88
169
92
77
14
0
{-# LANGUAGE OverloadedStrings #-} module Y2021.M02.D05.Exercise where {-- Okay, yesterday we found lots of duplicates of wine-labels and, digging further, we saw some wines had multiple reviews from the same reviewer, but also, some wines had multiple reviews from multiple reviewers. This begs the question, however: so? Why do I say this? Well, down the road (not today), because a wine may have multiple reviews from a reviewer, that means there are going to be multiple RATES_WINE relations between the same two nodes (wine, taster), and to CREATE multiple relations, we cannot add to one relation, no: we have to create a new relation for each review. Which means, in which case, that we want all the current relations to go away, so that we can add relations between wines and tasters as we add each review (and rating ... and possibly price). So: there 'tis. What does that mean for us now? What that means, tactically-speaking, is that for each wine with wine ids, (h:t) * for h, we delete the relation r of (wine { id: h })-[r]-(taster); and, * for a ids in t, we detach delete w (the redundant wine). We do this for every wine in our graph-store, we then should have a newly- cleaned state by which we can (re-)start uploading reviews to our graph. Let's do it. Yesterday we got a mapping of all wines to their (possibly multiple) ids: --} import Y2021.M02.D04.Solution (nodeMap, NodeIds) import Y2021.M01.D21.Solution (Idx) import Graph.Query import Graph.JSON.Cypher import qualified Data.Text as T removeDuplicateWines :: Endpoint -> NodeIds -> IO String removeDuplicateWines url wines = undefined -- what removeDuplicateWines does is, for the first wine id (the head of the -- list), we remove the relation: removeRelationQuery :: Idx -> Cypher removeRelationQuery wineId = T.pack (unwords ["MATCH (w:Wine)<-[r:RATES_WINE]-()", "WHERE id(w) =", show wineId, "DELETE r"]) -- For the rest of the wine ids (the rest of the wine ids for a wine), we want -- to detach and delete those wines, because they are duplicates. removeWinesQuery :: [Idx] -> Cypher removeWinesQuery [] = "" removeWinesQuery l@(_:_) = T.pack (unwords ["MATCH (w:Wine) WHERE id(w) IN", show l,"DETACH DELETE w"]) -- Remove all the duplicate wines and all RATES_WINE relations. You may want -- to try this on one wine, then 10 wines, then 100 wines, ... just to see how -- work flows. -- Verify, after running removeDuplicateWines, that there are, in fact, no -- duplicate wines remaining in the graph store. -- When you verify no dupes, run an index on the Wine.title.
geophf/1HaskellADay
exercises/HAD/Y2021/M02/D05/Exercise.hs
mit
2,606
0
9
478
198
119
79
17
1
-- | -- Module: Math.NumberTheory.Primes.Sieve.Indexing -- Copyright: (c) 2011 Daniel Fischer -- Licence: MIT -- Maintainer: Daniel Fischer <[email protected]> -- Stability: Provisional -- Portability: Non-portable (GHC extensions) -- {-# OPTIONS_HADDOCK hide #-} module Math.NumberTheory.Primes.Sieve.Indexing ( idxPr , toPrim , toIdx , rho , delta , tau , byte , idx , mu , nu ) where import Data.Array.Unboxed import Data.Bits import Math.NumberTheory.Unsafe -- Auxiliary stuff, conversion between number and index, -- remainders modulo 30 and related things. -- {-# SPECIALISE idxPr :: Integer -> (Int,Int), -- Int -> (Int,Int), -- Word -> (Int,Int) -- #-} {-# INLINE idxPr #-} idxPr :: Integral a => a -> (Int,Int) idxPr n0 | n0 < 7 = (0, 0) | otherwise = (fromIntegral bytes0, rm3) where n = if (fromIntegral n0 .&. 1 == (1 :: Int)) then n0 else (n0-1) (bytes0,rm0) = (n-7) `quotRem` 30 rm1 = fromIntegral rm0 rm2 = rm1 `quot` 3 rm3 = min 7 (if rm2 > 5 then rm2-1 else rm2) -- {-# SPECIALISE toPrim :: Int -> Integer, -- Int -> Int, -- Int -> Word, -- Int -> Word16 -- #-} {-# INLINE toPrim #-} toPrim :: Integral a => Int -> a toPrim ix = 30*fromIntegral k + fromIntegral (rho i) where i = ix .&. 7 k = ix `shiftR` 3 -- Assumes n >= 7, gcd n 30 == 1 {-# INLINE toIdx #-} toIdx :: Integral a => a -> Int toIdx n = 8*fromIntegral q+r2 where (q,r) = (n-7) `quotRem` 30 r1 = fromIntegral r `quot` 3 r2 = min 7 (if r1 > 5 then r1-1 else r1) {-# INLINE rho #-} rho :: Int -> Int rho i = unsafeAt residues i residues :: UArray Int Int residues = listArray (0,7) [7,11,13,17,19,23,29,31] {-# INLINE delta #-} delta :: Int -> Int delta i = unsafeAt deltas i deltas :: UArray Int Int deltas = listArray (0,7) [4,2,4,2,4,6,2,6] {-# INLINE tau #-} tau :: Int -> Int tau i = unsafeAt taus i taus :: UArray Int Int taus = listArray (0,63) [ 7, 4, 7, 4, 7, 12, 3, 12 , 12, 6, 11, 6, 12, 18, 5, 18 , 14, 7, 13, 7, 14, 21, 7, 21 , 18, 9, 19, 9, 18, 27, 9, 27 , 20, 10, 21, 10, 20, 30, 11, 30 , 25, 12, 25, 12, 25, 36, 13, 36 , 31, 15, 31, 15, 31, 47, 15, 47 , 33, 17, 33, 17, 33, 49, 17, 49 ] {-# INLINE byte #-} byte :: Int -> Int byte i = unsafeAt startByte i startByte :: UArray Int Int startByte = listArray (0,7) [1,3,5,9,11,17,27,31] {-# INLINE idx #-} idx :: Int -> Int idx i = unsafeAt startIdx i startIdx :: UArray Int Int startIdx = listArray (0,7) [4,7,4,4,7,4,7,7] {-# INLINE mu #-} mu :: Int -> Int mu i = unsafeAt mArr i {-# INLINE nu #-} nu :: Int -> Int nu i = unsafeAt nArr i mArr :: UArray Int Int mArr = listArray (0,63) [ 1, 2, 2, 3, 4, 5, 6, 7 , 2, 3, 4, 6, 6, 8, 10, 11 , 2, 4, 5, 7, 8, 9, 12, 13 , 3, 6, 7, 9, 10, 12, 16, 17 , 4, 6, 8, 10, 11, 14, 18, 19 , 5, 8, 9, 12, 14, 17, 22, 23 , 6, 10, 12, 16, 18, 22, 27, 29 , 7, 11, 13, 17, 19, 23, 29, 31 ] nArr :: UArray Int Int nArr = listArray (0,63) [ 4, 3, 7, 6, 2, 1, 5, 0 , 3, 7, 5, 0, 6, 2, 4, 1 , 7, 5, 4, 1, 0, 6, 3, 2 , 6, 0, 1, 4, 5, 7, 2, 3 , 2, 6, 0, 5, 7, 3, 1, 4 , 1, 2, 6, 7, 3, 4, 0, 5 , 5, 4, 3, 2, 1, 0, 7, 6 , 0, 1, 2, 3, 4, 5, 6, 7 ]
cfredric/arithmoi
Math/NumberTheory/Primes/Sieve/Indexing.hs
mit
3,559
0
11
1,191
1,447
883
564
96
3
{-# LANGUAGE GeneralizedNewtypeDeriving #-} import Control.Monad.Reader import Control.Monad.Writer import Control.Monad.State type Stack = [Int] type Output = [Int] type Program = [Instr] type VM a = ReaderT Program (WriterT Output (State Stack)) a newtype Comp a = Comp { unComp :: VM a } deriving (Monad, MonadReader Program, MonadWriter Output, MonadState Stack) data Instr = Push Int | Pop | Puts evalInstr :: Instr -> Comp () evalInstr instr = case instr of Pop -> modify tail Push n -> modify (n:) Puts -> do tos <- gets head tell [tos] eval :: Comp () eval = do instr <- ask case instr of [] -> return () (i:is) -> evalInstr i >> local (const is) eval execVM :: Program -> Output execVM = flip evalState [] . execWriterT . runReaderT (unComp eval) program :: Program program = [ Push 42, Push 27, Puts, Pop, Puts, Pop ] main :: IO () main = mapM_ print $ execVM program -- Another hoist implementation import Control.Monad.State import Control.Monad.Morph type Eval a = State [Int] a runEval :: [Int] -> Eval a -> a runEval = flip evalState pop :: Eval Int pop = do top <- gets head modify tail return top push :: Int -> Eval () push x = modify (x:) ev1 :: Eval Int ev1 = do push 3 push 4 pop pop -- hoist :: Monad m => (forall a. m a -> n a) -> t m b -> t n b -- generalize :: Monad m => Identity a -> m a ev2 :: StateT [Int] IO () ev2 = do result <- hoist generalize ev1 liftIO $ putStrLn $ "Result: " ++ show result
Airtnp/Freshman_Simple_Haskell_Lib
Intro/WIW/VM.hs
mit
1,587
0
13
440
582
303
279
-1
-1
{-# LANGUAGE OverloadedStrings #-} module PivotalTracker.Label(updateLabelsOnStories) where import Control.Monad.Trans(lift) import World import Schema import Control.Monad.Trans.Reader import Control.Lens((.~), (^.), (^?), (&), re) import qualified Data.ByteString.Char8 as BCH import Control.Monad(liftM) import Network.Wreq(FormParam( (:=) ), defaults, responseBody, header) import Data.Aeson.Lens (_Array) import Data.Aeson(Value(..)) import Data.Scientific(coefficient, Scientific(..)) import qualified Data.Text as T import Control.Applicative((<$>), (<*>)) import qualified Data.Maybe as MB import qualified Data.HashMap.Strict as HMS import qualified Data.Vector as V import App.Environment import qualified Network.Wreq as NW import qualified Network.Wreq.Types as NWT updateLabelsOnStories :: World m => String -> [PivotalStory] -> ReaderT Environment m () updateLabelsOnStories label stories = mapM_ (updateLabels label) stories data PivotalLabel = PivotalLabel { labelId :: Integer, labelText :: BCH.ByteString } deriving Show type Label = String updateLabels :: World m => Label -> PivotalStory -> ReaderT Environment m () updateLabels label story = do previousLabels <- getPreviousDeployLabels story if newLabelNeeded label previousLabels then do let labelsToDestroy = filter (not . partOfDeployPipeline) $ filter deploymentLabel previousLabels removeLabels story labelsToDestroy labelStory label story else return () labelStory :: World m => Label -> PivotalStory -> ReaderT Environment m () labelStory label story = do apiToken <- pivotalTrackerApiToken `liftM` ask let requestOptions = (pivotalApiOptions apiToken) & header "Content-Type" .~ ["application/json"] let formBody = "name" := label lift $ tryRequest $ postWith requestOptions (labelsUrl story) formBody return () deploymentPipelineLabels = ["deployed to zephyr-production", "deployed to zephyr-integration", "deployed to zephyr-preproduction" ] deploymentLabel :: PivotalLabel -> Bool deploymentLabel label = "deployed to " `BCH.isInfixOf` labelText label newLabelNeeded :: Label -> [PivotalLabel] -> Bool newLabelNeeded newLabel previousLabels = (deploymentPipelineLabel newLabel) || (not $ any inPipeline previousLabels) where deploymentPipelineLabel :: Label -> Bool deploymentPipelineLabel newLabel = (BCH.pack newLabel) `elem` deploymentPipelineLabels inPipeline :: PivotalLabel -> Bool inPipeline label = labelText label `elem` deploymentPipelineLabels removeLabels :: World m => PivotalStory -> [PivotalLabel] -> ReaderT Environment m () removeLabels story labels = do mapM_ removeLabel labels where removeLabel :: World m => PivotalLabel -> ReaderT Environment m () removeLabel label = do apiToken <- pivotalTrackerApiToken `liftM` ask let requestOptions = (pivotalApiOptions apiToken) & header "Content-Type" .~ ["application/json"] lift . tryRequest . (deleteWith requestOptions) . T.unpack $ labelDestroyUrl story label return () pivotalApiOptions token = defaults & header "X-TrackerToken" .~ [token] partOfDeployPipeline :: PivotalLabel -> Bool partOfDeployPipeline label = labelText label `elem` deploymentPipelineLabels labelDestroyUrl :: PivotalStory -> PivotalLabel -> T.Text labelDestroyUrl story label = T.concat ["https://www.pivotaltracker.com/services/v5/projects/", intToText (pivotalStoryProjectId story), "/stories/", (pivotalStoryTrackerId story), "/labels/", (T.pack . show $ labelId label) ] getPreviousDeployLabels :: World m => PivotalStory -> ReaderT Environment m [PivotalLabel] getPreviousDeployLabels story = do apiToken <- pivotalTrackerApiToken `liftM` ask let requestOptions = (pivotalApiOptions apiToken) & header "Content-Type" .~ ["application/json"] response <- lift . tryRequest $ getWith requestOptions (labelsUrl story) case response of Right res -> do let stories = MB.catMaybes . V.toList $ V.map pivotalLabelsFromReponse (res ^. responseBody . _Array) return stories Left a -> return [] extractByteString :: Value -> BCH.ByteString extractByteString (String t) = BCH.pack $ T.unpack t extractByteString _ = "" extractInteger :: Value -> Integer extractInteger (Number s) = coefficient s extractInteger _ = -1 pivotalLabelsFromReponse :: Value -> Maybe PivotalLabel pivotalLabelsFromReponse (Object val) = PivotalLabel <$> (extractInteger <$> HMS.lookup "id" val) <*> (extractByteString <$> HMS.lookup "name" val) labelsUrl :: PivotalStory -> String labelsUrl story = concat ["https://www.pivotaltracker.com/services/v5/projects/", show (pivotalStoryProjectId story), "/stories/", (T.unpack $ pivotalStoryTrackerId story), "/labels"] intToText = T.pack . show
zephyr-dev/flow-api
src/PivotalTracker/Label.hs
mit
4,935
100
16
896
1,323
728
595
-1
-1
mergeSort :: (Ord a) => [a] -> [a] mergeSort xs = merge . divide $ xs divide :: [a] -> [[a]] divide = map (\x -> [x]) mergeTwo :: (Ord a) => [a] -> [a] -> [a] mergeTwo xs [] = xs mergeTwo [] ys = ys mergeTwo (x:xs) (y:ys) = if x <= y then x:mergeTwo xs (y:ys) else y:mergeTwo (x:xs) ys mergeIter :: (Ord a) => [[a]] -> [[a]] mergeIter [] = [] mergeIter [x] = [x] mergeIter (x:y:t) = mergeTwo x y : (mergeIter t) merge' :: (Ord a) => Int -> [[a]] -> [[a]] merge' n xs | n <= 1 = xs merge' n xs = merge' (n-1) (mergeIter xs) merge :: (Ord a) => [[a]] -> [a] merge xs = concat $ merge' (length xs) xs
RAFIRAF/HASKELL
mergeSort2.hs
mit
604
0
9
138
426
230
196
17
2
module Day03 where type Triangle = (Int, Int, Int) intsFromStr :: String -> [Int] intsFromStr input = map (\i -> read i ::Int) (words input) take3 :: [Int] -> [Triangle] take3 = take3' [] where take3' acc [] = acc take3' acc ints' = take3' ((i,j,k):acc) rest where [i,j,k] = take 3 ints' rest = drop 3 ints' skip3 :: [Int] -> [Triangle] skip3 ints = take3 ([a | (i, a) <- ints', i `mod` 3 == 0 ] ++ [b | (i, b) <- ints', i `mod` 3 == 1 ] ++ [c | (i, c) <- ints', i `mod` 3 == 2 ]) where ints' = zip [0..] ints trianglesFromString :: String -> ([Int] -> [Triangle]) -> [Triangle] trianglesFromString s fn = fn (intsFromStr s) legal (a, b, c) = a + b > c && a + c > b && c + b > a
tftio/advent-of-code-2016
src/Day03.hs
cc0-1.0
757
0
12
227
409
226
183
22
2
-- | -- Module : $Header$ -- Description : The base Ohua compiler monad -- Copyright : (c) Justus Adam 2017. All Rights Reserved. -- License : EPL-1.0 -- Maintainer : [email protected], [email protected] -- Stability : experimental -- Portability : POSIX -- This source code is licensed under the terms described in the associated LICENSE.TXT file {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE Rank2Types #-} module Ohua.Internal.Monad where import Universum import Control.Monad.Except import Control.Monad.Logger import qualified Control.Monad.RWS.Lazy import Control.Monad.RWS.Strict (RWST, evalRWST) import qualified Control.Monad.State.Lazy import qualified Control.Monad.State.Strict import Control.Monad.Writer (WriterT) import Data.Default.Class import qualified Data.HashSet as HS import qualified Data.Text as T import qualified Data.Vector as V import Control.Lens.Plated import Control.Lens.Operators ((%=), (.=)) import Ohua.Types as Ty import Ohua.ALang.Lang -- The compiler monad. -- Encapsulates the state necessary to generate bindings -- Allows IO actions. -- In development this collects errors via a MonadWriter, in production this collection will -- be turned off and be replaced by an exception, as such errors should technically not occur -- there newtype OhuaM env a = OhuaM { runOhuaM :: RWST Environment () (OhuaState env) (ExceptT Error (LoggingT IO)) a } deriving ( Functor , Applicative , Monad , MonadIO , MonadError Error , MonadLogger , MonadLoggerIO ) class Monad m => MonadGenBnd m where generateBinding :: m Binding default generateBinding :: (MonadGenBnd n, MonadTrans t, t n ~ m) => m Binding generateBinding = lift generateBinding generateBindingWith :: Binding -> m Binding default generateBindingWith :: ( MonadGenBnd n , MonadTrans t , t n ~ m ) => Binding -> m Binding generateBindingWith = lift . generateBindingWith deepseqM :: (Monad m, NFData a) => a -> m () deepseqM a = a `deepseq` pure () instance MonadGenBnd (OhuaM env) where generateBinding = OhuaM $ generateBindingIn nameGenerator generateBindingWith = OhuaM . generateBindingWithIn nameGenerator generateBindingFromGenerator :: NameGenerator -> (Binding, NameGenerator) generateBindingFromGenerator g = (h, g') where taken = g ^. takenNames (h, t) = case dropWhile (`HS.member` taken) (g ^. simpleNameList) of (x:xs) -> (x, xs) [] -> error "Simple names is empty, this should be impossible" g' = g & simpleNameList .~ t & takenNames %~ HS.insert h generateBindingFromGeneratorWith :: Binding -> NameGenerator -> (Binding, NameGenerator) generateBindingFromGeneratorWith prefixBnd g = (h, g') where prefix = unwrap prefixBnd taken = g ^. takenNames prefix' = prefix <> "_" h = fromMaybe (error "IMPOSSIBLE") $ safeHead $ dropWhile (`HS.member` taken) $ map (makeThrow . (prefix' <>) . show) ([0 ..] :: [Int]) g' = g & takenNames %~ HS.insert h generateBindingIn :: MonadState s m => Lens' s NameGenerator -> m Binding generateBindingIn accessor = do (bnd, gen') <- generateBindingFromGenerator <$> use accessor accessor .= gen' pure bnd generateBindingWithIn :: MonadState s m => Lens' s NameGenerator -> Binding -> m Binding generateBindingWithIn accessor prefix = do (bnd, gen') <- generateBindingFromGeneratorWith prefix <$> use accessor accessor .= gen' pure bnd instance (MonadGenBnd m, Monad m) => MonadGenBnd (ReaderT e m) instance (MonadGenBnd m, Monad m, Monoid w) => MonadGenBnd (WriterT w m) instance (MonadGenBnd m, Monad m) => MonadGenBnd (Control.Monad.State.Strict.StateT s m) instance (MonadGenBnd m, Monad m) => MonadGenBnd (Control.Monad.State.Lazy.StateT s m) instance (MonadGenBnd m, Monad m, Monoid w) => MonadGenBnd (Control.Monad.RWS.Strict.RWST e w s m) instance (MonadGenBnd m, Monad m, Monoid w) => MonadGenBnd (Control.Monad.RWS.Lazy.RWST e w s m) class MonadGenId m where generateId :: m FnId default generateId :: (MonadGenId n, Monad n, MonadTrans t, t n ~ m) => m FnId generateId = lift generateId -- | Unsafe. Only use this if yoy know what you are doing!! resetIdCounter :: FnId -> m () default resetIdCounter :: (MonadGenId n, Monad n, MonadTrans t, t n ~ m) => FnId -> m () resetIdCounter = lift . resetIdCounter instance MonadGenId (OhuaM env) where generateId = OhuaM $ do idCounter %= succ use idCounter resetIdCounter val = OhuaM $ idCounter .= val instance (MonadGenId m, Monad m) => MonadGenId (ReaderT e m) instance (MonadGenId m, Monad m, Monoid w) => MonadGenId (WriterT w m) instance (MonadGenId m, Monad m) => MonadGenId (Control.Monad.State.Strict.StateT s m) instance (MonadGenId m, Monad m) => MonadGenId (Control.Monad.State.Lazy.StateT s m) instance (MonadGenId m, Monad m, Monoid w) => MonadGenId (Control.Monad.RWS.Lazy.RWST e w s m) instance (MonadGenId m, Monad m, Monoid w) => MonadGenId (Control.Monad.RWS.Strict.RWST e w s m) class HasEnvExpr (m :: * -> *) where type EnvExpr m instance HasEnvExpr (OhuaM e) where type EnvExpr (OhuaM e) = e instance HasEnvExpr (ReaderT e m) where type EnvExpr (ReaderT e m) = EnvExpr m instance HasEnvExpr (WriterT w m) where type EnvExpr (WriterT w m) = EnvExpr m instance HasEnvExpr (Control.Monad.State.Strict.StateT s m) where type EnvExpr (Control.Monad.State.Strict.StateT s m) = EnvExpr m instance HasEnvExpr (Control.Monad.State.Lazy.StateT s m) where type EnvExpr (Control.Monad.State.Lazy.StateT s m) = EnvExpr m instance HasEnvExpr (Control.Monad.RWS.Lazy.RWST e w s m) where type EnvExpr (Control.Monad.RWS.Lazy.RWST e w s m) = EnvExpr m instance HasEnvExpr (Control.Monad.RWS.Strict.RWST e w s m) where type EnvExpr (Control.Monad.RWS.Strict.RWST e w s m) = EnvExpr m class HasEnvExpr m => MonadReadEnvExpr m where lookupEnvExpr :: HostExpr -> m (Maybe (EnvExpr m)) default lookupEnvExpr :: ( MonadReadEnvExpr n , MonadTrans t , Monad n , m ~ t n , EnvExpr m ~ EnvExpr n ) => HostExpr -> m (Maybe (EnvExpr m)) lookupEnvExpr = lift . lookupEnvExpr instance MonadReadEnvExpr (OhuaM env) where lookupEnvExpr i = OhuaM $ (V.!? unwrap i) <$> use envExpressions instance (MonadReadEnvExpr m, Monad m) => MonadReadEnvExpr (ReaderT e m) instance (MonadReadEnvExpr m, Monad m, Monoid w) => MonadReadEnvExpr (WriterT w m) instance (MonadReadEnvExpr m, Monad m) => MonadReadEnvExpr (Control.Monad.State.Strict.StateT s m) instance (MonadReadEnvExpr m, Monad m) => MonadReadEnvExpr (Control.Monad.State.Lazy.StateT s m) instance (MonadReadEnvExpr m, Monad m, Monoid w) => MonadReadEnvExpr (Control.Monad.RWS.Lazy.RWST e w s m) instance (MonadReadEnvExpr m, Monad m, Monoid w) => MonadReadEnvExpr (Control.Monad.RWS.Strict.RWST e w s m) getEnvExpr :: (MonadError Error m, MonadReadEnvExpr m) => HostExpr -> m (EnvExpr m) getEnvExpr = maybe (throwError msg) pure <=< lookupEnvExpr where msg = "Invariant violated, host expression was not defined." class HasEnvExpr m => MonadRecordEnvExpr m where addEnvExpression :: EnvExpr m -> m HostExpr default addEnvExpression :: ( MonadTrans t , Monad n , MonadRecordEnvExpr n , t n ~ m , EnvExpr m ~ EnvExpr n ) => EnvExpr m -> m HostExpr addEnvExpression = lift . addEnvExpression instance MonadRecordEnvExpr (OhuaM env) where addEnvExpression expr = OhuaM $ do he <- makeThrow . V.length <$> use envExpressions envExpressions %= (`V.snoc` expr) pure he instance (MonadRecordEnvExpr m, Monad m) => MonadRecordEnvExpr (ReaderT e m) instance (MonadRecordEnvExpr m, Monad m, Monoid w) => MonadRecordEnvExpr (WriterT w m) instance (MonadRecordEnvExpr m, Monad m) => MonadRecordEnvExpr (Control.Monad.State.Strict.StateT s m) instance (MonadRecordEnvExpr m, Monad m) => MonadRecordEnvExpr (Control.Monad.State.Lazy.StateT s m) instance (MonadRecordEnvExpr m, Monad m, Monoid w) => MonadRecordEnvExpr (Control.Monad.RWS.Strict.RWST e w s m) instance (MonadRecordEnvExpr m, Monad m, Monoid w) => MonadRecordEnvExpr (Control.Monad.RWS.Lazy.RWST e w s m) class MonadReadEnvironment m where getEnvironment :: m Environment default getEnvironment :: ( MonadTrans t , Monad n , MonadReadEnvironment n , t n ~ m ) => m Environment getEnvironment = lift getEnvironment instance MonadReadEnvironment (OhuaM env) where getEnvironment = OhuaM ask instance (MonadReadEnvironment m, Monad m) => MonadReadEnvironment (ReaderT e m) instance (MonadReadEnvironment m, Monad m) => MonadReadEnvironment (Control.Monad.State.Lazy.StateT s m) instance (MonadReadEnvironment m, Monad m) => MonadReadEnvironment (Control.Monad.State.Strict.StateT s m) instance (MonadReadEnvironment m, Monad m, Monoid w) => MonadReadEnvironment (WriterT w m) instance (MonadReadEnvironment m, Monad m, Monoid w) => MonadReadEnvironment (Control.Monad.RWS.Lazy.RWST e w s m) instance (MonadReadEnvironment m, Monad m, Monoid w) => MonadReadEnvironment (Control.Monad.RWS.Strict.RWST e w s m) type MonadOhua m = ( MonadGenId m , MonadGenBnd m , MonadReadEnvExpr m , MonadRecordEnvExpr m , MonadError Error m , MonadIO m , MonadReadEnvironment m , MonadLogger m) -- | Run a compiler -- Creates the state from the tree being passed in -- If there are any errors during the compilation they are reported together at the end runFromExpr :: Options -> (Expression -> OhuaM env result) -> Expression -> LoggingT IO (Either Error result) runFromExpr opts f tree = runFromBindings opts (f tree) $ HS.fromList $ [b | Var b <- universe tree] runFromBindings :: Options -> OhuaM env result -> HS.HashSet Binding -> LoggingT IO (Either Error result) runFromBindings opts f taken = runExceptT $ do s0 <- make =<< ((, , mempty) <$> initNameGen taken <*> make 0) fst <$> evalRWST (runOhuaM f) env s0 where env = def & options .~ opts initNameGen :: MonadError Error m => HS.HashSet Binding -> m NameGenerator initNameGen taken = make ( taken , [ makeThrow $ char `T.cons` maybe [] show num | num <- Nothing : map Just [(0 :: Integer) ..] , char <- ['a' .. 'z'] ]) newtype GenBndT m a = GenBndT (StateT NameGenerator m a) deriving (Monad, Functor, Applicative, MonadTrans) instance Monad m => MonadGenBnd (GenBndT m) where generateBinding = GenBndT $ generateBindingIn id generateBindingWith = GenBndT . generateBindingWithIn id instance MonadIO m => MonadIO (GenBndT m) where liftIO = lift . liftIO instance ( MonadReadEnvironment m, Monad m ) => MonadReadEnvironment (GenBndT m) instance (MonadRecordEnvExpr m, Monad m) => MonadRecordEnvExpr (GenBndT m) instance HasEnvExpr (GenBndT m) where type EnvExpr (GenBndT m) = EnvExpr m instance (MonadGenId m, Monad m) => MonadGenId (GenBndT m) instance MonadLogger m => MonadLogger (GenBndT m) runGenBndT :: MonadError Error m => HS.HashSet Binding -> GenBndT m a -> m a runGenBndT taken (GenBndT comp) = do ng <- initNameGen taken evaluatingStateT ng comp
ohua-dev/ohua-core
core/src/Ohua/Internal/Monad.hs
epl-1.0
12,256
0
14
3,161
3,712
1,949
1,763
-1
-1
module Analyzer ( buildWebGraph, makeQueryTable, queryTable, fetchKeywords, ResultTable ) where ------------------------------------------------------------------------------- import Data.Maybe import Data.Char (toLower) import qualified Data.List as L import qualified Data.Map as M import qualified WebGraph as WG import HTMLScrapper import Network.URI (URI) ------------------------------------------------------------------------------- type ResultTable = M.Map String [(URI,Integer)] type PageRank = M.Map URI Integer ranks :: [(String, Integer)] ranks = [("title",10) ,("h1", 8), ("h2", 6), ("p",4), ("a", 3), ("div", 4)] -- | Builds the webGraph of a given pool of pages buildWebGraph :: [(URI,HTMLDoc,[URI])] -> WG.WebG buildWebGraph = g0 WG.empty . map (\(uri,doc,links) -> (uri,fetchKeywords doc ranks,links)) where g0 webG [] = webG g0 webG ((uri,kw,links):rest) = g0 (WG.insert uri kw links webG) rest -- | Fetches all the keywords of a page and assigns them a value fetchKeywords :: HTMLDoc -> [(String, Integer)] -> WG.Keywords fetchKeywords doc = foldl (\m (tag, val) -> foldl (\mp (word, points) -> M.insertWith (+) word points mp) m $ getAndClassify tag val) M.empty where getAndClassify :: String -> Integer -> [(String, Integer)] getAndClassify tag val = zip (map (map toLower) $ concatMap words $ fetchTag tag doc) (repeat val) -- | Assigns a rank to every page in a WebGraph according to the number -- | of times they are referenced rankPages :: WG.WebG -> PageRank rankPages = foldl (\m u -> M.insertWith (+) u 1 m) M.empty . allLinks where allLinks webg = concat $ mapMaybe (`WG.links` webg) (WG.getURIs webg) -- | Makes a search table which maps Words to web pages makeTable :: WG.WebG -> PageRank -> ResultTable makeTable webGraph pageRank = M.unionsWith (++) $ map processURI graphURIs where calculateRank valWord uri = getRank uri + valWord graphURIs = WG.getURIs webGraph processURI uri = M.fromList $ map (\(w,val) -> (w,[(uri,calculateRank val uri)])) $ M.toList $ fromJust $ WG.keywords uri webGraph getRank uri = case M.lookup uri pageRank of Nothing -> 0 Just r -> r -- | Search for a word in the ResultTable and return the list of pages -- | ordered by rank queryTable :: String -> ResultTable -> [(URI,Integer)] queryTable s = L.sortBy (\(_,v1) (_,v2) -> compare v2 v1) . concat . maybeToList . M.lookup s -- | makeQueryTable gets a pool of htmlpages and return the table with ranks makeQueryTable :: [(URI,HTMLDoc,[URI])] -> ResultTable makeQueryTable pagePool = makeTable webGraph pagesRank where webGraph = buildWebGraph pagePool pagesRank = rankPages webGraph
carlostome/HCrawler
src/Analyzer.hs
gpl-2.0
2,739
0
17
527
888
500
388
43
2
{- Copyright (C) 2005 John Goerzen <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} module FileDB.DB where import Config import Database.HSQL import Database.HSQL.SQLite3 import Data.Char import System.IO import Types import Data.List initdb :: IO Connection initdb = do putStrLn " *** Initializing database system..." dbpath <- dbdir handleSqlError $ do c <- connect (dbpath ++ "/media-index-main") ReadWriteMode initTables c return c initTables conn = do t <- tables conn let t2 = map (map toUpper) t if not (elem "MISTORE" t2) then do execute conn "CREATE TABLE mistore (api TEXT)" execute conn "INSERT INTO mistore VALUES ('media-index1')" else return () if not (elem "MIFILES" t2) then do execute conn $ "CREATE TABLE mifiles (" ++ "discid TEXT, filename TEXT, filesize INTEGER, " ++ "md5 TEXT, mimetype TEXT)" execute conn $ "CREATE UNIQUE INDEX mifilespri ON mifiles " ++ "(discid, filename)" execute conn $ "CREATE INDEX mifilesmd5 ON mifiles " ++ "(md5)" execute conn "CREATE INDEX mifilesfiles ON mifiles (filename)" else return () if not (elem "MIDISCS" t2) then do execute conn "CREATE TABLE midiscs (discid TEXT, discdescrip TEXT)" execute conn "CREATE UNIQUE INDEX midiscspri ON midiscs (discid)" else return () {- | Add a new disc to the system. -} addDisc :: Connection -> String -- ^ Disc ID -> String -- ^ Description -> IO () addDisc conn id descrip = handleSqlError $ execute conn $ "INSERT INTO midiscs VALUES (" ++ toSqlValue id ++ ", " ++ toSqlValue descrip ++ ")" {- | Add a new file to the system. -} addFile :: Connection -> String -- Disc ID -> String -- File name -> Integer -- File size -> String -- md5 -> String -- MIME type -> IO () addFile conn discid fname fsize md5 mimetype = handleSqlError $ execute conn $ "INSERT INTO mifiles VALUES (" ++ (concat . intersperse ", " $ [toSqlValue discid, toSqlValue fname, toSqlValue fsize, toSqlValue md5, toSqlValue mimetype]) ++ ")" {- | Adds a file from a FileRec. -} addFileRec conn discid fr = addFile conn discid (frname fr) (frsize fr) (frmd5 fr) (frmime fr) {- | Sets the list of files for a given disc to the passed list. -} setFilesRec :: Connection -> String -> [FileRec] -> IO () setFilesRec conn discid frlist = handleSqlError $ inTransaction conn (\tconn -> do wipeFiles tconn discid mapM_ (addFileRec tconn discid) frlist ) {- | Deletes all file records on the disc. -} wipeFiles :: Connection -> String -- ^ Disc ID -> IO () wipeFiles conn discid = handleSqlError $ execute conn $ "DELETE FROM mifiles WHERE discid = " ++ toSqlValue discid {- | Propogate SQL exceptions to IO monad. -} handleSqlError :: IO a -> IO a handleSqlError action = catchSql action handler where handler e = fail ("SQL error: " ++ show e)
jgoerzen/media-index
FileDB/DB.hs
gpl-2.0
4,184
0
13
1,405
728
355
373
74
4
-- | -- Copyright : (c) 2010-2012 Benedikt Schmidt -- License : GPL v3 (see LICENSE) -- -- Maintainer : Benedikt Schmidt <[email protected]> -- -- Computing the variants of a term. module Term.Narrowing.Variants.Compute ( computeVariantsBound , computeVariants -- * for testing , compareSubstVariant ) where import Term.LTerm import Term.Substitution import Term.Unification import Term.Narrowing.Variants.Check (leqSubstVariant,variantsFrom) import Extension.Prelude import Data.Ord import Data.List (partition,sortBy) import Data.Maybe import Control.Arrow -- import Control.Applicative import Control.Monad.Reader import Debug.Trace.Ignore ---------------------------------------------------------------------- -- Variant Narrowing ---------------------------------------------------------------------- -- | @substCompareVariant t s1 t2@ compares two substitutions using the variant order -- with respect to @t@. compareSubstVariant :: LNTerm -> LNSubstVFresh -> LNSubstVFresh -> WithMaude (Maybe Ordering) compareSubstVariant t s1 s2 | s1 == s2 = return $ Just EQ | otherwise = do isSmaller <- leqSubstVariant t s1 s2 isGreater <- leqSubstVariant t s2 s1 return $ case (isSmaller, isGreater) of (True, True) -> Just EQ (True, False) -> Just LT (False, True) -> Just GT (False, False) -> Nothing -- | A @Variant@ consists of its position in the narrowing tree and -- its substitution. data Variant = Variant { varPos :: [Int] -- ^ the position in the search tree , varSubst :: LNSubstVFresh -- ^ the composed substitution } deriving (Eq, Ord, Show) instance Sized Variant where size = size . varSubst -- | @narrowVariant rules t maxdepth@ either returns @Nothing@ -- if variant narrrowing hit the bound and there are still unexplored steps -- or @Just explored@ if the search finished before hitting the -- bound. narrowVariant :: LNTerm -- ^ The term. -> Maybe Int -- ^ The step bound. -> WithMaude (Maybe [Variant]) narrowVariant tstart maxdepth = reader $ \hnd -> go maxdepth [ Variant [] emptySubstVFresh ] [] hnd where go :: Maybe Int -> [Variant] -> [Variant] -> MaudeHandle -> Maybe [Variant] go _ [] explored _ = Just explored go (Just 0) _unexplored _explored _ = Nothing go n unexplored explored hnd = (\res -> (trace (show (n, unexplored, explored, res, new0, explored', new)) res)) $ go (fmap pred n) new explored' hnd where runWithMaude = (`runReader` hnd) explored0 = explored++unexplored new0 = filter (\newVariant -> varSubst newVariant `notElem` map varSubst explored0) $ concatMap variantsFrom' unexplored variants = reverse $ sortOn narrowSeqStepComplexity $ (tag False new0 ++ tag True explored0) minimized = filterMaximalBy fst cmp variants tag t xs = [ (t,a) | a <- xs] (explored',new) = map snd *** map snd $ partition fst minimized cmp a b = runWithMaude $ compareSubstVariant tstart (varSubst.snd $ a) (varSubst.snd $ b) variantsFrom' (Variant pos0 substComposed) = zipWith (\i substComposed' -> Variant (pos0++[i]) substComposed') [1..] (runWithMaude $ variantsFrom tstart substComposed) -- | @filterMaximalBy flags fastcmp alreadyFiltered cmp xs@ returns a -- list of maximal elements of @xs@ with respect to @cmp@. filterMaximalBy :: Eq a => (a -> Bool) -- ^ a function to check if an element has been -- already filtered in the last iteration -> (a -> a -> Maybe Ordering) -- ^ the comparison function -> [a] -- ^ the list that we want to filter -> [a] filterMaximalBy _ _ [] = [] filterMaximalBy alreadyFiltered cmp xs0 = go (last xs0) (init xs0,[]) where go x ([],[]) = [x] go x (y:todo,done) -- x and y have already been filtered earlier and are therefore incomparable | alreadyFiltered x && alreadyFiltered y = go x (todo,y:done) -- either x or y is new, so we have to compare the two | otherwise = case cmp x y of Nothing -> go x (todo,y:done) Just EQ | alreadyFiltered x -> keepx | otherwise -> keepy Just GT -> keepx Just LT -> keepy where keepx = go x (todo,done) keepy = go y (todo++done,[]) -- x is maximal, start comparing a new element to the others go x ([],y:done) = x:(go y (reverse done,[])) -- | This is used to sort narrowing steps such that similar steps are close narrowSeqStepComplexity :: (Bool,Variant) -> (Bool,Int,Int,Int) narrowSeqStepComplexity (checked, var@(Variant _ subst)) = (not checked, length (varPos var), size subst, length (varsRangeVFresh subst)) -- | @computeVariants t d@ compute the variants of term @t@ with bound @d@. -- The rewriting rules are taken from the Maude context. computeVariantsBound :: LNTerm -> Maybe Int -> WithMaude (Maybe [LNSubstVFresh]) computeVariantsBound t d = reader $ \hnd -> (\res -> trace (show ("ComputeVariantsBound", t, res)) res) $ case (`runReader` hnd) $ narrowVariant t d of Nothing -> Nothing Just explored -> Just (map varSubst (sortBy (comparing size) explored)) -- | @variantsList ts@ computes all variants of @ts@ considered as a single term -- without a bound or symmetry substitution. -- The rewriting rules are taken from the Maude context. computeVariants :: LNTerm -> WithMaude [LNSubstVFresh] computeVariants t = fromMaybe err <$> computeVariantsBound t Nothing where err = error "impossible: Variant computation failed without giving a bound"
samscott89/tamarin-prover
lib/term/src/Term/Narrowing/Variants/Compute.hs
gpl-3.0
5,935
0
17
1,572
1,461
786
675
92
6
module ExtraTransformations where import DataTypes import Utils (translate) moveEuclidean :: Float -> Float -> Transformation moveEuclidean dis theata = (translate x y) where x = (sin angle) * dis y = (cos angle) * dis angle = theata * (pi / 180) combineTransformation :: Transformation -> Transformation -> Transformation combineTransformation (x01,x02,x03, y01,y02,y03) (x11,x12,x13, y11,y12,y13) = (x01 * x11 + x02 * y11 + x03, x01 * x12 + x02 * y12 + x03, x01 * x13 + x02 * y13 + x03, y01 * x11 + y02 * y11 + y03, y01 * x12 + y02 * y12 + y03, y01 * x13 + y02 * y13 + y03)
Lexer747/Haskell-Fractals
Core/ExtraTransformations.hs
gpl-3.0
728
0
9
261
267
148
119
15
1
module Experimentation.P10 (p10_test, rle_rec) where import Test.HUnit import Data.List rle_rec :: (Eq a) => [a] -> [(Int,a)] rle_rec [] = [] rle_rec (a:as) = (b, a) : rle_rec (dropWhile (== a) as) where c = (takeWhile (== a) as) b = length (c) + 1 -- Tests p10_test = do runTestTT p10_tests test_rle_rec = TestCase $ do assertEqual "for (rle_rec aaabbc)" [(3,'a'),(2,'b'),(1,'c')] (rle_rec "aaabbc") p10_tests = TestList [ TestLabel "test_rle_rec" test_rle_rec ]
adarqui/99problems-hs
Experimentation/P10.hs
gpl-3.0
481
0
10
89
220
124
96
14
1
module Math.Arithmetic.Digits.Test (tests) where import Test.QuickCheck import Test.Framework.Providers.API import Test.Framework.Providers.QuickCheck2 import Math.Arithmetic.Digits prop_base10_roundtrip :: Integer -> Property prop_base10_roundtrip n = n >= 0 ==> (undigits $ digits n) == n prop_baseB_roundtrip :: Integer -> Integer -> Property prop_baseB_roundtrip b n = b > 1 && n >= 0 ==> (undigitsB b $ digitsB b n) == n tests :: [Test] tests = [ testGroup "Digits" [ testProperty "Base 10 Roundtrip" prop_base10_roundtrip, testProperty "Base B Roundtrip" prop_baseB_roundtrip ] ]
sykora/zeta
test/Math/Arithmetic/Digits/Test.hs
gpl-3.0
648
0
9
140
172
95
77
-1
-1
{- A positive fraction whose numerator is less than its denominator is called a proper fraction. For any denominator, d, there will be d1 proper fractions; for example, with d = 12: 1/12 , 2/12 , 3/12 , 4/12 , 5/12 , 6/12 , 7/12 , 8/12 , 9/12 , 10/12 , 11/12 . We shall call a fraction that cannot be cancelled down a resilient fraction. Furthermore we shall define the resilience of a denominator, R(d), to be the ratio of its proper fractions that are resilient; for example, R(12) = 4/11 . In fact, d = 12 is the smallest denominator having a resilience R(d) < 4/10 . Find the smallest denominator d, having a resilience R(d) < 15499/94744 . -} import Euler( totient, sigma0, primeDecomp, primorial ) import Control.Arrow( (&&&) ) import Data.List( foldl' ) resilience d = (fromIntegral $ totient d) / (fromIntegral (d - 1)) -- | Highly Composite Numbers -- I think the solution is in the form of R(hcn(n)) with n <- [1..] --hcn = 1 : hcn' 2 1 2 --hcn = 20160 : hcn' 25200 1 5040 --hcn = 554400 : hcn' 665280 1 110880 --hcn = 1396755360 : hcn' 1396755360 1 21621600 --hcn = 1396755360 : hcn' 1396755360 1 10810800 --hcn = 698377680 : hcn' 698377680 1 1663200 --hcn = 1396755360 : hcn' 1396755360 1 665280 --hcn = 1396755360 : hcn' 1396755360 1 60480 hcn = 16761064320 : hcn' 16761064320 1 332640 hcn' n d i | (sigma0 n) > d = n : hcn' (n+i) (sigma0 n) i | otherwise = hcn' (n+i) d i -- it should be a multiple of primes, so a try with primorial list nhcn = nhcn' 0 (map primorial [0..]) 1 nhcn' d (x:y:xs) m | x*m == y = nhcn' d (y:xs) 1 | otherwise = x*m : nhcn' d (x:y:xs) (m+1) nextI n = foldl' (*) 1 . map fst $ primeDecomp n --limite = 0.17 limite = 15499/94744 solution = head $ dropWhile (((<) limite) . snd) . map (id &&& resilience) $ drop 1 nhcn invList = [32125373280, (32125373280 - 2)..16761064320] solutionInv = head $ dropWhile (((<) limite) . snd) . map (id &&& resilience) $ drop 1 invList main = print $ fst solution --main = print solutionInv -- Obtenido con pruebas -- (27720,0.20779970417403226) -- (720720,0.19180845794269333) -- (36756720,0.1805253619073019) -- (698377680,0.17102402266209885) -- (1396755360,0.17102402253965507) -- (32125373280,0.16358819536068558) -- (64250746560,0.16358819535813948) -- (160626866400,0.16358819535661182) -- Este parece un limite superior
zhensydow/ljcsandbox
lang/haskell/euler/completed/problem243.hs
gpl-3.0
2,338
0
12
434
475
257
218
18
1
module Language.LXDFile.Version ( version ) where import Paths_lxdfile (version)
hverr/lxdfile
src/Language/LXDFile/Version.hs
gpl-3.0
84
0
5
12
20
13
7
3
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Books.Personalizedstream.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns a stream of personalized book clusters -- -- /See:/ <https://developers.google.com/books/docs/v1/getting_started Books API Reference> for @books.personalizedstream.get@. module Network.Google.Resource.Books.Personalizedstream.Get ( -- * REST Resource PersonalizedstreamGetResource -- * Creating a Request , personalizedstreamGet , PersonalizedstreamGet -- * Request Lenses , pgLocale , pgMaxAllowedMaturityRating , pgSource ) where import Network.Google.Books.Types import Network.Google.Prelude -- | A resource alias for @books.personalizedstream.get@ method which the -- 'PersonalizedstreamGet' request conforms to. type PersonalizedstreamGetResource = "books" :> "v1" :> "personalizedstream" :> "get" :> QueryParam "locale" Text :> QueryParam "maxAllowedMaturityRating" PersonalizedstreamGetMaxAllowedMaturityRating :> QueryParam "source" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Discoveryclusters -- | Returns a stream of personalized book clusters -- -- /See:/ 'personalizedstreamGet' smart constructor. data PersonalizedstreamGet = PersonalizedstreamGet' { _pgLocale :: !(Maybe Text) , _pgMaxAllowedMaturityRating :: !(Maybe PersonalizedstreamGetMaxAllowedMaturityRating) , _pgSource :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'PersonalizedstreamGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pgLocale' -- -- * 'pgMaxAllowedMaturityRating' -- -- * 'pgSource' personalizedstreamGet :: PersonalizedstreamGet personalizedstreamGet = PersonalizedstreamGet' { _pgLocale = Nothing , _pgMaxAllowedMaturityRating = Nothing , _pgSource = Nothing } -- | ISO-639-1 language and ISO-3166-1 country code. Ex: \'en_US\'. Used for -- generating recommendations. pgLocale :: Lens' PersonalizedstreamGet (Maybe Text) pgLocale = lens _pgLocale (\ s a -> s{_pgLocale = a}) -- | The maximum allowed maturity rating of returned recommendations. Books -- with a higher maturity rating are filtered out. pgMaxAllowedMaturityRating :: Lens' PersonalizedstreamGet (Maybe PersonalizedstreamGetMaxAllowedMaturityRating) pgMaxAllowedMaturityRating = lens _pgMaxAllowedMaturityRating (\ s a -> s{_pgMaxAllowedMaturityRating = a}) -- | String to identify the originator of this request. pgSource :: Lens' PersonalizedstreamGet (Maybe Text) pgSource = lens _pgSource (\ s a -> s{_pgSource = a}) instance GoogleRequest PersonalizedstreamGet where type Rs PersonalizedstreamGet = Discoveryclusters type Scopes PersonalizedstreamGet = '["https://www.googleapis.com/auth/books"] requestClient PersonalizedstreamGet'{..} = go _pgLocale _pgMaxAllowedMaturityRating _pgSource (Just AltJSON) booksService where go = buildClient (Proxy :: Proxy PersonalizedstreamGetResource) mempty
rueshyna/gogol
gogol-books/gen/Network/Google/Resource/Books/Personalizedstream/Get.hs
mpl-2.0
4,032
0
15
921
472
280
192
72
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.People.People.GetBatchGet -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Provides information about a list of specific people by specifying a -- list of requested resource names. Use \`people\/me\` to indicate the -- authenticated user. The request returns a 400 error if \'personFields\' -- is not specified. -- -- /See:/ <https://developers.google.com/people/ People API Reference> for @people.people.getBatchGet@. module Network.Google.Resource.People.People.GetBatchGet ( -- * REST Resource PeopleGetBatchGetResource -- * Creating a Request , peopleGetBatchGet , PeopleGetBatchGet -- * Request Lenses , pgbgXgafv , pgbgUploadProtocol , pgbgRequestMaskIncludeField , pgbgAccessToken , pgbgUploadType , pgbgSources , pgbgPersonFields , pgbgResourceNames , pgbgCallback ) where import Network.Google.People.Types import Network.Google.Prelude -- | A resource alias for @people.people.getBatchGet@ method which the -- 'PeopleGetBatchGet' request conforms to. type PeopleGetBatchGetResource = "v1" :> "people:batchGet" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "requestMask.includeField" GFieldMask :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParams "sources" PeopleGetBatchGetSources :> QueryParam "personFields" GFieldMask :> QueryParams "resourceNames" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] GetPeopleResponse -- | Provides information about a list of specific people by specifying a -- list of requested resource names. Use \`people\/me\` to indicate the -- authenticated user. The request returns a 400 error if \'personFields\' -- is not specified. -- -- /See:/ 'peopleGetBatchGet' smart constructor. data PeopleGetBatchGet = PeopleGetBatchGet' { _pgbgXgafv :: !(Maybe Xgafv) , _pgbgUploadProtocol :: !(Maybe Text) , _pgbgRequestMaskIncludeField :: !(Maybe GFieldMask) , _pgbgAccessToken :: !(Maybe Text) , _pgbgUploadType :: !(Maybe Text) , _pgbgSources :: !(Maybe [PeopleGetBatchGetSources]) , _pgbgPersonFields :: !(Maybe GFieldMask) , _pgbgResourceNames :: !(Maybe [Text]) , _pgbgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PeopleGetBatchGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pgbgXgafv' -- -- * 'pgbgUploadProtocol' -- -- * 'pgbgRequestMaskIncludeField' -- -- * 'pgbgAccessToken' -- -- * 'pgbgUploadType' -- -- * 'pgbgSources' -- -- * 'pgbgPersonFields' -- -- * 'pgbgResourceNames' -- -- * 'pgbgCallback' peopleGetBatchGet :: PeopleGetBatchGet peopleGetBatchGet = PeopleGetBatchGet' { _pgbgXgafv = Nothing , _pgbgUploadProtocol = Nothing , _pgbgRequestMaskIncludeField = Nothing , _pgbgAccessToken = Nothing , _pgbgUploadType = Nothing , _pgbgSources = Nothing , _pgbgPersonFields = Nothing , _pgbgResourceNames = Nothing , _pgbgCallback = Nothing } -- | V1 error format. pgbgXgafv :: Lens' PeopleGetBatchGet (Maybe Xgafv) pgbgXgafv = lens _pgbgXgafv (\ s a -> s{_pgbgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pgbgUploadProtocol :: Lens' PeopleGetBatchGet (Maybe Text) pgbgUploadProtocol = lens _pgbgUploadProtocol (\ s a -> s{_pgbgUploadProtocol = a}) -- | Required. Comma-separated list of person fields to be included in the -- response. Each path should start with \`person.\`: for example, -- \`person.names\` or \`person.photos\`. pgbgRequestMaskIncludeField :: Lens' PeopleGetBatchGet (Maybe GFieldMask) pgbgRequestMaskIncludeField = lens _pgbgRequestMaskIncludeField (\ s a -> s{_pgbgRequestMaskIncludeField = a}) -- | OAuth access token. pgbgAccessToken :: Lens' PeopleGetBatchGet (Maybe Text) pgbgAccessToken = lens _pgbgAccessToken (\ s a -> s{_pgbgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pgbgUploadType :: Lens' PeopleGetBatchGet (Maybe Text) pgbgUploadType = lens _pgbgUploadType (\ s a -> s{_pgbgUploadType = a}) -- | Optional. A mask of what source types to return. Defaults to -- READ_SOURCE_TYPE_CONTACT and READ_SOURCE_TYPE_PROFILE if not set. pgbgSources :: Lens' PeopleGetBatchGet [PeopleGetBatchGetSources] pgbgSources = lens _pgbgSources (\ s a -> s{_pgbgSources = a}) . _Default . _Coerce -- | Required. A field mask to restrict which fields on each person are -- returned. Multiple fields can be specified by separating them with -- commas. Valid values are: * addresses * ageRanges * biographies * -- birthdays * calendarUrls * clientData * coverPhotos * emailAddresses * -- events * externalIds * genders * imClients * interests * locales * -- locations * memberships * metadata * miscKeywords * names * nicknames * -- occupations * organizations * phoneNumbers * photos * relations * -- sipAddresses * skills * urls * userDefined pgbgPersonFields :: Lens' PeopleGetBatchGet (Maybe GFieldMask) pgbgPersonFields = lens _pgbgPersonFields (\ s a -> s{_pgbgPersonFields = a}) -- | Required. The resource names of the people to provide information about. -- It\'s repeatable. The URL query parameter should be -- resourceNames=&resourceNames=&... - To get information about the -- authenticated user, specify \`people\/me\`. - To get information about a -- google account, specify \`people\/{account_id}\`. - To get information -- about a contact, specify the resource name that identifies the contact -- as returned by \`people.connections.list\`. There is a maximum of 200 -- resource names. pgbgResourceNames :: Lens' PeopleGetBatchGet [Text] pgbgResourceNames = lens _pgbgResourceNames (\ s a -> s{_pgbgResourceNames = a}) . _Default . _Coerce -- | JSONP pgbgCallback :: Lens' PeopleGetBatchGet (Maybe Text) pgbgCallback = lens _pgbgCallback (\ s a -> s{_pgbgCallback = a}) instance GoogleRequest PeopleGetBatchGet where type Rs PeopleGetBatchGet = GetPeopleResponse type Scopes PeopleGetBatchGet = '["https://www.googleapis.com/auth/contacts", "https://www.googleapis.com/auth/contacts.readonly", "https://www.googleapis.com/auth/directory.readonly", "https://www.googleapis.com/auth/user.addresses.read", "https://www.googleapis.com/auth/user.birthday.read", "https://www.googleapis.com/auth/user.emails.read", "https://www.googleapis.com/auth/user.gender.read", "https://www.googleapis.com/auth/user.organization.read", "https://www.googleapis.com/auth/user.phonenumbers.read", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"] requestClient PeopleGetBatchGet'{..} = go _pgbgXgafv _pgbgUploadProtocol _pgbgRequestMaskIncludeField _pgbgAccessToken _pgbgUploadType (_pgbgSources ^. _Default) _pgbgPersonFields (_pgbgResourceNames ^. _Default) _pgbgCallback (Just AltJSON) peopleService where go = buildClient (Proxy :: Proxy PeopleGetBatchGetResource) mempty
brendanhay/gogol
gogol-people/gen/Network/Google/Resource/People/People/GetBatchGet.hs
mpl-2.0
8,363
0
19
1,840
1,025
605
420
151
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Directory.Users.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Delete user -- -- /See:/ <https://developers.google.com/admin-sdk/directory/ Admin Directory API Reference> for @directory.users.delete@. module Network.Google.Resource.Directory.Users.Delete ( -- * REST Resource UsersDeleteResource -- * Creating a Request , usersDelete , UsersDelete -- * Request Lenses , udUserKey ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @directory.users.delete@ method which the -- 'UsersDelete' request conforms to. type UsersDeleteResource = "admin" :> "directory" :> "v1" :> "users" :> Capture "userKey" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] () -- | Delete user -- -- /See:/ 'usersDelete' smart constructor. newtype UsersDelete = UsersDelete' { _udUserKey :: Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UsersDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'udUserKey' usersDelete :: Text -- ^ 'udUserKey' -> UsersDelete usersDelete pUdUserKey_ = UsersDelete' { _udUserKey = pUdUserKey_ } -- | Email or immutable Id of the user udUserKey :: Lens' UsersDelete Text udUserKey = lens _udUserKey (\ s a -> s{_udUserKey = a}) instance GoogleRequest UsersDelete where type Rs UsersDelete = () type Scopes UsersDelete = '["https://www.googleapis.com/auth/admin.directory.user"] requestClient UsersDelete'{..} = go _udUserKey (Just AltJSON) directoryService where go = buildClient (Proxy :: Proxy UsersDeleteResource) mempty
rueshyna/gogol
gogol-admin-directory/gen/Network/Google/Resource/Directory/Users/Delete.hs
mpl-2.0
2,560
0
13
601
307
188
119
48
1
{-# LANGUAGE TypeFamilies #-} module Math.Topology.KnotTh.Algebra.SurfaceDiagram ( SurfaceDiagram(..) , rightFace , rightPlace , rightPair , nthDartInCWTraverse , eulerCharOf , genusOf ) where import Control.Arrow ((***), first) import Math.Topology.KnotTh.Algebra.PlanarAlgebra class (VertexDiagram a) => SurfaceDiagram a where numberOfFaces :: a t -> Int nthFace :: a t -> Int -> Face a t allFaces :: a t -> [Face a t] data Face a t faceDegree :: Face a t -> Int faceOwner :: Face a t -> a t faceIndex :: Face a t -> Int leftFace :: Dart a t -> Face a t leftPlace :: Dart a t -> Int leftPair :: Dart a t -> (Face a t, Int) leftPair' :: Dart a t -> (Int, Int) leftFace = fst . leftPair leftPlace = snd . leftPair leftPair d = (leftFace d, leftPlace d) leftPair' = first faceIndex . leftPair nthDartInCCWTraverse :: Face a t -> Int -> Dart a t faceTraverseCCW :: Face a t -> [Dart a t] faceTraverseCCW f = map (nthDartInCCWTraverse f) [0 .. faceDegree f - 1] faceIndicesRange :: a t -> (Int, Int) facesRange :: a t -> (Face a t, Face a t) facesRange a | numberOfFaces a > 0 = (nthFace a *** nthFace a) $ faceIndicesRange a | otherwise = error "facesRange: no faces" instance (SurfaceDiagram a) => Eq (Face a t) where (==) a b = faceIndex a == faceIndex b instance (SurfaceDiagram a) => Ord (Face a t) where compare a b = faceIndex a `compare` faceIndex b {-# INLINE rightFace #-} rightFace :: (SurfaceDiagram a) => Dart a t -> Face a t rightFace = leftFace . opposite {-# INLINE rightPlace #-} rightPlace :: (SurfaceDiagram a) => Dart a t -> Int rightPlace = leftPlace . opposite {-# INLINE rightPair #-} rightPair :: (SurfaceDiagram a) => Dart a t -> (Face a t, Int) rightPair = leftPair . opposite nthDartInCWTraverse :: (SurfaceDiagram a) => Face a t -> Int -> Dart a t nthDartInCWTraverse f p = opposite $ nthDartInCCWTraverse f p eulerCharOf :: (SurfaceDiagram a) => a t -> Int eulerCharOf a = numberOfVertices a + numberOfFaces a - numberOfEdges a genusOf :: (SurfaceDiagram a) => a t -> Int genusOf a = (2 - eulerCharOf a) `div` 2
mishun/tangles
src/Math/Topology/KnotTh/Algebra/SurfaceDiagram.hs
lgpl-3.0
2,346
0
11
682
836
435
401
53
1
module Git.Traverse where import Control.Monad import Data.List import Data.Maybe import Git.Hash import Git.Parser import Git.Object.Commit import Git.Repository printCommit :: Commit -> IO () printCommit = putStrLn . onelineCommit printObject :: Object -> IO () printObject (GitCommit commit) = printCommit commit onlyCommits :: [Object] -> [Commit] onlyCommits [] = [] onlyCommits ((GitCommit x):xs) = x : (onlyCommits xs) onlyCommits (x:xs) = onlyCommits xs rejectCommits :: [Hash] -> [Commit] -> [Commit] rejectCommits [] xs = xs rejectCommits _ [] = [] rejectCommits hashes all@(x:xs) = case find (== commitHash x) hashes of Just c -> rejectCommits hashes xs Nothing -> x : (rejectCommits hashes xs) parents :: [Commit] -> [Hash] parents commits = concat $ map commitParents commits -- Maybe this is not the smartest way to do it. But what the hell, this works. -- The idea here is that you specify the upper and lower bounds of your list, -- in terms of hashes. And you get a list of Commits in between. revList :: Repository -> [Hash] -> [Hash] -> IO [Commit] revList _ _ [] = do return [] revList repo lower upper = do objects <- mapM (loadObject repo) upper let commits = rejectCommits lower $ onlyCommits objects liftM2 (++) (return commits) (revList repo lower (parents $ commits))
wereHamster/yag
Git/Traverse.hs
unlicense
1,323
0
11
240
458
239
219
30
2
{-# LANGUAGE FlexibleInstances #-} -- Copyright 2014 (c) Diego Souza <[email protected]> -- -- 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 Leela.HZMQ.IOLoop ( IOLoop () , alive , cancel , sendMsg , recvMsg , sendMsg_ , pollLoop , newIOLoop , useSocket , newIOLoop_ , pollInLoop , pollOutLoop , sendMsgWithCtrl , sendMsgWithCtrl' ) where import Data.Maybe import Data.IORef import System.ZMQ4 import Leela.Logger import Control.Monad import Control.DeepSeq import qualified Data.ByteString as B import Control.Concurrent import Leela.HZMQ.ZHelpers import qualified Data.ByteString.Lazy as L import Control.Concurrent.BoundedChan as C type SendCallback a = Socket a -> [B.ByteString] -> IO () type RecvCallback a = Socket a -> IO [B.ByteString] type CancelAction = IO () data IOLoop a = IOLoop { pollName :: String , pollInQ :: MVar [[B.ByteString]] , pollOutQ :: BoundedChan ([B.ByteString], IO Bool) , pollLock :: MVar (Socket a) , pollCtrl :: MVar () } data PollMode = PollRdonlyMode | PollWronlyMode | PollRdWrMode deriving (Eq) hasWrite :: PollMode -> Bool hasWrite PollRdonlyMode = False hasWrite _ = True hasRead :: PollMode -> Bool hasRead PollWronlyMode = False hasRead _ = True newIOLoop :: String -> MVar [[B.ByteString]] -> BoundedChan ([B.ByteString], IO Bool) -> Socket a -> IO (IOLoop a) newIOLoop name qsrc qdst fh = do ctrl <- newEmptyMVar lock <- newMVar fh return (IOLoop name qsrc qdst lock ctrl) newIOLoop_ :: String -> Socket a -> Int -> IO (IOLoop a) newIOLoop_ name fh limit = do qsrc <- newMVar [] qdst <- newBoundedChan limit newIOLoop name qsrc qdst fh alive :: IOLoop a -> IO Bool alive p = liftM isNothing (tryReadMVar (pollCtrl p)) enqueueD :: IOLoop a -> ([B.ByteString], IO Bool) -> IO Bool enqueueD p a = tryWriteChan (pollOutQ p) a enqueueS :: IOLoop a -> [[B.ByteString]] -> IO Bool enqueueS p msgs = case (filter checkMsg msgs) of [] -> return False msgs' -> putMVar (pollInQ p) msgs' >> return True where checkMsg msg = case (break B.null msg) of (_, (_ : [])) -> False _ -> True dequeue :: IOLoop a -> Maybe ([B.ByteString], IO Bool) -> IO ([B.ByteString], IO Bool) dequeue _ (Just acc) = return acc dequeue p _ = C.readChan (pollOutQ p) recvMsg :: (Receiver a) => IOLoop a -> IO [[B.ByteString]] recvMsg p = takeMVar (pollInQ p) sendMsg' :: (Sender a) => IOLoop a -> [B.ByteString] -> IO (CancelAction, Bool) sendMsg' p msg = do ctrl <- newIORef True ok <- sendMsgWithCtrl' p (readIORef ctrl) msg return (writeIORef ctrl False, ok) sendMsg :: (Sender a) => IOLoop a -> [L.ByteString] -> IO (CancelAction, Bool) sendMsg p = sendMsg' p . map L.toStrict sendMsg_ :: (Sender a) => IOLoop a -> [L.ByteString] -> IO Bool sendMsg_ p = sendMsgWithCtrl p (return True) sendMsgWithCtrl' :: (Sender a) => IOLoop a -> IO Bool -> [B.ByteString] -> IO Bool sendMsgWithCtrl' p ctrl msg = msg `deepseq` enqueueD p (msg, ctrl) sendMsgWithCtrl :: (Sender a) => IOLoop a -> IO Bool -> [L.ByteString] -> IO Bool sendMsgWithCtrl p ctrl = sendMsgWithCtrl' p ctrl . map L.toStrict cancel :: IOLoop a -> IO () cancel p = putMVar (pollCtrl p) () useSocket :: IOLoop a -> (Socket a -> IO b) -> IO b useSocket p = withMVar (pollLock p) pollOutLoop :: (Sender a) => Logger -> IOLoop a -> IO () pollOutLoop syslog = gpollLoop syslog PollWronlyMode (const $ return []) sendAll pollInLoop :: (Receiver a) => Logger -> IOLoop a -> IO () pollInLoop syslog = gpollLoop syslog PollRdonlyMode receiveMulti (\_ _ -> return ()) pollLoop :: (Receiver a, Sender a) => Logger -> IOLoop a -> IO () pollLoop syslog = gpollLoop syslog PollRdWrMode receiveMulti sendAll gpollLoop :: Logger -> PollMode -> RecvCallback a -> SendCallback a -> IOLoop a -> IO () gpollLoop logger mode recvCallback sendCallback p = go where handleRecv acc | length acc == 4 = enqueueS p acc >> handleRecv [] | otherwise = do mmsg <- useSocket p readMsg case mmsg of Just msg -> handleRecv (msg : acc) Nothing -> enqueueS p acc where readMsg fh = do zready <- events fh if (In `elem` zready) then fmap Just $ recvCallback fh else return Nothing handleSend state = do (msg, readStatus) <- dequeue p state live <- readStatus rest <- if live then useSocket p (mySendMsg msg readStatus) else do warning logger (printf "dropping message [%s#cancel]" (pollName p)) return Nothing case rest of Nothing -> handleSend rest _ -> return rest where mySendMsg msg ctrl fh = do zready <- events fh if (Out `elem` zready) then sendCallback fh msg >> return Nothing else return $ Just (msg, ctrl) goWrite fh miss = do miss' <- handleSend miss case miss' of Nothing -> goWrite fh miss' _ -> threadWaitWrite fh >> goWrite fh miss' goRead fh = do threadWaitRead fh handleRecv [] goRead fh go = do fh <- useSocket p fileDescriptor t0 <- forkIO (when (hasRead mode) $ goRead fh) t1 <- forkIO (when (hasWrite mode) $ goWrite fh Nothing) readMVar (pollCtrl p) mapM_ killThread [t0, t1]
locaweb/leela
src/warpdrive/src/Leela/HZMQ/IOLoop.hs
apache-2.0
6,444
0
17
2,013
2,076
1,046
1,030
144
7
module DataBase where -- Data variants for literals and addition data Lit = Lit Int data (Exp l, Exp r) => Add l r = Add l r -- The open union of data variants class Exp x instance Exp Lit instance (Exp l, Exp r) => Exp (Add l r)
egaburov/funstuff
Haskell/tytag/xproblem_src/samples/expressions/Haskell/OpenDatatype1/DataBase.hs
apache-2.0
236
0
7
57
87
47
40
-1
-1
-- | Low-level safe interface to gRPC. By "safe", we mean: -- 1. all gRPC objects are guaranteed to be cleaned up correctly. -- 2. all functions are thread-safe. -- 3. all functions leave gRPC in a consistent, safe state. -- These guarantees only apply to the functions exported by this module, -- and not to helper functions in submodules that aren't exported here. {-# LANGUAGE RecordWildCards #-} module Network.GRPC.LowLevel ( -- * Important types GRPC , withGRPC , GRPCIOError(..) , StatusCode(..) -- * Completion queue utilities , CompletionQueue , withCompletionQueue -- * Calls , GRPCMethodType(..) , RegisteredMethod , MethodPayload , NormalRequestResult(..) , MetadataMap(..) , MethodName(..) , StatusDetails(..) -- * Configuration options , Arg(..) , CompressionAlgorithm(..) , CompressionLevel(..) , Host(..) , Port(..) -- * Server , ServerConfig(..) , Server(normalMethods, sstreamingMethods, cstreamingMethods, bidiStreamingMethods) , ServerCall(payload, metadata) , withServer , serverHandleNormalCall , ServerHandlerLL , withServerCall , serverCallCancel , serverCallIsExpired , serverReader -- for client streaming , ServerReaderHandlerLL , serverWriter -- for server streaming , ServerWriterHandlerLL , serverRW -- for bidirectional streaming , ServerRWHandlerLL -- * Client and Server Auth , AuthContext , AuthProperty(..) , getAuthProperties , addAuthProperty -- * Server Auth , ServerSSLConfig(..) , ProcessMeta , AuthProcessorResult(..) , SslClientCertificateRequestType(..) -- * Client Auth , ClientSSLConfig(..) , ClientSSLKeyCertPair(..) , ClientMetadataCreate , ClientMetadataCreateResult(..) , AuthMetadataContext(..) -- * Client , ClientConfig(..) , Client , ClientCall , ConnectivityState(..) , clientConnectivity , withClient , clientRegisterMethodNormal , clientRegisterMethodClientStreaming , clientRegisterMethodServerStreaming , clientRegisterMethodBiDiStreaming , clientRequest , clientRequestParent , clientReader -- for server streaming , clientWriter -- for client streaming , clientRW -- for bidirectional streaming , withClientCall , withClientCallParent , clientCallCancel -- * Ops , Op(..) , OpRecvResult(..) -- * Streaming utilities , StreamSend , StreamRecv ) where import Network.GRPC.LowLevel.Call import Network.GRPC.LowLevel.Client import Network.GRPC.LowLevel.CompletionQueue import Network.GRPC.LowLevel.GRPC import Network.GRPC.LowLevel.Op import Network.GRPC.LowLevel.Server import Network.GRPC.Unsafe (ConnectivityState (..)) import Network.GRPC.Unsafe.ChannelArgs (Arg (..), CompressionAlgorithm (..), CompressionLevel (..)) import Network.GRPC.Unsafe.Op (StatusCode (..)) import Network.GRPC.Unsafe.Security (AuthContext, AuthMetadataContext (..), AuthProcessorResult (..), AuthProperty (..), ClientMetadataCreate, ClientMetadataCreateResult (..), ProcessMeta, SslClientCertificateRequestType (..), addAuthProperty, getAuthProperties)
awakenetworks/gRPC-haskell
core/src/Network/GRPC/LowLevel.hs
apache-2.0
3,630
0
6
1,064
515
368
147
96
0
{-| Module : Network.IRC.Client Description : Extensible configuration for the IRC bot. Copyright : (c) Abhinav Sarkar, 2014-2015 License : Apache-2.0 Maintainer : [email protected] Stability : experimental Portability : POSIX Extensible configuration for the IRC bot. -} {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, ExistentialQuantification, GADTs #-} module Network.IRC.Configuration ( Name , Value (..) , Configurable (..) , Configuration , fromMap , lookup , require , lookupDefault ) where import qualified ClassyPrelude as P import ClassyPrelude hiding (lookup) import Data.Maybe (fromJust) -- | Name of a configuration property. type Name = Text -- | Typeclass for the types that can be used as values in 'Configuration'. class Configurable a where fromValue :: Value -> Maybe a valueToList :: Value -> Maybe [a] valueToList (List xs) = mapM fromValue xs valueToList _ = Nothing toValue :: a -> Value listToValue :: [a] -> Value listToValue = List . map toValue valueToNum :: (Num a) => Value -> Maybe a valueToNum (Number n) = Just . fromInteger $ n valueToNum _ = Nothing instance Configurable Integer where fromValue = valueToNum toValue = Number instance Configurable Int where fromValue = valueToNum toValue = Number . toInteger instance Configurable Text where fromValue (String s) = Just s fromValue _ = Nothing toValue = String instance Configurable Bool where fromValue (Boolean b) = Just b fromValue _ = Nothing toValue = Boolean instance Configurable a => Configurable [a] where fromValue = valueToList toValue = listToValue -- | Value of a configuration property. data Value = String Text -- ^ A text value. | Number Integer -- ^ An integer value. | Boolean Bool -- ^ A boolean value. | List [Value] -- ^ A list of values as a value. deriving (Eq, Show) -- | A configuration data which can be used to look up properties. newtype Configuration = Configuration { configMap :: Map Name Value } deriving (Show, Eq) -- | Creates a 'Configuration' from a map of 'Name's to 'Value's. fromMap :: Map Name Value -> Configuration fromMap = Configuration -- | Looks up a property in the 'Configuration' by the given 'Name'. -- Returns 'Nothing' if the property is not found or is of wrong type. lookup :: (Configurable a) => Name -> Configuration -> Maybe a lookup name Configuration {..} = join . map fromValue $ P.lookup name configMap -- | Looks up a property in the 'Configuration' by the given 'Name'. -- Fails with an error if the property is not found or is of wrong type. require :: (Configurable a) => Name -> Configuration -> a require n = fromJust . lookup n -- | Looks up a property in the 'Configuration' by the given 'Name'. -- Returns the given default if the property is not found or is of wrong type. lookupDefault :: (Configurable a) => Name -> Configuration -> a -> a lookupDefault n c v = fromMaybe v $ lookup n c
abhin4v/hask-irc
hask-irc-core/Network/IRC/Configuration.hs
apache-2.0
3,064
0
9
686
612
338
274
-1
-1
-- Copyright (C) 2013 Fraser Tweedale -- -- 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. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-| JSON Web Signature algorithms. -} module Crypto.JOSE.JWA.JWS where import qualified Crypto.JOSE.TH -- | RFC 7518 §3.1. "alg" (Algorithm) Header Parameters Values for JWS -- $(Crypto.JOSE.TH.deriveJOSEType "Alg" [ "HS256" -- HMAC SHA ; REQUIRED , "HS384" -- HMAC SHA ; OPTIONAL , "HS512" -- HMAC SHA ; OPTIONAL , "RS256" -- RSASSA-PKCS-v1_5 SHA ; RECOMMENDED , "RS384" -- RSASSA-PKCS-v1_5 SHA ; OPTIONAL , "RS512" -- RSASSA-PKCS-v1_5 SHA ; OPTIONAL , "ES256" -- ECDSA P curve and SHA ; RECOMMENDED+ , "ES384" -- ECDSA P curve and SHA ; OPTIONAL , "ES512" -- ECDSA P curve and SHA ; OPTIONAL , "PS256" -- RSASSA-PSS SHA ; OPTIONAL , "PS384" -- RSASSA-PSS SHA ; OPTIONAL , "PS512" -- RSSSSA-PSS SHA ; OPTIONAL , "none" -- "none" No signature or MAC ; Optional , "EdDSA" -- EdDSA (RFC 8037) ])
frasertweedale/hs-jose
src/Crypto/JOSE/JWA/JWS.hs
apache-2.0
1,502
0
8
288
105
79
26
19
0
{-# LANGUAGE TemplateHaskell #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Type.Binary.TH -- Copyright : (C) 2006 Edward Kmett -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable (Template Haskell) -- -- Provides a simple way to construct type level binaries. -- $(binaryE 24) returns an undefined value with the same type as the -- Type.Binary with value 24. ----------------------------------------------------------------------------- module Data.Type.Binary.TH ( binaryE, binaryT ) where import Data.Type.Binary.Internals import Language.Haskell.TH f = conT $ mkName "F" t = conT $ mkName "T" o = conT $ mkName "O" i = conT $ mkName "I" -- | $(binaryT n) returns the appropriate TBinary instance binaryT :: Integral a => a -> TypeQ binaryT n = case n of 0 -> f -1 -> t n -> appT (if (n `mod` 2) == 0 then o else i) $ binaryT $ n `div` 2 -- | $(binaryE n) returns an undefined value of the appropriate TBinary instance binaryE :: Integral a => a -> ExpQ binaryE n = sigE (varE $ mkName "undefined") $ binaryT n
ekmett/type-int
Data/Type/Binary/TH.hs
bsd-2-clause
1,229
0
16
227
227
130
97
15
4
-- Some simple functions to generate anagrams of words import Data.Char import List import Data.Set (Set) import qualified Data.Set as Set import Data.Map (Map) import qualified Data.Map as Map wordfile = "/usr/share/dict/words" stringToKey :: String -> String stringToKey = sort.(map toLower) validWord :: String -> Bool validWord s = (not (null s)) && length s <= 10 && not (any (not.isAlpha) s) anagramList :: String -> IO (Map String (Set String)) anagramList file = do filecontent <- readFile file return (foldl (\x y -> Map.insertWith Set.union (stringToKey y) (Set.singleton y) x) Map.empty (filter validWord $ lines filecontent)) anagramsOf :: String -> IO () anagramsOf word = do anagrams <- anagramList wordfile putStrLn (show (Map.lookup (stringToKey word) anagrams))
fffej/haskellprojects
basics/anagrams.hs
bsd-2-clause
857
1
15
195
307
158
149
23
1
module Drasil.Projectile.References where import Language.Drasil import Data.Drasil.Citations (cartesianWiki) import Data.Drasil.People (rcHibbeler) citations :: BibRef citations = [accelerationWiki, velocityWiki, hibbeler2004, cartesianWiki] accelerationWiki, velocityWiki, hibbeler2004 :: Citation accelerationWiki = cMisc [author [mononym "Wikipedia Contributors"], title "Acceleration", howPublishedU "https://en.wikipedia.org/wiki/Acceleration", month Jun, year 2019] "accelerationWiki" velocityWiki = cMisc [author [mononym "Wikipedia Contributors"], title "Velocity", howPublishedU "https://en.wikipedia.org/wiki/Velocity", month Jun, year 2019] "velocityWiki" hibbeler2004 = cBookA [rcHibbeler] "Engineering Mechanics: Dynamics" "Pearson Prentice Hall" 2004 [] "hibbeler2004"
JacquesCarette/literate-scientific-software
code/drasil-example/Drasil/Projectile/References.hs
bsd-2-clause
805
0
9
91
180
101
79
18
1
------------------------------------------------------------------------------- -- -- | Main API for compiling plain Haskell source code. -- -- This module implements compilation of a Haskell source. It is -- /not/ concerned with preprocessing of source files; this is handled -- in "DriverPipeline". -- -- There are various entry points depending on what mode we're in: -- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and -- "interactive" mode (GHCi). There are also entry points for -- individual passes: parsing, typechecking/renaming, desugaring, and -- simplification. -- -- All the functions here take an 'HscEnv' as a parameter, but none of -- them return a new one: 'HscEnv' is treated as an immutable value -- from here on in (although it has mutable components, for the -- caches). -- -- Warning messages are dealt with consistently throughout this API: -- during compilation warnings are collected, and before any function -- in @HscMain@ returns, the warnings are either printed, or turned -- into a real compialtion error if the @-Werror@ flag is enabled. -- -- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000 -- ------------------------------------------------------------------------------- module HscMain ( -- * Making an HscEnv newHscEnv -- * Compiling complete source files , Compiler , HscStatus' (..) , InteractiveStatus, HscStatus , hscCompileOneShot , hscCompileBatch , hscCompileNothing , hscCompileInteractive , hscCompileCmmFile , hscCompileCore -- * Running passes separately , hscParse , hscTypecheckRename , hscDesugar , makeSimpleIface , makeSimpleDetails , hscSimplify -- ToDo, shouldn't really export this -- ** Backends , hscOneShotBackendOnly , hscBatchBackendOnly , hscNothingBackendOnly , hscInteractiveBackendOnly -- * Support for interactive evaluation , hscParseIdentifier , hscTcRcLookupName , hscTcRnGetInfo , hscCheckSafe , hscGetSafe #ifdef GHCI , hscIsGHCiMonad , hscGetModuleInterface , hscRnImportDecls , hscTcRnLookupRdrName , hscStmt, hscStmtWithLocation , hscDecls, hscDeclsWithLocation , hscTcExpr, hscImport, hscKcType , hscCompileCoreExpr #endif ) where #ifdef GHCI import ByteCodeGen ( byteCodeGen, coreExprToBCOs ) import Linker import CoreTidy ( tidyExpr ) import Type ( Type ) import PrelNames import {- Kind parts of -} Type ( Kind ) import CoreLint ( lintUnfolding ) import DsMeta ( templateHaskellNames ) import VarSet import VarEnv ( emptyTidyEnv ) import Panic import GHC.Exts #endif import Id import Module import Packages import RdrName import HsSyn import CoreSyn import StringBuffer import Parser import Lexer import SrcLoc import TcRnDriver import TcIface ( typecheckIface ) import TcRnMonad import IfaceEnv ( initNameCache ) import LoadIface ( ifaceStats, initExternalPackageState ) import PrelInfo import MkIface import Desugar import SimplCore import TidyPgm import CorePrep import CoreToStg ( coreToStg ) import qualified StgCmm ( codeGen ) import StgSyn import CostCentre import ProfInit import TyCon import Name import SimplStg ( stg2stg ) import CodeGen ( codeGen ) import qualified OldCmm as Old import qualified Cmm as New import CmmParse ( parseCmmFile ) import CmmBuildInfoTables import CmmPipeline import CmmInfo import CmmCvt import CodeOutput import NameEnv ( emptyNameEnv ) import NameSet ( emptyNameSet ) import InstEnv import FamInstEnv import Fingerprint ( Fingerprint ) import DynFlags import ErrUtils import UniqSupply ( mkSplitUniqSupply ) import Outputable import HscStats ( ppSourceStats ) import HscTypes import MkExternalCore ( emitExternalCore ) import FastString import UniqFM ( emptyUFM ) import UniqSupply ( initUs_ ) import Bag import Exception import qualified Stream import Stream (Stream) import Util import Data.List import Control.Monad import Data.Maybe import Data.IORef import System.FilePath as FilePath import System.Directory #include "HsVersions.h" {- ********************************************************************** %* * Initialisation %* * %********************************************************************* -} newHscEnv :: DynFlags -> IO HscEnv newHscEnv dflags = do eps_var <- newIORef initExternalPackageState us <- mkSplitUniqSupply 'r' nc_var <- newIORef (initNameCache us knownKeyNames) fc_var <- newIORef emptyUFM mlc_var <- newIORef emptyModuleEnv return HscEnv { hsc_dflags = dflags, hsc_targets = [], hsc_mod_graph = [], hsc_IC = emptyInteractiveContext dflags, hsc_HPT = emptyHomePackageTable, hsc_EPS = eps_var, hsc_NC = nc_var, hsc_FC = fc_var, hsc_MLC = mlc_var, hsc_type_env_var = Nothing } knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta, knownKeyNames = -- where templateHaskellNames are defined map getName wiredInThings ++ basicKnownKeyNames #ifdef GHCI ++ templateHaskellNames #endif -- ----------------------------------------------------------------------------- -- The Hsc monad: Passing an enviornment and warning state newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages)) instance Monad Hsc where return a = Hsc $ \_ w -> return (a, w) Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w case k a of Hsc k' -> k' e w1 instance MonadIO Hsc where liftIO io = Hsc $ \_ w -> do a <- io; return (a, w) instance Functor Hsc where fmap f m = m >>= \a -> return $ f a runHsc :: HscEnv -> Hsc a -> IO a runHsc hsc_env (Hsc hsc) = do (a, w) <- hsc hsc_env emptyBag printOrThrowWarnings (hsc_dflags hsc_env) w return a -- A variant of runHsc that switches in the DynFlags from the -- InteractiveContext before running the Hsc computation. -- runInteractiveHsc :: HscEnv -> Hsc a -> IO a runInteractiveHsc hsc_env = runHsc (hsc_env { hsc_dflags = ic_dflags (hsc_IC hsc_env) }) getWarnings :: Hsc WarningMessages getWarnings = Hsc $ \_ w -> return (w, w) clearWarnings :: Hsc () clearWarnings = Hsc $ \_ _ -> return ((), emptyBag) logWarnings :: WarningMessages -> Hsc () logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w) getHscEnv :: Hsc HscEnv getHscEnv = Hsc $ \e w -> return (e, w) instance HasDynFlags Hsc where getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w) handleWarnings :: Hsc () handleWarnings = do dflags <- getDynFlags w <- getWarnings liftIO $ printOrThrowWarnings dflags w clearWarnings -- | log warning in the monad, and if there are errors then -- throw a SourceError exception. logWarningsReportErrors :: Messages -> Hsc () logWarningsReportErrors (warns,errs) = do logWarnings warns when (not $ isEmptyBag errs) $ throwErrors errs -- | Throw some errors. throwErrors :: ErrorMessages -> Hsc a throwErrors = liftIO . throwIO . mkSrcErr -- | Deal with errors and warnings returned by a compilation step -- -- In order to reduce dependencies to other parts of the compiler, functions -- outside the "main" parts of GHC return warnings and errors as a parameter -- and signal success via by wrapping the result in a 'Maybe' type. This -- function logs the returned warnings and propagates errors as exceptions -- (of type 'SourceError'). -- -- This function assumes the following invariants: -- -- 1. If the second result indicates success (is of the form 'Just x'), -- there must be no error messages in the first result. -- -- 2. If there are no error messages, but the second result indicates failure -- there should be warnings in the first result. That is, if the action -- failed, it must have been due to the warnings (i.e., @-Werror@). ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a ioMsgMaybe ioA = do ((warns,errs), mb_r) <- liftIO ioA logWarnings warns case mb_r of Nothing -> throwErrors errs Just r -> ASSERT( isEmptyBag errs ) return r -- | like ioMsgMaybe, except that we ignore error messages and return -- 'Nothing' instead. ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a) ioMsgMaybe' ioA = do ((warns,_errs), mb_r) <- liftIO $ ioA logWarnings warns return mb_r -- ----------------------------------------------------------------------------- -- | Lookup things in the compiler's environment #ifdef GHCI hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name] hscTcRnLookupRdrName hsc_env0 rdr_name = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name #endif hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing) hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe' $ tcRnLookupName hsc_env name -- ignore errors: the only error we're likely to get is -- "name not found", and the Maybe in the return type -- is used to indicate that. hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst])) hscTcRnGetInfo hsc_env0 name = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe' $ tcRnGetInfo hsc_env name #ifdef GHCI hscIsGHCiMonad :: HscEnv -> String -> IO Name hscIsGHCiMonad hsc_env name = let icntxt = hsc_IC hsc_env in runHsc hsc_env $ ioMsgMaybe $ isGHCiMonad hsc_env icntxt name hscGetModuleInterface :: HscEnv -> Module -> IO ModIface hscGetModuleInterface hsc_env0 mod = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe $ getModuleInterface hsc_env mod -- ----------------------------------------------------------------------------- -- | Rename some import declarations hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv hscRnImportDecls hsc_env0 import_decls = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ioMsgMaybe $ tcRnImportDecls hsc_env import_decls #endif -- ----------------------------------------------------------------------------- -- | parse a file, returning the abstract syntax hscParse :: HscEnv -> ModSummary -> IO HsParsedModule hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary -- internal version, that doesn't fail due to -Werror hscParse' :: ModSummary -> Hsc HsParsedModule hscParse' mod_summary = do dflags <- getDynFlags let src_filename = ms_hspp_file mod_summary maybe_src_buf = ms_hspp_buf mod_summary -------------------------- Parser ---------------- liftIO $ showPass dflags "Parser" {-# SCC "Parser" #-} do -- sometimes we already have the buffer in memory, perhaps -- because we needed to parse the imports out of it, or get the -- module name. buf <- case maybe_src_buf of Just b -> return b Nothing -> liftIO $ hGetStringBuffer src_filename let loc = mkRealSrcLoc (mkFastString src_filename) 1 1 case unP parseModule (mkPState dflags buf loc) of PFailed span err -> liftIO $ throwOneError (mkPlainErrMsg dflags span err) POk pst rdr_module -> do logWarningsReportErrors (getMessages pst) liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $ ppr rdr_module liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $ ppSourceStats False rdr_module -- To get the list of extra source files, we take the list -- that the parser gave us, -- - eliminate files beginning with '<'. gcc likes to use -- pseudo-filenames like "<built-in>" and "<command-line>" -- - normalise them (elimiante differences between ./f and f) -- - filter out the preprocessed source file -- - filter out anything beginning with tmpdir -- - remove duplicates -- - filter out the .hs/.lhs source filename if we have one -- let n_hspp = FilePath.normalise src_filename srcs0 = nub $ filter (not . (tmpDir dflags `isPrefixOf`)) $ filter (not . (== n_hspp)) $ map FilePath.normalise $ filter (not . (isPrefixOf "<")) $ map unpackFS $ srcfiles pst srcs1 = case ml_hs_file (ms_location mod_summary) of Just f -> filter (/= FilePath.normalise f) srcs0 Nothing -> srcs0 -- sometimes we see source files from earlier -- preprocessing stages that cannot be found, so just -- filter them out: srcs2 <- liftIO $ filterM doesFileExist srcs1 return HsParsedModule { hpm_module = rdr_module, hpm_src_files = srcs2 } -- XXX: should this really be a Maybe X? Check under which circumstances this -- can become a Nothing and decide whether this should instead throw an -- exception/signal an error. type RenamedStuff = (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name], Maybe LHsDocString)) -- | Rename and typecheck a module, additionally returning the renamed syntax hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule -> IO (TcGblEnv, RenamedStuff) hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do tc_result <- tcRnModule' hsc_env mod_summary True rdr_module -- This 'do' is in the Maybe monad! let rn_info = do decl <- tcg_rn_decls tc_result let imports = tcg_rn_imports tc_result exports = tcg_rn_exports tc_result doc_hdr = tcg_doc_hdr tc_result return (decl,imports,exports,doc_hdr) return (tc_result, rn_info) -- wrapper around tcRnModule to handle safe haskell extras tcRnModule' :: HscEnv -> ModSummary -> Bool -> HsParsedModule -> Hsc TcGblEnv tcRnModule' hsc_env sum save_rn_syntax mod = do tcg_res <- {-# SCC "Typecheck-Rename" #-} ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src sum) save_rn_syntax mod tcSafeOK <- liftIO $ readIORef (tcg_safeInfer tcg_res) dflags <- getDynFlags -- end of the Safe Haskell line, how to respond to user? if not (safeHaskellOn dflags) || (safeInferOn dflags && not tcSafeOK) -- if safe haskell off or safe infer failed, wipe trust then wipeTrust tcg_res emptyBag -- module safe, throw warning if needed else do tcg_res' <- hscCheckSafeImports tcg_res safe <- liftIO $ readIORef (tcg_safeInfer tcg_res') when (safe && wopt Opt_WarnSafe dflags) (logWarnings $ unitBag $ mkPlainWarnMsg dflags (warnSafeOnLoc dflags) $ errSafe tcg_res') return tcg_res' where pprMod t = ppr $ moduleName $ tcg_mod t errSafe t = quotes (pprMod t) <+> text "has been inferred as safe!" -- | Convert a typechecked module to Core hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts hscDesugar hsc_env mod_summary tc_result = runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts hscDesugar' mod_location tc_result = do hsc_env <- getHscEnv r <- ioMsgMaybe $ {-# SCC "deSugar" #-} deSugar hsc_env mod_location tc_result -- always check -Werror after desugaring, this is the last opportunity for -- warnings to arise before the backend. handleWarnings return r -- | Make a 'ModIface' from the results of typechecking. Used when -- not optimising, and the interface doesn't need to contain any -- unfoldings or other cross-module optimisation info. -- ToDo: the old interface is only needed to get the version numbers, -- we should use fingerprint versions instead. makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails -> IO (ModIface,Bool) makeSimpleIface hsc_env maybe_old_iface tc_result details = runHsc hsc_env $ do safe_mode <- hscGetSafeMode tc_result ioMsgMaybe $ do mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) safe_mode details tc_result -- | Make a 'ModDetails' from the results of typechecking. Used when -- typechecking only, as opposed to full compilation. makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result {- ********************************************************************** %* * The main compiler pipeline %* * %********************************************************************* -} {- -------------------------------- The compilation proper -------------------------------- It's the task of the compilation proper to compile Haskell, hs-boot and core files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all (the module is still parsed and type-checked. This feature is mostly used by IDE's and the likes). Compilation can happen in either 'one-shot', 'batch', 'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode targets byte-code. The modes are kept separate because of their different types and meanings: * In 'one-shot' mode, we're only compiling a single file and can therefore discard the new ModIface and ModDetails. This is also the reason it only targets hard-code; compiling to byte-code or nothing doesn't make sense when we discard the result. * 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface and ModDetails. 'Batch' mode doesn't target byte-code since that require us to return the newly compiled byte-code. * 'Nothing' mode has exactly the same type as 'batch' mode but they're still kept separate. This is because compiling to nothing is fairly special: We don't output any interface files, we don't run the simplifier and we don't generate any code. * 'Interactive' mode is similar to 'batch' mode except that we return the compiled byte-code together with the ModIface and ModDetails. Trying to compile a hs-boot file to byte-code will result in a run-time error. This is the only thing that isn't caught by the type-system. -} -- | Status of a compilation to hard-code or nothing. data HscStatus' a = HscNoRecomp | HscRecomp (Maybe FilePath) -- Has stub files. This is a hack. We can't compile -- C files here since it's done in DriverPipeline. -- For now we just return True if we want the caller -- to compile them for us. a -- This is a bit ugly. Since we use a typeclass below and would like to avoid -- functional dependencies, we have to parameterise the typeclass over the -- result type. Therefore we need to artificially distinguish some types. We do -- this by adding type tags which will simply be ignored by the caller. type HscStatus = HscStatus' () type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks)) -- INVARIANT: result is @Nothing@ <=> input was a boot file type OneShotResult = HscStatus type BatchResult = (HscStatus, ModIface, ModDetails) type NothingResult = (HscStatus, ModIface, ModDetails) type InteractiveResult = (InteractiveStatus, ModIface, ModDetails) -- ToDo: The old interface and module index are only using in 'batch' and -- 'interactive' mode. They should be removed from 'oneshot' mode. type Compiler result = HscEnv -> ModSummary -> SourceModified -> Maybe ModIface -- Old interface, if available -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs) -> IO result data HsCompiler a = HsCompiler { -- | Called when no recompilation is necessary. hscNoRecomp :: ModIface -> Hsc a, -- | Called to recompile the module. hscRecompile :: ModSummary -> Maybe Fingerprint -> Hsc a, hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint -> Hsc a, -- | Code generation for Boot modules. hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint -> Hsc a, -- | Code generation for normal modules. hscGenOutput :: ModGuts -> ModSummary -> Maybe Fingerprint -> Hsc a } genericHscCompile :: HsCompiler a -> (HscEnv -> Maybe (Int,Int) -> RecompileRequired -> ModSummary -> IO ()) -> HscEnv -> ModSummary -> SourceModified -> Maybe ModIface -> Maybe (Int, Int) -> IO a genericHscCompile compiler hscMessage hsc_env mod_summary source_modified mb_old_iface0 mb_mod_index = do (recomp_reqd, mb_checked_iface) <- {-# SCC "checkOldIface" #-} checkOldIface hsc_env mod_summary source_modified mb_old_iface0 -- save the interface that comes back from checkOldIface. -- In one-shot mode we don't have the old iface until this -- point, when checkOldIface reads it from the disk. let mb_old_hash = fmap mi_iface_hash mb_checked_iface let skip iface = do hscMessage hsc_env mb_mod_index UpToDate mod_summary runHsc hsc_env $ hscNoRecomp compiler iface compile reason = do hscMessage hsc_env mb_mod_index reason mod_summary runHsc hsc_env $ hscRecompile compiler mod_summary mb_old_hash stable = case source_modified of SourceUnmodifiedAndStable -> True _ -> False -- If the module used TH splices when it was last compiled, -- then the recompilation check is not accurate enough (#481) -- and we must ignore it. However, if the module is stable -- (none of the modules it depends on, directly or indirectly, -- changed), then we *can* skip recompilation. This is why -- the SourceModified type contains SourceUnmodifiedAndStable, -- and it's pretty important: otherwise ghc --make would -- always recompile TH modules, even if nothing at all has -- changed. Stability is just the same check that make is -- doing for us in one-shot mode. case mb_checked_iface of Just iface | not (recompileRequired recomp_reqd) -> if mi_used_th iface && not stable then compile (RecompBecause "TH") else skip iface _otherwise -> compile recomp_reqd hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a hscCheckRecompBackend compiler tc_result hsc_env mod_summary source_modified mb_old_iface _m_of_n = do (recomp_reqd, mb_checked_iface) <- {-# SCC "checkOldIface" #-} checkOldIface hsc_env mod_summary source_modified mb_old_iface let mb_old_hash = fmap mi_iface_hash mb_checked_iface case mb_checked_iface of Just iface | not (recompileRequired recomp_reqd) -> runHsc hsc_env $ hscNoRecomp compiler iface{ mi_globals = Just (tcg_rdr_env tc_result) } _otherwise -> runHsc hsc_env $ hscBackend compiler tc_result mod_summary mb_old_hash genericHscRecompile :: HsCompiler a -> ModSummary -> Maybe Fingerprint -> Hsc a genericHscRecompile compiler mod_summary mb_old_hash | ExtCoreFile <- ms_hsc_src mod_summary = panic "GHC does not currently support reading External Core files" | otherwise = do tc_result <- hscFileFrontEnd mod_summary hscBackend compiler tc_result mod_summary mb_old_hash genericHscBackend :: HsCompiler a -> TcGblEnv -> ModSummary -> Maybe Fingerprint -> Hsc a genericHscBackend compiler tc_result mod_summary mb_old_hash | HsBootFile <- ms_hsc_src mod_summary = hscGenBootOutput compiler tc_result mod_summary mb_old_hash | otherwise = do guts <- hscDesugar' (ms_location mod_summary) tc_result hscGenOutput compiler guts mod_summary mb_old_hash compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ = runHsc hsc_env $ hscBackend comp tcg ms' Nothing -------------------------------------------------------------- -- Compilers -------------------------------------------------------------- hscOneShotCompiler :: HsCompiler OneShotResult hscOneShotCompiler = HsCompiler { hscNoRecomp = \_old_iface -> do hsc_env <- getHscEnv liftIO $ dumpIfaceStats hsc_env return HscNoRecomp , hscRecompile = genericHscRecompile hscOneShotCompiler , hscBackend = \tc_result mod_summary mb_old_hash -> do dflags <- getDynFlags case hscTarget dflags of HscNothing -> return (HscRecomp Nothing ()) _otherw -> genericHscBackend hscOneShotCompiler tc_result mod_summary mb_old_hash , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface hscWriteIface iface changed mod_summary return (HscRecomp Nothing ()) , hscGenOutput = \guts0 mod_summary mb_old_iface -> do guts <- hscSimplify' guts0 (iface, changed, _details, cgguts) <- hscNormalIface guts mb_old_iface hscWriteIface iface changed mod_summary hasStub <- hscGenHardCode cgguts mod_summary return (HscRecomp hasStub ()) } -- Compile Haskell, boot and extCore in OneShot mode. hscCompileOneShot :: Compiler OneShotResult hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n = do -- One-shot mode needs a knot-tying mutable variable for interface -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var. type_env_var <- newIORef emptyNameEnv let mod = ms_mod mod_summary hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) } genericHscCompile hscOneShotCompiler oneShotMsg hsc_env' mod_summary src_changed mb_old_iface mb_i_of_n hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult hscOneShotBackendOnly = compilerBackend hscOneShotCompiler -------------------------------------------------------------- hscBatchCompiler :: HsCompiler BatchResult hscBatchCompiler = HsCompiler { hscNoRecomp = \iface -> do details <- genModDetails iface return (HscNoRecomp, iface, details) , hscRecompile = genericHscRecompile hscBatchCompiler , hscBackend = genericHscBackend hscBatchCompiler , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do (iface, changed, details) <- hscSimpleIface tc_result mb_old_iface hscWriteIface iface changed mod_summary return (HscRecomp Nothing (), iface, details) , hscGenOutput = \guts0 mod_summary mb_old_iface -> do guts <- hscSimplify' guts0 (iface, changed, details, cgguts) <- hscNormalIface guts mb_old_iface hscWriteIface iface changed mod_summary hasStub <- hscGenHardCode cgguts mod_summary return (HscRecomp hasStub (), iface, details) } -- | Compile Haskell, boot and extCore in batch mode. hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails) hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler -------------------------------------------------------------- hscInteractiveCompiler :: HsCompiler InteractiveResult hscInteractiveCompiler = HsCompiler { hscNoRecomp = \iface -> do details <- genModDetails iface return (HscNoRecomp, iface, details) , hscRecompile = genericHscRecompile hscInteractiveCompiler , hscBackend = genericHscBackend hscInteractiveCompiler , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface return (HscRecomp Nothing Nothing, iface, details) , hscGenOutput = \guts0 mod_summary mb_old_iface -> do guts <- hscSimplify' guts0 (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface hscInteractive (iface, details, cgguts) mod_summary } -- Compile Haskell, extCore to bytecode. hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails) hscCompileInteractive = genericHscCompile hscInteractiveCompiler batchMsg hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler -------------------------------------------------------------- hscNothingCompiler :: HsCompiler NothingResult hscNothingCompiler = HsCompiler { hscNoRecomp = \iface -> do details <- genModDetails iface return (HscNoRecomp, iface, details) , hscRecompile = genericHscRecompile hscNothingCompiler , hscBackend = \tc_result _mod_summary mb_old_iface -> do handleWarnings (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface return (HscRecomp Nothing (), iface, details) , hscGenBootOutput = \_ _ _ -> panic "hscCompileNothing: hscGenBootOutput should not be called" , hscGenOutput = \_ _ _ -> panic "hscCompileNothing: hscGenOutput should not be called" } -- Type-check Haskell and .hs-boot only (no external core) hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails) hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult hscNothingBackendOnly = compilerBackend hscNothingCompiler -------------------------------------------------------------- -- NoRecomp handlers -------------------------------------------------------------- genModDetails :: ModIface -> Hsc ModDetails genModDetails old_iface = do hsc_env <- getHscEnv new_details <- {-# SCC "tcRnIface" #-} liftIO $ initIfaceCheck hsc_env (typecheckIface old_iface) liftIO $ dumpIfaceStats hsc_env return new_details -------------------------------------------------------------- -- Progress displayers. -------------------------------------------------------------- oneShotMsg :: HscEnv -> Maybe (Int,Int) -> RecompileRequired -> ModSummary -> IO () oneShotMsg hsc_env _mb_mod_index recomp _mod_summary = case recomp of UpToDate -> compilationProgressMsg (hsc_dflags hsc_env) $ "compilation IS NOT required" _other -> return () batchMsg :: HscEnv -> Maybe (Int,Int) -> RecompileRequired -> ModSummary -> IO () batchMsg hsc_env mb_mod_index recomp mod_summary = case recomp of MustCompile -> showMsg "Compiling " "" UpToDate | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping " "" | otherwise -> return () RecompBecause reason -> showMsg "Compiling " (" [" ++ reason ++ "]") where dflags = hsc_dflags hsc_env showMsg msg reason = compilationProgressMsg dflags $ (showModuleIndex mb_mod_index ++ msg ++ showModMsg dflags (hscTarget dflags) (recompileRequired recomp) mod_summary) ++ reason -------------------------------------------------------------- -- FrontEnds -------------------------------------------------------------- hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv hscFileFrontEnd mod_summary = do hpm <- hscParse' mod_summary hsc_env <- getHscEnv tcg_env <- tcRnModule' hsc_env mod_summary False hpm return tcg_env -------------------------------------------------------------- -- Safe Haskell -------------------------------------------------------------- -- Note [Safe Haskell Trust Check] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Safe Haskell checks that an import is trusted according to the following -- rules for an import of module M that resides in Package P: -- -- * If M is recorded as Safe and all its trust dependencies are OK -- then M is considered safe. -- * If M is recorded as Trustworthy and P is considered trusted and -- all M's trust dependencies are OK then M is considered safe. -- -- By trust dependencies we mean that the check is transitive. So if -- a module M that is Safe relies on a module N that is trustworthy, -- importing module M will first check (according to the second case) -- that N is trusted before checking M is trusted. -- -- This is a minimal description, so please refer to the user guide -- for more details. The user guide is also considered the authoritative -- source in this matter, not the comments or code. -- Note [Safe Haskell Inference] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Safe Haskell does Safe inference on modules that don't have any specific -- safe haskell mode flag. The basic aproach to this is: -- * When deciding if we need to do a Safe language check, treat -- an unmarked module as having -XSafe mode specified. -- * For checks, don't throw errors but return them to the caller. -- * Caller checks if there are errors: -- * For modules explicitly marked -XSafe, we throw the errors. -- * For unmarked modules (inference mode), we drop the errors -- and mark the module as being Unsafe. -- | Check that the safe imports of the module being compiled are valid. -- If not we either issue a compilation error if the module is explicitly -- using Safe Haskell, or mark the module as unsafe if we're in safe -- inference mode. hscCheckSafeImports :: TcGblEnv -> Hsc TcGblEnv hscCheckSafeImports tcg_env = do dflags <- getDynFlags tcg_env' <- checkSafeImports dflags tcg_env case safeLanguageOn dflags of True -> do -- we nuke user written RULES in -XSafe logWarnings $ warns dflags (tcg_rules tcg_env') return tcg_env' { tcg_rules = [] } False -- user defined RULES, so not safe or already unsafe | safeInferOn dflags && not (null $ tcg_rules tcg_env') || safeHaskell dflags == Sf_None -> wipeTrust tcg_env' $ warns dflags (tcg_rules tcg_env') -- trustworthy OR safe inferred with no RULES | otherwise -> return tcg_env' where warns dflags rules = listToBag $ map (warnRules dflags) rules warnRules dflags (L loc (HsRule n _ _ _ _ _ _)) = mkPlainWarnMsg dflags loc $ text "Rule \"" <> ftext n <> text "\" ignored" $+$ text "User defined rules are disabled under Safe Haskell" -- | Validate that safe imported modules are actually safe. For modules in the -- HomePackage (the package the module we are compiling in resides) this just -- involves checking its trust type is 'Safe' or 'Trustworthy'. For modules -- that reside in another package we also must check that the external pacakge -- is trusted. See the Note [Safe Haskell Trust Check] above for more -- information. -- -- The code for this is quite tricky as the whole algorithm is done in a few -- distinct phases in different parts of the code base. See -- RnNames.rnImportDecl for where package trust dependencies for a module are -- collected and unioned. Specifically see the Note [RnNames . Tracking Trust -- Transitively] and the Note [RnNames . Trust Own Package]. checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv checkSafeImports dflags tcg_env = do -- We want to use the warning state specifically for detecting if safe -- inference has failed, so store and clear any existing warnings. oldErrs <- getWarnings clearWarnings imps <- mapM condense imports' pkgs <- mapM checkSafe imps -- grab any safe haskell specific errors and restore old warnings errs <- getWarnings clearWarnings logWarnings oldErrs -- See the Note [Safe Haskell Inference] case (not $ isEmptyBag errs) of -- We have errors! True -> -- did we fail safe inference or fail -XSafe? case safeInferOn dflags of True -> wipeTrust tcg_env errs False -> liftIO . throwIO . mkSrcErr $ errs -- All good matey! False -> do when (packageTrustOn dflags) $ checkPkgTrust dflags pkg_reqs -- add in trusted package requirements for this module let new_trust = emptyImportAvails { imp_trust_pkgs = catMaybes pkgs } return tcg_env { tcg_imports = imp_info `plusImportAvails` new_trust } where imp_info = tcg_imports tcg_env -- ImportAvails imports = imp_mods imp_info -- ImportedMods imports' = moduleEnvToList imports -- (Module, [ImportedModsVal]) pkg_reqs = imp_trust_pkgs imp_info -- [PackageId] condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport) condense (_, []) = panic "HscMain.condense: Pattern match failure!" condense (m, x:xs) = do (_,_,l,s) <- foldlM cond' x xs -- we turn all imports into safe ones when -- inference mode is on. let s' = if safeInferOn dflags then True else s return (m, l, s') -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport) cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal cond' v1@(m1,_,l1,s1) (_,_,_,s2) | s1 /= s2 = throwErrors $ unitBag $ mkPlainErrMsg dflags l1 (text "Module" <+> ppr m1 <+> (text $ "is imported both as a safe and unsafe import!")) | otherwise = return v1 -- easier interface to work with checkSafe (_, _, False) = return Nothing checkSafe (m, l, True ) = fst `fmap` hscCheckSafe' dflags m l -- | Check that a module is safe to import. -- -- We return True to indicate the import is safe and False otherwise -- although in the False case an exception may be thrown first. hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO Bool hscCheckSafe hsc_env m l = runHsc hsc_env $ do dflags <- getDynFlags pkgs <- snd `fmap` hscCheckSafe' dflags m l when (packageTrustOn dflags) $ checkPkgTrust dflags pkgs errs <- getWarnings return $ isEmptyBag errs -- | Return if a module is trusted and the pkgs it depends on to be trusted. hscGetSafe :: HscEnv -> Module -> SrcSpan -> IO (Bool, [PackageId]) hscGetSafe hsc_env m l = runHsc hsc_env $ do dflags <- getDynFlags (self, pkgs) <- hscCheckSafe' dflags m l good <- isEmptyBag `fmap` getWarnings clearWarnings -- don't want them printed... let pkgs' | Just p <- self = p:pkgs | otherwise = pkgs return (good, pkgs') -- | Is a module trusted? If not, throw or log errors depending on the type. -- Return (regardless of trusted or not) if the trust type requires the modules -- own package be trusted and a list of other packages required to be trusted -- (these later ones haven't been checked) but the own package trust has been. hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageId, [PackageId]) hscCheckSafe' dflags m l = do (tw, pkgs) <- isModSafe m l case tw of False -> return (Nothing, pkgs) True | isHomePkg m -> return (Nothing, pkgs) | otherwise -> return (Just $ modulePackageId m, pkgs) where isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageId]) isModSafe m l = do iface <- lookup' m case iface of -- can't load iface to check trust! Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l $ text "Can't load the interface file for" <+> ppr m <> text ", to check that it can be safely imported" -- got iface, check trust Just iface' -> let trust = getSafeMode $ mi_trust iface' trust_own_pkg = mi_trust_pkg iface' -- check module is trusted safeM = trust `elem` [Sf_SafeInferred, Sf_Safe, Sf_Trustworthy] -- check package is trusted safeP = packageTrusted trust trust_own_pkg m -- pkg trust reqs pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface' -- General errors we throw but Safe errors we log errs = case (safeM, safeP) of (True, True ) -> emptyBag (True, False) -> pkgTrustErr (False, _ ) -> modTrustErr in do logWarnings errs return (trust == Sf_Trustworthy, pkgRs) where pkgTrustErr = unitBag $ mkPlainErrMsg dflags l $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The package (" <> ppr (modulePackageId m) <> text ") the module resides in isn't trusted." ] modTrustErr = unitBag $ mkPlainErrMsg dflags l $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The module itself isn't safe." ] -- | Check the package a module resides in is trusted. Safe compiled -- modules are trusted without requiring that their package is trusted. For -- trustworthy modules, modules in the home package are trusted but -- otherwise we check the package trust flag. packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool packageTrusted Sf_None _ _ = False -- shouldn't hit these cases packageTrusted Sf_Unsafe _ _ = False -- prefer for completeness. packageTrusted _ _ _ | not (packageTrustOn dflags) = True packageTrusted Sf_Safe False _ = True packageTrusted Sf_SafeInferred False _ = True packageTrusted _ _ m | isHomePkg m = True | otherwise = trusted $ getPackageDetails (pkgState dflags) (modulePackageId m) lookup' :: Module -> Hsc (Maybe ModIface) lookup' m = do hsc_env <- getHscEnv hsc_eps <- liftIO $ hscEPS hsc_env let pkgIfaceT = eps_PIT hsc_eps homePkgT = hsc_HPT hsc_env iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m #ifdef GHCI -- the 'lookupIfaceByModule' method will always fail when calling from GHCi -- as the compiler hasn't filled in the various module tables -- so we need to call 'getModuleInterface' to load from disk iface' <- case iface of Just _ -> return iface Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m) return iface' #else return iface #endif isHomePkg :: Module -> Bool isHomePkg m | thisPackage dflags == modulePackageId m = True | otherwise = False -- | Check the list of packages are trusted. checkPkgTrust :: DynFlags -> [PackageId] -> Hsc () checkPkgTrust dflags pkgs = case errors of [] -> return () _ -> (liftIO . throwIO . mkSrcErr . listToBag) errors where errors = catMaybes $ map go pkgs go pkg | trusted $ getPackageDetails (pkgState dflags) pkg = Nothing | otherwise = Just $ mkPlainErrMsg dflags noSrcSpan $ text "The package (" <> ppr pkg <> text ") is required" <> text " to be trusted but it isn't!" -- | Set module to unsafe and wipe trust information. -- -- Make sure to call this method to set a module to inferred unsafe, -- it should be a central and single failure method. wipeTrust :: TcGblEnv -> WarningMessages -> Hsc TcGblEnv wipeTrust tcg_env whyUnsafe = do dflags <- getDynFlags when (wopt Opt_WarnUnsafe dflags) (logWarnings $ unitBag $ mkPlainWarnMsg dflags (warnUnsafeOnLoc dflags) (whyUnsafe' dflags)) liftIO $ writeIORef (tcg_safeInfer tcg_env) False return $ tcg_env { tcg_imports = wiped_trust } where wiped_trust = (tcg_imports tcg_env) { imp_trust_pkgs = [] } pprMod = ppr $ moduleName $ tcg_mod tcg_env whyUnsafe' df = vcat [ quotes pprMod <+> text "has been inferred as unsafe!" , text "Reason:" , nest 4 $ (vcat $ badFlags df) $+$ (vcat $ pprErrMsgBagWithLoc whyUnsafe) ] badFlags df = concat $ map (badFlag df) unsafeFlags badFlag df (str,loc,on,_) | on df = [mkLocMessage SevOutput (loc df) $ text str <+> text "is not allowed in Safe Haskell"] | otherwise = [] -- | Figure out the final correct safe haskell mode hscGetSafeMode :: TcGblEnv -> Hsc SafeHaskellMode hscGetSafeMode tcg_env = do dflags <- getDynFlags liftIO $ finalSafeMode dflags tcg_env -------------------------------------------------------------- -- Simplifiers -------------------------------------------------------------- hscSimplify :: HscEnv -> ModGuts -> IO ModGuts hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts hscSimplify' :: ModGuts -> Hsc ModGuts hscSimplify' ds_result = do hsc_env <- getHscEnv {-# SCC "Core2Core" #-} liftIO $ core2core hsc_env ds_result -------------------------------------------------------------- -- Interface generators -------------------------------------------------------------- hscSimpleIface :: TcGblEnv -> Maybe Fingerprint -> Hsc (ModIface, Bool, ModDetails) hscSimpleIface tc_result mb_old_iface = do hsc_env <- getHscEnv details <- liftIO $ mkBootModDetailsTc hsc_env tc_result safe_mode <- hscGetSafeMode tc_result (new_iface, no_change) <- {-# SCC "MkFinalIface" #-} ioMsgMaybe $ mkIfaceTc hsc_env mb_old_iface safe_mode details tc_result -- And the answer is ... liftIO $ dumpIfaceStats hsc_env return (new_iface, no_change, details) hscNormalIface :: ModGuts -> Maybe Fingerprint -> Hsc (ModIface, Bool, ModDetails, CgGuts) hscNormalIface simpl_result mb_old_iface = do hsc_env <- getHscEnv (cg_guts, details) <- {-# SCC "CoreTidy" #-} liftIO $ tidyProgram hsc_env simpl_result -- BUILD THE NEW ModIface and ModDetails -- and emit external core if necessary -- This has to happen *after* code gen so that the back-end -- info has been set. Not yet clear if it matters waiting -- until after code output (new_iface, no_change) <- {-# SCC "MkFinalIface" #-} ioMsgMaybe $ mkIface hsc_env mb_old_iface details simpl_result -- Emit external core -- This should definitely be here and not after CorePrep, -- because CorePrep produces unqualified constructor wrapper declarations, -- so its output isn't valid External Core (without some preprocessing). liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts liftIO $ dumpIfaceStats hsc_env -- Return the prepared code. return (new_iface, no_change, details, cg_guts) -------------------------------------------------------------- -- BackEnd combinators -------------------------------------------------------------- hscWriteIface :: ModIface -> Bool -> ModSummary -> Hsc () hscWriteIface iface no_change mod_summary = do dflags <- getDynFlags unless no_change $ {-# SCC "writeIface" #-} liftIO $ writeIfaceFile dflags (ms_location mod_summary) iface -- | Compile to hard-code. hscGenHardCode :: CgGuts -> ModSummary -> Hsc (Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f hscGenHardCode cgguts mod_summary = do hsc_env <- getHscEnv liftIO $ do let CgGuts{ -- This is the last use of the ModGuts in a compilation. -- From now on, we just use the bits we need. cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_foreign = foreign_stubs0, cg_dep_pkgs = dependencies, cg_hpc_info = hpc_info } = cgguts dflags = hsc_dflags hsc_env location = ms_location mod_summary data_tycons = filter isDataTyCon tycons -- cg_tycons includes newtypes, for the benefit of External Core, -- but we don't generate any code for newtypes ------------------- -- PREPARE FOR CODE GENERATION -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} corePrepPgm dflags hsc_env core_binds data_tycons ; ----------------- Convert to STG ------------------ (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-} myCoreToStg dflags this_mod prepd_binds let prof_init = profilingInitCode this_mod cost_centre_info foreign_stubs = foreign_stubs0 `appendStubC` prof_init ------------------ Code generation ------------------ cmms <- if dopt Opt_TryNewCodeGen dflags then {-# SCC "NewCodeGen" #-} tryNewCodeGen hsc_env this_mod data_tycons cost_centre_info stg_binds hpc_info else {-# SCC "CodeGen" #-} return (codeGen dflags this_mod data_tycons cost_centre_info stg_binds hpc_info) ------------------ Code output ----------------------- rawcmms0 <- {-# SCC "cmmToRawCmm" #-} cmmToRawCmm dflags cmms let dump a = do dumpIfSet_dyn dflags Opt_D_dump_raw_cmm "Raw Cmm" (ppr a) return a rawcmms1 = Stream.mapM dump rawcmms0 (_stub_h_exists, stub_c_exists) <- {-# SCC "codeOutput" #-} codeOutput dflags this_mod location foreign_stubs dependencies rawcmms1 return stub_c_exists hscInteractive :: (ModIface, ModDetails, CgGuts) -> ModSummary -> Hsc (InteractiveStatus, ModIface, ModDetails) #ifdef GHCI hscInteractive (iface, details, cgguts) mod_summary = do dflags <- getDynFlags let CgGuts{ -- This is the last use of the ModGuts in a compilation. -- From now on, we just use the bits we need. cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_foreign = foreign_stubs, cg_modBreaks = mod_breaks } = cgguts location = ms_location mod_summary data_tycons = filter isDataTyCon tycons -- cg_tycons includes newtypes, for the benefit of External Core, -- but we don't generate any code for newtypes ------------------- -- PREPARE FOR CODE GENERATION -- Do saturation and convert to A-normal form hsc_env <- getHscEnv prepd_binds <- {-# SCC "CorePrep" #-} liftIO $ corePrepPgm dflags hsc_env core_binds data_tycons ----------------- Generate byte code ------------------ comp_bc <- liftIO $ byteCodeGen dflags this_mod prepd_binds data_tycons mod_breaks ------------------ Create f-x-dynamic C-side stuff --- (_istub_h_exists, istub_c_exists) <- liftIO $ outputForeignStubs dflags this_mod location foreign_stubs return (HscRecomp istub_c_exists (Just (comp_bc, mod_breaks)) , iface, details) #else hscInteractive _ _ = panic "GHC not compiled with interpreter" #endif ------------------------------ hscCompileCmmFile :: HscEnv -> FilePath -> IO () hscCompileCmmFile hsc_env filename = runHsc hsc_env $ do let dflags = hsc_dflags hsc_env cmm <- ioMsgMaybe $ parseCmmFile dflags filename liftIO $ do rawCmms <- cmmToRawCmm dflags (Stream.yield cmm) _ <- codeOutput dflags no_mod no_loc NoStubs [] rawCmms return () where no_mod = panic "hscCmmFile: no_mod" no_loc = ModLocation{ ml_hs_file = Just filename, ml_hi_file = panic "hscCmmFile: no hi file", ml_obj_file = panic "hscCmmFile: no obj file" } -------------------- Stuff for new code gen --------------------- tryNewCodeGen :: HscEnv -> Module -> [TyCon] -> CollectedCCs -> [(StgBinding,[(Id,[Id])])] -> HpcInfo -> IO (Stream IO Old.CmmGroup ()) -- Note we produce a 'Stream' of CmmGroups, so that the -- backend can be run incrementally. Otherwise it generates all -- the C-- up front, which has a significant space cost. tryNewCodeGen hsc_env this_mod data_tycons cost_centre_info stg_binds hpc_info = do let dflags = hsc_dflags hsc_env let cmm_stream :: Stream IO New.CmmGroup () cmm_stream = {-# SCC "StgCmm" #-} StgCmm.codeGen dflags this_mod data_tycons cost_centre_info stg_binds hpc_info -- codegen consumes a stream of CmmGroup, and produces a new -- stream of CmmGroup (not necessarily synchronised: one -- CmmGroup on input may produce many CmmGroups on output due -- to proc-point splitting). let dump1 a = do dumpIfSet_dyn dflags Opt_D_dump_cmmz "Cmm produced by new codegen" (ppr a) return a ppr_stream1 = Stream.mapM dump1 cmm_stream -- We are building a single SRT for the entire module, so -- we must thread it through all the procedures as we cps-convert them. us <- mkSplitUniqSupply 'S' let initTopSRT = initUs_ us emptySRT let run_pipeline topSRT cmmgroup = do (topSRT, cmmgroup) <- cmmPipeline hsc_env topSRT cmmgroup return (topSRT,cmmOfZgraph cmmgroup) let pipeline_stream = {-# SCC "cmmPipeline" #-} do topSRT <- Stream.mapAccumL run_pipeline initTopSRT ppr_stream1 Stream.yield (cmmOfZgraph (srtToData topSRT)) let dump2 a = do dumpIfSet_dyn dflags Opt_D_dump_cmmz "Output Cmm" $ ppr a return a ppr_stream2 = Stream.mapM dump2 pipeline_stream return ppr_stream2 myCoreToStg :: DynFlags -> Module -> CoreProgram -> IO ( [(StgBinding,[(Id,[Id])])] -- output program , CollectedCCs) -- cost centre info (declared and used) myCoreToStg dflags this_mod prepd_binds = do stg_binds <- {-# SCC "Core2Stg" #-} coreToStg dflags prepd_binds (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-} stg2stg dflags this_mod stg_binds return (stg_binds2, cost_centre_info) {- ********************************************************************** %* * \subsection{Compiling a do-statement} %* * %********************************************************************* -} {- When the UnlinkedBCOExpr is linked you get an HValue of type *IO [HValue]* When you run it you get a list of HValues that should be the same length as the list of names; add them to the ClosureEnv. A naked expression returns a singleton Name [it]. The stmt is lifted into the IO monad as explained in Note [Interactively-bound Ids in GHCi] in TcRnDriver -} #ifdef GHCI -- | Compile a stmt all the way to an HValue, but don't run it -- -- We return Nothing to indicate an empty statement (or comment only), not a -- parse error. hscStmt :: HscEnv -> String -> IO (Maybe ([Id], IO [HValue], FixityEnv)) hscStmt hsc_env stmt = hscStmtWithLocation hsc_env stmt "<interactive>" 1 -- | Compile a stmt all the way to an HValue, but don't run it -- -- We return Nothing to indicate an empty statement (or comment only), not a -- parse error. hscStmtWithLocation :: HscEnv -> String -- ^ The statement -> String -- ^ The source -> Int -- ^ Starting line -> IO (Maybe ([Id], IO [HValue], FixityEnv)) hscStmtWithLocation hsc_env0 stmt source linenumber = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv maybe_stmt <- hscParseStmtWithLocation source linenumber stmt case maybe_stmt of Nothing -> return Nothing Just parsed_stmt -> do let icntxt = hsc_IC hsc_env rdr_env = ic_rn_gbl_env icntxt type_env = mkTypeEnvWithImplicits (ic_tythings icntxt) src_span = srcLocSpan interactiveSrcLoc -- Rename and typecheck it -- Here we lift the stmt into the IO monad, see Note -- [Interactively-bound Ids in GHCi] in TcRnDriver (ids, tc_expr, fix_env) <- ioMsgMaybe $ tcRnStmt hsc_env icntxt parsed_stmt -- Desugar it ds_expr <- ioMsgMaybe $ deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr handleWarnings -- Then code-gen, and link it hsc_env <- getHscEnv hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr let hval_io = unsafeCoerce# hval :: IO [HValue] return $ Just (ids, hval_io, fix_env) -- | Compile a decls hscDecls :: HscEnv -> String -- ^ The statement -> IO ([TyThing], InteractiveContext) hscDecls hsc_env str = hscDeclsWithLocation hsc_env str "<interactive>" 1 -- | Compile a decls hscDeclsWithLocation :: HscEnv -> String -- ^ The statement -> String -- ^ The source -> Int -- ^ Starting line -> IO ([TyThing], InteractiveContext) hscDeclsWithLocation hsc_env0 str source linenumber = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv L _ (HsModule{ hsmodDecls = decls }) <- hscParseThingWithLocation source linenumber parseModule str {- Rename and typecheck it -} let icontext = hsc_IC hsc_env tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env icontext decls {- Grab the new instances -} -- We grab the whole environment because of the overlapping that may have -- been done. See the notes at the definition of InteractiveContext -- (ic_instances) for more details. let finsts = tcg_fam_insts tc_gblenv insts = tcg_insts tc_gblenv let defaults = tcg_default tc_gblenv {- Desugar it -} -- We use a basically null location for iNTERACTIVE let iNTERACTIVELoc = ModLocation{ ml_hs_file = Nothing, ml_hi_file = panic "hsDeclsWithLocation:ml_hi_file", ml_obj_file = panic "hsDeclsWithLocation:ml_hi_file"} ds_result <- hscDesugar' iNTERACTIVELoc tc_gblenv {- Simplify -} simpl_mg <- liftIO $ hscSimplify hsc_env ds_result {- Tidy -} (tidy_cg, _mod_details) <- liftIO $ tidyProgram hsc_env simpl_mg let dflags = hsc_dflags hsc_env !CgGuts{ cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_modBreaks = mod_breaks } = tidy_cg data_tycons = filter isDataTyCon tycons {- Prepare For Code Generation -} -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} liftIO $ corePrepPgm dflags hsc_env core_binds data_tycons {- Generate byte code -} cbc <- liftIO $ byteCodeGen dflags this_mod prepd_binds data_tycons mod_breaks let src_span = srcLocSpan interactiveSrcLoc hsc_env <- getHscEnv liftIO $ linkDecls hsc_env src_span cbc let tcs = filter (not . isImplicitTyCon) $ (mg_tcs simpl_mg) ext_vars = filter (isExternalName . idName) $ bindersOfBinds core_binds (sys_vars, user_vars) = partition is_sys_var ext_vars is_sys_var id = isDFunId id || isRecordSelector id || isJust (isClassOpId_maybe id) -- we only need to keep around the external bindings -- (as decided by TidyPgm), since those are the only ones -- that might be referenced elsewhere. tythings = map AnId user_vars ++ map ATyCon tcs let ictxt1 = extendInteractiveContext icontext tythings ictxt = ictxt1 { ic_sys_vars = sys_vars ++ ic_sys_vars ictxt1, ic_instances = (insts, finsts), ic_default = defaults } return (tythings, ictxt) hscImport :: HscEnv -> String -> IO (ImportDecl RdrName) hscImport hsc_env str = runInteractiveHsc hsc_env $ do (L _ (HsModule{hsmodImports=is})) <- hscParseThing parseModule str case is of [i] -> return (unLoc i) _ -> liftIO $ throwOneError $ mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan $ ptext (sLit "parse error in import declaration") -- | Typecheck an expression (but don't run it) hscTcExpr :: HscEnv -> String -- ^ The expression -> IO Type hscTcExpr hsc_env0 expr = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv maybe_stmt <- hscParseStmt expr case maybe_stmt of Just (L _ (ExprStmt expr _ _ _)) -> ioMsgMaybe $ tcRnExpr hsc_env (hsc_IC hsc_env) expr _ -> throwErrors $ unitBag $ mkPlainErrMsg (hsc_dflags hsc_env) noSrcSpan (text "not an expression:" <+> quotes (text expr)) -- | Find the kind of a type hscKcType :: HscEnv -> Bool -- ^ Normalise the type -> String -- ^ The type as a string -> IO (Type, Kind) -- ^ Resulting type (possibly normalised) and kind hscKcType hsc_env0 normalise str = runInteractiveHsc hsc_env0 $ do hsc_env <- getHscEnv ty <- hscParseType str ioMsgMaybe $ tcRnType hsc_env (hsc_IC hsc_env) normalise ty hscParseStmt :: String -> Hsc (Maybe (LStmt RdrName)) hscParseStmt = hscParseThing parseStmt hscParseStmtWithLocation :: String -> Int -> String -> Hsc (Maybe (LStmt RdrName)) hscParseStmtWithLocation source linenumber stmt = hscParseThingWithLocation source linenumber parseStmt stmt hscParseType :: String -> Hsc (LHsType RdrName) hscParseType = hscParseThing parseType #endif hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName) hscParseIdentifier hsc_env str = runInteractiveHsc hsc_env $ hscParseThing parseIdentifier str hscParseThing :: (Outputable thing) => Lexer.P thing -> String -> Hsc thing hscParseThing = hscParseThingWithLocation "<interactive>" 1 hscParseThingWithLocation :: (Outputable thing) => String -> Int -> Lexer.P thing -> String -> Hsc thing hscParseThingWithLocation source linenumber parser str = {-# SCC "Parser" #-} do dflags <- getDynFlags liftIO $ showPass dflags "Parser" let buf = stringToStringBuffer str loc = mkRealSrcLoc (fsLit source) linenumber 1 case unP parser (mkPState dflags buf loc) of PFailed span err -> do let msg = mkPlainErrMsg dflags span err throwErrors $ unitBag msg POk pst thing -> do logWarningsReportErrors (getMessages pst) liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing) return thing hscCompileCore :: HscEnv -> Bool -> SafeHaskellMode -> ModSummary -> CoreProgram -> IO () hscCompileCore hsc_env simplify safe_mode mod_summary binds = runHsc hsc_env $ do guts <- maybe_simplify (mkModGuts (ms_mod mod_summary) safe_mode binds) (iface, changed, _details, cgguts) <- hscNormalIface guts Nothing hscWriteIface iface changed mod_summary _ <- hscGenHardCode cgguts mod_summary return () where maybe_simplify mod_guts | simplify = hscSimplify' mod_guts | otherwise = return mod_guts -- Makes a "vanilla" ModGuts. mkModGuts :: Module -> SafeHaskellMode -> CoreProgram -> ModGuts mkModGuts mod safe binds = ModGuts { mg_module = mod, mg_boot = False, mg_exports = [], mg_deps = noDependencies, mg_dir_imps = emptyModuleEnv, mg_used_names = emptyNameSet, mg_used_th = False, mg_rdr_env = emptyGlobalRdrEnv, mg_fix_env = emptyFixityEnv, mg_tcs = [], mg_insts = [], mg_fam_insts = [], mg_rules = [], mg_vect_decls = [], mg_binds = binds, mg_foreign = NoStubs, mg_warns = NoWarnings, mg_anns = [], mg_hpc_info = emptyHpcInfo False, mg_modBreaks = emptyModBreaks, mg_vect_info = noVectInfo, mg_inst_env = emptyInstEnv, mg_fam_inst_env = emptyFamInstEnv, mg_safe_haskell = safe, mg_trust_pkg = False, mg_dependent_files = [] } {- ********************************************************************** %* * Desugar, simplify, convert to bytecode, and link an expression %* * %********************************************************************* -} #ifdef GHCI hscCompileCoreExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue hscCompileCoreExpr hsc_env srcspan ds_expr | rtsIsProfiled = throwIO (InstallationError "You can't call hscCompileCoreExpr in a profiled compiler") -- Otherwise you get a seg-fault when you run it | otherwise = do let dflags = hsc_dflags hsc_env let lint_on = dopt Opt_DoCoreLinting dflags {- Simplify it -} simpl_expr <- simplifyExpr dflags ds_expr {- Tidy it (temporary, until coreSat does cloning) -} let tidy_expr = tidyExpr emptyTidyEnv simpl_expr {- Prepare for codegen -} prepd_expr <- corePrepExpr dflags hsc_env tidy_expr {- Lint if necessary -} -- ToDo: improve SrcLoc when lint_on $ let ictxt = hsc_IC hsc_env te = mkTypeEnvWithImplicits (ic_tythings ictxt ++ map AnId (ic_sys_vars ictxt)) tyvars = varSetElems $ tyThingsTyVars $ typeEnvElts $ te vars = typeEnvIds te in case lintUnfolding noSrcLoc (tyvars ++ vars) prepd_expr of Just err -> pprPanic "hscCompileCoreExpr" err Nothing -> return () {- Convert to BCOs -} bcos <- coreExprToBCOs dflags iNTERACTIVE prepd_expr {- link it -} hval <- linkExpr hsc_env srcspan bcos return hval #endif {- ********************************************************************** %* * Statistics on reading interfaces %* * %********************************************************************* -} dumpIfaceStats :: HscEnv -> IO () dumpIfaceStats hsc_env = do eps <- readIORef (hsc_EPS hsc_env) dumpIfSet dflags (dump_if_trace || dump_rn_stats) "Interface statistics" (ifaceStats eps) where dflags = hsc_dflags hsc_env dump_rn_stats = dopt Opt_D_dump_rn_stats dflags dump_if_trace = dopt Opt_D_dump_if_trace dflags {- ********************************************************************** %* * Progress Messages: Module i of n %* * %********************************************************************* -} showModuleIndex :: Maybe (Int, Int) -> String showModuleIndex Nothing = "" showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] " where n_str = show n i_str = show i padded = replicate (length n_str - length i_str) ' ' ++ i_str
nomeata/ghc
compiler/main/HscMain.hs
bsd-3-clause
70,097
7
28
20,093
12,380
6,363
6,017
-1
-1
{-# OPTIONS -fno-warn-unused-do-bind #-} module Data.MultiProto.Protobuf.Parser where import Control.Applicative import Data.Attoparsec.ByteString.Char8 hiding (option) import Data.ByteString.Char8 (ByteString) import Data.Monoid import Prelude hiding (Enum) import Text.Read (readMaybe) import qualified Data.Attoparsec.ByteString.Char8 as Parser import qualified Data.ByteString.Char8 as ByteString data Proto = ProtoMessage Message | ProtoExtend Extend | ProtoEnum Enum | ProtoImport ByteString | ProtoPackage ByteString | ProtoOption Option | Empty deriving (Show, Read, Eq) data Message = Message ByteString [MessageInner] deriving (Show, Read, Eq) data Extend = Extend UserType [MessageInner] deriving (Show, Read, Eq) data MessageInner = MessageField Field | MessageEnum Enum | NestedMessage Message | MessageExtend Extend | MessageExtensions | MessageOption Option deriving (Show, Read, Eq) data Field = Field Modifier Type ByteString Integer [Option] deriving (Show, Read, Eq) data Type = TDouble | TFloat | TInt32 | TInt64 | TUInt32 | TUInt64 | TSInt32 | TSInt64 | TFixed32 | TFixed64 | TSFixed32 | TSFixed64 | TBool | TString | TBytes | TUser UserType deriving (Show, Read, Eq) data UserType = FullyQualified [ByteString] | InScope [ByteString] deriving (Show, Read, Eq) data Modifier = Required | Optional | Repeated deriving (Show, Read, Eq) data Option = Option [ByteString] Literal deriving (Show, Read, Eq) data Literal = Identifier ByteString | StringLit ByteString | IntegerLit Integer | FloatLit Double | BoolLit Bool deriving (Show, Read, Eq) data Enum = Enum ByteString [EnumInner] deriving (Show, Read, Eq) data EnumInner = EnumOption Option | EnumField ByteString Integer deriving (Show, Read, Eq) protos :: Parser [Proto] protos = many proto <* endOfInput proto :: Parser Proto proto = choice [ lineComment *> pure Empty , blockComment *> pure Empty , ProtoMessage <$> message , ProtoExtend <$> extend , ProtoEnum <$> enum , ProtoImport <$> import_ , ProtoPackage <$> package , ProtoOption <$> option , ";" *> pure Empty ] lineComment :: Parser ByteString lineComment = "//" *> ss (takeTill (inClass "\r\n")) blockComment :: Parser ByteString blockComment = ByteString.pack <$> ss ("/*" *> manyTill anyChar "*/") message :: Parser Message message = ss "message" *> (Message <$> ss identifier <*> ss messageBody) messageBody :: Parser [MessageInner] messageBody = wrapped (ss "{") (ss "}") $ ss $ many $ choice [ MessageField <$> messageField , MessageEnum <$> enum , NestedMessage <$> message , MessageExtend <$> extend ] messageField :: Parser Field messageField = Field <$> ss modifier <*> ss type_ <*> ss identifier <* ss "=" <*> ss integerLit <*> ss options <* ss ";" options :: Parser [Option] options = Parser.option [] $ wrapped (ss "[") (ss "]") $ ss optionBody `sepBy1` "," optionBody :: Parser Option optionBody = Option <$> ss (identifier `sepBy1` ".") <*> (ss "=" *> constant) modifier :: Parser Modifier modifier = choice ["required" *> pure Required, "optional" *> pure Optional, "repeated" *> pure Repeated] type_ :: Parser Type type_ = choice [ "double" *> pure TDouble , "float" *> pure TFloat , "int32" *> pure TInt32 , "int64" *> pure TInt64 , "uint32" *> pure TUInt32 , "uint64" *> pure TUInt64 , "sint32" *> pure TSInt32 , "sint64" *> pure TSInt64 , "fixed32" *> pure TFixed32 , "sfixed32" *> pure TSFixed32 , "sfixed64" *> pure TSFixed64 , "bool" *> pure TBool , "string" *> pure TString , "bytes" *> pure TBytes , TUser <$> userType ] userType :: Parser UserType userType = (FullyQualified <$> ("." *> ids)) <|> (InScope <$> ids) where ids = identifier `sepBy1` "." enum :: Parser Enum enum = Enum <$> (ss "enum" *> ss identifier) <*> wrapped (ss "{") (ss "}") (ss $ many enumField) enumField :: Parser EnumInner enumField = EnumField <$> (ss identifier <* ss "=") <*> (ss integerLit <* ss ";") identifier :: Parser ByteString identifier = ByteString.cons <$> satisfy (inClass "a-zA-Z_") <*> Parser.takeWhile (inClass "a-zA-Z0-9_") capitalIdentifier :: Parser ByteString capitalIdentifier = ByteString.cons <$> satisfy (inClass "A-Z") <*> Parser.takeWhile (inClass "a-zA-Z0-9_") extend :: Parser Extend extend = Extend <$> (ss "extend" *> ss userType) <*> ss messageBody import_ :: Parser ByteString import_ = ss "import" *> ss stringLit <* ss ";" package :: Parser ByteString package = ss "package" *> ss stringLit <* ss ";" option :: Parser Option option = Option <$> (ss "option" *> ss (identifier `sepBy` ".")) <*> (ss "=" *> ss constant <* ss ";") constant :: Parser Literal constant = choice [ Identifier <$> identifier , IntegerLit <$> integerLit , FloatLit <$> floatLit , StringLit <$> stringLit , BoolLit <$> boolLit ] stringLit :: Parser ByteString stringLit = mconcat <$> (("\"" *> many (insides '"') <* "\"") <|> ("\'" *> many (insides '\'') <* "\'")) where insides b = escapeHex <|> escapeChar <|> escapeOct <|> (ByteString.singleton <$> satisfy (notInClass (b : "\0\n"))) escapeChar :: Parser ByteString escapeChar = fmap fst $ match $ do char '\\' satisfy $ inClass "abdnrtv\\?'\"" escapeHex :: Parser ByteString escapeHex = fmap fst $ match $ do char '\\' satisfy $ inClass "xX" satisfy $ inClass "A-Fa-f0-9" Parser.option () $ satisfy (inClass "A-Fa-f0-9") *> pure () escapeOct :: Parser ByteString escapeOct = fmap fst $ match $ do char '\\' Parser.option "" "0" satisfy $ inClass "0-7" Parser.option () $ satisfy (inClass "0-7") *> pure () Parser.option () $ satisfy (inClass "0-7") *> pure () integerLit :: Parser Integer integerLit = readParse =<< Parser.takeWhile (inClass "0-9.+-") floatLit :: Parser Double floatLit = (=<<) (readParse . fst) $ match $ do many1 digit Parser.option "" $ do "." many1 digit Parser.option "" $ do "e" <|> "E" Parser.option "" $ "+" <|> "-" many1 digit hexLit :: Parser Integer hexLit = (=<<) (readParse . fst) $ match $ do "0x" <|> "0X" Parser.takeWhile (inClass "A-Fa-f0-9") boolLit :: Parser Bool boolLit = ("true" *> pure True) <|> ("false" *> pure False) readParse :: Read a => ByteString -> Parser a readParse s = case readMaybe $ ByteString.unpack s of Just res -> pure res Nothing -> fail "no read" ss :: Parser a -> Parser a ss p = p <* skipSpace wrapped :: Parser a -> Parser b -> Parser c -> Parser c wrapped begin end middle = begin *> middle <* end
intolerable/multiproto
src/Data/MultiProto/Protobuf/Parser.hs
bsd-3-clause
6,975
0
14
1,710
2,361
1,213
1,148
196
2
{-# Language TypeFamilies #-} module Data.Recons.Dict.Internal.TrieDictSkipMap where import Data.Monoid import qualified Data.Map as M import Data.Recons.Dict.TrieDictMap as T newtype TrieDictSkipKey k = TrieDictSkipKey { unwrap :: [Maybe k] } deriving (Eq,Show) instance Monoid (TrieDictSkipKey k) where mempty = TrieDictSkipKey [] mappend (TrieDictSkipKey s1) (TrieDictSkipKey s2) = TrieDictSkipKey (s1 <> s2) instance Functor TrieDictSkipKey where fmap f (TrieDictSkipKey q) = TrieDictSkipKey (fmap (fmap f) q) type TrieImpl k v = GTrieDictMap (TrieDictSkipKey k) v instance Ord k => TrieDictMapKey (TrieDictSkipKey k) where data GTrieDictMap (TrieDictSkipKey k) v = Nil | NodeA (Maybe v) (M.Map k (TrieImpl k v)) | NodeB (Maybe v) (TrieImpl k v) deriving (Eq,Show) empty = Nil lookup k trie = find (unwrap k) trie where find _ Nil = Nothing find (Just x:xs) (NodeA _ tries) = maybe Nothing (find xs) (M.lookup x tries) find (Nothing:_) (NodeA _ _) = Nothing find (_:xs) (NodeB _ trie) = find xs trie find [] (NodeA mv _) = mv find [] (NodeB mv _) = mv lookupPartial k t = find (unwrap k) t where find _ Nil = Nil find (Just x:xs) (NodeA _ mtries) = maybe Nil (find xs) (M.lookup x mtries) find (Nothing:_) (NodeA _ _) = Nil find (_:xs) (NodeB _ trie) = find xs trie find [] e = e toList trie = go mempty trie where go :: TrieDictSkipKey k -> TrieImpl k v -> [(TrieDictSkipKey k, v)] go _ Nil = [] go key (NodeA mv mtries) = r where r = maybe [] (\v -> [(key,v)]) mv <> foldMap (\(k,t) -> go (key <> keyA k) t) (M.toList mtries) go key (NodeB mv trie) = r where r = maybe [] (\v -> [(key,v)]) mv <> go (key <> keyB) trie keyA = TrieDictSkipKey . pure . pure keyB = (TrieDictSkipKey . pure) Nothing insertWith fn k v trie = ins (unwrap k) trie where ins [] Nil = NodeA (pure v) M.empty ins [] (NodeA mv mtries) = NodeA (Just $ maybe v (`fn` v) mv) mtries ins [] (NodeB mv trie) = NodeB (Just $ maybe v (`fn` v) mv) trie ins (Nothing:xs) Nil = NodeB Nothing (ins xs Nil) ins (Nothing:xs) (NodeA mv mtries) = NodeB mv (ins xs (unionsWith fn $ M.elems mtries)) ins (Nothing:xs) (NodeB mv trie) = NodeB mv (ins xs trie) ins (Just x:xs) Nil = NodeA Nothing (M.singleton x (ins xs Nil)) ins (Just x:xs) (NodeA mv mtries) = NodeA mv (M.alter (alt xs) x mtries) ins (Just _:xs) (NodeB mv trie) = NodeB mv (ins xs trie) alt xs = Just . maybe (ins xs empty) (ins xs) makeKey :: [k] -> TrieDictSkipKey k makeKey = TrieDictSkipKey . fmap pure
voidlizard/recons
src/Data/Recons/Dict/Internal/TrieDictSkipMap.hs
bsd-3-clause
2,852
0
17
867
1,325
682
643
54
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. ----------------------------------------------------------------- -- Auto-generated by regenClassifiers -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Duckling.Ranking.Classifiers.ZH (classifiers) where import Prelude import Duckling.Ranking.Types import qualified Data.HashMap.Strict as HashMap import Data.String classifiers :: Classifiers classifiers = HashMap.fromList [("<time> timezone", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("<time-of-day> am|pm", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 1}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("integer (numeric)", Classifier{okData = ClassData{prior = -0.5292593254548287, unseen = -3.8066624897703196, likelihoods = HashMap.fromList [("", 0.0)], n = 43}, koData = ClassData{prior = -0.8892620594862358, unseen = -3.4657359027997265, likelihoods = HashMap.fromList [("", 0.0)], n = 30}}), ("the day before yesterday", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("today", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("mm/dd", Classifier{okData = ClassData{prior = -1.6094379124341003, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -0.2231435513142097, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}}), ("absorption of , after named day", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("named-day", -0.6931471805599453)], n = 6}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("tonight", Classifier{okData = ClassData{prior = 0.0, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("month (grain)", Classifier{okData = ClassData{prior = -1.0296194171811581, unseen = -3.0910424533583156, likelihoods = HashMap.fromList [("", 0.0)], n = 20}, koData = ClassData{prior = -0.4418327522790392, unseen = -3.6375861597263857, likelihoods = HashMap.fromList [("", 0.0)], n = 36}}), ("<time-of-day> o'clock", Classifier{okData = ClassData{prior = -0.5108256237659907, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 6}, koData = ClassData{prior = -0.916290731874155, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)", -0.6931471805599453), ("hour", -0.6931471805599453)], n = 4}}), ("national day", Classifier{okData = ClassData{prior = 0.0, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [("", 0.0)], n = 6}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("hour (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("", 0.0)], n = 12}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("intersect", Classifier{okData = ClassData{prior = -0.4473122180436648, unseen = -4.553876891600541, likelihoods = HashMap.fromList [("children's day<part-of-day> <dim time>", -3.4446824936018943), ("year (numeric with year symbol)<named-month> <day-of-month>", -1.547562508716013), ("dayday", -1.978345424808467), ("hourhour", -2.9338568698359033), ("hourminute", -3.4446824936018943), ("absorption of , after named day<named-month> <day-of-month>", -1.978345424808467), ("dayminute", -3.4446824936018943), ("tonight<time-of-day> o'clock", -2.9338568698359033), ("<dim time> <part-of-day>relative minutes after|past <integer> (hour-of-day)", -3.4446824936018943), ("yearday", -1.547562508716013)], n = 39}, koData = ClassData{prior = -1.0198314108149953, unseen = -4.110873864173311, likelihoods = HashMap.fromList [("children's day<part-of-day> <dim time>", -2.1484344131667874), ("dayhour", -2.4849066497880004), ("daymonth", -2.1484344131667874), ("<dim time> <part-of-day><time-of-day> o'clock", -2.995732273553991), ("year (numeric with year symbol)named-month", -2.1484344131667874), ("hourhour", -2.995732273553991), ("hourminute", -2.995732273553991), ("absorption of , after named daynamed-month", -2.1484344131667874), ("yearmonth", -2.1484344131667874), ("dayminute", -2.995732273553991), ("<dim time> <part-of-day>relative minutes after|past <integer> (hour-of-day)", -2.995732273553991)], n = 22}}), ("year (grain)", Classifier{okData = ClassData{prior = -1.2809338454620642, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -0.325422400434628, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("", 0.0)], n = 13}}), ("last tuesday, last july", Classifier{okData = ClassData{prior = -1.3350010667323402, unseen = -3.332204510175204, likelihoods = HashMap.fromList [("day", -0.8979415932059586), ("named-day", -0.8979415932059586)], n = 10}, koData = ClassData{prior = -0.3053816495511819, unseen = -4.1588830833596715, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)", -1.0076405104623831), ("named-month", -3.4499875458315876), ("month (numeric with month symbol)", -2.3513752571634776), ("hour", -1.0076405104623831), ("month", -2.1972245773362196)], n = 28}}), ("next <cycle>", Classifier{okData = ClassData{prior = -0.7884573603642702, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("week", -1.540445040947149), ("month (grain)", -1.252762968495368), ("week (grain)", -1.540445040947149), ("month", -1.252762968495368)], n = 5}, koData = ClassData{prior = -0.6061358035703156, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("week", -0.8266785731844679), ("week (grain)", -0.8266785731844679)], n = 6}}), ("last year", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("this <day-of-week>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.295836866004329, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("named-day", -0.6931471805599453)], n = 12}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("yyyy-mm-dd", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("mm/dd/yyyy", Classifier{okData = ClassData{prior = 0.0, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("evening|night", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("yesterday", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("next year", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("hh:mm (time-of-day)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<integer> (latent time-of-day)", Classifier{okData = ClassData{prior = -1.540445040947149, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("integer (numeric)", -1.0296194171811581), ("integer (0..10)", -0.4418327522790392)], n = 12}, koData = ClassData{prior = -0.2411620568168881, unseen = -3.8501476017100584, likelihoods = HashMap.fromList [("integer (numeric)", -2.2192034840549946), ("integer (0..10)", -0.11506932978478723)], n = 44}}), ("nth <time> of <time>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("monthday", -0.7884573603642702), ("month (numeric with month symbol)ordinal (digits)named-day", -1.2992829841302609), ("named-monthordinal (digits)named-day", -1.2992829841302609)], n = 4}, koData = ClassData{prior = -infinity, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [], n = 0}}), ("named-month", Classifier{okData = ClassData{prior = -4.255961441879589e-2, unseen = -3.2188758248682006, likelihoods = HashMap.fromList [("", 0.0)], n = 23}, koData = ClassData{prior = -3.1780538303479458, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}}), ("month (numeric with month symbol)", Classifier{okData = ClassData{prior = -0.15415067982725836, unseen = -3.6635616461296463, likelihoods = HashMap.fromList [("integer (numeric)", -0.9985288301111273), ("integer (0..10)", -0.4595323293784402)], n = 36}, koData = ClassData{prior = -1.9459101490553135, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("integer (0..10)", -0.13353139262452263)], n = 6}}), ("week (grain)", Classifier{okData = ClassData{prior = -0.8754687373538999, unseen = -3.0910424533583156, likelihoods = HashMap.fromList [("", 0.0)], n = 20}, koData = ClassData{prior = -0.5389965007326869, unseen = -3.4011973816621555, likelihoods = HashMap.fromList [("", 0.0)], n = 28}}), ("valentine's day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("year (numeric with year symbol)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 13}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("now", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("numbers prefix with -, negative or minus", Classifier{okData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("integer (numeric)", 0.0)], n = 4}}), ("tomorrow", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("this year", Classifier{okData = ClassData{prior = 0.0, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [("", 0.0)], n = 1}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("afternoon", Classifier{okData = ClassData{prior = 0.0, unseen = -1.9459101490553135, likelihoods = HashMap.fromList [("", 0.0)], n = 5}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("this <cycle>", Classifier{okData = ClassData{prior = -0.8754687373538999, unseen = -3.2188758248682006, likelihoods = HashMap.fromList [("week", -0.9808292530117262), ("year (grain)", -2.0794415416798357), ("week (grain)", -0.9808292530117262), ("year", -2.0794415416798357)], n = 10}, koData = ClassData{prior = -0.5389965007326869, unseen = -3.4965075614664802, likelihoods = HashMap.fromList [("week", -0.7576857016975165), ("week (grain)", -0.7576857016975165)], n = 14}}), ("minute (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("", 0.0)], n = 12}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<dim time> <part-of-day>", Classifier{okData = ClassData{prior = 0.0, unseen = -3.9889840465642745, likelihoods = HashMap.fromList [("dayhour", -0.7514160886839211), ("national dayevening|night", -2.871679624884012), ("<named-month> <day-of-month>morning", -1.405342556090585), ("named-daymorning", -1.7730673362159024), ("children's dayafternoon", -2.871679624884012)], n = 24}, koData = ClassData{prior = -infinity, unseen = -1.791759469228055, likelihoods = HashMap.fromList [], n = 0}}), ("<part-of-day> <dim time>", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -3.5553480614894135, likelihoods = HashMap.fromList [("tonight<integer> (latent time-of-day)", -1.916922612182061), ("hourhour", -1.329135947279942), ("afternoonrelative minutes after|past <integer> (hour-of-day)", -1.916922612182061), ("hourminute", -1.7346010553881064), ("afternoonhh:mm (time-of-day)", -2.833213344056216), ("tonight<time-of-day> o'clock", -1.916922612182061)], n = 13}, koData = ClassData{prior = -0.6931471805599453, unseen = -3.5553480614894135, likelihoods = HashMap.fromList [("hourhour", -1.2237754316221157), ("afternoonrelative minutes after|past <integer> (hour-of-day)", -1.916922612182061), ("afternoon<time-of-day> o'clock", -1.916922612182061), ("hourminute", -1.916922612182061), ("afternoon<integer> (latent time-of-day)", -1.7346010553881064)], n = 13}}), ("<integer> <unit-of-duration>", Classifier{okData = ClassData{prior = -infinity, unseen = -2.833213344056216, likelihoods = HashMap.fromList [], n = 0}, koData = ClassData{prior = 0.0, unseen = -5.54907608489522, likelihoods = HashMap.fromList [("week", -2.9802280870180256), ("integer (0..10)month (grain)", -1.9075912847531766), ("integer (0..10)hour (grain)", -2.9802280870180256), ("second", -3.242592351485517), ("integer (0..10)day (grain)", -3.4657359027997265), ("integer (0..10)year (grain)", -3.7534179752515073), ("integer (numeric)year (grain)", -2.906120114864304), ("integer (0..10)second (grain)", -3.242592351485517), ("day", -3.4657359027997265), ("year", -2.600738465313122), ("integer (0..10)minute (grain)", -2.9802280870180256), ("hour", -2.9802280870180256), ("integer (0..10)week (grain)", -2.9802280870180256), ("month", -1.6133518117552368), ("integer (numeric)month (grain)", -2.906120114864304), ("minute", -2.9802280870180256)], n = 120}}), ("integer (11..19)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.639057329615259, likelihoods = HashMap.fromList [("integer (0..10)", 0.0)], n = 12}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<time-of-day> am|pm", Classifier{okData = ClassData{prior = -0.4700036292457356, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("hh:mm (time-of-day)", -1.252762968495368), ("<integer> (latent time-of-day)", -1.540445040947149), ("hour", -1.540445040947149), ("minute", -1.252762968495368)], n = 5}, koData = ClassData{prior = -0.9808292530117262, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)", -0.916290731874155), ("hour", -0.916290731874155)], n = 3}}), ("relative minutes after|past <integer> (hour-of-day)", Classifier{okData = ClassData{prior = -0.6931471805599453, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)integer (11..19)", -0.7884573603642702), ("hour", -0.7884573603642702)], n = 4}, koData = ClassData{prior = -0.6931471805599453, unseen = -2.4849066497880004, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)integer (0..10)", -0.7884573603642702), ("hour", -0.7884573603642702)], n = 4}}), ("army's day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("intersect by \",\"", Classifier{okData = ClassData{prior = -0.40546510810816444, unseen = -3.367295829986474, likelihoods = HashMap.fromList [("dayday", -0.7672551527136672), ("named-day<named-month> <day-of-month>", -0.7672551527136672)], n = 12}, koData = ClassData{prior = -1.0986122886681098, unseen = -2.833213344056216, likelihoods = HashMap.fromList [("named-daynamed-month", -0.8266785731844679), ("daymonth", -0.8266785731844679)], n = 6}}), ("named-day", Classifier{okData = ClassData{prior = 0.0, unseen = -4.406719247264253, likelihoods = HashMap.fromList [("", 0.0)], n = 80}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("second (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("", 0.0)], n = 9}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("the day after tomorrow", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("next <time>", Classifier{okData = ClassData{prior = -2.2512917986064953, unseen = -2.3978952727983707, likelihoods = HashMap.fromList [("day", -1.2039728043259361), ("named-day", -1.2039728043259361)], n = 2}, koData = ClassData{prior = -0.11122563511022437, unseen = -3.713572066704308, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)", -1.1239300966523995), ("month (numeric with month symbol)", -2.995732273553991), ("day", -2.0794415416798357), ("named-day", -2.0794415416798357), ("hour", -1.1239300966523995), ("month", -2.995732273553991)], n = 17}}), ("last <cycle>", Classifier{okData = ClassData{prior = -0.9555114450274363, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("week", -1.540445040947149), ("month (grain)", -1.252762968495368), ("week (grain)", -1.540445040947149), ("month", -1.252762968495368)], n = 5}, koData = ClassData{prior = -0.48550781578170077, unseen = -3.044522437723423, likelihoods = HashMap.fromList [("week", -0.7985076962177716), ("week (grain)", -0.7985076962177716)], n = 8}}), ("christmas", Classifier{okData = ClassData{prior = 0.0, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("new year's day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.6094379124341003, likelihoods = HashMap.fromList [("", 0.0)], n = 3}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("next n <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -4.07753744390572, likelihoods = HashMap.fromList [("week", -2.451005098112319), ("integer (0..10)month (grain)", -2.6741486494265287), ("integer (0..10)hour (grain)", -2.451005098112319), ("second", -2.6741486494265287), ("integer (0..10)day (grain)", -2.6741486494265287), ("integer (0..10)year (grain)", -3.367295829986474), ("integer (0..10)second (grain)", -2.6741486494265287), ("day", -2.6741486494265287), ("year", -3.367295829986474), ("integer (0..10)minute (grain)", -2.451005098112319), ("hour", -2.451005098112319), ("integer (0..10)week (grain)", -2.451005098112319), ("month", -2.6741486494265287), ("minute", -2.451005098112319)], n = 22}, koData = ClassData{prior = -infinity, unseen = -2.70805020110221, likelihoods = HashMap.fromList [], n = 0}}), ("children's day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.791759469228055, likelihoods = HashMap.fromList [("", 0.0)], n = 4}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("<named-month> <day-of-month>", Classifier{okData = ClassData{prior = 0.0, unseen = -4.770684624465665, likelihoods = HashMap.fromList [("month (numeric with month symbol)integer (11..19)", -2.5649493574615367), ("named-monthinteger (11..19)", -2.5649493574615367), ("named-monthinteger (numeric)", -3.6635616461296463), ("month (numeric with month symbol)integer (numeric)", -2.1231166051824975), ("month", -0.7368222440626069), ("month (numeric with month symbol)integer (0..10)", -2.1231166051824975), ("named-monthinteger (0..10)", -2.277267285009756)], n = 55}, koData = ClassData{prior = -infinity, unseen = -2.0794415416798357, likelihoods = HashMap.fromList [], n = 0}}), ("integer (0..10)", Classifier{okData = ClassData{prior = -0.5010216236693698, unseen = -4.8283137373023015, likelihoods = HashMap.fromList [("", 0.0)], n = 123}, koData = ClassData{prior = -0.9311793443679057, unseen = -4.406719247264253, likelihoods = HashMap.fromList [("", 0.0)], n = 80}}), ("last n <cycle>", Classifier{okData = ClassData{prior = 0.0, unseen = -4.61512051684126, likelihoods = HashMap.fromList [("week", -2.995732273553991), ("integer (0..10)month (grain)", -2.120263536200091), ("integer (0..10)hour (grain)", -2.4079456086518722), ("second", -2.659260036932778), ("integer (0..10)day (grain)", -2.995732273553991), ("integer (0..10)year (grain)", -3.506557897319982), ("integer (0..10)second (grain)", -2.659260036932778), ("day", -2.995732273553991), ("year", -3.506557897319982), ("integer (0..10)minute (grain)", -2.4079456086518722), ("hour", -2.4079456086518722), ("integer (0..10)week (grain)", -2.995732273553991), ("month", -2.120263536200091), ("minute", -2.4079456086518722)], n = 43}, koData = ClassData{prior = -infinity, unseen = -2.70805020110221, likelihoods = HashMap.fromList [], n = 0}}), ("this|next <day-of-week>", Classifier{okData = ClassData{prior = 0.0, unseen = -2.70805020110221, likelihoods = HashMap.fromList [("day", -0.6931471805599453), ("named-day", -0.6931471805599453)], n = 6}, koData = ClassData{prior = -infinity, unseen = -1.0986122886681098, likelihoods = HashMap.fromList [], n = 0}}), ("ordinal (digits)", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("integer (0..10)", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("morning", Classifier{okData = ClassData{prior = 0.0, unseen = -2.890371757896165, likelihoods = HashMap.fromList [("", 0.0)], n = 16}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("week-end", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("day (grain)", Classifier{okData = ClassData{prior = 0.0, unseen = -2.1972245773362196, likelihoods = HashMap.fromList [("", 0.0)], n = 7}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("labor day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("women's day", Classifier{okData = ClassData{prior = 0.0, unseen = -1.3862943611198906, likelihoods = HashMap.fromList [("", 0.0)], n = 2}, koData = ClassData{prior = -infinity, unseen = -0.6931471805599453, likelihoods = HashMap.fromList [], n = 0}}), ("this <time>", Classifier{okData = ClassData{prior = -0.35667494393873245, unseen = -3.5263605246161616, likelihoods = HashMap.fromList [("day", -0.9315582040049435), ("named-day", -0.9315582040049435), ("hour", -2.3978952727983707), ("week-end", -2.3978952727983707)], n = 14}, koData = ClassData{prior = -1.2039728043259361, unseen = -2.890371757896165, likelihoods = HashMap.fromList [("<integer> (latent time-of-day)", -0.8873031950009028), ("hour", -0.8873031950009028)], n = 6}})]
rfranek/duckling
Duckling/Ranking/Classifiers/ZH.hs
bsd-3-clause
43,739
0
15
21,119
8,334
5,180
3,154
739
1
module Module3.Task16 where data Odd = Odd Integer deriving (Eq, Show) instance Enum Odd where succ (Odd x) = Odd $ x + 2 pred (Odd x) = Odd $ x - 2 toEnum x = Odd $ toInteger x * 2 + 1 fromEnum (Odd x) = quot (fromInteger x - 1) 2 enumFrom = iterate succ enumFromThen (Odd x) (Odd y) = map Odd [x, y ..] enumFromTo (Odd x) (Odd y) = map Odd [x, x + 2 .. y] enumFromThenTo (Odd x) (Odd y) (Odd z) = map Odd [x , y .. z]
dstarcev/stepic-haskell
src/Module3/Task16.hs
bsd-3-clause
438
0
9
116
256
132
124
11
0
-- | DBus helpers for MCCtl. module MCCtl.DBus (dbusCall, dbusCallWith, Client, connectSystem, disconnect) where import DBus import DBus.Client import MCCtl.Config -- | Create a method call for MCCtl. dbusMeth :: MemberName -> [Variant] -> MethodCall dbusMeth member args = (methodCall dbusObj dbusIface member) { methodCallDestination = Just dbusBus, methodCallBody = args } -- | Connect to the system bus, make a DBus call to the MCCtl server, then -- disconnect from the bus. -- -- Use only for oneshot invocations; for anything else we should reuse the -- connection. dbusCall :: MemberName -> [Variant] -> IO MethodReturn dbusCall memb args = do client <- connectSystem res <- call_ client $ dbusMeth memb args disconnect client return res -- | Connect to the system bus, make a DBus call to the MCCtl server, then -- disconnect from the bus. -- -- Use only for oneshot invocations; for anything else we should reuse the -- connection. dbusCallWith :: Client -> MemberName -> [Variant] -> IO MethodReturn dbusCallWith client memb args = do res <- call_ client $ dbusMeth memb args return res
valderman/mcctl
src/MCCtl/DBus.hs
bsd-3-clause
1,134
0
9
217
228
122
106
18
1
module Graphics.Gloss.Juicy ( -- * Conversion from JuicyPixels' types to gloss' Picture fromDynamicImage , fromImageRGBA8 , fromImageRGB8 , fromImageY8 , fromImageYA8 , fromImageYCbCr8 -- * Loading a gloss Picture from a file through JuicyPixels , loadJuicy , loadJuicyJPG , loadJuicyPNG -- * From gloss, exported here for convenience , loadBMP ) where import Codec.Picture import Codec.Picture.Types import Graphics.Gloss.Data.Picture import Graphics.Gloss.Data.Bitmap import Data.Vector.Storable (unsafeToForeignPtr) -- | Tries to convert a 'DynamicImage' from JuicyPixels to a gloss 'Picture'. All formats except RGBF and YF should successfully -- yield a 'Picture'. fromDynamicImage :: DynamicImage -> Maybe Picture fromDynamicImage (ImageY8 img) = Just $ fromImageY8 img fromDynamicImage (ImageYA8 img) = Just $ fromImageYA8 img fromDynamicImage (ImageRGB8 img) = Just $ fromImageRGB8 img fromDynamicImage (ImageRGBA8 img) = Just $ fromImageRGBA8 img fromDynamicImage (ImageYCbCr8 img) = Just $ fromImageYCbCr8 img fromDynamicImage (ImageRGBF _) = Nothing fromDynamicImage (ImageYF _) = Nothing -- | O(N) conversion from 'PixelRGBA8' image to gloss 'Picture', where N is the number of pixels. fromImageRGBA8 :: Image PixelRGBA8 -> Picture fromImageRGBA8 (Image { imageWidth = w, imageHeight = h, imageData = id }) = bitmapOfForeignPtr w h (BitmapFormat TopToBottom PxRGBA) ptr True where (ptr, _, _) = unsafeToForeignPtr id {-# INLINE fromImageRGBA8 #-} -- | Creation of a gloss 'Picture' by promoting (through 'promoteImage') the 'PixelRGB8' image to 'PixelRGBA8' and calling 'fromImageRGBA8'. fromImageRGB8 :: Image PixelRGB8 -> Picture fromImageRGB8 = fromImageRGBA8 . promoteImage {-# INLINE fromImageRGB8 #-} -- | Creation of a gloss 'Picture' by promoting (through 'promoteImage') the 'PixelY8' image to 'PixelRGBA8' and calling 'fromImageRGBA8'. fromImageY8 :: Image Pixel8 -> Picture fromImageY8 = fromImageRGBA8 . promoteImage {-# INLINE fromImageY8 #-} -- | Creation of a gloss 'Picture' by promoting (through 'promoteImage') the 'PixelYA8' image to 'PixelRGBA8' and calling 'fromImageRGBA8'. fromImageYA8 :: Image PixelYA8 -> Picture fromImageYA8 = fromImageRGBA8 . promoteImage {-# INLINE fromImageYA8 #-} -- | Creation of a gloss 'Picture' by promoting (through 'promoteImage') the 'PixelYCbCr8' image to 'PixelRGBA8' and calling 'fromImageRGBA8'. fromImageYCbCr8 :: Image PixelYCbCr8 -> Picture fromImageYCbCr8 = fromImageRGB8 . convertImage {-# INLINE fromImageYCbCr8 #-} -- | Tries to load an image file into a Picture using 'readImage' from JuicyPixels. -- It means it'll try to successively read the content as an image in the following order, -- until it succeeds (or fails on all of them): jpeg, png, bmp, gif, hdr (the last two are not supported) -- This is handy when you don't know what format the image contained in the file is encoded with. -- If you know the format in advance, use 'loadBMP', 'loadJuicyJPG' or 'loadJuicyPNG' loadJuicy :: FilePath -> IO (Maybe Picture) loadJuicy = loadWith readImage {-# INLINE loadJuicy #-} loadJuicyJPG :: FilePath -> IO (Maybe Picture) loadJuicyJPG = loadWith readJpeg {-# INLINE loadJuicyJPG #-} loadJuicyPNG :: FilePath -> IO (Maybe Picture) loadJuicyPNG = loadWith readPng {-# INLINE loadJuicyPNG #-} loadWith :: (FilePath -> IO (Either String DynamicImage)) -> FilePath -> IO (Maybe Picture) loadWith reader fp = do eImg <- reader fp return $ either (const Nothing) fromDynamicImage eImg
alpmestan/gloss-juicy
Graphics/Gloss/Juicy.hs
bsd-3-clause
3,629
0
10
665
568
309
259
57
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} -- | Functions for IDEs. module Stack.IDE ( listPackages , listTargets ) where import qualified Data.Map as Map import qualified Data.Set as Set import qualified Data.Text as T import Stack.Config (getLocalPackages) import Stack.Package (findOrGenerateCabalFile) import Stack.Prelude import Stack.Types.Config import Stack.Types.Package import Stack.Types.PackageName -- | List the packages inside the current project. listPackages :: HasEnvConfig env => RIO env () listPackages = do -- TODO: Instead of setting up an entire EnvConfig only to look up the package directories, -- make do with a Config (and the Project inside) and use resolvePackageEntry to get -- the directory. packageDirs <- liftM (map lpvRoot . Map.elems . lpProject) getLocalPackages forM_ packageDirs $ \dir -> do cabalfp <- findOrGenerateCabalFile dir pkgName <- parsePackageNameFromFilePath cabalfp (logInfo . packageNameText) pkgName -- | List the targets in the current project. listTargets :: HasEnvConfig env => RIO env () listTargets = do rawLocals <- lpProject <$> getLocalPackages logInfo (T.intercalate "\n" (map renderPkgComponent (concatMap toNameAndComponent (Map.toList rawLocals)))) where toNameAndComponent (pkgName,view') = map (pkgName, ) (Set.toList (lpvComponents view'))
MichielDerhaeg/stack
src/Stack/IDE.hs
bsd-3-clause
1,714
0
16
470
306
168
138
37
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} module Llvm.Asm.Printer.LlvmPrint (module Llvm.Asm.Printer.LlvmPrint ,module Llvm.Asm.Printer.Common ) where import Llvm.Asm.Printer.Common import Llvm.Asm.Data import qualified Llvm.Asm.Printer.SharedEntityPrint as P import Llvm.Asm.Printer.SharedEntityPrint (integral) import Llvm.Util.Mapping (getValOrImplError) class AsmPrint a where toLlvm :: a -> Doc commaSepMaybe :: AsmPrint a => Maybe a -> Doc commaSepMaybe = maybe empty ((comma<+>) . toLlvm) maybeSepByEquals :: AsmPrint a => Maybe a -> Doc maybeSepByEquals = maybe empty ((<+>equals).toLlvm) instance AsmPrint a => AsmPrint (Maybe a) where toLlvm (Just x) = toLlvm x toLlvm Nothing = empty instance AsmPrint LabelId where toLlvm (LabelString s) = text s toLlvm (LabelNumber n) = integral n toLlvm (LabelDqNumber n) = doubleQuotes $ integral n toLlvm (LabelDqString s) = doubleQuotes $ text s instance AsmPrint PercentLabel where toLlvm (PercentLabel li) = char '%' <> (toLlvm li) instance AsmPrint TargetLabel where toLlvm (TargetLabel x) = text "label" <+> toLlvm x instance AsmPrint BlockLabel where toLlvm (ImplicitBlockLabel (f, l, c)) = text ";<label>:? ;" <+> parens ((text f) <> comma <+> (integer $ toInteger l) <> comma <+> (integer $ toInteger c)) toLlvm (ExplicitBlockLabel l) = toLlvm l <> char ':' instance AsmPrint ComplexConstant where toLlvm (Cstruct b ts) = let (start, end) = case b of Packed -> (char '<', char '>') Unpacked -> (empty, empty) in start <> braces (commaSepList $ fmap toLlvm ts) <> end toLlvm (Cvector ts) = char '<' <+> (commaSepList $ fmap toLlvm ts) <+> char '>' toLlvm (Carray ts) = brackets $ commaSepList $ fmap toLlvm ts instance AsmPrint IbinOp where toLlvm x = text $ getValOrImplError (ibinOpMap, "ibinOpMap") x instance AsmPrint FbinOp where toLlvm x = text $ getValOrImplError (fbinOpMap, "fbinOpMap") x instance AsmPrint (BinExpr Const) where toLlvm (Ie v) = toLlvm v toLlvm (Fe v) = toLlvm v instance AsmPrint (BinExpr Value) where toLlvm (Ie v) = toLlvm v toLlvm (Fe v) = toLlvm v instance AsmPrint (IbinExpr Const) where toLlvm (IbinExpr op cs t c1 c2) = toLlvm op <+> (hsep $ fmap toLlvm cs) <+> parens (toLlvm (Typed t c1) <> comma <+> toLlvm (Typed t c2)) instance AsmPrint (FbinExpr Const) where toLlvm (FbinExpr op cs t c1 c2) = toLlvm op <+> toLlvm cs <+> parens (toLlvm (Typed t c1) <> comma <+> toLlvm (Typed t c2)) instance AsmPrint (Conversion Const) where toLlvm (Conversion op tc t) = toLlvm op <+> parens (toLlvm tc <+> text "to" <+> toLlvm t) instance AsmPrint (GetElementPtr Const) where toLlvm (GetElementPtr b base indices) = text "getelementptr" <+> toLlvm b <+> parens (commaSepList ((toLlvm base):fmap toLlvm indices)) instance AsmPrint (Select Const) where toLlvm (Select cnd tc1 tc2) = text "select" <+> parens (commaSepList [toLlvm cnd, toLlvm tc1, toLlvm tc2]) instance AsmPrint (Icmp Const) where toLlvm (Icmp op t c1 c2) = text "icmp" <+> toLlvm op <+> parens (toLlvm (Typed t c1) <> comma <+> toLlvm (Typed t c2)) instance AsmPrint (Fcmp Const) where toLlvm (Fcmp op t c1 c2) = text "fcmp" <+> toLlvm op <+> parens (toLlvm (Typed t c1) <> comma <+> toLlvm (Typed t c2)) instance AsmPrint (ShuffleVector Const) where toLlvm (ShuffleVector tc1 tc2 mask) = text "shufflevector" <+> parens (commaSepList [toLlvm tc1, toLlvm tc2, toLlvm mask]) instance AsmPrint (ExtractValue Const) where toLlvm (ExtractValue tc indices) = text "extractvalue" <+> parens (commaSepList ((toLlvm tc):fmap integral indices)) instance AsmPrint (InsertValue Const) where toLlvm (InsertValue vect tc indices) = text "insertvalue" <+> parens (commaSepList ((toLlvm vect):(toLlvm tc):fmap integral indices)) instance AsmPrint (ExtractElement Const) where toLlvm (ExtractElement tc index) = text "extractelement" <+> parens (toLlvm tc <> comma <+> toLlvm index) instance AsmPrint (InsertElement Const) where toLlvm (InsertElement tc1 tc2 index) = text "insertelement" <+> parens (commaSepList [toLlvm tc1, toLlvm tc2, toLlvm index]) instance AsmPrint TrapFlag where toLlvm Nuw = text "nuw" toLlvm Nsw = text "nsw" toLlvm Exact = text "exact" instance AsmPrint Const where toLlvm x = case x of C_simple c -> toLlvm c C_complex a -> toLlvm a C_labelId l -> toLlvm l C_blockAddress g a -> text "blockaddress" <+> parens (toLlvm g <> comma <+> toLlvm a) C_binexp a -> toLlvm a C_conv a -> toLlvm a C_gep a -> toLlvm a C_select a -> toLlvm a C_icmp a -> toLlvm a C_fcmp a -> toLlvm a C_shufflevector a -> toLlvm a C_extractvalue a -> toLlvm a C_insertvalue a -> toLlvm a C_extractelement a -> toLlvm a C_insertelement a -> toLlvm a instance AsmPrint MdName where toLlvm (MdName s) = char '!'<> (text s) instance AsmPrint MdNode where toLlvm (MdNode s) = char '!' <> (integer $ fromIntegral s) instance AsmPrint MdRef where toLlvm x = case x of MdRefName n -> toLlvm n MdRefNode n -> toLlvm n instance AsmPrint MetaConst where toLlvm (McStruct c) = char '!' <> braces (commaSepList (fmap toLlvm c)) toLlvm (McString s) = char '!' <> (toLlvm s) toLlvm (McMdRef n) = toLlvm n toLlvm (McSsa s) = toLlvm s toLlvm (McSimple sc) = toLlvm sc instance AsmPrint MetaKindedConst where toLlvm x = case x of (MetaKindedConst mk mc) -> toLlvm mk <+> toLlvm mc UnmetaKindedNull -> text "null" instance AsmPrint (GetElementPtr Value) where toLlvm (GetElementPtr ib tv tcs) = text "getelementptr" <+> toLlvm ib <+> (commaSepList ((toLlvm tv):fmap toLlvm tcs)) instance AsmPrint (IbinExpr Value) where toLlvm (IbinExpr op cs t v1 v2) = hsep ((toLlvm op):(fmap toLlvm cs)++[toLlvm t, toLlvm v1 <> comma, toLlvm v2]) instance AsmPrint (FbinExpr Value) where toLlvm (FbinExpr op cs t v1 v2) = hsep [toLlvm op, toLlvm cs, toLlvm t, toLlvm v1 <> comma, toLlvm v2] instance AsmPrint (Icmp Value) where toLlvm (Icmp op t v1 v2) = hsep [text "icmp", toLlvm op, toLlvm t, toLlvm v1 <> comma, toLlvm v2] instance AsmPrint (Fcmp Value) where toLlvm (Fcmp op t v1 v2) = hsep [text "fcmp", toLlvm op, toLlvm t, toLlvm v1 <> comma, toLlvm v2] instance AsmPrint (Conversion Value) where toLlvm (Conversion op tv t) = hsep [toLlvm op, toLlvm tv, text "to", toLlvm t] instance AsmPrint (Select Value) where toLlvm (Select c t f) = hsep [text "select", toLlvm c <> comma, toLlvm t <> comma, toLlvm f] instance AsmPrint Expr where toLlvm (ExprGetElementPtr a) = toLlvm a toLlvm (ExprIcmp a) = toLlvm a toLlvm (ExprFcmp a) = toLlvm a toLlvm (ExprBinExpr a) = toLlvm a toLlvm (ExprConversion a) = toLlvm a toLlvm (ExprSelect a) = toLlvm a instance AsmPrint MemOp where toLlvm (Alloca ma t s a) = hsep [text "alloca", toLlvm ma, hcat [toLlvm t, commaSepMaybe s, commaSepMaybe a]] toLlvm (Load b ptr align noterm inv nonul) = hsep [text "load", toLlvm b, hcat [toLlvm ptr, commaSepMaybe align, commaSepMaybe noterm, commaSepMaybe inv, commaSepMaybe nonul]] toLlvm (LoadAtomic (Atomicity st ord) b ptr align) = hsep [text "load", text "atomic", toLlvm b, toLlvm ptr, toLlvm st, toLlvm ord] <> (commaSepMaybe align) toLlvm (Store b v addr align noterm) = hsep [text "store", toLlvm b, toLlvm v <> comma, toLlvm addr <> (commaSepMaybe align) <> (commaSepMaybe noterm)] toLlvm (StoreAtomic (Atomicity st ord) b v ptr align) = hsep [text "store", text "atomic", toLlvm b, toLlvm v <> comma, toLlvm ptr, toLlvm st, toLlvm ord] <> (commaSepMaybe align) toLlvm (Fence b order) = hsep [text "fence", toLlvm b, toLlvm order] toLlvm (CmpXchg wk v p c n st sord ford) = hsep [text "cmpxchg", toLlvm wk, toLlvm v, toLlvm p <> comma, toLlvm c <> comma, toLlvm n, toLlvm st, toLlvm sord, toLlvm ford] toLlvm (AtomicRmw v op p vl st ord) = hsep [text "atomicrmw", toLlvm v, toLlvm op, toLlvm p <> comma, toLlvm vl, toLlvm st, toLlvm ord] instance AsmPrint Value where toLlvm (Val_local i) = toLlvm i toLlvm (Val_const c) = toLlvm c instance AsmPrint v => AsmPrint (Typed v) where toLlvm (Typed t v) = toLlvm t <+> toLlvm v instance AsmPrint a => AsmPrint (Pointer a) where toLlvm (Pointer i) = toLlvm i instance AsmPrint FunName where toLlvm (FunNameGlobal s) = toLlvm s toLlvm (FunNameBitcast tv t) = text "bitcast" <> parens (toLlvm tv <+> text "to" <+> toLlvm t) toLlvm (FunNameInttoptr tv t) = text "inttoptr" <> parens (toLlvm tv <+> text "to" <+> toLlvm t) toLlvm FunName_null = text "null" toLlvm FunName_undef = text "null" instance AsmPrint CallSite where toLlvm (CallSiteFun cc ra rt ident params fa) = hsep [toLlvm cc, hsep $ fmap toLlvm ra, toLlvm rt, toLlvm ident, parens (commaSepList $ fmap toLlvm params), hsep $ fmap toLlvm fa] instance AsmPrint InlineAsmExp where toLlvm (InlineAsmExp t se as dia s1 s2 params fa) = hsep [toLlvm t, text "asm", toLlvm se, toLlvm as, toLlvm dia, toLlvm s1 <> comma, toLlvm s2, parens (commaSepList $ fmap toLlvm params), hsep $ fmap toLlvm fa] instance AsmPrint Clause where toLlvm (ClauseCatch tv) = text "catch" <+> toLlvm tv toLlvm (ClauseFilter tc) = text "filter" <+> toLlvm tc toLlvm (ClauseConversion c) = toLlvm c instance AsmPrint (Conversion GlobalOrLocalId) where toLlvm (Conversion op (Typed t g) dt) = toLlvm op <+> parens (hsep [toLlvm t, toLlvm g, text "to", toLlvm dt]) instance AsmPrint (ExtractElement Value) where toLlvm (ExtractElement tv1 tv2) = text "extractelement" <+> (commaSepList [toLlvm tv1, toLlvm tv2]) instance AsmPrint (InsertElement Value) where toLlvm (InsertElement vect tv idx) = text "insertelement" <+> (commaSepList [toLlvm vect, toLlvm tv, toLlvm idx]) instance AsmPrint (ShuffleVector Value) where toLlvm (ShuffleVector vect1 vect2 mask) = text "shufflevector" <+> (commaSepList [toLlvm vect1, toLlvm vect2, toLlvm mask]) instance AsmPrint (ExtractValue Value) where toLlvm (ExtractValue tv idxs) = text "extractvalue" <+> (commaSepList ((toLlvm tv):(fmap integral idxs))) instance AsmPrint (InsertValue Value) where toLlvm (InsertValue vect tv idxs) = text "insertvalue" <+> (commaSepList ((toLlvm vect):(toLlvm tv):(fmap integral idxs))) instance AsmPrint Rhs where toLlvm (RhsMemOp a) = toLlvm a toLlvm (RhsExpr a) = toLlvm a toLlvm (RhsCall tailc callSite) = hsep [toLlvm tailc, text "call", toLlvm callSite] toLlvm (RhsInlineAsm callSite) = hsep [text "call", toLlvm callSite] toLlvm (RhsExtractElement a) = toLlvm a toLlvm (RhsInsertElement a) = toLlvm a toLlvm (RhsShuffleVector a) = toLlvm a toLlvm (RhsExtractValue a) = toLlvm a toLlvm (RhsInsertValue a) = toLlvm a toLlvm (RhsVaArg (VaArg tv t)) = hsep [text "va_arg", toLlvm tv <> comma, toLlvm t] toLlvm (RhsLandingPad (LandingPad rt pt tgl b clause)) = hsep ([text "landingpad", toLlvm rt, text "personality", toLlvm pt, toLlvm tgl, toLlvm b] ++ (fmap toLlvm clause)) instance AsmPrint ActualParam where toLlvm x = case x of ActualParamData t att1 v -> hsep [toLlvm t, hsep $ fmap toLlvm att1, toLlvm v] ActualParamLabel t att1 v -> hsep [toLlvm t, hsep $ fmap toLlvm att1, toLlvm v] ActualParamMeta mc -> toLlvm mc instance AsmPrint Dbg where toLlvm (Dbg mv meta) = toLlvm mv <+> toLlvm meta instance AsmPrint PhiInst where toLlvm (PhiInst lhs t pairs) = hsep [maybe empty ((<+> equals) . toLlvm) lhs, text "phi" , toLlvm t, commaSepList $ fmap tvToLLvm pairs] where tvToLLvm (h1,h2) = brackets (toLlvm h1 <> comma <+> toLlvm h2) instance AsmPrint ComputingInst where toLlvm (ComputingInst lhs rhs) = maybe empty ((<+> equals) . toLlvm) lhs <+> toLlvm rhs instance AsmPrint TerminatorInst where toLlvm RetVoid = text "ret" <+> text "void" toLlvm (Return x) = text "ret" <+> (commaSepList $ fmap toLlvm x) toLlvm (Br a) = text "br" <+> toLlvm a toLlvm (Cbr v t f) = hsep [text "br", text "i1", toLlvm v <> comma, toLlvm t <> comma, toLlvm f] toLlvm (IndirectBr v l) = hsep [text "indirectbr", toLlvm v <> comma, brackets (commaSepList $ fmap toLlvm l)] toLlvm (Switch v d tbl) = hsep [text "switch", toLlvm v <> comma, toLlvm d , brackets (hsep $ fmap (\(p1,p2) -> toLlvm p1 <> comma <+> toLlvm p2) tbl)] toLlvm (Invoke lhs callSite toL unwindL) = hsep [maybe empty ((<+> equals) . toLlvm) lhs, text "invoke", toLlvm callSite, text "to" , toLlvm toL, text "unwind", toLlvm unwindL] toLlvm (InvokeInlineAsm lhs callSite toL unwindL) = hsep [maybe empty ((<+> equals) . toLlvm) lhs, text "invoke", toLlvm callSite, text "to" , toLlvm toL, text "unwind", toLlvm unwindL] toLlvm Unreachable = text "unreachable" toLlvm (Resume a) = text "resume" <+> toLlvm a instance AsmPrint PhiInstWithDbg where toLlvm (PhiInstWithDbg ins dbgs) = commaSepList ((toLlvm ins):fmap toLlvm dbgs) instance AsmPrint TerminatorInstWithDbg where toLlvm (TerminatorInstWithDbg ins dbgs) = commaSepList ((toLlvm ins):fmap toLlvm dbgs) instance AsmPrint ComputingInstWithDbg where toLlvm ci = case ci of ComputingInstWithDbg ins dbgs -> commaSepList ((toLlvm ins):fmap toLlvm dbgs) ComputingInstWithComment s -> char ';' <+> text s instance AsmPrint Aliasee where toLlvm (Aliasee tv) = toLlvm tv toLlvm (AliaseeConversion c) = toLlvm c toLlvm (AliaseeGetElementPtr a) = toLlvm a instance AsmPrint FunctionPrototype where toLlvm (FunctionPrototype fhLinkage fhVisibility fhDllStorageClass fhCCoonc fhAttr fhRetType fhName fhParams fnd fhAttr1 fhSection fhcmd fhAlign fhGc fhPrefix fhPrologue) = hsep [toLlvm fhLinkage, toLlvm fhVisibility, toLlvm fhDllStorageClass, toLlvm fhCCoonc, hsep $ fmap toLlvm fhAttr , toLlvm fhRetType, toLlvm fhName, toLlvm fhParams, toLlvm fnd, hsep $ fmap toLlvm fhAttr1 , toLlvm fhSection, toLlvm fhcmd, toLlvm fhAlign, toLlvm fhGc, toLlvm fhPrefix, toLlvm fhPrologue] instance AsmPrint Block where toLlvm (Block lbl phis ins end) = toLlvm lbl $$ (nest 2 ((vcat $ fmap toLlvm phis) $$ (vcat $ fmap toLlvm ins) $$ toLlvm end)) instance AsmPrint Toplevel where toLlvm (ToplevelTriple (TlTriple s)) = hsep [text "target", text "triple", equals, toLlvm s] toLlvm (ToplevelDataLayout (TlDataLayout s)) = hsep [text "target", text "datalayout", equals, toLlvm s] toLlvm (ToplevelAlias (TlAlias lhs vis dll tlm naddr link aliasee)) = hsep [toLlvm lhs, equals, toLlvm vis, toLlvm dll, toLlvm tlm, toLlvm naddr, text "alias", toLlvm link, toLlvm aliasee] toLlvm (ToplevelUnamedMd smd) = toLlvm smd toLlvm (ToplevelNamedMd (TlNamedMd mv nds)) = char '!' <> text mv <+> equals <+> char '!'<>(braces (commaSepList $ fmap toLlvm nds)) toLlvm (ToplevelDeclare (TlDeclare fproto)) = text "declare" <+> toLlvm fproto toLlvm (ToplevelDefine (TlDefine fproto blocks)) = text "define" <+> toLlvm fproto <+> text "{" $$ (fcat $ fmap toLlvm blocks) $$ text "}" toLlvm (ToplevelGlobal (TlGlobal lhs linkage vis dllStor threadLoc un addrspace externali gty ty const0 section comdat align)) = hsep [maybeSepByEquals lhs, toLlvm linkage, toLlvm vis, toLlvm dllStor, toLlvm threadLoc, toLlvm un , toLlvm addrspace, toLlvm externali, toLlvm gty, toLlvm ty, toLlvm const0] <> (hcat [commaSepMaybe section, commaSepMaybe comdat, commaSepMaybe align]) toLlvm (ToplevelTypeDef (TlTypeDef n t)) = toLlvm n <+> equals <+> text "type" <+> toLlvm t toLlvm (ToplevelDepLibs (TlDepLibs l)) = text "deplibs" <+> equals <+> brackets (commaSepList $ fmap toLlvm l) toLlvm (ToplevelUnamedType (TlUnamedType x t)) = text "type" <+> toLlvm t <+> text "; " <+> (integral x) toLlvm (ToplevelModuleAsm (TlModuleAsm qs)) = text "module asm" <+> toLlvm qs toLlvm (ToplevelAttribute (TlAttribute n l)) = hsep [text "attributes", char '#' <> (integral n), equals, braces (hsep $ fmap toLlvm l)] toLlvm (ToplevelComdat (TlComdat l c)) = hsep [toLlvm l, equals, text "comdat", toLlvm c] toLlvm (ToplevelComment s) = foldl (\p e -> p $+$ (char ';' <+> text e)) empty s instance AsmPrint TlUnamedMd where toLlvm (TlUnamedMd lhs rhs) = char '!' <> (integer $ fromIntegral lhs) <+> equals <+> toLlvm rhs instance AsmPrint FormalParam where toLlvm x = case x of (FormalParamData t att1 id) -> (toLlvm t) <+> (hsep $ fmap toLlvm att1) <+> (toLlvm id) (FormalParamMeta e lv) -> toLlvm e <+> toLlvm lv instance AsmPrint FormalParamList where toLlvm (FormalParamList params var) = -- atts) = parens (commaSepNonEmpty ((fmap toLlvm params) ++ [maybe empty toLlvm var])) -- <+> (hsep $ fmap toLlvm atts) instance AsmPrint TypeParamList where toLlvm (TypeParamList params b) = parens (commaSepNonEmpty ((fmap toLlvm params) ++ [maybe empty toLlvm b])) instance AsmPrint TypePrimitive where toLlvm a = case a of TpI i -> text "i" <> integral i TpF f -> text "f" <> integral f TpV v -> text "v" <> integral v TpHalf -> text "half" TpFloat -> text "float" TpDouble -> text "double" TpFp128 -> text "fp128" TpX86Fp80 -> text "x86_fp80" TpPpcFp128 -> text "ppc_fp128" TpX86Mmx -> text "x86_mmx" TpLabel -> text "label" TpNull -> text "null" instance AsmPrint MetaKind where toLlvm a = case a of Mtype e -> toLlvm e Mmetadata -> text "metadata" instance AsmPrint Type where toLlvm a = case a of Tprimitive tp -> toLlvm tp Tvoid -> text "void" Topaque -> text "opaque" Tname s -> char '%' <> text s TquoteName s -> char '%'<> (doubleQuotes $ text s) Tno i -> char '%'<> integral i Tarray i t -> brackets (integral i <+> char 'x' <+> toLlvm t) Tvector i t -> char '<' <> integral i <+> char 'x' <+> toLlvm t <> char '>' Tstruct b ts -> let (start, end) = case b of Packed -> (char '<', char '>') Unpacked -> (empty, empty) in start <> braces (hsep $ punctuate comma $ fmap toLlvm ts) <> end Tpointer t addr -> toLlvm t <+> toLlvm addr <> text "*" Tfunction t fp atts -> toLlvm t <+> toLlvm fp <+> (hsep $ punctuate comma $ fmap toLlvm atts) instance AsmPrint AddrSpace where toLlvm (AddrSpace n) = text "addrspace" <+> (parens $ integral n) toLlvm AddrSpaceUnspecified = empty instance AsmPrint ConvertOp where toLlvm x = text $ getValOrImplError (convertOpMap, "convertOpMap") x instance AsmPrint TypedConstOrNull where toLlvm (TypedConst tc) = toLlvm tc toLlvm UntypedNull = text "null" instance AsmPrint Module where toLlvm (Module tops) = vcat $ fmap toLlvm tops instance AsmPrint Prefix where toLlvm (Prefix n) = text "prefix" <+> toLlvm n instance AsmPrint Prologue where toLlvm (Prologue n) = text "prologue" <+> toLlvm n instance AsmPrint IcmpOp where toLlvm = P.print instance AsmPrint FcmpOp where toLlvm = P.print instance AsmPrint Linkage where toLlvm = P.print instance AsmPrint CallConv where toLlvm = P.print instance AsmPrint Visibility where toLlvm = P.print instance AsmPrint DllStorageClass where toLlvm = P.print instance AsmPrint ThreadLocalStorage where toLlvm = P.print instance AsmPrint RetAttr where toLlvm = P.print instance AsmPrint CallFunAttr where toLlvm = P.print instance AsmPrint ParamAttr where toLlvm = P.print instance AsmPrint FunAttr where toLlvm = P.print instance AsmPrint SelectionKind where toLlvm = P.print instance AsmPrint AddrNaming where toLlvm = P.print instance AsmPrint DqString where toLlvm = P.print instance AsmPrint Section where toLlvm = P.print instance AsmPrint AlignInByte where toLlvm = P.print instance AsmPrint Gc where toLlvm = P.print instance AsmPrint GlobalType where toLlvm = P.print instance AsmPrint GlobalOrLocalId where toLlvm = P.print instance AsmPrint LocalId where toLlvm = P.print instance AsmPrint GlobalId where toLlvm = P.print instance AsmPrint SimpleConstant where toLlvm = P.print instance AsmPrint AtomicMemoryOrdering where toLlvm = P.print instance AsmPrint AtomicOp where toLlvm = P.print instance AsmPrint Fparam where toLlvm = P.print instance AsmPrint VarArgParam where toLlvm = P.print instance AsmPrint InAllocaAttr where toLlvm = P.print instance AsmPrint Volatile where toLlvm = P.print instance AsmPrint Weak where toLlvm = P.print instance AsmPrint SingleThread where toLlvm = P.print instance AsmPrint InBounds where toLlvm = P.print instance (P.Print a, AsmPrint a) => AsmPrint (IsOrIsNot a) where toLlvm = P.print instance AsmPrint Nontemporal where toLlvm = P.print instance AsmPrint InvariantLoad where toLlvm = P.print instance AsmPrint Nonnull where toLlvm = P.print instance AsmPrint TailCall where toLlvm = P.print instance AsmPrint DollarId where toLlvm = P.print instance AsmPrint Comdat where toLlvm = P.print instance AsmPrint FastMathFlag where toLlvm = P.print instance AsmPrint FastMathFlags where toLlvm = P.print instance AsmPrint ExternallyInitialized where toLlvm = P.print instance AsmPrint AsmDialect where toLlvm = P.print instance AsmPrint Endianness where toLlvm = P.print instance AsmPrint LayoutAddrSpace where toLlvm = P.print instance AsmPrint SizeInBit where toLlvm = P.print instance AsmPrint AlignInBit where toLlvm = P.print instance AsmPrint StackAlign where toLlvm = P.print instance AsmPrint Mangling where toLlvm = P.print instance AsmPrint AlignMetrics where toLlvm = P.print instance AsmPrint LayoutSpec where toLlvm = P.print instance AsmPrint DataLayout where toLlvm = P.print instance AsmPrint SideEffect where toLlvm = P.print instance AsmPrint AlignStack where toLlvm = P.print instance AsmPrint Cleanup where toLlvm = P.print instance AsmPrint TargetTriple where toLlvm = P.print
mlite/hLLVM
src/Llvm/Asm/Printer/LlvmPrint.hs
bsd-3-clause
22,650
0
17
5,182
8,657
4,243
4,414
464
1
{-# OPTIONS_GHC -Wall #-} {-# OPTIONS_GHC -Wno-incomplete-patterns #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DuplicateRecordFields #-} module Punter.Longest where import qualified Data.Aeson as J import Data.List (sortBy) import Data.Ord import Data.HashMap.Lazy (HashMap) import qualified Data.HashMap.Lazy as HashMap import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import qualified Data.Set as Set import GHC.Generics import qualified CommonState as CS import qualified Protocol as P import Punter import NormTypes import Dijkstra import qualified UnionFind as UF import qualified ScoreTable as ScoreTable data Punter = Punter { setupInfo :: P.Setup , scoreTable :: ScoreTable.ScoreTable , movePool :: CS.MovePool , targets :: [(P.SiteId, P.SiteId)] } deriving (Generic) instance J.ToJSON Punter instance J.FromJSON Punter instance Punter.IsPunter Punter where setup s = P.ReadyOn { P.ready = P.setupPunter s , P.state = Just $ Punter { setupInfo = s , scoreTable = sc , movePool = CS.empty m , targets = map fst $ sortBy (flip (comparing snd)) [((mine,site),w) | (mine,sites) <- IntMap.toList sc, (site,w) <- IntMap.toList sites] } , P.futures = Nothing } where m = P.map s sc = ScoreTable.mkScoreTable m applyMoves (P.Moves moves) p1@Punter{ movePool = movePool1 } = p1 { movePool = CS.applyMoves moves movePool1 } chooseMoveSimple = undefined chooseMove p@Punter{ setupInfo = si, movePool = pool, targets = tgs } | Set.null ars = P.MyMove (P.MvPass punterId) (Just p) | Just r <- mr, (s,t) <- deNRiver r = P.MyMove (P.MvClaim punterId s t) (Just p{ targets = tgs2 }) | otherwise = P.MyMove (P.MvPass punterId) (Just p) where punterId = P.setupPunter si siteClasses1 = CS.reachabilityOf pool punterId ars = CS.unclaimedRivers pool mrs = CS.riversOf pool punterId (mr, tgs2) = f tgs f :: [(P.SiteId,P.SiteId)] -> (Maybe NRiver, [(P.SiteId,P.SiteId)]) f [] = (Nothing, []) f xxs@((mine,site) : xs) | not (site `HashMap.member` stree) = f xs | not (r `Set.member` ars) = f xs | otherwise = (Just r, xxs) where mineRepr = UF.getRepr siteClasses1 mine stree = spanningTrees IntMap.! mine r = loop site where loop site' = case stree HashMap.! site' of (_, Nothing) -> undefined (_, Just (parentSite, r2)) -> if UF.getRepr siteClasses1 parentSite == mineRepr then r2 else loop parentSite spanningTrees :: IntMap (HashMap P.SiteId (Int, Maybe (P.SiteId, NRiver))) spanningTrees = IntMap.fromList [(mine, dijkstra g [mine]) | mine <- P.mines (P.map si)] g :: HashMap P.SiteId [(P.SiteId, Int, NRiver)] g = HashMap.fromListWith (++) $ [e | r <- Set.toList ars, let (s,t) = deNRiver r, e <- [(s, [(t,1,r)]), (t, [(s,1,r)])]] ++ [e | r <- Set.toList mrs, let (s,t) = deNRiver r, e <- [(s, [(t,0,r)]), (t, [(s,0,r)])]]
nobsun/icfpc2017
hs/src/Punter/Longest.hs
bsd-3-clause
3,209
0
18
880
1,214
679
535
78
0
module RamerDouglasPeuckerParts ( Range, Stack, Point, All(..), findFarthestPoints, initStack, recurProcess, myfst, mysnd, trd, getRightSliceFromStack, optimizing, distFunc ) where import Data.Maybe import Data.List import Control.Monad ( void ) import GHC.Int (Int32) type Range = [Int] type Stack = [Range] type Point = (Int32, Int32) type Direction = (Bool, Bool) up = (True, True) down = (False, False) left = (True, False) right = (False, True) hori = True verti = False data All = All { finalContours :: [Point], stack :: Stack } deriving Show getFinalContours :: All -> [Point] getFinalContours (All fc s) = fc getStack :: All -> Stack getStack (All fc s) = s getRightSliceFromStack :: All -> Range getRightSliceFromStack all = last (getStack all) replaceStack :: All -> Stack -> All replaceStack (All fc s) newStack = (All fc newStack) pushSlice :: Range -> Stack -> Stack pushSlice slice stack = slice : stack readPt :: [Point] -> Int -> Point readPt srcContours pos = srcContours !! pos readDstPt :: [Point] -> Int -> Point readDstPt dstContours pos = dstContours !! pos writePt :: [Point] -> Point -> [Point] writePt fc point = fc ++ [point] findFarthestPoints :: [Point] -> Int -> Double -> Double -> Double -> Range -> Int -> Int -> Point -> (Range, Point, Bool) findFarthestPoints srcContours iters dist max_dist epsi right_slice count pos start_pt | iters == 0 = (right_slice, start_pt, (max_dist <= epsi)) | otherwise = findFarthestPoints srcContours (iters - 1) dist (fst nestedFunc) epsi (snd nestedFunc) count cntPos (readPt srcContours cntPos) where cntPos = cntPosFunc pos right_slice count nestedFunc = findFarthestPointsSecond srcContours count 1 (readPt srcContours 1) max_dist start_pt right_slice cntPosFunc :: Int -> Range -> Int -> Int cntPosFunc pos right_slice count = (pos + (head right_slice)) `mod` count findFarthestPointsSecond :: [Point] -> Int -> Int -> Point -> Double -> Point -> Range -> (Double, Range) findFarthestPointsSecond srcContours count j pt max_dist start_pt right_slice | count == j = (max_dist, right_slice) | otherwise = findFarthestPointsSecond srcContours count (j + 1) (readPt srcContours (j + 1)) (fst dist_slice) start_pt (snd dist_slice) where dist_slice = dist_sliceFunc j pt max_dist right_slice start_pt dist_sliceFunc :: Int -> Point -> Double -> Range -> Point -> (Double, Range) dist_sliceFunc j pt max_dist right_slice start_pt | (distFunc pt start_pt) > max_dist = ((distFunc pt start_pt), (changeFirstValue right_slice j)) | otherwise = (max_dist, right_slice) distFunc :: Point -> Point -> Double distFunc pt start_pt = fromIntegral (dx * dx + dy * dy) where dx = (fst pt) - (fst start_pt) dy = (snd pt) - (snd start_pt) changeFirstValue :: [Int] -> Int -> [Int] changeFirstValue (x : xs) n = n : xs changeSecondValue :: [Int] -> Int -> [Int] changeSecondValue xs n = changeSecondValue' xs n [] changeSecondValue' :: [Int] -> Int -> [Int] -> [Int] changeSecondValue' [x] n acc = acc ++ [n] changeSecondValue' (x : xs) n acc = changeSecondValue' xs n (acc ++ [x]) initStack :: [Point] -> Range -> Range -> Point -> Bool -> Int -> All -> All initStack srcContours right_slice slice start_pt le_eps count (All dstC stck) | le_eps == True = All (writePt [] start_pt) [] | otherwise = All [] (pushingInStack mixingFunctions) where mixingFunctions = listfy (mixTwoFunctions right_slice slice (fromJust (elemIndex start_pt srcContours)) count) pushingInStack :: [Range] -> Stack pushingInStack xs = foldl (\acc x -> x : acc) [] xs listfy :: (Range, Range) -> [Range] listfy (range1, range2) = [range1, range2] mixTwoFunctions :: Range -> Range -> Int -> Int -> (Range, Range) mixTwoFunctions right_slice slice pos count = (final_right_slice, final_slice) where final_right_slice = snd rightSliceMC final_slice = fst rightSliceMC rightSliceMC = rightSliceModCount currentRightSlice currentSlice count currentRightSlice = fst posMC currentSlice = snd posMC posMC = posModCount right_slice slice pos count posModCount :: Range -> Range -> Int -> Int -> (Range, Range) posModCount right_slice slice pos count = ((changeSecondValue right_slice (pos `mod` count)), (changeFirstValue slice (pos `mod` count))) rightSliceModCount :: Range -> Range -> Int -> (Range, Range) rightSliceModCount right_slice slice count = ((changeSecondValue slice ecuation), (changeFirstValue right_slice ecuation)) where ecuation = ((head right_slice) + (head slice)) `mod` count myfst :: (a, b, c) -> a myfst (x, _, _) = x mysnd :: (a, b, c) -> b mysnd (_, x, _) = x trd :: (a, b, c) -> c trd (_, _, x) = x recurProcess :: All -> [Point] -> Double -> Range -> Int -> [Point] recurProcess (All fC []) srcContours epsi right_slice count = fC recurProcess all srcContours epsi right_slice count |le_eps == True && new_right_slice == [-1, -1] = recurProcess (All (getFinalContours all) (tail crrntStck)) srcContours epsi right_slice count |le_eps == True = recurProcess (All (writePt (getFinalContours all) new_start_pt) crrntStck) srcContours epsi new_right_slice count |otherwise = recurProcess (All (getFinalContours all) (pushSlice last_slice (pushSlice last_right_slice crrntStck))) srcContours epsi last_right_slice count where slice = head (getStack all) crrntStck = tail (getStack all) end_pt = srcContours !! (last slice) pos = head slice start_pt = srcContours !! pos recuFunc = recursiveFunc all srcContours epsi slice right_slice start_pt end_pt (addSafePos pos count) count new_start_pt = myfst recuFunc le_eps = mysnd recuFunc new_right_slice = trd recuFunc last_right_slice = changeSecondValue new_right_slice (last slice) last_slice = changeSecondValue slice (head new_right_slice) recursiveFunc :: All -> [Point] -> Double -> Range -> Range -> Point -> Point -> Int -> Int -> (Point, Bool, Range) recursiveFunc all srcContours epsi slice right_slice start_pt end_pt pos count | dx == 0 && dy == 0 = (srcContours !! (head slice), True, [-1, -1]) | pos /= last slice = (start_pt, le_eps, (fst range_dist)) | otherwise = (srcContours !! (head slice), True, right_slice) where dx = dxFunc end_pt start_pt dy = dyFunc end_pt start_pt max_dist = 0 range_dist = secondRecursiveFunc srcContours count dx dy max_dist pos slice right_slice start_pt newDis = snd range_dist le_eps = fromIntegral (newDis * newDis) <= epsi * fromIntegral (dx * dx + dy * dy) dxFunc :: Point -> Point -> Int32 dxFunc end_pt start_pt = (fst end_pt) - (fst start_pt) dyFunc :: Point -> Point -> Int32 dyFunc end_pt start_pt = (snd end_pt) - (snd start_pt) secondRecursiveFunc :: [Point] -> Int -> Int32 -> Int32 -> Int -> Int -> Range -> Range -> Point -> (Range, Int) secondRecursiveFunc srcContours count dx dy max_dist pos slice right_slice start_pt | pos == (last slice) = (right_slice, max_dist) | pos /= (last slice) && ((fromIntegral dist) > max_dist) = secondRecursiveFunc srcContours count dx dy (fromIntegral dist) (addSafePos pos count) slice new_right_slice start_pt | otherwise = secondRecursiveFunc srcContours count dx dy max_dist (addSafePos pos count) slice right_slice start_pt where new_right_slice = changeFirstValue right_slice ((pos + count - 1) `mod` count) pt = readPt srcContours pos dist = abs (((snd pt) - (snd start_pt)) * dx - ((fst pt) - (fst start_pt)) * dy) addSafePos :: Int -> Int -> Int addSafePos pos count | (pos + 1) >= count = 0 | otherwise = pos + 1 lessSafePos :: Int -> Int -> Int lessSafePos pos count | (pos - 1) < 0 = count - 1 | otherwise = pos - 1 last_stage :: Int -> Double -> Int -> Int -> Int -> Point -> Int -> Point -> [Point] -> [Point] last_stage i epsi count new_count pos start_pt wpos pt dstContours | i == count || new_count <= 2 = dstContours | otherwise = last_stage (l_s_f_fst !! 0) epsi count (l_s_f_fst !! 1) (addSafePos (l_s_f_fst !! 3) count) (l_s_f_trd !! 0) (l_s_f_fst !! 2) (l_s_f_trd !! 1) l_s_f_snd where end_pt = readDstPt dstContours pos dx = dxFunc end_pt start_pt dy = dyFunc end_pt start_pt dist = abs (((fst pt) - (fst start_pt)) * dy - ((snd pt) - (snd start_pt)) * dx) successive_inner_product = (((fst pt) - (fst start_pt)) * ((fst end_pt) - (fst pt)) + ((snd pt) - (snd start_pt)) * ((snd end_pt) - (snd pt))) l_s_f = last_stage_decision (fromIntegral dist) successive_inner_product epsi dx dy i count wpos pos new_count start_pt end_pt pt dstContours l_s_f_fst = myfst l_s_f l_s_f_snd = mysnd l_s_f l_s_f_trd = trd l_s_f last_stage_decision :: Int -> Int32 -> Double -> Int32 -> Int32 -> Int -> Int -> Int -> Int -> Int -> Point -> Point -> Point -> [Point] -> ([Int], [Point], [Point]) last_stage_decision dist succesive_inner_product eps dx dy i count wpos pos new_count start_pt end_pt pt dstContours | condition = ([(i+1), (new_count - 1), (addSafePos wpos count), (addSafePos pos count)], finalDstContours, [end_pt, (readDstPt finalDstContours pos)]) | otherwise = ([(i+1), new_count, (addSafePos wpos count), pos], finalSecondDstContours, [pt, pt]) where condition = fromIntegral (dist * dist) <= 0.5 * eps * fromIntegral (dx * dx + dy * dy) && dx /= 0 && dy /= 0 && succesive_inner_product >= 0 finalDstContours = replaceListValue dstContours end_pt wpos finalSecondDstContours = replaceListValue dstContours pt wpos replaceListValue :: [Point] -> Point -> Int -> [Point] replaceListValue (x:dstContours) end_pt wpos | wpos == 0 = end_pt : dstContours | otherwise = x : replaceListValue dstContours end_pt (wpos - 1) optimizing :: [Point] -> Double -> [Point] optimizing listOfPoints epsi = do let listOfLines' = listOfLines listOfPoints (length listOfPoints) 0 False True [] let listOfFinalLines = foldl (\acc x -> acc ++ [getSparePoint x epsi]) [] listOfLines' let takeOf = foldl (++) [] listOfFinalLines listOfPoints \\ takeOf getSparePoint :: [Point] -> Double -> [Point] getSparePoint listOfPoints epsi | (length listOfPoints) <= 2 = [] | otherwise = listOfPoints \\ (rdpFinal listOfPoints listOfPoints epsi []) listOfLines :: [Point] -> Int -> Int -> Bool -> Bool -> [[Point]] -> [[Point]] listOfLines listOfPoint count pos theLast pointsYet acc | not pointsYet = acc | otherwise = listOfLines listOfPoint count (myfst takingPoints) (fst (mysnd takingPoints)) (snd (mysnd takingPoints)) (acc ++ [trd takingPoints]) where takingPoints = takeEveryPoint listOfPoint currentPoint foundDirection count (addSafePos pos count) theLast pointsYet ([currentPoint]) currentPoint = listOfPoint !! pos foundDirection = findDirection currentPoint (listOfPoint !! (addSafePos pos count)) takeEveryPoint :: [Point] -> Point -> Direction -> Int -> Int -> Bool -> Bool -> [Point] -> (Int, (Bool, Bool), [Point]) takeEveryPoint listOfPoint lastPoint direction count pos theLast pointsYet acc | not (sameDirection direction lastPoint currentPoint) = ((lessSafePos pos count), (theLast, not (theLast && pointsYet)), acc) | (lastPoint == realLastPoint) && (theLast == False) = takeEveryPoint listOfPoint lastPoint direction count pos True pointsYet acc | otherwise = takeEveryPoint listOfPoint currentPoint direction count (addSafePos pos count) theLast pointsYet (acc ++ [currentPoint]) where currentPoint = listOfPoint !! pos realLastPoint = listOfPoint !! (count - 1) findDirection :: Point -> Point -> Direction findDirection (x, y) (x1, y1) | (slope == hori) && (x1 >= x) = right | (slope == hori) && (x1 < x) = left | (slope == verti) && (y1 >= y) = up | otherwise = down where slope = getSlope (x, y) (x1, y1) getSlope :: Point -> Point -> Bool getSlope (x, y) (x1, y1) | slope <= 1 = hori | otherwise = verti where slope = abs (fromIntegral (y1 - y) / fromIntegral (x1 - x)) sameDirection :: Direction -> Point -> Point -> Bool sameDirection direction point1 point2 | direction == findDirection point1 point2 = True | otherwise = False pointToPointDist :: Point -> Point -> Double pointToPointDist (x1, y1) (x2, y2) = sqrt (fromIntegral (x'^2 + y'^2)) where x' = x1 - x2 y' = y1 - y2 pointToLineDist :: Point -> Point -> Point -> Double --Line -> (x1, y1) ^ (x2, y2) pointToLineDist (x1, y1) (x2, y2) (x0, y0) = abs (fromIntegral ((y2 - y1) * x0 - (x2 - x1) * y0 + x2 * y1 - y2 * x1) / pointToPointDist (x1, y1) (x2, y2)) findFarthestPoint :: [Point] -> Point -> Point -> Double -> Point findFarthestPoint [] firstPoint finalPoint dist = finalPoint findFarthestPoint (currntPoint : pointList) firstPoint finalPoint dist | pointToPointDist currntPoint firstPoint >= dist = findFarthestPoint pointList firstPoint currntPoint (pointToPointDist currntPoint firstPoint) | otherwise = findFarthestPoint pointList firstPoint finalPoint dist findFarthestTwoPoints :: [Point] -> [Point] -> Double -> [Point] findFarthestTwoPoints [] finalList dist = finalList findFarthestTwoPoints (currntPoint : pointList) finalList dist | newDist >= dist = findFarthestTwoPoints pointList [currntPoint, farthestPoint] newDist | otherwise = findFarthestTwoPoints pointList finalList dist where farthestPoint = findFarthestPoint pointList currntPoint currntPoint 0 newDist = pointToPointDist farthestPoint currntPoint findFarthestPointToLine :: [Point] -> [Point] -> Point -> Double -> Point findFarthestPointToLine [] line finalPoint dist = finalPoint findFarthestPointToLine (currntPoint : pointList) line finalPoint dist | newDist >= dist = findFarthestPointToLine pointList line currntPoint newDist | otherwise = findFarthestPointToLine pointList line finalPoint dist where newDist = pointToLineDist (line !! 0) (line !! 1) currntPoint rdpFinal :: [Point] -> [Point] -> Double -> [Point] -> [Point] rdpFinal [x] original epsi acc = acc ++ [x] rdpFinal listOfPoints original epsi acc | (length listOfPoints) == 2 = rdpFinal restOfList original epsi (acc ++ [point1]) | distToLine < epsi = rdpFinal restOfList original epsi (acc ++ [point1]) | otherwise = rdpFinal tilPoint original epsi acc where twoPoints = findFarthestTwoPoints listOfPoints [] 0 point1 = twoPoints !! 0 point2 = twoPoints !! 1 distOfTwoPoints = distFunc point1 point2 farthestPoint = findFarthestPointToLine listOfPoints twoPoints (0,0) 0 distToLine = pointToLineDist point1 point2 farthestPoint restOfList = drop (fromJust (elemIndex point2 original)) original tilPoint = take (fromJust (elemIndex farthestPoint original)) original ++ [farthestPoint]
Chuck-Aguilar/haskell-opencv-work
src/RamerDouglasPeuckerParts.hs
bsd-3-clause
16,775
0
20
4,855
5,596
2,939
2,657
252
1
module Watch.Matches where import qualified Data.List.NonEmpty as N import qualified Data.Map as M import System.FilePath.Glob import Watch.Types -- we use trie search to find the parent dir then match on pattern -- left is pattern, right is file that worries about it type Filter = [(Pattern, FilePath)] matches :: Refs -> M.Map FilePath Filter matches = M.fromListWith (++) . concatMap fromPair . M.toList fromPair :: (FilePath, Matches) -> [(FilePath, Filter)] fromPair (fp, ms) = map (\ (target, pat) -> (init target, [(pat, fp)])) $ N.toList ms
pikajude/src-watch
src/Watch/Matches.hs
bsd-3-clause
572
0
11
108
174
105
69
11
1
module Report where import qualified Data.Map.Strict as M import Imports import SysInfo (SysInfo (..)) import Types import Util header :: IO () header = do putStrLn "-----------+-----------------------+- part 1 ---------------------+- part 2 ---------------------" putStrLn " day | answers | time allocs maxhea maxmem | time allocs maxhea maxmem " putStrLn "-----------+-----------------------+------------------------------+------------------------------" footer :: SysInfo -> IO () footer i = do putStrLn "-----------+-----------------------+------------------------------+------------------------------" putStrLn . unlines . map (" " ++) . lines . showSysInfo $ i dayPrefix :: DayPrefix -> IO () dayPrefix dayP = do printf " %-9s | " dayP hFlush stdout dayPrefixToModuleName :: DayPrefix -> ModuleName dayPrefixToModuleName = take (length ("YXX.DXX" :: String)) dayResults :: FilePath -> Map ModuleName [AnswerStr] -> DayPrefix -> [ExecResult] -> IO () dayResults answersPath mod2answers dayP results = do printf "%-21s | %s %s\n" (intercalate ", " $ results <&> output) (intercalate " | " $ results <&> \ExecResult{msReal, bytesAllocated, bytesPeak, bytesMaxInUse} -> printf "%5dms %6s %6s %6s" msReal (maybe "?" size2humanSize bytesAllocated) (maybe "?" size2humanSize bytesPeak) (maybe "?" size2humanSize bytesMaxInUse)) (case M.lookup (dayPrefixToModuleName dayP) mod2answers of Nothing -> " <-- couldn't find entry " ++ show dayP ++ " in " ++ show answersPath Just expected -> if expected /= (results <&> output) then " <-- expected: " ++ intercalate ", " expected else "") showSysInfo :: SysInfo -> String showSysInfo SysInfo{..} = let fm = fromMaybe "?" in intercalate "" [ "Platform: ", fm osName, ", " , fm osArch, ", v" , fm osVersion, ", " , fm hwModel , "\nCPU: ", fm cpuModel, ", " , fm $ show <$> cpuCores, " cores" , "\nRAM: ", fm $ size2humanSize . fromIntegral <$> ramTotal, " @ " , fm $ show <$> ramClock, "MHz" , "\nCompiler: ", fm compiler, " (" , fm compilerArch, ")" ]
oshyshko/adventofcode
src.exe/Report.hs
bsd-3-clause
2,491
0
15
795
583
302
281
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Network.Kafka.Specs.Kafka.ParsingSpecs where import Data.Serialize.Put import Network.Kafka.Consumer import Network.Kafka.Consumer.Basic import Network.Kafka.Producer import Network.Kafka.Response import Network.Kafka.Types import Network.Kafka.Specs.Kafka.Arbitrary() import Test.HUnit import Test.Hspec.HUnit() import Test.Hspec.Monadic import Test.Hspec.QuickCheck import qualified Data.ByteString.Char8 as B messageProperties :: Spec messageProperties = describe "the client" $ do let stream = Stream (Topic "ignored topic") (Partition 0) c = BasicConsumer stream (Offset 0) prop "serialize -> deserialize is id" $ \message -> parseMessage (runPut $ putMessage message) == message prop "serialize -> deserialize is id for message sets" $ \messages -> (fst $ parseMessageSet (putMessages' messages) c) == messages it "parsing empty message set gives empty list" $ fst (parseMessageSet "" c) @?= [] it "parsing the empty message set does not change the offset" $ getOffset (snd $ parseMessageSet "" c) @?= Offset 0 it "parsing a message set gets the offset of all the messages" $ let messages = [Message "Adsf"] in (getOffset $ snd $ parseMessageSet (putMessages' messages) c) @?= (Offset $ sum $ map mLength messages) prop "serialized message length is 1 + 4 + n" $ \message@(Message raw) -> parseMessageSize 0 (runPut $ putMessage message) == 1 + 4 + B.length raw parsingErrorCode :: Spec parsingErrorCode = describe "the client" $ it "parses an error code" $ do let b = putErrorCode 4 parseErrorCode b @?= InvalidFetchSize putMessages' :: [Message] -> B.ByteString putMessages' ms = runPut $ mapM_ putMessage ms putErrorCode :: Int -> B.ByteString putErrorCode code = runPut $ putWord16be $ fromIntegral code
tcrayford/hafka
Network/Kafka/Specs/Kafka/ParsingSpecs.hs
bsd-3-clause
1,826
0
16
315
512
265
247
41
1
module Handler.Verify where import Import import Data.Maybe import qualified Data.Text as T import qualified Data.Text.Lazy as LT import Data.Text.Lazy.Builder import Network.Mail.Mime import System.Random (newStdGen) import Text.Blaze.Html.Renderer.String import Text.Hamlet import Text.Shakespeare.Text (textFile) import Email getResendVerificationR :: Handler RepHtml getResendVerificationR = defaultLayout [whamlet|<h1>not implemented|] postResendVerificationR :: Handler RepHtml postResendVerificationR = defaultLayout [whamlet|<h1>not implemented|] -- Assumes email maps to a valid user. sendVerificationEmail :: Text -> Handler () sendVerificationEmail email = do Entity userId _ <- fmap fromJust $ runDB $ getBy $ UniqueEmail email -- Generate new verKey stdgen <- liftIO newStdGen let verKey = T.pack $ fst $ randomString 20 stdgen runDB $ do mEmailVer <- getBy $ UniqueUserEmailVer userId case mEmailVer of -- Insert new verification record. Nothing -> do _ <- insert $ EmailVerification userId verKey return () -- Update a previous record with new verKey. Just (Entity evId _) -> do update evId [EmailVerificationVerKey =. verKey] return () -- Generate verUrl and create and send email. render <- getUrlRender tm <- getRouteToMaster let verUrl = render $ tm $ VerifyR userId verKey to = Address Nothing email from = noreplyAddr subject = "Bannerstalker verification email" text = toLazyText $ $(textFile "templates/verification.text") () html = LT.pack $ renderHtml $(shamletFile "templates/verification.hamlet") liftIO $ simpleMail to from subject text html [] >>= mySendmail getVerifyR :: UserId -> Text -> Handler RepHtml getVerifyR userId verKey = do mCurrUser <- currentUser success <- case mCurrUser of -- Skip if logged in. Just _ -> return False Nothing -> do mUser <- runDB $ getBy $ UniqueUserEmailVer userId case mUser of -- Skip nonexistant users. Nothing -> return False Just (Entity evId (EmailVerification _ correctVerKey)) -> -- Keys don't match. if (verKey /= correctVerKey) then return False -- Verify and login if keys match. else do runDB $ do update userId [UserVerified =. True] delete evId doLogin userId return True if success then do setSession "_orderSuccess" "You have been successfully verified. \ \Welcome to Bannerstalker!" redirect AccountR else redirect AccountR
nejstastnejsistene/bannerstalker-yesod
src/Handler/Verify.hs
bsd-3-clause
2,916
0
24
936
645
323
322
-1
-1
{-# LANGUAGE PackageImports #-} import "hint" HLint.Dollar import "hint" HLint.HLint
cblp/crdt
HLint.hs
bsd-3-clause
106
0
4
31
14
9
5
3
0
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} module Ling.Proto.Skel ( Skel(Act), combineS, dotS, unknownS, prllActS, dotActS, actS, replS, prune, select, subst, nonParallelChannelSet, check, ) where import Data.Set hiding (foldr) import Prelude hiding (null) import Ling.Norm (TraverseKind (..), RFactor) import Ling.Prelude hiding (null, op, q, Prll) import Ling.Print.Class -- A way to deal with Unknown would be to stick an identifier on each of them. Then the normal -- equality could be used safely. One way would be to use an `IORef ()` data Op = Dot | Prll !Bool | Unknown deriving (Eq, Ord, Read, Show) -- Use compat instead of (==) to avoid treating two unknowns as the same. compat :: Rel Op Dot `compat` Dot = True Prll b `compat` Prll b' = b == b' _ `compat` _ = False -- Yes Unknown /= Unknown data Skel a = Act a | Zero | Op !Op (Skel a) (Skel a) deriving (Eq, Ord, Read, Show) mkOp :: Eq a => Op -> Op2 (Skel a) mkOp op = go where Zero `go` p = p p `go` Zero = p Act c `go` p | Prll _ <- op, c `elemS` p = p -- Avoid redundancies on the left: c * (c * sk) --> c * sk | Op op' (Act d) _ <- p, op `compat` op', c == d = p | Dot <- op, c `elemS` p = unknownS (Act c) (pruneEq c p) p `go` Act c | Prll _ <- op, c `elemS` p = p Act c `go` Act d | c == d = Act d -- Right nesting: (x * y) * z --> x * (y * z) -- Which also enables further reductions when the result is built back. Op op' p0 p1 `go` q | op `compat` op' = mkOp op p0 (mkOp op p1 q) p `go` q = Op op p q skel :: (Ord a, Ord b) => Traversal (Skel a) (Skel b) a b skel f = \case Zero -> pure Zero Act a -> Act <$> f a Op op sk0 sk1 -> mkOp op <$> skel f sk0 <*> skel f sk1 fcSkel :: (Eq a, Ord a) => Skel a -> Set a fcSkel = setOf skel infixr 4 `dotS` dotS :: Eq a => Op2 (Skel a) dotS = mkOp Dot unknownS :: Eq a => Op2 (Skel a) unknownS = mkOp Unknown combineS :: Eq a => TraverseKind -> Op2 (Skel a) combineS = \case ParK -> unknownS TenK -> mappend SeqK -> dotS instance Eq a => Monoid (Skel a) where mempty = Zero mappend = mkOp (Prll True) mconcat [] = Zero mconcat xs = foldr1 mappend xs instance Print Op where prt _ = txt . \case Prll True -> "\n|" Prll False -> "\nX" Unknown -> "\n⁇" Dot -> ".\n" instance (Print a, Eq a) => Print (Skel a) where prt _ = \case Zero -> txt "()" Act act -> prt 0 act Op op proc1 proc2 -> concatD [ txt "(\n" , prt 0 proc1 , prt 0 op , prt 0 proc2 , txt "\n)"] prtList _ = prt 0 . mconcat infixr 4 `actS` actS :: Eq a => a -> Endom (Skel a) actS act sk = Act act `dotS` sk infixr 4 `prllActS` prllActS :: Eq a => [a] -> Endom (Skel a) prllActS [act] sk = act `actS` sk prllActS acts sk = mconcat (Act <$> acts) `dotS` sk infixr 4 `dotActS` dotActS :: Eq a => [a] -> Endom (Skel a) dotActS [] sk = sk dotActS (act:acts) sk = act `actS` acts `dotActS` sk replS :: Eq a => TraverseKind -> RFactor -> Endom (Skel a) replS k _r sk = case k of SeqK -> sk `dotS` sk TenK -> sk ParK -> sk -- ParK -> error "replS ParK impossible" elemS :: Eq a => a -> Skel a -> Bool elemS c0 = go where go = \case Zero -> False Act c -> c == c0 Op _ sk0 sk1 -> go sk0 || go sk1 subst :: Eq b => (a -> Skel b) -> Skel a -> Skel b subst act = go where go = \case Zero -> Zero Act c -> act c Op op sk0 sk1 -> mkOp op (go sk0) (go sk1) pruneEq :: Eq a => a -> Endom (Skel a) pruneEq c = subst (subst1 (c, Zero) Act) prune :: Ord a => Set a -> Endom (Skel a) prune cs = subst (substMember (cs, Zero) Act) select :: Ord a => Set a -> Endom (Skel a) select cs = subst (substPred ((`notMember` cs), Zero) Act) -- This function is used for the strict-par mode. -- -- This function returns Nothing as soon as a parallel operator is encountered. -- In particular Unknown is accepted as in strict-par mode, Unknown is tweaked -- to mean "in some order but not in parallel". nonParallelChannelSet :: Ord a => Skel a -> Maybe (Set a) nonParallelChannelSet = \case Zero -> pure ø Act c -> pure (l2s [c]) Op (Prll _) _ _ -> Nothing Op _ sk0 sk1 -> union <$> nonParallelChannelSet sk0 <*> nonParallelChannelSet sk1 mAct :: Maybe channel -> Skel channel mAct Nothing = Zero mAct (Just c) = Act c prllFalse :: Ord a => Maybe a -> Set a -> Op2 (Skel a) prllFalse c scs sk0 sk1 = mkOp (Prll False) (go sk0) (go sk1) where go = subst (substMember (scs, mAct c) Act) check :: (MonadError String m, Ord channel, Show channel) => Maybe channel -> [channel] -> EndoM m (Skel channel) check c cs = fmap (uncurry (<>)) . go where scs = l2s cs -- Given a skeleton sk, `go` returns a pair (sk', sk'') -- sk' is a skeleton with occurrences from scs -- sk'' is a skeleton without occurrences from scs -- sk should be equivalent to sk' | sk'' go = \case Zero -> return (Zero, Zero) Act a | a `member` scs -> return (Act a, Zero) | otherwise -> return (Zero, Act a) Op op sk0 sk1 -> do (sk0', sk0'') <- go sk0 (sk1', sk1'') <- go sk1 let cs0 = scs `intersection` fcSkel sk0' cs1 = scs `intersection` fcSkel sk1' cs' = cs0 `union` cs1 -- We could throw an error when the intersection of cs0 and cs1 -- is not null, however these errors are also caught elsewhere -- (when merging parallel protocols for instance) -- One case we want to let pass is when the same channel is used -- twice on one side: -- c[d,e] (send d 1 | send e 2. send a 3. send e 4) -- Here the skeleton is: `(d | e.a.e)`, the channel `e` appear twice -- and we chose to keep the ordering. We need the reconstruction of: -- `e.a.e` not to raise an error. case op of _ | null cs0 && null cs1 -> return (Zero, mkOp op (sk0' <> sk0'') (sk1' <> sk1'')) Prll True | not (null cs1) && not (null cs0) -> return (prllFalse c cs' sk0' sk1', sk0'' <> sk1'') Prll True | null cs0 && not (null cs1) -> return (sk1', sk0' <> sk0'' <> sk1'') Prll True | null cs1 && not (null cs0) -> return (sk0', sk0'' <> sk1' <> sk1'') _ | not (null cs1) && not (null cs0) && cs0 /= cs1 -> throwError $ "checkSel: " ++ show op _ -> return (mkOp op (sk0' <> sk0'') (sk1' <> sk1''), Zero)
np/ling
Ling/Proto/Skel.hs
bsd-3-clause
6,829
0
23
2,162
2,554
1,299
1,255
177
8
{-# LANGUAGE OverloadedStrings #-} module Geekingfrog.Parse (parseGhostExport) where import Prelude hiding (readFile, head) import Data.ByteString (readFile, ByteString) import Data.Aeson (eitherDecodeStrict, Value, parseJSON, FromJSON) import Data.Aeson.Types ( parseEither , withObject , withArray , Parser , (.:) , Value(..) , Object ) import Data.Text (Text) import Data.Vector (head) import Control.Monad (join) import Data.Either (lefts, rights) import Control.Applicative (liftA, liftA3) import Geekingfrog.GhostTypes (Post, Tag, PostTag) parseGhostExport :: ByteString -> Either String ([String], ([Post], [Tag], [PostTag])) parseGhostExport rawContent = do let eitherData = eitherDecodeStrict rawContent >>= parseEither parseData -- then parse the various required objects let eitherPosts = eitherData >>= parseEither verboseParseManyPosts let eitherTags = eitherData >>= parseEither verboseParseManyTags let eitherTags = eitherData >>= parseEither verboseParseManyTags let eitherPostTags = eitherData >>= parseEither verboseParseManyPostTags let grouped = liftA3 (,,) eitherPosts eitherTags eitherPostTags case grouped of Left err -> Left err Right (posts, tags, postTags) -> do let errors = lefts posts ++ lefts tags ++ lefts postTags Right (errors, (rights posts, rights tags, rights postTags)) verboseParseManyPosts :: Object -> Parser [Either String Post] verboseParseManyPosts = verboseParseKey "posts" verboseParseManyTags :: Object -> Parser [Either String Tag] verboseParseManyTags = verboseParseKey "tags" verboseParseManyPostTags :: Object -> Parser [Either String PostTag] verboseParseManyPostTags = verboseParseKey "posts_tags" verboseParseKey :: (FromJSON a) => Text -> Object -> Parser [Either String a] verboseParseKey key o = do raw <- o .: key return $ fmap (join . parseEither verboseParser) raw parseData :: Value -> Parser Object parseData val = do db <- withObject "ghost export" (.: "db") val -- get the first (and only?) export in the `db` array arrDb <- withArray "db" (return . head) db -- Extract the data from the db actualData <- withObject "data" (.: "data") arrDb -- Make sure it's an object withObject "content" return actualData verboseParser :: (FromJSON a) => Value -> Parser (Either String a) verboseParser v = do let parsed = parseEither parseJSON v case parsed of Left err -> return . Left $ err ++ " -- Invalid object is: " ++ show v Right p -> return $ Right p
geekingfrog/geekingfrog.com
src/Geekingfrog/Parse.hs
bsd-3-clause
2,508
0
17
435
763
397
366
54
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveGeneric #-} {-# OPTIONS_GHC -fplugin Brisk.Plugin #-} {-# OPTIONS_GHC -fplugin-opt Brisk.Plugin:main #-} module Simple00 (main) where import GHC.Base.Brisk import Control.Distributed.BriskStatic import Control.Distributed.Process.Closure import Control.Distributed.Process.Brisk import Brisk.Annotations import Brisk.Model.Types hiding (Process) import Data.Binary import Data.Typeable import GHC.Generics (Generic) data Ping = Ping ProcessId | Pong ProcessId deriving (Typeable, Generic) instance Binary Ping data ABigRecord = Foo { a :: Int, b :: ProcessId } deriving (Typeable, Generic) instance Binary ABigRecord child :: ProcessId -> Process () child p = do me <- getSelfPid send p (Ping me) q <- expect send q (Foo { a = 0, b = me }) expect :: Process () remotable ['child] main :: NodeId -> Process () main n = do p <- getSelfPid q <- spawn n $ $(mkBriskClosure 'child) p let myBigRecord = Foo 3 p Ping q <- expect flip send (b myBigRecord) q msg <- expect send (b msg) () return ()
abakst/brisk-prelude
examples/SimpleSpawn00.hs
bsd-3-clause
1,190
0
12
305
368
192
176
37
1
{-# LANGUAGE OverloadedStrings #-} import Control.Monad (forM_) import Data.Maybe (fromMaybe) import qualified Data.Text as T import qualified Data.Text.Slugger as Slugger import Hakyll import Text.Pandoc ( Extension (Ext_fenced_code_attributes, Ext_footnotes, Ext_gfm_auto_identifiers, Ext_implicit_header_references, Ext_smart), Extensions, ReaderOptions, WriterOptions (writerHighlightStyle), extensionsFromList, githubMarkdownExtensions, readerExtensions, writerExtensions, ) import Text.Pandoc.Highlighting (Style, breezeDark, styleToCss) -------------------------------------------------------------------------------- -- CONFIG root :: String root = "https://robertwpearce.com" siteName :: String siteName = "Robert Pearce | Senior Software Developer" config :: Configuration config = defaultConfiguration { destinationDirectory = "dist" , ignoreFile = const False , previewHost = "127.0.0.1" , previewPort = 8000 , providerDirectory = "src" , storeDirectory = "ssg/_cache" , tmpDirectory = "ssg/_tmp" } -------------------------------------------------------------------------------- -- BUILD main :: IO () main = hakyllWith config $ do forM_ [ "CNAME" , "favicon.ico" , "robots.txt" , "_config.yml" , "js/dist/*" , "images/*" , "fonts/*" --, ".well-known/*" -- not working ] $ \f -> match f $ do route idRoute compile copyFileCompiler match "css/*" $ do route idRoute compile compressCssCompiler match "posts/*" $ do let ctx = constField "type" "article" <> postCtx route $ metadataRoute titleRoute compile $ pandocCompilerCustom >>= saveSnapshot "content" >>= loadAndApplyTemplate "templates/post.html" ctx >>= loadAndApplyTemplate "templates/default.html" ctx match "new-zealand/**" $ do let ctx = constField "type" "article" <> postCtx route $ setExtension "html" compile $ pandocCompilerCustom >>= saveSnapshot "content" >>= loadAndApplyTemplate "templates/info.html" ctx >>= loadAndApplyTemplate "templates/default.html" ctx match "index.html" $ do route idRoute compile $ do posts <- recentFirst =<< loadAll "posts/*" let indexCtx = listField "posts" postCtx (return posts) <> constField "root" root <> constField "siteName" siteName <> defaultContext getResourceBody >>= applyAsTemplate indexCtx >>= loadAndApplyTemplate "templates/default.html" indexCtx match "templates/*" $ compile templateBodyCompiler create ["sitemap.xml"] $ do route idRoute compile $ do posts <- recentFirst =<< loadAll "posts/*" nzPages <- loadAll "new-zealand/**" let pages = posts <> nzPages sitemapCtx = constField "root" root <> constField "siteName" siteName <> listField "pages" postCtx (return pages) makeItem ("" :: String) >>= loadAndApplyTemplate "templates/sitemap.xml" sitemapCtx create ["rss.xml"] $ do route idRoute compile (feedCompiler renderRss) create ["atom.xml"] $ do route idRoute compile (feedCompiler renderAtom) -------------------------------------------------------------------------------- -- COMPILER HELPERS makeStyle :: Style -> Compiler (Item String) makeStyle = makeItem . compressCss . styleToCss -------------------------------------------------------------------------------- -- CONTEXT feedCtx :: Context String feedCtx = titleCtx <> postCtx <> bodyField "description" postCtx :: Context String postCtx = constField "root" root <> constField "siteName" siteName <> dateField "date" "%Y-%m-%d" <> defaultContext titleCtx :: Context String titleCtx = field "title" updatedTitle -------------------------------------------------------------------------------- -- TITLE HELPERS replaceAmp :: String -> String replaceAmp = replaceAll "&" (const "&amp;") replaceTitleAmp :: Metadata -> String replaceTitleAmp = replaceAmp . safeTitle safeTitle :: Metadata -> String safeTitle = fromMaybe "no title" . lookupString "title" updatedTitle :: Item a -> Compiler String updatedTitle = fmap replaceTitleAmp . getMetadata . itemIdentifier -------------------------------------------------------------------------------- -- PANDOC pandocCompilerCustom :: Compiler (Item String) pandocCompilerCustom = pandocCompilerWith pandocReaderOpts pandocWriterOpts pandocExtensionsCustom :: Extensions pandocExtensionsCustom = githubMarkdownExtensions <> extensionsFromList [ Ext_fenced_code_attributes , Ext_gfm_auto_identifiers , Ext_implicit_header_references , Ext_smart , Ext_footnotes ] pandocReaderOpts :: ReaderOptions pandocReaderOpts = defaultHakyllReaderOptions { readerExtensions = pandocExtensionsCustom } pandocWriterOpts :: WriterOptions pandocWriterOpts = defaultHakyllWriterOptions { writerExtensions = pandocExtensionsCustom , writerHighlightStyle = Just pandocHighlightStyle } pandocHighlightStyle :: Style pandocHighlightStyle = breezeDark -- https://hackage.haskell.org/package/pandoc/docs/Text-Pandoc-Highlighting.html -------------------------------------------------------------------------------- -- FEEDS type FeedRenderer = FeedConfiguration -> Context String -> [Item String] -> Compiler (Item String) feedCompiler :: FeedRenderer -> Compiler (Item String) feedCompiler renderer = renderer feedConfiguration feedCtx =<< recentFirst =<< loadAllSnapshots "posts/*" "content" feedConfiguration :: FeedConfiguration feedConfiguration = FeedConfiguration { feedTitle = "Robert Pearce's blog" , feedDescription = "Posts on JavaScript, Node.js, Haskell, Elm, Ruby and more." , feedAuthorName = "Robert Pearce" , feedAuthorEmail = "[email protected]" , feedRoot = root } -------------------------------------------------------------------------------- -- CUSTOM ROUTE getTitleFromMeta :: Metadata -> String getTitleFromMeta = fromMaybe "no title" . lookupString "title" fileNameFromTitle :: Metadata -> FilePath fileNameFromTitle = T.unpack . (`T.append` ".html") . Slugger.toSlug . T.pack . getTitleFromMeta titleRoute :: Metadata -> Routes titleRoute = constRoute . fileNameFromTitle
rpearce/robertwpearce.com
ssg/src/Main.hs
bsd-3-clause
6,445
17
22
1,260
1,301
664
637
175
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Opts ( ConfigReader , runConfig , Config (..) , parseArgs , showUsage ) where import System.Console.GetOpt import Control.Applicative import Control.Monad.Reader newtype ConfigReader m a = ConfigReader { unwrap :: ReaderT Config m a } deriving (Functor, Applicative, Monad, MonadTrans, MonadIO, MonadReader Config) runConfig :: ConfigReader m a -> Config -> m a runConfig = runReaderT . unwrap data Config = Config { cfgVerbose :: Bool, cfgRoot :: FilePath, cfgClean :: Bool, cfgRunIO :: Bool } deriving (Show) defaultConfig :: Config defaultConfig = Config { cfgVerbose = True, cfgRoot = "MailBox", cfgClean = False, cfgRunIO = True } options :: [OptDescr (Config -> Maybe Config) ] options = [ Option "q" ["quiet"] (NoArg opt_quiet) "disable verbose output" , Option "r" ["root"] (ReqArg opt_root "DIR") "set root directory" , Option "C" ["clean"] (NoArg opt_clean) "clean duplicate files after processing" , Option "n" ["dry-run"] (NoArg opt_dryRun) "no execute of file output" , Option "h" ["help"] (NoArg opt_usage) "print this help" ] where opt_quiet cfg = return cfg { cfgVerbose = False } opt_root arg cfg = return cfg { cfgRoot = arg } opt_clean cfg = return cfg { cfgClean = True } opt_dryRun cfg = return cfg { cfgRunIO = False } opt_usage _ = Nothing parseArgs :: [String] -> Either String (Config, [String]) parseArgs rawArgs = case getOpt RequireOrder options rawArgs of (acts, args, []) -> case foldl (>>=) (return defaultConfig) acts of Just cfg -> Right (cfg, args) Nothing -> Left "" (_, _, errs) -> Left $ concat errs showUsage :: String -> String showUsage progName = usageInfo ("usage: " ++ progName ++ " [options] filenames") options
kataoka271/vmgconv
src/Opts.hs
bsd-3-clause
2,001
0
12
567
584
323
261
59
3
module RPF.Parser where import Control.Applicative hiding (many,optional,(<|>)) import Control.Monad import qualified Data.ByteString.Char8 as BS import Data.IP import Data.List import Data.Maybe import Network.DNS.Types (Domain) import Network.DomainAuth import RPF.Domain import RPF.IP import RPF.Lexer import RPF.State import RPF.Types import Text.Parsec import Text.ParserCombinators.Parsec.Expr ---------------------------------------------------------------- type Parser a = Lexer ParserState a ---------------------------------------------------------------- parsePolicy :: String -> Policy parsePolicy cs = case runParser config initialState "" cs of Left err -> error $ show err Right rs -> rs ---------------------------------------------------------------- config :: Parser Policy config = do whiteSpace blks <- many1 defBlock eof st <- getState checkUnused (unused st) return $ Policy blks (iptbls st) (domtbls st) where iptbls = map makeIPTable . reverse . iplol domtbls = map makeDomainTable . reverse . domlol checkUnused [] = return () checkUnused us = unexpected $ ": Not used -- " ++ concat (intersperse ", " us) ---------------------------------------------------------------- defBlock :: Parser Block defBlock = many definition >> block definition :: Parser () definition = do cst <- identifier -- $foo reservedOp "=" dat <- ipList <|> domainList <|> resultList void semi define cst dat return () where define cst dat = do st <- getState let ent = lookup cst (consttbl st) when (isJust ent) $ unexpected $ ": Multiple declarations of '" ++ cst ++ "'" setState st { consttbl = (cst, dat) : consttbl st , unused = cst : unused st } block :: Parser Block block = do blknm <- blockname checkBlock blknm cs <- braces (many actionCond) check blknm cs nextBlock return $ Block blknm cs where blockname :: Parser BlockName blockname = sym2enum blockNames [minBound..maxBound] checkBlock blknm = do st <- getState let cblknm = head $ blocks st when (blknm /= cblknm) $ unexpected $ ": " ++ show cblknm ++ "{} is expected" nextBlock = do st <- getState setState st { blocks = tail $ blocks st } check blknm cs = case last cs of ActionCond _ Nothing _ -> return () _ -> unexpected $ ": action without condition must exist in " ++ show blknm ++ "{}" ---------------------------------------------------------------- actionCond :: Parser ActionCond actionCond = do pos <- getPosition let l = sourceLine pos act <- action cnd <- option Nothing condition void semi return $ ActionCond l cnd act where action :: Parser Action action = sym2enum actionWords [minBound..maxBound] condition = do void colon cnd <- cond return $ Just cnd ---------------------------------------------------------------- cond :: Parser Cond cond = buildExpressionParser table term where table = [[Infix opAnd AssocRight]] term :: Parser Cond term = do void $ char '#' var@(vtyp,vid) <- variable checkVar vid opr <- opMatch <|> opNotMatch cst@(ctyp,cval) <- constant when (vtyp /= ctyp) $ unexpected ": Data type mismatch" when (vtyp == DT_Res) $ checkResult vid cval return $ var `opr` cst where variable :: Parser Variable variable = var2enum variableNames [minBound..maxBound] variableTypes checkVar vid = do st <- getState let blknm = head $ blocks st sanity = fromJust $ lookup blknm varSanity unless (vid `elem` sanity) $ unexpected $ ": #" ++ show vid ++ " cannot be used in " ++ show blknm ++ "{}" checkResult vid (CV_Result cval) = do let sanity = fromJust $ lookup vid resultSanity mapM_ (test vid sanity) cval checkResult _ _ = return () test vid rs r = unless (r `elem` rs) $ unexpected $ ": '" ++ show r ++ "' cannot be used for #" ++ show vid ---------------------------------------------------------------- constant :: Parser Constant constant = ipList <|> domainList <|> resultList2 <|> definedConstant <|> yesOrNo definedConstant :: Parser Constant definedConstant = identifier >>= resolve where resolve cst = do st <- getState let ent = lookup cst $ consttbl st when (isNothing ent) $ unexpected $ ": No definition of '" ++ cst ++ "'" let cused = cst : used st cunused = delete cst $ unused st setState st { used = cused, unused = cunused } let cd@(typ, CV_Index n) = fromJust ent if typ == DT_Res then return (typ, CV_Result (reslol st !! n)) else return cd yesOrNo :: Parser Constant yesOrNo = do b <- yesno return (DT_Sig, CV_Sig b) where yesno :: Parser Bool yesno = sym2enum noyes [minBound..maxBound] ---------------------------------------------------------------- op :: String -> a -> Parser a op str opr = do reservedOp str return opr opAnd :: Parser (Cond -> Cond -> Cond) opAnd = op "&&" (:&&) opMatch :: Parser (Variable -> Constant -> Cond) opMatch = op "==" (:==) opNotMatch :: Parser (Variable -> Constant -> Cond) opNotMatch = op "!=" (:!=) ---------------------------------------------------------------- ip4range :: Parser IPRange ip4range = IPv4Range . read <$> many1 (oneOf $ ['0'..'9'] ++ "./") ip6range :: Parser IPRange ip6range = IPv6Range . read <$> many1 (oneOf $ ['0'..'9'] ++ ['a'..'f'] ++ ['A'..'F'] ++ ".:/") ipList :: Parser Constant ipList = do ips <- commaSep1 (try(lexeme ip4range) <|> lexeme ip6range) n <- index ips return (DT_IP, CV_Index n) where index ips = do st <- getState let n = ipcnt st setState st { iplol = ips : iplol st , ipcnt = n + 1 } return n ---------------------------------------------------------------- domain :: Parser Domain domain = BS.pack <$> (char '"' >> many1 (noneOf "\"")) <* symbol "\"" domainList :: Parser Constant domainList = do dms <- commaSep1 (lexeme domain) n <- index dms return (DT_Dom, CV_Index n) where index dms = do st <- getState let n = domcnt st setState st { domlol = dms : domlol st , domcnt = n + 1 } return n ---------------------------------------------------------------- result :: Parser DAResult result = (char '\'' >> authResult) <* char '\'' -- backward compatibility <|> authResult where authResult :: Parser DAResult authResult = sym2enum resultWords [minBound..maxBound] resultList :: Parser Constant resultList = do rs <- commaSep1 (lexeme result) n <- index rs return (DT_Res, CV_Index n) where index rs = do st <- getState let n = rescnt st setState st { reslol = rs : reslol st , rescnt = n + 1 } return n resultList2 :: Parser Constant resultList2 = do rs <- commaSep1 (lexeme result) return (DT_Res, CV_Result rs) ---------------------------------------------------------------- sym2enum :: [String] -> [a] -> Parser a sym2enum ss es = choice ps where func res sym = do {reserved res; return sym} ps = zipWith func ss es var2enum :: [String] -> [VariableId] -> [DataType] -> Parser Variable var2enum ss ns ts = choice ps where func res nam typ = do {reserved res; return (typ,nam)} ps = zipWith3 func ss ns ts
kazu-yamamoto/rpf
RPF/Parser.hs
bsd-3-clause
7,662
0
17
2,023
2,494
1,229
1,265
197
2
{-# LANGUAGE OverloadedStrings #-} module Purescript.Ide.CommandSpec where import Data.Either (isLeft) import Purescript.Ide.Command import Test.Hspec spec :: Spec spec = do describe "Parsing commands" $ do it "parses a load command" $ parseCommand "load Module.Name" `shouldBe` Right (Load "Module.Name") it "parses a dependencies command" $ parseCommand "dependencies Module.Name" `shouldBe` Right (LoadDependencies "Module.Name") it "parses a print command" $ parseCommand "print" `shouldBe` Right Print it "parses a cwd command" $ parseCommand "cwd" `shouldBe` Right Cwd it "parses a quit command" $ parseCommand "quit" `shouldBe` Right Quit it "parses a type lookup command" $ parseCommand "typeLookup ident" `shouldBe` Right (TypeLookup "ident") it "parses a completion command" $ parseCommand "complete stub Project" `shouldBe` Right (Complete "stub" Project) it "fails to parse a malformed command" $ parseCommand "compasd asd" `shouldSatisfy` isLeft
passy/psc-ide
test/Purescript/Ide/CommandSpec.hs
bsd-3-clause
1,077
0
13
244
248
121
127
24
1
----------------------------------------------------------------------------- -- -- Machine-specific parts of the register allocator -- -- (c) The University of Glasgow 1996-2004 -- ----------------------------------------------------------------------------- {-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details module PPC.RegInfo ( JumpDest( DestBlockId ), getJumpDestBlockId, canShortcut, shortcutJump, shortcutStatics ) where #include "nativeGen/NCG.h" #include "HsVersions.h" import PPC.Instr import BlockId import Cmm import CLabel import Unique data JumpDest = DestBlockId BlockId getJumpDestBlockId :: JumpDest -> Maybe BlockId getJumpDestBlockId (DestBlockId bid) = Just bid canShortcut :: Instr -> Maybe JumpDest canShortcut _ = Nothing shortcutJump :: (BlockId -> Maybe JumpDest) -> Instr -> Instr shortcutJump _ other = other -- Here because it knows about JumpDest shortcutStatics :: (BlockId -> Maybe JumpDest) -> CmmStatics -> CmmStatics shortcutStatics fn (Statics lbl statics) = Statics lbl $ map (shortcutStatic fn) statics -- we need to get the jump tables, so apply the mapping to the entries -- of a CmmData too. shortcutLabel :: (BlockId -> Maybe JumpDest) -> CLabel -> CLabel shortcutLabel fn lab | Just uq <- maybeAsmTemp lab = shortBlockId fn (mkBlockId uq) | otherwise = lab shortcutStatic :: (BlockId -> Maybe JumpDest) -> CmmStatic -> CmmStatic shortcutStatic fn (CmmStaticLit (CmmLabel lab)) = CmmStaticLit (CmmLabel (shortcutLabel fn lab)) shortcutStatic fn (CmmStaticLit (CmmLabelDiffOff lbl1 lbl2 off)) = CmmStaticLit (CmmLabelDiffOff (shortcutLabel fn lbl1) lbl2 off) -- slightly dodgy, we're ignoring the second label, but this -- works with the way we use CmmLabelDiffOff for jump tables now. shortcutStatic _ other_static = other_static shortBlockId :: (BlockId -> Maybe JumpDest) -> BlockId -> CLabel shortBlockId fn blockid = case fn blockid of Nothing -> mkAsmTempLabel uq Just (DestBlockId blockid') -> shortBlockId fn blockid' where uq = getUnique blockid
ekmett/ghc
compiler/nativeGen/PPC/RegInfo.hs
bsd-3-clause
2,384
12
10
422
493
259
234
44
2
module FRP.Helm.Engine where import qualified Graphics.UI.SDL as SDL import qualified Graphics.Rendering.Cairo as Cairo import qualified Data.Map as Map {-| A data structure describing the current engine state. -} data Engine = Engine { window :: SDL.Window, renderer :: SDL.Renderer, cache :: Map.Map FilePath Cairo.Surface, continue :: Bool }
didmar/helm
src/FRP/Helm/Engine.hs
mit
358
0
10
61
80
53
27
9
0
-- File: Optimal2.hs -- Author: Adam Juraszek -- Purpose: Partly generated map of optimal second guesses for 2 cards answers. -- Source: https://github.com/juriad/Cardguess module Optimal2 where import Common import Data.Map as Map optimal2 :: Map.Map Feedback Selection optimal2 = Map.fromList [ ( ( 0 , 0 , 0 , 0 , 0 ) , [Card Heart R9 , Card Spade R9] ) , ( ( 0 , 0 , 0 , 0 , 1 ) , [Card Diamond R9 , Card Spade R9] ) , ( ( 0 , 0 , 0 , 0 , 2 ) , [Card Club R9 , Card Diamond R9] ) , ( ( 0 , 0 , 0 , 1 , 0 ) , [Card Heart Jack , Card Spade R9] ) , ( ( 0 , 0 , 0 , 1 , 1 ) , [Card Diamond Ace , Card Spade R9] ) , ( ( 0 , 0 , 0 , 1 , 2 ) , [Card Club Jack , Card Diamond R9] ) , ( ( 0 , 0 , 0 , 2 , 0 ) , [Card Heart Ace , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 2 , 1 ) , [Card Diamond Ace , Card Spade Ace] ) , ( ( 0 , 0 , 0 , 2 , 2 ) , [Card Club Ace , Card Diamond Ace] ) , ( ( 0 , 0 , 1 , 0 , 0 ) , [Card Heart R10 , Card Spade R10] ) , ( ( 0 , 0 , 1 , 0 , 1 ) , [Card Diamond R6 , Card Spade R6] ) , ( ( 0 , 0 , 1 , 0 , 2 ) , [Card Club R7 , Card Diamond R6] ) , ( ( 0 , 0 , 1 , 1 , 0 ) , [Card Heart Jack , Card Spade R10] ) , ( ( 0 , 0 , 1 , 1 , 1 ) , [Card Club R10 , Card Club Jack] ) , ( ( 0 , 0 , 1 , 1 , 2 ) , [Card Club Ace , Card Diamond R6] ) , ( ( 0 , 0 , 2 , 0 , 0 ) , [Card Spade R6 , Card Spade R10] ) , ( ( 0 , 0 , 2 , 0 , 1 ) , [Card Diamond R6 , Card Spade R10] ) , ( ( 0 , 0 , 2 , 0 , 2 ) , [Card Club R10 , Card Diamond R6] ) , ( ( 0 , 1 , 0 , 0 , 0 ) , [Card Heart R7 , Card Spade R5] ) , ( ( 0 , 1 , 0 , 0 , 1 ) , [Card Diamond R9 , Card Spade R5] ) , ( ( 0 , 1 , 0 , 0 , 2 ) , [Card Club R7 , Card Diamond R5] ) , ( ( 0 , 1 , 0 , 1 , 0 ) , [Card Spade R5 , Card Spade Ace] ) , ( ( 0 , 1 , 0 , 1 , 1 ) , [Card Diamond Ace , Card Spade R5] ) , ( ( 0 , 1 , 0 , 1 , 2 ) , [Card Club Jack , Card Diamond R5] ) , ( ( 0 , 1 , 1 , 0 , 0 ) , [Card Heart R6 , Card Spade R5] ) , ( ( 0 , 1 , 1 , 0 , 1 ) , [Card Diamond R5 , Card Diamond R6] ) , ( ( 0 , 1 , 1 , 0 , 2 ) , [Card Club R10 , Card Diamond R2] ) , ( ( 0 , 2 , 0 , 0 , 0 ) , [Card Heart R5 , Card Spade R5] ) , ( ( 0 , 2 , 0 , 0 , 1 ) , [Card Diamond R5 , Card Spade R5] ) , ( ( 0 , 2 , 0 , 0 , 2 ) , [Card Club R5 , Card Diamond R5] ) , ( ( 1 , 0 , 1 , 0 , 1 ) , [Card Diamond R10 , Card Spade R10] ) , ( ( 1 , 0 , 1 , 0 , 2 ) , [Card Club R10 , Card Diamond R10] ) , ( ( 1 , 0 , 1 , 1 , 1 ) , [Card Diamond R10 , Card Diamond Ace] ) , ( ( 1 , 0 , 1 , 1 , 2 ) , [Card Club Ace , Card Diamond R10] ) , ( ( 1 , 0 , 2 , 0 , 1 ) , [Card Diamond R6 , Card Diamond R10] ) , ( ( 1 , 1 , 1 , 0 , 1 ) , [Card Diamond R2 , Card Diamond R10] ) , ( ( 1 , 1 , 1 , 0 , 2 ) , [Card Club R6 , Card Diamond R2] ) , ( ( 2 , 0 , 2 , 0 , 2 ) , [Card Club R6 , Card Diamond R10] ) ]
hikui/Cardguess
src/Optimal2.hs
mit
2,899
0
9
1,038
1,560
937
623
43
1
{-# OPTIONS_GHC -fglasgow-exts #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Functor.Combinators.Of -- Copyright : (C) 2008 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : portable -- ---------------------------------------------------------------------------- module Control.Functor.Combinators.Of ( Of(Of,runOf), liftOf ) where import Prelude hiding ((.),id) import Control.Category import Control.Category.Hask import Control.Category.Braided import Control.Functor import Control.Functor.Pointed -- import Control.Functor.Zip -- import Control.Functor.Zap newtype Of f p a b = Of { runOf :: f (p a b) } liftOf :: Functor f => (p a b -> p c d) -> Of f p a b -> Of f p c d liftOf f = Of . fmap f . runOf instance (Functor f, PFunctor p Hask Hask) => PFunctor (f `Of` p) Hask Hask where first f = liftOf (first f) instance (Functor f, QFunctor p Hask Hask) => QFunctor (f `Of` p) Hask Hask where second g = liftOf (second g) instance (Functor f, Bifunctor p Hask Hask Hask) => Bifunctor (f `Of` p) Hask Hask Hask where bimap f g = liftOf (bimap f g) instance (Functor f, Braided Hask p ) => Braided Hask (f `Of` p) where braid = liftOf braid instance (Functor f, Symmetric Hask p) => Symmetric Hask (f `Of` p) instance (Functor f, Functor (p a)) => Functor (Of f p a) where fmap f = Of . fmap (fmap f) . runOf instance (Pointed f, PPointed p) => PPointed (f `Of` p) where preturn = Of . point . preturn instance (Copointed f, PCopointed p) => PCopointed (f `Of` p) where pextract = pextract . extract . runOf instance (Pointed f, Pointed (p a)) => Pointed (Of f p a) where point = Of . point . point instance (Copointed f, Copointed (p a)) => Copointed (Of f p a) where extract = extract . extract . runOf {- instance (Zip f, Bizip p) => Bizip (f `Of` p) where bizipWith f g = Of . fzipWith (bizipWith f g) . runOf instance (Zip f, Zip (p a)) => Zip (Of f p a) where fzipWith f = Of . fzipWith (fzipWith f) . runOf instance (Bizap p q, Zap f g) => Bizap (f `Of` p) (g `Of` q) where bizapWith f g = Of . zapWith (bizapWith f g) . runOf -}
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
Control/Functor/Combinators/Of.hs
apache-2.0
2,291
4
10
475
708
387
321
-1
-1
{-# LANGUAGE ScopedTypeVariables, CPP #-} module Main where #if __GLASGOW_HASKELL__ < 709 import Control.Applicative #endif import Data.Aeson import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy.Char8 as BL import Data.List import System.Directory import System.FilePath import Control.Monad import JSON hdir :: FilePath hdir = "test-hpack/hpack-test-case/nghttp2" wdir1 :: FilePath wdir1 = "test-hpack/hpack-test-case/haskell-http2-naive" wdir2 :: FilePath wdir2 = "test-hpack/hpack-test-case/haskell-http2-naive-huffman" wdir3 :: FilePath wdir3 = "test-hpack/hpack-test-case/haskell-http2-static" wdir4 :: FilePath wdir4 = "test-hpack/hpack-test-case/haskell-http2-static-huffman" wdir5 :: FilePath wdir5 = "test-hpack/hpack-test-case/haskell-http2-linear" wdir6 :: FilePath wdir6 = "test-hpack/hpack-test-case/haskell-http2-linear-huffman" main :: IO () main = do hs <- get getHeaderSize hdir hlen <- get getHeaderLen hdir ws1 <- get getWireSize wdir1 ws2 <- get getWireSize wdir2 ws3 <- get getWireSize wdir3 ws4 <- get getWireSize wdir4 ws5 <- get getWireSize wdir5 ws6 <- get getWireSize wdir6 let h :: Float = fromIntegral $ sum hs w1 :: Float = fromIntegral $ sum ws1 w2 :: Float = fromIntegral $ sum ws2 w3 :: Float = fromIntegral $ sum ws3 w4 :: Float = fromIntegral $ sum ws4 w5 :: Float = fromIntegral $ sum ws5 w6 :: Float = fromIntegral $ sum ws6 hl :: Float = fromIntegral $ sum hlen print (w1 / h ,w2 / h ,w3 / h ,w4 / h ,w5 / h ,w6 / h) print ((w4 - w6) / hl) get :: (FilePath -> IO Int) -> String -> IO [Int] get func dir = do files0 <- valid . sort <$> getDirectoryContents dir files1 <- filterM doesFileExist files0 mapM func files1 where valid = map (dir </>) . filter (isSuffixOf ".json") getHeaderSize :: FilePath -> IO Int getHeaderSize file = do bs <- BL.readFile file let Just tc = decode bs :: Maybe Test let len = sum $ map toT $ cases tc return len where toT (Case _ _ hs _) = sum $ map (\(x,y) -> BS.length x + BS.length y) hs getHeaderLen :: FilePath -> IO Int getHeaderLen file = do bs <- BL.readFile file let Just tc = decode bs :: Maybe Test let len = length $ cases tc return len getWireSize :: FilePath -> IO Int getWireSize file = do bs <- BL.readFile file let Just tc = decode bs :: Maybe Test let len = sum $ map toT $ cases tc return len where toT (Case _ w _ _) = BS.length w `div` 2
bergmark/http2
test-hpack/hpack-stat.hs
bsd-3-clause
2,596
0
13
638
885
433
452
76
1
{-# LANGUAGE OverloadedStrings #-} module Examples.Primes(primes) where import Development.NSIS -- Based on primes.nsi from NSIS -- -- This is an example of the possibities of the NSIS Script language. -- It calculates prime numbers. ---------------------------------- primes = do name "primes" allowRootDirInstall True outFile "primes.exe" caption "Prime number generator" showInstDetails Show installDir "$EXEDIR" requestExecutionLevel User ---------------------------------- --Pages page Directory page InstFiles ---------------------------------- section "" [] $ do setOutPath "$INSTDIR" hideProgress doPrimes doPrimes = do hdl <- fileOpen ModeWrite "$INSTDIR/primes.txt" let output x = do detailPrint $ strShow x & " is prime!" fileWrite hdl $ strShow x & " is prime!\r\n" output 2 output 3 ppos <- mutableInt "PPOS" 5 -- position in prime searching pdiv <- mutableInt "PDIV" 0 -- divisor pcnt <- mutableInt "PCNT" 2 -- count of how many we've printed loop $ \breakOuter -> do pdiv @= 3 loop $ \breakInner -> do iff_ (ppos `mod` pdiv %== 0) $ do ppos @= ppos + 2 breakInner pdiv @= pdiv + 2 iff_ (pdiv %>= ppos) $ do output ppos pcnt @= pcnt + 1 iff_ (pcnt %== 100) $ do pcnt @= 0 ans <- messageBox [MB_YESNO] "Process more?" iff_ (ans %== "NO") breakOuter fileClose hdl
ndmitchell/nsis
test/Examples/Primes.hs
bsd-3-clause
1,636
0
23
560
394
178
216
42
1
{-# LANGUAGE TypeFamilies #-} module Control.CP.FD.OvertonFD.Sugar ( ) where import Data.Set(Set) import qualified Data.Set as Set import Control.CP.Debug import Control.Mixin.Mixin import Control.CP.Solver import Control.CP.FD.FD import Control.CP.FD.SimpleFD import Data.Expr.Data import Data.Expr.Sugar -- import Control.CP.FD.Expr.Util import Control.CP.FD.Model import Control.CP.FD.Graph import Control.CP.FD.OvertonFD.OvertonFD newVars :: Term s t => Int -> s [t] newVars 0 = return [] newVars n = do l <- newVars $ n-1 n <- newvar return $ n:l instance FDSolver OvertonFD where type FDIntTerm OvertonFD = FDVar type FDBoolTerm OvertonFD = FDVar type FDIntSpec OvertonFD = FDVar type FDBoolSpec OvertonFD = FDVar type FDColSpec OvertonFD = [FDVar] type FDIntSpecType OvertonFD = () type FDBoolSpecType OvertonFD = () type FDColSpecType OvertonFD = () fdIntSpec_const (Const i) = ((),do v <- newvar add $ OHasValue v $ fromInteger i return v) fdIntSpec_term i = ((),return i) fdBoolSpec_const (BoolConst i) = ((),do v <- newvar add $ OHasValue v $ if i then 1 else 0 return v) fdBoolSpec_term i = ((),return i) fdColSpec_list l = ((),return l) fdColSpec_size (Const s) = ((),newVars $ fromInteger s) fdColSpec_const l = ((),error "constant collections not yet supported by overton interface") fdColInspect = return fdSpecify = specify <@> simple_fdSpecify fdProcess = process <@> simple_fdProcess fdEqualInt v1 v2 = addFD $ OSame v1 v2 fdEqualBool v1 v2 = addFD $ OSame v1 v2 fdEqualCol v1 v2 = do if length v1 /= length v2 then setFailed else sequence_ $ zipWith (\a b -> addFD $ OSame a b) v1 v2 fdIntVarSpec = return . Just fdBoolVarSpec = return . Just fdSplitIntDomain b = do d <- fd_domain b return $ (map (b `OHasValue`) d, True) fdSplitBoolDomain b = do d <- fd_domain b return $ (map (b `OHasValue`) $ filter (\x -> x==0 || x==1) d, True) -- processBinary :: (EGVarId,EGVarId,EGVarId) -> (FDVar -> FDVar -> FDVar -> OConstraint) -> FDInstance OvertonFD () processBinary (v1,v2,va) f = addFD $ f (getDefIntSpec v1) (getDefIntSpec v2) (getDefIntSpec va) -- processUnary :: (EGVarId,EGVarId) -> (FDVar -> FDVar -> OConstraint) -> FDInstance OvertonFD () processUnary (v1,va) f = addFD $ f (getDefIntSpec v1) (getDefIntSpec va) specify :: Mixin (SpecFn OvertonFD) specify s t edge = case (debug ("overton-specify("++(show edge)++")") edge) of EGEdge { egeCons = EGChannel, egeLinks = EGTypeData { intData=[i], boolData=[b] } } -> ([(1000,b,True,do s <- getIntSpec i case s of Just ss -> return $ SpecResSpec ((),return (ss,Nothing)) _ -> return SpecResNone )],[(1000,i,True,do s <- getBoolSpec b case s of Just ss -> return $ SpecResSpec ((),return (ss,Nothing)) _ -> return SpecResNone )],[]) _ -> s edge -- process :: Mixin (EGEdge -> FDInstance OvertonFD ()) process s t con info = case (con,info) of (EGIntValue c, ([],[a],[])) -> case c of Const v -> addFD $ OHasValue (getDefIntSpec a) (fromInteger v) _ -> error "Overton solver does not support parametrized values" (EGPlus, ([],[a,b,c],[])) -> processBinary (b,c,a) OAdd (EGMinus, ([],[a,b,c],[])) -> processBinary (a,c,b) OAdd (EGMult, ([],[a,b,c],[])) -> processBinary (b,c,a) OMult (EGAbs, ([],[a,b],[])) -> processUnary (b,a) OAbs (EGDiff, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ ODiff (getDefIntSpec a) (getDefIntSpec b) (EGLess True, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ OLess (getDefIntSpec a) (getDefIntSpec b) (EGLess False, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ OLessEq (getDefIntSpec a) (getDefIntSpec b) (EGEqual, ([FDSpecInfoBool {fdspBoolVal = Just (BoolConst True)}],[a,b],[])) -> addFD $ OSame (getDefIntSpec a) (getDefIntSpec b) _ -> s con info
FranklinChen/monadiccp
Control/CP/FD/OvertonFD/Sugar.hs
bsd-3-clause
4,012
0
20
818
1,668
904
764
89
11
{-# OPTIONS_GHC -XGADTs -XNoMonoLocalBinds #-} -- Norman likes local bindings -- If this module lives on I'd like to get rid of the -XNoMonoLocalBinds -- flag in due course {-# OPTIONS -fno-warn-tabs #-} -- The above warning supression flag is a temporary kludge. -- While working on this module you are encouraged to remove it and -- detab the module (please do the detabbing in a separate patch). See -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#TabsvsSpaces -- for details -- Todo: remove -fno-warn-warnings-deprecations {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} #if __GLASGOW_HASKELL__ >= 703 -- GHC 7.0.1 improved incomplete pattern warnings with GADTs {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} #endif module CmmStackLayout ( SlotEnv, liveSlotAnal, liveSlotTransfers, removeLiveSlotDefs , getSpEntryMap, layout, manifestSP, igraph, areaBuilder , stubSlotsOnDeath ) -- to help crash early during debugging where import Constants import Prelude hiding (succ, zip, unzip, last) import BlockId import Cmm import CmmUtils import CmmProcPoint import Maybes import MkGraph (stackStubExpr) import Control.Monad import OptimizationFuel import Outputable import SMRep (ByteOff) import Compiler.Hoopl import Data.Map (Map) import qualified Data.Map as Map import qualified FiniteMap as Map ------------------------------------------------------------------------ -- Stack Layout -- ------------------------------------------------------------------------ -- | Before we lay out the stack, we need to know something about the -- liveness of the stack slots. In particular, to decide whether we can -- reuse a stack location to hold multiple stack slots, we need to know -- when each of the stack slots is used. -- Although tempted to use something simpler, we really need a full interference -- graph. Consider the following case: -- case <...> of -- 1 -> <spill x>; // y is dead out -- 2 -> <spill y>; // x is dead out -- 3 -> <spill x and y> -- If we consider the arms in order and we use just the deadness information given by a -- dataflow analysis, we might decide to allocate the stack slots for x and y -- to the same stack location, which will lead to incorrect code in the third arm. -- We won't make this mistake with an interference graph. -- First, the liveness analysis. -- We represent a slot with an area, an offset into the area, and a width. -- Tracking the live slots is a bit tricky because there may be loads and stores -- into only a part of a stack slot (e.g. loading the low word of a 2-word long), -- e.g. Slot A 0 8 overlaps with Slot A 4 4. -- -- The definition of a slot set is intended to reduce the number of overlap -- checks we have to make. There's no reason to check for overlap between -- slots in different areas, so we segregate the map by Area's. -- We expect few slots in each Area, so we collect them in an unordered list. -- To keep these lists short, any contiguous live slots are coalesced into -- a single slot, on insertion. slotLattice :: DataflowLattice SubAreaSet slotLattice = DataflowLattice "live slots" Map.empty add where add _ (OldFact old) (NewFact new) = case Map.foldRightWithKey addArea (False, old) new of (change, x) -> (changeIf change, x) addArea a newSlots z = foldr (addSlot a) z newSlots addSlot a slot (changed, map) = let (c, live) = liveGen slot $ Map.findWithDefault [] a map in (c || changed, Map.insert a live map) slotLatticeJoin :: [SubAreaSet] -> SubAreaSet slotLatticeJoin facts = foldr extend (fact_bot slotLattice) facts where extend fact res = snd $ fact_join slotLattice undefined (OldFact fact) (NewFact res) type SlotEnv = BlockEnv SubAreaSet -- The sub-areas live on entry to the block liveSlotAnal :: CmmGraph -> FuelUniqSM SlotEnv liveSlotAnal g = liftM snd $ dataflowPassBwd g [] $ analBwd slotLattice liveSlotTransfers -- Add the subarea s to the subareas in the list-set (possibly coalescing it with -- adjacent subareas), and also return whether s was a new addition. liveGen :: SubArea -> [SubArea] -> (Bool, [SubArea]) liveGen s set = liveGen' s set [] where liveGen' s [] z = (True, s : z) liveGen' s@(a, hi, w) (s'@(a', hi', w') : rst) z = if a /= a' || hi < lo' || lo > hi' then -- no overlap liveGen' s rst (s' : z) else if s' `contains` s then -- old contains new (False, set) else -- overlap: coalesce the slots let new_hi = max hi hi' new_lo = min lo lo' in liveGen' (a, new_hi, new_hi - new_lo) rst z where lo = hi - w -- remember: areas grow down lo' = hi' - w' contains (a, hi, w) (a', hi', w') = a == a' && hi >= hi' && hi - w <= hi' - w' liveKill :: SubArea -> [SubArea] -> [SubArea] liveKill (a, hi, w) set = -- pprTrace "killing slots in area" (ppr a) $ liveKill' set [] where liveKill' [] z = z liveKill' (s'@(a', hi', w') : rst) z = if a /= a' || hi < lo' || lo > hi' then -- no overlap liveKill' rst (s' : z) else -- overlap: split the old slot let z' = if hi' > hi then (a, hi', hi' - hi) : z else z z'' = if lo > lo' then (a, lo, lo - lo') : z' else z' in liveKill' rst z'' where lo = hi - w -- remember: areas grow down lo' = hi' - w' -- Note: the stack slots that hold variables returned on the stack are not -- considered live in to the block -- we treat the first node as a definition site. -- BEWARE?: Am I being a little careless here in failing to check for the -- entry Id (which would use the CallArea Old). liveSlotTransfers :: BwdTransfer CmmNode SubAreaSet liveSlotTransfers = mkBTransfer3 frt mid lst where frt :: CmmNode C O -> SubAreaSet -> SubAreaSet frt (CmmEntry l) f = Map.delete (CallArea (Young l)) f mid :: CmmNode O O -> SubAreaSet -> SubAreaSet mid n f = foldSlotsUsed addSlot (removeLiveSlotDefs f n) n lst :: CmmNode O C -> FactBase SubAreaSet -> SubAreaSet lst n f = liveInSlots n $ case n of CmmCall {cml_cont=Nothing, cml_args=args} -> add_area (CallArea Old) args out CmmCall {cml_cont=Just k, cml_args=args} -> add_area (CallArea Old) args (add_area (CallArea (Young k)) args out) CmmForeignCall {succ=k, updfr=oldend} -> add_area (CallArea Old) oldend (add_area (CallArea (Young k)) wORD_SIZE out) _ -> out where out = joinOutFacts slotLattice n f add_area _ n live | n == 0 = live add_area a n live = Map.insert a (snd $ liveGen (a, n, n) $ Map.findWithDefault [] a live) live -- Slot sets: adding slots, removing slots, and checking for membership. liftToArea :: Area -> ([SubArea] -> [SubArea]) -> SubAreaSet -> SubAreaSet addSlot, removeSlot :: SubAreaSet -> SubArea -> SubAreaSet elemSlot :: SubAreaSet -> SubArea -> Bool liftToArea a f map = Map.insert a (f (Map.findWithDefault [] a map)) map addSlot live (a, i, w) = liftToArea a (snd . liveGen (a, i, w)) live removeSlot live (a, i, w) = liftToArea a (liveKill (a, i, w)) live elemSlot live (a, i, w) = not $ fst $ liveGen (a, i, w) (Map.findWithDefault [] a live) removeLiveSlotDefs :: (DefinerOfSlots s, UserOfSlots s) => SubAreaSet -> s -> SubAreaSet removeLiveSlotDefs = foldSlotsDefd removeSlot liveInSlots :: (DefinerOfSlots s, UserOfSlots s) => s -> SubAreaSet -> SubAreaSet liveInSlots x live = foldSlotsUsed addSlot (removeLiveSlotDefs live x) x liveLastIn :: CmmNode O C -> (BlockId -> SubAreaSet) -> SubAreaSet liveLastIn l env = liveInSlots l (liveLastOut env l) -- Don't forget to keep the outgoing parameters in the CallArea live, -- as well as the update frame. -- Note: We have to keep the update frame live at a call because of the -- case where the function doesn't return -- in that case, there won't -- be a return to keep the update frame live. We'd still better keep the -- info pointer in the update frame live at any call site; -- otherwise we could screw up the garbage collector. liveLastOut :: (BlockId -> SubAreaSet) -> CmmNode O C -> SubAreaSet liveLastOut env l = case l of CmmCall _ Nothing n _ _ -> add_area (CallArea Old) n out -- add outgoing args (includes upd frame) CmmCall _ (Just k) n _ _ -> add_area (CallArea Old) n (add_area (CallArea (Young k)) n out) CmmForeignCall { succ = k, updfr = oldend } -> add_area (CallArea Old) oldend (add_area (CallArea (Young k)) wORD_SIZE out) _ -> out where out = slotLatticeJoin $ map env $ successors l add_area _ n live | n == 0 = live add_area a n live = Map.insert a (snd $ liveGen (a, n, n) $ Map.findWithDefault [] a live) live -- The liveness analysis must be precise: otherwise, we won't know if a definition -- should really kill a live-out stack slot. -- But the interference graph does not have to be precise -- it might decide that -- any live areas interfere. To maintain both a precise analysis and an imprecise -- interference graph, we need to convert the live-out stack slots to graph nodes -- at each and every instruction; rather than reconstruct a new list of nodes -- every time, I provide a function to fold over the nodes, which should be a -- reasonably efficient approach for the implementations we envision. -- Of course, it will probably be much easier to program if we just return a list... type Set x = Map x () data IGraphBuilder n = Builder { foldNodes :: forall z. SubArea -> (n -> z -> z) -> z -> z , _wordsOccupied :: AreaSizeMap -> AreaMap -> n -> [Int] } areaBuilder :: IGraphBuilder Area areaBuilder = Builder fold words where fold (a, _, _) f z = f a z words areaSize areaMap a = case Map.lookup a areaMap of Just addr -> [addr .. addr + (Map.lookup a areaSize `orElse` pprPanic "wordsOccupied: unknown area" (ppr areaSize <+> ppr a))] Nothing -> [] --slotBuilder :: IGraphBuilder (Area, Int) --slotBuilder = undefined -- Now, we can build the interference graph. -- The usual story: a definition interferes with all live outs and all other -- definitions. type IGraph x = Map x (Set x) type IGPair x = (IGraph x, IGraphBuilder x) igraph :: (Ord x) => IGraphBuilder x -> SlotEnv -> CmmGraph -> IGraph x igraph builder env g = foldr interfere Map.empty (postorderDfs g) where foldN = foldNodes builder interfere block igraph = foldBlockNodesB3 (first, middle, last) block igraph where first _ (igraph, _) = igraph middle node (igraph, liveOut) = (addEdges igraph node liveOut, liveInSlots node liveOut) last node igraph = (addEdges igraph node $ liveLastOut env' node, liveLastIn node env') -- add edges between a def and the other defs and liveouts addEdges igraph i out = fst $ foldSlotsDefd addDef (igraph, out) i addDef (igraph, out) def@(a, _, _) = (foldN def (addDefN out) igraph, Map.insert a (snd $ liveGen def (Map.findWithDefault [] a out)) out) addDefN out n igraph = let addEdgeNO o igraph = foldN o addEdgeNN igraph addEdgeNN n' igraph = addEdgeNN' n n' $ addEdgeNN' n' n igraph addEdgeNN' n n' igraph = Map.insert n (Map.insert n' () set) igraph where set = Map.findWithDefault Map.empty n igraph in Map.foldRightWithKey (\ _ os igraph -> foldr addEdgeNO igraph os) igraph out env' bid = mapLookup bid env `orElse` panic "unknown blockId in igraph" -- Before allocating stack slots, we need to collect one more piece of information: -- what's the highest offset (in bytes) used in each Area? -- We'll need to allocate that much space for each Area. -- Mapping of areas to area sizes (not offsets!) type AreaSizeMap = AreaMap -- JD: WHY CAN'T THIS COME FROM THE slot-liveness info? getAreaSize :: ByteOff -> CmmGraph -> AreaSizeMap -- The domain of the returned mapping consists only of Areas -- used for (a) variable spill slots, and (b) parameter passing areas for calls getAreaSize entry_off g = foldGraphBlocks (foldBlockNodesF3 (first, add_regslots, last)) (Map.singleton (CallArea Old) entry_off) g where first _ z = z last :: CmmNode O C -> Map Area Int -> Map Area Int last l@(CmmCall _ Nothing args res _) z = add_regslots l (add (add z area args) area res) where area = CallArea Old last l@(CmmCall _ (Just k) args res _) z = add_regslots l (add (add z area args) area res) where area = CallArea (Young k) last l@(CmmForeignCall {succ = k}) z = add_regslots l (add z area wORD_SIZE) where area = CallArea (Young k) last l z = add_regslots l z add_regslots i z = foldSlotsUsed addSlot (foldSlotsDefd addSlot z i) i addSlot z (a@(RegSlot (LocalReg _ ty)), _, _) = add z a $ widthInBytes $ typeWidth ty addSlot z _ = z add z a off = Map.insert a (max off (Map.findWithDefault 0 a z)) z -- The 'max' is important. Two calls, to f and g, might share a common -- continuation (and hence a common CallArea), but their number of overflow -- parameters might differ. -- EZY: Ought to use insert with combining function... -- Find the Stack slots occupied by the subarea's conflicts conflictSlots :: Ord x => IGPair x -> AreaSizeMap -> AreaMap -> SubArea -> Set Int conflictSlots (ig, Builder foldNodes wordsOccupied) areaSize areaMap subarea = foldNodes subarea foldNode Map.empty where foldNode n set = Map.foldRightWithKey conflict set $ Map.findWithDefault Map.empty n ig conflict n' () set = liveInSlots areaMap n' set -- Add stack slots occupied by igraph node n liveInSlots areaMap n set = foldr setAdd set (wordsOccupied areaSize areaMap n) setAdd w s = Map.insert w () s -- Find any open space for 'area' on the stack, starting from the -- 'offset'. If the area is a CallArea or a spill slot for a pointer, -- then it must be word-aligned. freeSlotFrom :: Ord x => IGPair x -> AreaSizeMap -> Int -> AreaMap -> Area -> Int freeSlotFrom ig areaSize offset areaMap area = let size = Map.lookup area areaSize `orElse` 0 conflicts = conflictSlots ig areaSize areaMap (area, size, size) -- CallAreas and Ptrs need to be word-aligned (round up!) align = case area of CallArea _ -> align' RegSlot r | isGcPtrType (localRegType r) -> align' RegSlot _ -> id align' n = (n + (wORD_SIZE - 1)) `div` wORD_SIZE * wORD_SIZE -- Find a space big enough to hold the area findSpace curr 0 = curr findSpace curr cnt = -- part of target slot, # of bytes left to check if Map.member curr conflicts then findSpace (align (curr + size)) size -- try the next (possibly) open space else findSpace (curr - 1) (cnt - 1) in findSpace (align (offset + size)) size -- Find an open space on the stack, and assign it to the area. allocSlotFrom :: Ord x => IGPair x -> AreaSizeMap -> Int -> AreaMap -> Area -> AreaMap allocSlotFrom ig areaSize from areaMap area = if Map.member area areaMap then areaMap else Map.insert area (freeSlotFrom ig areaSize from areaMap area) areaMap -- Figure out all of the offsets from the slot location; this will be -- non-zero for procpoints. type SpEntryMap = BlockEnv Int getSpEntryMap :: Int -> CmmGraph -> SpEntryMap getSpEntryMap entry_off g@(CmmGraph {g_entry = entry}) = foldGraphBlocks add_sp_off (mapInsert entry entry_off emptyBlockMap) g where add_sp_off :: CmmBlock -> BlockEnv Int -> BlockEnv Int add_sp_off b env = case lastNode b of CmmCall {cml_cont=Just succ, cml_ret_args=off} -> mapInsert succ off env CmmForeignCall {succ=succ} -> mapInsert succ wORD_SIZE env _ -> env -- | Greedy stack layout. -- Compute liveness, build the interference graph, and allocate slots for the areas. -- We visit each basic block in a (generally) forward order. -- At each instruction that names a register subarea r, we immediately allocate -- any available slot on the stack by the following procedure: -- 1. Find the sub-areas S that conflict with r -- 2. Find the stack slots used for S -- 3. Choose a contiguous stack space s not in S (s must be large enough to hold r) -- For a CallArea, we allocate the stack space only when we reach a function -- call that returns to the CallArea's blockId. -- Then, we allocate the Area subject to the following constraints: -- a) It must be younger than all the sub-areas that are live on entry to the block -- This constraint is only necessary for the successor of a call -- b) It must not overlap with any already-allocated Area with which it conflicts -- (ie at some point, not necessarily now, is live at the same time) -- Part (b) is just the 1,2,3 part above -- Note: The stack pointer only has to be younger than the youngest live stack slot -- at proc points. Otherwise, the stack pointer can point anywhere. layout :: ProcPointSet -> SpEntryMap -> SlotEnv -> ByteOff -> CmmGraph -> AreaMap -- The domain of the returned map includes an Area for EVERY block -- including each block that is not the successor of a call (ie is not a proc-point) -- That's how we return the info of what the SP should be at the entry of every non -- procpoint block. However, note that procpoint blocks have their -- /slot/ stored, which is not necessarily the value of the SP on entry -- to the block (in fact, it probably isn't, due to argument passing). -- See [Procpoint Sp offset] layout procPoints spEntryMap env entry_off g = let ig = (igraph areaBuilder env g, areaBuilder) env' bid = mapLookup bid env `orElse` panic "unknown blockId in igraph" areaSize = getAreaSize entry_off g -- Find the youngest live stack slot that has already been allocated youngest_live :: AreaMap -- Already allocated -> SubAreaSet -- Sub-areas live here -> ByteOff -- Offset of the youngest byte of any -- already-allocated, live sub-area youngest_live areaMap live = fold_subareas young_slot live 0 where young_slot (a, o, _) z = case Map.lookup a areaMap of Just top -> max z $ top + o Nothing -> z fold_subareas f m z = Map.foldRightWithKey (\_ s z -> foldr f z s) z m -- Allocate space for spill slots and call areas allocVarSlot = allocSlotFrom ig areaSize 0 -- Update the successor's incoming SP. setSuccSPs inSp bid areaMap = case (Map.lookup area areaMap , mapLookup bid (toBlockMap g)) of (Just _, _) -> areaMap -- succ already knows incoming SP (Nothing, Just _) -> if setMember bid procPoints then let young = youngest_live areaMap $ env' bid -- start = case returnOff stackInfo of Just b -> max b young -- Nothing -> young start = young -- maybe wrong, but I don't understand -- why the preceding is necessary... in allocSlotFrom ig areaSize start areaMap area else Map.insert area inSp areaMap (_, Nothing) -> panic "Block not found in cfg" where area = CallArea (Young bid) layoutAreas areaMap block = foldBlockNodesF3 (flip const, allocMid, allocLast (entryLabel block)) block areaMap allocMid m areaMap = foldSlotsDefd alloc' (foldSlotsUsed alloc' areaMap m) m allocLast bid l areaMap = foldr (setSuccSPs inSp) areaMap' (successors l) where inSp = slot + spOffset -- [Procpoint Sp offset] -- If it's not in the map, we should use our previous -- calculation unchanged. spOffset = mapLookup bid spEntryMap `orElse` 0 slot = expectJust "slot in" $ Map.lookup (CallArea (Young bid)) areaMap areaMap' = foldSlotsDefd alloc' (foldSlotsUsed alloc' areaMap l) l alloc' areaMap (a@(RegSlot _), _, _) = allocVarSlot areaMap a alloc' areaMap _ = areaMap initMap = Map.insert (CallArea (Young (g_entry g))) 0 . Map.insert (CallArea Old) 0 $ Map.empty areaMap = foldl layoutAreas initMap (postorderDfs g) in -- pprTrace "ProcPoints" (ppr procPoints) $ -- pprTrace "Area SizeMap" (ppr areaSize) $ -- pprTrace "Entry offset" (ppr entry_off) $ -- pprTrace "Area Map" (ppr areaMap) $ areaMap {- Note [Procpoint Sp offset] The calculation of inSp is a little tricky. (Un)fortunately, if you get it wrong, you will get inefficient but correct code. You know you've got it wrong if the generated stack pointer bounces up and down for no good reason. Why can't we just set inSp to the location of the slot? (This is what the code used to do.) The trouble is when we actually hit the proc point the start of the slot will not be the same as the actual Sp due to argument passing: a: I32[(young<b> + 4)] = cde; // Stack pointer is moved to young end (bottom) of young<b> for call // +-------+ // | arg 1 | // +-------+ <- Sp call (I32[foobar::I32])(...) returns to Just b (4) (4) with update frame 4; b: // After call, stack pointer is above the old end (top) of // young<b> (the difference is spOffset) // +-------+ <- Sp // | arg 1 | // +-------+ If we blithely set the Sp to be the same as the slot (the young end of young<b>), an adjustment will be necessary when we go to the next block. This is wasteful. So, instead, for the next block after a procpoint, the actual Sp should be set to the same as the true Sp when we just entered the procpoint. Then manifestSP will automatically do the right thing. Questions you may ask: 1. Why don't we need to change the mapping for the procpoint itself? Because manifestSP does its own calculation of the true stack value, manifestSP will notice the discrepancy between the actual stack pointer and the slot start, and adjust all of its memory accesses accordingly. So the only problem is when we adjust the Sp in preparation for the successor block; that's why this code is here and not in setSuccSPs. 2. Why don't we make the procpoint call area and the true offset match up? If we did that, we would never use memory above the true value of the stack pointer, thus wasting all of the stack we used to store arguments. You might think that some clever changes to the slot offsets, using negative offsets, might fix it, but this does not make semantic sense. 3. If manifestSP is already calculating the true stack value, why we can't do this trick inside manifestSP itself? The reason is that if two branches join with inconsistent SPs, one of them has to be fixed: we can't know what the fix should be without already knowing what the chosen location of SP is on the next successor. (This is the "succ already knows incoming SP" case), This calculation cannot be easily done in manifestSP, since it processes the nodes /backwards/. So we need to have figured this out before we hit manifestSP. -} -- After determining the stack layout, we can: -- 1. Replace references to stack Areas with addresses relative to the stack -- pointer. -- 2. Insert adjustments to the stack pointer to ensure that it is at a -- conventional location at each proc point. -- Because we don't take interrupts on the execution stack, we only need the -- stack pointer to be younger than the live values on the stack at proc points. -- 3. Compute the maximum stack offset used in the procedure and replace -- the stack high-water mark with that offset. manifestSP :: SpEntryMap -> AreaMap -> ByteOff -> CmmGraph -> FuelUniqSM CmmGraph manifestSP spEntryMap areaMap entry_off g@(CmmGraph {g_entry=entry}) = ofBlockMap entry `liftM` foldl replB (return mapEmpty) (postorderDfs g) where slot a = -- pprTrace "slot" (ppr a) $ Map.lookup a areaMap `orElse` panic "unallocated Area" slot' (Just id) = slot $ CallArea (Young id) slot' Nothing = slot $ CallArea Old sp_high = maxSlot slot g proc_entry_sp = slot (CallArea Old) + entry_off spOffset id = mapLookup id spEntryMap `orElse` 0 sp_on_entry id | id == entry = proc_entry_sp sp_on_entry id = slot' (Just id) + spOffset id -- On entry to procpoints, the stack pointer is conventional; -- otherwise, we check the SP set by predecessors. replB :: FuelUniqSM (BlockEnv CmmBlock) -> CmmBlock -> FuelUniqSM (BlockEnv CmmBlock) replB blocks block = do let (head, middles, JustC tail :: MaybeC C (CmmNode O C)) = blockToNodeList block middles' = map (middle spIn) middles bs <- replLast head middles' tail flip (foldr insertBlock) bs `liftM` blocks where spIn = sp_on_entry (entryLabel block) middle spOff m = mapExpDeep (replSlot spOff) m -- XXX there shouldn't be any global registers in the -- CmmCall, so there shouldn't be any slots in -- CmmCall... check that... last spOff l = mapExpDeep (replSlot spOff) l replSlot spOff (CmmStackSlot a i) = CmmRegOff (CmmGlobal Sp) (spOff - (slot a + i)) replSlot _ (CmmLit CmmHighStackMark) = -- replacing the high water mark CmmLit (CmmInt (toInteger (max 0 (sp_high - proc_entry_sp))) (typeWidth bWord)) -- Invariant: Sp is always greater than SpLim. Thus, if -- the high water mark is zero, we can optimize away the -- conditional branch. Relies on dead code elimination -- to get rid of the dead GC blocks. -- EZY: Maybe turn this into a guard that checks if a -- statement is stack-check ish? Maybe we should make -- an actual mach-op for it, so there's no chance of -- mixing this up with something else... replSlot _ (CmmMachOp (MO_U_Lt _) [CmmMachOp (MO_Sub _) [ CmmReg (CmmGlobal Sp) , CmmLit (CmmInt 0 _)], CmmReg (CmmGlobal SpLim)]) = CmmLit (CmmInt 0 wordWidth) replSlot _ e = e replLast :: MaybeC C (CmmNode C O) -> [CmmNode O O] -> CmmNode O C -> FuelUniqSM [CmmBlock] replLast h m l@(CmmCall _ k n _ _) = updSp (slot' k + n) h m l -- JD: LastForeignCall probably ought to have an outgoing -- arg size, just like LastCall replLast h m l@(CmmForeignCall {succ=k}) = updSp (slot' (Just k) + wORD_SIZE) h m l replLast h m l@(CmmBranch k) = updSp (sp_on_entry k) h m l replLast h m l = uncurry (:) `liftM` foldr succ (return (b, [])) (successors l) where b :: CmmBlock b = updSp' spIn h m l succ succId z = let succSp = sp_on_entry succId in if succSp /= spIn then do (b, bs) <- z (b', bs') <- insertBetween b (adjustSp succSp) succId return (b', bs' ++ bs) else z updSp sp h m l = return [updSp' sp h m l] updSp' sp h m l | sp == spIn = blockOfNodeList (h, m, JustC $ last sp l) | otherwise = blockOfNodeList (h, m ++ adjustSp sp, JustC $ last sp l) adjustSp sp = [CmmAssign (CmmGlobal Sp) e] where e = CmmMachOp (MO_Add wordWidth) [CmmReg (CmmGlobal Sp), off] off = CmmLit $ CmmInt (toInteger $ spIn - sp) wordWidth -- To compute the stack high-water mark, we fold over the graph and -- compute the highest slot offset. maxSlot :: (Area -> Int) -> CmmGraph -> Int maxSlot slotOff g = foldGraphBlocks (foldBlockNodesF3 (flip const, highSlot, highSlot)) 0 g where highSlot i z = foldSlotsUsed add (foldSlotsDefd add z i) i add z (a, i, _) = max z (slotOff a + i) ----------------------------------------------------------------------------- -- | Sanity check: stub pointers immediately after they die ----------------------------------------------------------------------------- -- This will miss stack slots that are last used in a Last node, -- but it should do pretty well... stubSlotsOnDeath :: CmmGraph -> FuelUniqSM CmmGraph stubSlotsOnDeath g = liftM fst $ dataflowPassBwd g [] $ analRewBwd slotLattice liveSlotTransfers rewrites where rewrites = mkBRewrite3 frt mid lst frt _ _ = return Nothing mid m liveSlots = return $ foldSlotsUsed (stub liveSlots m) Nothing m lst _ _ = return Nothing stub liveSlots m rst subarea@(a, off, w) = if elemSlot liveSlots subarea then rst else let store = mkMiddle $ CmmStore (CmmStackSlot a off) (stackStubExpr (widthFromBytes w)) in case rst of Nothing -> Just (mkMiddle m <*> store) Just g -> Just (g <*> store)
mcmaniac/ghc
compiler/cmm/CmmStackLayout.hs
bsd-3-clause
30,511
1
19
8,747
6,265
3,297
2,968
-1
-1
module TestTypes ( IncPK(..) , CompoundPK(..) ) where import qualified Data.Aeson as JSON import Data.Aeson ((.:)) import Protolude data IncPK = IncPK { incId :: Int , incNullableStr :: Maybe Text , incStr :: Text , incInsert :: Text } deriving (Eq, Show) instance JSON.FromJSON IncPK where parseJSON (JSON.Object r) = IncPK <$> r .: "id" <*> r .: "nullable_string" <*> r .: "non_nullable_string" <*> r .: "inserted_at" parseJSON _ = mzero data CompoundPK = CompoundPK { compoundK1 :: Int , compoundK2 :: Text , compoundExtra :: Maybe Int } deriving (Eq, Show) instance JSON.FromJSON CompoundPK where parseJSON (JSON.Object r) = CompoundPK <$> r .: "k1" <*> r .: "k2" <*> r .: "extra" parseJSON _ = mzero
Skyfold/postgrest
test/TestTypes.hs
mit
753
0
13
166
255
144
111
30
0
<?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="sl-SI"> <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_sl_SI/helpset_sl_SI.hs
apache-2.0
966
82
53
157
396
209
187
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ja-JP"> <title>DOM XSS Active Scan Rule | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>コンテンツ</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>インデックス</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>検索</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>お気に入り</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/domxss/src/main/javahelp/org/zaproxy/zap/extension/domxss/resources/help_ja_JP/helpset_ja_JP.hs
apache-2.0
1,011
91
49
162
395
208
187
-1
-1
----------------------------------------------------------------------------- -- | -- Module : Text.ParserCombinators.Parsec.Prim -- Copyright : (c) Paolo Martini 2007 -- License : BSD-style (see the LICENSE file) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Parsec compatibility module -- ----------------------------------------------------------------------------- module Text.ParserCombinators.Parsec.Prim ( (<?>), (<|>), Parser, GenParser, runParser, parse, parseFromFile, parseTest, token, tokens, tokenPrim, tokenPrimEx, try, label, labels, unexpected, pzero, many, skipMany, getState, setState, updateState, getPosition, setPosition, getInput, setInput, State(..), getParserState, setParserState ) where import Text.Parsec.Prim hiding (runParser, try) import qualified Text.Parsec.Prim as N -- 'N' for 'New' import Text.Parsec.String import Text.Parsec.Error import Text.Parsec.Pos pzero :: GenParser tok st a pzero = parserZero runParser :: GenParser tok st a -> st -> SourceName -> [tok] -> Either ParseError a runParser = N.runParser try :: GenParser tok st a -> GenParser tok st a try = N.try
maurer/15-411-Haskell-Base-Code
src/Text/ParserCombinators/Parsec/Prim.hs
bsd-3-clause
1,408
0
9
383
251
161
90
45
1
{- (c) The AQUA Project, Glasgow University, 1993-1998 \section[SimplUtils]{The simplifier utilities} -} {-# LANGUAGE CPP #-} module SimplUtils ( -- Rebuilding mkLam, mkCase, prepareAlts, tryEtaExpandRhs, -- Inlining, preInlineUnconditionally, postInlineUnconditionally, activeUnfolding, activeRule, getUnfoldingInRuleMatch, simplEnvForGHCi, updModeForStableUnfoldings, updModeForRuleLHS, -- The continuation type SimplCont(..), DupFlag(..), isSimplified, contIsDupable, contResultType, contHoleType, contIsTrivial, contArgs, countValArgs, countArgs, mkBoringStop, mkRhsStop, mkLazyArgStop, contIsRhsOrArg, interestingCallContext, -- ArgInfo ArgInfo(..), ArgSpec(..), mkArgInfo, addValArgTo, addCastTo, addTyArgTo, argInfoExpr, argInfoAppArgs, pushSimplifiedArgs, abstractFloats ) where #include "HsVersions.h" import SimplEnv import CoreMonad ( SimplifierMode(..), Tick(..) ) import MkCore ( sortQuantVars ) import DynFlags import CoreSyn import qualified CoreSubst import PprCore import CoreFVs import CoreUtils import CoreArity import CoreUnfold import Name import Id import Var import Demand import SimplMonad import Type hiding( substTy ) import Coercion hiding( substCo, substTy ) import DataCon ( dataConWorkId ) import VarEnv import VarSet import BasicTypes import Util import MonadUtils import Outputable import FastString import Pair import Control.Monad ( when ) {- ************************************************************************ * * The SimplCont and DupFlag types * * ************************************************************************ A SimplCont allows the simplifier to traverse the expression in a zipper-like fashion. The SimplCont represents the rest of the expression, "above" the point of interest. You can also think of a SimplCont as an "evaluation context", using that term in the way it is used for operational semantics. This is the way I usually think of it, For example you'll often see a syntax for evaluation context looking like C ::= [] | C e | case C of alts | C `cast` co That's the kind of thing we are doing here, and I use that syntax in the comments. Key points: * A SimplCont describes a *strict* context (just like evaluation contexts do). E.g. Just [] is not a SimplCont * A SimplCont describes a context that *does not* bind any variables. E.g. \x. [] is not a SimplCont -} data SimplCont = Stop -- An empty context, or <hole> OutType -- Type of the <hole> CallCtxt -- Tells if there is something interesting about -- the context, and hence the inliner -- should be a bit keener (see interestingCallContext) -- Specifically: -- This is an argument of a function that has RULES -- Inlining the call might allow the rule to fire -- Never ValAppCxt (use ApplyToVal instead) -- or CaseCtxt (use Select instead) | CastIt -- <hole> `cast` co OutCoercion -- The coercion simplified -- Invariant: never an identity coercion SimplCont | ApplyToVal { -- <hole> arg sc_dup :: DupFlag, -- See Note [DupFlag invariants] sc_arg :: InExpr, -- The argument, sc_env :: StaticEnv, -- and its static env sc_cont :: SimplCont } | ApplyToTy { -- <hole> ty sc_arg_ty :: OutType, -- Argument type sc_hole_ty :: OutType, -- Type of the function, presumably (forall a. blah) -- See Note [The hole type in ApplyToTy] sc_cont :: SimplCont } | Select { -- case <hole> of alts sc_dup :: DupFlag, -- See Note [DupFlag invariants] sc_bndr :: InId, -- case binder sc_alts :: [InAlt], -- Alternatives sc_env :: StaticEnv, -- and their static environment sc_cont :: SimplCont } -- The two strict forms have no DupFlag, because we never duplicate them | StrictBind -- (\x* \xs. e) <hole> InId [InBndr] -- let x* = <hole> in e InExpr StaticEnv -- is a special case SimplCont | StrictArg -- f e1 ..en <hole> ArgInfo -- Specifies f, e1..en, Whether f has rules, etc -- plus strictness flags for *further* args CallCtxt -- Whether *this* argument position is interesting SimplCont | TickIt (Tickish Id) -- Tick tickish <hole> SimplCont data DupFlag = NoDup -- Unsimplified, might be big | Simplified -- Simplified | OkToDup -- Simplified and small isSimplified :: DupFlag -> Bool isSimplified NoDup = False isSimplified _ = True -- Invariant: the subst-env is empty perhapsSubstTy :: DupFlag -> StaticEnv -> Type -> Type perhapsSubstTy dup env ty | isSimplified dup = ty | otherwise = substTy env ty {- Note [DupFlag invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~ In both (ApplyToVal dup _ env k) and (Select dup _ _ env k) the following invariants hold (a) if dup = OkToDup, then continuation k is also ok-to-dup (b) if dup = OkToDup or Simplified, the subst-env is empty (and and hence no need to re-simplify) -} instance Outputable DupFlag where ppr OkToDup = ptext (sLit "ok") ppr NoDup = ptext (sLit "nodup") ppr Simplified = ptext (sLit "simpl") instance Outputable SimplCont where ppr (Stop ty interesting) = ptext (sLit "Stop") <> brackets (ppr interesting) <+> ppr ty ppr (CastIt co cont ) = (ptext (sLit "CastIt") <+> ppr co) $$ ppr cont ppr (TickIt t cont) = (ptext (sLit "TickIt") <+> ppr t) $$ ppr cont ppr (ApplyToTy { sc_arg_ty = ty, sc_cont = cont }) = (ptext (sLit "ApplyToTy") <+> pprParendType ty) $$ ppr cont ppr (ApplyToVal { sc_arg = arg, sc_dup = dup, sc_cont = cont }) = (ptext (sLit "ApplyToVal") <+> ppr dup <+> pprParendExpr arg) $$ ppr cont ppr (StrictBind b _ _ _ cont) = (ptext (sLit "StrictBind") <+> ppr b) $$ ppr cont ppr (StrictArg ai _ cont) = (ptext (sLit "StrictArg") <+> ppr (ai_fun ai)) $$ ppr cont ppr (Select { sc_dup = dup, sc_bndr = bndr, sc_alts = alts, sc_env = se, sc_cont = cont }) = (ptext (sLit "Select") <+> ppr dup <+> ppr bndr) $$ ifPprDebug (nest 2 $ vcat [ppr (seTvSubst se), ppr alts]) $$ ppr cont {- Note [The hole type in ApplyToTy] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The sc_hole_ty field of ApplyToTy records the type of the "hole" in the continuation. It is absolutely necessary to compute contHoleType, but it is not used for anything else (and hence may not be evaluated). Why is it necessary for contHoleType? Consider the continuation ApplyToType Int (Stop Int) corresponding to (<hole> @Int) :: Int What is the type of <hole>? It could be (forall a. Int) or (forall a. a), and there is no way to know which, so we must record it. In a chain of applications (f @t1 @t2 @t3) we'll lazily compute exprType for (f @t1) and (f @t1 @t2), which is potentially non-linear; but it probably doesn't matter because we'll never compute them all. ************************************************************************ * * ArgInfo and ArgSpec * * ************************************************************************ -} data ArgInfo = ArgInfo { ai_fun :: OutId, -- The function ai_args :: [ArgSpec], -- ...applied to these args (which are in *reverse* order) ai_type :: OutType, -- Type of (f a1 ... an) ai_rules :: [CoreRule], -- Rules for this function ai_encl :: Bool, -- Flag saying whether this function -- or an enclosing one has rules (recursively) -- True => be keener to inline in all args ai_strs :: [Bool], -- Strictness of remaining arguments -- Usually infinite, but if it is finite it guarantees -- that the function diverges after being given -- that number of args ai_discs :: [Int] -- Discounts for remaining arguments; non-zero => be keener to inline -- Always infinite } data ArgSpec = ValArg OutExpr -- Apply to this (coercion or value); c.f. ApplyToVal | TyArg { as_arg_ty :: OutType -- Apply to this type; c.f. ApplyToTy , as_hole_ty :: OutType } -- Type of the function (presumably forall a. blah) | CastBy OutCoercion -- Cast by this; c.f. CastIt instance Outputable ArgSpec where ppr (ValArg e) = ptext (sLit "ValArg") <+> ppr e ppr (TyArg { as_arg_ty = ty }) = ptext (sLit "TyArg") <+> ppr ty ppr (CastBy c) = ptext (sLit "CastBy") <+> ppr c addValArgTo :: ArgInfo -> OutExpr -> ArgInfo addValArgTo ai arg = ai { ai_args = ValArg arg : ai_args ai , ai_type = funResultTy (ai_type ai) } addTyArgTo :: ArgInfo -> OutType -> ArgInfo addTyArgTo ai arg_ty = ai { ai_args = arg_spec : ai_args ai , ai_type = applyTy poly_fun_ty arg_ty } where poly_fun_ty = ai_type ai arg_spec = TyArg { as_arg_ty = arg_ty, as_hole_ty = poly_fun_ty } addCastTo :: ArgInfo -> OutCoercion -> ArgInfo addCastTo ai co = ai { ai_args = CastBy co : ai_args ai , ai_type = pSnd (coercionKind co) } argInfoAppArgs :: [ArgSpec] -> [OutExpr] argInfoAppArgs [] = [] argInfoAppArgs (CastBy {} : _) = [] -- Stop at a cast argInfoAppArgs (ValArg e : as) = e : argInfoAppArgs as argInfoAppArgs (TyArg { as_arg_ty = ty } : as) = Type ty : argInfoAppArgs as pushSimplifiedArgs :: SimplEnv -> [ArgSpec] -> SimplCont -> SimplCont pushSimplifiedArgs _env [] k = k pushSimplifiedArgs env (arg : args) k = case arg of TyArg { as_arg_ty = arg_ty, as_hole_ty = hole_ty } -> ApplyToTy { sc_arg_ty = arg_ty, sc_hole_ty = hole_ty, sc_cont = rest } ValArg e -> ApplyToVal { sc_arg = e, sc_env = env, sc_dup = Simplified, sc_cont = rest } CastBy c -> CastIt c rest where rest = pushSimplifiedArgs env args k -- The env has an empty SubstEnv argInfoExpr :: OutId -> [ArgSpec] -> OutExpr -- NB: the [ArgSpec] is reversed so that the first arg -- in the list is the last one in the application argInfoExpr fun rev_args = go rev_args where go [] = Var fun go (ValArg a : as) = go as `App` a go (TyArg { as_arg_ty = ty } : as) = go as `App` Type ty go (CastBy co : as) = mkCast (go as) co {- ************************************************************************ * * Functions on SimplCont * * ************************************************************************ -} mkBoringStop :: OutType -> SimplCont mkBoringStop ty = Stop ty BoringCtxt mkRhsStop :: OutType -> SimplCont -- See Note [RHS of lets] in CoreUnfold mkRhsStop ty = Stop ty RhsCtxt mkLazyArgStop :: OutType -> CallCtxt -> SimplCont mkLazyArgStop ty cci = Stop ty cci ------------------- contIsRhsOrArg :: SimplCont -> Bool contIsRhsOrArg (Stop {}) = True contIsRhsOrArg (StrictBind {}) = True contIsRhsOrArg (StrictArg {}) = True contIsRhsOrArg _ = False contIsRhs :: SimplCont -> Bool contIsRhs (Stop _ RhsCtxt) = True contIsRhs _ = False ------------------- contIsDupable :: SimplCont -> Bool contIsDupable (Stop {}) = True contIsDupable (ApplyToTy { sc_cont = k }) = contIsDupable k contIsDupable (ApplyToVal { sc_dup = OkToDup }) = True -- See Note [DupFlag invariants] contIsDupable (Select { sc_dup = OkToDup }) = True -- ...ditto... contIsDupable (CastIt _ k) = contIsDupable k contIsDupable _ = False ------------------- contIsTrivial :: SimplCont -> Bool contIsTrivial (Stop {}) = True contIsTrivial (ApplyToTy { sc_cont = k }) = contIsTrivial k contIsTrivial (ApplyToVal { sc_arg = Coercion _, sc_cont = k }) = contIsTrivial k contIsTrivial (CastIt _ k) = contIsTrivial k contIsTrivial _ = False ------------------- contResultType :: SimplCont -> OutType contResultType (Stop ty _) = ty contResultType (CastIt _ k) = contResultType k contResultType (StrictBind _ _ _ _ k) = contResultType k contResultType (StrictArg _ _ k) = contResultType k contResultType (Select { sc_cont = k }) = contResultType k contResultType (ApplyToTy { sc_cont = k }) = contResultType k contResultType (ApplyToVal { sc_cont = k }) = contResultType k contResultType (TickIt _ k) = contResultType k contHoleType :: SimplCont -> OutType contHoleType (Stop ty _) = ty contHoleType (TickIt _ k) = contHoleType k contHoleType (CastIt co _) = pFst (coercionKind co) contHoleType (StrictBind b _ _ se _) = substTy se (idType b) contHoleType (StrictArg ai _ _) = funArgTy (ai_type ai) contHoleType (ApplyToTy { sc_hole_ty = ty }) = ty -- See Note [The hole type in ApplyToTy] contHoleType (ApplyToVal { sc_arg = e, sc_env = se, sc_dup = dup, sc_cont = k }) = mkFunTy (perhapsSubstTy dup se (exprType e)) (contHoleType k) contHoleType (Select { sc_dup = d, sc_bndr = b, sc_env = se }) = perhapsSubstTy d se (idType b) ------------------- countValArgs :: SimplCont -> Int -- Count value arguments excluding coercions countValArgs (ApplyToVal { sc_arg = arg, sc_cont = cont }) | Coercion {} <- arg = countValArgs cont | otherwise = 1 + countValArgs cont countValArgs _ = 0 countArgs :: SimplCont -> Int -- Count all arguments, including types, coercions, and other values countArgs (ApplyToTy { sc_cont = cont }) = 1 + countArgs cont countArgs (ApplyToVal { sc_cont = cont }) = 1 + countArgs cont countArgs _ = 0 contArgs :: SimplCont -> (Bool, [ArgSummary], SimplCont) -- Summarises value args, discards type args and coercions -- The returned continuation of the call is only used to -- answer questions like "are you interesting?" contArgs cont | lone cont = (True, [], cont) | otherwise = go [] cont where lone (ApplyToTy {}) = False -- See Note [Lone variables] in CoreUnfold lone (ApplyToVal {}) = False lone (CastIt {}) = False lone _ = True go args (ApplyToVal { sc_arg = arg, sc_env = se, sc_cont = k }) = go (is_interesting arg se : args) k go args (ApplyToTy { sc_cont = k }) = go args k go args (CastIt _ k) = go args k go args k = (False, reverse args, k) is_interesting arg se = interestingArg se arg -- Do *not* use short-cutting substitution here -- because we want to get as much IdInfo as possible ------------------- mkArgInfo :: Id -> [CoreRule] -- Rules for function -> Int -- Number of value args -> SimplCont -- Context of the call -> ArgInfo mkArgInfo fun rules n_val_args call_cont | n_val_args < idArity fun -- Note [Unsaturated functions] = ArgInfo { ai_fun = fun, ai_args = [], ai_type = fun_ty , ai_rules = rules, ai_encl = False , ai_strs = vanilla_stricts , ai_discs = vanilla_discounts } | otherwise = ArgInfo { ai_fun = fun, ai_args = [], ai_type = fun_ty , ai_rules = rules , ai_encl = interestingArgContext rules call_cont , ai_strs = add_type_str fun_ty arg_stricts , ai_discs = arg_discounts } where fun_ty = idType fun vanilla_discounts, arg_discounts :: [Int] vanilla_discounts = repeat 0 arg_discounts = case idUnfolding fun of CoreUnfolding {uf_guidance = UnfIfGoodArgs {ug_args = discounts}} -> discounts ++ vanilla_discounts _ -> vanilla_discounts vanilla_stricts, arg_stricts :: [Bool] vanilla_stricts = repeat False arg_stricts = case splitStrictSig (idStrictness fun) of (demands, result_info) | not (demands `lengthExceeds` n_val_args) -> -- Enough args, use the strictness given. -- For bottoming functions we used to pretend that the arg -- is lazy, so that we don't treat the arg as an -- interesting context. This avoids substituting -- top-level bindings for (say) strings into -- calls to error. But now we are more careful about -- inlining lone variables, so its ok (see SimplUtils.analyseCont) if isBotRes result_info then map isStrictDmd demands -- Finite => result is bottom else map isStrictDmd demands ++ vanilla_stricts | otherwise -> WARN( True, text "More demands than arity" <+> ppr fun <+> ppr (idArity fun) <+> ppr n_val_args <+> ppr demands ) vanilla_stricts -- Not enough args, or no strictness add_type_str :: Type -> [Bool] -> [Bool] -- If the function arg types are strict, record that in the 'strictness bits' -- No need to instantiate because unboxed types (which dominate the strict -- types) can't instantiate type variables. -- add_type_str is done repeatedly (for each call); might be better -- once-for-all in the function -- But beware primops/datacons with no strictness add_type_str _ [] = [] add_type_str fun_ty strs -- Look through foralls | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty -- Includes coercions = add_type_str fun_ty' strs add_type_str fun_ty (str:strs) -- Add strict-type info | Just (arg_ty, fun_ty') <- splitFunTy_maybe fun_ty = (str || isStrictType arg_ty) : add_type_str fun_ty' strs add_type_str _ strs = strs {- Note [Unsaturated functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider (test eyeball/inline4) x = a:as y = f x where f has arity 2. Then we do not want to inline 'x', because it'll just be floated out again. Even if f has lots of discounts on its first argument -- it must be saturated for these to kick in -} {- ************************************************************************ * * Interesting arguments * * ************************************************************************ Note [Interesting call context] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We want to avoid inlining an expression where there can't possibly be any gain, such as in an argument position. Hence, if the continuation is interesting (eg. a case scrutinee, application etc.) then we inline, otherwise we don't. Previously some_benefit used to return True only if the variable was applied to some value arguments. This didn't work: let x = _coerce_ (T Int) Int (I# 3) in case _coerce_ Int (T Int) x of I# y -> .... we want to inline x, but can't see that it's a constructor in a case scrutinee position, and some_benefit is False. Another example: dMonadST = _/\_ t -> :Monad (g1 _@_ t, g2 _@_ t, g3 _@_ t) .... case dMonadST _@_ x0 of (a,b,c) -> .... we'd really like to inline dMonadST here, but we *don't* want to inline if the case expression is just case x of y { DEFAULT -> ... } since we can just eliminate this case instead (x is in WHNF). Similar applies when x is bound to a lambda expression. Hence contIsInteresting looks for case expressions with just a single default case. -} interestingCallContext :: SimplCont -> CallCtxt -- See Note [Interesting call context] interestingCallContext cont = interesting cont where interesting (Select {}) = CaseCtxt interesting (ApplyToVal {}) = ValAppCtxt -- Can happen if we have (f Int |> co) y -- If f has an INLINE prag we need to give it some -- motivation to inline. See Note [Cast then apply] -- in CoreUnfold interesting (StrictArg _ cci _) = cci interesting (StrictBind {}) = BoringCtxt interesting (Stop _ cci) = cci interesting (TickIt _ k) = interesting k interesting (ApplyToTy { sc_cont = k }) = interesting k interesting (CastIt _ k) = interesting k -- If this call is the arg of a strict function, the context -- is a bit interesting. If we inline here, we may get useful -- evaluation information to avoid repeated evals: e.g. -- x + (y * z) -- Here the contIsInteresting makes the '*' keener to inline, -- which in turn exposes a constructor which makes the '+' inline. -- Assuming that +,* aren't small enough to inline regardless. -- -- It's also very important to inline in a strict context for things -- like -- foldr k z (f x) -- Here, the context of (f x) is strict, and if f's unfolding is -- a build it's *great* to inline it here. So we must ensure that -- the context for (f x) is not totally uninteresting. interestingArgContext :: [CoreRule] -> SimplCont -> Bool -- If the argument has form (f x y), where x,y are boring, -- and f is marked INLINE, then we don't want to inline f. -- But if the context of the argument is -- g (f x y) -- where g has rules, then we *do* want to inline f, in case it -- exposes a rule that might fire. Similarly, if the context is -- h (g (f x x)) -- where h has rules, then we do want to inline f; hence the -- call_cont argument to interestingArgContext -- -- The ai-rules flag makes this happen; if it's -- set, the inliner gets just enough keener to inline f -- regardless of how boring f's arguments are, if it's marked INLINE -- -- The alternative would be to *always* inline an INLINE function, -- regardless of how boring its context is; but that seems overkill -- For example, it'd mean that wrapper functions were always inlined -- -- The call_cont passed to interestingArgContext is the context of -- the call itself, e.g. g <hole> in the example above interestingArgContext rules call_cont = notNull rules || enclosing_fn_has_rules where enclosing_fn_has_rules = go call_cont go (Select {}) = False go (ApplyToVal {}) = False -- Shouldn't really happen go (ApplyToTy {}) = False -- Ditto go (StrictArg _ cci _) = interesting cci go (StrictBind {}) = False -- ?? go (CastIt _ c) = go c go (Stop _ cci) = interesting cci go (TickIt _ c) = go c interesting RuleArgCtxt = True interesting _ = False {- Note [Interesting arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ An argument is interesting if it deserves a discount for unfoldings with a discount in that argument position. The idea is to avoid unfolding a function that is applied only to variables that have no unfolding (i.e. they are probably lambda bound): f x y z There is little point in inlining f here. Generally, *values* (like (C a b) and (\x.e)) deserve discounts. But we must look through lets, eg (let x = e in C a b), because the let will float, exposing the value, if we inline. That makes it different to exprIsHNF. Before 2009 we said it was interesting if the argument had *any* structure at all; i.e. (hasSomeUnfolding v). But does too much inlining; see Trac #3016. But we don't regard (f x y) as interesting, unless f is unsaturated. If it's saturated and f hasn't inlined, then it's probably not going to now! Note [Conlike is interesting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f d = ...((*) d x y)... ... f (df d')... where df is con-like. Then we'd really like to inline 'f' so that the rule for (*) (df d) can fire. To do this a) we give a discount for being an argument of a class-op (eg (*) d) b) we say that a con-like argument (eg (df d)) is interesting -} interestingArg :: SimplEnv -> CoreExpr -> ArgSummary -- See Note [Interesting arguments] interestingArg env e = go env 0 e where -- n is # value args to which the expression is applied go env n (Var v) | SimplEnv { seIdSubst = ids, seInScope = in_scope } <- env = case lookupVarEnv ids v of Nothing -> go_var n (refineFromInScope in_scope v) Just (DoneId v') -> go_var n (refineFromInScope in_scope v') Just (DoneEx e) -> go (zapSubstEnv env) n e Just (ContEx tvs cvs ids e) -> go (setSubstEnv env tvs cvs ids) n e go _ _ (Lit {}) = ValueArg go _ _ (Type _) = TrivArg go _ _ (Coercion _) = TrivArg go env n (App fn (Type _)) = go env n fn go env n (App fn (Coercion _)) = go env n fn go env n (App fn _) = go env (n+1) fn go env n (Tick _ a) = go env n a go env n (Cast e _) = go env n e go env n (Lam v e) | isTyVar v = go env n e | n>0 = go env (n-1) e | otherwise = ValueArg go env n (Let _ e) = case go env n e of { ValueArg -> ValueArg; _ -> NonTrivArg } go _ _ (Case {}) = NonTrivArg go_var n v | isConLikeId v = ValueArg -- Experimenting with 'conlike' rather that -- data constructors here | idArity v > n = ValueArg -- Catches (eg) primops with arity but no unfolding | n > 0 = NonTrivArg -- Saturated or unknown call | conlike_unfolding = ValueArg -- n==0; look for an interesting unfolding -- See Note [Conlike is interesting] | otherwise = TrivArg -- n==0, no useful unfolding where conlike_unfolding = isConLikeUnfolding (idUnfolding v) {- ************************************************************************ * * SimplifierMode * * ************************************************************************ The SimplifierMode controls several switches; see its definition in CoreMonad sm_rules :: Bool -- Whether RULES are enabled sm_inline :: Bool -- Whether inlining is enabled sm_case_case :: Bool -- Whether case-of-case is enabled sm_eta_expand :: Bool -- Whether eta-expansion is enabled -} simplEnvForGHCi :: DynFlags -> SimplEnv simplEnvForGHCi dflags = mkSimplEnv $ SimplMode { sm_names = ["GHCi"] , sm_phase = InitialPhase , sm_rules = rules_on , sm_inline = False , sm_eta_expand = eta_expand_on , sm_case_case = True } where rules_on = gopt Opt_EnableRewriteRules dflags eta_expand_on = gopt Opt_DoLambdaEtaExpansion dflags -- Do not do any inlining, in case we expose some unboxed -- tuple stuff that confuses the bytecode interpreter updModeForStableUnfoldings :: Activation -> SimplifierMode -> SimplifierMode -- See Note [Simplifying inside stable unfoldings] updModeForStableUnfoldings inline_rule_act current_mode = current_mode { sm_phase = phaseFromActivation inline_rule_act , sm_inline = True , sm_eta_expand = False } -- For sm_rules, just inherit; sm_rules might be "off" -- because of -fno-enable-rewrite-rules where phaseFromActivation (ActiveAfter n) = Phase n phaseFromActivation _ = InitialPhase updModeForRuleLHS :: SimplifierMode -> SimplifierMode -- See Note [Simplifying rule LHSs] updModeForRuleLHS current_mode = current_mode { sm_phase = InitialPhase , sm_inline = False , sm_rules = False , sm_eta_expand = False } {- Note [Simplifying rule LHSs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When simplifying on the LHS of a rule, refrain from all inlining and all RULES. Doing anything to the LHS is plain confusing, because it means that what the rule matches is not what the user wrote. c.f. Trac #10595, and #10528. Moreover, inlining (or applying rules) on rule LHSs risks introducing Ticks into the LHS, which makes matching trickier. Trac #10665, #10745. Note [Inlining in gentle mode] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Something is inlined if (i) the sm_inline flag is on, AND (ii) the thing has an INLINE pragma, AND (iii) the thing is inlinable in the earliest phase. Example of why (iii) is important: {-# INLINE [~1] g #-} g = ... {-# INLINE f #-} f x = g (g x) If we were to inline g into f's inlining, then an importing module would never be able to do f e --> g (g e) ---> RULE fires because the stable unfolding for f has had g inlined into it. On the other hand, it is bad not to do ANY inlining into an stable unfolding, because then recursive knots in instance declarations don't get unravelled. However, *sometimes* SimplGently must do no call-site inlining at all (hence sm_inline = False). Before full laziness we must be careful not to inline wrappers, because doing so inhibits floating e.g. ...(case f x of ...)... ==> ...(case (case x of I# x# -> fw x#) of ...)... ==> ...(case x of I# x# -> case fw x# of ...)... and now the redex (f x) isn't floatable any more. The no-inlining thing is also important for Template Haskell. You might be compiling in one-shot mode with -O2; but when TH compiles a splice before running it, we don't want to use -O2. Indeed, we don't want to inline anything, because the byte-code interpreter might get confused about unboxed tuples and suchlike. Note [Simplifying inside stable unfoldings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We must take care with simplification inside stable unfoldings (which come from INLINE pragmas). First, consider the following example let f = \pq -> BIG in let g = \y -> f y y {-# INLINE g #-} in ...g...g...g...g...g... Now, if that's the ONLY occurrence of f, it might be inlined inside g, and thence copied multiple times when g is inlined. HENCE we treat any occurrence in a stable unfolding as a multiple occurrence, not a single one; see OccurAnal.addRuleUsage. Second, we do want *do* to some modest rules/inlining stuff in stable unfoldings, partly to eliminate senseless crap, and partly to break the recursive knots generated by instance declarations. However, suppose we have {-# INLINE <act> f #-} f = <rhs> meaning "inline f in phases p where activation <act>(p) holds". Then what inlinings/rules can we apply to the copy of <rhs> captured in f's stable unfolding? Our model is that literally <rhs> is substituted for f when it is inlined. So our conservative plan (implemented by updModeForStableUnfoldings) is this: ------------------------------------------------------------- When simplifying the RHS of an stable unfolding, set the phase to the phase in which the stable unfolding first becomes active ------------------------------------------------------------- That ensures that a) Rules/inlinings that *cease* being active before p will not apply to the stable unfolding, consistent with it being inlined in its *original* form in phase p. b) Rules/inlinings that only become active *after* p will not apply to the stable unfolding, again to be consistent with inlining the *original* rhs in phase p. For example, {-# INLINE f #-} f x = ...g... {-# NOINLINE [1] g #-} g y = ... {-# RULE h g = ... #-} Here we must not inline g into f's RHS, even when we get to phase 0, because when f is later inlined into some other module we want the rule for h to fire. Similarly, consider {-# INLINE f #-} f x = ...g... g y = ... and suppose that there are auto-generated specialisations and a strictness wrapper for g. The specialisations get activation AlwaysActive, and the strictness wrapper get activation (ActiveAfter 0). So the strictness wrepper fails the test and won't be inlined into f's stable unfolding. That means f can inline, expose the specialised call to g, so the specialisation rules can fire. A note about wrappers ~~~~~~~~~~~~~~~~~~~~~ It's also important not to inline a worker back into a wrapper. A wrapper looks like wraper = inline_me (\x -> ...worker... ) Normally, the inline_me prevents the worker getting inlined into the wrapper (initially, the worker's only call site!). But, if the wrapper is sure to be called, the strictness analyser will mark it 'demanded', so when the RHS is simplified, it'll get an ArgOf continuation. -} activeUnfolding :: SimplEnv -> Id -> Bool activeUnfolding env | not (sm_inline mode) = active_unfolding_minimal | otherwise = case sm_phase mode of InitialPhase -> active_unfolding_gentle Phase n -> active_unfolding n where mode = getMode env getUnfoldingInRuleMatch :: SimplEnv -> InScopeEnv -- When matching in RULE, we want to "look through" an unfolding -- (to see a constructor) if *rules* are on, even if *inlinings* -- are not. A notable example is DFuns, which really we want to -- match in rules like (op dfun) in gentle mode. Another example -- is 'otherwise' which we want exprIsConApp_maybe to be able to -- see very early on getUnfoldingInRuleMatch env = (in_scope, id_unf) where in_scope = seInScope env mode = getMode env id_unf id | unf_is_active id = idUnfolding id | otherwise = NoUnfolding unf_is_active id | not (sm_rules mode) = active_unfolding_minimal id | otherwise = isActive (sm_phase mode) (idInlineActivation id) active_unfolding_minimal :: Id -> Bool -- Compuslory unfoldings only -- Ignore SimplGently, because we want to inline regardless; -- the Id has no top-level binding at all -- -- NB: we used to have a second exception, for data con wrappers. -- On the grounds that we use gentle mode for rule LHSs, and -- they match better when data con wrappers are inlined. -- But that only really applies to the trivial wrappers (like (:)), -- and they are now constructed as Compulsory unfoldings (in MkId) -- so they'll happen anyway. active_unfolding_minimal id = isCompulsoryUnfolding (realIdUnfolding id) active_unfolding :: PhaseNum -> Id -> Bool active_unfolding n id = isActiveIn n (idInlineActivation id) active_unfolding_gentle :: Id -> Bool -- Anything that is early-active -- See Note [Gentle mode] active_unfolding_gentle id = isInlinePragma prag && isEarlyActive (inlinePragmaActivation prag) -- NB: wrappers are not early-active where prag = idInlinePragma id ---------------------- activeRule :: SimplEnv -> Activation -> Bool -- Nothing => No rules at all activeRule env | not (sm_rules mode) = \_ -> False -- Rewriting is off | otherwise = isActive (sm_phase mode) where mode = getMode env {- ************************************************************************ * * preInlineUnconditionally * * ************************************************************************ preInlineUnconditionally ~~~~~~~~~~~~~~~~~~~~~~~~ @preInlineUnconditionally@ examines a bndr to see if it is used just once in a completely safe way, so that it is safe to discard the binding inline its RHS at the (unique) usage site, REGARDLESS of how big the RHS might be. If this is the case we don't simplify the RHS first, but just inline it un-simplified. This is much better than first simplifying a perhaps-huge RHS and then inlining and re-simplifying it. Indeed, it can be at least quadratically better. Consider x1 = e1 x2 = e2[x1] x3 = e3[x2] ...etc... xN = eN[xN-1] We may end up simplifying e1 N times, e2 N-1 times, e3 N-3 times etc. This can happen with cascades of functions too: f1 = \x1.e1 f2 = \xs.e2[f1] f3 = \xs.e3[f3] ...etc... THE MAIN INVARIANT is this: ---- preInlineUnconditionally invariant ----- IF preInlineUnconditionally chooses to inline x = <rhs> THEN doing the inlining should not change the occurrence info for the free vars of <rhs> ---------------------------------------------- For example, it's tempting to look at trivial binding like x = y and inline it unconditionally. But suppose x is used many times, but this is the unique occurrence of y. Then inlining x would change y's occurrence info, which breaks the invariant. It matters: y might have a BIG rhs, which will now be dup'd at every occurrenc of x. Even RHSs labelled InlineMe aren't caught here, because there might be no benefit from inlining at the call site. [Sept 01] Don't unconditionally inline a top-level thing, because that can simply make a static thing into something built dynamically. E.g. x = (a,b) main = \s -> h x [Remember that we treat \s as a one-shot lambda.] No point in inlining x unless there is something interesting about the call site. But watch out: if you aren't careful, some useful foldr/build fusion can be lost (most notably in spectral/hartel/parstof) because the foldr didn't see the build. Doing the dynamic allocation isn't a big deal, in fact, but losing the fusion can be. But the right thing here seems to be to do a callSiteInline based on the fact that there is something interesting about the call site (it's strict). Hmm. That seems a bit fragile. Conclusion: inline top level things gaily until Phase 0 (the last phase), at which point don't. Note [pre/postInlineUnconditionally in gentle mode] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even in gentle mode we want to do preInlineUnconditionally. The reason is that too little clean-up happens if you don't inline use-once things. Also a bit of inlining is *good* for full laziness; it can expose constant sub-expressions. Example in spectral/mandel/Mandel.hs, where the mandelset function gets a useful let-float if you inline windowToViewport However, as usual for Gentle mode, do not inline things that are inactive in the intial stages. See Note [Gentle mode]. Note [Stable unfoldings and preInlineUnconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Surprisingly, do not pre-inline-unconditionally Ids with INLINE pragmas! Example {-# INLINE f #-} f :: Eq a => a -> a f x = ... fInt :: Int -> Int fInt = f Int dEqInt ...fInt...fInt...fInt... Here f occurs just once, in the RHS of f1. But if we inline it there we'll lose the opportunity to inline at each of fInt's call sites. The INLINE pragma will only inline when the application is saturated for exactly this reason; and we don't want PreInlineUnconditionally to second-guess it. A live example is Trac #3736. c.f. Note [Stable unfoldings and postInlineUnconditionally] Note [Top-level botomming Ids] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Don't inline top-level Ids that are bottoming, even if they are used just once, because FloatOut has gone to some trouble to extract them out. Inlining them won't make the program run faster! Note [Do not inline CoVars unconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Coercion variables appear inside coercions, and the RHS of a let-binding is a term (not a coercion) so we can't necessarily inline the latter in the former. -} preInlineUnconditionally :: DynFlags -> SimplEnv -> TopLevelFlag -> InId -> InExpr -> Bool -- Precondition: rhs satisfies the let/app invariant -- See Note [CoreSyn let/app invariant] in CoreSyn -- Reason: we don't want to inline single uses, or discard dead bindings, -- for unlifted, side-effect-full bindings preInlineUnconditionally dflags env top_lvl bndr rhs | not active = False | isStableUnfolding (idUnfolding bndr) = False -- Note [Stable unfoldings and preInlineUnconditionally] | isTopLevel top_lvl && isBottomingId bndr = False -- Note [Top-level bottoming Ids] | not (gopt Opt_SimplPreInlining dflags) = False | isCoVar bndr = False -- Note [Do not inline CoVars unconditionally] | otherwise = case idOccInfo bndr of IAmDead -> True -- Happens in ((\x.1) v) OneOcc in_lam True int_cxt -> try_once in_lam int_cxt _ -> False where mode = getMode env active = isActive (sm_phase mode) act -- See Note [pre/postInlineUnconditionally in gentle mode] act = idInlineActivation bndr try_once in_lam int_cxt -- There's one textual occurrence | not in_lam = isNotTopLevel top_lvl || early_phase | otherwise = int_cxt && canInlineInLam rhs -- Be very careful before inlining inside a lambda, because (a) we must not -- invalidate occurrence information, and (b) we want to avoid pushing a -- single allocation (here) into multiple allocations (inside lambda). -- Inlining a *function* with a single *saturated* call would be ok, mind you. -- || (if is_cheap && not (canInlineInLam rhs) then pprTrace "preinline" (ppr bndr <+> ppr rhs) ok else ok) -- where -- is_cheap = exprIsCheap rhs -- ok = is_cheap && int_cxt -- int_cxt The context isn't totally boring -- E.g. let f = \ab.BIG in \y. map f xs -- Don't want to substitute for f, because then we allocate -- its closure every time the \y is called -- But: let f = \ab.BIG in \y. map (f y) xs -- Now we do want to substitute for f, even though it's not -- saturated, because we're going to allocate a closure for -- (f y) every time round the loop anyhow. -- canInlineInLam => free vars of rhs are (Once in_lam) or Many, -- so substituting rhs inside a lambda doesn't change the occ info. -- Sadly, not quite the same as exprIsHNF. canInlineInLam (Lit _) = True canInlineInLam (Lam b e) = isRuntimeVar b || canInlineInLam e canInlineInLam (Tick t e) = not (tickishIsCode t) && canInlineInLam e canInlineInLam _ = False -- not ticks. Counting ticks cannot be duplicated, and non-counting -- ticks around a Lam will disappear anyway. early_phase = case sm_phase mode of Phase 0 -> False _ -> True -- If we don't have this early_phase test, consider -- x = length [1,2,3] -- The full laziness pass carefully floats all the cons cells to -- top level, and preInlineUnconditionally floats them all back in. -- Result is (a) static allocation replaced by dynamic allocation -- (b) many simplifier iterations because this tickles -- a related problem; only one inlining per pass -- -- On the other hand, I have seen cases where top-level fusion is -- lost if we don't inline top level thing (e.g. string constants) -- Hence the test for phase zero (which is the phase for all the final -- simplifications). Until phase zero we take no special notice of -- top level things, but then we become more leery about inlining -- them. {- ************************************************************************ * * postInlineUnconditionally * * ************************************************************************ postInlineUnconditionally ~~~~~~~~~~~~~~~~~~~~~~~~~ @postInlineUnconditionally@ decides whether to unconditionally inline a thing based on the form of its RHS; in particular if it has a trivial RHS. If so, we can inline and discard the binding altogether. NB: a loop breaker has must_keep_binding = True and non-loop-breakers only have *forward* references. Hence, it's safe to discard the binding NOTE: This isn't our last opportunity to inline. We're at the binding site right now, and we'll get another opportunity when we get to the ocurrence(s) Note that we do this unconditional inlining only for trival RHSs. Don't inline even WHNFs inside lambdas; doing so may simply increase allocation when the function is called. This isn't the last chance; see NOTE above. NB: Even inline pragmas (e.g. IMustBeINLINEd) are ignored here Why? Because we don't even want to inline them into the RHS of constructor arguments. See NOTE above NB: At one time even NOINLINE was ignored here: if the rhs is trivial it's best to inline it anyway. We often get a=E; b=a from desugaring, with both a and b marked NOINLINE. But that seems incompatible with our new view that inlining is like a RULE, so I'm sticking to the 'active' story for now. -} postInlineUnconditionally :: DynFlags -> SimplEnv -> TopLevelFlag -> OutId -- The binder (an InId would be fine too) -- (*not* a CoVar) -> OccInfo -- From the InId -> OutExpr -> Unfolding -> Bool -- Precondition: rhs satisfies the let/app invariant -- See Note [CoreSyn let/app invariant] in CoreSyn -- Reason: we don't want to inline single uses, or discard dead bindings, -- for unlifted, side-effect-full bindings postInlineUnconditionally dflags env top_lvl bndr occ_info rhs unfolding | not active = False | isWeakLoopBreaker occ_info = False -- If it's a loop-breaker of any kind, don't inline -- because it might be referred to "earlier" | isExportedId bndr = False | isStableUnfolding unfolding = False -- Note [Stable unfoldings and postInlineUnconditionally] | isTopLevel top_lvl = False -- Note [Top level and postInlineUnconditionally] | exprIsTrivial rhs = True | otherwise = case occ_info of -- The point of examining occ_info here is that for *non-values* -- that occur outside a lambda, the call-site inliner won't have -- a chance (because it doesn't know that the thing -- only occurs once). The pre-inliner won't have gotten -- it either, if the thing occurs in more than one branch -- So the main target is things like -- let x = f y in -- case v of -- True -> case x of ... -- False -> case x of ... -- This is very important in practice; e.g. wheel-seive1 doubles -- in allocation if you miss this out OneOcc in_lam _one_br int_cxt -- OneOcc => no code-duplication issue -> smallEnoughToInline dflags unfolding -- Small enough to dup -- ToDo: consider discount on smallEnoughToInline if int_cxt is true -- -- NB: Do NOT inline arbitrarily big things, even if one_br is True -- Reason: doing so risks exponential behaviour. We simplify a big -- expression, inline it, and simplify it again. But if the -- very same thing happens in the big expression, we get -- exponential cost! -- PRINCIPLE: when we've already simplified an expression once, -- make sure that we only inline it if it's reasonably small. && (not in_lam || -- Outside a lambda, we want to be reasonably aggressive -- about inlining into multiple branches of case -- e.g. let x = <non-value> -- in case y of { C1 -> ..x..; C2 -> ..x..; C3 -> ... } -- Inlining can be a big win if C3 is the hot-spot, even if -- the uses in C1, C2 are not 'interesting' -- An example that gets worse if you add int_cxt here is 'clausify' (isCheapUnfolding unfolding && int_cxt)) -- isCheap => acceptable work duplication; in_lam may be true -- int_cxt to prevent us inlining inside a lambda without some -- good reason. See the notes on int_cxt in preInlineUnconditionally IAmDead -> True -- This happens; for example, the case_bndr during case of -- known constructor: case (a,b) of x { (p,q) -> ... } -- Here x isn't mentioned in the RHS, so we don't want to -- create the (dead) let-binding let x = (a,b) in ... _ -> False -- Here's an example that we don't handle well: -- let f = if b then Left (\x.BIG) else Right (\y.BIG) -- in \y. ....case f of {...} .... -- Here f is used just once, and duplicating the case work is fine (exprIsCheap). -- But -- - We can't preInlineUnconditionally because that woud invalidate -- the occ info for b. -- - We can't postInlineUnconditionally because the RHS is big, and -- that risks exponential behaviour -- - We can't call-site inline, because the rhs is big -- Alas! where active = isActive (sm_phase (getMode env)) (idInlineActivation bndr) -- See Note [pre/postInlineUnconditionally in gentle mode] {- Note [Top level and postInlineUnconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We don't do postInlineUnconditionally for top-level things (even for ones that are trivial): * Doing so will inline top-level error expressions that have been carefully floated out by FloatOut. More generally, it might replace static allocation with dynamic. * Even for trivial expressions there's a problem. Consider {-# RULE "foo" forall (xs::[T]). reverse xs = ruggle xs #-} blah xs = reverse xs ruggle = sort In one simplifier pass we might fire the rule, getting blah xs = ruggle xs but in *that* simplifier pass we must not do postInlineUnconditionally on 'ruggle' because then we'll have an unbound occurrence of 'ruggle' If the rhs is trivial it'll be inlined by callSiteInline, and then the binding will be dead and discarded by the next use of OccurAnal * There is less point, because the main goal is to get rid of local bindings used in multiple case branches. * The inliner should inline trivial things at call sites anyway. Note [Stable unfoldings and postInlineUnconditionally] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Do not do postInlineUnconditionally if the Id has an stable unfolding, otherwise we lose the unfolding. Example -- f has stable unfolding with rhs (e |> co) -- where 'e' is big f = e |> co Then there's a danger we'll optimise to f' = e f = f' |> co and now postInlineUnconditionally, losing the stable unfolding on f. Now f' won't inline because 'e' is too big. c.f. Note [Stable unfoldings and preInlineUnconditionally] ************************************************************************ * * Rebuilding a lambda * * ************************************************************************ -} mkLam :: [OutBndr] -> OutExpr -> SimplCont -> SimplM OutExpr -- mkLam tries three things -- a) eta reduction, if that gives a trivial expression -- b) eta expansion [only if there are some value lambdas] mkLam [] body _cont = return body mkLam bndrs body cont = do { dflags <- getDynFlags ; mkLam' dflags bndrs body } where mkLam' :: DynFlags -> [OutBndr] -> OutExpr -> SimplM OutExpr mkLam' dflags bndrs (Cast body co) | not (any bad bndrs) -- Note [Casts and lambdas] = do { lam <- mkLam' dflags bndrs body ; return (mkCast lam (mkPiCos Representational bndrs co)) } where co_vars = tyCoVarsOfCo co bad bndr = isCoVar bndr && bndr `elemVarSet` co_vars mkLam' dflags bndrs body@(Lam {}) = mkLam' dflags (bndrs ++ bndrs1) body1 where (bndrs1, body1) = collectBinders body mkLam' dflags bndrs (Tick t expr) | tickishFloatable t = mkTick t <$> mkLam' dflags bndrs expr mkLam' dflags bndrs body | gopt Opt_DoEtaReduction dflags , Just etad_lam <- tryEtaReduce bndrs body = do { tick (EtaReduction (head bndrs)) ; return etad_lam } | not (contIsRhs cont) -- See Note [Eta-expanding lambdas] , gopt Opt_DoLambdaEtaExpansion dflags , any isRuntimeVar bndrs , let body_arity = exprEtaExpandArity dflags body , body_arity > 0 = do { tick (EtaExpansion (head bndrs)) ; return (mkLams bndrs (etaExpand body_arity body)) } | otherwise = return (mkLams bndrs body) {- Note [Eta expanding lambdas] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In general we *do* want to eta-expand lambdas. Consider f (\x -> case x of (a,b) -> \s -> blah) where 's' is a state token, and hence can be eta expanded. This showed up in the code for GHc.IO.Handle.Text.hPutChar, a rather important function! The eta-expansion will never happen unless we do it now. (Well, it's possible that CorePrep will do it, but CorePrep only has a half-baked eta-expander that can't deal with casts. So it's much better to do it here.) However, when the lambda is let-bound, as the RHS of a let, we have a better eta-expander (in the form of tryEtaExpandRhs), so we don't bother to try expansion in mkLam in that case; hence the contIsRhs guard. Note [Casts and lambdas] ~~~~~~~~~~~~~~~~~~~~~~~~ Consider (\x. (\y. e) `cast` g1) `cast` g2 There is a danger here that the two lambdas look separated, and the full laziness pass might float an expression to between the two. So this equation in mkLam' floats the g1 out, thus: (\x. e `cast` g1) --> (\x.e) `cast` (tx -> g1) where x:tx. In general, this floats casts outside lambdas, where (I hope) they might meet and cancel with some other cast: \x. e `cast` co ===> (\x. e) `cast` (tx -> co) /\a. e `cast` co ===> (/\a. e) `cast` (/\a. co) /\g. e `cast` co ===> (/\g. e) `cast` (/\g. co) (if not (g `in` co)) Notice that it works regardless of 'e'. Originally it worked only if 'e' was itself a lambda, but in some cases that resulted in fruitless iteration in the simplifier. A good example was when compiling Text.ParserCombinators.ReadPrec, where we had a definition like (\x. Get `cast` g) where Get is a constructor with nonzero arity. Then mkLam eta-expanded the Get, and the next iteration eta-reduced it, and then eta-expanded it again. Note also the side condition for the case of coercion binders. It does not make sense to transform /\g. e `cast` g ==> (/\g.e) `cast` (/\g.g) because the latter is not well-kinded. ************************************************************************ * * Eta expansion * * ************************************************************************ -} tryEtaExpandRhs :: SimplEnv -> OutId -> OutExpr -> SimplM (Arity, OutExpr) -- See Note [Eta-expanding at let bindings] tryEtaExpandRhs env bndr rhs = do { dflags <- getDynFlags ; (new_arity, new_rhs) <- try_expand dflags ; WARN( new_arity < old_id_arity, (ptext (sLit "Arity decrease:") <+> (ppr bndr <+> ppr old_id_arity <+> ppr old_arity <+> ppr new_arity) $$ ppr new_rhs) ) -- Note [Arity decrease] in Simplify return (new_arity, new_rhs) } where try_expand dflags | exprIsTrivial rhs = return (exprArity rhs, rhs) | sm_eta_expand (getMode env) -- Provided eta-expansion is on , let new_arity1 = findRhsArity dflags bndr rhs old_arity new_arity2 = idCallArity bndr new_arity = max new_arity1 new_arity2 , new_arity > old_arity -- And the current manifest arity isn't enough = do { tick (EtaExpansion bndr) ; return (new_arity, etaExpand new_arity rhs) } | otherwise = return (old_arity, rhs) old_arity = exprArity rhs -- See Note [Do not expand eta-expand PAPs] old_id_arity = idArity bndr {- Note [Eta-expanding at let bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We now eta expand at let-bindings, which is where the payoff comes. The most significant thing is that we can do a simple arity analysis (in CoreArity.findRhsArity), which we can't do for free-floating lambdas One useful consequence of not eta-expanding lambdas is this example: genMap :: C a => ... {-# INLINE genMap #-} genMap f xs = ... myMap :: D a => ... {-# INLINE myMap #-} myMap = genMap Notice that 'genMap' should only inline if applied to two arguments. In the stable unfolding for myMap we'll have the unfolding (\d -> genMap Int (..d..)) We do not want to eta-expand to (\d f xs -> genMap Int (..d..) f xs) because then 'genMap' will inline, and it really shouldn't: at least as far as the programmer is concerned, it's not applied to two arguments! Note [Do not eta-expand PAPs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to have old_arity = manifestArity rhs, which meant that we would eta-expand even PAPs. But this gives no particular advantage, and can lead to a massive blow-up in code size, exhibited by Trac #9020. Suppose we have a PAP foo :: IO () foo = returnIO () Then we can eta-expand do foo = (\eta. (returnIO () |> sym g) eta) |> g where g :: IO () ~ State# RealWorld -> (# State# RealWorld, () #) But there is really no point in doing this, and it generates masses of coercions and whatnot that eventually disappear again. For T9020, GHC allocated 6.6G beore, and 0.8G afterwards; and residency dropped from 1.8G to 45M. But note that this won't eta-expand, say f = \g -> map g Does it matter not eta-expanding such functions? I'm not sure. Perhaps strictness analysis will have less to bite on? ************************************************************************ * * \subsection{Floating lets out of big lambdas} * * ************************************************************************ Note [Floating and type abstraction] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this: x = /\a. C e1 e2 We'd like to float this to y1 = /\a. e1 y2 = /\a. e2 x = /\a. C (y1 a) (y2 a) for the usual reasons: we want to inline x rather vigorously. You may think that this kind of thing is rare. But in some programs it is common. For example, if you do closure conversion you might get: data a :-> b = forall e. (e -> a -> b) :$ e f_cc :: forall a. a :-> a f_cc = /\a. (\e. id a) :$ () Now we really want to inline that f_cc thing so that the construction of the closure goes away. So I have elaborated simplLazyBind to understand right-hand sides that look like /\ a1..an. body and treat them specially. The real work is done in SimplUtils.abstractFloats, but there is quite a bit of plumbing in simplLazyBind as well. The same transformation is good when there are lets in the body: /\abc -> let(rec) x = e in b ==> let(rec) x' = /\abc -> let x = x' a b c in e in /\abc -> let x = x' a b c in b This is good because it can turn things like: let f = /\a -> letrec g = ... g ... in g into letrec g' = /\a -> ... g' a ... in let f = /\ a -> g' a which is better. In effect, it means that big lambdas don't impede let-floating. This optimisation is CRUCIAL in eliminating the junk introduced by desugaring mutually recursive definitions. Don't eliminate it lightly! [May 1999] If we do this transformation *regardless* then we can end up with some pretty silly stuff. For example, let st = /\ s -> let { x1=r1 ; x2=r2 } in ... in .. becomes let y1 = /\s -> r1 y2 = /\s -> r2 st = /\s -> ...[y1 s/x1, y2 s/x2] in .. Unless the "..." is a WHNF there is really no point in doing this. Indeed it can make things worse. Suppose x1 is used strictly, and is of the form x1* = case f y of { (a,b) -> e } If we abstract this wrt the tyvar we then can't do the case inline as we would normally do. That's why the whole transformation is part of the same process that floats let-bindings and constructor arguments out of RHSs. In particular, it is guarded by the doFloatFromRhs call in simplLazyBind. -} abstractFloats :: [OutTyVar] -> SimplEnv -> OutExpr -> SimplM ([OutBind], OutExpr) abstractFloats main_tvs body_env body = ASSERT( notNull body_floats ) do { (subst, float_binds) <- mapAccumLM abstract empty_subst body_floats ; return (float_binds, CoreSubst.substExpr (text "abstract_floats1") subst body) } where main_tv_set = mkVarSet main_tvs body_floats = getFloatBinds body_env empty_subst = CoreSubst.mkEmptySubst (seInScope body_env) abstract :: CoreSubst.Subst -> OutBind -> SimplM (CoreSubst.Subst, OutBind) abstract subst (NonRec id rhs) = do { (poly_id, poly_app) <- mk_poly tvs_here id ; let poly_rhs = mkLams tvs_here rhs' subst' = CoreSubst.extendIdSubst subst id poly_app ; return (subst', (NonRec poly_id poly_rhs)) } where rhs' = CoreSubst.substExpr (text "abstract_floats2") subst rhs tvs_here = varSetElemsKvsFirst (main_tv_set `intersectVarSet` exprSomeFreeVars isTyVar rhs') -- Abstract only over the type variables free in the rhs -- wrt which the new binding is abstracted. But the naive -- approach of abstract wrt the tyvars free in the Id's type -- fails. Consider: -- /\ a b -> let t :: (a,b) = (e1, e2) -- x :: a = fst t -- in ... -- Here, b isn't free in x's type, but we must nevertheless -- abstract wrt b as well, because t's type mentions b. -- Since t is floated too, we'd end up with the bogus: -- poly_t = /\ a b -> (e1, e2) -- poly_x = /\ a -> fst (poly_t a *b*) -- So for now we adopt the even more naive approach of -- abstracting wrt *all* the tyvars. We'll see if that -- gives rise to problems. SLPJ June 98 abstract subst (Rec prs) = do { (poly_ids, poly_apps) <- mapAndUnzipM (mk_poly tvs_here) ids ; let subst' = CoreSubst.extendSubstList subst (ids `zip` poly_apps) poly_rhss = [mkLams tvs_here (CoreSubst.substExpr (text "abstract_floats3") subst' rhs) | rhs <- rhss] ; return (subst', Rec (poly_ids `zip` poly_rhss)) } where (ids,rhss) = unzip prs -- For a recursive group, it's a bit of a pain to work out the minimal -- set of tyvars over which to abstract: -- /\ a b c. let x = ...a... in -- letrec { p = ...x...q... -- q = .....p...b... } in -- ... -- Since 'x' is abstracted over 'a', the {p,q} group must be abstracted -- over 'a' (because x is replaced by (poly_x a)) as well as 'b'. -- Since it's a pain, we just use the whole set, which is always safe -- -- If you ever want to be more selective, remember this bizarre case too: -- x::a = x -- Here, we must abstract 'x' over 'a'. tvs_here = sortQuantVars main_tvs mk_poly tvs_here var = do { uniq <- getUniqueM ; let poly_name = setNameUnique (idName var) uniq -- Keep same name poly_ty = mkForAllTys tvs_here (idType var) -- But new type of course poly_id = transferPolyIdInfo var tvs_here $ -- Note [transferPolyIdInfo] in Id.hs mkLocalId poly_name poly_ty ; return (poly_id, mkTyApps (Var poly_id) (mkTyVarTys tvs_here)) } -- In the olden days, it was crucial to copy the occInfo of the original var, -- because we were looking at occurrence-analysed but as yet unsimplified code! -- In particular, we mustn't lose the loop breakers. BUT NOW we are looking -- at already simplified code, so it doesn't matter -- -- It's even right to retain single-occurrence or dead-var info: -- Suppose we started with /\a -> let x = E in B -- where x occurs once in B. Then we transform to: -- let x' = /\a -> E in /\a -> let x* = x' a in B -- where x* has an INLINE prag on it. Now, once x* is inlined, -- the occurrences of x' will be just the occurrences originally -- pinned on x. {- Note [Abstract over coercions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If a coercion variable (g :: a ~ Int) is free in the RHS, then so is the type variable a. Rather than sort this mess out, we simply bale out and abstract wrt all the type variables if any of them are coercion variables. Historical note: if you use let-bindings instead of a substitution, beware of this: -- Suppose we start with: -- -- x = /\ a -> let g = G in E -- -- Then we'll float to get -- -- x = let poly_g = /\ a -> G -- in /\ a -> let g = poly_g a in E -- -- But now the occurrence analyser will see just one occurrence -- of poly_g, not inside a lambda, so the simplifier will -- PreInlineUnconditionally poly_g back into g! Badk to square 1! -- (I used to think that the "don't inline lone occurrences" stuff -- would stop this happening, but since it's the *only* occurrence, -- PreInlineUnconditionally kicks in first!) -- -- Solution: put an INLINE note on g's RHS, so that poly_g seems -- to appear many times. (NB: mkInlineMe eliminates -- such notes on trivial RHSs, so do it manually.) ************************************************************************ * * prepareAlts * * ************************************************************************ prepareAlts tries these things: 1. Eliminate alternatives that cannot match, including the DEFAULT alternative. 2. If the DEFAULT alternative can match only one possible constructor, then make that constructor explicit. e.g. case e of x { DEFAULT -> rhs } ===> case e of x { (a,b) -> rhs } where the type is a single constructor type. This gives better code when rhs also scrutinises x or e. 3. Returns a list of the constructors that cannot holds in the DEFAULT alternative (if there is one) Here "cannot match" includes knowledge from GADTs It's a good idea to do this stuff before simplifying the alternatives, to avoid simplifying alternatives we know can't happen, and to come up with the list of constructors that are handled, to put into the IdInfo of the case binder, for use when simplifying the alternatives. Eliminating the default alternative in (1) isn't so obvious, but it can happen: data Colour = Red | Green | Blue f x = case x of Red -> .. Green -> .. DEFAULT -> h x h y = case y of Blue -> .. DEFAULT -> [ case y of ... ] If we inline h into f, the default case of the inlined h can't happen. If we don't notice this, we may end up filtering out *all* the cases of the inner case y, which give us nowhere to go! -} prepareAlts :: OutExpr -> OutId -> [InAlt] -> SimplM ([AltCon], [InAlt]) -- The returned alternatives can be empty, none are possible prepareAlts scrut case_bndr' alts | Just (tc, tys) <- splitTyConApp_maybe (varType case_bndr') -- Case binder is needed just for its type. Note that as an -- OutId, it has maximum information; this is important. -- Test simpl013 is an example = do { us <- getUniquesM ; let (idcs1, alts1) = filterAlts tc tys imposs_cons alts (yes2, alts2) = refineDefaultAlt us tc tys idcs1 alts1 (yes3, idcs3, alts3) = combineIdenticalAlts idcs1 alts2 -- "idcs" stands for "impossible default data constructors" -- i.e. the constructors that can't match the default case ; when yes2 $ tick (FillInCaseDefault case_bndr') ; when yes3 $ tick (AltMerge case_bndr') ; return (idcs3, alts3) } | otherwise -- Not a data type, so nothing interesting happens = return ([], alts) where imposs_cons = case scrut of Var v -> otherCons (idUnfolding v) _ -> [] {- ************************************************************************ * * mkCase * * ************************************************************************ mkCase tries these things 1. Merge Nested Cases case e of b { ==> case e of b { p1 -> rhs1 p1 -> rhs1 ... ... pm -> rhsm pm -> rhsm _ -> case b of b' { pn -> let b'=b in rhsn pn -> rhsn ... ... po -> let b'=b in rhso po -> rhso _ -> let b'=b in rhsd _ -> rhsd } which merges two cases in one case when -- the default alternative of the outer case scrutises the same variable as the outer case. This transformation is called Case Merging. It avoids that the same variable is scrutinised multiple times. 2. Eliminate Identity Case case e of ===> e True -> True; False -> False and similar friends. -} mkCase, mkCase1, mkCase2 :: DynFlags -> OutExpr -> OutId -> OutType -> [OutAlt] -- Alternatives in standard (increasing) order -> SimplM OutExpr -------------------------------------------------- -- 1. Merge Nested Cases -------------------------------------------------- mkCase dflags scrut outer_bndr alts_ty ((DEFAULT, _, deflt_rhs) : outer_alts) | gopt Opt_CaseMerge dflags , (ticks, Case (Var inner_scrut_var) inner_bndr _ inner_alts) <- stripTicksTop tickishFloatable deflt_rhs , inner_scrut_var == outer_bndr = do { tick (CaseMerge outer_bndr) ; let wrap_alt (con, args, rhs) = ASSERT( outer_bndr `notElem` args ) (con, args, wrap_rhs rhs) -- Simplifier's no-shadowing invariant should ensure -- that outer_bndr is not shadowed by the inner patterns wrap_rhs rhs = Let (NonRec inner_bndr (Var outer_bndr)) rhs -- The let is OK even for unboxed binders, wrapped_alts | isDeadBinder inner_bndr = inner_alts | otherwise = map wrap_alt inner_alts merged_alts = mergeAlts outer_alts wrapped_alts -- NB: mergeAlts gives priority to the left -- case x of -- A -> e1 -- DEFAULT -> case x of -- A -> e2 -- B -> e3 -- When we merge, we must ensure that e1 takes -- precedence over e2 as the value for A! ; fmap (mkTicks ticks) $ mkCase1 dflags scrut outer_bndr alts_ty merged_alts } -- Warning: don't call mkCase recursively! -- Firstly, there's no point, because inner alts have already had -- mkCase applied to them, so they won't have a case in their default -- Secondly, if you do, you get an infinite loop, because the bindCaseBndr -- in munge_rhs may put a case into the DEFAULT branch! mkCase dflags scrut bndr alts_ty alts = mkCase1 dflags scrut bndr alts_ty alts -------------------------------------------------- -- 2. Eliminate Identity Case -------------------------------------------------- mkCase1 _dflags scrut case_bndr _ alts@((_,_,rhs1) : _) -- Identity case | all identity_alt alts = do { tick (CaseIdentity case_bndr) ; return (mkTicks ticks $ re_cast scrut rhs1) } where ticks = concatMap (stripTicksT tickishFloatable . thirdOf3) (tail alts) identity_alt (con, args, rhs) = check_eq rhs con args check_eq (Cast rhs co) con args = not (any (`elemVarSet` tyCoVarsOfCo co) args) && check_eq rhs con args -- See Note [RHS casts] check_eq (Lit lit) (LitAlt lit') _ = lit == lit' check_eq (Var v) _ _ | v == case_bndr = True check_eq (Var v) (DataAlt con) [] = v == dataConWorkId con -- Optimisation only check_eq (Tick t e) alt args = tickishFloatable t && check_eq e alt args check_eq rhs (DataAlt con) args = cheapEqExpr' tickishFloatable rhs $ mkConApp con (arg_tys ++ varsToCoreExprs args) check_eq _ _ _ = False arg_tys = map Type (tyConAppArgs (idType case_bndr)) -- Note [RHS casts] -- ~~~~~~~~~~~~~~~~ -- We've seen this: -- case e of x { _ -> x `cast` c } -- And we definitely want to eliminate this case, to give -- e `cast` c -- So we throw away the cast from the RHS, and reconstruct -- it at the other end. All the RHS casts must be the same -- if (all identity_alt alts) holds. -- -- Don't worry about nested casts, because the simplifier combines them re_cast scrut (Cast rhs co) = Cast (re_cast scrut rhs) co re_cast scrut _ = scrut mkCase1 dflags scrut bndr alts_ty alts = mkCase2 dflags scrut bndr alts_ty alts -------------------------------------------------- -- Catch-all -------------------------------------------------- mkCase2 _dflags scrut bndr alts_ty alts = return (Case scrut bndr alts_ty alts) {- Note [Dead binders] ~~~~~~~~~~~~~~~~~~~~ Note that dead-ness is maintained by the simplifier, so that it is accurate after simplification as well as before. Note [Cascading case merge] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Case merging should cascade in one sweep, because it happens bottom-up case e of a { DEFAULT -> case a of b DEFAULT -> case b of c { DEFAULT -> e A -> ea B -> eb C -> ec ==> case e of a { DEFAULT -> case a of b DEFAULT -> let c = b in e A -> let c = b in ea B -> eb C -> ec ==> case e of a { DEFAULT -> let b = a in let c = b in e A -> let b = a in let c = b in ea B -> let b = a in eb C -> ec However here's a tricky case that we still don't catch, and I don't see how to catch it in one pass: case x of c1 { I# a1 -> case a1 of c2 -> 0 -> ... DEFAULT -> case x of c3 { I# a2 -> case a2 of ... After occurrence analysis (and its binder-swap) we get this case x of c1 { I# a1 -> let x = c1 in -- Binder-swap addition case a1 of c2 -> 0 -> ... DEFAULT -> case x of c3 { I# a2 -> case a2 of ... When we simplify the inner case x, we'll see that x=c1=I# a1. So we'll bind a2 to a1, and get case x of c1 { I# a1 -> case a1 of c2 -> 0 -> ... DEFAULT -> case a1 of ... This is corect, but we can't do a case merge in this sweep because c2 /= a1. Reason: the binding c1=I# a1 went inwards without getting changed to c1=I# c2. I don't think this is worth fixing, even if I knew how. It'll all come out in the next pass anyway. -}
acowley/ghc
compiler/simplCore/SimplUtils.hs
bsd-3-clause
79,256
0
18
24,250
8,504
4,553
3,951
-1
-1
{-# LANGUAGE TypeFamilies #-} data family T1 a :: * -> * data instance T1 Int = T1_1 -- must fail: too few args
siddhanathan/ghc
testsuite/tests/indexed-types/should_fail/SimpleFail1a.hs
bsd-3-clause
125
0
5
37
27
16
11
3
0
-- | Keeps all game loaders in one record, for easy access from various parts -- of the game. module Game.Loaders ( Loaders(..) , updateLoaders , runLoadersDeferred ) where import Prelewd import IO import Game.Resource.Loader import Game.Resource.Texture import Graphics.Rendering.OpenGL.Monad -- | The resource loaders associated with any running game. data Loaders = Loaders { textureL :: ResourceLoader DynamicImage Texture } -- | Runs 'chooseResources' on all available loaders. -- -- Adding a loader? Applicative its 'chooseResource' function on the end here. -- -- Do we have a whole bunch of loaders? Run the resource choosers in parallel! updateLoaders :: Loaders -> [ResourceRequest] -> SystemIO Loaders updateLoaders = (Loaders <$>)<$$> chooseResources . textureL -- | Calls 'runDeferred' on all loaders. -- -- Adding a loader? Applicative its 'runDeferred' function on the end here. runLoadersDeferred :: Loaders -> GL Loaders runLoadersDeferred = Loaders <$$> runDeferred . textureL
bfops/Chess
src/Game/Loaders.hs
mit
1,096
0
9
246
138
86
52
-1
-1
-------------------------------------------------------------------------- -- Copyright (c) 2007-2010, 2012, 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, Universitaetstr. 6, CH-8092 Zurich, -- Attn: Systems Group. -- -- Configuration options for Hake -- -------------------------------------------------------------------------- module Config where import HakeTypes import Data.Char import qualified Args import Data.List -- path to source and install directories; these are automatically set by hake.sh at setup time source_dir :: String -- source_dir = undefined -- (set by hake.sh, see end of file) install_dir :: String -- install_dir = undefined -- (set by hake.sh, see end of file) -- Set of architectures for which to generate rules architectures :: [String] -- architectures = undefined -- (set by hake.sh, see end of file) -- Optimisation flags (-Ox -g etc.) passed to compiler cOptFlags :: String cOptFlags = "-g -O2" -- Selects which libc to compile with, "oldc" or "newlib" libc :: String --libc = "oldc" libc = "newlib" newlib_malloc :: String --newlib_malloc = "sbrk" -- use sbrk and newlib's malloc() --newlib_malloc = "dlmalloc" -- use dlmalloc newlib_malloc = "oldmalloc" -- Use a frame pointer use_fp :: Bool use_fp = True -- Default timeslice duration in milliseconds timeslice :: Integer timeslice = 80 -- Put kernel into microbenchmarks mode microbenchmarks :: Bool microbenchmarks = False -- Enable tracing trace :: Bool trace = False -- Enable QEMU networking. (ie. make network work in small memory) support_qemu_networking :: Bool support_qemu_networking = False -- armv7 platform to build for -- Currently available: gem5, pandaboard armv7_platform :: String --armv7_platform = "gem5" armv7_platform = "pandaboard" -- on pandaboard, build a heterogenous image and let the cortex-A9 set up and start the -- cortex-M3 processor (build targets "heteropanda_slave" and "heteropanda_master_image") heteropanda :: Bool heteropanda = False -- enable network tracing trace_network_subsystem :: Bool trace_network_subsystem = False -- May want to disable LRPC to improve trace visuals trace_disable_lrpc :: Bool trace_disable_lrpc = False -- use Kaluga use_kaluga_dvm :: Bool use_kaluga_dvm = True -- Domain and driver debugging global_debug :: Bool global_debug = False e1000n_debug :: Bool e1000n_debug = False eMAC_debug :: Bool eMAC_debug = False rtl8029_debug :: Bool rtl8029_debug = False ahcid_debug :: Bool ahcid_debug = False libahci_debug :: Bool libahci_debug = False vfs_debug :: Bool vfs_debug = False ethersrv_debug :: Bool ethersrv_debug = False netd_debug :: Bool netd_debug = False libacpi_debug :: Bool libacpi_debug = False acpi_interface_debug :: Bool acpi_interface_debug = False lpc_timer_debug :: Bool lpc_timer_debug = False lwip_debug :: Bool lwip_debug = False libpci_debug :: Bool libpci_debug = False usrpci_debug :: Bool usrpci_debug = False timer_debug :: Bool timer_debug = False eclipse_kernel_debug :: Bool eclipse_kernel_debug = False skb_debug :: Bool skb_debug = False skb_client_debug :: Bool skb_client_debug = False flounder_debug :: Bool flounder_debug = False flounder_failed_debug :: Bool flounder_failed_debug = False webserver_debug :: Bool webserver_debug = False sqlclient_debug :: Bool sqlclient_debug = False sqlite_debug :: Bool sqlite_debug = False sqlite_backend_debug :: Bool sqlite_backend_debug = False nfs_debug :: Bool nfs_debug = False rpc_debug :: Bool rpc_debug = False loopback_debug :: Bool loopback_debug = False octopus_debug :: Bool octopus_debug = False term_debug :: Bool term_debug = False serial_debug :: Bool serial_debug = False -- Deadlock debugging debug_deadlocks :: Bool debug_deadlocks = False -- Partitioned memory server memserv_percore :: Bool memserv_percore = False -- Lazy THC implementation (requires use_fp = True) lazy_thc :: Bool lazy_thc | elem "armv7" architectures = False | otherwise = True -- Select remote cap database implementation data Rcap_db = RCAP_DB_NULL | RCAP_DB_CENTRAL | RCAP_DB_TWOPC deriving (Show,Eq) rcap_db :: Rcap_db rcap_db = RCAP_DB_NULL -- Select scheduler data Scheduler = RBED | RR deriving (Show,Eq) scheduler :: Scheduler scheduler = RBED -- Physical Address Extensions (PAE)-enabled paging on x86-32 pae_paging :: Bool pae_paging = False -- Page Size Extensions (PSE)-enabled paging on x86-32 -- Always enabled when pae_paging == True, regardless of value pse_paging :: Bool pse_paging = False -- No Execute Extensions (NXE)-enabled paging on x86-32 -- May not be True when pae_paging == False nxe_paging :: Bool nxe_paging = False oneshot_timer :: Bool oneshot_timer = False defines :: [RuleToken] defines = [ Str ("-D" ++ d) | d <- [ if microbenchmarks then "CONFIG_MICROBENCHMARKS" else "", if trace then "CONFIG_TRACE" else "", if support_qemu_networking then "CONFIG_QEMU_NETWORK" else "", if trace_network_subsystem then "NETWORK_STACK_TRACE" else "", if trace_disable_lrpc then "TRACE_DISABLE_LRPC" else "", if global_debug then "GLOBAL_DEBUG" else "", if e1000n_debug then "E1000N_SERVICE_DEBUG" else "", if ahcid_debug then "AHCI_SERVICE_DEBUG" else "", if libahci_debug then "AHCI_LIB_DEBUG" else "", if vfs_debug then "VFS_DEBUG" else "", if eMAC_debug then "EMAC_SERVICE_DEBUG" else "", if rtl8029_debug then "RTL8029_SERVICE_DEBUG" else "", if ethersrv_debug then "ETHERSRV_SERVICE_DEBUG" else "", if netd_debug then "NETD_SERVICE_DEBUG" else "", if libacpi_debug then "ACPI_DEBUG_OUTPUT" else "", if acpi_interface_debug then "ACPI_BF_DEBUG" else "", if lpc_timer_debug then "LPC_TIMER_DEBUG" else "", if lwip_debug then "LWIP_BARRELFISH_DEBUG" else "", if libpci_debug then "PCI_CLIENT_DEBUG" else "", if usrpci_debug then "PCI_SERVICE_DEBUG" else "", if timer_debug then "TIMER_CLIENT_DEBUG" else "", if eclipse_kernel_debug then "ECLIPSE_KERNEL_DEBUG" else "", if skb_debug then "SKB_SERVICE_DEBUG" else "", if skb_client_debug then "SKB_CLIENT_DEBUG" else "", if flounder_debug then "FLOUNDER_DEBUG" else "", if flounder_failed_debug then "FLOUNDER_FAILED_DEBUG" else "", if webserver_debug then "WEBSERVER_DEBUG" else "", if sqlclient_debug then "SQL_CLIENT_DEBUG" else "", if sqlite_debug then "SQL_SERVICE_DEBUG" else "", if sqlite_backend_debug then "SQL_BACKEND_DEBUG" else "", if nfs_debug then "NFS_CLIENT_DEBUG" else "", if rpc_debug then "RPC_DEBUG" else "", if loopback_debug then "LOOPBACK_DEBUG" else "", if octopus_debug then "DIST_SERVICE_DEBUG" else "", if term_debug then "TERMINAL_LIBRARY_DEBUG" else "", if serial_debug then "SERIAL_DRIVER_DEBUG" else "", if debug_deadlocks then "CONFIG_DEBUG_DEADLOCKS" else "", if memserv_percore then "CONFIG_MEMSERV_PERCORE" else "", if lazy_thc then "CONFIG_LAZY_THC" else "", if pae_paging then "CONFIG_PAE" else "", if pse_paging then "CONFIG_PSE" else "", if nxe_paging then "CONFIG_NXE" else "", if libc == "oldc" then "CONFIG_OLDC" else "CONFIG_NEWLIB", if oneshot_timer then "CONFIG_ONESHOT_TIMER" else "", if use_kaluga_dvm then "USE_KALUGA_DVM" else "", if heteropanda then "HETEROPANDA" else "" ], d /= "" ] -- Sets the include path for the libc libcInc :: String libcInc = if libc == "oldc" then "/include/oldc" else "/lib/newlib/newlib/libc/include" -- some defines depend on the architecture/compile options arch_defines :: Options -> [RuleToken] arch_defines opts -- enable config flags for interconnect drivers in use for this arch = [ Str ("-D" ++ d) | d <- ["CONFIG_INTERCONNECT_DRIVER_" ++ (map toUpper n) | n <- optInterconnectDrivers opts] ] -- enable config flags for flounder backends in use for this arch ++ [ Str ("-D" ++ d) | d <- ["CONFIG_FLOUNDER_BACKEND_" ++ (map toUpper n) | n <- optFlounderBackends opts] ] -- newlib common compile flags (maybe put these in a config.h file?) newlibAddCFlags :: [String] newlibAddCFlags = [ "-DPACKAGE_NAME=\"newlib\"" , "-DPACKAGE_TARNAME=\"newlib\"", "-DPACKAGE_VERSION=\"1.19.0\"", "-DPACKAGE_BUGREPORT=\"\"", "-DPACKAGE_URL=\"\"", "-D_I386MACH_ALLOW_HW_INTERRUPTS", "-DMISSING_SYSCALL_NAMES", "-D_WANT_IO_C99_FORMATS", "-D_COMPILING_NEWLIB", "-D_WANT_IO_LONG_LONG", "-D_WANT_IO_LONG_DOUBLE", "-D_MB_CAPABLE", "-D__BSD_VISIBLE"] -- Automatically added by hake.sh. Do NOT copy these definitions to the defaults source_dir = ".." architectures = [ "x86_64" ] install_dir = "."
daleooo/barrelfish
build/hake/Config.hs
mit
9,451
0
12
2,172
1,448
895
553
194
47
-- File: Config.hs -- Copyright rejuvyesh <[email protected]>, 2014 -- License: GNU GPL 3 <http://www.gnu.org/copyleft/gpl.html> module Site.Config ( config , feedConfiguration ) where import Hakyll config :: Configuration config = defaultConfiguration { deployCommand = "/usr/bin/cp -rf _site/* ../rejuvyesh.github.io/ && cd ../rejuvyesh.github.io/ && git add -A && git commit -m \"update\" && git push origin" } feedConfiguration :: FeedConfiguration feedConfiguration = FeedConfiguration { feedTitle = "Rejuvyesh's Whisperings into the Wire" , feedDescription = "Personal blog of Jayesh Kumar Gupta" , feedAuthorName = "Jayesh Kumar Gupta" , feedAuthorEmail = "[email protected]" , feedRoot = "http://rejuvyesh.com" }
rejuvyesh/homepage
src/Site/Config.hs
mit
797
0
6
166
80
52
28
14
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE LambdaCase #-} module Yage.Rendering.Resources.Types where import Yage.Prelude import Yage.Lens import Control.Monad.RWS import qualified Graphics.Rendering.OpenGL as GL import Graphics.GLUtil import Yage.Rendering.Mesh import Yage.Rendering.Shader import Yage.Rendering.Backend.RenderPass (TargetSlot) import Yage.Rendering.Resources.ResTypes -- | RHI RenderHardwareInterface type VertexBufferRHI = (MeshHash, GL.BufferObject) type IndexBufferRHI = (MeshHash, GL.BufferObject) type VertexArrayRHI = VAO type ShaderRHI = ShaderProgram type TextureRHI = (BufferSpec, TextureConfig, GL.TextureObject) type RenderbufferRHI = (BufferSpec, GL.RenderbufferObject) type FramebufferRHI = GL.FramebufferObject data GLResources = GLResources { _loadedShaders :: Map ShaderProgramUnit ShaderRHI , _loadedVertexBuffer :: Map MeshId VertexBufferRHI , _loadedVertexArrays :: Map (MeshId, ShaderProgramUnit) VertexArrayRHI , _loadedIndexBuffers :: Map MeshId IndexBufferRHI , _loadedTextures :: Map Texture TextureRHI , _loadedRenderbuffers :: Map Renderbuffer RenderbufferRHI , _compiledFBOs :: Map TargetSlot FramebufferRHI } makeLenses ''GLResources type ResourceManager = RWST () [String] GLResources IO data UpdateTag a = Clean a | Dirty a deriving ( Show, Eq, Ord, Functor, Foldable, Traversable ) instance Applicative UpdateTag where pure = return (<*>) = ap instance Monad UpdateTag where return = Clean Clean a >>= f = f a Dirty a >>= f = case f a of Dirty b -> Dirty b Clean b -> Dirty b tagDirty :: a -> UpdateTag a tagDirty = Dirty tagClean :: a -> UpdateTag a tagClean = Clean updateTag :: (a -> c) -> (a -> c) -> UpdateTag a -> c updateTag clean dirty = \case Clean a -> clean a Dirty a -> dirty a isDirty :: UpdateTag a -> Bool isDirty (Dirty _) = True isDirty _ = False isClean :: UpdateTag a -> Bool isClean (Clean _) = True isClean _ = False
MaxDaten/yage-rendering
src/Yage/Rendering/Resources/Types.hs
mit
2,301
0
10
676
580
320
260
54
2
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Betfair.APING.Requests.Login ( sessionToken , login ) where import Control.Exception.Safe import qualified Data.ByteString.Lazy as L (ByteString) import Data.String.Conversions import Data.Text import Network.HTTP.Conduit import Protolude hiding (error, null) import Betfair.APING.API.Context import Betfair.APING.API.GetResponse import Betfair.APING.API.Headers (headers) import Betfair.APING.Types.AppKey (AppKey) import Betfair.APING.Types.Login import Betfair.APING.Types.Token (Token) -- http://stackoverflow.com/questions/3232074/what-is-the-best-way-to-convert-string-to-bytestring encodeBody :: AppKey -> Text -> Text -> Request -> Request encodeBody appKey username password req = urlEncodedBody [("username", cs username), ("password", cs password)] req {requestHeaders = headers appKey Nothing} -- Note that loginRequest uses a url encoded body unlike other -- requests (which are json objects) loginRequest :: Context -> Text -> Text -> IO Request loginRequest context username password = fmap (encodeBody (cAppKey context) username password) (parseUrlThrow "https://identitysso.betfair.com/api/login") sessionToken :: Context -> Text -> Text -> IO Token sessionToken context username password = either throwM pure =<< fmap parseLogin . getDecodedResponse context =<< loginRequest context username password parseLogin :: Login -> Either LoginError Token parseLogin l | null (token l) = Left (toLoginError l) | otherwise = Right (token l) login :: Context -> Text -> Text -> IO (Response L.ByteString) login c u p = getResponse c =<< loginRequest c u p
joe9/betfair-api
src/Betfair/APING/Requests/Login.hs
mit
1,765
0
11
321
443
242
201
38
1
module NES.Mapper where import Data.Word (Word8, Word16) import Data.Bits ((.&.), shiftR, shiftL, testBit) import Data.STRef (STRef, newSTRef, readSTRef) import Data.Array.ST (readArray, writeArray) import Control.Monad.ST (ST) import Control.Monad (when) import NES.ROM import NES.MemoryMap data NameTable = NT0 | NT1 | NT2 | NT3 data NameTableMap = NameTableMap { nt0 :: NameTable , nt1 :: NameTable , nt2 :: NameTable , nt3 :: NameTable } nameTableAddress :: NameTable -> Word16 nameTableAddress nametable = case nametable of NT0 -> 0x0000 NT1 -> 0x0400 NT2 -> 0x0800 NT3 -> 0x0C00 data MirrorType = HorizontalMirror | VerticalMirror | SingleScreenMirror0 | SingleScreenMirror1 | FourScreenMirror data Mapper s = Mapper0 (STRef s NameTableMap) prgLoad :: Mapper s -> MemoryMap s -> Word16 -> ST s Word8 prgLoad (Mapper0 _) mem addr = case addr of x | x >= 0x8000 -> readArray (prg mem) (addr .&. (if prgSize mem > 0x4000 then 0x7FFF else 0x3FFF)) x | x >= 0x6000 -> readArray (prgRAM mem) (addr .&. 0x1FFF) _ -> return 0 prgStore :: Mapper s -> MemoryMap s -> Word16 -> Word8 -> ST s () prgStore (Mapper0 _) mem addr w8 = when (addr >= 0x6000 && addr < 0x8000) $ writeArray (prgRAM mem) (addr .&. 0x1FFF) w8 chrLoad :: Mapper s -> MemoryMap s -> Word16 -> ST s Word8 chrLoad (Mapper0 ntMap) mem addr = if addr < 0x2000 then readArray (chr mem) addr else do ntMap' <- readSTRef ntMap case addr .&. 0xC00 of 0x000 -> readArray (nametables mem) (addr .&. 0x3FF + nameTableAddress (nt0 ntMap')) 0x400 -> readArray (nametables mem) (addr .&. 0x3FF + nameTableAddress (nt1 ntMap')) 0x800 -> readArray (nametables mem) (addr .&. 0x3FF + nameTableAddress (nt2 ntMap')) _ -> if addr >= 0x3F00 -- includes addr .&. 0xC00 == 0xC00 then do let addr' = fromIntegral $ addr .&. 0x1F addr'' = if addr' >= 0x10 && (addr' .&. 0x3 == 0) then addr' - 0x10 else addr' readArray (palette mem) addr'' else readArray (nametables mem) (addr .&. 0x3FF + nameTableAddress (nt3 ntMap')) chrStore :: Mapper s -> MemoryMap s -> Word16 -> Word8 -> ST s () chrStore (Mapper0 ntMap) mem addr w8 = do let addr' = addr .&. 0x3FFF if addr' < 0x2000 then when (hasChrRam mem) $ writeArray (chr mem) addr' w8 else do ntMap' <- readSTRef ntMap case addr' .&. 0xC00 of 0x000 -> writeArray (nametables mem) (addr' .&. 0x3FF + nameTableAddress (nt0 ntMap')) w8 0x400 -> writeArray (nametables mem) (addr' .&. 0x3FF + nameTableAddress (nt1 ntMap')) w8 0x800 -> writeArray (nametables mem) (addr' .&. 0x3FF + nameTableAddress (nt2 ntMap')) w8 0xC00 -> if addr' >= 0x3F00 && addr' <= 0x3FFF then do let addr'' = fromIntegral $ addr' .&. 0x1F addr''' = if addr'' >= 0x10 && (addr'' .&. 0x3 == 0) then addr'' - 0x10 else addr'' writeArray (palette mem) addr''' (w8 .&. 0x3F) else writeArray (nametables mem) (addr' .&. 0x3FF + nameTableAddress (nt3 ntMap')) w8 _ -> return () loadMapper :: ROM -> ST s (Mapper s) loadMapper catridge = case mapnum of 0 -> do ntMap <- newSTRef defaultNameTableMap return $ Mapper0 ntMap x -> error $ "Mapper " ++ show x ++ " not implemented" where mapnum = (flags6 (header catridge) `shiftR` 4) + ((flags7 (header catridge) `shiftR` 4) `shiftL` 4) defaultNameTableMap | testBit (flags6 $ header catridge) 3 = setMirroring FourScreenMirror | testBit (flags6 $ header catridge) 0 = setMirroring VerticalMirror | otherwise = setMirroring HorizontalMirror setMirroring :: MirrorType -> NameTableMap setMirroring mirrorType = case mirrorType of HorizontalMirror -> NameTableMap NT0 NT0 NT1 NT1 VerticalMirror -> NameTableMap NT0 NT1 NT0 NT1 FourScreenMirror -> NameTableMap NT0 NT1 NT2 NT3 SingleScreenMirror0 -> NameTableMap NT0 NT0 NT0 NT0 SingleScreenMirror1 -> NameTableMap NT1 NT1 NT1 NT1
ksaveljev/hNES
NES/Mapper.hs
mit
4,494
0
23
1,429
1,482
751
731
89
8
{-# OPTIONS_GHC -fno-warn-orphans #-} module Vindinium.Api ( startTraining , startArena , move ) where import Vindinium.Types import Prelude (error,Int) import Control.Applicative ((<$>), (<*>)) import Control.Monad (liftM, mzero) import Control.Monad.IO.Class (liftIO) import Data.Aeson import Data.Either (Either(Right,Left)) import Data.Function (($),(.)) import Data.List (map,foldl,(++)) import Data.Maybe(Maybe(Just,Nothing),maybe) import Data.Monoid ((<>)) import Data.Text (Text, pack, unpack) import Data.String (String) import Network.HTTP.Client import Network.HTTP.Types import Text.Show (show) import Text.Read (read) startTraining :: Maybe Int -> Maybe Board -> Vindinium State startTraining mi mb = do url <- startUrl "training" let obj = object ( maybe [] (\i -> [("turns", toJSON i)]) mi <> maybe [] (\b -> [("map", toJSON b)]) mb ) request url obj move :: State -> Dir -> Vindinium State move s d = do let url = statePlayUrl s obj = object [("dir", toJSON d)] request url obj startArena :: Vindinium State startArena = do url <- startUrl "arena" let obj = object [] request url obj startUrl :: Text -> Vindinium Text startUrl v = liftM (\x -> x <> "/api/" <> v) $ asks settingsUrl request :: Text -> Value -> Vindinium State request url val = do key <- asks settingsKey initReq <- liftIO $ parseUrl $ unpack url let req = initReq { method = "POST" , requestHeaders = [ (hContentType, "application/json") , (hAccept, "application/json") , (hUserAgent, "vindinium-starter-haskell") ] , requestBody = jsonBody (injectKey val key) } liftIO $ withManager managerSettings $ \mgr -> liftM (decodeBody . responseBody) $ httpLbs req mgr where jsonBody = RequestBodyLBS . encode decodeBody body = case eitherDecode body of Left e -> error $ "request: unable to decode state: " ++ e Right s -> s injectKey (Object a) k = let (Object b) = object [("key", toJSON k)] in Object (a <> b) injectKey any _ = any managerSettings = defaultManagerSettings { managerResponseTimeout = Just 20000000 } parseBoard :: Int -> String -> Board parseBoard s t = Board s $ map parse (chunks t) where chunks [] = [] chunks (_:[]) = error "chunks: even chars number" chunks (a:b:xs) = (a, b):chunks xs parse (' ', ' ') = FreeTile parse ('#', '#') = WoodTile parse ('@', x) = HeroTile $ HeroId $ read [x] parse ('[', ']') = TavernTile parse ('$', '-') = MineTile Nothing parse ('$', x) = MineTile $ Just $ HeroId $ read [x] parse (a, b) = error $ "parse: unknown tile pattern " ++ (show $ a:b:[]) printTiles :: [Tile] -> Text printTiles = foldl (<>) "" . map printTile where printTile FreeTile = " " printTile WoodTile = "##" printTile (HeroTile (HeroId i)) = "@" <> (pack $ show i) printTile TavernTile = "[]" printTile (MineTile Nothing) = "$-" printTile (MineTile (Just (HeroId i))) = "$" <> (pack $ show i) instance ToJSON Key where toJSON (Key k) = String k instance ToJSON Board where toJSON b = object [ "size" .= boardSize b , "tiles" .= (printTiles $ boardTiles b) ] instance FromJSON State where parseJSON (Object o) = State <$> o .: "game" <*> o .: "hero" <*> o .: "token" <*> o .: "viewUrl" <*> o .: "playUrl" parseJSON _ = mzero instance FromJSON Game where parseJSON (Object o) = Game <$> o .: "id" <*> o .: "turn" <*> o .: "maxTurns" <*> o .: "heroes" <*> o .: "board" <*> o .: "finished" parseJSON _ = mzero instance FromJSON GameId where parseJSON x = GameId <$> parseJSON x instance FromJSON Hero where parseJSON (Object o) = Hero <$> o .: "id" <*> o .: "name" <*> o .:? "userId" <*> o .:? "elo" <*> o .: "pos" <*> o .: "life" <*> o .: "gold" <*> o .: "mineCount" <*> o .: "spawnPos" <*> o .: "crashed" parseJSON _ = mzero instance FromJSON HeroId where parseJSON x = HeroId <$> parseJSON x instance FromJSON Pos where parseJSON (Object o) = Pos <$> o .: "y" <*> o .: "x" parseJSON _ = mzero instance FromJSON Board where parseJSON (Object o) = parseBoard <$> o .: "size" <*> o .: "tiles" parseJSON _ = mzero instance ToJSON Dir where toJSON Stay = String "Stay" toJSON North = String "North" toJSON South = String "South" toJSON East = String "East" toJSON West = String "West"
benkolera/dalek-caan
src/Vindinium/Api.hs
mit
5,300
0
25
1,923
1,741
909
832
134
9
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.MediaControlsHost (sortedTrackListForMenu, sortedTrackListForMenu_, sortedTrackListForMenuAudio, sortedTrackListForMenuAudio_, displayNameForTrack, displayNameForTrack_, setSelectedTextTrack, setPreparedToReturnVideoLayerToInline, updateTextTrackContainer, enteredFullscreen, exitedFullscreen, generateUUID, generateUUID_, base64StringForIconNameAndType, base64StringForIconNameAndType_, getCaptionMenuOffItem, getCaptionMenuAutomaticItem, getCaptionDisplayMode, getTextTrackContainer, getAllowsInlineMediaPlayback, getSupportsFullscreen, getIsVideoLayerInline, getUserGestureRequired, getIsInMediaDocument, getShouldForceControlsDisplay, getExternalDeviceDisplayName, getExternalDeviceType, setControlsDependOnPageScaleFactor, getControlsDependOnPageScaleFactor, getShadowRootCSSText, MediaControlsHost(..), gTypeMediaControlsHost) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.sortedTrackListForMenu Mozilla MediaControlsHost.sortedTrackListForMenu documentation> sortedTrackListForMenu :: (MonadDOM m) => MediaControlsHost -> TextTrackList -> m [TextTrack] sortedTrackListForMenu self trackList = liftDOM ((self ^. jsf "sortedTrackListForMenu" [toJSVal trackList]) >>= fromJSArrayUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.sortedTrackListForMenu Mozilla MediaControlsHost.sortedTrackListForMenu documentation> sortedTrackListForMenu_ :: (MonadDOM m) => MediaControlsHost -> TextTrackList -> m () sortedTrackListForMenu_ self trackList = liftDOM (void (self ^. jsf "sortedTrackListForMenu" [toJSVal trackList])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.sortedTrackListForMenu Mozilla MediaControlsHost.sortedTrackListForMenu documentation> sortedTrackListForMenuAudio :: (MonadDOM m) => MediaControlsHost -> AudioTrackList -> m [AudioTrack] sortedTrackListForMenuAudio self trackList = liftDOM ((self ^. jsf "sortedTrackListForMenu" [toJSVal trackList]) >>= fromJSArrayUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.sortedTrackListForMenu Mozilla MediaControlsHost.sortedTrackListForMenu documentation> sortedTrackListForMenuAudio_ :: (MonadDOM m) => MediaControlsHost -> AudioTrackList -> m () sortedTrackListForMenuAudio_ self trackList = liftDOM (void (self ^. jsf "sortedTrackListForMenu" [toJSVal trackList])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.displayNameForTrack Mozilla MediaControlsHost.displayNameForTrack documentation> displayNameForTrack :: (MonadDOM m, IsTrack track, FromJSString result) => MediaControlsHost -> Maybe track -> m result displayNameForTrack self track = liftDOM ((self ^. jsf "displayNameForTrack" [toJSVal track]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.displayNameForTrack Mozilla MediaControlsHost.displayNameForTrack documentation> displayNameForTrack_ :: (MonadDOM m, IsTrack track) => MediaControlsHost -> Maybe track -> m () displayNameForTrack_ self track = liftDOM (void (self ^. jsf "displayNameForTrack" [toJSVal track])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.setSelectedTextTrack Mozilla MediaControlsHost.setSelectedTextTrack documentation> setSelectedTextTrack :: (MonadDOM m) => MediaControlsHost -> Maybe TextTrack -> m () setSelectedTextTrack self track = liftDOM (void (self ^. jsf "setSelectedTextTrack" [toJSVal track])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.setPreparedToReturnVideoLayerToInline Mozilla MediaControlsHost.setPreparedToReturnVideoLayerToInline documentation> setPreparedToReturnVideoLayerToInline :: (MonadDOM m) => MediaControlsHost -> Bool -> m () setPreparedToReturnVideoLayerToInline self prepared = liftDOM (void (self ^. jsf "setPreparedToReturnVideoLayerToInline" [toJSVal prepared])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.updateTextTrackContainer Mozilla MediaControlsHost.updateTextTrackContainer documentation> updateTextTrackContainer :: (MonadDOM m) => MediaControlsHost -> m () updateTextTrackContainer self = liftDOM (void (self ^. jsf "updateTextTrackContainer" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.enteredFullscreen Mozilla MediaControlsHost.enteredFullscreen documentation> enteredFullscreen :: (MonadDOM m) => MediaControlsHost -> m () enteredFullscreen self = liftDOM (void (self ^. jsf "enteredFullscreen" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.exitedFullscreen Mozilla MediaControlsHost.exitedFullscreen documentation> exitedFullscreen :: (MonadDOM m) => MediaControlsHost -> m () exitedFullscreen self = liftDOM (void (self ^. jsf "exitedFullscreen" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.generateUUID Mozilla MediaControlsHost.generateUUID documentation> generateUUID :: (MonadDOM m, FromJSString result) => MediaControlsHost -> m result generateUUID self = liftDOM ((self ^. jsf "generateUUID" ()) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.generateUUID Mozilla MediaControlsHost.generateUUID documentation> generateUUID_ :: (MonadDOM m) => MediaControlsHost -> m () generateUUID_ self = liftDOM (void (self ^. jsf "generateUUID" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.base64StringForIconNameAndType Mozilla MediaControlsHost.base64StringForIconNameAndType documentation> base64StringForIconNameAndType :: (MonadDOM m, ToJSString iconName, ToJSString iconType, FromJSString result) => MediaControlsHost -> iconName -> iconType -> m result base64StringForIconNameAndType self iconName iconType = liftDOM ((self ^. jsf "base64StringForIconNameAndType" [toJSVal iconName, toJSVal iconType]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.base64StringForIconNameAndType Mozilla MediaControlsHost.base64StringForIconNameAndType documentation> base64StringForIconNameAndType_ :: (MonadDOM m, ToJSString iconName, ToJSString iconType) => MediaControlsHost -> iconName -> iconType -> m () base64StringForIconNameAndType_ self iconName iconType = liftDOM (void (self ^. jsf "base64StringForIconNameAndType" [toJSVal iconName, toJSVal iconType])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.captionMenuOffItem Mozilla MediaControlsHost.captionMenuOffItem documentation> getCaptionMenuOffItem :: (MonadDOM m) => MediaControlsHost -> m TextTrack getCaptionMenuOffItem self = liftDOM ((self ^. js "captionMenuOffItem") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.captionMenuAutomaticItem Mozilla MediaControlsHost.captionMenuAutomaticItem documentation> getCaptionMenuAutomaticItem :: (MonadDOM m) => MediaControlsHost -> m TextTrack getCaptionMenuAutomaticItem self = liftDOM ((self ^. js "captionMenuAutomaticItem") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.captionDisplayMode Mozilla MediaControlsHost.captionDisplayMode documentation> getCaptionDisplayMode :: (MonadDOM m, FromJSString result) => MediaControlsHost -> m result getCaptionDisplayMode self = liftDOM ((self ^. js "captionDisplayMode") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.textTrackContainer Mozilla MediaControlsHost.textTrackContainer documentation> getTextTrackContainer :: (MonadDOM m) => MediaControlsHost -> m HTMLElement getTextTrackContainer self = liftDOM ((self ^. js "textTrackContainer") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.allowsInlineMediaPlayback Mozilla MediaControlsHost.allowsInlineMediaPlayback documentation> getAllowsInlineMediaPlayback :: (MonadDOM m) => MediaControlsHost -> m Bool getAllowsInlineMediaPlayback self = liftDOM ((self ^. js "allowsInlineMediaPlayback") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.supportsFullscreen Mozilla MediaControlsHost.supportsFullscreen documentation> getSupportsFullscreen :: (MonadDOM m) => MediaControlsHost -> m Bool getSupportsFullscreen self = liftDOM ((self ^. js "supportsFullscreen") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.isVideoLayerInline Mozilla MediaControlsHost.isVideoLayerInline documentation> getIsVideoLayerInline :: (MonadDOM m) => MediaControlsHost -> m Bool getIsVideoLayerInline self = liftDOM ((self ^. js "isVideoLayerInline") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.userGestureRequired Mozilla MediaControlsHost.userGestureRequired documentation> getUserGestureRequired :: (MonadDOM m) => MediaControlsHost -> m Bool getUserGestureRequired self = liftDOM ((self ^. js "userGestureRequired") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.isInMediaDocument Mozilla MediaControlsHost.isInMediaDocument documentation> getIsInMediaDocument :: (MonadDOM m) => MediaControlsHost -> m Bool getIsInMediaDocument self = liftDOM ((self ^. js "isInMediaDocument") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.shouldForceControlsDisplay Mozilla MediaControlsHost.shouldForceControlsDisplay documentation> getShouldForceControlsDisplay :: (MonadDOM m) => MediaControlsHost -> m Bool getShouldForceControlsDisplay self = liftDOM ((self ^. js "shouldForceControlsDisplay") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.externalDeviceDisplayName Mozilla MediaControlsHost.externalDeviceDisplayName documentation> getExternalDeviceDisplayName :: (MonadDOM m, FromJSString result) => MediaControlsHost -> m result getExternalDeviceDisplayName self = liftDOM ((self ^. js "externalDeviceDisplayName") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.externalDeviceType Mozilla MediaControlsHost.externalDeviceType documentation> getExternalDeviceType :: (MonadDOM m) => MediaControlsHost -> m DeviceType getExternalDeviceType self = liftDOM ((self ^. js "externalDeviceType") >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.controlsDependOnPageScaleFactor Mozilla MediaControlsHost.controlsDependOnPageScaleFactor documentation> setControlsDependOnPageScaleFactor :: (MonadDOM m) => MediaControlsHost -> Bool -> m () setControlsDependOnPageScaleFactor self val = liftDOM (self ^. jss "controlsDependOnPageScaleFactor" (toJSVal val)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.controlsDependOnPageScaleFactor Mozilla MediaControlsHost.controlsDependOnPageScaleFactor documentation> getControlsDependOnPageScaleFactor :: (MonadDOM m) => MediaControlsHost -> m Bool getControlsDependOnPageScaleFactor self = liftDOM ((self ^. js "controlsDependOnPageScaleFactor") >>= valToBool) -- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaControlsHost.shadowRootCSSText Mozilla MediaControlsHost.shadowRootCSSText documentation> getShadowRootCSSText :: (MonadDOM m, FromJSString result) => MediaControlsHost -> m result getShadowRootCSSText self = liftDOM ((self ^. js "shadowRootCSSText") >>= fromJSValUnchecked)
ghcjs/jsaddle-dom
src/JSDOM/Generated/MediaControlsHost.hs
mit
13,602
0
12
2,247
2,172
1,175
997
180
1
{-| Module : TTN.Util Description : Some mostly generic functions, used in the other modules. Author : Sam van Herwaarden <[email protected]> -} {-# LANGUAGE OverloadedStrings #-} module TTN.Util where import Control.Monad ( replicateM_ ) import Data.Maybe ( listToMaybe ) import Data.Char ( isAlpha, isDigit ) import Data.Text ( Text ) import Text.Pandoc ( def, readMarkdown, writeHtmlString ) import qualified Data.Text as T import qualified Data.Attoparsec.Text as P import qualified Data.Attoparsec.Combinator as P -- | This is a one-to-one copy from Network.CGI.Protocol -- More info about reads here: -- https://www.vex.net/~trebla/haskell/reads.xhtml maybeRead :: Read a => String -> Maybe a maybeRead = fmap fst . listToMaybe . reads -- | Validate non-empty property checkNE :: T.Text -> Bool checkNE = (> 0) . T.length -- | Funky zipper, type is self-explanatory innerZip :: [a] -> [[b]] -> [[(a,b)]] innerZip [] __ = [] innerZip __ [] = [] innerZip xs (ys:yss) = zip as ys : innerZip bs yss where (as, bs) = splitAt (length ys) xs zipMaybe :: [a] -> [b] -> [(a, Maybe b)] zipMaybe (x:xs) (y:ys) = (x, Just y) : zipMaybe xs ys zipMaybe (x:xs) [] = (x, Nothing) : zipMaybe xs [] zipMaybe [] __ = [] zipMaybe' :: [a] -> Maybe [b] -> [(a, Maybe b)] zipMaybe' xs Nothing = zip xs $ repeat Nothing zipMaybe' xs (Just ys) = zipMaybe xs ys -- * Functions related to parsing -- | Like normal parse but does not accept Partial parseNoPartial :: P.Parser a -> Text -> P.IResult Text a parseNoPartial p t = finalize result where result = P.parse p t finalize r = case r of P.Partial f -> finalize $ f "" _ -> r -- | Only test if the pattern is valid, don't use results testPattern :: P.Parser a -> Text -> Bool testPattern p t = test result where result = P.parse p t test r = case r of P.Fail{} -> False P.Partial f -> test $ f "" (P.Done i _) -> T.null i -- Some patterns that are sort of generic -- This holds for all: they are not exactly right... but good enough for now -- | Characters in the label parts of hostnames isHostChar :: Char -> Bool isHostChar c = isDigit c || isAlpha c || c == '-' -- | Characters in the name part of an email address isNameChar :: Char -> Bool isNameChar c = isDigit c || isAlpha c || c `elem` ("_-." :: String) -- | Simple hostname pattern hostnameP :: P.Parser () hostnameP = do P.takeWhile1 isHostChar P.many1 label return () where label = do P.satisfy $ \c -> c == '.' P.takeWhile1 isHostChar -- | Simple email address pattern emailP :: P.Parser () emailP = do P.takeWhile1 isNameChar P.satisfy $ \c -> c == '@' hostnameP -- | Date in format YYYY-MM-DD dateP :: P.Parser () dateP = do replicateM_ 4 P.digit P.satisfy (== '-') replicateM_ 2 P.digit P.satisfy (== '-') replicateM_ 2 P.digit mdToHtml :: String -> String mdToHtml src = case md of Left _ -> "<h3>Error! Sorry...</h3>" Right p -> writeHtmlString def p where md = readMarkdown def src
samvher/translatethenews
app/TTN/Util.hs
mit
3,305
0
12
932
1,006
526
480
64
3
{-# LANGUAGE OverloadedStrings #-} module Frinfo.INotify where import qualified Control.Concurrent as Conc import Control.Exception import qualified Control.Foldl as F import Control.Monad import qualified Data.Text as T import qualified Filesystem.Path.CurrentOS as FS import qualified Frinfo.Config as Config import qualified System.INotify as IN import qualified Turtle as Tur hiding (FilePath, Text) -- | Boolean blindness is not fun data Action = Add | Remove -- | Use 'IN.addWatch' to watch for 'IN.Create', 'IN.MoveIn', 'IN.Delete' and -- 'IN.MoveOut' events in all @new\/@ subfolders of 'mailFolder'. Updates the -- returned 'Conc.MVar' on each callback watchEmailFolder :: Conc.MVar Int -> IO () watchEmailFolder mvar = bracketOnError IN.initINotify IN.killINotify $ \notify -> do folders <- allNewFolders forM_ folders $ \folder -> do files <- getTotalFiles folder when (files > 0) $ Conc.modifyMVar_ mvar $ \x -> return (x + files) IN.addWatch notify [IN.Create, IN.MoveIn, IN.Delete, IN.MoveOut] (toPreludeFp folder) (eventLength mvar) -- | Turtle gives back 'FS.FilePath' but 'System.INotify' uses 'Prelude.FilePath' -- so we have to convert between the two. toPreludeFp :: FS.FilePath -> Prelude.FilePath toPreludeFp = T.unpack . either id id . FS.toText -- | Partially apply to get the callback used with 'IN.addWatch' eventLength :: Conc.MVar Int -> IN.Event -> IO () eventLength mvar (IN.Created isDir _) = updateMVar mvar Add isDir eventLength mvar (IN.MovedIn isDir _ _) = updateMVar mvar Add isDir eventLength mvar (IN.Deleted isDir _) = updateMVar mvar Remove isDir eventLength mvar (IN.MovedOut isDir _ _) = updateMVar mvar Remove isDir eventLength _ _ = return () -- | update the 'Conc.MVar' by adding 1 or removing 1 updateMVar :: Conc.MVar Int -- ^ MVar to update -> Action -- ^ 'Add' or 'Remove' the file from the count in the 'Conc.MVar' -> Bool -- ^ if the file is a folder we ignore it -> IO () updateMVar mvar action isDir = unless isDir $ case action of Add -> Conc.modifyMVar_ mvar $ \x -> return (x + 1) Remove -> Conc.modifyMVar_ mvar $ \x -> return (x - 1) -- | Find all the subfolders of 'mailFolder' called @new@ allNewFolders :: IO [FS.FilePath] allNewFolders = Tur.fold (FS.fromText . Tur.lineToText <$> dirStream) F.list where dirStream = Tur.inproc -- Turtle has a find function but it was ~30 times slower than find -- This takes ~0.02 seconds, find takes ~0.60 on my machine "find" [Config.mailFolder, "-name", "new", "-type", "d"] Tur.empty -- | Total number of files in a 'FS.FilePath' getTotalFiles :: FS.FilePath -> IO Int getTotalFiles folder = Tur.fold (Tur.ls folder) F.length
Arguggi/Frinfo
src/Frinfo/INotify.hs
mit
2,870
0
17
653
683
366
317
53
2
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} module Cenary.Syntax where -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- type AST = [GlobalStmt] type Name = String newtype Block = Block [Stmt] deriving (Show, Eq) data Op = OpAdd | OpMul | OpSub | OpDiv | OpMod | OpGt | OpLt | OpEq deriving (Eq, Show) type Length = Integer data PrimType = TInt | TChar | TBool | TArray PrimType | TMap PrimType PrimType | TFun PrimType deriving (Show, Eq) data Stmt = SVarDecl PrimType Name | SDeclAndAssignment PrimType Name Expr | SAssignment Name Expr | SArrAssignment Name Expr Expr | SMapAssignment Name Expr Expr | SWhile Expr Block | SIf Expr Block | SIfThenElse Expr Block Block | SResize Name Expr | SReturn Expr | SExpr Expr deriving (Show, Eq) data FunModifier = PureModifier deriving (Show, Eq) data FunSig = FunSig [FunModifier] String [(PrimType, Name)] deriving (Show, Eq) data GlobalStmt = GlobalDecl Stmt | GlobalFunc FunStmt deriving (Show, Eq) data FunStmt = FunStmt FunSig Block PrimType deriving (Show, Eq) data Expr = EInt Integer | EChar Char | EBool Bool | EIdentifier Name | EArrIdentifier Name Expr | EMapIdentifier Name Expr | EBinop Op Expr Expr | EFunCall String [Expr] | EArray [Expr] deriving (Show, Eq)
yigitozkavci/ivy
src/Cenary/Syntax.hs
mit
1,542
0
8
363
409
240
169
61
0
{- | Module : Bio.Motions.Callback.Class Description : Contains the definitions of various 'Callback'-related primitives. License : MIT Stability : experimental Portability : unportable -} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FunctionalDependencies #-} module Bio.Motions.Callback.Class where import Bio.Motions.Types import Bio.Motions.Representation.Class -- |Represents the mode of a callback data Mode = Pre -- ^Such a callback will be fired before a move is made | Post -- ^Such a callback will be fired after a move is made -- |Represents a callback -- -- 'm' denotes a 'Monad' (or 'Applicative') in which the callback -- is willing to operate. class Callback m (mode :: Mode) cb | cb -> mode where -- |Computes the callback's result from scratch. runCallback :: ReadRepresentation m repr => repr -- ^The representation. -> m cb -- ^The computed value. -- |Computes the callback's result after a move. updateCallback :: ReadRepresentation m repr => repr -- ^The representation before/after the move. See 'Mode'. -> cb -- ^The previous value. -> Move -- ^A move that is about to be/was made. See 'Mode'. -> m cb -- ^The new value. default updateCallback :: (ReadRepresentation m repr, mode ~ 'Post) => repr -> cb -> Move -> m cb updateCallback repr _ _ = runCallback repr -- |A convenient existential wrapper around a 'Callback' running in a 'Monad' 'm' -- -- The result of the callback is required to be 'Show'able due to the need of -- serialization. TODO: Create a better serializability constraint. data CallbackWrapper mode m where CallbackWrapper :: (Callback m mode cb, Show cb) => cb -> CallbackWrapper mode m -- |An alias for a particularily important class of callbacks, viz. score functions. type Score m cb = (Callback m 'Pre cb, Num cb, Ord cb)
amharc/motions-playground
src/Bio/Motions/Callback/Class.hs
mit
2,153
0
12
482
265
158
107
29
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-vpcconfig.html module Stratosphere.ResourceProperties.CodeBuildProjectVpcConfig where import Stratosphere.ResourceImports -- | Full data type definition for CodeBuildProjectVpcConfig. See -- 'codeBuildProjectVpcConfig' for a more convenient constructor. data CodeBuildProjectVpcConfig = CodeBuildProjectVpcConfig { _codeBuildProjectVpcConfigSecurityGroupIds :: Maybe (ValList Text) , _codeBuildProjectVpcConfigSubnets :: Maybe (ValList Text) , _codeBuildProjectVpcConfigVpcId :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON CodeBuildProjectVpcConfig where toJSON CodeBuildProjectVpcConfig{..} = object $ catMaybes [ fmap (("SecurityGroupIds",) . toJSON) _codeBuildProjectVpcConfigSecurityGroupIds , fmap (("Subnets",) . toJSON) _codeBuildProjectVpcConfigSubnets , fmap (("VpcId",) . toJSON) _codeBuildProjectVpcConfigVpcId ] -- | Constructor for 'CodeBuildProjectVpcConfig' containing required fields as -- arguments. codeBuildProjectVpcConfig :: CodeBuildProjectVpcConfig codeBuildProjectVpcConfig = CodeBuildProjectVpcConfig { _codeBuildProjectVpcConfigSecurityGroupIds = Nothing , _codeBuildProjectVpcConfigSubnets = Nothing , _codeBuildProjectVpcConfigVpcId = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-vpcconfig.html#cfn-codebuild-project-vpcconfig-securitygroupids cbpvcSecurityGroupIds :: Lens' CodeBuildProjectVpcConfig (Maybe (ValList Text)) cbpvcSecurityGroupIds = lens _codeBuildProjectVpcConfigSecurityGroupIds (\s a -> s { _codeBuildProjectVpcConfigSecurityGroupIds = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-vpcconfig.html#cfn-codebuild-project-vpcconfig-subnets cbpvcSubnets :: Lens' CodeBuildProjectVpcConfig (Maybe (ValList Text)) cbpvcSubnets = lens _codeBuildProjectVpcConfigSubnets (\s a -> s { _codeBuildProjectVpcConfigSubnets = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-vpcconfig.html#cfn-codebuild-project-vpcconfig-vpcid cbpvcVpcId :: Lens' CodeBuildProjectVpcConfig (Maybe (Val Text)) cbpvcVpcId = lens _codeBuildProjectVpcConfigVpcId (\s a -> s { _codeBuildProjectVpcConfigVpcId = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/CodeBuildProjectVpcConfig.hs
mit
2,503
0
12
253
355
202
153
32
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE ScopedTypeVariables #-} import Codec.Compression.GZip import Control.Applicative import Control.Lens import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Maybe import qualified Data.ByteString.Lazy.Char8 as LB import Data.Default import qualified Data.Foldable as F import Data.List (foldl') import System.Environment import System.FilePath import System.IO as IO -- import HEP.Automation.EventGeneration.Config import HEP.Automation.MadGraph.Model import HEP.Automation.MadGraph.Model.SM import HEP.Automation.MadGraph.SetupType import HEP.Automation.MadGraph.Type import HEP.Automation.MadGraph.Util import HEP.Parser.LHCOAnalysis.PhysObj import HEP.Parser.LHCOAnalysis.Parse import HEP.Storage.WebDAV.CURL import HEP.Storage.WebDAV.Type -- import HEP.Physics.Analysis.Common.XSecNTotNum -- import qualified Paths_madgraph_auto as PMadGraph import qualified Paths_madgraph_auto_model as PModel -- | getScriptSetup :: IO ScriptSetup getScriptSetup = do workdir <- getEnv "WORKDIR" -- homedir <- getHomeDirectory mdldir <- (</> "template") <$> PModel.getDataDir rundir <- (</> "template") <$> PMadGraph.getDataDir return $ SS { modeltmpldir = mdldir , runtmpldir = rundir , sandboxdir = workdir </> "montecarlo/sandbox" , mg5base = workdir </> "montecarlo/MG5_aMC_v2_1_2" , mcrundir = workdir </> "montecarlo/mcrun" , pythia8dir = "" , pythia8toHEPEVT = "" , hepevt2stdhep = "" , pythiapgsdir = "/nix/store/8c0ja4dh6rlii1xnbq48c9bcii57wly4-pythia-pgs-2.4.0/share/pythia-pgs" } -- | processSetup :: ProcessSetup SM processSetup = PS { model = SM , process = MGProc [] [ "g g > t t~ QED=0" ] , processBrief = "ttbarQCD" , workname = "ttbarQCD" , hashSalt = HashSalt Nothing } -- | pset :: ModelParam SM pset = SMParam -- | rsetup :: Double -> Int -> RunSetup rsetup sqrts n = RS { numevent = 10000 , machine = Parton (0.5*sqrts) ATLAS -- LHC14 ATLAS , rgrun = Auto , rgscale = 200.0 , match = NoMatch , cut = NoCut -- DefCut , pythia = NoPYTHIA -- RunPYTHIA , lhesanitizer = [] , pgs = NoPGS -- RunPGS (Cone 0.4, WithTau) , uploadhep = NoUploadHEP , setnum = n } -- | getWSetup :: (Double,Int) -> IO (WorkSetup SM) getWSetup (sqrts,n) = WS <$> getScriptSetup <*> pure processSetup <*> pure pset <*> pure (rsetup sqrts n) <*> pure (WebDAVRemoteDir "montecarlo/HeavyHiggs/interfere_test") genset = [ (sqrts,n) | sqrts <- [350,360..850] {- ,420..1000] -} , n <- [1] ] checkAndDownload :: WebDAVConfig -> WebDAVRemoteDir -> FilePath -> MaybeT IO () checkAndDownload cfg rdir fpath = do b <- liftIO $ doesFileExistInDAV cfg rdir fpath guard b liftIO $ downloadFile False cfg rdir fpath liftIO $ putStrLn $ fpath ++ " is successfully downloaded" readxsec :: Handle -> Double -> IO () readxsec h sqrts = do ws1 <- getWSetup (sqrts,1) let rname = makeRunName (ws_psetup ws1) (ws_param ws1) (ws_rsetup ws1) let pkey = "/afs/cern.ch/work/i/ikim/private/webdav/priv.txt" pswd = "/afs/cern.ch/work/i/ikim/private/webdav/cred.txt" Just cr <- getCredential pkey pswd let whost = "http://top.physics.lsa.umich.edu:10080/webdav/" wdavcfg = WebDAVConfig cr whost wdavrdir = WebDAVRemoteDir "montecarlo/HeavyHiggs/interfere_test" mr <- xsec XSecLHE wdavcfg wdavrdir rname F.forM_ mr $ \r -> do print (sqrts,r) hPutStrLn h (show sqrts ++ " " ++ show r) main = do withFile "myresultqcd.dat" WriteMode $ \h -> do mapM_ (readxsec h) [350,360..850]
wavewave/lhc-analysis-collection
heavyhiggs/xsecgraphQCD.hs
gpl-3.0
3,901
0
15
968
965
546
419
95
1
-- Various utility functions that make writing the parser functions easier and -- cleaner by separating out common patterns module Parser.Utils ( Parser(..) , ParserResult , ParserResultList , ParserConsumed , consume , advance , many , manySep , leftRecursive , rightRecursive , notFound ) where import Lexer import Parser.Ast -- Define the Parser Monad newtype Parser a = Parser a -- Use the values for `a` as defined below deriving Show type ParserResult = Parser (Ast, [Token]) type ParserResultList = Parser ([Ast], [Token]) type ParserConsumed = Parser [Token] instance Monad Parser where return = Parser (Parser tokens) >>= subtreeParser = subtreeParser tokens -- Discard a specific token consume :: [Token] -> Token -> ParserConsumed consume (tHead:tTail) matched | tHead == matched = return tTail | otherwise = error $ "Can't match expected '" ++ (show matched) ++ "' with '" ++ (show tHead) ++ "'" consume _ matched = error $ "Expecting '" ++ (show matched) ++ "' but got EOF" -- Discard the next token, not checking what it actually is -- This is like consume, but less safe. Use it instead of consume only after you -- already checked it yourself (in a conditional block or something) advance :: [Token] -> ParserConsumed advance (_:tTail) = return tTail -- An error should not occur here if you already checked for the token yourself advance _ = error $ "Expecting discardable symbol but got EOF" -- Repeatedly call a parser **until** a end conditional is matched. There may be -- zero or more results. many :: [Token] -> ([Token] -> ParserResult) -> ([Token] -> Bool) -> ParserResultList many ta par cond = if cond ta then return ([], ta) else do (ab, tb) <- par ta (ac, tc) <- many tb par cond return (ab : ac, tc) -- Like many, but instead of taking a conditional function, it takes an expected -- separator. When the separator is no longer matched, it returns a -- ParserResultList. Because of parsing limitations, we assume one or more -- results. An empty list will fail. manySep :: [Token] -> ([Token] -> ParserResult) -> Token -> ParserResultList manySep tokens parsingFunc separator = do (aa, ta) <- parsingFunc tokens -- we assume at least one match (ab, tb) <- many ta consumingParsingFunc sepCond return (aa : ab, tb) where -- Consume a separator and then parse an element consumingParsingFunc partialTokens = consume partialTokens separator >>= parsingFunc -- Stop when the separator is no longer matched or on EOF sepCond (t:_) = t /= separator -- the separator is no longer matched sepCond _ = True -- we hit an EOF -- For simple left-recursive grammars such as -- Ta -> Ta 'aug' Tc -- -> Tc -- It first generates a flat list of the subtrees, and then forms a recursive -- tree with the Ast constructor leftRecursive :: [Token] -> ([Token] -> ParserResult) -> Token -> (Ast -> Ast -> Ast) -> ParserResult leftRecursive tokens parsingFunc separator astType = do (aa, ta) <- manySep tokens parsingFunc separator return (buildTree aa, ta) where buildTree subList = if length subList == 1 then head subList else astType (buildTree $ init subList) (last subList) rightRecursive :: [Token] -> ([Token] -> ParserResult) -> Token -> (Ast -> Ast -> Ast) -> ParserResult rightRecursive tokens parsingFunc separator astType = do (aa, ta) <- manySep tokens parsingFunc separator return (buildTree aa, ta) where buildTree subList = if length subList == 1 then head subList else astType (head subList) (buildTree $ tail subList) -- Generate error handler when a matcher fails notFound :: String -> [Token] -> b notFound expected (token:_) = error $ "Expected " ++ expected ++ " but instead found (" ++ (show token) ++ ")" notFound expected _ = error $ "Expected " ++ expected ++ " but instead found EOF"
bgw/hs-rpal
src/Parser/Utils.hs
gpl-3.0
4,287
0
11
1,203
965
522
443
69
2
{-# LANGUAGE OverloadedStrings , TypeFamilies , StandaloneDeriving , DeriveDataTypeable , TupleSections , ViewPatterns #-} module Text.Gedcom.Types where import Control.Applicative import Data.ByteString (ByteString) import Data.Data import Data.Functor.Foldable import Data.Typeable() import Data.Generics.Uniplate.Operations import Data.Generics.Uniplate.Data() import Text.Gedcom.Utils import qualified Safe as S data TreeF a r = TreeF a [r] deriving (Eq, Show, Data, Typeable) instance Functor (TreeF a) where fmap g (TreeF v rs) = TreeF v (fmap g rs) newtype XRef = XRef ByteString deriving (Eq, Show, Data, Typeable) data Payload = X XRef | B ByteString | Null deriving (Eq, Show, Data, Typeable) data Record = Record ByteString Payload deriving (Eq, Show, Data, Typeable) type RawName = ByteString type Surname = ByteString type GivenName = ByteString type Place = ByteString type Date = ByteString data Death = Death Place Date deriving (Eq, Show, Data, Typeable) data Birth = Birth Place Date deriving (Eq, Show, Data, Typeable) data Burial = Burial Place Date deriving (Eq, Show, Data, Typeable) data Marriage = Marriage Place Date deriving (Eq, Show, Data, Typeable) data Name = Name RawName (Maybe GivenName) (Maybe Surname) deriving (Eq, Show, Data, Typeable) data Typed = D Death | Bi Birth | Bu Burial | N Name | M Marriage deriving (Eq, Show, Data, Typeable) data Mixed = U Record | T Typed deriving (Eq, Show, Data, Typeable) type Tree a = Fix (TreeF a) type Records = Tree Mixed data Gedcom = Gedcom XRef ByteString [Records] deriving (Eq, Show, Typeable, Data) tag :: Records -> Maybe ByteString tag (Fix (TreeF (U (Record t _)) _)) = Just t tag _ = Nothing value :: Records -> Maybe ByteString value (Fix (TreeF (U (Record _ (B v))) _)) = Just v value _ = Nothing xref :: Records -> Maybe ByteString xref (Fix (TreeF (U (Record _ (X (XRef x)))) _)) = Just x xref _ = Nothing tagXRef :: Records -> Maybe (ByteString, ByteString) tagXRef (Fix (TreeF (U (Record t (X (XRef x)))) _)) = Just (t,x) tagXRef _ = Nothing tagValue :: Records -> Maybe (ByteString, ByteString) tagValue (Fix (TreeF (U (Record t (B v))) _)) = Just (t,v) tagValue _ = Nothing untyped :: Records -> Maybe Record untyped (Fix (TreeF (U x) _)) = Just x untyped _ = Nothing typed :: Records -> Maybe Typed typed (Fix (TreeF (T x) _)) = Just x typed _ = Nothing viewTV :: ByteString -> Records -> Maybe (Payload, [Records]) viewTV t (Fix (TreeF (U (Record k v)) rs)) | k == t = Just (v,rs) viewTV _ _ = Nothing viewTX :: ByteString -> Records -> Maybe (ByteString, ByteString) viewTX t (Fix (TreeF (U (Record k (X (XRef x)))) rs)) | k == t = Just (k,x) viewTX _ _ = Nothing matchTag :: Records -> ByteString -> Bool matchTag (tag -> Just x) t = x == t matchTag _ _ = False viewTag :: ByteString -> [Records] -> Maybe (Records, [Records]) viewTag = find1By matchTag viewTag2 :: ByteString -> ByteString -> [Records] -> Maybe ((Records,Records), [Records]) viewTag2 = find2By matchTag viewMaybeTag :: ByteString -> [Records] -> (Maybe Records, [Records]) viewMaybeTag = findMaybe1By matchTag viewMaybeTag2 :: ByteString -> ByteString -> [Records] -> ((Maybe Records, Maybe Records), [Records]) viewMaybeTag2 = findMaybe2By matchTag -- | rewrite simple events like Birth / Death / Burial into typed tags placerw :: ByteString -- ^ tag -> (Place -> Date -> Typed) -- ^ ctor -> Records -> Maybe Records placerw etag ctor (viewTV etag -> Just ( Null , ((viewTag2 "PLAC" "DATE") -> Just (ts, rs)) )) = f <$> event where f = (\e -> Fix (TreeF (T e) rs)) ((value -> place), (value -> date)) = ts event = ctor <$> place <*> date placerw _ _ _ = Nothing deathrw :: Records -> Maybe Records deathrw = placerw "DEAT" (\p d -> D $ Death p d) birthrw :: Records -> Maybe Records birthrw = placerw "BIRT" (\p d -> Bi $ Birth p d) burialrw :: Records -> Maybe Records burialrw = placerw "BURI" (\p d -> Bu $ Burial p d) marriagerw :: Records -> Maybe Records marriagerw = placerw "MARR" (\p d -> M $ Marriage p d) namerw :: Records -> Maybe Records namerw (viewTV "NAME" -> Just ( B rawName , ((viewMaybeTag2 "GIVN" "SURN") -> ((mg,ms),rs)) )) = Just $ Fix (TreeF (T n) rs) where n = N $ Name rawName (mg >>= value) (ms >>= value) namerw _ = Nothing rewriteTyped :: [Records] -> [Records] rewriteTyped = transformBi g where g (deathrw -> Just x) = x g (birthrw -> Just x) = x g (burialrw -> Just x) = x g (namerw -> Just x) = x g (marriagerw -> Just x) = x g x = x name :: [Records] -> Maybe Name name rs = S.headMay $ do (typed -> Just (N n@(Name _ _ _))) <- childrenBi rs return n death :: [Records] -> Maybe Death death rs = S.headMay $ do (typed -> Just (D d@(Death _ _))) <- childrenBi rs return d birth :: [Records] -> Maybe Birth birth rs = S.headMay $ do (typed -> Just (Bi b@(Birth _ _))) <- childrenBi rs return b burial :: [Records] -> Maybe Burial burial rs = S.headMay $ do (typed -> Just (Bu b@(Burial _ _))) <- childrenBi rs return b marriage :: [Records] -> Maybe Marriage marriage rs = S.headMay $ do (typed -> Just (M m@(Marriage _ _))) <- childrenBi rs return m wife :: [Records] -> Maybe ByteString wife = S.headMay . xrefsForTag "WIFE" husb :: [Records] -> Maybe ByteString husb = S.headMay . xrefsForTag "HUSB" children :: [Records] -> [ByteString] children = xrefsForTag "CHIL" xrefsForTag :: ByteString -> [Records] -> [ByteString] xrefsForTag bs rs = do (viewTX bs -> Just (_,x)) <- childrenBi rs return x
benjumanji/gedcom
src/Text/Gedcom/Types.hs
gpl-3.0
5,951
0
17
1,515
2,543
1,331
1,212
164
6
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module ArbitraryGens ( arith, bool ) where import CodeBuilders import Control.Applicative ((<$>), (<*>)) import LLVMRepresentation import Test.QuickCheck import Types arith :: forall a. Arith a => Gen (NodeBuilder a) arith = sized tree' where tree' 0 = return . Const <$> arbitrary tree' n = oneof [return . Const <$> arbitrary, mkArithM <$> split 2 <*> arbitrary <*> split 2, mkIfM <$> subBool 3 <*> split 3 <*> split 3 ] where split m = tree' (n `div` m) subBool m = resize (n `div` m) (bool (getType :: a)) bool :: forall a. Arith a => a -> Gen (NodeBuilder Bool) bool _ = sized tree' where tree' 0 = return . Const <$> arbitrary tree' n = oneof [return . Const <$> arbitrary, mkCondM <$> subCond <*> arbitrary <*> subCond, mkIfM <$> subBool <*> subBool <*> subBool ] where subCond = resize (n `div` 2) (arith :: Gen (NodeBuilder a)) subBool = tree' (n `div` 3)
GaroBrik/haskell-compiler
test/ArbitraryGens.hs
gpl-3.0
1,219
0
13
455
384
206
178
26
2
module Types where import GEGL import qualified Data.Map as M data UserData = UserData { nodeGraph :: M.Map MapKey GeglNode , buffer :: GeglBuffer , state :: State , screen :: ScreenMode , tminus :: Double , mouseAreas :: M.Map Assoc MouseArea , numberChanged :: Bool } data State = Setting | Running data MapKey = KeyRoot | KeySink | KeyDark | KeyNorm | KeyWarn | KeyRed | KeyScale | KeyClock | KeyBtnS | KeyBtn deriving (Eq, Ord) data ScreenMode = Full | Windowed deriving (Eq) data MouseArea = MouseArea { area :: GeglRectangle , assoc :: Assoc } data Assoc = Hx | Hi | Mx | Mi | Sx | Si deriving (Eq, Ord)
nek0/countdown.hs
src/Types.hs
gpl-3.0
686
0
10
192
206
127
79
41
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ViewPatterns #-} -- | -- Copyright : (c) 2010-2012 Benedikt Schmidt & Simon Meier -- License : GPL v3 (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- Portability : GHC only -- -- This module implements all rules that do not result in case distinctions -- and equation solving. Some additional cases may although result from -- splitting over multiple AC-unifiers. Note that a few of these rules are -- implemented directly in the methods for inserting constraints to the -- constraint system. These methods are provided by -- "Theory.Constraint.Solver.Reduction". -- module Theory.Constraint.Solver.Simplify ( simplifySystem ) where import Debug.Trace import Prelude hiding (id, (.)) import qualified Data.DAG.Simple as D -- import Data.Data -- import Data.Either (partitionEithers) import qualified Data.Foldable as F import Data.List import qualified Data.Map as M import Data.Monoid (Monoid(..)) import qualified Data.Set as S import Control.Basics import Control.Category import Control.Monad.Disj -- import Control.Monad.Fresh import Control.Monad.Reader import Control.Monad.State (gets) import Extension.Data.Label import Extension.Prelude import Theory.Constraint.Solver.Goals import Theory.Constraint.Solver.Reduction -- import Theory.Constraint.Solver.Types import Theory.Constraint.System import Theory.Model import Theory.Text.Pretty -- | Apply CR-rules that don't result in case splitting until the constraint -- system does not change anymore. simplifySystem :: Reduction () simplifySystem = do isdiff <- getM sDiffSystem -- Start simplification, indicating that some change happened go (0 :: Int) [Changed] -- Add all ordering constraint implied by CR-rule *N6*. if isdiff then do removeSolvedSplitGoals else do exploitUniqueMsgOrder -- Remove equation split goals that do not exist anymore removeSolvedSplitGoals where go n changes0 -- We stop as soon as all simplification steps have been run without -- reporting any change to the constraint systemm. | Unchanged == mconcat changes0 = return () | otherwise = do -- Store original system for reporting se0 <- gets id -- Perform one initial substitution. We do not have to consider its -- changes as 'substSystem' is idempotent. void substSystem -- Perform one simplification pass. isdiff <- getM sDiffSystem -- In the diff case, we cannot enfore N4-N6. if isdiff then do (c1,c3) <- enforceFreshNodeUniqueness c4 <- enforceEdgeUniqueness c5 <- solveUniqueActions c6 <- reduceFormulas c7 <- evalFormulaAtoms c8 <- insertImpliedFormulas -- Report on looping behaviour if necessary let changes = filter ((Changed ==) . snd) $ [ ("unique fresh instances (DG4)", c1) -- , ("unique K↓-facts (N5↓)", c2) , ("unique K↑-facts (N5↑)", c3) , ("unique (linear) edges (DG2 and DG3)", c4) , ("solve unambiguous actions (S_@)", c5) , ("decompose trace formula", c6) , ("propagate atom valuation to formula", c7) , ("saturate under ∀-clauses (S_∀)", c8) ] traceIfLooping | n <= 10 = id | otherwise = trace $ render $ vsep [ text "Simplifier iteration" <-> int n <> colon , fsep $ text "The reduction-rules for" : (punctuate comma $ map (text . fst) changes) ++ [text "were applied to the following constraint system."] , nest 2 (prettySystem se0) ] traceIfLooping $ go (n + 1) (map snd changes) else do (c1,c2,c3) <- enforceNodeUniqueness c4 <- enforceEdgeUniqueness c5 <- solveUniqueActions c6 <- reduceFormulas c7 <- evalFormulaAtoms c8 <- insertImpliedFormulas -- Report on looping behaviour if necessary let changes = filter ((Changed ==) . snd) $ [ ("unique fresh instances (DG4)", c1) , ("unique K↓-facts (N5↓)", c2) , ("unique K↑-facts (N5↑)", c3) , ("unique (linear) edges (DG2 and DG3)", c4) , ("solve unambiguous actions (S_@)", c5) , ("decompose trace formula", c6) , ("propagate atom valuation to formula", c7) , ("saturate under ∀-clauses (S_∀)", c8) ] traceIfLooping | n <= 10 = id | otherwise = trace $ render $ vsep [ text "Simplifier iteration" <-> int n <> colon , fsep $ text "The reduction-rules for" : (punctuate comma $ map (text . fst) changes) ++ [text "were applied to the following constraint system."] , nest 2 (prettySystem se0) ] traceIfLooping $ go (n + 1) (map snd changes) -- | CR-rule *N6*: add ordering constraints between all KU-actions and -- KD-conclusions. exploitUniqueMsgOrder :: Reduction () exploitUniqueMsgOrder = do kdConcs <- gets (M.fromList . map (\(i, _, m) -> (m, i)) . allKDConcs) kuActions <- gets (M.fromList . map (\(i, _, m) -> (m, i)) . allKUActions) -- We can add all elements where we have an intersection F.mapM_ (uncurry insertLess) $ M.intersectionWith (,) kdConcs kuActions -- | CR-rules *DG4*, *N5_u*, and *N5_d*: enforcing uniqueness of *Fresh* rule -- instances, *KU*-actions, and *KD*-conclusions. -- -- Returns 'Changed' if a change was done. enforceNodeUniqueness :: Reduction (ChangeIndicator, ChangeIndicator, ChangeIndicator) enforceNodeUniqueness = (,,) <$> (merge (const $ return Unchanged) freshRuleInsts) <*> (merge (solveRuleEqs SplitNow) kdConcs) <*> (merge (solveFactEqs SplitNow) kuActions) where -- *DG4* freshRuleInsts se = do (i, ru) <- M.toList $ get sNodes se guard (isFreshRule ru) return (ru, ((), i)) -- no need to merge equal rules -- *N5_d* kdConcs sys = (\(i, ru, m) -> (m, (ru, i))) <$> allKDConcs sys -- *N5_u* kuActions se = (\(i, fa, m) -> (m, (fa, i))) <$> allKUActions se merge :: Ord b => ([Equal a] -> Reduction ChangeIndicator) -- ^ Equation solver for 'Equal a' -> (System -> [(b,(a,NodeId))]) -- ^ Candidate selector -> Reduction ChangeIndicator -- merge solver candidates = do changes <- gets (map mergers . groupSortOn fst . candidates) mconcat <$> sequence changes where mergers [] = unreachable "enforceUniqueness" mergers ((_,(xKeep, iKeep)):remove) = mappend <$> solver (map (Equal xKeep . fst . snd) remove) <*> solveNodeIdEqs (map (Equal iKeep . snd . snd) remove) -- | CR-rule *DG4*: enforcing uniqueness of *Fresh* rule -- instances. -- -- Returns 'Changed' if a change was done. enforceFreshNodeUniqueness :: Reduction (ChangeIndicator, ChangeIndicator) enforceFreshNodeUniqueness = (,) <$> (merge (const $ return Unchanged) freshRuleInsts) <*> (merge (solveFactEqs SplitNow) kuActions) where -- *DG4* freshRuleInsts se = do (i, ru) <- M.toList $ get sNodes se guard (isFreshRule ru) return (ru, ((), i)) -- no need to merge equal rules -- *N5_u* kuActions se = (\(i, fa, m) -> (m, (fa, i))) <$> allKUActions se merge :: Ord b => ([Equal a] -> Reduction ChangeIndicator) -- ^ Equation solver for 'Equal a' -> (System -> [(b,(a,NodeId))]) -- ^ Candidate selector -> Reduction ChangeIndicator -- merge solver candidates = do changes <- gets (map mergers . groupSortOn fst . candidates) mconcat <$> sequence changes where mergers [] = unreachable "enforceFreshUniqueness" mergers ((_,(xKeep, iKeep)):remove) = mappend <$> solver (map (Equal xKeep . fst . snd) remove) <*> solveNodeIdEqs (map (Equal iKeep . snd . snd) remove) -- | CR-rules *DG2_1* and *DG3*: merge multiple incoming edges to all facts -- and multiple outgoing edges from linear facts. enforceEdgeUniqueness :: Reduction ChangeIndicator enforceEdgeUniqueness = do se <- gets id let edges = S.toList (get sEdges se) (<>) <$> mergeNodes eSrc eTgt edges <*> mergeNodes eTgt eSrc (filter (proveLinearConc se . eSrc) edges) where -- | @proveLinearConc se (v,i)@ tries to prove that the @i@-th -- conclusion of node @v@ is a linear fact. proveLinearConc se (v, i) = maybe False (isLinearFact . (get (rConc i))) $ M.lookup v $ get sNodes se -- merge the nodes on the 'mergeEnd' for edges that are equal on the -- 'compareEnd' mergeNodes mergeEnd compareEnd edges | null eqs = return Unchanged | otherwise = do -- all indices of merged premises and conclusions must be equal contradictoryIf (not $ and [snd l == snd r | Equal l r <- eqs]) -- nodes must be equal solveNodeIdEqs $ map (fmap fst) eqs where eqs = concatMap (merge mergeEnd) $ groupSortOn compareEnd edges merge _ [] = error "exploitEdgeProps: impossible" merge proj (keep:remove) = map (Equal (proj keep) . proj) remove -- | Special version of CR-rule *S_at*, which is only applied to solve actions -- that are guaranteed not to result in case splits. solveUniqueActions :: Reduction ChangeIndicator solveUniqueActions = do rules <- nonSilentRules <$> askM pcRules actionAtoms <- gets unsolvedActionAtoms -- FIXME: We might cache the result of this static computation in the -- proof-context, e.g., in the 'ClassifiedRules'. let uniqueActions = [ x | [x] <- group (sort ruleActions) ] ruleActions = [ (tag, length ts) | ru <- rules, Fact tag ts <- get rActs ru ] isUnique (Fact tag ts) = (tag, length ts) `elem` uniqueActions -- multiset union leads to case-splits because there -- are multiple unifiers && null [ () | t <- ts, FUnion _ <- return (viewTerm2 t) ] trySolve (i, fa) | isUnique fa = solveGoal (ActionG i fa) >> return Changed | otherwise = return Unchanged mconcat <$> mapM trySolve actionAtoms -- | Reduce all formulas as far as possible. See 'insertFormula' for the -- CR-rules exploited in this step. Note that this step is normally only -- required to decompose the formula in the initial constraint system. reduceFormulas :: Reduction ChangeIndicator reduceFormulas = do formulas <- getM sFormulas applyChangeList $ do fm <- S.toList formulas guard (reducibleFormula fm) return $ do modM sFormulas $ S.delete fm insertFormula fm -- | Try to simplify the atoms contained in the formulas. See -- 'partialAtomValuation' for an explanation of what CR-rules are exploited -- here. evalFormulaAtoms :: Reduction ChangeIndicator evalFormulaAtoms = do ctxt <- ask valuation <- gets (partialAtomValuation ctxt) formulas <- getM sFormulas applyChangeList $ do fm <- S.toList formulas case simplifyGuarded valuation fm of Just fm' -> return $ do case fm of GDisj disj -> markGoalAsSolved "simplified" (DisjG disj) _ -> return () modM sFormulas $ S.delete fm modM sSolvedFormulas $ S.insert fm insertFormula fm' Nothing -> [] -- | A partial valuation for atoms. The return value of this function is -- interpreted as follows. -- -- @partialAtomValuation ctxt sys ato == Just True@ if for every valuation -- @theta@ satisfying the graph constraints and all atoms in the constraint -- system @sys@, the atom @ato@ is also satisfied by @theta@. -- -- The interpretation for @Just False@ is analogous. @Nothing@ is used to -- represent *unknown*. -- partialAtomValuation :: ProofContext -> System -> LNAtom -> Maybe Bool partialAtomValuation ctxt sys = eval where runMaude = (`runReader` get pcMaudeHandle ctxt) before = alwaysBefore sys lessRel = rawLessRel sys nodesAfter = \i -> filter (i /=) $ S.toList $ D.reachableSet [i] lessRel -- | 'True' iff there in every solution to the system the two node-ids are -- instantiated to a different index *in* the trace. nonUnifiableNodes :: NodeId -> NodeId -> Bool nonUnifiableNodes i j = maybe False (not . runMaude) $ (unifiableRuleACInsts) <$> M.lookup i (get sNodes sys) <*> M.lookup j (get sNodes sys) -- | Try to evaluate the truth value of this atom in all models of the -- constraint system 'sys'. eval ato = case ato of Action (ltermNodeId' -> i) fa | ActionG i fa `M.member` get sGoals sys -> Just True | otherwise -> case M.lookup i (get sNodes sys) of Just ru | any (fa ==) (get rActs ru) -> Just True | all (not . runMaude . unifiableLNFacts fa) (get rActs ru) -> Just False _ -> Nothing Less (ltermNodeId' -> i) (ltermNodeId' -> j) | i == j || j `before` i -> Just False | i `before` j -> Just True | isLast sys i && isInTrace sys j -> Just False | isLast sys j && isInTrace sys i && nonUnifiableNodes i j -> Just True | otherwise -> Nothing EqE x y | x == y -> Just True | not (runMaude (unifiableLNTerms x y)) -> Just False | otherwise -> case (,) <$> ltermNodeId x <*> ltermNodeId y of Just (i, j) | i `before` j || j `before` i -> Just False | nonUnifiableNodes i j -> Just False _ -> Nothing Last (ltermNodeId' -> i) | isLast sys i -> Just True | any (isInTrace sys) (nodesAfter i) -> Just False | otherwise -> case get sLastAtom sys of Just j | nonUnifiableNodes i j -> Just False _ -> Nothing -- | CR-rule *S_∀*: insert all newly implied formulas. insertImpliedFormulas :: Reduction ChangeIndicator insertImpliedFormulas = do sys <- gets id hnd <- getMaudeHandle applyChangeList $ do clause <- (S.toList $ get sFormulas sys) ++ (S.toList $ get sLemmas sys) implied <- impliedFormulas hnd sys clause if ( implied `S.notMember` get sFormulas sys && implied `S.notMember` get sSolvedFormulas sys ) then return (insertFormula implied) else []
ekr/tamarin-prover
lib/theory/src/Theory/Constraint/Solver/Simplify.hs
gpl-3.0
16,452
0
26
5,885
3,628
1,872
1,756
249
7
module Filter.Util (splitIt, intoChunks,formatChunk, unlines',sanatizeHtml) where import Prelude import Data.Char (isDigit) import Text.Blaze.Html import Text.Blaze.Html.Renderer.String splitIt [] = ([],[]) splitIt l = case break (== '\n') l of (h,t@(_:x:xs)) -> if x == '|' then let (h',t') = splitIt (x:xs) in (h ++ ('\n':h'),t') else (h,x:xs) (h,"\n") -> (h,[]) y -> y intoChunks [] = [] intoChunks l = case splitIt l of ([],t) -> intoChunks t (h,t) -> h : intoChunks t formatChunk = map cleanProof . lines where cleanProof ('|':xs) = dropWhile (\y -> isDigit y || (y == '.')) xs cleanProof l = l unlines' [] = "" unlines' (x:[]) = x unlines' (x:xs) = x ++ '\n':unlines' xs sanatizeHtml = renderHtml . toHtml
opentower/carnap
Carnap-Server/Filter/Util.hs
gpl-3.0
916
2
10
321
378
211
167
24
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.SourceRepo.Types.Product -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.SourceRepo.Types.Product where import Network.Google.Prelude import Network.Google.SourceRepo.Types.Sum -- | The \`Status\` type defines a logical error model that is suitable for -- different programming environments, including REST APIs and RPC APIs. It -- is used by [gRPC](https:\/\/github.com\/grpc). Each \`Status\` message -- contains three pieces of data: error code, error message, and error -- details. You can find out more about this error model and how to work -- with it in the [API Design -- Guide](https:\/\/cloud.google.com\/apis\/design\/errors). -- -- /See:/ 'status' smart constructor. data Status = Status' { _sDetails :: !(Maybe [StatusDetailsItem]) , _sCode :: !(Maybe (Textual Int32)) , _sMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Status' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sDetails' -- -- * 'sCode' -- -- * 'sMessage' status :: Status status = Status' {_sDetails = Nothing, _sCode = Nothing, _sMessage = Nothing} -- | A list of messages that carry the error details. There is a common set -- of message types for APIs to use. sDetails :: Lens' Status [StatusDetailsItem] sDetails = lens _sDetails (\ s a -> s{_sDetails = a}) . _Default . _Coerce -- | The status code, which should be an enum value of google.rpc.Code. sCode :: Lens' Status (Maybe Int32) sCode = lens _sCode (\ s a -> s{_sCode = a}) . mapping _Coerce -- | A developer-facing error message, which should be in English. Any -- user-facing error message should be localized and sent in the -- google.rpc.Status.details field, or localized by the client. sMessage :: Lens' Status (Maybe Text) sMessage = lens _sMessage (\ s a -> s{_sMessage = a}) instance FromJSON Status where parseJSON = withObject "Status" (\ o -> Status' <$> (o .:? "details" .!= mempty) <*> (o .:? "code") <*> (o .:? "message")) instance ToJSON Status where toJSON Status'{..} = object (catMaybes [("details" .=) <$> _sDetails, ("code" .=) <$> _sCode, ("message" .=) <$> _sMessage]) -- | Specifies the audit configuration for a service. The configuration -- determines which permission types are logged, and what identities, if -- any, are exempted from logging. An AuditConfig must have one or more -- AuditLogConfigs. If there are AuditConfigs for both \`allServices\` and -- a specific service, the union of the two AuditConfigs is used for that -- service: the log_types specified in each AuditConfig are enabled, and -- the exempted_members in each AuditLogConfig are exempted. Example Policy -- with multiple AuditConfigs: { \"audit_configs\": [ { \"service\": -- \"allServices\", \"audit_log_configs\": [ { \"log_type\": \"DATA_READ\", -- \"exempted_members\": [ \"user:jose\'example.com\" ] }, { \"log_type\": -- \"DATA_WRITE\" }, { \"log_type\": \"ADMIN_READ\" } ] }, { \"service\": -- \"sampleservice.googleapis.com\", \"audit_log_configs\": [ { -- \"log_type\": \"DATA_READ\" }, { \"log_type\": \"DATA_WRITE\", -- \"exempted_members\": [ \"user:aliya\'example.com\" ] } ] } ] } For -- sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ -- logging. It also exempts jose\'example.com from DATA_READ logging, and -- aliya\'example.com from DATA_WRITE logging. -- -- /See:/ 'auditConfig' smart constructor. data AuditConfig = AuditConfig' { _acService :: !(Maybe Text) , _acAuditLogConfigs :: !(Maybe [AuditLogConfig]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AuditConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acService' -- -- * 'acAuditLogConfigs' auditConfig :: AuditConfig auditConfig = AuditConfig' {_acService = Nothing, _acAuditLogConfigs = Nothing} -- | Specifies a service that will be enabled for audit logging. For example, -- \`storage.googleapis.com\`, \`cloudsql.googleapis.com\`. \`allServices\` -- is a special value that covers all services. acService :: Lens' AuditConfig (Maybe Text) acService = lens _acService (\ s a -> s{_acService = a}) -- | The configuration for logging of each type of permission. acAuditLogConfigs :: Lens' AuditConfig [AuditLogConfig] acAuditLogConfigs = lens _acAuditLogConfigs (\ s a -> s{_acAuditLogConfigs = a}) . _Default . _Coerce instance FromJSON AuditConfig where parseJSON = withObject "AuditConfig" (\ o -> AuditConfig' <$> (o .:? "service") <*> (o .:? "auditLogConfigs" .!= mempty)) instance ToJSON AuditConfig where toJSON AuditConfig'{..} = object (catMaybes [("service" .=) <$> _acService, ("auditLogConfigs" .=) <$> _acAuditLogConfigs]) -- | Cloud Source Repositories configuration of a project. -- -- /See:/ 'projectConfig' smart constructor. data ProjectConfig = ProjectConfig' { _pcPubsubConfigs :: !(Maybe ProjectConfigPubsubConfigs) , _pcEnablePrivateKeyCheck :: !(Maybe Bool) , _pcName :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcPubsubConfigs' -- -- * 'pcEnablePrivateKeyCheck' -- -- * 'pcName' projectConfig :: ProjectConfig projectConfig = ProjectConfig' { _pcPubsubConfigs = Nothing , _pcEnablePrivateKeyCheck = Nothing , _pcName = Nothing } -- | How this project publishes a change in the repositories through Cloud -- Pub\/Sub. Keyed by the topic names. pcPubsubConfigs :: Lens' ProjectConfig (Maybe ProjectConfigPubsubConfigs) pcPubsubConfigs = lens _pcPubsubConfigs (\ s a -> s{_pcPubsubConfigs = a}) -- | Reject a Git push that contains a private key. pcEnablePrivateKeyCheck :: Lens' ProjectConfig (Maybe Bool) pcEnablePrivateKeyCheck = lens _pcEnablePrivateKeyCheck (\ s a -> s{_pcEnablePrivateKeyCheck = a}) -- | The name of the project. Values are of the form \`projects\/\`. pcName :: Lens' ProjectConfig (Maybe Text) pcName = lens _pcName (\ s a -> s{_pcName = a}) instance FromJSON ProjectConfig where parseJSON = withObject "ProjectConfig" (\ o -> ProjectConfig' <$> (o .:? "pubsubConfigs") <*> (o .:? "enablePrivateKeyCheck") <*> (o .:? "name")) instance ToJSON ProjectConfig where toJSON ProjectConfig'{..} = object (catMaybes [("pubsubConfigs" .=) <$> _pcPubsubConfigs, ("enablePrivateKeyCheck" .=) <$> _pcEnablePrivateKeyCheck, ("name" .=) <$> _pcName]) -- | Represents a textual expression in the Common Expression Language (CEL) -- syntax. CEL is a C-like expression language. The syntax and semantics of -- CEL are documented at https:\/\/github.com\/google\/cel-spec. Example -- (Comparison): title: \"Summary size limit\" description: \"Determines if -- a summary is less than 100 chars\" expression: \"document.summary.size() -- \< 100\" Example (Equality): title: \"Requestor is owner\" description: -- \"Determines if requestor is the document owner\" expression: -- \"document.owner == request.auth.claims.email\" Example (Logic): title: -- \"Public documents\" description: \"Determine whether the document -- should be publicly visible\" expression: \"document.type != \'private\' -- && document.type != \'internal\'\" Example (Data Manipulation): title: -- \"Notification string\" description: \"Create a notification string with -- a timestamp.\" expression: \"\'New message received at \' + -- string(document.create_time)\" The exact variables and functions that -- may be referenced within an expression are determined by the service -- that evaluates it. See the service documentation for additional -- information. -- -- /See:/ 'expr' smart constructor. data Expr = Expr' { _eLocation :: !(Maybe Text) , _eExpression :: !(Maybe Text) , _eTitle :: !(Maybe Text) , _eDescription :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Expr' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'eLocation' -- -- * 'eExpression' -- -- * 'eTitle' -- -- * 'eDescription' expr :: Expr expr = Expr' { _eLocation = Nothing , _eExpression = Nothing , _eTitle = Nothing , _eDescription = Nothing } -- | Optional. String indicating the location of the expression for error -- reporting, e.g. a file name and a position in the file. eLocation :: Lens' Expr (Maybe Text) eLocation = lens _eLocation (\ s a -> s{_eLocation = a}) -- | Textual representation of an expression in Common Expression Language -- syntax. eExpression :: Lens' Expr (Maybe Text) eExpression = lens _eExpression (\ s a -> s{_eExpression = a}) -- | Optional. Title for the expression, i.e. a short string describing its -- purpose. This can be used e.g. in UIs which allow to enter the -- expression. eTitle :: Lens' Expr (Maybe Text) eTitle = lens _eTitle (\ s a -> s{_eTitle = a}) -- | Optional. Description of the expression. This is a longer text which -- describes the expression, e.g. when hovered over it in a UI. eDescription :: Lens' Expr (Maybe Text) eDescription = lens _eDescription (\ s a -> s{_eDescription = a}) instance FromJSON Expr where parseJSON = withObject "Expr" (\ o -> Expr' <$> (o .:? "location") <*> (o .:? "expression") <*> (o .:? "title") <*> (o .:? "description")) instance ToJSON Expr where toJSON Expr'{..} = object (catMaybes [("location" .=) <$> _eLocation, ("expression" .=) <$> _eExpression, ("title" .=) <$> _eTitle, ("description" .=) <$> _eDescription]) -- | Response for ListRepos. The size is not set in the returned -- repositories. -- -- /See:/ 'listReposResponse' smart constructor. data ListReposResponse = ListReposResponse' { _lrrNextPageToken :: !(Maybe Text) , _lrrRepos :: !(Maybe [Repo]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListReposResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lrrNextPageToken' -- -- * 'lrrRepos' listReposResponse :: ListReposResponse listReposResponse = ListReposResponse' {_lrrNextPageToken = Nothing, _lrrRepos = Nothing} -- | If non-empty, additional repositories exist within the project. These -- can be retrieved by including this value in the next ListReposRequest\'s -- page_token field. lrrNextPageToken :: Lens' ListReposResponse (Maybe Text) lrrNextPageToken = lens _lrrNextPageToken (\ s a -> s{_lrrNextPageToken = a}) -- | The listed repos. lrrRepos :: Lens' ListReposResponse [Repo] lrrRepos = lens _lrrRepos (\ s a -> s{_lrrRepos = a}) . _Default . _Coerce instance FromJSON ListReposResponse where parseJSON = withObject "ListReposResponse" (\ o -> ListReposResponse' <$> (o .:? "nextPageToken") <*> (o .:? "repos" .!= mempty)) instance ToJSON ListReposResponse where toJSON ListReposResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lrrNextPageToken, ("repos" .=) <$> _lrrRepos]) -- | This resource represents a long-running operation that is the result of -- a network API call. -- -- /See:/ 'operation' smart constructor. data Operation = Operation' { _oDone :: !(Maybe Bool) , _oError :: !(Maybe Status) , _oResponse :: !(Maybe OperationResponse) , _oName :: !(Maybe Text) , _oMetadata :: !(Maybe OperationMetadata) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Operation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oDone' -- -- * 'oError' -- -- * 'oResponse' -- -- * 'oName' -- -- * 'oMetadata' operation :: Operation operation = Operation' { _oDone = Nothing , _oError = Nothing , _oResponse = Nothing , _oName = Nothing , _oMetadata = Nothing } -- | If the value is \`false\`, it means the operation is still in progress. -- If \`true\`, the operation is completed, and either \`error\` or -- \`response\` is available. oDone :: Lens' Operation (Maybe Bool) oDone = lens _oDone (\ s a -> s{_oDone = a}) -- | The error result of the operation in case of failure or cancellation. oError :: Lens' Operation (Maybe Status) oError = lens _oError (\ s a -> s{_oError = a}) -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as \`Delete\`, the response is -- \`google.protobuf.Empty\`. If the original method is standard -- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource. -- For other methods, the response should have the type \`XxxResponse\`, -- where \`Xxx\` is the original method name. For example, if the original -- method name is \`TakeSnapshot()\`, the inferred response type is -- \`TakeSnapshotResponse\`. oResponse :: Lens' Operation (Maybe OperationResponse) oResponse = lens _oResponse (\ s a -> s{_oResponse = a}) -- | The server-assigned name, which is only unique within the same service -- that originally returns it. If you use the default HTTP mapping, the -- \`name\` should be a resource name ending with -- \`operations\/{unique_id}\`. oName :: Lens' Operation (Maybe Text) oName = lens _oName (\ s a -> s{_oName = a}) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. oMetadata :: Lens' Operation (Maybe OperationMetadata) oMetadata = lens _oMetadata (\ s a -> s{_oMetadata = a}) instance FromJSON Operation where parseJSON = withObject "Operation" (\ o -> Operation' <$> (o .:? "done") <*> (o .:? "error") <*> (o .:? "response") <*> (o .:? "name") <*> (o .:? "metadata")) instance ToJSON Operation where toJSON Operation'{..} = object (catMaybes [("done" .=) <$> _oDone, ("error" .=) <$> _oError, ("response" .=) <$> _oResponse, ("name" .=) <$> _oName, ("metadata" .=) <$> _oMetadata]) -- | A generic empty message that you can re-use to avoid defining duplicated -- empty messages in your APIs. A typical example is to use it as the -- request or the response type of an API method. For instance: service Foo -- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The -- JSON representation for \`Empty\` is empty JSON object \`{}\`. -- -- /See:/ 'empty' smart constructor. data Empty = Empty' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Empty' with the minimum fields required to make a request. -- empty :: Empty empty = Empty' instance FromJSON Empty where parseJSON = withObject "Empty" (\ o -> pure Empty') instance ToJSON Empty where toJSON = const emptyObject -- | Request for UpdateRepo. -- -- /See:/ 'updateRepoRequest' smart constructor. data UpdateRepoRequest = UpdateRepoRequest' { _urrUpdateMask :: !(Maybe GFieldMask) , _urrRepo :: !(Maybe Repo) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UpdateRepoRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'urrUpdateMask' -- -- * 'urrRepo' updateRepoRequest :: UpdateRepoRequest updateRepoRequest = UpdateRepoRequest' {_urrUpdateMask = Nothing, _urrRepo = Nothing} -- | A FieldMask specifying which fields of the repo to modify. Only the -- fields in the mask will be modified. If no mask is provided, this -- request is no-op. urrUpdateMask :: Lens' UpdateRepoRequest (Maybe GFieldMask) urrUpdateMask = lens _urrUpdateMask (\ s a -> s{_urrUpdateMask = a}) -- | The new configuration for the repository. urrRepo :: Lens' UpdateRepoRequest (Maybe Repo) urrRepo = lens _urrRepo (\ s a -> s{_urrRepo = a}) instance FromJSON UpdateRepoRequest where parseJSON = withObject "UpdateRepoRequest" (\ o -> UpdateRepoRequest' <$> (o .:? "updateMask") <*> (o .:? "repo")) instance ToJSON UpdateRepoRequest where toJSON UpdateRepoRequest'{..} = object (catMaybes [("updateMask" .=) <$> _urrUpdateMask, ("repo" .=) <$> _urrRepo]) -- -- /See:/ 'statusDetailsItem' smart constructor. newtype StatusDetailsItem = StatusDetailsItem' { _sdiAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StatusDetailsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdiAddtional' statusDetailsItem :: HashMap Text JSONValue -- ^ 'sdiAddtional' -> StatusDetailsItem statusDetailsItem pSdiAddtional_ = StatusDetailsItem' {_sdiAddtional = _Coerce # pSdiAddtional_} -- | Properties of the object. Contains field \'type with type URL. sdiAddtional :: Lens' StatusDetailsItem (HashMap Text JSONValue) sdiAddtional = lens _sdiAddtional (\ s a -> s{_sdiAddtional = a}) . _Coerce instance FromJSON StatusDetailsItem where parseJSON = withObject "StatusDetailsItem" (\ o -> StatusDetailsItem' <$> (parseJSONObject o)) instance ToJSON StatusDetailsItem where toJSON = toJSON . _sdiAddtional -- | Request message for \`SetIamPolicy\` method. -- -- /See:/ 'setIAMPolicyRequest' smart constructor. data SetIAMPolicyRequest = SetIAMPolicyRequest' { _siprUpdateMask :: !(Maybe GFieldMask) , _siprPolicy :: !(Maybe Policy) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SetIAMPolicyRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'siprUpdateMask' -- -- * 'siprPolicy' setIAMPolicyRequest :: SetIAMPolicyRequest setIAMPolicyRequest = SetIAMPolicyRequest' {_siprUpdateMask = Nothing, _siprPolicy = Nothing} -- | OPTIONAL: A FieldMask specifying which fields of the policy to modify. -- Only the fields in the mask will be modified. If no mask is provided, -- the following default mask is used: \`paths: \"bindings, etag\"\` siprUpdateMask :: Lens' SetIAMPolicyRequest (Maybe GFieldMask) siprUpdateMask = lens _siprUpdateMask (\ s a -> s{_siprUpdateMask = a}) -- | REQUIRED: The complete policy to be applied to the \`resource\`. The -- size of the policy is limited to a few 10s of KB. An empty policy is a -- valid policy but certain Cloud Platform services (such as Projects) -- might reject them. siprPolicy :: Lens' SetIAMPolicyRequest (Maybe Policy) siprPolicy = lens _siprPolicy (\ s a -> s{_siprPolicy = a}) instance FromJSON SetIAMPolicyRequest where parseJSON = withObject "SetIAMPolicyRequest" (\ o -> SetIAMPolicyRequest' <$> (o .:? "updateMask") <*> (o .:? "policy")) instance ToJSON SetIAMPolicyRequest where toJSON SetIAMPolicyRequest'{..} = object (catMaybes [("updateMask" .=) <$> _siprUpdateMask, ("policy" .=) <$> _siprPolicy]) -- | Configuration to publish a Cloud Pub\/Sub message. -- -- /See:/ 'pubsubConfig' smart constructor. data PubsubConfig = PubsubConfig' { _pcTopic :: !(Maybe Text) , _pcServiceAccountEmail :: !(Maybe Text) , _pcMessageFormat :: !(Maybe PubsubConfigMessageFormat) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'PubsubConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcTopic' -- -- * 'pcServiceAccountEmail' -- -- * 'pcMessageFormat' pubsubConfig :: PubsubConfig pubsubConfig = PubsubConfig' { _pcTopic = Nothing , _pcServiceAccountEmail = Nothing , _pcMessageFormat = Nothing } -- | A topic of Cloud Pub\/Sub. Values are of the form -- \`projects\/\/topics\/\`. The project needs to be the same project as -- this config is in. pcTopic :: Lens' PubsubConfig (Maybe Text) pcTopic = lens _pcTopic (\ s a -> s{_pcTopic = a}) -- | Email address of the service account used for publishing Cloud Pub\/Sub -- messages. This service account needs to be in the same project as the -- PubsubConfig. When added, the caller needs to have -- iam.serviceAccounts.actAs permission on this service account. If -- unspecified, it defaults to the compute engine default service account. pcServiceAccountEmail :: Lens' PubsubConfig (Maybe Text) pcServiceAccountEmail = lens _pcServiceAccountEmail (\ s a -> s{_pcServiceAccountEmail = a}) -- | The format of the Cloud Pub\/Sub messages. pcMessageFormat :: Lens' PubsubConfig (Maybe PubsubConfigMessageFormat) pcMessageFormat = lens _pcMessageFormat (\ s a -> s{_pcMessageFormat = a}) instance FromJSON PubsubConfig where parseJSON = withObject "PubsubConfig" (\ o -> PubsubConfig' <$> (o .:? "topic") <*> (o .:? "serviceAccountEmail") <*> (o .:? "messageFormat")) instance ToJSON PubsubConfig where toJSON PubsubConfig'{..} = object (catMaybes [("topic" .=) <$> _pcTopic, ("serviceAccountEmail" .=) <$> _pcServiceAccountEmail, ("messageFormat" .=) <$> _pcMessageFormat]) -- | Request for UpdateProjectConfig. -- -- /See:/ 'updateProjectConfigRequest' smart constructor. data UpdateProjectConfigRequest = UpdateProjectConfigRequest' { _upcrProjectConfig :: !(Maybe ProjectConfig) , _upcrUpdateMask :: !(Maybe GFieldMask) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UpdateProjectConfigRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'upcrProjectConfig' -- -- * 'upcrUpdateMask' updateProjectConfigRequest :: UpdateProjectConfigRequest updateProjectConfigRequest = UpdateProjectConfigRequest' {_upcrProjectConfig = Nothing, _upcrUpdateMask = Nothing} -- | The new configuration for the project. upcrProjectConfig :: Lens' UpdateProjectConfigRequest (Maybe ProjectConfig) upcrProjectConfig = lens _upcrProjectConfig (\ s a -> s{_upcrProjectConfig = a}) -- | A FieldMask specifying which fields of the project_config to modify. -- Only the fields in the mask will be modified. If no mask is provided, -- this request is no-op. upcrUpdateMask :: Lens' UpdateProjectConfigRequest (Maybe GFieldMask) upcrUpdateMask = lens _upcrUpdateMask (\ s a -> s{_upcrUpdateMask = a}) instance FromJSON UpdateProjectConfigRequest where parseJSON = withObject "UpdateProjectConfigRequest" (\ o -> UpdateProjectConfigRequest' <$> (o .:? "projectConfig") <*> (o .:? "updateMask")) instance ToJSON UpdateProjectConfigRequest where toJSON UpdateProjectConfigRequest'{..} = object (catMaybes [("projectConfig" .=) <$> _upcrProjectConfig, ("updateMask" .=) <$> _upcrUpdateMask]) -- | Request message for \`TestIamPermissions\` method. -- -- /See:/ 'testIAMPermissionsRequest' smart constructor. newtype TestIAMPermissionsRequest = TestIAMPermissionsRequest' { _tiprPermissions :: Maybe [Text] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TestIAMPermissionsRequest' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tiprPermissions' testIAMPermissionsRequest :: TestIAMPermissionsRequest testIAMPermissionsRequest = TestIAMPermissionsRequest' {_tiprPermissions = Nothing} -- | The set of permissions to check for the \`resource\`. Permissions with -- wildcards (such as \'*\' or \'storage.*\') are not allowed. For more -- information see [IAM -- Overview](https:\/\/cloud.google.com\/iam\/docs\/overview#permissions). tiprPermissions :: Lens' TestIAMPermissionsRequest [Text] tiprPermissions = lens _tiprPermissions (\ s a -> s{_tiprPermissions = a}) . _Default . _Coerce instance FromJSON TestIAMPermissionsRequest where parseJSON = withObject "TestIAMPermissionsRequest" (\ o -> TestIAMPermissionsRequest' <$> (o .:? "permissions" .!= mempty)) instance ToJSON TestIAMPermissionsRequest where toJSON TestIAMPermissionsRequest'{..} = object (catMaybes [("permissions" .=) <$> _tiprPermissions]) -- | Metadata of SyncRepo. This message is in the metadata field of -- Operation. -- -- /See:/ 'syncRepoMetadata' smart constructor. data SyncRepoMetadata = SyncRepoMetadata' { _srmStartTime :: !(Maybe DateTime') , _srmUpdateTime :: !(Maybe DateTime') , _srmName :: !(Maybe Text) , _srmStatusMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SyncRepoMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'srmStartTime' -- -- * 'srmUpdateTime' -- -- * 'srmName' -- -- * 'srmStatusMessage' syncRepoMetadata :: SyncRepoMetadata syncRepoMetadata = SyncRepoMetadata' { _srmStartTime = Nothing , _srmUpdateTime = Nothing , _srmName = Nothing , _srmStatusMessage = Nothing } -- | The time this operation is started. srmStartTime :: Lens' SyncRepoMetadata (Maybe UTCTime) srmStartTime = lens _srmStartTime (\ s a -> s{_srmStartTime = a}) . mapping _DateTime -- | The time this operation\'s status message is updated. srmUpdateTime :: Lens' SyncRepoMetadata (Maybe UTCTime) srmUpdateTime = lens _srmUpdateTime (\ s a -> s{_srmUpdateTime = a}) . mapping _DateTime -- | The name of the repo being synchronized. Values are of the form -- \`projects\/\/repos\/\`. srmName :: Lens' SyncRepoMetadata (Maybe Text) srmName = lens _srmName (\ s a -> s{_srmName = a}) -- | The latest status message on syncing the repository. srmStatusMessage :: Lens' SyncRepoMetadata (Maybe Text) srmStatusMessage = lens _srmStatusMessage (\ s a -> s{_srmStatusMessage = a}) instance FromJSON SyncRepoMetadata where parseJSON = withObject "SyncRepoMetadata" (\ o -> SyncRepoMetadata' <$> (o .:? "startTime") <*> (o .:? "updateTime") <*> (o .:? "name") <*> (o .:? "statusMessage")) instance ToJSON SyncRepoMetadata where toJSON SyncRepoMetadata'{..} = object (catMaybes [("startTime" .=) <$> _srmStartTime, ("updateTime" .=) <$> _srmUpdateTime, ("name" .=) <$> _srmName, ("statusMessage" .=) <$> _srmStatusMessage]) -- | How this repository publishes a change in the repository through Cloud -- Pub\/Sub. Keyed by the topic names. -- -- /See:/ 'repoPubsubConfigs' smart constructor. newtype RepoPubsubConfigs = RepoPubsubConfigs' { _rpcAddtional :: HashMap Text PubsubConfig } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RepoPubsubConfigs' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rpcAddtional' repoPubsubConfigs :: HashMap Text PubsubConfig -- ^ 'rpcAddtional' -> RepoPubsubConfigs repoPubsubConfigs pRpcAddtional_ = RepoPubsubConfigs' {_rpcAddtional = _Coerce # pRpcAddtional_} rpcAddtional :: Lens' RepoPubsubConfigs (HashMap Text PubsubConfig) rpcAddtional = lens _rpcAddtional (\ s a -> s{_rpcAddtional = a}) . _Coerce instance FromJSON RepoPubsubConfigs where parseJSON = withObject "RepoPubsubConfigs" (\ o -> RepoPubsubConfigs' <$> (parseJSONObject o)) instance ToJSON RepoPubsubConfigs where toJSON = toJSON . _rpcAddtional -- | How this project publishes a change in the repositories through Cloud -- Pub\/Sub. Keyed by the topic names. -- -- /See:/ 'projectConfigPubsubConfigs' smart constructor. newtype ProjectConfigPubsubConfigs = ProjectConfigPubsubConfigs' { _pcpcAddtional :: HashMap Text PubsubConfig } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectConfigPubsubConfigs' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pcpcAddtional' projectConfigPubsubConfigs :: HashMap Text PubsubConfig -- ^ 'pcpcAddtional' -> ProjectConfigPubsubConfigs projectConfigPubsubConfigs pPcpcAddtional_ = ProjectConfigPubsubConfigs' {_pcpcAddtional = _Coerce # pPcpcAddtional_} pcpcAddtional :: Lens' ProjectConfigPubsubConfigs (HashMap Text PubsubConfig) pcpcAddtional = lens _pcpcAddtional (\ s a -> s{_pcpcAddtional = a}) . _Coerce instance FromJSON ProjectConfigPubsubConfigs where parseJSON = withObject "ProjectConfigPubsubConfigs" (\ o -> ProjectConfigPubsubConfigs' <$> (parseJSONObject o)) instance ToJSON ProjectConfigPubsubConfigs where toJSON = toJSON . _pcpcAddtional -- | A repository (or repo) is a Git repository storing versioned source -- content. -- -- /See:/ 'repo' smart constructor. data Repo = Repo' { _rPubsubConfigs :: !(Maybe RepoPubsubConfigs) , _rSize :: !(Maybe (Textual Int64)) , _rURL :: !(Maybe Text) , _rName :: !(Maybe Text) , _rMirrorConfig :: !(Maybe MirrorConfig) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Repo' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rPubsubConfigs' -- -- * 'rSize' -- -- * 'rURL' -- -- * 'rName' -- -- * 'rMirrorConfig' repo :: Repo repo = Repo' { _rPubsubConfigs = Nothing , _rSize = Nothing , _rURL = Nothing , _rName = Nothing , _rMirrorConfig = Nothing } -- | How this repository publishes a change in the repository through Cloud -- Pub\/Sub. Keyed by the topic names. rPubsubConfigs :: Lens' Repo (Maybe RepoPubsubConfigs) rPubsubConfigs = lens _rPubsubConfigs (\ s a -> s{_rPubsubConfigs = a}) -- | The disk usage of the repo, in bytes. Read-only field. Size is only -- returned by GetRepo. rSize :: Lens' Repo (Maybe Int64) rSize = lens _rSize (\ s a -> s{_rSize = a}) . mapping _Coerce -- | URL to clone the repository from Google Cloud Source Repositories. -- Read-only field. rURL :: Lens' Repo (Maybe Text) rURL = lens _rURL (\ s a -> s{_rURL = a}) -- | Resource name of the repository, of the form \`projects\/\/repos\/\`. -- The repo name may contain slashes. eg, -- \`projects\/myproject\/repos\/name\/with\/slash\` rName :: Lens' Repo (Maybe Text) rName = lens _rName (\ s a -> s{_rName = a}) -- | How this repository mirrors a repository managed by another service. -- Read-only field. rMirrorConfig :: Lens' Repo (Maybe MirrorConfig) rMirrorConfig = lens _rMirrorConfig (\ s a -> s{_rMirrorConfig = a}) instance FromJSON Repo where parseJSON = withObject "Repo" (\ o -> Repo' <$> (o .:? "pubsubConfigs") <*> (o .:? "size") <*> (o .:? "url") <*> (o .:? "name") <*> (o .:? "mirrorConfig")) instance ToJSON Repo where toJSON Repo'{..} = object (catMaybes [("pubsubConfigs" .=) <$> _rPubsubConfigs, ("size" .=) <$> _rSize, ("url" .=) <$> _rURL, ("name" .=) <$> _rName, ("mirrorConfig" .=) <$> _rMirrorConfig]) -- | Response message for \`TestIamPermissions\` method. -- -- /See:/ 'testIAMPermissionsResponse' smart constructor. newtype TestIAMPermissionsResponse = TestIAMPermissionsResponse' { _tiamprPermissions :: Maybe [Text] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'TestIAMPermissionsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tiamprPermissions' testIAMPermissionsResponse :: TestIAMPermissionsResponse testIAMPermissionsResponse = TestIAMPermissionsResponse' {_tiamprPermissions = Nothing} -- | A subset of \`TestPermissionsRequest.permissions\` that the caller is -- allowed. tiamprPermissions :: Lens' TestIAMPermissionsResponse [Text] tiamprPermissions = lens _tiamprPermissions (\ s a -> s{_tiamprPermissions = a}) . _Default . _Coerce instance FromJSON TestIAMPermissionsResponse where parseJSON = withObject "TestIAMPermissionsResponse" (\ o -> TestIAMPermissionsResponse' <$> (o .:? "permissions" .!= mempty)) instance ToJSON TestIAMPermissionsResponse where toJSON TestIAMPermissionsResponse'{..} = object (catMaybes [("permissions" .=) <$> _tiamprPermissions]) -- | An Identity and Access Management (IAM) policy, which specifies access -- controls for Google Cloud resources. A \`Policy\` is a collection of -- \`bindings\`. A \`binding\` binds one or more \`members\` to a single -- \`role\`. Members can be user accounts, service accounts, Google groups, -- and domains (such as G Suite). A \`role\` is a named list of -- permissions; each \`role\` can be an IAM predefined role or a -- user-created custom role. For some types of Google Cloud resources, a -- \`binding\` can also specify a \`condition\`, which is a logical -- expression that allows access to a resource only if the expression -- evaluates to \`true\`. A condition can add constraints based on -- attributes of the request, the resource, or both. To learn which -- resources support conditions in their IAM policies, see the [IAM -- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies). -- **JSON example:** { \"bindings\": [ { \"role\": -- \"roles\/resourcemanager.organizationAdmin\", \"members\": [ -- \"user:mike\'example.com\", \"group:admins\'example.com\", -- \"domain:google.com\", -- \"serviceAccount:my-project-id\'appspot.gserviceaccount.com\" ] }, { -- \"role\": \"roles\/resourcemanager.organizationViewer\", \"members\": [ -- \"user:eve\'example.com\" ], \"condition\": { \"title\": \"expirable -- access\", \"description\": \"Does not grant access after Sep 2020\", -- \"expression\": \"request.time \< -- timestamp(\'2020-10-01T00:00:00.000Z\')\", } } ], \"etag\": -- \"BwWWja0YfJA=\", \"version\": 3 } **YAML example:** bindings: - -- members: - user:mike\'example.com - group:admins\'example.com - -- domain:google.com - -- serviceAccount:my-project-id\'appspot.gserviceaccount.com role: -- roles\/resourcemanager.organizationAdmin - members: - -- user:eve\'example.com role: roles\/resourcemanager.organizationViewer -- condition: title: expirable access description: Does not grant access -- after Sep 2020 expression: request.time \< -- timestamp(\'2020-10-01T00:00:00.000Z\') - etag: BwWWja0YfJA= - version: -- 3 For a description of IAM and its features, see the [IAM -- documentation](https:\/\/cloud.google.com\/iam\/docs\/). -- -- /See:/ 'policy' smart constructor. data Policy = Policy' { _pAuditConfigs :: !(Maybe [AuditConfig]) , _pEtag :: !(Maybe Bytes) , _pVersion :: !(Maybe (Textual Int32)) , _pBindings :: !(Maybe [Binding]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Policy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pAuditConfigs' -- -- * 'pEtag' -- -- * 'pVersion' -- -- * 'pBindings' policy :: Policy policy = Policy' { _pAuditConfigs = Nothing , _pEtag = Nothing , _pVersion = Nothing , _pBindings = Nothing } -- | Specifies cloud audit logging configuration for this policy. pAuditConfigs :: Lens' Policy [AuditConfig] pAuditConfigs = lens _pAuditConfigs (\ s a -> s{_pAuditConfigs = a}) . _Default . _Coerce -- | \`etag\` is used for optimistic concurrency control as a way to help -- prevent simultaneous updates of a policy from overwriting each other. It -- is strongly suggested that systems make use of the \`etag\` in the -- read-modify-write cycle to perform policy updates in order to avoid race -- conditions: An \`etag\` is returned in the response to \`getIamPolicy\`, -- and systems are expected to put that etag in the request to -- \`setIamPolicy\` to ensure that their change will be applied to the same -- version of the policy. **Important:** If you use IAM Conditions, you -- must include the \`etag\` field whenever you call \`setIamPolicy\`. If -- you omit this field, then IAM allows you to overwrite a version \`3\` -- policy with a version \`1\` policy, and all of the conditions in the -- version \`3\` policy are lost. pEtag :: Lens' Policy (Maybe ByteString) pEtag = lens _pEtag (\ s a -> s{_pEtag = a}) . mapping _Bytes -- | Specifies the format of the policy. Valid values are \`0\`, \`1\`, and -- \`3\`. Requests that specify an invalid value are rejected. Any -- operation that affects conditional role bindings must specify version -- \`3\`. This requirement applies to the following operations: * Getting a -- policy that includes a conditional role binding * Adding a conditional -- role binding to a policy * Changing a conditional role binding in a -- policy * Removing any role binding, with or without a condition, from a -- policy that includes conditions **Important:** If you use IAM -- Conditions, you must include the \`etag\` field whenever you call -- \`setIamPolicy\`. If you omit this field, then IAM allows you to -- overwrite a version \`3\` policy with a version \`1\` policy, and all of -- the conditions in the version \`3\` policy are lost. If a policy does -- not include any conditions, operations on that policy may specify any -- valid version or leave the field unset. To learn which resources support -- conditions in their IAM policies, see the [IAM -- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies). pVersion :: Lens' Policy (Maybe Int32) pVersion = lens _pVersion (\ s a -> s{_pVersion = a}) . mapping _Coerce -- | Associates a list of \`members\` to a \`role\`. Optionally, may specify -- a \`condition\` that determines how and when the \`bindings\` are -- applied. Each of the \`bindings\` must contain at least one member. pBindings :: Lens' Policy [Binding] pBindings = lens _pBindings (\ s a -> s{_pBindings = a}) . _Default . _Coerce instance FromJSON Policy where parseJSON = withObject "Policy" (\ o -> Policy' <$> (o .:? "auditConfigs" .!= mempty) <*> (o .:? "etag") <*> (o .:? "version") <*> (o .:? "bindings" .!= mempty)) instance ToJSON Policy where toJSON Policy'{..} = object (catMaybes [("auditConfigs" .=) <$> _pAuditConfigs, ("etag" .=) <$> _pEtag, ("version" .=) <$> _pVersion, ("bindings" .=) <$> _pBindings]) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. -- -- /See:/ 'operationMetadata' smart constructor. newtype OperationMetadata = OperationMetadata' { _omAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'omAddtional' operationMetadata :: HashMap Text JSONValue -- ^ 'omAddtional' -> OperationMetadata operationMetadata pOmAddtional_ = OperationMetadata' {_omAddtional = _Coerce # pOmAddtional_} -- | Properties of the object. Contains field \'type with type URL. omAddtional :: Lens' OperationMetadata (HashMap Text JSONValue) omAddtional = lens _omAddtional (\ s a -> s{_omAddtional = a}) . _Coerce instance FromJSON OperationMetadata where parseJSON = withObject "OperationMetadata" (\ o -> OperationMetadata' <$> (parseJSONObject o)) instance ToJSON OperationMetadata where toJSON = toJSON . _omAddtional -- | Provides the configuration for logging a type of permissions. Example: { -- \"audit_log_configs\": [ { \"log_type\": \"DATA_READ\", -- \"exempted_members\": [ \"user:jose\'example.com\" ] }, { \"log_type\": -- \"DATA_WRITE\" } ] } This enables \'DATA_READ\' and \'DATA_WRITE\' -- logging, while exempting jose\'example.com from DATA_READ logging. -- -- /See:/ 'auditLogConfig' smart constructor. data AuditLogConfig = AuditLogConfig' { _alcLogType :: !(Maybe AuditLogConfigLogType) , _alcExemptedMembers :: !(Maybe [Text]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AuditLogConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alcLogType' -- -- * 'alcExemptedMembers' auditLogConfig :: AuditLogConfig auditLogConfig = AuditLogConfig' {_alcLogType = Nothing, _alcExemptedMembers = Nothing} -- | The log type that this config enables. alcLogType :: Lens' AuditLogConfig (Maybe AuditLogConfigLogType) alcLogType = lens _alcLogType (\ s a -> s{_alcLogType = a}) -- | Specifies the identities that do not cause logging for this type of -- permission. Follows the same format of Binding.members. alcExemptedMembers :: Lens' AuditLogConfig [Text] alcExemptedMembers = lens _alcExemptedMembers (\ s a -> s{_alcExemptedMembers = a}) . _Default . _Coerce instance FromJSON AuditLogConfig where parseJSON = withObject "AuditLogConfig" (\ o -> AuditLogConfig' <$> (o .:? "logType") <*> (o .:? "exemptedMembers" .!= mempty)) instance ToJSON AuditLogConfig where toJSON AuditLogConfig'{..} = object (catMaybes [("logType" .=) <$> _alcLogType, ("exemptedMembers" .=) <$> _alcExemptedMembers]) -- | Configuration to automatically mirror a repository from another hosting -- service, for example GitHub or Bitbucket. -- -- /See:/ 'mirrorConfig' smart constructor. data MirrorConfig = MirrorConfig' { _mcURL :: !(Maybe Text) , _mcDeployKeyId :: !(Maybe Text) , _mcWebhookId :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'MirrorConfig' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mcURL' -- -- * 'mcDeployKeyId' -- -- * 'mcWebhookId' mirrorConfig :: MirrorConfig mirrorConfig = MirrorConfig' {_mcURL = Nothing, _mcDeployKeyId = Nothing, _mcWebhookId = Nothing} -- | URL of the main repository at the other hosting service. mcURL :: Lens' MirrorConfig (Maybe Text) mcURL = lens _mcURL (\ s a -> s{_mcURL = a}) -- | ID of the SSH deploy key at the other hosting service. Removing this key -- from the other service would deauthorize Google Cloud Source -- Repositories from mirroring. mcDeployKeyId :: Lens' MirrorConfig (Maybe Text) mcDeployKeyId = lens _mcDeployKeyId (\ s a -> s{_mcDeployKeyId = a}) -- | ID of the webhook listening to updates to trigger mirroring. Removing -- this webhook from the other hosting service will stop Google Cloud -- Source Repositories from receiving notifications, and thereby disabling -- mirroring. mcWebhookId :: Lens' MirrorConfig (Maybe Text) mcWebhookId = lens _mcWebhookId (\ s a -> s{_mcWebhookId = a}) instance FromJSON MirrorConfig where parseJSON = withObject "MirrorConfig" (\ o -> MirrorConfig' <$> (o .:? "url") <*> (o .:? "deployKeyId") <*> (o .:? "webhookId")) instance ToJSON MirrorConfig where toJSON MirrorConfig'{..} = object (catMaybes [("url" .=) <$> _mcURL, ("deployKeyId" .=) <$> _mcDeployKeyId, ("webhookId" .=) <$> _mcWebhookId]) -- | Request for SyncRepo. -- -- /See:/ 'syncRepoRequest' smart constructor. data SyncRepoRequest = SyncRepoRequest' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SyncRepoRequest' with the minimum fields required to make a request. -- syncRepoRequest :: SyncRepoRequest syncRepoRequest = SyncRepoRequest' instance FromJSON SyncRepoRequest where parseJSON = withObject "SyncRepoRequest" (\ o -> pure SyncRepoRequest') instance ToJSON SyncRepoRequest where toJSON = const emptyObject -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as \`Delete\`, the response is -- \`google.protobuf.Empty\`. If the original method is standard -- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource. -- For other methods, the response should have the type \`XxxResponse\`, -- where \`Xxx\` is the original method name. For example, if the original -- method name is \`TakeSnapshot()\`, the inferred response type is -- \`TakeSnapshotResponse\`. -- -- /See:/ 'operationResponse' smart constructor. newtype OperationResponse = OperationResponse' { _orAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orAddtional' operationResponse :: HashMap Text JSONValue -- ^ 'orAddtional' -> OperationResponse operationResponse pOrAddtional_ = OperationResponse' {_orAddtional = _Coerce # pOrAddtional_} -- | Properties of the object. Contains field \'type with type URL. orAddtional :: Lens' OperationResponse (HashMap Text JSONValue) orAddtional = lens _orAddtional (\ s a -> s{_orAddtional = a}) . _Coerce instance FromJSON OperationResponse where parseJSON = withObject "OperationResponse" (\ o -> OperationResponse' <$> (parseJSONObject o)) instance ToJSON OperationResponse where toJSON = toJSON . _orAddtional -- | Associates \`members\` with a \`role\`. -- -- /See:/ 'binding' smart constructor. data Binding = Binding' { _bMembers :: !(Maybe [Text]) , _bRole :: !(Maybe Text) , _bCondition :: !(Maybe Expr) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Binding' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'bMembers' -- -- * 'bRole' -- -- * 'bCondition' binding :: Binding binding = Binding' {_bMembers = Nothing, _bRole = Nothing, _bCondition = Nothing} -- | Specifies the identities requesting access for a Cloud Platform -- resource. \`members\` can have the following values: * \`allUsers\`: A -- special identifier that represents anyone who is on the internet; with -- or without a Google account. * \`allAuthenticatedUsers\`: A special -- identifier that represents anyone who is authenticated with a Google -- account or a service account. * \`user:{emailid}\`: An email address -- that represents a specific Google account. For example, -- \`alice\'example.com\` . * \`serviceAccount:{emailid}\`: An email -- address that represents a service account. For example, -- \`my-other-app\'appspot.gserviceaccount.com\`. * \`group:{emailid}\`: An -- email address that represents a Google group. For example, -- \`admins\'example.com\`. * \`deleted:user:{emailid}?uid={uniqueid}\`: An -- email address (plus unique identifier) representing a user that has been -- recently deleted. For example, -- \`alice\'example.com?uid=123456789012345678901\`. If the user is -- recovered, this value reverts to \`user:{emailid}\` and the recovered -- user retains the role in the binding. * -- \`deleted:serviceAccount:{emailid}?uid={uniqueid}\`: An email address -- (plus unique identifier) representing a service account that has been -- recently deleted. For example, -- \`my-other-app\'appspot.gserviceaccount.com?uid=123456789012345678901\`. -- If the service account is undeleted, this value reverts to -- \`serviceAccount:{emailid}\` and the undeleted service account retains -- the role in the binding. * \`deleted:group:{emailid}?uid={uniqueid}\`: -- An email address (plus unique identifier) representing a Google group -- that has been recently deleted. For example, -- \`admins\'example.com?uid=123456789012345678901\`. If the group is -- recovered, this value reverts to \`group:{emailid}\` and the recovered -- group retains the role in the binding. * \`domain:{domain}\`: The G -- Suite domain (primary) that represents all the users of that domain. For -- example, \`google.com\` or \`example.com\`. bMembers :: Lens' Binding [Text] bMembers = lens _bMembers (\ s a -> s{_bMembers = a}) . _Default . _Coerce -- | Role that is assigned to \`members\`. For example, \`roles\/viewer\`, -- \`roles\/editor\`, or \`roles\/owner\`. bRole :: Lens' Binding (Maybe Text) bRole = lens _bRole (\ s a -> s{_bRole = a}) -- | The condition that is associated with this binding. If the condition -- evaluates to \`true\`, then this binding applies to the current request. -- If the condition evaluates to \`false\`, then this binding does not -- apply to the current request. However, a different role binding might -- grant the same role to one or more of the members in this binding. To -- learn which resources support conditions in their IAM policies, see the -- [IAM -- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies). bCondition :: Lens' Binding (Maybe Expr) bCondition = lens _bCondition (\ s a -> s{_bCondition = a}) instance FromJSON Binding where parseJSON = withObject "Binding" (\ o -> Binding' <$> (o .:? "members" .!= mempty) <*> (o .:? "role") <*> (o .:? "condition")) instance ToJSON Binding where toJSON Binding'{..} = object (catMaybes [("members" .=) <$> _bMembers, ("role" .=) <$> _bRole, ("condition" .=) <$> _bCondition])
brendanhay/gogol
gogol-sourcerepo/gen/Network/Google/SourceRepo/Types/Product.hs
mpl-2.0
53,013
0
15
11,696
7,947
4,630
3,317
865
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Directory.MobileDevices.Action -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Take action on Mobile Device -- -- /See:/ <https://developers.google.com/admin-sdk/directory/ Admin Directory API Reference> for @directory.mobiledevices.action@. module Network.Google.Resource.Directory.MobileDevices.Action ( -- * REST Resource MobileDevicesActionResource -- * Creating a Request , mobileDevicesAction , MobileDevicesAction -- * Request Lenses , mdaResourceId , mdaPayload , mdaCustomerId ) where import Network.Google.Directory.Types import Network.Google.Prelude -- | A resource alias for @directory.mobiledevices.action@ method which the -- 'MobileDevicesAction' request conforms to. type MobileDevicesActionResource = "admin" :> "directory" :> "v1" :> "customer" :> Capture "customerId" Text :> "devices" :> "mobile" :> Capture "resourceId" Text :> "action" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] MobileDeviceAction :> Post '[JSON] () -- | Take action on Mobile Device -- -- /See:/ 'mobileDevicesAction' smart constructor. data MobileDevicesAction = MobileDevicesAction' { _mdaResourceId :: !Text , _mdaPayload :: !MobileDeviceAction , _mdaCustomerId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'MobileDevicesAction' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mdaResourceId' -- -- * 'mdaPayload' -- -- * 'mdaCustomerId' mobileDevicesAction :: Text -- ^ 'mdaResourceId' -> MobileDeviceAction -- ^ 'mdaPayload' -> Text -- ^ 'mdaCustomerId' -> MobileDevicesAction mobileDevicesAction pMdaResourceId_ pMdaPayload_ pMdaCustomerId_ = MobileDevicesAction' { _mdaResourceId = pMdaResourceId_ , _mdaPayload = pMdaPayload_ , _mdaCustomerId = pMdaCustomerId_ } -- | Immutable id of Mobile Device mdaResourceId :: Lens' MobileDevicesAction Text mdaResourceId = lens _mdaResourceId (\ s a -> s{_mdaResourceId = a}) -- | Multipart request metadata. mdaPayload :: Lens' MobileDevicesAction MobileDeviceAction mdaPayload = lens _mdaPayload (\ s a -> s{_mdaPayload = a}) -- | Immutable id of the Google Apps account mdaCustomerId :: Lens' MobileDevicesAction Text mdaCustomerId = lens _mdaCustomerId (\ s a -> s{_mdaCustomerId = a}) instance GoogleRequest MobileDevicesAction where type Rs MobileDevicesAction = () type Scopes MobileDevicesAction = '["https://www.googleapis.com/auth/admin.directory.device.mobile", "https://www.googleapis.com/auth/admin.directory.device.mobile.action"] requestClient MobileDevicesAction'{..} = go _mdaCustomerId _mdaResourceId (Just AltJSON) _mdaPayload directoryService where go = buildClient (Proxy :: Proxy MobileDevicesActionResource) mempty
rueshyna/gogol
gogol-admin-directory/gen/Network/Google/Resource/Directory/MobileDevices/Action.hs
mpl-2.0
3,872
0
18
931
480
285
195
79
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.YouTube.Subscriptions.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Inserts a new resource into this collection. -- -- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.subscriptions.insert@. module Network.Google.Resource.YouTube.Subscriptions.Insert ( -- * REST Resource SubscriptionsInsertResource -- * Creating a Request , subscriptionsInsert , SubscriptionsInsert -- * Request Lenses , siXgafv , siPart , siUploadProtocol , siAccessToken , siUploadType , siPayload , siCallback ) where import Network.Google.Prelude import Network.Google.YouTube.Types -- | A resource alias for @youtube.subscriptions.insert@ method which the -- 'SubscriptionsInsert' request conforms to. type SubscriptionsInsertResource = "youtube" :> "v3" :> "subscriptions" :> QueryParams "part" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Subscription :> Post '[JSON] Subscription -- | Inserts a new resource into this collection. -- -- /See:/ 'subscriptionsInsert' smart constructor. data SubscriptionsInsert = SubscriptionsInsert' { _siXgafv :: !(Maybe Xgafv) , _siPart :: ![Text] , _siUploadProtocol :: !(Maybe Text) , _siAccessToken :: !(Maybe Text) , _siUploadType :: !(Maybe Text) , _siPayload :: !Subscription , _siCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SubscriptionsInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'siXgafv' -- -- * 'siPart' -- -- * 'siUploadProtocol' -- -- * 'siAccessToken' -- -- * 'siUploadType' -- -- * 'siPayload' -- -- * 'siCallback' subscriptionsInsert :: [Text] -- ^ 'siPart' -> Subscription -- ^ 'siPayload' -> SubscriptionsInsert subscriptionsInsert pSiPart_ pSiPayload_ = SubscriptionsInsert' { _siXgafv = Nothing , _siPart = _Coerce # pSiPart_ , _siUploadProtocol = Nothing , _siAccessToken = Nothing , _siUploadType = Nothing , _siPayload = pSiPayload_ , _siCallback = Nothing } -- | V1 error format. siXgafv :: Lens' SubscriptionsInsert (Maybe Xgafv) siXgafv = lens _siXgafv (\ s a -> s{_siXgafv = a}) -- | The *part* parameter serves two purposes in this operation. It -- identifies the properties that the write operation will set as well as -- the properties that the API response will include. siPart :: Lens' SubscriptionsInsert [Text] siPart = lens _siPart (\ s a -> s{_siPart = a}) . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). siUploadProtocol :: Lens' SubscriptionsInsert (Maybe Text) siUploadProtocol = lens _siUploadProtocol (\ s a -> s{_siUploadProtocol = a}) -- | OAuth access token. siAccessToken :: Lens' SubscriptionsInsert (Maybe Text) siAccessToken = lens _siAccessToken (\ s a -> s{_siAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). siUploadType :: Lens' SubscriptionsInsert (Maybe Text) siUploadType = lens _siUploadType (\ s a -> s{_siUploadType = a}) -- | Multipart request metadata. siPayload :: Lens' SubscriptionsInsert Subscription siPayload = lens _siPayload (\ s a -> s{_siPayload = a}) -- | JSONP siCallback :: Lens' SubscriptionsInsert (Maybe Text) siCallback = lens _siCallback (\ s a -> s{_siCallback = a}) instance GoogleRequest SubscriptionsInsert where type Rs SubscriptionsInsert = Subscription type Scopes SubscriptionsInsert = '["https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtubepartner"] requestClient SubscriptionsInsert'{..} = go _siPart _siXgafv _siUploadProtocol _siAccessToken _siUploadType _siCallback (Just AltJSON) _siPayload youTubeService where go = buildClient (Proxy :: Proxy SubscriptionsInsertResource) mempty
brendanhay/gogol
gogol-youtube/gen/Network/Google/Resource/YouTube/Subscriptions/Insert.hs
mpl-2.0
5,212
0
18
1,264
807
471
336
116
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} module Gonimo.Server.State.Types where import Control.Concurrent.STM (TVar) import Control.Concurrent.Async (Async) import Control.Lens import Control.Monad.Trans.Maybe import Control.Monad.State.Class import Control.Monad.Trans.State (StateT (..)) import Data.Aeson.Types (FromJSON (..), FromJSON, ToJSON (..), ToJSON (..), defaultOptions, genericToEncoding, genericToJSON) import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Text (Text) import GHC.Generics (Generic) import Servant.PureScript (jsonParseHeader, jsonParseUrlPiece) import Web.HttpApiData (FromHttpApiData (..)) import Gonimo.Server.Db.Entities (DeviceId, FamilyId) import Gonimo.Server.Types (DeviceType, Secret) type FromId = DeviceId type ToId = DeviceId -- | For online session to identify a particular session newtype SessionId = SessionId Int deriving (Ord, Eq, Show, Generic) instance ToJSON SessionId where toJSON = genericToJSON defaultOptions toEncoding = genericToEncoding defaultOptions instance FromJSON SessionId instance FromHttpApiData SessionId where parseUrlPiece = jsonParseUrlPiece parseHeader = jsonParseHeader -- | To identify messages on socket/channel to avoid race conditions when reading. newtype MessageNumber = MessageNumber Int deriving (Ord, Eq, Show, Generic) instance ToJSON MessageNumber where toJSON = genericToJSON defaultOptions toEncoding = genericToEncoding defaultOptions instance FromJSON MessageNumber instance FromHttpApiData MessageNumber where parseUrlPiece = jsonParseUrlPiece parseHeader = jsonParseHeader data MessageState a = Written a | Read deriving (Eq, Show) $(makePrisms ''MessageState) -- | A request for opening a channel on a socket. type ChannelRequest = (DeviceId, Secret) -- | Writers wait for the receiver to receive a message, -- | the reader then signals that it has read it's message -- | and the writer afterwards removes the message. In case the receiver does not -- | receive the message in time, the writer also removes the message. -- | The reader never removes a message, because then it would be possible -- | that the writer deletes someone elses message in case of a timeout. -- | -- | The message could already have been received and replaced by a new one and we would delete -- | a message sent by someone else. This would have been a really nasty bug *phooooh* data MessageBox num val = MessageBox { _messageNumber :: !num -- We need message numbers to make sure the reader does not mark the wrong message as read! , _messageState :: !(MessageState val) -- Signal the writer that the reader successfully retrieved a message. } deriving (Eq, Show) $(makeLenses ''MessageBox) -- | Baby station calls receiveSocket: Map of it's client id to the requester's client id and the channel secret. type ChannelSecrets = Map ToId (MessageBox ChannelRequest ChannelRequest) type ChannelData a = Map (FromId, ToId, Secret) (MessageBox MessageNumber a) data FamilyOnlineState = FamilyOnlineState { _channelSecrets :: ChannelSecrets , _channelData :: ChannelData [Text] , _sessions :: Map DeviceId (SessionId, DeviceType) , _sessionThreads :: Map DeviceId (Async ()) , _idCounter :: Int -- Used for SessionId's currently , _channelSequence :: Int -- Used to identify messages on channels/sockets. } deriving (Eq) $(makeLenses ''FamilyOnlineState) type FamilyMap = Map FamilyId (TVar FamilyOnlineState) type OnlineState = TVar FamilyMap type UpdateFamilyT m a = StateT FamilyOnlineState m a type MayUpdateFamily a = UpdateFamilyT (MaybeT Identity) a type UpdateFamily a = UpdateFamilyT Identity a emptyFamily :: FamilyOnlineState emptyFamily = FamilyOnlineState { _channelSecrets = M.empty , _channelData = M.empty , _sessions = M.empty , _sessionThreads = M.empty , _idCounter = 0 , _channelSequence = 0 } class GetMessageNumber state val number where getMessageNumber :: MonadState state m => val -> m number instance GetMessageNumber FamilyOnlineState [Text] MessageNumber where getMessageNumber _ = do newId <- use channelSequence channelSequence += 1 pure $ MessageNumber newId instance GetMessageNumber FamilyOnlineState (DeviceId, Secret) (DeviceId, Secret) where getMessageNumber val = pure val
gonimo/gonimo-back
src/Gonimo/Server/State/Types.hs
agpl-3.0
4,954
0
12
1,246
877
512
365
86
1
{-# OPTIONS_GHC -Wall -fno-cse -fno-full-laziness #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module Dyno.Interpolant ( Interpolant(..) -- * FFI , CInterpolant(..) , newCInterpolant , evalCInterpolant , arrangeValues2 , arrangeValues3 , arrangeValues4 ) where import Control.Monad ( void, when ) import Data.List ( intercalate ) import Data.Int ( Int8, Int64 ) import qualified Data.Vector as V import qualified Data.Vector.Storable as SV import qualified Data.Vector.Storable.Mutable as SVM import Data.Word ( Word64 ) import Foreign.C.String import Foreign.C.Types import Foreign.Ptr ( Ptr ) import Foreign.Marshal.Alloc ( free ) import Foreign.Marshal.Array ( mallocArray, newArray, peekArray, withArray ) import Linear ( V2(..), V3(..), V4(..) ) import System.IO.Unsafe ( unsafePerformIO ) import Dyno.Vectorize ( Vectorize(vectorize, devectorize') ) foreign import ccall unsafe "interpolant.hpp new_interpolant" c_newInterpolant :: Ptr (Ptr CDouble) -> Int64 -> Ptr Int64 -> Int64 -> CString -> Ptr CDouble -> Word64 -> Ptr Int64 -> Word64 -> Ptr Int64 -> Word64 -> IO Int8 foreign import ccall unsafe "casadi_interpn" c_casadiInterpn :: Ptr CDouble -> Int64 -> Ptr CDouble -> Ptr Int64 -> Ptr CDouble -> Ptr CDouble -> Ptr Int64 -> Int64 -> Ptr Int64 -> Ptr CDouble -> IO () data CInterpolant = CInterpolant { ciNDims :: Int , ciNOutputs :: Int , ciGrid :: SV.Vector CDouble , ciOffset :: SV.Vector Int64 , ciValues :: SV.Vector CDouble , ciLookupModes :: SV.Vector Int64 , ciIW :: SVM.IOVector Int64 , ciW :: SVM.IOVector CDouble } newCInterpolant :: String -> [[Double]] -> [Double] -> IO CInterpolant newCInterpolant lookupMode grid values = do let ndims = length grid gridLengths = map length grid nvalues = length values gridLengthProd = product gridLengths noutputs :: Int noutputs = nvalues `div` gridLengthProd void $ when (noutputs * gridLengthProd /= nvalues) $ error $ intercalate "\n" [ "newInterpolant: noutputs * gridLengthProd /= nvalues" , "grid lengths: " ++ show gridLengths , "# values: " ++ show nvalues , "noutputs: " ++ show noutputs ] gridPtrs <- mapM (newArray . map realToFrac) grid :: IO [Ptr CDouble] gridPtr <- newArray gridPtrs :: IO (Ptr (Ptr CDouble)) gridLengthsPtr <- newArray (map fromIntegral gridLengths) :: IO (Ptr Int64) stackedGridMut <- SVM.new (sum gridLengths) :: IO (SVM.IOVector CDouble) offsetMut <- SVM.new (ndims + 1) :: IO (SVM.IOVector Int64) lookupModesMut <- SVM.new ndims :: IO (SVM.IOVector Int64) ret <- SVM.unsafeWith stackedGridMut $ \stackedGridPtr -> SVM.unsafeWith offsetMut $ \offsetPtr -> SVM.unsafeWith lookupModesMut $ \lookupModesPtr -> withCString lookupMode $ \lookupModePtr -> c_newInterpolant gridPtr (fromIntegral ndims) gridLengthsPtr (fromIntegral nvalues) lookupModePtr stackedGridPtr (fromIntegral (SVM.length stackedGridMut)) offsetPtr (fromIntegral (SVM.length offsetMut)) lookupModesPtr (fromIntegral (SVM.length lookupModesMut)) stackedGrid <- SV.freeze stackedGridMut offset <- SV.freeze offsetMut lookupModes <- SV.freeze lookupModesMut free gridLengthsPtr free gridPtr mapM_ free gridPtrs iw <- SVM.new (2 * ndims) w <- SVM.new ndims if ret /= 0 then error "interpolant creation failed!" else return CInterpolant { ciNDims = ndims , ciNOutputs = noutputs , ciGrid = stackedGrid , ciOffset = offset , ciValues = SV.fromList (fmap realToFrac values) , ciLookupModes = lookupModes , ciIW = iw , ciW = w } evalCInterpolant :: CInterpolant -> [Double] -> IO [Double] evalCInterpolant cinterpolant inputs | length inputs /= ciNDims cinterpolant = error $ intercalate "\n" [ "interpolant called with wrong number of values" , "expected dimension: " ++ show (ciNDims cinterpolant) , "given dimensions: " ++ show (length inputs) ] | otherwise = do let noutputs = ciNOutputs cinterpolant outputPtr <- mallocArray noutputs :: IO (Ptr CDouble) withArray (map realToFrac inputs) $ \inputPtr -> SV.unsafeWith (ciGrid cinterpolant) $ \gridPtr -> SV.unsafeWith (ciOffset cinterpolant) $ \offsetPtr -> SV.unsafeWith (ciLookupModes cinterpolant) $ \lookupModesPtr -> SV.unsafeWith (ciValues cinterpolant) $ \valuesPtr -> SVM.unsafeWith (ciIW cinterpolant) $ \iwPtr -> SVM.unsafeWith (ciW cinterpolant) $ \wPtr -> c_casadiInterpn outputPtr (fromIntegral (ciNDims cinterpolant)) gridPtr offsetPtr valuesPtr inputPtr lookupModesPtr (fromIntegral noutputs) iwPtr wPtr ret <- peekArray noutputs outputPtr :: IO [CDouble] free outputPtr return (map realToFrac ret) arrangeValues2 :: forall f0 f1 g . ( Vectorize f0, Traversable f0 , Vectorize f1 , Vectorize g ) => f0 Double -> f1 Double -> f0 (f1 (g Double)) -> (V.Vector (V.Vector Double), V.Vector Double) arrangeValues2 grid0 grid1 values0 = (grid, concatValues vectorizedValues) where -- transpose values values :: f1 (f0 (g Double)) values = sequenceA values0 vectorizedValues :: V.Vector (g Double) vectorizedValues = V.concatMap vectorize (vectorize values) grid :: V.Vector (V.Vector Double) grid = V.fromList [vectorize grid0, vectorize grid1] arrangeValues3 :: forall f0 f1 f2 g . ( Vectorize f0, Traversable f0 , Vectorize f1, Traversable f1 , Vectorize f2 , Vectorize g ) => f0 Double -> f1 Double -> f2 Double -> f0 (f1 (f2 (g Double))) -> (V.Vector (V.Vector Double), V.Vector Double) arrangeValues3 grid0 grid1 grid2 values0 = (grid, concatValues vectorizedValues) where -- transpose values values :: f2 (f1 (f0 (g Double))) values = v3 where v0 :: f0 (f1 (f2 (g Double))) v0 = values0 v1 :: f1 (f0 (f2 (g Double))) v1 = sequenceA v0 v2 :: f1 (f2 (f0 (g Double))) v2 = fmap sequenceA v1 v3 :: f2 (f1 (f0 (g Double))) v3 = sequenceA v2 vectorizedValues :: V.Vector (g Double) vectorizedValues = V.concatMap vectorize $ V.concatMap vectorize (vectorize values) grid :: V.Vector (V.Vector Double) grid = V.fromList [vectorize grid0, vectorize grid1, vectorize grid2] arrangeValues4 :: forall f0 f1 f2 f3 g . ( Vectorize f0, Traversable f0 , Vectorize f1, Traversable f1 , Vectorize f2, Traversable f2 , Vectorize f3 , Vectorize g ) => f0 Double -> f1 Double -> f2 Double -> f3 Double -> f0 (f1 (f2 (f3 (g Double)))) -> (V.Vector (V.Vector Double), V.Vector Double) arrangeValues4 grid0 grid1 grid2 grid3 values0 = (grid, concatValues vectorizedValues) where -- transpose values values :: f3 (f2 (f1 (f0 (g Double)))) values = v6 where v0 :: f0 (f1 (f2 (f3 (g Double)))) v0 = values0 v1 :: f1 (f0 (f2 (f3 (g Double)))) v1 = sequenceA v0 v2 :: f1 (f2 (f0 (f3 (g Double)))) v2 = fmap sequenceA v1 v3 :: f1 (f2 (f3 (f0 (g Double)))) v3 = fmap (fmap sequenceA) v2 v4 :: f2 (f1 (f3 (f0 (g Double)))) v4 = sequenceA v3 v5 :: f2 (f3 (f1 (f0 (g Double)))) v5 = fmap sequenceA v4 v6 :: f3 (f2 (f1 (f0 (g Double)))) v6 = sequenceA v5 vectorizedValues :: V.Vector (g Double) vectorizedValues = V.concatMap vectorize $ V.concatMap vectorize $ V.concatMap vectorize (vectorize values) grid :: V.Vector (V.Vector Double) grid = V.fromList [vectorize grid0, vectorize grid1, vectorize grid2, vectorize grid3] concatValues :: Vectorize g => V.Vector (g Double) -> V.Vector Double concatValues = V.concatMap vectorize {-# NOINLINE makeCInterpolant1 #-} makeCInterpolant1 :: forall g . Vectorize g => String -> V.Vector (Double, g Double) -> IO (Double -> g Double) makeCInterpolant1 lookupName gridAndValues = do let (grid, values) = V.unzip gridAndValues interpolant <- newCInterpolant lookupName [V.toList grid] (V.toList (concatValues values)) let {-# NOINLINE interpolate #-} interpolate :: Double -> g Double interpolate x = unsafePerformIO $ do ret <- evalCInterpolant interpolant [x] case devectorize' (V.fromList ret) of Right r -> return r Left err -> error $ "interpolant1 error devectorizing outputs: " ++ err return interpolate {-# NOINLINE makeCInterpolant2 #-} makeCInterpolant2 :: forall f0 f1 g . ( Vectorize f0, Traversable f0 , Vectorize f1 , Vectorize g ) => String -> f0 Double -> f1 Double -> f0 (f1 (g Double)) -> IO (V2 Double -> g Double) makeCInterpolant2 lookupName grid0 grid1 values0 = do let grid :: V.Vector (V.Vector Double) vectorizedValues :: V.Vector Double (grid, vectorizedValues) = arrangeValues2 grid0 grid1 values0 interpolant <- newCInterpolant lookupName (map V.toList (V.toList grid)) (V.toList vectorizedValues) let {-# NOINLINE interpolate #-} interpolate :: V2 Double -> g Double interpolate (V2 x y) = unsafePerformIO $ do ret <- evalCInterpolant interpolant [x, y] case devectorize' (V.fromList ret) of Right r -> return r Left err -> error $ "interpolant2 error devectorizing outputs: " ++ err return interpolate {-# NOINLINE makeCInterpolant3 #-} makeCInterpolant3 :: forall f0 f1 f2 g . ( Vectorize f0, Traversable f0 , Vectorize f1, Traversable f1 , Vectorize f2 , Vectorize g ) => String -> f0 Double -> f1 Double -> f2 Double -> f0 (f1 (f2 (g Double))) -> IO (V3 Double -> g Double) makeCInterpolant3 lookupName grid0 grid1 grid2 values0 = do let grid :: V.Vector (V.Vector Double) vectorizedValues :: V.Vector Double (grid, vectorizedValues) = arrangeValues3 grid0 grid1 grid2 values0 interpolant <- newCInterpolant lookupName (map V.toList (V.toList grid)) (V.toList vectorizedValues) let {-# NOINLINE interpolate #-} interpolate :: V3 Double -> g Double interpolate (V3 x y z) = unsafePerformIO $ do ret <- evalCInterpolant interpolant [x, y, z] case devectorize' (V.fromList ret) of Right r -> return r Left err -> error $ "interpolant3 error devectorizing outputs: " ++ err return interpolate {-# NOINLINE makeCInterpolant4 #-} makeCInterpolant4 :: forall f0 f1 f2 f3 g . ( Vectorize f0, Traversable f0 , Vectorize f1, Traversable f1 , Vectorize f2, Traversable f2 , Vectorize f3 , Vectorize g ) => String -> f0 Double -> f1 Double -> f2 Double -> f3 Double -> f0 (f1 (f2 (f3 (g Double)))) -> IO (V4 Double -> g Double) makeCInterpolant4 lookupName grid0 grid1 grid2 grid3 values0 = do let grid :: V.Vector (V.Vector Double) vectorizedValues :: V.Vector Double (grid, vectorizedValues) = arrangeValues4 grid0 grid1 grid2 grid3 values0 interpolant <- newCInterpolant lookupName (map V.toList (V.toList grid)) (V.toList vectorizedValues) let {-# NOINLINE interpolate #-} interpolate :: V4 Double -> g Double interpolate (V4 x y z w) = unsafePerformIO $ do ret <- evalCInterpolant interpolant [x, y, z, w] case devectorize' (V.fromList ret) of Right r -> return r Left err -> error $ "interpolant4 error devectorizing outputs: " ++ err return interpolate class Interpolant a where makeInterpolant1 :: Vectorize g => String -> String -> V.Vector (Double, g Double) -> IO (a -> g a) makeInterpolant2 :: ( Vectorize f0, Traversable f0 , Vectorize f1 , Vectorize g ) => String -> String -> f0 Double -> f1 Double -> f0 (f1 (g Double)) -> IO (V2 a -> g a) makeInterpolant3 :: ( Vectorize f0, Traversable f0 , Vectorize f1, Traversable f1 , Vectorize f2 , Vectorize g ) => String -> String -> f0 Double -> f1 Double -> f2 Double -> f0 (f1 (f2 (g Double))) -> IO (V3 a -> g a) makeInterpolant4 :: ( Vectorize f0, Traversable f0 , Vectorize f1, Traversable f1 , Vectorize f2, Traversable f2 , Vectorize f3 , Vectorize g ) => String -> String -> f0 Double -> f1 Double -> f2 Double -> f3 Double -> f0 (f1 (f2 (f3 (g Double)))) -> IO (V4 a -> g a) instance Interpolant Double where makeInterpolant1 _ = makeCInterpolant1 makeInterpolant2 _ = makeCInterpolant2 makeInterpolant3 _ = makeCInterpolant3 makeInterpolant4 _ = makeCInterpolant4
ghorn/dynobud
dynobud-interpolant/src/Dyno/Interpolant.hs
lgpl-3.0
13,206
0
26
3,579
4,454
2,232
2,222
312
2
module DaPhone where data DaPhone = Daphone
aniketd/learn.haskell
haskellbook/daphone.hs
unlicense
45
0
5
8
11
7
4
2
0
module Main where import Data.List nucleotideComplement :: Char -> Char nucleotideComplement 'A' = 'T' nucleotideComplement 'T' = 'A' nucleotideComplement 'C' = 'G' nucleotideComplement 'G' = 'C' main = do contents <- getContents putStrLn $ foldl' accumulateReversedNucleotideComplement [] contents where accumulateReversedNucleotideComplement = flip $ (:) . nucleotideComplement
ctimmons/hs_rosalind
3 - Complementing a Strand of DNA/Main.hs
unlicense
410
0
9
76
95
50
45
11
1
{-# LANGUAGE OverloadedStrings #-} module Messages.RespFacade where import Control.Applicative import Control.Monad import Data.Aeson import Model.URI ------------------------------------------------------------------------------ | Data type holding the message's formats Facade Server can send to the client. data RespFacade = RespFacade01 { replyTo :: URI -- TODO: Shouldn't we use a simple HTTP redirect? (Probably...) } deriving (Eq, Show) instance ToJSON RespFacade where toJSON (RespFacade01 rt) = object [ "replyTo" .= rt ] instance FromJSON RespFacade where parseJSON (Object v) = RespFacade01 <$> v .: "replyTo" parseJSON _ = mzero
alexandrelucchesi/pfec
facade-server/src/Messages/RespFacade.hs
apache-2.0
732
0
8
174
125
69
56
17
0
module Solar.Continuum.Types where import qualified Data.Serialize as S import qualified Data.ByteString as B import Data.Int import Control.Applicative type LogName = B.ByteString -- | Known positions are meant to be persisted, -- but data may go through intermediary stages as the positions are finalized data LogPos = Known Int64 | Unknown Int deriving (Eq, Show) -- | Shortcut for what 'S.Serialize' has when parsing -- Only to be used when reading from a log, not when getting -- a message. type TryRead a = Either String a -- | Gets and stores the position within a log as a 64 bit int. -- If something is ever persisted that should not be, look for the magic number, -- @0xFEED0B0BDEADBEEF@ instance S.Serialize LogPos where put p = case p of Known v -> S.putWord64host $ fromIntegral v Unknown _ -> S.putWord64host 0xFEED0B0BDEADBEEF -- The above: Filler for now. Pointless to store the internal identifier. get = Known <$> fromIntegral <$> S.getWord64host -- | A loggable and serializeable data type should implement this. -- A note to implementors, make sure to use least-fixed-point -- to detect whether or not the collection to persist is not fully resolveable. class (S.Serialize a) => Loggable a where resolvePositions :: a -> (Int -> Maybe Int64) -> a unresolvedPositions :: a -> Int
Cordite-Studios/solar-continuum
src/Solar/Continuum/Types.hs
bsd-2-clause
1,357
0
11
274
211
121
90
19
0