code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Control.Monad.Random
import Control.Applicative
import Control.Concurrent.ParallelIO
import Data.List (zipWith, sortBy, replicate, intercalate)
import Data.IORef
import Data.List.Split (splitOn)
import qualified Data.ByteString.Lazy as T
import qualified Data.Aeson as A
import Data.Aeson ((.=))
import Options
import System.IO
newtype MutationRate = MutationRate Double
deriving (Show, Eq, Ord)
newtype Goal = Goal [Bool] -- ^ This is the goal vector, but it might change!
deriving (Show, Eq, Ord)
newtype Offspring = Offspring Int
deriving (Show, Eq, Ord)
newtype Survival = Survival Int
deriving (Show, Eq, Ord)
data Genome = Genome
{ sexual :: Bool
, fitness :: [Bool]
} deriving (Show, Eq, Ord)
data World = World
{ worldGoal :: Goal
, worldGenome :: [Genome]
} deriving (Show)
instance A.ToJSON Goal where
toJSON (Goal g) = A.toJSON g
instance A.ToJSON Genome where
toJSON (Genome s f) = A.object
[ "sexual" .= s
-- , "vec" .= f
]
instance A.ToJSON World where
toJSON (World { worldGoal = g, worldGenome = gen }) =
let serialize genome = A.object
[ "sexual" .= sexual genome
, "fitness" .= fitnessEval g genome
]
in A.toJSON $ map serialize gen
getChance :: (RandomGen g) => Rand g Double
getChance = getRandomR (0, 1)
withProb :: (RandomGen g) => Double -> a -> a -> Rand g a
withProb p x y = do
r <- getChance
return $ if r < p then x else y
choice :: (RandomGen g) => [a] -> Rand g (Maybe a)
choice [] = return Nothing
choice (x:xs) = Just <$> choice' 0 x xs
where
choice' :: (RandomGen g) => Double -> a -> [a] -> Rand g a
choice' i d [] = return d
choice' i d (x:xs) = do
newD <- withProb (1/i) x d
choice' (i+1) newD xs
mutateGene :: (RandomGen g) => MutationRate -> Bool -> Rand g Bool
mutateGene (MutationRate mt) b = withProb mt (not b) b
mutate :: (RandomGen g) => MutationRate -> Genome -> Rand g Genome
mutate m g =
Genome <$> mutateGene m (sexual g) <*> mapM (mutateGene m) (fitness g)
crossover :: (RandomGen g) => Genome -> Genome -> Rand g Genome
crossover g1 g2 = do
when (not (sexual g1 && sexual g2)) $ fail "Nonsexual sex?!"
let f1 = fitness g1
f2 = fitness g2
c = zip f1 f2
choose (x,y) = withProb 0.5 x y
Genome True <$> mapM choose c
fitnessEval :: Goal -> Genome -> Double
fitnessEval (Goal bs) (Genome { fitness = f }) =
sum $ zipWith (\x y -> if x == y then 1 else 0) bs f
bestPopulation :: Survival -> Goal -> [Genome] -> [Genome]
bestPopulation (Survival n) goal population =
let compare' x y = fitnessEval goal x `compare` fitnessEval goal y
in take n $ sortBy compare' population
reproduce :: (RandomGen g) => MutationRate -> Offspring -> [Genome] ->
Genome -> Rand g [Genome]
reproduce mr (Offspring n) _ g@(Genome { sexual = False }) =
mapM (mutate mr) $ replicate n g
reproduce mr (Offspring n) population g@(Genome { sexual = True }) = do
mate' <- choice $ filter sexual population
case mate' of
Nothing -> return []
Just mate -> do
crossed <- mapM (\_ -> crossover mate g) [1..n `div` 2]
mapM (mutate mr) crossed
updatePopulation :: (RandomGen g) =>
MutationRate -> Survival ->
Offspring -> Goal -> [Genome] -> Rand g [Genome]
updatePopulation mr s os goal population = do
pop' <- mapM (reproduce mr os population) population
let pop = concat pop'
return $ bestPopulation s goal pop
updateWorld :: (RandomGen g) =>
MutationRate -> MutationRate -> Survival ->
Offspring -> Goal -> [Genome] -> Rand g (Goal, [Genome])
updateWorld goalMutation mr s os goal@(Goal goalvec) population =
(,) <$> (Goal <$> mapM (mutateGene goalMutation) goalvec)
<*> updatePopulation mr s os goal population
dumpWorld :: Goal -> [Genome] -> T.ByteString
dumpWorld goal genome =
A.encode $ World goal genome
instance Random Genome where
randomR ((Genome { fitness = f1 }), _) g =
let len = length f1
(sex, g') = random g
addRand (l, gen) _ = case random gen of
(el, gen') -> (el:l, gen')
(f', g'') = foldl addRand ([], g') [1..len]
in (Genome sex f', g'')
random g =
let gene = Genome True $ replicate 100 True
in randomR (gene, gene) g
data CmdOptions = CmdOptions
{ cmdGoalChange :: [Double]
, cmdMutationRate :: [Double]
, cmdOffspring :: [Int]
, cmdPopsize :: [Int]
, cmdGenomesize :: [Int]
, cmdGenerations :: Int
}
listOption :: SimpleOptionType a => String -> String -> DefineOptions [a]
listOption name doc = defineOption t mod
where t = optionType_list ',' simpleOptionType
mod o = o { optionLongFlags = [name]
, optionDefault = []
, optionDescription = doc
}
instance Options CmdOptions where
defineOptions = CmdOptions
<$> listOption "goal-change" "Mutation rate of the goal"
<*> listOption "mutation-rate" "Mutation rate of the population"
<*> listOption "offspring" "Number of children each member has"
<*> listOption "population" "Population size"
<*> listOption "genome" "Genome size"
<*> simpleOption "generations" 100 "Number of generations to run"
runSingle :: String -> MutationRate -> MutationRate ->
Offspring -> Survival -> Int -> Int -> IO ()
runSingle prefix goalMr@(MutationRate gmr') mr@(MutationRate mr')
offspring@(Offspring offspring') survival@(Survival survival')
genome generations = do
let filename = prefix ++ "-" ++ intercalate "-" [ show gmr'
, show mr'
, show offspring'
, show survival'
, show genome
] ++ ".json"
file <- openFile filename WriteMode
let goal = Goal $ replicate genome True
template = Genome True $ replicate genome True
population' <- getRandomRs (template, template)
let population = take survival' population'
goalRef <- newIORef goal
geneRef <- newIORef population
forM_ [1..generations] $ \_ -> do
g <- readIORef goalRef
pop <- readIORef geneRef
(g', genes) <- evalRandIO $ updateWorld goalMr mr
survival offspring g pop
writeIORef goalRef g'
writeIORef geneRef genes
T.hPutStr file $ dumpWorld g' genes
T.hPutStr file "\n"
hClose file
mainCmd :: CmdOptions -> [String] -> IO ()
mainCmd opts [] = mainCmd opts ["exp"]
mainCmd opts (prefix:o) = do
let all = do
goal <- cmdGoalChange opts
mr <- cmdMutationRate opts
offspring <- cmdOffspring opts
pop <- cmdPopsize opts
genome <- cmdGenomesize opts
return (MutationRate goal, MutationRate mr, Offspring offspring
, Survival pop, genome)
let run (goal, mr, offspring, pop, genome) =
runSingle prefix goal mr offspring pop genome (cmdGenerations opts)
actions = map run all
void $ parallelInterleaved actions
main = runCommand mainCmd
|
zombiecalypse/SexSelect
|
src/SexSelect.hs
|
mit
| 7,319 | 44 | 16 | 2,070 | 2,710 | 1,356 | 1,354 | 177 | 2 |
-- InfTreeNode.hs ---
--
-- Filename: InfTreeNode.hs
-- Description:
-- Author: Manuel Schneckenreither
-- Maintainer:
-- Created: Mon Oct 6 13:20:02 2014 (+0200)
-- Version:
-- Package-Requires: ()
-- Last-Updated: Tue Apr 11 14:34:02 2017 (+0200)
-- By: Manuel Schneckenreither
-- Update #: 7
-- URL:
-- Doc URL:
-- Keywords:
-- Compatibility:
--
--
-- Commentary:
--
--
--
--
-- Change Log:
--
--
--
--
--
--
--
-- Code:
-- | TODO: comment this module
module Data.Rewriting.ARA.ByInferenceRules.InfTreeNode
( module Data.Rewriting.ARA.ByInferenceRules.InfTreeNode.Type
, module Data.Rewriting.ARA.ByInferenceRules.InfTreeNode.Pretty
, module Data.Rewriting.ARA.ByInferenceRules.InfTreeNode.Ops
)
where
import Data.Rewriting.ARA.ByInferenceRules.InfTreeNode.Ops
import Data.Rewriting.ARA.ByInferenceRules.InfTreeNode.Pretty
import Data.Rewriting.ARA.ByInferenceRules.InfTreeNode.Type
--
-- InfTreeNode.hs ends here
|
ComputationWithBoundedResources/ara-inference
|
src/Data/Rewriting/ARA/ByInferenceRules/InfTreeNode.hs
|
mit
| 989 | 0 | 5 | 175 | 103 | 88 | 15 | 7 | 0 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Save changes to a new or existing site
--
-- License: MIT
-- Maintainer: Montez Fitzpatrick
-- Stability: experimental
-- APIVersion: 1.1
--
module Nexpose.API.SiteSave where
-- (
-- * Main Datatypes
-- * Picklers
-- ) where
import Text.XML.Expat.Pickle
import Text.XML.Expat.Tree
import Data.ByteString.Lazy.Char8 (pack, unpack)
import Nexpose.URI
import Nexpose.API.Site
data SiteSaveRequest = SiteSaveRequest
{ siteSaveReq_syncId :: Maybe String
, siteSaveReq_sessionId :: !String
, siteSaveReq_site :: !Site
} deriving (Eq, Show)
instance ApiVersion SiteSaveRequest where
versionURI a = api11
data SiteSaveResponse = SiteSaveResponse -- TODO: Handle Failure
{ siteSaveRes_success :: !String
, siteSaveRes_siteId :: !String
} deriving (Eq, Show)
xpSiteSaveRequest :: PU [UNode String] SiteSaveRequest
xpSiteSaveRequest =
xpWrap (\((sy,sess),ssite) -> SiteSaveRequest sy sess ssite,
\(SiteSaveRequest sy sess ssite) -> ((sy,sess),ssite)) $
xpElem "SiteSaveRequest"
(xpPair
(xpOption (xpAttr "sync-id" xpText0))
(xpAttr "session-id" xpText0))
(xpSite)
xpSiteSaveResponse :: PU [UNode String] SiteSaveResponse
xpSiteSaveResponse =
xpWrap ( uncurry SiteSaveResponse,
\(SiteSaveResponse succ sid) -> (succ,sid)) $
xpElemAttrs "SiteSaveResponse"
(xpPair
(xpAttr "success" xpText0)
(xpAttr "site-id" xpText0))
-- REPL Test Functions
|
m15k/hs-nexpose-client
|
nexpose/src/Nexpose/API/SiteSave.hs
|
mit
| 1,546 | 0 | 12 | 291 | 366 | 211 | 155 | 45 | 1 |
{-# htermination (*) :: Num a => a -> a -> a #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_STAR_1.hs
|
mit
| 49 | 0 | 2 | 13 | 3 | 2 | 1 | 1 | 0 |
{-# LANGUAGE MultiWayIf #-}
module Main where
import Control.Monad
import Data.Char
import Language.Formura.Parser.Combinator
verbatim :: Char -> String
verbatim c
| c == '|' = "\\verb+" ++ [c] ++ "+"
| otherwise = "\\verb|" ++ [c] ++ "|"
main :: IO ()
main = do
putStrLn "\\begin{tabular}{cccccccccccccccc}"
forM_ [0..7] $ \j -> do
forM_ [0..15] $ \i -> do
let asc :: Int
asc = j*16+i
chr :: Char
chr = toEnum asc
if | isIdentifierAlphabet0 chr -> putStr $ "\\cellcolor{alphabetcolor} " ++ verbatim chr
| isIdentifierAlphabet1 chr -> putStr $ "\\cellcolor{alphabetoidcolor} " ++ verbatim chr
| isIdentifierSymbol chr -> putStr $ "\\cellcolor{symbolcolor} " ++ verbatim chr
| isStandaloneIdentifierSymbol chr -> putStr $ "\\cellcolor{symboliccolor} " ++ verbatim chr
| isPrint chr -> putStr $ "\\cellcolor{othercharcolor} " ++ verbatim chr
| otherwise -> putStr $ " "
when (i < 15) $ putStr " &"
when (j < 7) $ putStrLn "\\\\"
putStrLn ""
putStrLn "\\end{tabular}"
|
nushio3/formura
|
exe-src/formura-list-reserved-char.hs
|
mit
| 1,167 | 0 | 19 | 357 | 359 | 171 | 188 | 28 | 6 |
type Node = Int
start :: Node
start = 16
operator :: Node -> [Node]
operator x =
| x > 5 = [x-3, x - 5]
| x > 3 = [x-3]
| otherwise = []
terminal :: Node -> Boolean
terminal n = (operator n == [])
alphabeta :: [State] -> Int -> Int -> Int -> Boolean -> Int
alphabeta [x] d a b player = x
alphabeta (x:xs) d a b player
| ((d == 0) = x
| b >= a = x
| player = max( -9999999, alphabeta (newstates ++ x) (d-1) a b False)
| otherwise = min( 9999999, alphabeta (newstates ++ x) (d-1) a b True)
where newstates = operator xs
alphabetaMin :: [State] -> Int -> Int -> Int -> Int -> Int
alphabetaMin [] d v a b = v
alphabetaMin (x:xs) d v a b
| b <= newA = v
| otherwise
|
fultonms/artificial-intelligence
|
exam/minmax.hs
|
mit
| 711 | 6 | 12 | 204 | 422 | 211 | 211 | -1 | -1 |
module Solidran.Prot.Detail (encode) where
import Data.Map (Map)
import qualified Data.Map as Map
import Solidran.List (groupEvery)
codonTable :: Map String Char
codonTable =
Map.fromList
[ ("UUU", 'F')
, ("CUU", 'L')
, ("AUU", 'I')
, ("GUU", 'V')
, ("UUC", 'F')
, ("CUC", 'L')
, ("AUC", 'I')
, ("GUC", 'V')
, ("UUA", 'L')
, ("CUA", 'L')
, ("AUA", 'I')
, ("GUA", 'V')
, ("UUG", 'L')
, ("CUG", 'L')
, ("AUG", 'M')
, ("GUG", 'V')
, ("UCU", 'S')
, ("CCU", 'P')
, ("ACU", 'T')
, ("GCU", 'A')
, ("UCC", 'S')
, ("CCC", 'P')
, ("ACC", 'T')
, ("GCC", 'A')
, ("UCA", 'S')
, ("CCA", 'P')
, ("ACA", 'T')
, ("GCA", 'A')
, ("UCG", 'S')
, ("CCG", 'P')
, ("ACG", 'T')
, ("GCG", 'A')
, ("UAU", 'Y')
, ("CAU", 'H')
, ("AAU", 'N')
, ("GAU", 'D')
, ("UAC", 'Y')
, ("CAC", 'H')
, ("AAC", 'N')
, ("GAC", 'D')
, ("UAA", '\0')
, ("CAA", 'Q')
, ("AAA", 'K')
, ("GAA", 'E')
, ("UAG", '\0')
, ("CAG", 'Q')
, ("AAG", 'K')
, ("GAG", 'E')
, ("UGU", 'C')
, ("CGU", 'R')
, ("AGU", 'S')
, ("GGU", 'G')
, ("UGC", 'C')
, ("CGC", 'R')
, ("AGC", 'S')
, ("GGC", 'G')
, ("UGA", '\0')
, ("CGA", 'R')
, ("AGA", 'R')
, ("GGA", 'G')
, ("UGG", 'W')
, ("CGG", 'R')
, ("AGG", 'R')
, ("GGG", 'G') ]
replaceCodon :: String -> Char
replaceCodon s =
let (Just x) = Map.lookup s codonTable
in x
encode :: String -> String
encode = map replaceCodon . filter ((==3) . length) . groupEvery 3
|
Jefffrey/Solidran
|
src/Solidran/Prot/Detail.hs
|
mit
| 1,868 | 0 | 10 | 779 | 720 | 462 | 258 | 77 | 1 |
{- Using textures instead of surfaces -}
{-# LANGUAGE OverloadedStrings #-}
module Lesson07 where
--
import qualified SDL
import Linear.V4 (V4(..))
--
import Control.Monad (unless,when)
--
import qualified Config
--
lesson07 :: IO ()
lesson07 = do
-- initialize SDL
SDL.initialize [SDL.InitVideo]
-- create window
window <- SDL.createWindow "Lesson07" Config.winConfig
-- using Hint, comment out for seeing the effects
-- reference: https://en.wikipedia.org/wiki/Image_scaling#Scaling_methods
-- ***************
SDL.HintRenderScaleQuality SDL.$= SDL.ScaleLinear
-- ***************
renderer <- SDL.createRenderer window (-1) Config.rdrConfig
-- set a color for renderer
SDL.rendererDrawColor renderer
SDL.$= V4 minBound minBound maxBound maxBound
-- load image into main memory (as a surface)
imgSf <- SDL.loadBMP "./img/07/Potion.bmp"
-- translate a surface to a texture
-- i.e. load image into video memory
imgTx <- SDL.createTextureFromSurface renderer imgSf
SDL.freeSurface imgSf
let
loop = do
events <- SDL.pollEvents
let quit = any (== SDL.QuitEvent) $ map SDL.eventPayload events
-- clear(i.e. fill) renderer with the color we set
SDL.clear renderer
-- copy(blit) image texture onto renderer
SDL.copy renderer imgTx Nothing Nothing
-- A renderer in SDL is basically a buffer
-- the present function forces a renderer to flush
SDL.present renderer
--
unless quit loop
loop
-- releasing resources
SDL.destroyWindow window
SDL.destroyRenderer renderer
SDL.destroyTexture imgTx
SDL.quit
|
rueshyna/sdl2-examples
|
src/Lesson07.hs
|
mit
| 1,682 | 0 | 18 | 390 | 315 | 159 | 156 | 30 | 1 |
module Tracer.Color ( Color(..) ) where
import Data.Vect
data Color = Color Float Float Float deriving Eq
instance Pointwise Color where
pointwise (Color r g b) (Color r' g' b') = Color (r*r') (g*g') (b*b')
instance AbelianGroup Color where
(&+) (Color r1 g1 b1) (Color r2 g2 b2) = Color (r1+r2) (g1+g2) (b1+b2)
(&-) (Color r1 g1 b1) (Color r2 g2 b2) = Color (r1-r2) (g1-g2) (b1-b2)
neg (Color r g b) = Color (-r) (-g) (-b)
zero = Color 0 0 0
instance Vector Color where
scalarMul s (Color r g b) = Color (s*r) (s*g) (s*b)
mapVec f (Color r g b) = Color (f r) (f g) (f b)
|
sdeframond/haskell-tracer
|
src/Tracer/Color.hs
|
mit
| 625 | 0 | 8 | 165 | 383 | 202 | 181 | 13 | 0 |
--
-- this version takes each line individually
--
isPalindrome :: String -> String
isPalindrome input
| input == reverse input = "palindrome!\n"
| otherwise = "boo\n"
-- main = do
-- line <- getLine
-- putStr $ isPalindrome line
-- main
--
-- this version takes everything in one go..
--
respondPalindrome :: String -> String
respondPalindrome input =
-- unlines . map (\xs -> if xs == reverse xs then "palindrome" else "boo!!") . lines $ input
unlines . map (\xs -> isPalindrome xs) . lines $ input
main = interact respondPalindrome
|
adizere/nifty-tree
|
playground/palindrome.hs
|
mit
| 587 | 3 | 10 | 146 | 104 | 55 | 49 | 8 | 1 |
module LispParser where
import Text.ParserCombinators.Parsec
-- magic :: a
-- magic = error "Not implemented yet."
-- AST for a simple lisp
type LSymbol = String
data LAtom = LSymbol LSymbol | LString String | LInt Int deriving Show
data LProg = LAtom LAtom | LList [LProg] | LQuote LProg deriving Show
-- Parser for that simple lisp, sans comments
lprog :: Parser LProg
lprog = ((fmap LAtom latom) <|>
(fmap LList llist) <|>
(fmap LQuote lquote))
latom :: Parser LAtom
latom = (fmap LSymbol lsymbol) <|>
(fmap LString lstring) <|>
(fmap LInt lint) <?> "atom"
lsymbol :: Parser LSymbol
lsymbol = many1 lsymbchar <?>
"symbol"
lsymbchar :: Parser Char
lsymbchar = choice [letter, digit, oneOf "!?/@£$%^&*-_=+:#~.,><|"] <?> "symbol-char"
lstring :: Parser String
lstring = (do
char '"'
body <- lstringbody
char '"'
return body) <?> "lstring"
lstringbody :: Parser String
lstringbody = (many $ choice [noneOf "\\\"", (char '\\' >> anyChar)]) <?> "lstringbody"
lint :: Parser Int
lint = (fmap read $ many1 digit) <?> "lint"
llist :: Parser [LProg]
llist = (do
char '('
many space
progs <- sepEndBy lprog (many1 space)
char ')'
return $ progs)
<?> "s-expression"
lquote :: Parser LProg
lquote = (char '\'' >> fmap LQuote lprog) <?> "lquote"
lfile :: Parser [LProg]
lfile = do
many space
progs <- sepEndBy lprog (many space)
eof
return progs
-- Parser to strip comments from a lisp file
lcomment :: Parser String
lcomment = (char ';' >> many (noneOf "\n\r") >> newline >> return "")
<?> "lcomment"
commentStripper :: Parser String
commentStripper = do
parts <- many1 (lcomment <|> (fmap (:[]) (noneOf "\";")) <|> (lstring >> return ""))
return $ concat parts
-- Stringing the two together
lparse :: String -> Either ParseError [LProg]
lparse str = let stripped = parse commentStripper "" str in
either Left (parse lfile "") stripped
lparseFile :: FilePath -> IO (Either ParseError [LProg])
lparseFile path = do
contents <- readFile path
return $ lparse contents
|
totherme/Toys
|
Parsec/LispParser.hs
|
gpl-2.0
| 2,219 | 0 | 15 | 588 | 716 | 361 | 355 | 58 | 1 |
module Blaaargh.Internal.Time where
import Data.Time.Clock
import Data.Time.Format
import Data.Time.LocalTime
import System.Locale
import Text.Printf
formatAtomTime :: TimeZone -> UTCTime -> String
formatAtomTime tz = fmt . utcToLocalTime tz
where
fmt t = formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S" t ++ z
where
mins = timeZoneMinutes tz
minus = if mins < 0 then "-" else ""
h = printf "%02d" $ abs mins `div` 60
m = printf "%02d" $ abs mins `rem` 60
z = concat [minus, h, ":", m]
parseAtomTime :: String -> ZonedTime
parseAtomTime s = readTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%Z" s
friendlyTime :: ZonedTime -> String
friendlyTime t = formatTime defaultTimeLocale "%b %e, %Y" t
|
gregorycollins/blaaargh
|
src/Blaaargh/Internal/Time.hs
|
gpl-2.0
| 834 | 0 | 11 | 248 | 221 | 120 | 101 | 18 | 2 |
{-# LANGUAGE DeriveDataTypeable, TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses, DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances, DeriveDataTypeable #-}
module Petri.Property where
import Petri.Type
import Autolib.Reporter
import Autolib.ToDoc
import Autolib.Reader
import qualified Data.Map as M
import qualified Data.Set as S
import Control.Monad ( forM, void )
import Data.Typeable
data Property = Default
| Max_Num_Places Int
| Max_Num_Transitions Int
| Max_Edge_Multiplicity Int
| Max_Initial_Tokens Int
| Capacity ( Capacity () )
deriving ( Typeable )
$(derives [makeReader, makeToDoc] [''Property])
validates props n = void $ forM props $ \ prop -> validate prop n
validate :: ( Ord s, Ord t, ToDoc s, ToDoc t )
=> Property
-> Net s t
-> Reporter ()
validate p n = case p of
Max_Num_Places m -> guard_bound ( text "Anzahl der Stellen" )
( S.size $ places n ) m
Max_Num_Transitions m -> guard_bound
( text "Anzahl der Transitionen" ) ( S.size $ transitions n ) m
Max_Initial_Tokens m -> guard_bound
( text "Anzahl der Token in Startzustand" )
( sum $ M.elems $ unState $ start n ) m
Max_Edge_Multiplicity m -> void $
forM ( connections n ) $ \ c @ (vor, t, nach) -> do
let bad_vor = M.filter ( > m )
$ M.fromListWith (+) $ zip vor $ repeat 1
bad_nach = M.filter ( > m )
$ M.fromListWith (+) $ zip nach $ repeat 1
when ( not $ M.null bad_vor ) $ reject $ vcat
[ text "Verbindung:" <+> toDoc c
, text "Vielfachheit der Eingangskanten zu hoch:"
</> toDoc bad_vor
]
when ( not $ M.null bad_nach ) $ reject $ vcat
[ text "Verbindung:" <+> toDoc c
, text "Vielfachheit der Ausgangskanten zu hoch:"
</> toDoc bad_nach
]
Capacity cap -> case cap of
Unbounded -> when ( capacity n /= Unbounded) $ reject
$ text "Als Kapazität ist vorgeschrieben:" <+> toDoc cap
All_Bounded b -> when ( capacity n /= All_Bounded b) $ reject
$ text "Als Kapazität ist vorgeschrieben:" <+> toDoc cap
Default -> do
when ( not $ all_non_negative $ start n ) $ reject
$ text "Startzustand enthält negative Markierungen"
when ( not $ conforms ( capacity n ) ( start n ) ) $ reject
$ text "Startzustand überschreitet Kapazitäten"
forM ( connections n ) $ \ c @ ( vor, t, nach ) -> do
when ( not $ S.member t $ transitions n ) $ reject $ vcat
[ text "Verbindung:" <+> toDoc c
, text "nicht deklarierte Transition:" <+> toDoc t
]
forM vor $ \ v -> do
when ( not $ S.member v $ places n ) $ reject $ vcat
[ text "Verbindung:" <+> toDoc c
, text "nicht deklarierte Stelle im Vorbereich:" <+> toDoc v
]
forM nach $ \ a -> do
when ( not $ S.member a $ places n ) $ reject $ vcat
[ text "Verbindung:" <+> toDoc c
, text "nicht deklarierte Stelle im Nachbereich:" <+> toDoc a
]
case capacity n of
Bounded f -> do
let out = S.difference ( M.keysSet f ) ( places n )
when ( not $ S.null out ) $ reject $ vcat
[ text "nicht definierte Stellen in Kapazitätsfunktion:"
, toDoc out
]
_ -> return ()
let out = S.difference ( M.keysSet $ unState $ start n ) ( places n )
when ( not $ S.null out ) $ reject $ vcat
[ text "nicht definierte Stellen im Startzustand:"
, toDoc out
]
guard_bound name actual bound =
when ( actual > bound) $ reject $ vcat
[ name <+> parens ( toDoc actual )
, text "ist größer als die Schranke" <+> parens ( toDoc bound )
]
|
Erdwolf/autotool-bonn
|
src/Petri/Property.hs
|
gpl-2.0
| 4,239 | 2 | 25 | 1,621 | 1,243 | 604 | 639 | 84 | 8 |
-- Copyright (c) 2011-16, Nicola Bonelli
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of University of Pisa nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
--
--
{-# LANGUAGE ImpredicativeTypes #-}
module Network.PFQ.Lang.Experimental
(
-- * Experimental Functions
-- | This set of experimental functions may be subject to changes in future releases
dummy_int
, dummy_ints
, dummy_ip
, dummy_ips
, dummy_string
, dummy_strings
, dummy_cidr
, dummy_cidrs
, steer_gtp_usr
, steer_key
, gtp
, gtp_cp
, gtp_up
, is_gtp
, is_gtp_cp
, is_gtp_up
, shift
, src
, dst
, trace
, kernel_if
, detour_if
, is_broadcast
, is_multicast
, is_ip_broadcast
, is_ip_multicast
, is_ip_host
, is_incoming_host
, mac_broadcast
, mac_multicast
, incoming_host
, ip_broadcast
, ip_multicast
, ip_host
, is_eth_pup
, is_eth_sprite
, is_eth_ip
, is_eth_arp
, is_eth_revarp
, is_eth_at
, is_eth_aarp
, is_eth_vlan
, is_eth_ipx
, is_eth_ipv6
, is_eth_loopback
) where
import Network.PFQ
import Network.PFQ.Lang
import Data.Word
-- Experimental/Testing in-kernel computations
dummy_int :: Int -> NetFunction
dummy_int n = Function "dummy_int" n () () () () () () ()
dummy_ints :: [Int] -> NetFunction
dummy_ints xs = Function "dummy_ints" xs () () () () () () ()
dummy_ip :: IPv4 -> NetFunction
dummy_ip x = Function "dummy_ip" x () () () () () () ()
dummy_ips :: [IPv4] -> NetFunction
dummy_ips xs = Function "dummy_ips" xs () () () () () () ()
dummy_string :: String -> NetFunction
dummy_string xs = Function "dummy_string" xs () () () () () () ()
dummy_strings :: [String] -> NetFunction
dummy_strings xs = Function "dummy_strings" xs () () () () () () ()
dummy_cidr :: CIDR -> NetFunction
dummy_cidr x = Function "dummy_cidr" x () () () () () () ()
dummy_cidrs :: [CIDR] -> NetFunction
dummy_cidrs xs = Function "dummy_cidrs" xs () () () () () () ()
-- | Dispatch the packet across the sockets
-- with a randomized algorithm that guarantees
-- per-user flows consistency on top of GTP tunnel protocol (Control-Plane packets
-- are broadcasted to all sockets).
--
-- > (steer_gtp_usr "192.168.0.0" 16)
steer_gtp_usr :: IPv4 -> Int -> NetFunction
steer_gtp_usr net prefix = Function "steer_gtp_usr" net prefix () () () () () () :: NetFunction
-- | Dispatch the packet to a given socket with id.
--
-- > ip >-> steer_key key_5tuple
steer_key :: FlowKey -> NetFunction
steer_key key = Function "steer_key" (getFlowKey key) () () () () () () () :: NetFunction
-- | Evaluate to /Pass Qbuff/ in case of GTP packet, /Drop/ it otherwise.
gtp = Function "gtp" () () () () () () () () :: NetFunction
-- | Evaluate to /Pass Qbuff/ in case of GTP Control-Plane packet, /Drop/ it otherwise.
gtp_cp = Function "gtp_cp" () () () () () () () () :: NetFunction
-- | Evaluate to /Pass Qbuff/ in case of GTP User-Plane packet, /Drop/ it otherwise.
gtp_up = Function "gtp_up" () () () () () () () () :: NetFunction
-- | Evaluate to /True/ if the Qbuff is a GTP packet.
is_gtp = Predicate "is_gtp" () () () () () () () () :: NetPredicate
-- | Evaluate to /True/ if the Qbuff is a GTP Control-Plane packet.
is_gtp_cp = Predicate "is_gtp_cp" () () () () () () () () :: NetPredicate
-- | Evaluate to /True/ if the Qbuff is a GTP User-Plane packet.
is_gtp_up = Predicate "is_gtp_up" () () () () () () () () :: NetPredicate
-- The function shift an action...
--
-- > shift steer_flow
shift :: NetFunction -> NetFunction
shift f = Function "shift" f () () () () () () ()
-- This function creates a 'source' context...
--
-- > src $ ...
src :: NetFunction -> NetFunction
src f = Function "src" f () () () () () () ()
-- The function creates a 'destination' context...
--
-- > dst $ ...
dst :: NetFunction -> NetFunction
dst f = Function "dst" f () () () () () () ()
-- | Log monadic/state information to syslog.
--
-- > udp >-> log_msg "This is an UDP packet"
--
trace :: NetFunction
trace = Function "trace" () () () () () () () ()
-- | Conditional forwarder to kernel. Evaluate to /Pass Qbuff/.
--
-- > kernel_if is_tcp
kernel_if :: NetPredicate -> NetFunction
kernel_if p = Function "kernel_if" p () () () () () () ()
-- | Conditional forwarder to kernel. Evaluate to /Drop/ if
-- predicate evaluates to True, /Pass/ otherwise.
--
-- > detour_if is_tcp
detour_if :: NetPredicate -> NetFunction
detour_if p = Function "detour_if" p () () () () () () ()
-- | Evaluate to /True/ if the Qbuff is broadcast frame.
is_broadcast = Predicate "is_broadcast" () () () () () () () ()
-- | Evaluate to /True/ if the Qbuff is multicast frame.
is_multicast = Predicate "is_multicast" () () () () () () () ()
-- | Evaluate to /True/ if the Qbuff is broadcast IP packet.
is_ip_broadcast = Predicate "is_ip_broadcast" () () () () () () () ()
-- | Evaluate to /True/ if the Qbuff is multicast IP packet.
is_ip_multicast = Predicate "is_ip_multicast" () () () () () () () ()
-- | Evaluate to /True/ if the Qbuff IP address matches that of the incoming interface,
-- /False/ otherwise.
is_ip_host = Predicate "is_ip_host" () () () () () () () ()
-- | Evaluate to /True/ if the Qbuff IP address matches that of the incoming interface,
-- is a broadcast or a multicast frame.
is_incoming_host = Predicate "is_incoming_host" () () () () () () () ()
-- | Evaluate to /Pass Qbuff/ if it is a broadcast frame, /Drop/ it otherwise.
mac_broadcast = Function "mac_broadcast" () () () () () () () () :: NetFunction
-- | Evaluate to /Pass Qbuff/ if it is a multicast frame, /Drop/ it otherwise.
mac_multicast = Function "mac_multicast" () () () () () () () () :: NetFunction
-- | Evaluate to /Pass Qbuff/ if it is a broadcast IP packet, /Drop/ it otherwise.
ip_broadcast = Function "ip_broadcast" () () () () () () () () :: NetFunction
-- | Evaluate to /Pass Qbuff/ if it is a multicast IP packet, /Drop/ it otherwise.
ip_multicast = Function "ip_multicast" () () () () () () () () :: NetFunction
-- | Evaluate to /Pass Qbuff/ if the IP address matches that of the incoming interface, /Drop/ it otherwise.
ip_host = Function "ip_host" () () () () () () () () :: NetFunction
-- | Evaluate to /Pass Qbuff/ if the IP address matches that of the incoming interface,
-- is a broadcast or a multicast frame, /Drop/ it otherwise.
incoming_host = Function "incoming_host" () () () () () () () () :: NetFunction
-- | Ethernet protocols
is_eth_pup = Predicate "is_l3_proto" (0x0200 :: Word16) () () () () () () ()
is_eth_sprite = Predicate "is_l3_proto" (0x0500 :: Word16) () () () () () () ()
is_eth_ip = Predicate "is_l3_proto" (0x0800 :: Word16) () () () () () () ()
is_eth_arp = Predicate "is_l3_proto" (0x0806 :: Word16) () () () () () () ()
is_eth_revarp = Predicate "is_l3_proto" (0x8035 :: Word16) () () () () () () ()
is_eth_at = Predicate "is_l3_proto" (0x809B :: Word16) () () () () () () ()
is_eth_aarp = Predicate "is_l3_proto" (0x80F3 :: Word16) () () () () () () ()
is_eth_vlan = Predicate "is_l3_proto" (0x8100 :: Word16) () () () () () () ()
is_eth_ipx = Predicate "is_l3_proto" (0x8137 :: Word16) () () () () () () ()
is_eth_ipv6 = Predicate "is_l3_proto" (0x86dd :: Word16) () () () () () () ()
is_eth_loopback = Predicate "is_l3_proto" (0x9000 :: Word16) () () () () () () ()
|
pfq/PFQ
|
user/lib/Haskell/Network/PFQ/Lang/Experimental.hs
|
gpl-2.0
| 8,924 | 0 | 7 | 1,920 | 2,307 | 1,242 | 1,065 | 112 | 1 |
import Text.Pandoc2
import Criterion.Main
import Data.List (isSuffixOf)
import Text.JSON.Generic
import Data.Text.Encoding (decodeUtf8)
import Data.ByteString as B
main = do
inp <- B.readFile "README.markdown"
let poptions' = poptions
let convert :: B.ByteString -> Maybe Blocks
convert = markdownDoc poptions' . decodeUtf8
defaultMain [ bench ("markdown reader") $ whnf convert inp ]
|
jgm/pandoc2
|
Benchmark.hs
|
gpl-2.0
| 401 | 1 | 11 | 66 | 128 | 65 | 63 | 12 | 1 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-}
-- | Manage, read, write lambda-associated param lists
module Lamdu.Sugar.Convert.ParamList
( ParamList, loadForLambdas
) where
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.Trans.State (mapStateT)
import qualified Control.Monad.Trans.State as State
import qualified Data.Store.Property as Property
import Data.Store.Transaction (Transaction)
import qualified Data.Store.Transaction as Transaction
import Lamdu.Calc.Type (Type)
import qualified Lamdu.Calc.Type as T
import qualified Lamdu.Calc.Val as V
import Lamdu.Calc.Val.Annotated (Val(..))
import Lamdu.Data.Anchors (ParamList, assocFieldParamList)
import qualified Lamdu.Expr.IRef as ExprIRef
import qualified Lamdu.Expr.IRef.Infer as IRefInfer
import qualified Lamdu.Expr.Lens as ExprLens
import Lamdu.Infer (Infer)
import qualified Lamdu.Infer as Infer
import Lamdu.Infer.Unify (unify)
import Lamdu.Infer.Update (update)
import qualified Lamdu.Infer.Update as Update
import qualified Lamdu.Sugar.Convert.Input as Input
import Prelude.Compat
type T = Transaction
loadStored :: Monad m => ExprIRef.ValIProperty m -> T m (Maybe ParamList)
loadStored = Transaction.getP . assocFieldParamList . Property.value
mkFuncType :: Infer.Scope -> ParamList -> Infer Type
mkFuncType scope paramList =
T.TFun
<$> (T.TRecord <$> foldr step (pure T.CEmpty) paramList)
<*> Infer.freshInferredVar scope "l"
where
step tag rest = T.CExtend tag <$> Infer.freshInferredVar scope "t" <*> rest
loadForLambdas ::
Monad m => Val (Input.Payload m a) -> IRefInfer.M m (Val (Input.Payload m a))
loadForLambdas val =
do
Lens.itraverseOf_ ExprLens.subExprPayloads loadLambdaParamList val
val
& traverse . Input.inferredType %%~ update
>>= traverse . Input.inferredScope %%~ update
& Update.run & State.gets
where
loadLambdaParamList (Val _ V.BLam {}) pl = loadUnifyParamList pl
loadLambdaParamList _ _ = return ()
loadUnifyParamList pl =
do
mParamList <- loadStored (pl ^. Input.stored) & lift & lift
case mParamList of
Nothing -> return ()
Just paramList ->
do
funcType <-
mkFuncType (pl ^. Input.inferredScope) paramList
unify (pl ^. Input.inferredType) funcType
& Infer.run
& mapStateT IRefInfer.toEitherT
|
da-x/lamdu
|
Lamdu/Sugar/Convert/ParamList.hs
|
gpl-3.0
| 2,764 | 0 | 20 | 753 | 682 | 386 | 296 | -1 | -1 |
module SolvePCP where
--
-- SolvePCP -- Solve a given instance of PCP
--
import Control.Arrow
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe)
import Data.Tree
import System.Environment (getArgs, getProgName)
-- define PCP instances
type WordPair = (String, String)
type PCPInstance = [WordPair]
instanceOne :: PCPInstance
instanceOne = [("a", "aaa"),
("abaaa", "ab"),
("ab", "b")]
instanceTwo :: PCPInstance
instanceTwo = [("bba", "b"),
("ba", "baa"),
("ba", "aba"),
("ab", "bba")]
-- size of instance
sizeOfInstance :: PCPInstance -> Int
sizeOfInstance = length
-- nth element of instance
nthOfInstance :: PCPInstance -> Int -> WordPair
nthOfInstance p i = p !! (i - 1)
-- reverse instance
-- revInstance :: PCPInstance -> PCPInstance
-- revInstance = map $ join (***) reverse
-- revInstance = map $ \ (x, y) -> (reverse x, reverse y)
-- get word pair from list of indeces
getWords :: PCPInstance -> [Int] -> WordPair
getWords p = (concatMap fst &&& concatMap snd) . map (nthOfInstance p)
data PruneValue = Solution
| ExtensionPossible
| NoExtensionPossible
check :: PCPInstance -> [Int] -> PruneValue
check _ [] = ExtensionPossible
check p xs
| u == v = Solution
| u `isPrefixOf` v || v `isPrefixOf` u = ExtensionPossible
| otherwise = NoExtensionPossible
where
(u, v) = getWords p xs
createSearchTree :: Int -> Tree [Int]
createSearchTree br = unfoldTree (\ xs -> (xs, [xs ++ [i] | i <- [1..br]])) []
pruneSearchTree :: ([Int] -> PruneValue) -> Tree [Int] -> Tree ([Int], Bool)
pruneSearchTree f (Node xs ts) =
case f xs of
Solution -> Node (xs, True) $ map (pruneSearchTree f) ts
ExtensionPossible -> Node (xs, False) $ map (pruneSearchTree f) ts
NoExtensionPossible -> Node (xs, False) []
search :: Tree ([Int], Bool) -> Maybe [Int]
search = go . flatten
where
go :: [([Int], Bool)] -> Maybe [Int]
go [] = Nothing
go ((xs, True) : _) = Just xs
go (_ : ys) = go ys
limitTree :: Int -> Tree ([Int], Bool) -> Tree ([Int], Bool)
limitTree 0 (Node l _) = Node l []
limitTree n (Node l ts) = Node l $ map (limitTree (n-1)) ts
searchMaxLevel :: Int -> Tree ([Int], Bool) -> [Int]
searchMaxLevel i t = fromMaybe (searchMaxLevel (i + 1) t) (search $ limitTree i t)
searchLevels :: Tree ([Int], Bool) -> [Int]
searchLevels = go . concat . levels
where
go :: [([Int], Bool)] -> [Int]
go ((xs, True) : _) = xs
go (_ : ys) = go ys
startSearch :: PCPInstance -> [Int]
-- startSearch p = searchMaxLevel 1 $ pruneSearchTree (check p) $ createSearchTree $ sizeOfInstance p
startSearch p = searchLevels $ pruneSearchTree (check p) $ createSearchTree $ sizeOfInstance p
showSolution :: [Int] -> IO ()
showSolution xs = mapM_ putStrLn
[ "Solution: " ++ show xs ++ "."
, "Length of solution: " ++ show (length xs) ++ "."
]
main :: IO ()
main = do args <- getArgs
case args of
["1"] -> showSolution $ startSearch instanceOne
["2"] -> showSolution $ startSearch instanceTwo
_ -> printHelp
printHelp :: IO ()
printHelp = getProgName >>= \ progName -> mapM_ putStrLn
[ progName ++ " <CMD>"
, " where <CMD> is one of"
, " 1: Solve PCP instance P_1 := " ++ show instanceOne ++ "."
, " 2: Solve PCP instance P_2 := " ++ show instanceTwo ++ "."
]
{-
Written by Marcel Lippmann <[email protected]>.
Copyright (c) 2015 by Marcel Lippmann. All rights reserved.
-}
|
mzq42/PCPPlayground
|
Haskell/SolvePCP.hs
|
gpl-3.0
| 3,676 | 0 | 12 | 984 | 1,224 | 668 | 556 | 75 | 3 |
import Data.Char
l1 = [1, 1, 2, 3, 5]
mul x n = x * n
pow x n = x ^ n
doubleList = map (*2) l1
doubleList' = map (\x -> x * 2) l1
doubleList'' = map (mul 2) l1
doubleList''' = map (\x -> mul 2 x) l1
squareList = map (^2) l1
squareList' = map (\x -> x * x) l1
squareList'' = map (\x -> pow x 2) l1
powerOfTwo = map (2^) l1
powerOfTwo' = map (\x -> 2 ^ x) l1
powerOfTwo'' = map (pow 2) l1
powerOfTwo''' = map (\x -> pow 2 x) l1
upperString [] = []
upperString (s:ss) = toUpper s : upperString ss
upperString' ss = map toUpper ss
upperString'' ss = map toUpper
|
graninas/Haskell-Algorithms
|
Tests/Lessons/ListMap.hs
|
gpl-3.0
| 673 | 6 | 8 | 241 | 339 | 171 | 168 | 19 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Jumpie.TileIncrement where
import ClassyPrelude hiding(Real)
import Jumpie.Types
import Jumpie.GameConfig
newtype TileIncrement = TileIncrement { tileIncrementRelative :: Int } deriving(Num)
tileIncrementAbsReal :: TileIncrement -> Real
tileIncrementAbsReal = fromIntegral . (*gcTileSize) . tileIncrementRelative
|
pmiddend/jumpie
|
lib/Jumpie/TileIncrement.hs
|
gpl-3.0
| 367 | 0 | 7 | 39 | 72 | 45 | 27 | 8 | 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.PlayLists.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of resources, possibly filtered.
--
-- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.playlists.list@.
module Network.Google.Resource.YouTube.PlayLists.List
(
-- * REST Resource
PlayListsListResource
-- * Creating a Request
, playListsList
, PlayListsList
-- * Request Lenses
, pllXgafv
, pllPart
, pllMine
, pllUploadProtocol
, pllAccessToken
, pllUploadType
, pllChannelId
, pllHl
, pllOnBehalfOfContentOwner
, pllOnBehalfOfContentOwnerChannel
, pllId
, pllPageToken
, pllMaxResults
, pllCallback
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.playlists.list@ method which the
-- 'PlayListsList' request conforms to.
type PlayListsListResource =
"youtube" :>
"v3" :>
"playlists" :>
QueryParams "part" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "mine" Bool :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "channelId" Text :>
QueryParam "hl" Text :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "onBehalfOfContentOwnerChannel" Text :>
QueryParams "id" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] PlayListListResponse
-- | Retrieves a list of resources, possibly filtered.
--
-- /See:/ 'playListsList' smart constructor.
data PlayListsList =
PlayListsList'
{ _pllXgafv :: !(Maybe Xgafv)
, _pllPart :: ![Text]
, _pllMine :: !(Maybe Bool)
, _pllUploadProtocol :: !(Maybe Text)
, _pllAccessToken :: !(Maybe Text)
, _pllUploadType :: !(Maybe Text)
, _pllChannelId :: !(Maybe Text)
, _pllHl :: !(Maybe Text)
, _pllOnBehalfOfContentOwner :: !(Maybe Text)
, _pllOnBehalfOfContentOwnerChannel :: !(Maybe Text)
, _pllId :: !(Maybe [Text])
, _pllPageToken :: !(Maybe Text)
, _pllMaxResults :: !(Textual Word32)
, _pllCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pllXgafv'
--
-- * 'pllPart'
--
-- * 'pllMine'
--
-- * 'pllUploadProtocol'
--
-- * 'pllAccessToken'
--
-- * 'pllUploadType'
--
-- * 'pllChannelId'
--
-- * 'pllHl'
--
-- * 'pllOnBehalfOfContentOwner'
--
-- * 'pllOnBehalfOfContentOwnerChannel'
--
-- * 'pllId'
--
-- * 'pllPageToken'
--
-- * 'pllMaxResults'
--
-- * 'pllCallback'
playListsList
:: [Text] -- ^ 'pllPart'
-> PlayListsList
playListsList pPllPart_ =
PlayListsList'
{ _pllXgafv = Nothing
, _pllPart = _Coerce # pPllPart_
, _pllMine = Nothing
, _pllUploadProtocol = Nothing
, _pllAccessToken = Nothing
, _pllUploadType = Nothing
, _pllChannelId = Nothing
, _pllHl = Nothing
, _pllOnBehalfOfContentOwner = Nothing
, _pllOnBehalfOfContentOwnerChannel = Nothing
, _pllId = Nothing
, _pllPageToken = Nothing
, _pllMaxResults = 5
, _pllCallback = Nothing
}
-- | V1 error format.
pllXgafv :: Lens' PlayListsList (Maybe Xgafv)
pllXgafv = lens _pllXgafv (\ s a -> s{_pllXgafv = a})
-- | The *part* parameter specifies a comma-separated list of one or more
-- playlist resource properties that the API response will include. If the
-- parameter identifies a property that contains child properties, the
-- child properties will be included in the response. For example, in a
-- playlist resource, the snippet property contains properties like author,
-- title, description, tags, and timeCreated. As such, if you set
-- *part=snippet*, the API response will contain all of those properties.
pllPart :: Lens' PlayListsList [Text]
pllPart
= lens _pllPart (\ s a -> s{_pllPart = a}) . _Coerce
-- | Return the playlists owned by the authenticated user.
pllMine :: Lens' PlayListsList (Maybe Bool)
pllMine = lens _pllMine (\ s a -> s{_pllMine = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pllUploadProtocol :: Lens' PlayListsList (Maybe Text)
pllUploadProtocol
= lens _pllUploadProtocol
(\ s a -> s{_pllUploadProtocol = a})
-- | OAuth access token.
pllAccessToken :: Lens' PlayListsList (Maybe Text)
pllAccessToken
= lens _pllAccessToken
(\ s a -> s{_pllAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pllUploadType :: Lens' PlayListsList (Maybe Text)
pllUploadType
= lens _pllUploadType
(\ s a -> s{_pllUploadType = a})
-- | Return the playlists owned by the specified channel ID.
pllChannelId :: Lens' PlayListsList (Maybe Text)
pllChannelId
= lens _pllChannelId (\ s a -> s{_pllChannelId = a})
-- | Returen content in specified language
pllHl :: Lens' PlayListsList (Maybe Text)
pllHl = lens _pllHl (\ s a -> s{_pllHl = a})
-- | *Note:* This parameter is intended exclusively for YouTube content
-- partners. The *onBehalfOfContentOwner* parameter indicates that the
-- request\'s authorization credentials identify a YouTube CMS user who is
-- acting on behalf of the content owner specified in the parameter value.
-- This parameter is intended for YouTube content partners that own and
-- manage many different YouTube channels. It allows content owners to
-- authenticate once and get access to all their video and channel data,
-- without having to provide authentication credentials for each individual
-- channel. The CMS account that the user authenticates with must be linked
-- to the specified YouTube content owner.
pllOnBehalfOfContentOwner :: Lens' PlayListsList (Maybe Text)
pllOnBehalfOfContentOwner
= lens _pllOnBehalfOfContentOwner
(\ s a -> s{_pllOnBehalfOfContentOwner = a})
-- | This parameter can only be used in a properly authorized request.
-- *Note:* This parameter is intended exclusively for YouTube content
-- partners. The *onBehalfOfContentOwnerChannel* parameter specifies the
-- YouTube channel ID of the channel to which a video is being added. This
-- parameter is required when a request specifies a value for the
-- onBehalfOfContentOwner parameter, and it can only be used in conjunction
-- with that parameter. In addition, the request must be authorized using a
-- CMS account that is linked to the content owner that the
-- onBehalfOfContentOwner parameter specifies. Finally, the channel that
-- the onBehalfOfContentOwnerChannel parameter value specifies must be
-- linked to the content owner that the onBehalfOfContentOwner parameter
-- specifies. This parameter is intended for YouTube content partners that
-- own and manage many different YouTube channels. It allows content owners
-- to authenticate once and perform actions on behalf of the channel
-- specified in the parameter value, without having to provide
-- authentication credentials for each separate channel.
pllOnBehalfOfContentOwnerChannel :: Lens' PlayListsList (Maybe Text)
pllOnBehalfOfContentOwnerChannel
= lens _pllOnBehalfOfContentOwnerChannel
(\ s a -> s{_pllOnBehalfOfContentOwnerChannel = a})
-- | Return the playlists with the given IDs for Stubby or Apiary.
pllId :: Lens' PlayListsList [Text]
pllId
= lens _pllId (\ s a -> s{_pllId = a}) . _Default .
_Coerce
-- | The *pageToken* parameter identifies a specific page in the result set
-- that should be returned. In an API response, the nextPageToken and
-- prevPageToken properties identify other pages that could be retrieved.
pllPageToken :: Lens' PlayListsList (Maybe Text)
pllPageToken
= lens _pllPageToken (\ s a -> s{_pllPageToken = a})
-- | The *maxResults* parameter specifies the maximum number of items that
-- should be returned in the result set.
pllMaxResults :: Lens' PlayListsList Word32
pllMaxResults
= lens _pllMaxResults
(\ s a -> s{_pllMaxResults = a})
. _Coerce
-- | JSONP
pllCallback :: Lens' PlayListsList (Maybe Text)
pllCallback
= lens _pllCallback (\ s a -> s{_pllCallback = a})
instance GoogleRequest PlayListsList where
type Rs PlayListsList = PlayListListResponse
type Scopes PlayListsList =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl",
"https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/youtubepartner"]
requestClient PlayListsList'{..}
= go _pllPart _pllXgafv _pllMine _pllUploadProtocol
_pllAccessToken
_pllUploadType
_pllChannelId
_pllHl
_pllOnBehalfOfContentOwner
_pllOnBehalfOfContentOwnerChannel
(_pllId ^. _Default)
_pllPageToken
(Just _pllMaxResults)
_pllCallback
(Just AltJSON)
youTubeService
where go
= buildClient (Proxy :: Proxy PlayListsListResource)
mempty
|
brendanhay/gogol
|
gogol-youtube/gen/Network/Google/Resource/YouTube/PlayLists/List.hs
|
mpl-2.0
| 10,275 | 0 | 25 | 2,400 | 1,426 | 832 | 594 | 188 | 1 |
module Rendering ( fromToFieldPos
, draw
, DrawSettings(..)
) where
import Data.Default
import Data.Maybe
import Control.Monad
import Data.Colour.RGBSpace as Colour
import qualified GI.Cairo.Render as Cairo
import Player
import Field
data DrawSettings = DrawSettings { dsHReflection :: Bool
, dsVReflection :: Bool
, dsGridThickness :: Int
, dsGridColor :: RGB Double
, dsBackgroundColor :: RGB Double
, dsRedColor :: RGB Double
, dsBlackColor :: RGB Double
, dsPointRadius :: Double
, dsFillingAlpha :: Double
, dsFullFill :: Bool
}
instance Default DrawSettings where
def = DrawSettings { dsHReflection = False
, dsVReflection = False
, dsGridThickness = 1
, dsGridColor = RGB 0.3 0.3 0.3
, dsBackgroundColor = RGB 1 1 1
, dsRedColor = RGB 1 0 0
, dsBlackColor = RGB 0 0 0
, dsPointRadius = 1
, dsFillingAlpha = 0.5
, dsFullFill = True
}
fromPosXY :: Bool -> Double -> Int -> Int -> Double
fromPosXY reflection areaSize fieldSize x =
let cellSize = areaSize / fromIntegral fieldSize
x' = (fromIntegral x + 0.5) * cellSize
in if reflection
then areaSize - x'
else x'
toPosXY :: Bool -> Double -> Int -> Double -> Int
toPosXY reflection areaSize fieldSize x =
let cellSize = areaSize / fromIntegral fieldSize
x' = floor $ x / cellSize
in if reflection
then fieldSize - x' - 1
else x'
shift :: Double -> Double -> Double
shift size balancedSize = (size - balancedSize) / 2
dimensions :: Int -> Int -> Double -> Double -> (Double, Double, Double, Double)
dimensions fieldWidth' fieldHeight' width height =
let fieldHeight'' = fromIntegral fieldHeight'
fieldWidth'' = fromIntegral fieldWidth'
width' = min width $ height / fieldHeight'' * fieldWidth''
height' = min height $ width / fieldWidth'' * fieldHeight''
shiftX = shift width width'
shiftY = shift height height'
in (width', height', shiftX, shiftY)
fromToFieldPos :: Bool -> Bool -> Int -> Int -> Double -> Double -> (Int -> Double, Int -> Double, Double -> Int, Double -> Int)
fromToFieldPos hReflection vReflection fieldWidth' fieldHeight' width height =
let (width', height', shiftX, shiftY) = dimensions fieldWidth' fieldHeight' width height
in ( (shiftX +) . fromPosXY hReflection width' fieldWidth' -- fromGamePosX
, (shiftY +) . fromPosXY (not vReflection) height' fieldHeight' -- fromGamePosY
, \coordX -> toPosXY hReflection width' fieldWidth' (coordX - shiftX) -- toGamePosX
, \coordY -> toPosXY (not vReflection) height' fieldHeight' (coordY - shiftY) -- toGamePosY
)
setSourceRGBA :: RGB Double -> Double -> Cairo.Render ()
setSourceRGBA rgb = Cairo.setSourceRGBA (channelRed rgb) (channelGreen rgb) (channelBlue rgb)
setSourceRGB :: RGB Double -> Cairo.Render ()
setSourceRGB rgb = Cairo.setSourceRGB (channelRed rgb) (channelGreen rgb) (channelBlue rgb)
polygon :: [(Double, Double)] -> Cairo.Render ()
polygon list =
do uncurry Cairo.moveTo $ head list
mapM_ (uncurry Cairo.lineTo) $ tail list
Cairo.fill
draw :: DrawSettings -> Double -> Double -> [Field] -> Cairo.Render ()
draw DrawSettings { dsHReflection = hReflection
, dsVReflection = vReflection
, dsGridThickness = gridThickness
, dsGridColor = gridColor
, dsBackgroundColor = backgroundColor
, dsRedColor = redColor
, dsBlackColor = blackColor
, dsPointRadius = pointRadius
, dsFillingAlpha = fillingAlpha
, dsFullFill = fullFill
} width height fields =
do let headField = head fields
fieldWidth' = fieldWidth headField
fieldHeight' = fieldHeight headField
(width', height', shiftX, shiftY) = dimensions fieldWidth' fieldHeight' width height
scale = width' / fromIntegral fieldWidth'
(fromPosX, fromPosY, _, _) = fromToFieldPos hReflection vReflection fieldWidth' fieldHeight' width height
fromPos (x, y) = (fromPosX x, fromPosY y)
verticalLines = [fromPosX i | i <- [0 .. (fieldWidth headField - 1)]]
horizontalLines = [fromPosY i | i <- [0 .. (fieldHeight headField - 1)]]
--Rendering background.
Cairo.setAntialias Cairo.AntialiasNone
setSourceRGB backgroundColor
Cairo.rectangle shiftX shiftY width' height'
Cairo.fill
--Rendering grig.
Cairo.setLineWidth $ fromIntegral gridThickness
setSourceRGB gridColor
mapM_ (\x -> do Cairo.moveTo x shiftY
Cairo.lineTo x (shiftY + height')
Cairo.stroke) verticalLines
mapM_ (\y -> do Cairo.moveTo shiftX y
Cairo.lineTo (shiftX + width') y
Cairo.stroke) horizontalLines
--Rendering points.
Cairo.setAntialias Cairo.AntialiasBest
mapM_ (\((x, y), player) ->
do setSourceRGB $ if player == Red then redColor else blackColor
Cairo.arc (fromPosX x) (fromPosY y) (pointRadius * scale / 5) 0 (2 * pi)
Cairo.fill) $ moves headField
--Rendering last point.
unless (null $ moves headField) $ (\((x, y), player) ->
do Cairo.setLineWidth 2
setSourceRGB $ if player == Red then redColor else blackColor
Cairo.arc (fromPosX x) (fromPosY y) (pointRadius * scale / 3) 0 (2 * pi)
Cairo.stroke) $ head $ moves headField
--Rendering little surrounds.
Cairo.setAntialias Cairo.AntialiasNone
when fullFill $ mapM_ (\(field, (pos, player)) ->
do if player == Red then setSourceRGBA redColor fillingAlpha else setSourceRGBA blackColor fillingAlpha
if isPlayer field (s pos) player && isPlayer field (e pos) player
then polygon [fromPos pos, fromPos $ s pos, fromPos $ e pos]
else do when (isPlayer field (s pos) player && isPlayer field (se pos) player) $
polygon [fromPos pos, fromPos $ s pos, fromPos $ se pos]
when (isPlayer field (e pos) player && isPlayer field (se pos) player) $
polygon [fromPos pos, fromPos $ e pos, fromPos $ se pos]
if isPlayer field (e pos) player && isPlayer field (n pos) player
then polygon [fromPos pos, fromPos $ e pos, fromPos $ n pos]
else do when (isPlayer field (e pos) player && isPlayer field (ne pos) player) $
polygon [fromPos pos, fromPos $ e pos, fromPos $ ne pos]
when (isPlayer field (n pos) player && isPlayer field (ne pos) player) $
polygon [fromPos pos, fromPos $ n pos, fromPos $ ne pos]
if isPlayer field (n pos) player && isPlayer field (w pos) player
then polygon [fromPos pos, fromPos $ n pos, fromPos $ w pos]
else do when (isPlayer field (n pos) player && isPlayer field (nw pos) player) $
polygon [fromPos pos, fromPos $ n pos, fromPos $ nw pos]
when (isPlayer field (w pos) player && isPlayer field (nw pos) player) $
polygon [fromPos pos, fromPos $ w pos, fromPos $ nw pos]
if isPlayer field (w pos) player && isPlayer field (s pos) player
then polygon [fromPos pos, fromPos $ w pos, fromPos $ s pos]
else do when (isPlayer field (w pos) player && isPlayer field (sw pos) player) $
polygon [fromPos pos, fromPos $ w pos, fromPos $ sw pos]
when (isPlayer field (s pos) player && isPlayer field (sw pos) player) $
polygon [fromPos pos, fromPos $ s pos, fromPos $ sw pos]) $ zip (reverse fields) (map (head . moves) $ tail $ reverse fields)
--Rendering surrounds.
mapM_ (\(chain, player) ->
do if player == Red then setSourceRGBA redColor fillingAlpha else setSourceRGBA blackColor fillingAlpha
polygon $ map fromPos chain) $ mapMaybe lastSurroundChain $ reverse fields
|
kurnevsky/missile
|
src/Rendering.hs
|
agpl-3.0
| 8,511 | 0 | 23 | 2,719 | 2,709 | 1,382 | 1,327 | 145 | 9 |
module Paths_bitrest where
getDataFileName :: FilePath -> IO FilePath
getDataFileName = return
|
bitraten/bitrest
|
src/Paths_bitrest.hs
|
agpl-3.0
| 96 | 0 | 6 | 13 | 21 | 12 | 9 | 3 | 1 |
module Fibonacci where
import Data.List
import Data.Bits
fibonacci :: Int -> Integer
fibonacci n = snd . foldl' fib' (1, 0) . dropWhile not $
[testBit n k | k <- let s = finiteBitSize n in [s - 1, s - 2 .. 0]]
where fib' (f, g) p
|p = (f * (f + 2 * g), ss)
|otherwise = (ss, g * (2 * f - g))
where ss = f * f + g * g
--
fib :: Integer -> Integer
fib n
|n >= 0 = fibonacci $ fromInteger n
|mod n 2 == 1 = fibonacci $ (0 - fromInteger n)
|otherwise = 0 - fibonacci (0 - fromInteger n)
--
|
ice1000/OI-codes
|
codewars/1-100/the-millionth-fibonacci-kata.hs
|
agpl-3.0
| 547 | 0 | 13 | 179 | 292 | 150 | 142 | 15 | 1 |
{-# LANGUAGE ExistentialQuantification,
TypeFamilies,
GADTs,
RankNTypes,
ScopedTypeVariables,
DeriveDataTypeable,
StandaloneDeriving,
MultiParamTypeClasses,
FlexibleInstances #-}
{-# LANGUAGE DeriveFunctor #-}
{- # LANGUAGE FlexibleContexts # -}
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.Async
import Control.Concurrent.Chan
import Control.Monad.Trans.Class
import Control.Monad.Trans.Free
import Data.List
import Data.Typeable
import qualified Data.Map as Map
import qualified Data.Sequence as S -- Queue with O(1) head and tail operations
main = putStrLn "hello"
data Id = Id String
deriving (Eq,Show,Ord)
friendsOf :: Id -> IO [Id]
friendsOf x = do
return $ Map.findWithDefault [] x friendsMap
friendsMap = Map.fromList
[(Id "a", [Id "b",Id "c"])
,(Id "b", [Id "a",Id "c"])
]
numFof :: Id -> Id -> IO Int
numFof x y = do
fox <- friendsOf x
foy <- friendsOf y
return $ length (intersect fox foy)
concurrentNumFof x y = do
m1 <- newEmptyMVar
m2 <- newEmptyMVar
forkIO (friendsOf x >>= putMVar m1)
forkIO (friendsOf y >>= putMVar m2)
fx <- takeMVar m1
fy <- takeMVar m2
return (length (intersect fx fy))
asyncNumFof x y = do
ax <- async (friendsOf x)
ay <- async (friendsOf y)
fx <- wait ax
fy <- wait ay
return (length (intersect fx fy))
concurrentlyNumFof x y = do
(fx,fy) <- concurrently (friendsOf x) (friendsOf y)
return (length (intersect fx fy))
-- ---------------------------------------------------------------------
newtype Haxl a = Haxl { unHaxl :: IO (Result a) }
deriving (Functor)
data Result a = Done a
| Blocked (Haxl a)
deriving (Functor)
instance Monad Haxl where
return a = Haxl (return (Done a))
-- (>>=) :: Monad m => m a -> (a -> m b) -> m b
-- (>>=) :: Haxl a -> (a -> Haxl b) -> Haxl b
m >>= k = Haxl $ do
a <- unHaxl m
case a of
Done a' -> unHaxl (k a')
Blocked r -> return (Blocked (r >>= k))
-- ---------------------------------------------------------------------
-- We need a recursive data structure to thread through the
-- computation
-- http://www.haskellforall.com/2012/06/you-could-have-invented-free-monads.html
-- This could come about as the interaction of Haxl and Result
-- Result (IO (Result a)) = Blocked (Haxl (IO Result a))
t1 :: Haxl Char
t1 = Haxl (return (Done 'a'))
t2 :: Haxl (Haxl Char)
t2 = Haxl (return (Blocked (return t1)))
t3 :: Haxl (Haxl Char)
t3 = Haxl (return (Blocked (return (Haxl (return (Done 'a'))))))
-- Do we need some way of forking, or does Applicative do that for us?
-- We need to go from hFriendsOf x to some kind of structure.
-- The essence of dataFetch is that we get back something like
t4 :: IO (Result a) -> Haxl a
t4 j = Haxl (return (Blocked (Haxl j)))
-- where j is 'getResult' of the original request.
-- In monadic computation, we have
commonFriends x y = do
xf <- friendsOf x
yf <- friendsOf y
return $ intersect xf yf
-- Desugared
commonFriends' x y =
friendsOf x >>=
(\xf -> friendsOf y >>=
(\yf -> return
(intersect xf yf)
)
)
-- substituting (getResult (FindFriends x)) and (getResult (findFriends y)) as per t4
{-
commonFriends'' x y =
(getResult (FindFriends x)) >>=
(\xf -> (getResult (FindFriends y)) >>=
(\yf -> return
(intersect xf yf)
)
)
-}
-- ---------------------------------------------------------------------
hFriendsOf :: Id -> Haxl [Id]
hFriendsOf x = dataFetch (FindFriends x)
-- ---------------------------------------------------------------------
-- data Request a = R a
data Request a where
FindFriends :: Id -> Request [Id]
deriving (Typeable)
deriving instance Eq (Request a)
deriving instance Ord (Request a)
deriving instance Show (Request a)
-- Is dataFetch like build_trace in EventsThreads?
dataFetch :: Request a -> Haxl a
dataFetch r = do
addRequest r
Haxl (return (Blocked (Haxl (getResult r))))
-- ---------------------------------------------------------------------
-- Introducing the Free Monad (as used in EventsThreads)
data ThreadF a = AddRequest a
| GetResult a
deriving (Functor)
type Thread = FreeT ThreadF
-- or fAddRequest :: MonadFree ThreadF m => a -> m a
fAddRequest :: (Monad m) => a -> Thread m a
fAddRequest r = liftF (AddRequest r)
fGetResult :: (Monad m) => a -> Thread m a
fGetResult r = liftF (GetResult r)
-- State structure. Each request must be cached. Duplicate requests
-- must be coalesced. BUT, need to keep track of the individual
-- blocked calculation points.
--
-- cache : (req,Maybe res,mvar)
--
worker_main c ready_queue = do
trace <- readChan ready_queue
s' <- case trace of
AddRequest req@(FindFriends x) ->
do
case Map.lookup req c of
Nothing -> do
mvar <- newEmptyMVar
forkIO (friendsOf x >>= putMVar mvar)
return $ Map.insert req (Nothing,mvar) c
Just (Just r,_) -> do
-- How to return the result?
return c
Just (Nothing,mvar) -> do
mr <- tryTakeMVar mvar
case mr of
Nothing -> return c
Just r -> return $ Map.insert req (Just r,mvar) c
GetResult req@(FindFriends x) ->
do
return c
-- recurse
worker_main s' ready_queue
run calc = do
rq <- newChan
worker_main Map.empty rq
-- ---------------------------------------------------------------------
-- From EventsThreads
build_trace :: Haxl a -> Result a
-- build_trace (Haxl f) = f (\c -> SYS_RET)
build_trace (Haxl f) = undefined
{-
roundRobin h -> go Map.empty (S.singleton t)
where
go c ts = case (viewl ts) of
-- The queue is empty: we're done!
EmptyL -> return ()
t S.:< ts' -> do
x <- runFreeT t
case x of
Free (Done x) -> go ts'
Free (Blocked x)
-}
-- ---------------------------------------------------------------------
addRequest :: Request a -> Haxl (Request a)
addRequest req@(FindFriends x) = undefined
getResult :: Request a -> IO (Result a)
getResult req = undefined
-- Note: Needs to be generalised to all requests, by implementing a
-- class for Request
doAddRequest ::
Map.Map (Request [Id]) (Maybe a, MVar [Id])
-> Request t
-> IO (Map.Map (Request [Id]) (Maybe a, MVar [Id]))
doAddRequest c req@(FindFriends x) = do
case Map.lookup req c of
Nothing -> do
mvar <- newEmptyMVar
forkIO (friendsOf x >>= putMVar mvar)
return $ Map.insert req (Nothing,mvar) c
Just _ -> return c
doGetResult c req@(FindFriends x) = do
case Map.lookup req c of
Nothing -> do
-- This should never happen....
mvar <- newEmptyMVar
forkIO (friendsOf x >>= putMVar mvar)
return (Map.insert req (Nothing,mvar) c, Nothing)
Just (Just r,_) -> return (c,Just r)
Just (Nothing,mvar) -> do
mr <- tryTakeMVar mvar
case mr of
Nothing -> return (c,Nothing)
Just r -> return (Map.insert req (Just r,mvar) c,Just r)
-- ---------------------------------------------------------------------
-- numCommonFriends :: Id -> Id -> Haxl Int
numCommonFriends1 x y = do
fx <- friendsOf x
fy <- friendsOf y
return (length (intersect fx fy))
-- ---------------------------------------------------------------------
instance Applicative Haxl where
pure = return
Haxl f <*> Haxl a = Haxl $ do
r <- f
case r of
Done f' -> do
ra <- a
case ra of
Done a' -> return (Done (f' a'))
Blocked a' -> return (Blocked (f' <$> a'))
Blocked f' -> do
ra <- a
case ra of
Done a' -> return (Blocked (f' <*> return a'))
Blocked a' -> return (Blocked (f' <*> a'))
-- ---------------------------------------------------------------------
numCommonFriends x y =
length <$> (intersect <$> friendsOf x <*> friendsOf y)
-- ---------------------------------------------------------------------
haxlFriendsOf :: Id -> Haxl [Id]
haxlFriendsOf x = dataFetch (FindFriends x)
haxlCommonFriends :: Id -> Id -> Haxl [Id]
haxlCommonFriends x y =
(intersect <$> haxlFriendsOf x <*> haxlFriendsOf y)
|
alanz/haxl-play
|
src/simple.hs
|
unlicense
| 8,454 | 58 | 24 | 2,180 | 2,367 | 1,186 | 1,181 | 179 | 5 |
{-# LANGUAGE DeriveDataTypeable, FunctionalDependencies, MultiParamTypeClasses,
RecordWildCards #-}
-- |
-- Module: Network.Riak.Types.Internal
-- Copyright: (c) 2011 MailRank, Inc.
-- License: Apache
-- Maintainer: Bryan O'Sullivan <[email protected]>
-- Stability: experimental
-- Portability: portable
--
-- Basic types.
module Network.Riak.Types.Internal
(
-- * Client management
ClientID
, Client(..)
-- * Connection management
, Connection(..)
-- * Errors
, RiakException(excModule, excFunction, excMessage)
, netError
, typeError
, unexError
-- * Data types
, Bucket
, Key
, Tag
, VClock(..)
, Job(..)
-- * Quorum management
, Quorum(..)
, DW
, R
, RW
, W
, fromQuorum
, toQuorum
-- * Message identification
, Request(..)
, Response
, Exchange
, MessageTag(..)
, Tagged(..)
) where
import Control.Exception (Exception, throw)
import Data.ByteString.Lazy (ByteString)
import Data.Digest.Pure.MD5 (md5)
import Data.IORef (IORef)
import Data.Typeable (Typeable)
import Data.Word (Word32)
import Network.Socket (HostName, ServiceName, Socket)
import Text.ProtocolBuffers (ReflectDescriptor, Wire)
-- | A client identifier. This is used by the Riak cluster when
-- logging vector clock changes, and should be unique for each client.
type ClientID = ByteString
data Client = Client {
host :: HostName
-- ^ Name of the server to connect to.
, port :: ServiceName
-- ^ Port number to connect to (default is 8087).
, clientID :: ClientID
-- ^ Client identifier.
} deriving (Eq, Show, Typeable)
-- | A connection to a Riak server.
data Connection = Connection {
connSock :: Socket
, connClient :: Client
-- ^ The configuration we connected with.
, connBuffer :: IORef ByteString
-- ^ Received data that has not yet been consumed.
} deriving (Eq)
-- | The main Riak exception type.
data RiakException = NetException {
excModule :: String
, excFunction :: String
, excMessage :: String
} | TypeException {
excModule :: String
, excFunction :: String
, excMessage :: String
} | UnexpectedResponse {
excModule :: String
, excFunction :: String
, excMessage :: String
}deriving (Eq, Typeable)
showRiakException :: RiakException -> String
showRiakException exc@NetException{..} =
"Riak network error " ++ formatRiakException exc
showRiakException exc@TypeException{..} =
"Riak type error " ++ formatRiakException exc
showRiakException exc@UnexpectedResponse{..} =
"Riak server sent unexpected response " ++ formatRiakException exc
formatRiakException :: RiakException -> String
formatRiakException exc =
"(" ++ excModule exc ++ "." ++ excFunction exc ++ "): " ++ excMessage exc
instance Show RiakException where
show = showRiakException
instance Exception RiakException
netError :: String -> String -> String -> a
netError modu func msg = throw (NetException modu func msg)
typeError :: String -> String -> String -> a
typeError modu func msg = throw (TypeException modu func msg)
unexError :: String -> String -> String -> a
unexError modu func msg = throw (UnexpectedResponse modu func msg)
instance Show Connection where
show conn = show "Connection " ++ host c ++ ":" ++ port c
where c = connClient conn
-- | A Bucket is a container and keyspace for data stored in Riak,
-- with a set of common properties for its contents (the number of
-- replicas, for instance).
type Bucket = ByteString
-- | Keys are unique object identifiers in Riak and are scoped within
-- buckets.
type Key = ByteString
-- | An application-specific identifier for a link. See
-- <http://wiki.basho.com/Links.html> for details.
type Tag = ByteString
-- | A specification of a MapReduce
-- job. <http://wiki.basho.com/MapReduce.html>.
data Job = JSON ByteString
| Erlang ByteString
deriving (Eq, Show, Typeable)
-- | An identifier for an inbound or outbound message.
data MessageTag = ErrorResponse
| PingRequest
| PingResponse
| GetClientIDRequest
| GetClientIDResponse
| SetClientIDRequest
| SetClientIDResponse
| GetServerInfoRequest
| GetServerInfoResponse
| GetRequest
| GetResponse
| PutRequest
| PutResponse
| DeleteRequest
| DeleteResponse
| ListBucketsRequest
| ListBucketsResponse
| ListKeysRequest
| ListKeysResponse
| GetBucketRequest
| GetBucketResponse
| SetBucketRequest
| SetBucketResponse
| MapReduceRequest
| MapReduceResponse
deriving (Eq, Show, Enum, Typeable)
-- | Messages are tagged.
class Tagged msg where
messageTag :: msg -> MessageTag -- ^ Retrieve a message's tag.
instance Tagged MessageTag where
messageTag m = m
{-# INLINE messageTag #-}
-- | A message representing a request from client to server.
class (Tagged msg, ReflectDescriptor msg, Show msg, Wire msg) => Request msg
where expectedResponse :: msg -> MessageTag
-- | A message representing a response from server to client.
class (Tagged msg, ReflectDescriptor msg, Show msg, Wire msg) => Response msg
class (Request req, Response resp) => Exchange req resp
| req -> resp, resp -> req
instance (Tagged a, Tagged b) => Tagged (Either a b) where
messageTag (Left l) = messageTag l
messageTag (Right r) = messageTag r
{-# INLINE messageTag #-}
-- | A wrapper that keeps Riak vector clocks opaque.
newtype VClock = VClock {
fromVClock :: ByteString
-- ^ Unwrap the 'ByteString'. (This is really only useful for
-- printing the raw vclock string.)
} deriving (Eq, Typeable)
instance Show VClock where
show (VClock s) = "VClock " ++ show (md5 s)
-- | A read/write quorum. The quantity of replicas that must respond
-- to a read or write request before it is considered successful. This
-- is defined as a bucket property or as one of the relevant
-- parameters to a single request ('R','W','DW','RW').
data Quorum = Default -- ^ Use the default quorum settings for the bucket.
| One -- ^ Success after one server has responded.
| Quorum -- ^ Success after a quorum of servers has responded.
| All -- ^ Success after all servers have responded.
deriving (Bounded, Eq, Enum, Ord, Show, Typeable)
-- | Read/write quorum. How many replicas need to collaborate when
-- deleting a value.
type RW = Quorum
-- | Read quorum. How many replicas need to agree when retrieving a
-- value.
type R = Quorum
-- | Write quorum. How many replicas to write to before returning a
-- successful response.
type W = Quorum
-- | Durable write quorum. How many replicas to commit to durable
-- storage before returning a successful response.
type DW = Quorum
fromQuorum :: Quorum -> Maybe Word32
fromQuorum Default = Just 4294967291
fromQuorum One = Just 4294967294
fromQuorum Quorum = Just 4294967293
fromQuorum All = Just 4294967292
{-# INLINE fromQuorum #-}
toQuorum :: Word32 -> Maybe Quorum
toQuorum 4294967294 = Just One
toQuorum 4294967293 = Just Quorum
toQuorum 4294967292 = Just All
toQuorum 4294967291 = Just Default
toQuorum v = error $ "invalid quorum value " ++ show v
{-# INLINE toQuorum #-}
|
bumptech/riak-haskell-client
|
src/Network/Riak/Types/Internal.hs
|
apache-2.0
| 7,635 | 0 | 10 | 1,959 | 1,383 | 801 | 582 | -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="hu-HU">
<title>Passive Scan Rules - Alpha | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
0xkasun/security-tools
|
src/org/zaproxy/zap/extension/pscanrulesAlpha/resources/help_hu_HU/helpset_hu_HU.hs
|
apache-2.0
| 988 | 92 | 29 | 163 | 409 | 216 | 193 | -1 | -1 |
module Chapter2.DataModels where
data Client = GovOrg String
| Company String Integer Person String
| Individual Person Bool
deriving (Show)
data Person = Person String String Gender
deriving Show
data Gender = Male | Female | Unknown
deriving Show
data GenderStats = GenderStats (Integer, Integer, Integer)
data TimeMachine = TimeMachine String Integer String TravelDirection Double
deriving Show
data TravelDirection = Past | Future | PastAndFuture
deriving Show
|
zer/BeginningHaskell
|
src/Chapter2/DataModels.hs
|
apache-2.0
| 584 | 0 | 7 | 186 | 126 | 74 | 52 | 14 | 0 |
-- Language extensions {{{
{-# LANGUAGE UnicodeSyntax #-}
-- }}} Language extensions
-- Imports {{{
import Criterion.Main
import Data.Quantum.Small.Operator
import Data.Quantum.Small.Operator.SubsystemCode
import Data.Quantum.Small.Operator.ReducedEschelonForm
-- }}} Imports
main = defaultMain
-- Benchmarks {{{
[bgroup "construction of reduced eschelon form" -- {{{
[bench "4 ops" $ -- {{{
whnf constructReducedEschelonForm
[read "IIZZZIYI"
,read "ZIXXXZZZ"
,read "YYZIIIXX"
,read "YIYIZIIZ"
]
-- }}}
,bench "8 ops" $ -- {{{
whnf constructReducedEschelonForm
[read "IIXIXIXY"
,read "XIYZYXZZ"
,read "ZZYZIZZX"
,read "IXIIYIZY"
,read "ZZZYZZYX"
,read "YYZIXZIX"
,read "ZXYYXIXI"
,read "IIIIIYIX"
,read "YYIZIXXZ"
,read "IIYZZYZY"
,read "ZYXYXZXI"
,read "IZIIZZIY"
]
-- }}}
,bench "16 ops" $ -- {{{
whnf constructReducedEschelonForm
[read "YXIZYZII"
,read "XYZZZXZZ"
,read "XIYXIXZZ"
,read "ZZIZYXYZ"
,read "ZIIZZZXZ"
,read "ZIIXIZIY"
,read "ZXYIYYZZ"
,read "XXZXYXXI"
,read "IYYZIIIX"
,read "XXIYIXZY"
,read "IYYXXXXI"
,read "XZXZXXYX"
,read "XYXXXIYX"
,read "ZIYXIZYI"
,read "IZIIIXZI"
,read "XYXYIZZZ"
]
-- }}}
,bench "32 ops" $ -- {{{
whnf constructReducedEschelonForm
[read "ZYIYYXZY"
,read "IIYYZZXI"
,read "IYYIIYYI"
,read "XYIXXYIX"
,read "ZIZZYZXI"
,read "IIZXXIXI"
,read "IYXYIIZZ"
,read "YZIZXYYZ"
,read "IIYIYYZI"
,read "IXIYYZXI"
,read "YIXXYIXZ"
,read "XIZZIXZZ"
,read "YIYXZXXI"
,read "IXZYIYII"
,read "YYIZYZYZ"
,read "ZZZXIIXZ"
,read "IIZZIZII"
,read "XZYYYYZY"
,read "IXXZIIZY"
,read "IIIZYIXZ"
,read "XYXYXYYI"
,read "IYXYXZYY"
,read "YXXYXXXZ"
,read "ZIYZYXII"
,read "YZZYZZYX"
,read "IZZZYZZX"
,read "IYZYIZYZ"
,read "IYYZYXZI"
,read "YYIXYZIZ"
,read "YYXXZZIX"
,read "YYYIZZZI"
,read "YZYIIIXI"
]
-- }}}
]
-- }}}
,bgroup "construction of subsystem code" -- {{{
[bench "4 ops" $ -- {{{
whnf (constructSubsystemCodeFromMeasurements 8)
[read "IIZZZIYI"
,read "ZIXXXZZZ"
,read "YYZIIIXX"
,read "YIYIZIIZ"
]
-- }}}
,bench "8 ops" $ -- {{{
whnf (constructSubsystemCodeFromMeasurements 8)
[read "YIIIIXZI"
,read "IXIIYYYZ"
,read "ZYXYZIZX"
,read "IYZXXYIZ"
,read "YZZYXXYX"
,read "ZZIXIZIZ"
,read "YXYIXYXI"
,read "YIXIXYZY"
]
-- }}}
,bench "12 ops" $ -- {{{
whnf (constructSubsystemCodeFromMeasurements 8)
[read "IIXIXIXY"
,read "XIYZYXZZ"
,read "ZZYZIZZX"
,read "IXIIYIZY"
,read "ZZZYZZYX"
,read "YYZIXZIX"
,read "ZXYYXIXI"
,read "IIIIIYIX"
,read "YYIZIXXZ"
,read "IIYZZYZY"
,read "ZYXYXZXI"
,read "IZIIZZIY"
]
-- }}}
,bench "16 ops" $ -- {{{
whnf (constructSubsystemCodeFromMeasurements 8)
[read "YXIZYZII"
,read "XYZZZXZZ"
,read "XIYXIXZZ"
,read "ZZIZYXYZ"
,read "ZIIZZZXZ"
,read "ZIIXIZIY"
,read "ZXYIYYZZ"
,read "XXZXYXXI"
,read "IYYZIIIX"
,read "XXIYIXZY"
,read "IYYXXXXI"
,read "XZXZXXYX"
,read "XYXXXIYX"
,read "ZIYXIZYI"
,read "IZIIIXZI"
,read "XYXYIZZZ"
]
-- }}}
,bench "32 ops" $ -- {{{
whnf (constructSubsystemCodeFromMeasurements 8)
[read "ZYIYYXZY"
,read "IIYYZZXI"
,read "IYYIIYYI"
,read "XYIXXYIX"
,read "ZIZZYZXI"
,read "IIZXXIXI"
,read "IYXYIIZZ"
,read "YZIZXYYZ"
,read "IIYIYYZI"
,read "IXIYYZXI"
,read "YIXXYIXZ"
,read "XIZZIXZZ"
,read "YIYXZXXI"
,read "IXZYIYII"
,read "YYIZYZYZ"
,read "ZZZXIIXZ"
,read "IIZZIZII"
,read "XZYYYYZY"
,read "IXXZIIZY"
,read "IIIZYIXZ"
,read "XYXYXYYI"
,read "IYXYXZYY"
,read "YXXYXXXZ"
,read "ZIYZYXII"
,read "YZZYZZYX"
,read "IZZZYZZX"
,read "IYZYIZYZ"
,read "IYYZYXZI"
,read "YYIXYZIZ"
,read "YYXXZZIX"
,read "YYYIZZZI"
,read "YZYIIIXI"
]
-- }}}
]
-- }}}
]
|
gcross/PauliQSC
|
benchmark.hs
|
bsd-2-clause
| 5,473 | 1 | 11 | 2,477 | 1,065 | 546 | 519 | 162 | 1 |
module Mockup.server where
|
klangner/splayer
|
test-src/Mockup/Server.hs
|
bsd-2-clause
| 28 | 1 | 5 | 4 | 10 | 4 | 6 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | An simple, experimental tree generation module.
module NLP.TAG.Vanilla.Gen
( GenConf (..)
, generateAll
, generateRand
) where
import Control.Applicative ((<$>), (<*>))
-- import Control.Monad (void, when, forM_)
-- import Control.Monad (when)
import qualified Control.Monad.State.Strict as E
import Control.Monad.Trans.Maybe (MaybeT (..))
-- import Control.Monad.Trans.Class (lift)
-- import Control.Monad.IO.Class (liftIO)
import Pipes
import qualified Pipes.Prelude as Pipes
import System.Random (randomRIO)
import qualified Data.Foldable as F
import Data.Maybe (maybeToList)
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import qualified Data.PSQueue as Q
import Data.PSQueue (Binding(..))
import qualified Data.Tree as R
import NLP.TAG.Vanilla.Tree.Other
--------------------------
-- Basic types
--------------------------
deriving instance (Ord n, Ord t) => (Ord (Tree n t))
-- | A TAG grammar.
type Gram n t = S.Set (Tree n t)
--------------------------
-- Tree size
--------------------------
-- | Size of a tree, i.e. number of nodes.
treeSize :: Tree n t -> Int
treeSize = length . R.flatten
--------------------------
-- Generation state
--------------------------
-- | Map of visited trees.
type DoneMap n t = M.Map Int (S.Set (Tree n t))
-- | Underlying state of the generation pipe.
data GenST n t = GenST {
waiting :: Q.PSQ (Tree n t) Int
-- ^ Queue of the derived trees yet to be visited.
, doneFinal :: DoneMap n t
-- ^ Set of visited, final trees divided by size
, doneActive :: DoneMap n t
-- ^ Set of visited, active (not final) trees divided by size
}
-- | Construct new generation state with all trees in the priority queue.
newGenST :: (Ord n, Ord t) => Gram n t -> GenST n t
newGenST gramSet = GenST {
waiting = Q.fromList
[ t :-> treeSize t
| t <- S.toList gramSet ]
, doneFinal = M.empty
, doneActive = M.empty }
-- | Pop the tree with the lowest score from the queue.
pop
:: (E.MonadState (GenST n t) m, Ord n, Ord t)
-- => m (Maybe (Tree n t))
=> ListT m (Tree n t)
pop = do
mayTree <- E.state $ \s@GenST{..} -> case Q.minView waiting of
Nothing -> (Nothing, s)
Just (t :-> _, q) -> (Just t, s {waiting=q})
-- return mayTree
some $ maybeToList mayTree
-- | Push tree into the waiting queue.
push :: (E.MonadState (GenST n t) m, Ord n, Ord t) => Tree n t -> m ()
push t = E.modify $ \s -> s
{waiting = Q.insert t (treeSize t) (waiting s)}
-- | Save tree as visited.
save :: (E.MonadState (GenST n t) m, Ord n, Ord t) => Tree n t -> m ()
save t = if isFinal t
then E.modify $ \s -> s
{ doneFinal = M.insertWith S.union
(treeSize t) (S.singleton t) (doneFinal s) }
else E.modify $ \s -> s
{ doneActive = M.insertWith S.union
(treeSize t) (S.singleton t) (doneActive s) }
-- | Check if tree already visited.
visited
:: (E.MonadState (GenST n t) m, Ord n, Ord t)
=> Tree n t -> m Bool
visited t = if isFinal t
then isVisited doneFinal
else isVisited doneActive
where
isVisited doneMap = do
done <- E.gets doneMap
return $ case M.lookup (treeSize t) done of
Just ts -> S.member t ts
Nothing -> False
-- | Retrieve all trees from the given map with the size satsifying
-- the given condition.
visitedWith
:: (E.MonadState (GenST n t) m, Ord n, Ord t)
=> (GenST n t -> DoneMap n t)
-> (Int -> Bool)
-> ListT m (Tree n t)
visitedWith doneMap cond = do
done <- E.gets doneMap
some [ t
| (k, treeSet) <- M.toList done
, cond k, t <- S.toList treeSet ]
-- -- | Retrieve all visited final trees with a size satsifying the
-- -- given condition.
-- finalWith
-- :: (E.MonadState (GenST n t) m, Ord n, Ord t)
-- => (Int -> Bool) -> ListT m (Tree n t)
-- finalWith = visitedWith doneFinal
--
--
-- -- | Retrieve all visited trees with a size satsifying
-- -- the given condition.
-- activeWith
-- :: (E.MonadState (GenST n t) m, Ord n, Ord t)
-- => (Int -> Bool) -> ListT m (Tree n t)
-- activeWith cond = visitedWith doneActive
--------------------------
-- Higher-level generation
--------------------------
data GenConf = GenConf {
genAllSize :: Int
-- ^ Generate all derivable trees up to the given size
, adjProb :: Double
-- ^ Adjunction probability
} deriving (Show, Eq, Ord)
-- | Randomized version of tree generation.
generateRand
:: (MonadIO m, Ord n, Ord t)
=> Gram n t
-> GenConf
-> Producer (Tree n t) m ()
generateRand gramSet cfg = E.forever $ do
finalSet <- collect basePipe
mayTree <- drawTree gramSet finalSet cfg
F.forM_ mayTree yield
-- case mayTree of
-- Nothing -> return ()
-- Just t -> yield t
where
-- first compute the base set of final trees
basePipe = generateAll gramSet (genAllSize cfg)
>-> Pipes.filter isFinal
-- | Try to construct randomly a tree based on the TAG grammar and
-- on the pre-built set of derived final trees.
drawTree
:: (MonadIO m, Ord n, Ord t)
=> Gram n t -- ^ The grammar
-> Gram n t -- ^ Final trees
-> GenConf -- ^ Global config
-> m (Maybe (Tree n t))
drawTree gramSet finalSet GenConf{..} = runMaybeT $ do
-- randomly draw an elementary tree
t0 <- drawFrom $ limitTo isInitial gramSet
-- recursivey modify the tree
modify t0
where
modify t@(R.Node (Term _) []) =
return t
modify (R.Node (NonTerm x) []) =
let cond = (&&) <$> hasRoot x <*> isInitial
in drawFrom (limitTo cond finalSet)
modify (R.Node (NonTerm x) xs0) = do
-- modify subtrees
xs <- mapM modify xs0
-- construct the new tree
let t = R.Node (NonTerm x) xs
-- adjoin some tree if lucky
lottery adjProb (return t) $ do
let cond = (&&) <$> hasRoot x <*> isAuxiliary
auxTree <- drawFrom $ limitTo cond finalSet
return $ replaceFoot t auxTree
modify _ = error "drawTree.modify: unhandled node type"
drawFrom s = do
E.guard $ S.size s > 0
i <- liftIO $ randomRIO (0, S.size s - 1)
-- return $ S.elemAt i s <- works starting from containers 0.5.2
return $ S.toList s !! i
limitTo f = S.fromList . filter f . S.toList
--------------------------
-- Generation
--------------------------
-- | Type of the generator.
type Gen m n t = E.StateT (GenST n t) (Producer (Tree n t) m) ()
-- Generate all trees derivable from the given grammar
-- up to a given size.
generateAll
:: (MonadIO m, Ord n, Ord t)
=> Gram n t -> Int -> Producer (Tree n t) m ()
generateAll gram0 sizeMax =
-- gram <- subGram gram0
E.evalStateT
(genPipe sizeMax)
(newGenST gram0)
-- -- | Select sub-grammar rules.
-- subGram
-- :: (MonadIO m, Ord n, Ord t) => Double -> Gram n t -> m (Gram n t)
-- subGram probMax gram = do
-- stdGen <- liftIO getStdGen
-- let ps = randomRs (0, 1) stdGen
-- return $ S.fromList
-- [t | (t, p) <- zip (S.toList gram) ps, p <= probMax]
-- | A function which generates trees derived from the grammar. The
-- second argument allows to specify a probability of ignoring a tree
-- popped up from the waiting queue. When set to `1`, all derived
-- trees up to the given size should be generated.
genPipe :: (MonadIO m, Ord n, Ord t) => Int -> Gen m n t
genPipe sizeMax = runListT $ do
-- pop best-score tree from the queue
t <- pop
lift $ do
genStep sizeMax t
genPipe sizeMax
-- | Generation step.
genStep
:: (MonadIO m, Ord n, Ord t)
=> Int -- ^ Tree size limit
-> Tree n t -- ^ Tree from the queue
-> Gen m n t
genStep sizeMax t = runListT $ do
-- check if it's not in the set of visited trees yet
-- TODO: is it even necessary?
E.guard . not =<< visited t
-- save tree `t` and yield it
save t
lift . lift $ yield t
-- choices based on whether 't' is final
let doneMap = if isFinal t
then doneActive
else doneFinal
-- find all possible combinations of 't' and some visited 'u',
-- and add them to the waiting queue;
-- note that `t` is now in the set of visited trees --
-- this allows the process to generate `combinations t t`;
u <- visitedWith doneMap $
let n = treeSize t
in \k -> k + n <= sizeMax + 1
-- NOTE: at this point we know that `v` cannot yet be visited;
-- it must be larger than any tree in the set of visited trees.
let combine x y = some $
inject x y ++
inject y x
v <- combine t u
-- we only put to the queue trees which do not exceed
-- the specified size
E.guard $ treeSize v <= sizeMax
push v
---------------------------------------------------------------------
-- Composition
---------------------------------------------------------------------
-- | Identify all possible ways to inject (i.e. substitute
-- or adjoin) the first tree to the second one.
inject :: (Eq n, Eq t) => Tree n t -> Tree n t -> [Tree n t]
inject s t = if isAuxiliary s
then adjoin s t
else subst s t
-- | Compute all possible ways of adjoining the first tree into the
-- second one.
adjoin :: (Eq n, Eq t) => Tree n t -> Tree n t -> [Tree n t]
adjoin _ (R.Node (NonTerm _) []) = []
adjoin s (R.Node n ts) =
here ++ below
where
-- perform adjunction here
here = [replaceFoot (R.Node n ts) s | R.rootLabel s == n]
-- consider to perform adjunction lower in the tree
below = map (R.Node n) (doit ts)
doit [] = []
doit (x:xs) =
[u : xs | u <- adjoin s x] ++
[x : us | us <- doit xs]
-- | Replace foot of the second tree with the first tree.
-- If there is no foot in the second tree, it will be returned
-- unchanged.
replaceFoot :: Tree n t -> Tree n t -> Tree n t
replaceFoot t (R.Node (Foot _) []) = t
replaceFoot t (R.Node x xs) = R.Node x $ map (replaceFoot t) xs
-- | Compute all possible ways of substituting the first tree into
-- the second one.
subst :: (Eq n, Eq t) => Tree n t -> Tree n t -> [Tree n t]
subst s = take 1 . _subst s
-- | Compute all possible ways of substituting the first tree into
-- the second one.
_subst :: (Eq n, Eq t) => Tree n t -> Tree n t -> [Tree n t]
_subst s (R.Node n []) =
[s | R.rootLabel s == n]
_subst s (R.Node n ts) =
map (R.Node n) (doit ts)
where
doit [] = []
doit (x:xs) =
[u : xs | u <- subst s x] ++
[x : us | us <- doit xs]
--------------------------
-- Utils
--------------------------
-- -- | MaybeT constructor.
-- maybeT :: Monad m => Maybe a -> MaybeT m a
-- maybeT = MaybeT . return
-- | ListT from a list.
some :: Monad m => [a] -> ListT m a
some = Select . each
-- -- | Draw a number between 0 and 1, and check if it is <= the given
-- -- maximal probability.
-- lottery :: (MonadPlus m, MonadIO m) => Double -> m ()
-- lottery probMax = do
-- p <- liftIO $ randomRIO (0, 1)
-- E.guard $ p <= probMax
-- | Collect elements from the pipe into a set.
collect :: (Monad m, Ord a) => Producer a m () -> m (S.Set a)
collect inputPipe =
flip E.execStateT S.empty
$ runEffect
$ hoist lift inputPipe >-> collectPipe
where
collectPipe = E.forever $ do
x <- await
lift . E.modify $ S.insert x
-- | Run `my` if lucky, `mx` otherwise.
lottery :: (MonadIO m, MonadPlus m) => Double -> m a -> m a -> m a
lottery probMax mx my = do
p <- liftIO $ randomRIO (0, 1)
if p > probMax
then mx
else my
|
kawu/tag-vanilla
|
src/NLP/TAG/Vanilla/Gen.hs
|
bsd-2-clause
| 12,041 | 3 | 17 | 3,330 | 3,204 | 1,687 | 1,517 | 201 | 4 |
{-
Verified Koopa Troopa Movement
Toon Nolten
-}
{-# LANGUAGE GADTs, DataKinds, KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
module Koopa where
data Nat = Z | S Nat
data Natty :: Nat -> * where
Zy :: Natty Z
Sy :: Natty n -> Natty (S n)
natter :: Natty n -> Nat
natter Zy = Z
natter (Sy n) = S (natter n)
data NATTY :: * where
Nat :: Natty n -> NATTY
nattyer :: Nat -> NATTY
nattyer Z = Nat Zy
nattyer (S n) = case nattyer n of Nat m -> Nat (Sy m)
data Fin :: Nat -> * where
Zf :: Fin (S n)
Sf :: Fin n -> Fin (S n)
intToFin :: Natty n -> Integer -> Fin n
intToFin Zy _ = error "Fin Z is an empty type"
intToFin (Sy n) i
| i < 0 = error "Negative Integers cannot be represented by a finite natural"
| i == 0 = Zf
| i > 0 = Sf (intToFin n (i-1))
data Vec :: * -> Nat -> * where
V0 :: Vec a Z
(:>) :: a -> Vec a n -> Vec a (S n)
infixr 5 :>
vlookup :: Fin n -> Vec a n -> a
vlookup (Zf) (a :> _) = a
vlookup (Sf n) (_ :> as) = vlookup n as
vreplicate :: Natty n -> a -> Vec a n
vreplicate Zy _ = V0
vreplicate (Sy n) a = a :> vreplicate n a
vreverse :: Vec a n -> Vec a n
vreverse V0 = V0
vreverse (a :> V0) = a :> V0
vreverse (a :> as) = vreverse' as a
where
vreverse' :: Vec a n -> a -> Vec a (S n)
vreverse' V0 x' = x' :> V0
vreverse' (x :> xs) x' = x :> vreverse' xs x'
data Matrix :: * -> Nat -> Nat -> * where
Mat :: Vec (Vec a w) h -> Matrix a w h
mlookup :: Fin h -> Fin w -> Matrix a w h -> a
mlookup row column (Mat rows) = vlookup column (vlookup row rows)
data Color = Green | Red
data Colorry :: Color -> * where
Greeny :: Colorry Green
Redy :: Colorry Red
data KoopaTroopa :: Color -> * where
KT :: Colorry c -> KoopaTroopa c
data Material = Gas | Solid
data Matty :: Material -> * where
Gasy :: Matty Gas
Solidy :: Matty Solid
data MATTY :: * where
Mater :: Matty m -> MATTY
mattyer :: Material -> MATTY
mattyer Gas = Mater Gasy
mattyer Solid = Mater Solidy
data Clearance = Low | High | Ultimate
data Clearry :: Clearance -> * where
Lowy :: Clearry Low
Highy :: Clearry High
Ultimatey :: Clearry Ultimate
data CLEARRY :: * where
Clear :: Clearry cl -> CLEARRY
clearryer :: Clearance -> CLEARRY
clearryer Low = Clear Lowy
clearryer High = Clear Highy
clearryer Ultimate = Clear Ultimatey
data Position = Pos { getX :: Nat
, getY :: Nat
, matter :: Material
, clr :: Clearance
}
data Positionny :: Position -> * where
Posy :: Natty x -> Natty y -> Matty m -> Clearry cl
-> Positionny (Pos x y m cl)
data POSITIONNY :: * where
Posit :: Positionny p -> POSITIONNY
positionnyer :: Position -> POSITIONNY
positionnyer (Pos x y m cl)
| Nat xY <- nattyer x
, Nat yY <- nattyer y
, Mater mY <- mattyer m
, Clear clY <- clearryer cl
= Posit (Posy xY yY mY clY)
class CoClr (c :: Color) (cl :: Clearance)
instance CoClr c Low
instance CoClr Green High
data Follows :: Position -> Position -> Color -> * where
Stay :: Follows (Pos x y Gas Low) (Pos x y Gas Low) c
Next :: CoClr c cl => Follows (Pos (S x) y Gas cl) (Pos x y Gas Low) c
Back :: CoClr c cl => Follows (Pos x y Gas cl) (Pos (S x) y Gas Low) c
Fall :: Follows (Pos x y Gas cl) (Pos x (S y) Gas High) c
data Path :: Color -> Position -> Position -> * where
P0 :: Path c p p
Pcons :: Positionny p -> Follows q p c -> Path c q r -> Path c p r
-- Examples
exPath :: Path Red (Pos Z Z Gas Low) (Pos Z Z Gas Low)
exPath = Pcons (Posy Zy Zy Gasy Lowy) Next
(Pcons (Posy (Sy Zy) Zy Gasy Lowy) Back
(Pcons (Posy Zy Zy Gasy Lowy) Stay P0))
matterToPosVec :: Vec Material n -> Vec Material n -> Nat -> Nat
-> Vec Position n
matterToPosVec V0 V0 _ _ = V0
matterToPosVec (mat :> mats) (under :> unders) x y =
Pos x y mat cl :> matterToPosVec mats unders (S x) y
where
clearance :: Material -> Material -> Clearance
clearance Gas Gas = High
clearance Gas Solid = Low
clearance Solid _ = Ultimate
cl = clearance mat under
matterToPosVecs :: Natty w -> Natty h -> Vec (Vec Material w) h
-> Vec (Vec Position w) h
matterToPosVecs _ _ V0 = V0
matterToPosVecs w (Sy z) (mats :> matss) =
matterToPosVec mats (unders w matss Gas) Z y :> matterToPosVecs w z matss
where
y = natter (Sy z)
unders :: Natty m -> Vec (Vec a m) n -> a -> Vec a m
unders m V0 fallback = vreplicate m fallback
unders _ (us :> _) _ = us
mattersToMatrix :: Natty w -> Natty h -> Vec (Vec Material w) h
-> Matrix Position w h
mattersToMatrix w h matss = Mat (vreverse (matterToPosVecs w h matss))
o :: Material
o = Gas
c :: Material
c = Solid
exampleLevel :: Matrix Position
(S(S(S(S(S(S(S(S(S(S Z)))))))))) -- 10
(S(S(S(S(S(S(S Z))))))) -- 7
exampleLevel = mattersToMatrix
(Sy(Sy(Sy(Sy(Sy(Sy(Sy(Sy(Sy(Sy Zy)))))))))) -- 10
(Sy(Sy(Sy(Sy(Sy(Sy(Sy Zy))))))) -- 7
(
(o :> o :> o :> o :> o :> o :> o :> o :> o :> o :> V0) :>
(o :> o :> o :> o :> o :> o :> c :> c :> c :> o :> V0) :>
(o :> o :> o :> o :> o :> o :> o :> o :> o :> o :> V0) :>
(o :> o :> o :> c :> c :> c :> o :> o :> o :> o :> V0) :>
(o :> o :> o :> o :> o :> o :> o :> o :> o :> o :> V0) :>
(c :> o :> o :> o :> o :> o :> o :> o :> o :> c :> V0) :>
(c :> c :> c :> c :> c :> o :> o :> c :> c :> c :> V0) :> V0)
ix :: Integer -> Fin (S(S(S(S(S(S(S(S(S(S Z)))))))))) -- 10
ix = intToFin (Sy(Sy(Sy(Sy(Sy(Sy(Sy(Sy(Sy(Sy Zy)))))))))) -- 10
iy :: Integer -> Fin (S(S(S(S(S(S(S Z))))))) -- 7
iy = intToFin (Sy(Sy(Sy(Sy(Sy(Sy(Sy Zy))))))) -- 7
p :: Fin (S(S(S(S(S(S(S(S(S(S Z))))))))))
-> Fin (S(S(S(S(S(S(S Z)))))))
-> POSITIONNY
p x y | Pos x' y' m' cl' <- mlookup y x exampleLevel
, Nat xy <- nattyer x'
, Nat yy <- nattyer y'
, Mater my <- mattyer m'
, Clear cly <- clearryer cl'
= Posit (Posy xy yy my cly)
p01 = Posy Zy (Sy Zy) Solidy Ultimatey
p11 = Posy (Sy Zy) (Sy Zy) Gasy Lowy
p21 = Posy (Sy(Sy Zy)) (Sy Zy) Gasy Lowy
p22 = Posy (Sy(Sy Zy)) (Sy(Sy Zy)) Gasy Highy
p23 = Posy (Sy(Sy Zy)) (Sy(Sy(Sy Zy))) Gasy Highy
p24 = Posy (Sy(Sy Zy)) (Sy(Sy(Sy(Sy Zy)))) Gasy Highy
p31 = Posy (Sy(Sy(Sy Zy))) (Sy Zy) Gasy Lowy
p34 = Posy (Sy(Sy(Sy Zy))) (Sy(Sy(Sy(Sy Zy)))) Gasy Lowy
p41 = Posy (Sy(Sy(Sy(Sy Zy)))) (Sy Zy) Gasy Lowy
p44 = Posy (Sy(Sy(Sy(Sy Zy)))) (Sy(Sy(Sy(Sy Zy)))) Gasy Lowy
p51 = Posy (Sy(Sy(Sy(Sy(Sy Zy))))) (Sy Zy) Gasy Highy
p54 = Posy (Sy(Sy(Sy(Sy(Sy Zy))))) (Sy(Sy(Sy(Sy Zy)))) Gasy Lowy
p55 = Posy (Sy(Sy(Sy(Sy(Sy Zy))))) (Sy(Sy(Sy(Sy(Sy Zy))))) Gasy Highy
p56 = Posy (Sy(Sy(Sy(Sy(Sy Zy))))) (Sy(Sy(Sy(Sy(Sy(Sy Zy)))))) Gasy Highy
p66 = Posy (Sy(Sy(Sy(Sy(Sy(Sy Zy))))))
(Sy(Sy(Sy(Sy(Sy(Sy Zy)))))) Gasy Lowy
p76 = Posy (Sy(Sy(Sy(Sy(Sy(Sy(Sy Zy)))))))
(Sy(Sy(Sy(Sy(Sy(Sy Zy)))))) Gasy Lowy
p86 = Posy (Sy(Sy(Sy(Sy(Sy(Sy(Sy(Sy Zy))))))))
(Sy(Sy(Sy(Sy(Sy(Sy Zy)))))) Gasy Lowy
redPathOne :: Path Red (Pos (S(S(S(S(S(S(S Z)))))))
(S(S(S(S(S(S Z)))))) Gas Low)
(Pos (S(S(S(S(S(S(S(S Z))))))))
(S(S(S(S(S(S Z)))))) Gas Low)
redPathOne = Pcons p76 Back
$ Pcons p66 Next
$ Pcons p76 Next
$ Pcons p86 Stay P0
redPathTwo :: Path Red (Pos (S(S Z)) (S Z) Gas Low)
(Pos (S(S(S Z))) (S Z) Gas Low)
redPathTwo = Pcons p21 Back
$ Pcons p11 Next
$ Pcons p21 Next
$ Pcons p31 Next
$ Pcons p41 Back
$ Pcons p31 Stay P0
-- Because Stay only allows a position with material Gas to follow from
-- a position with material Gas, this is a type error
-- redNoPathOne :: Path Red (Pos (S Z) (S Z) Gas Low)
-- (Pos Z (S Z) Solid Ultimate)
-- redNoPathOne = Pcons p11 Back
-- $ Pcons p01 Stay P0
-- Red Koopa Troopa can't step into a wall
-- This is for the same reason as in redNoPathOne but with the Back
-- constructor
-- redNoPathTwo :: Path Red (Pos (S Z) (S Z) Gas Low)
-- (Pos Z (S Z) Solid Ultimate)
-- redNoPathTwo = Pcons p11 Back P0
-- Red Koopa Troopa can't step into air
-- Here the problem is that there is no instance for CoClr Red High which
-- is necessary for Next, however the solution GHC suggests is to add it
-- while it was actually not defined on purpose
-- redNoPathThree :: Path Red (Pos (S(S(S(S Z)))) (S Z) Gas Low)
-- (Pos (S(S(S(S(S Z))))) (S Z) Gas High)
-- redNoPathThree = Pcons p41 Next P0
-- Any path that is valid for red Koopa Troopas, is also valid for green
-- Koopa Troopas because we did not constrain Koopa Troopas to only turn
-- when there is an obstacle
greenPathOne :: Path Green (Pos (S(S(S(S(S(S(S Z)))))))
(S(S(S(S(S(S Z)))))) Gas Low)
(Pos (S(S(S(S(S(S(S(S Z))))))))
(S(S(S(S(S(S Z)))))) Gas Low)
greenPathOne = Pcons p76 Back
$ Pcons p66 Next
$ Pcons p76 Next
$ Pcons p86 Stay P0
greenPathTwo :: Path Green (Pos (S(S(S(S(S(S(S Z)))))))
(S(S(S(S(S(S Z)))))) Gas Low)
(Pos (S(S(S(S(S Z))))) Z Gas Low)
greenPathTwo = Pcons p76 Back
$ Pcons p66 Back
$ Pcons p56 Fall
$ Pcons p55 Fall
$ Pcons p54 Back
$ Pcons p44 Back
$ Pcons p34 Back
$ Pcons p24 Fall
$ Pcons p23 Fall
$ Pcons p22 Fall
$ Pcons p21 Back
$ Pcons p11 Next
$ Pcons p21 Next
$ Pcons p31 Next
$ Pcons p41 Next
$ Pcons p51 Fall P0
-- Green Koopa Troopa can't step into a wall
-- Exactly the same as for redNoPathTwo
-- greenNoPathOne :: Path Green (Pos (S Z) (S Z) Gas Low)
-- (Pos Z (S Z) Solid Ultimate)
-- greenNoPathOne = Pcons p11 Back P0
|
toonn/haskell-casestt
|
koopa.hs
|
bsd-2-clause
| 10,152 | 0 | 26 | 3,151 | 5,041 | 2,534 | 2,507 | -1 | -1 |
-- This module generates the files src/Extra.hs and test/TestGen.hs.
-- Either call "runghc Generate" or start "ghci" and use ":generate".
module Generate(main) where
import Data.List.Extra
import System.IO.Extra
import Control.Exception
import Control.Monad.Extra
import System.FilePath
import System.Directory
import Data.Char
import Data.Maybe
import Data.Functor
import Prelude
main :: IO ()
main = do
src <- readFile "extra.cabal"
let mods = filter (isSuffixOf ".Extra") $ map trim $ lines src
ifaces <- forM (mods \\ exclude) $ \mod -> do
src <- readFile $ joinPath ("src" : split (== '.') mod) <.> "hs"
let funcs = filter validIdentifier $ takeWhile (/= "where") $
words $ replace "," " " $ drop1 $ dropWhile (/= '(') $
unlines $ filter (\x -> not $ any (`isPrefixOf` trim x) ["--","#"]) $ lines src
let tests = if mod `elem` excludeTests then [] else mapMaybe (stripPrefix "-- > ") $ lines src
pure (mod, funcs, tests)
writeFileBinaryChanged "src/Extra.hs" $ unlines $
["-- GENERATED CODE - DO NOT MODIFY"
,"-- See Generate.hs for details of how to generate"
,""
,"-- | This module documents all the functions available in this package."
,"--"
,"-- Most users should import the specific modules (e.g. @\"Data.List.Extra\"@), which"
,"-- also reexport their non-@Extra@ modules (e.g. @\"Data.List\"@)."
,"module Extra {-# DEPRECATED \"This module is provided as documentation of all new functions, you should import the more specific modules directly.\" #-} ("] ++
concat [ [" -- * " ++ mod
," -- | Extra functions available in @" ++ show mod ++ "@."
," " ++ unwords (map (++",") $ filter (notHidden mod) funs)]
| (mod,funs@(_:_),_) <- ifaces] ++
[" ) where"
,""] ++
["import " ++ addHiding mod | (mod,_:_,_) <- ifaces]
writeFileBinaryChanged "test/TestGen.hs" $ unlines $
["-- GENERATED CODE - DO NOT MODIFY"
,"-- See Generate.hs for details of how to generate"
,""
,"{-# LANGUAGE ExtendedDefaultRules, ScopedTypeVariables, TypeApplications, ViewPatterns #-}"
,"module TestGen(tests) where"
,"import TestUtil"
,"import qualified Data.Ord"
,"import Test.QuickCheck.Instances.Semigroup ()"
,"default(Maybe Bool,Int,Double,Maybe (Maybe Bool),Maybe (Maybe Char))"
,"tests :: IO ()"
,"tests = do"] ++
[" " ++ if "let " `isPrefixOf` t then t else "testGen " ++ show t ++ " $ " ++ tweakTest t | (_,_,ts) <- ifaces, t <- rejoin ts]
rejoin :: [String] -> [String]
rejoin (x1:x2:xs) | " " `isPrefixOf` x2 = rejoin $ (x1 ++ x2) : xs
rejoin (x:xs) = x : rejoin xs
rejoin [] = []
writeFileBinaryChanged :: FilePath -> String -> IO ()
writeFileBinaryChanged file x = do
evaluate $ length x -- ensure we don't write out files with _|_ in them
old <- ifM (doesFileExist file) (Just <$> readFileBinary' file) (pure Nothing)
when (Just x /= old) $
writeFileBinary file x
exclude :: [String]
exclude =
["Data.Foldable.Extra" -- because all their imports clash
]
excludeTests :: [String]
-- FIXME: Should probably generate these in another module
excludeTests =
["Data.List.NonEmpty.Extra" -- because !? clashes and is tested
]
hidden :: String -> [String]
hidden "Data.List.NonEmpty.Extra" = words
"cons snoc sortOn union unionBy nubOrd nubOrdBy nubOrdOn (!?) foldl1'"
hidden _ = []
notHidden :: String -> String -> Bool
notHidden mod fun = fun `notElem` hidden mod
addHiding :: String -> String
addHiding mod
| xs@(_:_) <- hidden mod = mod ++ " hiding (" ++ intercalate ", " xs ++ ")"
| otherwise = mod
validIdentifier xs =
(take 1 xs == "(" || isName (takeWhile (/= '(') xs)) &&
xs `notElem` ["module","Numeric"]
isName (x:xs) = isAlpha x && all (\x -> isAlphaNum x || x `elem` "_'") xs
isName _ = False
tweakTest x
| Just x <- stripSuffix " == undefined" x =
if not $ "\\" `isPrefixOf` x then
(if "fileEq" `isInfixOf` x then "erroneousIO $ " else "erroneous $ ") ++ trim x
else
let (a,b) = breakOn "->" $ trim x
in a ++ "-> erroneous $ " ++ trim (drop 2 b)
| otherwise = x
|
ndmitchell/extra
|
Generate.hs
|
bsd-3-clause
| 4,343 | 0 | 24 | 1,121 | 1,226 | 647 | 579 | 89 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveGeneric #-}
module Aws.DynamoDb.Commands.Table(
-- * Commands
CreateTable(..)
, CreateTableResult(..)
, DescribeTable(..)
, DescribeTableResult(..)
, UpdateTable(..)
, UpdateTableResult(..)
, DeleteTable(..)
, DeleteTableResult(..)
, ListTables(..)
, ListTablesResult(..)
-- * Data passed in the commands
, KeyAttributeType(..)
, KeyAttributeDefinition(..)
, KeySchema(..)
, Projection(..)
, LocalSecondaryIndex(..)
, LocalSecondaryIndexStatus(..)
, ProvisionedThroughput(..)
, ProvisionedThroughputStatus(..)
, GlobalSecondaryIndex(..)
, GlobalSecondaryIndexStatus(..)
, GlobalSecondaryIndexUpdate(..)
, TableDescription(..)
) where
import Aws.Core
import Aws.DynamoDb.Core
import Control.Applicative
import Data.Aeson ((.=), (.:), (.!=), (.:?))
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A
import Data.Char (toUpper)
import Data.Time
import Data.Time.Clock.POSIX
import qualified Data.Text as T
import qualified Data.Vector as V
import qualified Data.HashMap.Strict as M
import GHC.Generics (Generic)
capitalizeOpt :: A.Options
capitalizeOpt = A.defaultOptions { A.fieldLabelModifier = \x -> case x of
(c:cs) -> toUpper c : cs
[] -> []
}
dropOpt :: Int -> A.Options
dropOpt d = A.defaultOptions { A.fieldLabelModifier = drop d }
-- | The type of a key attribute that appears in the table key or as a key in one of the indices.
data KeyAttributeType = AttrStringT | AttrNumberT | AttrBinaryT
deriving (Show, Eq, Enum, Bounded, Generic)
instance A.ToJSON KeyAttributeType where
toJSON AttrStringT = A.String "S"
toJSON AttrNumberT = A.String "N"
toJSON AttrBinaryT = A.String "B"
instance A.FromJSON KeyAttributeType where
parseJSON (A.String str) =
case str of
"S" -> return AttrStringT
"N" -> return AttrNumberT
"B" -> return AttrBinaryT
_ -> fail $ "Invalid attribute type " ++ T.unpack str
parseJSON _ = fail "Attribute type must be a string"
-- | A key attribute that appears in the table key or as a key in one of the indices.
data KeyAttributeDefinition
= KeyAttributeDefinition {
attributeName :: T.Text
, attributeType :: KeyAttributeType
}
deriving (Show, Generic)
instance A.ToJSON KeyAttributeDefinition where
toJSON = A.genericToJSON capitalizeOpt
instance A.FromJSON KeyAttributeDefinition where
parseJSON = A.genericParseJSON capitalizeOpt
-- | The key schema can either be a hash of a single attribute name or a hash attribute name
-- and a range attribute name.
data KeySchema = KeyHashOnly T.Text
| KeyHashAndRange T.Text T.Text
deriving (Show)
instance A.ToJSON KeySchema where
toJSON (KeyHashOnly attr)
= A.Array $ V.fromList [ A.object [ "AttributeName" .= attr
, "KeyType" .= ("HASH" :: T.Text)
]
]
toJSON (KeyHashAndRange hash range)
= A.Array $ V.fromList [ A.object [ "AttributeName" .= hash
, "KeyType" .= ("HASH" :: T.Text)
]
, A.object [ "AttributeName" .= range
, "KeyType" .= ("RANGE" :: T.Text)
]
]
instance A.FromJSON KeySchema where
parseJSON (A.Array v) =
case V.length v of
1 -> do obj <- A.parseJSON (v V.! 0)
kt <- obj .: "KeyType"
if kt /= ("HASH" :: T.Text)
then fail "With only one key, the type must be HASH"
else KeyHashOnly <$> obj .: "AttributeName"
2 -> do hash <- A.parseJSON (v V.! 0)
range <- A.parseJSON (v V.! 1)
hkt <- hash .: "KeyType"
rkt <- range .: "KeyType"
if hkt /= ("HASH" :: T.Text) || rkt /= ("RANGE" :: T.Text)
then fail "With two keys, one must be HASH and the other RANGE"
else KeyHashAndRange <$> hash .: "AttributeName"
<*> range .: "AttributeName"
_ -> fail "Key schema must have one or two entries"
parseJSON _ = fail "Key schema must be an array"
-- | This determines which attributes are projected into a secondary index.
data Projection = ProjectKeysOnly
| ProjectAll
| ProjectInclude [T.Text]
deriving Show
instance A.ToJSON Projection where
toJSON ProjectKeysOnly = A.object [ "ProjectionType" .= ("KEYS_ONLY" :: T.Text) ]
toJSON ProjectAll = A.object [ "ProjectionType" .= ("ALL" :: T.Text) ]
toJSON (ProjectInclude a) = A.object [ "ProjectionType" .= ("INCLUDE" :: T.Text)
, "NonKeyAttributes" .= a
]
instance A.FromJSON Projection where
parseJSON (A.Object o) = do
ty <- (o .: "ProjectionType") :: A.Parser T.Text
case ty of
"KEYS_ONLY" -> return ProjectKeysOnly
"ALL" -> return ProjectAll
"INCLUDE" -> ProjectInclude <$> o .: "NonKeyAttributes"
_ -> fail "Invalid projection type"
parseJSON _ = fail "Projection must be an object"
-- | Describes a single local secondary index. The KeySchema MUST share the same hash key attribute
-- as the parent table, only the range key can differ.
data LocalSecondaryIndex
= LocalSecondaryIndex {
localIndexName :: T.Text
, localKeySchema :: KeySchema
, localProjection :: Projection
}
deriving (Show, Generic)
instance A.ToJSON LocalSecondaryIndex where
toJSON = A.genericToJSON $ dropOpt 5
instance A.FromJSON LocalSecondaryIndex where
parseJSON = A.genericParseJSON $ dropOpt 5
-- | This is returned by AWS to describe the local secondary index.
data LocalSecondaryIndexStatus
= LocalSecondaryIndexStatus {
locStatusIndexName :: T.Text
, locStatusIndexSizeBytes :: Integer
, locStatusItemCount :: Integer
, locStatusKeySchema :: KeySchema
, locStatusProjection :: Projection
}
deriving (Show, Generic)
instance A.FromJSON LocalSecondaryIndexStatus where
parseJSON = A.genericParseJSON $ dropOpt 9
-- | The target provisioned throughput you are requesting for the table or global secondary index.
data ProvisionedThroughput
= ProvisionedThroughput {
readCapacityUnits :: Int
, writeCapacityUnits :: Int
}
deriving (Show, Generic)
instance A.ToJSON ProvisionedThroughput where
toJSON = A.genericToJSON capitalizeOpt
instance A.FromJSON ProvisionedThroughput where
parseJSON = A.genericParseJSON capitalizeOpt
-- | This is returned by AWS as the status of the throughput for a table or global secondary index.
data ProvisionedThroughputStatus
= ProvisionedThroughputStatus {
statusLastDecreaseDateTime :: UTCTime
, statusLastIncreaseDateTime :: UTCTime
, statusNumberOfDecreasesToday :: Int
, statusReadCapacityUnits :: Int
, statusWriteCapacityUnits :: Int
}
deriving (Show, Generic)
instance A.FromJSON ProvisionedThroughputStatus where
parseJSON = A.withObject "Throughput status must be an object" $ \o ->
ProvisionedThroughputStatus
<$> (posixSecondsToUTCTime . fromInteger <$> o .:? "LastDecreaseDateTime" .!= 0)
<*> (posixSecondsToUTCTime . fromInteger <$> o .:? "LastIncreaseDateTime" .!= 0)
<*> o .:? "NumberOfDecreasesToday" .!= 0
<*> o .: "ReadCapacityUnits"
<*> o .: "WriteCapacityUnits"
-- | Describes a global secondary index.
data GlobalSecondaryIndex
= GlobalSecondaryIndex {
globalIndexName :: T.Text
, globalKeySchema :: KeySchema
, globalProjection :: Projection
, globalProvisionedThroughput :: ProvisionedThroughput
}
deriving (Show, Generic)
instance A.ToJSON GlobalSecondaryIndex where
toJSON = A.genericToJSON $ dropOpt 6
instance A.FromJSON GlobalSecondaryIndex where
parseJSON = A.genericParseJSON $ dropOpt 6
-- | This is returned by AWS to describe the status of a global secondary index.
data GlobalSecondaryIndexStatus
= GlobalSecondaryIndexStatus {
gStatusIndexName :: T.Text
, gStatusIndexSizeBytes :: Integer
, gStatusIndexStatus :: T.Text
, gStatusItemCount :: Integer
, gStatusKeySchema :: KeySchema
, gStatusProjection :: Projection
, gStatusProvisionedThroughput :: ProvisionedThroughputStatus
}
deriving (Show, Generic)
instance A.FromJSON GlobalSecondaryIndexStatus where
parseJSON = A.genericParseJSON $ dropOpt 7
-- | This is used to request a change in the provisioned throughput of a global secondary index as
-- part of an 'UpdateTable' operation.
data GlobalSecondaryIndexUpdate
= GlobalSecondaryIndexUpdate {
gUpdateIndexName :: T.Text
, gUpdateProvisionedThroughput :: ProvisionedThroughput
}
deriving (Show, Generic)
instance A.ToJSON GlobalSecondaryIndexUpdate where
toJSON gi = A.object ["Update" .= A.genericToJSON (dropOpt 7) gi]
-- | This describes the table and is the return value from AWS for all the table-related commands.
data TableDescription
= TableDescription {
rTableName :: T.Text
, rTableSizeBytes :: Integer
, rTableStatus :: T.Text -- ^ one of CREATING, UPDATING, DELETING, ACTIVE
, rCreationDateTime :: UTCTime
, rItemCount :: Integer
, rAttributeDefinitions :: [KeyAttributeDefinition]
, rKeySchema :: KeySchema
, rProvisionedThroughput :: ProvisionedThroughputStatus
, rLocalSecondaryIndexes :: [LocalSecondaryIndexStatus]
, rGlobalSecondaryIndexes :: [GlobalSecondaryIndexStatus]
}
deriving (Show, Generic)
instance A.FromJSON TableDescription where
parseJSON = A.withObject "Table must be an object" $ \o -> do
t <- case (M.lookup "Table" o, M.lookup "TableDescription" o) of
(Just (A.Object t), _) -> return t
(_, Just (A.Object t)) -> return t
_ -> fail "Table description must have key 'Table' or 'TableDescription'"
TableDescription <$> t .: "TableName"
<*> t .: "TableSizeBytes"
<*> t .: "TableStatus"
<*> (posixSecondsToUTCTime . fromInteger <$> t .: "CreationDateTime")
<*> t .: "ItemCount"
<*> t .: "AttributeDefinitions"
<*> t .: "KeySchema"
<*> t .: "ProvisionedThroughput"
<*> t .:? "LocalSecondaryIndexes" .!= []
<*> t .:? "GlobalSecondaryIndexes" .!= []
{- Can't derive these instances onto the return values
instance ResponseConsumer r TableDescription where
type ResponseMetadata TableDescription = DyMetadata
responseConsumer _ _ = dyResponseConsumer
instance AsMemoryResponse TableDescription where
type MemoryResponse TableDescription = TableDescription
loadToMemory = return
-}
-------------------------------------------------------------------------------
--- Commands
-------------------------------------------------------------------------------
data CreateTable
= CreateTable {
createTableName :: T.Text
, createAttributeDefinitions :: [KeyAttributeDefinition] -- ^ only attributes appearing in a key must be listed here
, createKeySchema :: KeySchema
, createProvisionedThroughput :: ProvisionedThroughput
, createLocalSecondaryIndexes :: [LocalSecondaryIndex] -- ^ at most 5 local secondary indices are allowed
, createGlobalSecondaryIndexes :: [GlobalSecondaryIndex]
}
deriving (Show, Generic)
instance A.ToJSON CreateTable where
toJSON ct = A.object $ m ++ lindex ++ gindex
where
m = [ "TableName" .= createTableName ct
, "AttributeDefinitions" .= createAttributeDefinitions ct
, "KeySchema" .= createKeySchema ct
, "ProvisionedThroughput" .= createProvisionedThroughput ct
]
-- AWS will error with 500 if (LocalSecondaryIndexes : []) is present in the JSON
lindex = if null (createLocalSecondaryIndexes ct)
then []
else [ "LocalSecondaryIndexes" .= createLocalSecondaryIndexes ct ]
gindex = if null (createGlobalSecondaryIndexes ct)
then []
else [ "GlobalSecondaryIndexes" .= createGlobalSecondaryIndexes ct ]
--instance A.ToJSON CreateTable where
-- toJSON = A.genericToJSON $ dropOpt 6
-- | ServiceConfiguration: 'DyConfiguration'
instance SignQuery CreateTable where
type ServiceConfiguration CreateTable = DyConfiguration
signQuery = dySignQuery "CreateTable"
newtype CreateTableResult = CreateTableResult { ctStatus :: TableDescription }
deriving (Show, A.FromJSON)
-- ResponseConsumer and AsMemoryResponse can't be derived
instance ResponseConsumer r CreateTableResult where
type ResponseMetadata CreateTableResult = DyMetadata
responseConsumer _ _ = dyResponseConsumer
instance AsMemoryResponse CreateTableResult where
type MemoryResponse CreateTableResult = TableDescription
loadToMemory = return . ctStatus
instance Transaction CreateTable CreateTableResult
data DescribeTable
= DescribeTable {
dTableName :: T.Text
}
deriving (Show, Generic)
instance A.ToJSON DescribeTable where
toJSON = A.genericToJSON $ dropOpt 1
-- | ServiceConfiguration: 'DyConfiguration'
instance SignQuery DescribeTable where
type ServiceConfiguration DescribeTable = DyConfiguration
signQuery = dySignQuery "DescribeTable"
newtype DescribeTableResult = DescribeTableResult { dtStatus :: TableDescription }
deriving (Show, A.FromJSON)
-- ResponseConsumer can't be derived
instance ResponseConsumer r DescribeTableResult where
type ResponseMetadata DescribeTableResult = DyMetadata
responseConsumer _ _ = dyResponseConsumer
instance AsMemoryResponse DescribeTableResult where
type MemoryResponse DescribeTableResult = TableDescription
loadToMemory = return . dtStatus
instance Transaction DescribeTable DescribeTableResult
data UpdateTable
= UpdateTable {
updateTableName :: T.Text
, updateProvisionedThroughput :: ProvisionedThroughput
, updateGlobalSecondaryIndexUpdates :: [GlobalSecondaryIndexUpdate]
}
deriving (Show, Generic)
instance A.ToJSON UpdateTable where
toJSON = A.genericToJSON $ dropOpt 6
-- | ServiceConfiguration: 'DyConfiguration'
instance SignQuery UpdateTable where
type ServiceConfiguration UpdateTable = DyConfiguration
signQuery = dySignQuery "UpdateTable"
newtype UpdateTableResult = UpdateTableResult { uStatus :: TableDescription }
deriving (Show, A.FromJSON)
-- ResponseConsumer can't be derived
instance ResponseConsumer r UpdateTableResult where
type ResponseMetadata UpdateTableResult = DyMetadata
responseConsumer _ _ = dyResponseConsumer
instance AsMemoryResponse UpdateTableResult where
type MemoryResponse UpdateTableResult = TableDescription
loadToMemory = return . uStatus
instance Transaction UpdateTable UpdateTableResult
data DeleteTable
= DeleteTable {
deleteTableName :: T.Text
}
deriving (Show, Generic)
instance A.ToJSON DeleteTable where
toJSON = A.genericToJSON $ dropOpt 6
-- | ServiceConfiguration: 'DyConfiguration'
instance SignQuery DeleteTable where
type ServiceConfiguration DeleteTable = DyConfiguration
signQuery = dySignQuery "DeleteTable"
newtype DeleteTableResult = DeleteTableResult { dStatus :: TableDescription }
deriving (Show, A.FromJSON)
-- ResponseConsumer can't be derived
instance ResponseConsumer r DeleteTableResult where
type ResponseMetadata DeleteTableResult = DyMetadata
responseConsumer _ _ = dyResponseConsumer
instance AsMemoryResponse DeleteTableResult where
type MemoryResponse DeleteTableResult = TableDescription
loadToMemory = return . dStatus
instance Transaction DeleteTable DeleteTableResult
-- | TODO: currently this does not support restarting a cutoff query because of size.
data ListTables = ListTables
deriving (Show)
instance A.ToJSON ListTables where
toJSON _ = A.object []
-- | ServiceConfiguration: 'DyConfiguration'
instance SignQuery ListTables where
type ServiceConfiguration ListTables = DyConfiguration
signQuery = dySignQuery "ListTables"
newtype ListTablesResult
= ListTablesResult {
tableNames :: [T.Text]
}
deriving (Show, Generic)
instance A.FromJSON ListTablesResult where
parseJSON = A.genericParseJSON capitalizeOpt
instance ResponseConsumer r ListTablesResult where
type ResponseMetadata ListTablesResult = DyMetadata
responseConsumer _ _ = dyResponseConsumer
instance AsMemoryResponse ListTablesResult where
type MemoryResponse ListTablesResult = [T.Text]
loadToMemory = return . tableNames
instance Transaction ListTables ListTablesResult
|
RayRacine/aws
|
Aws/DynamoDb/Commands/Table.hs
|
bsd-3-clause
| 17,659 | 0 | 30 | 4,619 | 3,334 | 1,849 | 1,485 | -1 | -1 |
{-# LANGUAGE CPP, GADTs, NondecreasingIndentation #-}
-----------------------------------------------------------------------------
--
-- Generating machine code (instruction selection)
--
-- (c) The University of Glasgow 1996-2004
--
-----------------------------------------------------------------------------
-- This is a big module, but, if you pay attention to
-- (a) the sectioning, and (b) the type signatures, the
-- structure should not be too overwhelming.
module X86.CodeGen (
cmmTopCodeGen,
generateJumpTableForInstr,
InstrBlock
)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
#include "../includes/MachDeps.h"
-- NCG stuff:
import X86.Instr
import X86.Cond
import X86.Regs
import X86.RegInfo
import CodeGen.Platform
import CPrim
import Instruction
import PIC
import NCGMonad
import Size
import Reg
import Platform
-- Our intermediate code:
import BasicTypes
import BlockId
import Module ( primPackageKey )
import PprCmm ()
import CmmUtils
import Cmm
import Hoopl
import CLabel
-- The rest:
import ForeignCall ( CCallConv(..) )
import OrdList
import Outputable
import Unique
import FastString
import FastBool ( isFastTrue )
import DynFlags
import Util
import Control.Monad
import Data.Bits
import Data.Int
import Data.Maybe
import Data.Word
is32BitPlatform :: NatM Bool
is32BitPlatform = do
dflags <- getDynFlags
return $ target32Bit (targetPlatform dflags)
sse2Enabled :: NatM Bool
sse2Enabled = do
dflags <- getDynFlags
return (isSse2Enabled dflags)
sse4_2Enabled :: NatM Bool
sse4_2Enabled = do
dflags <- getDynFlags
return (isSse4_2Enabled dflags)
if_sse2 :: NatM a -> NatM a -> NatM a
if_sse2 sse2 x87 = do
b <- sse2Enabled
if b then sse2 else x87
cmmTopCodeGen
:: RawCmmDecl
-> NatM [NatCmmDecl (Alignment, CmmStatics) Instr]
cmmTopCodeGen (CmmProc info lab live graph) = do
let blocks = toBlockListEntryFirst graph
(nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks
picBaseMb <- getPicBaseMaybeNat
dflags <- getDynFlags
let proc = CmmProc info lab live (ListGraph $ concat nat_blocks)
tops = proc : concat statics
os = platformOS $ targetPlatform dflags
case picBaseMb of
Just picBase -> initializePicBase_x86 ArchX86 os picBase tops
Nothing -> return tops
cmmTopCodeGen (CmmData sec dat) = do
return [CmmData sec (1, dat)] -- no translation, we just use CmmStatic
basicBlockCodeGen
:: CmmBlock
-> NatM ( [NatBasicBlock Instr]
, [NatCmmDecl (Alignment, CmmStatics) Instr])
basicBlockCodeGen block = do
let (CmmEntry id, nodes, tail) = blockSplit block
stmts = blockToList nodes
mid_instrs <- stmtsToInstrs stmts
tail_instrs <- stmtToInstrs tail
let instrs = mid_instrs `appOL` tail_instrs
-- code generation may introduce new basic block boundaries, which
-- are indicated by the NEWBLOCK instruction. We must split up the
-- instruction stream into basic blocks again. Also, we extract
-- LDATAs here too.
let
(top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs
mkBlocks (NEWBLOCK id) (instrs,blocks,statics)
= ([], BasicBlock id instrs : blocks, statics)
mkBlocks (LDATA sec dat) (instrs,blocks,statics)
= (instrs, blocks, CmmData sec dat:statics)
mkBlocks instr (instrs,blocks,statics)
= (instr:instrs, blocks, statics)
return (BasicBlock id top : other_blocks, statics)
stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock
stmtsToInstrs stmts
= do instrss <- mapM stmtToInstrs stmts
return (concatOL instrss)
stmtToInstrs :: CmmNode e x -> NatM InstrBlock
stmtToInstrs stmt = do
dflags <- getDynFlags
is32Bit <- is32BitPlatform
case stmt of
CmmComment s -> return (unitOL (COMMENT s))
CmmAssign reg src
| isFloatType ty -> assignReg_FltCode size reg src
| is32Bit && isWord64 ty -> assignReg_I64Code reg src
| otherwise -> assignReg_IntCode size reg src
where ty = cmmRegType dflags reg
size = cmmTypeSize ty
CmmStore addr src
| isFloatType ty -> assignMem_FltCode size addr src
| is32Bit && isWord64 ty -> assignMem_I64Code addr src
| otherwise -> assignMem_IntCode size addr src
where ty = cmmExprType dflags src
size = cmmTypeSize ty
CmmUnsafeForeignCall target result_regs args
-> genCCall dflags is32Bit target result_regs args
CmmBranch id -> genBranch id
CmmCondBranch arg true false -> do b1 <- genCondJump true arg
b2 <- genBranch false
return (b1 `appOL` b2)
CmmSwitch arg ids -> do dflags <- getDynFlags
genSwitch dflags arg ids
CmmCall { cml_target = arg
, cml_args_regs = gregs } -> do
dflags <- getDynFlags
genJump arg (jumpRegs dflags gregs)
_ ->
panic "stmtToInstrs: statement should have been cps'd away"
jumpRegs :: DynFlags -> [GlobalReg] -> [Reg]
jumpRegs dflags gregs = [ RegReal r | Just r <- map (globalRegMaybe platform) gregs ]
where platform = targetPlatform dflags
--------------------------------------------------------------------------------
-- | 'InstrBlock's are the insn sequences generated by the insn selectors.
-- They are really trees of insns to facilitate fast appending, where a
-- left-to-right traversal yields the insns in the correct order.
--
type InstrBlock
= OrdList Instr
-- | Condition codes passed up the tree.
--
data CondCode
= CondCode Bool Cond InstrBlock
-- | a.k.a "Register64"
-- Reg is the lower 32-bit temporary which contains the result.
-- Use getHiVRegFromLo to find the other VRegUnique.
--
-- Rules of this simplified insn selection game are therefore that
-- the returned Reg may be modified
--
data ChildCode64
= ChildCode64
InstrBlock
Reg
-- | Register's passed up the tree. If the stix code forces the register
-- to live in a pre-decided machine register, it comes out as @Fixed@;
-- otherwise, it comes out as @Any@, and the parent can decide which
-- register to put it in.
--
data Register
= Fixed Size Reg InstrBlock
| Any Size (Reg -> InstrBlock)
swizzleRegisterRep :: Register -> Size -> Register
swizzleRegisterRep (Fixed _ reg code) size = Fixed size reg code
swizzleRegisterRep (Any _ codefn) size = Any size codefn
-- | Grab the Reg for a CmmReg
getRegisterReg :: Platform -> Bool -> CmmReg -> Reg
getRegisterReg _ use_sse2 (CmmLocal (LocalReg u pk))
= let sz = cmmTypeSize pk in
if isFloatSize sz && not use_sse2
then RegVirtual (mkVirtualReg u FF80)
else RegVirtual (mkVirtualReg u sz)
getRegisterReg platform _ (CmmGlobal mid)
= case globalRegMaybe platform mid of
Just reg -> RegReal $ reg
Nothing -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid)
-- By this stage, the only MagicIds remaining should be the
-- ones which map to a real machine register on this
-- platform. Hence ...
-- | Memory addressing modes passed up the tree.
data Amode
= Amode AddrMode InstrBlock
{-
Now, given a tree (the argument to an CmmLoad) that references memory,
produce a suitable addressing mode.
A Rule of the Game (tm) for Amodes: use of the addr bit must
immediately follow use of the code part, since the code part puts
values in registers which the addr then refers to. So you can't put
anything in between, lest it overwrite some of those registers. If
you need to do some other computation between the code part and use of
the addr bit, first store the effective address from the amode in a
temporary, then do the other computation, and then use the temporary:
code
LEA amode, tmp
... other computation ...
... (tmp) ...
-}
-- | Check whether an integer will fit in 32 bits.
-- A CmmInt is intended to be truncated to the appropriate
-- number of bits, so here we truncate it to Int64. This is
-- important because e.g. -1 as a CmmInt might be either
-- -1 or 18446744073709551615.
--
is32BitInteger :: Integer -> Bool
is32BitInteger i = i64 <= 0x7fffffff && i64 >= -0x80000000
where i64 = fromIntegral i :: Int64
-- | Convert a BlockId to some CmmStatic data
jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic
jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel)
where blockLabel = mkAsmTempLabel (getUnique blockid)
-- -----------------------------------------------------------------------------
-- General things for putting together code sequences
-- Expand CmmRegOff. ToDo: should we do it this way around, or convert
-- CmmExprs into CmmRegOff?
mangleIndexTree :: DynFlags -> CmmReg -> Int -> CmmExpr
mangleIndexTree dflags reg off
= CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)]
where width = typeWidth (cmmRegType dflags reg)
-- | The dual to getAnyReg: compute an expression into a register, but
-- we don't mind which one it is.
getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock)
getSomeReg expr = do
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed _ reg code ->
return (reg, code)
assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock
assignMem_I64Code addrTree valueTree = do
Amode addr addr_code <- getAmode addrTree
ChildCode64 vcode rlo <- iselExpr64 valueTree
let
rhi = getHiVRegFromLo rlo
-- Little-endian store
mov_lo = MOV II32 (OpReg rlo) (OpAddr addr)
mov_hi = MOV II32 (OpReg rhi) (OpAddr (fromJust (addrOffset addr 4)))
return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi)
assignReg_I64Code :: CmmReg -> CmmExpr -> NatM InstrBlock
assignReg_I64Code (CmmLocal (LocalReg u_dst _)) valueTree = do
ChildCode64 vcode r_src_lo <- iselExpr64 valueTree
let
r_dst_lo = RegVirtual $ mkVirtualReg u_dst II32
r_dst_hi = getHiVRegFromLo r_dst_lo
r_src_hi = getHiVRegFromLo r_src_lo
mov_lo = MOV II32 (OpReg r_src_lo) (OpReg r_dst_lo)
mov_hi = MOV II32 (OpReg r_src_hi) (OpReg r_dst_hi)
return (
vcode `snocOL` mov_lo `snocOL` mov_hi
)
assignReg_I64Code _ _
= panic "assignReg_I64Code(i386): invalid lvalue"
iselExpr64 :: CmmExpr -> NatM ChildCode64
iselExpr64 (CmmLit (CmmInt i _)) = do
(rlo,rhi) <- getNewRegPairNat II32
let
r = fromIntegral (fromIntegral i :: Word32)
q = fromIntegral (fromIntegral (i `shiftR` 32) :: Word32)
code = toOL [
MOV II32 (OpImm (ImmInteger r)) (OpReg rlo),
MOV II32 (OpImm (ImmInteger q)) (OpReg rhi)
]
return (ChildCode64 code rlo)
iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do
Amode addr addr_code <- getAmode addrTree
(rlo,rhi) <- getNewRegPairNat II32
let
mov_lo = MOV II32 (OpAddr addr) (OpReg rlo)
mov_hi = MOV II32 (OpAddr (fromJust (addrOffset addr 4))) (OpReg rhi)
return (
ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi)
rlo
)
iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty
= return (ChildCode64 nilOL (RegVirtual $ mkVirtualReg vu II32))
-- we handle addition, but rather badly
iselExpr64 (CmmMachOp (MO_Add _) [e1, CmmLit (CmmInt i _)]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
(rlo,rhi) <- getNewRegPairNat II32
let
r = fromIntegral (fromIntegral i :: Word32)
q = fromIntegral (fromIntegral (i `shiftR` 32) :: Word32)
r1hi = getHiVRegFromLo r1lo
code = code1 `appOL`
toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
ADD II32 (OpImm (ImmInteger r)) (OpReg rlo),
MOV II32 (OpReg r1hi) (OpReg rhi),
ADC II32 (OpImm (ImmInteger q)) (OpReg rhi) ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do
ChildCode64 code1 r1lo <- iselExpr64 e1
ChildCode64 code2 r2lo <- iselExpr64 e2
(rlo,rhi) <- getNewRegPairNat II32
let
r1hi = getHiVRegFromLo r1lo
r2hi = getHiVRegFromLo r2lo
code = code1 `appOL`
code2 `appOL`
toOL [ MOV II32 (OpReg r1lo) (OpReg rlo),
ADD II32 (OpReg r2lo) (OpReg rlo),
MOV II32 (OpReg r1hi) (OpReg rhi),
ADC II32 (OpReg r2hi) (OpReg rhi) ]
return (ChildCode64 code rlo)
iselExpr64 (CmmMachOp (MO_UU_Conv _ W64) [expr]) = do
fn <- getAnyReg expr
r_dst_lo <- getNewRegNat II32
let r_dst_hi = getHiVRegFromLo r_dst_lo
code = fn r_dst_lo
return (
ChildCode64 (code `snocOL`
MOV II32 (OpImm (ImmInt 0)) (OpReg r_dst_hi))
r_dst_lo
)
iselExpr64 expr
= pprPanic "iselExpr64(i386)" (ppr expr)
--------------------------------------------------------------------------------
getRegister :: CmmExpr -> NatM Register
getRegister e = do dflags <- getDynFlags
is32Bit <- is32BitPlatform
getRegister' dflags is32Bit e
getRegister' :: DynFlags -> Bool -> CmmExpr -> NatM Register
getRegister' dflags is32Bit (CmmReg reg)
= case reg of
CmmGlobal PicBaseReg
| is32Bit ->
-- on x86_64, we have %rip for PicBaseReg, but it's not
-- a full-featured register, it can only be used for
-- rip-relative addressing.
do reg' <- getPicBaseNat (archWordSize is32Bit)
return (Fixed (archWordSize is32Bit) reg' nilOL)
_ ->
do use_sse2 <- sse2Enabled
let
sz = cmmTypeSize (cmmRegType dflags reg)
size | not use_sse2 && isFloatSize sz = FF80
| otherwise = sz
--
let platform = targetPlatform dflags
return (Fixed size (getRegisterReg platform use_sse2 reg) nilOL)
getRegister' dflags is32Bit (CmmRegOff r n)
= getRegister' dflags is32Bit $ mangleIndexTree dflags r n
-- for 32-bit architectuers, support some 64 -> 32 bit conversions:
-- TO_W_(x), TO_W_(x >> 32)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W64 W32)
[CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 (getHiVRegFromLo rlo) code
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W64 W32) [x])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W64 W32) [x])
| is32Bit = do
ChildCode64 code rlo <- iselExpr64 x
return $ Fixed II32 rlo code
getRegister' _ _ (CmmLit lit@(CmmFloat f w)) =
if_sse2 float_const_sse2 float_const_x87
where
float_const_sse2
| f == 0.0 = do
let
size = floatSize w
code dst = unitOL (XOR size (OpReg dst) (OpReg dst))
-- I don't know why there are xorpd, xorps, and pxor instructions.
-- They all appear to do the same thing --SDM
return (Any size code)
| otherwise = do
Amode addr code <- memConstant (widthInBytes w) lit
loadFloatAmode True w addr code
float_const_x87 = case w of
W64
| f == 0.0 ->
let code dst = unitOL (GLDZ dst)
in return (Any FF80 code)
| f == 1.0 ->
let code dst = unitOL (GLD1 dst)
in return (Any FF80 code)
_otherwise -> do
Amode addr code <- memConstant (widthInBytes w) lit
loadFloatAmode False w addr code
-- catch simple cases of zero- or sign-extended load
getRegister' _ _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVZxL II8) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_SS_Conv W8 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVSxL II8) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVZxL II16) addr
return (Any II32 code)
getRegister' _ _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad addr _]) = do
code <- intLoadCode (MOVSxL II16) addr
return (Any II32 code)
-- catch simple cases of zero- or sign-extended load
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVZxL II8) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W8 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II8) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVZxL II16) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II16) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOV II32) addr -- 32-bit loads zero-extend
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad addr _])
| not is32Bit = do
code <- intLoadCode (MOVSxL II32) addr
return (Any II64 code)
getRegister' _ is32Bit (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg),
CmmLit displacement])
| not is32Bit = do
return $ Any II64 (\dst -> unitOL $
LEA II64 (OpAddr (ripRel (litToImm displacement))) (OpReg dst))
getRegister' dflags is32Bit (CmmMachOp mop [x]) = do -- unary MachOps
sse2 <- sse2Enabled
case mop of
MO_F_Neg w
| sse2 -> sse2NegCode w x
| otherwise -> trivialUFCode FF80 (GNEG FF80) x
MO_S_Neg w -> triv_ucode NEGI (intSize w)
MO_Not w -> triv_ucode NOT (intSize w)
-- Nop conversions
MO_UU_Conv W32 W8 -> toI8Reg W32 x
MO_SS_Conv W32 W8 -> toI8Reg W32 x
MO_UU_Conv W16 W8 -> toI8Reg W16 x
MO_SS_Conv W16 W8 -> toI8Reg W16 x
MO_UU_Conv W32 W16 -> toI16Reg W32 x
MO_SS_Conv W32 W16 -> toI16Reg W32 x
MO_UU_Conv W64 W32 | not is32Bit -> conversionNop II64 x
MO_SS_Conv W64 W32 | not is32Bit -> conversionNop II64 x
MO_UU_Conv W64 W16 | not is32Bit -> toI16Reg W64 x
MO_SS_Conv W64 W16 | not is32Bit -> toI16Reg W64 x
MO_UU_Conv W64 W8 | not is32Bit -> toI8Reg W64 x
MO_SS_Conv W64 W8 | not is32Bit -> toI8Reg W64 x
MO_UU_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intSize rep1) x
MO_SS_Conv rep1 rep2 | rep1 == rep2 -> conversionNop (intSize rep1) x
-- widenings
MO_UU_Conv W8 W32 -> integerExtend W8 W32 MOVZxL x
MO_UU_Conv W16 W32 -> integerExtend W16 W32 MOVZxL x
MO_UU_Conv W8 W16 -> integerExtend W8 W16 MOVZxL x
MO_SS_Conv W8 W32 -> integerExtend W8 W32 MOVSxL x
MO_SS_Conv W16 W32 -> integerExtend W16 W32 MOVSxL x
MO_SS_Conv W8 W16 -> integerExtend W8 W16 MOVSxL x
MO_UU_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOVZxL x
MO_UU_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOVZxL x
MO_UU_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOVZxL x
MO_SS_Conv W8 W64 | not is32Bit -> integerExtend W8 W64 MOVSxL x
MO_SS_Conv W16 W64 | not is32Bit -> integerExtend W16 W64 MOVSxL x
MO_SS_Conv W32 W64 | not is32Bit -> integerExtend W32 W64 MOVSxL x
-- for 32-to-64 bit zero extension, amd64 uses an ordinary movl.
-- However, we don't want the register allocator to throw it
-- away as an unnecessary reg-to-reg move, so we keep it in
-- the form of a movzl and print it as a movl later.
MO_FF_Conv W32 W64
| sse2 -> coerceFP2FP W64 x
| otherwise -> conversionNop FF80 x
MO_FF_Conv W64 W32 -> coerceFP2FP W32 x
MO_FS_Conv from to -> coerceFP2Int from to x
MO_SF_Conv from to -> coerceInt2FP from to x
MO_V_Insert {} -> needLlvm
MO_V_Extract {} -> needLlvm
MO_V_Add {} -> needLlvm
MO_V_Sub {} -> needLlvm
MO_V_Mul {} -> needLlvm
MO_VS_Quot {} -> needLlvm
MO_VS_Rem {} -> needLlvm
MO_VS_Neg {} -> needLlvm
MO_VU_Quot {} -> needLlvm
MO_VU_Rem {} -> needLlvm
MO_VF_Insert {} -> needLlvm
MO_VF_Extract {} -> needLlvm
MO_VF_Add {} -> needLlvm
MO_VF_Sub {} -> needLlvm
MO_VF_Mul {} -> needLlvm
MO_VF_Quot {} -> needLlvm
MO_VF_Neg {} -> needLlvm
_other -> pprPanic "getRegister" (pprMachOp mop)
where
triv_ucode :: (Size -> Operand -> Instr) -> Size -> NatM Register
triv_ucode instr size = trivialUCode size (instr size) x
-- signed or unsigned extension.
integerExtend :: Width -> Width
-> (Size -> Operand -> Operand -> Instr)
-> CmmExpr -> NatM Register
integerExtend from to instr expr = do
(reg,e_code) <- if from == W8 then getByteReg expr
else getSomeReg expr
let
code dst =
e_code `snocOL`
instr (intSize from) (OpReg reg) (OpReg dst)
return (Any (intSize to) code)
toI8Reg :: Width -> CmmExpr -> NatM Register
toI8Reg new_rep expr
= do codefn <- getAnyReg expr
return (Any (intSize new_rep) codefn)
-- HACK: use getAnyReg to get a byte-addressable register.
-- If the source was a Fixed register, this will add the
-- mov instruction to put it into the desired destination.
-- We're assuming that the destination won't be a fixed
-- non-byte-addressable register; it won't be, because all
-- fixed registers are word-sized.
toI16Reg = toI8Reg -- for now
conversionNop :: Size -> CmmExpr -> NatM Register
conversionNop new_size expr
= do e_code <- getRegister' dflags is32Bit expr
return (swizzleRegisterRep e_code new_size)
getRegister' _ is32Bit (CmmMachOp mop [x, y]) = do -- dyadic MachOps
sse2 <- sse2Enabled
case mop of
MO_F_Eq _ -> condFltReg is32Bit EQQ x y
MO_F_Ne _ -> condFltReg is32Bit NE x y
MO_F_Gt _ -> condFltReg is32Bit GTT x y
MO_F_Ge _ -> condFltReg is32Bit GE x y
MO_F_Lt _ -> condFltReg is32Bit LTT x y
MO_F_Le _ -> condFltReg is32Bit LE x y
MO_Eq _ -> condIntReg EQQ x y
MO_Ne _ -> condIntReg NE x y
MO_S_Gt _ -> condIntReg GTT x y
MO_S_Ge _ -> condIntReg GE x y
MO_S_Lt _ -> condIntReg LTT x y
MO_S_Le _ -> condIntReg LE x y
MO_U_Gt _ -> condIntReg GU x y
MO_U_Ge _ -> condIntReg GEU x y
MO_U_Lt _ -> condIntReg LU x y
MO_U_Le _ -> condIntReg LEU x y
MO_F_Add w | sse2 -> trivialFCode_sse2 w ADD x y
| otherwise -> trivialFCode_x87 GADD x y
MO_F_Sub w | sse2 -> trivialFCode_sse2 w SUB x y
| otherwise -> trivialFCode_x87 GSUB x y
MO_F_Quot w | sse2 -> trivialFCode_sse2 w FDIV x y
| otherwise -> trivialFCode_x87 GDIV x y
MO_F_Mul w | sse2 -> trivialFCode_sse2 w MUL x y
| otherwise -> trivialFCode_x87 GMUL x y
MO_Add rep -> add_code rep x y
MO_Sub rep -> sub_code rep x y
MO_S_Quot rep -> div_code rep True True x y
MO_S_Rem rep -> div_code rep True False x y
MO_U_Quot rep -> div_code rep False True x y
MO_U_Rem rep -> div_code rep False False x y
MO_S_MulMayOflo rep -> imulMayOflo rep x y
MO_Mul rep -> triv_op rep IMUL
MO_And rep -> triv_op rep AND
MO_Or rep -> triv_op rep OR
MO_Xor rep -> triv_op rep XOR
{- Shift ops on x86s have constraints on their source, it
either has to be Imm, CL or 1
=> trivialCode is not restrictive enough (sigh.)
-}
MO_Shl rep -> shift_code rep SHL x y {-False-}
MO_U_Shr rep -> shift_code rep SHR x y {-False-}
MO_S_Shr rep -> shift_code rep SAR x y {-False-}
MO_V_Insert {} -> needLlvm
MO_V_Extract {} -> needLlvm
MO_V_Add {} -> needLlvm
MO_V_Sub {} -> needLlvm
MO_V_Mul {} -> needLlvm
MO_VS_Quot {} -> needLlvm
MO_VS_Rem {} -> needLlvm
MO_VS_Neg {} -> needLlvm
MO_VF_Insert {} -> needLlvm
MO_VF_Extract {} -> needLlvm
MO_VF_Add {} -> needLlvm
MO_VF_Sub {} -> needLlvm
MO_VF_Mul {} -> needLlvm
MO_VF_Quot {} -> needLlvm
MO_VF_Neg {} -> needLlvm
_other -> pprPanic "getRegister(x86) - binary CmmMachOp (1)" (pprMachOp mop)
where
--------------------
triv_op width instr = trivialCode width op (Just op) x y
where op = instr (intSize width)
imulMayOflo :: Width -> CmmExpr -> CmmExpr -> NatM Register
imulMayOflo rep a b = do
(a_reg, a_code) <- getNonClobberedReg a
b_code <- getAnyReg b
let
shift_amt = case rep of
W32 -> 31
W64 -> 63
_ -> panic "shift_amt"
size = intSize rep
code = a_code `appOL` b_code eax `appOL`
toOL [
IMUL2 size (OpReg a_reg), -- result in %edx:%eax
SAR size (OpImm (ImmInt shift_amt)) (OpReg eax),
-- sign extend lower part
SUB size (OpReg edx) (OpReg eax)
-- compare against upper
-- eax==0 if high part == sign extended low part
]
return (Fixed size eax code)
--------------------
shift_code :: Width
-> (Size -> Operand -> Operand -> Instr)
-> CmmExpr
-> CmmExpr
-> NatM Register
{- Case1: shift length as immediate -}
shift_code width instr x (CmmLit lit) = do
x_code <- getAnyReg x
let
size = intSize width
code dst
= x_code dst `snocOL`
instr size (OpImm (litToImm lit)) (OpReg dst)
return (Any size code)
{- Case2: shift length is complex (non-immediate)
* y must go in %ecx.
* we cannot do y first *and* put its result in %ecx, because
%ecx might be clobbered by x.
* if we do y second, then x cannot be
in a clobbered reg. Also, we cannot clobber x's reg
with the instruction itself.
* so we can either:
- do y first, put its result in a fresh tmp, then copy it to %ecx later
- do y second and put its result into %ecx. x gets placed in a fresh
tmp. This is likely to be better, because the reg alloc can
eliminate this reg->reg move here (it won't eliminate the other one,
because the move is into the fixed %ecx).
-}
shift_code width instr x y{-amount-} = do
x_code <- getAnyReg x
let size = intSize width
tmp <- getNewRegNat size
y_code <- getAnyReg y
let
code = x_code tmp `appOL`
y_code ecx `snocOL`
instr size (OpReg ecx) (OpReg tmp)
return (Fixed size tmp code)
--------------------
add_code :: Width -> CmmExpr -> CmmExpr -> NatM Register
add_code rep x (CmmLit (CmmInt y _))
| is32BitInteger y = add_int rep x y
add_code rep x y = trivialCode rep (ADD size) (Just (ADD size)) x y
where size = intSize rep
-- TODO: There are other interesting patterns we want to replace
-- with a LEA, e.g. `(x + offset) + (y << shift)`.
--------------------
sub_code :: Width -> CmmExpr -> CmmExpr -> NatM Register
sub_code rep x (CmmLit (CmmInt y _))
| is32BitInteger (-y) = add_int rep x (-y)
sub_code rep x y = trivialCode rep (SUB (intSize rep)) Nothing x y
-- our three-operand add instruction:
add_int width x y = do
(x_reg, x_code) <- getSomeReg x
let
size = intSize width
imm = ImmInt (fromInteger y)
code dst
= x_code `snocOL`
LEA size
(OpAddr (AddrBaseIndex (EABaseReg x_reg) EAIndexNone imm))
(OpReg dst)
--
return (Any size code)
----------------------
div_code width signed quotient x y = do
(y_op, y_code) <- getRegOrMem y -- cannot be clobbered
x_code <- getAnyReg x
let
size = intSize width
widen | signed = CLTD size
| otherwise = XOR size (OpReg edx) (OpReg edx)
instr | signed = IDIV
| otherwise = DIV
code = y_code `appOL`
x_code eax `appOL`
toOL [widen, instr size y_op]
result | quotient = eax
| otherwise = edx
return (Fixed size result code)
getRegister' _ _ (CmmLoad mem pk)
| isFloatType pk
= do
Amode addr mem_code <- getAmode mem
use_sse2 <- sse2Enabled
loadFloatAmode use_sse2 (typeWidth pk) addr mem_code
getRegister' _ is32Bit (CmmLoad mem pk)
| is32Bit && not (isWord64 pk)
= do
code <- intLoadCode instr mem
return (Any size code)
where
width = typeWidth pk
size = intSize width
instr = case width of
W8 -> MOVZxL II8
_other -> MOV size
-- We always zero-extend 8-bit loads, if we
-- can't think of anything better. This is because
-- we can't guarantee access to an 8-bit variant of every register
-- (esi and edi don't have 8-bit variants), so to make things
-- simpler we do our 8-bit arithmetic with full 32-bit registers.
-- Simpler memory load code on x86_64
getRegister' _ is32Bit (CmmLoad mem pk)
| not is32Bit
= do
code <- intLoadCode (MOV size) mem
return (Any size code)
where size = intSize $ typeWidth pk
getRegister' _ is32Bit (CmmLit (CmmInt 0 width))
= let
size = intSize width
-- x86_64: 32-bit xor is one byte shorter, and zero-extends to 64 bits
size1 = if is32Bit then size
else case size of
II64 -> II32
_ -> size
code dst
= unitOL (XOR size1 (OpReg dst) (OpReg dst))
in
return (Any size code)
-- optimisation for loading small literals on x86_64: take advantage
-- of the automatic zero-extension from 32 to 64 bits, because the 32-bit
-- instruction forms are shorter.
getRegister' dflags is32Bit (CmmLit lit)
| not is32Bit, isWord64 (cmmLitType dflags lit), not (isBigLit lit)
= let
imm = litToImm lit
code dst = unitOL (MOV II32 (OpImm imm) (OpReg dst))
in
return (Any II64 code)
where
isBigLit (CmmInt i _) = i < 0 || i > 0xffffffff
isBigLit _ = False
-- note1: not the same as (not.is32BitLit), because that checks for
-- signed literals that fit in 32 bits, but we want unsigned
-- literals here.
-- note2: all labels are small, because we're assuming the
-- small memory model (see gcc docs, -mcmodel=small).
getRegister' dflags _ (CmmLit lit)
= do let size = cmmTypeSize (cmmLitType dflags lit)
imm = litToImm lit
code dst = unitOL (MOV size (OpImm imm) (OpReg dst))
return (Any size code)
getRegister' _ _ other
| isVecExpr other = needLlvm
| otherwise = pprPanic "getRegister(x86)" (ppr other)
intLoadCode :: (Operand -> Operand -> Instr) -> CmmExpr
-> NatM (Reg -> InstrBlock)
intLoadCode instr mem = do
Amode src mem_code <- getAmode mem
return (\dst -> mem_code `snocOL` instr (OpAddr src) (OpReg dst))
-- Compute an expression into *any* register, adding the appropriate
-- move instruction if necessary.
getAnyReg :: CmmExpr -> NatM (Reg -> InstrBlock)
getAnyReg expr = do
r <- getRegister expr
anyReg r
anyReg :: Register -> NatM (Reg -> InstrBlock)
anyReg (Any _ code) = return code
anyReg (Fixed rep reg fcode) = return (\dst -> fcode `snocOL` reg2reg rep reg dst)
-- A bit like getSomeReg, but we want a reg that can be byte-addressed.
-- Fixed registers might not be byte-addressable, so we make sure we've
-- got a temporary, inserting an extra reg copy if necessary.
getByteReg :: CmmExpr -> NatM (Reg, InstrBlock)
getByteReg expr = do
is32Bit <- is32BitPlatform
if is32Bit
then do r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed rep reg code
| isVirtualReg reg -> return (reg,code)
| otherwise -> do
tmp <- getNewRegNat rep
return (tmp, code `snocOL` reg2reg rep reg tmp)
-- ToDo: could optimise slightly by checking for
-- byte-addressable real registers, but that will
-- happen very rarely if at all.
else getSomeReg expr -- all regs are byte-addressable on x86_64
-- Another variant: this time we want the result in a register that cannot
-- be modified by code to evaluate an arbitrary expression.
getNonClobberedReg :: CmmExpr -> NatM (Reg, InstrBlock)
getNonClobberedReg expr = do
dflags <- getDynFlags
r <- getRegister expr
case r of
Any rep code -> do
tmp <- getNewRegNat rep
return (tmp, code tmp)
Fixed rep reg code
-- only certain regs can be clobbered
| reg `elem` instrClobberedRegs (targetPlatform dflags)
-> do
tmp <- getNewRegNat rep
return (tmp, code `snocOL` reg2reg rep reg tmp)
| otherwise ->
return (reg, code)
reg2reg :: Size -> Reg -> Reg -> Instr
reg2reg size src dst
| size == FF80 = GMOV src dst
| otherwise = MOV size (OpReg src) (OpReg dst)
--------------------------------------------------------------------------------
getAmode :: CmmExpr -> NatM Amode
getAmode e = do is32Bit <- is32BitPlatform
getAmode' is32Bit e
getAmode' :: Bool -> CmmExpr -> NatM Amode
getAmode' _ (CmmRegOff r n) = do dflags <- getDynFlags
getAmode $ mangleIndexTree dflags r n
getAmode' is32Bit (CmmMachOp (MO_Add W64) [CmmReg (CmmGlobal PicBaseReg),
CmmLit displacement])
| not is32Bit
= return $ Amode (ripRel (litToImm displacement)) nilOL
-- This is all just ridiculous, since it carefully undoes
-- what mangleIndexTree has just done.
getAmode' is32Bit (CmmMachOp (MO_Sub _rep) [x, CmmLit lit@(CmmInt i _)])
| is32BitLit is32Bit lit
-- ASSERT(rep == II32)???
= do (x_reg, x_code) <- getSomeReg x
let off = ImmInt (-(fromInteger i))
return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
getAmode' is32Bit (CmmMachOp (MO_Add _rep) [x, CmmLit lit])
| is32BitLit is32Bit lit
-- ASSERT(rep == II32)???
= do (x_reg, x_code) <- getSomeReg x
let off = litToImm lit
return (Amode (AddrBaseIndex (EABaseReg x_reg) EAIndexNone off) x_code)
-- Turn (lit1 << n + lit2) into (lit2 + lit1 << n) so it will be
-- recognised by the next rule.
getAmode' is32Bit (CmmMachOp (MO_Add rep) [a@(CmmMachOp (MO_Shl _) _),
b@(CmmLit _)])
= getAmode' is32Bit (CmmMachOp (MO_Add rep) [b,a])
-- Matches: (x + offset) + (y << shift)
getAmode' _ (CmmMachOp (MO_Add _) [CmmRegOff x offset,
CmmMachOp (MO_Shl _)
[y, CmmLit (CmmInt shift _)]])
| shift == 0 || shift == 1 || shift == 2 || shift == 3
= x86_complex_amode (CmmReg x) y shift (fromIntegral offset)
getAmode' _ (CmmMachOp (MO_Add _) [x, CmmMachOp (MO_Shl _)
[y, CmmLit (CmmInt shift _)]])
| shift == 0 || shift == 1 || shift == 2 || shift == 3
= x86_complex_amode x y shift 0
getAmode' _ (CmmMachOp (MO_Add _)
[x, CmmMachOp (MO_Add _)
[CmmMachOp (MO_Shl _) [y, CmmLit (CmmInt shift _)],
CmmLit (CmmInt offset _)]])
| shift == 0 || shift == 1 || shift == 2 || shift == 3
&& is32BitInteger offset
= x86_complex_amode x y shift offset
getAmode' _ (CmmMachOp (MO_Add _) [x,y])
= x86_complex_amode x y 0 0
getAmode' is32Bit (CmmLit lit) | is32BitLit is32Bit lit
= return (Amode (ImmAddr (litToImm lit) 0) nilOL)
getAmode' _ expr = do
(reg,code) <- getSomeReg expr
return (Amode (AddrBaseIndex (EABaseReg reg) EAIndexNone (ImmInt 0)) code)
-- | Like 'getAmode', but on 32-bit use simple register addressing
-- (i.e. no index register). This stops us from running out of
-- registers on x86 when using instructions such as cmpxchg, which can
-- use up to three virtual registers and one fixed register.
getSimpleAmode :: DynFlags -> Bool -> CmmExpr -> NatM Amode
getSimpleAmode dflags is32Bit addr
| is32Bit = do
addr_code <- getAnyReg addr
addr_r <- getNewRegNat (intSize (wordWidth dflags))
let amode = AddrBaseIndex (EABaseReg addr_r) EAIndexNone (ImmInt 0)
return $! Amode amode (addr_code addr_r)
| otherwise = getAmode addr
x86_complex_amode :: CmmExpr -> CmmExpr -> Integer -> Integer -> NatM Amode
x86_complex_amode base index shift offset
= do (x_reg, x_code) <- getNonClobberedReg base
-- x must be in a temp, because it has to stay live over y_code
-- we could compre x_reg and y_reg and do something better here...
(y_reg, y_code) <- getSomeReg index
let
code = x_code `appOL` y_code
base = case shift of 0 -> 1; 1 -> 2; 2 -> 4; 3 -> 8;
n -> panic $ "x86_complex_amode: unhandled shift! (" ++ show n ++ ")"
return (Amode (AddrBaseIndex (EABaseReg x_reg) (EAIndex y_reg base) (ImmInt (fromIntegral offset)))
code)
-- -----------------------------------------------------------------------------
-- getOperand: sometimes any operand will do.
-- getNonClobberedOperand: the value of the operand will remain valid across
-- the computation of an arbitrary expression, unless the expression
-- is computed directly into a register which the operand refers to
-- (see trivialCode where this function is used for an example).
getNonClobberedOperand :: CmmExpr -> NatM (Operand, InstrBlock)
getNonClobberedOperand (CmmLit lit) = do
use_sse2 <- sse2Enabled
if use_sse2 && isSuitableFloatingPointLit lit
then do
let CmmFloat _ w = lit
Amode addr code <- memConstant (widthInBytes w) lit
return (OpAddr addr, code)
else do
is32Bit <- is32BitPlatform
dflags <- getDynFlags
if is32BitLit is32Bit lit && not (isFloatType (cmmLitType dflags lit))
then return (OpImm (litToImm lit), nilOL)
else getNonClobberedOperand_generic (CmmLit lit)
getNonClobberedOperand (CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2)
&& (if is32Bit then not (isWord64 pk) else True)
then do
dflags <- getDynFlags
let platform = targetPlatform dflags
Amode src mem_code <- getAmode mem
(src',save_code) <-
if (amodeCouldBeClobbered platform src)
then do
tmp <- getNewRegNat (archWordSize is32Bit)
return (AddrBaseIndex (EABaseReg tmp) EAIndexNone (ImmInt 0),
unitOL (LEA (archWordSize is32Bit) (OpAddr src) (OpReg tmp)))
else
return (src, nilOL)
return (OpAddr src', mem_code `appOL` save_code)
else do
getNonClobberedOperand_generic (CmmLoad mem pk)
getNonClobberedOperand e = getNonClobberedOperand_generic e
getNonClobberedOperand_generic :: CmmExpr -> NatM (Operand, InstrBlock)
getNonClobberedOperand_generic e = do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
amodeCouldBeClobbered :: Platform -> AddrMode -> Bool
amodeCouldBeClobbered platform amode = any (regClobbered platform) (addrModeRegs amode)
regClobbered :: Platform -> Reg -> Bool
regClobbered platform (RegReal (RealRegSingle rr)) = isFastTrue (freeReg platform rr)
regClobbered _ _ = False
-- getOperand: the operand is not required to remain valid across the
-- computation of an arbitrary expression.
getOperand :: CmmExpr -> NatM (Operand, InstrBlock)
getOperand (CmmLit lit) = do
use_sse2 <- sse2Enabled
if (use_sse2 && isSuitableFloatingPointLit lit)
then do
let CmmFloat _ w = lit
Amode addr code <- memConstant (widthInBytes w) lit
return (OpAddr addr, code)
else do
is32Bit <- is32BitPlatform
dflags <- getDynFlags
if is32BitLit is32Bit lit && not (isFloatType (cmmLitType dflags lit))
then return (OpImm (litToImm lit), nilOL)
else getOperand_generic (CmmLit lit)
getOperand (CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True)
then do
Amode src mem_code <- getAmode mem
return (OpAddr src, mem_code)
else
getOperand_generic (CmmLoad mem pk)
getOperand e = getOperand_generic e
getOperand_generic :: CmmExpr -> NatM (Operand, InstrBlock)
getOperand_generic e = do
(reg, code) <- getSomeReg e
return (OpReg reg, code)
isOperand :: Bool -> CmmExpr -> Bool
isOperand _ (CmmLoad _ _) = True
isOperand is32Bit (CmmLit lit) = is32BitLit is32Bit lit
|| isSuitableFloatingPointLit lit
isOperand _ _ = False
memConstant :: Int -> CmmLit -> NatM Amode
memConstant align lit = do
lbl <- getNewLabelNat
dflags <- getDynFlags
(addr, addr_code) <- if target32Bit (targetPlatform dflags)
then do dynRef <- cmmMakeDynamicReference
dflags
DataReference
lbl
Amode addr addr_code <- getAmode dynRef
return (addr, addr_code)
else return (ripRel (ImmCLbl lbl), nilOL)
let code =
LDATA ReadOnlyData (align, Statics lbl [CmmStaticLit lit])
`consOL` addr_code
return (Amode addr code)
loadFloatAmode :: Bool -> Width -> AddrMode -> InstrBlock -> NatM Register
loadFloatAmode use_sse2 w addr addr_code = do
let size = floatSize w
code dst = addr_code `snocOL`
if use_sse2
then MOV size (OpAddr addr) (OpReg dst)
else GLD size addr dst
return (Any (if use_sse2 then size else FF80) code)
-- if we want a floating-point literal as an operand, we can
-- use it directly from memory. However, if the literal is
-- zero, we're better off generating it into a register using
-- xor.
isSuitableFloatingPointLit :: CmmLit -> Bool
isSuitableFloatingPointLit (CmmFloat f _) = f /= 0.0
isSuitableFloatingPointLit _ = False
getRegOrMem :: CmmExpr -> NatM (Operand, InstrBlock)
getRegOrMem e@(CmmLoad mem pk) = do
is32Bit <- is32BitPlatform
use_sse2 <- sse2Enabled
if (not (isFloatType pk) || use_sse2) && (if is32Bit then not (isWord64 pk) else True)
then do
Amode src mem_code <- getAmode mem
return (OpAddr src, mem_code)
else do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
getRegOrMem e = do
(reg, code) <- getNonClobberedReg e
return (OpReg reg, code)
is32BitLit :: Bool -> CmmLit -> Bool
is32BitLit is32Bit (CmmInt i W64)
| not is32Bit
= -- assume that labels are in the range 0-2^31-1: this assumes the
-- small memory model (see gcc docs, -mcmodel=small).
is32BitInteger i
is32BitLit _ _ = True
-- Set up a condition code for a conditional branch.
getCondCode :: CmmExpr -> NatM CondCode
-- yes, they really do seem to want exactly the same!
getCondCode (CmmMachOp mop [x, y])
=
case mop of
MO_F_Eq W32 -> condFltCode EQQ x y
MO_F_Ne W32 -> condFltCode NE x y
MO_F_Gt W32 -> condFltCode GTT x y
MO_F_Ge W32 -> condFltCode GE x y
MO_F_Lt W32 -> condFltCode LTT x y
MO_F_Le W32 -> condFltCode LE x y
MO_F_Eq W64 -> condFltCode EQQ x y
MO_F_Ne W64 -> condFltCode NE x y
MO_F_Gt W64 -> condFltCode GTT x y
MO_F_Ge W64 -> condFltCode GE x y
MO_F_Lt W64 -> condFltCode LTT x y
MO_F_Le W64 -> condFltCode LE x y
MO_Eq _ -> condIntCode EQQ x y
MO_Ne _ -> condIntCode NE x y
MO_S_Gt _ -> condIntCode GTT x y
MO_S_Ge _ -> condIntCode GE x y
MO_S_Lt _ -> condIntCode LTT x y
MO_S_Le _ -> condIntCode LE x y
MO_U_Gt _ -> condIntCode GU x y
MO_U_Ge _ -> condIntCode GEU x y
MO_U_Lt _ -> condIntCode LU x y
MO_U_Le _ -> condIntCode LEU x y
_other -> pprPanic "getCondCode(x86,x86_64)" (ppr (CmmMachOp mop [x,y]))
getCondCode other = pprPanic "getCondCode(2)(x86,x86_64)" (ppr other)
-- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be
-- passed back up the tree.
condIntCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condIntCode cond x y = do is32Bit <- is32BitPlatform
condIntCode' is32Bit cond x y
condIntCode' :: Bool -> Cond -> CmmExpr -> CmmExpr -> NatM CondCode
-- memory vs immediate
condIntCode' is32Bit cond (CmmLoad x pk) (CmmLit lit)
| is32BitLit is32Bit lit = do
Amode x_addr x_code <- getAmode x
let
imm = litToImm lit
code = x_code `snocOL`
CMP (cmmTypeSize pk) (OpImm imm) (OpAddr x_addr)
--
return (CondCode False cond code)
-- anything vs zero, using a mask
-- TODO: Add some sanity checking!!!!
condIntCode' is32Bit cond (CmmMachOp (MO_And _) [x,o2]) (CmmLit (CmmInt 0 pk))
| (CmmLit lit@(CmmInt mask _)) <- o2, is32BitLit is32Bit lit
= do
(x_reg, x_code) <- getSomeReg x
let
code = x_code `snocOL`
TEST (intSize pk) (OpImm (ImmInteger mask)) (OpReg x_reg)
--
return (CondCode False cond code)
-- anything vs zero
condIntCode' _ cond x (CmmLit (CmmInt 0 pk)) = do
(x_reg, x_code) <- getSomeReg x
let
code = x_code `snocOL`
TEST (intSize pk) (OpReg x_reg) (OpReg x_reg)
--
return (CondCode False cond code)
-- anything vs operand
condIntCode' is32Bit cond x y
| isOperand is32Bit y = do
dflags <- getDynFlags
(x_reg, x_code) <- getNonClobberedReg x
(y_op, y_code) <- getOperand y
let
code = x_code `appOL` y_code `snocOL`
CMP (cmmTypeSize (cmmExprType dflags x)) y_op (OpReg x_reg)
return (CondCode False cond code)
-- operand vs. anything: invert the comparison so that we can use a
-- single comparison instruction.
| isOperand is32Bit x
, Just revcond <- maybeFlipCond cond = do
dflags <- getDynFlags
(y_reg, y_code) <- getNonClobberedReg y
(x_op, x_code) <- getOperand x
let
code = y_code `appOL` x_code `snocOL`
CMP (cmmTypeSize (cmmExprType dflags x)) x_op (OpReg y_reg)
return (CondCode False revcond code)
-- anything vs anything
condIntCode' _ cond x y = do
dflags <- getDynFlags
(y_reg, y_code) <- getNonClobberedReg y
(x_op, x_code) <- getRegOrMem x
let
code = y_code `appOL`
x_code `snocOL`
CMP (cmmTypeSize (cmmExprType dflags x)) (OpReg y_reg) x_op
return (CondCode False cond code)
--------------------------------------------------------------------------------
condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode
condFltCode cond x y
= if_sse2 condFltCode_sse2 condFltCode_x87
where
condFltCode_x87
= ASSERT(cond `elem` ([EQQ, NE, LE, LTT, GE, GTT])) do
(x_reg, x_code) <- getNonClobberedReg x
(y_reg, y_code) <- getSomeReg y
let
code = x_code `appOL` y_code `snocOL`
GCMP cond x_reg y_reg
-- The GCMP insn does the test and sets the zero flag if comparable
-- and true. Hence we always supply EQQ as the condition to test.
return (CondCode True EQQ code)
-- in the SSE2 comparison ops (ucomiss, ucomisd) the left arg may be
-- an operand, but the right must be a reg. We can probably do better
-- than this general case...
condFltCode_sse2 = do
dflags <- getDynFlags
(x_reg, x_code) <- getNonClobberedReg x
(y_op, y_code) <- getOperand y
let
code = x_code `appOL`
y_code `snocOL`
CMP (floatSize $ cmmExprWidth dflags x) y_op (OpReg x_reg)
-- NB(1): we need to use the unsigned comparison operators on the
-- result of this comparison.
return (CondCode True (condToUnsigned cond) code)
-- -----------------------------------------------------------------------------
-- Generating assignments
-- Assignments are really at the heart of the whole code generation
-- business. Almost all top-level nodes of any real importance are
-- assignments, which correspond to loads, stores, or register
-- transfers. If we're really lucky, some of the register transfers
-- will go away, because we can use the destination register to
-- complete the code generation for the right hand side. This only
-- fails when the right hand side is forced into a fixed register
-- (e.g. the result of a call).
assignMem_IntCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_IntCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
assignMem_FltCode :: Size -> CmmExpr -> CmmExpr -> NatM InstrBlock
assignReg_FltCode :: Size -> CmmReg -> CmmExpr -> NatM InstrBlock
-- integer assignment to memory
-- specific case of adding/subtracting an integer to a particular address.
-- ToDo: catch other cases where we can use an operation directly on a memory
-- address.
assignMem_IntCode pk addr (CmmMachOp op [CmmLoad addr2 _,
CmmLit (CmmInt i _)])
| addr == addr2, pk /= II64 || is32BitInteger i,
Just instr <- check op
= do Amode amode code_addr <- getAmode addr
let code = code_addr `snocOL`
instr pk (OpImm (ImmInt (fromIntegral i))) (OpAddr amode)
return code
where
check (MO_Add _) = Just ADD
check (MO_Sub _) = Just SUB
check _ = Nothing
-- ToDo: more?
-- general case
assignMem_IntCode pk addr src = do
is32Bit <- is32BitPlatform
Amode addr code_addr <- getAmode addr
(code_src, op_src) <- get_op_RI is32Bit src
let
code = code_src `appOL`
code_addr `snocOL`
MOV pk op_src (OpAddr addr)
-- NOTE: op_src is stable, so it will still be valid
-- after code_addr. This may involve the introduction
-- of an extra MOV to a temporary register, but we hope
-- the register allocator will get rid of it.
--
return code
where
get_op_RI :: Bool -> CmmExpr -> NatM (InstrBlock,Operand) -- code, operator
get_op_RI is32Bit (CmmLit lit) | is32BitLit is32Bit lit
= return (nilOL, OpImm (litToImm lit))
get_op_RI _ op
= do (reg,code) <- getNonClobberedReg op
return (code, OpReg reg)
-- Assign; dst is a reg, rhs is mem
assignReg_IntCode pk reg (CmmLoad src _) = do
load_code <- intLoadCode (MOV pk) src
dflags <- getDynFlags
let platform = targetPlatform dflags
return (load_code (getRegisterReg platform False{-no sse2-} reg))
-- dst is a reg, but src could be anything
assignReg_IntCode _ reg src = do
dflags <- getDynFlags
let platform = targetPlatform dflags
code <- getAnyReg src
return (code (getRegisterReg platform False{-no sse2-} reg))
-- Floating point assignment to memory
assignMem_FltCode pk addr src = do
(src_reg, src_code) <- getNonClobberedReg src
Amode addr addr_code <- getAmode addr
use_sse2 <- sse2Enabled
let
code = src_code `appOL`
addr_code `snocOL`
if use_sse2 then MOV pk (OpReg src_reg) (OpAddr addr)
else GST pk src_reg addr
return code
-- Floating point assignment to a register/temporary
assignReg_FltCode _ reg src = do
use_sse2 <- sse2Enabled
src_code <- getAnyReg src
dflags <- getDynFlags
let platform = targetPlatform dflags
return (src_code (getRegisterReg platform use_sse2 reg))
genJump :: CmmExpr{-the branch target-} -> [Reg] -> NatM InstrBlock
genJump (CmmLoad mem _) regs = do
Amode target code <- getAmode mem
return (code `snocOL` JMP (OpAddr target) regs)
genJump (CmmLit lit) regs = do
return (unitOL (JMP (OpImm (litToImm lit)) regs))
genJump expr regs = do
(reg,code) <- getSomeReg expr
return (code `snocOL` JMP (OpReg reg) regs)
-- -----------------------------------------------------------------------------
-- Unconditional branches
genBranch :: BlockId -> NatM InstrBlock
genBranch = return . toOL . mkJumpInstr
-- -----------------------------------------------------------------------------
-- Conditional jumps
{-
Conditional jumps are always to local labels, so we can use branch
instructions. We peek at the arguments to decide what kind of
comparison to do.
I386: First, we have to ensure that the condition
codes are set according to the supplied comparison operation.
-}
genCondJump
:: BlockId -- the branch target
-> CmmExpr -- the condition on which to branch
-> NatM InstrBlock
genCondJump id bool = do
CondCode is_float cond cond_code <- getCondCode bool
use_sse2 <- sse2Enabled
if not is_float || not use_sse2
then
return (cond_code `snocOL` JXX cond id)
else do
lbl <- getBlockIdNat
-- see comment with condFltReg
let code = case cond of
NE -> or_unordered
GU -> plain_test
GEU -> plain_test
_ -> and_ordered
plain_test = unitOL (
JXX cond id
)
or_unordered = toOL [
JXX cond id,
JXX PARITY id
]
and_ordered = toOL [
JXX PARITY lbl,
JXX cond id,
JXX ALWAYS lbl,
NEWBLOCK lbl
]
return (cond_code `appOL` code)
-- -----------------------------------------------------------------------------
-- Generating C calls
-- Now the biggest nightmare---calls. Most of the nastiness is buried in
-- @get_arg@, which moves the arguments to the correct registers/stack
-- locations. Apart from that, the code is easy.
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
genCCall
:: DynFlags
-> Bool -- 32 bit platform?
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
-- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-- Unroll memcpy calls if the source and destination pointers are at
-- least DWORD aligned and the number of bytes to copy isn't too
-- large. Otherwise, call C's memcpy.
genCCall dflags is32Bit (PrimTarget MO_Memcpy) _
[dst, src,
(CmmLit (CmmInt n _)),
(CmmLit (CmmInt align _))]
| fromInteger insns <= maxInlineMemcpyInsns dflags && align .&. 3 == 0 = do
code_dst <- getAnyReg dst
dst_r <- getNewRegNat size
code_src <- getAnyReg src
src_r <- getNewRegNat size
tmp_r <- getNewRegNat size
return $ code_dst dst_r `appOL` code_src src_r `appOL`
go dst_r src_r tmp_r (fromInteger n)
where
-- The number of instructions we will generate (approx). We need 2
-- instructions per move.
insns = 2 * ((n + sizeBytes - 1) `div` sizeBytes)
size = if align .&. 4 /= 0 then II32 else (archWordSize is32Bit)
-- The size of each move, in bytes.
sizeBytes :: Integer
sizeBytes = fromIntegral (sizeInBytes size)
go :: Reg -> Reg -> Reg -> Integer -> OrdList Instr
go dst src tmp i
| i >= sizeBytes =
unitOL (MOV size (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV size (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - sizeBytes)
-- Deal with remaining bytes.
| i >= 4 = -- Will never happen on 32-bit
unitOL (MOV II32 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II32 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 4)
| i >= 2 =
unitOL (MOVZxL II16 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II16 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 2)
| i >= 1 =
unitOL (MOVZxL II8 (OpAddr src_addr) (OpReg tmp)) `appOL`
unitOL (MOV II8 (OpReg tmp) (OpAddr dst_addr)) `appOL`
go dst src tmp (i - 1)
| otherwise = nilOL
where
src_addr = AddrBaseIndex (EABaseReg src) EAIndexNone
(ImmInteger (n - i))
dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone
(ImmInteger (n - i))
genCCall dflags _ (PrimTarget MO_Memset) _
[dst,
CmmLit (CmmInt c _),
CmmLit (CmmInt n _),
CmmLit (CmmInt align _)]
| fromInteger insns <= maxInlineMemsetInsns dflags && align .&. 3 == 0 = do
code_dst <- getAnyReg dst
dst_r <- getNewRegNat size
return $ code_dst dst_r `appOL` go dst_r (fromInteger n)
where
(size, val) = case align .&. 3 of
2 -> (II16, c2)
0 -> (II32, c4)
_ -> (II8, c)
c2 = c `shiftL` 8 .|. c
c4 = c2 `shiftL` 16 .|. c2
-- The number of instructions we will generate (approx). We need 1
-- instructions per move.
insns = (n + sizeBytes - 1) `div` sizeBytes
-- The size of each move, in bytes.
sizeBytes :: Integer
sizeBytes = fromIntegral (sizeInBytes size)
go :: Reg -> Integer -> OrdList Instr
go dst i
-- TODO: Add movabs instruction and support 64-bit sets.
| i >= sizeBytes = -- This might be smaller than the below sizes
unitOL (MOV size (OpImm (ImmInteger val)) (OpAddr dst_addr)) `appOL`
go dst (i - sizeBytes)
| i >= 4 = -- Will never happen on 32-bit
unitOL (MOV II32 (OpImm (ImmInteger c4)) (OpAddr dst_addr)) `appOL`
go dst (i - 4)
| i >= 2 =
unitOL (MOV II16 (OpImm (ImmInteger c2)) (OpAddr dst_addr)) `appOL`
go dst (i - 2)
| i >= 1 =
unitOL (MOV II8 (OpImm (ImmInteger c)) (OpAddr dst_addr)) `appOL`
go dst (i - 1)
| otherwise = nilOL
where
dst_addr = AddrBaseIndex (EABaseReg dst) EAIndexNone
(ImmInteger (n - i))
genCCall _ _ (PrimTarget MO_WriteBarrier) _ _ = return nilOL
-- write barrier compiles to no code on x86/x86-64;
-- we keep it this long in order to prevent earlier optimisations.
genCCall _ _ (PrimTarget MO_Touch) _ _ = return nilOL
genCCall _ is32bit (PrimTarget (MO_Prefetch_Data n )) _ [src] =
case n of
0 -> genPrefetch src $ PREFETCH NTA size
1 -> genPrefetch src $ PREFETCH Lvl2 size
2 -> genPrefetch src $ PREFETCH Lvl1 size
3 -> genPrefetch src $ PREFETCH Lvl0 size
l -> panic $ "unexpected prefetch level in genCCall MO_Prefetch_Data: " ++ (show l)
-- the c / llvm prefetch convention is 0, 1, 2, and 3
-- the x86 corresponding names are : NTA, 2 , 1, and 0
where
size = archWordSize is32bit
-- need to know what register width for pointers!
genPrefetch inRegSrc prefetchCTor =
do
code_src <- getAnyReg inRegSrc
src_r <- getNewRegNat size
return $ code_src src_r `appOL`
(unitOL (prefetchCTor (OpAddr
((AddrBaseIndex (EABaseReg src_r ) EAIndexNone (ImmInt 0)))) ))
-- prefetch always takes an address
genCCall dflags is32Bit (PrimTarget (MO_BSwap width)) [dst] [src] = do
let platform = targetPlatform dflags
let dst_r = getRegisterReg platform False (CmmLocal dst)
case width of
W64 | is32Bit -> do
ChildCode64 vcode rlo <- iselExpr64 src
let dst_rhi = getHiVRegFromLo dst_r
rhi = getHiVRegFromLo rlo
return $ vcode `appOL`
toOL [ MOV II32 (OpReg rlo) (OpReg dst_rhi),
MOV II32 (OpReg rhi) (OpReg dst_r),
BSWAP II32 dst_rhi,
BSWAP II32 dst_r ]
W16 -> do code_src <- getAnyReg src
return $ code_src dst_r `appOL`
unitOL (BSWAP II32 dst_r) `appOL`
unitOL (SHR II32 (OpImm $ ImmInt 16) (OpReg dst_r))
_ -> do code_src <- getAnyReg src
return $ code_src dst_r `appOL` unitOL (BSWAP size dst_r)
where
size = intSize width
genCCall dflags is32Bit (PrimTarget (MO_PopCnt width)) dest_regs@[dst]
args@[src] = do
sse4_2 <- sse4_2Enabled
let platform = targetPlatform dflags
if sse4_2
then do code_src <- getAnyReg src
src_r <- getNewRegNat size
let dst_r = getRegisterReg platform False (CmmLocal dst)
return $ code_src src_r `appOL`
(if width == W8 then
-- The POPCNT instruction doesn't take a r/m8
unitOL (MOVZxL II8 (OpReg src_r) (OpReg src_r)) `appOL`
unitOL (POPCNT II16 (OpReg src_r) dst_r)
else
unitOL (POPCNT size (OpReg src_r) dst_r)) `appOL`
(if width == W8 || width == W16 then
-- We used a 16-bit destination register above,
-- so zero-extend
unitOL (MOVZxL II16 (OpReg dst_r) (OpReg dst_r))
else nilOL)
else do
targetExpr <- cmmMakeDynamicReference dflags
CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall dflags is32Bit target dest_regs args
where
size = intSize width
lbl = mkCmmCodeLabel primPackageKey (fsLit (popCntLabel width))
genCCall dflags is32Bit (PrimTarget (MO_UF_Conv width)) dest_regs args = do
targetExpr <- cmmMakeDynamicReference dflags
CallReference lbl
let target = ForeignTarget targetExpr (ForeignConvention CCallConv
[NoHint] [NoHint]
CmmMayReturn)
genCCall dflags is32Bit target dest_regs args
where
lbl = mkCmmCodeLabel primPackageKey (fsLit (word2FloatLabel width))
genCCall dflags is32Bit (PrimTarget (MO_AtomicRMW width amop)) [dst] [addr, n] = do
Amode amode addr_code <-
if amop `elem` [AMO_Add, AMO_Sub]
then getAmode addr
else getSimpleAmode dflags is32Bit addr -- See genCCall for MO_Cmpxchg
arg <- getNewRegNat size
arg_code <- getAnyReg n
use_sse2 <- sse2Enabled
let platform = targetPlatform dflags
dst_r = getRegisterReg platform use_sse2 (CmmLocal dst)
code <- op_code dst_r arg amode
return $ addr_code `appOL` arg_code arg `appOL` code
where
-- Code for the operation
op_code :: Reg -- Destination reg
-> Reg -- Register containing argument
-> AddrMode -- Address of location to mutate
-> NatM (OrdList Instr)
op_code dst_r arg amode = case amop of
-- In the common case where dst_r is a virtual register the
-- final move should go away, because it's the last use of arg
-- and the first use of dst_r.
AMO_Add -> return $ toOL [ LOCK (XADD size (OpReg arg) (OpAddr amode))
, MOV size (OpReg arg) (OpReg dst_r)
]
AMO_Sub -> return $ toOL [ NEGI size (OpReg arg)
, LOCK (XADD size (OpReg arg) (OpAddr amode))
, MOV size (OpReg arg) (OpReg dst_r)
]
AMO_And -> cmpxchg_code (\ src dst -> unitOL $ AND size src dst)
AMO_Nand -> cmpxchg_code (\ src dst -> toOL [ AND size src dst
, NOT size dst
])
AMO_Or -> cmpxchg_code (\ src dst -> unitOL $ OR size src dst)
AMO_Xor -> cmpxchg_code (\ src dst -> unitOL $ XOR size src dst)
where
-- Simulate operation that lacks a dedicated instruction using
-- cmpxchg.
cmpxchg_code :: (Operand -> Operand -> OrdList Instr)
-> NatM (OrdList Instr)
cmpxchg_code instrs = do
lbl <- getBlockIdNat
tmp <- getNewRegNat size
return $ toOL
[ MOV size (OpAddr amode) (OpReg eax)
, JXX ALWAYS lbl
, NEWBLOCK lbl
-- Keep old value so we can return it:
, MOV size (OpReg eax) (OpReg dst_r)
, MOV size (OpReg eax) (OpReg tmp)
]
`appOL` instrs (OpReg arg) (OpReg tmp) `appOL` toOL
[ LOCK (CMPXCHG size (OpReg tmp) (OpAddr amode))
, JXX NE lbl
]
size = intSize width
genCCall dflags _ (PrimTarget (MO_AtomicRead width)) [dst] [addr] = do
load_code <- intLoadCode (MOV (intSize width)) addr
let platform = targetPlatform dflags
use_sse2 <- sse2Enabled
return (load_code (getRegisterReg platform use_sse2 (CmmLocal dst)))
genCCall _ _ (PrimTarget (MO_AtomicWrite width)) [] [addr, val] = do
code <- assignMem_IntCode (intSize width) addr val
return $ code `snocOL` MFENCE
genCCall dflags is32Bit (PrimTarget (MO_Cmpxchg width)) [dst] [addr, old, new] = do
-- On x86 we don't have enough registers to use cmpxchg with a
-- complicated addressing mode, so on that architecture we
-- pre-compute the address first.
Amode amode addr_code <- getSimpleAmode dflags is32Bit addr
newval <- getNewRegNat size
newval_code <- getAnyReg new
oldval <- getNewRegNat size
oldval_code <- getAnyReg old
use_sse2 <- sse2Enabled
let platform = targetPlatform dflags
dst_r = getRegisterReg platform use_sse2 (CmmLocal dst)
code = toOL
[ MOV size (OpReg oldval) (OpReg eax)
, LOCK (CMPXCHG size (OpReg newval) (OpAddr amode))
, MOV size (OpReg eax) (OpReg dst_r)
]
return $ addr_code `appOL` newval_code newval `appOL` oldval_code oldval
`appOL` code
where
size = intSize width
genCCall _ is32Bit target dest_regs args = do
dflags <- getDynFlags
let platform = targetPlatform dflags
case (target, dest_regs) of
-- void return type prim op
(PrimTarget op, []) ->
outOfLineCmmOp op Nothing args
-- we only cope with a single result for foreign calls
(PrimTarget op, [r])
| not is32Bit -> outOfLineCmmOp op (Just r) args
| otherwise -> do
l1 <- getNewLabelNat
l2 <- getNewLabelNat
sse2 <- sse2Enabled
if sse2
then
outOfLineCmmOp op (Just r) args
else case op of
MO_F32_Sqrt -> actuallyInlineFloatOp GSQRT FF32 args
MO_F64_Sqrt -> actuallyInlineFloatOp GSQRT FF64 args
MO_F32_Sin -> actuallyInlineFloatOp (\s -> GSIN s l1 l2) FF32 args
MO_F64_Sin -> actuallyInlineFloatOp (\s -> GSIN s l1 l2) FF64 args
MO_F32_Cos -> actuallyInlineFloatOp (\s -> GCOS s l1 l2) FF32 args
MO_F64_Cos -> actuallyInlineFloatOp (\s -> GCOS s l1 l2) FF64 args
MO_F32_Tan -> actuallyInlineFloatOp (\s -> GTAN s l1 l2) FF32 args
MO_F64_Tan -> actuallyInlineFloatOp (\s -> GTAN s l1 l2) FF64 args
_other_op -> outOfLineCmmOp op (Just r) args
where
actuallyInlineFloatOp instr size [x]
= do res <- trivialUFCode size (instr size) x
any <- anyReg res
return (any (getRegisterReg platform False (CmmLocal r)))
actuallyInlineFloatOp _ _ args
= panic $ "genCCall.actuallyInlineFloatOp: bad number of arguments! ("
++ show (length args) ++ ")"
(PrimTarget (MO_S_QuotRem width), _) -> divOp1 platform True width dest_regs args
(PrimTarget (MO_U_QuotRem width), _) -> divOp1 platform False width dest_regs args
(PrimTarget (MO_U_QuotRem2 width), _) -> divOp2 platform False width dest_regs args
(PrimTarget (MO_Add2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do hCode <- getAnyReg (CmmLit (CmmInt 0 width))
let size = intSize width
lCode <- anyReg =<< trivialCode width (ADD_CC size)
(Just (ADD_CC size)) arg_x arg_y
let reg_l = getRegisterReg platform True (CmmLocal res_l)
reg_h = getRegisterReg platform True (CmmLocal res_h)
code = hCode reg_h `appOL`
lCode reg_l `snocOL`
ADC size (OpImm (ImmInteger 0)) (OpReg reg_h)
return code
_ -> panic "genCCall: Wrong number of arguments/results for add2"
(PrimTarget (MO_U_Mul2 width), [res_h, res_l]) ->
case args of
[arg_x, arg_y] ->
do (y_reg, y_code) <- getRegOrMem arg_y
x_code <- getAnyReg arg_x
let size = intSize width
reg_h = getRegisterReg platform True (CmmLocal res_h)
reg_l = getRegisterReg platform True (CmmLocal res_l)
code = y_code `appOL`
x_code rax `appOL`
toOL [MUL2 size y_reg,
MOV size (OpReg rdx) (OpReg reg_h),
MOV size (OpReg rax) (OpReg reg_l)]
return code
_ -> panic "genCCall: Wrong number of arguments/results for add2"
_ -> if is32Bit
then genCCall32' dflags target dest_regs args
else genCCall64' dflags target dest_regs args
where divOp1 platform signed width results [arg_x, arg_y]
= divOp platform signed width results Nothing arg_x arg_y
divOp1 _ _ _ _ _
= panic "genCCall: Wrong number of arguments for divOp1"
divOp2 platform signed width results [arg_x_high, arg_x_low, arg_y]
= divOp platform signed width results (Just arg_x_high) arg_x_low arg_y
divOp2 _ _ _ _ _
= panic "genCCall: Wrong number of arguments for divOp2"
divOp platform signed width [res_q, res_r]
m_arg_x_high arg_x_low arg_y
= do let size = intSize width
reg_q = getRegisterReg platform True (CmmLocal res_q)
reg_r = getRegisterReg platform True (CmmLocal res_r)
widen | signed = CLTD size
| otherwise = XOR size (OpReg rdx) (OpReg rdx)
instr | signed = IDIV
| otherwise = DIV
(y_reg, y_code) <- getRegOrMem arg_y
x_low_code <- getAnyReg arg_x_low
x_high_code <- case m_arg_x_high of
Just arg_x_high ->
getAnyReg arg_x_high
Nothing ->
return $ const $ unitOL widen
return $ y_code `appOL`
x_low_code rax `appOL`
x_high_code rdx `appOL`
toOL [instr size y_reg,
MOV size (OpReg rax) (OpReg reg_q),
MOV size (OpReg rdx) (OpReg reg_r)]
divOp _ _ _ _ _ _ _
= panic "genCCall: Wrong number of results for divOp"
genCCall32' :: DynFlags
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall32' dflags target dest_regs args = do
let
prom_args = map (maybePromoteCArg dflags W32) args
-- Align stack to 16n for calls, assuming a starting stack
-- alignment of 16n - word_size on procedure entry. Which we
-- maintiain. See Note [rts/StgCRun.c : Stack Alignment on X86]
sizes = map (arg_size . cmmExprType dflags) (reverse args)
raw_arg_size = sum sizes + wORD_SIZE dflags
arg_pad_size = (roundTo 16 $ raw_arg_size) - raw_arg_size
tot_arg_size = raw_arg_size + arg_pad_size - wORD_SIZE dflags
delta0 <- getDeltaNat
setDeltaNat (delta0 - arg_pad_size)
use_sse2 <- sse2Enabled
push_codes <- mapM (push_arg use_sse2) (reverse prom_args)
delta <- getDeltaNat
MASSERT(delta == delta0 - tot_arg_size)
-- deal with static vs dynamic call targets
(callinsns,cconv) <-
case target of
ForeignTarget (CmmLit (CmmLabel lbl)) conv
-> -- ToDo: stdcall arg sizes
return (unitOL (CALL (Left fn_imm) []), conv)
where fn_imm = ImmCLbl lbl
ForeignTarget expr conv
-> do { (dyn_r, dyn_c) <- getSomeReg expr
; ASSERT( isWord32 (cmmExprType dflags expr) )
return (dyn_c `snocOL` CALL (Right dyn_r) [], conv) }
PrimTarget _
-> panic $ "genCCall: Can't handle PrimTarget call type here, error "
++ "probably because too many return values."
let push_code
| arg_pad_size /= 0
= toOL [SUB II32 (OpImm (ImmInt arg_pad_size)) (OpReg esp),
DELTA (delta0 - arg_pad_size)]
`appOL` concatOL push_codes
| otherwise
= concatOL push_codes
-- Deallocate parameters after call for ccall;
-- but not for stdcall (callee does it)
--
-- We have to pop any stack padding we added
-- even if we are doing stdcall, though (#5052)
pop_size
| ForeignConvention StdCallConv _ _ _ <- cconv = arg_pad_size
| otherwise = tot_arg_size
call = callinsns `appOL`
toOL (
(if pop_size==0 then [] else
[ADD II32 (OpImm (ImmInt pop_size)) (OpReg esp)])
++
[DELTA delta0]
)
setDeltaNat delta0
dflags <- getDynFlags
let platform = targetPlatform dflags
let
-- assign the results, if necessary
assign_code [] = nilOL
assign_code [dest]
| isFloatType ty =
if use_sse2
then let tmp_amode = AddrBaseIndex (EABaseReg esp)
EAIndexNone
(ImmInt 0)
sz = floatSize w
in toOL [ SUB II32 (OpImm (ImmInt b)) (OpReg esp),
DELTA (delta0 - b),
GST sz fake0 tmp_amode,
MOV sz (OpAddr tmp_amode) (OpReg r_dest),
ADD II32 (OpImm (ImmInt b)) (OpReg esp),
DELTA delta0]
else unitOL (GMOV fake0 r_dest)
| isWord64 ty = toOL [MOV II32 (OpReg eax) (OpReg r_dest),
MOV II32 (OpReg edx) (OpReg r_dest_hi)]
| otherwise = unitOL (MOV (intSize w) (OpReg eax) (OpReg r_dest))
where
ty = localRegType dest
w = typeWidth ty
b = widthInBytes w
r_dest_hi = getHiVRegFromLo r_dest
r_dest = getRegisterReg platform use_sse2 (CmmLocal dest)
assign_code many = pprPanic "genCCall.assign_code - too many return values:" (ppr many)
return (push_code `appOL`
call `appOL`
assign_code dest_regs)
where
arg_size :: CmmType -> Int -- Width in bytes
arg_size ty = widthInBytes (typeWidth ty)
roundTo a x | x `mod` a == 0 = x
| otherwise = x + a - (x `mod` a)
push_arg :: Bool -> CmmActual {-current argument-}
-> NatM InstrBlock -- code
push_arg use_sse2 arg -- we don't need the hints on x86
| isWord64 arg_ty = do
ChildCode64 code r_lo <- iselExpr64 arg
delta <- getDeltaNat
setDeltaNat (delta - 8)
let
r_hi = getHiVRegFromLo r_lo
return ( code `appOL`
toOL [PUSH II32 (OpReg r_hi), DELTA (delta - 4),
PUSH II32 (OpReg r_lo), DELTA (delta - 8),
DELTA (delta-8)]
)
| isFloatType arg_ty = do
(reg, code) <- getSomeReg arg
delta <- getDeltaNat
setDeltaNat (delta-size)
return (code `appOL`
toOL [SUB II32 (OpImm (ImmInt size)) (OpReg esp),
DELTA (delta-size),
let addr = AddrBaseIndex (EABaseReg esp)
EAIndexNone
(ImmInt 0)
size = floatSize (typeWidth arg_ty)
in
if use_sse2
then MOV size (OpReg reg) (OpAddr addr)
else GST size reg addr
]
)
| otherwise = do
(operand, code) <- getOperand arg
delta <- getDeltaNat
setDeltaNat (delta-size)
return (code `snocOL`
PUSH II32 operand `snocOL`
DELTA (delta-size))
where
arg_ty = cmmExprType dflags arg
size = arg_size arg_ty -- Byte size
genCCall64' :: DynFlags
-> ForeignTarget -- function to call
-> [CmmFormal] -- where to put the result
-> [CmmActual] -- arguments (of mixed type)
-> NatM InstrBlock
genCCall64' dflags target dest_regs args = do
-- load up the register arguments
let prom_args = map (maybePromoteCArg dflags W32) args
(stack_args, int_regs_used, fp_regs_used, load_args_code)
<-
if platformOS platform == OSMinGW32
then load_args_win prom_args [] [] (allArgRegs platform) nilOL
else do (stack_args, aregs, fregs, load_args_code)
<- load_args prom_args (allIntArgRegs platform) (allFPArgRegs platform) nilOL
let fp_regs_used = reverse (drop (length fregs) (reverse (allFPArgRegs platform)))
int_regs_used = reverse (drop (length aregs) (reverse (allIntArgRegs platform)))
return (stack_args, int_regs_used, fp_regs_used, load_args_code)
let
arg_regs_used = int_regs_used ++ fp_regs_used
arg_regs = [eax] ++ arg_regs_used
-- for annotating the call instruction with
sse_regs = length fp_regs_used
arg_stack_slots = if platformOS platform == OSMinGW32
then length stack_args + length (allArgRegs platform)
else length stack_args
tot_arg_size = arg_size * arg_stack_slots
-- Align stack to 16n for calls, assuming a starting stack
-- alignment of 16n - word_size on procedure entry. Which we
-- maintain. See Note [rts/StgCRun.c : Stack Alignment on X86]
(real_size, adjust_rsp) <-
if (tot_arg_size + wORD_SIZE dflags) `rem` 16 == 0
then return (tot_arg_size, nilOL)
else do -- we need to adjust...
delta <- getDeltaNat
setDeltaNat (delta - wORD_SIZE dflags)
return (tot_arg_size + wORD_SIZE dflags, toOL [
SUB II64 (OpImm (ImmInt (wORD_SIZE dflags))) (OpReg rsp),
DELTA (delta - wORD_SIZE dflags) ])
-- push the stack args, right to left
push_code <- push_args (reverse stack_args) nilOL
-- On Win64, we also have to leave stack space for the arguments
-- that we are passing in registers
lss_code <- if platformOS platform == OSMinGW32
then leaveStackSpace (length (allArgRegs platform))
else return nilOL
delta <- getDeltaNat
-- deal with static vs dynamic call targets
(callinsns,_cconv) <-
case target of
ForeignTarget (CmmLit (CmmLabel lbl)) conv
-> -- ToDo: stdcall arg sizes
return (unitOL (CALL (Left fn_imm) arg_regs), conv)
where fn_imm = ImmCLbl lbl
ForeignTarget expr conv
-> do (dyn_r, dyn_c) <- getSomeReg expr
return (dyn_c `snocOL` CALL (Right dyn_r) arg_regs, conv)
PrimTarget _
-> panic $ "genCCall: Can't handle PrimTarget call type here, error "
++ "probably because too many return values."
let
-- The x86_64 ABI requires us to set %al to the number of SSE2
-- registers that contain arguments, if the called routine
-- is a varargs function. We don't know whether it's a
-- varargs function or not, so we have to assume it is.
--
-- It's not safe to omit this assignment, even if the number
-- of SSE2 regs in use is zero. If %al is larger than 8
-- on entry to a varargs function, seg faults ensue.
assign_eax n = unitOL (MOV II32 (OpImm (ImmInt n)) (OpReg eax))
let call = callinsns `appOL`
toOL (
-- Deallocate parameters after call for ccall;
-- stdcall has callee do it, but is not supported on
-- x86_64 target (see #3336)
(if real_size==0 then [] else
[ADD (intSize (wordWidth dflags)) (OpImm (ImmInt real_size)) (OpReg esp)])
++
[DELTA (delta + real_size)]
)
setDeltaNat (delta + real_size)
let
-- assign the results, if necessary
assign_code [] = nilOL
assign_code [dest] =
case typeWidth rep of
W32 | isFloatType rep -> unitOL (MOV (floatSize W32) (OpReg xmm0) (OpReg r_dest))
W64 | isFloatType rep -> unitOL (MOV (floatSize W64) (OpReg xmm0) (OpReg r_dest))
_ -> unitOL (MOV (cmmTypeSize rep) (OpReg rax) (OpReg r_dest))
where
rep = localRegType dest
r_dest = getRegisterReg platform True (CmmLocal dest)
assign_code _many = panic "genCCall.assign_code many"
return (load_args_code `appOL`
adjust_rsp `appOL`
push_code `appOL`
lss_code `appOL`
assign_eax sse_regs `appOL`
call `appOL`
assign_code dest_regs)
where platform = targetPlatform dflags
arg_size = 8 -- always, at the mo
load_args :: [CmmExpr]
-> [Reg] -- int regs avail for args
-> [Reg] -- FP regs avail for args
-> InstrBlock
-> NatM ([CmmExpr],[Reg],[Reg],InstrBlock)
load_args args [] [] code = return (args, [], [], code)
-- no more regs to use
load_args [] aregs fregs code = return ([], aregs, fregs, code)
-- no more args to push
load_args (arg : rest) aregs fregs code
| isFloatType arg_rep =
case fregs of
[] -> push_this_arg
(r:rs) -> do
arg_code <- getAnyReg arg
load_args rest aregs rs (code `appOL` arg_code r)
| otherwise =
case aregs of
[] -> push_this_arg
(r:rs) -> do
arg_code <- getAnyReg arg
load_args rest rs fregs (code `appOL` arg_code r)
where
arg_rep = cmmExprType dflags arg
push_this_arg = do
(args',ars,frs,code') <- load_args rest aregs fregs code
return (arg:args', ars, frs, code')
load_args_win :: [CmmExpr]
-> [Reg] -- used int regs
-> [Reg] -- used FP regs
-> [(Reg, Reg)] -- (int, FP) regs avail for args
-> InstrBlock
-> NatM ([CmmExpr],[Reg],[Reg],InstrBlock)
load_args_win args usedInt usedFP [] code
= return (args, usedInt, usedFP, code)
-- no more regs to use
load_args_win [] usedInt usedFP _ code
= return ([], usedInt, usedFP, code)
-- no more args to push
load_args_win (arg : rest) usedInt usedFP
((ireg, freg) : regs) code
| isFloatType arg_rep = do
arg_code <- getAnyReg arg
load_args_win rest (ireg : usedInt) (freg : usedFP) regs
(code `appOL`
arg_code freg `snocOL`
-- If we are calling a varargs function
-- then we need to define ireg as well
-- as freg
MOV II64 (OpReg freg) (OpReg ireg))
| otherwise = do
arg_code <- getAnyReg arg
load_args_win rest (ireg : usedInt) usedFP regs
(code `appOL` arg_code ireg)
where
arg_rep = cmmExprType dflags arg
push_args [] code = return code
push_args (arg:rest) code
| isFloatType arg_rep = do
(arg_reg, arg_code) <- getSomeReg arg
delta <- getDeltaNat
setDeltaNat (delta-arg_size)
let code' = code `appOL` arg_code `appOL` toOL [
SUB (intSize (wordWidth dflags)) (OpImm (ImmInt arg_size)) (OpReg rsp) ,
DELTA (delta-arg_size),
MOV (floatSize width) (OpReg arg_reg) (OpAddr (spRel dflags 0))]
push_args rest code'
| otherwise = do
ASSERT(width == W64) return ()
(arg_op, arg_code) <- getOperand arg
delta <- getDeltaNat
setDeltaNat (delta-arg_size)
let code' = code `appOL` arg_code `appOL` toOL [
PUSH II64 arg_op,
DELTA (delta-arg_size)]
push_args rest code'
where
arg_rep = cmmExprType dflags arg
width = typeWidth arg_rep
leaveStackSpace n = do
delta <- getDeltaNat
setDeltaNat (delta - n * arg_size)
return $ toOL [
SUB II64 (OpImm (ImmInt (n * wORD_SIZE dflags))) (OpReg rsp),
DELTA (delta - n * arg_size)]
maybePromoteCArg :: DynFlags -> Width -> CmmExpr -> CmmExpr
maybePromoteCArg dflags wto arg
| wfrom < wto = CmmMachOp (MO_UU_Conv wfrom wto) [arg]
| otherwise = arg
where
wfrom = cmmExprWidth dflags arg
outOfLineCmmOp :: CallishMachOp -> Maybe CmmFormal -> [CmmActual] -> NatM InstrBlock
outOfLineCmmOp mop res args
= do
dflags <- getDynFlags
targetExpr <- cmmMakeDynamicReference dflags CallReference lbl
let target = ForeignTarget targetExpr
(ForeignConvention CCallConv [] [] CmmMayReturn)
stmtToInstrs (CmmUnsafeForeignCall target (catMaybes [res]) args')
where
-- Assume we can call these functions directly, and that they're not in a dynamic library.
-- TODO: Why is this ok? Under linux this code will be in libm.so
-- Is is because they're really implemented as a primitive instruction by the assembler?? -- BL 2009/12/31
lbl = mkForeignLabel fn Nothing ForeignLabelInThisPackage IsFunction
args' = case mop of
MO_Memcpy -> init args
MO_Memset -> init args
MO_Memmove -> init args
_ -> args
fn = case mop of
MO_F32_Sqrt -> fsLit "sqrtf"
MO_F32_Sin -> fsLit "sinf"
MO_F32_Cos -> fsLit "cosf"
MO_F32_Tan -> fsLit "tanf"
MO_F32_Exp -> fsLit "expf"
MO_F32_Log -> fsLit "logf"
MO_F32_Asin -> fsLit "asinf"
MO_F32_Acos -> fsLit "acosf"
MO_F32_Atan -> fsLit "atanf"
MO_F32_Sinh -> fsLit "sinhf"
MO_F32_Cosh -> fsLit "coshf"
MO_F32_Tanh -> fsLit "tanhf"
MO_F32_Pwr -> fsLit "powf"
MO_F64_Sqrt -> fsLit "sqrt"
MO_F64_Sin -> fsLit "sin"
MO_F64_Cos -> fsLit "cos"
MO_F64_Tan -> fsLit "tan"
MO_F64_Exp -> fsLit "exp"
MO_F64_Log -> fsLit "log"
MO_F64_Asin -> fsLit "asin"
MO_F64_Acos -> fsLit "acos"
MO_F64_Atan -> fsLit "atan"
MO_F64_Sinh -> fsLit "sinh"
MO_F64_Cosh -> fsLit "cosh"
MO_F64_Tanh -> fsLit "tanh"
MO_F64_Pwr -> fsLit "pow"
MO_Memcpy -> fsLit "memcpy"
MO_Memset -> fsLit "memset"
MO_Memmove -> fsLit "memmove"
MO_PopCnt _ -> fsLit "popcnt"
MO_BSwap _ -> fsLit "bswap"
MO_AtomicRMW _ _ -> fsLit "atomicrmw"
MO_AtomicRead _ -> fsLit "atomicread"
MO_AtomicWrite _ -> fsLit "atomicwrite"
MO_Cmpxchg _ -> fsLit "cmpxchg"
MO_UF_Conv _ -> unsupported
MO_S_QuotRem {} -> unsupported
MO_U_QuotRem {} -> unsupported
MO_U_QuotRem2 {} -> unsupported
MO_Add2 {} -> unsupported
MO_U_Mul2 {} -> unsupported
MO_WriteBarrier -> unsupported
MO_Touch -> unsupported
(MO_Prefetch_Data _ ) -> unsupported
unsupported = panic ("outOfLineCmmOp: " ++ show mop
++ " not supported here")
-- -----------------------------------------------------------------------------
-- Generating a table-branch
genSwitch :: DynFlags -> CmmExpr -> [Maybe BlockId] -> NatM InstrBlock
genSwitch dflags expr ids
| gopt Opt_PIC dflags
= do
(reg,e_code) <- getSomeReg expr
lbl <- getNewLabelNat
dflags <- getDynFlags
dynRef <- cmmMakeDynamicReference dflags DataReference lbl
(tableReg,t_code) <- getSomeReg $ dynRef
let op = OpAddr (AddrBaseIndex (EABaseReg tableReg)
(EAIndex reg (wORD_SIZE dflags)) (ImmInt 0))
return $ if target32Bit (targetPlatform dflags)
then e_code `appOL` t_code `appOL` toOL [
ADD (intSize (wordWidth dflags)) op (OpReg tableReg),
JMP_TBL (OpReg tableReg) ids ReadOnlyData lbl
]
else case platformOS (targetPlatform dflags) of
OSDarwin ->
-- on Mac OS X/x86_64, put the jump table
-- in the text section to work around a
-- limitation of the linker.
-- ld64 is unable to handle the relocations for
-- .quad L1 - L0
-- if L0 is not preceded by a non-anonymous
-- label in its section.
e_code `appOL` t_code `appOL` toOL [
ADD (intSize (wordWidth dflags)) op (OpReg tableReg),
JMP_TBL (OpReg tableReg) ids Text lbl
]
_ ->
-- HACK: On x86_64 binutils<2.17 is only able
-- to generate PC32 relocations, hence we only
-- get 32-bit offsets in the jump table. As
-- these offsets are always negative we need
-- to properly sign extend them to 64-bit.
-- This hack should be removed in conjunction
-- with the hack in PprMach.hs/pprDataItem
-- once binutils 2.17 is standard.
e_code `appOL` t_code `appOL` toOL [
MOVSxL II32 op (OpReg reg),
ADD (intSize (wordWidth dflags)) (OpReg reg) (OpReg tableReg),
JMP_TBL (OpReg tableReg) ids ReadOnlyData lbl
]
| otherwise
= do
(reg,e_code) <- getSomeReg expr
lbl <- getNewLabelNat
let op = OpAddr (AddrBaseIndex EABaseNone (EAIndex reg (wORD_SIZE dflags)) (ImmCLbl lbl))
code = e_code `appOL` toOL [
JMP_TBL op ids ReadOnlyData lbl
]
return code
generateJumpTableForInstr :: DynFlags -> Instr -> Maybe (NatCmmDecl (Alignment, CmmStatics) Instr)
generateJumpTableForInstr dflags (JMP_TBL _ ids section lbl)
= Just (createJumpTable dflags ids section lbl)
generateJumpTableForInstr _ _ = Nothing
createJumpTable :: DynFlags -> [Maybe BlockId] -> Section -> CLabel
-> GenCmmDecl (Alignment, CmmStatics) h g
createJumpTable dflags ids section lbl
= let jumpTable
| gopt Opt_PIC dflags =
let jumpTableEntryRel Nothing
= CmmStaticLit (CmmInt 0 (wordWidth dflags))
jumpTableEntryRel (Just blockid)
= CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0)
where blockLabel = mkAsmTempLabel (getUnique blockid)
in map jumpTableEntryRel ids
| otherwise = map (jumpTableEntry dflags) ids
in CmmData section (1, Statics lbl jumpTable)
-- -----------------------------------------------------------------------------
-- 'condIntReg' and 'condFltReg': condition codes into registers
-- Turn those condition codes into integers now (when they appear on
-- the right hand side of an assignment).
--
-- (If applicable) Do not fill the delay slots here; you will confuse the
-- register allocator.
condIntReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register
condIntReg cond x y = do
CondCode _ cond cond_code <- condIntCode cond x y
tmp <- getNewRegNat II8
let
code dst = cond_code `appOL` toOL [
SETCC cond (OpReg tmp),
MOVZxL II8 (OpReg tmp) (OpReg dst)
]
return (Any II32 code)
condFltReg :: Bool -> Cond -> CmmExpr -> CmmExpr -> NatM Register
condFltReg is32Bit cond x y = if_sse2 condFltReg_sse2 condFltReg_x87
where
condFltReg_x87 = do
CondCode _ cond cond_code <- condFltCode cond x y
tmp <- getNewRegNat II8
let
code dst = cond_code `appOL` toOL [
SETCC cond (OpReg tmp),
MOVZxL II8 (OpReg tmp) (OpReg dst)
]
return (Any II32 code)
condFltReg_sse2 = do
CondCode _ cond cond_code <- condFltCode cond x y
tmp1 <- getNewRegNat (archWordSize is32Bit)
tmp2 <- getNewRegNat (archWordSize is32Bit)
let
-- We have to worry about unordered operands (eg. comparisons
-- against NaN). If the operands are unordered, the comparison
-- sets the parity flag, carry flag and zero flag.
-- All comparisons are supposed to return false for unordered
-- operands except for !=, which returns true.
--
-- Optimisation: we don't have to test the parity flag if we
-- know the test has already excluded the unordered case: eg >
-- and >= test for a zero carry flag, which can only occur for
-- ordered operands.
--
-- ToDo: by reversing comparisons we could avoid testing the
-- parity flag in more cases.
code dst =
cond_code `appOL`
(case cond of
NE -> or_unordered dst
GU -> plain_test dst
GEU -> plain_test dst
_ -> and_ordered dst)
plain_test dst = toOL [
SETCC cond (OpReg tmp1),
MOVZxL II8 (OpReg tmp1) (OpReg dst)
]
or_unordered dst = toOL [
SETCC cond (OpReg tmp1),
SETCC PARITY (OpReg tmp2),
OR II8 (OpReg tmp1) (OpReg tmp2),
MOVZxL II8 (OpReg tmp2) (OpReg dst)
]
and_ordered dst = toOL [
SETCC cond (OpReg tmp1),
SETCC NOTPARITY (OpReg tmp2),
AND II8 (OpReg tmp1) (OpReg tmp2),
MOVZxL II8 (OpReg tmp2) (OpReg dst)
]
return (Any II32 code)
-- -----------------------------------------------------------------------------
-- 'trivial*Code': deal with trivial instructions
-- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode',
-- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions.
-- Only look for constants on the right hand side, because that's
-- where the generic optimizer will have put them.
-- Similarly, for unary instructions, we don't have to worry about
-- matching an StInt as the argument, because genericOpt will already
-- have handled the constant-folding.
{-
The Rules of the Game are:
* You cannot assume anything about the destination register dst;
it may be anything, including a fixed reg.
* You may compute an operand into a fixed reg, but you may not
subsequently change the contents of that fixed reg. If you
want to do so, first copy the value either to a temporary
or into dst. You are free to modify dst even if it happens
to be a fixed reg -- that's not your problem.
* You cannot assume that a fixed reg will stay live over an
arbitrary computation. The same applies to the dst reg.
* Temporary regs obtained from getNewRegNat are distinct from
each other and from all other regs, and stay live over
arbitrary computations.
--------------------
SDM's version of The Rules:
* If getRegister returns Any, that means it can generate correct
code which places the result in any register, period. Even if that
register happens to be read during the computation.
Corollary #1: this means that if you are generating code for an
operation with two arbitrary operands, you cannot assign the result
of the first operand into the destination register before computing
the second operand. The second operand might require the old value
of the destination register.
Corollary #2: A function might be able to generate more efficient
code if it knows the destination register is a new temporary (and
therefore not read by any of the sub-computations).
* If getRegister returns Any, then the code it generates may modify only:
(a) fresh temporaries
(b) the destination register
(c) known registers (eg. %ecx is used by shifts)
In particular, it may *not* modify global registers, unless the global
register happens to be the destination register.
-}
trivialCode :: Width -> (Operand -> Operand -> Instr)
-> Maybe (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCode width instr m a b
= do is32Bit <- is32BitPlatform
trivialCode' is32Bit width instr m a b
trivialCode' :: Bool -> Width -> (Operand -> Operand -> Instr)
-> Maybe (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialCode' is32Bit width _ (Just revinstr) (CmmLit lit_a) b
| is32BitLit is32Bit lit_a = do
b_code <- getAnyReg b
let
code dst
= b_code dst `snocOL`
revinstr (OpImm (litToImm lit_a)) (OpReg dst)
return (Any (intSize width) code)
trivialCode' _ width instr _ a b
= genTrivialCode (intSize width) instr a b
-- This is re-used for floating pt instructions too.
genTrivialCode :: Size -> (Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
genTrivialCode rep instr a b = do
(b_op, b_code) <- getNonClobberedOperand b
a_code <- getAnyReg a
tmp <- getNewRegNat rep
let
-- We want the value of b to stay alive across the computation of a.
-- But, we want to calculate a straight into the destination register,
-- because the instruction only has two operands (dst := dst `op` src).
-- The troublesome case is when the result of b is in the same register
-- as the destination reg. In this case, we have to save b in a
-- new temporary across the computation of a.
code dst
| dst `regClashesWithOp` b_op =
b_code `appOL`
unitOL (MOV rep b_op (OpReg tmp)) `appOL`
a_code dst `snocOL`
instr (OpReg tmp) (OpReg dst)
| otherwise =
b_code `appOL`
a_code dst `snocOL`
instr b_op (OpReg dst)
return (Any rep code)
regClashesWithOp :: Reg -> Operand -> Bool
reg `regClashesWithOp` OpReg reg2 = reg == reg2
reg `regClashesWithOp` OpAddr amode = any (==reg) (addrModeRegs amode)
_ `regClashesWithOp` _ = False
-----------
trivialUCode :: Size -> (Operand -> Instr)
-> CmmExpr -> NatM Register
trivialUCode rep instr x = do
x_code <- getAnyReg x
let
code dst =
x_code dst `snocOL`
instr (OpReg dst)
return (Any rep code)
-----------
trivialFCode_x87 :: (Size -> Reg -> Reg -> Reg -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialFCode_x87 instr x y = do
(x_reg, x_code) <- getNonClobberedReg x -- these work for float regs too
(y_reg, y_code) <- getSomeReg y
let
size = FF80 -- always, on x87
code dst =
x_code `appOL`
y_code `snocOL`
instr size x_reg y_reg dst
return (Any size code)
trivialFCode_sse2 :: Width -> (Size -> Operand -> Operand -> Instr)
-> CmmExpr -> CmmExpr -> NatM Register
trivialFCode_sse2 pk instr x y
= genTrivialCode size (instr size) x y
where size = floatSize pk
trivialUFCode :: Size -> (Reg -> Reg -> Instr) -> CmmExpr -> NatM Register
trivialUFCode size instr x = do
(x_reg, x_code) <- getSomeReg x
let
code dst =
x_code `snocOL`
instr x_reg dst
return (Any size code)
--------------------------------------------------------------------------------
coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register
coerceInt2FP from to x = if_sse2 coerce_sse2 coerce_x87
where
coerce_x87 = do
(x_reg, x_code) <- getSomeReg x
let
opc = case to of W32 -> GITOF; W64 -> GITOD;
n -> panic $ "coerceInt2FP.x87: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc x_reg dst
-- ToDo: works for non-II32 reps?
return (Any FF80 code)
coerce_sse2 = do
(x_op, x_code) <- getOperand x -- ToDo: could be a safe operand
let
opc = case to of W32 -> CVTSI2SS; W64 -> CVTSI2SD
n -> panic $ "coerceInt2FP.sse: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc (intSize from) x_op dst
return (Any (floatSize to) code)
-- works even if the destination rep is <II32
--------------------------------------------------------------------------------
coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register
coerceFP2Int from to x = if_sse2 coerceFP2Int_sse2 coerceFP2Int_x87
where
coerceFP2Int_x87 = do
(x_reg, x_code) <- getSomeReg x
let
opc = case from of W32 -> GFTOI; W64 -> GDTOI
n -> panic $ "coerceFP2Int.x87: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc x_reg dst
-- ToDo: works for non-II32 reps?
return (Any (intSize to) code)
coerceFP2Int_sse2 = do
(x_op, x_code) <- getOperand x -- ToDo: could be a safe operand
let
opc = case from of W32 -> CVTTSS2SIQ; W64 -> CVTTSD2SIQ;
n -> panic $ "coerceFP2Init.sse: unhandled width ("
++ show n ++ ")"
code dst = x_code `snocOL` opc (intSize to) x_op dst
return (Any (intSize to) code)
-- works even if the destination rep is <II32
--------------------------------------------------------------------------------
coerceFP2FP :: Width -> CmmExpr -> NatM Register
coerceFP2FP to x = do
use_sse2 <- sse2Enabled
(x_reg, x_code) <- getSomeReg x
let
opc | use_sse2 = case to of W32 -> CVTSD2SS; W64 -> CVTSS2SD;
n -> panic $ "coerceFP2FP: unhandled width ("
++ show n ++ ")"
| otherwise = GDTOF
code dst = x_code `snocOL` opc x_reg dst
return (Any (if use_sse2 then floatSize to else FF80) code)
--------------------------------------------------------------------------------
sse2NegCode :: Width -> CmmExpr -> NatM Register
sse2NegCode w x = do
let sz = floatSize w
x_code <- getAnyReg x
-- This is how gcc does it, so it can't be that bad:
let
const | FF32 <- sz = CmmInt 0x80000000 W32
| otherwise = CmmInt 0x8000000000000000 W64
Amode amode amode_code <- memConstant (widthInBytes w) const
tmp <- getNewRegNat sz
let
code dst = x_code dst `appOL` amode_code `appOL` toOL [
MOV sz (OpAddr amode) (OpReg tmp),
XOR sz (OpReg tmp) (OpReg dst)
]
--
return (Any sz code)
isVecExpr :: CmmExpr -> Bool
isVecExpr (CmmMachOp (MO_V_Insert {}) _) = True
isVecExpr (CmmMachOp (MO_V_Extract {}) _) = True
isVecExpr (CmmMachOp (MO_V_Add {}) _) = True
isVecExpr (CmmMachOp (MO_V_Sub {}) _) = True
isVecExpr (CmmMachOp (MO_V_Mul {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Quot {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Rem {}) _) = True
isVecExpr (CmmMachOp (MO_VS_Neg {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Insert {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Extract {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Add {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Sub {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Mul {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Quot {}) _) = True
isVecExpr (CmmMachOp (MO_VF_Neg {}) _) = True
isVecExpr (CmmMachOp _ [e]) = isVecExpr e
isVecExpr _ = False
needLlvm :: NatM a
needLlvm =
sorry $ unlines ["The native code generator does not support vector"
,"instructions. Please use -fllvm."]
|
holzensp/ghc
|
compiler/nativeGen/X86/CodeGen.hs
|
bsd-3-clause
| 109,961 | 14 | 23 | 36,616 | 28,761 | 14,178 | 14,583 | -1 | -1 |
-- | This module provides the JBC-'Program' type and functionality to compute
-- and set additional information (eg. super classes, fields of a class wrt to
-- its super classes).
module Jinja.Program.Data
(
Program (..)
, Class (..)
, Field (..)
, Method (..)
, Type (..)
, Value (..)
, PC
, Var (..)
, Instruction (..)
, FieldId (..)
, ClassId (..)
, MethodId (..)
, Address
, ClassPool
, FieldPool
, MethodPool
, initP
, typeOf
, defaultValue
)
where
import Jat.Utils.Pretty
import Prelude hiding ((<$>))
import Data.Array
import Data.Maybe (fromMaybe)
import qualified Data.Map as M
-- | A 'Program' is the static representation of a JBC file, complemented with
-- additional useful information.
data Program = P ClassPool deriving (Eq,Read)
instance Show Program where
show = show . pretty
-- | Internal type for storing classes.
type ClassPool = M.Map ClassId Class
-- | Internal type for storing classfields.
type FieldPool = M.Map FieldId Field
-- | Internal type for storing methodfields.
type MethodPool = M.Map MethodId Method
-- | Synonym for an address.
type Address = Int
-- | Identifier for a classfield.
data FieldId = FieldId String deriving (Ord,Eq,Show,Read)
-- | Identifier for a class.
data ClassId = ClassId String deriving (Ord,Eq,Show,Read)
-- | Identifier for a method.
data MethodId = MethodId String deriving (Ord,Eq,Show,Read)
-- | The 'Class' record based on the JBC description complemented with
-- additional information.
data Class = Class {
className :: ClassId
, supClass :: Maybe ClassId
, fieldPool :: FieldPool
, methodPool :: MethodPool
, supClasses :: [ClassId]
, subClasses :: [ClassId]
, hasFieldz :: [(FieldId, ClassId, Type)]
} deriving(Eq,Show,Read)
-- | The 'Field' record based on the JBC description.
data Field = Field {
fieldName :: FieldId
, fieldType :: Type
} deriving (Eq,Show,Read)
-- | The 'Method' record based on the JBC description.
data Method = Method {
methodName :: MethodId
, methodParams :: [Type]
, methodReturn :: Type
, maxStk :: Int
, maxLoc :: Int
, methodInstructions :: Array Int Instruction
} deriving (Eq,Show,Read)
-- | The types of a value in JBc.
data Type =
BoolType
| IntType
| RefType ClassId
| NullType
| Void
deriving (Eq,Ord,Show,Read)
type PC = Int
data Var = LocVar !Int !Int | StkVar !Int !Int deriving (Eq,Ord)
instance Pretty Var where
pretty (LocVar i j) = char 'l' <> int i <> int j
pretty (StkVar i j) = char 's' <> int i <> int j
instance Show Var where
show = show . pretty
-- | Returns the (common) default value of a type.
defaultValue :: Type -> Value
defaultValue BoolType = BoolVal False
defaultValue IntType = IntVal 0
defaultValue (RefType _) = Null
defaultValue NullType = Null
defaultValue Void = Unit
-- | Returns the type of the value.
-- Returns Nothing for RefVal.
typeOf :: Value -> Maybe Type
typeOf (BoolVal _) = Just BoolType
typeOf (IntVal _) = Just IntType
typeOf (RefVal _) = Nothing
typeOf Null = Just NullType
typeOf Unit = Just Void
-- | A JBC Value.
data Value =
BoolVal Bool
| IntVal Int
| RefVal Address
| Null
| Unit
deriving (Eq,Show,Read)
-- | JBC Instruction.
data Instruction =
Load Int
| Store Int
| Push Value
| New ClassId
| GetField FieldId ClassId
| PutField FieldId ClassId
| CheckCast ClassId
| Invoke MethodId Int
| Return
| Pop
| IAdd
| Goto Int
| CmpEq
| CmpNeq
| IfFalse Int
| ISub
| ICmpGeq
| BNot
| BAnd
| BOr
deriving (Eq,Show,Read)
-- | Computes and sets additional information (e.g. subclasses).
initP :: Program -> Program
initP p@(P p') = P $ M.map initClass p'
where
initClass :: Class -> Class
initClass c =
let sups = supClassesf p (className c) in
c { supClasses = sups
, subClasses = subClassesf p (className c)
, hasFieldz = hasFieldzf p sups
}
supClassesf :: Program -> ClassId -> [ClassId]
supClassesf p cn = reverse $ supClassesf' cn [cn]
where
supClassesf' cn1 cns = case supClassf p cn1 of
Nothing -> cns
Just cn2 -> supClassesf' cn2 (cn2:cns)
supClassf :: Program -> ClassId -> Maybe ClassId
supClassf p = supClass . classOf p
classOf :: Program -> ClassId -> Class
classOf (P cp) cn = errMsg `fromMaybe` M.lookup cn cp
where errMsg = error $ "Jat.Program.Data.classOf: element not found" ++ show cn
isSuper :: Program -> ClassId -> ClassId -> Bool
isSuper p cn cn' = cn `elem` supClassesf p cn'
subClassesf :: Program -> ClassId -> [ClassId]
subClassesf p@(P cp) cn = filter (isSuper p cn) (M.keys cp)
hasFieldzf :: Program -> [ClassId] -> [(FieldId, ClassId, Type)]
hasFieldzf p = concatMap (\cn' -> fds cn' . fieldPool $ classOf p cn')
where fds cn = M.foldr (\lfd lfdt -> (fieldName lfd, cn,fieldType lfd):lfdt) []
-- pretty
instance Pretty FieldId where
pretty (FieldId fn) = string fn
instance Pretty ClassId where
pretty (ClassId cn) = string cn
instance Pretty MethodId where
pretty (MethodId mn) = string mn
instance Pretty Class where
pretty c = text "Class:" <$> indent 2 prettyName <$> indent 2 prettyBody
where
prettyName = text "Name:" <+> pretty (className c)
prettyBody = text "ClassBody:" <$> indent 2 prettySuper <$> indent 2 prettyFields <$> indent 2 prettyMethods
prettySuper = text "Superclass:" <+> case supClass c of {Just c' -> pretty c'; Nothing -> text "<None>"}
prettyFields = text "Fields:" <$> indent 2 (vcat (map pretty . M.elems $ fieldPool c))
prettyMethods = text "Methods:" <$> indent 2 (vcat (map pretty . M.elems $ methodPool c))
instance Pretty Field where
pretty f = pretty (fieldType f) <+> pretty (fieldName f)
instance Pretty Method where
pretty m = prettyHeader <$> indent 2 prettyParams <$> indent 2 prettyBody
where
prettyHeader = text "Method:" <+> pretty (methodReturn m) <+> pretty (methodName m)
prettyParams = text "Parameters:" <$> (indent 2 . vcat $ map pretty (methodParams m))
prettyBody = text "Methodbody:" <$> indent 2 prettyMaxStack <$> indent 2 prettyMaxLoc <$> indent 2 prettyInstructions
prettyMaxStack = text "MaxStack:" <$> indent 2 (int $ maxStk m)
prettyMaxLoc = text "MaxVars:" <$> indent 2 (int $ maxLoc m)
prettyInstructions = text "Bytecode:" <$> (indent 2 . vcat $ zipWith (\c i -> int c <+> colon <+> pretty i) [0..] (elems $ methodInstructions m))
instance Pretty Type where
pretty BoolType = text "bool"
pretty IntType = text "int"
pretty (RefType cn) = pretty cn
pretty (NullType) = text "NT"
pretty Void = text "void"
instance Pretty Value where
pretty (BoolVal b) = text $ show b
pretty (IntVal i) = int i
pretty (RefVal a) = int a
pretty Null = text "null"
pretty Unit = text "unit"
instance Pretty Instruction where
pretty (Load i) = text "Load" <+> int i
pretty (Store i) = text "Store" <+> int i
pretty (Push v) = text "Push" <+> pretty v
pretty (New cn) = text "New" <+> pretty cn
pretty (GetField fn cn) = text "GetField" <+> pretty fn <+> pretty cn
pretty (PutField fn cn) = text "PutField" <+> pretty fn <+> pretty cn
pretty (CheckCast cn) = text "CheckCast" <+> pretty cn
pretty (Invoke mn i) = text "Invoke" <+> pretty mn <+> int i
pretty Return = text "Return"
pretty Pop = text "Pop"
pretty IAdd = text "IAdd"
pretty ICmpGeq = text "CmpGeq"
pretty (Goto i) = text "Goto" <+> int i
pretty CmpEq = text "CmpEq"
pretty CmpNeq = text "CmpNeq"
pretty (IfFalse i) = text "IfFalse" <+> int i
pretty ISub = text "ISub"
pretty BNot = text "Not"
pretty BAnd = text "And"
pretty BOr = text "Or"
instance Pretty Program where
pretty p = vsep prettyClasses
where
cs = case p of P cs' -> M.elems cs'
prettyClasses = map pretty cs
|
ComputationWithBoundedResources/jat
|
src/Jinja/Program/Data.hs
|
bsd-3-clause
| 8,171 | 0 | 16 | 2,101 | 2,684 | 1,395 | 1,289 | 205 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
module Structure.Monadiclasses.Functor.Monad.Continuation (
Continuation(..)
) where
import Structure.Function
import Structure.Monadiclasses.Functor
import Structure.Monadiclasses.Functor.Monad
class (Monad m) => Continuation m where
callCC :: ((a -> m b) -> m a) -> m a
callCC = undefined
|
Hexirp/monadiclasses
|
src/Structure/Monadiclasses/Functor/Monad/Continuation.hs
|
bsd-3-clause
| 363 | 0 | 12 | 75 | 92 | 54 | 38 | 9 | 0 |
--
-- String munging common across modules.
--
-- (c) 2015 Galois, Inc.
--
module Tower.AADL.Names
( periodicEmitter
, periodicCallback
, signalEmitter
, signalCallback
, systemInit
, initEmitter
, initCallback
, prettyTime
, threadFile
, threadEmitterHeader
, smaccmPrefix
) where
import qualified Ivory.Tower.AST as A
import qualified Ivory.Tower.Types.Time as T
import qualified Ivory.Tower.AST.Period as P
import qualified Ivory.Tower.AST.Signal as S
-- add aadl2rtos prefix
smaccmPrefix :: String -> String
smaccmPrefix = ("smaccm_" ++)
threadEmitterHeader :: A.Thread -> String
threadEmitterHeader t =
smaccmPrefix $ A.threadName t ++ ".h"
------------------------------------------------------------
periodicEmitter :: P.Period -> String
periodicEmitter p = "emitter_" ++ prettyTime p
periodicCallback :: P.Period -> String
periodicCallback p = "callback_" ++ prettyTime p
------------------------------------------------------------
systemInit :: String
systemInit = "systemInit"
initEmitter :: String
initEmitter = "emitter_" ++ systemInit
initCallback :: String
initCallback = "callback_" ++ systemInit
------------------------------------------------------------
signalEmitter :: S.Signal -> String
signalEmitter s = "emitter_" ++ S.signal_name s
signalCallback :: S.Signal -> String
signalCallback s = "callback_" ++ S.signal_name s
------------------------------------------------------------
prettyTime :: P.Period -> String
prettyTime p = T.prettyTime (P.period_dt p)
threadFile :: A.Monitor -> String
threadFile m = A.monitorName m ++ "_monitor"
|
GaloisInc/tower
|
tower-aadl/src/Tower/AADL/Names.hs
|
bsd-3-clause
| 1,612 | 0 | 8 | 234 | 347 | 202 | 145 | 39 | 1 |
module MB.Gen.RSS
( generateRssFeed
)
where
import Control.Applicative ((<|>))
import Data.Time.Format
( formatTime
, parseTime
)
import System.Locale
( rfc822DateFormat
)
import Data.Time.Format (defaultTimeLocale)
import MB.Types
import MB.Processing ( getRawPostTitle )
import MB.Templates
rssItem :: Blog -> Post -> String
rssItem blog p =
concat [ "<item>"
, "<title>" ++ getRawPostTitle blog p ++ "</title>\n"
, "<link>" ++ baseUrl blog ++ postUrl p ++ "</link>\n"
, "<pubDate>" ++ rssModificationTime p ++ "</pubDate>\n"
, "<guid>" ++ baseUrl blog ++ postUrl p ++ "</guid>\n"
, "</item>\n"
]
generateRssFeed :: Blog -> Template -> String
generateRssFeed blog tmpl =
let items = map (rssItem blog) $ blogPosts blog
itemStr = concat items
attrs = [ ("items", itemStr)
]
in fillTemplate blog tmpl attrs
rssModificationTime :: Post -> String
rssModificationTime p =
let Just t = parsed <|> (Just $ postModificationTime p)
parsed = parseTime defaultTimeLocale "%B %e, %Y" =<< postDate p
in formatTime defaultTimeLocale rfc822DateFormat t
|
jtdaugherty/mathblog
|
src/MB/Gen/RSS.hs
|
bsd-3-clause
| 1,198 | 0 | 12 | 311 | 332 | 175 | 157 | 31 | 1 |
module Numeric.MaxEnt.Deconvolution (
module Numeric.MaxEnt.Deconvolution.Internal
) where
import Numeric.MaxEnt.Deconvolution.Internal
|
jfischoff/Sharpen
|
src/Numeric/MaxEnt/Deconvolution.hs
|
bsd-3-clause
| 139 | 0 | 5 | 12 | 24 | 17 | 7 | 3 | 0 |
-- 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.
module Duckling.Duration.AR.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Duration.AR.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "AR Tests"
[ makeCorpusTest [Seal Duration] corpus
]
|
facebookincubator/duckling
|
tests/Duckling/Duration/AR/Tests.hs
|
bsd-3-clause
| 509 | 0 | 9 | 80 | 79 | 50 | 29 | 11 | 1 |
module Language.Iso.Target.Scheme where
import Language.Iso.App
import Language.Iso.Fls
import Language.Iso.Ite
import Language.Iso.Lam
import Language.Iso.Tru
import Language.Iso.Var
newtype Scheme = Scheme { runScheme :: String }
instance Show Scheme where
show (Scheme ps) = ps
instance Var Scheme where
var x = Scheme x
instance Lam Scheme where
lam v b = Scheme $ "(lambda (" ++ v ++ ") " ++ runScheme b ++ ")"
instance App Scheme where
app f x = Scheme $ "(" ++ runScheme f ++ " " ++ runScheme x ++ ")"
instance Fls Scheme where
fls = Scheme "#f"
instance Ite Scheme where
ite b t f= Scheme $
"(if " ++ runScheme b ++ " "
++ runScheme t ++ " "
++ runScheme f ++ ")"
instance Tru Scheme where
tru = Scheme "#t"
|
joneshf/iso
|
src/Language/Iso/Target/Scheme.hs
|
bsd-3-clause
| 813 | 0 | 12 | 228 | 272 | 143 | 129 | 25 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Netsuite.Restlet.Response (
RestletResponse (..),
RestletError (..),
interpretError
) where
import Data.Aeson
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.HashMap.Strict as HM
import Data.Monoid
import qualified Data.Text as Text
import Netsuite.Restlet.ResponseHandler
-- | Response type
data RestletResponse = RestletOk [BS.ByteString]
| RestletErrorResp HttpRestletError deriving (Show)
instance Monoid RestletResponse where
mappend (RestletOk x) (RestletOk y) = RestletOk (x ++ y)
mappend (RestletOk x) (RestletErrorResp _) = RestletOk x
mappend (RestletErrorResp x) _ = RestletErrorResp x
mempty = RestletOk []
-- | Response error
data RestletError = NotFound Int String
| ResourceConflict Int String
| InvalidSearchFilter Int String
| CCProcessorError Int String
| BeginChunking Int
| EndChunking Int
| UnknownError Int String BS.ByteString
| GibberishError Int String BS.ByteString deriving (Eq, Show)
interpretError :: RestletResponse -> RestletError
interpretError (RestletErrorResp e) = uncurry interpretError' e'
where
e' = httpClientErrorCodeBody e
interpretError _ = error "We should not be here"
httpClientErrorCodeBody :: HttpRestletError -> (Int, BS.ByteString)
httpClientErrorCodeBody (HttpRestletError code _ _ body) = (code, body)
-- | Interpret error message as a data type
interpretError' :: Int -> BS.ByteString -> RestletError
interpretError' http_code es = case mightValue of
Nothing -> GibberishError http_code "Unparseable response, expecting JSON." es
Just jv@Object{} ->
let
em = getErrorMessage jv
in case getVal jv ["error", "code"] of
Just "RCRD_DOESNT_EXIST" -> NotFound http_code em
Just "SSS_INVALID_SRCH_FILTER" -> InvalidSearchFilter http_code em
Just "CC_PROCESSOR_ERROR" -> CCProcessorError http_code em
Just x ->
if Text.isSuffixOf (Text.pack "_ALREADY_EXISTS") x
then ResourceConflict http_code em
else interpretErrorMsg http_code em es
Nothing -> interpretErrorMsg http_code em es
Just _ -> GibberishError http_code "Couldn't extract meaningful error object." es
where
mightValue = decode (BSL.fromStrict es) :: Maybe Value
-- | Get textual error message
getErrorMessage :: Value -> String
getErrorMessage v = maybe "" Text.unpack $ getVal v ["error", "message"]
-- | Get item from deep down in object tree
getVal :: Value -> [String] -> Maybe Text.Text
getVal (Object v) (key:xs) = case HM.lookup (Text.pack key) v of
Nothing -> Nothing
Just v' -> case length xs of
0 -> case v' of
String x -> Just x
y -> Just . Text.pack . show $ y
_ -> getVal v' xs
getVal _ [] = error "Netsuite.Restlet.Response.getVal: Tried to get a key that wasn't there."
-- | Get special error message meaning
interpretErrorMsg :: Int -> String -> BS.ByteString -> RestletError
interpretErrorMsg http_code msg body =
case msg of
"CHUNKY_MONKEY" -> BeginChunking http_code
"NO_MORE_CHUNKS" -> EndChunking http_code
y -> UnknownError http_code y body
|
anchor/haskell-netsuite
|
lib/Netsuite/Restlet/Response.hs
|
bsd-3-clause
| 3,543 | 0 | 17 | 988 | 854 | 445 | 409 | 67 | 8 |
{-# LANGUAGE TemplateHaskell #-}
module Orbits.Simulation
( Simulation(Simulation)
, getBodies
, getEnergy
, doStep
) where
import Control.Lens
import Data.Vector (Vector)
import Numeric.Units.Dimensional (Time)
import Numeric.Units.Dimensional.Quantities (Energy)
import Orbits.System (Body)
-- | A simulation of several bodies interacting gravitationally
data Simulation m a = Simulation
-- | Get the current bodies
{ _getBodies :: m (Vector (Body a))
-- | Compute the energy of the system.
-- This is a useful proxy for simulation stability because the energy should
-- not change.
, _getEnergy :: m (Energy a)
-- | Execute one simulation step, advancing time by the specified amount.
, _doStep :: Time a -> m ()
}
makeLenses ''Simulation
|
bjoeris/orbits-haskell-tensorflow
|
src/Orbits/Simulation.hs
|
bsd-3-clause
| 781 | 0 | 13 | 150 | 152 | 91 | 61 | 19 | 0 |
{-# LANGUAGE CPP #-}
{- |
Module : System.Log.Handler.Log4jXML
Copyright : Copyright (C) 2007-2011 John Goerzen
License : BSD3
Portability: GHC only?
log4j[1] XMLLayout log handlers.
Written by Bjorn Buckwalter, bjorn.buckwalter\@gmail.com
-}
module System.Log.Handler.Log4jXML (
-- * Introduction
{- | This module provides handlers for hslogger that are
compatible with log4j's XMLLayout. In particular log messages
created by the handlers can be published directly to the GUI-based
log viewer Chainsaw v2[2].
The set of log levels in hslogger is richer than the basic set
of log4j levels. Two sets of handlers are provided with hslogger4j,
one which produces logs with hslogger's levels and one which
\"demotes\" them to the basic log4j levels. If full hslogger
levels are used some Java installation (see below) is necessary
to make Chainsaw aware of them.
Usage of the handlers in hslogger4j is analoguous to usage of
the 'System.Log.Handler.Simple.StreamHandler' and
'System.Log.Handler.Simple.FileHandler' in "System.Log.Handler.Simple".
The following handlers are provided: -}
-- ** Handlers with hslogger levels
log4jStreamHandler,
log4jFileHandler,
-- ** Handlers with log4j levels
log4jStreamHandler',
log4jFileHandler'
-- * Java install process
{- | This is only necessary if you want to use the hslogger levels.
Add @hslogger4j.jar@ from @contrib\/java@ to your classpath.
To use you will also need to have the jars @log4j-1.3alpha-7.jar@
and @log4j-xml-1.3alpha-7.jar@ that are distributed with Chainsaw
on your classpath.
(On Mac OS X I added all three jars to @~\/Library\/Java\/Extensions@.
It seems that it is not sufficient that Chainsaw already includes
its jars in the classpath when launching - perhaps the plugin
classloader does not inherit Chainsaw's classpath. Adding the
jars to @~\/.chainsaw\/plugins@ wouldn't work either.)
If for whatever reason you have to rebuild the hslogger4j jar
just run @ant@[3] in the @contrib\/java@ directory. The new jar
will be created in the @contrib\/java\/dist@ directory. The Java
source code is copyright The Apache Software Foundation and
licensed under the Apache Licence version 2.0. -}
-- * Chainsaw setup
{- | If you are only using the basic log4j levels just use
Chainsaw's regular facilities to browse logs or listen for log
messages (e.g. @XMLSocketReceiver@).
If you want to use the hslogger levels the easiest way to set
up Chainsaw is to load the plugins in @hslogger4j-plugins.xml@
in @contrib\/java@ when launching Chainsaw. Two receivers will
be defined, one that listens for logmessages and one for reading
log files. Edit the properties of those receivers as needed
(e.g. @port@, @fileURL@) and restart them. You will also want
to modify Chainsaw's formatting preferences to display levels
as text instead of icons. -}
-- * Example usage
{- | In the IO monad:
> lh2 <- log4jFileHandler "log.xml" DEBUG
> updateGlobalLogger rootLoggerName (addHandler lh2)
> h <- connectTo "localhost" (PortNumber 4448)
> lh <- log4jStreamHandler h NOTICE
> updateGlobalLogger rootLoggerName (addHandler lh)
-}
-- * References
{- |
(1) <http://logging.apache.org/log4j/>
(2) <http://logging.apache.org/chainsaw/>
(3) <http://ant.apache.org/>
-}
) where
import Control.Concurrent (myThreadId) -- myThreadId is GHC only!
import Data.List (isPrefixOf)
import System.IO
#if MIN_VERSION_time(1,5,0)
import Data.Time.Format (defaultTimeLocale)
#else
import System.Locale (defaultTimeLocale)
#endif
import Data.Time
import System.Log
import System.Log.Handler
import System.Log.Handler.Simple (streamHandler, GenericHandler(..))
-- Handler that logs to a handle rendering message priorities according
-- to the supplied function.
log4jHandler :: (Priority -> String) -> Handle -> Priority -> IO (GenericHandler Handle)
log4jHandler showPrio h pri = do
hndlr <- streamHandler h pri
return $ setFormatter hndlr xmlFormatter
where
-- A Log Formatter that creates an XML element representing a log4j event/message.
xmlFormatter :: a -> (Priority,String) -> String -> IO String
xmlFormatter _ (prio,msg) logger = do
time <- getCurrentTime
thread <- myThreadId
return . show $ Elem "log4j:event"
[ ("logger" , logger )
, ("timestamp", millis time )
, ("level" , showPrio prio)
, ("thread" , show thread )
]
(Just $ Elem "log4j:message" [] (Just $ CDATA msg))
where
-- This is an ugly hack to get a unix epoch with milliseconds.
-- The use of "take 3" causes the milliseconds to always be
-- rounded downwards, which I suppose may be the expected
-- behaviour for time.
millis t = formatTime defaultTimeLocale "%s" t
++ (take 3 $ formatTime defaultTimeLocale "%q" t)
-- | Create a stream log handler that uses hslogger priorities.
log4jStreamHandler :: Handle -> Priority -> IO (GenericHandler Handle)
log4jStreamHandler = log4jHandler show
{- | Create a stream log handler that uses log4j levels (priorities). The
priorities of messages are shoehorned into log4j levels as follows:
@
DEBUG -> DEBUG
INFO, NOTICE -> INFO
WARNING -> WARN
ERROR, CRITICAL, ALERT -> ERROR
EMERGENCY -> FATAL
@
This is useful when the log will only be consumed by log4j tools and
you don't want to go out of your way transforming the log or configuring
the tools. -}
log4jStreamHandler' :: Handle -> Priority -> IO (GenericHandler Handle)
log4jStreamHandler' = log4jHandler show' where
show' :: Priority -> String
show' NOTICE = "INFO"
show' WARNING = "WARN"
show' CRITICAL = "ERROR"
show' ALERT = "ERROR"
show' EMERGENCY = "FATAL"
show' p = show p -- Identical for DEBUG, INFO, ERROR.
-- | Create a file log handler that uses hslogger priorities.
log4jFileHandler :: FilePath -> Priority -> IO (GenericHandler Handle)
log4jFileHandler fp pri = do
h <- openFile fp AppendMode
sh <- log4jStreamHandler h pri
return (sh{closeFunc = hClose})
{- | Create a file log handler that uses log4j levels (see
'log4jStreamHandler'' for mappings). -}
log4jFileHandler' :: FilePath -> Priority -> IO (GenericHandler Handle)
log4jFileHandler' fp pri = do
h <- openFile fp AppendMode
sh <- log4jStreamHandler' h pri
return (sh{closeFunc = hClose})
-- A type for building and showing XML elements. Could use a fancy XML
-- library but am reluctant to introduce dependencies.
data XML = Elem String [(String, String)] (Maybe XML)
| CDATA String
instance Show XML where
show (CDATA s) = "<![CDATA[" ++ escapeCDATA s ++ "]]>" where
escapeCDATA = replace "]]>" "]]<" -- The best we can do, I guess.
show (Elem name attrs child) = "<" ++ name ++ showAttrs attrs ++ showChild child where
showAttrs [] = ""
showAttrs ((k,v):as) = " " ++ k ++ "=\"" ++ escapeAttr v ++ "\""
++ showAttrs as
where escapeAttr = replace "\"" """
. replace "<" "<"
. replace "&" "&"
showChild Nothing = "/>"
showChild (Just c) = ">" ++ show c ++ "</" ++ name ++ ">"
-- Replaces instances of first list by second list in third list.
-- Definition blatantly stoled from jethr0's comment at
-- http://bluebones.net/2007/01/replace-in-haskell/. Can be swapped
-- with definition (or import) from MissingH.
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace _ _ [ ] = []
replace from to xs@(a:as) = if isPrefixOf from xs
then to ++ drop (length from) xs else a : replace from to as
|
jgoerzen/hslogger
|
src/System/Log/Handler/Log4jXML.hs
|
bsd-3-clause
| 8,330 | 0 | 16 | 2,270 | 1,011 | 539 | 472 | 69 | 6 |
-- | Base import. Imports the flexible version of the library which uses
-- Repa co-ordinates for access (allowing you to express moves in greater
-- than 3 dimensions and to perform analysis on the underlying Repa
-- representation of the board, if you want).
--
-- If you want a simpler interface using (x, y) tuples and/or don't want to
-- pull in the Repa dependency, import "Game.Go.Simple" instead.
module Game.Go
( module Game.Go.Game
, module Game.Go.Board
, module Game.Go.Rules
) where
import Game.Go.Game
import Game.Go.Board
import Game.Go.Rules
|
dpwright/igo
|
src/Game/Go.hs
|
bsd-3-clause
| 569 | 0 | 5 | 100 | 54 | 39 | 15 | 7 | 0 |
module Brain.Nop where
import Logic
import Brain
-- | The brain that always suggests 'nop'.
nopBrain :: Brain
nopBrain = simpleBrain (const nop)
|
sjoerdvisscher/icfp2011
|
src/Brain/Nop.hs
|
bsd-3-clause
| 147 | 0 | 7 | 25 | 32 | 19 | 13 | 5 | 1 |
module Servant (
-- | This module and its submodules can be used to define servant APIs. Note
-- that these API definitions don't directly implement a server (or anything
-- else).
module Servant.API,
-- | For implementing servers for servant APIs.
module Servant.Server,
-- | Using your types in request paths and query string parameters
module Servant.Common.Text,
-- | Utilities on top of the servant core
module Servant.QQ,
module Servant.Utils.Links,
module Servant.Utils.StaticFiles,
-- | Useful re-exports
Proxy(..),
) where
import Data.Proxy
import Servant.API
import Servant.Common.Text
import Servant.Server
import Servant.QQ
import Servant.Utils.Links
import Servant.Utils.StaticFiles
|
derekelkins/servant-server
|
src/Servant.hs
|
bsd-3-clause
| 727 | 0 | 5 | 125 | 98 | 68 | 30 | 15 | 0 |
import System.IO
import Data.Char (ord)
import Data.Binary
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
eurusdFileP = "EurUsdPacked.bin"
main :: IO ()
main = do
hp <- openFile eurusdFileP ReadMode
-- get all chars
L.hGet hp 3 >>= print
-- get last char ('R') of EUR
hSeek hp AbsoluteSeek 2
L.hGet hp 1 >>= print
|
thlorenz/Pricetory
|
src/spikes/ReadByteStringFromFile.hs
|
bsd-3-clause
| 376 | 0 | 9 | 85 | 110 | 59 | 51 | 12 | 1 |
module Emx.Track where
data Track = Tr {artist, album, title, ext, dlurl, label, arturl,
tracknum, genre :: String,
disccount, discnum, trackcount :: Int } deriving Show
|
bwo/getemx
|
Emx/Track.hs
|
bsd-3-clause
| 205 | 0 | 8 | 61 | 50 | 39 | 11 | 4 | 0 |
module Str where
import Language.Haskell.TH
import Language.Haskell.TH.Quote
str :: QuasiQuoter
str = QuasiQuoter
{ quoteExp = stringE
, quotePat = undefined
, quoteType = undefined
, quoteDec = undefined
}
|
m-schmidt/fuzzer
|
src/Str.hs
|
bsd-3-clause
| 232 | 0 | 6 | 55 | 53 | 35 | 18 | 9 | 1 |
{-# LANGUAGE TemplateHaskell
,ExistentialQuantification
,PolyKinds
,DataKinds #-}
module UnitB.FunctionTable.Spec.Doc where
import Control.Lens
import Control.Lens.Bound
import Control.Monad.Writer hiding (All)
import Data.Bitraversable
import Data.Char
import Data.Constraint
import Data.Existential
import Data.List.Lens
import Data.String hiding (lines)
import Data.String.Lines
import Data.String.Utils
import Data.Vector.Sized (Vector,toList)
-- import Data.Vector.Sized.Quote
import Data.Type.Natural
import Data.Typeable
import Prelude hiding (lines)
import GHC.Generics (Generic)
import Language.Haskell.Meta.Parse
import Language.Haskell.TH
import Language.Haskell.TH.Quote
newtype Table a = Tbl { _tableCell :: Cell1 (TableIntl a) All }
deriving (Generic)
data TableIntl a n = TblIntl (Dict (SingI n,Eq a)) (Vector a n) [Vector a n]
deriving (Eq,Ord,Show,Generic)
makeFields ''Table
data Doc =
Title Int String
| Ct Content
deriving (Eq,Ord,Show,Generic)
type URI = String
data Color = Red | Yellow | Green
deriving (Eq,Ord,Show,Generic,Enum,Bounded)
data FormatCell = FormatCell (Maybe Color) String
deriving (Eq,Ord,Show,Generic)
data Content =
Line String
| Item [Content]
| Enum [Content]
| Image Content URI
| Link Content URI
| Bold [Content]
| Italics [Content]
| StrikeThrough [Content]
| DocTable (Table FormatCell)
| Seq Content Content
| Nil
| Verbatim (Maybe String) String
deriving (Eq,Ord,Show,Generic)
instance (Typeable a,Eq a) => Eq (Table a) where
(==) = cell1Equal' (==)
instance (Typeable a,Ord a) => Ord (Table a) where
compare = cell1Compare' compare
instance Show a => Show (Table a) where
show = readCell1' show
class Monoid out => DocFormat out where
renderDoc :: Doc -> out
class Monad m => DocBuilder m where
emitContent :: Content -> m ()
runDoc :: DocFormat out => Writer [Doc] k -> out
runDoc = runIdentity . runDocT
runDocT :: (Monad m,DocFormat out) => WriterT [Doc] m k -> m out
runDocT = fmap (mconcat . fmap renderDoc) . execWriterT
instance IsString Doc where
fromString = Ct . Line
instance IsString FormatCell where
fromString = FormatCell Nothing
instance IsString Content where
fromString = Line
instance Monoid Content where
mempty = Nil
mappend Nil x = x
mappend x Nil = x
mappend (Seq x y) z = Seq x $ y `mappend` z
mappend x y = Seq x y
toInt :: Dict (SingI n, Eq a) -> SNat n -> Int
toInt _ = sNatToInt
columns :: Table a -> Int
columns = readCell1' columns'
columns' :: TableIntl a n -> Int
columns' (TblIntl d@Dict _ _) = toInt d sing
heading :: Table t -> [t]
heading (Tbl (Cell (TblIntl _ t _))) = toList t
rows :: Table t -> [[t]]
rows (Tbl (Cell (TblIntl _ _ ts))) = map toList ts
makeDocTable :: (DocBuilder m,SingI n,Typeable n)
=> Vector FormatCell n -> [Vector FormatCell n] -> m ()
makeDocTable h ts = emitContent $ docTable h ts
docTable :: (SingI n,Typeable n)
=> Vector FormatCell n -> [Vector FormatCell n] -> Content
docTable h ts = DocTable . makeCell1 $ TblIntl Dict h ts
text :: DocBuilder m => String -> m ()
text = emitContent . Line
paragraph :: DocBuilder m => m a -> m a
paragraph txt = text "\n" >> txt <* text "\n"
newtype ListEnv a = ListEnv (Writer [Content] a)
deriving (Functor,Applicative,Monad)
listBullet :: DocBuilder m => ListEnv a -> m a
listBullet (ListEnv cmd) = do
let (x,is) = runWriter cmd
emitContent $ Item is
return x
listNum :: DocBuilder m => ListEnv a -> m a
listNum (ListEnv cmd) = do
let (x,is) = runWriter cmd
emitContent $ Enum is
return x
newtype ContentWriter a = ContentWriter (Writer [Content] a)
deriving (Functor,Applicative,Monad)
instance DocBuilder ContentWriter where
emitContent = ContentWriter . tell . pure
instance a ~ () => IsString (ContentWriter a) where
fromString = ContentWriter . tell . pure . Line
execContentWriter :: ContentWriter a -> [Content]
execContentWriter (ContentWriter cmd) = execWriter cmd
item :: ContentWriter a -> ListEnv a
item (ContentWriter cmd) = do
let (x,is) = runWriter cmd
ListEnv $ tell [mconcat is]
return x
image :: DocBuilder m
=> ContentWriter a
-> FilePath
-> m a
image (ContentWriter cmd) lnk = do
let (x,is) = runWriter cmd
emitContent $ Image (mconcat is) lnk
return x
link :: DocBuilder m
=> ContentWriter a
-> FilePath
-> m a
link (ContentWriter cmd) lnk = do
let (x,is) = runWriter cmd
emitContent $ Link (mconcat is) lnk
return x
nest :: DocBuilder m
=> ([Content] -> Content)
-> ContentWriter a
-> m a
nest f (ContentWriter cmd) = emitContent (f w) >> return x
where
(x,w) = runWriter cmd
strike :: DocBuilder m
=> ContentWriter a -> m a
strike = nest StrikeThrough
bold :: DocBuilder m
=> ContentWriter a -> m a
bold = nest Bold
italics :: DocBuilder m
=> ContentWriter a -> m a
italics = nest Italics
trimLines :: String -> String
trimLines xs
| Just n' <- n = xs & traverseLines %~ drop n'
| otherwise = xs
where
n = minimumOf (traverse.filtered (not . all isSpace).to (length.takeWhile (' ' ==))) $ lines xs
verbatim :: QuasiQuoter
verbatim = QuasiQuoter
{ quoteExp = \s -> [| emitContent $ Verbatim Nothing $ trimLines s |]
, quoteDec = undefined
, quoteType = undefined
, quotePat = undefined }
quoteSyntax :: String -> ExpQ
quoteSyntax xs
| Just s' <- s^?prefixed "|" = [| emitContent $ Verbatim (Just lang) $ trimLines s' |]
| otherwise = error "invalid syntax: expecting '|'"
where
(lang,s) = span (/= '|') xs
syntax :: QuasiQuoter
syntax = QuasiQuoter
{ quoteExp = quoteSyntax
, quoteDec = undefined
, quoteType = undefined
, quotePat = undefined }
mkQuoted :: String -> ExpQ
mkQuoted str = case parseExp str' of
Left msg -> fail $ "Could not parse expression. " ++ msg
Right exp -> [e|
( $(pure exp)
, emitContent (Verbatim (Just "haskell") $(stringE $ trimLines str'))) |]
where
str' = replace "\\]" "|]" str
quoted :: QuasiQuoter
quoted = QuasiQuoter
{ quoteExp = \str -> [e| void $ bitraverse id id $(mkQuoted str) |]
, quoteDec = undefined
, quoteType = undefined
, quotePat = undefined }
listing :: QuasiQuoter
listing = QuasiQuoter
{ quoteExp = \str -> [e| fst <$> bitraverse return id $(mkQuoted str) |]
, quoteDec = undefined
, quoteType = undefined
, quotePat = undefined }
exec :: QuasiQuoter
exec = QuasiQuoter
{ quoteExp = \str -> [e| snd <$> bitraverse id return $(mkQuoted str) |]
, quoteDec = undefined
, quoteType = undefined
, quotePat = undefined }
|
unitb/logic-function-tables
|
src/UnitB/FunctionTable/Spec/Doc.hs
|
bsd-3-clause
| 7,029 | 0 | 14 | 1,828 | 2,458 | 1,291 | 1,167 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
module Penny.Price.Internal where
import Control.Lens
import Penny.Commodity
import Data.Map (Map)
import qualified Data.Map as M
import Data.Time
import Penny.Decimal
type FromCy = Commodity
type ToCy = Commodity
data FromTo = FromTo
{ fromCy :: Commodity
, toCy :: Commodity
} deriving (Eq, Ord, Show)
makeFromTo
:: Commodity
-- ^ From this commodity
-> Commodity
-- ^ To this commodity
-> Maybe FromTo
makeFromTo fr to
| fr /= to = Just $ FromTo fr to
| otherwise = Nothing
convertQty
:: Decimal
-- ^ Price
-> Decimal
-- ^ Quantity
-> Decimal
-- ^ New quantity
convertQty exch orig = exch * orig
newtype PriceDb = PriceDb
(Map FromCy (Map ToCy (Map UTCTime Decimal)))
deriving Show
data Price a = Price
{ _zonedTime :: ZonedTime
, _fromTo :: FromTo
, _exch :: Decimal
, _location :: a
} deriving (Show, Functor, Foldable, Traversable)
makeLenses ''Price
emptyDb :: PriceDb
emptyDb = PriceDb M.empty
addPriceToDb :: PriceDb -> Price a -> PriceDb
addPriceToDb (PriceDb db) (Price dt (FromTo fr to) exch _)
= PriceDb . M.alter fToMap fr $ db
where
utct = zonedTimeToUTC dt
fToMap mayToMap = case mayToMap of
Nothing -> Just (M.singleton to (M.singleton utct exch))
Just toMap -> Just $ M.alter fUTCmap to toMap
where
fUTCmap mayUTCmap = case mayUTCmap of
Nothing -> Just $ M.singleton utct exch
Just utcMap -> Just $ M.insert utct exch utcMap
data ExchLookupError
= FromCommodityNotFound
| ToCommodityNotFound
| NoPreviousPrice
deriving (Eq, Ord, Show)
lookupExch
:: FromTo
-> ZonedTime
-> PriceDb
-> Either ExchLookupError (UTCTime, Decimal)
lookupExch (FromTo fr to) dt (PriceDb db) = do
let utct = zonedTimeToUTC dt
toMap <- maybe (Left FromCommodityNotFound) Right
. M.lookup fr $ db
timeMap <- maybe (Left ToCommodityNotFound) Right
. M.lookup to $ toMap
maybe (Left NoPreviousPrice) Right
. M.lookupLT utct $ timeMap
|
massysett/penny
|
penny/lib/Penny/Price/Internal.hs
|
bsd-3-clause
| 2,082 | 0 | 17 | 468 | 668 | 348 | 320 | 67 | 3 |
{-# LANGUAGE TypeFamilies, ConstraintKinds, PatternSynonyms #-}
-- | This module is used for defining Shake build systems. As a simple example of a Shake build system,
-- let us build the file @result.tar@ from the files listed by @result.txt@:
--
-- @
-- import "Development.Shake"
-- import "Development.Shake.FilePath"
--
-- main = 'shakeArgs' 'shakeOptions' $ do
-- 'want' [\"result.tar\"]
-- \"*.tar\" '%>' \\out -> do
-- contents \<- 'readFileLines' $ out 'Development.Shake.FilePath.-<.>' \"txt\"
-- 'need' contents
-- 'cmd' \"tar -cf\" [out] contents
-- @
--
-- We start by importing the modules defining both Shake and routines for manipulating 'FilePath' values.
-- We define @main@ to call 'shake' with the default 'shakeOptions'. As the second argument to
-- 'shake', we provide a set of rules. There are two common forms of rules, 'want' to specify target files,
-- and '%>' to define a rule which builds a 'FilePattern'. We use 'want' to require that after the build
-- completes the file @result.tar@ should be ready.
--
-- The @*.tar@ rule describes how to build files with the extension @.tar@, including @result.tar@.
-- We 'readFileLines' on @result.txt@, after changing the @.tar@ extension to @.txt@. We read each line
-- into the variable @contents@ -- being a list of the files that should go into @result.tar@. Next, we
-- depend ('need') all the files in @contents@. If any of these files change, the rule will be repeated.
-- Finally we call the @tar@ program. If either @result.txt@ changes, or any of the files listed by @result.txt@
-- change, then @result.tar@ will be rebuilt.
--
-- To find out more:
--
-- * The user manual contains a longer example and background information on how to use Shake
-- <https://www.shakebuild.com/manual>.
--
-- * The home page has links to additional information <https://www.shakebuild.com/>, including
-- a mailing list.
--
-- * The theory behind Shake is described in an ICFP 2012 paper,
-- <https://ndmitchell.com/downloads/paper-shake_before_building-10_sep_2012.pdf Shake Before Building -- Replacing Make with Haskell>.
-- The <https://www.youtube.com/watch?v=xYCPpXVlqFM associated talk> forms a short overview of Shake.
module Development.Shake(
-- * Writing a build system
-- $writing
-- * GHC build flags
-- $flags
-- * Other Shake modules
-- $modules
-- * Core
shake,
shakeOptions,
Rules, action, withoutActions, alternatives, priority, versioned,
Action, traced,
liftIO, actionOnException, actionFinally, actionBracket, actionCatch, actionRetry, runAfter,
ShakeException(..),
-- * Configuration
ShakeOptions(..), Rebuild(..), Lint(..), Change(..),
getShakeOptions, getShakeOptionsRules, getHashedShakeVersion,
getShakeExtra, getShakeExtraRules, addShakeExtra,
-- ** Command line
shakeArgs, shakeArgsWith, shakeArgsOptionsWith, shakeOptDescrs, addHelpSuffix,
-- ** Targets
getTargets, addTarget, withTargetDocs, withoutTargets,
-- ** Progress reporting
Progress(..), progressSimple, progressDisplay, progressTitlebar, progressProgram, getProgress,
-- ** Verbosity
Verbosity(..), getVerbosity, putVerbose, putInfo, putWarn, putError, withVerbosity, quietly,
-- * Running commands
command, command_, cmd, cmd_, unit,
Stdout(..), StdoutTrim(..), Stderr(..), Stdouterr(..), Exit(..), Process(..), CmdTime(..), CmdLine(..), FSATrace(..),
CmdResult, CmdString, CmdOption(..),
addPath, addEnv,
-- * Explicit parallelism
parallel, forP, par,
-- * Utility functions
copyFile', copyFileChanged,
readFile', readFileLines,
writeFile', writeFileLines, writeFileChanged,
removeFiles, removeFilesAfter,
withTempFile, withTempDir,
withTempFileWithin, withTempDirWithin,
-- * File rules
need, want, (%>), (|%>), (?>), phony, (~>), phonys,
(&%>), (&?>),
orderOnly, orderOnlyAction,
FilePattern, (?==), (<//>), filePattern,
needed, trackRead, trackWrite, trackAllow,
-- * Directory rules
doesFileExist, doesDirectoryExist, getDirectoryContents, getDirectoryFiles, getDirectoryDirs,
getDirectoryFilesIO,
-- * Environment rules
getEnv, getEnvWithDefault, getEnvError,
-- * Oracle rules
ShakeValue, RuleResult, addOracle, addOracleCache, addOracleHash, askOracle, askOracles,
-- * Special rules
alwaysRerun,
-- * Resources
Resource, newResource, newResourceIO, withResource, withResources,
newThrottle, newThrottleIO,
unsafeExtraThread,
-- * Cache
newCache, newCacheIO,
historyDisable, produces,
-- * Batching
needHasChanged,
resultHasChanged,
batch,
reschedule,
-- * Deprecated
askOracleWith,
deprioritize,
pattern Quiet, pattern Normal, pattern Loud, pattern Chatty,
putLoud, putNormal, putQuiet
) where
-- I would love to use module export in the above export list, but alas Haddock
-- then shows all the things that are hidden in the docs, which is terrible.
import Control.Monad.IO.Class
import Development.Shake.Internal.Value
import Development.Shake.Internal.Options
import Development.Shake.Internal.Core.Types
import Development.Shake.Internal.Core.Action
import Development.Shake.Internal.Core.Rules
import Development.Shake.Internal.Resource
import Development.Shake.Internal.Derived
import Development.Shake.Internal.Errors
import Development.Shake.Internal.Progress
import Development.Shake.Internal.Args
import Development.Shake.Command
import Development.Shake.Internal.FilePattern
import Development.Shake.Internal.Rules.Directory
import Development.Shake.Internal.Rules.File
import Development.Shake.Internal.Rules.Files
import Development.Shake.Internal.Rules.Oracle
import Development.Shake.Internal.Rules.OrderOnly
import Development.Shake.Internal.Rules.Rerun
-- $writing
--
-- When writing a Shake build system, start by defining what you 'want', then write rules
-- with '%>' to produce the results. Before calling 'cmd' you should ensure that any files the command
-- requires are demanded with calls to 'need'. We offer the following advice to Shake users:
--
-- * If @ghc --make@ or @cabal@ is capable of building your project, use that instead. Custom build systems are
-- necessary for many complex projects, but many projects are not complex.
--
-- * The 'shakeArgs' function automatically handles command line arguments. To define non-file targets use 'phony'.
--
-- * Put all result files in a distinguished directory, for example @_make@. You can implement a @clean@
-- command by removing that directory, using @'removeFilesAfter' \"_make\" [\"\/\/\*\"]@.
--
-- * To obtain parallel builds set 'shakeThreads' to a number greater than 1.
--
-- * Lots of compilers produce @.o@ files. To avoid overlapping rules, use @.c.o@ for C compilers,
-- @.hs.o@ for Haskell compilers etc.
--
-- * Do not be afraid to mix Shake rules, system commands and other Haskell libraries -- use each for what
-- it does best.
--
-- * The more accurate the dependencies are, the better. Use additional rules like 'doesFileExist' and
-- 'getDirectoryFiles' to track information other than just the contents of files. For information in the environment
-- that you suspect will change regularly (perhaps @ghc@ version number), either write the information to
-- a file with 'alwaysRerun' and 'writeFileChanged', or use 'addOracle'.
-- $flags
--
-- For large build systems the choice of GHC flags can have a significant impact. We recommend:
--
-- > ghc --make MyBuildSystem -threaded -rtsopts "-with-rtsopts=-I0 -qg"
--
-- * @-rtsopts@: Allow the setting of further GHC options at runtime.
--
-- * @-I0@: Disable idle garbage collection, to avoid frequent unnecessary garbage collection, see
-- <https://stackoverflow.com/questions/34588057/why-does-shake-recommend-disabling-idle-garbage-collection/ a full explanation>.
--
-- * You may add @-threaded@, and pass the options @-qg@ to @-with-rtsopts@
-- to disable parallel garbage collection. Parallel garbage collection in Shake
-- programs typically goes slower than sequential garbage collection, while occupying many cores that
-- could be used for running system commands.
-- $modules
--
-- The main Shake module is this one, "Development.Shake", which should be sufficient for most
-- people writing build systems using Shake. However, Shake provides some additional modules,
--
-- * "Development.Shake.Classes" provides convenience exports of the classes Shake relies on,
-- in particular 'Binary', 'Hashable' and 'NFData'. Useful for deriving these types using
-- @GeneralizedNewtypeDeriving@ without adding dependencies on the associated packages.
--
-- * "Development.Shake.Command" provides the command line wrappers. These are reexported by
-- "Development.Shake", but if you want to reuse just the command-line running functionality
-- in a non-Shake program you can import just that.
--
-- * "Development.Shake.Config" provides a way to write configuration files that are tracked.
-- The configuration files are in the Ninja format. Useful for users of bigger systems who
-- want to track the build rules not in Haskell.
--
-- * "Development.Shake.Database" provides lower level primitives to drive Shake, particularly
-- useful if you want to run multiple Shake runs in a row without reloading from the database.
--
-- * "Development.Shake.FilePath" is an extension of "System.FilePath" with a few additional
-- methods and safer extension manipulation code.
--
-- * "Development.Shake.Forward" is an alternative take on build systems, where you write the
-- rules as a script where steps are skipped, rather than as a set of dependencies. Only really
-- works if you use @fsatrace@.
--
-- * "Development.Shake.Rule" provides tools for writing your own types of Shake rules. Useful
-- if you need something new, like a rule that queries a database or similar.
--
-- * "Development.Shake.Util" has general utilities that are useful for build systems, e.g.
-- reading @Makefile@ syntax and alternative forms of argument parsing.
---------------------------------------------------------------------
-- DEPRECATED SINCE 0.16.1, NOV 2017
-- | /Deprecated:/ Replace @'askOracleWith' q a@ by @'askOracle' q@
-- since the 'RuleResult' type family now fixes the result type.
{-# DEPRECATED askOracleWith "Use 'askOracle q' instead of 'askOracleWith q a', the result value is now unnecessary" #-}
askOracleWith :: (RuleResult q ~ a, ShakeValue q, ShakeValue a) => q -> a -> Action a
askOracleWith question _ = askOracle question
---------------------------------------------------------------------
-- DEPRECATED SINCE 0.18.4, JUL 2019
-- | /Deprecated:/ Alias for 'reschedule'.
{-# DEPRECATED deprioritize "Use 'reschedule' instead" #-}
deprioritize :: Double -> Action ()
deprioritize = reschedule
-- | /Deprecated:/ A bidirectional pattern synonym for 'Error'.
pattern Quiet :: Verbosity
pattern Quiet = Error
-- | /Deprecated:/ A bidirectional pattern synonym for 'Info'.
pattern Normal :: Verbosity
pattern Normal = Info
-- | /Deprecated:/ A bidirectional pattern synonym for 'Verbose'.
pattern Loud :: Verbosity
pattern Loud = Verbose
-- | /Deprecated:/ A bidirectional pattern synonym for 'Verbose'.
pattern Chatty :: Verbosity
pattern Chatty = Verbose
putLoud, putNormal, putQuiet :: String -> Action ()
-- | /Deprecated:/ Alias for 'putVerbose'.
putLoud = putVerbose
-- | /Deprecated:/ Alias for 'putInfo'.
putNormal = putInfo
-- | /Deprecated:/ Alias for 'putError'.
putQuiet = putError
|
ndmitchell/shake
|
src/Development/Shake.hs
|
bsd-3-clause
| 11,664 | 0 | 8 | 1,950 | 1,007 | 719 | 288 | 86 | 1 |
-- | Config helpers
module Pos.Util.Config
( embedYamlConfigCT
, embedYamlObject
, parseYamlConfig
, ConfigurationException (..)
) where
import Universum
import qualified Data.Map as Map
import qualified Data.Yaml as Y
import qualified Language.Haskell.TH.Syntax as TH
import System.Directory (canonicalizePath, getDirectoryContents)
import System.FilePath (takeDirectory, takeFileName, (</>))
import Pos.Util.Util (maybeThrow, templateHaskellError)
embedYamlObject :: Y.FromJSON r => FilePath -> FilePath -> (r -> TH.Q TH.Exp) -> TH.Q TH.Exp
embedYamlObject name marker parser = do
-- This code was stolen from file-embed ('makeRelativeToProject'). We
-- don't use file-embed because the config-finding logic has already been
-- changed several times and switching from file-embed to custom logic
-- and back is annoying.
let findConfigDir x = do
let dir = takeDirectory x
contents <- getDirectoryContents dir
let isRoot = any ((== marker) . takeFileName) contents
if | dir == x -> return Nothing
| isRoot -> return (Just dir)
| otherwise -> findConfigDir dir
loc <- TH.qLocation
path <- TH.runIO $ do
srcFP <- canonicalizePath $ TH.loc_filename loc
mdir <- findConfigDir srcFP
case mdir of
Just dir -> return (dir </> name)
Nothing -> error $ toText $
"Could not find " ++ marker ++ " for path: " ++ srcFP
TH.qAddDependentFile path
TH.runIO (Y.decodeFileEither path) >>= \case
Right x -> parser x
Left err -> templateHaskellError $
"Couldn't parse " <> pretty path <> ": " <>
fromString (Y.prettyPrintParseException err)
embedYamlConfigCT :: forall conf . (Y.FromJSON conf, TH.Lift conf)
=> Proxy conf -> FilePath -> FilePath -> Text -> TH.Q TH.Exp
embedYamlConfigCT _ name marker key =
embedYamlObject @(Map Text conf) name marker $ \multiConfig ->
case Map.lookup key multiConfig of
Just a -> TH.lift a
Nothing -> templateHaskellError $
"Embedded file " <> fromString name <> " contains no key " <> key
parseYamlConfig :: (MonadThrow m, MonadIO m, Y.FromJSON conf)
=> FilePath -> Text -> m conf
parseYamlConfig cfoFilePath cfoKey = do
decoded <- liftIO $ Y.decodeFileEither cfoFilePath
multiConfig <- either (throwM . ConfigurationParseFailure cfoFilePath) return decoded
maybeThrow (ConfigurationKeyNotFound cfoFilePath cfoKey)
(Map.lookup cfoKey multiConfig)
data ConfigurationException =
-- | Couldn't parse the configuration file.
ConfigurationParseFailure !FilePath !(Y.ParseException)
-- | Configuration at the given key not found.
| ConfigurationKeyNotFound !FilePath !Text
deriving (Show)
instance Exception ConfigurationException
|
input-output-hk/pos-haskell-prototype
|
lib/src/Pos/Util/Config.hs
|
mit
| 2,969 | 0 | 18 | 787 | 755 | 380 | 375 | -1 | -1 |
module Test.Hspec.Expectations.Matcher (matchList) where
import Prelude hiding (showList)
import Data.List
matchList :: (Show a, Eq a) => [a] -> [a] -> Maybe String
xs `matchList` ys
| null extra && null missing = Nothing
| otherwise = Just (err "")
where
extra = xs \\ ys
missing = ys \\ xs
msgAndList msg zs = showString msg . showList zs . showString "\n"
optMsgList msg zs = if null zs then id else msgAndList msg zs
err :: ShowS
err =
showString "Actual list is not a permutation of expected list!\n"
. msgAndList " expected list contains: " ys
. msgAndList " actual list contains: " xs
. optMsgList " the missing elements are: " missing
. optMsgList " the extra elements are: " extra
showList :: Show a => [a] -> ShowS
showList xs = showChar '[' . foldr (.) (showChar ']') (intersperse (showString ", ") $ map shows xs)
|
soenkehahn/hspec-expectations
|
src/Test/Hspec/Expectations/Matcher.hs
|
mit
| 927 | 0 | 11 | 252 | 303 | 153 | 150 | 20 | 2 |
{-# LANGUAGE UnboxedTuples #-}
module JavaScript.Object ( Object
, create
, getProp, unsafeGetProp
, setProp, unsafeSetProp
, allProps, listProps
, isInstanceOf
) where
import Data.JSString
import qualified JavaScript.Array as A
import qualified JavaScript.Array.Internal as AI
import JavaScript.Object.Internal (Object(..))
import JavaScript.Object.Internal -- as I
import GHCJS.Types
{-
-- | create an empty object
create :: IO Object
create = fmap Object I.create
{-# INLINE create #-}
allProps :: Object -> IO (JSArray JSString)
allProps (Object o) = fmap AI.JSArray (I.allProps o)
{-# INLINE allProps #-}
listProps :: Object -> IO [JSString]
listProps (Object o) = I.listProps o
{-# INLINE listProps #-}
{- | get a property from an object. If accessing the property results in
an exception, the exception is converted to a JSException. Since exception
handling code prevents some optimizations in some JS engines, you may want
to use unsafeGetProp instead
-}
getProp :: JSString -> Object -> IO (JSVal a)
getProp p (Object o) = I.getProp p o
{-# INLINE getProp #-}
unsafeGetProp :: JSString -> Object -> IO (JSVal a)
unsafeGetProp p (Object o) = I.unsafeGetProp p o
{-# INLINE unsafeGetProp #-}
setProp :: JSString -> JSVal a -> Object -> IO ()
setProp p v (Object o) = I.setProp p v o
{-# INLINE setProp #-}
unsafeSetProp :: JSString -> JSVal a -> Object -> IO ()
unsafeSetProp p v (Object o) = I.unsafeSetProp p v o
{-# INLINE unsafeSetProp #-}
isInstanceOf :: Object -> JSVal a -> Bool
isInstanceOf (Object o) s = I.isInstanceOf o s
{-# INLINE isInstanceOf #-}
-}
-- -----------------------------------------------------------------------------
{-
foreign import javascript safe "$2[$1]"
js_getProp :: JSString -> JSVal a -> IO (JSVal b)
foreign import javascript unsafe "$2[$1]"
js_unsafeGetProp :: JSString -> JSVal a -> IO (JSVal b)
foreign import javascript safe "$3[$1] = $2"
js_setProp :: JSString -> JSVal a -> JSVal b -> IO ()
foreign import javascript unsafe "$3[$1] = $2"
js_unsafeSetProp :: JSString -> JSVal a -> JSVal b -> IO ()
foreign import javascript unsafe "$1 instanceof $2"
js_isInstanceOf :: Object -> JSVal a -> Bool
foreign import javascript unsafe "h$allProps"
js_allProps :: Object -> IO (JSArray JSString)
foreign import javascript unsafe "h$listProps"
js_listProps :: Object -> (# [JSString] #)
-}
|
ghcjs/ghcjs-base
|
JavaScript/Object.hs
|
mit
| 2,598 | 0 | 6 | 631 | 88 | 61 | 27 | 13 | 0 |
{-|
Module : Translation.TypeInference
Description : Type inference for expressions
Maintainer : Josh Acay <[email protected]>
Stability : experimental
-}
module Translation.TypeInference (Context, Error, infer) where
import Control.Monad
import Control.Monad.Error (throwError)
import Control.Monad.Reader (ReaderT (runReaderT), asks, lift)
import Data.List (stripPrefix)
import qualified Data.Map.Strict as Map
import AST.AST
import AST.Operations
import AST.Types (Type (..))
import Util.Error (assertMsg, liftMaybe, msum1)
type Context = Map.Map Ident Type
type Error = Either String
type State = ReaderT Context Error
infer :: Context -> Exp -> Error Type
infer ctx e = runReaderT (inferExp e) ctx
inferExp :: Exp -> State Type
inferExp exp = case exp of
Null -> return TVoid
Bool _ -> return TBool
Int _ -> return TInt
Float _ -> return TFloat
CudaVar _ -> return TInt
Ident id ->
asks (Map.lookup id) >>= liftMaybe ("undefined variable: " ++ id)
Binop op e1 e2 -> do
t1 <- inferExp e1
t2 <- inferExp e2
lift $ applyAny exp (inferArithmetic op) [t1, t2]
Cmp op e1 e2 -> do
t1 <- inferExp e1
t2 <- inferExp e2
lift $ applyAny exp (inferComparison op) [t1, t2]
Case c e1 e2 -> do
checkExp exp c TBool;
t1 <- inferExp e1
t2 <- inferExp e2
lift $ unify exp t1 t2
Call "len" [l] -> return TInt
Call id args -> do
t1 <- inferFun id
t2 <- mapM inferExp args
lift $ applyAny exp t1 t2
Index e1 e2 -> do
t1 <- inferExp e1
t2 <- inferExp e2
lift $ index exp t1 t2
checkExp :: Show a => a -> Exp -> Type -> State Type
checkExp err e t = do t' <- inferExp e; lift (unify err t' t)
inferFun :: Ident -> State [Type]
inferFun s | Just f <- stripPrefix "math." s = lift (inferMath f)
inferFun s | Right ts <- inferCast s = return ts
inferFun s = do t <- inferExp (Ident s); return [t]
inferMath :: Ident -> Error [Type]
inferMath s
| isF2F s = return [TFunction TFloat [TFloat]]
| isFF2F s = return [TFunction TFloat [TFloat, TFloat]]
| isFFF2F s = return [TFunction TFloat [TFloat, TFloat, TFloat]]
| isD2D s = return [TFunction TDouble [TDouble]]
| isDD2D s = return [TFunction TDouble [TDouble, TDouble]]
| isDDD2D s = return [TFunction TDouble [TDouble, TDouble, TDouble]]
where
isF2F = flip elem
[ "aconsf", "aconshf", "asinf", "asinhf", "atanf", "atanhf", "cbrtf"
, "ceilf", "cosf", "coshf", "cospif", "erfcf", "erfcinvf", "erfcxf"
, "erff", "erfinvf", "exp10f", "exp2f", "expf", "expm1f", "fabsf"
, "floorf", "j0f", "j1f", "lgammaf", "log10f", "log1pf", "log2f"
, "logbf", "logf", "nearbyintf", "rcbrtf", "rintf", "roundf", "rsqrtf"
, "sinf", "sinhf", "sinpif", "sqrtf", "tanf", "tanhf", "tgammaf"
, "truncf", "y0f", "y1f"
]
isFF2F = flip elem
[ "atan2f", "copysignf", "fdimf", "fdividef", "fmaxf", "fminf"
, "fmodf", "hypotf", "nextafterf", "powf", "remainderf"
]
isFFF2F = flip elem ["fmaf"]
isD2D = flip elem
[ "acons", "aconsh", "asin", "asinh", "atan", "atanh", "cbrt"
, "ceil", "cos", "cosh", "cospi", "erfc", "erfcinv", "erfcx"
, "erf", "erfinv", "exp10", "exp2", "exp", "expm1", "fabs"
, "floor", "j0", "j1", "lgamma", "log10", "log1p", "log2"
, "logb", "log", "nearbyint", "rcbrt", "rint", "round", "rsqrt"
, "sin", "sinh", "sinpi", "sqrt", "tan", "tanh", "tgamma"
, "trunc", "y0", "y1"
]
isDD2D = flip elem
[ "atan2", "copysign", "fdim", "fdivide", "fmax", "fmin"
, "fmod", "hypot", "nextafter", "pow", "remainder"
]
isDDD2D = flip elem ["fma"]
-- Others here
inferMath s = throwError $ "Not a math library function: " ++ s
inferCast :: Ident -> Error [Type]
inferCast s = case s of
"(int)" -> return [toInt TInt, toInt TFloat, toInt TDouble]
"(float)" -> return [toFloat TInt, toFloat TFloat, toFloat TDouble]
"(double)" -> return [toDouble TInt, toDouble TFloat, toDouble TDouble]
_ -> throwError $ "Not a cast: " ++ s
where
toInt t = TFunction TInt [t]
toFloat t = TFunction TFloat [t]
toDouble t = TFunction TDouble [t]
inferArithmetic :: Arithmetic -> [Type]
inferArithmetic op = case op of
Add -> numeric
Sub -> numeric
Mul -> numeric
Div -> numeric
Mod -> numeric
Shl -> justInts
Shr -> justInts
And -> justInts
Xor -> justInts
Ior -> justInts
where
ints = TFunction TInt [TInt, TInt]
floats = TFunction TFloat [TFloat, TFloat]
doubles = TFunction TDouble [TDouble, TDouble]
justInts = [ints]
numeric = [ints, floats, doubles]
inferComparison :: Comparison -> [Type]
inferComparison op = case op of
Eq -> polymorphic
Neq -> polymorphic
Less -> numeric
LessEq -> numeric
Greater -> numeric
GreaterEq -> numeric
where
bools = TFunction TBool [TBool, TBool]
ints = TFunction TBool [TInt, TInt]
floats = TFunction TBool [TFloat, TFloat]
doubles = TFunction TBool [TDouble, TDouble]
numeric = [ints, floats, doubles]
polymorphic = bools : numeric
unify :: Show a => a -> Type -> Type -> Error Type
unify _ t1 t2 | t1 == t2 = return t1
unify err t1 t2 = throwError $
"cannot unify " ++ show t1 ++ " with " ++ show t2 ++ " in " ++ show err
apply :: Show a => a -> Type -> [Type] -> Error Type
apply err (TFunction r args) pars = do
assertMsg ("incorrect arity in " ++ show err) (length args == length pars)
zipWithM_ (unify err) args pars
return r
apply err t _ = throwError $
"expected function got " ++ show t ++ " in " ++ show err
applyAny :: Show a => a -> [Type] -> [Type] -> Error Type
applyAny err [] _ = throwError $ "function has no type: " ++ show err
applyAny err funs args = msum1 $ map (flip (apply err) args) funs
index :: Show a => a -> Type -> Type -> Error Type
index err (TArray t1) t2 = do unify err t2 TInt; return t1
index err t _ = throwError $
"expected array got " ++ show t ++ " in " ++ show err
|
oulgen/CudaPy
|
py2cuda/src/Translation/TypeInference.hs
|
mit
| 5,941 | 0 | 13 | 1,377 | 2,276 | 1,183 | 1,093 | 143 | 12 |
{- |
Module : ./CASL/Fold.hs
Description : folding functions for CASL terms and formulas
Copyright : (c) Christian Maeder, Uni Bremen 2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
folding functions for CASL terms and formulas
-}
module CASL.Fold where
import Common.Id
import CASL.AS_Basic_CASL
data Record f a b = Record
{ foldQuantification :: FORMULA f -> QUANTIFIER -> [VAR_DECL] ->
a -> Range -> a
, foldJunction :: FORMULA f -> Junctor -> [a] -> Range -> a
, foldRelation :: FORMULA f -> a -> Relation -> a -> Range -> a
, foldNegation :: FORMULA f -> a -> Range -> a
, foldAtom :: FORMULA f -> Bool -> Range -> a
, foldPredication :: FORMULA f -> PRED_SYMB -> [b] -> Range -> a
, foldDefinedness :: FORMULA f -> b -> Range -> a
, foldEquation :: FORMULA f -> b -> Equality -> b -> Range -> a
, foldMembership :: FORMULA f -> b -> SORT -> Range -> a
, foldMixfix_formula :: FORMULA f -> b -> a
, foldSort_gen_ax :: FORMULA f -> [Constraint] -> Bool -> a
, foldQuantOp :: FORMULA f -> OP_NAME -> OP_TYPE -> a -> a
, foldQuantPred :: FORMULA f -> PRED_NAME -> PRED_TYPE -> a -> a
, foldExtFORMULA :: FORMULA f -> f -> a
, foldQual_var :: TERM f -> VAR -> SORT -> Range -> b
, foldApplication :: TERM f -> OP_SYMB -> [b] -> Range -> b
, foldSorted_term :: TERM f -> b -> SORT -> Range -> b
, foldCast :: TERM f -> b -> SORT -> Range -> b
, foldConditional :: TERM f -> b -> a -> b -> Range -> b
, foldMixfix_qual_pred :: TERM f -> PRED_SYMB -> b
, foldMixfix_term :: TERM f -> [b] -> b
, foldMixfix_token :: TERM f -> Token -> b
, foldMixfix_sorted_term :: TERM f -> SORT -> Range -> b
, foldMixfix_cast :: TERM f -> SORT -> Range -> b
, foldMixfix_parenthesized :: TERM f -> [b] -> Range -> b
, foldMixfix_bracketed :: TERM f -> [b] -> Range -> b
, foldMixfix_braced :: TERM f -> [b] -> Range -> b
, foldExtTERM :: TERM f -> f -> b
}
mapRecord :: (f -> g) -> Record f (FORMULA g) (TERM g)
mapRecord mf = Record
{ foldQuantification = const Quantification
, foldJunction = const Junction
, foldRelation = const Relation
, foldNegation = const Negation
, foldAtom = const Atom
, foldPredication = const Predication
, foldDefinedness = const Definedness
, foldEquation = const Equation
, foldMembership = const Membership
, foldMixfix_formula = const Mixfix_formula
, foldSort_gen_ax = const mkSort_gen_ax
, foldQuantOp = const QuantOp
, foldQuantPred = const QuantPred
, foldExtFORMULA = \ _ -> ExtFORMULA . mf
, foldQual_var = const Qual_var
, foldApplication = const Application
, foldSorted_term = const Sorted_term
, foldCast = const Cast
, foldConditional = const Conditional
, foldMixfix_qual_pred = const Mixfix_qual_pred
, foldMixfix_term = const Mixfix_term
, foldMixfix_token = const Mixfix_token
, foldMixfix_sorted_term = const Mixfix_sorted_term
, foldMixfix_cast = const Mixfix_cast
, foldMixfix_parenthesized = const Mixfix_parenthesized
, foldMixfix_bracketed = const Mixfix_bracketed
, foldMixfix_braced = const Mixfix_braced
, foldExtTERM = \ _ -> ExtTERM . mf
}
constRecord :: (f -> a) -> ([a] -> a) -> a -> Record f a a
constRecord mf join c = Record
{ foldQuantification = \ _ _ _ r _ -> r
, foldJunction = \ _ _ l _ -> join l
, foldRelation = \ _ l _ r _ -> join [l, r]
, foldNegation = \ _ r _ -> r
, foldAtom = \ _ _ _ -> c
, foldPredication = \ _ _ l _ -> join l
, foldDefinedness = \ _ r _ -> r
, foldEquation = \ _ l _ r _ -> join [l, r]
, foldMembership = \ _ r _ _ -> r
, foldMixfix_formula = \ _ r -> r
, foldSort_gen_ax = \ _ _ _ -> c
, foldQuantOp = \ _ _ _ a -> a
, foldQuantPred = \ _ _ _ a -> a
, foldExtFORMULA = const mf
, foldQual_var = \ _ _ _ _ -> c
, foldApplication = \ _ _ l _ -> join l
, foldSorted_term = \ _ r _ _ -> r
, foldCast = \ _ r _ _ -> r
, foldConditional = \ _ l f r _ -> join [l, f, r]
, foldMixfix_qual_pred = \ _ _ -> c
, foldMixfix_term = const join
, foldMixfix_token = \ _ _ -> c
, foldMixfix_sorted_term = \ _ _ _ -> c
, foldMixfix_cast = \ _ _ _ -> c
, foldMixfix_parenthesized = \ _ l _ -> join l
, foldMixfix_bracketed = \ _ l _ -> join l
, foldMixfix_braced = \ _ l _ -> join l
, foldExtTERM = const mf
}
foldFormula :: Record f a b -> FORMULA f -> a
foldFormula r f = case f of
Quantification q vs e ps -> foldQuantification r f q vs (foldFormula r e) ps
Junction j fs ps -> foldJunction r f j (map (foldFormula r) fs) ps
Relation f1 c f2 ps -> foldRelation r f (foldFormula r f1) c
(foldFormula r f2) ps
Negation e ps -> foldNegation r f (foldFormula r e) ps
Atom b ps -> foldAtom r f b ps
Predication p ts ps -> foldPredication r f p (map (foldTerm r) ts) ps
Definedness t ps -> foldDefinedness r f (foldTerm r t) ps
Equation t1 e t2 ps -> foldEquation r f (foldTerm r t1) e
(foldTerm r t2) ps
Membership t s ps -> foldMembership r f (foldTerm r t) s ps
Mixfix_formula t -> foldMixfix_formula r f (foldTerm r t)
Unparsed_formula s _ -> error $ "Fold.foldFormula.Unparsed" ++ s
Sort_gen_ax cs b -> foldSort_gen_ax r f cs b
QuantOp o t q -> foldQuantOp r f o t $ foldFormula r q
QuantPred p t q -> foldQuantPred r f p t $ foldFormula r q
ExtFORMULA e -> foldExtFORMULA r f e
foldTerm :: Record f a b -> TERM f -> b
foldTerm r = foldOnlyTerm (foldFormula r) r
foldOnlyTerm :: (FORMULA f -> a) -> Record f a b -> TERM f -> b
foldOnlyTerm ff r t = case t of
Qual_var v s ps -> foldQual_var r t v s ps
Application o ts ps -> foldApplication r t o (map (foldOnlyTerm ff r) ts) ps
Sorted_term st s ps -> foldSorted_term r t (foldOnlyTerm ff r st) s ps
Cast ct s ps -> foldCast r t (foldOnlyTerm ff r ct) s ps
Conditional t1 f t2 ps -> foldConditional r t (foldOnlyTerm ff r t1)
(ff f) (foldOnlyTerm ff r t2) ps
Unparsed_term s _ -> error $ "Fold.Unparsed_term" ++ s
Mixfix_qual_pred p -> foldMixfix_qual_pred r t p
Mixfix_term ts -> foldMixfix_term r t (map (foldOnlyTerm ff r) ts)
Mixfix_token s -> foldMixfix_token r t s
Mixfix_sorted_term s ps -> foldMixfix_sorted_term r t s ps
Mixfix_cast s ps -> foldMixfix_cast r t s ps
Mixfix_parenthesized ts ps -> foldMixfix_parenthesized r t
(map (foldOnlyTerm ff r) ts) ps
Mixfix_bracketed ts ps -> foldMixfix_bracketed r t
(map (foldOnlyTerm ff r) ts) ps
Mixfix_braced ts ps -> foldMixfix_braced r t
(map (foldOnlyTerm ff r) ts) ps
ExtTERM e -> foldExtTERM r t e
|
spechub/Hets
|
CASL/Fold.hs
|
gpl-2.0
| 6,792 | 0 | 13 | 1,793 | 2,544 | 1,319 | 1,225 | 135 | 15 |
module Nirum.Constructs.TypeExpression ( TypeExpression ( ListModifier
, MapModifier
, OptionModifier
, SetModifier
, TypeIdentifier
, elementType
, identifier
, keyType
, type'
, valueType
)
, toCode
) where
import Data.String (IsString (fromString))
import qualified Data.Text as T
import Nirum.Constructs (Construct (toCode))
import Nirum.Constructs.Identifier (Identifier)
-- | Refers a type.
data TypeExpression
= TypeIdentifier { identifier :: Identifier }
| OptionModifier { type' :: TypeExpression }
| SetModifier { elementType :: TypeExpression }
| ListModifier { elementType :: TypeExpression }
| MapModifier { keyType :: TypeExpression
, valueType :: TypeExpression
}
deriving (Eq, Ord, Show)
instance Construct TypeExpression where
toCode (TypeIdentifier id') = toCode id'
toCode (OptionModifier type_) = toCode type_ `T.snoc` '?'
toCode (SetModifier element) =
'{' `T.cons` toCode element `T.snoc` '}'
toCode (ListModifier element) =
'[' `T.cons` toCode element `T.snoc` ']'
toCode (MapModifier key value) =
T.concat ["{", toCode key, ": ", toCode value, "}"]
instance IsString TypeExpression where
fromString string = TypeIdentifier (fromString string :: Identifier)
|
spoqa/nirum
|
src/Nirum/Constructs/TypeExpression.hs
|
gpl-3.0
| 1,933 | 0 | 8 | 911 | 351 | 209 | 142 | 36 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.CognitoIdentity.Types.Sum
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.CognitoIdentity.Types.Sum where
import Network.AWS.Prelude
data CognitoErrorCode
= AccessDenied
| InternalServerError
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText CognitoErrorCode where
parser = takeLowerText >>= \case
"accessdenied" -> pure AccessDenied
"internalservererror" -> pure InternalServerError
e -> fromTextError $ "Failure parsing CognitoErrorCode from value: '" <> e
<> "'. Accepted values: AccessDenied, InternalServerError"
instance ToText CognitoErrorCode where
toText = \case
AccessDenied -> "AccessDenied"
InternalServerError -> "InternalServerError"
instance Hashable CognitoErrorCode
instance ToByteString CognitoErrorCode
instance ToQuery CognitoErrorCode
instance ToHeader CognitoErrorCode
instance FromJSON CognitoErrorCode where
parseJSON = parseJSONText "CognitoErrorCode"
|
fmapfmapfmap/amazonka
|
amazonka-cognito-identity/gen/Network/AWS/CognitoIdentity/Types/Sum.hs
|
mpl-2.0
| 1,499 | 0 | 12 | 284 | 200 | 110 | 90 | 27 | 0 |
module QR.Pancakes where
import Data.List
type SleepCount = Either String Int
getCodejam :: String -> IO String
getCodejam xs = do
putStrLn xs
let out = getPanCakes xs
putStrLn out
return out
getPanCakes :: String -> String
getPanCakes xs =
let inputs = words xs
ys = head inputs
y = read (last inputs)::Int
in
either id show (pancakeHappyNumber ys y 0)
--either id show (pancakeHappyNumber "+++++" 4 0)
-- getPanCakesNumber:: String -> Int -> SleepCount
-- getPanCakesNumber xs n =
-- case mod unhappyCount n of 0 -> Right (pancakeHappyNumber xs n 0)
-- _ -> Left "IMPOSSIBLE"
-- where
-- unhappyCount = length $ filter (== '-') xs
pancakeHappyNumber:: String -> Int -> Int -> SleepCount
pancakeHappyNumber xs x y =
let unHappyCake = dropWhileEnd (== '+') $ dropWhile (== '+') xs
mHappyIndex = elemIndex '+' unHappyCake
in if (length unHappyCake) == 0
then Right y
else if length unHappyCake < x
then Left "IMPOSSIBLE"
else case mHappyIndex of Nothing ->
if mod (length unHappyCake) x == 0 then Right (y + (div (length unHappyCake) x)) else Left "IMPOSSIBLE"
Just n -> case mod n x of 0 -> pancakeHappyNumber (drop n unHappyCake) x (y+(div n x))
m -> pancakeHappyNumber (flipPancake (drop (n-m) unHappyCake) x) x (y+(div n x)+1)
flipPancake :: String -> Int -> String
flipPancake xs x =
let (ys, zs) = splitAt x xs
yxs = fmap flipCake ys
in yxs ++ zs
flipCake:: Char -> Char
flipCake '+' = '-'
flipCake _ = '+'
|
lihlcnkr/codejam
|
src/QR/Pancakes.hs
|
apache-2.0
| 1,686 | 0 | 21 | 524 | 515 | 260 | 255 | 35 | 6 |
<?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="sr-SP">
<title>Bug Tracker</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/bugtracker/src/main/javahelp/org/zaproxy/zap/extension/bugtracker/resources/help_sr_SP/helpset_sr_SP.hs
|
apache-2.0
| 957 | 79 | 66 | 157 | 409 | 207 | 202 | -1 | -1 |
{-# LANGUAGE CPP #-}
module GHC.Prof
( decode
, decode'
-- * Parser
, profile
-- * Cost-centre tree
, CostCentreTree
, aggregatedCostCentres
, aggregatedCostCentresOrderBy
, costCentres
, costCentresOrderBy
, aggregateCallSites
, aggregateCallSitesOrderBy
, callSites
, callSitesOrderBy
, aggregateModules
, aggregateModulesOrderBy
-- * Types
, Profile(..)
, TotalTime(..)
, TotalAlloc(..)
, AggregatedCostCentre(..)
, CostCentre(..)
, CostCentreNo
, CallSite(..)
, AggregateModule(..)
) where
#if !MIN_VERSION_base(4, 13, 0)
import Control.Applicative ((<*))
#endif
import qualified Data.Attoparsec.Text.Lazy as ATL
import qualified Data.Attoparsec.Text as AT
import qualified Data.Text.Lazy as TL
import qualified Data.Text as T
import GHC.Prof.CostCentreTree
import GHC.Prof.Parser (profile)
import GHC.Prof.Types
-- | Decode a GHC time allocation profiling report from a lazy 'ATL.Text'
decode :: TL.Text -> Either String Profile
decode text = case ATL.parse profile text of
ATL.Fail _unconsumed _contexts reason -> Left reason
ATL.Done _unconsumed prof -> Right prof
-- | Decode a GHC time allocation profiling report from a strict 'AT.Text'
decode' :: T.Text -> Either String Profile
decode' text = AT.parseOnly (profile <* AT.endOfInput) text
|
maoe/ghc-time-alloc-prof
|
src/GHC/Prof.hs
|
bsd-3-clause
| 1,314 | 0 | 9 | 230 | 290 | 181 | 109 | 38 | 2 |
--------------------------------------------------------------------------------
-- |
-- Module : HEP.Kinematics.Variable
-- Copyright : (c) 2015-2020 Chan Beom Park
-- License : BSD-style
-- Maintainer : Chan Beom Park <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-- Various kinematic variables for collider studies.
--
--------------------------------------------------------------------------------
module HEP.Kinematics.Variable
(
mT2Symm
, mT2Asymm
, mTLowerBound
, maosMomenta
, maosMomentaSymmetric
, maosMomentaSymmetric2
, SolutionType (..)
, mAT
, mATMAOS
) where
import HEP.Kinematics
import HEP.Kinematics.Variable.Antler (Visibles (..))
import qualified HEP.Kinematics.Variable.Antler as AT
import qualified HEP.Kinematics.Variable.Internal as Internal
import HEP.Kinematics.Variable.MAOS
import HEP.Kinematics.Variable.MT2 (mT2)
import HEP.Kinematics.Variable.MTLowerAndUpper (mTLowerBound)
mT2Symm :: FourMomentum -- ^ four-momentum of the first visible system
-> FourMomentum -- ^ four-momentum of the second visible system
-> TransverseMomentum -- ^ missing transverse momentum
-> Double -- ^ invariant mass of each invisible system
-> Double
mT2Symm = Internal.mT2Symm
mT2Asymm :: FourMomentum -- ^ four-momentum of the first visible system
-> FourMomentum -- ^ four-momentum of the second visible system
-> TransverseMomentum -- ^ missing transverse momentum
-> Double -- ^ invariant mass of the first invisible system
-> Double -- ^ invariant mass of the second invisible system
-> Double
mT2Asymm vis1 vis2 miss mInv1 mInv2 = mT2 vis1 vis2 miss mInv1 mInv2 0 True
-- | MAOS momenta for symmetric decay chains.
--
-- Each decay topology is like parent --> visible + invisible.
maosMomentaSymmetric :: Double -- ^ the MT2 value
-> FourMomentum -- ^ four-momentum of the first visible system
-> FourMomentum -- ^ four-momentum of the second visible system
-> TransverseMomentum -- ^ missing transverse momentum
-> Double -- ^ parent particle mass
-> Double -- ^ invisible particle mass
-> ([FourMomentum], [FourMomentum], SolutionType)
maosMomentaSymmetric = Internal.maosMomentaSymmetric
-- | This calculates the modified MAOS momenta defined in
-- <http://arxiv.org/abs/1106.6087 arXiv:1106.6087>.
maosMomentaSymmetric2 :: Double -- ^ the MT2 value
-> FourMomentum -- ^ four-momentum of the first visible system
-> FourMomentum -- ^ four-momentum of the second visible system
-> TransverseMomentum -- ^ missing transverse momentum
-> Double -- ^ invisible particle mass
-> ([FourMomentum], [FourMomentum], SolutionType)
maosMomentaSymmetric2 mT2value vis1 vis2 miss mX =
maosMomenta mT2value (vis1, mT2value, mX) (vis2, mT2value, mX) miss
-- | returns the list of M_{AT}.
mAT :: FourMomentum -- ^ the four-momentum of visible particles (1)
-> FourMomentum -- ^ the four-momentum of visible particles (2)
-> Double -- ^ Q_{x}
-> Double -- ^ Q_{y}
-> Double -- ^ a guess of the longitudinal momentum of the resonance
-> Double -- ^ the mass of intermediate particle
-> Double -- ^ the mass of invisible particle
-> Maybe [Double]
mAT p1 p2 qx qy qz mA mB = do
at <- AT.mkAntler mB mA (Visibles p1 p2)
AT.mAT at qx qy qz
-- | returns (M_{AT}, M_{MAOS}, M_{T2}).
mATMAOS :: FourMomentum -- ^ the four-momentum of visible particles (1)
-> FourMomentum -- ^ the four-momentum of visible particles (2)
-> TransverseMomentum -- ^ the missing transverse momentum
-> Double -- ^ Q_{x}
-> Double -- ^ Q_{y}
-> Double -- ^ the mass of intermediate particle
-> Double -- ^ the mass of invisible particle
-> Maybe [Double]
mATMAOS p1 p2 ptmiss qx qy mA mB = do
at <- AT.mkAntler mB mA (Visibles p1 p2)
(mATs, _, _) <- AT.mATMAOS at qx qy ptmiss
return mATs
|
cbpark/hep-kinematics
|
src/HEP/Kinematics/Variable.hs
|
bsd-3-clause
| 4,533 | 0 | 13 | 1,386 | 596 | 354 | 242 | 70 | 1 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[RnSource]{Main pass of renamer}
-}
{-# LANGUAGE CPP #-}
module Eta.Rename.RnTypes (
-- Type related stuff
rnHsType, rnLHsType, rnLHsTypes, rnContext,
rnHsKind, rnLHsKind, rnLHsMaybeKind,
rnHsSigType, rnLHsInstType, rnConDeclFields,
newTyVarNameRn,
-- Precence related stuff
mkOpAppRn, mkNegAppRn, mkOpFormRn, mkConOpPatRn,
checkPrecMatch, checkSectionPrec,
-- Binding related stuff
warnContextQuantification, warnUnusedForAlls,
bindSigTyVarsFV, bindHsTyVars, rnHsBndrSig,
extractHsTyRdrTyVars, extractHsTysRdrTyVars,
extractRdrKindSigVars, extractDataDefnKindVars,
extractWildcards, filterInScope
) where
import {-# SOURCE #-} Eta.Rename.RnSplice( rnSpliceType )
import Eta.Main.DynFlags
import Eta.HsSyn.HsSyn
import Eta.Rename.RnHsDoc ( rnLHsDoc, rnMbLHsDoc )
import Eta.Rename.RnEnv
import Eta.TypeCheck.TcRnMonad
import Eta.BasicTypes.RdrName
import Eta.Prelude.PrelNames
import Eta.Prelude.TysPrim ( funTyConName )
import Eta.BasicTypes.Name
import Eta.BasicTypes.SrcLoc
import Eta.BasicTypes.NameSet
import qualified Eta.LanguageExtensions as LangExt
import Eta.Utils.Util
import Eta.BasicTypes.BasicTypes ( compareFixity, funTyFixity, negateFixity,
Fixity(..), FixityDirection(..) )
import Eta.Utils.Outputable
import Eta.Utils.FastString
import Eta.Utils.Maybes
import Data.List ( nub, nubBy )
import Control.Monad ( unless, when )
#include "HsVersions.h"
{-
These type renamers are in a separate module, rather than in (say) RnSource,
to break several loop.
*********************************************************
* *
\subsection{Renaming types}
* *
*********************************************************
-}
rnHsSigType :: SDoc -> LHsType RdrName -> RnM (LHsType Name, FreeVars)
-- rnHsSigType is used for source-language type signatures,
-- which use *implicit* universal quantification.
rnHsSigType doc_str ty = rnLHsType (TypeSigCtx doc_str) ty
rnLHsInstType :: SDoc -> LHsType RdrName -> RnM (LHsType Name, FreeVars)
-- Rename the type in an instance or standalone deriving decl
rnLHsInstType doc_str ty
= do { (ty', fvs) <- rnLHsType (GenericCtx doc_str) ty
; unless good_inst_ty (addErrAt (getLoc ty) (badInstTy ty))
; return (ty', fvs) }
where
good_inst_ty
| Just (_, _, L _ cls, _) <-
splitLHsInstDeclTy_maybe (flattenTopLevelLHsForAllTy ty)
, isTcOcc (rdrNameOcc cls) = True
| otherwise = False
badInstTy :: LHsType RdrName -> SDoc
badInstTy ty = ptext (sLit "Malformed instance:") <+> ppr ty
{-
rnHsType is here because we call it from loadInstDecl, and I didn't
want a gratuitous knot.
Note [Context quantification]
-----------------------------
Variables in type signatures are implicitly quantified
when (1) they are in a type signature not beginning
with "forall" or (2) in any qualified type T => R.
We are phasing out (2) since it leads to inconsistencies
(Trac #4426):
data A = A (a -> a) is an error
data A = A (Eq a => a -> a) binds "a"
data A = A (Eq a => a -> b) binds "a" and "b"
data A = A (() => a -> b) binds "a" and "b"
f :: forall a. a -> b is an error
f :: forall a. () => a -> b is an error
f :: forall a. a -> (() => b) binds "a" and "b"
The -fwarn-context-quantification flag warns about
this situation. See rnHsTyKi for case HsForAllTy Qualified.
-}
rnLHsTyKi :: Bool -- True <=> renaming a type, False <=> a kind
-> HsDocContext -> LHsType RdrName -> RnM (LHsType Name, FreeVars)
rnLHsTyKi isType doc (L loc ty)
= setSrcSpan loc $
do { (ty', fvs) <- rnHsTyKi isType doc ty
; return (L loc ty', fvs) }
rnLHsType :: HsDocContext -> LHsType RdrName -> RnM (LHsType Name, FreeVars)
rnLHsType = rnLHsTyKi True
rnLHsKind :: HsDocContext -> LHsKind RdrName -> RnM (LHsKind Name, FreeVars)
rnLHsKind = rnLHsTyKi False
rnLHsMaybeKind :: HsDocContext -> Maybe (LHsKind RdrName)
-> RnM (Maybe (LHsKind Name), FreeVars)
rnLHsMaybeKind _ Nothing
= return (Nothing, emptyFVs)
rnLHsMaybeKind doc (Just kind)
= do { (kind', fvs) <- rnLHsKind doc kind
; return (Just kind', fvs) }
rnHsType :: HsDocContext -> HsType RdrName -> RnM (HsType Name, FreeVars)
rnHsType = rnHsTyKi True
rnHsKind :: HsDocContext -> HsKind RdrName -> RnM (HsKind Name, FreeVars)
rnHsKind = rnHsTyKi False
rnHsTyKi :: Bool -> HsDocContext -> HsType RdrName -> RnM (HsType Name, FreeVars)
rnHsTyKi isType doc ty@HsForAllTy{}
= rnHsTyKiForAll isType doc (flattenTopLevelHsForAllTy ty)
rnHsTyKi isType _ (HsTyVar rdr_name)
= do { name <- rnTyVar isType rdr_name
; return (HsTyVar name, unitFV name) }
-- If we see (forall a . ty), without foralls on, the forall will give
-- a sensible error message, but we don't want to complain about the dot too
-- Hence the jiggery pokery with ty1
rnHsTyKi isType doc ty@(HsOpTy ty1 (wrapper, L loc op) ty2)
= ASSERT( isType ) setSrcSpan loc $
do { ops_ok <- xoptM LangExt.TypeOperators
; op' <- if ops_ok
then rnTyVar isType op
else do { addErr (opTyErr op ty)
; return (mkUnboundName op) } -- Avoid double complaint
; let l_op' = L loc op'
; fix <- lookupTyFixityRn l_op'
; (ty1', fvs1) <- rnLHsType doc ty1
; (ty2', fvs2) <- rnLHsType doc ty2
; res_ty <- mkHsOpTyRn (\t1 t2 -> HsOpTy t1 (wrapper, l_op') t2)
op' fix ty1' ty2'
; return (res_ty, (fvs1 `plusFV` fvs2) `addOneFV` op') }
rnHsTyKi isType doc (HsParTy ty)
= do { (ty', fvs) <- rnLHsTyKi isType doc ty
; return (HsParTy ty', fvs) }
rnHsTyKi isType doc (HsBangTy b ty)
= ASSERT( isType )
do { (ty', fvs) <- rnLHsType doc ty
; return (HsBangTy b ty', fvs) }
rnHsTyKi _ doc ty@(HsRecTy flds)
= do { addErr (hang (ptext (sLit "Record syntax is illegal here:"))
2 (ppr ty))
; (flds', fvs) <- rnConDeclFields doc flds
; return (HsRecTy flds', fvs) }
rnHsTyKi isType doc (HsFunTy ty1 ty2)
= do { (ty1', fvs1) <- rnLHsTyKi isType doc ty1
-- Might find a for-all as the arg of a function type
; (ty2', fvs2) <- rnLHsTyKi isType doc ty2
-- Or as the result. This happens when reading Prelude.hi
-- when we find return :: forall m. Monad m -> forall a. a -> m a
-- Check for fixity rearrangements
; res_ty <- if isType
then mkHsOpTyRn HsFunTy funTyConName funTyFixity ty1' ty2'
else return (HsFunTy ty1' ty2')
; return (res_ty, fvs1 `plusFV` fvs2) }
rnHsTyKi isType doc listTy@(HsListTy ty)
= do { data_kinds <- xoptM LangExt.DataKinds
; unless (data_kinds || isType) (addErr (dataKindsErr isType listTy))
; (ty', fvs) <- rnLHsTyKi isType doc ty
; return (HsListTy ty', fvs) }
rnHsTyKi isType doc (HsKindSig ty k)
= ASSERT( isType )
do { kind_sigs_ok <- xoptM LangExt.KindSignatures
; unless kind_sigs_ok (badSigErr False doc ty)
; (ty', fvs1) <- rnLHsType doc ty
; (k', fvs2) <- rnLHsKind doc k
; return (HsKindSig ty' k', fvs1 `plusFV` fvs2) }
rnHsTyKi isType doc (HsPArrTy ty)
= ASSERT( isType )
do { (ty', fvs) <- rnLHsType doc ty
; return (HsPArrTy ty', fvs) }
-- Unboxed tuples are allowed to have poly-typed arguments. These
-- sometimes crop up as a result of CPR worker-wrappering dictionaries.
rnHsTyKi isType doc tupleTy@(HsTupleTy tup_con tys)
= do { data_kinds <- xoptM LangExt.DataKinds
; unless (data_kinds || isType) (addErr (dataKindsErr isType tupleTy))
; (tys', fvs) <- mapFvRn (rnLHsTyKi isType doc) tys
; return (HsTupleTy tup_con tys', fvs) }
-- Ensure that a type-level integer is nonnegative (#8306, #8412)
rnHsTyKi isType _ tyLit@(HsTyLit t)
= do { data_kinds <- xoptM LangExt.DataKinds
; unless data_kinds (addErr (dataKindsErr isType tyLit))
; when (negLit t) (addErr negLitErr)
; return (HsTyLit t, emptyFVs) }
where
negLit (HsStrTy _ _) = False
negLit (HsNumTy _ i) = i < 0
negLitErr = ptext (sLit "Illegal literal in type (type literals must not be negative):") <+> ppr tyLit
rnHsTyKi isType doc (HsAppTy ty1 ty2)
= do { (ty1', fvs1) <- rnLHsTyKi isType doc ty1
; (ty2', fvs2) <- rnLHsTyKi isType doc ty2
; return (HsAppTy ty1' ty2', fvs1 `plusFV` fvs2) }
rnHsTyKi isType doc (HsIParamTy n ty)
= ASSERT( isType )
do { (ty', fvs) <- rnLHsType doc ty
; return (HsIParamTy n ty', fvs) }
rnHsTyKi isType doc (HsEqTy ty1 ty2)
= ASSERT( isType )
do { (ty1', fvs1) <- rnLHsType doc ty1
; (ty2', fvs2) <- rnLHsType doc ty2
; return (HsEqTy ty1' ty2', fvs1 `plusFV` fvs2) }
rnHsTyKi isType _ (HsSpliceTy sp _)
= ASSERT( isType )
rnSpliceType sp
rnHsTyKi isType doc (HsDocTy ty haddock_doc)
= ASSERT( isType )
do { (ty', fvs) <- rnLHsType doc ty
; haddock_doc' <- rnLHsDoc haddock_doc
; return (HsDocTy ty' haddock_doc', fvs) }
rnHsTyKi isType _ (HsCoreTy ty)
= ASSERT( isType )
return (HsCoreTy ty, emptyFVs)
-- The emptyFVs probably isn't quite right
-- but I don't think it matters
rnHsTyKi _ _ (HsWrapTy {})
= panic "rnHsTyKi"
rnHsTyKi isType doc ty@(HsExplicitListTy k tys)
= ASSERT( isType )
do { data_kinds <- xoptM LangExt.DataKinds
; unless data_kinds (addErr (dataKindsErr isType ty))
; (tys', fvs) <- rnLHsTypes doc tys
; return (HsExplicitListTy k tys', fvs) }
rnHsTyKi isType doc ty@(HsExplicitTupleTy kis tys)
= ASSERT( isType )
do { data_kinds <- xoptM LangExt.DataKinds
; unless data_kinds (addErr (dataKindsErr isType ty))
; (tys', fvs) <- rnLHsTypes doc tys
; return (HsExplicitTupleTy kis tys', fvs) }
rnHsTyKi _ _ HsWildcardTy = panic "rnHsTyKi HsWildcardTy"
-- Should be replaced by a HsNamedWildcardTy
rnHsTyKi isType _doc (HsNamedWildcardTy rdr_name)
= ASSERT( isType )
do { name <- rnTyVar isType rdr_name
; return (HsNamedWildcardTy name, unitFV name) }
--------------
rnHsTyKiForAll :: Bool -> HsDocContext -> HsType RdrName
-> RnM (HsType Name, FreeVars)
rnHsTyKiForAll isType doc (HsForAllTy Implicit extra _ lctxt@(L _ ctxt) ty)
= ASSERT( isType ) do
-- Implicit quantifiction in source code (no kinds on tyvars)
-- Given the signature C => T we universally quantify
-- over FV(T) \ {in-scope-tyvars}
rdr_env <- getLocalRdrEnv
loc <- getSrcSpanM
let
(forall_kvs, forall_tvs) = filterInScope rdr_env $
extractHsTysRdrTyVars (ty:ctxt)
-- In for-all types we don't bring in scope
-- kind variables mentioned in kind signatures
-- (Well, not yet anyway....)
-- f :: Int -> T (a::k) -- Not allowed
-- The filterInScope is to ensure that we don't quantify over
-- type variables that are in scope; when GlasgowExts is off,
-- there usually won't be any, except for class signatures:
-- class C a where { op :: a -> a }
tyvar_bndrs = userHsTyVarBndrs loc forall_tvs
rnForAll doc Implicit extra forall_kvs (mkHsQTvs tyvar_bndrs) lctxt ty
rnHsTyKiForAll isType doc
fulltype@(HsForAllTy Qualified extra _ lctxt@(L _ ctxt) ty)
= ASSERT( isType ) do
rdr_env <- getLocalRdrEnv
loc <- getSrcSpanM
let
(forall_kvs, forall_tvs) = filterInScope rdr_env $
extractHsTysRdrTyVars (ty:ctxt)
tyvar_bndrs = userHsTyVarBndrs loc forall_tvs
in_type_doc = ptext (sLit "In the type") <+> quotes (ppr fulltype)
-- See Note [Context quantification]
warnContextQuantification (in_type_doc $$ docOfHsDocContext doc) tyvar_bndrs
rnForAll doc Implicit extra forall_kvs (mkHsQTvs tyvar_bndrs) lctxt ty
rnHsTyKiForAll isType doc
ty@(HsForAllTy Explicit extra forall_tyvars lctxt@(L _ ctxt) tau)
= ASSERT( isType ) do { -- Explicit quantification.
-- Check that the forall'd tyvars are actually
-- mentioned in the type, and produce a warning if not
let (kvs, mentioned) = extractHsTysRdrTyVars (tau:ctxt)
in_type_doc = ptext (sLit "In the type") <+> quotes (ppr ty)
; warnUnusedForAlls (in_type_doc $$ docOfHsDocContext doc)
forall_tyvars mentioned
; traceRn "rnHsTyKiForAll:Exlicit" (vcat
[ppr forall_tyvars, ppr lctxt,ppr tau ])
; rnForAll doc Explicit extra kvs forall_tyvars lctxt tau }
-- The following should never happen but keeps the completeness checker happy
rnHsTyKiForAll isType doc ty = rnHsTyKi isType doc ty
--------------
rnTyVar :: Bool -> RdrName -> RnM Name
rnTyVar is_type rdr_name
| is_type = lookupTypeOccRn rdr_name
| otherwise = lookupKindOccRn rdr_name
--------------
rnLHsTypes :: HsDocContext -> [LHsType RdrName]
-> RnM ([LHsType Name], FreeVars)
rnLHsTypes doc tys = mapFvRn (rnLHsType doc) tys
rnForAll :: HsDocContext -> HsExplicitFlag
-> Maybe SrcSpan -- Location of an extra-constraints wildcard
-> [RdrName] -- Kind variables
-> LHsTyVarBndrs RdrName -- Type variables
-> LHsContext RdrName -> LHsType RdrName
-> RnM (HsType Name, FreeVars)
rnForAll doc exp extra kvs forall_tyvars ctxt ty
| null kvs, null (hsQTvBndrs forall_tyvars), null (unLoc ctxt), isNothing extra
= rnHsType doc (unLoc ty)
-- One reason for this case is that a type like Int#
-- starts off as (HsForAllTy Implicit Nothing [] Int), in case
-- there is some quantification. Now that we have quantified
-- and discovered there are no type variables, it's nicer to turn
-- it into plain Int. If it were Int# instead of Int, we'd actually
-- get an error, because the body of a genuine for-all is
-- of kind *.
| otherwise
= bindHsTyVars doc Nothing kvs forall_tyvars $ \ new_tyvars ->
do { (new_ctxt, fvs1) <- rnContext doc ctxt
; (new_ty, fvs2) <- rnLHsType doc ty
; return (HsForAllTy exp extra new_tyvars new_ctxt new_ty, fvs1 `plusFV` fvs2) }
-- Retain the same implicit/explicit flag as before
-- so that we can later print it correctly
---------------
bindSigTyVarsFV :: [Name]
-> RnM (a, FreeVars)
-> RnM (a, FreeVars)
-- Used just before renaming the defn of a function
-- with a separate type signature, to bring its tyvars into scope
-- With no -XScopedTypeVariables, this is a no-op
bindSigTyVarsFV tvs thing_inside
= do { scoped_tyvars <- xoptM LangExt.ScopedTypeVariables
; if not scoped_tyvars then
thing_inside
else
bindLocalNamesFV tvs thing_inside }
---------------
bindHsTyVars :: HsDocContext
-> Maybe a -- Just _ => an associated type decl
-> [RdrName] -- Kind variables from scope
-> LHsTyVarBndrs RdrName -- Type variables
-> (LHsTyVarBndrs Name -> RnM (b, FreeVars))
-> RnM (b, FreeVars)
-- (a) Bring kind variables into scope
-- both (i) passed in (kv_bndrs)
-- and (ii) mentioned in the kinds of tv_bndrs
-- (b) Bring type variables into scope
bindHsTyVars doc mb_assoc kv_bndrs tv_bndrs thing_inside
= do { rdr_env <- getLocalRdrEnv
; let tvs = hsQTvBndrs tv_bndrs
kvs_from_tv_bndrs = [ kv | L _ (KindedTyVar _ kind) <- tvs
, let (_, kvs) = extractHsTyRdrTyVars kind
, kv <- kvs ]
all_kvs' = nub (kv_bndrs ++ kvs_from_tv_bndrs)
all_kvs = filterOut (`elemLocalRdrEnv` rdr_env) all_kvs'
overlap_kvs = [ kv | kv <- all_kvs, any ((==) kv . hsLTyVarName) tvs ]
-- These variables appear both as kind and type variables
-- in the same declaration; eg type family T (x :: *) (y :: x)
-- We disallow this: too confusing!
; poly_kind <- xoptM LangExt.PolyKinds
; unless (poly_kind || null all_kvs)
(addErr (badKindBndrs doc all_kvs))
; unless (null overlap_kvs)
(addErr (overlappingKindVars doc overlap_kvs))
; loc <- getSrcSpanM
; kv_names <- mapM (newLocalBndrRn . L loc) all_kvs
; bindLocalNamesFV kv_names $
do { let tv_names_w_loc = hsLTyVarLocNames tv_bndrs
rn_tv_bndr :: LHsTyVarBndr RdrName -> RnM (LHsTyVarBndr Name, FreeVars)
rn_tv_bndr (L loc (UserTyVar rdr))
= do { nm <- newTyVarNameRn mb_assoc rdr_env loc rdr
; return (L loc (UserTyVar nm), emptyFVs) }
rn_tv_bndr (L loc (KindedTyVar (L lv rdr) kind))
= do { sig_ok <- xoptM LangExt.KindSignatures
; unless sig_ok (badSigErr False doc kind)
; nm <- newTyVarNameRn mb_assoc rdr_env loc rdr
; (kind', fvs) <- rnLHsKind doc kind
; return (L loc (KindedTyVar (L lv nm) kind'), fvs) }
-- Check for duplicate or shadowed tyvar bindrs
; checkDupRdrNames tv_names_w_loc
; when (isNothing mb_assoc) (checkShadowedRdrNames tv_names_w_loc)
; (tv_bndrs', fvs1) <- mapFvRn rn_tv_bndr tvs
; (res, fvs2) <- bindLocalNamesFV (map hsLTyVarName tv_bndrs') $
do { inner_rdr_env <- getLocalRdrEnv
; traceRn "bhtv" (vcat
[ ppr tvs, ppr kv_bndrs, ppr kvs_from_tv_bndrs
, ppr $ map (`elemLocalRdrEnv` rdr_env) all_kvs'
, ppr $ map (getUnique . rdrNameOcc) all_kvs'
, ppr all_kvs, ppr rdr_env, ppr inner_rdr_env ])
; thing_inside (HsQTvs { hsq_tvs = tv_bndrs', hsq_kvs = kv_names }) }
; return (res, fvs1 `plusFV` fvs2) } }
newTyVarNameRn :: Maybe a -> LocalRdrEnv -> SrcSpan -> RdrName -> RnM Name
newTyVarNameRn mb_assoc rdr_env loc rdr
| Just _ <- mb_assoc -- Use the same Name as the parent class decl
, Just n <- lookupLocalRdrEnv rdr_env rdr
= return n
| otherwise
= newLocalBndrRn (L loc rdr)
--------------------------------
rnHsBndrSig :: HsDocContext
-> HsWithBndrs RdrName (LHsType RdrName)
-> (HsWithBndrs Name (LHsType Name) -> RnM (a, FreeVars))
-> RnM (a, FreeVars)
rnHsBndrSig doc (HsWB { hswb_cts = ty@(L loc _) }) thing_inside
= do { sig_ok <- xoptM LangExt.ScopedTypeVariables
; unless sig_ok (badSigErr True doc ty)
; let (kv_bndrs, tv_bndrs) = extractHsTyRdrTyVars ty
; name_env <- getLocalRdrEnv
; tv_names <- newLocalBndrsRn [L loc tv | tv <- tv_bndrs
, not (tv `elemLocalRdrEnv` name_env) ]
; kv_names <- newLocalBndrsRn [L loc kv | kv <- kv_bndrs
, not (kv `elemLocalRdrEnv` name_env) ]
; (wcs, ty') <- extractWildcards ty
; bindLocalNamesFV kv_names $
bindLocalNamesFV tv_names $
bindLocatedLocalsFV wcs $ \wcs_new ->
do { (ty'', fvs1) <- rnLHsType doc ty'
; (res, fvs2) <- thing_inside (HsWB { hswb_cts = ty'', hswb_kvs = kv_names,
hswb_tvs = tv_names, hswb_wcs = wcs_new })
; return (res, fvs1 `plusFV` fvs2) } }
overlappingKindVars :: HsDocContext -> [RdrName] -> SDoc
overlappingKindVars doc kvs
= vcat [ ptext (sLit "Kind variable") <> plural kvs <+>
ptext (sLit "also used as type variable") <> plural kvs
<> colon <+> pprQuotedList kvs
, docOfHsDocContext doc ]
badKindBndrs :: HsDocContext -> [RdrName] -> SDoc
badKindBndrs doc kvs
= vcat [ hang (ptext (sLit "Unexpected kind variable") <> plural kvs
<+> pprQuotedList kvs)
2 (ptext (sLit "Perhaps you intended to use PolyKinds"))
, docOfHsDocContext doc ]
badSigErr :: Bool -> HsDocContext -> LHsType RdrName -> TcM ()
badSigErr is_type doc (L loc ty)
= setSrcSpan loc $ addErr $
vcat [ hang (ptext (sLit "Illegal") <+> what
<+> ptext (sLit "signature:") <+> quotes (ppr ty))
2 (ptext (sLit "Perhaps you intended to use") <+> flag)
, docOfHsDocContext doc ]
where
what | is_type = ptext (sLit "type")
| otherwise = ptext (sLit "kind")
flag | is_type = ptext (sLit "ScopedTypeVariables")
| otherwise = ptext (sLit "KindSignatures")
dataKindsErr :: Bool -> HsType RdrName -> SDoc
dataKindsErr is_type thing
= hang (ptext (sLit "Illegal") <+> what <> colon <+> quotes (ppr thing))
2 (ptext (sLit "Perhaps you intended to use DataKinds"))
where
what | is_type = ptext (sLit "type")
| otherwise = ptext (sLit "kind")
{-
*********************************************************
* *
\subsection{Contexts and predicates}
* *
*********************************************************
-}
rnConDeclFields :: HsDocContext -> [LConDeclField RdrName]
-> RnM ([LConDeclField Name], FreeVars)
rnConDeclFields doc fields = mapFvRn (rnField doc) fields
rnField :: HsDocContext -> LConDeclField RdrName
-> RnM (LConDeclField Name, FreeVars)
rnField doc (L l (ConDeclField names ty haddock_doc _))
= do { new_names <- mapM lookupLocatedTopBndrRn names
; (new_ty, fvs) <- rnLHsType doc ty
; new_haddock_doc <- rnMbLHsDoc haddock_doc
; return (L l (ConDeclField new_names new_ty new_haddock_doc []), fvs) }
rnContext :: HsDocContext -> LHsContext RdrName -> RnM (LHsContext Name, FreeVars)
rnContext doc (L loc cxt)
= do { (cxt', fvs) <- rnLHsTypes doc cxt
; return (L loc cxt', fvs) }
{-
************************************************************************
* *
Fixities and precedence parsing
* *
************************************************************************
@mkOpAppRn@ deals with operator fixities. The argument expressions
are assumed to be already correctly arranged. It needs the fixities
recorded in the OpApp nodes, because fixity info applies to the things
the programmer actually wrote, so you can't find it out from the Name.
Furthermore, the second argument is guaranteed not to be another
operator application. Why? Because the parser parses all
operator appications left-associatively, EXCEPT negation, which
we need to handle specially.
Infix types are read in a *right-associative* way, so that
a `op` b `op` c
is always read in as
a `op` (b `op` c)
mkHsOpTyRn rearranges where necessary. The two arguments
have already been renamed and rearranged. It's made rather tiresome
by the presence of ->, which is a separate syntactic construct.
-}
---------------
-- Building (ty1 `op1` (ty21 `op2` ty22))
mkHsOpTyRn :: (LHsType Name -> LHsType Name -> HsType Name)
-> Name -> Fixity -> LHsType Name -> LHsType Name
-> RnM (HsType Name)
mkHsOpTyRn mk1 pp_op1 fix1 ty1 (L loc2 (HsOpTy ty21 (w2, op2) ty22))
= do { fix2 <- lookupTyFixityRn op2
; mk_hs_op_ty mk1 pp_op1 fix1 ty1
(\t1 t2 -> HsOpTy t1 (w2, op2) t2)
(unLoc op2) fix2 ty21 ty22 loc2 }
mkHsOpTyRn mk1 pp_op1 fix1 ty1 (L loc2 (HsFunTy ty21 ty22))
= mk_hs_op_ty mk1 pp_op1 fix1 ty1
HsFunTy funTyConName funTyFixity ty21 ty22 loc2
mkHsOpTyRn mk1 _ _ ty1 ty2 -- Default case, no rearrangment
= return (mk1 ty1 ty2)
---------------
mk_hs_op_ty :: (LHsType Name -> LHsType Name -> HsType Name)
-> Name -> Fixity -> LHsType Name
-> (LHsType Name -> LHsType Name -> HsType Name)
-> Name -> Fixity -> LHsType Name -> LHsType Name -> SrcSpan
-> RnM (HsType Name)
mk_hs_op_ty mk1 op1 fix1 ty1
mk2 op2 fix2 ty21 ty22 loc2
| nofix_error = do { precParseErr (op1,fix1) (op2,fix2)
; return (mk1 ty1 (L loc2 (mk2 ty21 ty22))) }
| associate_right = return (mk1 ty1 (L loc2 (mk2 ty21 ty22)))
| otherwise = do { -- Rearrange to ((ty1 `op1` ty21) `op2` ty22)
new_ty <- mkHsOpTyRn mk1 op1 fix1 ty1 ty21
; return (mk2 (noLoc new_ty) ty22) }
where
(nofix_error, associate_right) = compareFixity fix1 fix2
---------------------------
mkOpAppRn :: LHsExpr Name -- Left operand; already rearranged
-> LHsExpr Name -> Fixity -- Operator and fixity
-> LHsExpr Name -- Right operand (not an OpApp, but might
-- be a NegApp)
-> RnM (HsExpr Name)
-- (e11 `op1` e12) `op2` e2
mkOpAppRn e1@(L _ (OpApp e11 op1 fix1 e12)) op2 fix2 e2
| nofix_error
= do precParseErr (get_op op1,fix1) (get_op op2,fix2)
return (OpApp e1 op2 fix2 e2)
| associate_right = do
new_e <- mkOpAppRn e12 op2 fix2 e2
return (OpApp e11 op1 fix1 (L loc' new_e))
where
loc'= combineLocs e12 e2
(nofix_error, associate_right) = compareFixity fix1 fix2
---------------------------
-- (- neg_arg) `op` e2
mkOpAppRn e1@(L _ (NegApp neg_arg neg_name)) op2 fix2 e2
| nofix_error
= do precParseErr (negateName,negateFixity) (get_op op2,fix2)
return (OpApp e1 op2 fix2 e2)
| associate_right
= do new_e <- mkOpAppRn neg_arg op2 fix2 e2
return (NegApp (L loc' new_e) neg_name)
where
loc' = combineLocs neg_arg e2
(nofix_error, associate_right) = compareFixity negateFixity fix2
---------------------------
-- e1 `op` - neg_arg
mkOpAppRn e1 op1 fix1 e2@(L _ (NegApp _ _)) -- NegApp can occur on the right
| not associate_right -- We *want* right association
= do precParseErr (get_op op1, fix1) (negateName, negateFixity)
return (OpApp e1 op1 fix1 e2)
where
(_, associate_right) = compareFixity fix1 negateFixity
---------------------------
-- Default case
mkOpAppRn e1 op fix e2 -- Default case, no rearrangment
= ASSERT2( right_op_ok fix (unLoc e2),
ppr e1 $$ text "---" $$ ppr op $$ text "---" $$ ppr fix $$ text "---" $$ ppr e2
)
return (OpApp e1 op fix e2)
----------------------------
get_op :: LHsExpr Name -> Name
get_op (L _ (HsVar n)) = n
get_op other = pprPanic "get_op" (ppr other)
-- Parser left-associates everything, but
-- derived instances may have correctly-associated things to
-- in the right operarand. So we just check that the right operand is OK
right_op_ok :: Fixity -> HsExpr Name -> Bool
right_op_ok fix1 (OpApp _ _ fix2 _)
= not error_please && associate_right
where
(error_please, associate_right) = compareFixity fix1 fix2
right_op_ok _ _
= True
-- Parser initially makes negation bind more tightly than any other operator
-- And "deriving" code should respect this (use HsPar if not)
mkNegAppRn :: LHsExpr id -> SyntaxExpr id -> RnM (HsExpr id)
mkNegAppRn neg_arg neg_name
= ASSERT( not_op_app (unLoc neg_arg) )
return (NegApp neg_arg neg_name)
not_op_app :: HsExpr id -> Bool
not_op_app (OpApp _ _ _ _) = False
not_op_app _ = True
---------------------------
mkOpFormRn :: LHsCmdTop Name -- Left operand; already rearranged
-> LHsExpr Name -> Fixity -- Operator and fixity
-> LHsCmdTop Name -- Right operand (not an infix)
-> RnM (HsCmd Name)
-- (e11 `op1` e12) `op2` e2
mkOpFormRn a1@(L loc (HsCmdTop (L _ (HsCmdArrForm op1 (Just fix1) [a11,a12])) _ _ _))
op2 fix2 a2
| nofix_error
= do precParseErr (get_op op1,fix1) (get_op op2,fix2)
return (HsCmdArrForm op2 (Just fix2) [a1, a2])
| associate_right
= do new_c <- mkOpFormRn a12 op2 fix2 a2
return (HsCmdArrForm op1 (Just fix1)
[a11, L loc (HsCmdTop (L loc new_c)
placeHolderType placeHolderType [])])
-- TODO: locs are wrong
where
(nofix_error, associate_right) = compareFixity fix1 fix2
-- Default case
mkOpFormRn arg1 op fix arg2 -- Default case, no rearrangment
= return (HsCmdArrForm op (Just fix) [arg1, arg2])
--------------------------------------
mkConOpPatRn :: Located Name -> Fixity -> LPat Name -> LPat Name
-> RnM (Pat Name)
mkConOpPatRn op2 fix2 p1@(L loc (ConPatIn op1 (InfixCon p11 p12))) p2
= do { fix1 <- lookupFixityRn (unLoc op1)
; let (nofix_error, associate_right) = compareFixity fix1 fix2
; if nofix_error then do
{ precParseErr (unLoc op1,fix1) (unLoc op2,fix2)
; return (ConPatIn op2 (InfixCon p1 p2)) }
else if associate_right then do
{ new_p <- mkConOpPatRn op2 fix2 p12 p2
; return (ConPatIn op1 (InfixCon p11 (L loc new_p))) } -- XXX loc right?
else return (ConPatIn op2 (InfixCon p1 p2)) }
mkConOpPatRn op _ p1 p2 -- Default case, no rearrangment
= ASSERT( not_op_pat (unLoc p2) )
return (ConPatIn op (InfixCon p1 p2))
not_op_pat :: Pat Name -> Bool
not_op_pat (ConPatIn _ (InfixCon _ _)) = False
not_op_pat _ = True
--------------------------------------
checkPrecMatch :: Name -> MatchGroup Name body -> RnM ()
-- Check precedence of a function binding written infix
-- eg a `op` b `C` c = ...
-- See comments with rnExpr (OpApp ...) about "deriving"
checkPrecMatch op (MG { mg_alts = ms })
= mapM_ check ms
where
check (L _ (Match _ (L l1 p1 : L l2 p2 :_) _ _))
= setSrcSpan (combineSrcSpans l1 l2) $
do checkPrec op p1 False
checkPrec op p2 True
check _ = return ()
-- This can happen. Consider
-- a `op` True = ...
-- op = ...
-- The infix flag comes from the first binding of the group
-- but the second eqn has no args (an error, but not discovered
-- until the type checker). So we don't want to crash on the
-- second eqn.
checkPrec :: Name -> Pat Name -> Bool -> IOEnv (Env TcGblEnv TcLclEnv) ()
checkPrec op (ConPatIn op1 (InfixCon _ _)) right = do
op_fix@(Fixity op_prec op_dir) <- lookupFixityRn op
op1_fix@(Fixity op1_prec op1_dir) <- lookupFixityRn (unLoc op1)
let
inf_ok = op1_prec > op_prec ||
(op1_prec == op_prec &&
(op1_dir == InfixR && op_dir == InfixR && right ||
op1_dir == InfixL && op_dir == InfixL && not right))
info = (op, op_fix)
info1 = (unLoc op1, op1_fix)
(infol, infor) = if right then (info, info1) else (info1, info)
unless inf_ok (precParseErr infol infor)
checkPrec _ _ _
= return ()
-- Check precedence of (arg op) or (op arg) respectively
-- If arg is itself an operator application, then either
-- (a) its precedence must be higher than that of op
-- (b) its precedency & associativity must be the same as that of op
checkSectionPrec :: FixityDirection -> HsExpr RdrName
-> LHsExpr Name -> LHsExpr Name -> RnM ()
checkSectionPrec direction section op arg
= case unLoc arg of
OpApp _ op fix _ -> go_for_it (get_op op) fix
NegApp _ _ -> go_for_it negateName negateFixity
_ -> return ()
where
op_name = get_op op
go_for_it arg_op arg_fix@(Fixity arg_prec assoc) = do
op_fix@(Fixity op_prec _) <- lookupFixityRn op_name
unless (op_prec < arg_prec
|| (op_prec == arg_prec && direction == assoc))
(sectionPrecErr (op_name, op_fix)
(arg_op, arg_fix) section)
-- Precedence-related error messages
precParseErr :: (Name, Fixity) -> (Name, Fixity) -> RnM ()
precParseErr op1@(n1,_) op2@(n2,_)
| isUnboundName n1 || isUnboundName n2
= return () -- Avoid error cascade
| otherwise
= addErr $ hang (ptext (sLit "Precedence parsing error"))
4 (hsep [ptext (sLit "cannot mix"), ppr_opfix op1, ptext (sLit "and"),
ppr_opfix op2,
ptext (sLit "in the same infix expression")])
sectionPrecErr :: (Name, Fixity) -> (Name, Fixity) -> HsExpr RdrName -> RnM ()
sectionPrecErr op@(n1,_) arg_op@(n2,_) section
| isUnboundName n1 || isUnboundName n2
= return () -- Avoid error cascade
| otherwise
= addErr $ vcat [ptext (sLit "The operator") <+> ppr_opfix op <+> ptext (sLit "of a section"),
nest 4 (sep [ptext (sLit "must have lower precedence than that of the operand,"),
nest 2 (ptext (sLit "namely") <+> ppr_opfix arg_op)]),
nest 4 (ptext (sLit "in the section:") <+> quotes (ppr section))]
ppr_opfix :: (Name, Fixity) -> SDoc
ppr_opfix (op, fixity) = pp_op <+> brackets (ppr fixity)
where
pp_op | op == negateName = ptext (sLit "prefix `-'")
| otherwise = quotes (ppr op)
{-
*********************************************************
* *
\subsection{Errors}
* *
*********************************************************
-}
warnUnusedForAlls :: SDoc -> LHsTyVarBndrs RdrName -> [RdrName] -> TcM ()
warnUnusedForAlls in_doc bound mentioned_rdrs
= whenWOptM Opt_WarnUnusedMatches $
mapM_ add_warn bound_but_not_used
where
bound_names = hsLTyVarLocNames bound
bound_but_not_used = filterOut ((`elem` mentioned_rdrs) . unLoc) bound_names
add_warn (L loc tv)
= addWarnAt (Reason Opt_WarnUnusedMatches) loc $
vcat [ ptext (sLit "Unused quantified type variable") <+> quotes (ppr tv)
, in_doc ]
warnContextQuantification :: SDoc -> [LHsTyVarBndr RdrName] -> TcM ()
warnContextQuantification in_doc tvs
= whenWOptM Opt_WarnContextQuantification $
mapM_ add_warn tvs
where
add_warn (L loc tv)
= addWarnAt (Reason Opt_WarnContextQuantification) loc $
vcat [ ptext (sLit "Variable") <+> quotes (ppr tv) <+>
ptext (sLit "is implicitly quantified due to a context") $$
ptext (sLit "Use explicit forall syntax instead.") $$
ptext (sLit "This will become an error in GHC 7.12.")
, in_doc ]
opTyErr :: RdrName -> HsType RdrName -> SDoc
opTyErr op ty@(HsOpTy ty1 _ _)
= hang (ptext (sLit "Illegal operator") <+> quotes (ppr op) <+> ptext (sLit "in type") <+> quotes (ppr ty))
2 extra
where
extra | op == dot_tv_RDR && forall_head ty1
= perhapsForallMsg
| otherwise
= ptext (sLit "Use TypeOperators to allow operators in types")
forall_head (L _ (HsTyVar tv)) = tv == forall_tv_RDR
forall_head (L _ (HsAppTy ty _)) = forall_head ty
forall_head _other = False
opTyErr _ ty = pprPanic "opTyErr: Not an op" (ppr ty)
{-
************************************************************************
* *
Finding the free type variables of a (HsType RdrName)
* *
************************************************************************
Note [Kind and type-variable binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a type signature we may implicitly bind type varaible and, more
recently, kind variables. For example:
* f :: a -> a
f = ...
Here we need to find the free type variables of (a -> a),
so that we know what to quantify
* class C (a :: k) where ...
This binds 'k' in ..., as well as 'a'
* f (x :: a -> [a]) = ....
Here we bind 'a' in ....
* f (x :: T a -> T (b :: k)) = ...
Here we bind both 'a' and the kind variable 'k'
* type instance F (T (a :: Maybe k)) = ...a...k...
Here we want to constrain the kind of 'a', and bind 'k'.
In general we want to walk over a type, and find
* Its free type variables
* The free kind variables of any kind signatures in the type
Hence we returns a pair (kind-vars, type vars)
See also Note [HsBSig binder lists] in HsTypes
-}
type FreeKiTyVars = ([RdrName], [RdrName])
filterInScope :: LocalRdrEnv -> FreeKiTyVars -> FreeKiTyVars
filterInScope rdr_env (kvs, tvs)
= (filterOut in_scope kvs, filterOut in_scope tvs)
where
in_scope tv = tv `elemLocalRdrEnv` rdr_env
extractHsTyRdrTyVars :: LHsType RdrName -> FreeKiTyVars
-- extractHsTyRdrNames finds the free (kind, type) variables of a HsType
-- or the free (sort, kind) variables of a HsKind
-- It's used when making the for-alls explicit.
-- See Note [Kind and type-variable binders]
extractHsTyRdrTyVars ty
= case extract_lty ty ([],[]) of
(kvs, tvs) -> (nub kvs, nub tvs)
extractHsTysRdrTyVars :: [LHsType RdrName] -> FreeKiTyVars
-- See Note [Kind and type-variable binders]
extractHsTysRdrTyVars ty
= case extract_ltys ty ([],[]) of
(kvs, tvs) -> (nub kvs, nub tvs)
extractRdrKindSigVars :: Maybe (LHsKind RdrName) -> [RdrName]
extractRdrKindSigVars Nothing = []
extractRdrKindSigVars (Just k) = nub (fst (extract_lkind k ([],[])))
extractDataDefnKindVars :: HsDataDefn RdrName -> [RdrName]
-- Get the scoped kind variables mentioned free in the constructor decls
-- Eg data T a = T1 (S (a :: k) | forall (b::k). T2 (S b)
-- Here k should scope over the whole definition
extractDataDefnKindVars (HsDataDefn { dd_ctxt = ctxt, dd_kindSig = ksig
, dd_cons = cons, dd_derivs = derivs })
= fst $ extract_lctxt ctxt $
extract_mb extract_lkind ksig $
extract_mb (extract_ltys . unLoc) derivs $
foldr (extract_con . unLoc) ([],[]) cons
where
extract_con (ConDecl { con_res = ResTyGADT {} }) acc = acc
extract_con (ConDecl { con_res = ResTyH98, con_qvars = qvs
, con_cxt = ctxt, con_details = details }) acc
= extract_hs_tv_bndrs qvs acc $
extract_lctxt ctxt $
extract_ltys (hsConDeclArgTys details) ([],[])
extract_lctxt :: LHsContext RdrName -> FreeKiTyVars -> FreeKiTyVars
extract_lctxt ctxt = extract_ltys (unLoc ctxt)
extract_ltys :: [LHsType RdrName] -> FreeKiTyVars -> FreeKiTyVars
extract_ltys tys acc = foldr extract_lty acc tys
extract_mb :: (a -> FreeKiTyVars -> FreeKiTyVars) -> Maybe a -> FreeKiTyVars -> FreeKiTyVars
extract_mb _ Nothing acc = acc
extract_mb f (Just x) acc = f x acc
extract_lkind :: LHsType RdrName -> FreeKiTyVars -> FreeKiTyVars
extract_lkind kind (acc_kvs, acc_tvs) = case extract_lty kind ([], acc_kvs) of
(_, res_kvs) -> (res_kvs, acc_tvs)
-- Kinds shouldn't have sort signatures!
extract_lty :: LHsType RdrName -> FreeKiTyVars -> FreeKiTyVars
extract_lty (L _ ty) acc
= case ty of
HsTyVar tv -> extract_tv tv acc
HsBangTy _ ty -> extract_lty ty acc
HsRecTy flds -> foldr (extract_lty . cd_fld_type . unLoc) acc
flds
HsAppTy ty1 ty2 -> extract_lty ty1 (extract_lty ty2 acc)
HsListTy ty -> extract_lty ty acc
HsPArrTy ty -> extract_lty ty acc
HsTupleTy _ tys -> extract_ltys tys acc
HsFunTy ty1 ty2 -> extract_lty ty1 (extract_lty ty2 acc)
HsIParamTy _ ty -> extract_lty ty acc
HsEqTy ty1 ty2 -> extract_lty ty1 (extract_lty ty2 acc)
HsOpTy ty1 (_, (L _ tv)) ty2 -> extract_tv tv (extract_lty ty1 (extract_lty ty2 acc))
HsParTy ty -> extract_lty ty acc
HsCoreTy {} -> acc -- The type is closed
HsSpliceTy {} -> acc -- Type splices mention no type variables
HsDocTy ty _ -> extract_lty ty acc
HsExplicitListTy _ tys -> extract_ltys tys acc
HsExplicitTupleTy _ tys -> extract_ltys tys acc
HsTyLit _ -> acc
HsWrapTy _ _ -> panic "extract_lty"
HsKindSig ty ki -> extract_lty ty (extract_lkind ki acc)
HsForAllTy _ _ tvs cx ty -> extract_hs_tv_bndrs tvs acc $
extract_lctxt cx $
extract_lty ty ([],[])
-- We deal with these to in a later stage, because they need to be
-- replaced by fresh HsTyVars.
HsWildcardTy -> acc
HsNamedWildcardTy _ -> acc
extract_hs_tv_bndrs :: LHsTyVarBndrs RdrName -> FreeKiTyVars
-> FreeKiTyVars -> FreeKiTyVars
extract_hs_tv_bndrs (HsQTvs { hsq_tvs = tvs })
(acc_kvs, acc_tvs) -- Note accumulator comes first
(body_kvs, body_tvs)
| null tvs
= (body_kvs ++ acc_kvs, body_tvs ++ acc_tvs)
| otherwise
= (acc_kvs ++ filterOut (`elem` local_kvs) body_kvs,
acc_tvs ++ filterOut (`elem` local_tvs) body_tvs)
where
local_tvs = map hsLTyVarName tvs
(_, local_kvs) = foldr extract_lty ([], []) [k | L _ (KindedTyVar _ k) <- tvs]
-- These kind variables are bound here if not bound further out
extract_tv :: RdrName -> FreeKiTyVars -> FreeKiTyVars
extract_tv tv acc
| isRdrTyVar tv = case acc of (kvs,tvs) -> (kvs, tv : tvs)
| otherwise = acc
-- | Replace all unnamed wildcards in the given type with named wildcards.
-- These names are freshly generated, based on "_". Return a tuple of the
-- named wildcards that weren't already in scope (amongst them the named
-- wildcards the unnamed ones were converted into), and the type in which the
-- unnamed wildcards are replaced by named wildcards.
extractWildcards :: LHsType RdrName -> RnM ([Located RdrName], LHsType RdrName)
extractWildcards ty
= do { (nwcs, awcs, ty') <- go ty
; rdr_env <- getLocalRdrEnv
-- Filter out named wildcards that are already in scope
; let nwcs' = nubBy eqLocated $ filterOut (flip (elemLocalRdrEnv . unLoc) rdr_env) nwcs
; return (nwcs' ++ awcs, ty') }
where
go orig@(L l ty) = case ty of
(HsForAllTy exp extra bndrs (L locCxt cxt) ty) ->
do (nwcs1, awcs1, cxt') <- extList cxt
(nwcs2, awcs2, ty') <- go ty
return (nwcs1 ++ nwcs2, awcs1 ++ awcs2,
L l (HsForAllTy exp extra bndrs (L locCxt cxt') ty'))
(HsAppTy ty1 ty2) -> go2 HsAppTy ty1 ty2
(HsFunTy ty1 ty2) -> go2 HsFunTy ty1 ty2
(HsListTy ty) -> go1 HsListTy ty
(HsPArrTy ty) -> go1 HsPArrTy ty
(HsTupleTy con tys) -> goList (HsTupleTy con) tys
(HsOpTy ty1 op ty2) -> go2 (\t1 t2 -> HsOpTy t1 op t2) ty1 ty2
(HsParTy ty) -> go1 HsParTy ty
(HsIParamTy n ty) -> go1 (HsIParamTy n) ty
(HsEqTy ty1 ty2) -> go2 HsEqTy ty1 ty2
(HsKindSig ty kind) -> go2 HsKindSig ty kind
(HsDocTy ty doc) -> go1 (flip HsDocTy doc) ty
(HsBangTy b ty) -> go1 (HsBangTy b) ty
(HsExplicitListTy ptk tys) -> goList (HsExplicitListTy ptk) tys
(HsExplicitTupleTy ptk tys) -> goList (HsExplicitTupleTy ptk) tys
HsWildcardTy -> do
uniq <- newUnique
let name = mkInternalName uniq (mkTyVarOcc "_") l
rdrName = nameRdrName name
return ([], [L l rdrName], L l $ HsNamedWildcardTy rdrName)
(HsNamedWildcardTy name) -> return ([L l name], [], orig)
-- TODO: Is this correct?
HsSpliceTy (HsSpliced _ (HsSplicedTy ty)) _ -> go $ L noSrcSpan ty
-- HsSpliceTy, HsRecTy, HsCoreTy, HsTyLit, HsWrapTy
_ -> return ([], [], orig)
where
go1 f t = do (nwcs, awcs, t') <- go t
return (nwcs, awcs, L l $ f t')
go2 f t1 t2 =
do (nwcs1, awcs1, t1') <- go t1
(nwcs2, awcs2, t2') <- go t2
return (nwcs1 ++ nwcs2, awcs1 ++ awcs2, L l $ f t1' t2')
extList l = do rec_res <- mapM go l
let (nwcs, awcs, tys') =
foldr (\(nwcs, awcs, ty) (nwcss, awcss, tys) ->
(nwcs ++ nwcss, awcs ++ awcss, ty : tys))
([], [], []) rec_res
return (nwcs, awcs, tys')
goList f tys = do (nwcs, awcs, tys') <- extList tys
return (nwcs, awcs, L l $ f tys')
|
rahulmutt/ghcvm
|
compiler/Eta/Rename/RnTypes.hs
|
bsd-3-clause
| 45,197 | 0 | 22 | 13,150 | 12,072 | 6,160 | 5,912 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Hooks.DynamicBars
-- Copyright : (c) Ben Boeckel 2012
-- License : BSD-style (as xmonad)
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : unportable
--
-- Manage per-screen status bars.
--
-----------------------------------------------------------------------------
module XMonad.Hooks.DynamicBars (
-- * Usage
-- $usage
DynamicStatusBar
, DynamicStatusBarCleanup
, dynStatusBarStartup
, dynStatusBarEventHook
, multiPP
) where
import Prelude
import Control.Concurrent.MVar
import Control.Monad
import Control.Monad.Trans (lift)
import Control.Monad.Writer (WriterT, execWriterT, tell)
import Data.Maybe
import Data.Monoid
import Data.Traversable (traverse)
import Graphics.X11.Xinerama
import Graphics.X11.Xlib
import Graphics.X11.Xlib.Extras
import Graphics.X11.Xrandr
import System.IO
import System.IO.Unsafe
import XMonad
import qualified XMonad.StackSet as W
import XMonad.Hooks.DynamicLog
-- $usage
-- Provides a few helper functions to manage per-screen status bars while
-- dynamically responding to screen changes. A startup action, event hook, and
-- a way to separate PP styles based on the screen's focus are provided:
--
-- * The 'dynStatusBarStartup' hook which initializes the status bars.
--
-- * The 'dynStatusBarEventHook' hook which respawns status bars when the
-- number of screens changes.
--
-- * The 'multiPP' function which allows for different output based on whether
-- the screen for the status bar has focus.
--
-- The hooks take a 'DynamicStatusBar' function which is given the id of the
-- screen to start up and returns the 'Handle' to the pipe to write to. The
-- 'DynamicStatusBarCleanup' argument should tear down previous instances. It
-- is called when the number of screens changes and on startup.
--
data DynStatusBarInfo = DynStatusBarInfo
{ dsbInfoScreens :: [ScreenId]
, dsbInfoHandles :: [Handle]
}
type DynamicStatusBar = ScreenId -> IO Handle
type DynamicStatusBarCleanup = IO ()
-- Global state
statusBarInfo :: MVar DynStatusBarInfo
statusBarInfo = unsafePerformIO $ newMVar (DynStatusBarInfo [] [])
dynStatusBarStartup :: DynamicStatusBar -> DynamicStatusBarCleanup -> X ()
dynStatusBarStartup sb cleanup = liftIO $ do
dpy <- openDisplay ""
xrrSelectInput dpy (defaultRootWindow dpy) rrScreenChangeNotifyMask
closeDisplay dpy
updateStatusBars sb cleanup
dynStatusBarEventHook :: DynamicStatusBar -> DynamicStatusBarCleanup -> Event -> X All
dynStatusBarEventHook sb cleanup (RRScreenChangeNotifyEvent {}) = liftIO (updateStatusBars sb cleanup) >> return (All True)
dynStatusBarEventHook _ _ _ = return (All True)
updateStatusBars :: DynamicStatusBar -> DynamicStatusBarCleanup -> IO ()
updateStatusBars sb cleanup = liftIO $ do
dsbInfo <- takeMVar statusBarInfo
screens <- getScreens
if (screens /= (dsbInfoScreens dsbInfo))
then do
mapM hClose (dsbInfoHandles dsbInfo)
cleanup
newHandles <- mapM sb screens
putMVar statusBarInfo (DynStatusBarInfo screens newHandles)
else putMVar statusBarInfo dsbInfo
-----------------------------------------------------------------------------
-- The following code is from adamvo's xmonad.hs file.
-- http://www.haskell.org/haskellwiki/Xmonad/Config_archive/adamvo%27s_xmonad.hs
multiPP :: PP -- ^ The PP to use if the screen is focused
-> PP -- ^ The PP to use otherwise
-> X ()
multiPP focusPP unfocusPP = do
dsbInfo <- liftIO $ readMVar statusBarInfo
multiPP' dynamicLogString focusPP unfocusPP (dsbInfoHandles dsbInfo)
multiPP' :: (PP -> X String) -> PP -> PP -> [Handle] -> X ()
multiPP' dynlStr focusPP unfocusPP handles = do
st <- get
let pickPP :: WorkspaceId -> WriterT (Last XState) X String
pickPP ws = do
let isFoc = (ws ==) . W.tag . W.workspace . W.current $ windowset st
put st{ windowset = W.view ws $ windowset st }
out <- lift $ dynlStr $ if isFoc then focusPP else unfocusPP
when isFoc $ get >>= tell . Last . Just
return out
traverse put . getLast
=<< execWriterT . (io . zipWithM_ hPutStrLn handles <=< mapM pickPP) . catMaybes
=<< mapM screenWorkspace (zipWith const [0 .. ] handles)
return ()
getScreens :: IO [ScreenId]
getScreens = do
screens <- do
dpy <- openDisplay ""
rects <- getScreenInfo dpy
closeDisplay dpy
return rects
let ids = zip [0 .. ] screens
return $ map fst ids
|
markus1189/xmonad-contrib-710
|
XMonad/Hooks/DynamicBars.hs
|
bsd-3-clause
| 4,571 | 0 | 19 | 848 | 966 | 507 | 459 | -1 | -1 |
-- | Properties that specify the appearance of the GUI elements.
-- The specification is inspired by CSS. All properties
-- are set in the cascade manner. For example, if you want to change the font type
-- for all elements you should set this property only for the top-most GUI element.
-- If the property is set on the lower level it wins versus property that is set on the
-- higher level.
module Csound.Control.Gui.Props (
-- * Properties
props, forceProps,
Prop(..), BorderType(..), Color,
Rect(..), FontType(..), Emphasis(..),
Material(..), Orient(..),
-- * Setters
-- | Handy short-cuts for the function @props@.
setBorder, setLabel, setMaterial,
setColor1, setColor2, setColors, setTextColor,
setFontSize, setFontType, setEmphasis, setOrient
) where
import Csound.Typed.Gui
|
isomorphism/csound-expression
|
src/Csound/Control/Gui/Props.hs
|
bsd-3-clause
| 831 | 0 | 5 | 165 | 116 | 83 | 33 | 9 | 0 |
module FunIn4 where
--Default parameters can be added to definition of functions and simple constants.
--In this example: add parameter 'y' to 'foo'
main::Int
main = sum [x+4 |let foo =[1..4], x<-foo]
|
kmate/HaRe
|
test/testdata/AddOneParameter/FunIn4.hs
|
bsd-3-clause
| 205 | 0 | 11 | 36 | 49 | 28 | 21 | 3 | 1 |
{-# LANGUAGE GADTs, DataKinds, KindSignatures, PolyKinds, FlexibleContexts, RankNTypes, ScopedTypeVariables #-}
module T9725 where
data En = M Bool
class Kn (l :: En)
instance Kn (M b)
data Fac :: En -> * where
Mo :: Kn (M b) => Fac (M b)
data Fm :: * -> * where
HiF :: Kn (ent b) => Fm (Fac (ent b)) -> Fm (O ent)
MoF :: Kn (M b) => Fm (Fac (M b))
data O :: (k -> En) -> * where
Hi :: Fac (ent k) -> O ent
data Co :: (* -> *) -> * -> * where
Ab :: (t -> f t) -> Co f t
-- Restricted kind signature:
--test :: forall (ent :: Bool -> En) . (forall i . Kn (ent i) => Fm (Fac (ent i))) -> Co Fm (O ent)
test :: forall ent . (forall i . Kn (ent i) => Fm (Fac (ent i))) -> Co Fm (O ent)
test de = Ab h
where h :: O ent -> Fm (O ent)
h (Hi m@Mo) = HiF (d m)
d :: Kn (ent i) => Fac (ent i) -> Fm (Fac (ent i))
d _ = de
{-
9725.hs:27:25:
Could not deduce (Kn (ent k1)) arising from a use of ‘HiF’
from the context (ent k1 ~ 'M b, Kn ('M b))
bound by a pattern with constructor
Mo :: forall (b :: Bool). Kn ('M b) => Fac ('M b),
in an equation for ‘h’
at 9725.hs:27:19-20
In the expression: HiF (d m)
In an equation for ‘h’: h (Hi m@Mo) = HiF (d m)
In an equation for ‘test’:
test de
= Ab h
where
h :: O ent -> Fm (O ent)
h (Hi m@Mo) = HiF (d m)
d :: Kn (ent i) => Fac (ent i) -> Fm (Fac (ent i))
d _ = de
Failed, modules loaded: none.
-}
|
shlevy/ghc
|
testsuite/tests/polykinds/T9725.hs
|
bsd-3-clause
| 1,547 | 0 | 14 | 520 | 431 | 222 | 209 | -1 | -1 |
{-# LANGUAGE TypeFamilies, ConstraintKinds #-}
import qualified Data.Set as S
import GHC.Exts ( Constraint )
class RMonad m where
type RMonadCtxt m a :: Constraint
returnR :: (RMonadCtxt m a) => a -> m a
bindR :: (RMonadCtxt m a, RMonadCtxt m b) => m a -> (a -> m b) -> m b
instance RMonad [] where
type RMonadCtxt [] a = ()
returnR x = [x]
bindR = flip concatMap
instance RMonad S.Set where
type RMonadCtxt S.Set a = Ord a
returnR x = S.singleton x
bindR mx fxmy = S.fromList [y | x <- S.toList mx, y <- S.toList (fxmy x)]
main = do
print $ (returnR 1 ++ returnR 2) `bindR`
(\x -> returnR (x + 1) ++ returnR (x + 2))
print $ (returnR 1 `S.union` returnR 2) `bindR`
(\x -> returnR (x + 1) `S.union` returnR (x + 2))
|
olsner/ghc
|
testsuite/tests/typecheck/should_run/tcrun044.hs
|
bsd-3-clause
| 806 | 0 | 13 | 235 | 370 | 194 | 176 | 20 | 1 |
module Imp10 where
import {-# SOURCE #-} Imp10Aux
|
siddhanathan/ghc
|
testsuite/tests/rename/should_compile/rn009.hs
|
bsd-3-clause
| 50 | 0 | 3 | 8 | 8 | 6 | 2 | 2 | 0 |
module Euler.Problem010Test (suite) where
import Test.Tasty (testGroup, TestTree)
import Test.Tasty.HUnit
import Euler.Problem010
suite :: TestTree
suite = testGroup "Problem010"
[ testCase "ceiling of 10" test10
]
test10 :: Assertion
test10 = 17 @=? solution 10
|
whittle/euler
|
test/Euler/Problem010Test.hs
|
mit
| 303 | 0 | 7 | 75 | 75 | 43 | 32 | 9 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
module Bio.Data.Bed.Types
( BEDLike(..)
, BEDConvert(..)
, BED(..)
, BED3(..)
, BEDGraph(..)
, bdgValue
, NarrowPeak(..)
, npSignal
, npPvalue
, npQvalue
, npPeak
, BroadPeak(..)
, bpSignal
, bpPvalue
, bpQvalue
, BEDExt(..)
, _bed
, _data
, BEDTree
, Sorted(..)
) where
import Lens.Micro
import Lens.Micro.TH (makeLensesFor)
import qualified Data.ByteString.Char8 as B
import Data.ByteString.Lex.Integral (packDecimal)
import Data.Double.Conversion.ByteString (toShortest)
import qualified Data.HashMap.Strict as M
import qualified Data.IntervalMap.Strict as IM
import Data.Maybe (fromJust, fromMaybe)
import GHC.Generics (Generic)
import Control.DeepSeq (NFData)
import Bio.Utils.Misc (readDouble, readInt)
readDoubleNonnegative :: B.ByteString -> Maybe Double
readDoubleNonnegative x | v < 0 = Nothing
| otherwise = Just v
where
v = readDouble x
{-# INLINE readDoubleNonnegative #-}
readIntNonnegative :: B.ByteString -> Maybe Int
readIntNonnegative x | v < 0 = Nothing
| otherwise = Just v
where
v = readInt x
{-# INLINE readIntNonnegative #-}
-- | A class representing BED-like data, e.g., BED3, BED6 and BED12. BED format
-- uses 0-based index (see documentation).
class BEDLike b where
-- | Field lens
chrom :: Lens' b B.ByteString
chromStart :: Lens' b Int
chromEnd :: Lens' b Int
name :: Lens' b (Maybe B.ByteString)
score :: Lens' b (Maybe Int)
strand :: Lens' b (Maybe Bool)
-- | Return the size of a bed region.
size :: b -> Int
size bed = bed^.chromEnd - bed^.chromStart
{-# INLINE size #-}
{-# MINIMAL chrom, chromStart, chromEnd, name, score, strand #-}
class BEDLike b => BEDConvert b where
-- | Construct bed record from chromsomoe, start location and end location
asBed :: B.ByteString -> Int -> Int -> b
-- | Convert bytestring to bed format
fromLine :: B.ByteString -> b
-- | Convert bed to bytestring
toLine :: b -> B.ByteString
convert :: BEDLike b' => b' -> b
convert bed = asBed (bed^.chrom) (bed^.chromStart) (bed^.chromEnd)
{-# INLINE convert #-}
{-# MINIMAL asBed, fromLine, toLine #-}
-- * BED6 format
-- | BED6 format, as described in http://genome.ucsc.edu/FAQ/FAQformat.html#format1.7
data BED = BED
{ _bed_chrom :: B.ByteString
, _bed_chromStart :: Int
, _bed_chromEnd :: Int
, _bed_name :: Maybe B.ByteString
, _bed_score :: Maybe Int
, _bed_strand :: Maybe Bool -- ^ True: "+", False: "-"
} deriving (Eq, Show, Read, Generic, NFData)
instance Ord BED where
compare (BED x1 x2 x3 x4 x5 x6) (BED y1 y2 y3 y4 y5 y6) =
compare (x1,x2,x3,x4,x5,x6) (y1,y2,y3,y4,y5,y6)
instance BEDLike BED where
chrom = lens _bed_chrom (\bed x -> bed { _bed_chrom = x })
chromStart = lens _bed_chromStart (\bed x -> bed { _bed_chromStart = x })
chromEnd = lens _bed_chromEnd (\bed x -> bed { _bed_chromEnd = x })
name = lens _bed_name (\bed x -> bed { _bed_name = x })
score = lens _bed_score (\bed x -> bed { _bed_score = x })
strand = lens _bed_strand (\bed x -> bed { _bed_strand = x })
instance BEDConvert BED where
asBed chr s e = BED chr s e Nothing Nothing Nothing
fromLine l = f $ take 6 $ B.split '\t' l
where
f [f1,f2,f3,f4,f5,f6] = BED f1 (readInt f2) (readInt f3) (getName f4)
(getScore f5) (getStrand f6)
f [f1,f2,f3,f4,f5] = BED f1 (readInt f2) (readInt f3) (getName f4)
(getScore f5) Nothing
f [f1,f2,f3,f4] = BED f1 (readInt f2) (readInt f3) (getName f4)
Nothing Nothing
f [f1,f2,f3] = asBed f1 (readInt f2) (readInt f3)
f _ = error "Read BED fail: Not enough fields!"
getName x | x == "." = Nothing
| otherwise = Just x
getScore x | x == "." = Nothing
| s >= 0 = Just s
| otherwise = error "Read BED fail: score must be greater than 0"
where
s = readInt x
getStrand str | str == "-" = Just False
| str == "+" = Just True
| otherwise = Nothing
{-# INLINE fromLine #-}
toLine (BED f1 f2 f3 f4 f5 f6) = B.intercalate "\t"
[ f1, fromJust $ packDecimal f2, fromJust $ packDecimal f3
, fromMaybe "." f4, score', strand' ]
where
strand' | f6 == Just True = "+"
| f6 == Just False = "-"
| otherwise = "."
score' = case f5 of
Just x -> fromJust $ packDecimal x
_ -> "."
{-# INLINE toLine #-}
convert bed = BED (bed^.chrom) (bed^.chromStart) (bed^.chromEnd) (bed^.name)
(bed^.score) (bed^.strand)
-- | BED3 format
data BED3 = BED3
{ _bed3_chrom :: B.ByteString
, _bed3_chrom_start :: Int
, _bed3_chrom_end :: Int
} deriving (Eq, Show, Read, Generic, NFData)
instance Ord BED3 where
compare (BED3 x1 x2 x3) (BED3 y1 y2 y3) = compare (x1,x2,x3) (y1,y2,y3)
instance BEDLike BED3 where
chrom = lens _bed3_chrom (\bed x -> bed { _bed3_chrom = x })
chromStart = lens _bed3_chrom_start (\bed x -> bed { _bed3_chrom_start = x })
chromEnd = lens _bed3_chrom_end (\bed x -> bed { _bed3_chrom_end = x })
name = lens (const Nothing) (\bed _ -> bed)
score = lens (const Nothing) (\bed _ -> bed)
strand = lens (const Nothing) (\bed _ -> bed)
instance BEDConvert BED3 where
asBed = BED3
fromLine l = case B.split '\t' l of
(a:b:c:_) -> BED3 a (readInt b) $ readInt c
_ -> error "Read BED fail: Incorrect number of fields"
{-# INLINE fromLine #-}
toLine (BED3 a b c) = B.intercalate "\t"
[a, fromJust $ packDecimal b, fromJust $ packDecimal c]
{-# INLINE toLine #-}
-- | Bedgraph format.
data BEDGraph = BEDGraph
{ _bdg_chrom :: B.ByteString
, _bdg_chrom_start :: Int
, _bdg_chrom_end :: Int
, _bdg_value :: Double
} deriving (Eq, Show, Read, Generic, NFData)
makeLensesFor [("_bdg_value", "bdgValue")] ''BEDGraph
instance Ord BEDGraph where
compare (BEDGraph x1 x2 x3 x4) (BEDGraph y1 y2 y3 y4) =
compare (x1,x2,x3,x4) (y1,y2,y3,y4)
instance BEDLike BEDGraph where
chrom = lens _bdg_chrom (\bed x -> bed { _bdg_chrom = x })
chromStart = lens _bdg_chrom_start (\bed x -> bed { _bdg_chrom_start = x })
chromEnd = lens _bdg_chrom_end (\bed x -> bed { _bdg_chrom_end = x })
name = lens (const Nothing) (\bed _ -> bed)
score = lens (const Nothing) (\bed _ -> bed)
strand = lens (const Nothing) (\bed _ -> bed)
instance BEDConvert BEDGraph where
asBed a b c = BEDGraph a b c 0
{-# INLINE asBed #-}
fromLine l = case B.split '\t' l of
(a:b:c:d:_) -> BEDGraph a (readInt b) (readInt c) $ readDouble d
_ -> error "Read BEDGraph fail: Incorrect number of fields"
{-# INLINE fromLine #-}
toLine (BEDGraph a b c d) = B.intercalate "\t"
[a, fromJust $ packDecimal b, fromJust $ packDecimal c, toShortest d]
{-# INLINE toLine #-}
-- | ENCODE narrowPeak format: https://genome.ucsc.edu/FAQ/FAQformat.html#format12
data NarrowPeak = NarrowPeak
{ _npChrom :: B.ByteString
, _npStart :: Int
, _npEnd :: Int
, _npName :: Maybe B.ByteString
, _npScore :: Int
, _npStrand :: Maybe Bool
, _npSignal :: Double
, _npPvalue :: Maybe Double
, _npQvalue :: Maybe Double
, _npPeak :: Maybe Int
} deriving (Eq, Show, Read, Generic, NFData)
makeLensesFor [ ("_npSignal", "npSignal")
, ("_npPvalue", "npPvalue")
, ("_npQvalue", "npQvalue")
, ("_npPeak", "npPeak")
] ''NarrowPeak
instance BEDLike NarrowPeak where
chrom = lens _npChrom (\bed x -> bed { _npChrom = x })
chromStart = lens _npStart (\bed x -> bed { _npStart = x })
chromEnd = lens _npEnd (\bed x -> bed { _npEnd = x })
name = lens _npName (\bed x -> bed { _npName = x })
score = lens (Just . _npScore) (\bed x -> bed { _npScore = fromJust x })
strand = lens _npStrand (\bed x -> bed { _npStrand = x })
instance BEDConvert NarrowPeak where
asBed chr s e = NarrowPeak chr s e Nothing 0 Nothing 0 Nothing Nothing Nothing
fromLine = go . B.split '\t'
where
go [a,b,c] = convert $ BED3 a (readInt b) $ readInt c
go (a:b:c:d:e:f:g:h:i:j:_) = NarrowPeak a (readInt b) (readInt c)
(if d == "." then Nothing else Just d)
(readInt e)
(if f == "." then Nothing else if f == "+" then Just True else Just False)
(readDouble g)
(readDoubleNonnegative h)
(readDoubleNonnegative i)
(readIntNonnegative j)
go x = error $ "Cannot parse line: " <> show x
{-# INLINE fromLine #-}
toLine (NarrowPeak a b c d e f g h i j) = B.intercalate "\t"
[ a, fromJust $ packDecimal b, fromJust $ packDecimal c, fromMaybe "." d
, fromJust $ packDecimal e
, case f of
Nothing -> "."
Just True -> "+"
_ -> "-"
, toShortest g, fromMaybe "-1" $ fmap toShortest h
, fromMaybe "-1" $ fmap toShortest i
, fromMaybe "-1" $ fmap (fromJust . packDecimal) j
]
{-# INLINE toLine #-}
convert bed = NarrowPeak (bed^.chrom) (bed^.chromStart) (bed^.chromEnd) (bed^.name)
(fromMaybe 0 $ bed^.score) (bed^.strand) 0 Nothing Nothing Nothing
-- | ENCODE broadPeak format: https://genome.ucsc.edu/FAQ/FAQformat.html#format13
data BroadPeak = BroadPeak
{ _bpChrom :: B.ByteString
, _bpStart :: Int
, _bpEnd :: Int
, _bpName :: Maybe B.ByteString
, _bpScore :: Int
, _bpStrand :: Maybe Bool
, _bpSignal :: Double
, _bpPvalue :: Maybe Double
, _bpQvalue :: Maybe Double
} deriving (Eq, Show, Read, Generic, NFData)
makeLensesFor [ ("_bpSignal", "bpSignal")
, ("_bpPvalue", "bpPvalue")
, ("_bpQvalue", "bpQvalue")
] ''BroadPeak
instance BEDLike BroadPeak where
chrom = lens _bpChrom (\bed x -> bed { _bpChrom = x })
chromStart = lens _bpStart (\bed x -> bed { _bpStart = x })
chromEnd = lens _bpEnd (\bed x -> bed { _bpEnd = x })
name = lens _bpName (\bed x -> bed { _bpName = x })
score = lens (Just . _bpScore) (\bed x -> bed { _bpScore = fromJust x })
strand = lens _bpStrand (\bed x -> bed { _bpStrand = x })
instance BEDConvert BroadPeak where
asBed chr s e = BroadPeak chr s e Nothing 0 Nothing 0 Nothing Nothing
fromLine l = BroadPeak a (readInt b) (readInt c)
(if d == "." then Nothing else Just d)
(readInt e)
(if f == "." then Nothing else if f == "+" then Just True else Just False)
(readDouble g)
(readDoubleNonnegative h)
(readDoubleNonnegative i)
where
(a:b:c:d:e:f:g:h:i:_) = B.split '\t' l
{-# INLINE fromLine #-}
toLine (BroadPeak a b c d e f g h i) = B.intercalate "\t"
[ a, fromJust $ packDecimal b, fromJust $ packDecimal c, fromMaybe "." d
, fromJust $ packDecimal e
, case f of
Nothing -> "."
Just True -> "+"
_ -> "-"
, toShortest g, fromMaybe "-1" $ fmap toShortest h
, fromMaybe "-1" $ fmap toShortest i
]
{-# INLINE toLine #-}
convert bed = BroadPeak (bed^.chrom) (bed^.chromStart) (bed^.chromEnd) (bed^.name)
(fromMaybe 0 $ bed^.score) (bed^.strand) 0 Nothing Nothing
data BEDExt bed a = BEDExt
{ _ext_bed :: bed
, _ext_data :: a
} deriving (Eq, Show, Read, Generic, NFData)
makeLensesFor [("_ext_bed", "_bed"), ("_ext_data", "_data")] ''BEDExt
instance BEDLike bed => BEDLike (BEDExt bed a) where
chrom = _bed . chrom
chromStart = _bed . chromStart
chromEnd = _bed . chromEnd
name = _bed . name
score = _bed . score
strand = _bed . strand
instance (Read a, Show a, BEDConvert bed) => BEDConvert (BEDExt bed a) where
asBed _ _ _ = error "Unable to transform arbitrary record to BEDExt"
fromLine l = let (a, b) = B.breakEnd (=='\t') l
in BEDExt (fromLine $ B.init a) $ read $ B.unpack b
{-# INLINE fromLine #-}
toLine (BEDExt bed a) = toLine bed <> "\t" <> B.pack (show a)
{-# INLINE toLine #-}
type BEDTree a = M.HashMap B.ByteString (IM.IntervalMap Int a)
-- | a type to imply that underlying data structure is sorted
newtype Sorted b = Sorted {fromSorted :: b} deriving (Show, Read, Eq)
|
kaizhang/bioinformatics-toolkit
|
bioinformatics-toolkit/src/Bio/Data/Bed/Types.hs
|
mit
| 12,918 | 0 | 19 | 3,810 | 4,441 | 2,394 | 2,047 | 283 | 1 |
{-# htermination (ord :: Char -> MyInt) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Char = Char MyInt ;
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
primCharToInt :: Char -> MyInt;
primCharToInt (Char x) = x;
fromEnumChar :: Char -> MyInt
fromEnumChar = primCharToInt;
ord :: Char -> MyInt;
ord = fromEnumChar;
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/basic_haskell/ord_1.hs
|
mit
| 404 | 0 | 8 | 95 | 131 | 78 | 53 | 12 | 1 |
-- Haskell version of bst.ps with `seq` to try to improve performance
data Bst = Mt | Node Bst Int Bst
type Ints = [Int]
list_bst :: Ints -> Bst
list_bst xs = list_bst_acc xs Mt
list_bst_acc :: Ints -> Bst -> Bst
list_bst_acc xs t0 =
case xs of
(x:xs1) ->
let t1 = bst_insert x t0
in t1 `seq` list_bst_acc xs1 t1
[] -> t0
bst_insert :: Int -> Bst -> Bst
bst_insert x t0 =
case t0 of
Mt -> Node Mt x Mt
(Node l n r) ->
if x <= n then
let t1 = bst_insert x l
in t1 `seq` Node t1 n r
else
let t1 = bst_insert x r
in t1 `seq` Node l n t1
bst_size :: Bst -> Int
bst_size t =
case t of
Mt -> 0
(Node l n r) -> 1 + (bst_size l) + (bst_size r)
tst = bst_size (list_bst [1..10])
main = do print (bst_size (list_bst [1..30000]))
-- C;ghc -O3 hsbst.hs ; time ./hsbst
-- [1 of 1] Compiling Main ( hsbst.hs, hsbst.o )
-- Linking hsbst ...
-- 10000
--
-- real 0m11.908s
-- user 0m11.855s
-- sys 0m0.028s
-- C;ghc -O3 hsbst.hs ; time ./hsbst
-- [1 of 1] Compiling Main ( hsbst.hs, hsbst.o )
-- Linking hsbst ...
-- 30000
--
-- real 3m50.300s
-- user 3m49.509s
-- sys 0m0.280s
|
lee-naish/Pawns
|
bench/hssbst.hs
|
mit
| 1,284 | 0 | 13 | 451 | 376 | 200 | 176 | 28 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Stockfighter
import Stockfighter.UI
main :: IO ()
main = runStockfighter "API_KEY" (withLevel "first_steps" startBlotter)
|
cnr/stockfighter-hs
|
app/Main.hs
|
mit
| 185 | 0 | 7 | 25 | 41 | 23 | 18 | 6 | 1 |
-- sum of all the primes less than two million
module Main where
import Data.List
-- utility functions
slice :: (Int,Int) -> [b] -> [b]
slice (a,b) list = map (list !!) [a..b]
fstTrue :: (a -> Bool) -> [a] -> a
fstTrue test list = head $ filter test list
safeElemIndex :: Eq a => a -> [a] -> Int
safeElemIndex item list = head $ elemIndices item list -- head is still prone to errors... just avoiding monads for now
ixFstTrue :: Eq a => (a -> Bool) -> [a] -> Int
ixFstTrue test list = safeElemIndex (fstTrue test list) list
stop :: Eq a => (a -> Bool) -> [a] -> [a]
stop test list = slice (0, ixFstTrue test list - 1) list
-- the list of primes is the list of numbers that are divisible by no prime less than them
-- the first prime is two
-- the next prime is the first number greater than two that is not divisible by two
-- the next prime is the first number greater than that number that is divisible by neither two nor that number
-- and so on
primes 0 = 2
primes 1 = fstTrue prime $ slice (0,0) primes
primes 2 = fstTrue prime $ slice (0,1) primes
divBy :: Integral a => a -> a -> Bool
n `divBy` d = gcd n d == n
candidates :: Integral a => a -> [a]
candidates n = [2..(maxCand n)]
maxCand :: Integral a => a -> a
maxCand = floor . sqrt . fromIntegral
prime' :: Integral a => a -> Bool
prime' n = not $ any (n `divBy`) $ candidates n
primes' :: Integral a => [a]
primes' = filter prime' [2..]
prime :: Integral a => a -> Bool
prime n = not $ any (n `divBy`) $ stop (> maxCand n) primes'
primes :: Integral a => [a]
primes = filter prime [2..]
-- work
list :: Integral a => [a]
list = stop (> 2000000) primes
result :: Integral a => a
result = sum list
main :: IO ()
main = print result
|
ron-wolf/haskeuler
|
src/10.hs
|
mit
| 1,717 | 0 | 8 | 383 | 662 | 352 | 310 | 35 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BangPatterns #-}
module Statistics.Correlation.Spearman
( spearman
, spearmanMatrix
) where
import Data.Ord
import qualified Data.Vector.Unboxed as U
import Data.Vector.Generic ((!))
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as M
import qualified Data.Matrix.Unboxed as MU
import qualified Data.Matrix.Generic as MG
import qualified Data.Matrix.Symmetric as MS
import qualified Data.Vector.Algorithms.Intro as I
import Statistics.Correlation.Pearson
-- | compute spearman correlation between two samples
spearman :: ( Ord a
, Ord b
, G.Vector v a
, G.Vector v b
, G.Vector v (a, b)
, G.Vector v Int
, G.Vector v Double
, G.Vector v (Double, Double)
, G.Vector v (Int, a)
, G.Vector v (Int, b)
)
=> v (a, b)
-> Double
spearman xy
= pearson
$ G.zip (rankUnsorted x) (rankUnsorted y)
where
(x, y) = G.unzip xy
{-# INLINE spearman #-}
spearmanMatrix :: ( MG.Matrix m v Double
, G.Vector v (Int, Double)
, G.Vector v Int
, G.Vector v (Double, Double)
)
=> m v Double -> MS.SymMatrix U.Vector Double
spearmanMatrix mat = pearsonMatrix mat'
where
mat' :: MU.Matrix Double
mat' = MG.fromRows $ map (rankUnsorted . G.convert) $ MG.toRows mat
-- Private data type for unfolding
data Rank v a = Rank {
rankCnt :: {-# UNPACK #-} !Int -- Number of ranks to return
, rankVal :: {-# UNPACK #-} !Double -- Rank to return
, rankNum :: {-# UNPACK #-} !Double -- Current rank
, rankVec :: v a -- Remaining vector
}
-- | Calculate rank of every element of sample. In case of ties ranks
-- are averaged. Sample should be already sorted in ascending order.
--
-- >>> rank (==) (fromList [10,20,30::Int])
-- > fromList [1.0,2.0,3.0]
--
-- >>> rank (==) (fromList [10,10,10,30::Int])
-- > fromList [2.0,2.0,2.0,4.0]
rank :: (G.Vector v a, G.Vector v Double)
=> (a -> a -> Bool) -- ^ Equivalence relation
-> v a -- ^ Vector to rank
-> v Double
rank eq vec = G.unfoldr go (Rank 0 (-1) 1 vec)
where
go (Rank 0 _ r v)
| G.null v = Nothing
| otherwise =
case G.length h of
1 -> Just (r, Rank 0 0 (r+1) rest)
n -> go Rank { rankCnt = n
, rankVal = 0.5 * (r*2 + fromIntegral (n-1))
, rankNum = r + fromIntegral n
, rankVec = rest
}
where
(h,rest) = G.span (eq $ G.head v) v
go (Rank n val r v) = Just (val, Rank (n-1) val r v)
{-# INLINE rank #-}
-- | Compute rank of every element of vector. Unlike rank it doesn't
-- require sample to be sorted.
rankUnsorted :: ( Ord a
, G.Vector v a
, G.Vector v Int
, G.Vector v Double
, G.Vector v (Int, a)
)
=> v a
-> v Double
rankUnsorted xs = G.create $ do
-- Put ranks into their original positions
-- NOTE: backpermute will do wrong thing
vec <- M.new n
for 0 n $ \i ->
M.unsafeWrite vec (index ! i) (ranks ! i)
return vec
where
n = G.length xs
-- Calculate ranks for sorted array
ranks = rank (==) sorted
-- Sort vector and retain original indices of elements
(index, sorted)
= G.unzip
$ G.modify (I.sortBy (comparing snd))
$ G.zip (G.enumFromTo 0 (G.length xs - 1)) xs
{-# INLINE rankUnsorted #-}
-- | Simple for loop. Counts from /start/ to /end/-1.
for :: Monad m => Int -> Int -> (Int -> m ()) -> m ()
for n0 !n f = loop n0
where
loop i | i == n = return ()
| otherwise = f i >> loop (i+1)
{-# INLINE for #-}
|
kaizhang/statistics-correlation
|
Statistics/Correlation/Spearman.hs
|
mit
| 3,992 | 0 | 19 | 1,377 | 1,157 | 629 | 528 | 86 | 3 |
module Main where
import Config
main :: IO ()
main = do
putStrLn "InstaHuskee 🐕 "
showBogusSettings :: IO ()
showBogusSettings = do
code <- lookupSetting "IG_CODE" "default-code"
secret <- lookupSetting "IG_SECRET" "default-secret"
clientId <- lookupSetting "IG_CLIENT_ID" "default-client-id"
redirectUri <- lookupSetting "IG_REDIRECT_URI" "https://example.com/auth/ig"
print $ "Client ID: " ++ clientId
print $ "Secret: " ++ secret
print $ "Code: " ++ code
print $ "Redirect URI: : " ++ redirectUri
return ()
|
dzotokan/instahuskee
|
app/Main.hs
|
mit
| 546 | 0 | 8 | 105 | 143 | 66 | 77 | 16 | 1 |
-----------------------------------------------------------------------------
--
-- Module : Language.PureScript.CoreFn.Literals
-- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
-- License : MIT
--
-- Maintainer : Phil Freeman <[email protected]>, Gary Burgess <[email protected]>
-- Stability : experimental
-- Portability :
--
-- | The core functional representation for literal values.
--
-----------------------------------------------------------------------------
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
module Language.PureScript.CoreFn.Literals where
import qualified Data.Data as D
-- |
-- Data type for literal values. Parameterised so it can be used for Exprs and
-- Binders.
--
data Literal a
-- |
-- A numeric literal
--
= NumericLiteral (Either Integer Double)
-- |
-- A string literal
--
| StringLiteral String
-- |
-- A character literal
--
| CharLiteral Char
-- |
-- A boolean literal
--
| BooleanLiteral Bool
-- |
-- An array literal
--
| ArrayLiteral [a]
-- |
-- An object literal
--
| ObjectLiteral [(String, a)] deriving (Show, Read, D.Data, D.Typeable, Functor)
|
michaelficarra/purescript
|
src/Language/PureScript/CoreFn/Literals.hs
|
mit
| 1,224 | 0 | 8 | 232 | 135 | 96 | 39 | 11 | 0 |
import qualified Data.Map as M
type PersonName = String
type PhoneNumber = String
type BillingAddress = String
data MobileCarrier = Honest_Bobs_Phone_Network
| Morrisas_Marvelous_Mobiles
| Peters_Plutocratic_Phones
deriving (Eq, Ord)
findCarrierBillingAddress :: PersonName
-> M.Map PersonName PhoneNumber
-> M.Map PhoneNumber MobileCarrier
-> M.Map MobileCarrier BillingAddress
-> Maybe BillingAddress
|
zhangjiji/real-world-haskell
|
ch14/Carrier.hs
|
mit
| 579 | 0 | 10 | 222 | 96 | 53 | 43 | 13 | 0 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Text
import Data.Aeson
import Control.Monad
import Control.Applicative
data Neighbor = Neighbor
{ ip :: Text
, port :: Int
, revision :: Int
} deriving (Eq, Show)
instance FromJSON Neighbor where
parseJSON (Object v) = Neighbor <$>
v .: "ip" <*>
v .: "port" <*>
v .: "revision"
parseJSON _ = mzero
data NeighborList = NeighborList
{ list :: [Neighbor]
} deriving (Eq, Show)
instance FromJSON NeighborList where
parseJSON (Object v) = NeighborList <$>
v .: "list"
main = do
-- let a = decode "{\"ip\":\"127.0.0.1\",\"port\":12, \"revision\":1}" :: Maybe Neighbor
let a = decode "{\"list\":[{\"ip\":\"127.0.0.1\",\"port\":12,\"revision\":1},{\"ip\":\"127.0.0.2\",\"port\":13,\"revision\":1},{\"ip\":\"127.0.0.3\",\"port\":14,\"revision\":1}]}" :: Maybe NeighborList
print a
|
adizere/nifty-tree
|
playground/aeson.hs
|
mit
| 988 | 0 | 11 | 274 | 203 | 109 | 94 | 25 | 1 |
module Move where
import Text.ParserCombinators.Parsec
import Data.Char (toUpper)
import Data.Maybe (fromJust)
import System.IO
data PlayerResponse = Position Coord | MetaResponse Option | Invalid
data Coord = Coord (Int, Int) deriving (Eq, Ord)
data Option = Pass | Exit | Save deriving Show
data Player = White | Black deriving Eq
instance Show Player where
show White = "O"
show Black = "X"
instance Show PlayerResponse where
show (Position c) = show c
show (MetaResponse o) = show o
show Invalid = "Invalid"
instance Show Coord where
show (Coord (x,y)) = numberToLetter x : show (y+1)
letterToNumber :: Char -> Int
letterToNumber c = fromJust $ lookup (toUpper c) (zip ['A'..'Z'] [0..])
numberToLetter :: Int -> Char
numberToLetter = (['A' .. 'Z'] !!)
int :: Parser Int
int = fmap read $ many1 digit
coord :: Parser PlayerResponse
coord = do
x <- fmap letterToNumber $ oneOf $ ['A'..'Z'] ++ ['a'..'z']
spaces
y <- int
return $ Position $ Coord (x,y-1)
pass :: Parser Option
pass = choice [string "pass", string "Pass"] >> return Pass
exit :: Parser Option
exit = choice [string "exit", string "Exit"] >> return Exit
save :: Parser Option
save = choice [string "save", string "Save"] >> return Save
metaCommand :: Parser PlayerResponse
metaCommand = fmap MetaResponse $ choice [pass,exit,save]
move :: Parser PlayerResponse
move = try coord <|> metaCommand
prompt :: String -> IO String
prompt s = do
putStr s
hFlush stdout
getLine
-- | Repeatedly prompts player for a game move until a valid coord or metacommand is entered
getMove :: (Player, Int) -> IO PlayerResponse
getMove str@(p, num) = do
let player = case p of
Black -> "Black"
White -> "White"
response <- prompt $ player ++ "(" ++ show num ++ "): "
case parse move "Failed to parse move" response of
-- Left _ -> putStrLn "Not a valid move." >> getMove str
Left _ -> return Invalid
Right m -> return m
|
JonHarder/haskell-go
|
Move.hs
|
gpl-2.0
| 1,940 | 0 | 12 | 397 | 718 | 369 | 349 | 54 | 3 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE TemplateHaskell #-}
module Reg where
import Text.Show.Functions
import qualified Data.List as L
data RegTerm = Is Char | OneOf [Char] | NoneOf [Char] | Any deriving (Eq)
data RegExp = Or [Either RegTerm RegExp] |
And [Either RegTerm RegExp] |
Star (Either RegTerm RegExp) |
Lone (Either RegTerm RegExp) |
Some (Either RegTerm RegExp) deriving (Eq)
type Reg = (Either RegTerm RegExp)
star :: Reg -> Reg
star a = (Right (Star a))
lone :: Reg -> Reg
lone a = (Right (Lone a))
some :: Reg -> Reg
some a = (Right (Some a))
and :: [Reg] -> Reg
and rs = (Right (And rs))
(&&) :: [Reg] -> Reg
(&&) = Reg.and
or :: [Reg] -> Reg
or rs = (Right (Or rs))
(||) :: [Reg] -> Reg
(||) = Reg.or
get :: Char -> Reg
get a = (Left (Is a))
gets :: [Char] -> Reg
gets xs = (Right (And (map get xs)))
oneOf :: [Char] -> Reg
oneOf xs = (Left (OneOf xs))
noneOf :: [Char] -> Reg
noneOf xs = (Left (NoneOf xs))
any :: Reg
any = (Left Any)
alphabetCls :: Reg
alphabetCls = (Left (OneOf ['a'..'z']))
digitCls :: Reg
digitCls = (Left (OneOf ['0'..'9']))
alnumCls :: Reg
alnumCls = (Left (OneOf (['a'..'z']++['0'..'9'])))
instance Show RegTerm where
show (Is x) = [x]
show (OneOf xs) = "[" ++ xs ++ "]"
show (NoneOf xs) = "[^" ++ xs ++ "]"
show Any = "."
instance Show RegExp where
show (Or xs) = L.intercalate "+" (map (\x -> (show x)) xs)
show (And xs) = L.intercalate "" (map (\x -> (show x)) xs)
show (Star a) = (show a) ++ "*"
show (Lone a) = (show a) ++ "?"
show (Some a) = (show a) ++ "+"
instance Show Reg where
show (Left a) = show a
show (Right a) = "(" ++ show a ++ ")"
|
pocket7878/min-tokenizer
|
src/Reg.hs
|
gpl-3.0
| 1,809 | 0 | 12 | 461 | 879 | 474 | 405 | 58 | 1 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings,FlexibleContexts #-}
import Hakyll
import Data.Monoid ((<>), mconcat, mappend)
import Data.List (isInfixOf)
import System.FilePath.Posix (takeBaseName,takeDirectory,(</>),splitFileName)
import Text.Pandoc
--------------------------------------------------------------------------------
main :: IO ()
main = hakyllWith config $ do
tags <- buildTags "posts/*" (fromCapture "tags/*")
match (fromList staticFiles) $ do
route idRoute
compile copyFileCompiler
match "img/**" $ do
route idRoute
compile copyFileCompiler
match "font-awesome-4.1.0/**" $ do
route idRoute
compile copyFileCompiler
match "fonts/*" $ do
route idRoute
compile copyFileCompiler
match "css/**" $ do
route idRoute
compile copyFileCompiler
match "js/**" $ do
route idRoute
compile copyFileCompiler
match "notes/*" $ do
route noteRoute
compile $ pandocCompilerWith defaultHakyllReaderOptions pandocTocWriter
>>= loadAndApplyTemplate "templates/post.html" defaultContext
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
>>= removeIndexHtml
match "index.html" $ do
route idRoute
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/homepage.html" defaultContext
>>= loadAndApplyTemplate "templates/default.html" defaultContext
match "posts/*" $ do
route niceDateRoute
compile $ pandocCompiler
>>= saveSnapshot "content"
>>= loadAndApplyTemplate "templates/post.html" (postCtx tags)
>>= loadAndApplyTemplate "templates/default.html" (postCtx tags)
>>= relativizeUrls
>>= removeIndexHtml
create ["archive.html"] $ do
route niceRoute
compile $ do
let archiveCtx =
field "posts" (\_ -> postList tags recentFirst) `mappend`
constField "title" "Archive" `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/archive.html" archiveCtx
>>= loadAndApplyTemplate "templates/default.html" archiveCtx
>>= relativizeUrls
>>= removeIndexHtml
create ["notes.html"] $ do
route niceRoute
compile $ do
let noteCtx =
field "posts" (const noteList) `mappend`
constField "title" "Notes" `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/notes.html" noteCtx
>>= loadAndApplyTemplate "templates/default.html" noteCtx
>>= relativizeUrls
>>= removeIndexHtml
create ["blog/feed.xml"] $ do
route idRoute
compile $ do
loadAllSnapshots "posts/*" "content"
>>= fmap (take 10) . recentFirst
>>= renderAtom (feedConfiguration "All posts") feedCtx
match "blog.html" $ do
route niceRoute
compile $ do
let indexCtx = field "posts" $ \_ ->
completePostList tags $ fmap (take 5) . recentFirst
getResourceBody
>>= applyAsTemplate indexCtx
>>= loadAndApplyTemplate "templates/blog.html" (postCtx tags)
>>= loadAndApplyTemplate "templates/default.html" (postCtx tags)
>>= relativizeUrls
>>= removeIndexHtml
tagsRules tags $ \tag pattern -> do
let title = "Posts tagged " ++ tag
route niceRoute
compile $ do
posts <- recentFirst =<< loadAll pattern
let ctx = constField "title" title <>
listField "posts" (postCtx tags) (return posts) <>
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/tag.html" ctx
>>= loadAndApplyTemplate "templates/default.html" ctx
>>= relativizeUrls
>>= removeIndexHtml
match "templates/*" $ compile templateCompiler
where pandocTocWriter = defaultHakyllWriterOptions { writerTableOfContents = True
, writerTemplate = "$if(toc)$ $toc$ $endif$\n$body$"
, writerStandalone = True }
staticFiles = ["CNAME", "humans.txt", "robots.txt", "favicon.png", "favicon.ico"]
--------------------------------------------------------------------------------
postCtx :: Tags -> Context String
postCtx tags = mconcat
[ dateField "date" "%B %e, %Y"
, tagsField "tags" tags
, defaultContext
]
--------------------------------------------------------------------------------
postList :: Tags -> ([Item String] -> Compiler [Item String]) -> Compiler String
postList tags sortFilter = do
posts <- sortFilter =<< loadAll "posts/*"
itemTpl <- loadBody "templates/post-item.html"
applyTemplateList itemTpl (postCtx tags) posts
--------------------------------------------------------------------------------
noteList :: Compiler String
noteList = do
posts <- loadAll "notes/*"
itemTpl <- loadBody "templates/post-item.html"
applyTemplateList itemTpl defaultContext posts
--------------------------------------------------------------------------------
-- | Returns a list of post bodies
completePostList :: Tags -> ([Item String] -> Compiler [Item String]) -> Compiler String
completePostList tags sortFilter = do
posts <- sortFilter =<< loadAllSnapshots "posts/*" "content"
itemTpl <- loadBody "templates/post-with-link.html"
applyTemplateList itemTpl (postCtx tags) posts
--------------------------------------------------------------------------------
dateRoute :: Routes
dateRoute = gsubRoute "posts/" (const "blog/") `composeRoutes`
gsubRoute "[0-9]{4}-[0-9]{2}-[0-9]{2}-" (map replaceChars)
where
replaceChars c | c == '-' || c == '_' = '/'
| otherwise = c
--------------------------------------------------------------------------------
niceRoute :: Routes
niceRoute = customRoute createIndexRoute
where
createIndexRoute ident =
takeDirectory p </> takeBaseName p </> "index.html"
where
p = toFilePath ident
--------------------------------------------------------------------------------
-- |Turns 2012-02-01-post.html into 2012/02/01/post/index.html
niceDateRoute :: Routes
niceDateRoute = composeRoutes dateRoute niceRoute
--------------------------------------------------------------------------------
-- | Turns notes/post.html into /post/index.html
noteRoute :: Routes
noteRoute = gsubRoute "notes/" (const "") `composeRoutes` niceRoute
--------------------------------------------------------------------------------
-- |Replace an url of the form foo/bar/index.html by foo/bar
removeIndexHtml :: Item String -> Compiler (Item String)
removeIndexHtml item = return $ fmap (withUrls removeIndexStr) item
--------------------------------------------------------------------------------
-- |Removes the .html component of a URL if it is local
removeIndexStr :: String -> String
removeIndexStr url = case splitFileName url of
(dir, "index.html") | isLocal dir -> dir
| otherwise -> url
_ -> url
where
isLocal uri = not ("://" `isInfixOf` uri)
--------------------------------------------------------------------------------
-- | Feeds
feedCtx :: Context String
feedCtx = mconcat
[ bodyField "description"
, niceUrlField "url"
, defaultContext
]
niceUrlField :: String -> Context a
niceUrlField key = field key $
fmap (maybe "" toWordPressUrl) . getRoute . itemIdentifier
toWordPressUrl :: FilePath -> String
toWordPressUrl url =
replaceAll "/index.html" (const "/") (toUrl url)
feedConfiguration :: String -> FeedConfiguration
feedConfiguration title = FeedConfiguration
{ feedTitle = "Recursivity blog - " ++ title
, feedDescription = ""
, feedAuthorName = "Wille Faler"
, feedAuthorEmail = "[email protected]"
, feedRoot = "http://recursivity.com"
}
--------------------------------------------------------------------------------
-- | Deployment
config :: Configuration
config = defaultConfiguration
|
wfaler/recursivity-com
|
recursivity-site.hs
|
gpl-3.0
| 8,350 | 0 | 23 | 1,966 | 1,716 | 826 | 890 | 168 | 2 |
module WordCount where
import Data.List (sort, group)
import Data.Char (isAlphaNum, toLower)
import Data.Map (fromList)
wordCount xs =
fromList [ (head x, length x) | x <- group . sort . map (map toLower) $ words' xs]
words' :: String -> [String]
words' s =
case dropWhile (not . isAlphaNum) s of
"" -> []
s' -> w : words' s''
where (w, s'') = span isAlphaNum s'
|
ciderpunx/exercismo
|
src/WordCount.hs
|
gpl-3.0
| 397 | 0 | 13 | 101 | 174 | 92 | 82 | 12 | 2 |
-- Problem 8
-- (0.00 secs, 2,602,832 bytes)
import Data.Char (digitToInt)
import Data.List (tails, transpose)
e008 = do
n <- readFile "../res/e008.txt"
print . maximum . map product . transpose
. take 13 . tails . map digitToInt
. concat . lines $ n
|
synndicate/euler
|
solutions/e008.hs
|
gpl-3.0
| 282 | 0 | 15 | 75 | 89 | 45 | 44 | 7 | 1 |
{-# OPTIONS_GHC -F -pgmF htfpp #-}
{-
# This file is part of matrix-arbitrary. #
# #
# matrix-arbitrary is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# matrix-arbitrary 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. #
# #
# A copy of the GNU General Public License resides in the `LICENSE` #
# file distributed along with matrix-arbitrary. #
# #
# Copyright 2012, Johannes Weiß <[email protected]> #
-}
-- vim: set fileencoding=utf8 :
-- # STDLIB
import Data.List (transpose)
-- # LOCAL
import Data.Matrix
-- # HTF
import Test.Framework hiding ((><))
arbitraryShapeMatrix :: (Enum e, Num e)
=> (Int -> Int -> Matrix e -> Bool) -> Property
arbitraryShapeMatrix f =
forAll (choose (1, 100)) $ \r -> forAll (choose (1,100)) $ \c ->
let m = (r >< c) [1..]
in f r c m
prop_matrixEqualsTransTransMatrix :: Property
prop_matrixEqualsTransTransMatrix =
arbitraryShapeMatrix $ \r c m ->
m == (trans . trans) m
prop_matrixShape :: Property
prop_matrixShape =
arbitraryShapeMatrix $ \r c m ->
(r, c) == shape m
prop_matrixRows :: Property
prop_matrixRows =
arbitraryShapeMatrix $ \r c m ->
r == rows m
prop_matrixCols :: Property
prop_matrixCols =
arbitraryShapeMatrix $ \r c m ->
c == cols m
prop_matrixListsConversion :: Property
prop_matrixListsConversion =
arbitraryShapeMatrix $ \r c m ->
m == (fromLists . toLists) m
prop_matrixTranspose :: Property
prop_matrixTranspose =
arbitraryShapeMatrix $ \r c m ->
trans m == (fromLists . transpose . toLists) m
main = htfMain htf_thisModulesTests
|
weissi/matrix-arbitrary
|
test/SimpleMatrixTests.hs
|
gpl-3.0
| 2,550 | 0 | 15 | 1,001 | 386 | 210 | 176 | 35 | 1 |
{-| Module : Lexer
License : GPL
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module Helium.Parser.Lexer
( lexer, strategiesLexer
, Token, Lexeme(..)
, lexemeLength
, checkTokenStreamForClassOrInstance
, module Helium.Parser.LexerMessage
) where
import Helium.Main.Args
import Helium.Parser.LexerMonad
import Helium.Parser.LexerMessage
import Helium.Parser.LexerToken
import Helium.StaticAnalysis.Messages.StaticErrors
import Text.ParserCombinators.Parsec.Pos
import Helium.Utils.Utils(internalError, hole)
import Control.Monad(when, liftM)
import Data.Char(ord)
import Data.List(isPrefixOf)
lexer :: [Option] -> String -> [Char] -> Either LexerError ([Token], [LexerWarning])
lexer opts fileName input = runLexerMonad opts fileName (mainLexer input)
strategiesLexer :: [Option] -> String -> [Char] -> Either LexerError ([Token], [LexerWarning])
strategiesLexer opts fileName input =
case lexer opts fileName input of
Left err -> Left err
Right (tokens, warnings) -> Right (reserveStrategyNames tokens, warnings)
type Lexer = [Char] -> LexerMonad [Token]
mainLexer :: Lexer
mainLexer a =
do useTutor <- elem UseTutor `liftM` getOpts
mainLexer' useTutor a
mainLexer' :: Bool -> Lexer
mainLexer' _ [] = do
checkBracketsAtEOF
pos <- getPos
return [(incSourceLine (setSourceColumn pos 0) 1, LexEOF)]
mainLexer' _ ('-':'-':cs)
| not (nextCharSatisfy isSymbol rest) = do
incPos (2 + length minuses)
lexOneLineComment rest
where
(minuses, rest) = span (== '-') cs
mainLexer' useTutor ('{':'-':'#':' ':'M':'U':'S':'T':'U':'S':'E':' ':'#':'-':'}':cs) | useTutor =
returnToken LexMustUse 15 mainLexer cs
mainLexer' useTutor ('{':'-':'#':' ':'F':'C':cs) | useTutor = do
pos <- getPos
lexCaseFeedbackComment "" pos cs
mainLexer' useTutor ('{':'-':'#':' ':'F':cs) | useTutor = do
pos <- getPos
incPos 5
lexFeedbackComment "" pos cs
mainLexer' _ ('{':'-':cs) = do
pos <- getPos
incPos 2
lexMultiLineComment [pos] 0 cs
mainLexer' _ input@('\'':_) =
lexChar input
mainLexer' _ input@('"':_) =
lexString input
-- warn if we see something like ".2"
mainLexer' _ ('.':c:cs)
| myIsDigit c = do
pos <- getPos
lexerWarning (LooksLikeFloatNoDigits (takeWhile myIsDigit (c:cs))) pos
returnToken (LexVarSym ".") 1 mainLexer (c:cs)
mainLexer' useTutor input@(c:cs)
| myIsLower c || c == '_' = -- variable or keyword
lexName isLetter LexVar LexKeyword keywords input
| myIsSpace c = do
when (c == '\t') $ do
pos <- getPos
lexerWarning TabCharacter pos
nextPos c
mainLexer cs
| myIsUpper c = -- constructor
lexName isLetter LexCon (internalError "Lexer" "mainLexer'" "constructor") [] input
| c == ':' = -- constructor operator
lexName isSymbol LexConSym LexResConSym reservedConSyms input
| isSymbol c = -- variable operator
lexName isSymbol LexVarSym LexResVarSym (if useTutor then hole : reservedVarSyms else reservedVarSyms) input
| c `elem` "([{" = do
openBracket c
returnToken (LexSpecial c) 1 mainLexer cs
| c `elem` ")]}" = do
closeBracket c
returnToken (LexSpecial c) 1 mainLexer cs
| c `elem` specialsWithoutBrackets =
returnToken (LexSpecial c) 1 mainLexer cs
| myIsDigit c = -- number
lexIntFloat input
| otherwise = do
pos <- getPos
lexerError (UnexpectedChar c) pos
lexName :: (Char -> Bool) -> (String -> Lexeme) ->
(String -> Lexeme) -> [String] -> Lexer
lexName predicate normal reserved reserveds cs = do
let (name@(first:_), rest) = span predicate cs
lexeme = if name `elem` reserveds
then reserved name
else normal name
when ((isSymbol first || first == ':') && name `contains` "--") $ do
pos <- getPos
lexerWarning CommentOperator pos
returnToken lexeme (length name) mainLexer rest
contains :: Eq a => [a] -> [a] -> Bool
[] `contains` _ = False
xs@(_:rest) `contains` ys = ys `isPrefixOf` xs || rest `contains` ys
-----------------------------------------------------------
-- Numbers
-----------------------------------------------------------
lexIntFloat :: Lexer
lexIntFloat input = do
_ <- getPos
let (digits, rest) = span myIsDigit input
case rest of
('.':rest2@(next:_))
| myIsDigit next -> do
let (fraction, rest3) = span myIsDigit rest2
prefix = digits ++ "." ++ fraction
lexMaybeExponent prefix LexFloat rest3
| next /= '.' -> do
pos <- getPos
lexerWarning (LooksLikeFloatNoFraction digits) pos
lexMaybeExponent digits LexInt rest
_ ->
lexMaybeExponent digits LexInt rest
lexMaybeExponent :: String -> (String -> Lexeme) -> Lexer
lexMaybeExponent prefix lexemeFun input =
case input of
('e':'+':rest) ->
lexExponent (prefix ++ "e+") rest
('E':'+':rest) ->
lexExponent (prefix ++ "E+") rest
('e':'-':rest) ->
lexExponent (prefix ++ "e-") rest
('E':'-':rest) ->
lexExponent (prefix ++ "E-") rest
('e':rest) ->
lexExponent (prefix ++ "e") rest
('E':rest) ->
lexExponent (prefix ++ "E") rest
_ ->
returnToken (lexemeFun prefix) (length prefix) mainLexer input
lexExponent :: String -> Lexer
lexExponent prefix input = do
startPos <- getPos
let posAtExponent = addPos (length prefix) startPos
(exponentDigits, rest) = span myIsDigit input
if null exponentDigits then
lexerError MissingExponentDigits posAtExponent
else do
let text = prefix ++ exponentDigits
returnToken (LexFloat text) (length text) mainLexer rest
-----------------------------------------------------------
-- Characters
-----------------------------------------------------------
lexChar :: Lexer
lexChar input = do
pos <- getPos
case input of
'\'':'\\':c:'\'':cs -> -- '\n' etc
if c `elem` escapeChars then
returnToken (LexChar ['\\',c]) 4 mainLexer cs
else
lexerError IllegalEscapeInChar pos
'\'':'\'':_ -> -- ''
lexerError EmptyChar pos
'\'':c:'\'':cs -> -- 'a' '%'
if ord c >= 32 && ord c <= 126 then
returnToken (LexChar [c]) 3 mainLexer cs
else
lexerError IllegalCharInChar pos
['\''] -> -- ' at end of file
lexerError EOFInChar pos
('\'':cs) -> -- if there is a name between single quotes, we give a hint that backquotes might be meant
let (ds, es) = span (/= '\'') cs
ws = words ds
in if not (null es) && head es == '\'' && length ws == 1 && isName (head ws) then
lexerError (NonTerminatedChar (Just (head ws))) pos
else
lexerError (NonTerminatedChar Nothing) pos
_ -> internalError "Lexer" "lexChar" "unexpected characters"
lexString :: Lexer
lexString ('"':cs) =
lexStringChar "" cs
lexString _ =
internalError "Lexer" "lexString" "should start with \""
lexStringChar :: String -> Lexer
lexStringChar revSoFar input = do
startPos <- getPos
let curPos = addPos (length revSoFar + 1) startPos
case input of
[] ->
lexerError EOFInString startPos
'\\':c:cs ->
if c `elem` escapeChars then
lexStringChar (c:'\\':revSoFar) cs
else
lexerError IllegalEscapeInString curPos
'"':cs ->
returnToken (LexString (reverse revSoFar))
(length revSoFar + 2) mainLexer cs
'\n':_ ->
lexerError NewLineInString startPos
c:cs ->
if ord c >= 32 && ord c <= 126 then
lexStringChar (c:revSoFar) cs
else
lexerError IllegalCharInString curPos
nextCharSatisfy :: (Char -> Bool) -> String -> Bool
nextCharSatisfy _ [] = False
nextCharSatisfy p (c:_) = p c
returnToken :: Lexeme -> Int -> Lexer -> Lexer
returnToken lexeme width continue input = do
pos <- getPos
incPos width
let token = (pos, lexeme)
tokens <- continue input
return (token:tokens)
-----------------------------------------------------------
-- Comment
-----------------------------------------------------------
lexOneLineComment :: Lexer
lexOneLineComment input =
case input of
[] -> mainLexer []
('\n':cs) -> do
nextPos '\n'
mainLexer cs
(c:cs) -> do
nextPos c
lexOneLineComment cs
lexMultiLineComment :: [SourcePos] -> Int -> Lexer
lexMultiLineComment starts level input =
case input of
'-':'}':cs
| level == 0 -> do
incPos 2
mainLexer cs
| otherwise -> do
incPos 2
lexMultiLineComment (tail starts) (level - 1) cs
'{':'-':cs -> do
pos <- getPos
lexerWarning (NestedComment (head starts)) pos
incPos 2
lexMultiLineComment (pos:starts) (level+1) cs
c:cs -> do
nextPos c
lexMultiLineComment starts level cs
[] ->
lexerError UnterminatedComment (head starts)
-- at end-of-file show the most recently opened comment
lexFeedbackComment :: String -> SourcePos -> Lexer
lexFeedbackComment feedback start input =
case input of
'#':'-':'}':cs ->
returnToken (LexFeedback (reverse feedback))
(length feedback + 6) mainLexer cs
c:cs -> do
nextPos c
lexFeedbackComment (c:feedback) start cs
[] ->
lexerError UnterminatedComment start
lexCaseFeedbackComment :: String -> SourcePos -> Lexer
lexCaseFeedbackComment feedback start input =
case input of
'#':'-':'}':cs ->
returnToken (LexCaseFeedback (reverse feedback)) 0 mainLexer cs
c:cs ->
-- nextPos c
lexCaseFeedbackComment (c:feedback) start cs
[] ->
lexerError UnterminatedComment start
-----------------------------------------------------------
-- Utility functions
-----------------------------------------------------------
isSymbol :: Char -> Bool
isSymbol = (`elem` symbols)
isLetter :: Char -> Bool
isLetter '\'' = True
isLetter '_' = True
isLetter c = myIsAlphaNum c
-- write our own isLower.. so that we don't accept funny symbols
myIsLower :: Char -> Bool
myIsLower c = c >= 'a' && c <= 'z'
myIsUpper :: Char -> Bool
myIsUpper c = c >= 'A' && c <= 'Z'
myIsDigit :: Char -> Bool
myIsDigit c = c >= '0' && c <= '9'
myIsAlphaNum :: Char -> Bool
myIsAlphaNum c = myIsLower c || myIsUpper c || myIsDigit c
myIsSpace :: Char -> Bool
myIsSpace c = c == ' ' || c == '\n' || c == '\t' || c == '\r'
isName :: String -> Bool
isName [] = False
isName (hd:tl) = (myIsUpper hd || myIsLower hd) && all isLetter tl
-----------------------------------------------------------
-- Constants
-----------------------------------------------------------
escapeChars :: String
escapeChars = "\\nabfnrtv\"'"
symbols :: String
symbols = "!#$%&*+./<=>?@^|-~:\\"
keywords :: [String]
keywords =
[ "let", "in", "do", "where", "case", "of", "if"
, "then", "else", "data", "type", "module", "import", "hiding"
, "infix", "infixl", "infixr", "_", "deriving"
, "class", "instance", "default"
, "newtype" -- not supported
]
reservedConSyms :: [String]
reservedConSyms =
[ "::" ]
reservedVarSyms :: [String]
reservedVarSyms =
[ "=>", "->", "<-", "..", "-", "-.", "@", "=", "\\", "|", "~" ]
specialsWithoutBrackets :: String
specialsWithoutBrackets =
",`;"
reserveStrategyNames :: [Token] -> [Token]
reserveStrategyNames =
map (\token@(pos, lexeme) -> case lexeme of
LexVar s | s `elem` strategiesKeywords -> (pos, LexKeyword s)
LexVarSym s | s == "==" -> (pos, LexResVarSym s)
LexConSym s | s == ":" -> (pos, LexResConSym s)
_ -> token
)
strategiesKeywords :: [String]
strategiesKeywords = [ "phase", "constraints", "siblings" ]
checkTokenStreamForClassOrInstance :: [Token] -> Errors
checkTokenStreamForClassOrInstance tokens = concatMap f tokens
where f (pos, LexKeyword "class") = [ClassesAndInstancesNotAllowed (sourcePosToRange pos)]
f (pos, LexKeyword "instance") = [ClassesAndInstancesNotAllowed (sourcePosToRange pos)]
f _ = []
|
roberth/uu-helium
|
src/Helium/Parser/Lexer.hs
|
gpl-3.0
| 13,062 | 0 | 21 | 3,790 | 4,013 | 2,041 | 1,972 | 306 | 9 |
{-# 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.Logging.BillingAccounts.Sinks.List
-- 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)
--
-- Lists sinks.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.billingAccounts.sinks.list@.
module Network.Google.Resource.Logging.BillingAccounts.Sinks.List
(
-- * REST Resource
BillingAccountsSinksListResource
-- * Creating a Request
, billingAccountsSinksList
, BillingAccountsSinksList
-- * Request Lenses
, baslParent
, baslXgafv
, baslUploadProtocol
, baslAccessToken
, baslUploadType
, baslPageToken
, baslPageSize
, baslCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.billingAccounts.sinks.list@ method which the
-- 'BillingAccountsSinksList' request conforms to.
type BillingAccountsSinksListResource =
"v2" :>
Capture "parent" Text :>
"sinks" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListSinksResponse
-- | Lists sinks.
--
-- /See:/ 'billingAccountsSinksList' smart constructor.
data BillingAccountsSinksList =
BillingAccountsSinksList'
{ _baslParent :: !Text
, _baslXgafv :: !(Maybe Xgafv)
, _baslUploadProtocol :: !(Maybe Text)
, _baslAccessToken :: !(Maybe Text)
, _baslUploadType :: !(Maybe Text)
, _baslPageToken :: !(Maybe Text)
, _baslPageSize :: !(Maybe (Textual Int32))
, _baslCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BillingAccountsSinksList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'baslParent'
--
-- * 'baslXgafv'
--
-- * 'baslUploadProtocol'
--
-- * 'baslAccessToken'
--
-- * 'baslUploadType'
--
-- * 'baslPageToken'
--
-- * 'baslPageSize'
--
-- * 'baslCallback'
billingAccountsSinksList
:: Text -- ^ 'baslParent'
-> BillingAccountsSinksList
billingAccountsSinksList pBaslParent_ =
BillingAccountsSinksList'
{ _baslParent = pBaslParent_
, _baslXgafv = Nothing
, _baslUploadProtocol = Nothing
, _baslAccessToken = Nothing
, _baslUploadType = Nothing
, _baslPageToken = Nothing
, _baslPageSize = Nothing
, _baslCallback = Nothing
}
-- | Required. The parent resource whose sinks are to be listed:
-- \"projects\/[PROJECT_ID]\" \"organizations\/[ORGANIZATION_ID]\"
-- \"billingAccounts\/[BILLING_ACCOUNT_ID]\" \"folders\/[FOLDER_ID]\"
baslParent :: Lens' BillingAccountsSinksList Text
baslParent
= lens _baslParent (\ s a -> s{_baslParent = a})
-- | V1 error format.
baslXgafv :: Lens' BillingAccountsSinksList (Maybe Xgafv)
baslXgafv
= lens _baslXgafv (\ s a -> s{_baslXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
baslUploadProtocol :: Lens' BillingAccountsSinksList (Maybe Text)
baslUploadProtocol
= lens _baslUploadProtocol
(\ s a -> s{_baslUploadProtocol = a})
-- | OAuth access token.
baslAccessToken :: Lens' BillingAccountsSinksList (Maybe Text)
baslAccessToken
= lens _baslAccessToken
(\ s a -> s{_baslAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
baslUploadType :: Lens' BillingAccountsSinksList (Maybe Text)
baslUploadType
= lens _baslUploadType
(\ s a -> s{_baslUploadType = a})
-- | Optional. If present, then retrieve the next batch of results from the
-- preceding call to this method. pageToken must be the value of
-- nextPageToken from the previous response. The values of other method
-- parameters should be identical to those in the previous call.
baslPageToken :: Lens' BillingAccountsSinksList (Maybe Text)
baslPageToken
= lens _baslPageToken
(\ s a -> s{_baslPageToken = a})
-- | Optional. The maximum number of results to return from this request.
-- Non-positive values are ignored. The presence of nextPageToken in the
-- response indicates that more results might be available.
baslPageSize :: Lens' BillingAccountsSinksList (Maybe Int32)
baslPageSize
= lens _baslPageSize (\ s a -> s{_baslPageSize = a})
. mapping _Coerce
-- | JSONP
baslCallback :: Lens' BillingAccountsSinksList (Maybe Text)
baslCallback
= lens _baslCallback (\ s a -> s{_baslCallback = a})
instance GoogleRequest BillingAccountsSinksList where
type Rs BillingAccountsSinksList = ListSinksResponse
type Scopes BillingAccountsSinksList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read"]
requestClient BillingAccountsSinksList'{..}
= go _baslParent _baslXgafv _baslUploadProtocol
_baslAccessToken
_baslUploadType
_baslPageToken
_baslPageSize
_baslCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy :: Proxy BillingAccountsSinksListResource)
mempty
|
brendanhay/gogol
|
gogol-logging/gen/Network/Google/Resource/Logging/BillingAccounts/Sinks/List.hs
|
mpl-2.0
| 6,266 | 0 | 18 | 1,406 | 894 | 520 | 374 | 129 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.EC2.RequestSpotInstances
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a Spot instance request. Spot instances are instances that
-- Amazon EC2 launches when the bid price that you specify exceeds the
-- current Spot price. Amazon EC2 periodically sets the Spot price based on
-- available Spot Instance capacity and current Spot instance requests. For
-- more information, see
-- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html Spot Instance Requests>
-- in the /Amazon Elastic Compute Cloud User Guide/.
--
-- /See:/ <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-RequestSpotInstances.html AWS API Reference> for RequestSpotInstances.
module Network.AWS.EC2.RequestSpotInstances
(
-- * Creating a Request
requestSpotInstances
, RequestSpotInstances
-- * Request Lenses
, rsiClientToken
, rsiInstanceCount
, rsiLaunchSpecification
, rsiAvailabilityZoneGroup
, rsiValidUntil
, rsiLaunchGroup
, rsiType
, rsiValidFrom
, rsiDryRun
, rsiSpotPrice
-- * Destructuring the Response
, requestSpotInstancesResponse
, RequestSpotInstancesResponse
-- * Response Lenses
, rsirsSpotInstanceRequests
, rsirsResponseStatus
) where
import Network.AWS.EC2.Types
import Network.AWS.EC2.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Contains the parameters for RequestSpotInstances.
--
-- /See:/ 'requestSpotInstances' smart constructor.
data RequestSpotInstances = RequestSpotInstances'
{ _rsiClientToken :: !(Maybe Text)
, _rsiInstanceCount :: !(Maybe Int)
, _rsiLaunchSpecification :: !(Maybe RequestSpotLaunchSpecification)
, _rsiAvailabilityZoneGroup :: !(Maybe Text)
, _rsiValidUntil :: !(Maybe ISO8601)
, _rsiLaunchGroup :: !(Maybe Text)
, _rsiType :: !(Maybe SpotInstanceType)
, _rsiValidFrom :: !(Maybe ISO8601)
, _rsiDryRun :: !(Maybe Bool)
, _rsiSpotPrice :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RequestSpotInstances' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rsiClientToken'
--
-- * 'rsiInstanceCount'
--
-- * 'rsiLaunchSpecification'
--
-- * 'rsiAvailabilityZoneGroup'
--
-- * 'rsiValidUntil'
--
-- * 'rsiLaunchGroup'
--
-- * 'rsiType'
--
-- * 'rsiValidFrom'
--
-- * 'rsiDryRun'
--
-- * 'rsiSpotPrice'
requestSpotInstances
:: Text -- ^ 'rsiSpotPrice'
-> RequestSpotInstances
requestSpotInstances pSpotPrice_ =
RequestSpotInstances'
{ _rsiClientToken = Nothing
, _rsiInstanceCount = Nothing
, _rsiLaunchSpecification = Nothing
, _rsiAvailabilityZoneGroup = Nothing
, _rsiValidUntil = Nothing
, _rsiLaunchGroup = Nothing
, _rsiType = Nothing
, _rsiValidFrom = Nothing
, _rsiDryRun = Nothing
, _rsiSpotPrice = pSpotPrice_
}
-- | Unique, case-sensitive identifier that you provide to ensure the
-- idempotency of the request. For more information, see
-- <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Run_Instance_Idempotency.html How to Ensure Idempotency>
-- in the /Amazon Elastic Compute Cloud User Guide/.
rsiClientToken :: Lens' RequestSpotInstances (Maybe Text)
rsiClientToken = lens _rsiClientToken (\ s a -> s{_rsiClientToken = a});
-- | The maximum number of Spot instances to launch.
--
-- Default: 1
rsiInstanceCount :: Lens' RequestSpotInstances (Maybe Int)
rsiInstanceCount = lens _rsiInstanceCount (\ s a -> s{_rsiInstanceCount = a});
-- | Undocumented member.
rsiLaunchSpecification :: Lens' RequestSpotInstances (Maybe RequestSpotLaunchSpecification)
rsiLaunchSpecification = lens _rsiLaunchSpecification (\ s a -> s{_rsiLaunchSpecification = a});
-- | The user-specified name for a logical grouping of bids.
--
-- When you specify an Availability Zone group in a Spot Instance request,
-- all Spot instances in the request are launched in the same Availability
-- Zone. Instance proximity is maintained with this parameter, but the
-- choice of Availability Zone is not. The group applies only to bids for
-- Spot Instances of the same instance type. Any additional Spot instance
-- requests that are specified with the same Availability Zone group name
-- are launched in that same Availability Zone, as long as at least one
-- instance from the group is still active.
--
-- If there is no active instance running in the Availability Zone group
-- that you specify for a new Spot instance request (all instances are
-- terminated, the bid is expired, or the bid falls below current market),
-- then Amazon EC2 launches the instance in any Availability Zone where the
-- constraint can be met. Consequently, the subsequent set of Spot
-- instances could be placed in a different zone from the original request,
-- even if you specified the same Availability Zone group.
--
-- Default: Instances are launched in any available Availability Zone.
rsiAvailabilityZoneGroup :: Lens' RequestSpotInstances (Maybe Text)
rsiAvailabilityZoneGroup = lens _rsiAvailabilityZoneGroup (\ s a -> s{_rsiAvailabilityZoneGroup = a});
-- | The end date of the request. If this is a one-time request, the request
-- remains active until all instances launch, the request is canceled, or
-- this date is reached. If the request is persistent, it remains active
-- until it is canceled or this date and time is reached.
--
-- Default: The request is effective indefinitely.
rsiValidUntil :: Lens' RequestSpotInstances (Maybe UTCTime)
rsiValidUntil = lens _rsiValidUntil (\ s a -> s{_rsiValidUntil = a}) . mapping _Time;
-- | The instance launch group. Launch groups are Spot instances that launch
-- together and terminate together.
--
-- Default: Instances are launched and terminated individually
rsiLaunchGroup :: Lens' RequestSpotInstances (Maybe Text)
rsiLaunchGroup = lens _rsiLaunchGroup (\ s a -> s{_rsiLaunchGroup = a});
-- | The Spot instance request type.
--
-- Default: 'one-time'
rsiType :: Lens' RequestSpotInstances (Maybe SpotInstanceType)
rsiType = lens _rsiType (\ s a -> s{_rsiType = a});
-- | The start date of the request. If this is a one-time request, the
-- request becomes active at this date and time and remains active until
-- all instances launch, the request expires, or the request is canceled.
-- If the request is persistent, the request becomes active at this date
-- and time and remains active until it expires or is canceled.
--
-- Default: The request is effective indefinitely.
rsiValidFrom :: Lens' RequestSpotInstances (Maybe UTCTime)
rsiValidFrom = lens _rsiValidFrom (\ s a -> s{_rsiValidFrom = a}) . mapping _Time;
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have
-- the required permissions, the error response is 'DryRunOperation'.
-- Otherwise, it is 'UnauthorizedOperation'.
rsiDryRun :: Lens' RequestSpotInstances (Maybe Bool)
rsiDryRun = lens _rsiDryRun (\ s a -> s{_rsiDryRun = a});
-- | The maximum hourly price (bid) for any Spot instance launched to fulfill
-- the request.
rsiSpotPrice :: Lens' RequestSpotInstances Text
rsiSpotPrice = lens _rsiSpotPrice (\ s a -> s{_rsiSpotPrice = a});
instance AWSRequest RequestSpotInstances where
type Rs RequestSpotInstances =
RequestSpotInstancesResponse
request = postQuery eC2
response
= receiveXML
(\ s h x ->
RequestSpotInstancesResponse' <$>
(x .@? "spotInstanceRequestSet" .!@ mempty >>=
may (parseXMLList "item"))
<*> (pure (fromEnum s)))
instance ToHeaders RequestSpotInstances where
toHeaders = const mempty
instance ToPath RequestSpotInstances where
toPath = const "/"
instance ToQuery RequestSpotInstances where
toQuery RequestSpotInstances'{..}
= mconcat
["Action" =: ("RequestSpotInstances" :: ByteString),
"Version" =: ("2015-04-15" :: ByteString),
"ClientToken" =: _rsiClientToken,
"InstanceCount" =: _rsiInstanceCount,
"LaunchSpecification" =: _rsiLaunchSpecification,
"AvailabilityZoneGroup" =: _rsiAvailabilityZoneGroup,
"ValidUntil" =: _rsiValidUntil,
"LaunchGroup" =: _rsiLaunchGroup, "Type" =: _rsiType,
"ValidFrom" =: _rsiValidFrom, "DryRun" =: _rsiDryRun,
"SpotPrice" =: _rsiSpotPrice]
-- | Contains the output of RequestSpotInstances.
--
-- /See:/ 'requestSpotInstancesResponse' smart constructor.
data RequestSpotInstancesResponse = RequestSpotInstancesResponse'
{ _rsirsSpotInstanceRequests :: !(Maybe [SpotInstanceRequest])
, _rsirsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'RequestSpotInstancesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rsirsSpotInstanceRequests'
--
-- * 'rsirsResponseStatus'
requestSpotInstancesResponse
:: Int -- ^ 'rsirsResponseStatus'
-> RequestSpotInstancesResponse
requestSpotInstancesResponse pResponseStatus_ =
RequestSpotInstancesResponse'
{ _rsirsSpotInstanceRequests = Nothing
, _rsirsResponseStatus = pResponseStatus_
}
-- | One or more Spot instance requests.
rsirsSpotInstanceRequests :: Lens' RequestSpotInstancesResponse [SpotInstanceRequest]
rsirsSpotInstanceRequests = lens _rsirsSpotInstanceRequests (\ s a -> s{_rsirsSpotInstanceRequests = a}) . _Default . _Coerce;
-- | The response status code.
rsirsResponseStatus :: Lens' RequestSpotInstancesResponse Int
rsirsResponseStatus = lens _rsirsResponseStatus (\ s a -> s{_rsirsResponseStatus = a});
|
olorin/amazonka
|
amazonka-ec2/gen/Network/AWS/EC2/RequestSpotInstances.hs
|
mpl-2.0
| 10,637 | 0 | 15 | 2,071 | 1,333 | 805 | 528 | 145 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
module Dyno.Nlp
( Bounds
, Nlp(..), NlpIn(..), NlpOut(..)
) where
import GHC.Generics ( Generic )
import Casadi.Viewable ( Viewable )
import qualified Data.Vector as V
import Data.Binary ( Binary )
import Dyno.View.View ( View(..), J, S )
type Bounds = (Maybe Double, Maybe Double)
data NlpIn x p g =
NlpIn
{ nlpX0 :: J x (V.Vector Double)
, nlpBX :: J x (V.Vector Bounds)
, nlpBG :: J g (V.Vector Bounds)
, nlpP :: J p (V.Vector Double)
, nlpLamX0 :: Maybe (J x (V.Vector Double))
, nlpLamG0 :: Maybe (J g (V.Vector Double))
}
-- | nonlinear program (NLP)
--
-- > minimize f(x,p)
-- > x
-- >
-- > subject to xlb <= x <= xub
-- > glb <= g(x) <= gub
--
-- where p is some parameter
--
data Nlp x p g a =
Nlp
{ nlpFG :: J x a -> J p a -> (S a, J g a)
, nlpIn :: NlpIn x p g
, nlpScaleF :: Maybe Double
, nlpScaleX :: Maybe (J x (V.Vector Double))
, nlpScaleG :: Maybe (J g (V.Vector Double))
}
-- | NLP output
data NlpOut x g a =
NlpOut
{ fOpt :: S a
, xOpt :: J x a
, gOpt :: J g a
, lambdaXOpt :: J x a
, lambdaGOpt :: J g a
} deriving (Eq, Show, Generic)
instance (View x, View g, Binary a, Viewable a) => Binary (NlpOut x g a)
|
ghorn/dynobud
|
dynobud/src/Dyno/Nlp.hs
|
lgpl-3.0
| 1,358 | 0 | 14 | 370 | 509 | 292 | 217 | 37 | 0 |
module Network.Haskoin.Transaction.Types
( Tx(..)
, TxIn(..)
, TxOut(..)
, OutPoint(..)
, CoinbaseTx(..)
, txHash
, nosigTxHash
, cbHash
) where
import Control.DeepSeq (NFData, rnf)
import Control.Monad (liftM2, replicateM, forM_, unless)
import Control.Applicative ((<$>),(<*>))
import Data.Aeson (Value(String), FromJSON, ToJSON, parseJSON, toJSON, withText)
import Data.Word (Word32, Word64)
import qualified Data.Text as T
import Data.Binary (Binary, get, put)
import Data.Binary.Get
( getWord32le
, getWord64le
, getByteString
)
import Data.Binary.Put
( putWord32le
, putWord64le
, putByteString
)
import qualified Data.ByteString as BS
( ByteString
, length
, empty
)
import Network.Haskoin.Util
import Network.Haskoin.Crypto.BigWord
import Network.Haskoin.Crypto.Hash
import Network.Haskoin.Node.Types
-- | Computes the hash of a transaction.
txHash :: Tx -> TxHash
txHash = fromIntegral . doubleHash256 . encode'
nosigTxHash :: Tx -> TxHash
nosigTxHash tx =
txHash tx{ txIn = map clearInput $ txIn tx}
where
clearInput ti = ti{ scriptInput = BS.empty }
-- | Computes the hash of a coinbase transaction.
cbHash :: CoinbaseTx -> TxHash
cbHash = fromIntegral . doubleHash256 . encode'
-- | Data type representing a bitcoin transaction
data Tx =
Tx {
-- | Transaction data format version
txVersion :: !Word32
-- | List of transaction inputs
, txIn :: ![TxIn]
-- | List of transaction outputs
, txOut :: ![TxOut]
-- | The block number of timestamp at which this transaction is locked
, txLockTime :: !Word32
} deriving (Eq, Show, Read)
instance NFData Tx where
rnf (Tx v i o l) = rnf v `seq` rnf i `seq` rnf o `seq` rnf l
instance Binary Tx where
get = Tx <$> getWord32le
<*> (replicateList =<< get)
<*> (replicateList =<< get)
<*> getWord32le
where
replicateList (VarInt c) = replicateM (fromIntegral c) get
put (Tx v is os l) = do
putWord32le v
put $ VarInt $ fromIntegral $ length is
forM_ is put
put $ VarInt $ fromIntegral $ length os
forM_ os put
putWord32le l
instance FromJSON Tx where
parseJSON = withText "transaction" $ \t -> either fail return $
maybeToEither "tx not hex" (hexToBS $ T.unpack t) >>= decodeToEither
instance ToJSON Tx where
toJSON = String . T.pack . bsToHex . encode'
-- | Data type representing the coinbase transaction of a 'Block'. Coinbase
-- transactions are special types of transactions which are created by miners
-- when they find a new block. Coinbase transactions have no inputs. They have
-- outputs sending the newly generated bitcoins together with all the block's
-- fees to a bitcoin address (usually the miners address). Data can be embedded
-- in a Coinbase transaction which can be chosen by the miner of a block. This
-- data also typically contains some randomness which is used, together with
-- the nonce, to find a partial hash collision on the block's hash.
data CoinbaseTx =
CoinbaseTx {
-- | Transaction data format version.
cbVersion :: !Word32
-- | Previous outpoint. This is ignored for
-- coinbase transactions but preserved for computing
-- the correct txid.
, cbPrevOutput :: !OutPoint
-- | Data embedded inside the coinbase transaction.
, cbData :: !BS.ByteString
-- | Transaction sequence number. This is ignored for
-- coinbase transactions but preserved for computing
-- the correct txid.
, cbInSequence :: !Word32
-- | List of transaction outputs.
, cbOut :: ![TxOut]
-- | The block number of timestamp at which this
-- transaction is locked.
, cbLockTime :: !Word32
} deriving (Eq, Show, Read)
instance NFData CoinbaseTx where
rnf (CoinbaseTx v p d i o l) =
rnf v `seq` rnf p `seq` rnf d `seq` rnf i `seq` rnf o `seq` rnf l
instance Binary CoinbaseTx where
get = do
v <- getWord32le
(VarInt len) <- get
unless (len == 1) $ fail "CoinbaseTx get: Input size is not 1"
op <- get
(VarInt cbLen) <- get
cb <- getByteString (fromIntegral cbLen)
sq <- getWord32le
(VarInt oLen) <- get
os <- replicateM (fromIntegral oLen) get
lt <- getWord32le
return $ CoinbaseTx v op cb sq os lt
put (CoinbaseTx v op cb sq os lt) = do
putWord32le v
put $ VarInt 1
put op
put $ VarInt $ fromIntegral $ BS.length cb
putByteString cb
putWord32le sq
put $ VarInt $ fromIntegral $ length os
forM_ os put
putWord32le lt
-- | Data type representing a transaction input.
data TxIn =
TxIn {
-- | Reference the previous transaction output (hash + position)
prevOutput :: !OutPoint
-- | Script providing the requirements of the previous transaction
-- output to spend those coins.
, scriptInput :: !BS.ByteString
-- | Transaction version as defined by the sender of the
-- transaction. The intended use is for replacing transactions with
-- new information before the transaction is included in a block.
, txInSequence :: !Word32
} deriving (Eq, Show, Read)
instance NFData TxIn where
rnf (TxIn p i s) = rnf p `seq` rnf i `seq` rnf s
instance Binary TxIn where
get =
TxIn <$> get <*> (readBS =<< get) <*> getWord32le
where
readBS (VarInt len) = getByteString $ fromIntegral len
put (TxIn o s q) = do
put o
put $ VarInt $ fromIntegral $ BS.length s
putByteString s
putWord32le q
-- | Data type representing a transaction output.
data TxOut =
TxOut {
-- | Transaction output value.
outValue :: !Word64
-- | Script specifying the conditions to spend this output.
, scriptOutput :: !BS.ByteString
} deriving (Eq, Show, Read)
instance NFData TxOut where
rnf (TxOut v o) = rnf v `seq` rnf o
instance Binary TxOut where
get = do
val <- getWord64le
(VarInt len) <- get
TxOut val <$> (getByteString $ fromIntegral len)
put (TxOut o s) = do
putWord64le o
put $ VarInt $ fromIntegral $ BS.length s
putByteString s
-- | The OutPoint is used inside a transaction input to reference the previous
-- transaction output that it is spending.
data OutPoint =
OutPoint {
-- | The hash of the referenced transaction.
outPointHash :: !TxHash
-- | The position of the specific output in the transaction.
-- The first output position is 0.
, outPointIndex :: !Word32
} deriving (Read, Show, Eq)
instance NFData OutPoint where
rnf (OutPoint h i) = rnf h `seq` rnf i
instance FromJSON OutPoint where
parseJSON = withText "outpoint" $ \t -> either fail return $
maybeToEither "outpoint not hex"
(hexToBS $ T.unpack t) >>= decodeToEither
instance ToJSON OutPoint where
toJSON = String . T.pack . bsToHex . encode'
instance Binary OutPoint where
get = do
(h,i) <- liftM2 (,) get getWord32le
return $ OutPoint h i
put (OutPoint h i) = put h >> putWord32le i
|
nuttycom/haskoin
|
Network/Haskoin/Transaction/Types.hs
|
unlicense
| 7,645 | 0 | 14 | 2,359 | 1,771 | 940 | 831 | 187 | 1 |
module Functor where
-- Fixed point on functors
data Fix f = In (f (Fix f))
unIn (In x) = x
-- Sum of functors
data SumF f g x = LeftF (f x) | RightF (g x)
instance (Functor f, Functor g) => Functor (SumF f g)
where
fmap f (LeftF x) = LeftF $ fmap f x
fmap f (RightF x) = RightF $ fmap f x
bimap f g (LeftF x) = f x
bimap f g (RightF x) = g x
-- Folds over functors
fold :: (Functor f) => (f a -> a) -> Fix f -> a
fold f = f . fmap (fold f) . unIn
|
egaburov/funstuff
|
Haskell/tytag/xproblem_src/samples/expressions/Haskell/FunctorialStyle/Functor.hs
|
apache-2.0
| 468 | 0 | 10 | 133 | 255 | 132 | 123 | 11 | 1 |
{-
Copyright 2018 The CodeWorld Authors. All Rights Reserved.
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.
-}
import Distribution.Simple
main = defaultMain
|
tgdavies/codeworld
|
funblocks-client/Setup.hs
|
apache-2.0
| 657 | 0 | 4 | 121 | 12 | 7 | 5 | 2 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-| Exposes some of Spark's joining algorithms.
-}
module Spark.Core.Internal.Joins(
join,
join',
joinInner,
joinInner',
joinObs,
joinObs'
) where
import qualified Data.Aeson as A
import qualified Data.Vector as V
import Control.Arrow
import Spark.Core.Internal.ColumnStructures
import Spark.Core.Internal.ColumnFunctions
import Spark.Core.Internal.DatasetStructures
import Spark.Core.Internal.DatasetFunctions
import Spark.Core.Internal.FunctionsInternals
import Spark.Core.Internal.OpStructures
import Spark.Core.Internal.TypesStructures
import Spark.Core.Internal.Utilities
import Spark.Core.Internal.TypesFunctions(structTypeFromFields)
import Spark.Core.Try
import Spark.Core.StructuresInternal(unsafeFieldName)
{-| Standard (inner) join on two sets of data.
-}
join :: Column ref1 key -> Column ref1 value1 -> Column ref2 key -> Column ref2 value2 -> Dataset (key, value1, value2)
join = joinInner
{-| Untyped version of the standard join.
-}
join' :: DynColumn -> DynColumn -> DynColumn -> DynColumn -> DataFrame
join' = joinInner'
{-| Explicit inner join.
-}
joinInner :: Column ref1 key -> Column ref1 value1 -> Column ref2 key -> Column ref2 value2 -> Dataset (key, value1, value2)
joinInner key1 val1 key2 val2 = unsafeCastDataset (forceRight df) where
df = joinInner' (untypedCol key1) (untypedCol val1) (untypedCol key2) (untypedCol val2)
{-| Untyped version of the inner join.
-}
joinInner' :: DynColumn -> DynColumn -> DynColumn -> DynColumn -> DataFrame
joinInner' key1 val1 key2 val2 = do
df1 <- pack' (struct' [key1, val1])
df2 <- pack' (struct' [key2, val2])
dt <- _joinTypeInner key1 val1 val2
let so = StandardOperator { soName = "org.spark.Join", soOutputType = dt, soExtra = A.String "inner" }
let ds = emptyDataset (NodeDistributedOp so) (SQLType dt)
let f ds' = ds' { _cnParents = V.fromList [untyped df1, untyped df2] }
return $ updateNode ds f
{-| Broadcasts an observable alongside a dataset to make it available as an
extra column.
-}
-- This is the low-level operation that is used to implement the other
-- broadcast operations.
joinObs :: (HasCallStack) => Column ref val -> LocalData val' -> Dataset (val, val')
joinObs c ld =
-- TODO: has a forcing at the last moment so that we can at least
-- have stronger guarantees in the type coercion.
unsafeCastDataset $ forceRight $ joinObs' (untypedCol c) (pure (untypedLocalData ld))
{-| Broadcasts an observable along side a dataset to make it available as
an extra column.
The resulting dataframe has 2 columns:
- one column called 'values'
- one column called 'broadcast'
Note: this is a low-level operation. Users may want to use broadcastObs instead.
-}
-- TODO: what is the difference with broadcastPair???
joinObs' :: DynColumn -> LocalFrame -> DataFrame
joinObs' dc lf = do
let df = pack' dc
dc' <- df
c <- asCol' df
o <- lf
st <- structTypeFromFields [(unsafeFieldName "values", unSQLType (colType c)), (unsafeFieldName "broadcast", unSQLType (nodeType o))]
let sqlt = SQLType (StrictType (Struct st))
return $ emptyDataset NodeBroadcastJoin sqlt `parents` [untyped dc', untyped o]
_joinTypeInner :: DynColumn -> DynColumn -> DynColumn -> Try DataType
_joinTypeInner kcol col1 col2 = do
cs <- sequence [kcol, col1, col2]
st <- structTypeFromFields $ (colFieldName &&& unSQLType . colType) <$> cs
return $ StrictType (Struct st)
|
krapsh/kraps-haskell
|
src/Spark/Core/Internal/Joins.hs
|
apache-2.0
| 3,452 | 0 | 14 | 552 | 886 | 471 | 415 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module ArchitectureDiagram.Target.Dot
( nodeStatement
, NodeLeafest
, toGraph
, nodeLeafest
, edgeStatement
, listAllNodes
) where
import qualified Language.Dot.Syntax as Dot
import qualified Data.Map as Map
import Control.Applicative
import Data.Map (Map)
import Data.Text (Text)
import Data.Text.Conversions (fromText)
import Data.List (intercalate)
import Data.Maybe (catMaybes, fromMaybe)
import Language.Dot.Syntax hiding (Graph)
import ArchitectureDiagram.Data.Node (Node(..), NodeRef(..), NodeStyle(..), Shape(..))
import ArchitectureDiagram.Data.Edge (Edge(..), EdgeStyle(..), EdgeRank(..))
import ArchitectureDiagram.Data.Graph (Graph(..))
nodeStatement :: (NodeRef, Node) -> Statement
nodeStatement (ref, node) =
if Map.null (_nNodes node)
then toNodeStatement ref node
else toClusterStatement ref node
toNodeStatement :: NodeRef -> Node -> Statement
toNodeStatement ref node = NodeStatement (nodeId ref) (toNodeAttributes node)
toNodeAttributes :: Node -> [Attribute]
toNodeAttributes n = attributes ++ catMaybes mAttributes
where
attributes :: [Attribute]
attributes =
[ label (_nName n)
, shape (_nShape n)
]
mAttributes :: [Maybe Attribute]
mAttributes =
[ nodeStyles (_nStyles n)
, width <$> _nWidth n
]
nodeId :: NodeRef -> NodeId
nodeId ref = NodeId (StringId $ fromText (unNodeRef ref)) Nothing
label :: Text -> Attribute
label x = AttributeSetValue (NameId "label") (StringId $ fromText x)
shape :: Shape -> Attribute
shape x = AttributeSetValue (NameId "shape") (StringId $ shapeId x)
shapeId :: Shape -> String
shapeId Record = "record"
shapeId Box3d = "box3d"
nodeStyles :: [NodeStyle] -> Maybe Attribute
nodeStyles = style nodeStyleId
nodeStyleId :: NodeStyle -> String
nodeStyleId Rounded = "rounded"
width :: Float -> Attribute
width x = AttributeSetValue (NameId "width") (FloatId x)
toClusterStatement :: NodeRef -> Node -> Statement
toClusterStatement ref node = SubgraphStatement $ NewSubgraph (Just $ clusterId ref) statements
where
statements =
[ AssignmentStatement (NameId "label") (StringId . fromText $ _nName node) ] ++
(map nodeStatement . Map.toList $ _nNodes node)
clusterId :: NodeRef -> Id
clusterId ref = StringId . fromText $ "cluster_" `mappend` (unNodeRef ref)
edgeStatement :: (NodeLeafest, Edge) -> Statement
edgeStatement (nl@(NodeLeafest leafest), e) = EdgeStatement
[ ENodeId NoEdge (nodeId fromEdge)
, ENodeId DirectedEdge (nodeId toEdge)
]
(toEdgeAttributes toEdgeLeafest fromEdgeLeafest e)
where
toEdge = fromMaybe (_eTo e) toEdgeLeafest
toEdgeLeafest = Map.lookup (_eTo e) leafest
fromEdge = fromMaybe (_eFrom e) fromEdgeLeafest
fromEdgeLeafest = Map.lookup (_eFrom e) leafest
toEdgeAttributes :: Maybe NodeRef -> Maybe NodeRef -> Edge -> [Attribute]
toEdgeAttributes toEdge fromEdge e = attributes ++ catMaybes mAttributes
where
attributes :: [Attribute]
attributes = []
mAttributes :: [Maybe Attribute]
mAttributes =
[ rankAttribute (_eRank e)
, toEdgeClusterAttribute
, fromEdgeClusterAttribute
, edgeStyles (_eStyles e)
]
toEdgeClusterAttribute = case toEdge of
Nothing -> Nothing
Just _ -> Just $ case _eRank e of
To -> AttributeSetValue (NameId "ltail") (clusterId $ _eTo e)
From -> AttributeSetValue (NameId "lhead") (clusterId $ _eTo e)
fromEdgeClusterAttribute = case fromEdge of
Nothing -> Nothing
Just _ -> Just $ case _eRank e of
From -> AttributeSetValue (NameId "ltail") (clusterId $ _eFrom e)
To -> AttributeSetValue (NameId "lhead") (clusterId $ _eFrom e)
rankAttribute :: EdgeRank -> Maybe Attribute
rankAttribute rank = case rank of
To -> Just $ AttributeSetValue (NameId "dir") (StringId "back")
From -> Nothing
edgeStyles :: [EdgeStyle] -> Maybe Attribute
edgeStyles = style edgeStyleId
edgeStyleId :: EdgeStyle -> String
edgeStyleId Dashed = "dashed"
style :: (a -> String) -> [a] -> Maybe Attribute
style f xs
| null xs = Nothing
| otherwise = Just $ AttributeSetValue (NameId "style") (StringId $ intercalate "," (map f xs))
toGraph :: Graph -> Dot.Graph
toGraph graph = Dot.Graph UnstrictGraph DirectedGraph (Just $ StringId (fromText $ _gName graph))
(
[ AssignmentStatement (NameId "ranksep") (IntegerId 1)
, AssignmentStatement (NameId "rankdir") (NameId "TB")
, AssignmentStatement (NameId "compound") (NameId "true")
] ++
(map nodeStatement (Map.toList $ _gNodes graph)) ++
(map (\e -> edgeStatement (leafest, e)) (_gEdges graph))
)
where
leafest = nodeLeafest (_gNodes graph)
newtype NodeLeafest = NodeLeafest { unNodeLeafest :: Map NodeRef NodeRef }
deriving (Show, Eq)
someChildNodeKey :: Node -> Maybe NodeRef
someChildNodeKey n = let
mKeyNode = fmap fst (Map.minViewWithKey $ _nNodes n)
mKey = fmap fst mKeyNode
mNode = fmap snd mKeyNode
mChildKey = someChildNodeKey =<< mNode
in mChildKey <|> mKey
nodeLeafest :: Map NodeRef Node -> NodeLeafest
nodeLeafest nodes = NodeLeafest $ Map.fromList $ catMaybes (map nodeChild $ listAllNodes nodes)
where
nodeChild :: (NodeRef, Node) -> Maybe (NodeRef, NodeRef)
nodeChild (ref, node) = (ref,) <$> someChildNodeKey node
listAllNodes :: Map NodeRef Node -> [(NodeRef, Node)]
listAllNodes nodes = Map.toList nodes ++ childCousins ++ grandCousins
where
grandCousins :: [(NodeRef, Node)]
grandCousins = if null childCousins then [] else listAllNodes (Map.fromList childCousins)
childCousins :: [(NodeRef, Node)]
childCousins = concat . map (Map.toList . _nNodes . snd) . Map.toList $ nodes
|
cjdev/architecture-diagram
|
src/ArchitectureDiagram/Target/Dot.hs
|
bsd-3-clause
| 5,762 | 0 | 17 | 1,091 | 1,908 | 1,010 | 898 | 131 | 5 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Char8 as S
import Data.Maybe (isJust)
import qualified Data.Vector as V
import GitHub
import System.Environment
import Shlurp.Config
import Shlurp.Operations
main :: IO ()
main = do
config <- loadSettings "afcowie" "tablinator"
issues <- executeGitHub config listIssues
labels <- executeGitHub config listLabels
mapM_ (print . issueTitle) issues
-- mapM_ (print . V.map labelName . issueLabels) issues
mapM_ (print . labelName) labels
|
afcowie/shlurp
|
tests/Snippet.hs
|
bsd-3-clause
| 549 | 0 | 9 | 97 | 132 | 72 | 60 | 16 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Bootstrap.Components where
import Bootstrap.Util
import Snap
import Heist
import Heist.Interpreted
import qualified Text.XmlHtml as X
import Data.Maybe (fromMaybe)
import Data.Monoid
dividerSplice :: MonadSnap m => Splice m
dividerSplice = getParamNode <$$>
mkElement' "li" (const []) []
[ ( "vertical" , Just . flip (maybe id (<>)) "divider" . ("vertical-" <$) ) ]
[] []
-- Dropdown {{{
dropdownSplice :: MonadSnap m => Splice m
dropdownSplice = getParamNode <$$>
mkElement "ul"
[ "dropdown-menu" ]
[ ( "pull-right" , ("pull-right" <$) ) ]
[ ( "role" , "menu" ) ] []
entrySplice :: MonadSnap m => Splice m
entrySplice = do
node <- getParamNode
let aNodes = mkElement "a"
[] []
[ ( "tabindex" , "-1" ) ]
[ ( "href" , (\mhr -> Just ("href",fromMaybe "#" mhr)) )
, ( "active" , (("active","") <$) )
]
node
let liNodes = mkElement' "li" (const aNodes)
[] [] []
[ ( "disabled" , (("disabled","") <$) ) ]
node
return liNodes
-- }}}
-- Button {{{
btnSplice :: MonadSnap m => Splice m
btnSplice = getParamNode <$$>
mkElement "button"
[ "btn" ]
[ ( "size" , fmap ("btn-" <>) )
, ( "color" , fmap ("btn-" <>) )
]
[] []
btngroupSplice :: MonadSnap m => Splice m
btngroupSplice = getParamNode <$$>
mkElement "div"
[ "btn-group" ]
[ ( "vertical" , ("btn-group-vertical" <$) ) ]
[] []
btntoolbarSplice :: MonadSnap m => Splice m
btntoolbarSplice = getParamNode <$$>
mkElement "div" [ "btn-toolbar" ] [] [] []
-- }}}
-- Button Dropdown {{{
btndropupSplice :: MonadSnap m => Splice m
btndropupSplice = do
node <- getParamNode
let ulNodes = mkElement "ul"
[ "dropdown-menu" ] []
[] []
node
let dNodes = mkElement' "div" (const ulNodes)
[ "btn-group" , "dropup" ] []
[] []
node
return dNodes
btndropdownSplice :: MonadSnap m => Splice m
btndropdownSplice = do
node <- getParamNode
let mtxt = X.getAttribute "label" node
let aNodes = mkElement' "a"
(const
[ X.TextNode (fromMaybe "" mtxt)
, X.Element "span" [("class","caret")] []
])
[ "btn" , "dropdown-toggle" ]
[]
[ ( "data-toggle" , "dropdown" )
, ( "href" , "#" )
]
[]
node
let dNodes = mkElement' "div" (aNodes ++)
[ "btn-group" ]
[ ( "size" , fmap ("btn-" <>) ) ]
[] []
node
return dNodes
-- }}}
-- Nav {{{
navSplice :: MonadSnap m => Splice m
navSplice = getParamNode <$$>
mkElement "ul"
[ "nav" ]
[ ( "type" , fmap ("nav-" <>) )
, ( "pull" , fmap ("pull-" <>) )
, ( "stacked" , ("nav-stacked" <$) )
, ( "list" , ("nav-list" <$) )
]
[] []
navheaderSplice :: MonadSnap m => Splice m
navheaderSplice = getParamNode <$$>
mkElement "li"
[ "nav-header" ]
[] [] []
navbarSplice :: MonadSnap m => Splice m
navbarSplice = getParamNode <$$>
mkElement "div"
[ "navbar" ]
[] [] []
navbarheaderSplice :: MonadSnap m => Splice m
navbarheaderSplice = getParamNode <$$>
mkElement "div"
[ "navbar-header" ]
[] [] []
navbarcollapseSplice :: MonadSnap m => Splice m
navbarcollapseSplice = do
node <- getParamNode
let ulNodes = mkElement "ul"
[ "nav" , "navbar-nav" ]
[] [] []
node
let dNodes = mkElement' "div" (const ulNodes)
[ "collapse" , "navbar-collapse" ]
[] [] []
node
return dNodes
tabbableSplice :: MonadSnap m => Splice m
tabbableSplice = getParamNode <$$>
mkElement "div"
[ "tabbable" ]
[] [] []
brandSplice :: MonadSnap m => Splice m
brandSplice = getParamNode <$$>
mkElement "a"
[ "navbar-brand" ]
[]
[]
[ ( "href" , (\mhr -> Just ("href",fromMaybe "#" mhr)) ) ]
navbarformSplice :: MonadSnap m => Splice m
navbarformSplice = getParamNode <$$>
mkElement "form"
[ "navbar-form" ]
[ ( "pull" , fmap ("pull-" <>) ) ]
[] []
-- }}}
bootstrapComponentSplices :: MonadSnap m => Splices (Splice m)
bootstrapComponentSplices = do
"divider" ## dividerSplice
"dropdown" ## dropdownSplice
"entry" ## entrySplice
"btn" ## btnSplice
"btngroup" ## btngroupSplice
"btntoolbar" ## btntoolbarSplice
"btndropup" ## btndropupSplice
"btndropdown" ## btndropdownSplice
"nav" ## navSplice
"nav-header" ## navheaderSplice
"navbar" ## navbarSplice
"navbar-header" ## navbarheaderSplice
"navbar-collapse" ## navbarcollapseSplice
"tabbable" ## tabbableSplice
"brand" ## brandSplice
"navbar-form" ## navbarformSplice
|
kylcarte/qclib
|
src/Bootstrap/Components.hs
|
bsd-3-clause
| 4,932 | 0 | 17 | 1,536 | 1,506 | 791 | 715 | 154 | 1 |
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
module Main where
import Control.Monad.State
import System.Console.Haskeline
import System.Console.Haskeline.MonadException
import System.Exit
import System.FilePath
import Unbound.LocallyNameless.Subst
import qualified Data.Map.Strict as M
--import Eval
import Parser
--import Pretty
import Syntax
import Queue
--import TypeChecker
agdaName :: String
agdaName = "Agda-LLS"
banner :: String
banner = "Welcome to "++agdaName++"!"
type Qelm = (CVnm, CTerm)
type REPLStateIO = StateT (FilePath,Queue (QDefName, QDefDef)) IO
instance MonadException m => MonadException (StateT (FilePath,Queue (QDefName, QDefDef)) m) where
controlIO f = StateT $ \s -> controlIO $ \(RunIO run) -> let
run' = RunIO (fmap (StateT . const) . run . flip runStateT s)
in fmap (flip runStateT s) $ f run'
data QDefName = Var CVnm | DefName CVnm
deriving (Show, Eq)
data QDefDef = DefTerm CTerm | VarType Type
deriving Show
getQDefM :: (QDefName, QDefDef) -> REPLStateIO (Either (CVnm, Type) (CVnm, CTerm))
getQDefM e@(Var x, DefTerm t) = return $ Right (x , t)
getQDefM e@(DefName x, VarType ty) = return $ Left (x , ty)
getQDefM e@(x,y) = error $ "Failed to get definition from context. Mismatched variable and type or term in: "++(prettyDef e)
getQDef :: (QDefName, QDefDef) -> Either (CVnm, Type) (CVnm, CTerm)
getQDef e@(Var x, DefTerm t) = Right (x , t)
getQDef e@(DefName x, VarType ty) = Left (x , ty)
getQDef e@(x,y) = error $ "Failed to get definition from context. Mismatched variable and type or term in: "++(prettyDef e)
-- Extract only free variables that are defined from queue
getQFVM :: Queue (QDefName,QDefDef) -> Queue (CVnm,Type) -> REPLStateIO (Queue (CVnm,Type))
getQFVM (Queue [] []) qFV = return $ qFV
getQFVM q qFV = getQDefM (headQ q) >>= (\x -> case x of
(Left fv) -> getQFVM (tailQ q) (enqueue fv qFV)
(Right cv) -> getQFVM (tailQ q) qFV)
-- Extract only closed terms from queue
getQCTM :: Queue (QDefName,QDefDef) -> Queue Qelm -> REPLStateIO (Queue Qelm)
getQCTM (Queue [] []) qCV = return $ qCV
getQCTM q qCV = getQDefM (headQ q) >>= (\x -> case x of
(Left fv) -> getQCTM (tailQ q) qCV
(Right cv) -> getQCTM (tailQ q) (enqueue cv qCV))
-- Extract only free variables that are defined from queue, non-monadic version
getQFV :: Queue (QDefName,QDefDef) -> Queue (CVnm,Type) -> (Queue (CVnm,Type))
getQFV (Queue [] []) qFV = qFV
getQFV q qFV = case getQDef (headQ q) of
(Left fv) -> getQFV (tailQ q) (enqueue fv qFV)
(Right cv) -> getQFV (tailQ q) qFV
-- Extract only closed terms from queue, non-monadic version
getQCT :: Queue (QDefName,QDefDef) -> Queue Qelm -> (Queue Qelm)
getQCT (Queue [] []) qCV = qCV
getQCT q qCV = case getQDef (headQ q) of
(Left fv) -> getQCT (tailQ q) qCV
(Right cv) -> getQCT (tailQ q) (enqueue cv qCV)
qToMap :: Queue (CVnm,Type) -> (M.Map CVnm Type)
qToMap q = foldl (\m (a,b) -> M.insert a b m) M.empty (toListQ q)
io :: IO a -> REPLStateIO a
io i = liftIO i
pop :: REPLStateIO (QDefName, QDefDef)
pop = get >>= return.headQ.snd
push :: (QDefName, QDefDef) -> REPLStateIO ()
push t = do
(f,q) <- get
put (f,(q `snoc` t))
set_wdir :: FilePath -> REPLStateIO ()
set_wdir wdir = do
(_,q) <- get
put (wdir,q)
-- unfoldDefsInTerm :: (Queue Qelm) -> CTerm -> CTerm
-- unfoldDefsInTerm q t =
-- let uq = toListQ $ unfoldQueue q
-- in substs uq t
-- unfoldQueue :: (Queue Qelm) -> (Queue Qelm)
-- unfoldQueue q = fixQ q emptyQ step
-- where
-- step :: (Name CTerm, CTerm) -> t -> Queue Qelm -> Queue Qelm
-- step e@(x,t) _ r = (mapQ (substDef x t) r) `snoc` e
-- where
-- substDef :: Name CTerm -> CTerm -> Qelm -> Qelm
-- substDef x t (y, t') = (y, subst x t t')
-- containsTerm :: Queue (QDefName,QDefDef) -> QDefName -> Bool
-- containsTerm (Queue [] []) _ = False
-- containsTerm q v = (containsTerm_Qelm (getQCT q emptyQ) v) || (containsTerm_QFV (getQFV q emptyQ) v)
-- containsTerm_Qelm :: Queue Qelm -> QDefName -> Bool
-- containsTerm_Qelm (Queue f r) v@(Var vnm) = ((foldl (\b (defName, defTerm)-> b || (vnm == defName)) False r) || (foldl (\b (defName, defTerm)-> b || (vnm == defName)) False f ))
-- containsTerm_Qelm (Queue f r) v@(DefName vnm) = ((foldl (\b (defName, defTerm)-> b || (vnm == defName)) False r) || (foldl (\b (defName, defTerm)-> b || (vnm == defName)) False f ))
-- containsTerm_QFV :: Queue (CVnm, Type) -> QDefName -> Bool
-- containsTerm_QFV (Queue f r) v@(Var vnm) = ((foldl (\b (defName, defTerm)-> b || (vnm == defName)) False r) || (foldl (\b (defName, defTerm)-> b || (vnm == defName)) False f ))
-- containsTerm_QFV (Queue f r) v@(DefName vnm) = ((foldl (\b (defName, defTerm)-> b || (vnm == defName)) False r) || (foldl (\b (defName, defTerm)-> b || (vnm == defName)) False f ))
-- tyCheckQ :: GFile -> REPLStateIO ()
-- tyCheckQ (Queue [] []) = return ()
-- tyCheckQ q = do
-- (f, defs') <- get
-- defs <- getQCTM defs' emptyQ
-- qfv <- getQFVM defs' emptyQ
-- let term'@(Def v ty t) = headQ q
-- -- Case split here as well before unfolding t
-- -- Unfold each term from queue and see if free variables exist
-- let tu = unfoldDefsInTerm defs t
-- let numFV = length (getFV tu)
-- if (numFV == 0)
-- -- TypeCheck term from Prog
-- then let r = runIR tu $ qToMap qfv
-- in case r of
-- Left err -> io.putStrLn.readTypeError $ err
-- -- Verify type from TypeChecker matches expected type from file
-- -- If it does, add to context (i.e. definition queue)
-- Right ity ->
-- do
-- case ity `isSubtype` ty of
-- Left er -> io.putStrLn.readTypeError $ er
-- Right b ->
-- if b
-- then do
-- -- Determine if definition already in queue
-- if(containsTerm defs' (Var v))
-- then io.putStrLn $ "Error: The variable "++(show v)++" is already in the context."
-- else do
-- push (Var v,DefTerm tu)
-- tyCheckQ $ tailQ q
-- else io.putStrLn $ "Error: "++(runPrettyType ity)++" is not a subtype of "++(runPrettyType ty)
-- else io.putStrLn $ "Error: free variables found in "++(show v)
handleCMD :: String -> REPLStateIO ()
handleCMD "" = return ()
handleCMD s =
case (parseLine s) of
Left msg -> io $ putStrLn msg
Right l -> undefined --handleLine l
where
-- handleLine (Eval t) = do
-- (f, defs') <- get
-- defs <- getQCTM defs' emptyQ
-- let tu = unfoldDefsInTerm defs t
-- r = eval tu
-- in case r of
-- Left m -> io.putStrLn.readTypeError $ m
-- Right e -> io.putStrLn.runPrettyCTerm $ e
-- handleLine (Let x t) = do
-- (f, defs') <- get
-- defs <- getQCTM defs' emptyQ
-- qfv <- getQFVM defs' emptyQ
-- io $ putStrLn "Place term in context"
-- let tu = unfoldDefsInTerm defs t
-- r = runIR tu $ qToMap qfv
-- in case r of
-- Left m -> io.putStrLn.readTypeError $ m
-- Right ty -> do
-- if(containsTerm defs' (Var x))
-- then io.putStrLn $ "error: The variable "++(show x)++" is already in the context."
-- else push (Var x,DefTerm t)
-- handleLine (TypeCheck t) = do
-- (_, defs') <- get
-- defs <- getQCTM defs' emptyQ
-- qfv <- getQFVM defs' emptyQ
-- let tu = unfoldDefsInTerm defs t
-- r = runIR tu $ qToMap qfv
-- in case r of
-- Left m -> io.putStrLn.readTypeError $ m
-- Right ty -> io.putStrLn.runPrettyType $ ty
-- handleLine (ShowAST t) = do
-- (_,defs') <- get
-- defs <- getQCTM defs' emptyQ
-- io.putStrLn.show $ unfoldDefsInTerm defs t
-- handleLine (Unfold t) = do
-- (f,defs') <- get
-- defs <- getQCTM defs' emptyQ
-- io.putStrLn.runPrettyCTerm $ unfoldDefsInTerm defs t
-- handleLine DumpState = get >>= io.print.(mapQ prettyDef).snd
prettyDef :: (QDefName, QDefDef) -> String
prettyDef elem = undefined
-- case getQDef elem of
-- Right (a, t) -> "let "++(n2s a)++" = "++(runPrettyCTerm t)
-- Left (a, ty ) -> (n2s a)++" : "++(runPrettyType ty)
getFV :: CTerm -> [CVnm]
getFV t = fv t :: [CVnm]
helpMenu :: String
helpMenu =
"-----------------------------------------------------------------------------------\n"++
" The "++agdaName++" Help Menu \n"++
"-----------------------------------------------------------------------------------\n"++
":help (:h) Display the help menu\n"++
":full (:f) Designates Full Linear Logic"++
":classic (:c) Designates Classic Linear Logic"++
":type term (:t) Typecheck a term\n"++
":show <term> (:s) Display the Abstract Syntax Type of a term\n"++
":unfold <term> (:u) Unfold the expression into one without toplevel definition.\n"++
":dump (:d) Display the context\n"++
"-----------------------------------------------------------------------------------"
main :: IO ()
main = do
evalStateT (runInputT defaultSettings loop) ("",emptyQ)
where
loop :: InputT REPLStateIO ()
loop = do
minput <- getInputLine $agdaName++"> "
case minput of
Nothing -> return ()
Just [] -> loop
Just input | input == ":q" || input == ":quit"
-> liftIO $ putStrLn ("Leaving "++agdaName) >> return ()
| input == ":h" || input == ":help"
-> (liftIO $ putStrLn helpMenu) >> loop
| otherwise -> (lift.handleCMD $ input) >> loop
|
heades/Agda-LLS
|
Source/ALL/Main.hs
|
bsd-3-clause
| 10,446 | 0 | 20 | 3,152 | 1,876 | 1,029 | 847 | 107 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.