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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-2015
-}
-- | Functions to computing the statistics reflective of the "size"
-- of a Core expression
module CoreStats (
-- * Expression and bindings size
coreBindsSize, exprSize,
CoreStats(..), coreBindsStats, exprStats,
) where
import GhcPrelude
import BasicTypes
import CoreSyn
import Outputable
import Coercion
import Var
import Type (Type, typeSize)
import Id (isJoinId)
data CoreStats = CS { cs_tm :: !Int -- Terms
, cs_ty :: !Int -- Types
, cs_co :: !Int -- Coercions
, cs_vb :: !Int -- Local value bindings
, cs_jb :: !Int } -- Local join bindings
instance Outputable CoreStats where
ppr (CS { cs_tm = i1, cs_ty = i2, cs_co = i3, cs_vb = i4, cs_jb = i5 })
= braces (sep [text "terms:" <+> intWithCommas i1 <> comma,
text "types:" <+> intWithCommas i2 <> comma,
text "coercions:" <+> intWithCommas i3 <> comma,
text "joins:" <+> intWithCommas i5 <> char '/' <>
intWithCommas (i4 + i5) ])
plusCS :: CoreStats -> CoreStats -> CoreStats
plusCS (CS { cs_tm = p1, cs_ty = q1, cs_co = r1, cs_vb = v1, cs_jb = j1 })
(CS { cs_tm = p2, cs_ty = q2, cs_co = r2, cs_vb = v2, cs_jb = j2 })
= CS { cs_tm = p1+p2, cs_ty = q1+q2, cs_co = r1+r2, cs_vb = v1+v2
, cs_jb = j1+j2 }
zeroCS, oneTM :: CoreStats
zeroCS = CS { cs_tm = 0, cs_ty = 0, cs_co = 0, cs_vb = 0, cs_jb = 0 }
oneTM = zeroCS { cs_tm = 1 }
sumCS :: (a -> CoreStats) -> [a] -> CoreStats
sumCS f = foldl' (\s a -> plusCS s (f a)) zeroCS
coreBindsStats :: [CoreBind] -> CoreStats
coreBindsStats = sumCS (bindStats TopLevel)
bindStats :: TopLevelFlag -> CoreBind -> CoreStats
bindStats top_lvl (NonRec v r) = bindingStats top_lvl v r
bindStats top_lvl (Rec prs) = sumCS (\(v,r) -> bindingStats top_lvl v r) prs
bindingStats :: TopLevelFlag -> Var -> CoreExpr -> CoreStats
bindingStats top_lvl v r = letBndrStats top_lvl v `plusCS` exprStats r
bndrStats :: Var -> CoreStats
bndrStats v = oneTM `plusCS` tyStats (varType v)
letBndrStats :: TopLevelFlag -> Var -> CoreStats
letBndrStats top_lvl v
| isTyVar v || isTopLevel top_lvl = bndrStats v
| isJoinId v = oneTM { cs_jb = 1 } `plusCS` ty_stats
| otherwise = oneTM { cs_vb = 1 } `plusCS` ty_stats
where
ty_stats = tyStats (varType v)
exprStats :: CoreExpr -> CoreStats
exprStats (Var {}) = oneTM
exprStats (Lit {}) = oneTM
exprStats (Type t) = tyStats t
exprStats (Coercion c) = coStats c
exprStats (App f a) = exprStats f `plusCS` exprStats a
exprStats (Lam b e) = bndrStats b `plusCS` exprStats e
exprStats (Let b e) = bindStats NotTopLevel b `plusCS` exprStats e
exprStats (Case e b _ as) = exprStats e `plusCS` bndrStats b
`plusCS` sumCS altStats as
exprStats (Cast e co) = coStats co `plusCS` exprStats e
exprStats (Tick _ e) = exprStats e
altStats :: CoreAlt -> CoreStats
altStats (_, bs, r) = altBndrStats bs `plusCS` exprStats r
altBndrStats :: [Var] -> CoreStats
-- Charge one for the alternative, not for each binder
altBndrStats vs = oneTM `plusCS` sumCS (tyStats . varType) vs
tyStats :: Type -> CoreStats
tyStats ty = zeroCS { cs_ty = typeSize ty }
coStats :: Coercion -> CoreStats
coStats co = zeroCS { cs_co = coercionSize co }
coreBindsSize :: [CoreBind] -> Int
-- We use coreBindStats for user printout
-- but this one is a quick and dirty basis for
-- the simplifier's tick limit
coreBindsSize bs = sum (map bindSize bs)
exprSize :: CoreExpr -> Int
-- ^ A measure of the size of the expressions, strictly greater than 0
-- Counts *leaves*, not internal nodes. Types and coercions are not counted.
exprSize (Var _) = 1
exprSize (Lit _) = 1
exprSize (App f a) = exprSize f + exprSize a
exprSize (Lam b e) = bndrSize b + exprSize e
exprSize (Let b e) = bindSize b + exprSize e
exprSize (Case e b _ as) = exprSize e + bndrSize b + 1 + sum (map altSize as)
exprSize (Cast e _) = 1 + exprSize e
exprSize (Tick n e) = tickSize n + exprSize e
exprSize (Type _) = 1
exprSize (Coercion _) = 1
tickSize :: Tickish Id -> Int
tickSize (ProfNote _ _ _) = 1
tickSize _ = 1
bndrSize :: Var -> Int
bndrSize _ = 1
bndrsSize :: [Var] -> Int
bndrsSize = sum . map bndrSize
bindSize :: CoreBind -> Int
bindSize (NonRec b e) = bndrSize b + exprSize e
bindSize (Rec prs) = sum (map pairSize prs)
pairSize :: (Var, CoreExpr) -> Int
pairSize (b,e) = bndrSize b + exprSize e
altSize :: CoreAlt -> Int
altSize (_,bs,e) = bndrsSize bs + exprSize e
|
sdiehl/ghc
|
compiler/coreSyn/CoreStats.hs
|
bsd-3-clause
| 4,766 | 0 | 13 | 1,245 | 1,684 | 899 | 785 | 105 | 1 |
-- quick and dirty size extraction from PNG files
-- see also http://www.w3.org/TR/PNG/
module Util.Png (pngSize) where
import Data.Binary.Get
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString as S
pngSize :: S.ByteString -> (Int, Int)
pngSize = runGet pngSize' . L.fromChunks . (:[])
pngSize' :: Get (Int, Int)
pngSize' = do
fileHeader
imgHeader
fileHeader :: Get ()
fileHeader = do
0x89504E47 <- getWord32be
0x0D0A1A0A <- getWord32be
return ()
imgHeader :: Get (Int, Int)
imgHeader = do
13 <- getWord32be
0x49484452 <- getWord32be
w <- getWord32be
h <- getWord32be
return (fromIntegral w, fromIntegral h)
|
Erdwolf/autotool-bonn
|
server/src/Util/Png.hs
|
gpl-2.0
| 679 | 0 | 9 | 139 | 204 | 110 | 94 | 22 | 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="ur-PK">
<title>SOAP Support Add-on</title>
<maps>
<homeID>soap</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_ur_PK/helpset_ur_PK.hs
|
apache-2.0
| 965 | 82 | 53 | 157 | 396 | 209 | 187 | -1 | -1 |
module WhereIn1 where
data Tree a = Leaf a | Branch (Tree a) (Tree a)
fringe_global x
= fringe x
where
fringe :: (Tree a) -> [a]
fringe (Leaf x) = [x]
fringe (Branch left right)
= case left of
left@(Leaf b_1) -> (fringe left) ++ (fringe right)
left@(Branch b_1 b_2)
-> (fringe left) ++ (fringe right)
fringe (Branch left right)
= (fringe left) ++ (fringe right)
|
kmate/HaRe
|
old/testing/introCase/WhereIn1AST.hs
|
bsd-3-clause
| 475 | 0 | 12 | 180 | 197 | 103 | 94 | 13 | 4 |
{-# LANGUAGE BangPatterns #-}
import System.Environment
import Control.Applicative
import Data.List
import Data.Ord
import qualified Data.Map as M
import qualified Data.ByteString.Char8 as S
import Data.ByteString.Internal
import Data.ByteString.Unsafe
import Foreign
main = do
f <- head <$> getArgs
x <- S.readFile f
let t = foldl' count M.empty (S.words x) :: M.Map S.ByteString Int
print . take 20 . sortBy (flip (comparing snd)) . M.toList $ t
count counts word = M.insertWith' (+) (word) 1 counts
------------------------------------------------------------------------
-- a different Ord
newtype OrdString = OrdString S.ByteString
deriving (Eq, Show)
instance Ord OrdString where
compare (OrdString p) (OrdString q) = compareBytes p q
compareBytes :: ByteString -> ByteString -> Ordering
compareBytes (PS fp1 off1 len1) (PS fp2 off2 len2)
| len1 == 0 && len2 == 0 = EQ -- short cut for empty strings
| fp1 == fp2 && off1 == off2 && len1 == len2 = EQ -- short cut for the same string
-- | max len1 len2 > 1 = inlinePerformIO $
| otherwise = inlinePerformIO $
withForeignPtr fp1 $ \p1 ->
withForeignPtr fp2 $ \p2 -> do
i <- memcmp (p1 `plusPtr` off1) (p2 `plusPtr` off2) (fromIntegral $ min len1 len2)
return $! case i `compare` 0 of
EQ -> len1 `compare` len2
x -> x
{-
| otherwise = inlinePerformIO $
withForeignPtr fp1 $ \p1 ->
withForeignPtr fp2 $ \p2 ->
cmp (p1 `plusPtr` off1)
(p2 `plusPtr` off2) 0 len1 len2
-}
-- XXX todo.
cmp :: Ptr Word8 -> Ptr Word8 -> Int -> Int -> Int-> IO Ordering
cmp p1 p2 n len1 len2
| n == len1 = if n == len2 then return EQ else return LT
| n == len2 = return GT
| otherwise = do
a <- peekByteOff p1 n :: IO Word8
b <- peekByteOff p2 n
case a `compare` b of
EQ -> cmp p1 p2 (n+1) len1 len2
LT -> return LT
GT -> return GT
|
meiersi/bytestring-builder
|
tests/Words.hs
|
bsd-3-clause
| 2,140 | 2 | 15 | 698 | 646 | 330 | 316 | 42 | 4 |
{-# OPTIONS_GHC -Wall #-}
module AST.Declaration where
import Data.Binary
import qualified AST.Expression.General as General
import qualified AST.Expression.Source as Source
import qualified AST.Expression.Valid as Valid
import qualified AST.Expression.Canonical as Canonical
import qualified AST.Type as Type
import qualified Reporting.Annotation as A
-- DECLARATIONS
data Declaration' port def tipe expr
= Definition def
| Datatype String [String] [(String, [tipe])]
| TypeAlias String [String] tipe
| Port port
| Fixity Assoc Int String
-- INFIX STUFF
data Assoc = L | N | R
deriving (Eq)
assocToString :: Assoc -> String
assocToString assoc =
case assoc of
L -> "left"
N -> "non"
R -> "right"
-- DECLARATION PHASES
type SourceDecl' =
Declaration' SourcePort Source.Def Type.Raw Source.Expr
data SourceDecl
= Comment String
| Decl (A.Located SourceDecl')
type ValidDecl =
A.Commented (Declaration' ValidPort Valid.Def Type.Raw Valid.Expr)
type CanonicalDecl =
A.Commented (Declaration' CanonicalPort Canonical.Def Type.Canonical Canonical.Expr)
-- PORTS
data SourcePort
= PortAnnotation String Type.Raw
| PortDefinition String Source.Expr
data ValidPort
= In String Type.Raw
| Out String Valid.Expr Type.Raw
newtype CanonicalPort
= CanonicalPort (General.PortImpl Canonical.Expr Type.Canonical)
validPortName :: ValidPort -> String
validPortName port =
case port of
In name _ -> name
Out name _ _ -> name
-- BINARY CONVERSION
instance Binary Assoc where
get =
do n <- getWord8
return $ case n of
0 -> L
1 -> N
2 -> R
_ -> error "Error reading valid associativity from serialized string"
put assoc =
putWord8 $
case assoc of
L -> 0
N -> 1
R -> 2
|
pairyo/elm-compiler
|
src/AST/Declaration.hs
|
bsd-3-clause
| 1,887 | 0 | 12 | 485 | 499 | 282 | 217 | 59 | 3 |
module T5665a where
import Language.Haskell.TH
doSomeTH s tp = return [NewtypeD [] n [] (NormalC n [(NotStrict, ConT tp)]) []]
where n = mkName s
|
urbanslug/ghc
|
testsuite/tests/th/T5665a.hs
|
bsd-3-clause
| 157 | 0 | 12 | 36 | 73 | 39 | 34 | 4 | 1 |
module Tut01 where
import Graphics.Rendering.OpenGL
import qualified Graphics.UI.GLUT as UT
import System.IO
import Data.IORef (newIORef, readIORef, writeIORef)
import Foreign.Ptr
import Foreign.C.Types
foreign import ccall unsafe float_mono_time :: IO Double
-- foreign import ccall unsafe glXGetCurrentDisplay :: IO (Ptr Evil)
-- foreign import ccall unsafe glXGetCurrentDrawable :: IO (Ptr Evil)
-- foreign import ccall unsafe glXSwapIntervalEXT :: Ptr Evil -> Ptr Evil -> CInt -> IO ()
-- data Evil
main = do (argv0, args) <- UT.getArgsAndInitialize
UT.initialWindowSize $= (UT.Size 800 600)
UT.initialDisplayMode $= [UT.RGBAMode,
UT.WithDepthBuffer,
UT.DoubleBuffered]
-- evil1 <- glXGetCurrentDisplay
-- evil2 <- glXGetCurrentDrawable
-- glXSwapIntervalEXT evil1 evil2 1
get UT.displayModePossible >>= (putStrLn . show)
w <- UT.createWindow "Bacon"
putStrLn (show w)
time_begin <- float_mono_time
stateR <- newIORef (0, time_begin)
[frag] <- genObjectNames 1
shaderSource frag $= [unlines [
"#version 330",
"out vec4 outputColor;",
"void main()",
"{",
" outputColor = vec4(1.0f, 1.0f, 1.0f, 1.0f);",
"}",
""]]
compileShader frag
get (shaderInfoLog frag) >>= putStrLn
True <- get (compileStatus frag)
[vert] <- genObjectNames 1
shaderSource vert $= [unlines [
"#version 330",
"layout(location = 0) in vec4 position;",
"void main()",
"{",
" gl_Position = position;",
"}",
""]]
compileShader vert
get (shaderInfoLog vert) >>= putStrLn
True <- get (compileStatus vert)
[prog] <- genObjectNames 1
attachedShaders prog $= ([vert], [frag])
linkProgram prog
get (programInfoLog prog) >>= putStrLn
True <- get (linkStatus prog)
UT.displayCallback $= (disp stateR prog)
-- UT.idleCallback $= Just (disp stateR)
UT.mainLoop
clamp x | x >= 0 && x <= 1 = x
| x > 1 = 1
| otherwise = 0
fmod p bound | p < bound = p
| otherwise = fmod (p - bound) bound
disp stateR prog = do
(phase_then, time_then) <- readIORef stateR
time_now <- float_mono_time
let phase_delta = time_now - time_then
let phase_now = (phase_then + phase_delta) `fmod` (2*pi)
writeIORef stateR (phase_now, time_now)
let i = realToFrac $ (1 + sin phase_now) / 2
clearColor $= (Color4 i i i 1)
clear [ColorBuffer]
putStrLn (show (1000 * phase_delta))
UT.swapBuffers
UT.postRedisplay Nothing
|
RichardBarrell/snippets
|
gltut/Tut01.hs
|
isc
| 2,864 | 0 | 14 | 944 | 739 | 369 | 370 | 66 | 1 |
module Y2021.M03.D30.Exercise where
import Data.List (isSuffixOf)
import System.Directory (listDirectory)
{--
Okay, today, we're going to list (presumably to operate on) certain kinds of
files in a directory. To do that we need to build a filter-function.
--}
filterer :: [String] -> FilePath -> Bool
filterer suffixes file = undefined
-- filterer returns True if file ends with one of the suffixes
-- with filterer, list the contents of this directory of files that end with
-- ".txt" or ".dat" (remember those good old days?) or ".hs"
sourceFiles :: FilePath -> IO [FilePath]
sourceFiles dir = undefined
|
geophf/1HaskellADay
|
exercises/HAD/Y2021/M03/D30/Exercise.hs
|
mit
| 613 | 0 | 7 | 103 | 81 | 48 | 33 | 7 | 1 |
module Zwerg.UI.GlyphMap where
import Zwerg.Prelude
import Zwerg.Data.Glyph
import Zwerg.Data.GridMap
import Zwerg.Util
type GlyphMap = GridMap GlyphMapCell
blankGlyphMap :: GlyphMap
blankGlyphMap = zBuild (const emptyCellData)
where emptyGlyph = Glyph ' ' (CellColor black $ Just black)
emptyCellData = GlyphMapCell False emptyGlyph emptyGlyph
glyphMapToRows :: GlyphMap -> [[GlyphMapCell]]
glyphMapToRows = chunksOf mapWidthINT . zElems
|
zmeadows/zwerg
|
lib/Zwerg/UI/GlyphMap.hs
|
mit
| 459 | 0 | 10 | 72 | 121 | 67 | 54 | 12 | 1 |
module Rebase.GHC.TypeNats
(
module GHC.TypeNats
)
where
import GHC.TypeNats
|
nikita-volkov/rebase
|
library/Rebase/GHC/TypeNats.hs
|
mit
| 80 | 0 | 5 | 12 | 20 | 13 | 7 | 4 | 0 |
data Weapon = PEASHOOTER
| HITCHSLAP
| OKAYCANNON
| DIRTYHARRY
| KILLMACHINE
deriving (Enum,Show)
data Engine = HAMSTERPOWER
| HERBIEPOWER
| PINTOPOWER
| BIGHONKINGENGINE
| ARNOLDPOWER
deriving (Enum,Show)
data HullStrength = PaperPlates
| TinFoil
| StayFast
| Elephunt
| Rhinoceros
deriving (Show,Enum)
data CargoSize = ShoeBox
| Closet
| Trunk
| Garage
| AllTheThings
deriving (Enum,Show)
data TankSize = DixieCup
| MudPuddle
| DayTrip
| Tanker
| NvrEmpty
deriving (Enum,Show)
-- the number is 68. can't go past
|
mlitchard/IX
|
spike/weapon_engine_cargo.hs
|
mit
| 889 | 0 | 6 | 453 | 152 | 91 | 61 | 30 | 0 |
{-# LANGUAGE TemplateHaskell, Rank2Types, FlexibleContexts #-}
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances, ConstraintKinds, MultiWayIf #-}
module Chimera.Engine.Core.Field where
import FreeGame
import FreeGame.Class (ButtonState(..))
import Control.Lens
import qualified Data.Vector as V
import qualified Data.Map as M
import qualified Data.IntMap.Strict as IM
import qualified Data.Foldable as F
import qualified Data.Traversable as T
import Data.Reflection
import Data.Default
import Data.Char (digitToInt)
import Chimera.State
import Chimera.Engine.Core.Util
import Chimera.Engine.Core.Types
data GroupFlag = GPlayer | GEnemy | None deriving (Eq, Show)
data ZIndex = Invisible | Background | OnObject | Foreground deriving (Eq, Show)
data StatePiece = Standby | Alive | Attack | Damaged | Dead deriving (Eq, Show)
data Piece = Piece {
_objectPiece :: Object,
_group :: GroupFlag,
_drawing :: Game (),
_statePiece :: StatePiece,
_scaleRate :: Double
}
data EffectPiece = EffectPiece {
_pieceEffect :: Piece,
_zIndex :: ZIndex,
_slowRate :: Int
}
data Chara = Chara {
_pieceChara :: Piece,
_hp :: Int,
_effectIndexes :: [Int]
}
data Player = Player {
_charaPlayer :: Chara,
_shotZ :: (Given Resource) => State Chara [Bullet],
_shotX :: (Given Resource) => State Chara [Bullet],
_bombCount :: Int,
_cshots :: [Bullet]
}
data Field = Field {
_player :: Player,
_enemies :: IM.IntMap Enemy,
_bullets :: IM.IntMap Bullet,
_effects :: IM.IntMap Effect,
_counterF :: Int,
_isDebug :: Bool,
_danmakuTitle :: String,
_sceneEffects :: [Int]
}
type Danmaku c = LookAt c Field
type Component a = Autonomie (Danmaku a) a
type Bullet = Component Piece
type Enemy = Component Chara
type Effect = Component EffectPiece
makeClassy ''Chara
makeClassy ''Piece
makeClassy ''EffectPiece
makeLenses ''Player
makeLenses ''Field
type EnemyLike c = (HasObject c, HasChara c, HasPiece c)
instance HasObject Piece where object = objectPiece
instance HasPiece Chara where piece = pieceChara
instance HasObject Chara where object = piece . object
instance HasPiece EffectPiece where piece = pieceEffect
instance HasObject EffectPiece where object = piece . object
instance HasChara Player where chara = charaPlayer
instance HasPiece Player where piece = charaPlayer . piece
instance HasObject Player where object = charaPlayer . object
instance HasObject Bullet where object = auto . object
instance HasPiece Bullet where piece = auto
instance HasObject Enemy where object = auto . object
instance HasPiece Enemy where piece = auto . piece
instance HasChara Enemy where chara = auto
instance HasObject Effect where object = auto . object
instance HasPiece Effect where piece = auto . piece
instance HasEffectPiece Effect where effectPiece = auto
instance Default Piece where
def = Piece def None (return ()) Standby 1.0
instance Default EffectPiece where
def = EffectPiece def Background 3
instance Default Chara where
def = Chara def 10 []
instance Default Player where
def = Player {
_charaPlayer =
pos .~ V2 320 420 $
speed .~ 2.5 $
size .~ V2 5 5 $
hp .~ 10 $
def,
_shotZ = error "uninitialized shotZ",
_shotX = error "uninitialized shotX",
_bombCount = error "uninitialized bombCount",
_cshots = []
}
instance Default Field where
def = Field def IM.empty IM.empty IM.empty 0 False "" [] where
instance GUIClass Player where
update = do
counter %= (+1)
use spXY >>= \sp -> pos += sp
spXY .= 0
pos %= clamp
dir <- keyStates_ >>= \keys -> return $ sum $ [v | (k,v) <-
[(KeyUp, V2 0 (-1)),(KeyDown, V2 0 1),(KeyRight,V2 1 0),(KeyLeft,V2 (-1) 0)],
case keys M.! k of Press -> True; _ -> False]
shift <- (||) <$> keyPress KeyLeftShift <*> keyPress KeyRightShift
s <- use speed
spXY .= case shift of
True -> (0.5 * s) *^ (dir :: Vec2)
False -> s *^ dir
addBullet
where
addBullet = do
cnt <- use counter
cshots .= []
z <- keyPress (charToKey 'Z')
when (z && cnt `mod` 10 == 0) $ do
s <- use shotZ
p <- use charaPlayer
cshots .= evalState s p
n <- use bombCount
x <- keyPress (charToKey 'X')
when (x && cnt `mod` 20 == 0 && n > 0) $ do
s <- use shotX
p <- use charaPlayer
cshots .= evalState s p
bombCount -= 1
paint = do
p <- get
let resource = given :: Resource
draw $ translate (p^.pos) $ bitmap $ (resource^.charaImg) V.! 0
instance (HasPiece (Component a), HasObject (Component a)) =>
GUIClass (Component a) where
update = do
r <- use speed
t <- use ang
pos += rotate2 (V2 r 0) t
sp <- use spXY
pos += sp
counter += 1
let config = given :: Config
use pos >>= \p -> unless (p `isInside` (config^.validArea)) $ do
use statePiece >>= \s -> when (s /= Standby) $ do
statePiece .= Dead
paint = do
b <- get
V2 x y <- use size
case x /= y of
True -> lift $ translate (b^.pos) $
scale (V2 (b^.scaleRate) (b^.scaleRate)) $ rotateR (b^.ang + pi/2) $ b^.drawing
False -> lift $ translate (b^.pos) $
scale (V2 (b^.scaleRate) (b^.scaleRate)) $ b^.drawing
instance GUIClass Field where
update = do
counterF += 1
danmakuTitle .= ""
collideObj
deadEnemyEffects
damagedEffects
scanAutonomies enemies
scanAutonomies bullets
scanAutonomies effects
enemies <=~ T.mapM (\x -> lift . execStateT update $! x) . IM.filter (\p -> p^.statePiece /= Dead)
bullets <=~ T.mapM (\x -> lift . execStateT update $! x) . IM.filter (\p -> p^.statePiece /= Dead)
effects <=~ T.mapM (\x -> lift . execStateT update $! x) . IM.filter (\p -> p^.statePiece /= Dead)
player <=~ \x -> lift . execStateT update $! x
cs <- use (player.cshots)
bullets %= insertsIM' cs
where
deadEnemyEffects = do
ds <- IM.filter (\p -> p^.statePiece == Dead) `fmap` use enemies
F.forM_ ds $ \e -> do
effects %= insertIM (effEnemyDead $ e^.pos)
F.forM_ (e^.effectIndexes) $ \i ->
effects %= IM.adjust (execState $ statePiece .= Dead) i
damagedEffects = do
p <- use player
when (p^.statePiece == Damaged) $
effects %= insertIM (effPlayerDead $ p^.pos)
player %= (statePiece .~ Attack)
paint = do
drawEffs Background
drawObj
drawEffs OnObject
translate (V2 320 240) . bitmap $ resource ^. board
drawMessages
drawEffs Foreground
use danmakuTitle >>= \t -> when (t /= "") drawTitle
use isDebug >>= \m -> when m $ debugging
where
resource = given :: Resource
drawObj = do
_ <- lift . execStateT paint =<< use player
F.mapM_ (\x -> lift . execStateT paint $! x) =<< use bullets
F.mapM_ (\x -> lift . execStateT paint $! x) =<< use enemies
drawEffs z = do
F.mapM_ (\x -> lift . execStateT paint $! x) . IM.filter (\r -> r^.zIndex == z)
=<< use effects
debugging = do
F.mapM_ (\b -> color blue . polygon $
boxVertexRotated (b^.pos) (b^.size) (b^.ang)) =<< use bullets
_ <- (\p -> color yellow . polygon $
boxVertex (p^.pos) (p^.size)) =<< use player
F.mapM_ (\e -> color green . polygon $
boxVertex (e^.pos) (e^.size)) =<< use enemies
drawMessages = do
let ls = resource ^. labels
lift $ translate (V2 430 30) $ ls M.! "fps"
drawScore 30 =<< getFPS
lift $ translate (V2 430 50) $ ls M.! "score"
drawScore 50 =<< use counterF
lift $ translate (V2 430 70) $ ls M.! "hiscore"
drawScore 70 (0 :: Int)
lift $ translate (V2 430 90) $ ls M.! "hp"
drawScore 90 =<< use (player.hp)
lift $ translate (V2 430 170) $ ls M.! "bullets"
drawScore 170 . IM.size =<< use bullets
lift $ translate (V2 430 190) $ ls M.! "enemies"
drawScore 190 . IM.size =<< use enemies
lift $ translate (V2 430 210) $ ls M.! "effects"
drawScore 210 . IM.size =<< use effects
drawScore y sc = do
forM_ (zip (show $ maximum [sc, 0]) [1..]) $ \(n, i) ->
when (n /= '-') $
lift $ translate (V2 (550 + i*13) y) $ (resource^.numbers) V.! digitToInt n
drawTitle = do
translate (V2 40 30) . text (resource^.font) 10 =<< use danmakuTitle
clamp :: (Given Config) => Vec2 -> Vec2
clamp (V2 x y) = V2 (edgeX x) (edgeY y)
where
config = given :: Config
Box (V2 areaLeft areaTop) (V2 areaRight areaBottom) = config ^. gameArea
edgeX = (\p -> bool p areaLeft (p < areaLeft)) .
(\p -> bool p areaRight (p > areaRight))
edgeY = (\p -> bool p areaTop (p < areaTop)) .
(\p -> bool p areaBottom (p > areaBottom))
scanAutonomies :: (Monad m) => Lens' Field (IM.IntMap (Component a)) -> StateT Field m ()
scanAutonomies member = do
put =<< liftM2 (IM.foldrWithKey' iter) get (use member)
put =<< liftM2 (IM.foldr' iter2) get (use member)
where
iter k a f = let (aut,_) = execState (a^.runAuto) (a^.auto,f) in
f & member %~ IM.adjust (auto .~ aut) k
iter2 a f = let (_,f') = execState (a^.runAuto) (a^.auto,f) in f'
collide :: (HasObject c, HasObject b) => c -> b -> Bool
collide oc ob = let oc' = extend oc; ob' = extend ob; in
detect ob' oc' || detect oc' ob'
where
extend :: (HasObject c) => c -> c
extend x = x & size -~ V2 (x^.speed) 0 + (x^.spXY)
detect :: (HasObject c, HasObject c') => c -> c' -> Bool
detect a b =
let V2 w' h' = a^.size
r = \v -> rotate2 v $ a^.ang in
or [(a^.pos) `isIn` b,
(a^.pos + r (V2 w' h' )) `isIn` b,
(a^.pos + r (V2 (-w') h' )) `isIn` b,
(a^.pos + r (V2 w' (-h'))) `isIn` b,
(a^.pos + r (V2 (-w') (-h'))) `isIn` b]
isIn :: (HasObject c) => Vec2 -> c -> Bool
isIn p box = isInCentoredBox (p-box^.pos) where
isInCentoredBox :: Vec2 -> Bool
isInCentoredBox p' = let V2 px' py' = p' `rotate2` (-box^.ang) in
abs px' < (box^.size^._x)/2 && abs py' < (box^.size^._y)/2
makeBullet :: (Given Resource, HasPiece c, HasObject c) => BKind -> BColor -> c -> c
makeBullet bk bc b = let resource = given :: Resource in b
& size .~ (resource^.areaBullet) bk & group .~ GEnemy & statePiece .~ Alive
& drawing .~ (bitmap $ (resource^.bulletImg) V.! (fromEnum bk) V.! (fromEnum bc))
collideObj :: (Given Resource, Monad m) => StateT Field m ()
collideObj = do
es <- use enemies
bs <- use bullets
let (es',bs') = collides GPlayer es bs
enemies .= es'
p <- use player
let (p',bs'') = collideTo GEnemy p bs'
player .= p'
bullets .= bs''
where
collides :: (EnemyLike e) =>
GroupFlag -> IM.IntMap e -> IM.IntMap Bullet -> (IM.IntMap e, IM.IntMap Bullet)
collides flag es bs = IM.foldrWithKey' f (es,bs) es where
f k e (xs,ys) = let (e',ys') = collideTo flag e ys in (IM.insert k (hpCheck e') xs,ys')
hpCheck x = if (x^.hp) <= 0 then x & statePiece .~ Dead else x
collideTo :: (EnemyLike e) =>
GroupFlag -> e -> IM.IntMap Bullet -> (e, IM.IntMap Bullet)
collideTo flag e bs = IM.foldrWithKey' f (e,bs) bs where
f k b (x,ys) = if (b^.group) == flag && collide e b
then (x & hp -~ 1 & statePiece %~ if flag == GEnemy then const Damaged else id, IM.adjust (statePiece .~ Dead) k ys)
else (x,ys)
effPlayerDead :: (Given Resource) => Vec2 -> Effect
effPlayerDead = go . effCommonAnimated 1 where
go :: Effect -> Effect
go e = e & size .~ V2 0.8 0.8 & slowRate .~ 5 & runAuto %~ (>> (zoom self $ size *= 1.01))
effEnemyDead :: (Given Resource) => Vec2 -> Effect
effEnemyDead = effCommonAnimated 0
effCommonAnimated :: (Given Resource) => Int -> Vec2 -> Effect
effCommonAnimated k p = def & pos .~ p & zIndex .~ OnObject & runAuto .~ run where
run :: Danmaku EffectPiece ()
run = zoom self $ do
let resource = given :: Resource
i <- liftM2 div (use counter) (use slowRate)
drawing .= (bitmap $ (resource^.effectImg) V.! k V.! i)
when (i == V.length ((resource^.effectImg) V.! k)) $ statePiece .= Dead
|
myuon/Chimera
|
Chimera/Engine/Core/Field.hs
|
mit
| 12,399 | 0 | 20 | 3,353 | 5,233 | 2,674 | 2,559 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
module Stastics where
import Data.Heap
import Data.Maybe (fromJust)
import qualified Data.Vector.Unboxed as U
import Graphics.EasyPlot
import Statistics.LinearRegression
-- Moving/Running Mean
-- convert raw data to Double
clean raw = map (\s -> read s :: Double) (lines raw)
-- Calculate moving average -- hardcoded smoothening factor = 0.95
avg :: [Double] -> Double
avg xs = case xs of
(x:xs) -> a * x + (1 - a) * (avg xs)
[] -> 0
where a = 0.95
movingMean = do
rawInput <- readFile "numbers.txt"
let input = avg . clean $ rawInput
print input
-- Calculating a Moving Median
strToInt raw = map (\s -> read s :: Int) (lines raw)
-- put smaller nums in maxheap and big nums in minheap
median (x:xs) maxheap minheap = case viewHead maxheap of
Just theMax -> if x < theMax
then median xs (insert x maxheap) minheap
else median xs maxheap (insert x minheap)
Nothing -> median xs (insert x maxheap) minheap
median [] maxheap minheap
| size maxheap + 1 < size minheap =
median [] (insert minelem maxheap) $ (snd.fromJust.view) minheap
| size minheap + 1 < size maxheap =
median [] ((snd.fromJust.view) maxheap) $ insert maxelem minheap
| size maxheap == size minheap =
(fromIntegral maxelem + fromIntegral minelem) / 2.0
| size maxheap > size minheap = fromIntegral maxelem
| otherwise = fromIntegral minelem
where
maxelem = fromJust (viewHead maxheap)
minelem = fromJust (viewHead minheap)
movingMedian = do
raw <- readFile "numbers.txt"
let input = strToInt raw
print $ median input (empty :: MaxHeap Int) (empty :: MinHeap Int)
-- APPROXIMATING A LINEAR REGRESSION
linearR =do
let xs = U.fromList [1.0, 2.0, 3.0, 4.0, 5.0] :: U.Vector Double
let ys = U.fromList [1.0, 2.0, 1.3, 3.75, 2.25] :: U.Vector Double
let (b,m) = linearRegression xs ys
print $ concat ["y = ", show m, " x + ", show b]
--
main = do
let values = [4,5,16,15,14,13,13,17]
let values2 = [2,5,7,10,21, 18, 15]
-- plot X11 $
-- Data2D [ Title "Line Graph"
-- , Style Linespoints
-- , Color Blue]
-- [] (zip [1..] values)
-- plot X11 $ [ Data2D [Color Red] [] (zip [1..] values)
-- , Data2D [Color Blue] [] (zip [1..] values2) ]
-- 3D
-- plot' [Interactive] X11
-- [ Data3D [Color Red] [] [(1,1,1), (1,2,1), (0,1,1), (1,1,0)]
-- , Data3D [Color Blue] [] [(4,3,2), (3,3,2), (3,2,3), (4,4,3)] ]
-- regression
let winEstimate = map (\x -> x * 0.425 + 0.7850000000000001) [1.3, 2.4 .. 4.7]
let regressionLine = zip [1.3, 2.4 .. 4.7] winEstimate
plot X11 [Data2D [Title "Runs Per Game VS Win % in 2014" ] [] (zip [1.0, 2.0, 3.0, 4.0, 5.0] [1.0, 2.0, 1.3, 3.75, 2.25]), Data2D [Title "Regression Line", Style Lines, Color Blue] [] regressionLine]
|
alokpndy/haskell-learn
|
src/dataScience/stastics.hs
|
mit
| 3,084 | 0 | 14 | 907 | 963 | 503 | 460 | 49 | 3 |
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module Main where
import Data.ByteString (ByteString)
import Data.Conduit
import Data.Conduit.Binary (sourceHandle, sinkHandle)
import Data.Conduit.List as CL
import Data.CSV.Conduit
import Data.Text (Text)
import System.Environment
import System.IO (stdout, stdin, Handle, openFile, IOMode(..))
import Options.Applicative
import Control.Applicative
process :: Monad m => Conduit (Row Text) m (Row Text)
process = CL.map id
data Conf = Conf {
delimiter :: Char
, source :: String
}
main :: IO ()
main = do
Conf{..} <- execParser opts
let outCSVSettings = CSVSettings delimiter Nothing
source' <- case source of
"-" -> return stdin
f -> openFile f ReadMode
runResourceT $
transformCSV' defCSVSettings
outCSVSettings
(sourceHandle source')
process
(sinkHandle stdout)
opts = info (helper <*> parseOpts)
(fullDesc
<> progDesc "Converts CSV to DSV format"
<> header "csv2dsv"
<> footer "See https://github.com/danchoi/csv2dsv for more information.")
parseOpts :: Parser Conf
parseOpts = Conf
<$> (Prelude.head <$>
strOption (value "\t"
<> short 'd'
<> long "delimiter"
<> metavar "CHAR"
<> help "Delimiter characters. Defaults to \\t."))
<*> strArgument (metavar "FILE" <> help "Source CSV file. '-' for STDIN")
{-
https://hackage.haskell.org/package/conduit-extra
https://hackage.haskell.org/package/conduit-extra-1.1.9.2/docs/Data-Conduit-Binary.html
https://hackage.haskell.org/package/conduit
http://hackage.haskell.org/package/csv-conduit
-}
|
danchoi/csv2dsv
|
Main.hs
|
mit
| 1,775 | 0 | 15 | 459 | 392 | 206 | 186 | 44 | 2 |
{- |
- Module : CYK
- Description : CYK algorithm
- Copyright : (c) Maciej Bendkowski
-
- Maintainer : [email protected]
- Stability : experimental
-}
module CYK where
import Data.Array
import Data.List
import Data.Set (Set)
import qualified Data.Set as Set
type Symbol = Char
type Rule = String
-- | Chomsky normal form productions,
-- i.e. A -> BC or A -> x
data Production =
NonTerminal Rule (Rule, Rule) -- Production: A -> BC
| Terminal Rule Symbol -- Production A -> b
-- | Opaques the given string into a
-- non-terminal representation
opaque :: String -> String
opaque s = "{" ++ s ++ "}"
instance Show Production where
show (NonTerminal s (r, l)) = opaque s ++ " -> " ++ opaque r ++ opaque l
show (Terminal s t) = opaque s ++ " -> " ++ [t]
-- | Returns the LHS of a production
productionLHS :: Production -> Rule
productionLHS (NonTerminal rule _) = rule
productionLHS (Terminal rule _) = rule
-- | Returns whether the given production
-- is a terminal production or not
isTerminal :: Production -> Bool
isTerminal (Terminal _ _) = True
isTerminal _ = False
-- | Returns whether the given production
-- is a non-terminal production
isNonTerminal :: Production -> Bool
isNonTerminal = not . isTerminal
-- | Returns whether the given production
-- generates the symbol s or not
producesSymbol :: Symbol -> Production -> Bool
producesSymbol s (Terminal _ t) = t == s
producesSymbol _ _ = False
-- | Returns whether the given production
-- generates the rule pair or not
producesRule :: (Rule,Rule) -> Production -> Bool
producesRule (b,c) (NonTerminal _ (b',c')) = b' == b && c' == c
producesRule _ _ = False
type Productions = [Production]
type AWord = Array Int Symbol
type Rules = Set Rule
-- | Context-free grammar in Chomsky normal form
data Grammar = Grammar {
startRule :: Rule,
productions :: Productions
}
instance Show Grammar where
show g = show' g "" where
show' g = (("start: " ++ startRule g) ++) . prods (productions g)
prods :: [Production] -> ShowS
prods = foldr (\x -> (.) (('\n' : show x) ++)) ("" ++)
-- | Returns the number of productions
-- in the given context-free grammar
size :: Grammar -> Int
size = length . productions
type CYKMatrix = Array (Int, Int) Rules
-- | Computes the CYK matrix for the given
-- production list and input word of size n
cykMatrix :: Productions -> AWord -> Int -> CYKMatrix
cykMatrix productions word n = matrix where
-- filters all terminal productions
terminalProductions :: Productions
terminalProductions = filter isTerminal productions
-- filters all non-terminal productions
nonTerminalProductions :: Productions
nonTerminalProductions = filter isNonTerminal productions
matrix = array ((1,1), (n,n)) $
[((i,i), Set.fromList $ map productionLHS $ terminalRules (word ! i)) | i <- [1..n]] ++
[((i,i+h-1), induction i h) | h <- [2..n], i <- [1..(n-h+1)]] where
-- returns all terminals productions generating s
terminalRules :: Symbol -> Productions
terminalRules s = filter (producesSymbol s) terminalProductions
-- returns all non-terminals productions generating both rules
nonTerminalRules :: (Rule, Rule) -> Productions
nonTerminalRules p = filter (producesRule p) nonTerminalProductions
-- main CYK induction step
induction :: Int -> Int -> Rules
induction i h = Set.fromList $ concat rs where
rs = [map productionLHS $ nonTerminalRules (b,c)
| j <- [1..h-1], b <- Set.toList (matrix ! (i,i+j-1)),
c <- Set.toList (matrix ! (i+j, i+h-1))]
-- | CYK parsing algorithm returns whether
-- the given grammar generates the input string
cyk :: Grammar -> String -> Bool
cyk cnfg s = start `Set.member` (matrix ! (1,n)) where
n = length s
w = array (1,n) $ zip [1..n] s
matrix = cykMatrix (productions cnfg) w n
start = startRule cnfg
|
maciej-bendkowski/blaz
|
src/CYK.hs
|
mit
| 4,488 | 0 | 19 | 1,415 | 1,136 | 628 | 508 | 67 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.DOMSettableTokenList
(js__get, _get, js_setValue, setValue, js_getValue, getValue,
DOMSettableTokenList, castToDOMSettableTokenList,
gTypeDOMSettableTokenList)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"_get\"]($2)" js__get ::
DOMSettableTokenList -> Word -> IO (Nullable JSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMSettableTokenList._get Mozilla DOMSettableTokenList._get documentation>
_get ::
(MonadIO m, FromJSString result) =>
DOMSettableTokenList -> Word -> m (Maybe result)
_get self index
= liftIO (fromMaybeJSString <$> (js__get (self) index))
foreign import javascript unsafe "$1[\"value\"] = $2;" js_setValue
:: DOMSettableTokenList -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMSettableTokenList.value Mozilla DOMSettableTokenList.value documentation>
setValue ::
(MonadIO m, ToJSString val) => DOMSettableTokenList -> val -> m ()
setValue self val = liftIO (js_setValue (self) (toJSString val))
foreign import javascript unsafe "$1[\"value\"]" js_getValue ::
DOMSettableTokenList -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/DOMSettableTokenList.value Mozilla DOMSettableTokenList.value documentation>
getValue ::
(MonadIO m, FromJSString result) =>
DOMSettableTokenList -> m result
getValue self = liftIO (fromJSString <$> (js_getValue (self)))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/DOMSettableTokenList.hs
|
mit
| 2,306 | 22 | 10 | 317 | 570 | 340 | 230 | 37 | 1 |
module Google.Cloud
( Handle
, createHandle, mkHandle
, Cloud
, evalCloud
) where
import Control.Concurrent.STM
import Network.HTTP.Client (Manager, newManager)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Google.Cloud.Internal.Types
import Google.Cloud.Internal.Token
-- | Create a new 'Handle' with sensible defaults. The defaults are such that
-- the 'Handle' works out of the box when the application is running on an
-- instance in the Google cloud.
createHandle :: IO Handle
createHandle = do
manager <- newManager tlsManagerSettings
mkHandle manager defaultMetadataToken
-- | Create a new 'Handle' with your own configuration options.
mkHandle :: Manager -> Cloud Token -> IO Handle
mkHandle manager fetchToken = do
token <- newTVarIO Nothing
return $ Handle manager token fetchToken
|
wereHamster/google-cloud
|
src/Google/Cloud.hs
|
mit
| 858 | 0 | 8 | 163 | 157 | 88 | 69 | 18 | 1 |
module Web.Slack.Types
( module Web.Slack.Types.Base
, module Web.Slack.Types.Bot
, module Web.Slack.Types.Channel
, module Web.Slack.Types.ChannelOpt
, module Web.Slack.Types.Comment
, module Web.Slack.Types.Error
, module Web.Slack.Types.Event
, module Web.Slack.Types.Event.Subtype
, module Web.Slack.Types.File
, module Web.Slack.Types.IM
, module Web.Slack.Types.Id
, module Web.Slack.Types.Item
, module Web.Slack.Types.Message
, module Web.Slack.Types.Preferences
, module Web.Slack.Types.Presence
, module Web.Slack.Types.Self
, module Web.Slack.Types.Session
, module Web.Slack.Types.Team
, module Web.Slack.Types.TeamPreferences
, module Web.Slack.Types.Time
, module Web.Slack.Types.Topic
, module Web.Slack.Types.User
) where
import Web.Slack.Types.Base
import Web.Slack.Types.Bot
import Web.Slack.Types.Channel
import Web.Slack.Types.ChannelOpt
import Web.Slack.Types.Comment
import Web.Slack.Types.Error
import Web.Slack.Types.Event
import Web.Slack.Types.Event.Subtype
import Web.Slack.Types.File
import Web.Slack.Types.IM
import Web.Slack.Types.Id
import Web.Slack.Types.Item
import Web.Slack.Types.Message
import Web.Slack.Types.Preferences
import Web.Slack.Types.Presence
import Web.Slack.Types.Self
import Web.Slack.Types.Session
import Web.Slack.Types.Team
import Web.Slack.Types.TeamPreferences
import Web.Slack.Types.Time
import Web.Slack.Types.Topic
import Web.Slack.Types.User
|
mpickering/slack-api
|
src/Web/Slack/Types.hs
|
mit
| 1,494 | 0 | 5 | 207 | 341 | 250 | 91 | 45 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.BitSet.Dynamic
-- Copyright : (c) Sergei Lebedev, Aleksey Kladov, Fedor Gogolev 2013
-- Based on Data.BitSet (c) Denis Bueno 2008-2009
-- License : MIT
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- A space-efficient implementation of set data structure for enumerated
-- data types.
module Data.BitSet ( module Data.BitSet.Dynamic ) where
import Data.BitSet.Dynamic
|
lambda-llama/bitset
|
src/Data/BitSet.hs
|
mit
| 549 | 0 | 5 | 102 | 33 | 26 | 7 | 2 | 0 |
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Control.Monad.Except
import Data.Either.Combinators
import System.IO
import Types
import Parse
import Eval
flushStr :: String -> IO ()
flushStr s = putStr s >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushStr prompt >> getLine
evalString :: Env -> String -> IO (Either LispError LispVal)
evalString env = runExceptT . (eval env <=< readExpr)
evalToString :: Env -> String -> IO String
evalToString env = fmap (uneither . mapBoth show show) . evalString env
uneither :: Either a a -> a
uneither (Left x) = x
uneither (Right x) = x
evalAndPrint :: Env -> String -> IO ()
evalAndPrint env = putStrLn <=< evalToString env
repl :: Env -> IO ()
repl env = do
expr <- readPrompt "Lisp>>> "
case expr of "quit" -> return ()
_ -> evalAndPrint env expr >> repl env
main :: IO ()
main = repl =<< primitiveBindings
|
ublubu/wyascheme
|
src/Main.hs
|
mit
| 920 | 0 | 11 | 186 | 344 | 172 | 172 | 28 | 2 |
module Core (module MusicTheory, blackNotes, chordsWithNotes,
chordsWithExactNotes, toPitch, fromPitch, noteToCOFAngle,
scalesWithNotes, guessScales, majorChordTypes, minorChordTypes,
isMajorChord) where
import Data.Maybe
import qualified Data.List as L
import qualified Data.Map as M
import qualified Sound.MIDI.Message as Msg
import Sound.MIDI.Message.Channel (T (Cons), messageBody, Body (Voice))
import qualified Sound.MIDI.Message.Channel.Voice as V
import MusicTheory
blackNotes = [C',D',F',G',A']
noteToCOFAngle n = fromIntegral (fromJust $ L.elemIndex n (circleOfFifths C)) * 30.0
chordsWithNotes :: [Note] -> [Chord]
chordsWithNotes [] = []
chordsWithNotes ns =
[ chord |
n <- [minBound..],
t <- [minBound..],
let chord = Chord n t,
all (inChord chord) ns]
chordsWithExactNotes :: [Note] -> [Chord]
chordsWithExactNotes ns =
[ chord |
chord <- chordsWithNotes ns,
null $ notes chord L.\\ ns]
scalesWithNotes :: [Note] -> [Scale]
scalesWithNotes ns =
[ scale |
n <- [minBound..],
t <- [minBound..],
let scale = Scale n t,
all (`elem` notes scale) ns && null (notes scale L.\\ ns)]
guessScales :: [Note] -> [Scale]
guessScales ns = scalesWithNotes mostFrequentlyPlayedNotes
where mostFrequentlyPlayedNotes = snd (foldUntil enough aggregate (0, []) $ sortedHistogram ns)
foldUntil crit act = foldl (\x y -> if crit x then x else act x y)
aggregate (s, notes) (cnt, n) = (s + cnt, n : notes)
enough (s, _) = s >= (length ns - 5)
sortedHistogram :: [Note] -> [(Int, Note)]
sortedHistogram xs = L.sortBy compareFst [ (length l, head l) | l <- L.group (L.sort xs) ]
where compareFst (f1,_) (f2,_) = compare f2 f1
-- | Converts a Pitch to a Note as defined in MusicTheory
fromPitch :: V.Pitch -> Note
fromPitch p = toEnum (V.fromPitch p `mod` fromEnum PerfectOctave)
toPitch :: Note -> V.Pitch
toPitch k = V.toPitch (fromEnum k)
majorChordTypes = [Major, Major7th, Dominant7th]
minorChordTypes = [Minor, Minor7th]
isMajorChord (Chord _ mode) = mode `elem` majorChordTypes
{-
import qualified Data.Set as S
import qualified Data.List as L
import qualified Data.Map as M
import Data.Maybe
import qualified Sound.MIDI.Message as Msg
import Sound.MIDI.Message.Channel (T (Cons), messageBody, Body (Voice))
import qualified Sound.MIDI.Message.Channel.Voice as V
type Interval = Int
type ScaleIntervals = [Interval]
type ChordIntervals = [Interval]
data Key = C | Db | D | Eb | E | F | Gb | G | Ab | A | Bb | B
deriving (Show, Eq, Ord, Enum)
-- Intervals
unison = 0 :: Interval
semitone = 1 :: Interval
minor_second = 1 :: Interval
wholetone = 2 :: Interval
major_second = 2 :: Interval
minor_third = 3 :: Interval
major_third = 4 :: Interval
perfect_fourth = 5 :: Interval
tritone = 6 :: Interval
raised_fourth = 6 :: Interval
perfect_fifth = 7 :: Interval
minor_sixth = 8 :: Interval
major_sixth = 9 :: Interval
minor_seventh = 10 :: Interval
major_seventh = 11 :: Interval
octave = 12 :: Interval
nineth = 13 :: Interval
-- Modes
scales :: M.Map String ScaleIntervals
scales = M.fromList [
("major", [2,2,1,2,2,2,1]),
("dorian", [2,1,2,2,2,1,2]),
("phrygian", [1,2,2,2,1,2,2]),
("minor", [2,1,2,2,1,2,2]),
("blues", [3,2,1,1,3,2]),
("chromatic", take 12 $ repeat semitone),
("whole tone", take 6 $ repeat wholetone)
]
-- Chords
chords :: M.Map String ChordIntervals
chords = M.fromList [
("maj", [unison, major_third, perfect_fifth]),
("6", [unison, major_third, perfect_fifth, major_sixth]),
("7", [unison, major_third, perfect_fifth, minor_seventh]),
("maj7", [unison, major_third, perfect_fifth, major_seventh]),
("m", [unison, minor_third, perfect_fifth]),
("m6", [unison, minor_third, perfect_fifth, major_sixth]),
("m7", [unison, minor_third, perfect_fifth, minor_seventh]),
("m9", [unison, minor_third, minor_seventh, 14]),
("m9'", [unison, minor_third, perfect_fifth, minor_seventh, 14]),
("dim", [unison, minor_third, tritone]),
("dim7", [unison, minor_third, tritone, major_sixth]),
("add9", [unison, major_third, perfect_fifth, 14]),
("aug", [unison, major_third, minor_sixth]),
("sus2", [unison, wholetone, perfect_fifth]),
("sus4", [unison, perfect_fourth, perfect_fifth])
]
--}
|
lordi/jazzmate
|
src/Core.hs
|
gpl-2.0
| 4,595 | 0 | 12 | 1,082 | 795 | 445 | 350 | 49 | 2 |
-- -*-haskell-*-
-- ** @configure_input@ **
-- ===========================================================================
-- C -> Haskell Compiler: configuration
--
-- Author : Manuel M T Chakravarty
-- Created: 27 September 99
--
-- Copyright (c) [1999..2005] Manuel M T Chakravarty
--
-- This file is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This file is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
--- DESCRIPTION ---------------------------------------------------------------
--
-- Configuration options; largely set by `configure'.
--
--- TODO ----------------------------------------------------------------------
--
module C2HS.Config (
--
-- programs and paths
--
cpp, cppopts, libfname, hpaths,
--
-- parameters of the targeted C compiler
--
PlatformSpec(..), defaultPlatformSpec, platformSpecDB
) where
import Foreign (toBool)
import Foreign.C (CInt)
import System.Info (arch, os)
-- program settings
-- ----------------
-- | C preprocessor executable
--
cpp :: FilePath
cpp = case os of
"darwin" -> "gcc"
_ -> "cpp"
-- | C preprocessor options
--
-- * `-x c' forces CPP to regard the input as C code; this option seems to be
-- understood at least on Linux, FreeBSD, and Solaris and seems to make a
-- difference over the default language setting on FreeBSD
--
-- * @-P@ would suppress @#line@ directives
--
cppopts :: [String]
cppopts = case (os,cpp) of
-- why is gcc different between all these platforms?
("openbsd","cpp") -> ["-xc"]
(_,"cpp") -> ["-x", "c"]
(_,"gcc") -> ["-E", "-x", "c"]
_ -> []
-- | C2HS Library file name
--
libfname :: FilePath
libfname = "C2HS.hs"
-- | Standard system search paths for header files
--
hpaths :: [FilePath]
hpaths = [".", "/usr/include", "/usr/local/include"]
-- parameters of the targeted C compiler
-- -------------------------------------
-- | Parameters that characterise implementation-dependent features of the
-- targeted C compiler
--
data PlatformSpec = PlatformSpec {
identPS :: String, -- platform identifier
bitfieldDirectionPS :: Int, -- to fill bitfields
bitfieldPaddingPS :: Bool, -- padding or split?
bitfieldIntSignedPS :: Bool, -- `int' signed bitf.?
bitfieldAlignmentPS :: Int -- alignment constraint
}
instance Show PlatformSpec where
show (PlatformSpec ident dir pad intSig align) =
show ident ++ " <" ++ show dir ++ ", " ++ show pad ++ ", " ++
show intSig ++ ", " ++ show align ++ ">"
-- | Platform specification for the C compiler used to compile c2hs (which is
-- the default target).
--
defaultPlatformSpec :: PlatformSpec
defaultPlatformSpec = PlatformSpec {
identPS = arch ++ "-" ++ os,
bitfieldDirectionPS = bitfieldDirection,
bitfieldPaddingPS = bitfieldPadding,
bitfieldIntSignedPS = bitfieldIntSigned,
bitfieldAlignmentPS = bitfieldAlignment
}
-- | The set of platform specification that may be choosen for cross compiling
-- bindings.
--
platformSpecDB :: [PlatformSpec]
platformSpecDB =
[
PlatformSpec {
identPS = "x86_64-linux",
bitfieldDirectionPS = 1,
bitfieldPaddingPS = True,
bitfieldIntSignedPS = True,
bitfieldAlignmentPS = 1
},
PlatformSpec {
identPS = "i686-linux",
bitfieldDirectionPS = 1,
bitfieldPaddingPS = True,
bitfieldIntSignedPS = True,
bitfieldAlignmentPS = 1
},
PlatformSpec {
identPS = "m68k-palmos",
bitfieldDirectionPS = -1,
bitfieldPaddingPS = True,
bitfieldIntSignedPS = True,
bitfieldAlignmentPS = 1
}
]
-- | indicates in which direction the C compiler fills bitfields
--
-- * the value is 1 or -1, depending on whether the direction is growing
-- towards the MSB
--
bitfieldDirection :: Int
bitfieldDirection = fromIntegral bitfield_direction
foreign import ccall "config.h" bitfield_direction :: CInt
-- | indicates whether a bitfield that does not fit into a partially filled
-- storage unit in its entirety introduce padding or split over two storage
-- units
--
-- * 'True' means that such a bitfield introduces padding (instead of being
-- split)
--
bitfieldPadding :: Bool
bitfieldPadding = toBool bitfield_padding
foreign import ccall "config.h" bitfield_padding :: CInt
-- | indicates whether a bitfield of type `int' is signed in the targeted C
-- compiler
--
bitfieldIntSigned :: Bool
bitfieldIntSigned = toBool bitfield_int_signed
foreign import ccall "config.h" bitfield_int_signed :: CInt
-- | the alignment constraint for a bitfield
--
-- * this makes the assumption that the alignment of a bitfield is independent
-- of the bitfield's size
--
bitfieldAlignment :: Int
bitfieldAlignment = fromIntegral bitfield_alignment
foreign import ccall "config.h" bitfield_alignment :: CInt
|
jrockway/c2hs
|
src/C2HS/Config.hs
|
gpl-2.0
| 5,563 | 0 | 15 | 1,402 | 682 | 439 | 243 | 70 | 4 |
module Shapes where
import System.IO.Unsafe
import Data.Array.ST
import Data.Array.MArray
import Data.Array
-- oh my goodness, I can't remember the last time I used mutable arrays but here we go
-- I think that using mutable arrays will probably be better than
import Control.Monad.ST
import Control.Monad.Random
import Data.List
type Height = Int
type Width = Int
type FPoint = (Float,Float)
type Point = (Int,Int)
type Thickness = Float
type Color = (Int,Int,Int)
debugPrint a = unsafePerformIO $ print a >> return a
{-
Here's the preliminary DSL for making the kinds of shapes I want.
I'm still arguing with myself on the semantics and it's all a bit silly.
Ellipses are a bit obvious, with needing to specify their major and minor axes as well as the foci
Arcs are circular arcs with their radius, origin and the radians of the arc specified
Vertical means that the two shapes should be stacked top then bottom
Horizontal means that they should be left and right next to each other
On means that the images should be layered within the same space
Region gives scales for horizontal and vertical relative to the space.
-}
{-
Okay, note to self, what we need to do is have a scale of (-1,1) on the x and y-axis for the internal representation of the shapes and then we can map it onto actual regions later with proper scaling. Will this work? I don't know but it seems reasonable to someone who hasn't thought very long about this.
Now, you might ask "why have this intermmediate DSL to begin with?" ehh basically because I want to do cute things with random instances and that sort of thing
-}
data Shape = Arc Float FPoint Float Float Thickness
| Line FPoint FPoint Thickness -- <-- ^ relative points
| Vertical Shape Shape
| Horizontal Shape Shape
| On Shape Shape -- layer shapes onto one region
| Region Float Float Shape -- scaling another shape to fit a region
| Empty
deriving (Eq,Show, Ord)
mirrorH :: Shape -> Shape
mirrorH (On s1 s2) = On (mirrorH s1) (mirrorH s2)
mirrorH (Vertical s1 s2) = Vertical (mirrorH s1) (mirrorH s2)
mirrorH (Horizontal s1 s2) = Vertical (mirrorH s2) (mirrorH s1)
mirrorH (Region x y s) = Region x y (mirrorH s)
mirrorH (Line (fx1,fy1) (fx2, fy2) t) = Line (1-fx2,fy2) (1-fx1, fy1) t
mirrorH (Arc r (x,y) th1 th2 t) = Arc r (1-x,y) (pi - th2) (pi - th1) t
mirrorH Empty = Empty
mirrorPairH :: Shape -> Shape
mirrorPairH s = s `Horizontal` (mirrorH s)
mirrorV :: Shape -> Shape
mirrorV (On s1 s2) = On (mirrorV s1) (mirrorV s2)
mirrorV (Vertical s1 s2) = Vertical (mirrorV s2) (mirrorV s1)
mirrorV (Horizontal s1 s2) = Horizontal (mirrorV s1) (mirrorV s2)
mirrorV (Region x y s) = Region x y (mirrorV s)
mirrorV (Line (fx1,fy1) (fx2,fy2) t) = Line (fx1, 1-fy2) (fx2, 1-fy1) t
mirrorV (Arc r (x,y) th1 th2 t) = Arc r (x,1-y) (2*pi - th2) (2*pi - th1) t
mirrorV Empty = Empty
mirrorPairV :: Shape -> Shape
mirrorPairV s = s `Vertical` (mirrorV s)
shapeToInt :: Shape -> Int
shapeToInt (Arc _ _ _ _ _) = 0
shapeToInt (Line _ _ _) = 1
shapeToInt (Vertical _ _) = 2
shapeToInt (Horizontal _ _) = 3
shapeToInt (On _ _) = 4
shapeToInt (Region _ _ _) = 5
shapeToInt Empty = 6
instance Random Shape where
randomR (s1,s2) g = let (i,g') = randomR (shape1, shape2) g
shape1 = shapeToInt s1
shape2 = shapeToInt s2
in case i of
0 -> let (radius, g2) = randomR (0,1) g'
(x1, g3) = randomR (0,1) g2
(y1, g4) = randomR (0,1) g3
(rad1, g5) = randomR (0,1) g4
(rad2, g6) = randomR (0,1) g5
(t, g7) = randomR (0.01,0.1) g6
in (Arc radius (x1,y1) rad1 rad2 t,g7)
1 -> let (x1,g2) = randomR (0,1) g'
(y1,g3) = randomR (0,1) g2
(x2,g4) = randomR (0,1) g3
(y2,g5) = randomR (0,1) g4
(t,g6) = randomR (0.01,0.1) g5
in (Line (x1,y1) (x2,y2) t, g6)
2 -> let (sh1,g2) = randomR (s1,s2) g'
(sh2,g3) = randomR (s1,s2) g2
in (Vertical sh1 sh2, g3)
3 -> let (sh1, g2) = randomR (s1,s2) g'
(sh2, g3) = randomR (s1,s2) g2
in (Horizontal sh1 sh2, g3)
4 -> let (sh1, g2) = randomR (s1,s2) g'
(sh2, g3) = randomR (s1,s2) g2
in (On sh1 sh2, g3)
5 -> let (x, g2) = randomR (0,1) g'
(y, g3) = randomR (0,1) g2
(sh, g4) = randomR (s1,s2) g3
in (Region x y sh, g4)
6 -> (Empty, g')
random g = randomR (Arc undefined undefined undefined undefined undefined,
Region undefined undefined undefined) g
randcircle :: RandomGen g => Thickness -> Float -> Float -> Rand g Shape
randcircle t minR maxR = do
x <- getRandomR (0,1)
y <- getRandomR (0,1)
r <- getRandomR (minR, maxR)
return $ Arc r (x,y) (0 :: Float) (2*pi) t
randarc :: RandomGen g => Thickness -> Float -> Float -> Rand g Shape
randarc t minR maxR = do
x <- getRandomR (0,1)
y <- getRandomR (0,1)
r <- getRandomR (minR, maxR)
th1 <- getRandomR (0,2*pi)
th2 <- getRandomR (th1,2*pi)
return $ Arc r (x,y) th1 th2 t
circle :: Float -> Float -> Float -> Float -> Shape
circle x y r t = Arc r (x,y) 0 (2*pi) t
square :: Float -> Float -> Float -> Float -> Shape
square x y side t = side1 `On` (side2 `On` (side3 `On` side4))
where side1 = Line (x,y) (x + side, y) t
side2 = Line (x + side, y) (x + side, y + side) t
side3 = Line (x, y) (x, y + side) t
side4 = Line (x, y + side) (x + side, y + side) t
randSquare :: RandomGen g => Float -> Rand g Shape
randSquare t = do
x <- getRandomR (0,1)
y <- getRandomR (0,1)
s <- getRandomR (0,1)
return $ square x y s t
triangle :: FPoint -> FPoint -> FPoint -> Thickness -> Shape
triangle p1 p2 p3 t = side1 `On` (side2 `On` side3)
where side1 = Line p1 p2 t
side2 = Line p1 p3 t
side3 = Line p2 p3 t
randPoint :: RandomGen g => Rand g FPoint
randPoint = do
x <- getRandomR (0,1)
y <- getRandomR (0,1)
return (x,y)
randTriangle :: RandomGen g => Thickness -> Rand g Shape
randTriangle t = do
p1 <- randPoint
p2 <- randPoint
p3 <- randPoint
return $ triangle p1 p2 p3 t
randLine :: RandomGen g => Thickness -> Rand g Shape
randLine t = do
p1 <- randPoint
p2 <- randPoint
return $ Line p1 p2 t
randConnective :: RandomGen g => Rand g (Shape -> Shape -> Shape)
randConnective = do
c <- getRandomR (1 :: Int,3)
case c of
1 -> return On
2 -> return Vertical
3 -> return Horizontal
{-
Let's figure out how lines are going to work:
Now, let's assume that the FPoints tell us how far to the right and up to set things
The range is going to be (0,0) to (1,1)
with (0,0) being the bottom left corner,
(1,0) is the bottom right corner
(0,1) is the top left corner
(1,1) is the top right corner
if the region for a line covers points (x1, x2, y1, y2) (with x1 < x2, y1 < y2)
then the regional coordinates are given, as a function of rx and ry (relative coords),
x = x1 + (x2 - x1)*rx
y = y1 + (y2 - y1)*ry
we also have that the slope of the line is going to be given by
(fy2 - fy1)/(fx2 - fx1)
so the set of regional points is going to be given by taking small steps to create an actual
set of integral points (and then reducing out the duplicates) so how small do we need?
Well if we have the equations of the line be
x = x1 + fx1*(x2 - x1) + (x2 - x1)*(fx2 - fx1)*t
y = y1 + fy1*(y2 - y1) + (y2 - y1)*(fy2 - fy1)*t
now I think that's right because if we assume that fx2-fx1 = 0 then
the x-coordinate will be locked in as x1 + fx1*(x2 - x1)
if fy2 - fy1 = 0 then the y-coordinate will be locked in as y1 + fy1*(y2 - y1)
so I think I've got these equations right. Now we just need to figure out what the
actual fine-grainedness for t should be. It needs to go from 0 to 1 and we could be
adaptive in the partioning but instead let's just set it at 1000 elements
so then what we'll have as the code for all of this will be
xs = map $ (round . (\ t -> ...)) $ [0..1000]
ys = map $ (round . (\ t -> ...)) $ [0..1000]
Arc's are going to be similar:
x = x1 + fx1*(x2 - x1) + r*cos (radd * t + rad1)
y = y1 + fy1*(y2 - y1) + r*sin (radd * t + rad1)
-}
timesteps :: [Float]
timesteps = map (\t -> fromIntegral t / 1000) [0..1000]
tSteps :: Int
tSteps = 10
safefilter :: [(Int,Int)] -> Int -> Int -> Int -> Int -> [(Int,Int)]
safefilter ps x1 y1 x2 y2 = filter (\(x,y) -> x >= x1 && x <= x2 && y >= y1 && y <= y2) ps
renderFloat :: Shape -> [(Float,Float)]
renderFloat (Vertical s1 s2) = (map (\(x,y) -> (x,0.5 * y)) $ renderFloat s1)
++ (map (\(x,y) -> (x,0.5*y + 0.5)) $ renderFloat s2)
renderFloat (Horizontal s1 s2) = (map (\(x,y) -> (0.5 * x,y)) $ renderFloat s1)
++ (map (\(x,y) -> (0.5 * x + 0.5,y)) $ renderFloat s2)
renderFloat (On s1 s2) = renderFloat s1 ++ renderFloat s2
renderFloat (Region xs ys s) = map (\(x,y) -> (x*xs,y*ys)) $ renderFloat s
renderFloat (Line (x1,y1) (x2,y2) t) = thickness t $ map (\s -> (x1 + xd*s, y1 + yd*s)) timesteps
where xd = x2 - x1
yd = y2 - y1
renderFloat (Arc r (x,y) th1 th2 t) = thickness t $ map (\s -> (x + r * (cos $ thf s),
y + r * (sin $ thf s))) timesteps
where thd = th2 - th1
thf s = (th2 - th1)*s + th1
renderFloat Empty = []
-- this is a bit of a hack but I'm not sure how to do it better
thickness :: Float -> [(Float,Float)] -> [(Float,Float)]
thickness t ps = concat ps'
where ps' = do
xt <- [-tSteps..tSteps]
yt <- [-tSteps..tSteps]
return $ map (\(x,y) -> (x + (fromIntegral xt / (fromIntegral tSteps)) * t,
y + (fromIntegral yt / (fromIntegral tSteps)) * t)) ps
floatToArray :: [(Float,Float)] -> STArray s (Int,Int) Color -> (Int,Int,Int,Int) -> ST s ()
floatToArray ps a (x1,x2,y1,y2) = mapM_ (\p -> writeArray a p (0,0,0)) $ nub ps''
where ps'' = safefilter ps' x1 y1 x2 y2
dx = fromIntegral $ x2 - x1
dy = fromIntegral $ y2 - y1
x1' = fromIntegral x1
y1' = fromIntegral y1
ps' = map (\(fx,fy) -> (round $ x1' + fx*dx, round $ y1' + fy*dy)) ps
render :: Shape -> STArray s (Int,Int) Color -> (Int,Int,Int,Int) -> ST s ()
render s a ds = floatToArray (renderFloat s) a ds
runRender :: Shape -> Int -> Int -> Array (Int,Int) Color
runRender s xsize ysize = runSTArray (runRender' s xsize ysize)
runRender' :: Shape -> Int -> Int -> ST s (STArray s (Int,Int) Color)
runRender' s xsize ysize = do
a <- newArray ((-xsize `div` 2,-ysize `div` 2),
(xsize `div` 2, ysize `div` 2)) (1,1,1)
render s a (-xsize `div` 2, xsize `div` 2, -ysize `div` 2, ysize `div` 2)
return a
printArray :: (Show a) => Array (Int,Int) a -> String
printArray arr = unlines $ [concat $ row i | i <- [negy..y]]
where ((negx,negy),(x,y)) = bounds arr
row i = [ show $ arr ! (rx,i) | rx <- [negx..x] ]
outputArray :: Array (Int,Int) Color -> IO ()
outputArray arr = putStrLn $ printArray $ fmap aux arr
where aux (0,0,0) = '0'
aux (1,1,1) = '1'
renderTest1 :: IO ()
renderTest1 = do
let l = Line (0,0) (1,1) 0.1
arr = runRender l 10 10
outputArray arr
renderTest2 :: IO ()
renderTest2 = do
let l1 = Line (0,0) (1,1) 0.1
l2 = Line (0,1) (1,0) 0.1
arr = runRender (l1 `On` l2) 10 10
outputArray arr
renderTest3 :: IO ()
renderTest3 = do
let l = Line (0,0) (1,1) 0.1
arr = runRender (l `Vertical` l) 10 10
outputArray arr
renderTest4 = do
let l = Line (0,0) (1,1) 0.1
arr = runRender (l `Horizontal` l) 10 10
outputArray arr
renderTest5 = do
let t = triangle (0,0) (0.5,1) (1,0) 0.1
arr = runRender t 10 10
outputArray arr
renderTest6 = do
let s = square 0 0 0.5 0.1
arr = runRender s 10 10
outputArray arr
renderTest7 r = do
let c = circle 0.5 0.5 r 0.1
arr = runRender c 20 20
outputArray arr
|
clarissalittler/randomimages
|
Shapes.hs
|
gpl-2.0
| 12,932 | 0 | 19 | 4,134 | 4,667 | 2,487 | 2,180 | 227 | 3 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module SnakeRender where
import Control.Applicative
import Linear.V2
import Game.Graphics hiding (loadFont, sprite)
import Game.Folivora.Utils
import Game.Folivora.TileGrid
import Game.Folivora.Render
import Game.Folivora.Wires
import World
import Game
data SnakeTextures = SnakeTextures
{ getRedSquare :: Image
, getGreenSquare :: Image
, getNormalFont :: Font
}
instance Loadable SnakeTextures where
load = do
etex <- loadTexture Standard Linear "tiles-16x16.png"
let tex = either error id etex
font <- loadFont "LiberationMono-Regular.ttf"
return SnakeTextures
{ getRedSquare = sprite (V2 0 0) (V2 16 16) tex
, getGreenSquare = sprite (V2 16 0) (V2 16 16) tex
, getNormalFont = font
}
instance Renderable SnakeWorld SnakeTextures where
renderGfx texs world = translate (V2 16 16)
*> renderedTable
where
renderedTable = renderTable (V2 16 16) (\c -> case c of
TileSnake _ -> redSquare
TileFood -> greenSquare
_ -> empty)
(getTC . getTable $ world)
redSquare = translate (V2 8 8) *> getRedSquare texs
greenSquare = translate (V2 8 8) *> getGreenSquare texs
instance Renderable Game SnakeTextures where
renderGfx texs state = renderGui <|> renderWorld
where
renderGui =
case mode state of
NotStarted -> translate (V2 300 290) *>
drawText font "Press [space] to (re)start"
Playing -> empty
Paused -> translate (V2 300 290) *>
drawText font "Press [space] to continue"
renderWorld =
case getData state of
Right w -> renderGfx texs w
Left _ -> empty
font = getNormalFont texs
|
caryoscelus/folivora-ge
|
demos/snake/SnakeRender.hs
|
gpl-3.0
| 2,211 | 0 | 14 | 860 | 499 | 258 | 241 | 50 | 0 |
{-# LANGUAGE NoImplicitPrelude #-}
module Lamdu.Infer.Internal.Scheme
( makeScheme
, instantiateWithRenames
, instantiate
, generalize
, applyRenames
) where
import Prelude.Compat
import Control.Lens.Operators
import Control.Monad (liftM)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Lamdu.Expr.Constraints (Constraints)
import qualified Lamdu.Expr.Constraints as Constraints
import Lamdu.Expr.Scheme (Scheme(..))
import qualified Lamdu.Expr.Scheme as Scheme
import Lamdu.Expr.Type (Type)
import qualified Lamdu.Expr.Type as T
import Lamdu.Expr.TypeVars (TypeVars(..))
import qualified Lamdu.Expr.TypeVars as TV
import Lamdu.Infer.Internal.Monad (InferCtx)
import qualified Lamdu.Infer.Internal.Monad as M
import Lamdu.Infer.Internal.Scope (SkolemScope)
import qualified Lamdu.Infer.Internal.Subst as Subst
{-# INLINE makeScheme #-}
makeScheme :: M.Context -> Type -> Scheme
makeScheme = Scheme.make . M._constraints . M._ctxResults
{-# INLINE mkInstantiateSubstPart #-}
mkInstantiateSubstPart ::
(M.VarKind t, Monad m) => SkolemScope -> String -> Set (T.Var t) -> InferCtx m (Map (T.Var t) (T.Var t))
mkInstantiateSubstPart skolemScope prefix =
liftM Map.fromList . mapM f . Set.toList
where
f oldVar =
do
freshVarExpr <- M.freshInferredVarName skolemScope prefix
return (oldVar, freshVarExpr)
generalize :: TypeVars -> Constraints -> Type -> Scheme
generalize outerTVs innerConstraints innerType =
Scheme tvs (Constraints.intersect tvs innerConstraints) innerType
where
tvs = TV.free innerType `TV.difference` outerTVs
{-# INLINE instantiateWithRenames #-}
instantiateWithRenames :: Monad m => SkolemScope -> Scheme -> InferCtx m (TV.Renames, Type)
instantiateWithRenames skolemScope (Scheme (TypeVars tv rv sv) constraints t) =
do
typeVarSubsts <- mkInstantiateSubstPart skolemScope "i" tv
recordSubsts <- mkInstantiateSubstPart skolemScope "k" rv
sumSubsts <- mkInstantiateSubstPart skolemScope "s" sv
let renames = TV.Renames typeVarSubsts recordSubsts sumSubsts
let subst = Subst.fromRenames renames
constraints' = Constraints.applyRenames renames constraints
-- Avoid tell for these new constraints, because they refer to
-- fresh variables, no need to apply the ordinary expensive
-- and error-emitting tell
M.Infer $ M.ctxResults . M.constraints <>= constraints'
return (renames, Subst.apply subst t)
{-# INLINE instantiate #-}
instantiate :: Monad m => SkolemScope -> Scheme -> InferCtx m Type
instantiate skolemScope scheme = liftM snd (instantiateWithRenames skolemScope scheme)
{-# INLINE applyRenames #-}
applyRenames :: TV.Renames -> Scheme -> Scheme
applyRenames renames (Scheme forAll constraints typ) =
Scheme
(TV.applyRenames renames forAll)
(Constraints.applyRenames renames constraints)
(Subst.apply (Subst.fromRenames renames) typ)
|
da-x/Algorithm-W-Step-By-Step
|
Lamdu/Infer/Internal/Scheme.hs
|
gpl-3.0
| 3,160 | 0 | 14 | 672 | 778 | 428 | 350 | -1 | -1 |
module EZID.ANVL
( ANVL
, encode
, parse
) where
import Control.Applicative ((<|>))
import qualified Data.Attoparsec.ByteString.Char8 as P
import Data.Bits (shiftL, (.|.))
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Builder.Prim as BP
import Data.ByteString.Internal (c2w)
import Data.Char (isHexDigit, digitToInt)
import Data.Monoid ((<>))
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Data.Word (Word8)
type ANVL = [(T.Text, T.Text)]
charEscaped :: Bool -> BP.BoundedPrim Word8
charEscaped colon =
BP.condB (\c -> c == c2w '%' || (colon && c == c2w ':') || c < c2w ' ')
(BP.liftFixedToBounded $ (,) '%' BP.>$< BP.char8 BP.>*< BP.word8HexFixed)
(BP.liftFixedToBounded BP.word8)
encode :: ANVL -> B.Builder
encode = foldMap $ \(n,v) ->
TE.encodeUtf8BuilderEscaped (charEscaped True) n <> B.char8 ':' <> B.char8 ' ' <> TE.encodeUtf8BuilderEscaped (charEscaped False) v <> B.char8 '\n'
parse :: P.Parser ANVL
parse = P.sepBy nv P.endOfLine <* P.skipSpace
where
hd = digitToInt <$> P.satisfy isHexDigit
pe = P.char '%' >> (.|.) . (`shiftL` 4) <$> hd <*> hd
textWhile1 p = either (fail . show) return . TE.decodeUtf8' =<< P.takeWhile1 p
tx d = mconcat <$> P.many' (textWhile1 (`notElem` '%':d) <|> (T.singleton . toEnum <$> pe))
nv = do
n <- tx ":\n" P.<?> "name"
_ <- P.char ':'
P.skipMany (P.char ' ')
v <- tx "\n" P.<?> "value"
return (n, v)
|
databrary/databrary
|
src/EZID/ANVL.hs
|
agpl-3.0
| 1,468 | 0 | 14 | 271 | 601 | 330 | 271 | 36 | 1 |
{- Copyright 2014 David Farrell <[email protected]>
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-}
{-# LANGUAGE LambdaCase #-}
module IRCD.Helper where
import qualified Data.IntMap as IM
import Control.Monad.State
import System.IO (hPutStrLn)
import IRCD.Types
import IRCD.Env
import IRCD.Clients
checkClient :: Int -> State Env (Maybe Client)
checkClient uid' = do
uids <- gets (byUid . envClients)
return (IM.lookup uid' uids)
checkClientRegistered :: Int -> State Env (Maybe Bool)
checkClientRegistered uid' = checkClient uid' >>= return . \case
Nothing -> Nothing
Just client' -> Just (registered client')
updateClient :: (Client -> Client) -> Int -> State Env ()
updateClient f uid' = do
checkClient uid' >>= modify . mapEnvClients . \case
Nothing -> insertClient (f (defaultClient uid'))
Just client' -> replaceClient client' (f client')
updateClientNick :: String -> Int -> State Env ()
updateClientNick nick' = updateClient (\c -> c {nick=Just nick'})
updateClientUser :: String -> Int -> State Env ()
updateClientUser user' = updateClient (\c -> c {user=Just user'})
updateClientRealName :: String -> Int -> State Env ()
updateClientRealName realname = updateClient (\c -> c {realName=Just realname})
updateClientRegistered :: Bool -> Int -> State Env ()
updateClientRegistered r = updateClient (\c -> c {registered=r})
reply_ :: Source -> String -> StateT Env IO ()
reply_ (ClientSrc client) msg = case handle client of
Nothing -> return ()
Just h -> liftIO (hPutStrLn h msg)
|
shockkolate/lambdircd
|
src/IRCD/Helper.hs
|
apache-2.0
| 2,048 | 0 | 15 | 371 | 544 | 277 | 267 | 33 | 2 |
module Palindromes.A249641 (a249641) where
import Helpers.PalindromeCounter (countPalindromes)
a249641 :: Int -> Integer
a249641 n = a249641_list !! n
a249641_list :: [Integer]
a249641_list = countPalindromes 8
|
peterokagey/haskellOEIS
|
src/Palindromes/A249641.hs
|
apache-2.0
| 213 | 0 | 5 | 27 | 58 | 33 | 25 | 6 | 1 |
module CCO.TypeCheck (
typeCheck,
typeCheckATerm
) where
import CCO.Component (component, printer, Component)
import CCO.Tree (parser, ATerm, Tree (fromTree, toTree))
import CCO.TypeCheck.AG
import qualified CCO.TypeCheck.Util as T
import CCO.Feedback (errorMessage, Feedback)
import CCO.Printing (text)
import Control.Arrow (Arrow (arr), (>>>))
typeCheck' :: Diag -> Feedback Diag
typeCheck' d = case sem_Diag d of
T.Error e -> errorMessage $ text e
_ -> return d
typeCheck :: Component String String
typeCheck = parser >>> typeCheckATerm >>> printer
typeCheckATerm :: Component ATerm ATerm
typeCheckATerm = component toTree >>> component typeCheck' >>> arr fromTree
|
aochagavia/CompilerConstruction
|
tdiagrams/lib/CCO/TypeCheck.hs
|
apache-2.0
| 722 | 0 | 9 | 143 | 218 | 124 | 94 | 18 | 2 |
{-# LANGUAGE BangPatterns #-}
module Data.HaskID
( encode
, decode
, init_haskid
, opts
, haskid
, HaskID
, HashOptions (opt_salt, opt_alphabet, opt_min_length)
) where
import qualified Data.Vector.Unboxed as Vec
import Data.Vector.Unboxed (Vector)
import Data.Vector.Unboxed.Mutable (swap)
import Control.Monad.ST (runST)
import Data.Char (ord, chr)
import Data.List (mapAccumL, (\\), nub, intersect)
import Data.Maybe (fromJust)
data HaskID
= HaskID
{ h_alphabet :: Vector Int
, h_separators :: Vector Int
, h_min_hash_length :: Int
, h_salt :: Vector Int
, h_guards :: Vector Int
}
deriving Show
data HashOptions = HashOptions
{ opt_salt :: String
, opt_alphabet :: String
, opt_separators :: String
, opt_min_length :: Int
, opt_min_alpha_length :: Int
, opt_separator_ratio :: Double
, opt_guard_ratio :: Double
}
deriving Show
-- | Default Hashid options.
opts :: HashOptions
opts = HashOptions
{ opt_salt = ""
, opt_alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234\
\567890"
, opt_separators = "cfhistuCFHISTU"
, opt_min_length = 0
, opt_min_alpha_length = 16
, opt_separator_ratio = 3.5
, opt_guard_ratio = 12
}
haskid :: HaskID
Right haskid = init_haskid opts
init_haskid :: HashOptions -> Either String HaskID
init_haskid (HashOptions salt alpha sep minlen minalphalen sepratio gratio)
| length (nub alpha) < minalphalen = Left "alphabet must be 16+ unique characters."
| otherwise = Right $ HaskID avec sepvec (max 0 minlen) saltvec gvec
where
(avec, sepvec, gvec) = uncurry process2 . process1 $ map ord alpha
saltvec = Vec.fromList $ map ord salt
process1 as
| some > 0 = (Vec.drop some alf, sep' Vec.++ Vec.take some alf)
| otherwise = (alf, sep')
where
sep' = shuffle (Vec.fromList $ map ord sep `intersect` as) saltvec
alf = shuffle (Vec.fromList $ nub as \\ map ord sep) saltvec
some = Vec.length alf `ceildiv` sepratio - Vec.length sep'
process2 as ss
| Vec.length as < 3 = (as, Vec.drop some ss, Vec.take some ss)
| otherwise = (Vec.drop some as, ss, Vec.take some as)
where some = Vec.length as `ceildiv` gratio
ceildiv a b = ceiling $ fromIntegral a / b
encode :: HaskID -> [Int] -> String
encode (HaskID alpha separators min_length salt guards) input
| not $ all (>= 0) input = ""
| long_enough raw = map chr raw
| long_enough graw = map chr graw
| long_enough grawg = map chr grawg
| otherwise = map chr $ shuffle_pad alpha' grawg min_length
where
(alpha', raw) = encode_raw input salt alpha separators
graw = guard_choice (head raw) : raw
grawg = graw ++ [guard_choice (raw !! 1)]
long_enough = (>= min_length) . length
guard_choice n = guards !~% (sum (zipWith rem input [100..]) + n)
decode :: HaskID -> String -> [Int]
decode (HaskID alpha separators _ salt guards) encoded =
case str_split (`Vec.elem` guards) $ map ord encoded of
[_, seed : it, _] -> decode' it $ Vec.cons seed salt
[_, seed : it] -> decode' it $ Vec.cons seed salt
[seed : it] -> decode' it $ Vec.cons seed salt
_ -> []
where decode' it s = snd $ mapAccumL (dec_step s) alpha $
str_split (`Vec.elem` separators) it
dec_step :: Vector Int -> Vector Int -> [Int] -> (Vector Int, Int)
dec_step salt alpha radixed = (alpha', int)
where
alpha_salt = Vec.take (Vec.length alpha) (salt Vec.++ alpha)
alpha' = shuffle alpha alpha_salt
int = read_base (Vec.length alpha') index_in radixed
index_in = fromJust . (`Vec.elemIndex` alpha')
read_base :: Integral a => a -> (b -> a) -> [b] -> a
read_base _ _ [] = error "empty numeral"
read_base base f (x:xs)
| base < 1 = error "base < 1"
| otherwise = go xs $ f x
where
go [] n = n
go (y:ys) n = go ys $ f y + n * base
shuffle_pad :: Vector Int -> [Int] -> Int -> [Int]
shuffle_pad alpha xs min_length
| length xs >= min_length = take min_length $ drop exlen2 xs
| otherwise = shuffle_pad alpha' xs' min_length
where
alpha' = shuffle alpha alpha
xs' = Vec.toList (Vec.drop d alpha') ++ xs ++ Vec.toList (Vec.take d alpha')
where d = Vec.length alpha' `quot` 2
exlen2 = (length xs - min_length) `quot` 2
encode_raw :: [Int] -> Vector Int -> Vector Int -> Vector Int
-> (Vector Int, [Int])
encode_raw input salt alpha separators =
(alpha', init $ seed : interleave_with encoded seps)
where
seps = mk_seps separators input encoded
(alpha', encoded) = mapAccumL (enc_step seedsalt) alpha input
seedsalt = Vec.cons seed salt
seed = alpha !~% sum (zipWith rem input [100..])
mk_seps :: Vector Int -> [Int] -> [[Int]] -> [Int]
mk_seps seps input chunks = zipWith3 mk' [0..] input $ map head chunks
where mk' idx val c = seps !~% (val `rem` (c + idx))
enc_step :: Vector Int -> Vector Int -> Int -> (Vector Int, [Int])
enc_step salt alpha val = (alpha', encoded)
where
alpha' = shuffle alpha $ Vec.take (Vec.length alpha) (salt Vec.++ alpha)
encoded = to_base (Vec.length alpha) (alpha' !~) val
to_base :: Integral a => a -> (a -> b) -> a -> [b]
to_base base f n
| base <= 1 = error "base <= 1"
| n < 0 = error "negative"
| otherwise = go (n `quot` base) [f $ n `rem` base]
where
go 0 accum = accum
go q accum = go q' $ f r' : accum where (q', r') = quotRem q base
shuffle :: Vector Int -> Vector Int -> Vector Int
shuffle input salt | Vec.length salt == 0 = input | otherwise = runST $
Vec.thaw input >>= loop (Vec.length input - 1) (salt !~ 0) 0 >>= Vec.freeze
where
loop !ind !summ !grainpos vec
| ind < 1 = return vec
| otherwise = swap vec ind alt >> loop (ind - 1) summ' grainpos' vec
where
alt = (summ + grainpos + salt !~ grainpos) `rem` ind
grainpos' = (grainpos + 1) `rem` Vec.length salt
summ' = (summ + salt !~ grainpos')
(!~) :: Vec.Unbox a => Vector a -> Int -> a
(!~) = Vec.unsafeIndex
(!~%) :: Vec.Unbox a => Vector a -> Int -> a
vec !~% n = Vec.unsafeIndex vec $ n `rem` Vec.length vec
interleave_with :: [[a]] -> [a] -> [a]
interleave_with chunks seps = concat (zipWith (++) chunks seps')
where seps' = map (: []) seps
str_split :: Eq a => (a -> Bool) -> [a] -> [[a]]
str_split f = filter (/= []) . foldr f' [[]]
where f' c accum
| f c = [] : accum
| otherwise = (c : head accum) : tail accum
|
bryant/haskid
|
src/Data/HaskID.hs
|
apache-2.0
| 6,595 | 0 | 13 | 1,715 | 2,669 | 1,387 | 1,282 | 149 | 4 |
import Data.List
kai 0 = 1
kai 1 = 1
kai n = n * kai (n-1)
dist m s d =
let d1 = abs $ s - d
d2 = m - d1
mn = minimum [d1,d2]
c = if d1 == d2 then 2 else 1
in
(mn,c)
ans [mx,my,sx,sy,dx,dy] =
let (x,cx) = dist mx sx dx
(y,cy) = dist my sy dy
a = kai (x+y)
b = kai x
c = kai y
in
( a `div` b `div` c * cx * cy ) `mod` 100000007
main = do
l <- getLine
let i = map read $ words l :: [Integer]
o = ans i
print o
|
a143753/AOJ
|
1501.hs
|
apache-2.0
| 484 | 0 | 12 | 191 | 302 | 160 | 142 | 22 | 2 |
module BinaryField
(
Poly(..),
toInt,
fromBits,
fromInt,
zeroPoly,
onePoly,
allPolys,
expand,
embedPoly,
polySum,
polyProduct,
timesX,
polyGCD,
powerOfX,
powerOfY
)
where
import Bit(bitsToInt, intToBits, intWToBits, xor, showTrues)
data Poly = Poly {
polyLen :: Int
, polyBits :: [Bool]
} deriving Eq
instance Show Poly where
show p@(Poly len pp) =
show (len, toInt p, showTrues (expand len pp))
{------}
toInt (Poly len pp) = bitsToInt $ expand len pp
fromBits bits = Poly (length bits) bits
fromInt len = fromBits . intWToBits len []
zeroPoly len = Poly len []
onePoly len = Poly len $ replicate (len - 1) False ++ [True]
allPolys len = map (fromBits . intWToBits len []) [1..(2 ^ len - 1)]
{------}
expand 0 _ = []
expand len [] = replicate len False
expand len (p:ps) = p : expand (len - 1) ps
prunePoly (Poly l pp) = prunePoly' l pp
prunePoly' 0 _ = Poly 0 []
prunePoly' _ [] = Poly 0 []
prunePoly' l pp@(p:ps) =
if p
then Poly l pp
else prunePoly' (l - 1) ps
embedPoly newLength (Poly length p) =
Poly newLength (replicate (newLength - length) False ++ p)
{-------}
{-Multiply by x, then reduce by characteristic polynomial -}
timesX _charPoly p@(Poly _ []) = p
timesX charPoly (Poly l (a:as)) =
if a
then polySum charPoly (Poly l as)
else Poly l as
polySum (Poly la pa) (Poly lb pb) =
if la == lb
then Poly la (polySum' pa pb)
else error "Polynomial length mismatch."
polySum' (a:as) (b:bs) = xor a b : polySum' as bs
polySum' [] bb = bb
polySum' aa [] = aa
polyProduct charPoly@(Poly l _) a@(Poly la _) (Poly lb pb) =
if l == la && l == lb
then polyProduct' charPoly a (expand l pb) (zeroPoly l)
else error "Polynomial length mismatch."
polyProduct' _charPoly _ [] accum = accum
polyProduct' charPoly a (b:bs) accum =
let accum2 = timesX charPoly accum
accum3 = if b
then polySum a accum2
else accum2
in polyProduct' charPoly a bs accum3
polyRem a b =
polyRem' (prunePoly a) (prunePoly b)
polyRem' a@(Poly la _) b@(Poly lb pb) =
if lb > la
then a
else let aa = prunePoly . polySum a $ Poly la pb
in polyRem' aa b
polyGCD a b =
if 0 == toInt b
then a
else polyGCD b $ polyRem a b
powerOfX charPoly n =
let square x = polyProduct charPoly x x
times = timesX charPoly
bits = intToBits n
one = onePoly (polyLen charPoly)
in power square times bits one
powerOfY charPoly n y =
let square x = polyProduct charPoly x x
times = polyProduct charPoly y
bits = intToBits n
one = onePoly (polyLen charPoly)
in power square times bits one
power _ _ [] accum = accum
power square times (b:bs) accum =
let accum2 = square accum
accum3 = if b
then times accum2
else accum2
in power square times bs accum3
|
cullina/Extractor
|
src/BinaryField.hs
|
bsd-3-clause
| 3,074 | 0 | 12 | 972 | 1,238 | 633 | 605 | 96 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
module Category.Semigroupal
( Semigroupal(Semigroupal)
, tensor_product
, associator
) where
import Functor.Bifunctor (Bifunctor)
import Isomorphism (Isomorphism)
-- associator . associator = id * associator . associator . associator
data Semigroupal :: (* -> * -> *) -> (* -> * -> *) -> * where
Semigroupal ::
{ tensor_product :: Bifunctor cat cat cat pro
, associator :: (forall a b c. Isomorphism cat (pro (pro a b) c) (pro a (pro b c)))
} -> Semigroupal cat pro
|
Hexirp/untypeclass
|
src/Category/Semigroupal.hs
|
bsd-3-clause
| 624 | 0 | 14 | 135 | 164 | 96 | 68 | 18 | 0 |
module Control.Monad.Par.Async where
import Control.Applicative
import Control.Exception
import Control.Monad.Base
import Control.Monad.Catch hiding (try)
import Control.Monad.IO.Class
import Control.Monad.Par.Class
import Control.Monad.Par.IO
import Data.Functor
import Data.Semigroup
newtype Async a = Async { unAsync :: ParIO (Either SomeException a) }
runAsync :: Async a -> IO a
runAsync m = do
r <- tryAsync m
case r of
Left (SomeException e) -> throwIO e
Right a -> return a
tryAsync :: Async a -> IO (Either SomeException a)
tryAsync = runParIO . unAsync
liftParIO :: ParIO a -> Async a
liftParIO m = Async $ Right <$> m
instance Functor Async where
fmap f m = Async $ fmap (fmap f) $ unAsync m
instance Applicative Async where
pure = return
f <*> a = Async $ do
fi <- spawn_ $ unAsync f
ai <- spawn_ $ unAsync a
fr <- get fi
case fr of
Left e -> return $ Left e
Right f' -> do
ar <- get ai
case ar of
Left e' -> return $ Left e'
Right a' -> return $ Right $ f' a'
instance Monad Async where
return = liftParIO . return
m >>= f = Async $ do
r <- unAsync m
case r of
Left e -> return $ Left e
Right a -> unAsync $ f a
instance MonadIO Async where
liftIO = liftParIO . liftIO
instance MonadBase IO Async where
liftBase = liftIO
data AsyncEmptyException = AsyncEmptyException
deriving (Exception, Show)
instance Alternative Async where
empty = Async $ return $ Left $ SomeException AsyncEmptyException
a <|> b = Async $ do
ai <- spawn_ $ unAsync a
bi <- spawn_ $ unAsync b
ar <- get ai
case ar of
Left _ -> get bi >>= return
Right a' -> return $ Right a'
instance Semigroup a => Semigroup (Async a) where
a <> b = (<>) <$> a <*> b
instance Monoid a => Monoid (Async a) where
mempty = return mempty
a `mappend` b = mappend <$> a <*> b
instance MonadThrow Async where
throwM = Async . return . Left . SomeException
instance MonadCatch Async where
catch m f = Async $ do
r <- unAsync m
case r of
Left e -> case fromException e of
Just e' -> unAsync $ f e'
_ -> return $ Left e
Right a -> return $ Right a
newtype AVar a = AVar { unAVar :: IVar (Either SomeException a) }
newAVar :: Async (AVar a)
newAVar = liftParIO $ AVar <$> new
getAVar :: AVar a -> Async a
getAVar = Async . get . unAVar
putAVar :: AVar a -> a -> Async ()
putAVar v ~a = liftParIO $ put_ (unAVar v) (Right a)
forkAsync :: Async a -> Async ()
forkAsync m = liftParIO $ fork $ unAsync m $> ()
spawnAsync :: Async a -> Async (AVar a)
spawnAsync m = liftParIO $ do
v <- new
fork $ unAsync m >>= put_ v
return $ AVar v
instance ParFuture AVar Async where
spawn_ = spawnAsync
get = getAVar
instance ParIVar AVar Async where
fork = forkAsync
new = newAVar
put_ = putAVar
|
TerrorJack/monad-par-async
|
src/Control/Monad/Par/Async.hs
|
bsd-3-clause
| 3,076 | 0 | 18 | 957 | 1,169 | 572 | 597 | -1 | -1 |
{-# LANGUAGE CPP, TypeFamilies #-}
-----------------------------------------------------------------------------
--
-- Machine-dependent assembly language
--
-- (c) The University of Glasgow 1993-2004
--
-----------------------------------------------------------------------------
module X86.Instr (Instr(..), Operand(..), PrefetchVariant(..), JumpDest,
getJumpDestBlockId, canShortcut, shortcutStatics,
shortcutJump, i386_insert_ffrees, allocMoreStack,
maxSpillSlots, archWordSize)
where
#include "HsVersions.h"
#include "nativeGen/NCG.h"
import X86.Cond
import X86.Regs
import Instruction
import Size
import RegClass
import Reg
import TargetReg
import BlockId
import CodeGen.Platform
import Cmm
import FastString
import FastBool
import Outputable
import Platform
import BasicTypes (Alignment)
import CLabel
import DynFlags
import UniqSet
import Unique
import UniqSupply
import Control.Monad
import Data.Maybe (fromMaybe)
-- Size of an x86/x86_64 memory address, in bytes.
--
archWordSize :: Bool -> Size
archWordSize is32Bit
| is32Bit = II32
| otherwise = II64
-- | Instruction instance for x86 instruction set.
instance Instruction Instr where
regUsageOfInstr = x86_regUsageOfInstr
patchRegsOfInstr = x86_patchRegsOfInstr
isJumpishInstr = x86_isJumpishInstr
jumpDestsOfInstr = x86_jumpDestsOfInstr
patchJumpInstr = x86_patchJumpInstr
mkSpillInstr = x86_mkSpillInstr
mkLoadInstr = x86_mkLoadInstr
takeDeltaInstr = x86_takeDeltaInstr
isMetaInstr = x86_isMetaInstr
mkRegRegMoveInstr = x86_mkRegRegMoveInstr
takeRegRegMoveInstr = x86_takeRegRegMoveInstr
mkJumpInstr = x86_mkJumpInstr
mkStackAllocInstr = x86_mkStackAllocInstr
mkStackDeallocInstr = x86_mkStackDeallocInstr
-- -----------------------------------------------------------------------------
-- Intel x86 instructions
{-
Intel, in their infinite wisdom, selected a stack model for floating
point registers on x86. That might have made sense back in 1979 --
nowadays we can see it for the nonsense it really is. A stack model
fits poorly with the existing nativeGen infrastructure, which assumes
flat integer and FP register sets. Prior to this commit, nativeGen
could not generate correct x86 FP code -- to do so would have meant
somehow working the register-stack paradigm into the register
allocator and spiller, which sounds very difficult.
We have decided to cheat, and go for a simple fix which requires no
infrastructure modifications, at the expense of generating ropey but
correct FP code. All notions of the x86 FP stack and its insns have
been removed. Instead, we pretend (to the instruction selector and
register allocator) that x86 has six floating point registers, %fake0
.. %fake5, which can be used in the usual flat manner. We further
claim that x86 has floating point instructions very similar to SPARC
and Alpha, that is, a simple 3-operand register-register arrangement.
Code generation and register allocation proceed on this basis.
When we come to print out the final assembly, our convenient fiction
is converted to dismal reality. Each fake instruction is
independently converted to a series of real x86 instructions.
%fake0 .. %fake5 are mapped to %st(0) .. %st(5). To do reg-reg
arithmetic operations, the two operands are pushed onto the top of the
FP stack, the operation done, and the result copied back into the
relevant register. There are only six %fake registers because 2 are
needed for the translation, and x86 has 8 in total.
The translation is inefficient but is simple and it works. A cleverer
translation would handle a sequence of insns, simulating the FP stack
contents, would not impose a fixed mapping from %fake to %st regs, and
hopefully could avoid most of the redundant reg-reg moves of the
current translation.
We might as well make use of whatever unique FP facilities Intel have
chosen to bless us with (let's not be churlish, after all).
Hence GLDZ and GLD1. Bwahahahahahahaha!
-}
{-
Note [x86 Floating point precision]
Intel's internal floating point registers are by default 80 bit
extended precision. This means that all operations done on values in
registers are done at 80 bits, and unless the intermediate values are
truncated to the appropriate size (32 or 64 bits) by storing in
memory, calculations in registers will give different results from
calculations which pass intermediate values in memory (eg. via
function calls).
One solution is to set the FPU into 64 bit precision mode. Some OSs
do this (eg. FreeBSD) and some don't (eg. Linux). The problem here is
that this will only affect 64-bit precision arithmetic; 32-bit
calculations will still be done at 64-bit precision in registers. So
it doesn't solve the whole problem.
There's also the issue of what the C library is expecting in terms of
precision. It seems to be the case that glibc on Linux expects the
FPU to be set to 80 bit precision, so setting it to 64 bit could have
unexpected effects. Changing the default could have undesirable
effects on other 3rd-party library code too, so the right thing would
be to save/restore the FPU control word across Haskell code if we were
to do this.
gcc's -ffloat-store gives consistent results by always storing the
results of floating-point calculations in memory, which works for both
32 and 64-bit precision. However, it only affects the values of
user-declared floating point variables in C, not intermediate results.
GHC in -fvia-C mode uses -ffloat-store (see the -fexcess-precision
flag).
Another problem is how to spill floating point registers in the
register allocator. Should we spill the whole 80 bits, or just 64?
On an OS which is set to 64 bit precision, spilling 64 is fine. On
Linux, spilling 64 bits will round the results of some operations.
This is what gcc does. Spilling at 80 bits requires taking up a full
128 bit slot (so we get alignment). We spill at 80-bits and ignore
the alignment problems.
In the future [edit: now available in GHC 7.0.1, with the -msse2
flag], we'll use the SSE registers for floating point. This requires
a CPU that supports SSE2 (ordinary SSE only supports 32 bit precision
float ops), which means P4 or Xeon and above. Using SSE will solve
all these problems, because the SSE registers use fixed 32 bit or 64
bit precision.
--SDM 1/2003
-}
data Instr
-- comment pseudo-op
= COMMENT FastString
-- some static data spat out during code
-- generation. Will be extracted before
-- pretty-printing.
| LDATA Section (Alignment, CmmStatics)
-- start a new basic block. Useful during
-- codegen, removed later. Preceding
-- instruction should be a jump, as per the
-- invariants for a BasicBlock (see Cmm).
| NEWBLOCK BlockId
-- specify current stack offset for
-- benefit of subsequent passes
| DELTA Int
-- Moves.
| MOV Size Operand Operand
| MOVZxL Size Operand Operand -- size is the size of operand 1
| MOVSxL Size Operand Operand -- size is the size of operand 1
-- x86_64 note: plain mov into a 32-bit register always zero-extends
-- into the 64-bit reg, in contrast to the 8 and 16-bit movs which
-- don't affect the high bits of the register.
-- Load effective address (also a very useful three-operand add instruction :-)
| LEA Size Operand Operand
-- Int Arithmetic.
| ADD Size Operand Operand
| ADC Size Operand Operand
| SUB Size Operand Operand
| MUL Size Operand Operand
| MUL2 Size Operand -- %edx:%eax = operand * %rax
| IMUL Size Operand Operand -- signed int mul
| IMUL2 Size Operand -- %edx:%eax = operand * %eax
| DIV Size Operand -- eax := eax:edx/op, edx := eax:edx%op
| IDIV Size Operand -- ditto, but signed
-- Simple bit-twiddling.
| AND Size Operand Operand
| OR Size Operand Operand
| XOR Size Operand Operand
| NOT Size Operand
| NEGI Size Operand -- NEG instruction (name clash with Cond)
| BSWAP Size Reg
-- Shifts (amount may be immediate or %cl only)
| SHL Size Operand{-amount-} Operand
| SAR Size Operand{-amount-} Operand
| SHR Size Operand{-amount-} Operand
| BT Size Imm Operand
| NOP
-- x86 Float Arithmetic.
-- Note that we cheat by treating G{ABS,MOV,NEG} of doubles
-- as single instructions right up until we spit them out.
-- all the 3-operand fake fp insns are src1 src2 dst
-- and furthermore are constrained to be fp regs only.
-- IMPORTANT: keep is_G_insn up to date with any changes here
| GMOV Reg Reg -- src(fpreg), dst(fpreg)
| GLD Size AddrMode Reg -- src, dst(fpreg)
| GST Size Reg AddrMode -- src(fpreg), dst
| GLDZ Reg -- dst(fpreg)
| GLD1 Reg -- dst(fpreg)
| GFTOI Reg Reg -- src(fpreg), dst(intreg)
| GDTOI Reg Reg -- src(fpreg), dst(intreg)
| GITOF Reg Reg -- src(intreg), dst(fpreg)
| GITOD Reg Reg -- src(intreg), dst(fpreg)
| GDTOF Reg Reg -- src(fpreg), dst(fpreg)
| GADD Size Reg Reg Reg -- src1, src2, dst
| GDIV Size Reg Reg Reg -- src1, src2, dst
| GSUB Size Reg Reg Reg -- src1, src2, dst
| GMUL Size Reg Reg Reg -- src1, src2, dst
-- FP compare. Cond must be `elem` [EQQ, NE, LE, LTT, GE, GTT]
-- Compare src1 with src2; set the Zero flag iff the numbers are
-- comparable and the comparison is True. Subsequent code must
-- test the %eflags zero flag regardless of the supplied Cond.
| GCMP Cond Reg Reg -- src1, src2
| GABS Size Reg Reg -- src, dst
| GNEG Size Reg Reg -- src, dst
| GSQRT Size Reg Reg -- src, dst
| GSIN Size CLabel CLabel Reg Reg -- src, dst
| GCOS Size CLabel CLabel Reg Reg -- src, dst
| GTAN Size CLabel CLabel Reg Reg -- src, dst
| GFREE -- do ffree on all x86 regs; an ugly hack
-- SSE2 floating point: we use a restricted set of the available SSE2
-- instructions for floating-point.
-- use MOV for moving (either movss or movsd (movlpd better?))
| CVTSS2SD Reg Reg -- F32 to F64
| CVTSD2SS Reg Reg -- F64 to F32
| CVTTSS2SIQ Size Operand Reg -- F32 to I32/I64 (with truncation)
| CVTTSD2SIQ Size Operand Reg -- F64 to I32/I64 (with truncation)
| CVTSI2SS Size Operand Reg -- I32/I64 to F32
| CVTSI2SD Size Operand Reg -- I32/I64 to F64
-- use ADD & SUB for arithmetic. In both cases, operands
-- are Operand Reg.
-- SSE2 floating-point division:
| FDIV Size Operand Operand -- divisor, dividend(dst)
-- use CMP for comparisons. ucomiss and ucomisd instructions
-- compare single/double prec floating point respectively.
| SQRT Size Operand Reg -- src, dst
-- Comparison
| TEST Size Operand Operand
| CMP Size Operand Operand
| SETCC Cond Operand
-- Stack Operations.
| PUSH Size Operand
| POP Size Operand
-- both unused (SDM):
-- | PUSHA
-- | POPA
-- Jumping around.
| JMP Operand [Reg] -- including live Regs at the call
| JXX Cond BlockId -- includes unconditional branches
| JXX_GBL Cond Imm -- non-local version of JXX
-- Table jump
| JMP_TBL Operand -- Address to jump to
[Maybe BlockId] -- Blocks in the jump table
Section -- Data section jump table should be put in
CLabel -- Label of jump table
| CALL (Either Imm Reg) [Reg]
-- Other things.
| CLTD Size -- sign extend %eax into %edx:%eax
| FETCHGOT Reg -- pseudo-insn for ELF position-independent code
-- pretty-prints as
-- call 1f
-- 1: popl %reg
-- addl __GLOBAL_OFFSET_TABLE__+.-1b, %reg
| FETCHPC Reg -- pseudo-insn for Darwin position-independent code
-- pretty-prints as
-- call 1f
-- 1: popl %reg
-- SSE4.2
| POPCNT Size Operand Reg -- src, dst
-- prefetch
| PREFETCH PrefetchVariant Size Operand -- prefetch Variant, addr size, address to prefetch
-- variant can be NTA, Lvl0, Lvl1, or Lvl2
| LOCK -- lock prefix
| XADD Size Operand Operand -- src (r), dst (r/m)
| CMPXCHG Size Operand Operand -- src (r), dst (r/m), eax implicit
data PrefetchVariant = NTA | Lvl0 | Lvl1 | Lvl2
data Operand
= OpReg Reg -- register
| OpImm Imm -- immediate value
| OpAddr AddrMode -- memory reference
-- | Returns which registers are read and written as a (read, written)
-- pair.
x86_regUsageOfInstr :: Platform -> Instr -> RegUsage
x86_regUsageOfInstr platform instr
= case instr of
MOV _ src dst -> usageRW src dst
MOVZxL _ src dst -> usageRW src dst
MOVSxL _ src dst -> usageRW src dst
LEA _ src dst -> usageRW src dst
ADD _ src dst -> usageRM src dst
ADC _ src dst -> usageRM src dst
SUB _ src dst -> usageRM src dst
IMUL _ src dst -> usageRM src dst
IMUL2 _ src -> mkRU (eax:use_R src []) [eax,edx]
MUL _ src dst -> usageRM src dst
MUL2 _ src -> mkRU (eax:use_R src []) [eax,edx]
DIV _ op -> mkRU (eax:edx:use_R op []) [eax,edx]
IDIV _ op -> mkRU (eax:edx:use_R op []) [eax,edx]
AND _ src dst -> usageRM src dst
OR _ src dst -> usageRM src dst
XOR _ (OpReg src) (OpReg dst)
| src == dst -> mkRU [] [dst]
XOR _ src dst -> usageRM src dst
NOT _ op -> usageM op
BSWAP _ reg -> mkRU [reg] [reg]
NEGI _ op -> usageM op
SHL _ imm dst -> usageRM imm dst
SAR _ imm dst -> usageRM imm dst
SHR _ imm dst -> usageRM imm dst
BT _ _ src -> mkRUR (use_R src [])
PUSH _ op -> mkRUR (use_R op [])
POP _ op -> mkRU [] (def_W op)
TEST _ src dst -> mkRUR (use_R src $! use_R dst [])
CMP _ src dst -> mkRUR (use_R src $! use_R dst [])
SETCC _ op -> mkRU [] (def_W op)
JXX _ _ -> mkRU [] []
JXX_GBL _ _ -> mkRU [] []
JMP op regs -> mkRUR (use_R op regs)
JMP_TBL op _ _ _ -> mkRUR (use_R op [])
CALL (Left _) params -> mkRU params (callClobberedRegs platform)
CALL (Right reg) params -> mkRU (reg:params) (callClobberedRegs platform)
CLTD _ -> mkRU [eax] [edx]
NOP -> mkRU [] []
GMOV src dst -> mkRU [src] [dst]
GLD _ src dst -> mkRU (use_EA src []) [dst]
GST _ src dst -> mkRUR (src : use_EA dst [])
GLDZ dst -> mkRU [] [dst]
GLD1 dst -> mkRU [] [dst]
GFTOI src dst -> mkRU [src] [dst]
GDTOI src dst -> mkRU [src] [dst]
GITOF src dst -> mkRU [src] [dst]
GITOD src dst -> mkRU [src] [dst]
GDTOF src dst -> mkRU [src] [dst]
GADD _ s1 s2 dst -> mkRU [s1,s2] [dst]
GSUB _ s1 s2 dst -> mkRU [s1,s2] [dst]
GMUL _ s1 s2 dst -> mkRU [s1,s2] [dst]
GDIV _ s1 s2 dst -> mkRU [s1,s2] [dst]
GCMP _ src1 src2 -> mkRUR [src1,src2]
GABS _ src dst -> mkRU [src] [dst]
GNEG _ src dst -> mkRU [src] [dst]
GSQRT _ src dst -> mkRU [src] [dst]
GSIN _ _ _ src dst -> mkRU [src] [dst]
GCOS _ _ _ src dst -> mkRU [src] [dst]
GTAN _ _ _ src dst -> mkRU [src] [dst]
CVTSS2SD src dst -> mkRU [src] [dst]
CVTSD2SS src dst -> mkRU [src] [dst]
CVTTSS2SIQ _ src dst -> mkRU (use_R src []) [dst]
CVTTSD2SIQ _ src dst -> mkRU (use_R src []) [dst]
CVTSI2SS _ src dst -> mkRU (use_R src []) [dst]
CVTSI2SD _ src dst -> mkRU (use_R src []) [dst]
FDIV _ src dst -> usageRM src dst
FETCHGOT reg -> mkRU [] [reg]
FETCHPC reg -> mkRU [] [reg]
COMMENT _ -> noUsage
DELTA _ -> noUsage
POPCNT _ src dst -> mkRU (use_R src []) [dst]
-- note: might be a better way to do this
PREFETCH _ _ src -> mkRU (use_R src []) []
LOCK -> noUsage
XADD _ src dst -> usageMM src dst
CMPXCHG _ src dst -> usageRMM src dst (OpReg eax)
_other -> panic "regUsage: unrecognised instr"
where
-- # Definitions
--
-- Written: If the operand is a register, it's written. If it's an
-- address, registers mentioned in the address are read.
--
-- Modified: If the operand is a register, it's both read and
-- written. If it's an address, registers mentioned in the address
-- are read.
-- 2 operand form; first operand Read; second Written
usageRW :: Operand -> Operand -> RegUsage
usageRW op (OpReg reg) = mkRU (use_R op []) [reg]
usageRW op (OpAddr ea) = mkRUR (use_R op $! use_EA ea [])
usageRW _ _ = panic "X86.RegInfo.usageRW: no match"
-- 2 operand form; first operand Read; second Modified
usageRM :: Operand -> Operand -> RegUsage
usageRM op (OpReg reg) = mkRU (use_R op [reg]) [reg]
usageRM op (OpAddr ea) = mkRUR (use_R op $! use_EA ea [])
usageRM _ _ = panic "X86.RegInfo.usageRM: no match"
-- 2 operand form; first operand Modified; second Modified
usageMM :: Operand -> Operand -> RegUsage
usageMM (OpReg src) (OpReg dst) = mkRU [src, dst] [src, dst]
usageMM (OpReg src) (OpAddr ea) = mkRU (use_EA ea [src]) [src]
usageMM _ _ = panic "X86.RegInfo.usageMM: no match"
-- 3 operand form; first operand Read; second Modified; third Modified
usageRMM :: Operand -> Operand -> Operand -> RegUsage
usageRMM (OpReg src) (OpReg dst) (OpReg reg) = mkRU [src, dst, reg] [dst, reg]
usageRMM (OpReg src) (OpAddr ea) (OpReg reg) = mkRU (use_EA ea [src, reg]) [reg]
usageRMM _ _ _ = panic "X86.RegInfo.usageRMM: no match"
-- 1 operand form; operand Modified
usageM :: Operand -> RegUsage
usageM (OpReg reg) = mkRU [reg] [reg]
usageM (OpAddr ea) = mkRUR (use_EA ea [])
usageM _ = panic "X86.RegInfo.usageM: no match"
-- Registers defd when an operand is written.
def_W (OpReg reg) = [reg]
def_W (OpAddr _ ) = []
def_W _ = panic "X86.RegInfo.def_W: no match"
-- Registers used when an operand is read.
use_R (OpReg reg) tl = reg : tl
use_R (OpImm _) tl = tl
use_R (OpAddr ea) tl = use_EA ea tl
-- Registers used to compute an effective address.
use_EA (ImmAddr _ _) tl = tl
use_EA (AddrBaseIndex base index _) tl =
use_base base $! use_index index tl
where use_base (EABaseReg r) tl = r : tl
use_base _ tl = tl
use_index EAIndexNone tl = tl
use_index (EAIndex i _) tl = i : tl
mkRUR src = src' `seq` RU src' []
where src' = filter (interesting platform) src
mkRU src dst = src' `seq` dst' `seq` RU src' dst'
where src' = filter (interesting platform) src
dst' = filter (interesting platform) dst
-- | Is this register interesting for the register allocator?
interesting :: Platform -> Reg -> Bool
interesting _ (RegVirtual _) = True
interesting platform (RegReal (RealRegSingle i)) = isFastTrue (freeReg platform i)
interesting _ (RegReal (RealRegPair{})) = panic "X86.interesting: no reg pairs on this arch"
-- | Applies the supplied function to all registers in instructions.
-- Typically used to change virtual registers to real registers.
x86_patchRegsOfInstr :: Instr -> (Reg -> Reg) -> Instr
x86_patchRegsOfInstr instr env
= case instr of
MOV sz src dst -> patch2 (MOV sz) src dst
MOVZxL sz src dst -> patch2 (MOVZxL sz) src dst
MOVSxL sz src dst -> patch2 (MOVSxL sz) src dst
LEA sz src dst -> patch2 (LEA sz) src dst
ADD sz src dst -> patch2 (ADD sz) src dst
ADC sz src dst -> patch2 (ADC sz) src dst
SUB sz src dst -> patch2 (SUB sz) src dst
IMUL sz src dst -> patch2 (IMUL sz) src dst
IMUL2 sz src -> patch1 (IMUL2 sz) src
MUL sz src dst -> patch2 (MUL sz) src dst
MUL2 sz src -> patch1 (MUL2 sz) src
IDIV sz op -> patch1 (IDIV sz) op
DIV sz op -> patch1 (DIV sz) op
AND sz src dst -> patch2 (AND sz) src dst
OR sz src dst -> patch2 (OR sz) src dst
XOR sz src dst -> patch2 (XOR sz) src dst
NOT sz op -> patch1 (NOT sz) op
BSWAP sz reg -> BSWAP sz (env reg)
NEGI sz op -> patch1 (NEGI sz) op
SHL sz imm dst -> patch1 (SHL sz imm) dst
SAR sz imm dst -> patch1 (SAR sz imm) dst
SHR sz imm dst -> patch1 (SHR sz imm) dst
BT sz imm src -> patch1 (BT sz imm) src
TEST sz src dst -> patch2 (TEST sz) src dst
CMP sz src dst -> patch2 (CMP sz) src dst
PUSH sz op -> patch1 (PUSH sz) op
POP sz op -> patch1 (POP sz) op
SETCC cond op -> patch1 (SETCC cond) op
JMP op regs -> JMP (patchOp op) regs
JMP_TBL op ids s lbl-> JMP_TBL (patchOp op) ids s lbl
GMOV src dst -> GMOV (env src) (env dst)
GLD sz src dst -> GLD sz (lookupAddr src) (env dst)
GST sz src dst -> GST sz (env src) (lookupAddr dst)
GLDZ dst -> GLDZ (env dst)
GLD1 dst -> GLD1 (env dst)
GFTOI src dst -> GFTOI (env src) (env dst)
GDTOI src dst -> GDTOI (env src) (env dst)
GITOF src dst -> GITOF (env src) (env dst)
GITOD src dst -> GITOD (env src) (env dst)
GDTOF src dst -> GDTOF (env src) (env dst)
GADD sz s1 s2 dst -> GADD sz (env s1) (env s2) (env dst)
GSUB sz s1 s2 dst -> GSUB sz (env s1) (env s2) (env dst)
GMUL sz s1 s2 dst -> GMUL sz (env s1) (env s2) (env dst)
GDIV sz s1 s2 dst -> GDIV sz (env s1) (env s2) (env dst)
GCMP sz src1 src2 -> GCMP sz (env src1) (env src2)
GABS sz src dst -> GABS sz (env src) (env dst)
GNEG sz src dst -> GNEG sz (env src) (env dst)
GSQRT sz src dst -> GSQRT sz (env src) (env dst)
GSIN sz l1 l2 src dst -> GSIN sz l1 l2 (env src) (env dst)
GCOS sz l1 l2 src dst -> GCOS sz l1 l2 (env src) (env dst)
GTAN sz l1 l2 src dst -> GTAN sz l1 l2 (env src) (env dst)
CVTSS2SD src dst -> CVTSS2SD (env src) (env dst)
CVTSD2SS src dst -> CVTSD2SS (env src) (env dst)
CVTTSS2SIQ sz src dst -> CVTTSS2SIQ sz (patchOp src) (env dst)
CVTTSD2SIQ sz src dst -> CVTTSD2SIQ sz (patchOp src) (env dst)
CVTSI2SS sz src dst -> CVTSI2SS sz (patchOp src) (env dst)
CVTSI2SD sz src dst -> CVTSI2SD sz (patchOp src) (env dst)
FDIV sz src dst -> FDIV sz (patchOp src) (patchOp dst)
CALL (Left _) _ -> instr
CALL (Right reg) p -> CALL (Right (env reg)) p
FETCHGOT reg -> FETCHGOT (env reg)
FETCHPC reg -> FETCHPC (env reg)
NOP -> instr
COMMENT _ -> instr
DELTA _ -> instr
JXX _ _ -> instr
JXX_GBL _ _ -> instr
CLTD _ -> instr
POPCNT sz src dst -> POPCNT sz (patchOp src) (env dst)
PREFETCH lvl size src -> PREFETCH lvl size (patchOp src)
LOCK -> instr
XADD sz src dst -> patch2 (XADD sz) src dst
CMPXCHG sz src dst -> patch2 (CMPXCHG sz) src dst
_other -> panic "patchRegs: unrecognised instr"
where
patch1 :: (Operand -> a) -> Operand -> a
patch1 insn op = insn $! patchOp op
patch2 :: (Operand -> Operand -> a) -> Operand -> Operand -> a
patch2 insn src dst = (insn $! patchOp src) $! patchOp dst
patchOp (OpReg reg) = OpReg $! env reg
patchOp (OpImm imm) = OpImm imm
patchOp (OpAddr ea) = OpAddr $! lookupAddr ea
lookupAddr (ImmAddr imm off) = ImmAddr imm off
lookupAddr (AddrBaseIndex base index disp)
= ((AddrBaseIndex $! lookupBase base) $! lookupIndex index) disp
where
lookupBase EABaseNone = EABaseNone
lookupBase EABaseRip = EABaseRip
lookupBase (EABaseReg r) = EABaseReg $! env r
lookupIndex EAIndexNone = EAIndexNone
lookupIndex (EAIndex r i) = (EAIndex $! env r) i
--------------------------------------------------------------------------------
x86_isJumpishInstr
:: Instr -> Bool
x86_isJumpishInstr instr
= case instr of
JMP{} -> True
JXX{} -> True
JXX_GBL{} -> True
JMP_TBL{} -> True
CALL{} -> True
_ -> False
x86_jumpDestsOfInstr
:: Instr
-> [BlockId]
x86_jumpDestsOfInstr insn
= case insn of
JXX _ id -> [id]
JMP_TBL _ ids _ _ -> [id | Just id <- ids]
_ -> []
x86_patchJumpInstr
:: Instr -> (BlockId -> BlockId) -> Instr
x86_patchJumpInstr insn patchF
= case insn of
JXX cc id -> JXX cc (patchF id)
JMP_TBL op ids section lbl
-> JMP_TBL op (map (fmap patchF) ids) section lbl
_ -> insn
-- -----------------------------------------------------------------------------
-- | Make a spill instruction.
x86_mkSpillInstr
:: DynFlags
-> Reg -- register to spill
-> Int -- current stack delta
-> Int -- spill slot to use
-> Instr
x86_mkSpillInstr dflags reg delta slot
= let off = spillSlotToOffset platform slot - delta
in
case targetClassOfReg platform reg of
RcInteger -> MOV (archWordSize is32Bit)
(OpReg reg) (OpAddr (spRel dflags off))
RcDouble -> GST FF80 reg (spRel dflags off) {- RcFloat/RcDouble -}
RcDoubleSSE -> MOV FF64 (OpReg reg) (OpAddr (spRel dflags off))
_ -> panic "X86.mkSpillInstr: no match"
where platform = targetPlatform dflags
is32Bit = target32Bit platform
-- | Make a spill reload instruction.
x86_mkLoadInstr
:: DynFlags
-> Reg -- register to load
-> Int -- current stack delta
-> Int -- spill slot to use
-> Instr
x86_mkLoadInstr dflags reg delta slot
= let off = spillSlotToOffset platform slot - delta
in
case targetClassOfReg platform reg of
RcInteger -> MOV (archWordSize is32Bit)
(OpAddr (spRel dflags off)) (OpReg reg)
RcDouble -> GLD FF80 (spRel dflags off) reg {- RcFloat/RcDouble -}
RcDoubleSSE -> MOV FF64 (OpAddr (spRel dflags off)) (OpReg reg)
_ -> panic "X86.x86_mkLoadInstr"
where platform = targetPlatform dflags
is32Bit = target32Bit platform
spillSlotSize :: Platform -> Int
spillSlotSize dflags = if is32Bit then 12 else 8
where is32Bit = target32Bit dflags
maxSpillSlots :: DynFlags -> Int
maxSpillSlots dflags
= ((rESERVED_C_STACK_BYTES dflags - 64) `div` spillSlotSize (targetPlatform dflags)) - 1
-- = 0 -- useful for testing allocMoreStack
-- number of bytes that the stack pointer should be aligned to
stackAlign :: Int
stackAlign = 16
-- convert a spill slot number to a *byte* offset, with no sign:
-- decide on a per arch basis whether you are spilling above or below
-- the C stack pointer.
spillSlotToOffset :: Platform -> Int -> Int
spillSlotToOffset platform slot
= 64 + spillSlotSize platform * slot
--------------------------------------------------------------------------------
-- | See if this instruction is telling us the current C stack delta
x86_takeDeltaInstr
:: Instr
-> Maybe Int
x86_takeDeltaInstr instr
= case instr of
DELTA i -> Just i
_ -> Nothing
x86_isMetaInstr
:: Instr
-> Bool
x86_isMetaInstr instr
= case instr of
COMMENT{} -> True
LDATA{} -> True
NEWBLOCK{} -> True
DELTA{} -> True
_ -> False
-- | Make a reg-reg move instruction.
-- On SPARC v8 there are no instructions to move directly between
-- floating point and integer regs. If we need to do that then we
-- have to go via memory.
--
x86_mkRegRegMoveInstr
:: Platform
-> Reg
-> Reg
-> Instr
x86_mkRegRegMoveInstr platform src dst
= case targetClassOfReg platform src of
RcInteger -> case platformArch platform of
ArchX86 -> MOV II32 (OpReg src) (OpReg dst)
ArchX86_64 -> MOV II64 (OpReg src) (OpReg dst)
_ -> panic "x86_mkRegRegMoveInstr: Bad arch"
RcDouble -> GMOV src dst
RcDoubleSSE -> MOV FF64 (OpReg src) (OpReg dst)
_ -> panic "X86.RegInfo.mkRegRegMoveInstr: no match"
-- | Check whether an instruction represents a reg-reg move.
-- The register allocator attempts to eliminate reg->reg moves whenever it can,
-- by assigning the src and dest temporaries to the same real register.
--
x86_takeRegRegMoveInstr
:: Instr
-> Maybe (Reg,Reg)
x86_takeRegRegMoveInstr (MOV _ (OpReg r1) (OpReg r2))
= Just (r1,r2)
x86_takeRegRegMoveInstr _ = Nothing
-- | Make an unconditional branch instruction.
x86_mkJumpInstr
:: BlockId
-> [Instr]
x86_mkJumpInstr id
= [JXX ALWAYS id]
x86_mkStackAllocInstr
:: Platform
-> Int
-> Instr
x86_mkStackAllocInstr platform amount
= case platformArch platform of
ArchX86 -> SUB II32 (OpImm (ImmInt amount)) (OpReg esp)
ArchX86_64 -> SUB II64 (OpImm (ImmInt amount)) (OpReg rsp)
_ -> panic "x86_mkStackAllocInstr"
x86_mkStackDeallocInstr
:: Platform
-> Int
-> Instr
x86_mkStackDeallocInstr platform amount
= case platformArch platform of
ArchX86 -> ADD II32 (OpImm (ImmInt amount)) (OpReg esp)
ArchX86_64 -> ADD II64 (OpImm (ImmInt amount)) (OpReg rsp)
_ -> panic "x86_mkStackDeallocInstr"
i386_insert_ffrees
:: [GenBasicBlock Instr]
-> [GenBasicBlock Instr]
i386_insert_ffrees blocks
| any (any is_G_instr) [ instrs | BasicBlock _ instrs <- blocks ]
= map insertGFREEs blocks
| otherwise
= blocks
where
insertGFREEs (BasicBlock id insns)
= BasicBlock id (insertBeforeNonlocalTransfers GFREE insns)
insertBeforeNonlocalTransfers :: Instr -> [Instr] -> [Instr]
insertBeforeNonlocalTransfers insert insns
= foldr p [] insns
where p insn r = case insn of
CALL _ _ -> insert : insn : r
JMP _ _ -> insert : insn : r
JXX_GBL _ _ -> panic "insertBeforeNonlocalTransfers: cannot handle JXX_GBL"
_ -> insn : r
-- if you ever add a new FP insn to the fake x86 FP insn set,
-- you must update this too
is_G_instr :: Instr -> Bool
is_G_instr instr
= case instr of
GMOV{} -> True
GLD{} -> True
GST{} -> True
GLDZ{} -> True
GLD1{} -> True
GFTOI{} -> True
GDTOI{} -> True
GITOF{} -> True
GITOD{} -> True
GDTOF{} -> True
GADD{} -> True
GDIV{} -> True
GSUB{} -> True
GMUL{} -> True
GCMP{} -> True
GABS{} -> True
GNEG{} -> True
GSQRT{} -> True
GSIN{} -> True
GCOS{} -> True
GTAN{} -> True
GFREE -> panic "is_G_instr: GFREE (!)"
_ -> False
--
-- Note [extra spill slots]
--
-- If the register allocator used more spill slots than we have
-- pre-allocated (rESERVED_C_STACK_BYTES), then we must allocate more
-- C stack space on entry and exit from this proc. Therefore we
-- insert a "sub $N, %rsp" at every entry point, and an "add $N, %rsp"
-- before every non-local jump.
--
-- This became necessary when the new codegen started bundling entire
-- functions together into one proc, because the register allocator
-- assigns a different stack slot to each virtual reg within a proc.
-- To avoid using so many slots we could also:
--
-- - split up the proc into connected components before code generator
--
-- - rename the virtual regs, so that we re-use vreg names and hence
-- stack slots for non-overlapping vregs.
--
-- Note that when a block is both a non-local entry point (with an
-- info table) and a local branch target, we have to split it into
-- two, like so:
--
-- <info table>
-- L:
-- <code>
--
-- becomes
--
-- <info table>
-- L:
-- subl $rsp, N
-- jmp Lnew
-- Lnew:
-- <code>
--
-- and all branches pointing to L are retargetted to point to Lnew.
-- Otherwise, we would repeat the $rsp adjustment for each branch to
-- L.
--
allocMoreStack
:: Platform
-> Int
-> NatCmmDecl statics X86.Instr.Instr
-> UniqSM (NatCmmDecl statics X86.Instr.Instr)
allocMoreStack _ _ top@(CmmData _ _) = return top
allocMoreStack platform slots proc@(CmmProc info lbl live (ListGraph code)) = do
let entries = entryBlocks proc
uniqs <- replicateM (length entries) getUniqueUs
let
delta = ((x + stackAlign - 1) `quot` stackAlign) * stackAlign -- round up
where x = slots * spillSlotSize platform -- sp delta
alloc = mkStackAllocInstr platform delta
dealloc = mkStackDeallocInstr platform delta
new_blockmap :: BlockEnv BlockId
new_blockmap = mapFromList (zip entries (map mkBlockId uniqs))
insert_stack_insns (BasicBlock id insns)
| Just new_blockid <- mapLookup id new_blockmap
= [ BasicBlock id [alloc, JXX ALWAYS new_blockid]
, BasicBlock new_blockid block' ]
| otherwise
= [ BasicBlock id block' ]
where
block' = foldr insert_dealloc [] insns
insert_dealloc insn r = case insn of
JMP _ _ -> dealloc : insn : r
JXX_GBL _ _ -> panic "insert_dealloc: cannot handle JXX_GBL"
_other -> x86_patchJumpInstr insn retarget : r
where retarget b = fromMaybe b (mapLookup b new_blockmap)
new_code = concatMap insert_stack_insns code
-- in
return (CmmProc info lbl live (ListGraph new_code))
data JumpDest = DestBlockId BlockId | DestImm Imm
getJumpDestBlockId :: JumpDest -> Maybe BlockId
getJumpDestBlockId (DestBlockId bid) = Just bid
getJumpDestBlockId _ = Nothing
canShortcut :: Instr -> Maybe JumpDest
canShortcut (JXX ALWAYS id) = Just (DestBlockId id)
canShortcut (JMP (OpImm imm) _) = Just (DestImm imm)
canShortcut _ = Nothing
-- This helper shortcuts a sequence of branches.
-- The blockset helps avoid following cycles.
shortcutJump :: (BlockId -> Maybe JumpDest) -> Instr -> Instr
shortcutJump fn insn = shortcutJump' fn (setEmpty :: BlockSet) insn
where shortcutJump' fn seen insn@(JXX cc id) =
if setMember id seen then insn
else case fn id of
Nothing -> insn
Just (DestBlockId id') -> shortcutJump' fn seen' (JXX cc id')
Just (DestImm imm) -> shortcutJump' fn seen' (JXX_GBL cc imm)
where seen' = setInsert id seen
shortcutJump' _ _ other = other
-- Here because it knows about JumpDest
shortcutStatics :: (BlockId -> Maybe JumpDest) -> (Alignment, CmmStatics) -> (Alignment, CmmStatics)
shortcutStatics fn (align, Statics lbl statics)
= (align, Statics lbl $ map (shortcutStatic fn) statics)
-- we need to get the jump tables, so apply the mapping to the entries
-- of a CmmData too.
shortcutLabel :: (BlockId -> Maybe JumpDest) -> CLabel -> CLabel
shortcutLabel fn lab
| Just uq <- maybeAsmTemp lab = shortBlockId fn emptyUniqSet (mkBlockId uq)
| otherwise = lab
shortcutStatic :: (BlockId -> Maybe JumpDest) -> CmmStatic -> CmmStatic
shortcutStatic fn (CmmStaticLit (CmmLabel lab))
= CmmStaticLit (CmmLabel (shortcutLabel fn lab))
shortcutStatic fn (CmmStaticLit (CmmLabelDiffOff lbl1 lbl2 off))
= CmmStaticLit (CmmLabelDiffOff (shortcutLabel fn lbl1) lbl2 off)
-- slightly dodgy, we're ignoring the second label, but this
-- works with the way we use CmmLabelDiffOff for jump tables now.
shortcutStatic _ other_static
= other_static
shortBlockId
:: (BlockId -> Maybe JumpDest)
-> UniqSet Unique
-> BlockId
-> CLabel
shortBlockId fn seen blockid =
case (elementOfUniqSet uq seen, fn blockid) of
(True, _) -> mkAsmTempLabel uq
(_, Nothing) -> mkAsmTempLabel uq
(_, Just (DestBlockId blockid')) -> shortBlockId fn (addOneToUniqSet seen uq) blockid'
(_, Just (DestImm (ImmCLbl lbl))) -> lbl
(_, _other) -> panic "shortBlockId"
where uq = getUnique blockid
|
frantisekfarka/ghc-dsi
|
compiler/nativeGen/X86/Instr.hs
|
bsd-3-clause
| 38,581 | 0 | 17 | 12,308 | 9,059 | 4,597 | 4,462 | 592 | 92 |
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, TypeFamilies, DataKinds #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -pgmP cpphs -optP-traditional -optP--cpp #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Geometry.Instances.Num
-- Copyright : Copyright (C) 2015 Artem M. Chirkin <[email protected]>
-- License : BSD3
--
-- Maintainer : Artem M. Chirkin <[email protected]>
-- Stability : Experimental
-- Portability :
--
--
-----------------------------------------------------------------------------
module Data.Geometry.Instances.Num () where
import Data.Geometry.VectorMath
#if defined(ghcjs_HOST_OS)
import Data.Coerce (coerce)
import GHC.TypeLits (KnownNat)
import Data.Geometry.Prim.JSNum
instance KnownNat n => Num (Vector n t) where
{-# SPECIALIZE instance Num (Vector 4 Float) #-}
{-# SPECIALIZE instance Num (Vector 4 Double) #-}
{-# SPECIALIZE instance Num (Vector 4 Int) #-}
{-# SPECIALIZE instance Num (Vector 3 Float) #-}
{-# SPECIALIZE instance Num (Vector 3 Double) #-}
{-# SPECIALIZE instance Num (Vector 3 Int) #-}
{-# SPECIALIZE instance Num (Vector 2 Float) #-}
{-# SPECIALIZE instance Num (Vector 2 Double) #-}
{-# SPECIALIZE instance Num (Vector 2 Int) #-}
{-# INLINE (+) #-}
a + b = coerce $ plusJSVec (coerce a) (coerce b)
{-# INLINE (-) #-}
a - b = coerce $ minusJSVec (coerce a) (coerce b)
{-# INLINE (*) #-}
a * b = coerce $ timesJSVec (coerce a) (coerce b)
{-# INLINE negate #-}
negate = coerce . negateJSVec . coerce
{-# INLINE abs #-}
abs = coerce . absJSVec . coerce
{-# INLINE signum #-}
signum = coerce . signumJSVec . coerce
{-# INLINE fromInteger #-}
fromInteger i = v
where v = coerce . broadcastJSVec (fromNum (fromInteger i :: Int)) $ dim v
instance KnownNat n => Num (Matrix n t) where
{-# SPECIALIZE instance Num (Matrix 4 Float) #-}
{-# SPECIALIZE instance Num (Matrix 4 Double) #-}
{-# SPECIALIZE instance Num (Matrix 4 Int) #-}
{-# SPECIALIZE instance Num (Matrix 3 Float) #-}
{-# SPECIALIZE instance Num (Matrix 3 Double) #-}
{-# SPECIALIZE instance Num (Matrix 3 Int) #-}
{-# SPECIALIZE instance Num (Matrix 2 Float) #-}
{-# SPECIALIZE instance Num (Matrix 2 Double) #-}
{-# SPECIALIZE instance Num (Matrix 2 Int) #-}
{-# INLINE (+) #-}
a + b = coerce $ plusJSVec (coerce a) (coerce b)
{-# INLINE (-) #-}
a - b = coerce $ minusJSVec (coerce a) (coerce b)
{-# INLINE (*) #-}
a * b = coerce $ timesJSVec (coerce a) (coerce b)
{-# INLINE negate #-}
negate = coerce . negateJSVec . coerce
{-# INLINE abs #-}
abs = coerce . absJSVec . coerce
{-# INLINE signum #-}
signum = coerce . signumJSVec . coerce
{-# INLINE fromInteger #-}
fromInteger i = v
where v = coerce $ broadcastJSVec (fromNum (fromInteger i :: Int)) (n*n)
n = dim v
#else
import GHC.Exts
import GHC.Int
import Foreign.C.Types
import Data.Geometry.Prim.Int32X4
import Data.Geometry.Prim.FloatX3
import Data.Geometry.Prim.FloatX4
import Data.Geometry.Types
#define emptyc(x) x
-- params: type, vectortype, Vector constr, Matrix constr, Elem constr, Elem newtype
#define NUMV(T,VT,P,VC,EC,EC2) \
instance Num (Vector P T) where { \
{-# INLINE (+) #-}; \
(VC a) + (VC b) = VC (plus/**/VT a b); \
{-# INLINE (-) #-}; \
(VC a) - (VC b) = VC (minus/**/VT a b); \
{-# INLINE (*) #-}; \
(VC a) * (VC b) = VC (times/**/VT a b); \
{-# INLINE negate #-}; \
negate (VC a) = VC (negate/**/VT a); \
{-# INLINE abs #-}; \
abs (VC a) = VC (abs/**/VT a); \
{-# INLINE signum #-}; \
signum (VC a) = VC (signum/**/VT a); \
{-# INLINE fromInteger #-}; \
fromInteger i = case fromInteger i of \
{EC2(EC f) -> VC (broadcast/**/VT f)}}
NUMV(Int32,Int32X4#,4,V4I32,I32#, emptyc)
NUMV(Int,Int32X4#,4,V4I,I#, emptyc)
NUMV(CInt,Int32X4#,4,V4CI,I32#,CInt)
NUMV(Float,FloatX4#,4,V4F,F#, emptyc)
NUMV(CFloat,FloatX4#,4,V4CF,F#,CFloat)
NUMV(Float,FloatX3#,3,V3F,F#, emptyc)
NUMV(CFloat,FloatX3#,3,V3CF,F#,CFloat)
-- params: type, vectortype, Vector constr, Matrix constr, Elem constr, Elem newtype
#define NUM4M(T,VT,MC,EC,EC2) \
instance Num (Matrix 4 T) where { \
{-# INLINE (+) #-}; \
(MC a1 a2 a3 a4) + (MC b1 b2 b3 b4) = MC (plus/**/VT a1 b1) \
(plus/**/VT a2 b2) \
(plus/**/VT a3 b3) \
(plus/**/VT a4 b4); \
{-# INLINE (-) #-}; \
(MC a1 a2 a3 a4) - (MC b1 b2 b3 b4) = MC (minus/**/VT a1 b1) \
(minus/**/VT a2 b2) \
(minus/**/VT a3 b3) \
(minus/**/VT a4 b4); \
{-# INLINE (*) #-}; \
(MC a1 a2 a3 a4) * (MC b1 b2 b3 b4) = MC (times/**/VT a1 b1) \
(times/**/VT a2 b2) \
(times/**/VT a3 b3) \
(times/**/VT a4 b4); \
{-# INLINE negate #-}; \
negate (MC a1 a2 a3 a4) = MC (negate/**/VT a1) \
(negate/**/VT a2) \
(negate/**/VT a3) \
(negate/**/VT a4); \
{-# INLINE abs #-}; \
abs (MC a1 a2 a3 a4) = MC (abs/**/VT a1) \
(abs/**/VT a2) \
(abs/**/VT a3) \
(abs/**/VT a4); \
{-# INLINE signum #-}; \
signum (MC a1 a2 a3 a4) = MC (signum/**/VT a1) \
(signum/**/VT a2) \
(signum/**/VT a3) \
(signum/**/VT a4); \
{-# INLINE fromInteger #-}; \
fromInteger i = case fromInteger i of \
{EC2(EC f) -> case broadcast/**/VT f of b -> MC b b b b} }
NUM4M(Int32,Int32X4#,M4I32,I32#, emptyc)
NUM4M(Int,Int32X4#,M4I,I#, emptyc)
NUM4M(CInt,Int32X4#,M4CI,I32#,CInt)
NUM4M(Float,FloatX4#,M4F,F#, emptyc)
NUM4M(CFloat,FloatX4#,M4CF,F#,CFloat)
-- params: type, vectortype, Vector constr, Matrix constr, Elem constr, Elem newtype
#define NUM3M(T,VT,MC,EC,EC2) \
instance Num (Matrix 3 T) where { \
{-# INLINE (+) #-}; \
(MC a1 a2 a3) + (MC b1 b2 b3) = MC (plus/**/VT a1 b1) \
(plus/**/VT a2 b2) \
(plus/**/VT a3 b3); \
{-# INLINE (-) #-}; \
(MC a1 a2 a3) - (MC b1 b2 b3) = MC (minus/**/VT a1 b1) \
(minus/**/VT a2 b2) \
(minus/**/VT a3 b3); \
{-# INLINE (*) #-}; \
(MC a1 a2 a3) * (MC b1 b2 b3) = MC (times/**/VT a1 b1) \
(times/**/VT a2 b2) \
(times/**/VT a3 b3); \
{-# INLINE negate #-}; \
negate (MC a1 a2 a3) = MC (negate/**/VT a1) \
(negate/**/VT a2) \
(negate/**/VT a3); \
{-# INLINE abs #-}; \
abs (MC a1 a2 a3) = MC (abs/**/VT a1) \
(abs/**/VT a2) \
(abs/**/VT a3); \
{-# INLINE signum #-}; \
signum (MC a1 a2 a3) = MC (signum/**/VT a1) \
(signum/**/VT a2) \
(signum/**/VT a3); \
{-# INLINE fromInteger #-}; \
fromInteger i = case fromInteger i of \
{EC2(EC f) -> case broadcast/**/VT f of b -> MC b b b} }
NUM3M(Float,FloatX3#,M3F,F#, emptyc)
NUM3M(CFloat,FloatX3#,M3CF,F#,CFloat)
#endif
|
achirkin/fastvec
|
src/Data/Geometry/Instances/Num.hs
|
bsd-3-clause
| 9,470 | 0 | 14 | 4,232 | 510 | 285 | 225 | -1 | -1 |
module Turbinado.Environment.Header (
module Turbinado.Environment.Header,
module Network.HTTP.Headers
) where
import Data.Maybe
import Network.HTTP
import Network.HTTP.Headers
import Turbinado.Controller.Monad
import Turbinado.Environment.Types
import Turbinado.Environment.Request
import Turbinado.Utility.Data
-- | Attempts to pull a HTTP header value.
getHeader :: (HasEnvironment m) => HeaderName -> m (Maybe String)
getHeader h = do e <- getEnvironment
return $ findHeader h (fromJust' "Header: getHeader" $ getRequest e)
-- | Unsafe version of getHeader. Fails if the key is not found.
getHeader_u :: (HasEnvironment m) => HeaderName -> m String
getHeader_u h = do h' <- getHeader h
maybe (error $ "getHeader_u : key does not exist - \"" ++ (show h) ++ "\"")
return
h'
|
abuiles/turbinado-blog
|
Turbinado/Environment/Header.hs
|
bsd-3-clause
| 874 | 0 | 12 | 205 | 202 | 110 | 92 | 18 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
module Hadron.Join
(
DataDefs
, DataSet (..)
, JoinType (..)
, JoinKey
, joinMain
, joinMapper
, joinReducer
, joinOpts
-- * TODO: To be put into an Internal module
, JoinAcc (..)
, bufToStr
) where
-------------------------------------------------------------------------------
import Control.Lens
import qualified Data.ByteString.Char8 as B
import Data.Conduit
import qualified Data.Conduit.List as C
import Data.Default
import Data.Hashable
import qualified Data.HashMap.Strict as HM
import Data.List
import Data.Monoid as M
import Data.Ord
import Data.Serialize
import Data.String
import qualified Data.Vector as V
import GHC.Generics
-------------------------------------------------------------------------------
import Hadron.Basic
-------------------------------------------------------------------------------
type DataDefs = [(DataSet, JoinType)]
data JoinType = JRequired | JOptional
deriving (Eq,Show,Read,Ord)
newtype DataSet = DataSet { getDataSet :: B.ByteString }
deriving (Eq,Show,Read,Ord,Serialize,Generic,Hashable,IsString)
type JoinKey = B.ByteString
-- | We are either buffering input rows or have started streaming, as
-- we think we're now receiving the last table we were expecting.
data JoinAcc a =
Buffering {
bufData :: ! (HM.HashMap DataSet [a])
-- ^ Buffer of in-memory retained data. We have to retain (n-1) of
-- the input datasets and we can then start emitting rows in
-- constant-space for the nth dataset.
}
| Streaming { strStems :: V.Vector a }
deriving (Eq,Show)
instance Default (JoinAcc a) where
def = Buffering mempty
-------------------------------------------------------------------------------
-- | Convert a buffering state to a ready-to-stream state. Once this
-- conversion is done, we'll start emitting output rows immediately
-- and in constant space.
bufToStr
:: Monoid a
=> DataDefs
-- ^ Table definitions for the current join
-> JoinAcc a
-- ^ Buffering
-> JoinAcc a
-- ^ Streaming
bufToStr defs Buffering{..} = Streaming rs
where
rs = V.fromList $ maybe [] (map M.mconcat . sequence) groups
-- | Maybe will reduce to Nothing if any of the Inner joins is
-- missing.
groups = mapM (flip HM.lookup data' . fst) defs
data' = foldl' step bufData defs
step m (_, JRequired) = m
step m (ds, JOptional) = HM.insertWith insMissing ds [mempty] m
insMissing new [] = new
insMissing _ old = old
bufToStr _ _ = error "bufToStr can only convert a Buffering to a Streaming"
-- | Given a new row in the final dataset of the joinset, emit all the
-- joined rows immediately.
emitStream :: (Monad m, Monoid b) => JoinAcc b -> b -> ConduitM i b m ()
emitStream Streaming{..} a = V.mapM_ (yield . mappend a) strStems
emitStream _ _ = error "emitStream can't be called unless it's in Streaming mode."
-------------------------------------------------------------------------------
joinOpts :: MROptions
joinOpts = def { _mroPart = (Partition 2 1) }
-------------------------------------------------------------------------------
-- | Make join reducer from given table definitions
joinReducer
:: (Show r, Monoid r)
=> [(DataSet, JoinType)]
-- ^ Table definitions
-> Reducer CompositeKey r r
joinReducer fs = red def
where
red ja = do
next <- await
case next of
Nothing -> joinFinalize fs ja
Just x -> do
ja' <- joinReduceStep fs ja x
red $! ja'
-------------------------------------------------------------------------------
joinFinalize
:: (Monad m, Monoid b)
=> [(DataSet, JoinType)]
-> JoinAcc b
-> ConduitM i b m ()
-- we're still in buffering, so nothing has been emitted yet. one of
-- the tables (and definitely the last table) did not have any input
-- at all. we'll try to emit in case the last table is not a required
-- table.
--
-- notice that unlike other calls to bufToStr, we include ALL the
-- tables here so that if the last table was required, it'll all
-- collapse to an empty list and nothing will be emitted.
joinFinalize fs buf@Buffering{} =
let str = bufToStr fs buf
in emitStream str mempty
-- we're already in streaming, so we've been emitting output in
-- real-time. nothing left to do at this point.
joinFinalize _ Streaming{} = return ()
-------------------------------------------------------------------------------
-- | Make a step function for a join operation
joinReduceStep
:: (Monad m, Monoid b)
=> DataDefs
-> JoinAcc b
-> (CompositeKey, b)
-> ConduitM i b m (JoinAcc b)
joinReduceStep fs buf@Buffering{..} (k, x) =
-- Accumulate until you start seeing the last table. We'll start
-- emitting immediately after that.
case ds' == lastDataSet of
False -> -- traceShow accumulate $
return $! accumulate
True ->
let xs = filter ((/= ds') . fst) fs
in joinReduceStep fs (bufToStr xs buf) (k,x)
where
fs' = sortBy (comparing fst) fs
lastDataSet = fst $ last fs'
accumulate =
Buffering { bufData = HM.insertWith add ds' [x] bufData
}
add new old = new ++ old
ds = last k
ds' = DataSet ds
joinReduceStep _ str@Streaming{} (_,x) = emitStream str x >> return str
-- | Helper for easy construction of specialized join mapper.
--
-- This mapper identifies the active dataset from the currently
-- streaming filename and uses filename to determine how the mapping
-- shoudl be done.
joinMapper
:: (String -> DataSet)
-- ^ Infer dataset from current filename
-> (DataSet -> Mapper a CompositeKey r)
-- ^ Given a dataset, map it to a common data type
-> Mapper a CompositeKey r
joinMapper getDS mkMap = do
fi <- getFileName
let ds = getDS fi
mkMap ds =$= C.map (go ds)
where
go ds (jk, a) = (jk ++ [getDataSet ds], a)
------------------------
-- A Main Application --
------------------------
-------------------------------------------------------------------------------
-- | Make a stand-alone program that can act as a mapper and reducer,
-- performing the join defined here.
--
-- For proper higher level operation, see the 'Controller' module.
joinMain
:: (Serialize r, Monoid r, Show r)
=> DataDefs
-- ^ Define your tables
-> (String -> DataSet)
-- ^ Infer dataset from input filename
-> (DataSet -> Mapper B.ByteString CompositeKey r)
-- ^ Map input stream to a join key and the common-denominator
-- uniform data type we know how to 'mconcat'.
-> Prism' B.ByteString r
-- ^ Choose serialization method for final output.
-> IO ()
joinMain fs getDS mkMap out = mapReduceMain joinOpts pSerialize mp rd
where
mp = joinMapper getDS mkMap
rd = joinReducer fs =$= C.mapMaybe (firstOf (re out))
|
Soostone/hadron
|
src/Hadron/Join.hs
|
bsd-3-clause
| 7,386 | 2 | 15 | 1,876 | 1,468 | 807 | 661 | 127 | 3 |
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fcontext-stack42 #-}
module Games.Chaos2010.Database.Section_orderv where
import Games.Chaos2010.Database.Fields
import Database.HaskellDB.DBLayout
type Section_orderv =
Record
(HCons (LVPair Section_order (Expr (Maybe Int)))
(HCons (LVPair Spell_category (Expr (Maybe String))) HNil))
section_orderv :: Table Section_orderv
section_orderv = baseTable "section_orderv"
|
JakeWheat/Chaos-2010
|
Games/Chaos2010/Database/Section_orderv.hs
|
bsd-3-clause
| 466 | 0 | 15 | 67 | 104 | 58 | 46 | 11 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Data.List.Zalgo
-- Copyright : (C) 2015 mniip
-- License : BSD3
-- Maintainer : mniip <[email protected]>
-- Stability : experimental
-- Portability : portable
--
-- A few efficient list-processing functions using the Z-function, which is
-- defined as:
--
-- > (z xs) !! i
--
-- is the length of the largest proper substring of @xs@ ending at position @i@,
-- such that it equals the beginning of @xs@.
--
-- For example:
--
-- > .-----. .-----.
-- > a b a c a b a a a b a b a c d
-- > 0 0 1 0 1 2 3 1 1 2 3 2 3 4 0
-- > ^
--
-- The marked substrings are equal, hence the value at the marked location is
-- their length, 4.
--------------------------------------------------------------------------------
module Data.List.Zalgo
(
zFun,
isInfixOf,
indexOf,
-- * Custom predicates
-- $predicates
zFunBy,
isInfixBy,
indexBy,
-- * Generic functions
-- $generic
genericZFun,
genericIndexOf,
genericZFunBy,
genericIndexBy
)
where
import Data.List hiding (isInfixOf)
import Data.Maybe
import Data.List.Zalgo.Internal
joinLists :: [a] -> [a] -> [Maybe a]
joinLists n h = map Just n ++ Nothing:map Just h
-- | /O(N)./ Compute the Z-function for a list.
zFun :: Eq a => [a] -> [Int]
zFun xs = map zLength $ zTraverse xs
-- | /O(N+H)./ @isInfixOf needle haystack@ tests whether needle is fully
-- contained somewhere in haystack.
isInfixOf :: Eq a => [a] -> [a] -> Bool
isInfixOf n h = isJust $ indexOf n h
-- | /O(N+H)./ @indexOf needle haystack@ returns the index at which needle
-- is found in haystack, or Nothing if it's not.
indexOf :: Eq a => [a] -> [a] -> Maybe Int
indexOf n h = go 0 $ zFun $ joinLists n h
where
ln = length n
go n [] = Nothing
go n (l:ls)
| l == ln = Just (n - ln - ln)
| otherwise = n `seq` go (n + 1) ls
-- $predicates
--
-- The @...By@ set of functions takes a custom equality predicate, and due to
-- the optimized nature of the algorithm, passed predicate must conform to
-- some laws:
--
-- > Commutativity: a == b => b == a
-- > Inverse commutativity: a /= b => b /= a
-- > Transitivity: a == b and b == c => a == c
-- > Inverse transitivity: a == b and b /= c => a /= c
--
-- If these laws do not hold, the behavior is undefined.
-- | /O(N) and O(N) calls to the predicate./ Compute the Z-function using a
-- custom equality predicate.
zFunBy :: (a -> a -> Bool) -> [a] -> [Int]
zFunBy eq xs = map zLength $ zTraverseBy eq xs
-- | /O(N+H) and O(N+H) calls to the predicate./ Compute 'isInfixOf' using a
-- custom equality predicate.
isInfixBy :: (a -> a -> Bool) -> [a] -> [a] -> Bool
isInfixBy eq n h = isJust $ indexBy eq n h
-- | /O(N+H) and O(N+H) calls to the predicate./ Compute 'indexOf' using a
-- cusom equality predicate.
indexBy :: (a -> a -> Bool) -> [a] -> [a] -> Maybe Int
indexBy eq n h = go 0 $ zFunBy (maybeEq eq) $ joinLists n h
where
ln = length n
go n [] = Nothing
go n (l:ls)
| l == ln = Just (n - ln - ln)
| otherwise = n `seq` go (n + 1) ls
maybeEq eq (Just x) (Just y) = x `eq` y
maybeEq _ _ _ = False
-- $generic
--
-- Some of the functions are generalized over the type of the numbers they
-- return, but keep in mind that the amount of arithmetic operations is linear.
genericZFun :: (Num i, Eq a) => [a] -> [i]
genericZFun xs = map (fromMaybe 0 . gzLength) $ gzTraverse xs
genericIndexOf :: (Eq i, Num i, Eq a) => [a] -> [a] -> Maybe i
genericIndexOf n h = go 0 $ genericZFun $ joinLists n h
where
ln = genericLength n
go n [] = Nothing
go n (l:ls)
| l == ln = Just (n - ln - ln)
| otherwise = n `seq` go (n + 1) ls
genericZFunBy :: Num i => (a -> a -> Bool) -> [a] -> [i]
genericZFunBy eq xs = map (fromMaybe 0 . gzLength) $ gzTraverseBy eq xs
genericIndexBy :: (Eq i, Num i) => (a -> a -> Bool) -> [a] -> [a] -> Maybe i
genericIndexBy eq n h = go 0 $ genericZFunBy (maybeEq eq) $ joinLists n h
where
ln = genericLength n
go n [] = Nothing
go n (l:ls)
| l == ln = Just (n - ln - ln)
| otherwise = n `seq` go (n + 1) ls
maybeEq eq (Just x) (Just y) = x `eq` y
maybeEq _ _ _ = False
|
bitemyapp/zalgo
|
src/Data/List/Zalgo.hs
|
bsd-3-clause
| 4,480 | 0 | 11 | 1,280 | 1,225 | 659 | 566 | 61 | 3 |
{-# OPTIONS_HADDOCK prune #-}
----------------------------------------------------------------------
-- |
-- Module : ForSyDe.Atom.ExB.Absent
-- Copyright : (c) George Ungureanu, 2015-2016
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- This module implements the constructors and assocuated utilities of
-- a type which extends the behavior of a function to express "absent
-- events" (see <ForSyDe-Atom.html#halbwachs91 [Halbwachs91]>).
--
-- The 'AbstExt' type can be used directly with the atom patterns
-- defined in "ForSyDe.Atom.ExB", and no helpers or utilities are
-- needed. Example usage:
--
-- >>> res21 (+) (Prst 1) (Prst 2)
-- 3
-- >>> res21 (+) Abst Abst
-- ⟂
-- >>> filter Abst (Prst 1)
-- ⟂
-- >>> filter (Prst False) (Prst 1)
-- ⟂
-- >>> filter (Prst True) (Prst 1)
-- 1
-- >>> filter' False 1 :: AbstExt Int
-- ⟂
-- >>> filter' True 1 :: AbstExt Int
-- 1
-- >>> degen 0 (Prst 1)
-- 1
-- >>> degen 0 Abst
-- 0
-- >>> ignore11 (+) 1 (Prst 1)
-- 2
-- >>> ignore11 (+) 1 Abst
-- 1
--
-- Incorrect usage (not covered by @doctest@):
--
-- > λ> res21 (+) (Prst 1) Abst
-- > *** Exception: [ExB.Absent] Illegal occurrence of an absent and present event
----------------------------------------------------------------------
module ForSyDe.Atom.ExB.Absent (
AbstExt(..),
-- | Module "ForSyDe.Atom.ExB" is re-exported for convenience, to
-- access the atom patterns more easily.
module ForSyDe.Atom.ExB
) where
import ForSyDe.Atom.ExB
import Prelude hiding (filter)
-- | The 'AbstExt' type extends the base type with the \'\(\bot\)\'
-- symbol denoting the absence of a value/event (see
-- <ForSyDe-Atom.html#halbwachs91 [Halbwachs91]>).
data AbstExt a = Abst -- ^ \(\bot\) denotes the absence of a value
| Prst a -- ^ \(\top\) a present event with a value
deriving (Eq)
-- | Implements the absent semantics of the extended behavior atoms.
instance ExB AbstExt where
------------------------
extend = Prst
------------------------
(/.\) = fmap
------------------------
(/*\) = (<*>)
------------------------
(Prst True) /&\ a = a
_ /&\ _ = Abst
------------------------
_ /!\ Prst a = a
a /!\ _ = a
------------------------
-- | Shows 'Abst' as \(\bot\), while a present event is represented
-- with its value.
instance Show a => Show (AbstExt a) where
showsPrec _ x = showsPrst x
where showsPrst Abst = (++) "\10178"
showsPrst (Prst x) = (++) (show x)
-- | Reads the \'_\' character to an 'Abst' and a normal value to
-- 'Prst'-wrapped one.
instance Read a => Read (AbstExt a) where
readsPrec _ x = readsAbstExt x
where
readsAbstExt s =
[(Abst, r1) | ("_", r1) <- lex s] ++
[(Prst x, r3) | (x, r3) <- reads s]
-- | 'Functor' instance. Bypasses the special values and maps a
-- function to the wrapped value.
instance Functor AbstExt where
fmap _ Abst = Abst
fmap f (Prst x) = Prst (f x)
-- | 'Applicative' instance, defines a resolution. Check source code
-- for the lifting rules.
instance Applicative AbstExt where
pure = Prst
(Prst x) <*> (Prst y) = Prst (x y)
Abst <*> Abst = Abst
_ <*> _ = error "[ExB.Absent] Illegal occurrence of an absent and present event"
|
forsyde/forsyde-atom
|
src/ForSyDe/Atom/ExB/Absent.hs
|
bsd-3-clause
| 3,386 | 0 | 12 | 746 | 500 | 296 | 204 | -1 | -1 |
module Hack.Frontend.Happstack where
import Data.Foldable (toList)
import Data.Maybe
import Hack (http, pathInfo, scriptName, queryString, hackInput, serverName, serverPort, Application)
import Happstack.Server
import Happstack.Server.HTTP.Types (Request (..), Version (Version))
import Happstack.Server.SURI (parse)
import Network.URI (unEscapeString)
import qualified Data.ByteString.Char8 as S
import qualified Hack
import qualified Hack as Hack
import qualified Happstack.Server as H
serverPartToApp :: (ToMessage b) => ServerPartT IO b -> Application
serverPartToApp = convert . processRequest
convert :: (Request -> IO Response) -> Application
convert f = \env -> do
let rq = toHappstackRequest env
rs <- f rq
let r = toHackResponse rs
return r
toHackResponse :: Response -> Hack.Response
toHackResponse r = Hack.Response
{
Hack.body = rsBody r
, Hack.status = rsCode r
, Hack.headers = map convertHeader $ toList (rsHeaders r)
}
-- | Sets all the headers coming from Happstack
convertHeader :: HeaderPair -> (String, String)
convertHeader (HeaderPair k v) = (S.unpack k, S.unpack (last v))
-- | Converts one request into another
toHappstackRequest :: Hack.Env -> Request
toHappstackRequest env =
tmpRequest
{ rqInputs = queryInput uri ++ bodyInput tmpRequest }
where
uri = fromJust $ parse $ concat $ map (\f -> f env)
[ serverName
, const ":"
, show . serverPort
, scriptName
, pathInfo
, add_q . queryString
]
tmpRequest =
Request { rqMethod = convertRequestMethod $ Hack.requestMethod env
, rqPaths = split '/' $ unescape $ pathInfo env
, rqUri = unescape $ scriptName env ++ pathInfo env
, rqQuery = unescape $ add_q $ queryString env
, rqInputs = []
, rqCookies = readCookies $ http env
, rqVersion = Version 1 1
, rqHeaders = mkHeaders $ http env
, rqBody = Body $ hackInput env
, rqPeer = (serverName env, serverPort env)
}
unescape = unEscapeString
convertRequestMethod Hack.OPTIONS = OPTIONS
convertRequestMethod Hack.GET = GET
convertRequestMethod Hack.HEAD = HEAD
convertRequestMethod Hack.POST = POST
convertRequestMethod Hack.PUT = PUT
convertRequestMethod Hack.DELETE = DELETE
convertRequestMethod Hack.TRACE = TRACE
convertRequestMethod Hack.CONNECT = CONNECT
readCookies = map cookieWithName
. either (const []) id . parseCookies . fromMaybe "" . lookup "Cookie"
add_q [] = []
add_q x = '?' : x
cookieWithName :: H.Cookie -> (String, H.Cookie)
cookieWithName x = (H.cookieName x, x)
-- | Transforms a ServerPartT into a function. This is a copy of simpleHTTP'
processRequest :: (ToMessage b, Monad m, Functor m) => ServerPartT m b -> Request -> m Response
processRequest hs req = (runWebT $ runServerPartT hs req) >>= (return . (maybe standardNotFound id))
where
standardNotFound = H.setHeader "Content-Type" "text/html" $ toResponse "Not found"
-- | Splits a list by character, the resulting lists don't have the character in them.
split :: Char -> String -> [String]
split c cs = filter (not.null) $ worker [] cs
where worker acc [] = [reverse acc]
worker acc (c':cs') | c==c' = reverse acc:worker [] cs'
worker acc (c':cs') = worker (c':acc) cs'
|
nfjinjing/hack-frontend-happstack
|
src/Hack/Frontend/Happstack.hs
|
bsd-3-clause
| 3,519 | 2 | 14 | 918 | 1,044 | 557 | 487 | 72 | 9 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
-- | This module implements SSA value numbering over the low-level Dalvik IR
--
-- The algorithm used is from Braun et al
-- (<http://www.cdl.uni-saarland.de/papers/bbhlmz13cc.pdf>). The
-- labeling maps each operand of a low-level Dalvik instruction to
-- the SSA number of that operand. Note that SSA numbers are only
-- required for *instructions*. Constants are, well, constant, and
-- can be handled directly during translation.
--
-- Translation to the SSA IR requires knot tying. Many instructions
-- can be ignored (moves, data pseudo-registers). Instructions with a
-- destination register get assigned the number placed on their
-- destination (in fact, they create a new value by virtue of having
-- that destination).
--
-- > newinstance r2 Double
--
-- is basically equivalent to
--
-- > r2 <- newinstance Double
--
-- So r2 is a new SSA value here.
--
-- > loop:
-- > binop Add r1 r1 r2
-- > br (r1 < 100) loop
--
-- Should translate into something like
--
-- > loop:
-- > r4 <- phi(r3, r1)
-- > r3 <- binop add r4 r2
-- > br (r4 < 100) loop
module Dalvik.SSA.Internal.Labeling (
-- * Data Types
Label(..),
Labeling(..),
ExceptionRange(..),
FromRegister(..),
labelMethod,
labelingInstructionAt,
labelingPhiIncomingValues,
filterWidePairs,
-- * Testing
prettyLabeling,
generatedLabelsAreUnique
) where
import qualified Control.Monad.Catch as E
import Control.Monad ( filterM, forM_, liftM )
import Control.Monad.Trans.Class
import Control.Monad.Trans.RWS.Strict
import qualified Data.ByteString.Char8 as BS
import qualified Data.Foldable as F
import Data.Function ( on )
import Data.IntSet ( IntSet )
import qualified Data.IntSet as IS
import Data.Map ( Map )
import qualified Data.Map as M
import Data.Maybe ( fromMaybe )
import qualified Data.List as L
import Data.Set ( Set )
import qualified Data.Set as S
import Data.Vector ( Vector )
import qualified Data.Vector as V
import Data.Word ( Word8, Word16 )
import Text.PrettyPrint as PP
import Text.Printf
import Dalvik.Types as DT
import Dalvik.Instruction as DT
import Dalvik.SSA.Internal.BasicBlocks
import Dalvik.SSA.Internal.Names
import Dalvik.SSA.Internal.RegisterAssignment
-- | Types of label. Arguments and Phi nodes have special labels
-- carrying extra information.
data Label = SimpleLabel Int
| PhiLabel BlockNumber [BlockNumber] Int
| ArgumentLabel BS.ByteString Int
deriving (Show)
labelNumber :: Label -> Int
labelNumber (SimpleLabel i) = i
labelNumber (PhiLabel _ _ i) = i
labelNumber (ArgumentLabel _ i) = i
instance Eq Label where
(==) = (==) `on` labelNumber
instance Ord Label where
compare = compare `on` labelNumber
-- | A labeling assigns an SSA number/Label to a register at *each*
-- 'Instruction'.
data Labeling =
Labeling { labelingReadRegs :: Map Int (Map Word16 Label)
, labelingWriteRegs :: Map Int Label
, labelingPhis :: Map Label (Set Label)
-- ^ The incoming values for each phi node (phi labels are the map keys)
, labelingPhiSources :: Map Label (Map Label (Set BlockNumber))
-- ^ Each key is (PhiLabel, IncomingValueLabel) and the
-- value associated is the basic block that the incoming
-- value came from. We want to separate them out so that
-- trivial phi detection is simple (and left up to the
-- Set). This map can safely have dead values, since it
-- will only be read from at SSA translation time, and
-- only relevant values will be queried.
, labelingBlockPhis :: Map BlockNumber [Label]
-- ^ For each basic block, note which phi labels belong
-- to it. This will be needed when we translate basic
-- blocks to the SSA IR.
, labelingBasicBlocks :: BasicBlocks
, labelingInstructions :: Vector Instruction
, labelingParameters :: [Label]
-- ^ The argument labels allocated for this function
}
deriving (Eq, Ord, Show)
-- | Look up all of the incoming values (tagged with the basic block
-- that they came from) for a phi node label. The basic block numbers
-- are stored separately to make trivial phi elimination simpler, so
-- we need to attach them to their labels here.
labelingPhiIncomingValues :: Labeling -> Label -> [(BlockNumber, Label)]
labelingPhiIncomingValues labeling phi = concatMap addBlockNumber (S.toList ivs)
where
Just ivs = M.lookup phi (labelingPhis labeling)
addBlockNumber iv
| Just m <- M.lookup phi (labelingPhiSources labeling)
, Just tagged <- M.lookup iv m =
zip (S.toList tagged) (repeat iv)
| otherwise = error ("Missing labelingPhiSources for " ++ show phi)
-- | The mutable state we are modifying while labeling. This mainly
-- models the register state and phi operands.
data LabelState =
LabelState { currentDefinition :: Map Word16 (Map BlockNumber Label)
-- ^ We track the current definition of each register at
-- each block.
, instructionLabels :: Map Int (Map Word16 Label)
-- ^ This is separate from @currentDefinition@ because
-- that field is mutated.
, instructionResultLabels :: Map Int Label
-- ^ Store the label of instructions that produce
-- a result separately from the normal map. This is only
-- really required because of the compound instructions
-- 'IBinopAssign' and 'FBinopAssign'
, registersWithLabel :: Map Label (Set (Word16, BlockNumber))
-- ^ A reverse mapping to let us know which registers
-- (in which block) refer to a label in
-- 'currentDefinition'. We need this reverse map to
-- efficiently update just those entries when
-- eliminating phi nodes.
, phiOperands :: Map Label (Set Label)
-- ^ Operands of each phi node. They are stored
-- separately to make them easier to update (since they
-- do need to be updated in several cases).
, phiOperandSources :: Map Label (Map Label (Set BlockNumber))
-- ^ Record where each phi operand came from (a block
-- number). Note that one operand could have come from
-- more than one block (hence the 'Set'). This is only
-- used when constructing the Labeling.
, incompletePhis :: Map BlockNumber (Map Word16 Label)
-- ^ These are the phi nodes in each block that cannot
-- be resolved yet because there are unfilled
-- predecessor blocks. Unfilled predecessors could add
-- definitions that affect the phi node by the time
-- they are filled. Once those blocks are filled, the
-- incomplete phis will be filled in.
, eliminatedPhis :: Map Label Label
-- ^ If we have eliminated a phi node, track what
-- references were replaced with. This must be
-- searched transitively.
, valueUsers :: Map Label (Set Use)
-- ^ Record the users of each value. This index is
-- necessary for phi simplification. When a trivial
-- phi node is found, all uses of that phi node need to
-- be replaced by a simpler phi node or another value.
-- These users will be used to modify @instructionLabels@.
, filledBlocks :: IntSet
-- ^ A block is filled if all of its instructions have been
-- labelled.
, sealedBlocks :: IntSet
-- ^ A block is sealed if all of its predecessors are
-- filled. Phi node operands are only computed for
-- sealed blocks (so that all operands are available).
, labelCounter :: Int
-- ^ A source of label unique IDs
}
data Use = NormalUse Int Instruction Word16
| PhiUse Label
deriving (Eq, Ord, Show)
data LabelEnv =
LabelEnv { envInstructionStream :: Vector Instruction
, envBasicBlocks :: BasicBlocks
-- ^ Information about basic blocks in the instruction
-- stream
, envRegisterAssignment :: Map Word16 Label
-- ^ The map of argument registers to their labels
}
-- | Create a new empty SSA labeling environment. This includes
-- computing CFG information.
emptyEnv :: [(BS.ByteString, Word16)] -> [ExceptionRange] -> Vector Instruction -> LabelEnv
emptyEnv argRegs ers ivec =
LabelEnv { envInstructionStream = ivec
, envBasicBlocks = findBasicBlocks ivec ers
, envRegisterAssignment =
fst $ L.foldl' allocateArgLabel (M.empty, 0) argRegs
}
where
allocateArgLabel (m, lno) (name, reg) =
(M.insert reg (ArgumentLabel name lno) m, lno + 1)
-- | Create a new empty state. This state is initialized to account
-- for method arguments, which occupy the last @length argRegs@
-- registers. Wide arguments take two registers, but we only need to
-- worry about the first register in the pair (since the second is
-- never explicitly accessed).
emptyLabelState :: [(BS.ByteString, Word16)] -> LabelState
emptyLabelState argRegs =
LabelState { currentDefinition = fst $ L.foldl' addArgDef (M.empty, 0) argRegs
, instructionLabels = M.empty
, instructionResultLabels = M.empty
, registersWithLabel = M.empty
, phiOperands = M.empty
, phiOperandSources = M.empty
, incompletePhis = M.empty
, eliminatedPhis = M.empty
, valueUsers = M.empty
, filledBlocks = IS.empty
, sealedBlocks = IS.empty
, labelCounter = fromIntegral $ length argRegs
}
where
addArgDef (m, lno) (name, reg) =
let l = ArgumentLabel name lno
in (M.insertWith M.union reg (M.singleton 0 l) m, lno + 1)
-- | Look up the low-level Dalvik instruction at the given index into
-- the original instruction stream.
labelingInstructionAt :: Labeling -> Int -> Maybe Instruction
labelingInstructionAt l = (labelingInstructions l V.!?)
-- | Compute SSA value labels for each register at each instruction in
-- the given method. We also compute some extra information about
-- parameters and phi nodes that are required for a complete SSA
-- transformation.
--
-- See note [Overview] for details
labelMethod :: (E.MonadThrow m) => DT.DexFile -> DT.EncodedMethod -> m Labeling
labelMethod _ (DT.EncodedMethod mId _ Nothing) = E.throwM $ NoCodeForMethod mId
labelMethod dx em@(DT.EncodedMethod _ _ (Just codeItem)) = do
insts <- DT.decodeInstructions (codeInsns codeItem)
regMap <- methodRegisterAssignment dx em
ers <- methodExceptionRanges dx em
labelInstructions dx regMap ers insts
-- | Parse the try/catch description tables for this 'EncodedMethod'
-- from the DexFile. The tables are reduced to summaries
-- ('ExceptionRange') that are easier to work with.
methodExceptionRanges :: (E.MonadThrow m) => DT.DexFile -> EncodedMethod -> m [ExceptionRange]
methodExceptionRanges _ (DT.EncodedMethod mId _ Nothing) = E.throwM $ NoCodeForMethod mId
methodExceptionRanges dx (DT.EncodedMethod _ _ (Just codeItem)) =
mapM toExceptionRange (codeTryItems codeItem)
where
catches = V.fromList $ codeHandlers codeItem
toExceptionRange tryItem = do
let hOffset = fromIntegral $ tryHandlerOff tryItem
case V.findIndex ((==hOffset) . chHandlerOff) catches of
Nothing -> E.throwM $ NoHandlerAtOffset hOffset
Just cix -> do
let errMsg = error ("No catch handler entry for handler at offset " ++ show cix)
let ch = fromMaybe errMsg $ catches V.!? cix
typeNames <- mapM (\(tix, off) -> liftM (, off) (getTypeName dx tix)) (chHandlers ch)
return ExceptionRange { erOffset = tryStartAddr tryItem
, erCount = tryInsnCount tryItem
, erCatch = typeNames
, erCatchAll = chAllAddr ch
}
-- | Label a stream of raw Dalvik instructions with SSA numbers,
-- adding phi nodes at the beginning of appropriate basic blocks.
--
-- If an argument has no name, it will be assigned a generic one that
-- cannot conflict with the real arguments.
labelInstructions :: (E.MonadThrow m)
=> DT.DexFile
-> [(Maybe BS.ByteString, Word16)]
-- ^ A mapping of argument names to the register numbers
-> [ExceptionRange]
-- ^ Information about exception handlers in the method
-> [Instruction]
-- ^ The instruction stream for the method
-> m Labeling
labelInstructions df argRegs ers is = liftM fst $ evalRWST (label' df) e0 s0
where
s0 = emptyLabelState argRegs'
e0 = emptyEnv argRegs' ers ivec
ivec = V.fromList is
argRegs' = zipWith (curry nameAnonArgs) [0..] argRegs
nameAnonArgs :: (Int, (Maybe BS.ByteString, Word16)) -> (BS.ByteString, Word16)
nameAnonArgs (ix, (name, reg)) =
case name of
Just name' -> (name', reg)
Nothing -> (generateNameForParameter ix, reg)
-- | An environment to carry state for the labeling algorithm
type SSALabeller m = RWST LabelEnv () LabelState m
-- | Driver for labeling
label' :: (E.MonadThrow m) => DT.DexFile -> SSALabeller m Labeling
label' df = do
ivec <- asks envInstructionStream
argRegs <- asks envRegisterAssignment
-- For each argument to the function, add phantom Phi nodes in the
-- entry block. These are not needed in all cases - when they are
-- not necessary, they will later be removed by
-- 'tryRemoveTrivialPhi'. They are required because, without them,
-- registers containing arguments always appear to have a mapping to
-- that argument in 'readRegister'. In cases where there is a loop
-- backedge to the entry block, this is not actually the case (a phi
-- is required).
forM_ (M.toList argRegs) $ \(regNo, _) ->
makeIncomplete regNo 0
-- This is the actual labeling step
mapM_ (labelAndFillInstruction df) $ V.toList $ V.indexed ivec
-- Now pull out all of the information we need to save to use the
-- labeling.
s <- get
bbs <- asks envBasicBlocks
argLabels <- asks (M.elems . envRegisterAssignment)
return Labeling { labelingReadRegs = instructionLabels s
, labelingWriteRegs = instructionResultLabels s
, labelingPhis = phiOperands s
, labelingPhiSources = phiOperandSources s
, labelingBlockPhis = foldr (addPhiForBlock s) M.empty $ M.keys (phiOperands s)
, labelingBasicBlocks = bbs
, labelingInstructions = ivec
, labelingParameters = argLabels
}
where
-- Record the phi nodes introduced in each basic block. The key
-- thing to note here is that we do not include phi nodes with no
-- references.
addPhiForBlock s p@(PhiLabel bnum _ _) m
| Just _ <- M.lookup p (phiOperands s)
, maybe False (not . S.null) $ M.lookup p (valueUsers s)
= M.insertWith (++) bnum [p] m
| otherwise = m
addPhiForBlock _ _ m = m
-- | Label instructions and, if they end a block, mark the block as filled.
--
-- If we do fill a block, we have to see if this filling will let us
-- seal any other blocks. A block can be sealed if all of its
-- predecessors are filled.
labelAndFillInstruction :: (E.MonadThrow m) => DT.DexFile -> (Int, Instruction) -> SSALabeller m ()
labelAndFillInstruction df i@(ix, _) = do
bbs <- asks envBasicBlocks
-- If an instruction doesn't have a block number, it is dead code.
case instructionBlockNumber bbs ix of
Nothing -> return ()
Just bnum -> do
canSeal <- canSealBlock bnum
notSealed <- liftM not (blockIsSealed bnum)
case canSeal && notSealed of
True -> sealBlock bnum
False -> return ()
labelInstruction df i
case instructionEndsBlock bbs ix of
False -> return ()
True -> do
modify $ \s -> s { filledBlocks = IS.insert bnum (filledBlocks s) }
-- Check this block and all of its successors. For each one,
-- if all predecessors are filled, then seal (unless already sealed)
succs <- basicBlockSuccessorsM bnum
succs' <- filterM (liftM not . blockIsSealed) succs
forM_ succs' $ \ss -> do
canSealS <- canSealBlock ss
case canSealS of
False -> return ()
True -> sealBlock ss
-- | Algorithm 4 (section 2.3) from the SSA algorithm. This is called
-- once all of the predecessors of the block are filled. This
-- computes the phi operands for incomplete phis.
sealBlock :: (E.MonadThrow m) => BlockNumber -> SSALabeller m ()
sealBlock block = do
iphis <- gets incompletePhis
let blockPhis = maybe [] M.toList $ M.lookup block iphis
forM_ blockPhis $ \(reg, l) ->
addPhiOperands reg block l
modify makeSealed
where
makeSealed s = s { sealedBlocks = IS.insert block (sealedBlocks s) }
-- | Check if the given block is sealed (i.e., all of its predecessors
-- are filled).
blockIsSealed :: (E.MonadThrow m) => BlockNumber -> SSALabeller m Bool
blockIsSealed bname = do
sealed <- gets sealedBlocks
return $ IS.member bname sealed
-- | Add an empty phi node as a placeholder. The operands will be
-- filled in once the block is sealed.
addIncompletePhi :: (E.MonadThrow m) => Word16 -> BlockNumber -> Label -> SSALabeller m ()
addIncompletePhi reg block l = modify addP
where
addP s = s { incompletePhis =
M.insertWith M.union block (M.singleton reg l) (incompletePhis s)
}
-- | Check if we can seal a block (we can if all predecessors are filled).
canSealBlock :: (E.MonadThrow m) => BlockNumber -> SSALabeller m Bool
canSealBlock bid = do
ps <- basicBlockPredecessorsM bid
go ps
where
go [] = return True
go (p:ps) = do
f <- isFilled p
if f then go ps else return False
-- | This is the main part of the algorithm from the paper. Each
-- instruction is processed separately. Apply *read* before *write*
-- rules. This will update the per-instruction register map. That
-- map will be used for the translation step.
labelInstruction :: (E.MonadThrow m) => DT.DexFile -> (Int, Instruction) -> SSALabeller m ()
labelInstruction df (ix, inst) = do
bbs <- asks envBasicBlocks
let instBlock = basicBlockForInstruction bbs ix
let rr :: (E.MonadThrow m, FromRegister a) => a -> SSALabeller m ()
rr = recordReadRegister ix inst instBlock
-- If we are writing a wide register, we have to remove the
-- mapping for the second register of the pair.
rw :: (E.MonadThrow m, FromRegister a) => Bool -> a -> SSALabeller m ()
rw wide = recordWriteRegister wide ix instBlock
rrs :: (E.MonadThrow m, FromRegister a) => [a] -> SSALabeller m ()
rrs = mapM_ rr
case inst of
Nop -> return ()
-- Move isn't quite like other instructions. It is a
-- register-register move, and doesn't create a new value. It
-- just copies the contents of one register to another as a side
-- effect. The @rw@ function only applies to instructions that
-- generate a new SSA value.
--
-- In terms of implementation, we do *not* want to make
-- an entry in the instructionResultLabels table.
Move mt dst src -> do
l <- readRegister src instBlock
recordAssignment ix inst src l
writeRegisterLabel (mt == DT.MWide) dst instBlock l
recordAssignment ix inst dst l
-- This is a pseudo-move that takes an item off of the stack
-- (following a call or other special instruction) and stuffs it
-- into a register. This brings a new value into existence,
-- unlike normal move.
Move1 mt dst -> rw (mt == DT.MResultWide) dst
ReturnVoid -> return ()
Return _ src -> rr src
LoadConst dst c -> rw (constWide c) dst
MonitorEnter src -> rr src
MonitorExit src -> rr src
CheckCast src _ -> rr src >> rw False src
InstanceOf dst src _ -> rr src >> rw False dst
ArrayLength dst src -> rr src >> rw False dst
NewInstance dst _ -> rw False dst
NewArray dst src _ -> rr src >> rw False dst
FilledNewArray _ srcs -> rrs srcs
FilledNewArrayRange _ srcs -> rrs srcs
FillArrayData src _ -> rr src
Throw src -> rr src
Goto _ -> return ()
Goto16 _ -> return ()
Goto32 _ -> return ()
PackedSwitch src _ -> rr src
SparseSwitch src _ -> rr src
Cmp _ dst src1 src2 -> rrs [src1, src2] >> rw False dst
If _ src1 src2 _ -> rrs [src1, src2]
IfZero _ src _ -> rr src
ArrayOp (Get at) dst src1 src2 -> rrs [src1, src2] >> rw (accessWide at) dst
ArrayOp (Put _) src3 src1 src2 -> rrs [src1, src2, src3]
InstanceFieldOp (Get at) dst src _ -> rr src >> rw (accessWide at) dst
InstanceFieldOp (Put _) src2 src1 _ -> rrs [src1, src2]
StaticFieldOp (Get at) dst _ -> rw (accessWide at) dst
StaticFieldOp (Put _) src _ -> rr src
Invoke ikind _ mid srcs -> do
srcs' <- lift $ filterWidePairs df mid ikind srcs
rrs srcs'
Unop op dst src -> rr src >> rw (unopWide op) dst
IBinop _ w dst src1 src2 -> rrs [src1, src2] >> rw w dst
FBinop _ w dst src1 src2 -> rrs [src1, src2] >> rw w dst
-- These two read and write from the dest register
IBinopAssign _ w dst src -> rrs [src, dst] >> rw w dst
FBinopAssign _ w dst src -> rrs [src, dst] >> rw w dst
-- The literal binop variants do not work on wide types
BinopLit16 _ dst src _ -> rr src >> rw False dst
BinopLit8 _ dst src _ -> rr src >> rw False dst
PackedSwitchData _ _ -> return ()
SparseSwitchData _ _ -> return ()
ArrayData _ _ _ -> return ()
-- | True if the unary op works over a wide type
unopWide :: DT.Unop -> Bool
unopWide o =
case o of
DT.NegLong -> True
DT.NotLong -> True
DT.NegDouble -> True
_ -> False
-- | True if we are reading or writing a wide value
accessWide :: Maybe DT.AccessType -> Bool
accessWide (Just DT.AWide) = True
accessWide _ = False
-- | True if the constant being loaded is wide (will occupy two registers)
constWide :: DT.ConstArg -> Bool
constWide carg =
case carg of
DT.ConstWide16 _ -> True
DT.ConstWide32 _ -> True
DT.ConstWide _ -> True
DT.ConstWideHigh16 _ -> True
_ -> False
-- | Looks up the mapping for this register at this instruction (from
-- the mutable @currentDefinition@) and record the label mapping for
-- this instruction.
recordReadRegister :: (E.MonadThrow m, FromRegister a) => Int -> Instruction -> BlockNumber -> a -> SSALabeller m ()
recordReadRegister ix inst instBlock srcReg = do
lbl <- readRegister srcReg instBlock
recordAssignment ix inst srcReg lbl
-- A possible source of the problem is that we only record the use of
-- the label after we create it. Possibly a necessary circularity,
-- but it means that a fake phi node is created and eliminated before
-- knowing that it will have a user here.
-- | Create a label for this value, associated with the destination register.
recordWriteRegister :: (E.MonadThrow m, FromRegister a) => Bool -> Int -> BlockNumber -> a -> SSALabeller m ()
recordWriteRegister wide ix instBlock dstReg = do
lbl <- writeRegister wide dstReg instBlock
modify (addAssignment lbl)
where
addAssignment lbl s =
let lbls = instructionResultLabels s
in s { instructionResultLabels = M.insert ix lbl lbls }
-- | At this instruction, associate the new given 'Label' with the
-- named register. Also add an entry for the reverse mapping (Label
-- is used by this instruction/reg).
recordAssignment :: (E.MonadThrow m, FromRegister a)
=> Int
-> Instruction
-> a
-> Label
-> SSALabeller m ()
recordAssignment ix inst (fromRegister -> reg) lbl =
modify $ \s ->
let lbls = instructionLabels s
users = valueUsers s
in s { instructionLabels = M.insertWith M.union ix (M.singleton reg lbl) lbls
, valueUsers = M.insertWith S.union lbl (S.singleton (NormalUse ix inst reg)) users
}
freshLabel :: (E.MonadThrow m) => SSALabeller m Label
freshLabel = do
s <- get
put s { labelCounter = labelCounter s + 1 }
return $ SimpleLabel (labelCounter s)
freshPhi :: (E.MonadThrow m) => BlockNumber -> SSALabeller m Label
freshPhi bn = do
preds <- basicBlockPredecessorsM bn
s <- get
let lid = labelCounter s
l = PhiLabel bn preds lid
put s { labelCounter = lid + 1
, phiOperands = M.insert l S.empty (phiOperands s)
}
return l
-- | Used for instructions that write to a register. These always
-- define a new value. From the paper, this is:
--
-- > writeVariable(variable, block, value):
-- > currentDef[variable][block] ← value
writeRegister :: (E.MonadThrow m, FromRegister a) => Bool -> a -> BlockNumber -> SSALabeller m Label
writeRegister wide (fromRegister -> reg) block = do
l <- freshLabel
writeRegisterLabel wide reg block l
return l
-- | Write a register with the provided label, instead of allocating a
-- fresh one.
--
-- If the register is wide, we also clear the definition of the second
-- register in the pair (always the next register). We must do this,
-- otherwise there will be "dangling" definitions where a register
-- pair has been written on one branch, and on a different branch an
-- old definition that was overwritten will appear to be live. These
-- phantom definitions show up in phi nodes and cannot be resolved
-- (since they never existed in that predecessor branch).
writeRegisterLabel :: (E.MonadThrow m, FromRegister a) => Bool -> a -> BlockNumber -> Label -> SSALabeller m ()
writeRegisterLabel wide (fromRegister -> reg) block l = do
s <- get
let defs' = M.insertWith M.union reg (M.singleton block l) (currentDefinition s)
defs'' = if wide then M.adjust (M.delete block) (reg+1) defs' else defs'
put s { currentDefinition = defs''
, registersWithLabel = M.insertWith' S.union l (S.singleton (reg, block)) (registersWithLabel s)
}
-- | Find the label for a register being read from. If we have a
-- local definition (due to local variable numbering, i.e., a write in
-- the current block), return that. Otherwise, check for a global
-- variable numbering.
readRegister :: (E.MonadThrow m, FromRegister a) => a -> BlockNumber -> SSALabeller m Label
readRegister (fromRegister -> reg) block = do
curDefs <- gets currentDefinition
case M.lookup reg curDefs of
Nothing -> readRegisterRecursive reg block
Just varDefs ->
case M.lookup block varDefs of
Nothing -> readRegisterRecursive reg block
Just label -> return label
-- | This is global variable numbering (global in the sense of not the
-- local block of the instruction). If a block has a single
-- predecessor, the label is retrieved from the predecessor block.
-- Otherwise, we need some phi magic.
--
-- There are calls to write here to let us memoize lookups.
--
-- Note: If there are no predecessors, it is actually not defined. We
-- would probably want to know about that... maybe just error for now.
readRegisterRecursive :: (E.MonadThrow m) => Word16 -> BlockNumber -> SSALabeller m Label
readRegisterRecursive reg block = do
isSealed <- blockIsSealed block
case isSealed of
False -> makeIncomplete reg block
True -> globalNumbering reg block
-- | When a block isn't sealed yet, we add a dummy phi empty phi node.
-- It will be filled in (or eliminated) once the block is sealed.
makeIncomplete :: (E.MonadThrow m) => Word16 -> BlockNumber -> SSALabeller m Label
makeIncomplete r b = do
p <- freshPhi b
addIncompletePhi r b p
writeRegisterLabel False r b p
return p
-- | global value numbering, with some recursive calls. The empty phi
-- is inserted to prevent infinite recursion.
globalNumbering :: (E.MonadThrow m) => Word16 -> BlockNumber -> SSALabeller m Label
globalNumbering r b = do
preds <- basicBlockPredecessorsM b
l <- case preds of
[singlePred] -> readRegister r singlePred
_ -> do
p <- freshPhi b
writeRegisterLabel False r b p
addPhiOperands r b p
-- FIXME is it okay to say this isn't wide? I guess nothing has
-- really been written right here...
writeRegisterLabel False r b l
return l
-- | Check if a basic block is filled
isFilled :: (E.MonadThrow m) => BlockNumber -> SSALabeller m Bool
isFilled b = do
f <- gets filledBlocks
return $ IS.member b f
-- | Look backwards along control flow edges to find incoming phi
-- values. These are the operands to the phi node.
addPhiOperands :: (E.MonadThrow m) => Word16 -> BlockNumber -> Label -> SSALabeller m Label
addPhiOperands reg block phi = do
let PhiLabel _ preds _ = phi
preds' <- filterM isFilled preds
forM_ preds' $ \p -> do
l <- readRegister reg p
appendPhiOperand phi p l
-- If this is the entry block, we also need to add in the
-- contributions from the initial register assignment
case block == 0 of
False -> return ()
True -> do
argLabels <- asks envRegisterAssignment
case M.lookup reg argLabels of
Nothing -> return ()
Just lbl -> appendPhiOperand phi 0 lbl
tryRemoveTrivialPhi phi
remapPhi phi
remapPhi :: (E.MonadThrow m) => Label -> SSALabeller m Label
remapPhi l = do
ep <- gets eliminatedPhis
case M.lookup l ep of
Nothing -> return l
Just l' -> remapPhi l'
-- | Remove any trivial phi nodes. The algorithm is a bit aggressive
-- with phi nodes. This step makes sure we have the minimal number of
-- phi nodes. A phi node is trivial if it has only one operand
-- (besides itself). Removing a phi node requires finding all of its
-- uses and replacing them with the trivial (singular) value.
tryRemoveTrivialPhi :: (E.MonadThrow m) => Label -> SSALabeller m ()
tryRemoveTrivialPhi phi = do
triv <- trivialPhiValue phi
case triv of
Nothing -> return ()
Just tval -> do
useMap <- gets valueUsers
-- Note that this list of value users does not include other phi nodes.
-- This is not a critical problem because we replace phi nodes that are
-- phi operands separately in 'replacePhiBy'.
let allUsers = maybe [] S.toList $ M.lookup phi useMap
replacePhiBy allUsers phi tval
-- Clear out the old operands to mark this phi node as dead.
-- This will be important to note during translation (and for
-- pretty printing).
modify $ \s -> s { phiOperands = M.insert phi S.empty (phiOperands s)
, valueUsers = M.delete phi (valueUsers s)
}
-- Check each user
forM_ allUsers $ \u ->
case u of
PhiUse phi' | phi' /= phi -> do
-- There is an interesting note here. This recursive call
-- to 'tryRemoveTrivialPhi' could remove a phi node that
-- is already being queried in 'globalValueNumbering'. If
-- that is the case, 'globalValueNumbering' won't
-- necessarily see the change if we just return (and drop
-- it) here. Instead, we have a side map of
-- eliminatedPhis that we can consult to figure out,
-- globally, which phis have been eliminated.
--
-- A cleaner alternative would be to add a layer of
-- indirection and register uses before we call
-- 'readRegister'. Then all users would be registered and
-- could be updated in this loop. Unfortunately, that
-- isn't really possible with the current formulation
-- since we can't allocate a label before we start
-- querying. That would be a good next change.
tryRemoveTrivialPhi phi'
_ -> return ()
modify $ \s -> s { phiOperands = M.delete phi (phiOperands s)
, phiOperandSources = M.delete phi (phiOperandSources s)
, registersWithLabel = M.delete phi (registersWithLabel s)
, eliminatedPhis = M.insert phi tval (eliminatedPhis s)
}
return ()
-- | Replace all of the given uses by the new label provided.
replacePhiBy :: (E.MonadThrow m) => [Use] -> Label -> Label -> SSALabeller m ()
replacePhiBy uses oldPhi trivialValue = do
regLabs <- gets registersWithLabel
case M.lookup oldPhi regLabs of
Nothing -> return ()
Just rls ->
F.forM_ rls $ \(r, b) -> do
modify $ \s ->
let replaceInBlock = M.insert b trivialValue
in s { currentDefinition = M.adjust replaceInBlock r (currentDefinition s)
, registersWithLabel = M.insertWith S.union trivialValue (S.singleton (r, b)) (registersWithLabel s)
}
forM_ uses $ \u ->
case u of
NormalUse ix inst reg -> recordAssignment ix inst reg trivialValue
PhiUse phiUser -> do
let replaceOp = S.insert trivialValue . S.delete oldPhi
modify $ \s ->
let opSrcs = fromMaybe M.empty $ M.lookup phiUser (phiOperandSources s)
bset = fromMaybe S.empty $ M.lookup oldPhi opSrcs
opSrcs' = M.delete oldPhi $ M.insert trivialValue bset opSrcs
in s { phiOperands = M.adjust replaceOp phiUser (phiOperands s)
, valueUsers = M.insertWith' S.union trivialValue (S.singleton u) (valueUsers s)
, phiOperandSources = M.insert phiUser opSrcs' (phiOperandSources s)
}
return ()
-- | A phi node is trivial if it merges two or more distinct values
-- (besides itself). Unique operands and then remove self references.
-- If there is only one label left, return Just that.
--
-- Note that each phi incoming value label is tagged with the block number
-- that it came from. This information is important for the SSA translation
-- later on, but it can get in the way here.
trivialPhiValue :: (E.MonadThrow m) => Label -> SSALabeller m (Maybe Label)
trivialPhiValue phi = do
operandMap <- gets phiOperands
case M.lookup phi operandMap of
Just ops ->
let withoutSelf = S.filter (/=phi) ops
-- FIXME: If the result of this is empty, the phi node is actually
-- undefined. We want a special case for that so we can insert an
-- undefined instruction in the translation phase. We can't
-- really introduce one of these in a syntactically valid Java
-- program, but the bytecode could probably contain
-- some... especially malicious bytecode.
--
-- That said, the bytecode verifier doesn't allow undefined
-- references to exist...
in case S.toList withoutSelf of
[trivial] -> return (Just trivial)
_ -> return Nothing
Nothing -> return Nothing
-- | > appendPhiOperand phi bnum operand
--
-- Adds an @operand@ (that came from basic block @bnum@) to a @phi@
-- node.
appendPhiOperand :: (E.MonadThrow m) => Label -> BlockNumber -> Label -> SSALabeller m ()
appendPhiOperand phi bnum operand = modify appendOperand
where
appendOperand s =
s { phiOperands = M.insertWith S.union phi (S.singleton operand) (phiOperands s)
, phiOperandSources = M.insertWith' (M.unionWith S.union) phi (M.singleton operand (S.singleton bnum)) (phiOperandSources s)
, valueUsers = M.insertWith S.union operand (S.singleton (PhiUse phi)) (valueUsers s)
}
-- | When wide values (longs or doubles) are passed as parameters to
-- methods, *both* registers appear as arguments to the invoke
-- instruction. This is different than in other instructions, where
-- only the first register is referenced. We can't do a label/value
-- lookup on the second register since we aren't accounting for them
-- (and don't want them in the argument lists anyway).
--
-- This function filters out the second register in each wide argument
-- pair.
--
-- This prevents us from accidentally processing these extra registers
-- and generating empty/undefined phi labels. We need this both for
-- the labeling and the SSA translation phases.
filterWidePairs :: (E.MonadThrow m) => DT.DexFile -> DT.MethodId -> DT.InvokeKind -> [DT.Reg16] -> m [DT.Reg16]
filterWidePairs df mId ikind argRegs = do
m <- getMethod df mId
p <- getProto df (DT.methProtoId m)
-- If this is an instance method, be sure to always save the first
-- argument (since it doesn't appear in the prototype). To do that,
-- we have to look up the class of the method and then iterate
-- through all of the EncodedMethods until we find it. Lame.
case ikind of
DT.Static -> go (DT.protoParams p) argRegs
_ -> do
let (this:rest) = argRegs
rest' <- go (DT.protoParams p) rest
return (this : rest')
where
-- After the types are exhausted, the rest of the arguments must
-- be varargs, which are explicitly boxed in the IR.
go [] rest = return rest
go (tid:tids) (r1:rest) = do
tyName <- DT.getTypeName df tid
case BS.unpack tyName of
"J" -> liftM (r1:) $ dropNextReg tids rest
"D" -> liftM (r1:) $ dropNextReg tids rest
_ -> do
rest' <- go tids rest
return (r1 : rest')
go _ [] = E.throwM $ DT.ArgumentTypeMismatch mId argRegs
dropNextReg _ [] = E.throwM $ DT.ArgumentTypeMismatch mId argRegs
dropNextReg tids (_:rest) = go tids rest
-- Block predecessors. These are some monadic wrappers around the
-- real functions. They just extract the BasicBlocks object from the
-- environment.
-- | A wrapper around 'basicBlockPredecessors' handling the environment lookup
basicBlockPredecessorsM :: (E.MonadThrow m) => BlockNumber -> SSALabeller m [BlockNumber]
basicBlockPredecessorsM bid = do
bbs <- asks envBasicBlocks
return $ basicBlockPredecessors bbs bid
-- | A wrapper around 'basicBlockSuccessors' handling the environment lookup
basicBlockSuccessorsM :: (E.MonadThrow m) => BlockNumber -> SSALabeller m [BlockNumber]
basicBlockSuccessorsM bid = do
bbs <- asks envBasicBlocks
return $ basicBlockSuccessors bbs bid
-- | This is a simple helper class to convert from Register
-- identifiers in the low-level IR to a consistent Word16. The spec
-- defines register numbers as < 2^16. This is a safer convenience so
-- that we don't have to just use a more general (Num a) constraint.
class FromRegister a where
fromRegister :: a -> Word16
instance FromRegister Word16 where
fromRegister = id
instance FromRegister Word8 where
fromRegister = fromIntegral
instance FromRegister Reg where
fromRegister (R4 r) = fromRegister r
fromRegister (R8 r) = fromRegister r
fromRegister (R16 r) = fromRegister r
-- Pretty printing for debugging
phiForBlock :: BlockNumber -> Label -> Bool
phiForBlock bid l =
case l of
PhiLabel phiBlock _ _ -> phiBlock == bid
_ -> False
-- | A simple pretty printer for computed SSA labels. This is
-- basically for debugging.
prettyLabeling :: Labeling -> String
prettyLabeling l =
PP.render $ PP.vcat $ map prettyBlock $ basicBlocksAsList bbs
where
bbs = labelingBasicBlocks l
ivec = labelingInstructions l
prettyBlock (bid, blockOff, insts) =
let header = PP.text ";; " PP.<> PP.int bid PP.<> PP.text (show (basicBlockPredecessors bbs bid))
blockPhis = filter (phiForBlock bid . fst) $ M.toList (labelingPhis l)
blockPhiDoc = PP.vcat [ PP.text (printf "$%d = phi(%s)" phiL (show vals))
| (PhiLabel _ _ phiL, S.toList -> vals) <- blockPhis,
not (null vals)
]
body = blockPhiDoc $+$ (PP.vcat $ zipWith (curry prettyInst) [blockOff..] $ V.toList insts)
in header $+$ PP.nest 2 body
branchTargets i = fromMaybe "??" $ do
ix <- V.elemIndex i ivec
srcBlock <- instructionBlockNumber bbs ix
let targetBlocks = basicBlockSuccessors bbs srcBlock
return $ L.intercalate ", " (map show targetBlocks)
prettyInst (ix, i) =
case i of
Nop -> PP.text ";; nop"
Move t r1 r2 -> PP.text $ printf ";; move %s %s %s" (show t) (show r1) (show r2)
Move1 t r -> PP.text $ printf "%s = move1 %s ;\t (move1 %s %s)" (wLabelId r) (show t) (show t) (show r)
ReturnVoid -> PP.text "ret"
Return _ r -> PP.text $ printf "ret $%s ;\t (ret %s)" (rLabelId r) (show r)
LoadConst r arg -> PP.text $ printf "$%s = loadc %s ;\t (loadc %s %s)" (wLabelId r) (show arg) (show r) (show arg)
MonitorEnter r -> PP.text $ printf "menter $%s ;\t (menter %s)" (rLabelId r) (show r)
MonitorExit r -> PP.text $ printf "mexit $%s ;\t (mexit %s)" (rLabelId r) (show r)
CheckCast r t -> PP.text $ printf "checkcast $%s %s ;\t (checkcast %s %s)" (rLabelId r) (show t) (show r) (show t)
InstanceOf d s t -> PP.text $ printf "$%s = instanceof $%s %s ;\t (instanceof %s %s %s)" (wLabelId d) (rLabelId s) (show t) (show d) (show s) (show t)
ArrayLength d s -> PP.text $ printf "$%s = arraylength $%s ;\t (arraylength %s %s)" (wLabelId d) (rLabelId s) (show d) (show s)
NewInstance d t -> PP.text $ printf "$%s = newinstance $%s ;\t (newinstance %s %s)" (wLabelId d) (show t) (show d) (show t)
NewArray d s t -> PP.text $ printf "$%s = newarray $%s $%s ;\t (newarray %s %s %s)" (wLabelId d) (rLabelId s) (show t) (show d) (show s) (show t)
FilledNewArray t srcs -> PP.text $ printf "fillednewarray %s %s ;\t (fillednewarray %s %s)" (show t) (concatMap rLabelId srcs) (show t) (show srcs)
FilledNewArrayRange t srcs -> PP.text $ printf "fillednewarrayrange %s %s ;\t (fillednewarrayrange %s %s)" (show t) (concatMap rLabelId srcs) (show t) (show srcs)
FillArrayData r off -> PP.text $ printf "fillarraydata $%s %s ;\t (fillarraydata %s %s)" (rLabelId r) (show off) (show r) (show off)
Throw r -> PP.text $ printf "throw $%s ;\t (throw %s)" (rLabelId r) (show r)
Cmp op d s1 s2 -> PP.text $ printf "$%s <- cmp %s $%s $%s ;\t (cmp %s %s %s %s)" (wLabelId d) (show op) (rLabelId s1) (rLabelId s2) (show op) (show d) (show s1) (show s2)
ArrayOp (Get _) dst src1 src2 -> PP.text $ printf "$%s = getarray $%s $%s ;\t (getarray %s %s %s)" (wLabelId dst) (rLabelId src1) (rLabelId src2) (show dst) (show src1) (show src2)
ArrayOp (Put _) src3 src1 src2 -> PP.text $ printf "putarray $%s $%s $%s ;\t (putarray %s %s %s)" (rLabelId src3) (rLabelId src1) (rLabelId src2) (show src3) (show src1) (show src2)
InstanceFieldOp (Get _) dst src f -> PP.text $ printf "$%s = getfield $%s %s ;\t (getfield %s %s %s)" (wLabelId dst) (rLabelId src) (show f) (show dst) (show src) (show f)
InstanceFieldOp (Put _) src2 src1 f -> PP.text $ printf "putfield $%s $%s %s ;\t (putfield %s %s %s)" (rLabelId src2) (rLabelId src1) (show f) (show src2) (show src1) (show f)
StaticFieldOp (Get _) dst f -> PP.text $ printf "$%s = getstatic %s ;\t (getstatic %s %s)" (wLabelId dst) (show f) (show dst) (show f)
StaticFieldOp (Put _) src f -> PP.text $ printf "putstatic $%s %s ;\t (putstatic %s %s)" (rLabelId src) (show f) (show src) (show f)
Invoke kind _ method srcs -> PP.text $ printf "invoke %s [%s] %s ;\t (%s)" (show kind) (show method) (show (map rLabelId srcs)) (show srcs)
Unop op d s -> PP.text $ printf "$%s <- %s $%s ;\t (%s %s %s)" (wLabelId d) (show op) (rLabelId s) (show op) (show d) (show s)
IBinop op _ d s1 s2 -> PP.text $ printf "$%s = %s $%s $%s ;\t (%s[i] %s %s %s)" (wLabelId d) (show op) (rLabelId s1) (rLabelId s2) (show op) (show d) (show s1) (show s2)
FBinop op _ d s1 s2 -> PP.text $ printf "$%s = %s $%s $%s ;\t (%s[f] %s %s %s)" (wLabelId d) (show op) (rLabelId s1) (rLabelId s2) (show op) (show d) (show s1) (show s2)
IBinopAssign op _ sd s -> PP.text $ printf "$%s = %s $%s $%s ;\t (%s[ia] %s %s)" (wLabelId sd) (show op) (rLabelId sd) (rLabelId s) (show op) (show sd) (show s)
FBinopAssign op _ sd s -> PP.text $ printf "$%s = %s $%s $%s ;\t (%s[fa] %s %s)" (wLabelId sd) (show op) (rLabelId sd) (rLabelId s) (show op) (show sd) (show s)
BinopLit16 op d s lit -> PP.text $ printf "$%s = %s $%s %d ;\t (%s %s %s %d)" (wLabelId d) (show op) (rLabelId s) lit (show op) (show d) (show s) lit
BinopLit8 op d s lit -> PP.text $ printf "$%s = %s $%s %d ;\t (%s %s %s %d)" (wLabelId d) (show op) (rLabelId s) lit (show op) (show d) (show s) lit
PackedSwitchData _ _ -> PP.text ";; packedswitchdata"
SparseSwitchData _ _ -> PP.text ";; sparseswitchdata"
ArrayData _ _ _ -> PP.text ";; arraydata"
Goto _ -> PP.text $ printf "goto %s" (branchTargets i)
Goto16 _ -> PP.text $ printf "goto %s" (branchTargets i)
Goto32 _ -> PP.text $ printf "goto %s" (branchTargets i)
PackedSwitch src _ -> PP.text $ printf "switch $%s %s" (rLabelId src) (branchTargets i)
SparseSwitch src _ -> PP.text $ printf "switch $%s %s" (rLabelId src) (branchTargets i)
IfZero op src _ -> PP.text $ printf "if0 %s $%s %s" (show op) (rLabelId src) (branchTargets i)
If op src1 src2 _ -> PP.text $ printf "if %s $%s $%s %s" (show op) (rLabelId src1) (rLabelId src2) (branchTargets i)
where
rLabelId reg = fromMaybe "??" $ do
regMap <- M.lookup ix (labelingReadRegs l)
lab <- M.lookup (fromRegister reg) regMap
case lab of
SimpleLabel lnum -> return (show lnum)
PhiLabel _ _ lnum -> return (show lnum)
ArgumentLabel s _ -> return (show s)
wLabelId _reg = fromMaybe "??" $ do
lab <- M.lookup ix (labelingWriteRegs l)
case lab of
SimpleLabel lnum -> return (show lnum)
PhiLabel _ _ lnum -> return (show lnum)
ArgumentLabel s _ -> return (show s)
-- Testing property
-- | Returns @True@ if all of the labels assigned to instructions
-- are unique.
generatedLabelsAreUnique :: Labeling -> Bool
generatedLabelsAreUnique =
snd . foldr checkRepeats (S.empty, True) . M.toList . labelingWriteRegs
where
checkRepeats (_, l) (marked, foundRepeat)
| S.member l marked = (marked, False)
| otherwise = (S.insert l marked, foundRepeat)
{- Note [Overview]
This implementation of SSA value numbering closely follows the linked
paper. This note tries to provide a high-level view of the algorithm.
The algorithm runs forward over the instruction stream, visiting each
instruction once. As it proceeds, it modifies the current register
state, held in the State record
> currentDefinition :: Map Word16 (Map BlockNumber Label)
This is a map of registers to their definitions in each basic block.
Definitions are SSA labels that are referenced at that point. This
map is destructively modified by each instruction. We largely use
@readRegister@, @writeRegister@, and @writeRegisterLabel@ to access
this map. We also maintain two other maps:
> instructionLabels :: Map Int (Map Word16 Label)
> instructionResultLabels :: Map Int Label
These record the labels referenced by each low-level Dalvik
instruction. @instructionLabels@ are the labels that each instruction
reads. @instructionResultLabels@ are the labels that instructions
*produce*. We have to track these separately because some
instructions read from and write to the same register. Note that once
an entry is made in either of these maps, it never changes (except
when we eliminate trivial phi nodes). These are also the main
features of the @Labeling@ result.
The basic idea of the algorithm is that, for a given instruction, we
determine what values it references (to populate @instructionLabels@)
by determining what label each register it refers to currently
contains (based on @currentDefinition@). If there was a definition
earlier in the current basic block, we take that. This is local value
numbering. Otherwise, we look at all of the predecessors of the block
and derive the definition from them. With a single predecessor, this
is trivial. Otherwise, we start introducing phi nodes. If the block
is sealed (i.e., all of its predecessors have been fully labeled),
then we recursively look at each predecessor and construct a phi node.
If there are predecessor blocks that haven't been processed yet, we
just leave a dummy phi node to be filled in later. Every time a basic
block is processed, we try to seal all of its successors (since one of
*their* predecessors has been processed) by filling in those
stubbed-out phi nodes.
Furthermore, every time we finish a phi node, we try to simplify it.
If it is trivial, we remove it and replace it with a simpler
definition.
= Future directions =
* Copy/constant propagation could allow some more dead code removal
* With an iterative and interleaved approach, we could actually eliminate
some superflouous control flow edges related to null pointer exceptions.
After the first time a pointer is dereferenced, we know that later
dereferences in the same basic block cannot fail.
* There are optimizations in the paper for producing the minimal number of
phi nodes in the presence of irreducable control flow. Irreducable control
flow is very rare in practice (especially with compiler-generated code), so
this isn't very important.
* There are also a few suggestions in the paper for reducing the number of
trivial phi nodes that are inserted and later removed. This isn't a huge
issue, but it could speed things up a little. An easier speedup is marked
with a FIXME above - our approach to replacing phi nodes could be made more
efficient with an index tracking more precisely where each phi node is used.
-}
|
travitch/dalvik
|
src/Dalvik/SSA/Internal/Labeling.hs
|
bsd-3-clause
| 50,216 | 0 | 25 | 12,693 | 11,179 | 5,675 | 5,504 | 599 | 46 |
{-
Copyright James d'Arcy 2010
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 James d'Arcy nor the names of other
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.
-}
module Data.Dicom.Accessor
(
-- * Accessors for 0x0002
getTransferSyntaxUid,
-- * Accessors for 0x0008
getSopClassUid,
getSopInstanceUid,
getStudyDate,
getSeriesDate,
getModality,
getStudyDescription,
getSeriesDescription,
-- * Accessors for 0x0010
getPatientName,
-- * Accessors for 0x0020
getStudyInstanceUid,
getSeriesInstanceUid,
getStudyId,
getSeriesNumber,
-- * Accessors for 0x0028
getNumberOfFrames,
getRows,
getColumns,
-- * Accessors for 0x7fe0
getPixelData
) where
import Data.Word
import Data.Int
import qualified Data.ByteString as B
import Data.Dicom
import Data.Dicom.Tag
-- | Group 0x0002 - Metadata
getTransferSyntaxUid :: DicomObject -> Maybe String
getTransferSyntaxUid = getString tRANSFER_SYNTAX_UID
-- | Group 0x0008
getSopClassUid :: DicomObject -> Maybe String
getSopClassUid = getString sOP_CLASS_UID
getSopInstanceUid :: DicomObject -> Maybe String
getSopInstanceUid = getString sOP_INSTANCE_UID
getStudyDate :: DicomObject -> Maybe String
getStudyDate = getString sTUDY_DATE
getSeriesDate :: DicomObject -> Maybe String
getSeriesDate = getString sERIES_DATE
getModality :: DicomObject -> Maybe String
getModality = getString mODALITY
getStudyDescription :: DicomObject -> Maybe String
getStudyDescription = getString sTUDY_DESCRIPTION
getSeriesDescription :: DicomObject -> Maybe String
getSeriesDescription = getString sERIES_DESCRIPTION
-- | Group 0x0010
getPatientName :: DicomObject -> Maybe String
getPatientName = getString pATIENT_NAME
-- | Group 0x0020
getStudyInstanceUid :: DicomObject -> Maybe String
getStudyInstanceUid = getString sTUDY_INSTANCE_UID
getSeriesInstanceUid :: DicomObject -> Maybe String
getSeriesInstanceUid = getString sERIES_INSTANCE_UID
getStudyId :: DicomObject -> Maybe String
getStudyId = getString sTUDY_ID
getSeriesNumber :: DicomObject -> Maybe String
getSeriesNumber = getString sERIES_NUMBER
-- | Group 0x0028
getNumberOfFrames :: DicomObject -> Maybe String
getNumberOfFrames = getString nUMBER_OF_FRAMES
getRows :: DicomObject -> Maybe Word16
getRows = getWord16 rOWS
getColumns :: DicomObject -> Maybe Word16
getColumns = getWord16 cOLUMNS
-- | Group 0x0028
getPixelData :: DicomObject -> Maybe B.ByteString
getPixelData = getBytes pIXEL_DATA
|
jamesdarcy/DicomH
|
src/Data/Dicom/Accessor.hs
|
bsd-3-clause
| 3,852 | 0 | 7 | 656 | 444 | 243 | 201 | 58 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -Wall #-}
{-# OPTIONS_GHC -Wno-orphans #-} -- See orphans below
-- Prevent warnings about inlining fst, snd, not, etc.
-- Might be worthwhile to turn back on and inspect warnings occasionally.
{-# OPTIONS_GHC -fno-warn-inline-rule-shadowing #-}
-- #define Testing
-- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
#ifdef Testing
{-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
#endif
----------------------------------------------------------------------
-- |
-- Module : ReificationRules.HOS
-- Copyright : (c) 2016 Conal Elliott
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Higher-order syntax interface to lambda expressions. Based on "Using Circular
-- Programs for Higher-Order Syntax" by Emil Axelsson and Koen Claessen
-- <http://www.cse.chalmers.se/~emax/documents/axelsson2013using.pdf>.
----------------------------------------------------------------------
module ReificationRules.HOS
( EP,toE,constP,appP,lamP,letP,letPairP,ifP,bottomP,evalP,reifyP,reify, litE
, abst,repr,abst',repr', abstP,reprP, unknownP
, E, Prim
, unI#
, succI
) where
import Data.Map
import GHC.Types (Int(..)) -- , type (~~)
import GHC.Prim (Addr#)
import GHC.CString (unpackCString#)
import Circat.Misc (Unop,Binop,(:*))
#ifdef Testing
import Circat.Misc (Ternop)
#endif
import qualified Circat.Rep as Rep
import Circat.Rep (HasRep,Rep)
-- import Circat.Pair (Pair(..)) -- TEMP
-- import qualified Circat.RTree as R
-- import qualified Circat.LTree as L
import ReificationRules.Misc (Evalable,PrimBasics(..))
import ReificationRules.Exp
import ReificationRules.Prim
import ReificationRules.ShowUtils
-- Reboxing experiment
import GHC.Exts (Int#)
type NameMap = Map Name Int
bot :: NameMap
bot = mempty
lub :: NameMap -> NameMap -> NameMap
lub = unionWith max
type E' p a = (E p a, NameMap)
toE :: E' p a -> E p a
toE = fst
infixl 9 ^:
(^:) :: E' p (a -> b) -> E' p a -> E' p b
(f,mf) ^: (x,mx) = (f :^ x, mf `lub` mx)
-- Establish a new name based on nm, augmenting name map as needed
bump :: Unop (Name, NameMap)
bump (nm,m) = (maybe nm ((nm ++) . show) mbN,m')
where
(mbN,m') = insertLookupWithKey (const (+)) nm 1 m
-- insertLookupWithKey ::
-- Ord k => (k -> a -> a -> a) -> k -> a -> Map k a -> (Maybe a, Map k a)
lam :: Name -> (E' p a -> E' p b) -> E' p (a -> b)
lam nma f = (Lam (VarPat (V nma')) body, mb)
where
(body,ma) = f (Var (V nma'),bot)
(nma',mb) = bump (nma,ma)
lamPair :: Name -> Name -> (E' p a -> E' p b -> E' p c) -> E' p (a :* b -> c)
lamPair nma nmb f = (Lam (VarPat (V nma') :$ VarPat (V nmb')) body, mc)
where
(body,ma) = f (Var (V nma'),bot) (Var (V nmb'),bot)
(nma',mb) = bump (nma,ma)
(nmb',mc) = bump (nmb,mb)
-- TODO: Maybe switch to bump :: Name -> State NameMap Name.
-- Especially convenient with lamPair. Maybe not, considering the circularity.
letE' :: Name -> E' p a -> (E' p a -> E' p b) -> E' p b
letE' x a f = lam x f ^: a
letPair' :: Name -> Name -> E' p (a :* b) -> (E' p a -> E' p b -> E' p c) -> E' p c
letPair' x y ab f = lamPair x y f ^: ab
constE' :: p a -> E' p a
constE' p = (ConstE p, bot)
reifyE' :: a -> E' p a
reifyE' e = (reifyE e,bot)
evalE' :: (Show' p, HasOpInfo p, Evalable p) => E' p a -> a
evalE' (e,_) = evalE e
(*#) :: PrimBasics p => E' p a -> E' p b -> E' p (a :* b)
a *# b = constE' pairP ^: a ^: b
{--------------------------------------------------------------------
Specializations to Prim
--------------------------------------------------------------------}
-- TODO: Eliminate these specialized definitions and pass Prim explicitly during
-- reification.
type EP a = E' Prim a
type Name# = Addr#
appP :: forall a b. EP (a -> b) -> EP a -> EP b
appP = (^:)
{-# NOINLINE appP #-}
lamP :: forall a b. Name# -> (EP a -> EP b) -> EP (a -> b)
lamP x = lam (unpackCString# x)
{-# NOINLINE lamP #-}
letP :: forall a b. Name# -> EP a -> (EP a -> EP b) -> EP b
letP x = letE' (unpackCString# x)
letPairP :: forall a b c. Name# -> Name# -> EP (a :* b) -> (EP a -> EP b -> EP c) -> EP c
letPairP x y = letPair' (unpackCString# x) (unpackCString# y)
-- letP :: forall a b. Name# -> EP a -> EP b -> EP b
-- letP x a b = Lam (varPat# x) b `appP` a
-- {-# NOINLINE letP #-}
reifyP :: forall a. a -> EP a
reifyP = reifyE'
{-# NOINLINE reifyP #-}
reify :: a -> E Prim a
reify _ = error "reify: not implemented"
-- reify f = renameVars (first (reifyP f))
{-# NOINLINE reify #-}
{-# RULES
-- "reify & drop name-map (temporary)" forall f. reify f = fst (reifyP f)
"reify & rename" forall f. reify f = renameVars (fst (reifyP f))
-- I haven't seen either of these two kick in
"repr . abst" forall r. repr (abst r) = r
"abst . repr" forall a. abst (repr a) = a
-- "reify ^" reifyP (^) = constP PowIP
"PowIP @Int" reifyP (^) = constP (PowIP @Int )
"PowIP @Float" reifyP (^) = constP (PowIP @Float )
"PowIP @Double" reifyP (^) = constP (PowIP @Double)
-- Competitors to the rules in GHC.Reals using balanced multiplication trees to
-- help parallelism. If/when I rebalance associative operations elsewhere, drop
-- these rules. Luckily, these orphan rules (-Wno-orphans) win over the rules in
-- GHC.Reals.
"^4/Int balanced" forall a. a ^ (4 :: Int) = (a ^ (2::Int)) ^ (2::Int)
"^5/Int balanced" forall a. a ^ (5 :: Int) = (a ^ (4::Int)) * a
"^6/Int balanced" forall a. a ^ (6 :: Int) = (a ^ (3::Int)) ^ (2::Int)
"^8/Int balanced" forall a. a ^ (8 :: Int) = (a ^ (4::Int)) ^ (2::Int)
-- I added rules for 6 and 8, because they cost the same as 5.
-- • No instance for (Circat.Circuit.GenBuses b)
-- arising from a use of ‘UnknownP’
-- "reify unknown" reifyP unknown = constP UnknownP
#-}
evalP :: forall a. EP a -> a
evalP = evalE'
{-# NOINLINE evalP #-}
constP :: forall a. Prim a -> EP a
constP = constE'
{-# NOINLINE constP #-}
-- The explicit 'forall's here help with reification.
-- The NOINLINEs are just to reduce noise when examining Core output.
-- Remove them later.
unknownP :: CircuitUnknown a b => EP (a -> b)
unknownP = constP UnknownP
bottomP :: CircuitBot a => EP a
bottomP = constP BottomP
ifP :: CircuitIf a => EP Bool -> Binop (EP a)
ifP i t e = constP IfP ^: (i *# (t *# e))
{-# NOINLINE ifP #-}
-- Reboxing experiment
unI# :: Int -> Int#
unI# (I# i) = i
{-# NOINLINE unI# #-}
{-# RULES
-- "rebox Int" forall n. I# (unI# n) = n
-- RULE left-hand side too complicated to desugar
-- Optimised lhs: case unI# n of wild_00 { __DEFAULT ->
-- GHC.Types.I# wild_00
-- }
#-}
{--------------------------------------------------------------------
HasRep
--------------------------------------------------------------------}
-- Synonyms for HasRep methods. Using these names postpones the method selector
-- unfolding built-in rule.
abst :: HasRep a => Rep a -> a
repr :: HasRep a => a -> Rep a
-- abst :: (HasRep a, Rep a ~~ a') => a' -> a
-- repr :: (HasRep a, Rep a ~~ a') => a -> a'
abst = Rep.abst
repr = Rep.repr
{-# NOINLINE abst #-}
{-# NOINLINE repr #-}
abst' :: HasRep a => Rep a -> a
repr' :: HasRep a => a -> Rep a
-- abst' :: (HasRep a, Rep a ~~ a') => a' -> a
-- repr' :: (HasRep a, Rep a ~~ a') => a -> a'
abst' = Rep.abst
repr' = Rep.repr
{-# INLINE abst' #-}
{-# INLINE repr' #-}
-- TODO: drop an abst/repr pair, now that I'm using the simpler signatures
-- consistently. I can't stop the Rep.abst and Rep.repr method selectors from
-- inlining, so use a NOINLINE synonym as the recognized prim in Plugin.
abstP :: HasRep a => EP (Rep a -> a)
reprP :: HasRep a => EP (a -> Rep a)
-- abstP :: (HasRep a, Rep a ~~ a') => EP (a' -> a)
-- reprP :: (HasRep a, Rep a ~~ a') => EP (a -> a')
abstP = constP AbstP
reprP = constP ReprP
-- TODO: Eliminate abstP & reprP, now that I know how to look up data
-- constructors.
litE :: HasLit a => a -> EP a
litE = constP . LitP . toLit
#ifdef Testing
{--------------------------------------------------------------------
Tests
--------------------------------------------------------------------}
app1 :: p (a -> b) -> E' p a -> E' p b
app1 p = (constE' p ^:)
app2 :: p (a -> b -> c) -> E' p a -> E' p b -> E' p c
app2 f a b = app1 f a ^: b
twice :: Unop (Unop a)
twice f = f . f
notOf :: Unop (EP Bool)
notOf = app1 NotP
orOf :: Binop (EP Bool)
orOf = app2 OrP
t1 :: EP (Bool -> Bool)
t1 = constE' NotP
-- (not,fromList [])
t2 :: EP (Unop Bool)
t2 = lam "b" notOf
-- (\ b -> not b,fromList [("b",1)])
t3 :: EP (Unop Bool)
t3 = lam "b" (twice notOf)
-- (\ b -> not (not b),fromList [("b",1)])
t4 :: EP (Unop Bool)
t4 = lam "b" (twice (twice notOf))
-- (\ b -> not (not (not (not b))),fromList [("b",1)])
t5 :: EP (Unop Bool)
t5 = lam "x" (\ x -> orOf x (notOf x))
-- (\ x -> x || not x,fromList [("x",1)])
t6 :: EP (Binop Bool)
t6 = lam "x" $ \ x -> lam "x" $ \ y -> orOf x (notOf y)
-- (\ x1 -> \ x -> x1 || not x,fromList [("x",2)])
t7 :: EP (Ternop Bool)
t7 = lam "x" $ \ x -> lam "x" $ \ y -> lam "x" $ \ z -> orOf x (notOf (orOf y z))
-- (\ x2 -> \ x1 -> \ x -> x2 || not (x1 || x),fromList [("x",3)])
#endif
succI :: Int -> Int
succI x = x + 1
|
conal/reification-rules
|
src/ReificationRules/HOS.hs
|
bsd-3-clause
| 9,463 | 0 | 15 | 2,040 | 2,408 | 1,305 | 1,103 | 131 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
-- | Craze is a small module for performing multiple similar HTTP GET requests
-- in parallel. This is performed through the `raceGet` function, which will
-- perform all the requests and pick the first successful response that passes
-- a certain check, meaning that the parallel requests are essentially racing
-- against each other.
--
-- __What is the usefulness of this?__
--
-- If you are dealing with data source or API that is very unreliable (high
-- latency, random failures) and there are no limitations on performing
-- significantly more requests, then performing multiple requests (through
-- direct connections, proxies, VPNs) may increase the chances of getting a
-- successful response faster and more reliably.
--
-- However, if using a different data source or transport is a possibility, it
-- is potentially a better option that this approach.
--
-- __Examples:__
--
-- Performing two parallel GET requests against https://chromabits.com and
-- returning the status code of the first successful one:
--
-- The providers generate two client configurations. The handler "parses" the
-- response (in this case it just gets the status code). Finally, the checker
-- filters out responses that we don't consider valid (anything that is not
-- HTTP 200 in this case).
--
-- >>> :set -XOverloadedStrings
-- >>> :{
-- let racer = (Racer
-- { racerProviders =
-- [ simpleTagged [] "Client A"
-- , simpleTagged [] "Client B"
-- ]
-- , racerHandler = return . respStatus
-- , racerChecker = (200 ==)
-- , racerDebug = False
-- , racerReturnLast = False
-- } :: Racer [(String, String)] ByteString Int)
-- in (raceGet racer "https://chromabits.com" >>= print)
-- :}
-- Just 200
--
module Network.Craze (
-- * Types
RacerHandler
, RacerChecker
, Racer(..)
, RacerProvider
, ProviderOptions(..)
, RacerResult(..)
, ClientStatus(..)
-- * Functions
, raceGet
, raceGetResult
-- * Providers
-- $providers
, simple
, simpleTagged
, delayed
, delayedTagged
-- * Deprecated
, defaultRacer
, defaultProviderOptions
) where
import Control.Monad (when)
import Data.Map.Lazy (keys, lookup)
import Prelude hiding (lookup)
import Control.Concurrent.Async
import Control.Monad.State (runStateT)
import Control.Monad.Trans (MonadIO, liftIO)
import Data.ByteString (ByteString)
import Data.Default.Class (def)
import Data.Text (Text, pack)
import qualified Data.Text.IO as TIO
import Network.Curl
import Network.Craze.Internal
import Network.Craze.Types
-- | Perform a GET request on the provided URL using all providers in
-- parallel.
--
-- Rough summary of the algorithm:
--
-- - Start all requests
-- - Wait for a request to finish.
--
-- * If the request is successful, apply the handler on it.
--
-- - If the result of the handler passes the checker, cancel all other
-- requests, and return the result.
-- - If the check fails, go back to waiting for another request to
-- finish.
--
-- * If the request fails, go back to waiting for another request to
-- finish.
--
raceGet
:: (Eq a, CurlHeader ht, CurlBuffer bt, MonadIO m)
=> Racer ht bt a
-> URLString
-> m (Maybe a)
raceGet r url = rrResponse <$> raceGetResult r url
-- | Same as @raceGet@, but returns a @RacerResult@ which contains more
-- information about the race performed.
raceGetResult
:: (Eq a, CurlHeader ht, CurlBuffer bt, MonadIO m)
=> Racer ht bt a
-> URLString
-> m (RacerResult a)
raceGetResult r@Racer{..} url = do
initialState@RaceState{..} <- makeRaceState (pack url) r
let asyncs = keys _rsClientMap
when racerDebug . liftIO $ do
TIO.putStr "[racer] Created Asyncs: "
print $ asyncThreadId <$> asyncs
(maybeResponse, finalState) <- runStateT waitForOne initialState
pure $ case maybeResponse of
Nothing -> RacerResult
{ rrResponse = Nothing
, rrWinner = Nothing
, rrProviders = racerProviders
, rrStatuses = extractStatuses finalState
}
Just (as, response) -> RacerResult
{ rrResponse = Just response
, rrWinner = _csOptions <$> lookup as _rsClientMap
, rrProviders = racerProviders
, rrStatuses = extractStatuses finalState
}
-- $providers
--
-- 'RacerProvider' provide client configurations. Craze comes bundled with a
-- few built-in providers which can be used for quickly building client
-- configurations.
-- | A simple provider. It does not delay requests.
simple :: Monad m => [CurlOption] -> m ProviderOptions
simple xs = pure $ def { poOptions = xs }
-- | Like @simple@, but with a tag for identification.
simpleTagged :: Monad m => [CurlOption] -> Text -> m ProviderOptions
simpleTagged xs t = do
opts <- simple xs
pure $ opts { poTag = t }
-- | A provider which will delay a request by the provided number of
-- microseconds.
delayed :: Monad m => [CurlOption] -> Int -> m ProviderOptions
delayed xs d = pure $ def
{ poOptions = xs
, poDelay = Just d
}
-- | Like @delayed@, but with a tag for identification.
delayedTagged :: Monad m => [CurlOption] -> Int -> Text -> m ProviderOptions
delayedTagged xs d t = do
opts <- delayed xs d
pure $ opts { poTag = t }
-- | A `Racer` with some default values.
--
-- __Note:__ The handler will extract the response body as a `ByteString` and
-- ignore everything else, hence the type:
--
-- @
-- Racer [(String, String)] ByteString ByteString
-- @
--
-- If this is not the desired behavior, or if the response should be parsed or
-- processed, you should use the `Racer` constructor directly and provide all
-- fields.
defaultRacer :: Racer [(String,String)] ByteString ByteString
defaultRacer = def
{-# DEPRECATED defaultRacer "Use Data.Default.Class.def instead" #-}
-- | A default set of options for a provider.
defaultProviderOptions :: ProviderOptions
defaultProviderOptions = def
{-# DEPRECATED defaultProviderOptions "Use Data.Default.Class.def instead" #-}
|
etcinit/craze
|
src/Network/Craze.hs
|
bsd-3-clause
| 6,505 | 0 | 14 | 1,516 | 901 | 538 | 363 | 86 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# OPTIONS_HADDOCK prune #-}
{-|
Module : Silver.Compiler.Ast
Description : The ast types for silver.
Copyright : (c) Nicholas Dujay, 2016
License : MIT
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
-}
module Silver.Compiler.Ast where
import Control.Lens
import Control.Lens.Plated
import Control.Lens.TH
import Data.Data
import Data.Data.Lens
import Data.List
import Data.Word
import Text.Megaparsec
import qualified Data.Map.Lazy as Map
{-|
A silver program is a list of declarations. This program might have a module id,
and it might also expose some functions for other modules to consume.
-}
data Program =
Program { _pmoduleId :: Maybe String, _pexposed :: Maybe [String], _pbody :: [Declaration] }
deriving (Show,Eq,Data,Typeable)
{-|
A silver declaration is one of 4 cases: A binding, type signature, abstract
data type declaration, or finally a type alias.
-}
data Declaration =
BindingCase { _dname :: String, _dparameters :: [Pattern], _dexpr :: Expression }
| TypeSignature { _dname :: String, _dconstraints :: [TypeClassConstraint], _dtype :: AstType }
| DataDeclaration { _dname :: String, _dparams :: [String], _dconstructors :: [Constructor] }
| TypeAlias { _dname :: String, _dparams :: [String], _daliased :: AstType }
deriving (Show,Eq,Data,Typeable)
newtype TypeClassConstraint = TypeClassConstraint (String,String)
deriving (Show,Eq,Data,Typeable)
{-|
A binding may use pattern matching in its arguments. The pattern may match
the constructors allowed by an abstract data type, or it may just be a simple
name. The pattern may also be a constant, or a hole to represent that I do
not care about this parameter.
-}
data Pattern =
IdentifierPattern { _pname :: String }
| ConstructorPattern { _pname :: String, _pvars :: [String] }
| RecordPattern { _pname :: String, _pfields :: [String] }
| LiteralPattern { _pliteral :: Primitive }
| HolePattern
deriving (Show,Eq,Data,Typeable)
{-|
The ast uses type declarations in a few areas, such as the type signature, or
the ADT constructors. The List type is syntax sugar, while the tuple and unit
types are required as well.
-}
data AstType =
SimpleType { _aname :: String }
| ParameterizedType { _aname :: String, _aparams :: [AstType] }
| RelationType { _afrom :: AstType, _ato :: AstType }
| ListType { _atype :: AstType }
| TupleType { _atypes :: [AstType] }
| UnitType
deriving (Show,Eq,Data,Typeable)
{-|
An abstract data type may have Three different kinds of constructors:
- A simple named empty value
- A simple struct like constructor that only holds other values
- A record constructor, which holds "named" values.
-}
data Constructor =
EmptyConstructor { _cname :: String }
| SimpleConstructor { _cname :: String, _ctypes :: [AstType] }
| RecordConstructor { _cname ::String, _fields :: [(String,AstType)] }
deriving (Show,Eq,Data,Typeable)
{-|
Expressions are not fully developed yet.
-}
data Expression =
Constant { _eprim :: Primitive }
| Var { _evar :: String }
| FuncApplication { _efunc :: String, _eargs :: [Expression] }
| LetExpression { _ecases :: [(String,Expression)], _ein :: Expression }
| IfExpression { _epredicate :: Expression, _etrue :: Expression, _efalse :: Expression }
| ListExpression { _eexprs :: [Expression] }
| TupleExpression { _eexprs :: [Expression] }
deriving (Show,Eq,Data,Typeable)
{-|
There are 4 main primitive types, which will be coerced down to smaller types
based on the usage / type signature.
-}
data Primitive =
PChar Char
| PInt Integer
| PString String
| PFloat Double
deriving (Show,Eq,Data,Typeable)
-- lenses & prisms instances
makeLenses ''Program
makeLenses ''Declaration
makePrisms ''Declaration
makeLenses ''Pattern
makeLenses ''AstType
makeLenses ''Constructor
makeLenses ''Expression
makeLenses ''Primitive
-- uniplate instances
instance Plated Program
instance Plated Declaration
instance Plated Pattern
instance Plated AstType
instance Plated Constructor
instance Plated Expression
instance Plated Primitive
{-|
When the parser is completed parsing the list of types separated by '->', it
needs to convert it to a Relation type. Due to the parser, the input list
will always have two or more elements, but if you use this function yourself
you must ensure the input has at least 2 types, or else the returned relation
will be of type a -> a, when given [a].
-}
makeRelationType :: [AstType] -> AstType
makeRelationType ts = foldr RelationType (last ts) (init ts)
-- | Group the similarly named declarations together into a map, for easier
-- analysis
groupDeclarations :: [Declaration] -> Map.Map String [Declaration]
groupDeclarations = foldr f Map.empty
where
f decl m = Map.insertWith (++) (_dname decl) [decl] m
|
silver-lang/silver
|
src/Silver/Compiler/Ast.hs
|
bsd-3-clause
| 4,920 | 0 | 10 | 891 | 968 | 567 | 401 | 79 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Concurrent
import Control.Monad.Except
import Data.Version (showVersion)
import Paths_tansit (version)
import System.Console.GetOpt
import System.Environment
import System.IO
import System.IO.Temp
import System.ZMQ4.Monadic hiding (version)
import Tansit
data CmdFlag = Verbose | Version | BindEndpoint String | SignAs String
deriving (Eq, Show)
options :: [OptDescr CmdFlag]
options =
[ Option "v" ["verbose"] (NoArg Verbose) "doesn't do anything at the moment"
, Option "V?" ["version"] (NoArg Version) "show version number"
, Option "b" ["bind"] (ReqArg BindEndpoint "ENDPOINT") "bind ENDPOINT"
, Option "s" ["sign-as"] (ReqArg SignAs "KEYID") "sign-as KEYID"
]
parseOpts :: [String] -> IO ([CmdFlag], [String])
parseOpts argv =
case getOpt Permute options argv of
(o, n, []) -> return (o,n)
(_, _, errs) -> ioError (userError (concat errs ++ usageInfo header options))
where header = "Usage: tansit [OPTION...]"
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
(opts, _) <- getArgs >>= parseOpts
let (endpoint, signAs) = findOpts opts
if Version `elem` opts
then putStrLn $ showVersion version
else startServer endpoint $! signAs
where findOpts = foldl (\(i, j) o -> case o of
BindEndpoint s -> (s, j)
SignAs s -> (i, s)
_ -> (i, j))
("ipc:///tmp/tansit.zmq", error "--sign-as required")
startServer :: String -> String -> IO ()
startServer endpoint signAs =
runZMQ $ withSystemTempDirectory "tansit-packages" $ \tempDir -> do
liftIO $ putStrLn $ "Tansit starting!\nTemp dir: " ++ tempDir
debS3MVar <- liftIO $ newMVar ()
sock <- socket Router
bind sock endpoint
sockWorkers <- socket Dealer
bind sockWorkers workersEndpoint
replicateM_ 10 $ async $ serverWorker tempDir signAs debS3MVar
liftIO $ putStrLn $ "Listening on " ++ endpoint
proxy sock sockWorkers Nothing
|
madebymany/tansit
|
src/Main.hs
|
bsd-3-clause
| 2,279 | 0 | 13 | 661 | 667 | 350 | 317 | 52 | 4 |
module Platform where
import Rumpus
-- Platform extent in x & z
w = 4
-- Platform depth in y
d = 0.5
start :: Start
start = do
spawnChild_ $ do
myPose ==> position (V3 0 (-d/2) 0)
myShape ==> Cube
myBody ==> Animated
myBodyFlags ==> [Ungrabbable, Teleportable]
myColor ==> colorHSL 0.25 0.8 0.2
mySize ==> 0
myStart ==> animateSizeFromTo 0 (V3 w d w) 0.3
|
lukexi/rumpus
|
pristine/Intro/Platform.hs
|
bsd-3-clause
| 471 | 0 | 16 | 183 | 137 | 69 | 68 | 14 | 1 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
import Data.Monoid (mappend)
import Hakyll
--------------------------------------------------------------------------------
main :: IO ()
main = hakyll $ do
match "images/*" $ do
route idRoute
compile copyFileCompiler
match "css/index.css" $ do
route idRoute
compile $ getResourceString
>>= withItemBody (unixFilter "postcss" ["-c", "postcss.config.js", "--no-map"])
>>= withItemBody (return . compressCss)
match "js/*" $ do
route idRoute
compile copyFileCompiler
match "templates/*" $ compile templateCompiler
match "posts/*" $ do
route $ setExtension "html"
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/post.html" postCtx
>>= loadAndApplyTemplate "templates/default.html" postCtx
>>= relativizeUrls
create ["blog.html"] $ do
route idRoute
compile $ do
posts <- recentFirst =<< loadAll "posts/*"
let archiveCtx =
listField "posts" postCtx (return posts) `mappend`
constField "title" "博客" `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/archive.html" archiveCtx
>>= loadAndApplyTemplate "templates/default.html" archiveCtx
>>= relativizeUrls
match "other/*" $ compile pandocCompiler
create ["resume.html"] $ do
route idRoute
compile $ do
let ctx = constField "title" "" `mappend` postCtx
loadBody "other/resume.md"
>>= makeItem
>>= loadAndApplyTemplate "templates/default.html" ctx
create ["apps.html"] $ do
route idRoute
compile $ makeItem ""
>>= loadAndApplyTemplate "templates/apps.html" defaultContext
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
create ["index.html"] $ do
route idRoute
compile $ do
posts <- recentFirst =<< loadAll "posts/*"
let indexCtx =
listField "posts" postCtx (return posts) `mappend`
constField "title" "" `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/home.html" indexCtx
>>= relativizeUrls
match ("static/*/*" .&&. fromRegex "(css|js|html)$") $ do
route idRoute
compile copyFileCompiler
--------------------------------------------------------------------------------
postCtx :: Context String
postCtx =
dateField "date" "%B %e, %Y" `mappend`
defaultContext
|
montagy/montagy.github.io
|
site.hs
|
bsd-3-clause
| 2,826 | 2 | 21 | 846 | 600 | 269 | 331 | 67 | 1 |
{-|
Module : Idris.Core.Unify
Description : Idris' unification code.
Copyright :
License : BSD3
Maintainer : The Idris Community.
Unification is applied inside the theorem prover. We're looking for holes
which can be filled in, by matching one term's normal form against another.
Returns a list of hole names paired with the term which solves them, and
a list of things which need to be injective.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.Core.Unify(
match_unify, unify
, Fails, FailContext(..), FailAt(..)
, unrecoverable
) where
import Idris.Core.Evaluate
import Idris.Core.TT
import Control.Monad
import Control.Monad.State.Strict
import Data.List
import Data.Maybe
import Debug.Trace
-- terms which need to be injective, with the things we're trying to unify
-- at the time
data FailAt = Match | Unify
deriving (Show, Eq)
data FailContext = FailContext { fail_sourceloc :: FC,
fail_fn :: Name,
fail_param :: Name
}
deriving (Eq, Show)
type Injs = [(TT Name, TT Name, TT Name)]
type Fails = [(TT Name, TT Name, -- unification error
Bool, -- ready to retry yet
Env, Err, [FailContext], FailAt)]
unrecoverable :: Fails -> Bool
unrecoverable = any bad
where bad (_,_,_,_, err, _, _) = unrec err
unrec (CantUnify r _ _ _ _ _) = not r
unrec (At _ e) = unrec e
unrec (Elaborating _ _ _ e) = unrec e
unrec (ElaboratingArg _ _ _ e) = unrec e
unrec _ = False
data UInfo = UI Int Fails
deriving Show
data UResult a = UOK a
| UPartOK a
| UFail Err
-- | Smart constructor for unification errors that takes into account the FailContext
cantUnify :: [FailContext] -> Bool -> (t, Maybe Provenance) -> (t, Maybe Provenance) -> (Err' t) -> [(Name, t)] -> Int -> Err' t
cantUnify [] r t1 t2 e ctxt i = CantUnify r t1 t2 e ctxt i
cantUnify (FailContext fc f x : prev) r t1 t2 e ctxt i =
At fc (ElaboratingArg f x
(map (\(FailContext _ f' x') -> (f', x')) prev)
(CantUnify r t1 t2 e ctxt i))
-- Solve metavariables by matching terms against each other
-- Not really unification, of course!
match_unify :: Context -> Env ->
(TT Name, Maybe Provenance) ->
(TT Name, Maybe Provenance) -> [Name] -> [Name] -> [FailContext] ->
TC [(Name, TT Name)]
match_unify ctxt env (topx, xfrom) (topy, yfrom) inj holes from =
case runStateT (un [] (renameBindersTm env topx)
(renameBindersTm env topy)) (UI 0 []) of
OK (v, UI _ []) ->
do v' <- trimSolutions (topx, xfrom) (topy, yfrom) from env v
return (map (renameBinders env) v')
res ->
let topxn = renameBindersTm env (normalise ctxt env topx)
topyn = renameBindersTm env (normalise ctxt env topy) in
case runStateT (un [] topxn topyn)
(UI 0 []) of
OK (v, UI _ fails) ->
do v' <- trimSolutions (topx, xfrom) (topy, yfrom) from env v
return (map (renameBinders env) v')
Error e ->
-- just normalise the term we're matching against
case runStateT (un [] topxn topy)
(UI 0 []) of
OK (v, UI _ fails) ->
do v' <- trimSolutions (topx, xfrom) (topy, yfrom) from env v
return (map (renameBinders env) v')
_ -> tfail e
where
un :: [((Name, Name), TT Name)] -> TT Name -> TT Name ->
StateT UInfo
TC [(Name, TT Name)]
un names tx@(P _ x _) tm
| tx /= tm && holeIn env x || x `elem` holes
= do sc 1; checkCycle names tx (x, tm)
un names tm ty@(P _ y _)
| ty /= tm && holeIn env y || y `elem` holes
= do sc 1; checkCycle names ty (y, tm)
un bnames (V i) (P _ x _)
| length bnames > i,
fst (fst (bnames!!i)) == x ||
snd (fst (bnames!!i)) == x = do sc 1; return []
un bnames (P _ x _) (V i)
| length bnames > i,
fst (fst (bnames!!i)) == x ||
snd (fst (bnames!!i)) == x = do sc 1; return []
un bnames (Bind x bx sx) (Bind y by sy) | notHole bx && notHole by
= do h1 <- uB bnames bx by
h2 <- un (((x, y), binderTy bx) : bnames) sx sy
combine bnames h1 h2
un names (App _ fx ax) (App _ fy ay)
= do hf <- un names fx fy
ha <- un names ax ay
combine names hf ha
un names x y
| OK True <- convEq' ctxt holes x y = do sc 1; return []
| otherwise = do UI s f <- get
let r = recoverable (normalise ctxt env x)
(normalise ctxt env y)
let err = cantUnify from r
(topx, xfrom) (topy, yfrom) (CantUnify r (x, Nothing) (y, Nothing) (Msg "") (errEnv env) s) (errEnv env) s
if (not r) then lift $ tfail err
else do put (UI s ((x, y, True, env, err, from, Match) : f))
lift $ tfail err
uB bnames (Let tx vx) (Let ty vy) = do h1 <- un bnames tx ty
h2 <- un bnames vx vy
combine bnames h1 h2
uB bnames (Lam _ tx) (Lam _ ty) = un bnames tx ty
uB bnames (Pi r i tx _) (Pi r' i' ty _) = un bnames tx ty
uB bnames x y = do UI s f <- get
let r = recoverable (normalise ctxt env (binderTy x))
(normalise ctxt env (binderTy y))
let err = cantUnify from r (topx, xfrom) (topy, yfrom)
(CantUnify r (binderTy x, Nothing)
(binderTy y, Nothing) (Msg "") (errEnv env) s)
(errEnv env) s
put (UI s ((binderTy x, binderTy y,
False,
env, err, from, Match) : f))
return []
notHole (Hole _) = False
notHole _ = True
-- TODO: there's an annoying amount of repetition between this and the
-- main unification function. Consider lifting it out.
-- Issue #1721 on the issue tracker: https://github.com/idris-lang/Idris-dev/issues/1721
sc i = do UI s f <- get
put (UI (s+i) f)
unifyFail x y = do UI s f <- get
let r = recoverable (normalise ctxt env x)
(normalise ctxt env y)
let err = cantUnify from r
(topx, xfrom) (topy, yfrom)
(CantUnify r (x, Nothing) (y, Nothing) (Msg "") (errEnv env) s) (errEnv env) s
put (UI s ((x, y, True, env, err, from, Match) : f))
lift $ tfail err
combine bnames as [] = return as
combine bnames as ((n, t) : bs)
= case lookup n as of
Nothing -> combine bnames (as ++ [(n,t)]) bs
Just t' -> do ns <- un bnames t t'
let ns' = filter (\ (x, _) -> x/=n) ns
sc 1
combine bnames as (ns' ++ bs)
-- substN n tm (var, sol) = (var, subst n tm sol)
checkCycle ns xtm p@(x, P _ x' _) | x == x' = return []
checkCycle ns xtm p@(x, P _ _ _) = return [p]
checkCycle ns xtm (x, tm)
| conGuarded ctxt x tm = lift $ tfail (InfiniteUnify x tm (errEnv env))
| x `elem` freeNames tm = unifyFail xtm tm
| otherwise = checkScope ns (x, tm)
checkScope ns (x, tm) =
-- case boundVs (envPos x 0 env) tm of
-- [] -> return [(x, tm)]
-- (i:_) -> lift $ tfail (UnifyScope x (fst (fst (ns!!i)))
-- (impl ns tm) (errEnv env))
let v = highV (-1) tm in
if v >= length ns
then lift $ tfail (Msg "SCOPE ERROR")
else return [(x, bind v ns tm)]
where impl [] tm = tm
impl ((n, _) : ns) tm = impl ns (substV (P Bound n Erased) tm)
bind i ns tm
| i < 0 = tm
| otherwise = let ((x,y),ty) = ns!!i in
App MaybeHoles (Bind y (Lam RigW ty) (bind (i-1) ns tm))
(P Bound x ty)
renameBinders env (x, t) = (x, renameBindersTm env t)
renameBindersTm :: Env -> TT Name -> TT Name
renameBindersTm env tm = uniqueBinders (map fstEnv env) tm
where
uniqueBinders env (Bind n b sc)
| n `elem` env
= let n' = uniqueName n env in
explicitHole $ Bind n' (fmap (uniqueBinders env) b)
(uniqueBinders (n':env) (rename n n' sc))
| otherwise = Bind n (fmap (uniqueBinders (n:env)) b)
(uniqueBinders (n:env) sc)
uniqueBinders env (App s f a) = App s (uniqueBinders env f) (uniqueBinders env a)
uniqueBinders env t = t
rename n n' (P nt x ty) | n == x = P nt n' ty
rename n n' (Bind x b sc) = Bind x (fmap (rename n n') b) (rename n n' sc)
rename n n' (App s f a) = App s (rename n n' f) (rename n n' a)
rename n n' t = t
explicitHole (Bind n (Hole ty) sc)
= Bind n (Hole ty) (instantiate (P Bound n ty) sc)
explicitHole t = t
trimSolutions (topx, xfrom) (topy, yfrom) from env topns = followSols [] (dropPairs topns)
where dropPairs [] = []
dropPairs (n@(x, P _ x' _) : ns)
| x == x' = dropPairs ns
| otherwise
= n : dropPairs
(filter (\t -> case t of
(n, P _ n' _) -> not (n == x' && n' == x)
_ -> True) ns)
dropPairs (n : ns) = n : dropPairs ns
followSols vs [] = return []
followSols vs ((n, P _ t _) : ns)
| Just t' <- lookup t ns
= do vs' <- case t' of
P _ tn _ ->
if (n, tn) `elem` vs then -- cycle
tfail (cantUnify from False (topx, xfrom) (topy, yfrom)
(Msg "") (errEnv env) 0)
else return ((n, tn) : vs)
_ -> return vs
followSols vs' ((n, t') : ns)
followSols vs (n : ns) = do ns' <- followSols vs ns
return $ n : ns'
expandLets env (x, tm) = (x, doSubst (reverse env) tm)
where
doSubst [] tm = tm
doSubst ((n, Let v t) : env) tm
= doSubst env (subst n v tm)
doSubst (_ : env) tm
= doSubst env tm
hasv :: TT Name -> Bool
hasv (V x) = True
hasv (App _ f a) = hasv f || hasv a
hasv (Bind x b sc) = hasv (binderTy b) || hasv sc
hasv _ = False
unify :: Context -> Env ->
(TT Name, Maybe Provenance) ->
(TT Name, Maybe Provenance) ->
[Name] -> [Name] -> [Name] -> [FailContext] ->
TC ([(Name, TT Name)], Fails)
unify ctxt env (topx, xfrom) (topy, yfrom) inj holes usersupp from =
-- traceWhen (hasv topx || hasv topy)
-- ("Unifying " ++ show topx ++ "\nAND\n" ++ show topy ++ "\n") $
-- don't bother if topx and topy are different at the head
case runStateT (un False [] (renameBindersTm env topx)
(renameBindersTm env topy)) (UI 0 []) of
OK (v, UI _ []) -> do v' <- trimSolutions (topx, xfrom) (topy, yfrom) from env v
return (map (renameBinders env) v', [])
res ->
let topxn = renameBindersTm env (normalise ctxt env topx)
topyn = renameBindersTm env (normalise ctxt env topy) in
-- trace ("Unifying " ++ show (topx, topy) ++ "\n\n==>\n" ++ show (topxn, topyn) ++ "\n\n") $
case runStateT (un False [] topxn topyn)
(UI 0 []) of
OK (v, UI _ fails) ->
do v' <- trimSolutions (topx, xfrom) (topy, yfrom) from env v
-- trace ("OK " ++ show (topxn, topyn, v, holes)) $
return (map (renameBinders env) v', reverse fails)
-- Error e@(CantUnify False _ _ _ _ _) -> tfail e
Error e -> tfail e
where
headDiff (P (DCon _ _ _) x _) (P (DCon _ _ _) y _) = x /= y
headDiff (P (TCon _ _) x _) (P (TCon _ _) y _) = x /= y
headDiff _ _ = False
injective (P (DCon _ _ _) _ _) = True
injective (P (TCon _ _) _ _) = True
injective (P Ref n _)
| Just i <- lookupInjectiveExact n ctxt = i
injective (App _ f a) = injective f -- && injective a
injective _ = False
-- injectiveVar (P _ (MN _ _) _) = True -- TMP HACK
injectiveVar (P _ n _) = n `elem` inj
injectiveVar (App _ f a) = injectiveVar f -- && injective a
injectiveVar _ = False
injectiveApp x = injective x || injectiveVar x
notP (P _ _ _) = False
notP _ = True
sc i = do UI s f <- get
put (UI (s+i) f)
errors :: StateT UInfo TC Bool
errors = do UI s f <- get
return (not (null f))
uplus u1 u2 = do UI s f <- get
r <- u1
UI s f' <- get
if (length f == length f')
then return r
else do put (UI s f); u2
un :: Bool -> [((Name, Name), TT Name)] -> TT Name -> TT Name ->
StateT UInfo
TC [(Name, TT Name)]
un = un' env
-- un fn names x y
-- = let (xf, _) = unApply x
-- (yf, _) = unApply y in
-- if headDiff xf yf then unifyFail x y else
-- uplus (un' fn names x y)
-- (un' fn names (hnf ctxt env x) (hnf ctxt env y))
un' :: Env -> Bool -> [((Name, Name), TT Name)] -> TT Name -> TT Name ->
StateT UInfo
TC [(Name, TT Name)]
un' env fn names x y | x == y = return [] -- shortcut
un' env fn names topx@(P (DCon _ _ _) x _) topy@(P (DCon _ _ _) y _)
| x /= y = unifyFail topx topy
un' env fn names topx@(P (TCon _ _) x _) topy@(P (TCon _ _) y _)
| x /= y = unifyFail topx topy
un' env fn names topx@(P (DCon _ _ _) x _) topy@(P (TCon _ _) y _)
= unifyFail topx topy
un' env fn names topx@(P (TCon _ _) x _) topy@(P (DCon _ _ _) y _)
= unifyFail topx topy
un' env fn names topx@(Constant _) topy@(P (TCon _ _) y _)
= unifyFail topx topy
un' env fn names topx@(P (TCon _ _) x _) topy@(Constant _)
= unifyFail topx topy
un' env fn bnames tx@(P _ x _) ty@(P _ y _)
| (x,y) `elem` map fst bnames || x == y = do sc 1; return []
| injective tx && not (holeIn env y || y `elem` holes)
= unifyTmpFail tx ty
| injective ty && not (holeIn env x || x `elem` holes)
= unifyTmpFail tx ty
-- pick the one bound earliest if both are holes
| tx /= ty && (holeIn env x || x `elem` holes)
&& (holeIn env y || y `elem` holes)
= case compare (envPos 0 x env) (envPos 0 y env) of
LT -> do sc 1; checkCycle bnames tx (x, ty)
_ -> do sc 1; checkCycle bnames ty (y, tx)
where envPos i n ((n',_,_):env) | n == n' = i
envPos i n (_:env) = envPos (i+1) n env
envPos _ _ _ = 100000
un' env fn bnames xtm@(P _ x _) tm
| pureTerm tm, holeIn env x || x `elem` holes
= do UI s f <- get
-- injectivity check
x <- checkCycle bnames xtm (x, tm)
if (notP tm && fn)
-- trace (show (x, tm, normalise ctxt env tm)) $
-- put (UI s ((tm, topx, topy) : i) f)
then unifyTmpFail xtm tm
else do sc 1
return x
| pureTerm tm, not (injective xtm) && injective tm
= do checkCycle bnames xtm (x, tm)
unifyTmpFail xtm tm
un' env fn bnames tm ytm@(P _ y _)
| pureTerm tm, holeIn env y || y `elem` holes
= do UI s f <- get
-- injectivity check
x <- checkCycle bnames ytm (y, tm)
if (notP tm && fn)
-- trace (show (y, tm, normalise ctxt env tm)) $
-- put (UI s ((tm, topx, topy) : i) f)
then unifyTmpFail tm ytm
else do sc 1
return x
| pureTerm tm, not (injective ytm) && injective tm
= do checkCycle bnames ytm (y, tm)
unifyTmpFail tm ytm
un' env fn bnames (V i) (P _ x _)
| length bnames > i,
fst ((map fst bnames)!!i) == x ||
snd ((map fst bnames)!!i) == x = do sc 1; return []
un' env fn bnames (P _ x _) (V i)
| length bnames > i,
fst ((map fst bnames)!!i) == x ||
snd ((map fst bnames)!!i) == x = do sc 1; return []
un' env fn names topx@(Bind n (Hole t) sc) y = unifyTmpFail topx y
un' env fn names x topy@(Bind n (Hole t) sc) = unifyTmpFail x topy
-- Pattern unification rule
un' env fn bnames tm app@(App _ _ _)
| (mvtm@(P _ mv _), args) <- unApply app,
holeIn env mv || mv `elem` holes,
all rigid args,
containsOnly (mapMaybe getname args) (mapMaybe getV args) tm
-- && TODO: tm does not refer to any variables other than those
-- in 'args'
= -- trace ("PATTERN RULE SOLVE: " ++ show (mv, tm, env, bindLams args (substEnv env tm))) $
checkCycle bnames mvtm (mv, eta [] $ bindLams args (substEnv env tm))
where rigid (V i) = True
rigid (P _ t _) = t `elem` map fstEnv env &&
not (holeIn env t || t `elem` holes)
rigid _ = False
getV (V i) = Just i
getV _ = Nothing
getname (P _ n _) = Just n
getname _ = Nothing
containsOnly args vs (V i) = i `elem` vs
containsOnly args vs (P Bound n ty)
= n `elem` args && containsOnly args vs ty
containsOnly args vs (P _ n ty)
= not (holeIn env n || n `elem` holes)
&& containsOnly args vs ty
containsOnly args vs (App _ f a)
= containsOnly args vs f && containsOnly args vs a
containsOnly args vs (Bind _ b sc)
= containsOnly args vs (binderTy b) &&
containsOnly args (0 : map (+1) vs) sc
containsOnly args vs _ = True
bindLams [] tm = tm
bindLams (a : as) tm = bindLam a (bindLams as tm)
bindLam (V i) tm = Bind (fstEnv (env !! i))
(Lam RigW (binderTy (sndEnv (env !! i))))
tm
bindLam (P _ n ty) tm = Bind n (Lam RigW ty) tm
bindLam _ tm = error "Can't happen [non rigid bindLam]"
substEnv [] tm = tm
substEnv ((n, _, t) : env) tm
= substEnv env (substV (P Bound n (binderTy t)) tm)
-- remove any unnecessary lambdas (helps with interface
-- resolution later).
eta ks (Bind n (Lam r ty) sc) = eta ((n, r, ty) : ks) sc
eta ks t = rebind ks t
rebind ((n, r, ty) : ks) (App _ f (P _ n' _))
| n == n' = eta ks f
rebind ((n, r, ty) : ks) t = rebind ks (Bind n (Lam r ty) t)
rebind _ t = t
un' env fn bnames appx@(App _ _ _) appy@(App _ _ _)
= unApp env fn bnames appx appy
-- = uplus (unApp fn bnames appx appy)
-- (unifyTmpFail appx appy) -- take the whole lot
un' env fn bnames x (Bind n (Lam _ t) (App _ y (P Bound n' _)))
| n == n' = un' env False bnames x y
un' env fn bnames (Bind n (Lam _ t) (App _ x (P Bound n' _))) y
| n == n' = un' env False bnames x y
un' env fn bnames x (Bind n (Lam _ t) (App _ y (V 0)))
= un' env False bnames x y
un' env fn bnames (Bind n (Lam _ t) (App _ x (V 0))) y
= un' env False bnames x y
-- un' env fn bnames (Bind x (PVar _) sx) (Bind y (PVar _) sy)
-- = un' env False ((x,y):bnames) sx sy
-- un' env fn bnames (Bind x (PVTy _) sx) (Bind y (PVTy _) sy)
-- = un' env False ((x,y):bnames) sx sy
-- f D unifies with t -> D. This is dubious, but it helps with
-- interface resolution for interfaces over functions.
un' env fn bnames (App _ f x) (Bind n (Pi r i t k) y)
| noOccurrence n y && injectiveApp f
= do ux <- un' env False bnames x y
uf <- un' env False bnames f (Bind (sMN 0 "uv") (Lam RigW (TType (UVar [] 0)))
(Bind n (Pi r i t k) (V 1)))
combine env bnames ux uf
un' env fn bnames (Bind n (Pi r i t k) y) (App _ f x)
| noOccurrence n y && injectiveApp f
= do ux <- un' env False bnames y x
uf <- un' env False bnames (Bind (sMN 0 "uv") (Lam RigW (TType (UVar [] 0)))
(Bind n (Pi r i t k) (V 1))) f
combine env bnames ux uf
un' env fn bnames (Bind x bx sx) (Bind y by sy)
| sameBinder bx by
= do h1 <- uB env bnames bx by
h2 <- un' ((x, RigW, bx) : env) False (((x,y),binderTy bx):bnames) sx sy
combine env bnames h1 h2
where sameBinder (Lam _ _) (Lam _ _) = True
sameBinder (Pi _ i _ _) (Pi _ i' _ _) = True
sameBinder _ _ = False -- never unify holes/guesses/etc
un' env fn bnames x y
| OK True <- convEq' ctxt holes x y = do sc 1; return []
| isUniverse x && isUniverse y = do sc 1; return []
| otherwise = do UI s f <- get
let r = recoverable (normalise ctxt env x)
(normalise ctxt env y)
let err = cantUnify from r
(topx, xfrom) (topy, yfrom) (CantUnify r (x, Nothing) (y, Nothing) (Msg "") (errEnv env) s) (errEnv env) s
if (not r) then lift $ tfail err
else do put (UI s ((x, y, True, env, err, from, Unify) : f))
return [] -- lift $ tfail err
unApp env fn bnames appx@(App _ fx ax) appy@(App _ fy ay)
-- shortcut for the common case where we just want to check the
-- arguments are correct
| (injectiveApp fx && fx == fy)
= un' env False bnames ax ay
| (injectiveApp fx && injectiveApp fy)
|| (injectiveApp fx && metavarApp fy && ax == ay)
|| (injectiveApp fy && metavarApp fx && ax == ay)
= do let (headx, _) = unApply fx
let (heady, _) = unApply fy
-- fail quickly if the heads are disjoint
checkHeads headx heady
uplus
(do hf <- un' env True bnames fx fy
let ax' = hnormalise hf ctxt env (substNames hf ax)
let ay' = hnormalise hf ctxt env (substNames hf ay)
-- Don't normalise if we don't have to
ha <- uplus (un' env False bnames (substNames hf ax)
(substNames hf ay))
(un' env False bnames ax' ay')
sc 1
combine env bnames hf ha)
(do ha <- un' env False bnames ax ay
let fx' = hnormalise ha ctxt env (substNames ha fx)
let fy' = hnormalise ha ctxt env (substNames ha fy)
-- Don't normalise if we don't have to
hf <- uplus (un' env False bnames (substNames ha fx)
(substNames ha fy))
(un' env False bnames fx' fy')
sc 1
combine env bnames hf ha)
| otherwise = unifyTmpFail appx appy
where hnormalise [] _ _ t = t
hnormalise ns ctxt env t = normalise ctxt env t
checkHeads (P (DCon _ _ _) x _) (P (DCon _ _ _) y _)
| x /= y = unifyFail appx appy
checkHeads (P (TCon _ _) x _) (P (TCon _ _) y _)
| x /= y = unifyFail appx appy
checkHeads (P (DCon _ _ _) x _) (P (TCon _ _) y _)
= unifyFail appx appy
checkHeads (P (TCon _ _) x _) (P (DCon _ _ _) y _)
= unifyFail appx appy
checkHeads _ _ = return []
numArgs tm = let (f, args) = unApply tm in length args
metavarApp tm = let (f, args) = unApply tm in
(metavar f &&
all (\x -> metavarApp x) args
&& nub args == args) ||
globmetavar tm
metavarArgs tm = let (f, args) = unApply tm in
all (\x -> metavar x || inenv x) args
&& nub args == args
metavarApp' tm = let (f, args) = unApply tm in
all (\x -> pat x || metavar x) (f : args)
&& nub args == args
rigid (P (DCon _ _ _) _ _) = True
rigid (P (TCon _ _) _ _) = True
rigid t@(P Ref _ _) = inenv t || globmetavar t
rigid (Constant _) = True
rigid (App _ f a) = rigid f && rigid a
rigid t = not (metavar t) || globmetavar t
globmetavar t = case unApply t of
(P _ x _, _) ->
case lookupDef x ctxt of
[TyDecl _ _] -> True
_ -> False
_ -> False
metavar t = case t of
P _ x _ -> (x `notElem` usersupp &&
(x `elem` holes || holeIn env x))
|| globmetavar t
_ -> False
pat t = case t of
P _ x _ -> x `elem` holes || patIn env x
_ -> False
inenv t = case t of
P _ x _ -> x `elem` (map fstEnv env)
_ -> False
notFn t = injective t || metavar t || inenv t
unifyTmpFail :: Term -> Term -> StateT UInfo TC [(Name, TT Name)]
unifyTmpFail x y
= do UI s f <- get
let r = recoverable (normalise ctxt env x) (normalise ctxt env y)
let err = cantUnify from r
(topx, xfrom) (topy, yfrom)
(CantUnify r (x, Nothing) (y, Nothing) (Msg "") (errEnv env) s) (errEnv env) s
put (UI s ((topx, topy, True, env, err, from, Unify) : f))
return []
-- shortcut failure, if we *know* nothing can fix it
unifyFail x y = do UI s f <- get
let r = recoverable (normalise ctxt env x) (normalise ctxt env y)
let err = cantUnify from r
(topx, xfrom) (topy, yfrom)
(CantUnify r (x, Nothing) (y, Nothing) (Msg "") (errEnv env) s) (errEnv env) s
put (UI s ((topx, topy, True, env, err, from, Unify) : f))
lift $ tfail err
uB env bnames (Let tx vx) (Let ty vy)
= do h1 <- un' env False bnames tx ty
h2 <- un' env False bnames vx vy
sc 1
combine env bnames h1 h2
uB env bnames (Guess tx vx) (Guess ty vy)
= do h1 <- un' env False bnames tx ty
h2 <- un' env False bnames vx vy
sc 1
combine env bnames h1 h2
uB env bnames (Lam _ tx) (Lam _ ty) = do sc 1; un' env False bnames tx ty
uB env bnames (Pi _ _ tx _) (Pi _ _ ty _) = do sc 1; un' env False bnames tx ty
uB env bnames (Hole tx) (Hole ty) = un' env False bnames tx ty
uB env bnames (PVar _ tx) (PVar _ ty) = un' env False bnames tx ty
uB env bnames x y
= do UI s f <- get
let r = recoverable (normalise ctxt env (binderTy x))
(normalise ctxt env (binderTy y))
let err = cantUnify from r (topx, xfrom) (topy, yfrom)
(CantUnify r (binderTy x, Nothing) (binderTy y, Nothing) (Msg "") (errEnv env) s)
(errEnv env) s
put (UI s ((binderTy x, binderTy y,
False,
env, err, from, Unify) : f))
return [] -- lift $ tfail err
checkCycle ns xtm p@(x, P _ _ _) = return [p]
checkCycle ns xtm (x, tm)
| conGuarded ctxt x tm = lift $ tfail (InfiniteUnify x tm (errEnv env))
| x `elem` freeNames tm = unifyTmpFail xtm tm
| otherwise = checkScope ns (x, tm)
checkScope ns (x, tm) | pureTerm tm =
-- case boundVs (envPos x 0 env) tm of
-- [] -> return [(x, tm)]
-- (i:_) -> lift $ tfail (UnifyScope x (fst (fst (ns!!i)))
-- (impl ns tm) (errEnv env))
let v = highV (-1) tm in
if v >= length ns
then lift $ tfail (Msg "SCOPE ERROR")
else return [(x, bind v ns tm)]
where impl [] tm = tm
impl (((n, _), _) : ns) tm = impl ns (substV (P Bound n Erased) tm)
checkScope ns (x, tm) = lift $ tfail (Msg "HOLE ERROR")
bind i ns tm
| i < 0 = tm
| otherwise = let ((x,y),ty) = ns!!i in
App MaybeHoles (Bind y (Lam RigW ty) (bind (i-1) ns tm))
(P Bound x ty)
combine env bnames as [] = return as
combine env bnames as ((n, t) : bs)
= case lookup n as of
Nothing -> combine env bnames (as ++ [(n,t)]) bs
Just t' -> do ns <- un' env False bnames t t'
-- make sure there's n mapping from n in ns
let ns' = filter (\ (x, _) -> x/=n) ns
sc 1
combine env bnames as (ns' ++ bs)
boundVs :: Int -> Term -> [Int]
boundVs i (V j) | j < i = []
| otherwise = [j]
boundVs i (Bind n b sc) = boundVs (i + 1) sc
boundVs i (App _ f x) = let fs = boundVs i f
xs = boundVs i x in
nub (fs ++ xs)
boundVs i _ = []
highV :: Int -> Term -> Int
highV i (V j) | j > i = j
| otherwise = i
highV i (Bind n b sc) = maximum [i, highV i (binderTy b), (highV i sc - 1)]
highV i (App _ f x) = max (highV i f) (highV i x)
highV i _ = i
envPos x i [] = 0
envPos x i ((y, _) : ys) | x == y = i
| otherwise = envPos x (i + 1) ys
-- If there are any clashes of constructors, deem it unrecoverable, otherwise some
-- more work may help.
-- FIXME: Depending on how overloading gets used, this may cause problems. Better
-- rethink overloading properly...
-- ASSUMPTION: inputs are in normal form
--
-- Issue #1722 on the issue tracker https://github.com/idris-lang/Idris-dev/issues/1722
--
recoverable t@(App _ _ _) _
| (P _ (UN l) _, _) <- unApply t, l == txt "Delayed" = False
recoverable _ t@(App _ _ _)
| (P _ (UN l) _, _) <- unApply t, l == txt "Delayed" = False
recoverable (P (DCon _ _ _) x _) (P (DCon _ _ _) y _) = x == y
recoverable (P (TCon _ _) x _) (P (TCon _ _) y _) = x == y
recoverable (TType _) (P (DCon _ _ _) y _) = False
recoverable (UType _) (P (DCon _ _ _) y _) = False
recoverable (Constant _) (P (DCon _ _ _) y _) = False
recoverable (Constant x) (Constant y) = x == y
recoverable (P (DCon _ _ _) x _) (TType _) = False
recoverable (P (DCon _ _ _) x _) (UType _) = False
recoverable (P (DCon _ _ _) x _) (Constant _) = False
recoverable (TType _) (P (TCon _ _) y _) = False
recoverable (UType _) (P (TCon _ _) y _) = False
recoverable (Constant _) (P (TCon _ _) y _) = False
recoverable (P (TCon _ _) x _) (TType _) = False
recoverable (P (TCon _ _) x _) (UType _) = False
recoverable (P (TCon _ _) x _) (Constant _) = False
recoverable (P (DCon _ _ _) x _) (P (TCon _ _) y _) = False
recoverable (P (TCon _ _) x _) (P (DCon _ _ _) y _) = False
recoverable p@(TType _) (App _ f a) = recoverable p f
recoverable p@(UType _) (App _ f a) = recoverable p f
recoverable p@(Constant _) (App _ f a) = recoverable p f
recoverable (App _ f a) p@(TType _) = recoverable f p
recoverable (App _ f a) p@(UType _) = recoverable f p
recoverable (App _ f a) p@(Constant _) = recoverable f p
recoverable p@(P _ n _) (App _ f a) = recoverable p f
recoverable (App _ f a) p@(P _ _ _) = recoverable f p
recoverable (App _ f a) (App _ f' a')
| f == f' = recoverable a a'
recoverable (App _ f a) (App _ f' a')
= recoverable f f' -- && recoverable a a'
recoverable f (Bind _ (Pi _ _ _ _) sc)
| (P (DCon _ _ _) _ _, _) <- unApply f = False
| (P (TCon _ _) _ _, _) <- unApply f = False
| (Constant _) <- f = False
| TType _ <- f = False
| UType _ <- f = False
recoverable (Bind _ (Pi _ _ _ _) sc) f
| (P (DCon _ _ _) _ _, _) <- unApply f = False
| (P (TCon _ _) _ _, _) <- unApply f = False
| (Constant _) <- f = False
| TType _ <- f = False
| UType _ <- f = False
recoverable (Bind _ (Lam _ _) sc) f = recoverable sc f
recoverable f (Bind _ (Lam _ _) sc) = recoverable f sc
recoverable x y = True
errEnv :: [(a, r, Binder b)] -> [(a, b)]
errEnv = map (\(x, _, b) -> (x, binderTy b))
holeIn :: Env -> Name -> Bool
holeIn env n = case lookupBinder n env of
Just (Hole _) -> True
Just (Guess _ _) -> True
_ -> False
patIn :: Env -> Name -> Bool
patIn env n = case lookupBinder n env of
Just (PVar _ _) -> True
Just (PVTy _) -> True
_ -> False
|
jmitchell/Idris-dev
|
src/Idris/Core/Unify.hs
|
bsd-3-clause
| 35,188 | 0 | 22 | 14,885 | 14,177 | 7,068 | 7,109 | 620 | 87 |
module Main ( main ) where
import qualified Types.BotTypes as BT
import Control.Monad (forever)
import System.Environment (getArgs)
import System.Exit (ExitCode(ExitSuccess, ExitFailure))
import System.IO (stdout, stdin, hSetBuffering, BufferMode(..))
import System.Process (readProcessWithExitCode)
import Text.Regex.PCRE ((=~))
import Data.Aeson (decode)
import qualified Data.Text.Lazy.IO as T
import qualified Data.Text.Lazy.Encoding as T
main :: IO ()
main = do
(nick:_) <- getArgs
hSetBuffering stdout LineBuffering
hSetBuffering stdin LineBuffering
forever $ do
line <- T.getLine
handleMessage nick $ (decode . T.encodeUtf8) line
handleMessage :: String -> Maybe BT.ServerMessage -> IO ()
handleMessage nick (Just (BT.ServerPrivMsg _ _ msg))
| str =~ helpPattern = putStrLn $ help nick
| [[_, text]] <- str =~ runPattern1 = asciitext text
| [[_, text]] <- str =~ runPattern2 = asciitext text
where
str = BT.getMessage msg
helpPattern = concat ["^", sp, nick, ":", ps, "asciitext", ps, "help", sp,
"$"]
runPattern1 = concat ["^", sp, "asciitext:", ps, "(.*)$"]
runPattern2 = concat ["^", sp, nick, ":", ps, "asciitext", ps, "(.*)$"]
sp = "[ \\t]*"
ps = "[ \\t]+"
handleMessage _ _ = return ()
asciitext :: String -> IO ()
asciitext text = do
(e, s, _) <- readProcessWithExitCode "/usr/bin/toilet" [text] []
case e of
ExitSuccess -> putStrLn s
ExitFailure _ -> return ()
help :: String -> String
help nick = unlines
[ nick ++ " asciitext help - display this message"
, "asciitext: <text> - display text as asciitext"
]
|
bus000/Dikunt
|
plugins/AsciiText/Main.hs
|
bsd-3-clause
| 1,645 | 0 | 14 | 350 | 578 | 319 | 259 | 42 | 2 |
{-# LANGUAGE BangPatterns, ScopedTypeVariables, TupleSections #-}
module Language.Haskell.GhcMod.GhcPkg (
ghcPkgList
, ghcPkgListEx
, ghcPkgDbOpt
, ghcPkgDbStackOpts
, ghcDbStackOpts
, ghcDbOpt
, getSandboxDb
, getPackageDbStack
) where
import Config (cProjectVersionInt) -- ghc version
import Control.Applicative ((<$>))
import Control.Exception (SomeException(..))
import qualified Control.Exception as E
import Data.Char (isSpace,isAlphaNum)
import Data.List (isPrefixOf, intercalate)
import Data.Maybe (listToMaybe, maybeToList)
import Language.Haskell.GhcMod.Types
import Language.Haskell.GhcMod.Utils
import System.Exit (ExitCode(..))
import System.FilePath ((</>))
import System.IO (hPutStrLn,stderr)
import System.Process (readProcessWithExitCode)
import Text.ParserCombinators.ReadP (ReadP, char, between, sepBy1, many1, string, choice, eof)
import qualified Text.ParserCombinators.ReadP as P
ghcVersion :: Int
ghcVersion = read cProjectVersionInt
-- | Get path to sandbox package db
getSandboxDb :: FilePath -- ^ Path to the cabal package root directory
-- (containing the @cabal.sandbox.config@ file)
-> IO FilePath
getSandboxDb cdir = getSandboxDbDir (cdir </> "cabal.sandbox.config")
-- | Extract the sandbox package db directory from the cabal.sandbox.config file.
-- Exception is thrown if the sandbox config file is broken.
getSandboxDbDir :: FilePath -- ^ Path to the @cabal.sandbox.config@ file
-> IO FilePath
getSandboxDbDir sconf = do
-- Be strict to ensure that an error can be caught.
!path <- extractValue . parse <$> readFile sconf
return path
where
key = "package-db:"
keyLen = length key
parse = head . filter (key `isPrefixOf`) . lines
extractValue = dropWhileEnd isSpace . dropWhile isSpace . drop keyLen
getPackageDbStack :: FilePath -- ^ Project Directory (where the
-- cabal.sandbox.config file would be if it
-- exists)
-> IO [GhcPkgDb]
getPackageDbStack cdir =
(getSandboxDb cdir >>= \db -> return [GlobalDb, PackageDb db])
`E.catch` \(_ :: SomeException) -> return [GlobalDb, UserDb]
-- | List packages in one or more ghc package store
ghcPkgList :: [GhcPkgDb] -> IO [PackageBaseName]
ghcPkgList dbs = map fst3 <$> ghcPkgListEx dbs
where fst3 (x,_,_) = x
ghcPkgListEx :: [GhcPkgDb] -> IO [Package]
ghcPkgListEx dbs = do
(rv,output,err) <- readProcessWithExitCode "ghc-pkg" opts ""
case rv of
ExitFailure val -> do
hPutStrLn stderr err
fail $ "ghc-pkg " ++ unwords opts ++ " (exit " ++ show val ++ ")"
ExitSuccess -> return ()
return $ parseGhcPkgOutput $ lines output
where
opts = ["list", "-v"] ++ ghcPkgDbStackOpts dbs
parseGhcPkgOutput :: [String] -> [Package]
parseGhcPkgOutput [] = []
parseGhcPkgOutput (l:ls) =
parseGhcPkgOutput ls ++ case l of
[] -> []
h:_ | isSpace h -> maybeToList $ packageLine l
| otherwise -> []
packageLine :: String -> Maybe Package
packageLine l =
case listToMaybe $ P.readP_to_S packageLineP l of
Just ((Normal,p),_) -> Just p
Just ((Hidden,p),_) -> Just p
_ -> Nothing
data PackageState = Normal | Hidden | Broken deriving (Eq,Show)
packageLineP :: ReadP (PackageState, Package)
packageLineP = do
P.skipSpaces
p <- choice [ (Hidden,) <$> between (char '(') (char ')') packageP
, (Broken,) <$> between (char '{') (char '}') packageP
, (Normal,) <$> packageP ]
eof
return p
packageP :: ReadP (PackageBaseName, PackageVersion, PackageId)
packageP = do
pkgSpec@(name,ver) <- packageSpecP
P.skipSpaces
i <- between (char '(') (char ')') $ packageIdSpecP pkgSpec
return (name,ver,i)
packageSpecP :: ReadP (PackageBaseName,PackageVersion)
packageSpecP = do
fs <- many1 packageCompCharP `sepBy1` char '-'
return (intercalate "-" (init fs), last fs)
packageIdSpecP :: (PackageBaseName,PackageVersion) -> ReadP PackageId
packageIdSpecP (name,ver) = do
string name >> char '-' >> string ver >> char '-' >> return ()
many1 (P.satisfy isAlphaNum)
packageCompCharP :: ReadP Char
packageCompCharP =
P.satisfy $ \c -> isAlphaNum c || c `elem` "_-."
-- | Get options needed to add a list of package dbs to ghc-pkg's db stack
ghcPkgDbStackOpts :: [GhcPkgDb] -- ^ Package db stack
-> [String]
ghcPkgDbStackOpts dbs = ghcPkgDbOpt `concatMap` dbs
-- | Get options needed to add a list of package dbs to ghc's db stack
ghcDbStackOpts :: [GhcPkgDb] -- ^ Package db stack
-> [String]
ghcDbStackOpts dbs = ghcDbOpt `concatMap` dbs
ghcPkgDbOpt :: GhcPkgDb -> [String]
ghcPkgDbOpt GlobalDb = ["--global"]
ghcPkgDbOpt UserDb = ["--user"]
ghcPkgDbOpt (PackageDb pkgDb)
| ghcVersion < 706 = ["--no-user-package-conf", "--package-conf=" ++ pkgDb]
| otherwise = ["--no-user-package-db", "--package-db=" ++ pkgDb]
ghcDbOpt :: GhcPkgDb -> [String]
ghcDbOpt GlobalDb
| ghcVersion < 706 = ["-global-package-conf"]
| otherwise = ["-global-package-db"]
ghcDbOpt UserDb
| ghcVersion < 706 = ["-user-package-conf"]
| otherwise = ["-user-package-db"]
ghcDbOpt (PackageDb pkgDb)
| ghcVersion < 706 = ["-no-user-package-conf", "-package-conf", pkgDb]
| otherwise = ["-no-user-package-db", "-package-db", pkgDb]
|
carlohamalainen/ghc-mod
|
Language/Haskell/GhcMod/GhcPkg.hs
|
bsd-3-clause
| 5,425 | 0 | 16 | 1,177 | 1,537 | 828 | 709 | 118 | 3 |
{-# LANGUAGE FlexibleContexts, TypeFamilies, ViewPatterns, TupleSections #-}
module TypeDiagrams
( drawCode
, typeDiagram
, lined, arrow ) where
import Annotations
import State
import Utils
import Control.Arrow ((***), (&&&), first, second)
import Control.Monad
import Control.Newtype
import Data.Data hiding (typeOf)
import Data.Default
import Data.Dynamic (fromDynamic)
import Data.Foldable (concat)
import Data.IORef
import Data.Label
import Data.List (intersperse, sort, find, findIndices)
import Data.List.Split (splitWhen, splitOn)
import Data.Maybe (catMaybes, fromMaybe)
import Data.Monoid (Monoid)
import Data.Supply
import Diagrams.Backend.Cairo.CmdLine
import Diagrams.Backend.Cairo.Text (StyleParam, textLineBounded)
import Graphics.Rendering.Diagrams.Names (NameMap(..), Name(..), AName(..))
import Graphics.UI.Gtk.Toy.Diagrams
import Graphics.UI.Gtk.Toy.Prelude hiding
((===), (|||), trim, debug, debug', fromDynamic, ivlContains, Ivl)
import Prelude hiding (concat)
import Language.Haskell.Exts.Annotated hiding (Name)
import qualified Data.Map as M
import System.IO.Unsafe
type ISupply = IORef (Supply Int)
startSupply :: IO ISupply
startSupply = newIORef =<< newDupableNumSupply
popSupply r = unsafePerformIO $ do
val <- readIORef r
let (val', _) = split2 val
writeIORef r val'
return (supplyValue val)
coloredShapes :: [String] -> M.Map String CairoDiagram
coloredShapes names
= M.fromList
. (++ [("Int", scale 0.2 $ monoText "Z")])
. zip names
$ zipWith (\i c -> fc c $ polygon $ def {polyType = PolyRegular i 1.0}) [4..]
[aqua, crimson, brown, fuchsia, khaki, indigo, papayawhip, thistle]
main :: IO ()
main = do
--sup <- startSupply
let tys = map (second parseT)
[ ("map", "forall a. (Arrow a) => a b c -> a d e -> a (b, d) (c, e)")
, ("(+1)", "a -> a")
, ("[1..]", "[a]") ]
squig _ xs = Just $ (lined (squiggle 1) # alignT ||| vsep xs # alignT)
usr = matchContext (parseT "Arrow a => a") (gtDraw squig)
-- usr r a t = r a t
let dia = typeDiagram (0 :: Int) (coloredShapes $ map (:[]) ['a'..]) usr (snd $ tys !! 0)
bg = fc white $ rect (20 + width dia) (20 + height dia)
defaultMain ((centerXY dia) `atop` (centerXY bg))
where
parseT = mustOk . parseIt
monoText :: String -> CairoDiagram
monoText = textLineBounded monoStyle
drawCode :: MarkedText (Versioned Ann) -> CairoDiagram
drawCode mt
= vcat
. map (draw . substrText True mtSorted . second (+1))
. ivlsFromSlices (textLength mt)
. findIndices (=='\n')
$ get mText mt
where
mtSorted = modify mMarks sortMarks mt
marks = get mMarks mtSorted
subsetIx = case filter (isCursor . snd) marks of
(ivl, _) : _ -> fromMaybe 0 $ do
(i, m) <- smallestEnclosing isSubsetA ivl mt
(s, _) <- getSubset m
return s
[] -> 0
drawText = draw . (`MarkedText` [])
drawSubstr mt = draw . substrText False mt
drawType = scale 5 . typeDiagram "" shapes (const $ const $ const Nothing)
drawIvlType ivl t =
case smallestEnclosing isTypeA ivl t of
Just (_, Version _ (TypeA (s, _) typ))
| s == subsetIx -> drawType typ
Nothing -> drawText "?"
shapes = coloredShapes . map prettyPrint $ uniquePrims allTypes
allTypes = [x | (_, Version _ (TypeA (s, _) x)) <- marks, s == subsetIx]
draw (MarkedText txt [])
= monoText $ filter (not . (`elem` "\r\n")) txt
draw (MarkedText txt (((fm, tm), m):xs))
= drawSubstr mt (-1, fm)
||| handleMark (get versionValue m) (substrText True mt (fm, tm))
||| drawSubstr mt (tm, length txt + 1)
where
mt = MarkedText txt xs
includeGaps mt = ivlsFromSlices (textLength mt)
. concatMap ivlSlices
handleMark CursorA -- = drawMark CursorMark txt . draw
= \mt' -> case get mText mt' of
"" -> lineWidth 1 . lineColor black
. moveOriginBy (-1.5, 2)
. setEnvelope mempty
$ drawSeg (0, 18)
_ -> draw mt'
# fc white
# highlight black
{-
handleMark (AppA ivls)
= \mt' -> let rec = map (drawSubstr mt') $ includeGaps mt' ivls
w = width rec
in hsep rec === alignL (hrule w) === texts "App"
-}
{-
handleMark (TypeA (s, _) ty)
| s == subsetIx = (\x -> x === drawType ty) . draw
| otherwise = draw
-}
{-
handleMark (SubsetA (s, _) tyc)
| s == subsetIx = (\x -> x === drawText (show tyc)) . draw
| otherwise = draw
-}
handleMark (AstA d)
= \t -> let t' = removeAstMarks t
in maybe (draw t') id
$ msum [ drawExpr t' <$> fromDynamic d
, drawOp t' <$> fromDynamic d ]
handleMark _ = draw
removeAstMarks (MarkedText txt ms)
= MarkedText txt $ filter (not . isTopExpr . second (get versionValue)) ms
where
isTopExpr (i, AstA d)
= i == (0, length txt - 1) -- && isJust (fromDynamic d :: Maybe ExpS)
isTopExpr _ = False
-- TODO: show (via highlight) which parts are part of the code
-- TODO: find position of ->
drawExpr t (InfixApp _ l o r) = hcat
[ drawSubstr t soIvl
, drawSubstr t oIvl
, drawSubstr t oeIvl
]
where
[soIvl, oIvl, oeIvl] = includeGaps mt [annSpan o]
drawExpr t a@(App _ l r) = drawApp t a
-- [ drawSubstr t ]
drawExpr t (Lambda _ pats expr) = hcat
[ drawText "λ"
, drawSubstr t bs
, strutX 10
, alignB . lined $ arrow (20, 0) (5, 5)
, strutX 10
, drawSubstr t e
, drawSubstr t pe
]
where
[pbs, bs, m, e, pe]
= includeGaps t [foldl1 ivlUnion $ map annSpan pats, annSpan expr]
drawExpr t (EnumFrom _ f)
= drawEnum t (annSpan f) Nothing
drawExpr t (EnumFromTo _ f to)
= drawEnum t (annSpan f) . Just $ annSpan to
drawExpr t (EnumFromThen _ f th)
= drawEnum t (ivlUnion (annSpan f) $ annSpan th) Nothing
drawExpr t (EnumFromThenTo _ f th to)
= drawEnum t (ivlUnion (annSpan f) $ annSpan th) . Just $ annSpan to
drawExpr t _ = draw t
drawApp :: MarkedText (Versioned Ann) -> ExpS -> CairoDiagram
drawApp t a@(App _ _ _)
= dia <> appBar
where
appBar :: CairoDiagram
appBar = foldl1 (<>) . zipWith lineBetween ps $ tail ps
lineBetween :: Point R2 -> Point R2 -> CairoDiagram
lineBetween p1 p2 = scale (-1) . moveOriginTo p1 $ drawSeg (p2 .-. p1)
ps = map (location . head) . catMaybes $ map (\n -> lookupN n (names dia)) xs
dia = hcat . zipWith tDia xs . ((strutY 5 ===):) $ repeat id
tDia ivl f = drawSubstr t ivl === (named ivl . f $ drawIvlType ivl t)
xs = map annSpan $ splitEApp a
{-
lPos :: [Point R2]
lPos ivl = [ location $ head p
| n <- M.assocs . unpack $ names dia
, let (Name (AName (cast -> Just nivl):_), p) = n
, nivl == ivl
]
dia = ( drawSubstr t lIvl
===
(--if isApp l then mempty else
named (rt,lIvl) $ drawIvlType lIvl t) )
drawApp t l r = dia <> case tPos of
(tr:tl:_) ->
-- moveOriginTo tl $ drawSeg (tr .-. tl)
{- moveOriginTo (scaleX (-1) tr) (circle 5)
<> moveOriginTo (scaleX (-1) tl) (circle 10)
-}
_ -> mempty
where
lIvl = annSpan l
rIvl = annSpan r
||| ( drawSubstr t rIvl
===
(named (rt,rIvl) . (strutY 2 ===) $ drawIvlType rIvl t) )
rt = "result type"
ns :: [(Name, Point R2)]
ns = map (second $ location . head) . M.assocs . unpack $ names dia
tPos :: [Point R2]
tPos = [p | (Name (AName (cast -> Just ("result type", ivl :: Ivl)):_), p) <- ns]
-}
-- drawExpr t (NegApp _ l) = hcat
ellipsis = translateY 2.5 (c1 ||| c1 ||| c1)
where c1 = circle 0.1 ||| strutX 3
drawEnum t (_, fr) to = hcat
[ drawSubstr t (0, fr)
, strutX 2
, ellipsis
, maybe mempty (drawSubstr t . (second $ const $ textLength t)) to
]
-- TODO: special cases for %
fancy = "@$%?%"
drawOp t op = case op of
QVarOp _ o -> helper o
QConOp _ o -> helper o
where
helper (Qual _ mn n) = drawText (prettyPrint $ Qual sp mn $ Symbol sp "")
||| drawOp' (prettyPrint n)
helper v = drawOp' . init . tail $ prettyPrint v
drawOp' :: String -> CairoDiagram
drawOp' = hcat . map (translateY 5.5 . helper)
where
seg = translateY 0.5 $ hrule 10
slash = rotate (Deg 60.0) (hrule 12)
equals = seg === strutY 3 === seg
diamond l r xs = undefined
helper '-' = seg
helper '+' = seg <> rotate (Deg 90.0) seg
helper '=' = equals
helper '#' = equals <> rotate (Deg 90.0) equals
helper '/' = slash
helper '\\' = scaleX (-1) slash
--TODO: better enclosure.
{-
helper '<' =
case map reverse . splitOn ">" $ reverse xs of
[post, pre] -> diamond True True pre ||| drawOp post
_ -> diamond True False xs
helper (p:'>':xs) = diamond
-}
helper '|' = vrule 16
helper '.' = circle 4
helper x = centerXY $ drawText [x]
{-
| Let l (Binds l) (Exp l)
| If l (Exp l) (Exp l) (Exp l)
| Case l (Exp l) [Alt l]
| Do l [Stmt l]
| MDo l [Stmt l]
| Tuple l [Exp l]
| TupleSection l [Maybe (Exp l)]
| List l [Exp l]
| Paren l (Exp l)
| LeftSection l (Exp l) (QOp l)
| RightSection l (QOp l) (Exp l)
| RecConstr l (QName l) [FieldUpdate l]
| RecUpdate l (Exp l) [FieldUpdate l]
| ListComp l (Exp l) [QualStmt l]
| ParComp l (Exp l) [[QualStmt l]]
| ExpTypeSig l (Exp l) (Type l)
| VarQuote l (QName l)
| TypQuote l (QName l)
| BracketExp l (Bracket l)
| SpliceExp l (Splice l)
| QuasiQuote l String String
| XTag l (XName l) [XAttr l] (Maybe (Exp l)) [Exp l]
| XETag l (XName l) [XAttr l] (Maybe (Exp l))
| XPcdata l String
| XExpTag l (Exp l)
| XChildTag l [Exp l]
| CorePragma l String (Exp l)
| SCCPragma l String (Exp l)
| GenPragma l String (Int, Int) (Int, Int) (Exp l)
| Proc l (Pat l) (Exp l)
| LeftArrApp l (Exp l) (Exp l)
| RightArrApp l (Exp l) (Exp l)
| LeftArrHighApp l (Exp l) (Exp l)
| RightArrHighApp l (Exp l) (Exp l)
-}
type TypeDiagram = [AsstS] -> TypeS -> CairoDiagram
type UserDiagram = TypeDiagram -> [AsstS] -> [TypeS] -> Maybe CairoDiagram
-- Utility to convert a function from a Type and its arguments into a
-- UserDiagram.
gtDraw :: (TypeS -> [CairoDiagram] -> Maybe CairoDiagram) -> UserDiagram
gtDraw f g as (t:ts) = f t $ map (g as) ts
-- Applies to primitives that posess a similar context as the given type
matchContext :: TypeS -> UserDiagram -> UserDiagram
matchContext (TyForall _ _ c t) usr rec c' ts@(t':_)
| process t (get contextList c) == process t' c' = usr rec c' ts
| otherwise = Nothing
where
process t = sort . map (\(ClassA _ x _) -> prettyPrint x) . filter pred
where
pred a@(ClassA _ _ xs) = elem (prettyPrint t) $ map prettyPrint xs
pred _ = False
matchContext _ _ _ _ _ = Nothing
-- Diagrams Utilities
cw (x, y) = (negate y, x)
ccw (x, y) = (y, -x)
--cwd = rotate (Deg (-90))
--ccwd = rotate (Deg 90)
ltrail = Trail . map Linear
scaleXY (x, y) = scaleX x . scaleY y
hsep, vsep
:: ( HasOrigin a, Enveloped a, Monoid a, Semigroup a, Juxtaposable a
, V a ~ (Double, Double) )
=> [a] -> a
hsep = hcat' (def {sep = 1})
vsep = vcat' (def {sep = 1})
hsep', vsep'
:: ( HasOrigin a, Enveloped a, Monoid a, Semigroup a, Juxtaposable a
, V a ~ (Double, Double) )
=> Double -> [a] -> a
hsep' s = hcat' (def {sep = s})
vsep' s = vcat' (def {sep = s})
drawSeg v = stroke . pathFromTrail
$ Trail [Linear v] False
stroked :: Path R2 -> CairoDiagram
stroked = stroke' (def { vertexNames = [] :: [[Int]] })
infixl 6 ===
infixl 6 |||
(|||), (===)
:: ( Monoid a, Juxtaposable a, HasOrigin a, Enveloped a, Semigroup a
, V a ~ (Double, Double))
=> a -> a -> a
x === y = vsep [x, y]
x ||| y = hsep [x, y]
setRectBounds :: R2 -> Diagram b R2 -> Diagram b R2
setRectBounds r2 = setEnvelope bnds
where
bnds = getEnvelope $ centerXY $ Path
[ (P zeroV, ltrail [ r2 ] False) ]
expandRectBounds :: R2 -> Diagram b R2 -> Diagram b R2
expandRectBounds (x, y) d = setRectBounds (width d + x, height d + y) d
texts :: String -> CairoDiagram
texts = centerY . textLineBounded (fontSize 14)
texts' :: String -> CairoDiagram
texts' = centerY . scale 0.1 . textLineBounded (fontSize 14)
arrow :: ( Floating (Scalar t)
, Num t
, InnerSpace t
, AdditiveGroup (Scalar t) )
=> (t, t) -- ^ Vector used for direction and length
-> (Scalar t, Scalar t) -- ^ Width and height of the arrow head
-> Path (t, t) -- ^ Path which yields an arrow diagram when stroked
arrow v (w, h) = Path
[ (P zeroV, ltrail [ v ] False)
, (P (v ^+^ hp ^+^ hn), ltrail [ negateV (hn ^+^ hp), hn ^-^ hp ] False)
]
where
nv = negateV $ normalized v
hn = nv ^* h
hp = cw nv ^* w
bracket :: (Fractional a) => (a, a) -> Path (a, a)
bracket (w, h) = Path
[ (P (w, -h / 2), ltrail [ (-w, 0), (0, h), (w, 0) ] False) ]
bannana :: R2 -> Double -> Double -> Path R2
bannana (x, y) t1 t2 = centerY $ Path $ [(P (0, -y), Trail segs True)]
where
segs = arcTrail (-40) 40 (x, y)
++ [Linear (-t2, 0)]
++ arcTrail (-40) 40 (x - t1, -y)
firstTrail :: Path R2 -> [Segment R2]
firstTrail (Path ((_, Trail t _):_)) = t
arcTrail :: Double -> Double -> R2 -> [Segment R2]
arcTrail ld hd v = firstTrail $ scaleXY v $ arc (Deg ld) (Deg hd)
squiggle :: Double -> Path R2
squiggle h = scaleY (-1)
. (mappend (arrow (0, 2) (1, 1)))
. Path . (:[]) . (P zeroV,) . (`Trail` False)
$ arcTrail (90) (-90) v
++ arcTrail (-270) (-90) v
++ arcTrail (90) (-90) v
++ arcTrail (-270) (-90) v
where
v = (h / 4, h / 3)
cross :: R2 -> Path R2
cross v = Path [ (P v, Trail [Linear $ v ^* (-2)] False)
, (P $ cw v, Trail [Linear $ ccw (v ^* 2)] False)
]
lined :: Path R2 -> CairoDiagram
lined = lineWidth 1 . stroked
{-
barTop d = (lined . hrule $ width d)
===
centerX d
barBottom d = centerX d
===
(lined . hrule $ width d)
-}
typeDiagram :: IsName t
=> t
-> M.Map String CairoDiagram
-> UserDiagram
-> TypeS
-> CairoDiagram
typeDiagram pre dm usr = (=== strutY 2) . rec []
where
prim ident s
= case M.lookup ident dm of
Just d -> named (ident, s) d
Nothing -> named (ident, s) $ texts' ident
primT ty = prim (trim $ prettyPrint ty) (getSpan' ty)
nameEnds t d = hcat
[ named (pre, getSpan' t, False) mempty
, d
, named (pre, getSpan' t, True) mempty
]
rec :: TypeDiagram
rec ctx ty = nameEnds ty $ draw ty
where
recc = rec ctx
draw t@(TyCon _ _) = primT t
draw t@(TyVar _ _) = primT t
draw t@(TyFun _ _ _)
= hsep' (-0.5) [ alignT . farrow $ height parts, alignT parts ]
where
parts = vsep . map recc $ splitTFunc t
farrow h = lined $ arrow (0, negate $ h + 3.0) (1.5, 1.5)
draw t@(TyApp _ _ _) = case usr rec ctx ts of
Just d -> d
_ -> let parts = hsep $ map recc ts
in moveOriginBy (0, -1.3)
$ centerX parts
where
ts = splitTApp t
draw (TyForall _ Nothing ctx' t) = -- rec ctx t --TODO
rec (ctx ++ get contextList ctx') t
draw (TyForall _ bnds ctx' t)
= ( texts' "A" # scaleY (-1)
-- ||| -- ===
-- vsep (zipWith prim (getVars bnds))
||| text "." # scaleXY (0.2, 0.2)
) ||| rec ctx t
draw (TyList _ x) = bracketDia $ draw x
draw (TyParen _ x) = draw x -- hsep [ lparen, draw x, rparen ]
draw (TyTuple _ _ xs) = hsep
$ [lparen] ++ intersperse tcross (map recc xs) ++ [rparen]
-- TODO: better intervals
draw (TyInfix s l o r) = recc (TyApp s (TyApp s (TyCon s o) l) r)
draw (TyKind _ t _) = recc t
tcross = lined $ cross (0.5, 0.5)
bracketDia d = hsep [ centerY . lined $ bracket (1, h), d, centerY . lined $ bracket (-1, h) ]
where h = height d
lparen = scaleX (-1) rparen
rparen = lineWidth 0 . fc black . stroked $ bannana (2, 2) 0.1 0.3
|
mgsloan/panopti
|
src/TypeDiagrams.hs
|
bsd-3-clause
| 16,562 | 0 | 18 | 5,012 | 5,655 | 2,959 | 2,696 | 317 | 25 |
{-# LANGUAGE BangPatterns #-}
module Data.Tree23.SortedMap (
Map,
empty, singleton,
null, size,
insert, insertAll,
insertWith, insertAllWith,
delete, deleteAll,
member, notMember,
lookup,
fromList, toList,
keys, values,
map, mapKeys, mapKeysMonotonic,
filter, partition,
unionWith, unionL, unionR, union,
unions, unionsWith,
findMin, findMax,
clean,
) where
import Prelude hiding (null, map, filter, lookup)
import Data.Maybe
import Data.Ord
import qualified Data.List as L
import Data.Monoid (Monoid, mempty, mappend, (<>), mconcat)
import Data.Foldable (Foldable(..))
import qualified Data.Foldable as F
import qualified Data.Tree23.Tree23 as T23
import qualified Data.Tree23.Entry as E
type Map k v = T23.Tree k v
empty :: Map k v
empty = T23.empty
null :: Map k v -> Bool
null = T23.null
singleton :: k -> v -> Map k v
singleton = T23.singleton
size :: Map k v -> Int
size = T23.size
-- insert or update (strict to avoid O(n) stack pending ops when used with List.foldl').
insert :: Ord k => (k, v) -> Map k v -> Map k v
insert = T23.insertWith (const)
insertWith :: Ord k => (v -> v -> v) -> (k, v) -> Map k v -> Map k v
insertWith = T23.insertWith
insertAll :: (Ord k, Foldable t) => t (k, v) -> Map k v -> Map k v
insertAll xs map = F.foldl' (flip insert) map xs
insertAllWith :: (Ord k, Foldable t) => (v -> v -> v) -> t (k, v) -> Map k v -> Map k v
insertAllWith f xs map = F.foldl' (flip (insertWith f)) map xs
delete :: Ord k => k -> Map k v -> Map k v
delete = T23.delete
deleteAll :: (Ord k, Foldable t) => t k -> Map k v -> Map k v
deleteAll xs map = F.foldl' (flip T23.delete) map xs
member, notMember :: Ord k => k -> Map k v -> Bool
member = T23.member
notMember k = not . T23.member k
lookup :: Ord k => k -> Map k v -> Maybe (k, v)
lookup = T23.lookup
---------------------------------------------------------------
fromList :: (Ord k, Foldable t) => t (k, v) -> Map k v
fromList xs = insertAll xs empty
toList :: Map k v -> [(k, v)]
toList = T23.toList
---------------------------------------------------------------
keys :: Map k v -> [k]
keys = fst . L.unzip . toList
values :: Map k v -> [v]
values = snd . L.unzip . toList
---------------------------------------------------------------
map :: (v1 -> v2) -> Map k v1 -> Map k v2
map f = T23.mapEntriesValues (E.mapEntryValue f)
mapKeys :: (Ord k1, Ord k2) => (k1 -> k2) -> Map k1 v -> Map k2 v
mapKeys f = fromList . L.map (\(k, v) -> (f k, v)) . toList
mapKeysMonotonic :: (Ord k1, Ord k2) => (k1 -> k2) -> Map k1 v -> Map k2 v
mapKeysMonotonic f = T23.mapEntriesKeysMonotonic (E.mapEntryKey f)
----------------------------------------------------------------
filter :: (k -> Bool) -> Map k v -> Map k v
filter prop = T23.mapEntries (E.filterEntry prop)
partition :: (k -> Bool) -> Map k v -> (Map k v, Map k v)
partition p xs = (filter p xs, filter (not . p) xs)
----------------------------------------------------------------
unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWith f tx ty = L.foldl' (flip (T23.insertWith f)) ty (toList tx)
unionL, unionR, union :: Ord k => Map k v -> Map k v -> Map k v
unionR tx ty = insertAll (toList ty) tx -- on collision it keeps last inserted
unionL tx ty = insertAll (toList tx) ty -- on collision it keeps last inserted
union = unionL
----------------------------------------------------------------
unions :: (Ord k) => [Map k v] -> Map k v
unions [] = T23.empty
unions (hd:tl) = insertAll tailElems hd
where tailElems = L.concatMap toList tl
unionsWith :: (Ord k) => (a -> a -> a) -> [Map k a] -> Map k a
unionsWith f [] = T23.empty
unionsWith f (hd:tl) = insertAllWith f tailElems hd
where tailElems = L.concatMap toList tl
----------------------------------------------------------------
-- remove deleted
clean :: Ord k => Map k v -> Map k v
clean = fromList . toList
----------------------------------------------------------------
findMin, findMax :: Ord k => Map k v -> Maybe (k, v)
findMin = T23.minimum
findMax = T23.maximum
|
griba2001/tree23-map-set
|
src/Data/Tree23/SortedMap.hs
|
bsd-3-clause
| 4,100 | 0 | 11 | 831 | 1,698 | 906 | 792 | 90 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module DbTests.TransactionAtmOperatorFee (transactionAtmOperatorFeeTests) where
import Test.Tasty
import Test.Tasty.HUnit
import Db
import DbTests.Internal
transactionAtmOperatorFeeTests :: TestTree
transactionAtmOperatorFeeTests = testGroup "TransactionAtmOperatorFee"
[ testCase "roundTrip" testRoundTrip ]
testRoundTrip :: Assertion
testRoundTrip = roundTripTest "transaction_atm_operator_fee"
insertTransactionAtmOperatorFee
getTransactionAtmOperatorFee
(\ n _ -> n)
(TransactionAtmOperatorFee 1 "Withdrawal")
|
benkolera/talk-stacking-your-monads
|
code/tests/DbTests/TransactionAtmOperatorFee.hs
|
mit
| 563 | 0 | 7 | 59 | 93 | 53 | 40 | 15 | 1 |
-- | a module for caching a monadic action based on its return type
--
-- The cache is a HashMap where the key uses the TypeReP from Typeable.
-- The value stored is toDyn from Dynamic to support arbitrary value types in the same Map.
--
-- un-exported newtype wrappers should be used to maintain unique keys in the cache.
-- Note that a TypeRep is unique to a module in a package, so types from different modules will not conflict if they have the same name.
--
-- used in 'Yesod.Core.Handler.cached' and 'Yesod.Core.Handler.cachedBy'
module Yesod.Core.TypeCache (cached, cacheGet, cacheSet, cachedBy, cacheByGet, cacheBySet, TypeMap, KeyedTypeMap) where
import Prelude hiding (lookup)
import Data.Typeable (Typeable, TypeRep, typeOf)
import Data.HashMap.Strict
import Data.ByteString (ByteString)
import Data.Dynamic (Dynamic, toDyn, fromDynamic)
type TypeMap = HashMap TypeRep Dynamic
type KeyedTypeMap = HashMap (TypeRep, ByteString) Dynamic
-- | avoid performing the same action multiple times.
-- Values are stored by their TypeRep from Typeable.
-- Therefore, you should use un-exported newtype wrappers for each cache.
--
-- For example, yesod-auth uses an un-exported newtype, CachedMaybeAuth and exports functions that utilize it such as maybeAuth.
-- This means that another module can create its own newtype wrapper to cache the same type from a different action without any cache conflicts.
--
-- In Yesod, this is used for a request-local cache that is cleared at the end of every request.
-- See the original announcement: <http://www.yesodweb.com/blog/2013/03/yesod-1-2-cleaner-internals>
--
-- Since 1.4.0
cached :: (Monad m, Typeable a)
=> TypeMap
-> m a -- ^ cache the result of this action
-> m (Either (TypeMap, a) a) -- ^ Left is a cache miss, Right is a hit
cached cache action = case cacheGet cache of
Just val -> return $ Right val
Nothing -> do
val <- action
return $ Left (cacheSet val cache, val)
-- | Retrieves a value from the cache
--
-- @since 1.6.10
cacheGet :: Typeable a => TypeMap -> Maybe a
cacheGet cache = res
where
res = lookup (typeOf $ fromJust res) cache >>= fromDynamic
fromJust :: Maybe a -> a
fromJust = error "Yesod.Handler.cached.fromJust: Argument to typeOf was evaluated"
-- | Sets a value in the cache
--
-- @since 1.6.10
cacheSet :: (Typeable a)
=> a
-> TypeMap
-> TypeMap
cacheSet v cache = insert (typeOf v) (toDyn v) cache
-- | similar to 'cached'.
-- 'cached' can only cache a single value per type.
-- 'cachedBy' stores multiple values per type by indexing on a ByteString key
--
-- 'cached' is ideal to cache an action that has only one value of a type, such as the session's current user
-- 'cachedBy' is required if the action has parameters and can return multiple values per type.
-- You can turn those parameters into a ByteString cache key.
-- For example, caching a lookup of a Link by a token where multiple token lookups might be performed.
--
-- Since 1.4.0
cachedBy :: (Monad m, Typeable a)
=> KeyedTypeMap
-> ByteString -- ^ a cache key
-> m a -- ^ cache the result of this action
-> m (Either (KeyedTypeMap, a) a) -- ^ Left is a cache miss, Right is a hit
cachedBy cache k action = case cacheByGet k cache of
Just val -> return $ Right val
Nothing -> do
val <- action
return $ Left (cacheBySet k val cache, val)
-- | Retrieves a value from the keyed cache
--
-- @since 1.6.10
cacheByGet :: Typeable a => ByteString -> KeyedTypeMap -> Maybe a
cacheByGet key c = res
where
res = lookup (typeOf $ fromJust res, key) c >>= fromDynamic
fromJust :: Maybe a -> a
fromJust = error "Yesod.Handler.cached.fromJust: Argument to typeOf was evaluated"
-- | Sets a value in the keyed cache
--
-- @since 1.6.10
cacheBySet :: Typeable a => ByteString -> a -> KeyedTypeMap -> KeyedTypeMap
cacheBySet key v cache = insert (typeOf v, key) (toDyn v) cache
|
geraldus/yesod
|
yesod-core/src/Yesod/Core/TypeCache.hs
|
mit
| 4,160 | 0 | 13 | 1,009 | 669 | 370 | 299 | 44 | 2 |
{-|
Module : Lib
Description : VECA library
Copyright : (c) 2017 Pascal Poizat
License : Apache-2.0 (see the file LICENSE)
Maintainer : [email protected]
Stability : experimental
Portability : unknown
-}
module Lib
where
import Data.Monoid ((<>))
import Examples.Rover.Model
import Veca.IO
{-|
Sample function to generate the XTA output for an example.
-}
dumpExampleAsXTA :: String -> String -> IO ()
dumpExampleAsXTA path example = case example of
"rover" -> do
writeToXTA (path <> ".xta") rover
putStrLn "generation done"
_ -> putStrLn "unknown example"
{-|
Sample function to dump an example into JSON.
-}
dumpExampleAsJSON :: String -> String -> IO ()
dumpExampleAsJSON path example = case example of
"rover" -> do
writeToJSON (path <> ".json") rover
putStrLn "generation done"
_ -> putStrLn "unknown example"
{-|
Sample function to read a component in JSON (to check if format is ok).
-}
read :: String -> IO ()
read path =
let input = path <> ".json"
output = path <> ".xta"
in do
mc <- readFromJSON input
case mc of
Nothing -> putStrLn $ "error could not read file " <> input
Just aComponent -> putStrLn "reading done"
{-|
Sample function to read a component in JSON format and dump it in XTA format.
-}
transform :: String -> IO ()
transform path =
let input = path <> ".json"
output = path <> ".xta"
in do
mc <- readFromJSON input
case mc of
Nothing -> putStrLn $ "error could not read file " <> input
Just aComponent -> do
writeToXTA output aComponent
putStrLn "generation done"
|
pascalpoizat/veca-haskell
|
src/Lib.hs
|
apache-2.0
| 1,712 | 0 | 14 | 474 | 357 | 175 | 182 | 36 | 2 |
-----------------------------------------------------------------------------
--
-- | Parsing the top of a Haskell source file to get its module name,
-- imports and options.
--
-- (c) Simon Marlow 2005
-- (c) Lemmih 2006
--
-----------------------------------------------------------------------------
module Eta.Main.HeaderInfo ( getImports
, mkPrelImports -- used by the renamer too
, getOptionsFromFile, getOptions
, optionsErrorMsgs,
checkProcessArgsResult ) where
import Eta.BasicTypes.RdrName
import Eta.Main.HscTypes
import Eta.Parser.Parser ( parseHeader )
import Eta.Parser.Lexer
import Eta.Utils.FastString
import Eta.HsSyn.HsSyn
import Eta.BasicTypes.Module
import Eta.Prelude.PrelNames
import Eta.Utils.StringBuffer
import Eta.BasicTypes.SrcLoc
import Eta.Main.DynFlags
import Eta.Main.ErrUtils
import qualified Eta.Main.ErrUtils as ErrUtils
import Eta.Utils.Util
import Eta.Utils.Outputable
import qualified Eta.Utils.Outputable as Outputable
import Eta.Utils.Pretty ()
import Eta.Utils.Maybes
import Eta.Utils.Bag ( emptyBag, listToBag, unitBag )
import Eta.Utils.MonadUtils
import Eta.Utils.Exception
import qualified Eta.Utils.Exception as Exception
import qualified Eta.LanguageExtensions as LangExt
import Control.Monad
import System.IO
import System.IO.Unsafe
import Data.List
------------------------------------------------------------------------------
-- | Parse the imports of a source file.
--
-- Throws a 'SourceError' if parsing fails.
getImports :: DynFlags
-> StringBuffer -- ^ Parse this.
-> FilePath -- ^ Filename the buffer came from. Used for
-- reporting parse error locations.
-> FilePath -- ^ The original source filename (used for locations
-- in the function result)
-> IO ([(Maybe FastString, Located ModuleName)],
[(Maybe FastString, Located ModuleName)],
Located ModuleName)
-- ^ The source imports, normal imports, and the module name.
getImports dflags buf filename source_filename = do
let loc = mkRealSrcLoc (mkFastString filename) 1 1
case unP parseHeader (mkPState dflags buf loc) of
PFailed span err -> parseError dflags span err
POk pst rdr_module -> do
let _ms@(_warns, errs) = getMessages pst
-- don't log warnings: they'll be reported when we parse the file
-- for real. See #2500.
ms = (emptyBag, errs)
-- logWarnings warns
if errorsFound dflags ms
then throwIO $ mkSrcErr errs
else
case rdr_module of
L _ (HsModule mb_mod _ imps _ _ _) ->
let
main_loc = srcLocSpan (mkSrcLoc (mkFastString source_filename) 1 1)
mod = mb_mod `orElse` L main_loc mAIN_NAME
(src_idecls, ord_idecls) = partition (ideclIsSource.unLoc) imps
-- GHC.Prim doesn't exist physically, so don't go looking for it.
ordinary_imps = filter ((/= moduleName gHC_PRIM) . unLoc . ideclName . unLoc)
ord_idecls
implicit_prelude = xopt LangExt.ImplicitPrelude dflags
implicit_imports = mkPrelImports (unLoc mod) main_loc
implicit_prelude imps
in
return (ideclsSimplified src_idecls,
ideclsSimplified (implicit_imports ++ ordinary_imps),
mod)
mkPrelImports :: ModuleName
-> SrcSpan -- Attribute the "import Prelude" to this location
-> Bool -> [LImportDecl RdrName]
-> [LImportDecl RdrName]
-- Consruct the implicit declaration "import Prelude" (or not)
--
-- NB: opt_NoImplicitPrelude is slightly different to import Prelude ();
-- because the former doesn't even look at Prelude.hi for instance
-- declarations, whereas the latter does.
mkPrelImports this_mod loc implicit_prelude import_decls
| this_mod == pRELUDE_NAME
|| explicit_prelude_import
|| not implicit_prelude
= []
| otherwise = [preludeImportDecl]
where
explicit_prelude_import
= notNull [ () | L _ (ImportDecl { ideclName = mod
, ideclPkgQual = Nothing })
<- import_decls
, unLoc mod == pRELUDE_NAME ]
preludeImportDecl :: LImportDecl RdrName
preludeImportDecl
= L loc $ ImportDecl { ideclSourceSrc = Nothing,
ideclName = L loc pRELUDE_NAME,
ideclPkgQual = Nothing,
ideclSource = False,
ideclSafe = False, -- Not a safe import
ideclQualified = False,
ideclImplicit = True, -- Implicit!
ideclAs = Nothing,
ideclHiding = Nothing }
parseError :: DynFlags -> SrcSpan -> MsgDoc -> IO a
parseError dflags span err = throwOneError $ mkPlainErrMsg dflags span err
--------------------------------------------------------------
-- Get options
--------------------------------------------------------------
-- | Parse OPTIONS and LANGUAGE pragmas of the source file.
--
-- Throws a 'SourceError' if flag parsing fails (including unsupported flags.)
getOptionsFromFile :: DynFlags
-> FilePath -- ^ Input file
-> IO [Located String] -- ^ Parsed options, if any.
getOptionsFromFile dflags filename
= Exception.bracket
(openBinaryFile filename ReadMode)
(hClose)
(\handle -> do
opts <- fmap (getOptions' dflags)
(lazyGetToks dflags' filename handle)
seqList opts $ return opts)
where -- We don't need to get haddock doc tokens when we're just
-- getting the options from pragmas, and lazily lexing them
-- correctly is a little tricky: If there is "\n" or "\n-"
-- left at the end of a buffer then the haddock doc may
-- continue past the end of the buffer, despite the fact that
-- we already have an apparently-complete token.
-- We therefore just turn Opt_EtaDoc off when doing the lazy
-- lex.
dflags' = gopt_unset dflags Opt_EtaDoc
blockSize :: Int
-- blockSize = 17 -- for testing :-)
blockSize = 1024
lazyGetToks :: DynFlags -> FilePath -> Handle -> IO [Located Token]
lazyGetToks dflags filename handle = do
buf <- hGetStringBufferBlock handle blockSize
unsafeInterleaveIO $ lazyLexBuf handle (pragState dflags buf loc) False blockSize
where
loc = mkRealSrcLoc (mkFastString filename) 1 1
lazyLexBuf :: Handle -> PState -> Bool -> Int -> IO [Located Token]
lazyLexBuf handle state eof size = do
case unP (lexer False return) state of
POk state' t -> do
-- pprTrace "lazyLexBuf" (text (show (buffer state'))) (return ())
if atEnd (buffer state') && not eof
-- if this token reached the end of the buffer, and we haven't
-- necessarily read up to the end of the file, then the token might
-- be truncated, so read some more of the file and lex it again.
then getMore handle state size
else case t of
L _ ITeof -> return [t]
_other -> do rest <- lazyLexBuf handle state' eof size
return (t : rest)
_ | not eof -> getMore handle state size
| otherwise -> return [L (RealSrcSpan (last_loc state)) ITeof]
-- parser assumes an ITeof sentinel at the end
getMore :: Handle -> PState -> Int -> IO [Located Token]
getMore handle state size = do
-- pprTrace "getMore" (text (show (buffer state))) (return ())
let new_size = size * 2
-- double the buffer size each time we read a new block. This
-- counteracts the quadratic slowdown we otherwise get for very
-- large module names (#5981)
nextbuf <- hGetStringBufferBlock handle new_size
if (len nextbuf == 0) then lazyLexBuf handle state True new_size else do
newbuf <- appendStringBuffers (buffer state) nextbuf
unsafeInterleaveIO $ lazyLexBuf handle state{buffer=newbuf} False new_size
getToks :: DynFlags -> FilePath -> StringBuffer -> [Located Token]
getToks dflags filename buf = lexAll (pragState dflags buf loc)
where
loc = mkRealSrcLoc (mkFastString filename) 1 1
lexAll state = case unP (lexer False return) state of
POk _ t@(L _ ITeof) -> [t]
POk state' t -> t : lexAll state'
_ -> [L (RealSrcSpan (last_loc state)) ITeof]
-- | Parse OPTIONS and LANGUAGE pragmas of the source file.
--
-- Throws a 'SourceError' if flag parsing fails (including unsupported flags.)
getOptions :: DynFlags
-> StringBuffer -- ^ Input Buffer
-> FilePath -- ^ Source filename. Used for location info.
-> [Located String] -- ^ Parsed options.
getOptions dflags buf filename
= getOptions' dflags (getToks dflags filename buf)
-- The token parser is written manually because Happy can't
-- return a partial result when it encounters a lexer error.
-- We want to extract options before the buffer is passed through
-- CPP, so we can't use the same trick as 'getImports'.
getOptions' :: DynFlags
-> [Located Token] -- Input buffer
-> [Located String] -- Options.
getOptions' dflags toks
= parseToks toks
where
getToken (L _loc tok) = tok
getLoc (L loc _tok) = loc
parseToks (open:close:xs)
| IToptions_prag str <- getToken open
, ITclose_prag <- getToken close
= map (L (getLoc open)) (words str) ++
parseToks xs
parseToks (open:close:xs)
| ITinclude_prag str <- getToken open
, ITclose_prag <- getToken close
= map (L (getLoc open)) ["-#include",removeSpaces str] ++
parseToks xs
parseToks (open:close:xs)
| ITdocOptions str <- getToken open
, ITclose_prag <- getToken close
= map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
++ parseToks xs
parseToks (open:xs)
| ITdocOptionsOld str <- getToken open
= map (L (getLoc open)) ["-haddock-opts", removeSpaces str]
++ parseToks xs
parseToks (open:xs)
| ITlanguage_prag <- getToken open
= parseLanguage xs
parseToks _ = []
parseLanguage (L loc (ITconid fs):rest)
= checkExtension dflags (L loc fs) :
case rest of
(L _loc ITcomma):more -> parseLanguage more
(L _loc ITclose_prag):more -> parseToks more
(L loc _):_ -> languagePragParseError dflags loc
[] -> panic "getOptions'.parseLanguage(1) went past eof token"
parseLanguage (tok:_)
= languagePragParseError dflags (getLoc tok)
parseLanguage []
= panic "getOptions'.parseLanguage(2) went past eof token"
-----------------------------------------------------------------------------
-- | Complain about non-dynamic flags in OPTIONS pragmas.
--
-- Throws a 'SourceError' if the input list is non-empty claiming that the
-- input flags are unknown.
checkProcessArgsResult :: MonadIO m => DynFlags -> [Located String] -> m ()
checkProcessArgsResult dflags flags
= when (notNull flags) $
liftIO $ throwIO $ mkSrcErr $ listToBag $ map mkMsg flags
where mkMsg (L loc flag)
= mkPlainErrMsg dflags loc $
(text "unknown flag in {-# OPTIONS_GHC #-} pragma:" <+>
text flag)
-----------------------------------------------------------------------------
checkExtension :: DynFlags -> Located FastString -> Located String
checkExtension dflags (L l ext)
-- Checks if a given extension is valid, and if so returns
-- its corresponding flag. Otherwise it throws an exception.
= let ext' = unpackFS ext in
if ext' `elem` supportedLanguagesAndExtensions
then L l ("-X"++ext')
else unsupportedExtnError dflags l ext'
languagePragParseError :: DynFlags -> SrcSpan -> a
languagePragParseError dflags loc =
throw $ mkSrcErr $ unitBag $
(mkPlainErrMsg dflags loc $
vcat [ text "Cannot parse LANGUAGE pragma"
, text "Expecting comma-separated list of language options,"
, text "each starting with a capital letter"
, nest 2 (text "E.g. {-# LANGUAGE TemplateHaskell, GADTs #-}") ])
unsupportedExtnError :: DynFlags -> SrcSpan -> String -> a
unsupportedExtnError dflags loc unsup =
throw $ mkSrcErr $ unitBag $
mkPlainErrMsg dflags loc $
text "Unsupported extension: " <> text unsup $$
if null suggestions then Outputable.empty else text "Perhaps you meant" <+> quotedListWithOr (map text suggestions)
where
suggestions = fuzzyMatch unsup supportedLanguagesAndExtensions
optionsErrorMsgs :: DynFlags -> [String] -> [Located String] -> FilePath -> Messages
optionsErrorMsgs dflags unhandled_flags flags_lines _filename
= (emptyBag, listToBag (map mkMsg unhandled_flags_lines))
where unhandled_flags_lines = [ L l f | f <- unhandled_flags,
L l f' <- flags_lines, f == f' ]
mkMsg (L flagSpan flag) =
ErrUtils.mkPlainErrMsg dflags flagSpan $
text "unknown flag in {-# OPTIONS_GHC #-} pragma:" <+> text flag
|
rahulmutt/ghcvm
|
compiler/Eta/Main/HeaderInfo.hs
|
bsd-3-clause
| 13,931 | 0 | 26 | 4,204 | 2,842 | 1,476 | 1,366 | 219 | 11 |
module Handler.Unsubscribe where
import Import
import Model.Subscription
getUnsubscribeR :: Token -> Handler Html
getUnsubscribeR token = do
runDB $ do
subscription <- getBy404 $ UniqueSubscription token
unsubscribe $ entityKey subscription
defaultLayout $ do
setTitle "Unsubscribe"
$(widgetFile "unsubscribe")
|
thoughtbot/carnival
|
Handler/Unsubscribe.hs
|
mit
| 356 | 0 | 12 | 82 | 88 | 41 | 47 | 11 | 1 |
module BuckConverter where
import Tuura.Concept.STG
--ZC absent scenario definition using concepts
circuit uv oc zc gp gp_ack gn gn_ack =
chargeFunc <> uvFunc <> uvReact -- <> zcAbsent
where
interface = inputs [uv, oc, zc, gp_ack, gn_ack] <> outputs [gp, gn]
uvFunc = rise uv ~> rise gp <> rise uv ~> fall gn
ocFunc = rise oc ~> fall gp <> rise oc ~> rise gn
uvReact = rise gp_ack ~> fall uv <> fall gn_ack ~> fall uv
ocReact = fall gp_ack ~> fall oc <> rise gn_ack ~> fall oc
environmentConstraint = me uv oc
noShortcircuit = me gp gn <> fall gn_ack ~> rise gp <> fall gp_ack ~> rise gn
gpHandshake = handshake gp gp_ack
gnHandshake = handshake gn gn_ack
initialState = initialise0 [uv, oc, zc, gp, gp_ack] <> initialise1 [gn, gn_ack]
chargeFunc = interface <> ocFunc <> ocReact <> environmentConstraint <>
noShortcircuit <> gpHandshake <> gnHandshake <> initialState
-- zcAbsent = silent zc
|
tuura/concepts
|
examples/zcAbsent_scenario.hs
|
bsd-3-clause
| 979 | 0 | 13 | 245 | 332 | 168 | 164 | 16 | 1 |
test = foo . not . not
|
mpickering/hlint-refactor
|
tests/examples/Default88.hs
|
bsd-3-clause
| 22 | 1 | 6 | 6 | 18 | 7 | 11 | 1 | 1 |
module Text.Parsec.String.Char where
{-
Wrappers for the Text.Parsec.Char module with the types fixed to
'Text.Parsec.String.Parser a', i.e. the stream is String, no user
state, Identity monad.
-}
import qualified Text.Parsec.Char as C
import Text.Parsec.String (Parser)
spaces :: Parser ()
spaces = C.spaces
space :: Parser Char
space = C.space
newline :: Parser Char
newline = C.newline
tab :: Parser Char
tab = C.tab
upper :: Parser Char
upper = C.upper
lower :: Parser Char
lower = C.lower
alphaNum :: Parser Char
alphaNum = C.alphaNum
letter :: Parser Char
letter = C.letter
digit :: Parser Char
digit = C.digit
hexDigit :: Parser Char
hexDigit = C.hexDigit
octDigit :: Parser Char
octDigit = C.octDigit
char :: Char -> Parser Char
char = C.char
string :: String -> Parser String
string = C.string
anyChar :: Parser Char
anyChar = C.anyChar
oneOf :: [Char] -> Parser Char
oneOf = C.oneOf
noneOf :: [Char] -> Parser Char
noneOf = C.noneOf
satisfy :: (Char -> Bool) -> Parser Char
satisfy = C.satisfy
|
EliuX/AdHocParser
|
src/Text/Parsec/String/Char.hs
|
bsd-3-clause
| 1,025 | 0 | 7 | 187 | 319 | 176 | 143 | 37 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
module Data.Word(Word,Word8,Word16,Word32,Word64,WordMax,WordPtr) where
import Jhc.Type.Word
|
m-alvarez/jhc
|
lib/haskell-extras/Data/Word.hs
|
mit
| 129 | 0 | 4 | 10 | 36 | 24 | 12 | 3 | 0 |
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE helpset
PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN"
"http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="en-GB">
<title>ToDo-List</title>
<maps>
<homeID>todo</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/todo/src/main/javahelp/help/helpset.hs
|
apache-2.0
| 968 | 92 | 29 | 168 | 401 | 217 | 184 | -1 | -1 |
{-# OPTIONS_GHC -fplugin Simple.RemovePlugin #-}
{-# OPTIONS_GHC -fplugin-opt Simple.RemovePlugin:map #-}
{-# OPTIONS_GHC -fplugin-opt Simple.RemovePlugin:interface #-}
module A where
-- test if a definition can be removed from loaded interface
map :: ()
map = ()
x :: ()
x = map
|
sdiehl/ghc
|
testsuite/tests/plugins/plugins14.hs
|
bsd-3-clause
| 282 | 0 | 5 | 43 | 34 | 22 | 12 | 8 | 1 |
module Yesod.Form.Generic.Bootstrap.Internal where
import Yesod.Core
data MarkdownRender = MarkdownRender
mkYesodSubData "MarkdownRender" [parseRoutes|
/markdown/render MarkdownRenderR POST
|]
|
andrewthad/yesod-bootstrap
|
src/Yesod/Form/Generic/Bootstrap/Internal.hs
|
mit
| 196 | 0 | 5 | 19 | 33 | 21 | 12 | -1 | -1 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Show (
Print(..),
putText,
putLText,
) where
import Prelude ((.), Char, IO)
import qualified Prelude
import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.IO as TL
class Print a where
putStr :: MonadIO m => a -> m ()
putStrLn :: MonadIO m => a -> m ()
instance Print T.Text where
putStr = liftIO . T.putStr
putStrLn = liftIO . T.putStrLn
instance Print TL.Text where
putStr = liftIO . TL.putStr
putStrLn = liftIO . TL.putStrLn
instance Print BS.ByteString where
putStr = liftIO . BS.putStr
putStrLn = liftIO . BS.putStrLn
instance Print BL.ByteString where
putStr = liftIO . BL.putStr
putStrLn = liftIO . BL.putStrLn
instance Print [Char] where
putStr = liftIO . Prelude.putStr
putStrLn = liftIO . Prelude.putStrLn
-- For forcing type inference
putText :: MonadIO m => T.Text -> m ()
putText = putStrLn
{-# SPECIALIZE putText :: T.Text -> IO () #-}
putLText :: MonadIO m => TL.Text -> m ()
putLText = putStrLn
{-# SPECIALIZE putLText :: TL.Text -> IO () #-}
|
ardfard/protolude
|
src/Show.hs
|
mit
| 1,398 | 0 | 10 | 252 | 386 | 227 | 159 | 42 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- WARNING!!!
-- To work with this example download some .mrc sample
-- It's easy to find one in the internet. I'll attach a link here.
import qualified Data.ByteString as B
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import qualified Data.Text.Encoding as E
import Data.Maybe
type Author = T.Text
type Title = T.Text
type Html = T.Text
-- MARC format types
type MarcRecordRaw = B.ByteString
type MarcLeaderRaw = B.ByteString
type MarcDirectoryRaw = B.ByteString
data Book = Book
{ author :: Author
, title :: Title
} deriving Show
-- MARC parsing
leaderLength :: Int
leaderLength = 24
getLeader :: MarcRecordRaw -> MarcLeaderRaw
getLeader record = B.take leaderLength record
getRecordLength :: MarcLeaderRaw -> Int
getRecordLength leader = rawToInt (B.take 5 leader)
nextAndRest :: B.ByteString -> (MarcRecordRaw, B.ByteString)
nextAndRest marcStream = B.splitAt recordLength marcStream
where recordLength = getRecordLength marcStream
allRecords :: B.ByteString -> [MarcRecordRaw]
allRecords marcStream = if marcStream == B.empty
then []
else next : allRecords rest
where (next, rest) = nextAndRest marcStream
-- Determine the size of a directory
getBaseAddress :: MarcLeaderRaw -> Int
getBaseAddress leader = rawToInt (B.take 5 remainder)
where remainder = B.drop 12 leader
getDirectoryLength :: MarcLeaderRaw -> Int
getDirectoryLength leader = getBaseAddress leader - (leaderLength - 1)
getDirectory :: MarcRecordRaw -> MarcDirectoryRaw
getDirectory record = B.take directoryLength afterLeader
where directoryLength = getDirectoryLength record
afterLeader = B.drop leaderLength record
-- Helper functions
rawToInt :: B.ByteString -> Int
rawToInt = read . T.unpack . E.decodeUtf8
-- page 327 typo
booksToHtml :: [Book] -> Html
booksToHtml books = mconcat [ "<html>\n"
, "<head><title>books</title>"
, "<meta charset='utf-8'/>"
, "</head>\n" -- typo is here
, "<body>\n"
, booksHtml
, "\n</body>\n"
, "</html>"]
where booksHtml = (mconcat . (map bookToHtml)) books
bookToHtml :: Book -> Html
bookToHtml book = mconcat [ "<p>\n"
, titleInTags
, authorInTags
, "</p>\n"]
where titleInTags = mconcat ["<strong>", (title book), "</strong>\n"]
authorInTags = mconcat ["<em>", (author book), "</em>\n"]
-- Test data
book1 :: Book
book1 = Book {
title = "The Conspiracy Against the Human Race"
, author = "Ligotti, Thomas"
}
book2 :: Book
book2 = Book {
title = "A short story of Haskell"
, author = "Brant, Kyle"
}
book3 :: Book
book3 = Book {
title = "Coq cookbook"
, author = "Ante, Julian"
}
myBooks :: [Book]
myBooks = [book1, book2, book3]
-- Test data END
main :: IO ()
main = do
marcData <- B.readFile "sample.mrc"
let marcRecords = allRecords marcData
print (length marcRecords)
|
raventid/coursera_learning
|
haskell/will_kurt/capstone_mark_to_html.hs
|
mit
| 3,167 | 0 | 11 | 835 | 738 | 418 | 320 | 77 | 2 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE RecordWildCards #-}
module Control.Concurrent.TaskMan
( Action
, Task
, TaskManState(_active, _finished)
, TaskMan
, TaskMap
, askId
, setPhase
, setTotalWork
, setDoneWork
, newTaskMan
, start
, getActiveTasks
, getFinishedInfos
, getAllInfos
, cancel
, getInfo
) where
import Control.Concurrent.TaskMan.Task.Info as I hiding (_initial)
import Control.Concurrent
import Control.Concurrent.STM
import Data.Either.Combinators (fromLeft')
import Data.Map (Map, empty, insert, delete, union, (!))
import Data.Traversable (sequence)
import Control.Monad.Reader
import Data.Time (getCurrentTime)
import Control.Exception (AsyncException(..), Handler(..), catches, throw, displayException)
data Params = Params
{ _initial :: Initial
, _currentV :: TVar Current
}
type ActionTo a = ReaderT Params IO a
type Action = ActionTo ()
data Task = Task
{ _threadId :: ThreadId
, _params :: Params
}
type TaskMap = Map TaskId Task
data TaskManState = TaskManState
{ _nextId :: TaskId
, _active :: TaskMap
, _finished :: InfoMap
}
newtype TaskMan = TaskMan { _stateM :: MVar TaskManState }
-- Exports
askId :: ActionTo TaskId
askId = asks (_taskId . (_initial :: Params -> Initial))
setPhase :: String -> ActionTo ()
setPhase s = modifyProgress (\p -> p { _phase = s })
setTotalWork :: Int -> ActionTo ()
setTotalWork x = modifyProgress (\p -> p { _totalWork = x})
setDoneWork :: Int -> ActionTo ()
setDoneWork x = modifyProgress (\p -> p { _doneWork = x})
newTaskMan :: IO TaskMan
newTaskMan = fmap TaskMan (newMVar $ TaskManState 0 empty empty)
start :: TaskMan -> Action -> String -> IO Task
start taskMan action title = do
let stateM = _stateM taskMan
state <- takeMVar stateM
let taskId = _nextId state
now <- getCurrentTime
let initial = Initial
{ _taskId = taskId
, _title = if null title then "Action #" ++ show taskId else title
, _started = now
}
let progress = Progress
{ _phase = "In progress"
, _totalWork = 0
, _doneWork = 0
}
currentV <- newTVarIO $ Left progress
let params = Params
{ _initial = initial
, _currentV = currentV
}
threadId <- forkIO $ runTask action params stateM
let descriptor = Task threadId params
let state' = state
{ _nextId = taskId + 1
, _active = insert taskId descriptor (_active state)
}
putMVar stateM state'
return descriptor
getActiveTasks :: TaskMan -> IO TaskMap
getActiveTasks = fmap _active . getState
getFinishedInfos :: TaskMan -> IO InfoMap
getFinishedInfos = fmap _finished . getState
getAllInfos :: TaskMan -> IO InfoMap
getAllInfos taskMan = do
state <- getState taskMan
active <- atomically $ sequence $ fmap getInfoSTM $ _active state
let finished = _finished state
return $ union active finished
cancel :: Task -> IO ()
cancel (Task{..}) = throwTo _threadId ThreadKilled
getInfo :: Task -> IO Info
getInfo = atomically . getInfoSTM
-- Internals
askCurrentV :: ActionTo (TVar Current)
askCurrentV = asks _currentV
getState :: TaskMan -> IO TaskManState
getState = readMVar . _stateM
modifyProgress :: (Progress -> Progress) -> ActionTo ()
modifyProgress f = do
c <- askCurrentV
lift $ atomically $ modifyTVar' c (Left . f . fromLeft')
runTask :: Action -> Params -> MVar TaskManState -> IO ()
runTask action params stateM =
catches ((runReaderT action params) >> onDone) (map Handler [onCanceled, onFailure]) where
onDone = signal Done
onCanceled e = if e == ThreadKilled then signal Canceled else throw e
onFailure e = signal $ Failure (displayException e)
signal status = onFinish taskId status stateM
taskId = _taskId $ _initial $ params
onFinish :: TaskId -> Status -> MVar TaskManState -> IO ()
onFinish taskId status stateM = do
state <- takeMVar stateM
now <- getCurrentTime
let descriptor = (_active state) ! taskId
let params = _params descriptor
let currentV = _currentV params
current <- readTVarIO currentV
let progress = fromLeft' current
let final = Final
{ _ended = now
, _status = status
, _work = _doneWork progress
}
let current' = Right final
atomically $ writeTVar currentV current'
let active' = delete taskId $ _active state
let initial = _initial params
let finished' = insert taskId (Info initial current') $ _finished state
let state' = state
{ _active = active'
, _finished = finished'
}
putMVar stateM state'
getInfoSTM :: Task -> STM Info
getInfoSTM task = do
let Params initial currentV = _params task
current <- readTVar currentV
return $ Info initial current
|
vadimvinnik/taskman-hs
|
src/Control/Concurrent/TaskMan.hs
|
mit
| 4,813 | 0 | 14 | 1,115 | 1,545 | 805 | 740 | 138 | 2 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SQLTransactionErrorCallback
(newSQLTransactionErrorCallback,
newSQLTransactionErrorCallbackSync,
newSQLTransactionErrorCallbackAsync, SQLTransactionErrorCallback)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation>
newSQLTransactionErrorCallback ::
(MonadIO m) =>
(Maybe SQLError -> IO ()) -> m SQLTransactionErrorCallback
newSQLTransactionErrorCallback callback
= liftIO
(SQLTransactionErrorCallback <$>
syncCallback1 ThrowWouldBlock
(\ error ->
fromJSValUnchecked error >>= \ error' -> callback error'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation>
newSQLTransactionErrorCallbackSync ::
(MonadIO m) =>
(Maybe SQLError -> IO ()) -> m SQLTransactionErrorCallback
newSQLTransactionErrorCallbackSync callback
= liftIO
(SQLTransactionErrorCallback <$>
syncCallback1 ContinueAsync
(\ error ->
fromJSValUnchecked error >>= \ error' -> callback error'))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SQLTransactionErrorCallback Mozilla SQLTransactionErrorCallback documentation>
newSQLTransactionErrorCallbackAsync ::
(MonadIO m) =>
(Maybe SQLError -> IO ()) -> m SQLTransactionErrorCallback
newSQLTransactionErrorCallbackAsync callback
= liftIO
(SQLTransactionErrorCallback <$>
asyncCallback1
(\ error ->
fromJSValUnchecked error >>= \ error' -> callback error'))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SQLTransactionErrorCallback.hs
|
mit
| 2,671 | 0 | 13 | 565 | 532 | 316 | 216 | 46 | 1 |
module B9.Shake.SharedImageRulesSpec
( spec,
)
where
import B9.Artifact.Readable
import B9.Artifact.Readable.Interpreter (assemble)
import B9.B9Config
import B9.B9Monad
import B9.DiskImages
import B9.Repository
import B9.RepositoryIO
import B9.Shake.SharedImageRules
import B9.Vm
import Control.Exception
import Control.Monad
import qualified Data.Set as Set
import Development.Shake as Shake
import System.Directory
import System.Environment
import System.FilePath
import System.IO.B9Extras
import Test.Hspec
import Text.Printf
testShakeBuild :: B9ConfigOverride -> IO ()
testShakeBuild cfg = shake shakeOptions $ do
enableSharedImageRules cfg
customSharedImageAction (SharedImageName "test") $
liftIO
( b9Build
cfg
( void
( assemble
( Artifact
(IID "test-image")
( VmImages
[ ImageTarget
(Share "test" Raw KeepSize)
(EmptyImage "test" Ext4 Raw (ImageSize 10 MB))
NotMounted
]
NoVmScript
)
)
)
)
)
action (needSharedImage (SharedImageName "test"))
spec :: HasCallStack => Spec
spec = do
context "missing shared image" $ do
it "builds a missing image" $ do
withTempBuildDirs $ \cfg -> do
testShakeBuild cfg
actualImages <- b9Build cfg (allCachedSharedImages <$> getSharedImages)
Set.size actualImages `shouldBe` 1
b9Build :: HasCallStack => B9ConfigOverride -> B9 a -> IO a
b9Build cfg effect =
runB9ConfigActionWithOverrides
(runB9 effect)
cfg
withTempBuildDirs :: HasCallStack => (B9ConfigOverride -> IO a) -> IO a
withTempBuildDirs k =
bracket acquire release use
where
acquire = do
nixOutDirEnv <- lookupEnv "NIX_BUILD_TOP"
let rootDir = maybe InTempDir (((.) . (.)) Path (</>)) nixOutDirEnv
repoRelPath <- printf "testsRepositoryIOSpec-test-repo-%U" <$> randomUUID
buildRelPath <- printf "RepositoryIOSpec-root-%U" <$> randomUUID
cfgRelPath <- printf "RepositoryIOSpec-b9cfg-%U" <$> randomUUID
let tmpRepoPath = rootDir ("tests" </> repoRelPath)
tmpBuildPath = rootDir ("tests" </> buildRelPath)
tmpCfgPath = rootDir ("tests" </> cfgRelPath)
ensureSystemPath tmpRepoPath
ensureSystemPath tmpBuildPath
tmpBuildPathFileName <- resolve tmpBuildPath
return (tmpRepoPath, tmpBuildPathFileName, tmpCfgPath)
release (tmpRepoPath, tmpBuildPathFileName, tmpCfgPath) = do
let cleanupTmpPath = removePathForcibly <=< resolve
cleanupTmpPath tmpRepoPath
cleanupTmpPath tmpCfgPath
removePathForcibly tmpBuildPathFileName
use (tmpRepoPath, tmpBuildPathFileName, tmpCfgPath) =
let mkCfg cfgIn =
cfgIn
{ _repositoryCache = Just tmpRepoPath,
_projectRoot = Just tmpBuildPathFileName
}
oCfg =
overrideB9Config
mkCfg
( overrideWorkingDirectory
tmpBuildPathFileName
( overrideDefaultB9ConfigPath
tmpCfgPath
noB9ConfigOverride
)
)
in k oCfg
|
sheyll/b9-vm-image-builder
|
src/tests/B9/Shake/SharedImageRulesSpec.hs
|
mit
| 3,380 | 0 | 25 | 1,062 | 760 | 384 | 376 | -1 | -1 |
-- Problems/Problem032.hs
module Problems.Problem032 (p32) where
import Data.List
import Data.Maybe
main = print p32
p32 :: Int
p32 = sum . nub $ [x*y | x <- [1..99], y <- [1..9999], isPandigit x y]
isPandigit :: Int -> Int -> Bool
isPandigit m n = (=="123456789") $ sort $ show m ++ show n ++ show (m*n)
|
Sgoettschkes/learning
|
haskell/ProjectEuler/src/Problems/Problem032.hs
|
mit
| 309 | 0 | 9 | 61 | 149 | 80 | 69 | 8 | 1 |
module Game.Disc where
import Data.Map
import qualified Data.Map as Map
import Data.Text
import Game.Util
import Graphics.Blank
data Disc = White | Black deriving (Show, Eq, Ord)
-- | Swaps the turn
swap :: Disc -> Disc
swap White = Black
swap Black = White
isBlack = (== Black)
isWhite = not . isBlack
-- | Draws the disc in the appropriate position
drawDisc :: Double -> Disc -> Canvas ()
drawDisc radius disc = do
beginPath()
arc(0, 0, radius, 0, 2 * pi, False)
fillStyle $ pack $ clr disc
fill()
lineWidth 5
strokeStyle $ pack $ clr disc
stroke()
-- | Returns the color of the disk
clr :: Disc -> String
clr Black = "#000000"
clr White = "#ffffff"
drawDiscs sz board =
sequence_ [ do save()
translate (sz / 2
+ (1.8 * sz / 9)
+ fromIntegral x * (sz / 9)
, sz / 2
-- + (0.5 * sz/9)
+ fromIntegral y * (sz / 9))
case Map.lookup (x,y) board of
Just d -> drawDisc (sz / 32) d
Nothing -> return ()
restore()
| x <- [minX..maxX::Int]
, y <- [minY..maxY::Int]
]
|
apoorvingle/h-reversi
|
src/Game/Disc.hs
|
mit
| 1,338 | 0 | 16 | 568 | 432 | 223 | 209 | 37 | 2 |
{-# LANGUAGE QuasiQuotes, TypeFamilies #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE Rank2Types #-}
-- | A Yesod plugin for Authentication via e-mail
--
-- This plugin works out of the box by only setting a few methods on the type class
-- that tell the plugin how to interoprate with your user data storage (your database).
-- However, almost everything is customizeable by setting more methods on the type class.
-- In addition, you can send all the form submissions via JSON and completely control the user's flow.
-- This is a standard registration e-mail flow
--
-- 1) A user registers a new e-mail address, and an e-mail is sent there
-- 2) The user clicks on the registration link in the e-mail
-- Note that at this point they are actually logged in (without a password)
-- That means that when they log out they will need to reset their password
-- 3) The user sets their password and is redirected to the site.
-- 4) The user can now
-- * logout and sign in
-- * reset their password
module Yesod.Auth.Email
( -- * Plugin
authEmail
, YesodAuthEmail (..)
, EmailCreds (..)
, saltPass
-- * Routes
, loginR
, registerR
, forgotPasswordR
, setpassR
, verifyR
, isValidPass
-- * Types
, Email
, VerKey
, VerUrl
, SaltedPass
, VerStatus
, Identifier
-- * Misc
, loginLinkKey
, setLoginLinkKey
-- * Default handlers
, defaultRegisterHandler
, defaultForgotPasswordHandler
, defaultSetPasswordHandler
) where
import Network.Mail.Mime (randomString)
import Yesod.Auth
import System.Random
import qualified Data.Text as TS
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Crypto.Hash.MD5 as H
import Data.ByteString.Base16 as B16
import Data.Text.Encoding (encodeUtf8, decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Data.Text (Text)
import Yesod.Core
import qualified Yesod.PasswordStore as PS
import qualified Text.Email.Validate
import qualified Yesod.Auth.Message as Msg
import Control.Applicative ((<$>), (<*>))
import Control.Monad (void)
import Yesod.Form
import Data.Time (getCurrentTime, addUTCTime)
import Safe (readMay)
loginR, registerR, forgotPasswordR, setpassR :: AuthRoute
loginR = PluginR "email" ["login"]
registerR = PluginR "email" ["register"]
forgotPasswordR = PluginR "email" ["forgot-password"]
setpassR = PluginR "email" ["set-password"]
-- |
--
-- Since 1.4.5
verifyR :: Text -> Text -> AuthRoute -- FIXME
verifyR eid verkey = PluginR "email" ["verify", eid, verkey]
type Email = Text
type VerKey = Text
type VerUrl = Text
type SaltedPass = Text
type VerStatus = Bool
-- | An Identifier generalizes an email address to allow users to log in with
-- some other form of credentials (e.g., username).
--
-- Note that any of these other identifiers must not be valid email addresses.
--
-- Since 1.2.0
type Identifier = Text
-- | Data stored in a database for each e-mail address.
data EmailCreds site = EmailCreds
{ emailCredsId :: AuthEmailId site
, emailCredsAuthId :: Maybe (AuthId site)
, emailCredsStatus :: VerStatus
, emailCredsVerkey :: Maybe VerKey
, emailCredsEmail :: Email
}
class ( YesodAuth site
, PathPiece (AuthEmailId site)
, (RenderMessage site Msg.AuthMessage)
)
=> YesodAuthEmail site where
type AuthEmailId site
-- | Add a new email address to the database, but indicate that the address
-- has not yet been verified.
--
-- Since 1.1.0
addUnverified :: Email -> VerKey -> HandlerT site IO (AuthEmailId site)
-- | Send an email to the given address to verify ownership.
--
-- Since 1.1.0
sendVerifyEmail :: Email -> VerKey -> VerUrl -> HandlerT site IO ()
-- | Get the verification key for the given email ID.
--
-- Since 1.1.0
getVerifyKey :: AuthEmailId site -> HandlerT site IO (Maybe VerKey)
-- | Set the verification key for the given email ID.
--
-- Since 1.1.0
setVerifyKey :: AuthEmailId site -> VerKey -> HandlerT site IO ()
-- | Verify the email address on the given account.
--
-- Since 1.1.0
verifyAccount :: AuthEmailId site -> HandlerT site IO (Maybe (AuthId site))
-- | Get the salted password for the given account.
--
-- Since 1.1.0
getPassword :: AuthId site -> HandlerT site IO (Maybe SaltedPass)
-- | Set the salted password for the given account.
--
-- Since 1.1.0
setPassword :: AuthId site -> SaltedPass -> HandlerT site IO ()
-- | Get the credentials for the given @Identifier@, which may be either an
-- email address or some other identification (e.g., username).
--
-- Since 1.2.0
getEmailCreds :: Identifier -> HandlerT site IO (Maybe (EmailCreds site))
-- | Get the email address for the given email ID.
--
-- Since 1.1.0
getEmail :: AuthEmailId site -> HandlerT site IO (Maybe Email)
-- | Generate a random alphanumeric string.
--
-- Since 1.1.0
randomKey :: site -> IO Text
randomKey _ = do
stdgen <- newStdGen
return $ TS.pack $ fst $ randomString 10 stdgen
-- | Route to send user to after password has been set correctly.
--
-- Since 1.2.0
afterPasswordRoute :: site -> Route site
-- | Does the user need to provide the current password in order to set a
-- new password?
--
-- Default: if the user logged in via an email link do not require a password.
--
-- Since 1.2.1
needOldPassword :: AuthId site -> HandlerT site IO Bool
needOldPassword aid' = do
mkey <- lookupSession loginLinkKey
case mkey >>= readMay . TS.unpack of
Just (aidT, time) | Just aid <- fromPathPiece aidT, toPathPiece (aid `asTypeOf` aid') == toPathPiece aid' -> do
now <- liftIO getCurrentTime
return $ addUTCTime (60 * 30) time <= now
_ -> return True
-- | Check that the given plain-text password meets minimum security standards.
--
-- Default: password is at least three characters.
checkPasswordSecurity :: AuthId site -> Text -> HandlerT site IO (Either Text ())
checkPasswordSecurity _ x
| TS.length x >= 3 = return $ Right ()
| otherwise = return $ Left "Password must be at least three characters"
-- | Response after sending a confirmation email.
--
-- Since 1.2.2
confirmationEmailSentResponse :: Text -> HandlerT site IO TypedContent
confirmationEmailSentResponse identifier = do
mr <- getMessageRender
selectRep $ do
provideJsonMessage (mr msg)
provideRep $ authLayout $ do
setTitleI Msg.ConfirmationEmailSentTitle
[whamlet|<p>_{msg}|]
where
msg = Msg.ConfirmationEmailSent identifier
-- | Additional normalization of email addresses, besides standard canonicalization.
--
-- Default: Lower case the email address.
--
-- Since 1.2.3
normalizeEmailAddress :: site -> Text -> Text
normalizeEmailAddress _ = TS.toLower
-- | Handler called to render the registration page. The
-- default works fine, but you may want to override it in
-- order to have a different DOM.
--
-- Default: 'defaultRegisterHandler'.
--
-- Since: 1.2.6.
registerHandler :: AuthHandler site Html
registerHandler = defaultRegisterHandler
-- | Handler called to render the \"forgot password\" page.
-- The default works fine, but you may want to override it in
-- order to have a different DOM.
--
-- Default: 'defaultForgotPasswordHandler'.
--
-- Since: 1.2.6.
forgotPasswordHandler :: AuthHandler site Html
forgotPasswordHandler = defaultForgotPasswordHandler
-- | Handler called to render the \"set password\" page. The
-- default works fine, but you may want to override it in
-- order to have a different DOM.
--
-- Default: 'defaultSetPasswordHandler'.
--
-- Since: 1.2.6.
setPasswordHandler ::
Bool
-- ^ Whether the old password is needed. If @True@, a
-- field for the old password should be presented.
-- Otherwise, just two fields for the new password are
-- needed.
-> AuthHandler site TypedContent
setPasswordHandler = defaultSetPasswordHandler
authEmail :: YesodAuthEmail m => AuthPlugin m
authEmail =
AuthPlugin "email" dispatch $ \tm ->
[whamlet|
$newline never
<form method="post" action="@{tm loginR}">
<table>
<tr>
<th>_{Msg.Email}
<td>
<input type="email" name="email" required>
<tr>
<th>_{Msg.Password}
<td>
<input type="password" name="password" required>
<tr>
<td colspan="2">
<button type=submit .btn .btn-success>
_{Msg.LoginViaEmail}
<a href="@{tm registerR}" .btn .btn-default>
_{Msg.RegisterLong}
|]
where
dispatch "GET" ["register"] = getRegisterR >>= sendResponse
dispatch "POST" ["register"] = postRegisterR >>= sendResponse
dispatch "GET" ["forgot-password"] = getForgotPasswordR >>= sendResponse
dispatch "POST" ["forgot-password"] = postForgotPasswordR >>= sendResponse
dispatch "GET" ["verify", eid, verkey] =
case fromPathPiece eid of
Nothing -> notFound
Just eid' -> getVerifyR eid' verkey >>= sendResponse
dispatch "POST" ["login"] = postLoginR >>= sendResponse
dispatch "GET" ["set-password"] = getPasswordR >>= sendResponse
dispatch "POST" ["set-password"] = postPasswordR >>= sendResponse
dispatch _ _ = notFound
getRegisterR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) Html
getRegisterR = registerHandler
-- | Default implementation of 'registerHandler'.
--
-- Since: 1.2.6
defaultRegisterHandler :: YesodAuthEmail master => AuthHandler master Html
defaultRegisterHandler = do
email <- newIdent
tp <- getRouteToParent
lift $ authLayout $ do
setTitleI Msg.RegisterLong
[whamlet|
<p>_{Msg.EnterEmail}
<form method="post" action="@{tp registerR}">
<div id="registerForm">
<label for=#{email}>_{Msg.Email}:
<input ##{email} type="email" name="email" width="150" autofocus>
<button .btn>_{Msg.Register}
|]
registerHelper :: YesodAuthEmail master
=> Bool -- ^ allow usernames?
-> Route Auth
-> HandlerT Auth (HandlerT master IO) TypedContent
registerHelper allowUsername dest = do
y <- lift getYesod
midentifier <- lookupPostParam "email"
let eidentifier = case midentifier of
Nothing -> Left Msg.NoIdentifierProvided
Just x
| Just x' <- Text.Email.Validate.canonicalizeEmail (encodeUtf8 x) ->
Right $ normalizeEmailAddress y $ decodeUtf8With lenientDecode x'
| allowUsername -> Right $ TS.strip x
| otherwise -> Left Msg.InvalidEmailAddress
case eidentifier of
Left route -> loginErrorMessageI dest route
Right identifier -> do
mecreds <- lift $ getEmailCreds identifier
registerCreds <-
case mecreds of
Just (EmailCreds lid _ _ (Just key) email) -> return $ Just (lid, key, email)
Just (EmailCreds lid _ _ Nothing email) -> do
key <- liftIO $ randomKey y
lift $ setVerifyKey lid key
return $ Just (lid, key, email)
Nothing
| allowUsername -> return Nothing
| otherwise -> do
key <- liftIO $ randomKey y
lid <- lift $ addUnverified identifier key
return $ Just (lid, key, identifier)
case registerCreds of
Nothing -> loginErrorMessageI dest (Msg.IdentifierNotFound identifier)
Just (lid, verKey, email) -> do
render <- getUrlRender
let verUrl = render $ verifyR (toPathPiece lid) verKey
lift $ sendVerifyEmail email verKey verUrl
lift $ confirmationEmailSentResponse identifier
postRegisterR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) TypedContent
postRegisterR = registerHelper False registerR
getForgotPasswordR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) Html
getForgotPasswordR = forgotPasswordHandler
-- | Default implementation of 'forgotPasswordHandler'.
--
-- Since: 1.2.6
defaultForgotPasswordHandler :: YesodAuthEmail master => AuthHandler master Html
defaultForgotPasswordHandler = do
tp <- getRouteToParent
email <- newIdent
lift $ authLayout $ do
setTitleI Msg.PasswordResetTitle
[whamlet|
<p>_{Msg.PasswordResetPrompt}
<form method="post" action="@{tp forgotPasswordR}">
<div id="registerForm">
<label for=#{email}>_{Msg.ProvideIdentifier}
<input ##{email} type=text name="email" width="150" autofocus>
<button .btn>_{Msg.SendPasswordResetEmail}
|]
postForgotPasswordR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) TypedContent
postForgotPasswordR = registerHelper True forgotPasswordR
getVerifyR :: YesodAuthEmail site
=> AuthEmailId site
-> Text
-> HandlerT Auth (HandlerT site IO) TypedContent
getVerifyR lid key = do
realKey <- lift $ getVerifyKey lid
memail <- lift $ getEmail lid
mr <- lift getMessageRender
case (realKey == Just key, memail) of
(True, Just email) -> do
muid <- lift $ verifyAccount lid
case muid of
Nothing -> invalidKey mr
Just uid -> do
lift $ setCreds False $ Creds "email-verify" email [("verifiedEmail", email)] -- FIXME uid?
lift $ setLoginLinkKey uid
let msgAv = Msg.AddressVerified
selectRep $ do
provideRep $ do
lift $ setMessageI msgAv
fmap asHtml $ redirect setpassR
provideJsonMessage $ mr msgAv
_ -> invalidKey mr
where
msgIk = Msg.InvalidKey
invalidKey mr = messageJson401 (mr msgIk) $ lift $ authLayout $ do
setTitleI msgIk
[whamlet|
$newline never
<p>_{msgIk}
|]
postLoginR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) TypedContent
postLoginR = do
(identifier, pass) <- lift $ runInputPost $ (,)
<$> ireq textField "email"
<*> ireq textField "password"
mecreds <- lift $ getEmailCreds identifier
maid <-
case ( mecreds >>= emailCredsAuthId
, emailCredsEmail <$> mecreds
, emailCredsStatus <$> mecreds
) of
(Just aid, Just email, Just True) -> do
mrealpass <- lift $ getPassword aid
case mrealpass of
Nothing -> return Nothing
Just realpass -> return $
if isValidPass pass realpass
then Just email
else Nothing
_ -> return Nothing
let isEmail = Text.Email.Validate.isValid $ encodeUtf8 identifier
case maid of
Just email ->
lift $ setCredsRedirect $ Creds
(if isEmail then "email" else "username")
email
[("verifiedEmail", email)]
Nothing ->
loginErrorMessageI LoginR $
if isEmail
then Msg.InvalidEmailPass
else Msg.InvalidUsernamePass
getPasswordR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) TypedContent
getPasswordR = do
maid <- lift maybeAuthId
case maid of
Nothing -> loginErrorMessageI LoginR Msg.BadSetPass
Just _ -> do
needOld <- maybe (return True) (lift . needOldPassword) maid
setPasswordHandler needOld
-- | Default implementation of 'setPasswordHandler'.
--
-- Since: 1.2.6
defaultSetPasswordHandler :: YesodAuthEmail master => Bool -> AuthHandler master TypedContent
defaultSetPasswordHandler needOld = do
tp <- getRouteToParent
pass0 <- newIdent
pass1 <- newIdent
pass2 <- newIdent
mr <- lift getMessageRender
selectRep $ do
provideJsonMessage $ mr Msg.SetPass
provideRep $ lift $ authLayout $ do
setTitleI Msg.SetPassTitle
[whamlet|
$newline never
<h3>_{Msg.SetPass}
<form method="post" action="@{tp setpassR}">
<table>
$if needOld
<tr>
<th>
<label for=#{pass0}>Current Password
<td>
<input ##{pass0} type="password" name="current" autofocus>
<tr>
<th>
<label for=#{pass1}>_{Msg.NewPass}
<td>
<input ##{pass1} type="password" name="new" :not needOld:autofocus>
<tr>
<th>
<label for=#{pass2}>_{Msg.ConfirmPass}
<td>
<input ##{pass2} type="password" name="confirm">
<tr>
<td colspan="2">
<input type="submit" value=_{Msg.SetPassTitle}>
|]
postPasswordR :: YesodAuthEmail master => HandlerT Auth (HandlerT master IO) TypedContent
postPasswordR = do
maid <- lift maybeAuthId
case maid of
Nothing -> loginErrorMessageI LoginR Msg.BadSetPass
Just aid -> do
tm <- getRouteToParent
needOld <- lift $ needOldPassword aid
if not needOld then confirmPassword aid tm else do
current <- lift $ runInputPost $ ireq textField "current"
mrealpass <- lift $ getPassword aid
case mrealpass of
Nothing ->
lift $ loginErrorMessage (tm setpassR) "You do not currently have a password set on your account"
Just realpass
| isValidPass current realpass -> confirmPassword aid tm
| otherwise ->
lift $ loginErrorMessage (tm setpassR) "Invalid current password, please try again"
where
msgOk = Msg.PassUpdated
confirmPassword aid tm = do
(new, confirm) <- lift $ runInputPost $ (,)
<$> ireq textField "new"
<*> ireq textField "confirm"
if new /= confirm
then loginErrorMessageI setpassR Msg.PassMismatch
else do
isSecure <- lift $ checkPasswordSecurity aid new
case isSecure of
Left e -> lift $ loginErrorMessage (tm setpassR) e
Right () -> do
salted <- liftIO $ saltPass new
y <- lift $ do
setPassword aid salted
deleteSession loginLinkKey
setMessageI msgOk
getYesod
mr <- lift getMessageRender
selectRep $ do
provideRep $
fmap asHtml $ lift $ redirect $ afterPasswordRoute y
provideJsonMessage (mr msgOk)
saltLength :: Int
saltLength = 5
-- | Salt a password with a randomly generated salt.
saltPass :: Text -> IO Text
saltPass = fmap (decodeUtf8With lenientDecode)
. flip PS.makePassword 14
. encodeUtf8
saltPass' :: String -> String -> String
saltPass' salt pass =
salt ++ T.unpack (TE.decodeUtf8 $ B16.encode $ H.hash $ TE.encodeUtf8 $ T.pack $ salt ++ pass)
isValidPass :: Text -- ^ cleartext password
-> SaltedPass -- ^ salted password
-> Bool
isValidPass ct salted =
PS.verifyPassword (encodeUtf8 ct) (encodeUtf8 salted) || isValidPass' ct salted
isValidPass' :: Text -- ^ cleartext password
-> SaltedPass -- ^ salted password
-> Bool
isValidPass' clear' salted' =
let salt = take saltLength salted
in salted == saltPass' salt clear
where
clear = TS.unpack clear'
salted = TS.unpack salted'
-- | Session variable set when user logged in via a login link. See
-- 'needOldPassword'.
--
-- Since 1.2.1
loginLinkKey :: Text
loginLinkKey = "_AUTH_EMAIL_LOGIN_LINK"
-- | Set 'loginLinkKey' to the current time.
--
-- Since 1.2.1
setLoginLinkKey :: (YesodAuthEmail site, MonadHandler m, HandlerSite m ~ site) => AuthId site -> m ()
setLoginLinkKey aid = do
now <- liftIO getCurrentTime
setSession loginLinkKey $ TS.pack $ show (toPathPiece aid, now)
|
ygale/yesod
|
yesod-auth/Yesod/Auth/Email.hs
|
mit
| 21,068 | 0 | 24 | 6,385 | 3,972 | 2,043 | 1,929 | 340 | 10 |
module Language.Lips.REPL where
--------------------
-- Global Imports --
import qualified Data.Map.Strict as Map
import Control.Monad.State
import System.IO
-------------------
-- Local Imports --
import Language.Lips.Evaluator
import Language.Lips.Parser
import Language.Lips.State
import Language.Lips.Base
----------
-- Code --
-- Printing the REPL header
printHeader :: IO ()
printHeader = do
putStrLn "--------------------"
putStrLn " lips REPL"
putStrLn "Enter 'quit' to exit"
putStrLn ""
hFlush stdout
-- The REPL itself
repl :: ProgramState ()
repl = do
liftIO $ putStr "lips} "
liftIO $ hFlush stdout
line <- liftIO $ getLine
case line of
"quit" -> return ()
other -> do
eval $ lips other
liftIO $ hFlush stdout
repl
-- Starting the REPL
startRepl :: IO ()
startRepl = do
printHeader
evalStateT repl $ Program { primitives = basePrimitives
, variables = Map.fromList []
}
|
crockeo/lips
|
src/lib/Language/Lips/REPL.hs
|
mit
| 1,003 | 0 | 13 | 252 | 247 | 128 | 119 | 31 | 2 |
{-# LANGUAGE NoMonomorphismRestriction #-}
-- {-# LANGUAGE TypeFamilies #-}
-- an attempt to try to distill to the simplest form the diagrams
-- simply shows a single box with the doctor login web-services
-- to generate the poster:
-- ghc --make doctorlogin.hs
-- ./doctorlogin. -o doctorlogin..pdf -w 1685 or
-- ./doctorlogin. -o doctorlogin..png -w 10000 (to generate a png with width 10000)
--
-- Then try:
-- ./doctorlogin. -o doctorlogin..pdf -w 500 --loop
-- to understand the code, go to http://projects.haskell.org/diagrams/manual/diagrams-manual.html
--
-- expected format: Din A1: 594 x 841
-- or Din A0: 841 x 1189 mm (sqrt 2 / 1)
import Diagrams.Prelude
-- import Diagrams.Backend.Cairo.CmdLine
import Diagrams.Backend.SVG.CmdLine
import Diagrams.Backend.Rasterific
import Data.Word
import Graphics.SVGFonts
import qualified Diagrams.TwoD.Size as Size
import Data.Tree
import Data.Colour hiding (atop)
import Data.Maybe
main = do
folderImg <- getDataFileName "folder.png"
filesImg <- getDataFileName "files.png"
pdp7 <- getDataFileName "pdp7_3.png"
let images = [folderImg, filesImg, pdp7]
defaultMain (tlcPoster images)
-- other stuff
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = return ("/Users/nickager/Downloads/unixPoster-master/img" ++ "/" ++ name)
--------------------------------------------------
-- basic building blocks of the diagram
--------------------------------------------------
tlcPoster [folderImg, filesImg, pdp7] = strutY 3 ===
header # centerXY
=== strutY 4 ===
poster_portrait # centerXY
folderPic f = image f -- 10 10 # centerXY
header = (textLin "Doctor login" 10 black) # alignBR
poster_portrait = (strutX 3 ||| doctorLogin ||| strutX 3 ||| doctorMessaging ||| strutX 3 )
doctorLogin = textBoxWithHeader
"Doctor login web-services"
["vpWebAPI/",
" Device/Register",
" Api/Version",
" Device/CheckVersion",
" Authenticate/Limited",
" Log/Errors",
" Device/Register",
" AuthenticateDoctor",
" Doctor/SynchroniseDoctorMessages",
" Device/SyncLocation/true",
" Trust/GetConsultantsWithSpecialities",
" PatientLists/GetPatientLists",
" Doctor/GetOnDutyLists",
" Ward/GetPatients/EMERALD/false",
" Patients/HighlightedPatientsForPersion/1272",
" Diagnosis/GetDiagnosisSummaryForPatientsInList",
" Authenticate/Limited",
" Log/Errors",
" Log/Errors",
" Doctor/SynchroniseDoctorMessages"] 2 white indianred # alignTL
doctorMessaging = textBoxWithHeader
"Doctor Messaging"
["Doctor/",
" SynchroniseDoctorMessages ReadMessages, DeletedMessages",
" Doctors/RespondToEscalation"] 2 white indianred # alignTL
textLin t h c | null t = mempty
| otherwise = textSVG_ (TextOpts t lin INSIDE_H HADV False 1 h) # fc c # lc c # fillRule EvenOdd
textBit t h c | null t = mempty
| otherwise = textSVG_ (TextOpts t bit INSIDE_H HADV False 1 h) # fc c # lc c # fillRule EvenOdd
textBoxWithHeader line lines h c0 c1 = (border 0.3 w hh placedTextLines) `atop` roundedBox
where
-- placing textLines below each other
placedTextLines = ((textBit line h black # centerXY) === (vcat' (with & sep .~ h/5) textLines # centerXY)) # alignTL
textLines = map (\t -> (textBit t h c0) # alignTL) lines
roundedBox = fancyRoundedBox w h hh c1
w = Size.width (placedTextLines :: D R2)
hh = Size.height (placedTextLines :: D R2)
-- reduce the size of an object by len in all directions
border hrel w h obj | w > len && h > len = obj # scaleX ((w-len)/w)
# scaleY ((h-len)/h)
# translateX (len/2)
# translateY (-len/2)
| otherwise = obj
where len = hrel*h
fancyRoundedBox w h hh c = ( (roundedRect (w-0.4-size*0.04) (hh-0.4-size*0.04) (h/5)) # centerXY # lwL 0 # fc (blend 0.5 c white)
`atop`
(roundedRect w hh (h/5)) # centerXY # lwL 0 # fc (blend 0.5 c black) ) # alignTL # opacity 0.7
where size | w > hh = hh
| otherwise = w
|
NickAger/LearningHaskell
|
haskellForMacMiscPlayground/poster2.hsproj/poster2.hs
|
mit
| 4,338 | 0 | 20 | 1,127 | 1,021 | 536 | 485 | 73 | 1 |
import Prelude hiding ( readFile )
import Data.ByteString.Lazy ( readFile )
import Data.Binary.Get ( isEmpty, runGet )
import qualified Data.Binary as B
type Chars = [B.Word8]
printChars :: Chars -> IO()
printChars cs = mapM_ print cs
getChars = do
e <- isEmpty
if e then return []
else do
c <- B.get
cs <- getChars
return (c:cs)
main :: IO()
main = do
input <- readFile "chars"
printChars $ runGet getChars input
|
DanielAtSamraksh/checkReceivedSnapshots
|
testread.hs
|
mit
| 445 | 0 | 12 | 104 | 175 | 92 | 83 | 18 | 2 |
data Cpx = Cpx (Int,Int) deriving (Show, Eq)
instance Num Cpx where
(*) (Cpx (a, b)) (Cpx (c, d)) = Cpx (a*c-b*d, a*d+b*c)
(+) (Cpx (a, b)) (Cpx (c, d)) = Cpx (a+c, b+d)
(-) (Cpx (a, b)) (Cpx (c, d)) = Cpx (a-c, b-d)
negate (Cpx (a, b)) = Cpx (-a, -b)
abs _ = Cpx (0, 0)
signum _ = 0
fromInteger a = Cpx (fromInteger a, 0)
data BinZ = BinZ [Int] deriving (Show, Eq)
getList (BinZ x) = x
instance Num BinZ where
--remember that BinZ [0,0,1,1] = 1100_z
(+) (BinZ []) a = a
(+) a (BinZ []) = a
(+) (BinZ (x:xs)) (BinZ (0:ys)) = BinZ (x:getList (BinZ xs + BinZ ys))
(+) (BinZ (0:xs)) (BinZ (x:ys)) = BinZ (x:getList (BinZ xs + BinZ ys))
(+) (BinZ (1:1:1:xs)) (BinZ (1:1:ys)) = BinZ (0:0:getList (BinZ (0:xs) + BinZ ys))
(+) (BinZ (1:1:xs)) (BinZ (1:1:1:ys)) = BinZ (0:0:getList (BinZ xs + BinZ (0:ys)))
(+) (BinZ (1:xs)) (BinZ (1:ys)) = BinZ [0,0,1,1] + BinZ (0:xs) + BinZ (0:ys)
(*) (BinZ xs) (BinZ ys) = sum $ zipWith (\a b -> if b == 1 then BinZ (a++xs) else BinZ [0]) [replicate a 0|a<-[0..]] ys
fromInteger a = toBinZ (fromInteger a :: Cpx)
abs a = toBinZ $ abs $ fromBinZ a
zs = Cpx (1,0):map (* Cpx (-1,1)) zs
scale s (Cpx (a, b)) = Cpx (s*a, s*b)
fromBinZ (BinZ n) = sum $ zipWith scale n zs
toBinZ (Cpx (0, 0)) = BinZ [0]
toBinZ (Cpx (a, 0))
| a>=0 = toBinZ (Cpx (a-1,0)) + BinZ [1]
| otherwise = toBinZ (Cpx (a+1,0)) + BinZ [1,0,1,1,1]
toBinZ (Cpx (0, b)) = BinZ [1,1] * toBinZ (Cpx (b, 0))
toBinZ (Cpx (a, b)) = toBinZ (Cpx (a, 0)) + toBinZ (Cpx (0, b))
insigZero (0:list) = insigZero list
insigZero list = list
lengthBinZ (BinZ list) = length $ insigZero $ reverse list
cpxSpan n = map fromInteger [-n..n-1]::[Cpx]
cpxField n m = map (\x -> map (+(x*Cpx (0,1))) (cpxSpan n)) (cpxSpan m)
binary ls = sum$zipWith (*) ls (iterate (*2) 1)
zField n m = (map.map) (\x->binary$getList$toBinZ x) $ cpxField n m
main = do
putStr$ unlines $ map unwords $(map.map) show $ zField 800 450
|
42f87d89/BinZ
|
binz.hs
|
mit
| 1,940 | 0 | 14 | 425 | 1,482 | 782 | 700 | 40 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module PostgREST.OpenAPI (
encodeOpenAPI
, isMalformedProxyUri
, pickProxy
) where
import Control.Lens
import Data.Aeson (decode, encode)
import qualified Data.HashMap.Strict as M
import Data.HashMap.Strict.InsOrd (InsOrdHashMap, fromList)
import Data.Maybe (fromJust)
import qualified Data.Set as Set
import Data.String (IsString (..))
import Data.Text (unpack, pack, concat, intercalate, init, tail, toLower)
import Network.URI (parseURI, isAbsoluteURI,
URI (..), URIAuth (..))
import Protolude hiding (concat, (&), Proxy, get, intercalate)
import Data.Swagger
import PostgREST.ApiRequest (ContentType(..))
import PostgREST.Config (prettyVersion)
import PostgREST.Types (Table(..), Column(..), PgArg(..),
Proxy(..), ProcDescription(..), toMime, operators)
makeMimeList :: [ContentType] -> MimeList
makeMimeList cs = MimeList $ map (fromString . toS . toMime) cs
toSwaggerType :: Text -> SwaggerType t
toSwaggerType "text" = SwaggerString
toSwaggerType "integer" = SwaggerInteger
toSwaggerType "boolean" = SwaggerBoolean
toSwaggerType "numeric" = SwaggerNumber
toSwaggerType _ = SwaggerString
makeTableDef :: (Table, [Column], [Text]) -> (Text, Schema)
makeTableDef (t, cs, _) =
let tn = tableName t in
(tn, (mempty :: Schema)
& type_ .~ SwaggerObject
& properties .~ fromList (map makeProperty cs))
makeProperty :: Column -> (Text, Referenced Schema)
makeProperty c = (colName c, Inline u)
where
r = mempty :: Schema
s = if null $ colEnum c
then r
else r & enum_ .~ decode (encode (colEnum c))
t = s & type_ .~ toSwaggerType (colType c)
u = t & format ?~ colType c
makeProcDef :: ProcDescription -> (Text, Schema)
makeProcDef pd = ("(rpc) " <> pdName pd, s)
where
s = (mempty :: Schema)
& type_ .~ SwaggerObject
& properties .~ fromList (map makeProcProperty (pdArgs pd))
& required .~ map pgaName (filter pgaReq (pdArgs pd))
makeProcProperty :: PgArg -> (Text, Referenced Schema)
makeProcProperty (PgArg n t _) = (n, Inline s)
where
s = (mempty :: Schema)
& type_ .~ toSwaggerType t
& format ?~ t
makeOperatorPattern :: Text
makeOperatorPattern =
intercalate "|"
[ concat ["^", x, y, "[.]"] |
x <- ["not[.]", ""],
y <- M.keys operators ]
makeRowFilter :: Column -> Param
makeRowFilter c =
(mempty :: Param)
& name .~ colName c
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamQuery
& type_ .~ SwaggerString
& format ?~ colType c
& pattern ?~ makeOperatorPattern)
makeRowFilters :: [Column] -> [Param]
makeRowFilters = map makeRowFilter
makeOrderItems :: [Column] -> [Text]
makeOrderItems cs =
[ concat [x, y, z] |
x <- map colName cs,
y <- [".asc", ".desc", ""],
z <- [".nullsfirst", ".nulllast", ""]
]
makeRangeParams :: [Param]
makeRangeParams =
[ (mempty :: Param)
& name .~ "Range"
& description ?~ "Limiting and Pagination"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamHeader
& type_ .~ SwaggerString)
, (mempty :: Param)
& name .~ "Range-Unit"
& description ?~ "Limiting and Pagination"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamHeader
& type_ .~ SwaggerString
& default_ .~ decode "\"items\"")
, (mempty :: Param)
& name .~ "offset"
& description ?~ "Limiting and Pagination"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamQuery
& type_ .~ SwaggerString)
, (mempty :: Param)
& name .~ "limit"
& description ?~ "Limiting and Pagination"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamQuery
& type_ .~ SwaggerString)
]
makePreferParam :: [Text] -> Param
makePreferParam ts =
(mempty :: Param)
& name .~ "Prefer"
& description ?~ "Preference"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamHeader
& type_ .~ SwaggerString
& enum_ .~ decode (encode ts))
makeSelectParam :: Param
makeSelectParam =
(mempty :: Param)
& name .~ "select"
& description ?~ "Filtering Columns"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamQuery
& type_ .~ SwaggerString)
makeGetParams :: [Column] -> [Param]
makeGetParams [] =
makeRangeParams ++
[ makeSelectParam
, makePreferParam ["count=none"]
]
makeGetParams cs =
makeRangeParams ++
[ makeSelectParam
, (mempty :: Param)
& name .~ "order"
& description ?~ "Ordering"
& required ?~ False
& schema .~ ParamOther ((mempty :: ParamOtherSchema)
& in_ .~ ParamQuery
& type_ .~ SwaggerString
& enum_ .~ decode (encode $ makeOrderItems cs))
, makePreferParam ["count=none"]
]
makePostParams :: Text -> [Param]
makePostParams tn =
[ makePreferParam ["return=representation",
"return=minimal", "return=none"]
, (mempty :: Param)
& name .~ "body"
& description ?~ tn
& required ?~ False
& schema .~ ParamBody (Ref (Reference tn))
]
makeProcParam :: Text -> [Param]
makeProcParam refName =
[ makePreferParam ["params=single-object"]
, (mempty :: Param)
& name .~ "args"
& required ?~ True
& schema .~ ParamBody (Ref (Reference refName))
]
makeDeleteParams :: [Param]
makeDeleteParams =
[ makePreferParam ["return=representation", "return=minimal", "return=none"] ]
makePathItem :: (Table, [Column], [Text]) -> (FilePath, PathItem)
makePathItem (t, cs, _) = ("/" ++ unpack tn, p $ tableInsertable t)
where
tOp = (mempty :: Operation)
& tags .~ Set.fromList [tn]
& produces ?~ makeMimeList [CTApplicationJSON, CTSingularJSON, CTTextCSV]
& at 200 ?~ "OK"
getOp = tOp
& parameters .~ map Inline (makeGetParams cs ++ rs)
& at 206 ?~ "Partial Content"
postOp = tOp
& consumes ?~ makeMimeList [CTApplicationJSON, CTSingularJSON, CTTextCSV]
& parameters .~ map Inline (makePostParams tn)
& at 201 ?~ "Created"
patchOp = tOp
& consumes ?~ makeMimeList [CTApplicationJSON, CTSingularJSON, CTTextCSV]
& parameters .~ map Inline (makePostParams tn ++ rs)
& at 204 ?~ "No Content"
deletOp = tOp
& parameters .~ map Inline (makeDeleteParams ++ rs)
pr = (mempty :: PathItem) & get ?~ getOp
pw = pr & post ?~ postOp & patch ?~ patchOp & delete ?~ deletOp
p False = pr
p True = pw
rs = makeRowFilters cs
tn = tableName t
makeProcPathItem :: ProcDescription -> (FilePath, PathItem)
makeProcPathItem pd = ("/rpc/" ++ toS (pdName pd), pe)
where
postOp = (mempty :: Operation)
& parameters .~ map Inline (makeProcParam $ "(rpc) " <> pdName pd)
& tags .~ Set.fromList ["(rpc) " <> pdName pd]
& produces ?~ makeMimeList [CTApplicationJSON, CTSingularJSON]
& at 200 ?~ "OK"
pe = (mempty :: PathItem) & post ?~ postOp
makeRootPathItem :: (FilePath, PathItem)
makeRootPathItem = ("/", p)
where
getOp = (mempty :: Operation)
& tags .~ Set.fromList ["/"]
& produces ?~ makeMimeList [CTOpenAPI, CTApplicationJSON]
& at 200 ?~ "OK"
pr = (mempty :: PathItem) & get ?~ getOp
p = pr
makePathItems :: [ProcDescription] -> [(Table, [Column], [Text])] -> InsOrdHashMap FilePath PathItem
makePathItems pds ti = fromList $ makeRootPathItem :
map makePathItem ti ++ map makeProcPathItem pds
escapeHostName :: Text -> Text
escapeHostName "*" = "0.0.0.0"
escapeHostName "*4" = "0.0.0.0"
escapeHostName "!4" = "0.0.0.0"
escapeHostName "*6" = "0.0.0.0"
escapeHostName "!6" = "0.0.0.0"
escapeHostName h = h
postgrestSpec :: [ProcDescription] -> [(Table, [Column], [Text])] -> (Text, Text, Integer, Text) -> Swagger
postgrestSpec pds ti (s, h, p, b) = (mempty :: Swagger)
& basePath ?~ unpack b
& schemes ?~ [s']
& info .~ ((mempty :: Info)
& version .~ prettyVersion
& title .~ "PostgREST API"
& description ?~ "This is a dynamic API generated by PostgREST")
& host .~ h'
& definitions .~ fromList (map makeTableDef ti <> map makeProcDef pds)
& paths .~ makePathItems pds ti
where
s' = if s == "http" then Http else Https
h' = Just $ Host (unpack $ escapeHostName h) (Just (fromInteger p))
encodeOpenAPI :: [ProcDescription] -> [(Table, [Column], [Text])] -> (Text, Text, Integer, Text) -> LByteString
encodeOpenAPI pds ti uri = encode $ postgrestSpec pds ti uri
{-|
Test whether a proxy uri is malformed or not.
A valid proxy uri should be an absolute uri without query and user info,
only http(s) schemes are valid, port number range is 1-65535.
For example
http://postgrest.com/openapi.json
https://postgrest.com:8080/openapi.json
-}
isMalformedProxyUri :: Maybe Text -> Bool
isMalformedProxyUri Nothing = False
isMalformedProxyUri (Just uri)
| isAbsoluteURI (toS uri) = not $ isUriValid $ toURI uri
| otherwise = True
toURI :: Text -> URI
toURI uri = fromJust $ parseURI (toS uri)
pickProxy :: Maybe Text -> Maybe Proxy
pickProxy proxy
| isNothing proxy = Nothing
-- should never happen
-- since the request would have been rejected by the middleware if proxy uri
-- is malformed
| isMalformedProxyUri proxy = Nothing
| otherwise = Just Proxy {
proxyScheme = scheme
, proxyHost = host'
, proxyPort = port''
, proxyPath = path'
}
where
uri = toURI $ fromJust proxy
scheme = init $ toLower $ pack $ uriScheme uri
path URI {uriPath = ""} = "/"
path URI {uriPath = p} = p
path' = pack $ path uri
authority = fromJust $ uriAuthority uri
host' = pack $ uriRegName authority
port' = uriPort authority
readPort = fromMaybe 80 . readMaybe
port'' :: Integer
port'' = case (port', scheme) of
("", "http") -> 80
("", "https") -> 443
_ -> readPort $ unpack $ tail $ pack port'
isUriValid:: URI -> Bool
isUriValid = fAnd [isSchemeValid, isQueryValid, isAuthorityValid]
fAnd :: [a -> Bool] -> a -> Bool
fAnd fs x = all ($x) fs
isSchemeValid :: URI -> Bool
isSchemeValid URI {uriScheme = s}
| toLower (pack s) == "https:" = True
| toLower (pack s) == "http:" = True
| otherwise = False
isQueryValid :: URI -> Bool
isQueryValid URI {uriQuery = ""} = True
isQueryValid _ = False
isAuthorityValid :: URI -> Bool
isAuthorityValid URI {uriAuthority = a}
| isJust a = fAnd [isUserInfoValid, isHostValid, isPortValid] $ fromJust a
| otherwise = False
isUserInfoValid :: URIAuth -> Bool
isUserInfoValid URIAuth {uriUserInfo = ""} = True
isUserInfoValid _ = False
isHostValid :: URIAuth -> Bool
isHostValid URIAuth {uriRegName = ""} = False
isHostValid _ = True
isPortValid :: URIAuth -> Bool
isPortValid URIAuth {uriPort = ""} = True
isPortValid URIAuth {uriPort = (':':p)} =
case readMaybe p of
Just i -> i > (0 :: Integer) && i < 65536
Nothing -> False
isPortValid _ = False
|
Skyfold/postgrest
|
src/PostgREST/OpenAPI.hs
|
mit
| 11,528 | 0 | 19 | 2,976 | 3,715 | 2,004 | 1,711 | 289 | 4 |
module Settings.Packages.GhcPrim (ghcPrimPackageArgs) where
import GHC
import Oracles.Flag
import Expression
ghcPrimPackageArgs :: Args
ghcPrimPackageArgs = package ghcPrim ? mconcat
[ builder GhcCabal ? arg "--flag=include-ghc-prim"
, builder (Cc CompileC) ?
(not <$> flag GccLt44) ?
(not <$> flag GccIsClang) ?
input "//cbits/atomic.c" ? arg "-Wno-sync-nand" ]
|
izgzhen/hadrian
|
src/Settings/Packages/GhcPrim.hs
|
mit
| 400 | 0 | 14 | 83 | 110 | 57 | 53 | 11 | 1 |
module Y2018.M07.D31.Exercise where
{--
KAKURO-DAY!
Today we're going to be solving arithmetic problems then solving mutually-
dependent arithmetic problems. Some of these problems have more than one
solution, so we have to solve these problems knowing this constraint.
--}
import Data.Array
-- CONTEXT: For x1, x2, ..., xn in [1..9]:
-- all xs must be mutually-different numbers
type Domain = [Int]
domain :: [Int]
domain = [1..9]
-- solve x1 + x2 = 3, return the answer in an Array
data XS = X1 | X2 | X3 | X4 | X5 | X6 | X7 | X8 | X9
deriving (Eq, Ord, Show, Enum, Bounded, Ix)
data Context = Ctx Domain [Array XS Int]
x1_plus_x2_equals_3 :: [Context] -> [Context]
x1_plus_x2_equals_3 ctxn= undefined
-- Of course, the initial context is that all variables are unbound.
-- ... how do you represent that?
-- Also note that the context can vary based on the outcome. How to model that?
-- what are the values that you arrive at for x1 and x2?
-- Okay, given the solution above, solve x1 + x3 = 5
x1_plus_x3_equals_5 :: [Context] -> [Context]
x1_plus_x3_equals_5 ctx = undefined
-- what are the values you arrive at for x1 and x3? Are any values 'settled'?
-- That is to say: have we bound x1 or x3 (or both) to a single value?
-- And, given the above, solve x2 + x4 = 3
x2_plus_x4_equals_3 :: [Context] -> [Context]
x2_plus_x4_equals_3 ctxn = undefined
-- What are the values you arrive at for x2 and x4? What variables are settled?
|
geophf/1HaskellADay
|
exercises/HAD/Y2018/M07/D31/Exercise.hs
|
mit
| 1,466 | 0 | 8 | 293 | 199 | 122 | 77 | 14 | 1 |
{-# LANGUAGE UndecidableInstances, OverlappingInstances, FunctionalDependencies, MultiParamTypeClasses, FlexibleInstances #-}
module Condition
( module Condition
, module Suggest
)
where
import Suggest
import Autolib.Reporter
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
class ( ToDoc prop, Reader prop, Typeable prop, Suggest prop )
=> Explain prop where
explain :: prop -> Doc
explain = toDoc
instance ( ToDoc prop, Reader prop, Typeable prop, Suggest prop )
=> Explain prop
class Explain prop
=> Condition prop ob | ob -> prop where
condition :: prop -> ob -> Reporter ()
investigate :: Condition prop ob
=> [ prop ] -> ob -> Reporter ()
investigate props ob = sequence_ $ do
prop <- props
return $ condition prop ob
|
Erdwolf/autotool-bonn
|
src/Condition.hs
|
gpl-2.0
| 798 | 2 | 10 | 173 | 229 | 120 | 109 | 23 | 1 |
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-}
module Graph.MST.Weight where
import Autolib.ToDoc
import Autolib.Reader
import Autolib.Graph.Type ( Kante (..) )
import Autolib.FiniteMap ( FiniteMap , lookupWithDefaultFM , listToFM )
import Data.Typeable
import Autolib.Hash ( Hash , hash )
import System.Random ( randomRIO )
import System.IO.Unsafe ( unsafePerformIO )
-------------------------------------------------------------------------------
data Weight = Summe
| Produkt
| Delta
| Hamming Int
| Random Int
| Direct (FiniteMap (Kante Int) Int)
deriving ( Eq, Typeable )
instance Hash Weight where
hash Summe = 7
hash Produkt = 11
hash Delta = 13
hash (Hamming n) = 3 * (hash $ succ n)
hash (Random n) = 5 * (hash $ succ n)
hash (Direct fm) = 2 * (hash fm)
wfun :: Weight-> Kante Int -> Int
wfun Summe (Kante {von=v,nach=n}) = v+n
wfun Produkt (Kante {von=v,nach=n}) = v*n
wfun Delta (Kante {von=v,nach=n}) = abs $ v-n
wfun (Hamming k) (Kante {von=v,nach=n}) =
let digs 0 = []
digs x = let (q,r) = divMod x 2 in r : digs q
digsK x = take k $ digs x ++ repeat 0
in length $ filter id $ zipWith (/=) (digsK v) (digsK n)
wfun (Random k) _ = unsafePerformIO $ randomRIO (1,k)
wfun (Direct fm) k = lookupWithDefaultFM fm (error "gewichte nicht komplett!?") k
direct :: Weight -> [Kante Int] -> Weight
direct f ks = Direct $ listToFM $ do k <- ks ; return (k,wfun f k)
$(derives [makeReader, makeToDoc] [''Weight])
-- Local Variables:
-- mode: haskell
-- End:
|
Erdwolf/autotool-bonn
|
src/Graph/MST/Weight.hs
|
gpl-2.0
| 1,568 | 6 | 13 | 351 | 667 | 356 | 311 | 38 | 2 |
import Control.Concurrent (forkIO)
import Network (connectTo, PortID(..))
import System.Environment (getArgs)
import Control.Monad (forever)
import System.IO (hSetBuffering, BufferMode(..), hGetLine, hPutStrLn)
import GHC.IO.Handle (Handle)
ping :: String
ping = "PING"
pong :: String
pong = "PONG"
startsWith :: String -> String -> Bool
startsWith [] [] = True
startsWith [] _ = True
startsWith _ [] = False
startsWith (p:ps) (s:xs) = (p == s) && (startsWith ps xs)
handleReceived :: Handle -> String -> IO ()
handleReceived h s = if (startsWith "PING" s)
then hPutStrLn h $ makeResponse s
else putStrLn s
makeResponse :: String -> String
makeResponse = unwords . (pong :) . drop 1 . words
listener :: Handle -> IO ()
listener h = do
msg <- hGetLine h
handleReceived h msg
identifyString :: String
identifyString = "/id"
joinString :: String
joinString = "/j"
performIdentify :: Handle -> String -> IO ()
performIdentify h line = do
let nick = drop 1 $ words line
putStrLn $ unwords nick
hPutStrLn h $ unwords $ "NICK ":nick
hPutStrLn h "USER noone 8 * :Just Nobody"
performJoin :: Handle -> String -> IO ()
performJoin h line = do
let command = unwords $ ("JOIN" :) $ drop 1 $ words line
hPutStrLn h command
handleCommand :: Handle -> String -> IO ()
handleCommand h line
| startsWith identifyString line = performIdentify h line
| startsWith joinString line = performJoin h line
| otherwise = hPutStrLn h line
responder :: Handle -> IO ()
responder h = do
line <- getLine
handleCommand h line
launch :: String -> PortID -> IO ()
launch host port = do
h <- connectTo host port
hSetBuffering h NoBuffering
t <- forkIO $ forever $ listener h
forever $ responder h
displayPrompt :: IO ()
displayPrompt = putStrLn "Usage: not implemented yet"
ircPort :: PortID
ircPort = PortNumber 6667
main :: IO ()
main = do
args <- getArgs
case args of
(address : _) -> launch address ircPort
_ -> displayPrompt
|
nkartashov/irc-hs
|
main.hs
|
gpl-2.0
| 2,006 | 0 | 13 | 438 | 768 | 383 | 385 | 64 | 2 |
{-# language GADTs, TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Numeric.LinearAlgebra.Sparse.Accelerate
-- Copyright : (c) Marco Zocca 2017
-- License : BSD3 (see the file LICENSE)
--
-- Maintainer : zocca marco gmail
-- Stability : experimental
-- Portability : portable
--
-- `accelerate` instances for sparse linear algebra
--
-----------------------------------------------------------------------------
module Numeric.LinearAlgebra.Sparse.Accelerate where
import Foreign.Storable (Storable(..))
import Control.Monad.Primitive
import Data.Ord (comparing)
import qualified Data.Array.Accelerate as A
import Data.Array.Accelerate
(Acc, Array, Vector, Segments, DIM1, DIM2, Exp, Any(Any), All(All), Z(Z), (:.)((:.)))
import Data.Array.Accelerate.IO -- (fromVectors, toVectors)
import Data.Array.Accelerate.Array.Sugar
import Data.Vector.Algorithms.Merge (sort, sortBy)
-- import Data.Vector.Algorithms.Common
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
-- import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Storable as VS
import Data.Array.Accelerate.Interpreter (run)
-- import Data.Array.Accelerate.Sparse.SMatrix
-- import Data.Array.Accelerate.Sparse.SVector
import Data.Array.Accelerate.Sparse.COOElem
-- takeWhile ins = A.fold ins (A.use []) where
-- extractRow i = A.filter (\coo -> let ixr = getRow coo in ixr == i)
-- extractRow i = A.filter (\e -> A.lift (eqRowIx i e))
-- eqRowIx :: Eq i => i -> COOElem i a -> Bool
-- eqRowIx i = (== i) . getRow . A.unlift
-- withExp :: (a -> b) -> Exp a -> Exp b
-- withExp f = A.lift . f . A.unlift
-- empty = A.use $ V.fromList []
-- * SpGEMM : matrix-matrix product
-- | Sort an accelerate array via vector-algorithms
sortA :: (Vectors (EltRepr e) ~ VS.Vector e
, Storable e
, Ord e
, Elt e
, Shape t
, PrimMonad m) => t -> Array t e -> m (Array t e)
sortA dim v = do
let vm = toVectors v
vm' <- sortVS vm
return $ fromVectors dim vm'
-- | Sort a storable vector
sortVS :: (Storable a, PrimMonad m, Ord a) =>
VS.Vector a -> m (VS.Vector a)
sortVS v = do
vm <- VS.thaw v
sort vm
VS.freeze vm
sortWith :: (Ord b, PrimMonad m) => (a -> b) -> V.Vector a -> m (V.Vector a)
sortWith by v = do
vm <- V.thaw v
sortBy (comparing by) vm
V.freeze vm
-- Sparse-matrix vector multiplication
-- -----------------------------------
-- type SparseVector e = Vector (A.Int32, e)
-- type SparseMatrix e = (Segments A.Int32, SparseVector e)
-- smvm :: A.Num a => Acc (SparseMatrix a) -> Acc (Vector a) -> Acc (Vector a)
-- smvm smat vec
-- = let (segd, svec) = A.unlift smat
-- (inds, vals) = A.unzip svec
-- -- vecVals = A.gather (A.map A.fromIntegral inds) vec
-- vecVals = A.backpermute
-- (A.shape inds)
-- (\i -> A.index1 $ A.fromIntegral $ inds A.! i)
-- vec
-- products = A.zipWith (*) vecVals vals
-- in
-- A.foldSeg (+) 0 products segd
-- sv0 :: A.Array DIM1 (Int, Int)
-- sv0 = A.fromList (Z :. 5) $ zip [0,1,3,4,6] [4 ..]
sv1 :: A.Array DIM1 (COOElem Int Double)
sv1 = A.fromList (Z :. 3) [a, b, c] where
a = CooE (0, 1, pi)
b = CooE (0, 0, 2.3)
c = CooE (1, 1, 1.23)
|
ocramz/sparse-linear-algebra
|
accelerate/src/Numeric/LinearAlgebra/Sparse/Accelerate.hs
|
gpl-3.0
| 3,438 | 0 | 11 | 806 | 636 | 377 | 259 | 42 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Toy.Backend.Classify where
import AI.DecisionTree
import Data.Aeson
import Data.Aeson.TH
import Data.Text (pack)
import Yesod.Core
data Classify = Classify (DecisionTree Bool Bool) deriving Show
deriveJSON defaultOptions ''Classify
classify :: Classify -> Int -> Bool -> Bool -> IO Bool
classify (Classify dt) age smile gender = do
print (age,smile,gender)
return $ decide dt $ Unlabeled "test" $ zip [Attr "age" [], Attr "smile" [], Attr "gender" []] [age > 32 , smile,gender]
|
Qinka/reimagined-pancake
|
toy-backend/toy-backend-classify/src/dt/Toy/Backend/Classify.hs
|
gpl-3.0
| 582 | 0 | 11 | 139 | 197 | 104 | 93 | 13 | 1 |
-- | A collection of default remotes.
--
-- These remotes are installed on an LXD instance by default.
--
-- Run @lxc image list@ for more information.
module Network.LXD.Client.Remotes where
import Network.LXD.Client.Internal.Prelude
imagesRemote :: String
imagesRemote = "https://images.linuxcontainers.org"
ubuntuRemote :: String
ubuntuRemote = "https://cloud-images.ubuntu.com/releases"
ubuntuDailyRemote :: String
ubuntuDailyRemote = "https://cloud-images.ubuntu.com/daily"
|
hverr/haskell-lxd-client
|
src/Network/LXD/Client/Remotes.hs
|
gpl-3.0
| 483 | 0 | 4 | 55 | 51 | 35 | 16 | 8 | 1 |
-- | Many-sorted first-order logic with equality.
module Logic.FOL.Sorted where
import Data.Maybe
import Data.List
import Control.Basics
import Text.PrettyPrint.Applicative
infixl 3 .&&
infixl 2 .||
infixr 1 .==>
infixl 1 .<==
infix 1 .<=>
infix 4 .==
infix 4 ./=
-- Utilities
------------
-- | Apply a function to the last element, if it exists.
mapLast :: (a -> a) -> [a] -> [a]
mapLast f = go
where go [] = []
go [x] = [f x]
go (x:xs) = x : go xs
-- Types
--------
newtype Sort = Sort { getSort :: String }
deriving(Eq, Ord)
instance Show Sort where
show = getSort
newtype Id = Id { getId :: String }
deriving(Eq, Ord)
instance Show Id where
show = getId
type SortedId = (Id, Sort)
data Fun = Fun SortedId [Sort]
deriving(Eq, Ord, Show)
data Rel = Rel Id [Sort]
deriving(Eq, Ord, Show)
data Term =
Var SortedId
| App Fun [Term]
deriving(Eq, Ord, Show)
data BinOp = Conj | Disj | Imp | Equiv
deriving(Eq, Ord, Show)
data Quant = All | Ex
deriving(Eq, Ord, Show)
data Formula =
Top
| Bot
| In Rel [Term]
| Neg Formula
| BinOp BinOp Formula Formula
| Quant Quant SortedId Formula
deriving(Eq, Ord, Show)
idSort :: SortedId -> Sort
idSort = snd
funSort :: Fun-> Sort
funSort (Fun si _) = idSort si
termSort :: Term -> Sort
termSort (Var si) = idSort si
termSort (App f _) = funSort f
sid :: String -> String -> SortedId
sid i s = (Id i, Sort s)
var :: String -> String -> Term
var = (Var.) . sid
apply :: Fun -> [Term] -> Term
apply f@(Fun _ ss) ts
| ss == map termSort ts = App f ts
| otherwise =
error $ "apply: '"++show f++"' to '"++show ts++"' - sorts don't agree"
const = flip apply []
neg = Neg
(.==) = eq
(./=) = (neg.) . eq
(.&&) = BinOp Conj
(.||) = BinOp Disj
(.<=>) = BinOp Equiv
(.==>) = BinOp Imp
(.<==) = flip (BinOp Imp)
univ :: SortedId -> Formula -> Formula
univ = Quant All
ex :: SortedId -> Formula -> Formula
ex = Quant Ex
eq :: Term -> Term -> Formula
eq x y
| sx == sy = In (Rel (Id "=") [sx,sx]) [x,y]
| otherwise = error $ "eq: sorts '"++show sx++"' and '"++show sy++"' do not agree."
where
sx = termSort x
sy = termSort y
inRel :: Rel -> [Term] -> Formula
inRel r@(Rel _ sorts) ts
| tss == sorts = In r ts
| otherwise = error $ "inRel: sorts '"++show tss++"' disagree with expected sorts '"++show sorts++"'"
where
tss = map termSort ts
conj :: [Formula] -> Formula
conj [] = Top
conj as = foldr1 (.&&) as
disj :: [Formula] -> Formula
disj [] = Bot
disj as = foldr1 (.||) as
-- Free algebra axioms
----------------------
indexedIds :: String -> [Id]
indexedIds v = [ Id (v ++ show i) | i <- [0..] ]
sortedSids :: String -> [Sort] -> [SortedId]
sortedSids v = zipWith (,) (indexedIds v)
sortedVars :: String -> [Sort] -> ([SortedId],[Term])
sortedVars v sorts = (sids, map Var sids)
where sids = sortedSids v sorts
allArguments :: String -> Fun -> (Formula -> Formula, Term, [Term])
allArguments v f@(Fun _ sorts) =
(\t -> foldr univ t is, App f ts, ts)
where
(is, ts) = sortedVars v sorts
injective :: MonadPlus m => Fun -> m Formula
injective f@(Fun _ []) = mzero
injective f@(Fun _ sorts) = return . xquant . yquant $
(fxs .== fys) .==> (conj $ zipWith (.==) xs ys)
where
(xquant, fxs, xs) = allArguments "X" f
(yquant, fys, ys) = allArguments "Y" f
free :: Fun -> [Fun] -> [Formula]
free f@(Fun _ sorts) fs = do
f'@(Fun _ sorts') <- fs
let (ys, yvs) = sortedVars "Y" sorts'
return $ foldr univ
(App f xvs ./= App f' yvs)
(xs ++ ys)
where
(xs, xvs) = sortedVars "X" sorts
freeAlgebra :: [Fun] -> [Formula]
freeAlgebra fs =
(fs >>= injective) <|>
(zip fs (tail (tails fs)) >>= uncurry free)
-- Pretty Printing
------------------
ppId :: Document d => Id -> d
ppId = text . getId
ppSort :: Document d => Sort -> d
ppSort = text . getSort
ppSortedId :: Document d => SortedId -> d
ppSortedId (i, s) = ppId i <> colon <> ppSort s
ppTerm :: Document d => Term -> d
ppTerm (Var (i,_)) = ppId i
ppTerm (App (Fun (i,_) _) []) = ppId i
ppTerm (App (Fun (i,_) _) ts) =
sep (ppId i <> lparen <> arg : args)
where
(arg:args) = map (nest 1) . mapLast (<> rparen) . punctuate comma $ map ppTerm ts
ppFormula :: Document d => Formula -> d
ppFormula Top = text "true"
ppFormula Bot = text "false"
ppFormula (In (Rel i _) ts) = case getId i of
[] -> error "ppFormula: empty identifier encountered"
op | head op `elem` "=!<>" && length ts == 2 ->
sep [ppTerm (ts !! 0) <-> text op, ppTerm (ts !! 1)]
_ ->
ppId i <> sep (lparen <> arg : map (nest 1) args)
where
(arg:args) = mapLast (<> rparen) . punctuate comma $ map ppTerm ts
ppFormula (Neg a) = text "not" <> parens (ppFormula a)
ppFormula (BinOp op a b) =
sep [parens (ppFormula a) <-> text (ppOp op), parens (ppFormula b)]
where
ppOp Conj = "&"
ppOp Disj = "|"
ppOp Imp = "==>"
ppOp Equiv = "<=>"
ppFormula (Quant q si a) =
sep [text (ppQuant q) <-> ppSortedId si <> text ".", nest 1 $ ppFormula a]
where
ppQuant All = "!"
ppQuant Ex = "?"
|
meiersi/scyther-proof
|
src/Logic/FOL/Sorted.hs
|
gpl-3.0
| 5,052 | 1 | 14 | 1,209 | 2,394 | 1,257 | 1,137 | 154 | 7 |
module VirMat.IO.Export.VTK.VTKODFRender
( renderVTK
, writeVTKfile )
where
import qualified Data.Vector as V
import Data.XML.Types
import qualified Text.XML.Enumerator.Document as X
import VirMat.Distributions.Texture.DiscreteODF ( DiscODF, step, nPHI1, nPHI, nPHI2, sPHI1, sPHI, sPHI2, odf )
import VirMat.IO.Export.VTK.TemplateVTKXMLStruc
writeVTKfile::FilePath -> DiscODF -> IO ()
writeVTKfile name df = X.writeFile name (renderVTK df)
renderVTK::DiscODF -> Document
renderVTK df = renderVTKDoc range origin stepSize [dataPoint] [dataCell]
where
range = (0, nPHI1 df - 1, 0, nPHI df - 1, 0, nPHI2 df - 1)
origin = (0, 0, 0)
stepSize = (step df, step df, step df)
size = V.length $ odf df
dataPoint = renderScalarPointData "Intensity" $ V.toList $ odf df
dataCell = renderScalarCellData "Intensity" $ V.toList $ odf df
|
lostbean/VirMat
|
src/VirMat/IO/Export/VTK/VTKODFRender.hs
|
gpl-3.0
| 917 | 0 | 9 | 211 | 299 | 171 | 128 | 18 | 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.Gmail.Users.Labels.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets the specified label.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.labels.get@.
module Network.Google.Resource.Gmail.Users.Labels.Get
(
-- * REST Resource
UsersLabelsGetResource
-- * Creating a Request
, usersLabelsGet
, UsersLabelsGet
-- * Request Lenses
, ulgUserId
, ulgId
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.labels.get@ method which the
-- 'UsersLabelsGet' request conforms to.
type UsersLabelsGetResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"labels" :>
Capture "id" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Label
-- | Gets the specified label.
--
-- /See:/ 'usersLabelsGet' smart constructor.
data UsersLabelsGet = UsersLabelsGet'
{ _ulgUserId :: !Text
, _ulgId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'UsersLabelsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ulgUserId'
--
-- * 'ulgId'
usersLabelsGet
:: Text -- ^ 'ulgId'
-> UsersLabelsGet
usersLabelsGet pUlgId_ =
UsersLabelsGet'
{ _ulgUserId = "me"
, _ulgId = pUlgId_
}
-- | The user\'s email address. The special value me can be used to indicate
-- the authenticated user.
ulgUserId :: Lens' UsersLabelsGet Text
ulgUserId
= lens _ulgUserId (\ s a -> s{_ulgUserId = a})
-- | The ID of the label to retrieve.
ulgId :: Lens' UsersLabelsGet Text
ulgId = lens _ulgId (\ s a -> s{_ulgId = a})
instance GoogleRequest UsersLabelsGet where
type Rs UsersLabelsGet = Label
type Scopes UsersLabelsGet =
'["https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.labels",
"https://www.googleapis.com/auth/gmail.metadata",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.readonly"]
requestClient UsersLabelsGet'{..}
= go _ulgUserId _ulgId (Just AltJSON) gmailService
where go
= buildClient (Proxy :: Proxy UsersLabelsGetResource)
mempty
|
rueshyna/gogol
|
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Labels/Get.hs
|
mpl-2.0
| 3,133 | 0 | 14 | 756 | 388 | 235 | 153 | 62 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EC2.DescribeSpotPriceHistory
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Describes the Spot Price history. The prices returned are listed in
-- chronological order, from the oldest to the most recent, for up to the past
-- 90 days. For more information, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html Spot Instance Pricing History> in the /Amazon Elastic Compute Cloud User Guide for Linux/.
--
-- When you specify a start and end time, this operation returns the prices of
-- the instance types within the time range that you specified and the time when
-- the price changed. The price is valid within the time period that you
-- specified; the response merely indicates the last time that the price changed.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotPriceHistory.html>
module Network.AWS.EC2.DescribeSpotPriceHistory
(
-- * Request
DescribeSpotPriceHistory
-- ** Request constructor
, describeSpotPriceHistory
-- ** Request lenses
, dsphAvailabilityZone
, dsphDryRun
, dsphEndTime
, dsphFilters
, dsphInstanceTypes
, dsphMaxResults
, dsphNextToken
, dsphProductDescriptions
, dsphStartTime
-- * Response
, DescribeSpotPriceHistoryResponse
-- ** Response constructor
, describeSpotPriceHistoryResponse
-- ** Response lenses
, dsphrNextToken
, dsphrSpotPriceHistory
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data DescribeSpotPriceHistory = DescribeSpotPriceHistory
{ _dsphAvailabilityZone :: Maybe Text
, _dsphDryRun :: Maybe Bool
, _dsphEndTime :: Maybe ISO8601
, _dsphFilters :: List "Filter" Filter
, _dsphInstanceTypes :: List "InstanceType" InstanceType
, _dsphMaxResults :: Maybe Int
, _dsphNextToken :: Maybe Text
, _dsphProductDescriptions :: List "ProductDescription" Text
, _dsphStartTime :: Maybe ISO8601
} deriving (Eq, Read, Show)
-- | 'DescribeSpotPriceHistory' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dsphAvailabilityZone' @::@ 'Maybe' 'Text'
--
-- * 'dsphDryRun' @::@ 'Maybe' 'Bool'
--
-- * 'dsphEndTime' @::@ 'Maybe' 'UTCTime'
--
-- * 'dsphFilters' @::@ ['Filter']
--
-- * 'dsphInstanceTypes' @::@ ['InstanceType']
--
-- * 'dsphMaxResults' @::@ 'Maybe' 'Int'
--
-- * 'dsphNextToken' @::@ 'Maybe' 'Text'
--
-- * 'dsphProductDescriptions' @::@ ['Text']
--
-- * 'dsphStartTime' @::@ 'Maybe' 'UTCTime'
--
describeSpotPriceHistory :: DescribeSpotPriceHistory
describeSpotPriceHistory = DescribeSpotPriceHistory
{ _dsphDryRun = Nothing
, _dsphStartTime = Nothing
, _dsphEndTime = Nothing
, _dsphInstanceTypes = mempty
, _dsphProductDescriptions = mempty
, _dsphFilters = mempty
, _dsphAvailabilityZone = Nothing
, _dsphMaxResults = Nothing
, _dsphNextToken = Nothing
}
-- | Filters the results by the specified Availability Zone.
dsphAvailabilityZone :: Lens' DescribeSpotPriceHistory (Maybe Text)
dsphAvailabilityZone =
lens _dsphAvailabilityZone (\s a -> s { _dsphAvailabilityZone = a })
dsphDryRun :: Lens' DescribeSpotPriceHistory (Maybe Bool)
dsphDryRun = lens _dsphDryRun (\s a -> s { _dsphDryRun = a })
-- | The date and time, up to the current date, from which to stop retrieving the
-- price history data.
dsphEndTime :: Lens' DescribeSpotPriceHistory (Maybe UTCTime)
dsphEndTime = lens _dsphEndTime (\s a -> s { _dsphEndTime = a }) . mapping _Time
-- | One or more filters.
--
-- 'availability-zone' - The Availability Zone for which prices should be
-- returned.
--
-- 'instance-type' - The type of instance (for example, 'm1.small').
--
-- 'product-description' - The product description for the Spot Price ('Linux/UNIX' | 'SUSE Linux' | 'Windows' | 'Linux/UNIX (Amazon VPC)' | 'SUSE Linux (Amazon VPC)' | 'Windows (Amazon VPC)').
--
-- 'spot-price' - The Spot Price. The value must match exactly (or use
-- wildcards; greater than or less than comparison is not supported).
--
-- 'timestamp' - The timestamp of the Spot Price history (for example,
-- 2010-08-16T05:06:11.000Z). You can use wildcards (* and ?). Greater than or
-- less than comparison is not supported.
--
--
dsphFilters :: Lens' DescribeSpotPriceHistory [Filter]
dsphFilters = lens _dsphFilters (\s a -> s { _dsphFilters = a }) . _List
-- | Filters the results by the specified instance types.
dsphInstanceTypes :: Lens' DescribeSpotPriceHistory [InstanceType]
dsphInstanceTypes =
lens _dsphInstanceTypes (\s a -> s { _dsphInstanceTypes = a })
. _List
-- | The maximum number of results to return for the request in a single page. The
-- remaining results of the initial request can be seen by sending another
-- request with the returned 'NextToken' value. This value can be between 5 and
-- 1000; if 'MaxResults' is given a value larger than 1000, only 1000 results are
-- returned.
dsphMaxResults :: Lens' DescribeSpotPriceHistory (Maybe Int)
dsphMaxResults = lens _dsphMaxResults (\s a -> s { _dsphMaxResults = a })
-- | The token to retrieve the next page of results.
dsphNextToken :: Lens' DescribeSpotPriceHistory (Maybe Text)
dsphNextToken = lens _dsphNextToken (\s a -> s { _dsphNextToken = a })
-- | Filters the results by the specified basic product descriptions.
dsphProductDescriptions :: Lens' DescribeSpotPriceHistory [Text]
dsphProductDescriptions =
lens _dsphProductDescriptions (\s a -> s { _dsphProductDescriptions = a })
. _List
-- | The date and time, up to the past 90 days, from which to start retrieving the
-- price history data.
dsphStartTime :: Lens' DescribeSpotPriceHistory (Maybe UTCTime)
dsphStartTime = lens _dsphStartTime (\s a -> s { _dsphStartTime = a }) . mapping _Time
data DescribeSpotPriceHistoryResponse = DescribeSpotPriceHistoryResponse
{ _dsphrNextToken :: Maybe Text
, _dsphrSpotPriceHistory :: List "item" SpotPrice
} deriving (Eq, Read, Show)
-- | 'DescribeSpotPriceHistoryResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dsphrNextToken' @::@ 'Maybe' 'Text'
--
-- * 'dsphrSpotPriceHistory' @::@ ['SpotPrice']
--
describeSpotPriceHistoryResponse :: DescribeSpotPriceHistoryResponse
describeSpotPriceHistoryResponse = DescribeSpotPriceHistoryResponse
{ _dsphrSpotPriceHistory = mempty
, _dsphrNextToken = Nothing
}
-- | The token to use to retrieve the next page of results. This value is 'null'
-- when there are no more results to return.
dsphrNextToken :: Lens' DescribeSpotPriceHistoryResponse (Maybe Text)
dsphrNextToken = lens _dsphrNextToken (\s a -> s { _dsphrNextToken = a })
-- | The historical Spot Prices.
dsphrSpotPriceHistory :: Lens' DescribeSpotPriceHistoryResponse [SpotPrice]
dsphrSpotPriceHistory =
lens _dsphrSpotPriceHistory (\s a -> s { _dsphrSpotPriceHistory = a })
. _List
instance ToPath DescribeSpotPriceHistory where
toPath = const "/"
instance ToQuery DescribeSpotPriceHistory where
toQuery DescribeSpotPriceHistory{..} = mconcat
[ "AvailabilityZone" =? _dsphAvailabilityZone
, "DryRun" =? _dsphDryRun
, "EndTime" =? _dsphEndTime
, "Filter" `toQueryList` _dsphFilters
, "InstanceType" `toQueryList` _dsphInstanceTypes
, "MaxResults" =? _dsphMaxResults
, "NextToken" =? _dsphNextToken
, "ProductDescription" `toQueryList` _dsphProductDescriptions
, "StartTime" =? _dsphStartTime
]
instance ToHeaders DescribeSpotPriceHistory
instance AWSRequest DescribeSpotPriceHistory where
type Sv DescribeSpotPriceHistory = EC2
type Rs DescribeSpotPriceHistory = DescribeSpotPriceHistoryResponse
request = post "DescribeSpotPriceHistory"
response = xmlResponse
instance FromXML DescribeSpotPriceHistoryResponse where
parseXML x = DescribeSpotPriceHistoryResponse
<$> x .@? "nextToken"
<*> x .@? "spotPriceHistorySet" .!@ mempty
instance AWSPager DescribeSpotPriceHistory where
page rq rs
| stop (rs ^. dsphrNextToken) = Nothing
| otherwise = (\x -> rq & dsphNextToken ?~ x)
<$> (rs ^. dsphrNextToken)
|
kim/amazonka
|
amazonka-ec2/gen/Network/AWS/EC2/DescribeSpotPriceHistory.hs
|
mpl-2.0
| 9,438 | 0 | 11 | 1,990 | 1,190 | 711 | 479 | 118 | 1 |
module ProjectM36.DataTypes.Primitive where
import ProjectM36.Base
primitiveTypeConstructorMapping :: TypeConstructorMapping
primitiveTypeConstructorMapping = boolMapping : map (\(name, aType) ->
(PrimitiveTypeConstructorDef name aType, [])) prims
where
prims = [("Integer", IntegerAtomType),
("Int", IntAtomType),
("Text", TextAtomType),
("Double", DoubleAtomType),
("UUID", UUIDAtomType),
("ByteString", ByteStringAtomType),
("DateTime", DateTimeAtomType),
("Day", DayAtomType)
]
boolMapping = (PrimitiveTypeConstructorDef "Bool" BoolAtomType,
[DataConstructorDef "True" [],
DataConstructorDef "False" []])
intTypeConstructor :: TypeConstructor
intTypeConstructor = PrimitiveTypeConstructor "Int" IntAtomType
doubleTypeConstructor :: TypeConstructor
doubleTypeConstructor = PrimitiveTypeConstructor "Double" DoubleAtomType
textTypeConstructor :: TypeConstructor
textTypeConstructor = PrimitiveTypeConstructor "Text" TextAtomType
dayTypeConstructor :: TypeConstructor
dayTypeConstructor = PrimitiveTypeConstructor "Day" DayAtomType
dateTimeTypeConstructor :: TypeConstructor
dateTimeTypeConstructor = PrimitiveTypeConstructor "DateTime" DayAtomType
uUIDTypeConstructor :: TypeConstructor
uUIDTypeConstructor = PrimitiveTypeConstructor "UUID" UUIDAtomType
-- | Return the type of an 'Atom'.
atomTypeForAtom :: Atom -> AtomType
atomTypeForAtom (IntAtom _) = IntAtomType
atomTypeForAtom (IntegerAtom _) = IntegerAtomType
atomTypeForAtom (ScientificAtom _) = ScientificAtomType
atomTypeForAtom (DoubleAtom _) = DoubleAtomType
atomTypeForAtom (TextAtom _) = TextAtomType
atomTypeForAtom (DayAtom _) = DayAtomType
atomTypeForAtom (DateTimeAtom _) = DateTimeAtomType
atomTypeForAtom (ByteStringAtom _) = ByteStringAtomType
atomTypeForAtom (BoolAtom _) = BoolAtomType
atomTypeForAtom (UUIDAtom _) = UUIDAtomType
atomTypeForAtom (RelationAtom (Relation attrs _)) = RelationAtomType attrs
atomTypeForAtom (ConstructedAtom _ aType _) = aType
atomTypeForAtom (RelationalExprAtom _) = RelationalExprAtomType
|
agentm/project-m36
|
src/lib/ProjectM36/DataTypes/Primitive.hs
|
unlicense
| 2,214 | 0 | 10 | 401 | 470 | 257 | 213 | 42 | 1 |
{-# LANGUAGE GADTs, RankNTypes #-}
-----------------------------------------------------------------------------
-- Copyright 2019, Ideas project team. This file is distributed under the
-- terms of the Apache License 2.0. For more information, see the files
-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution.
-----------------------------------------------------------------------------
-- |
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable (depends on ghc)
--
-----------------------------------------------------------------------------
module Ideas.Encoding.Evaluator (Evaluator(..), evalService) where
import Ideas.Common.Library
import Ideas.Encoding.Encoder
import Ideas.Encoding.Logging
import Ideas.Encoding.Options
import Ideas.Service.Diagnose
import Ideas.Service.Types
import Ideas.Utils.Decoding
data Evaluator a b c = Evaluator (TypedDecoder a b) (TypedEncoder a c)
data EvalResult a c = EvalResult
{ inputValues :: [TypedValue (Type a)]
, outputValue :: TypedValue (Type a)
, evalResult :: c
}
values :: EvalResult a c -> [TypedValue (Type a)]
values result = outputValue result : inputValues result
logType :: Options -> EvalResult a c -> Type a b -> (b -> Record -> Record) -> IO ()
logType opts res tp f =
case concatMap (findValuesOfType tp) (values res) of
[] -> return ()
hd:_ -> changeLog (logRef opts) (f hd)
evalService :: Exercise a -> Options -> Evaluator a b c -> Service -> b -> IO c
evalService ex opts f srv b = do
res <- eval ex opts f b (serviceFunction srv)
logType opts res tState addState
logType opts res tRule $ \rl r -> r {ruleid = showId rl}
logType opts res tDiagnosis $ \d r -> r {serviceinfo = show d}
return (evalResult res)
eval :: Exercise a -> Options -> Evaluator a b c -> b -> TypedValue (Type a) -> IO (EvalResult a c)
eval ex opts (Evaluator dec enc) b = rec
where
rec tv@(val ::: tp) =
case tp of
-- handle exceptions
Const String :|: t ->
either fail (\a -> rec (a ::: t)) val
-- uncurry function if possible
t1 :-> t2 :-> t3 ->
rec (uncurry val ::: Pair t1 t2 :-> t3)
t1 :-> t2 -> do
a <- runDecoder (dec t1) (ex, opts) b
res <- rec (val a ::: t2)
return res { inputValues = (a ::: t1) : inputValues res }
-- perform IO
IO t -> do
a <- val
rec (a ::: t)
_ -> do
c <- runEncoder (enc tv) (ex, opts)
return $ EvalResult [] tv c
|
ideas-edu/ideas
|
src/Ideas/Encoding/Evaluator.hs
|
apache-2.0
| 2,665 | 0 | 17 | 704 | 822 | 423 | 399 | 46 | 5 |
{-
Copyright 2020 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.
-}
{-# LANGUAGE StandaloneDeriving #-}
-- |
-- This module encapsulates the logics behind the prediction code in the
-- multi-player setup. It is the version of the code presented in the paper,
-- including here for completenss and testing.
module CodeWorld.Prediction.Paper where
import Data.List
type Player = Int
type Timestamp = Double
type Message = (Timestamp, Player, Event)
type Event = Char
class Game world where
start :: world
step :: Double -> world -> world
handle :: Player -> Event -> world -> world
gameRate :: Double
gameRate = 1 / 6
instance Eq world => Eq (Log world) where
l1 == l2 =
committed l1 == committed l2
&& sortMessages (events l1) == sortMessages (events l2)
&& sort (latest l1) == sort (latest l2)
deriving instance Show world => Show (Log world)
-- Code from figure below
type TState world = (Timestamp, world)
data Log world = Log
{ committed :: TState world,
events :: [Message],
latest :: [(Player, Timestamp)]
}
initLog :: Game world => [Player] -> Log world
initLog ps = Log (0, start) [] ([(p, 0) | p <- ps])
addPing :: Game world => (Timestamp, Player) -> Log world -> Log world
addPing (t, p) log = recordActivity t p log
addEvent :: Game world => (Timestamp, Player, Event) -> Log world -> Log world
addEvent (t, p, e) log =
recordActivity t p (log {events = events log ++ [(t, p, e)]})
recordActivity :: Game world => Timestamp -> Player -> Log world -> Log world
recordActivity t p log
| t < t_old = error "Messages out of order"
| otherwise = advanceCommitted (log {latest = latest'})
where
latest' = (p, t) : delete (p, t_old) (latest log)
Just t_old = lookup p (latest log)
advanceCommitted :: Game world => Log world -> Log world
advanceCommitted log =
log {events = to_keep, committed = applyEvents to_commit (committed log)}
where
(to_commit, to_keep) =
partition (\(t, _, _) -> t < commitHorizon log) (events log)
commitHorizon :: Log world -> Timestamp
commitHorizon log = minimum [t | (p, t) <- latest log]
currentState :: Game world => Timestamp -> Log world -> world
currentState now log
| now < commitHorizon log = error "Cannot look into the past"
currentState now log = gameStep (now - t) world
where
(past_events, future_events) =
partition (\(t, _, _) -> t <= now) (events log)
(t, world) = applyEvents past_events (committed log)
applyEvents :: Game world => [Message] -> TState world -> TState world
applyEvents messages ts = foldl apply ts (sortMessages messages)
where
apply (t0, world) (t1, p, e) = (t1, handle p e (gameStep (t1 - t0) world))
sortMessages :: [Message] -> [Message]
sortMessages = sortOn (\(t, p, _) -> (t, p))
gameStep :: Game world => Double -> world -> world
gameStep dt world
| dt <= 0 = world
| dt > gameRate = gameStep (dt - gameRate) (step gameRate world)
| otherwise = step dt world
|
google/codeworld
|
codeworld-prediction/src/CodeWorld/Prediction/Paper.hs
|
apache-2.0
| 3,496 | 0 | 12 | 726 | 1,151 | 608 | 543 | 61 | 1 |
{-|
Module : Marvin.API.Table.DataType
Description : Basic attribute types. Both static and dynamic.
-}
module Marvin.API.Table.DataType where
-- | Dynamic attribute type.
data DataType = Binary | Nominal | Numeric | Natural deriving (Eq, Show)
-- | Typeclass for static attribute types.
class DataTypeClass a where
atRuntime :: a -> DataType
staticType :: a
-- | Static attribute type for nominal (categorical) data.
data Nominal = Nom deriving (Eq, Show)
-- | Static attribute type for numeric (continuous, floating point) data.
data Numeric = Num deriving (Eq, Show)
-- | Static attribute type for binary (boolean) data.
data Binary = Bin deriving (Eq, Show)
-- | Static attribute type for natural data (non-negative integers).
data Natural = Nat deriving (Eq, Show)
instance DataTypeClass Nominal where
atRuntime _ = Nominal
staticType = Nom
instance DataTypeClass Numeric where
atRuntime _ = Numeric
staticType = Num
instance DataTypeClass Binary where
atRuntime _ = Binary
staticType = Bin
instance DataTypeClass Natural where
atRuntime _ = Natural
staticType = Nat
|
gaborhermann/marvin
|
src/Marvin/API/Table/DataType.hs
|
apache-2.0
| 1,104 | 0 | 7 | 197 | 221 | 125 | 96 | 21 | 0 |
-- | Provisional grammar selection module.
module NLP.Skladnica.Walenty.Select
( select
, select'
) where
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import Data.Text (Text)
import qualified NLP.Partage.Tree.Other as O
import qualified NLP.Skladnica.Walenty.Grammar as G
-- | Select grammar ETs which have all their terminals
-- in the given set of terminals.
select
:: S.Set Text -- ^ Set of terminals to which restrict the grammar
-> S.Set G.ET -- ^ The grammar itself
-> S.Set G.ET -- ^ Restricted grammar
select sentSet gram = S.fromList
[ tree | tree <- S.toList gram
, terminalSet tree `S.isSubsetOf` sentSet ]
where terminalSet = S.fromList . O.project
-- | Generalized version of `select` which works on weighted grammars.
select'
:: S.Set Text -- ^ Set of terminals to which restrict the grammar
-> M.Map G.ET Double -- ^ The grammar itself
-> M.Map G.ET Double -- ^ Restricted grammar
select' sentSet gram = M.fromList
[ (et, w) | (et, w) <- M.toList gram
, terminalSet et `S.isSubsetOf` sentSet ]
where terminalSet = S.fromList . O.project
|
kawu/skladnica-with-walenty
|
src/NLP/Skladnica/Walenty/Select.hs
|
bsd-2-clause
| 1,182 | 0 | 10 | 281 | 275 | 158 | 117 | 24 | 1 |
{-# LANGUAGE RecordWildCards #-}
import qualified Graphics.UI.GLFW as GLFW
import Graphics.GL
import Graphics.GL.Freetype
import Data.Bits
import Control.Monad
import Linear
import SetupGLFW
import ShaderLoader
-- import Cube
import GlyphQuad
-------------------------------------------------------------
-- A test to make sure font rendering works
-------------------------------------------------------------
resX, resY :: Num a => a
resX = 1920
resY = 1080
main :: IO a
main = do
win <- setupGLFW "Freetype-GL" resX resY
-- Test Freetype
atlas <- newTextureAtlas 512 512 BitDepth1
-- font <- newFontFromFile atlas 100 "freetype-gl/fonts/SourceSansPro-Regular.ttf"
font <- newFontFromFile atlas 50 "freetype-gl/fonts/Vera.ttf"
let text = "And he said his name was BEAR-A..."
missed <- loadFontGlyphs font text
putStrLn $ "Missed: " ++ show missed
let textureID = TextureID (atlasTextureID atlas)
glyphQuadProg <- createShaderProgram "test/glyphQuad.vert" "test/glyphQuad.frag"
(quads, xOffset, _) <- foldM (\(quads, xOffset, maybeLastChar) thisChar -> do
glyph <- getGlyph font thisChar
kerning <- case maybeLastChar of
Nothing -> return 0
Just lastChar -> getGlyphKerning glyph lastChar
glyphMetrics <- getGlyphMetrics glyph
(newXOffset, glyphQuad) <- makeGlyphQuad glyphQuadProg textureID glyphMetrics (xOffset, 0) kerning
return (glyphQuad:quads, newXOffset, Just thisChar)
) ([], 0, Nothing) text
-- Scene rendering setup
-- cubeProg <- createShaderProgram "test/cube.vert" "test/cube.frag"
-- cube <- makeCube cubeProg
glClearColor 0 0.1 0.1 1
glEnable GL_DEPTH_TEST
forever $
mainLoop win quads (-xOffset/2)
mainLoop :: GLFW.Window -> [GlyphQuad] -> Float -> IO ()
mainLoop win glyphQuads xOffset = do
-- glGetErrors
-- Get mouse/keyboard/OS events from GLFW
GLFW.pollEvents
-- Clear the framebuffer
glClear ( GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT )
glEnable GL_BLEND
glBlendFunc GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA
-- Render our scene
let projection = perspective 45 (resX/resY) 0.01 1000
model = mkTransformation 1 (V3 (realToFrac xOffset) 0 (-4))
view = lookAt (V3 0 2 500) (V3 0 0 (-4)) (V3 0 1 0)
mvp = projection !*! view !*! model
(x,y,w,h) = (0,0,1920,1080)
glViewport x y w h
-- renderCube cube mvp
forM_ glyphQuads (\glyphQuad -> renderGlyphQuad glyphQuad mvp)
GLFW.swapBuffers win
|
lukexi/wboit
|
test/TestBasic.hs
|
bsd-2-clause
| 2,624 | 0 | 17 | 625 | 662 | 339 | 323 | 50 | 2 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QImage.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:22
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QImage (
QqqImage(..), QqImage(..)
,QqqImage_nf(..), QqImage_nf(..)
,allGray
,bytesPerLine
,QconvertToFormat(..), QconvertToFormat_nf(..)
,QcreateAlphaMask(..), QcreateAlphaMask_nf(..)
,dotsPerMeterX
,dotsPerMeterY
,QqImageFromData(..), QqImageFromData_nf(..)
,QinvertPixels(..)
,isGrayscale
,Qmirrored(..), Qmirrored_nf(..)
,numBytes
,numColors
,qpixel
,QpixelIndex(..), qpixelIndex
,QrgbSwapped(..), QrgbSwapped_nf(..)
,setDotsPerMeterX
,setDotsPerMeterY
,setNumColors
,QsetPixel(..), qsetPixel
,textKeys
,textLanguages
,QqImageTrueMatrix(..)
,Qvalid(..), qvalid
,qImage_delete, qImage_delete1
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QImage
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QImage ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QImage_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QImage_userMethod" qtc_QImage_userMethod :: Ptr (TQImage a) -> CInt -> IO ()
instance QuserMethod (QImageSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QImage_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QImage ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QImage_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QImage_userMethodVariant" qtc_QImage_userMethodVariant :: Ptr (TQImage a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QImageSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QImage_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqqImage x1 where
qqImage :: x1 -> IO (QImage ())
class QqImage x1 where
qImage :: x1 -> IO (QImage ())
instance QqImage (()) where
qImage ()
= withQImageResult $
qtc_QImage
foreign import ccall "qtc_QImage" qtc_QImage :: IO (Ptr (TQImage ()))
instance QqImage ((String)) where
qImage (x1)
= withQImageResult $
withCWString x1 $ \cstr_x1 ->
qtc_QImage2 cstr_x1
foreign import ccall "qtc_QImage2" qtc_QImage2 :: CWString -> IO (Ptr (TQImage ()))
instance QqImage ((QImage t1)) where
qImage (x1)
= withQImageResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage3 cobj_x1
foreign import ccall "qtc_QImage3" qtc_QImage3 :: Ptr (TQImage t1) -> IO (Ptr (TQImage ()))
instance QqImage ((String, String)) where
qImage (x1, x2)
= withQImageResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage4 cstr_x1 cstr_x2
foreign import ccall "qtc_QImage4" qtc_QImage4 :: CWString -> CWString -> IO (Ptr (TQImage ()))
instance QqqImage ((QSize t1, QImageFormat)) where
qqImage (x1, x2)
= withQImageResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage5 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QImage5" qtc_QImage5 :: Ptr (TQSize t1) -> CLong -> IO (Ptr (TQImage ()))
instance QqImage ((Size, QImageFormat)) where
qImage (x1, x2)
= withQImageResult $
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage6 csize_x1_w csize_x1_h (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QImage6" qtc_QImage6 :: CInt -> CInt -> CLong -> IO (Ptr (TQImage ()))
instance QqImage ((Int, Int, QImageFormat)) where
qImage (x1, x2, x3)
= withQImageResult $
qtc_QImage8 (toCInt x1) (toCInt x2) (toCLong $ qEnum_toInt x3)
foreign import ccall "qtc_QImage8" qtc_QImage8 :: CInt -> CInt -> CLong -> IO (Ptr (TQImage ()))
class QqqImage_nf x1 where
qqImage_nf :: x1 -> IO (QImage ())
class QqImage_nf x1 where
qImage_nf :: x1 -> IO (QImage ())
instance QqImage_nf (()) where
qImage_nf ()
= withObjectRefResult $
qtc_QImage
instance QqImage_nf ((String)) where
qImage_nf (x1)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
qtc_QImage2 cstr_x1
instance QqImage_nf ((QImage t1)) where
qImage_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage3 cobj_x1
instance QqImage_nf ((String, String)) where
qImage_nf (x1, x2)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage4 cstr_x1 cstr_x2
instance QqqImage_nf ((QSize t1, QImageFormat)) where
qqImage_nf (x1, x2)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage5 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QqImage_nf ((Size, QImageFormat)) where
qImage_nf (x1, x2)
= withObjectRefResult $
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage6 csize_x1_w csize_x1_h (toCLong $ qEnum_toInt x2)
instance QqImage_nf ((Int, Int, QImageFormat)) where
qImage_nf (x1, x2, x3)
= withObjectRefResult $
qtc_QImage8 (toCInt x1) (toCInt x2) (toCLong $ qEnum_toInt x3)
allGray :: QImage a -> (()) -> IO (Bool)
allGray x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_allGray cobj_x0
foreign import ccall "qtc_QImage_allGray" qtc_QImage_allGray :: Ptr (TQImage a) -> IO CBool
instance QalphaChannel (QImage ()) (()) (IO (QImage ())) where
alphaChannel x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_alphaChannel cobj_x0
foreign import ccall "qtc_QImage_alphaChannel" qtc_QImage_alphaChannel :: Ptr (TQImage a) -> IO (Ptr (TQImage ()))
instance QalphaChannel (QImageSc a) (()) (IO (QImage ())) where
alphaChannel x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_alphaChannel cobj_x0
instance QalphaChannel_nf (QImage ()) (()) (IO (QImage ())) where
alphaChannel_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_alphaChannel cobj_x0
instance QalphaChannel_nf (QImageSc a) (()) (IO (QImage ())) where
alphaChannel_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_alphaChannel cobj_x0
bytesPerLine :: QImage a -> (()) -> IO (Int)
bytesPerLine x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_bytesPerLine cobj_x0
foreign import ccall "qtc_QImage_bytesPerLine" qtc_QImage_bytesPerLine :: Ptr (TQImage a) -> IO CInt
instance QcacheKey (QImage a) (()) where
cacheKey x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_cacheKey cobj_x0
foreign import ccall "qtc_QImage_cacheKey" qtc_QImage_cacheKey :: Ptr (TQImage a) -> IO CLLong
instance Qcolor (QImage a) ((Int)) (IO (Int)) where
color x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_color cobj_x0 (toCInt x1)
foreign import ccall "qtc_QImage_color" qtc_QImage_color :: Ptr (TQImage a) -> CInt -> IO CUInt
class QconvertToFormat x0 x1 where
convertToFormat :: x0 -> x1 -> IO (QImage ())
class QconvertToFormat_nf x0 x1 where
convertToFormat_nf :: x0 -> x1 -> IO (QImage ())
instance QconvertToFormat (QImage ()) ((QImageFormat)) where
convertToFormat x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_convertToFormat cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QImage_convertToFormat" qtc_QImage_convertToFormat :: Ptr (TQImage a) -> CLong -> IO (Ptr (TQImage ()))
instance QconvertToFormat (QImageSc a) ((QImageFormat)) where
convertToFormat x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_convertToFormat cobj_x0 (toCLong $ qEnum_toInt x1)
instance QconvertToFormat_nf (QImage ()) ((QImageFormat)) where
convertToFormat_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_convertToFormat cobj_x0 (toCLong $ qEnum_toInt x1)
instance QconvertToFormat_nf (QImageSc a) ((QImageFormat)) where
convertToFormat_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_convertToFormat cobj_x0 (toCLong $ qEnum_toInt x1)
instance QconvertToFormat (QImage ()) ((QImageFormat, ImageConversionFlags)) where
convertToFormat x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_convertToFormat1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QImage_convertToFormat1" qtc_QImage_convertToFormat1 :: Ptr (TQImage a) -> CLong -> CLong -> IO (Ptr (TQImage ()))
instance QconvertToFormat (QImageSc a) ((QImageFormat, ImageConversionFlags)) where
convertToFormat x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_convertToFormat1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
instance QconvertToFormat_nf (QImage ()) ((QImageFormat, ImageConversionFlags)) where
convertToFormat_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_convertToFormat1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
instance QconvertToFormat_nf (QImageSc a) ((QImageFormat, ImageConversionFlags)) where
convertToFormat_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_convertToFormat1 cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
instance Qcopy (QImage ()) (()) (IO (QImage ())) where
copy x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_copy cobj_x0
foreign import ccall "qtc_QImage_copy" qtc_QImage_copy :: Ptr (TQImage a) -> IO (Ptr (TQImage ()))
instance Qcopy (QImageSc a) (()) (IO (QImage ())) where
copy x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_copy cobj_x0
instance Qcopy_nf (QImage ()) (()) (IO (QImage ())) where
copy_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_copy cobj_x0
instance Qcopy_nf (QImageSc a) (()) (IO (QImage ())) where
copy_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_copy cobj_x0
instance Qcopy (QImage ()) ((Int, Int, Int, Int)) (IO (QImage ())) where
copy x0 (x1, x2, x3, x4)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_copy2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QImage_copy2" qtc_QImage_copy2 :: Ptr (TQImage a) -> CInt -> CInt -> CInt -> CInt -> IO (Ptr (TQImage ()))
instance Qcopy (QImageSc a) ((Int, Int, Int, Int)) (IO (QImage ())) where
copy x0 (x1, x2, x3, x4)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_copy2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qcopy_nf (QImage ()) ((Int, Int, Int, Int)) (IO (QImage ())) where
copy_nf x0 (x1, x2, x3, x4)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_copy2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qcopy_nf (QImageSc a) ((Int, Int, Int, Int)) (IO (QImage ())) where
copy_nf x0 (x1, x2, x3, x4)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_copy2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qqcopy (QImage ()) ((QRect t1)) (IO (QImage ())) where
qcopy x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_copy1 cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_copy1" qtc_QImage_copy1 :: Ptr (TQImage a) -> Ptr (TQRect t1) -> IO (Ptr (TQImage ()))
instance Qqcopy (QImageSc a) ((QRect t1)) (IO (QImage ())) where
qcopy x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_copy1 cobj_x0 cobj_x1
instance Qqcopy_nf (QImage ()) ((QRect t1)) (IO (QImage ())) where
qcopy_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_copy1 cobj_x0 cobj_x1
instance Qqcopy_nf (QImageSc a) ((QRect t1)) (IO (QImage ())) where
qcopy_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_copy1 cobj_x0 cobj_x1
instance Qcopy (QImage ()) ((Rect)) (IO (QImage ())) where
copy x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QImage_copy1_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QImage_copy1_qth" qtc_QImage_copy1_qth :: Ptr (TQImage a) -> CInt -> CInt -> CInt -> CInt -> IO (Ptr (TQImage ()))
instance Qcopy (QImageSc a) ((Rect)) (IO (QImage ())) where
copy x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QImage_copy1_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance Qcopy_nf (QImage ()) ((Rect)) (IO (QImage ())) where
copy_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QImage_copy1_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance Qcopy_nf (QImageSc a) ((Rect)) (IO (QImage ())) where
copy_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QImage_copy1_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
class QcreateAlphaMask x0 x1 where
createAlphaMask :: x0 -> x1 -> IO (QImage ())
class QcreateAlphaMask_nf x0 x1 where
createAlphaMask_nf :: x0 -> x1 -> IO (QImage ())
instance QcreateAlphaMask (QImage ()) (()) where
createAlphaMask x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createAlphaMask cobj_x0
foreign import ccall "qtc_QImage_createAlphaMask" qtc_QImage_createAlphaMask :: Ptr (TQImage a) -> IO (Ptr (TQImage ()))
instance QcreateAlphaMask (QImageSc a) (()) where
createAlphaMask x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createAlphaMask cobj_x0
instance QcreateAlphaMask_nf (QImage ()) (()) where
createAlphaMask_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createAlphaMask cobj_x0
instance QcreateAlphaMask_nf (QImageSc a) (()) where
createAlphaMask_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createAlphaMask cobj_x0
instance QcreateAlphaMask (QImage ()) ((ImageConversionFlags)) where
createAlphaMask x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createAlphaMask1 cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QImage_createAlphaMask1" qtc_QImage_createAlphaMask1 :: Ptr (TQImage a) -> CLong -> IO (Ptr (TQImage ()))
instance QcreateAlphaMask (QImageSc a) ((ImageConversionFlags)) where
createAlphaMask x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createAlphaMask1 cobj_x0 (toCLong $ qFlags_toInt x1)
instance QcreateAlphaMask_nf (QImage ()) ((ImageConversionFlags)) where
createAlphaMask_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createAlphaMask1 cobj_x0 (toCLong $ qFlags_toInt x1)
instance QcreateAlphaMask_nf (QImageSc a) ((ImageConversionFlags)) where
createAlphaMask_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createAlphaMask1 cobj_x0 (toCLong $ qFlags_toInt x1)
instance QcreateHeuristicMask (QImage ()) (()) (IO (QImage ())) where
createHeuristicMask x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createHeuristicMask cobj_x0
foreign import ccall "qtc_QImage_createHeuristicMask" qtc_QImage_createHeuristicMask :: Ptr (TQImage a) -> IO (Ptr (TQImage ()))
instance QcreateHeuristicMask (QImageSc a) (()) (IO (QImage ())) where
createHeuristicMask x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createHeuristicMask cobj_x0
instance QcreateHeuristicMask_nf (QImage ()) (()) (IO (QImage ())) where
createHeuristicMask_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createHeuristicMask cobj_x0
instance QcreateHeuristicMask_nf (QImageSc a) (()) (IO (QImage ())) where
createHeuristicMask_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createHeuristicMask cobj_x0
instance QcreateHeuristicMask (QImage ()) ((Bool)) (IO (QImage ())) where
createHeuristicMask x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createHeuristicMask1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QImage_createHeuristicMask1" qtc_QImage_createHeuristicMask1 :: Ptr (TQImage a) -> CBool -> IO (Ptr (TQImage ()))
instance QcreateHeuristicMask (QImageSc a) ((Bool)) (IO (QImage ())) where
createHeuristicMask x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createHeuristicMask1 cobj_x0 (toCBool x1)
instance QcreateHeuristicMask_nf (QImage ()) ((Bool)) (IO (QImage ())) where
createHeuristicMask_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createHeuristicMask1 cobj_x0 (toCBool x1)
instance QcreateHeuristicMask_nf (QImageSc a) ((Bool)) (IO (QImage ())) where
createHeuristicMask_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createHeuristicMask1 cobj_x0 (toCBool x1)
instance QcreateMaskFromColor (QImage ()) ((Int)) (IO (QImage ())) where
createMaskFromColor x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createMaskFromColor cobj_x0 (toCUInt x1)
foreign import ccall "qtc_QImage_createMaskFromColor" qtc_QImage_createMaskFromColor :: Ptr (TQImage a) -> CUInt -> IO (Ptr (TQImage ()))
instance QcreateMaskFromColor (QImageSc a) ((Int)) (IO (QImage ())) where
createMaskFromColor x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createMaskFromColor cobj_x0 (toCUInt x1)
instance QcreateMaskFromColor_nf (QImage ()) ((Int)) (IO (QImage ())) where
createMaskFromColor_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createMaskFromColor cobj_x0 (toCUInt x1)
instance QcreateMaskFromColor_nf (QImageSc a) ((Int)) (IO (QImage ())) where
createMaskFromColor_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createMaskFromColor cobj_x0 (toCUInt x1)
instance QcreateMaskFromColor (QImage ()) ((Int, MaskMode)) (IO (QImage ())) where
createMaskFromColor x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createMaskFromColor1 cobj_x0 (toCUInt x1) (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QImage_createMaskFromColor1" qtc_QImage_createMaskFromColor1 :: Ptr (TQImage a) -> CUInt -> CLong -> IO (Ptr (TQImage ()))
instance QcreateMaskFromColor (QImageSc a) ((Int, MaskMode)) (IO (QImage ())) where
createMaskFromColor x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createMaskFromColor1 cobj_x0 (toCUInt x1) (toCLong $ qEnum_toInt x2)
instance QcreateMaskFromColor_nf (QImage ()) ((Int, MaskMode)) (IO (QImage ())) where
createMaskFromColor_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createMaskFromColor1 cobj_x0 (toCUInt x1) (toCLong $ qEnum_toInt x2)
instance QcreateMaskFromColor_nf (QImageSc a) ((Int, MaskMode)) (IO (QImage ())) where
createMaskFromColor_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_createMaskFromColor1 cobj_x0 (toCUInt x1) (toCLong $ qEnum_toInt x2)
instance Qdepth (QImage a) (()) (IO (Int)) where
depth x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_depth cobj_x0
foreign import ccall "qtc_QImage_depth" qtc_QImage_depth :: Ptr (TQImage a) -> IO CInt
instance Qdetach (QImage a) (()) where
detach x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_detach cobj_x0
foreign import ccall "qtc_QImage_detach" qtc_QImage_detach :: Ptr (TQImage a) -> IO ()
instance QdevType (QImage ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_devType_h cobj_x0
foreign import ccall "qtc_QImage_devType_h" qtc_QImage_devType_h :: Ptr (TQImage a) -> IO CInt
instance QdevType (QImageSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_devType_h cobj_x0
dotsPerMeterX :: QImage a -> (()) -> IO (Int)
dotsPerMeterX x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_dotsPerMeterX cobj_x0
foreign import ccall "qtc_QImage_dotsPerMeterX" qtc_QImage_dotsPerMeterX :: Ptr (TQImage a) -> IO CInt
dotsPerMeterY :: QImage a -> (()) -> IO (Int)
dotsPerMeterY x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_dotsPerMeterY cobj_x0
foreign import ccall "qtc_QImage_dotsPerMeterY" qtc_QImage_dotsPerMeterY :: Ptr (TQImage a) -> IO CInt
instance Qfill (QImage a) ((Int)) where
fill x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_fill cobj_x0 (toCUInt x1)
foreign import ccall "qtc_QImage_fill" qtc_QImage_fill :: Ptr (TQImage a) -> CUInt -> IO ()
instance Qformat (QImage a) (()) (IO (QImageFormat)) where
format x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_format cobj_x0
foreign import ccall "qtc_QImage_format" qtc_QImage_format :: Ptr (TQImage a) -> IO CLong
class QqImageFromData x1 where
qImageFromData :: x1 -> IO (QImage ())
class QqImageFromData_nf x1 where
qImageFromData_nf :: x1 -> IO (QImage ())
instance QqImageFromData ((String)) where
qImageFromData (x1)
= withQImageResult $
withCWString x1 $ \cstr_x1 ->
qtc_QImage_fromData cstr_x1
foreign import ccall "qtc_QImage_fromData" qtc_QImage_fromData :: CWString -> IO (Ptr (TQImage ()))
instance QqImageFromData_nf ((String)) where
qImageFromData_nf (x1)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
qtc_QImage_fromData cstr_x1
instance QqImageFromData ((String, String)) where
qImageFromData (x1, x2)
= withQImageResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_fromData1 cstr_x1 cstr_x2
foreign import ccall "qtc_QImage_fromData1" qtc_QImage_fromData1 :: CWString -> CWString -> IO (Ptr (TQImage ()))
instance QqImageFromData_nf ((String, String)) where
qImageFromData_nf (x1, x2)
= withObjectRefResult $
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_fromData1 cstr_x1 cstr_x2
instance QhasAlphaChannel (QImage a) (()) where
hasAlphaChannel x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_hasAlphaChannel cobj_x0
foreign import ccall "qtc_QImage_hasAlphaChannel" qtc_QImage_hasAlphaChannel :: Ptr (TQImage a) -> IO CBool
instance Qqheight (QImage a) (()) (IO (Int)) where
qheight x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_height cobj_x0
foreign import ccall "qtc_QImage_height" qtc_QImage_height :: Ptr (TQImage a) -> IO CInt
class QinvertPixels x1 where
invertPixels :: QImage a -> x1 -> IO ()
instance QinvertPixels (()) where
invertPixels x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_invertPixels cobj_x0
foreign import ccall "qtc_QImage_invertPixels" qtc_QImage_invertPixels :: Ptr (TQImage a) -> IO ()
instance QinvertPixels ((InvertMode)) where
invertPixels x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_invertPixels1 cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QImage_invertPixels1" qtc_QImage_invertPixels1 :: Ptr (TQImage a) -> CLong -> IO ()
instance QisDetached (QImage a) (()) where
isDetached x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_isDetached cobj_x0
foreign import ccall "qtc_QImage_isDetached" qtc_QImage_isDetached :: Ptr (TQImage a) -> IO CBool
isGrayscale :: QImage a -> (()) -> IO (Bool)
isGrayscale x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_isGrayscale cobj_x0
foreign import ccall "qtc_QImage_isGrayscale" qtc_QImage_isGrayscale :: Ptr (TQImage a) -> IO CBool
instance QqisNull (QImage a) (()) where
qisNull x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_isNull cobj_x0
foreign import ccall "qtc_QImage_isNull" qtc_QImage_isNull :: Ptr (TQImage a) -> IO CBool
instance Qload (QImage a) ((QIODevice t1, String)) (IO (Bool)) where
load x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_load2 cobj_x0 cobj_x1 cstr_x2
foreign import ccall "qtc_QImage_load2" qtc_QImage_load2 :: Ptr (TQImage a) -> Ptr (TQIODevice t1) -> CWString -> IO CBool
instance Qload (QImage a) ((String)) (IO (Bool)) where
load x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QImage_load cobj_x0 cstr_x1
foreign import ccall "qtc_QImage_load" qtc_QImage_load :: Ptr (TQImage a) -> CWString -> IO CBool
instance Qload (QImage a) ((String, String)) (IO (Bool)) where
load x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_load1 cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QImage_load1" qtc_QImage_load1 :: Ptr (TQImage a) -> CWString -> CWString -> IO CBool
instance QloadFromData (QImage a) ((String)) where
loadFromData x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QImage_loadFromData cobj_x0 cstr_x1
foreign import ccall "qtc_QImage_loadFromData" qtc_QImage_loadFromData :: Ptr (TQImage a) -> CWString -> IO CBool
instance QloadFromData (QImage a) ((String, String)) where
loadFromData x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_loadFromData1 cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QImage_loadFromData1" qtc_QImage_loadFromData1 :: Ptr (TQImage a) -> CWString -> CWString -> IO CBool
instance Qmetric (QImage ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QImage_metric" qtc_QImage_metric :: Ptr (TQImage a) -> CLong -> IO CInt
instance Qmetric (QImageSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_metric cobj_x0 (toCLong $ qEnum_toInt x1)
class Qmirrored x0 x1 where
mirrored :: x0 -> x1 -> IO (QImage ())
class Qmirrored_nf x0 x1 where
mirrored_nf :: x0 -> x1 -> IO (QImage ())
instance Qmirrored (QImage ()) (()) where
mirrored x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored cobj_x0
foreign import ccall "qtc_QImage_mirrored" qtc_QImage_mirrored :: Ptr (TQImage a) -> IO (Ptr (TQImage ()))
instance Qmirrored (QImageSc a) (()) where
mirrored x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored cobj_x0
instance Qmirrored_nf (QImage ()) (()) where
mirrored_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored cobj_x0
instance Qmirrored_nf (QImageSc a) (()) where
mirrored_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored cobj_x0
instance Qmirrored (QImage ()) ((Bool)) where
mirrored x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QImage_mirrored1" qtc_QImage_mirrored1 :: Ptr (TQImage a) -> CBool -> IO (Ptr (TQImage ()))
instance Qmirrored (QImageSc a) ((Bool)) where
mirrored x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored1 cobj_x0 (toCBool x1)
instance Qmirrored_nf (QImage ()) ((Bool)) where
mirrored_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored1 cobj_x0 (toCBool x1)
instance Qmirrored_nf (QImageSc a) ((Bool)) where
mirrored_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored1 cobj_x0 (toCBool x1)
instance Qmirrored (QImage ()) ((Bool, Bool)) where
mirrored x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QImage_mirrored2" qtc_QImage_mirrored2 :: Ptr (TQImage a) -> CBool -> CBool -> IO (Ptr (TQImage ()))
instance Qmirrored (QImageSc a) ((Bool, Bool)) where
mirrored x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored2 cobj_x0 (toCBool x1) (toCBool x2)
instance Qmirrored_nf (QImage ()) ((Bool, Bool)) where
mirrored_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored2 cobj_x0 (toCBool x1) (toCBool x2)
instance Qmirrored_nf (QImageSc a) ((Bool, Bool)) where
mirrored_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_mirrored2 cobj_x0 (toCBool x1) (toCBool x2)
numBytes :: QImage a -> (()) -> IO (Int)
numBytes x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_numBytes cobj_x0
foreign import ccall "qtc_QImage_numBytes" qtc_QImage_numBytes :: Ptr (TQImage a) -> IO CInt
numColors :: QImage a -> (()) -> IO (Int)
numColors x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_numColors cobj_x0
foreign import ccall "qtc_QImage_numColors" qtc_QImage_numColors :: Ptr (TQImage a) -> IO CInt
instance Qoffset (QImage a) (()) (IO (Point)) where
offset x0 ()
= withPointResult $ \cpoint_ret_x cpoint_ret_y ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_offset_qth cobj_x0 cpoint_ret_x cpoint_ret_y
foreign import ccall "qtc_QImage_offset_qth" qtc_QImage_offset_qth :: Ptr (TQImage a) -> Ptr CInt -> Ptr CInt -> IO ()
instance Qqoffset (QImage a) (()) (IO (QPoint ())) where
qoffset x0 ()
= withQPointResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_offset cobj_x0
foreign import ccall "qtc_QImage_offset" qtc_QImage_offset :: Ptr (TQImage a) -> IO (Ptr (TQPoint ()))
instance QpaintEngine (QImage ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_paintEngine_h cobj_x0
foreign import ccall "qtc_QImage_paintEngine_h" qtc_QImage_paintEngine_h :: Ptr (TQImage a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QImageSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_paintEngine_h cobj_x0
instance Qpixel (QImage a) ((Int, Int)) where
pixel x0 (x1, x2)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_pixel1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QImage_pixel1" qtc_QImage_pixel1 :: Ptr (TQImage a) -> CInt -> CInt -> IO CUInt
instance Qpixel (QImage a) ((Point)) where
pixel x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QImage_pixel_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QImage_pixel_qth" qtc_QImage_pixel_qth :: Ptr (TQImage a) -> CInt -> CInt -> IO CUInt
qpixel :: QImage a -> ((QPoint t1)) -> IO (Int)
qpixel x0 (x1)
= withUnsignedIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_pixel cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_pixel" qtc_QImage_pixel :: Ptr (TQImage a) -> Ptr (TQPoint t1) -> IO CUInt
class QpixelIndex x1 where
pixelIndex :: QImage a -> x1 -> IO (Int)
instance QpixelIndex ((Int, Int)) where
pixelIndex x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_pixelIndex1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QImage_pixelIndex1" qtc_QImage_pixelIndex1 :: Ptr (TQImage a) -> CInt -> CInt -> IO CInt
instance QpixelIndex ((Point)) where
pixelIndex x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QImage_pixelIndex_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QImage_pixelIndex_qth" qtc_QImage_pixelIndex_qth :: Ptr (TQImage a) -> CInt -> CInt -> IO CInt
qpixelIndex :: QImage a -> ((QPoint t1)) -> IO (Int)
qpixelIndex x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_pixelIndex cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_pixelIndex" qtc_QImage_pixelIndex :: Ptr (TQImage a) -> Ptr (TQPoint t1) -> IO CInt
instance Qqqrect (QImage a) (()) (IO (QRect ())) where
qqrect x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_rect cobj_x0
foreign import ccall "qtc_QImage_rect" qtc_QImage_rect :: Ptr (TQImage a) -> IO (Ptr (TQRect ()))
instance Qqrect (QImage a) (()) (IO (Rect)) where
qrect x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_rect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QImage_rect_qth" qtc_QImage_rect_qth :: Ptr (TQImage a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
class QrgbSwapped x0 x1 where
rgbSwapped :: x0 -> x1 -> IO (QImage ())
class QrgbSwapped_nf x0 x1 where
rgbSwapped_nf :: x0 -> x1 -> IO (QImage ())
instance QrgbSwapped (QImage ()) (()) where
rgbSwapped x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_rgbSwapped cobj_x0
foreign import ccall "qtc_QImage_rgbSwapped" qtc_QImage_rgbSwapped :: Ptr (TQImage a) -> IO (Ptr (TQImage ()))
instance QrgbSwapped (QImageSc a) (()) where
rgbSwapped x0 ()
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_rgbSwapped cobj_x0
instance QrgbSwapped_nf (QImage ()) (()) where
rgbSwapped_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_rgbSwapped cobj_x0
instance QrgbSwapped_nf (QImageSc a) (()) where
rgbSwapped_nf x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_rgbSwapped cobj_x0
instance Qsave (QImage a) ((QIODevice t1)) (IO (Bool)) where
save x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_save1 cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_save1" qtc_QImage_save1 :: Ptr (TQImage a) -> Ptr (TQIODevice t1) -> IO CBool
instance Qsave (QImage a) ((QIODevice t1, String)) (IO (Bool)) where
save x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_save3 cobj_x0 cobj_x1 cstr_x2
foreign import ccall "qtc_QImage_save3" qtc_QImage_save3 :: Ptr (TQImage a) -> Ptr (TQIODevice t1) -> CWString -> IO CBool
instance Qsave (QImage a) ((QIODevice t1, String, Int)) (IO (Bool)) where
save x0 (x1, x2, x3)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_save4 cobj_x0 cobj_x1 cstr_x2 (toCInt x3)
foreign import ccall "qtc_QImage_save4" qtc_QImage_save4 :: Ptr (TQImage a) -> Ptr (TQIODevice t1) -> CWString -> CInt -> IO CBool
instance Qsave (QImage a) ((String)) (IO (Bool)) where
save x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QImage_save cobj_x0 cstr_x1
foreign import ccall "qtc_QImage_save" qtc_QImage_save :: Ptr (TQImage a) -> CWString -> IO CBool
instance Qsave (QImage a) ((String, String)) (IO (Bool)) where
save x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_save2 cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QImage_save2" qtc_QImage_save2 :: Ptr (TQImage a) -> CWString -> CWString -> IO CBool
instance Qsave (QImage a) ((String, String, Int)) (IO (Bool)) where
save x0 (x1, x2, x3)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_save5 cobj_x0 cstr_x1 cstr_x2 (toCInt x3)
foreign import ccall "qtc_QImage_save5" qtc_QImage_save5 :: Ptr (TQImage a) -> CWString -> CWString -> CInt -> IO CBool
instance Qscaled (QImage ()) ((Int, Int)) (IO (QImage ())) where
scaled x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled2 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QImage_scaled2" qtc_QImage_scaled2 :: Ptr (TQImage a) -> CInt -> CInt -> IO (Ptr (TQImage ()))
instance Qscaled (QImageSc a) ((Int, Int)) (IO (QImage ())) where
scaled x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled2 cobj_x0 (toCInt x1) (toCInt x2)
instance Qscaled_nf (QImage ()) ((Int, Int)) (IO (QImage ())) where
scaled_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled2 cobj_x0 (toCInt x1) (toCInt x2)
instance Qscaled_nf (QImageSc a) ((Int, Int)) (IO (QImage ())) where
scaled_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled2 cobj_x0 (toCInt x1) (toCInt x2)
instance Qscaled (QImage ()) ((Int, Int, AspectRatioMode)) (IO (QImage ())) where
scaled x0 (x1, x2, x3)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled4 cobj_x0 (toCInt x1) (toCInt x2) (toCLong $ qEnum_toInt x3)
foreign import ccall "qtc_QImage_scaled4" qtc_QImage_scaled4 :: Ptr (TQImage a) -> CInt -> CInt -> CLong -> IO (Ptr (TQImage ()))
instance Qscaled (QImageSc a) ((Int, Int, AspectRatioMode)) (IO (QImage ())) where
scaled x0 (x1, x2, x3)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled4 cobj_x0 (toCInt x1) (toCInt x2) (toCLong $ qEnum_toInt x3)
instance Qscaled_nf (QImage ()) ((Int, Int, AspectRatioMode)) (IO (QImage ())) where
scaled_nf x0 (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled4 cobj_x0 (toCInt x1) (toCInt x2) (toCLong $ qEnum_toInt x3)
instance Qscaled_nf (QImageSc a) ((Int, Int, AspectRatioMode)) (IO (QImage ())) where
scaled_nf x0 (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled4 cobj_x0 (toCInt x1) (toCInt x2) (toCLong $ qEnum_toInt x3)
instance Qscaled (QImage ()) ((Int, Int, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
scaled x0 (x1, x2, x3, x4)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled5 cobj_x0 (toCInt x1) (toCInt x2) (toCLong $ qEnum_toInt x3) (toCLong $ qEnum_toInt x4)
foreign import ccall "qtc_QImage_scaled5" qtc_QImage_scaled5 :: Ptr (TQImage a) -> CInt -> CInt -> CLong -> CLong -> IO (Ptr (TQImage ()))
instance Qscaled (QImageSc a) ((Int, Int, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
scaled x0 (x1, x2, x3, x4)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled5 cobj_x0 (toCInt x1) (toCInt x2) (toCLong $ qEnum_toInt x3) (toCLong $ qEnum_toInt x4)
instance Qscaled_nf (QImage ()) ((Int, Int, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
scaled_nf x0 (x1, x2, x3, x4)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled5 cobj_x0 (toCInt x1) (toCInt x2) (toCLong $ qEnum_toInt x3) (toCLong $ qEnum_toInt x4)
instance Qscaled_nf (QImageSc a) ((Int, Int, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
scaled_nf x0 (x1, x2, x3, x4)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaled5 cobj_x0 (toCInt x1) (toCInt x2) (toCLong $ qEnum_toInt x3) (toCLong $ qEnum_toInt x4)
instance Qqscaled (QImage ()) ((QSize t1)) (IO (QImage ())) where
qscaled x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_scaled" qtc_QImage_scaled :: Ptr (TQImage a) -> Ptr (TQSize t1) -> IO (Ptr (TQImage ()))
instance Qqscaled (QImageSc a) ((QSize t1)) (IO (QImage ())) where
qscaled x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled cobj_x0 cobj_x1
instance Qqscaled_nf (QImage ()) ((QSize t1)) (IO (QImage ())) where
qscaled_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled cobj_x0 cobj_x1
instance Qqscaled_nf (QImageSc a) ((QSize t1)) (IO (QImage ())) where
qscaled_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled cobj_x0 cobj_x1
instance Qqscaled (QImage ()) ((QSize t1, AspectRatioMode)) (IO (QImage ())) where
qscaled x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QImage_scaled1" qtc_QImage_scaled1 :: Ptr (TQImage a) -> Ptr (TQSize t1) -> CLong -> IO (Ptr (TQImage ()))
instance Qqscaled (QImageSc a) ((QSize t1, AspectRatioMode)) (IO (QImage ())) where
qscaled x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance Qqscaled_nf (QImage ()) ((QSize t1, AspectRatioMode)) (IO (QImage ())) where
qscaled_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance Qqscaled_nf (QImageSc a) ((QSize t1, AspectRatioMode)) (IO (QImage ())) where
qscaled_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance Qqscaled (QImage ()) ((QSize t1, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
qscaled x0 (x1, x2, x3)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled3 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) (toCLong $ qEnum_toInt x3)
foreign import ccall "qtc_QImage_scaled3" qtc_QImage_scaled3 :: Ptr (TQImage a) -> Ptr (TQSize t1) -> CLong -> CLong -> IO (Ptr (TQImage ()))
instance Qqscaled (QImageSc a) ((QSize t1, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
qscaled x0 (x1, x2, x3)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled3 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) (toCLong $ qEnum_toInt x3)
instance Qqscaled_nf (QImage ()) ((QSize t1, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
qscaled_nf x0 (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled3 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) (toCLong $ qEnum_toInt x3)
instance Qqscaled_nf (QImageSc a) ((QSize t1, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
qscaled_nf x0 (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_scaled3 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) (toCLong $ qEnum_toInt x3)
instance Qscaled (QImage ()) ((Size)) (IO (QImage ())) where
scaled x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QImage_scaled_qth" qtc_QImage_scaled_qth :: Ptr (TQImage a) -> CInt -> CInt -> IO (Ptr (TQImage ()))
instance Qscaled (QImageSc a) ((Size)) (IO (QImage ())) where
scaled x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled_qth cobj_x0 csize_x1_w csize_x1_h
instance Qscaled_nf (QImage ()) ((Size)) (IO (QImage ())) where
scaled_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled_qth cobj_x0 csize_x1_w csize_x1_h
instance Qscaled_nf (QImageSc a) ((Size)) (IO (QImage ())) where
scaled_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled_qth cobj_x0 csize_x1_w csize_x1_h
instance Qscaled (QImage ()) ((Size, AspectRatioMode)) (IO (QImage ())) where
scaled x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled1_qth cobj_x0 csize_x1_w csize_x1_h (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QImage_scaled1_qth" qtc_QImage_scaled1_qth :: Ptr (TQImage a) -> CInt -> CInt -> CLong -> IO (Ptr (TQImage ()))
instance Qscaled (QImageSc a) ((Size, AspectRatioMode)) (IO (QImage ())) where
scaled x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled1_qth cobj_x0 csize_x1_w csize_x1_h (toCLong $ qEnum_toInt x2)
instance Qscaled_nf (QImage ()) ((Size, AspectRatioMode)) (IO (QImage ())) where
scaled_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled1_qth cobj_x0 csize_x1_w csize_x1_h (toCLong $ qEnum_toInt x2)
instance Qscaled_nf (QImageSc a) ((Size, AspectRatioMode)) (IO (QImage ())) where
scaled_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled1_qth cobj_x0 csize_x1_w csize_x1_h (toCLong $ qEnum_toInt x2)
instance Qscaled (QImage ()) ((Size, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
scaled x0 (x1, x2, x3)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled3_qth cobj_x0 csize_x1_w csize_x1_h (toCLong $ qEnum_toInt x2) (toCLong $ qEnum_toInt x3)
foreign import ccall "qtc_QImage_scaled3_qth" qtc_QImage_scaled3_qth :: Ptr (TQImage a) -> CInt -> CInt -> CLong -> CLong -> IO (Ptr (TQImage ()))
instance Qscaled (QImageSc a) ((Size, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
scaled x0 (x1, x2, x3)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled3_qth cobj_x0 csize_x1_w csize_x1_h (toCLong $ qEnum_toInt x2) (toCLong $ qEnum_toInt x3)
instance Qscaled_nf (QImage ()) ((Size, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
scaled_nf x0 (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled3_qth cobj_x0 csize_x1_w csize_x1_h (toCLong $ qEnum_toInt x2) (toCLong $ qEnum_toInt x3)
instance Qscaled_nf (QImageSc a) ((Size, AspectRatioMode, TransformationMode)) (IO (QImage ())) where
scaled_nf x0 (x1, x2, x3)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QImage_scaled3_qth cobj_x0 csize_x1_w csize_x1_h (toCLong $ qEnum_toInt x2) (toCLong $ qEnum_toInt x3)
instance QscaledToHeight (QImage ()) ((Int)) (IO (QImage ())) where
scaledToHeight x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToHeight cobj_x0 (toCInt x1)
foreign import ccall "qtc_QImage_scaledToHeight" qtc_QImage_scaledToHeight :: Ptr (TQImage a) -> CInt -> IO (Ptr (TQImage ()))
instance QscaledToHeight (QImageSc a) ((Int)) (IO (QImage ())) where
scaledToHeight x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToHeight cobj_x0 (toCInt x1)
instance QscaledToHeight_nf (QImage ()) ((Int)) (IO (QImage ())) where
scaledToHeight_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToHeight cobj_x0 (toCInt x1)
instance QscaledToHeight_nf (QImageSc a) ((Int)) (IO (QImage ())) where
scaledToHeight_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToHeight cobj_x0 (toCInt x1)
instance QscaledToHeight (QImage ()) ((Int, TransformationMode)) (IO (QImage ())) where
scaledToHeight x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToHeight1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QImage_scaledToHeight1" qtc_QImage_scaledToHeight1 :: Ptr (TQImage a) -> CInt -> CLong -> IO (Ptr (TQImage ()))
instance QscaledToHeight (QImageSc a) ((Int, TransformationMode)) (IO (QImage ())) where
scaledToHeight x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToHeight1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
instance QscaledToHeight_nf (QImage ()) ((Int, TransformationMode)) (IO (QImage ())) where
scaledToHeight_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToHeight1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
instance QscaledToHeight_nf (QImageSc a) ((Int, TransformationMode)) (IO (QImage ())) where
scaledToHeight_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToHeight1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
instance QscaledToWidth (QImage ()) ((Int)) (IO (QImage ())) where
scaledToWidth x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QImage_scaledToWidth" qtc_QImage_scaledToWidth :: Ptr (TQImage a) -> CInt -> IO (Ptr (TQImage ()))
instance QscaledToWidth (QImageSc a) ((Int)) (IO (QImage ())) where
scaledToWidth x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToWidth cobj_x0 (toCInt x1)
instance QscaledToWidth_nf (QImage ()) ((Int)) (IO (QImage ())) where
scaledToWidth_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToWidth cobj_x0 (toCInt x1)
instance QscaledToWidth_nf (QImageSc a) ((Int)) (IO (QImage ())) where
scaledToWidth_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToWidth cobj_x0 (toCInt x1)
instance QscaledToWidth (QImage ()) ((Int, TransformationMode)) (IO (QImage ())) where
scaledToWidth x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToWidth1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QImage_scaledToWidth1" qtc_QImage_scaledToWidth1 :: Ptr (TQImage a) -> CInt -> CLong -> IO (Ptr (TQImage ()))
instance QscaledToWidth (QImageSc a) ((Int, TransformationMode)) (IO (QImage ())) where
scaledToWidth x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToWidth1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
instance QscaledToWidth_nf (QImage ()) ((Int, TransformationMode)) (IO (QImage ())) where
scaledToWidth_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToWidth1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
instance QscaledToWidth_nf (QImageSc a) ((Int, TransformationMode)) (IO (QImage ())) where
scaledToWidth_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_scaledToWidth1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2)
instance QserialNumber (QImage a) (()) where
serialNumber x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_serialNumber cobj_x0
foreign import ccall "qtc_QImage_serialNumber" qtc_QImage_serialNumber :: Ptr (TQImage a) -> IO CInt
instance QsetAlphaChannel (QImage a) ((QImage t1)) where
setAlphaChannel x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_setAlphaChannel cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_setAlphaChannel" qtc_QImage_setAlphaChannel :: Ptr (TQImage a) -> Ptr (TQImage t1) -> IO ()
instance QsetColor (QImage a) ((Int, Int)) where
setColor x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_setColor cobj_x0 (toCInt x1) (toCUInt x2)
foreign import ccall "qtc_QImage_setColor" qtc_QImage_setColor :: Ptr (TQImage a) -> CInt -> CUInt -> IO ()
setDotsPerMeterX :: QImage a -> ((Int)) -> IO ()
setDotsPerMeterX x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_setDotsPerMeterX cobj_x0 (toCInt x1)
foreign import ccall "qtc_QImage_setDotsPerMeterX" qtc_QImage_setDotsPerMeterX :: Ptr (TQImage a) -> CInt -> IO ()
setDotsPerMeterY :: QImage a -> ((Int)) -> IO ()
setDotsPerMeterY x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_setDotsPerMeterY cobj_x0 (toCInt x1)
foreign import ccall "qtc_QImage_setDotsPerMeterY" qtc_QImage_setDotsPerMeterY :: Ptr (TQImage a) -> CInt -> IO ()
setNumColors :: QImage a -> ((Int)) -> IO ()
setNumColors x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_setNumColors cobj_x0 (toCInt x1)
foreign import ccall "qtc_QImage_setNumColors" qtc_QImage_setNumColors :: Ptr (TQImage a) -> CInt -> IO ()
instance QsetOffset (QImage a) ((Point)) where
setOffset x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QImage_setOffset_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QImage_setOffset_qth" qtc_QImage_setOffset_qth :: Ptr (TQImage a) -> CInt -> CInt -> IO ()
instance QqsetOffset (QImage a) ((QPoint t1)) where
qsetOffset x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_setOffset cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_setOffset" qtc_QImage_setOffset :: Ptr (TQImage a) -> Ptr (TQPoint t1) -> IO ()
class QsetPixel x1 where
setPixel :: QImage a -> x1 -> IO ()
instance QsetPixel ((Int, Int, Int)) where
setPixel x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_setPixel1 cobj_x0 (toCInt x1) (toCInt x2) (toCUInt x3)
foreign import ccall "qtc_QImage_setPixel1" qtc_QImage_setPixel1 :: Ptr (TQImage a) -> CInt -> CInt -> CUInt -> IO ()
instance QsetPixel ((Point, Int)) where
setPixel x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QImage_setPixel_qth cobj_x0 cpoint_x1_x cpoint_x1_y (toCUInt x2)
foreign import ccall "qtc_QImage_setPixel_qth" qtc_QImage_setPixel_qth :: Ptr (TQImage a) -> CInt -> CInt -> CUInt -> IO ()
qsetPixel :: QImage a -> ((QPoint t1, Int)) -> IO ()
qsetPixel x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_setPixel cobj_x0 cobj_x1 (toCUInt x2)
foreign import ccall "qtc_QImage_setPixel" qtc_QImage_setPixel :: Ptr (TQImage a) -> Ptr (TQPoint t1) -> CUInt -> IO ()
instance QsetText (QImage a) ((String, String)) where
setText x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_setText cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QImage_setText" qtc_QImage_setText :: Ptr (TQImage a) -> CWString -> CWString -> IO ()
instance QsetText (QImage a) ((String, String, String)) where
setText x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
withCWString x3 $ \cstr_x3 ->
qtc_QImage_setText1 cobj_x0 cstr_x1 cstr_x2 cstr_x3
foreign import ccall "qtc_QImage_setText1" qtc_QImage_setText1 :: Ptr (TQImage a) -> CWString -> CWString -> CWString -> IO ()
instance Qqqsize (QImage a) (()) (IO (QSize ())) where
qqsize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_size cobj_x0
foreign import ccall "qtc_QImage_size" qtc_QImage_size :: Ptr (TQImage a) -> IO (Ptr (TQSize ()))
instance Qqsize (QImage a) (()) (IO (Size)) where
qsize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_size_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QImage_size_qth" qtc_QImage_size_qth :: Ptr (TQImage a) -> Ptr CInt -> Ptr CInt -> IO ()
instance Qtext (QImage a) (()) (IO (String)) where
text x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_text cobj_x0
foreign import ccall "qtc_QImage_text" qtc_QImage_text :: Ptr (TQImage a) -> IO (Ptr (TQString ()))
instance Qtext (QImage a) ((QImageTextKeyLang t1)) (IO (String)) where
text x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_text1 cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_text1" qtc_QImage_text1 :: Ptr (TQImage a) -> Ptr (TQImageTextKeyLang t1) -> IO (Ptr (TQString ()))
instance Qtext (QImage a) ((String)) (IO (String)) where
text x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QImage_text2 cobj_x0 cstr_x1
foreign import ccall "qtc_QImage_text2" qtc_QImage_text2 :: Ptr (TQImage a) -> CWString -> IO (Ptr (TQString ()))
instance Qtext (QImage a) ((String, String)) (IO (String)) where
text x0 (x1, x2)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QImage_text4 cobj_x0 cstr_x1 cstr_x2
foreign import ccall "qtc_QImage_text4" qtc_QImage_text4 :: Ptr (TQImage a) -> CWString -> CWString -> IO (Ptr (TQString ()))
textKeys :: QImage a -> (()) -> IO ([String])
textKeys x0 ()
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_textKeys cobj_x0 arr
foreign import ccall "qtc_QImage_textKeys" qtc_QImage_textKeys :: Ptr (TQImage a) -> Ptr (Ptr (TQString ())) -> IO CInt
textLanguages :: QImage a -> (()) -> IO ([String])
textLanguages x0 ()
= withQListStringResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_textLanguages cobj_x0 arr
foreign import ccall "qtc_QImage_textLanguages" qtc_QImage_textLanguages :: Ptr (TQImage a) -> Ptr (Ptr (TQString ())) -> IO CInt
instance QtextList (QImage a) (()) (IO ([QImageTextKeyLang ()])) where
textList x0 ()
= withQListObjectRefResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_textList cobj_x0 arr
foreign import ccall "qtc_QImage_textList" qtc_QImage_textList :: Ptr (TQImage a) -> Ptr (Ptr (TQImageTextKeyLang ())) -> IO CInt
instance Qtransformed (QImage ()) ((QMatrix t1)) (IO (QImage ())) where
transformed x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed1 cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_transformed1" qtc_QImage_transformed1 :: Ptr (TQImage a) -> Ptr (TQMatrix t1) -> IO (Ptr (TQImage ()))
instance Qtransformed (QImageSc a) ((QMatrix t1)) (IO (QImage ())) where
transformed x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed1 cobj_x0 cobj_x1
instance Qtransformed_nf (QImage ()) ((QMatrix t1)) (IO (QImage ())) where
transformed_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed1 cobj_x0 cobj_x1
instance Qtransformed_nf (QImageSc a) ((QMatrix t1)) (IO (QImage ())) where
transformed_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed1 cobj_x0 cobj_x1
instance Qtransformed (QImage ()) ((QMatrix t1, TransformationMode)) (IO (QImage ())) where
transformed x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed2 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QImage_transformed2" qtc_QImage_transformed2 :: Ptr (TQImage a) -> Ptr (TQMatrix t1) -> CLong -> IO (Ptr (TQImage ()))
instance Qtransformed (QImageSc a) ((QMatrix t1, TransformationMode)) (IO (QImage ())) where
transformed x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed2 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance Qtransformed_nf (QImage ()) ((QMatrix t1, TransformationMode)) (IO (QImage ())) where
transformed_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed2 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance Qtransformed_nf (QImageSc a) ((QMatrix t1, TransformationMode)) (IO (QImage ())) where
transformed_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed2 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance Qtransformed (QImage ()) ((QTransform t1)) (IO (QImage ())) where
transformed x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_transformed" qtc_QImage_transformed :: Ptr (TQImage a) -> Ptr (TQTransform t1) -> IO (Ptr (TQImage ()))
instance Qtransformed (QImageSc a) ((QTransform t1)) (IO (QImage ())) where
transformed x0 (x1)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed cobj_x0 cobj_x1
instance Qtransformed_nf (QImage ()) ((QTransform t1)) (IO (QImage ())) where
transformed_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed cobj_x0 cobj_x1
instance Qtransformed_nf (QImageSc a) ((QTransform t1)) (IO (QImage ())) where
transformed_nf x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed cobj_x0 cobj_x1
instance Qtransformed (QImage ()) ((QTransform t1, TransformationMode)) (IO (QImage ())) where
transformed x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed3 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QImage_transformed3" qtc_QImage_transformed3 :: Ptr (TQImage a) -> Ptr (TQTransform t1) -> CLong -> IO (Ptr (TQImage ()))
instance Qtransformed (QImageSc a) ((QTransform t1, TransformationMode)) (IO (QImage ())) where
transformed x0 (x1, x2)
= withQImageResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed3 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance Qtransformed_nf (QImage ()) ((QTransform t1, TransformationMode)) (IO (QImage ())) where
transformed_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed3 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance Qtransformed_nf (QImageSc a) ((QTransform t1, TransformationMode)) (IO (QImage ())) where
transformed_nf x0 (x1, x2)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_transformed3 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
class QqImageTrueMatrix x1 xr where
qImageTrueMatrix :: x1 -> xr
instance QqImageTrueMatrix ((QMatrix t1, Int, Int)) (IO (QMatrix ())) where
qImageTrueMatrix (x1, x2, x3)
= withQMatrixResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_trueMatrix cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QImage_trueMatrix" qtc_QImage_trueMatrix :: Ptr (TQMatrix t1) -> CInt -> CInt -> IO (Ptr (TQMatrix ()))
instance QqImageTrueMatrix ((QTransform t1, Int, Int)) (IO (QTransform ())) where
qImageTrueMatrix (x1, x2, x3)
= withQTransformResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_trueMatrix1 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QImage_trueMatrix1" qtc_QImage_trueMatrix1 :: Ptr (TQTransform t1) -> CInt -> CInt -> IO (Ptr (TQTransform ()))
class Qvalid x1 where
valid :: QImage a -> x1 -> IO (Bool)
instance Qvalid ((Int, Int)) where
valid x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_valid1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QImage_valid1" qtc_QImage_valid1 :: Ptr (TQImage a) -> CInt -> CInt -> IO CBool
instance Qvalid ((Point)) where
valid x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QImage_valid_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QImage_valid_qth" qtc_QImage_valid_qth :: Ptr (TQImage a) -> CInt -> CInt -> IO CBool
qvalid :: QImage a -> ((QPoint t1)) -> IO (Bool)
qvalid x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QImage_valid cobj_x0 cobj_x1
foreign import ccall "qtc_QImage_valid" qtc_QImage_valid :: Ptr (TQImage a) -> Ptr (TQPoint t1) -> IO CBool
instance Qqwidth (QImage a) (()) (IO (Int)) where
qwidth x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_width cobj_x0
foreign import ccall "qtc_QImage_width" qtc_QImage_width :: Ptr (TQImage a) -> IO CInt
qImage_delete :: QImage a -> IO ()
qImage_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_delete cobj_x0
foreign import ccall "qtc_QImage_delete" qtc_QImage_delete :: Ptr (TQImage a) -> IO ()
qImage_delete1 :: QImage a -> IO ()
qImage_delete1 x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QImage_delete1 cobj_x0
foreign import ccall "qtc_QImage_delete1" qtc_QImage_delete1 :: Ptr (TQImage a) -> IO ()
|
uduki/hsQt
|
Qtc/Gui/QImage.hs
|
bsd-2-clause
| 66,300 | 0 | 16 | 11,799 | 24,378 | 12,503 | 11,875 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.