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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# OPTIONS_GHC -XTemplateHaskell #-}
module Graphics.Rendering.Chart.Plot.PixelMap
( PixelMap(..), DefaultRange(..)
, defaultPixelMap
, plotPixelMap
, pixel_map_title
, pixel_map_palette
, pixel_map_values
, pixel_map_range
, greyscale
, make_range
) where
import qualified Graphics.Rendering.Cairo as C
import qualified Data.Array.Repa as R
import Data.Array.Repa(Z(..), (:.)(..))
import Graphics.Rendering.Chart.Types
import Graphics.Rendering.Chart.Plot.Types
import Graphics.Rendering.Chart.Axis
import Data.Colour
import Data.Colour.SRGB(sRGB)
import Data.Accessor.Template
import Control.Monad
data PixelMap z x y = PixelMap
{ pixel_map_title_ :: String
, pixel_map_palette_ :: [Colour Double]
, pixel_map_values_ :: R.Array R.DIM2 z
, pixel_map_range_ :: (z, z)
, pixel_map_locx_ :: [x]
, pixel_map_locy_ :: [y]
}
class DefaultRange a where
minDefVal :: a
maxDefVal :: a
instance DefaultRange Int where
minDefVal = 0
maxDefVal = 1
instance DefaultRange Double where
minDefVal = 0.0
maxDefVal = 1.0
instance DefaultRange Float where
minDefVal = 0.0
maxDefVal = 1.0
-- TODO: put a more sensible min here
make_range :: (R.Elt z, Ord z) => z -> z -> R.Array R.DIM2 z -> (z, z)
make_range minVal maxVal m = (R.foldAll min maxVal m
,R.foldAll max minVal m)
defaultPixelMap :: (PlotValue z, DefaultRange z) => R.Array R.DIM2 z -> PixelMap z Int Int
defaultPixelMap = mkPixelMap greyscale "" minDefVal maxDefVal
-- TODO: Repa-rize me
greyscale :: [Colour Double]
greyscale = map (\x -> sRGB x x x) [x/255.0 | x <- [0..255]]
mkPixelMap :: (PlotValue z) => [Colour Double] -> String -> z -> z -> R.Array R.DIM2 z -> PixelMap z Int Int
mkPixelMap palette title min max m = PixelMap
{ pixel_map_title_ = ""
, pixel_map_palette_ = palette
, pixel_map_values_ = m
, pixel_map_range_ = (min, max)
, pixel_map_locx_ = [0, w]
, pixel_map_locy_ = [0, h]
}
where (Z :. h :. w) = R.extent m
plotPixelMap :: (R.Elt z, PlotValue z) => PixelMap z Int Int -> Plot Int Int
plotPixelMap p = Plot { plot_render_ = renderPixelMap p
, plot_legend_ = [ (pixel_map_title_ p
, renderSpotLegend p) ]
, plot_all_points_ = ( pixel_map_locx_ p
, pixel_map_locy_ p )
}
renderPixelMap :: (R.Elt z, PlotValue z) => PixelMap z Int Int -> PointMapFn Int Int -> CRender ()
renderPixelMap p pmap = preserveCState $ mapM_ drawPixel [(x, y, elem x y) | x <- [0..(w-1)], y <- [0..(h-1)]]
where m = pixel_map_values_ p
(Z :. h :. w) = R.extent m
elem x y = m R.! (Z :. y :. x)
(minVal_, maxVal_) = pixel_map_range_ p
minVal = toValue minVal_
maxVal = toValue maxVal_
numColors = toValue $ (length (pixel_map_palette_ p)) - 1
scale = fromValue . (\x -> numColors * (x - minVal)/(maxVal - minVal)) . toValue
-- drawPixel :: (R.Elt z, PlotValue z) => (Int, Int, z) -> CRender ()
drawPixel (x, y, c) = do
setFillStyle $ solidFillStyle (opaque ((pixel_map_palette_ p) !! (scale c)))
let p1 = mapXY pmap (x, y)
p2 = mapXY pmap (x+1, y+1)
fillPath (rectPath (Rect p1 p2))
renderSpotLegend :: PixelMap z x y -> Rect -> CRender ()
renderSpotLegend p r@(Rect p1 p2) = preserveCState $ do
return ()
-- let radius = min (abs (p_y p1 - p_y p2)) (abs (p_x p1 - p_x p2))
-- centre = linearInterpolate p1 p2
-- let (CairoPointStyle drawSpotAt) = filledCircles radius
-- (flip withOpacity 0.2 $
-- head (pixel_map_palette__ p))
-- drawSpotAt centre
-- let (CairoPointStyle drawOutlineAt) = hollowCircles radius
-- (pixel_map_linethick__ p)
-- (opaque $
-- head (pixel_map_palette__ p))
-- drawOutlineAt centre
-- where
-- linearInterpolate (Point x0 y0) (Point x1 y1) =
-- Point (x0 + abs(x1-x0)/2) (y0 + abs(y1-y0)/2)
$( deriveAccessors ''PixelMap ) | chetant/rbm | Graphics/Rendering/Chart/Plot/PixelMap.hs | bsd-3-clause | 4,360 | 0 | 16 | 1,342 | 1,216 | 679 | 537 | -1 | -1 |
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Model where
import Data.Text (Text)
import Data.Time (UTCTime)
import Database.Persist
import Database.Persist.TH
share [mkPersist sqlSettings, mkMigrate "migrate"] [persist|
Post json
name Text
text Text
created UTCTime
deriving Show Read Eq Ord
|]
| daimatz/scotty-on-heroku | src/Model.hs | bsd-3-clause | 720 | 0 | 7 | 209 | 69 | 45 | 24 | 16 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
module Api.Types where
import GHC.Generics
import Data.Aeson
import Data.Aeson.Types
import Data.Maybe
import qualified Data.ByteString.Char8 as C8
import Network.HTTP.Simple
import Control.Applicative
data ReceivedError =
ReceivedError { msg :: String, code :: Int }
| ReceivedError' { msg :: String, rcode :: String }
deriving (Show, Generic)
instance FromJSON ReceivedError where
parseJSON v =
parseCodeInt v <|>
parseCodeStr v
parseCodeInt :: Value -> Parser ReceivedError
parseCodeInt = withObject "ReceivedError"
(\o -> ReceivedError <$> o .: "msg"
<*> o .: "code")
parseCodeStr :: Value -> Parser ReceivedError
parseCodeStr = withObject "ReceivedError"
(\o -> ReceivedError' <$> o .: "msg"
<*> o .: "code")
data HidriveRequest a b = HidriveRequest
{
method :: C8.ByteString,
httpReq :: Request
} deriving Show
mkHidriveRequest :: C8.ByteString
-> Request
-> HidriveRequest a b
mkHidriveRequest a b = HidriveRequest a b
type family HidriveResponse a :: *
{-- /app/me requests --}
data AppRequest
type instance HidriveResponse AppRequest = AppResponse
data AppResponse = AppResponse
{
appCreated :: Maybe Int,
appDeveloper :: Maybe Developer,
appHomepage :: Maybe String,
appId :: Maybe Int,
appMayPublish :: Maybe Bool,
appName :: Maybe String,
appPrivateFolder :: Maybe String,
appPrivateFolderId :: Maybe String,
appPublicationUrl :: Maybe String,
appRefreshToken :: Maybe RefreshToken,
appStatus :: Maybe String
} deriving (Show)
data Developer = Developer
{
devEmail :: Maybe String,
devName :: Maybe String
} deriving (Show)
instance FromJSON Developer where
parseJSON = withObject "Developer" parse
where
parse o = Developer
<$> o .:? "name"
<*> o .:? "email"
data RefreshToken = RefreshToken
{
refreshTokenExpire :: Maybe Int,
refreshTokenExpireIn :: Maybe Int,
refreshTokenInstanceId :: Maybe String,
refreshTokenScope :: Maybe String
} deriving (Show)
instance FromJSON RefreshToken where
parseJSON = withObject "RefreshToken" parse
where
parse o = RefreshToken
<$> o .:? "expire"
<*> o .:? "expire_in"
<*> o .:? "instance_id"
<*> o .:? "scope"
instance FromJSON AppResponse where
parseJSON = withObject "AppResponse" parse
where
parse o = AppResponse
<$> o .:? "created"
<*> o .:? "developer"
<*> o .:? "homepage"
<*> o .:? "id"
<*> o .:? "may_publish"
<*> o .:? "name"
<*> o .:? "private_folder"
<*> o .:? "private_folder_id"
<*> o .:? "publication_url"
<*> o .:? "refresh_token"
<*> o .:? "status"
{-- /app/me requests --}
{-- /permission requests --}
data PermissionsRequest
type instance HidriveResponse PermissionsRequest = PermissionsResponse
data PermissionsResponse = PermissionsResponse
{
permissionsAccount :: Maybe String,
permissionsWritable :: Bool,
permissionsReadable :: Bool,
permissionsPath :: Maybe String
} deriving (Show)
instance FromJSON PermissionsResponse where
parseJSON = withObject "PermissionsResponse" parse
where
parse o = PermissionsResponse
<$> o .:? "account"
<*> o .: "writable"
<*> o .: "readable"
<*> o .:? "path"
{-- /permission requests --}
{-- /dir requests --}
data ListDirRequest
type instance HidriveResponse ListDirRequest = ListDirResponse
data ListDirResponse = ListDirResponse
{
listdirChash :: Maybe String,
listdirCtime :: Maybe Int,
listdirHas_dirs :: Maybe Bool,
listdirId :: Maybe Int,
listdirMembers :: Maybe [ListDirResponse],
listdirMhash :: Maybe String,
listdirMohash :: Maybe String,
listdirMtime :: Maybe Int,
listdirName :: Maybe String,
listdirNhash :: Maybe String,
listdirNmembers :: Maybe Int,
listdirParentid :: Maybe String,
listdirPath :: Maybe String,
listdirReadable :: Maybe Bool,
listdirRshare :: Maybe [LsShare],
listdirSize :: Maybe Int,
listdirType :: Maybe String,
listdirWritable :: Maybe Bool
} deriving Show
instance FromJSON ListDirResponse where
parseJSON = withObject "ListDirResponse" parse
where
parse o = ListDirResponse
<$> o .:? "chash"
<*> o .:? "ctime"
<*> o .:? "has_dirs"
<*> o .:? "id"
<*> o .:? "members"
<*> o .:? "mhash"
<*> o .:? "mohash"
<*> o .:? "mtime"
<*> o .:? "name"
<*> o .:? "nhash"
<*> o .:? "nmembers"
<*> o .:? "parent_id"
<*> o .:? "path"
<*> o .:? "readable"
<*> o .:? "rshare"
<*> o .:? "size"
<*> o .:? "type"
<*> o .:? "writable"
data LsShare = LsShare
{
lsShareId :: String,
lsShareStatus :: String,
lsShareReadable :: Bool,
lsShareWritable :: Bool,
lsShareCount :: Int,
lsSharePassword :: Maybe String,
lsShareCreated :: Int,
lsShareLastModified :: Int,
lsShareShareType :: String,
lsShareIsEncrypted :: Bool
} deriving Show
instance FromJSON LsShare where
parseJSON = withObject "LsShare" parse
where
parse o = LsShare
<$> o .: "id"
<*> o .: "status"
<*> o .: "readable"
<*> o .: "writable"
<*> o .: "count"
<*> o .:? "password"
<*> o .: "created"
<*> o .: "last_modified"
<*> o .: "share_type"
<*> o .: "is_encrypted"
{-- /dir requests --}
{-- 2.1/file post --}
data UploadFileRequest
type instance HidriveResponse UploadFileRequest = UploadFileResponse
data UploadFileResponse = UploadFileResponse
{
uploadFileCtime :: Int,
uploadFileHasDirs :: Maybe Bool,
uploadFileId :: String,
uploadFileImage :: FileImage,
uploadFileMimeType :: String,
uploadFileMtime :: Int,
uploadFileName :: String,
uploadFileParentId :: String,
uploadFilePath :: String,
uploadFileReadable :: Bool,
-- uploadFileRshare :: Maybe LsShare,
uploadFileSize :: Int,
uploadFileType :: String,
uploadFileWritable :: Bool
} deriving Show
data FileImage = FileImage
{
fileImageExif :: Maybe FileImageExif,
fileImageWidth :: Maybe Int,
fileImageHeight :: Maybe Int
} deriving Show
data FileImageExif = FileImageExif
{
resolutionUnit :: Maybe Int,
imageHeight :: Maybe Int,
xResolution :: Maybe Int,
imageWidth :: Maybe Int,
bitsPerSample :: Maybe Int,
yResolution :: Maybe Int
} deriving (Generic, Show)
instance FromJSON FileImageExif
instance FromJSON FileImage where
parseJSON = withObject "FileImage" parse
where
parse o = FileImage
<$> o .:? "exif"
<*> o .:? "height"
<*> o .:? "width"
instance FromJSON UploadFileResponse where
parseJSON = withObject "UploadFileResponse" parse
where
parse o = UploadFileResponse
<$> o .: "ctime"
<*> o .:? "has_dirs"
<*> o .: "id"
<*> o .: "image"
<*> o .: "mime_type"
<*> o .: "mtime"
<*> o .: "name"
<*> o .: "parent_id"
<*> o .: "path"
<*> o .: "readable"
-- <*> o .:? "rshare"
<*> o .: "size"
<*> o .: "type"
<*> o .: "writable"
{-- /2.1/file post --}
type instance HidriveResponse Void = Void
data Void = Void deriving (Generic,Show)
instance FromJSON Void
{-- 2.1/sharelink post --}
data ShareRequest
type instance HidriveResponse ShareRequest = ShareResponse
data ShareResponse = ShareResponse
{
shareCount :: Int,
shareCreated :: Int,
shareId :: String,
shareLastModified :: Int,
shareMaxCount :: Int,
sharePid :: String,
sharePath :: String,
sharePassword :: Maybe String,
shareSize :: Int,
shareStatus :: String,
shareTtl :: Int,
shareType :: String,
shareUri :: String
} deriving Show
instance FromJSON ShareResponse where
parseJSON = withObject "ShareResponse" parse
where
parse o = ShareResponse
<$> o .: "count"
<*> o .: "created"
<*> o .: "id"
<*> o .: "last_modified"
<*> o .: "maxcount"
<*> o .: "pid"
<*> o .: "path"
<*> o .:? "password"
<*> o .: "size"
<*> o .: "status"
<*> o .: "ttl"
<*> o .: "type"
<*> o .: "uri"
{-- /2.1/sharelink post --}
{-- 2.1/sharelink get --}
data ShareLinkRequest
type instance HidriveResponse ShareLinkRequest = [ShareLinkObject]
data ShareLinkObject = ShareLinkObject
{
shareLinkObjectCount :: Maybe Int,
shareLinkObjectCreated :: Maybe Int,
shareLinkObjectHasPassword :: Maybe Bool,
shareLinkObjectId :: Maybe String,
shareLinkObjectLastModified :: Maybe Int,
shareLinkObjectMaxcount :: Maybe Int,
shareLinkObjectName :: Maybe String,
shareLinkObjectPath :: Maybe String,
shareLinkObjectPassword :: Maybe String,
shareLinkObjectPid :: Maybe String,
shareLinkObjectReadable :: Maybe Bool,
shareLinkObjectRemaining :: Maybe Int,
shareLinkObjectShareType :: Maybe String,
shareLinkObjectSize :: Maybe Int,
shareLinkObjectStatus :: Maybe String,
shareLinkObjectType :: Maybe String,
shareLinkObjectTtl :: Maybe Int,
shareLinkObjectUri :: Maybe String,
shareLinkObjectWritable :: Maybe Bool
} deriving Show
instance FromJSON ShareLinkObject where
parseJSON = withObject "ShareLinkObject" parse
where
parse o = ShareLinkObject
<$> o .:? "count"
<*> o .:? "created"
<*> o .:? "has_password"
<*> o .:? "id"
<*> o .:? "last_modified"
<*> o .:? "maxcount"
<*> o .:? "name"
<*> o .:? "path"
<*> o .:? "password"
<*> o .:? "pid"
<*> o .:? "readable"
<*> o .:? "remaining"
<*> o .:? "share_type"
<*> o .:? "size"
<*> o .:? "status"
<*> o .:? "type"
<*> o .:? "ttl"
<*> o .:? "uri"
<*> o .:? "writable"
{-- /2.1/sharelink get --}
{-- 2.1/rename post --}
data RenameFileRequest
type instance HidriveResponse RenameFileRequest = RenameFileResponse
data RenameFileResponse = RenameFileResponse
{
renameFileCtime :: Int,
renameFileHasDirs :: Maybe Bool,
renameFileId :: String,
renameFileImage :: Maybe FileImage,
renameFileMimetype :: String,
renameFileMtime :: Int,
renameFileName :: String,
renameFileParentId :: String,
renameFilePath :: String,
renameFileReadable :: Bool,
renameFileSize :: Int,
renameFileType :: String,
renameFileWritable :: Bool
} deriving Show
instance FromJSON RenameFileResponse where
parseJSON = withObject "RenameFileResponse" parse
where
parse o = RenameFileResponse
<$> o .: "ctime"
<*> o .:? "has_dirs"
<*> o .: "id"
<*> o .:? "image"
<*> o .: "mime_type"
<*> o .: "mtime"
<*> o .: "name"
<*> o .: "parent_id"
<*> o .: "path"
<*> o .: "readable"
<*> o .: "size"
<*> o .: "type"
<*> o .: "writable"
{-- /2.1/rename post --}
| lupuionut/homedmanager | src/Api/Types.hs | bsd-3-clause | 13,504 | 0 | 45 | 5,211 | 2,711 | 1,491 | 1,220 | -1 | -1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
module HTagger where
import HTagger.Internal
import CorePrelude
import Control.Monad
import qualified Data.Foldable as F
import qualified Data.Map.Strict as M
import qualified Data.Sequence as S
import qualified Data.Text as T
import Data.Traversable
import qualified Data.Traversable as TR
import qualified Filesystem as FS
import qualified Filesystem.Path as FP
import qualified Filesystem.Path.CurrentOS as OS
import qualified Sound.TagLib as TL
data Artist = Artist {
artistName :: String
} deriving (Eq, Show, Ord)
data Album = Album {
albumName :: String
} deriving (Eq, Show, Ord)
data Song = Song {
songTitle :: String
, songYear :: Integer
, songOldPath :: FP.FilePath
, songAlbum :: Album
, songArtist :: Artist
} deriving (Eq, Show, Ord)
type SongMap = M.Map Artist (M.Map Album [Song])
-- | List all directory contents. Used to get all files in a flat list
listAllDirectorContentsSeq :: FP.FilePath -> IO (S.Seq FP.FilePath)
listAllDirectorContentsSeq fp = do
fpIsFile <- FS.isFile fp
if fpIsFile
then return S.empty
else do
listContents <- FS.listDirectory fp
let contents = S.fromList listContents
cContents <- TR.mapM listAllDirectorContentsSeq contents
return $ contents S.>< concatSeq cContents
createSongMap :: FP.FilePath -> IO SongMap
createSongMap fp = do
fileList <- listAllDirectorContentsSeq fp
songList <- TR.traverse songFromFilePath (F.toList fileList)
return $ F.foldl insertSongIntoMap M.empty (catMaybes songList)
insertSongIntoMap :: SongMap -> Song -> SongMap
insertSongIntoMap songMap song =
let artist = songArtist song
album = songAlbum song
in case M.lookup artist songMap of
(Just albumMap) ->
case M.lookup album albumMap of
(Just songList) -> M.insert artist (M.insert album (song:songList) albumMap) songMap
Nothing ->
let artistMap = M.singleton album [song]
in M.insert artist artistMap songMap
songFromFilePath :: FP.FilePath -> IO (Maybe Song)
songFromFilePath fp = do
let mText = eitherToMaybe $ T.unpack <$> OS.toText fp
mTagFile <- TR.traverse TL.open mText
mTag <- TR.traverse TL.tag (join mTagFile)
TR.traverse (songFromTag fp) (join mTag)
tagMaybe :: Maybe TL.TagFile -> IO (Maybe TL.Tag)
tagMaybe (Just tf) = TL.tag tf
tagMaybe Nothing = return Nothing
openMaybe :: Maybe String -> IO (Maybe TL.TagFile)
openMaybe (Just t) = TL.open t
openMaybe Nothing = return Nothing
eitherToMaybe :: Either a b -> Maybe b
eitherToMaybe (Right r) = Just r
eitherToMaybe (Left _) = Nothing
songFromTag :: FP.FilePath -> TL.Tag -> IO Song
songFromTag fp tag = do
alb <- TL.album tag
art <- TL.artist tag
ttl <- TL.title tag
yr <- TL.year tag
return $ Song ttl yr fp (Album alb) (Artist art)
--traverseCreateFPArtist :: FP.FilePath -> S.Seq
createPath :: FP.FilePath -> S.Seq FP.FilePath -> Song -> S.Seq FP.FilePath
createPath baseFP lastSeq song =
let alb = OS.fromText . T.pack . albumName $ songAlbum song
art = OS.fromText . T.pack . artistName $ songArtist song
fname = FP.filename $ songOldPath song
in lastSeq S.|> baseFP FP.</> art FP.</> alb FP.</> fname
--copySongsToDir :: FP.FilePath -> FP.FilePath -> SongMap -> IO (Maybe ())
--copySongsToDir currDir goalDir sm = do
-- songMap <- createSongMap currDir
-- let foldList = F.toList $ M.foldl (createPath goalDir) S.empty songMap
-- return foldList
| KevinCotrone/htag | src/HTagger.hs | bsd-3-clause | 3,604 | 0 | 17 | 784 | 1,107 | 566 | 541 | 84 | 2 |
-- |
-- Module : Language.Forvie.Lexing.Text
-- Copyright : Robert Atkey 2012
-- License : BSD3
--
-- Maintainer : bob.atkey@gmail.com
-- Stability : experimental
-- Portability : unknown
--
-- Functions for turning `Data.Text.Text` into a stream of lexemes,
-- according to some lexical specification.
module Language.Forvie.Lexing.Text
( lex
, ErrorHandler (..) )
where
import Prelude hiding (lex)
import Data.ByteString (ByteString)
import qualified Data.Text as T
import Data.MonadicStream (Stream (..), StreamStep (..))
import qualified Data.FiniteStateMachine.Deterministic as DFA
import Language.Forvie.Lexing.Spec (CompiledLexSpec (..))
import Text.Lexeme (Lexeme (..))
import Text.Position (Span (Span), initPos, updatePos, Position)
{------------------------------------------------------------------------------}
data PositionWith a = (:-) { positionOf :: Position
, dataOf :: a
}
uncons :: PositionWith T.Text -> Maybe (PositionWith Char, PositionWith T.Text)
uncons (position :- text) =
case T.uncons text of
Nothing -> Nothing
Just (c,rest) -> Just ( position :- c
, (position `updatePos` c) :- rest)
{------------------------------------------------------------------------------}
data CurrentLexeme tok
= CurrentLexeme { curLexemeText :: !(PositionWith T.Text)
, curLexemeLen :: !Int
, curLexemeMatch :: !(CurrentMatch tok)
}
data CurrentMatch tok
= NoMatch
| Match !Int !tok !Position !(PositionWith T.Text)
advance :: CurrentLexeme tok -> CurrentLexeme tok
advance lexeme = lexeme { curLexemeLen = curLexemeLen lexeme + 1 }
(+.) :: CurrentLexeme tok -> (PositionWith tok, PositionWith T.Text) -> CurrentLexeme tok
lexeme +. (pos :- tok, rest) =
lexeme { curLexemeMatch = Match (curLexemeLen lexeme) tok pos rest }
initLexeme :: PositionWith T.Text -> CurrentLexeme tok
initLexeme text = CurrentLexeme text 0 NoMatch
{------------------------------------------------------------------------------}
data ErrorHandler m tok = OnError { onError :: Maybe (Char, Position) -> m tok }
{------------------------------------------------------------------------------}
{-
data State tok
= BeforeLexeme !(PositionWith T.Text)
| InLexeme !Int !(CurrentLexeme tok) !(PositionWith T.Text)
step :: State tok -> m (Maybe (State tok, Lexeme tok))
step (BeforeLexeme text) = undefined
step (InLexeme q lexeme text) = undefined
-}
{------------------------------------------------------------------------------}
lex :: (Ord tok, Monad m) =>
CompiledLexSpec tok
-> ErrorHandler m tok
-> ByteString
-> T.Text
-> Stream m (Lexeme tok)
lex lexSpec errorHandler sourceName text =
go (initPos sourceName :- text)
where
dfa = lexSpecDFA lexSpec
go text =
Stream $ beforeLexeme text
beforeLexeme text =
case uncons text of
Nothing -> return StreamEnd
Just step -> onChar (DFA.initialState dfa) step (initLexeme text)
inLexeme dfaState lexeme text =
case uncons text of
Nothing -> emit lexeme Nothing
Just step -> onChar dfaState step lexeme
onChar q input@(position :- c, rest) lexeme =
case DFA.transition dfa q c of
DFA.Accept t q' -> inLexeme q' (advance lexeme +. (position :- t, rest)) rest
DFA.Error -> emit lexeme (Just input)
DFA.Change q' -> inLexeme q' (advance lexeme) rest
emit lexeme input =
case curLexemeMatch lexeme of
NoMatch ->
do let input' = case input of Nothing -> Nothing; Just (p :- c, _) -> Just (c,p)
tok <- errorHandler `onError` input'
return (StreamElem (Lexeme tok span text) $ go rest)
where
endPos = case input of
Nothing -> positionOf $ curLexemeText lexeme -- FIXME: this is wrong!
Just (p :- _, _) -> p
rest = case input of
Nothing -> initPos sourceName :- T.empty -- FIXME
Just (_, rest) -> rest
length = curLexemeLen lexeme + case input of Nothing -> 0; Just _ -> 1
span = Span (positionOf $ curLexemeText lexeme) endPos
text = T.take length (dataOf $ curLexemeText lexeme)
Match length tok endPos rest ->
return (StreamElem (Lexeme tok span text) $ go rest)
where
span = Span (positionOf $ curLexemeText lexeme) endPos
text = T.take length (dataOf $ curLexemeText lexeme)
| bobatkey/Forvie | src/Language/Forvie/Lexing/Text.hs | bsd-3-clause | 4,948 | 6 | 20 | 1,520 | 1,219 | 644 | 575 | 91 | 10 |
{-# LANGUAGE OverloadedStrings #-}
import Test.Hspec
import Test.QuickCheck
import Data.Monoid ((<>))
import Data.ByteString.Char8 (ByteString)
import Sequence.Alignment
import Sequence.Alignment.Matrix
chains :: [ByteString]
chains = [ "EVQLVESGGGLVQPGGSLRLSCAASGFNIKDTYIHWVRQAPGKGLEWVA" <>
"RIYPTNGYTRYADSVKGRFTISADTSKNTAYLQMNSLRAEDTAVYYCSRWGGDGFYAMDYWGQGTLVTVSS"
, "EVQLVESGGGLVQPGGSLRLSCAASGFTFTDYTMDWVRQAPGKGLEWVA" <>
"DVNPNSGGSIYNQRFKGRFTLSVDRSKNTLYLQMNSLRAEDTAVYYCARNLGPSFYFDYWGQGTLVTVSS"
, "QVQLQQPGAELVKPGASVKMSCKASGYTFTSYNMHWVKQTPGRGLEWIG" <>
"AIYPGNGDTSYNQKFKGKATLTADKSSSTAYMQLSSLTSEDSAVYYCARSTYYGGDWYFNVWGAGTTVTVSA"
, "EVQLVESGGGLVQPGRSLRLSCAASGFTFDDYAMHWVRQAPGKGLEWVSAI" <>
"TWNSGHIDYADSVEGRFTISRDNAKNSLYLQMNSLRAEDTAVYCAKVSYLSTASSLDYWGQGTLVTVSS"
, "EVQLVESGGGLVQPGGSLRLSCAASGYTFTNYGMNWVRQAPGKGLEWVG" <>
"WINTYTGEPTYAADFKRRFTFSLDTSKSTAYLQMNSLRAEDTAVYCAKYPHYYGSSHWYFDVWGQGTLVTVSS"
, "QVQLVQSGVEVKKPGASVKVSCKASGYTFTNYYMYWVRQAPGQGLEWMG" <>
"GINPSNGGTNFNEKFKNRVTLTTDSSTTTAYMELKSLQFDDTAVYYCARRDYRFDMGFDYWGQGTTVTVSS"
, "EVQLVESGGGLVQPGGSLRLSCAASGFTFSNYWMNWVRQAPGKGLEWVA" <>
"AINQDGSEKYYVGSVKGRFTISRDNAKNSLYLQMNSLRVEDTAVYYCVRDYYDILTDYYIHYWYFDLWGRGTLVTVSS"
]
combinations :: [Int]
combinations = [fst $ alignment glob x y | x <- chains, y <- chains]
where glob = mkGlobal blosum62 (-5)
results :: [Int]
results = [ 645, 459, 345, 431, 401, 337, 405, 459, 634, 375, 437, 444
, 378, 425, 345, 375, 651, 306, 368, 418, 316, 431, 437, 306
, 628, 413, 312, 423, 401, 444, 368, 413, 669, 337, 436, 337
, 378, 418, 312, 337, 647, 304, 405, 425, 316, 423, 436, 304, 688]
main :: IO ()
main = hspec $ do
describe "Edit distance" $ do
it "align empty strings" $ do
let (_, (s', t')) = alignment mkEditDistance "" ""
s' `shouldBe` ""
t' `shouldBe` ""
it "align equal strings" $ do
let (_, (s', t')) = alignment mkEditDistance "AAA" "AAA"
s' `shouldBe` "AAA"
t' `shouldBe` "AAA"
describe "Global alignment" $ do
it "align antibodies" $ do
let (tra : per : _) = chains
let (score, (s', t')) = alignment (mkGlobal blosum62 (-5)) tra per
s' `shouldBe` "EVQLVESGGGLVQPGGSLRLSCAASGFNIKDTY-IHWVRQAPGKGLEWVARIYPTNGYTRYADSVKGRFTISADTSKNTAYLQMNSLRAEDTAVYYCSRWGGDGFYAMDYWGQGTLVTVSS"
t' `shouldBe` "EVQLVESGGGLVQPGGSLRLSCAASGFTFTD-YTMDWVRQAPGKGLEWVADVNPNSGGSIYNQRFKGRFTLSVDRSKNTLYLQMNSLRAEDTAVYYCARNLGPSFY-FDYWGQGTLVTVSS"
score `shouldBe` 459
it "align fast" $
combinations `shouldBe` results
| zmactep/zero-aligner | test/Spec.hs | bsd-3-clause | 2,791 | 0 | 21 | 652 | 597 | 338 | 259 | 50 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Network.HTTP.Download.VerifiedSpec where
import Crypto.Hash
import Control.Monad (unless)
import Control.Monad.Trans.Reader
import Data.Maybe
import Network.HTTP.Client.Conduit
import Network.HTTP.Download.Verified
import Path
import System.Directory
import System.IO.Temp
import Test.Hspec
-- TODO: share across test files
withTempDir :: (Path Abs Dir -> IO a) -> IO a
withTempDir f = withSystemTempDirectory "NHD_VerifiedSpec" $ \dirFp -> do
dir <- parseAbsDir dirFp
f dir
-- | An example path to download the exampleReq.
getExamplePath :: Path Abs Dir -> IO (Path Abs File)
getExamplePath dir = do
file <- parseRelFile "cabal-install-1.22.4.0.tar.gz"
return (dir </> file)
-- | An example DownloadRequest that uses a SHA1
exampleReq :: DownloadRequest
exampleReq = fromMaybe (error "exampleReq") $ do
req <- parseUrl "http://download.fpcomplete.com/stackage-cli/linux64/cabal-install-1.22.4.0.tar.gz"
return DownloadRequest
{ drRequest = req
, drHashChecks = [exampleHashCheck]
, drLengthCheck = Just exampleLengthCheck
}
exampleHashCheck :: HashCheck
exampleHashCheck = HashCheck
{ hashCheckAlgorithm = SHA1
, hashCheckHexDigest = CheckHexDigestString "b98eea96d321cdeed83a201c192dac116e786ec2"
}
exampleLengthCheck :: LengthCheck
exampleLengthCheck = 302513
-- | The wrong ContentLength for exampleReq
exampleWrongContentLength :: Int
exampleWrongContentLength = 302512
-- | The wrong SHA1 digest for exampleReq
exampleWrongDigest :: CheckHexDigest
exampleWrongDigest = CheckHexDigestString "b98eea96d321cdeed83a201c192dac116e786ec3"
exampleWrongContent :: String
exampleWrongContent = "example wrong content"
isWrongContentLength :: VerifiedDownloadException -> Bool
isWrongContentLength WrongContentLength{} = True
isWrongContentLength _ = False
isWrongDigest :: VerifiedDownloadException -> Bool
isWrongDigest WrongDigest{} = True
isWrongDigest _ = False
data T = T
{ manager :: Manager
}
runWith :: Manager -> ReaderT Manager m r -> m r
runWith = flip runReaderT
setup :: IO T
setup = do
manager <- newManager
return T{..}
teardown :: T -> IO ()
teardown _ = return ()
shouldNotBe :: (Show a, Eq a) => a -> a -> Expectation
actual `shouldNotBe` expected =
unless (actual /= expected) (expectationFailure msg)
where
msg = "Value was exactly what it shouldn't be: " ++ show expected
shouldNotReturn :: (Show a, Eq a) => IO a -> a -> Expectation
action `shouldNotReturn` unexpected = action >>= (`shouldNotBe` unexpected)
spec :: Spec
spec = beforeAll setup $ afterAll teardown $ do
let exampleProgressHook = return ()
describe "verifiedDownload" $ do
-- Preconditions:
-- * the exampleReq server is running
-- * the test runner has working internet access to it
it "downloads the file correctly" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
doesFileExist exampleFilePath `shouldReturn` False
let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook
go `shouldReturn` True
doesFileExist exampleFilePath `shouldReturn` True
it "is idempotent, and doesn't redownload unnecessarily" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
doesFileExist exampleFilePath `shouldReturn` False
let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook
go `shouldReturn` True
doesFileExist exampleFilePath `shouldReturn` True
go `shouldReturn` False
doesFileExist exampleFilePath `shouldReturn` True
-- https://github.com/commercialhaskell/stack/issues/372
it "does redownload when the destination file is wrong" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
writeFile exampleFilePath exampleWrongContent
doesFileExist exampleFilePath `shouldReturn` True
readFile exampleFilePath `shouldReturn` exampleWrongContent
let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook
go `shouldReturn` True
doesFileExist exampleFilePath `shouldReturn` True
readFile exampleFilePath `shouldNotReturn` exampleWrongContent
it "rejects incorrect content length" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
let wrongContentLengthReq = exampleReq
{ drLengthCheck = Just exampleWrongContentLength
}
let go = runWith manager $ verifiedDownload wrongContentLengthReq examplePath exampleProgressHook
go `shouldThrow` isWrongContentLength
doesFileExist exampleFilePath `shouldReturn` False
it "rejects incorrect digest" $ \T{..} -> withTempDir $ \dir -> do
examplePath <- getExamplePath dir
let exampleFilePath = toFilePath examplePath
let wrongHashCheck = exampleHashCheck { hashCheckHexDigest = exampleWrongDigest }
let wrongDigestReq = exampleReq { drHashChecks = [wrongHashCheck] }
let go = runWith manager $ verifiedDownload wrongDigestReq examplePath exampleProgressHook
go `shouldThrow` isWrongDigest
doesFileExist exampleFilePath `shouldReturn` False
-- https://github.com/commercialhaskell/stack/issues/240
it "can download hackage tarballs" $ \T{..} -> withTempDir $ \dir -> do
dest <- fmap (dir </>) $ parseRelFile "acme-missiles-0.3.tar.gz"
let destFp = toFilePath dest
req <- parseUrl "http://hackage.haskell.org/package/acme-missiles-0.3/acme-missiles-0.3.tar.gz"
let dReq = DownloadRequest
{ drRequest = req
, drHashChecks = []
, drLengthCheck = Nothing
}
let progressHook = return ()
let go = runWith manager $ verifiedDownload dReq dest progressHook
doesFileExist destFp `shouldReturn` False
go `shouldReturn` True
doesFileExist destFp `shouldReturn` True
| hesselink/stack | src/test/Network/HTTP/Download/VerifiedSpec.hs | bsd-3-clause | 6,148 | 0 | 22 | 1,192 | 1,470 | 742 | 728 | 120 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import System.Random (randomRIO)
import Web.Twitter.Conduit
import Web.Twitter.Conduit.Stream
import Web.Twitter.Types.Lens
import Data.Conduit
import qualified Data.Conduit.List as CL
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Control.Monad.IO.Class (liftIO, MonadIO)
import Control.Lens ((^.))
import Control.Monad.Trans.Resource (runResourceT)
import Lib -- estimators
import Info -- twitter API credentials
query :: APIRequest StatusesFilter StreamingAPI
query = statusesFilter [Track ["dog","fire"]]
isVowel :: Char -> Bool
isVowel x = x `elem` ("aiueo"::[Char])
-- Feature extraction (here just getting length and %consonant characters for testing)
process :: StreamingAPI -> Maybe (Double,Double)
process (SStatus status ) =
Just (tweetLength, propVowels)
where tweet = status ^. statusText
tweetLength = (fromIntegral $ T.length tweet ):: Double
propVowels = (fromIntegral $ T.length $ T.filter (not . isVowel) tweet) / (tweetLength)
process _ = Nothing
-- Print incrementally updated results
processPrint :: (Show a) => a -> IO ()
processPrint = do
T.putStrLn . T.pack . show
-- inverse transform using sequential search
qPois' :: Double -> Double -> Int -> Double -> Double -> Int
qPois' l u x p s = if u < s then x else qPois' l u x' p' s'
where x' = x+1
p' = p*l/(fromIntegral x')
s' = s+p'
qPois :: Double -> Double -> Int
qPois l u = qPois' l u 0 (exp $ -l) (exp $ -l)
-- poisSource :: Monad m => Source m Int
-- poisSource = CL.sourceList [1..] =$= CL.map (qPois 1)
--
-- poisSource' = newResumableSource poisSource
foo :: MonadIO m => Conduit StreamingAPI m (Maybe Double,Int)
foo = CL.mapM go where
go u = do
s <- liftIO $ (randomRIO (0,1) :: IO Double)
let s' = qPois 1 s
return (fmap fst $ process u,s')
-- blah = fuseBoth (CL.map process =$= CL.catMaybes =$= CL.map fst) poisSource
-- basic example pipeline. Computes a running estimate of mean and variance for tweet length
-- Could replace the initial estimate (0,0,0) with pseudo-data to act as a prior
-- Estimator defined in Lib.hs
-- pipeline = CL.map process =$= CL.map (fmap fst) =$= cumulativeStats (0,0,0) =$= summarizeMean
pipeline = foo =$= cumulativeStatsWeighted (0,0,0) =$= summarizeMean
main :: IO ()
-- main = return ()
main = do
mgr <- newManager tlsManagerSettings
runResourceT $ do
src <- stream twInfo mgr query
-- Only processes 100 tweets here.
src $$+- pipeline =$= CL.isolate 100 =$= CL.mapM_ (liftIO . print)
| phasedchirp/chirpy-learning | app/Main.hs | bsd-3-clause | 2,600 | 0 | 13 | 509 | 722 | 400 | 322 | 49 | 2 |
{-# LANGUAGE BangPatterns, FlexibleContexts, OverloadedStrings #-}
{-# OPTIONS -fno-warn-orphans #-}
-- |
-- File : NagiosStatus
-- Copyright : (c) Mike Maul 2013
--
-- License : BSD3
-- Maintainer : mike.maul@gmail.com
-- Stability : experimental
-- Portability : GHC
-- Description : Ultimately will place host-status
-- preformance-data into a RRD database
-- right now will watch status.dat and parse
-- when changed.
import qualified Data.HashMap.Strict as HMap
import System.FSNotify
import Filesystem
import Filesystem.Path.CurrentOS as O
import Data.Text as T
import Data.Maybe (catMaybes, isJust, fromJust)
import qualified Data.Map as Map
import System.Console.CmdArgs.Explicit
import Control.Monad
import Control.Monad.IO.Class (liftIO)
import System.Exit
import qualified Data.Either as E
import NagiosStatus
import Config
import Text.Parsec.Error
import Data.Maybe
import RRD
--import Data.HashMap.Strict as Map
-------------
--- Types ---
-------------
data HostStatusSummary = HostStatusSummary {
hssHostName::T.Text,
hssCheckCommand::T.Text,
hssCurrentState::Int,
hssPluginOutput::Text,
hssPerformanceData::Float,
hssLastCheck::Int
} deriving (Show)
--status_path = "/home/mmaul/hacking/haskell/yesod/magic-mirror"
fileToBeWatched::O.FilePath->Event->Bool
fileToBeWatched fn e =
case e of
Added f t
| f == fn -> True
Modified f t
| f == fn -> True
otherwise -> False
onlyHostStatus::[Section]->[Section]
onlyHostStatus section = Prelude.filter (\s -> case s of
HostStatus _ -> True
_ -> False) section
getFileName::Event->String
getFileName e =
O.encodeString $ case e of
Added f t -> f
Modified f t -> f
Removed f t -> f
shsHelper::String->IO Float
shsHelper v = do
print v
f <-parsePreformanceData v
print f
return (case f of
Right s -> s
_ -> 0.0)
shsHelper1:: Section -> IO HostStatusSummary
shsHelper1 sv = do
let (HostStatus v) = sv
xv <- shsHelper (fromJust $ Map.lookup "performance_data" v)
return HostStatusSummary {
hssHostName = (pack $ fromJust $ Map.lookup "host_name" v),
hssCheckCommand = (pack $ fromJust $ Map.lookup "check_command" v),
hssCurrentState = (read (fromJust $ Map.lookup "current_state" v))::Int,
hssPluginOutput = pack $ (fromJust ( Map.lookup "plugin_output" v)),
hssPerformanceData = xv,
hssLastCheck = (read (fromJust $ Map.lookup "last_check" v))::Int
}
summarizeHostStatus::Event -> IO [IO HostStatusSummary]
summarizeHostStatus evt = do
status <- (readStatus $ getFileName evt) -- ::IO (Either Text.Parsec.Error.ParseError [Section])
let Right r = status
return (Prelude.map (shsHelper1)
(onlyHostStatus r))
main :: IO ()
main = do
-- Process command line arguments
!args <- processArgs argsMode
when (isJust $ Prelude.lookup flHelp args) $ do
print $ helpText [] HelpFormatDefault argsMode
exitSuccess
let debug = isJust $ Prelude.lookup flDebug args
configFile = case (Prelude.lookup flConfig) args of
Just x -> x
Nothing -> error "Missing config file (-c)"
-- Load the config file
wc <- loadConfig configFile debug
print wc
--print (maybeToList . resolveToRrdConfigs wc)
let wd = O.fromText $ wcVar wc
rrdMaps = getit wc "external" -- :: WriterConfig -> Text -> t -> Config.RrdConfigMap
checkMap = Map.fromList [((pack "-"),1)]--Map.empty -- ::Map.HashMap T.Text Int
print wd
man <- startManager
watchTree man wd
(fileToBeWatched
(O.fromText $ T.append (T.append (wcVar wc) "/") "status.dat"))
(\e -> do
hs <- summarizeHostStatus e
--writeValues hs
-- let r = RrdConfig (T.pack "check-dns-server-alive") 60 [ T.pack "DS:Milliseconds:DERIVE:120:0:U" ] [ T.pack "RRA:AVERAGE:0.5:1:2880",T.pack "RRA:AVERAGE:0.5:15:1344",T.pack "RRA:AVERAGE:0.5:1440:730"::Text ]
-- updateRrd r (T.pack "x.rrd") 1381553944 55
mapM_ (\x -> do
hss <- x
let lastCheck = hssLastCheck hss
v = round((hssPerformanceData hss) * 1000.0::Float)
hostName = hssHostName hss
r = fromJust $ HMap.lookup (hssCheckCommand hss) rrdMaps
lastLastCheck = Map.lookup hostName checkMap
--if ((not (isJust lastLastCheck)) or (not ((fromJust lastLastCheck) == lastCheck)))
if (not (isJust lastLastCheck)) || (not $ (fromJust lastLastCheck) == lastCheck)
then do print r
print v
updateRrd r (T.append hostName ".rrd") lastCheck v
else do
print ("Last check has not changed for " ++ (unpack hostName))
print lastCheck
--print (fromJust lastLastCheck)
--(print hss)
--return hss
-- when ((isJust lastLastCheck) and ((fromJust lastLastCheck) == lastCheck))
--if (isJust lastLastCheck)
-- then do
-- print "X"
-- --print ("Last check has not changed for " ++ (unpack hostName))
-- --return hs
) hs
--print xs
)
print "press retrun to stop"
getLine
print "watching stopped, press retrun to exit"
stopManager man
getLine
return ()
getit :: WriterConfig -> Text -> RrdConfigMap
getit wc probe =
let probes = wcProbes wc
pc = fromJust $ HMap.lookup probe probes
in
pcRrdConfigs pc -- (HMap.lookup pn (pcRrdConfigs pc))
--resolveToRrdConfigs :: WriterConfig -> Value -> Maybe (Integer, [(RrdConfig, Value)])
--resolveToRrdConfigs wc v = do
-- addr <- getAddress v
-- pc <- HashMap.lookup addr $ wcProbes wc
-- msg <- getMessage v
-- sync <- getMessageSync msg
-- ds <- getMessageData msg
-- return (sync, lookupRrdConfigs pc ds)
--lookupRrdConfigs :: ProbeConfig -> [T.Text] -> [RrdConfig]
--lookupRrdConfigs pc ds = do
-- var <- ds
-- maybe [] Map.lookup var $ pcRrdConfigs pc
--writeValues :: Integer -> [(RrdConfig, Value)] -> IO ()
--writeValues sync ds = mapM_ (uncurry $ writeValue sync) ds
--writeValue :: Integer -> RrdConfig -> Value -> IO ()
--writeValue sync rrd (Number n) = updateRrd rrd sync n
--writeValue _ _ _ = return ()
-- Command line argument processing
argsMode :: Mode [(Name, String)]
argsMode =
(modeEmpty []) {
modeNames = [ "RRDWriter" ]
, modeHelp = "Nagios status.dat RRD writer"
, modeGroupFlags = toGroup [
flagNone [flDebug, "D"] (\v -> (flDebug, ""):v) "Enable debug output"
, flagReq [flConfig, "c"] (updateArg flConfig) "FILE" "Path to config FILE"
, flagHelpSimple ((flHelp, ""):)
]
}
where
updateArg fl x v = Right $ (fl, x):v
flDebug = "debug"
flConfig = "config"
flHelp = "help"
| mmaul/nagios-status | src/RRDWriter.hs | bsd-3-clause | 6,880 | 0 | 24 | 1,726 | 1,523 | 807 | 716 | 131 | 3 |
{-# LANGUAGE BangPatterns, Trustworthy #-}
-- | For day-to-day use, please see "Data.Patch"
module Data.Patch.Internal where
import Data.Monoid
import Data.Ord
import qualified Data.List as List
import qualified Data.Vector as Vector
import Data.Vector (Vector)
import Data.Vector.Distance
import Lens.Micro
import Control.Applicative
import Data.Function
-- $setup
-- >>> import Test.QuickCheck
-- >>> :{
-- let
-- nonEmpty :: Vector a -> Bool
-- nonEmpty = (>0) . Vector.length
-- editsTo :: Arbitrary a => Vector a -> Gen (Edit a)
-- editsTo v = do
-- i <- choose (0, Vector.length v -1)
-- c <- elements [const (Insert i), \o _ -> Delete i o, Replace i]
-- x <- arbitrary
-- return $ c (v Vector.! i) x
-- patchesFrom' :: (Eq a, Arbitrary a) => Vector a -> Gen (Patch a)
-- patchesFrom' v | Vector.length v > 0 = fromList <$> listOf (editsTo v)
-- patchesFrom' _ | otherwise = fromList <$> listOf (Insert 0 <$> arbitrary)
-- patchesFrom :: Vector Int -> Gen (Patch Int)
-- patchesFrom = patchesFrom'
-- historyFrom d 0 = return []
-- historyFrom d m = do
-- p <- patchesFrom d
-- r <- historyFrom (apply p d) $ m - 1
-- return (p:r)
-- :}
--
-- >>> :set -XScopedTypeVariables
-- >>> instance Arbitrary a => Arbitrary (Vector a) where arbitrary = Vector.fromList <$> listOf arbitrary
--
-- Blah
--
-- $doctest_sucks
-- prop> forAll (patchesFrom d) $ \ x -> read (show x) == x
-- | A /patch/ is a collection of edits performed to a /document/, in this case a 'Vector'. They are
-- implemented as a list
-- of 'Edit', and can be converted to and from raw lists of edits using 'toList' and 'fromList'
-- respectively.
--
-- Patches form a group (a 'Monoid' with inverses), where the inverse element can be computed with
-- 'inverse' and the group operation is /composition/ of patches. Applying @p1 <> p2@ is the
-- same as applying @p1@ /then/ @p2@ (see 'apply'). This composition operator may produce structurally
-- different patches depending on associativity, however the patches are guaranteed to be /equivalent/
-- in the sense that the resultant document will be the same when they are applied.
--
-- prop> forAll (patchesFrom d) $ \a -> a <> mempty == a
--
-- prop> forAll (patchesFrom d) $ \a -> mempty <> a == a
--
-- prop> forAll (historyFrom d 3) $ \[a, b, c] -> apply (a <> (b <> c)) d == apply ((a <> b) <> c) d
--
-- The indices of the 'Edit' s are all based on the /original document/, so:
--
-- >>> apply (fromList [Insert 0 'a', Insert 1 'b']) (Vector.fromList "123")
-- "a1b23"
--
-- >>> apply (fromList [Insert 0 'a', Insert 0 'b']) (Vector.fromList "123")
-- "ab123"
--
-- Note that the first 'Insert' didn't introduce an offset for the second.
newtype Patch a = Patch [Edit a] deriving (Eq)
instance Show a => Show (Patch a) where
show (Patch ls) = "fromList " ++ show ls
instance (Eq a, Read a) => Read (Patch a) where
readsPrec _ ('f':'r':'o':'m':'L':'i':'s':'t':' ':r) = map (\(a,s) -> (fromList a, s)) $ reads r
readsPrec _ _ = []
-- | An 'Edit' is a single alteration of the vector, either inserting, removing, or replacing an element.
--
-- Useful optics are provided below, for the 'index', the 'old' element, and the 'new' element.
data Edit a = Insert Int a -- ^ @Insert i x@ inserts the element @x@ at position @i@.
| Delete Int a -- ^ @Delete i x@ deletes the element @x@ from position @i@.
| Replace Int a a -- ^ @Replace i x x'@ replaces the element @x@ at position @i@ with @x'@.
deriving (Show, Read, Eq)
-- | Compute the inverse of a patch, such that:
--
-- prop> forAll (patchesFrom d) $ \p -> p <> inverse p == mempty
--
-- prop> forAll (patchesFrom d) $ \p -> inverse p <> p == mempty
--
-- prop> forAll (patchesFrom d) $ \p -> inverse (inverse p) == p
--
-- prop> forAll (historyFrom d 2) $ \[p, q] -> inverse (p <> q) == inverse q <> inverse p
--
-- prop> forAll (patchesFrom d) $ \p -> inverse mempty == mempty
inverse :: Patch a -> Patch a
inverse (Patch ls) = Patch $ snd $ List.mapAccumL go 0 ls
where
go :: Int -> Edit a -> (Int, Edit a)
go off (Insert i x) = (off + 1, Delete (off + i) x)
go off (Delete i x) = (off - 1, Insert (off + i) x)
go off (Replace i a b) = (off, Replace (off + i) b a)
-- | A lens for the index where an edit is to be performed.
--
-- prop> nonEmpty d ==> forAll (editsTo d) $ \e -> set index v e ^. index == v
--
-- prop> nonEmpty d ==> forAll (editsTo d) $ \e -> set index (e ^. index) e == e
--
-- prop> nonEmpty d ==> forAll (editsTo d) $ \e -> set index v' (set index v e) == set index v' e
index :: Lens' (Edit a) Int
index f (Insert i a) = fmap (flip Insert a) $ f i
index f (Delete i a) = fmap (flip Delete a) $ f i
index f (Replace i a b) = fmap (\i' -> Replace i' a b) $ f i
-- | A traversal for the old element to be replaced/deleted. Empty in the case of an @Insert@.
old :: Traversal' (Edit a) a
old _ (Insert i a) = pure $ Insert i a
old f (Delete i a) = Delete i <$> f a
old f (Replace i a b) = Replace i <$> f a <*> pure b
-- | A traversal for the new value to be inserted or replacing the old value. Empty in the case of a @Delete@.
new :: Traversal' (Edit a) a
new f (Insert i a) = Insert i <$> f a
new _ (Delete i a) = pure $ Delete i a
new f (Replace i a b) = Replace i <$> pure a <*> f b
-- | Convert a patch to a list of edits.
toList :: Patch a -> [Edit a]
toList (Patch a) = a
-- | Directly convert a list of edits to a patch, without sorting edits by index, and resolving contradictory
-- edits. Use this function if you know that the input list is already a wellformed patch.
unsafeFromList :: [Edit a] -> Patch a
unsafeFromList = Patch
-- | Convert a list of edits to a patch, making sure to eliminate conflicting edits and sorting by index.
fromList :: Eq a => [Edit a] -> Patch a
fromList = Patch . concat . map normalise . List.groupBy ((==) `on` (^. index)) . List.sortBy (comparing (^. index))
-- | Internal: Eliminate conflicting edits
normalise :: [Edit a] -> [Edit a]
normalise grp = let (inserts, deletes, replaces) = partition3 grp
in normalise' inserts deletes replaces
where partition3 (x@(Insert {}):xs) = let (i,d,r) = partition3 xs in (x:i,d,r)
partition3 (x@(Delete {}):xs) = let (i,d,r) = partition3 xs in (i,x:d,r)
partition3 (x@(Replace {}):xs) = let (i,d,r) = partition3 xs in (i,d,x:r)
partition3 [] = ([],[],[])
normalise' (Insert _ x:is) (Delete i y:ds) rs = normalise' is ds (Replace i y x : rs)
normalise' is [] rs = is ++ take 1 rs
normalise' [] (d:ds) _ = [d]
instance Eq a => Monoid (Patch a) where
mempty = Patch []
mappend (Patch a) (Patch b) = Patch $ merge a b (0 :: Int)
where
merge [] ys off = map (over index (+ off)) ys
merge xs [] _ = xs
merge (x:xs) (y:ys) off = let
y' = over index (+ off) y
in case comparing (^. index) x y' of
LT -> x : merge xs (y:ys) (off + offset x)
GT -> y' : merge (x:xs) ys off
EQ -> case (x,y') of
(Delete i o, Insert _ n) -> replace i o n $ merge xs ys (off + offset x)
(Delete {}, _) -> x : merge xs (y:ys) (off + offset x)
(_, Insert {}) -> y' : merge (x:xs) ys off
(Replace i o _, Replace _ _ o') -> replace i o o' $ merge xs ys off
(Replace i o _, Delete {}) -> Delete i o : merge xs ys off
(Insert i _, Replace _ _ o') -> Insert i o' : merge xs ys (off + offset x)
(Insert {}, Delete {}) -> merge xs ys (off + offset x)
offset (Insert {}) = -1
offset (Delete {}) = 1
offset (Replace {}) = 0
replace i o n | o == n = id
replace i o n | otherwise = (Replace i o n :)
-- | Apply a patch to a document.
--
-- Technically, 'apply' is a /monoid morphism/ to the monoid of endomorphisms @Vector a -> Vector a@,
-- and that's how we can derive the following two laws:
--
-- prop> forAll (historyFrom d 2) $ \[a, b] -> apply b (apply a d) == apply (a <> b) d
--
-- prop> apply mempty d == d
--
apply :: Patch a -> Vector a -> Vector a
apply (Patch s) i = Vector.concat $ go s [i] 0
where go [] v _ = v
go (a : as) v x
| x' <- a ^. index
= let (prefix, rest)
| x' > x = splitVectorListAt (x' - x) v
| otherwise = ([], v)
conclusion (Insert _ e) = Vector.singleton e : go as rest x'
conclusion (Delete _ _) = go as (drop1 rest) (x' + 1)
conclusion (Replace _ _ e) = go as (Vector.singleton e : drop1 rest) (x')
in prefix ++ conclusion a
drop1 :: [Vector a] -> [Vector a]
drop1 [] = []
drop1 (v:vs) | Vector.length v > 0 = Vector.drop 1 v : vs
drop1 (_:vs) | otherwise = drop1 vs
splitVectorListAt :: Int -> [Vector a] -> ([Vector a], [Vector a])
splitVectorListAt _ [] = ([],[])
splitVectorListAt j (v:vs) | j < Vector.length v = let (v1,v2) = Vector.splitAt j v in ([v1],v2:vs)
| otherwise = let (p1,p2) = splitVectorListAt (j - Vector.length v) vs
in (v:p1, p2)
-- | Compute the difference between two documents, using the Wagner-Fischer algorithm. O(mn) time and space.
--
-- prop> apply (diff d e) d == e
--
-- prop> apply (diff d e) d == apply (inverse (diff e d)) d
--
-- prop> apply (diff a b <> diff b c) a == apply (diff a c) a
--
diff :: Eq a => Vector a -> Vector a -> Patch a
diff v1 v2 = let (_ , s) = leastChanges params v1 v2
in unsafeFromList $ adjust 0 $ s
where
adjust _ [] = []
adjust !o (Insert i x:rest) = Insert (i+o) x : adjust (o-1) rest
adjust !o (Delete i x:rest) = Delete (i+o) x : adjust (o+1) rest
adjust !o (Replace i x x':rest) = Replace (i+o) x x' : adjust o rest
params :: Eq a => Params a (Edit a) (Sum Int)
params = Params { equivalent = (==)
, delete = \i c -> Delete i c
, insert = \i c -> Insert i c
, substitute = \i c c' -> Replace i c c'
, cost = \_ -> Sum 1
, positionOffset = \x -> case x of
Delete {} -> 0
_ -> 1
}
| phadej/patches-vector | Data/Patch/Internal.hs | bsd-3-clause | 10,465 | 0 | 20 | 2,999 | 3,058 | 1,608 | 1,450 | 115 | 7 |
{-# LANGUAGE OverloadedStrings #-}
module Templates.CoreForm where
import GHCCore
import Templates
import Text.Blaze ((!))
import qualified Text.Blaze.Html4.Strict as H
import qualified Text.Blaze.Html4.Strict.Attributes as A
coreForm :: H.Html
coreForm = H.p ! A.class_ "core-form" $ H.form ! A.action "/add" ! A.enctype "multipart/form-data" ! A.method "POST" $ do
H.h2 ! A.class_ "formHead" $ "Generate GHC Core for"
H.p ! A.class_ "author" $ inputTextFor "Author" "author"
H.p ! A.class_ "title" $ inputTextFor "Title" "title"
H.p ! A.class_ "haskell" $ H.textarea ! A.name "haskell" ! A.rows "50" ! A.cols "100" $ "Your Haskell code here."
H.p ! A.class_ "optlevel" $ selectFor "Optimization Level"
"optlevel"
[ ("No optimizations: -O0", "-O0")
, ("Basic optimizations: -O1", "-O1")
, ("Agressive optimizations: -O2", "-O2")
]
H.p ! A.class_ "ghcver" $ selectFor "GHC version"
"ghcver"
(map (\x -> (x, x)) ghcVersions)
H.p ! A.class_ "ismodule" $
inputTextWithHelpTextFor "Is this a module?"
"modulename"
"Is there a 'module ... where' clause in your code? If not, we enclose it in a M<n>.hs file, with a 'module M<n> where' at the top of the file, so leave this empty. If yes, please enter the module name."
H.p ! A.class_ "submit" $ H.input ! A.type_ "submit" ! A.value "Submit" | alpmestan/core-online | src/Templates/CoreForm.hs | bsd-3-clause | 1,691 | 0 | 15 | 600 | 383 | 195 | 188 | 26 | 1 |
module Main where
import Cz.MartinDobias.ChristmasKoma.PadCracker
import System.Console.ArgParser
import Data.Char(digitToInt, chr, ord)
import Numeric(showHex)
import Text.Printf(printf)
data Input = Input String String Int Int
deriving (Show)
inputParser :: ParserSpec Input
inputParser = Input
`parsedBy` reqPos "messages" `Descr` "Path to file with HEX encoded messages"
`andBy` optPos "" "passphrase" `Descr` "Passphrase HEX encoded with wildcards (_)"
`andBy` optPos 5 "keyLength" `Descr` "Resulting passphrase length to print"
`andBy` optPos 0 "keyStart" `Descr` "Resulting passphrase start position to print"
inputInterface :: IO (CmdLnInterface Input)
inputInterface =
(`setAppDescr` "Vit Koma Christmas Cracker")
. (`setAppEpilog` "Merry Christmas")
<$> mkApp inputParser
parsePhrase :: String -> Passphrase
parsePhrase [] = [[]]
parsePhrase [c] = case c of
'_' -> [[]]
_ -> error "Invalid input"
parsePhrase (h : l : cs) = case h of
'_' -> [] : parsePhrase (l : cs)
_ -> [chr (digitToInt h * 16 + digitToInt l)] : parsePhrase cs
parseMessage :: String -> Message
parseMessage [] = []
parseMessage [c] = if c == '\r' || c == '\n' then [] else error "Invalid input"
parseMessage (h : l : cs) = chr (digitToInt h * 16 + digitToInt l) : parseMessage cs
app :: Input -> IO()
app (Input mf pf l off) = do
putStrLn ("Processing " ++ mf ++ ", with initial passphrase: " ++ pf)
m <- readFile mf
let ms = map parseMessage $ lines m
p = parsePhrase pf
r = crack ms p
--putStrLn "Original messages"
--mapM_ print ms
--putStrLn ""
putStrLn "Decoded messages"
mapM_ (print . decode r) ms
putStrLn ""
printf "Resulting passphrase candidate %v - %v\n" off (off + l)
let rr = take l (drop off (map (map (showHex . ord)) r))
mapM_ (print . foldr (\f x -> ' ' : f x) "") rr
main :: IO()
main = do
input <- inputInterface
runApp input app
| martindobias/christmass-koma | src/Main.hs | bsd-3-clause | 2,007 | 0 | 18 | 485 | 699 | 363 | 336 | 48 | 3 |
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, OverloadedStrings, DataKinds, TypeOperators, TypeSynonymInstances, FlexibleInstances #-}
module WebApi.RouteSpec (spec) where
import WebApi hiding (get, put, post)
import Data.Text (Text)
import Test.Hspec
import Test.Hspec.Wai
import qualified Network.Wai as Wai
-- withApp :: SpecWith Wai.Application -> Spec
withApp :: SpecWith ((),Wai.Application) -> Spec
withApp = with (return routingSpecApp)
routingSpecApp :: Wai.Application
routingSpecApp = serverApp serverSettings RoutingSpecImpl
data RoutingSpec
data RoutingSpecImpl = RoutingSpecImpl
type StaticRoute1 = "this":/"is":/"a":/"static":/"route"
type StaticRoute2 = Static "static_route"
type RouteWithParam = "param":/Int
type RouteWithParamAtBegin = Bool:/"param"
type RouteWithParams = Text:/"param1":/Int:/"param2"
type OverlappingRoute = "foo":/"param1":/Int:/"param2"
type NamespaceR = RoutingSpec :// "foo" :/ "bar"
type NamespaceDyn = RoutingSpec :// "foo" :/ Int :/ "bar"
type NamespaceDynBeg = RoutingSpec :// Int :/ "baz" :/ "bar"
type NamespaceStatic = RoutingSpec :// "bar"
-- type NamespaceJustDyn = RoutingSpec :// Int
instance WebApi RoutingSpec where
type Version RoutingSpec = ()
type Apis RoutingSpec = '[ Route '[GET] StaticRoute1
, Route '[GET] StaticRoute2
, Route '[GET] RouteWithParam
, Route '[GET] RouteWithParamAtBegin
, Route '[GET] OverlappingRoute
, Route '[GET] RouteWithParams
, Route '[GET] NamespaceR
, Route '[GET] NamespaceStatic
, Route '[GET] NamespaceDyn
, Route '[GET] NamespaceDynBeg
-- , Route '[GET] NamespaceJustDyn
]
instance ApiContract RoutingSpec GET StaticRoute1 where
type ApiOut GET StaticRoute1 = ()
instance ApiContract RoutingSpec GET StaticRoute2 where
type ApiOut GET StaticRoute2 = ()
instance ApiContract RoutingSpec GET RouteWithParam where
type ApiOut GET RouteWithParam = ()
instance ApiContract RoutingSpec GET RouteWithParamAtBegin where
type ApiOut GET RouteWithParamAtBegin = Text
instance ApiContract RoutingSpec GET RouteWithParams where
type ApiOut GET RouteWithParams = Text
instance ApiContract RoutingSpec GET OverlappingRoute where
type ApiOut GET OverlappingRoute = Text
instance ApiContract RoutingSpec GET NamespaceR where
type ApiOut GET NamespaceR = Text
instance ApiContract RoutingSpec GET NamespaceDyn where
type ApiOut GET NamespaceDyn = Text
instance ApiContract RoutingSpec GET NamespaceDynBeg where
type ApiOut GET NamespaceDynBeg = Text
instance ApiContract RoutingSpec GET NamespaceStatic where
type ApiOut GET NamespaceStatic = Text
{-
instance ApiContract RoutingSpec GET NamespaceJustDyn where
type ApiOut GET NamespaceJustDyn = Text
-}
instance WebApiServer RoutingSpecImpl where
type HandlerM RoutingSpecImpl = IO
type ApiInterface RoutingSpecImpl = RoutingSpec
instance ApiHandler RoutingSpecImpl GET StaticRoute1 where
handler _ _ = respond ()
instance ApiHandler RoutingSpecImpl GET StaticRoute2 where
handler _ _ = respond ()
instance ApiHandler RoutingSpecImpl GET RouteWithParam where
handler _ _ = respond ()
instance ApiHandler RoutingSpecImpl GET RouteWithParamAtBegin where
handler _ _ = respond "RouteWithParamAtBegin"
instance ApiHandler RoutingSpecImpl GET RouteWithParams where
handler _ _ = respond "RouteWithParams"
instance ApiHandler RoutingSpecImpl GET OverlappingRoute where
handler _ _ = respond "OverlappingRoute"
instance ApiHandler RoutingSpecImpl GET NamespaceR where
handler _ _ = respond "Namespace"
instance ApiHandler RoutingSpecImpl GET NamespaceStatic where
handler _ _ = respond "NamespaceStatic"
instance ApiHandler RoutingSpecImpl GET NamespaceDyn where
handler _ _ = respond "NamespaceDyn"
instance ApiHandler RoutingSpecImpl GET NamespaceDynBeg where
handler _ _ = respond "NamespaceDynBeg"
{-
instance ApiHandler RoutingSpecImpl GET NamespaceJustDyn where
handler _ _ = respond "NamespaceJustDyn"
-}
spec :: Spec
spec = withApp $ describe "WebApi routing" $ do
context "static route with only one piece" $ do
it "should be 200 ok" $ do
get "static_route" `shouldRespondWith` 200
context "static route with many pieces" $ do
it "should be 200 ok" $ do
get "this/is/a/static/route" `shouldRespondWith` 200
context "route with param" $ do
it "should be 200 ok" $ do
get "param/5" `shouldRespondWith` 200
context "route with param at beginning" $ do
it "should be 200 ok returning RouteWithParamAtBegin" $ do
get "True/param" `shouldRespondWith` "\"RouteWithParamAtBegin\"" { matchStatus = 200 }
context "route with multiple params" $ do
it "should be 200 ok returning RouteWithParams" $ do
get "bar/param1/5/param2" `shouldRespondWith` "\"RouteWithParams\"" { matchStatus = 200 }
context "overlapping route selected by order" $ do
it "should be 200 ok returning OverlappingRoute" $ do
get "foo/param1/5/param2" `shouldRespondWith` "\"OverlappingRoute\"" { matchStatus = 200 }
context "namespaced route" $ do
it "should be 200 ok returning Namespace" $ do
get "foo/bar" `shouldRespondWith` "\"Namespace\"" { matchStatus = 200 }
context "namespaced static route" $ do
it "should be 200 ok returning NamespaceStatic" $ do
get "bar" `shouldRespondWith` "\"NamespaceStatic\"" { matchStatus = 200 }
context "namespaced dynamic route" $ do
it "should be 200 ok returning NamespaceDyn" $ do
get "foo/5/bar" `shouldRespondWith` "\"NamespaceDyn\"" { matchStatus = 200 }
context "namespaced dynamic route at beginning" $ do
it "should be 200 ok returning NamespaceDynBeg" $ do
get "5/baz/bar" `shouldRespondWith` "\"NamespaceDynBeg\"" { matchStatus = 200 }
{-
context "namespaced route with just one dynamic at the beginning" $ do
it "should be 200 ok returning NamespaceJustDyn" $ do
get "5" `shouldRespondWith` "\"NamespaceJustDyn\"" { matchStatus = 200 }
-}
context "non existing route" $ do
it "should be 404 ok" $ do
get "foo/param1/5/param3" `shouldRespondWith` 404
| byteally/webapi | webapi/tests/WebApi/RouteSpec.hs | bsd-3-clause | 6,397 | 0 | 16 | 1,365 | 1,379 | 706 | 673 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.Groups
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- All enumeration groups from the
-- <http://www.opengl.org/registry/ OpenGL registry>.
--
--------------------------------------------------------------------------------
module Graphics.GL.Groups (
-- $EnumerantGroups
) where
-- $EnumerantGroups
-- Note that the actual set of valid values depend on the OpenGL version, the
-- chosen profile and the supported extensions. Therefore, the groups mentioned
-- here should only be considered a rough guideline, for details see the OpenGL
-- specification.
--
-- === #AccumOp# AccumOp
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ACCUM'
-- * 'Graphics.GL.Tokens.GL_LOAD'
-- * 'Graphics.GL.Tokens.GL_RETURN'
-- * 'Graphics.GL.Tokens.GL_MULT'
-- * 'Graphics.GL.Tokens.GL_ADD'
--
-- === #AlphaFunction# AlphaFunction
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALWAYS'
-- * 'Graphics.GL.Tokens.GL_EQUAL'
-- * 'Graphics.GL.Tokens.GL_GEQUAL'
-- * 'Graphics.GL.Tokens.GL_GREATER'
-- * 'Graphics.GL.Tokens.GL_LEQUAL'
-- * 'Graphics.GL.Tokens.GL_LESS'
-- * 'Graphics.GL.Tokens.GL_NEVER'
-- * 'Graphics.GL.Tokens.GL_NOTEQUAL'
--
-- === #ArrayObjectPNameATI# ArrayObjectPNameATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_OBJECT_BUFFER_SIZE_ATI'
-- * 'Graphics.GL.Tokens.GL_OBJECT_BUFFER_USAGE_ATI'
--
-- === #ArrayObjectUsageATI# ArrayObjectUsageATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_STATIC_ATI'
-- * 'Graphics.GL.Tokens.GL_DYNAMIC_ATI'
--
-- === #AtomicCounterBufferPName# AtomicCounterBufferPName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER'
--
-- === #AttribMask# AttribMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ACCUM_BUFFER_BIT'
-- * 'Graphics.GL.Tokens.GL_ALL_ATTRIB_BITS'
-- * 'Graphics.GL.Tokens.GL_COLOR_BUFFER_BIT'
-- * 'Graphics.GL.Tokens.GL_CURRENT_BIT'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BUFFER_BIT'
-- * 'Graphics.GL.Tokens.GL_ENABLE_BIT'
-- * 'Graphics.GL.Tokens.GL_EVAL_BIT'
-- * 'Graphics.GL.Tokens.GL_FOG_BIT'
-- * 'Graphics.GL.Tokens.GL_HINT_BIT'
-- * 'Graphics.GL.Tokens.GL_LIGHTING_BIT'
-- * 'Graphics.GL.Tokens.GL_LINE_BIT'
-- * 'Graphics.GL.Tokens.GL_LIST_BIT'
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_BIT' (aliases: 'Graphics.GL.Tokens.GL_MULTISAMPLE_BIT_3DFX', 'Graphics.GL.Tokens.GL_MULTISAMPLE_BIT_ARB', 'Graphics.GL.Tokens.GL_MULTISAMPLE_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_PIXEL_MODE_BIT'
-- * 'Graphics.GL.Tokens.GL_POINT_BIT'
-- * 'Graphics.GL.Tokens.GL_POLYGON_BIT'
-- * 'Graphics.GL.Tokens.GL_POLYGON_STIPPLE_BIT'
-- * 'Graphics.GL.Tokens.GL_SCISSOR_BIT'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BUFFER_BIT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BIT'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_BIT'
-- * 'Graphics.GL.Tokens.GL_VIEWPORT_BIT'
--
-- === #AttributeType# AttributeType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_FLOAT_VEC2' (alias: 'Graphics.GL.Tokens.GL_FLOAT_VEC2_ARB')
-- * 'Graphics.GL.Tokens.GL_FLOAT_VEC3' (alias: 'Graphics.GL.Tokens.GL_FLOAT_VEC3_ARB')
-- * 'Graphics.GL.Tokens.GL_FLOAT_VEC4' (alias: 'Graphics.GL.Tokens.GL_FLOAT_VEC4_ARB')
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_VEC2'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_VEC3'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_VEC4'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_INT_VEC2' (alias: 'Graphics.GL.Tokens.GL_INT_VEC2_ARB')
-- * 'Graphics.GL.Tokens.GL_INT_VEC3' (alias: 'Graphics.GL.Tokens.GL_INT_VEC3_ARB')
-- * 'Graphics.GL.Tokens.GL_INT_VEC4' (alias: 'Graphics.GL.Tokens.GL_INT_VEC4_ARB')
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_VEC2'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_VEC3'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_VEC4'
-- * 'Graphics.GL.Tokens.GL_BOOL' (alias: 'Graphics.GL.Tokens.GL_BOOL_ARB')
-- * 'Graphics.GL.Tokens.GL_BOOL_VEC2' (alias: 'Graphics.GL.Tokens.GL_BOOL_VEC2_ARB')
-- * 'Graphics.GL.Tokens.GL_BOOL_VEC3' (alias: 'Graphics.GL.Tokens.GL_BOOL_VEC3_ARB')
-- * 'Graphics.GL.Tokens.GL_BOOL_VEC4' (alias: 'Graphics.GL.Tokens.GL_BOOL_VEC4_ARB')
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT2' (alias: 'Graphics.GL.Tokens.GL_FLOAT_MAT2_ARB')
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT3' (alias: 'Graphics.GL.Tokens.GL_FLOAT_MAT3_ARB')
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT4' (alias: 'Graphics.GL.Tokens.GL_FLOAT_MAT4_ARB')
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT2x3' (alias: 'Graphics.GL.Tokens.GL_FLOAT_MAT2x3_NV')
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT2x4' (alias: 'Graphics.GL.Tokens.GL_FLOAT_MAT2x4_NV')
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT3x2' (alias: 'Graphics.GL.Tokens.GL_FLOAT_MAT3x2_NV')
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT3x4' (alias: 'Graphics.GL.Tokens.GL_FLOAT_MAT3x4_NV')
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT4x2' (alias: 'Graphics.GL.Tokens.GL_FLOAT_MAT4x2_NV')
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT4x3' (alias: 'Graphics.GL.Tokens.GL_FLOAT_MAT4x3_NV')
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT2'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT3'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT4'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT2x3'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT2x4'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT3x2'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT3x4'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT4x2'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT4x3'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D' (alias: 'Graphics.GL.Tokens.GL_SAMPLER_1D_ARB')
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D' (alias: 'Graphics.GL.Tokens.GL_SAMPLER_2D_ARB')
-- * 'Graphics.GL.Tokens.GL_SAMPLER_3D' (aliases: 'Graphics.GL.Tokens.GL_SAMPLER_3D_ARB', 'Graphics.GL.Tokens.GL_SAMPLER_3D_OES')
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE' (alias: 'Graphics.GL.Tokens.GL_SAMPLER_CUBE_ARB')
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D_SHADOW' (alias: 'Graphics.GL.Tokens.GL_SAMPLER_1D_SHADOW_ARB')
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_SHADOW' (aliases: 'Graphics.GL.Tokens.GL_SAMPLER_2D_SHADOW_ARB', 'Graphics.GL.Tokens.GL_SAMPLER_2D_SHADOW_EXT')
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D_ARRAY_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_ARRAY_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_RECT' (alias: 'Graphics.GL.Tokens.GL_SAMPLER_2D_RECT_ARB')
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_RECT_SHADOW' (alias: 'Graphics.GL.Tokens.GL_SAMPLER_2D_RECT_SHADOW_ARB')
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_1D'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_3D'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_CUBE'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_1D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_3D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_CUBE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_IMAGE_1D'
-- * 'Graphics.GL.Tokens.GL_IMAGE_2D'
-- * 'Graphics.GL.Tokens.GL_IMAGE_3D'
-- * 'Graphics.GL.Tokens.GL_IMAGE_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_IMAGE_CUBE'
-- * 'Graphics.GL.Tokens.GL_IMAGE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_IMAGE_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_IMAGE_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_IMAGE_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_IMAGE_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_IMAGE_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_1D'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_2D'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_3D'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_CUBE'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_1D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_2D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_3D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_CUBE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT64_ARB' (alias: 'Graphics.GL.Tokens.GL_INT64_NV')
-- * 'Graphics.GL.Tokens.GL_INT64_VEC2_ARB'
-- * 'Graphics.GL.Tokens.GL_INT64_VEC3_ARB'
-- * 'Graphics.GL.Tokens.GL_INT64_VEC4_ARB'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT64_ARB' (alias: 'Graphics.GL.Tokens.GL_UNSIGNED_INT64_NV')
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT64_VEC2_ARB'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT64_VEC3_ARB'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT64_VEC4_ARB'
--
-- === #BindTransformFeedbackTarget# BindTransformFeedbackTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK'
--
-- === #BinormalPointerTypeEXT# BinormalPointerTypeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BYTE'
-- * 'Graphics.GL.Tokens.GL_SHORT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE' (alias: 'Graphics.GL.Tokens.GL_DOUBLE_EXT')
--
-- === #BlendEquationModeEXT# BlendEquationModeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALPHA_MAX_SGIX'
-- * 'Graphics.GL.Tokens.GL_ALPHA_MIN_SGIX'
-- * 'Graphics.GL.Tokens.GL_FUNC_ADD' (alias: 'Graphics.GL.Tokens.GL_FUNC_ADD_EXT')
-- * 'Graphics.GL.Tokens.GL_FUNC_REVERSE_SUBTRACT' (alias: 'Graphics.GL.Tokens.GL_FUNC_REVERSE_SUBTRACT_EXT')
-- * 'Graphics.GL.Tokens.GL_FUNC_SUBTRACT' (alias: 'Graphics.GL.Tokens.GL_FUNC_SUBTRACT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAX' (alias: 'Graphics.GL.Tokens.GL_MAX_EXT')
-- * 'Graphics.GL.Tokens.GL_MIN' (alias: 'Graphics.GL.Tokens.GL_MIN_EXT')
--
-- === #BlendingFactor# BlendingFactor
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ZERO'
-- * 'Graphics.GL.Tokens.GL_ONE'
-- * 'Graphics.GL.Tokens.GL_SRC_COLOR'
-- * 'Graphics.GL.Tokens.GL_ONE_MINUS_SRC_COLOR'
-- * 'Graphics.GL.Tokens.GL_DST_COLOR'
-- * 'Graphics.GL.Tokens.GL_ONE_MINUS_DST_COLOR'
-- * 'Graphics.GL.Tokens.GL_SRC_ALPHA'
-- * 'Graphics.GL.Tokens.GL_ONE_MINUS_SRC_ALPHA'
-- * 'Graphics.GL.Tokens.GL_DST_ALPHA'
-- * 'Graphics.GL.Tokens.GL_ONE_MINUS_DST_ALPHA'
-- * 'Graphics.GL.Tokens.GL_CONSTANT_COLOR'
-- * 'Graphics.GL.Tokens.GL_ONE_MINUS_CONSTANT_COLOR'
-- * 'Graphics.GL.Tokens.GL_CONSTANT_ALPHA'
-- * 'Graphics.GL.Tokens.GL_ONE_MINUS_CONSTANT_ALPHA'
-- * 'Graphics.GL.Tokens.GL_SRC_ALPHA_SATURATE'
-- * 'Graphics.GL.Tokens.GL_SRC1_COLOR'
-- * 'Graphics.GL.Tokens.GL_ONE_MINUS_SRC1_COLOR'
-- * 'Graphics.GL.Tokens.GL_SRC1_ALPHA'
-- * 'Graphics.GL.Tokens.GL_ONE_MINUS_SRC1_ALPHA'
--
-- === #BlitFramebufferFilter# BlitFramebufferFilter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NEAREST'
-- * 'Graphics.GL.Tokens.GL_LINEAR'
--
-- === #Boolean# Boolean
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FALSE'
-- * 'Graphics.GL.Tokens.GL_TRUE'
--
-- === #Buffer# Buffer
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COLOR'
-- * 'Graphics.GL.Tokens.GL_DEPTH'
-- * 'Graphics.GL.Tokens.GL_STENCIL'
--
-- === #BufferAccessARB# BufferAccessARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_READ_ONLY'
-- * 'Graphics.GL.Tokens.GL_WRITE_ONLY'
-- * 'Graphics.GL.Tokens.GL_READ_WRITE'
--
-- === #BufferBitQCOM# BufferBitQCOM
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_BUFFER_BIT7_QCOM'
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_BUFFER_BIT6_QCOM'
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_BUFFER_BIT5_QCOM'
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_BUFFER_BIT4_QCOM'
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_BUFFER_BIT3_QCOM'
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_BUFFER_BIT2_QCOM'
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_BUFFER_BIT1_QCOM'
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_BUFFER_BIT0_QCOM'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BUFFER_BIT7_QCOM'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BUFFER_BIT6_QCOM'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BUFFER_BIT5_QCOM'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BUFFER_BIT4_QCOM'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BUFFER_BIT3_QCOM'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BUFFER_BIT2_QCOM'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BUFFER_BIT1_QCOM'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BUFFER_BIT0_QCOM'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BUFFER_BIT7_QCOM'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BUFFER_BIT6_QCOM'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BUFFER_BIT5_QCOM'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BUFFER_BIT4_QCOM'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BUFFER_BIT3_QCOM'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BUFFER_BIT2_QCOM'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BUFFER_BIT1_QCOM'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BUFFER_BIT0_QCOM'
-- * 'Graphics.GL.Tokens.GL_COLOR_BUFFER_BIT7_QCOM'
-- * 'Graphics.GL.Tokens.GL_COLOR_BUFFER_BIT6_QCOM'
-- * 'Graphics.GL.Tokens.GL_COLOR_BUFFER_BIT5_QCOM'
-- * 'Graphics.GL.Tokens.GL_COLOR_BUFFER_BIT4_QCOM'
-- * 'Graphics.GL.Tokens.GL_COLOR_BUFFER_BIT3_QCOM'
-- * 'Graphics.GL.Tokens.GL_COLOR_BUFFER_BIT2_QCOM'
-- * 'Graphics.GL.Tokens.GL_COLOR_BUFFER_BIT1_QCOM'
-- * 'Graphics.GL.Tokens.GL_COLOR_BUFFER_BIT0_QCOM'
--
-- === #BufferPNameARB# BufferPNameARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BUFFER_SIZE' (alias: 'Graphics.GL.Tokens.GL_BUFFER_SIZE_ARB')
-- * 'Graphics.GL.Tokens.GL_BUFFER_USAGE' (alias: 'Graphics.GL.Tokens.GL_BUFFER_USAGE_ARB')
-- * 'Graphics.GL.Tokens.GL_BUFFER_ACCESS' (alias: 'Graphics.GL.Tokens.GL_BUFFER_ACCESS_ARB')
-- * 'Graphics.GL.Tokens.GL_BUFFER_ACCESS_FLAGS'
-- * 'Graphics.GL.Tokens.GL_BUFFER_IMMUTABLE_STORAGE'
-- * 'Graphics.GL.Tokens.GL_BUFFER_MAPPED' (alias: 'Graphics.GL.Tokens.GL_BUFFER_MAPPED_ARB')
-- * 'Graphics.GL.Tokens.GL_BUFFER_MAP_OFFSET'
-- * 'Graphics.GL.Tokens.GL_BUFFER_MAP_LENGTH'
-- * 'Graphics.GL.Tokens.GL_BUFFER_STORAGE_FLAGS'
--
-- === #BufferPointerNameARB# BufferPointerNameARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BUFFER_MAP_POINTER' (alias: 'Graphics.GL.Tokens.GL_BUFFER_MAP_POINTER_ARB')
--
-- === #BufferStorageMask# BufferStorageMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CLIENT_STORAGE_BIT' (alias: 'Graphics.GL.Tokens.GL_CLIENT_STORAGE_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_DYNAMIC_STORAGE_BIT' (alias: 'Graphics.GL.Tokens.GL_DYNAMIC_STORAGE_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_COHERENT_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_COHERENT_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_PERSISTENT_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_PERSISTENT_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_READ_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_READ_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_WRITE_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_WRITE_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_SPARSE_STORAGE_BIT_ARB'
-- * 'Graphics.GL.Tokens.GL_LGPU_SEPARATE_STORAGE_BIT_NVX' (alias: 'Graphics.GL.Tokens.GL_PER_GPU_STORAGE_BIT_NV')
-- * 'Graphics.GL.Tokens.GL_EXTERNAL_STORAGE_BIT_NVX'
--
-- === #BufferStorageTarget# BufferStorageTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ARRAY_BUFFER'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_COPY_READ_BUFFER'
-- * 'Graphics.GL.Tokens.GL_COPY_WRITE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_DISPATCH_INDIRECT_BUFFER'
-- * 'Graphics.GL.Tokens.GL_DRAW_INDIRECT_BUFFER'
-- * 'Graphics.GL.Tokens.GL_ELEMENT_ARRAY_BUFFER'
-- * 'Graphics.GL.Tokens.GL_PIXEL_PACK_BUFFER'
-- * 'Graphics.GL.Tokens.GL_PIXEL_UNPACK_BUFFER'
-- * 'Graphics.GL.Tokens.GL_QUERY_BUFFER'
-- * 'Graphics.GL.Tokens.GL_SHADER_STORAGE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BUFFER'
--
-- === #BufferTargetARB# BufferTargetARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ARRAY_BUFFER'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_COPY_READ_BUFFER'
-- * 'Graphics.GL.Tokens.GL_COPY_WRITE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_DISPATCH_INDIRECT_BUFFER'
-- * 'Graphics.GL.Tokens.GL_DRAW_INDIRECT_BUFFER'
-- * 'Graphics.GL.Tokens.GL_ELEMENT_ARRAY_BUFFER'
-- * 'Graphics.GL.Tokens.GL_PIXEL_PACK_BUFFER'
-- * 'Graphics.GL.Tokens.GL_PIXEL_UNPACK_BUFFER'
-- * 'Graphics.GL.Tokens.GL_QUERY_BUFFER'
-- * 'Graphics.GL.Tokens.GL_SHADER_STORAGE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BUFFER'
-- * 'Graphics.GL.Tokens.GL_PARAMETER_BUFFER'
--
-- === #BufferUsageARB# BufferUsageARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_STREAM_DRAW'
-- * 'Graphics.GL.Tokens.GL_STREAM_READ'
-- * 'Graphics.GL.Tokens.GL_STREAM_COPY'
-- * 'Graphics.GL.Tokens.GL_STATIC_DRAW'
-- * 'Graphics.GL.Tokens.GL_STATIC_READ'
-- * 'Graphics.GL.Tokens.GL_STATIC_COPY'
-- * 'Graphics.GL.Tokens.GL_DYNAMIC_DRAW'
-- * 'Graphics.GL.Tokens.GL_DYNAMIC_READ'
-- * 'Graphics.GL.Tokens.GL_DYNAMIC_COPY'
--
-- === #CheckFramebufferStatusTarget# CheckFramebufferStatusTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DRAW_FRAMEBUFFER'
-- * 'Graphics.GL.Tokens.GL_READ_FRAMEBUFFER'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER'
--
-- === #ClampColorModeARB# ClampColorModeARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FALSE' (alias: 'Graphics.GL.Tokens.GL_FALSE')
-- * 'Graphics.GL.Tokens.GL_TRUE' (alias: 'Graphics.GL.Tokens.GL_TRUE')
-- * 'Graphics.GL.Tokens.GL_TRUE' (alias: 'Graphics.GL.Tokens.GL_TRUE')
-- * 'Graphics.GL.Tokens.GL_FALSE' (alias: 'Graphics.GL.Tokens.GL_FALSE')
-- * 'Graphics.GL.Tokens.GL_FIXED_ONLY' (alias: 'Graphics.GL.Tokens.GL_FIXED_ONLY_ARB')
--
-- === #ClampColorTargetARB# ClampColorTargetARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CLAMP_VERTEX_COLOR_ARB'
-- * 'Graphics.GL.Tokens.GL_CLAMP_FRAGMENT_COLOR_ARB'
-- * 'Graphics.GL.Tokens.GL_CLAMP_READ_COLOR' (alias: 'Graphics.GL.Tokens.GL_CLAMP_READ_COLOR_ARB')
--
-- === #ClearBufferMask# ClearBufferMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ACCUM_BUFFER_BIT'
-- * 'Graphics.GL.Tokens.GL_COLOR_BUFFER_BIT'
-- * 'Graphics.GL.Tokens.GL_COVERAGE_BUFFER_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BUFFER_BIT'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BUFFER_BIT'
--
-- === #ClientAttribMask# ClientAttribMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CLIENT_ALL_ATTRIB_BITS'
-- * 'Graphics.GL.Tokens.GL_CLIENT_PIXEL_STORE_BIT'
-- * 'Graphics.GL.Tokens.GL_CLIENT_VERTEX_ARRAY_BIT'
--
-- === #ClipControlDepth# ClipControlDepth
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NEGATIVE_ONE_TO_ONE'
-- * 'Graphics.GL.Tokens.GL_ZERO_TO_ONE'
--
-- === #ClipControlOrigin# ClipControlOrigin
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_LOWER_LEFT'
-- * 'Graphics.GL.Tokens.GL_UPPER_LEFT'
--
-- === #ClipPlaneName# ClipPlaneName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE0' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE0')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE1' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE1')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE2' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE2')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE3' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE3')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE4' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE4')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE5' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE5')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE6'
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE7'
--
-- === #ColorBuffer# ColorBuffer
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NONE'
-- * 'Graphics.GL.Tokens.GL_FRONT_LEFT'
-- * 'Graphics.GL.Tokens.GL_FRONT_RIGHT'
-- * 'Graphics.GL.Tokens.GL_BACK_LEFT'
-- * 'Graphics.GL.Tokens.GL_BACK_RIGHT'
-- * 'Graphics.GL.Tokens.GL_FRONT'
-- * 'Graphics.GL.Tokens.GL_BACK'
-- * 'Graphics.GL.Tokens.GL_LEFT'
-- * 'Graphics.GL.Tokens.GL_RIGHT'
-- * 'Graphics.GL.Tokens.GL_FRONT_AND_BACK'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT1'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT2'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT3'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT4'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT5'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT6'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT7'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT8'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT9'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT10'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT11'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT12'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT13'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT14'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT15'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT16'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT17'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT18'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT19'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT20'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT21'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT22'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT23'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT24'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT25'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT26'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT27'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT28'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT29'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT30'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT31'
--
-- === #ColorMaterialFace# ColorMaterialFace
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BACK'
-- * 'Graphics.GL.Tokens.GL_FRONT'
-- * 'Graphics.GL.Tokens.GL_FRONT_AND_BACK'
--
-- === #ColorMaterialParameter# ColorMaterialParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_AMBIENT'
-- * 'Graphics.GL.Tokens.GL_AMBIENT_AND_DIFFUSE'
-- * 'Graphics.GL.Tokens.GL_DIFFUSE'
-- * 'Graphics.GL.Tokens.GL_EMISSION'
-- * 'Graphics.GL.Tokens.GL_SPECULAR'
--
-- === #ColorPointerType# ColorPointerType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BYTE'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
--
-- === #ColorTableParameterPNameSGI# ColorTableParameterPNameSGI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_BIAS' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_BIAS_SGI')
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_SCALE' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_SCALE_SGI')
--
-- === #ColorTableTarget# ColorTableTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_COLOR_TABLE'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_COLOR_TABLE'
--
-- === #ColorTableTargetSGI# ColorTableTargetSGI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_SGI')
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_COLOR_TABLE' (alias: 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI')
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_COLOR_TABLE' (alias: 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_COLOR_TABLE_SGI')
-- * 'Graphics.GL.Tokens.GL_PROXY_COLOR_TABLE' (alias: 'Graphics.GL.Tokens.GL_PROXY_COLOR_TABLE_SGI')
-- * 'Graphics.GL.Tokens.GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE' (alias: 'Graphics.GL.Tokens.GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI')
-- * 'Graphics.GL.Tokens.GL_PROXY_POST_CONVOLUTION_COLOR_TABLE' (alias: 'Graphics.GL.Tokens.GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI')
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_COLOR_TABLE_SGI'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COLOR_TABLE_SGI'
--
-- === #CombinerBiasNV# CombinerBiasNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NONE'
-- * 'Graphics.GL.Tokens.GL_BIAS_BY_NEGATIVE_ONE_HALF_NV'
--
-- === #CombinerComponentUsageNV# CombinerComponentUsageNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_RGB'
-- * 'Graphics.GL.Tokens.GL_ALPHA'
-- * 'Graphics.GL.Tokens.GL_BLUE'
--
-- === #CombinerMappingNV# CombinerMappingNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_IDENTITY_NV'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INVERT_NV'
-- * 'Graphics.GL.Tokens.GL_EXPAND_NORMAL_NV'
-- * 'Graphics.GL.Tokens.GL_EXPAND_NEGATE_NV'
-- * 'Graphics.GL.Tokens.GL_HALF_BIAS_NORMAL_NV'
-- * 'Graphics.GL.Tokens.GL_HALF_BIAS_NEGATE_NV'
-- * 'Graphics.GL.Tokens.GL_SIGNED_IDENTITY_NV'
-- * 'Graphics.GL.Tokens.GL_SIGNED_NEGATE_NV'
--
-- === #CombinerParameterNV# CombinerParameterNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COMBINER_INPUT_NV'
-- * 'Graphics.GL.Tokens.GL_COMBINER_MAPPING_NV'
-- * 'Graphics.GL.Tokens.GL_COMBINER_COMPONENT_USAGE_NV'
--
-- === #CombinerPortionNV# CombinerPortionNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_RGB'
-- * 'Graphics.GL.Tokens.GL_ALPHA'
--
-- === #CombinerRegisterNV# CombinerRegisterNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DISCARD_NV'
-- * 'Graphics.GL.Tokens.GL_PRIMARY_COLOR_NV'
-- * 'Graphics.GL.Tokens.GL_SECONDARY_COLOR_NV'
-- * 'Graphics.GL.Tokens.GL_SPARE0_NV'
-- * 'Graphics.GL.Tokens.GL_SPARE1_NV'
-- * 'Graphics.GL.Tokens.GL_TEXTURE0_ARB'
-- * 'Graphics.GL.Tokens.GL_TEXTURE1_ARB'
--
-- === #CombinerScaleNV# CombinerScaleNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NONE'
-- * 'Graphics.GL.Tokens.GL_SCALE_BY_TWO_NV'
-- * 'Graphics.GL.Tokens.GL_SCALE_BY_FOUR_NV'
-- * 'Graphics.GL.Tokens.GL_SCALE_BY_ONE_HALF_NV'
--
-- === #CombinerStageNV# CombinerStageNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COMBINER0_NV'
-- * 'Graphics.GL.Tokens.GL_COMBINER1_NV'
-- * 'Graphics.GL.Tokens.GL_COMBINER2_NV'
-- * 'Graphics.GL.Tokens.GL_COMBINER3_NV'
-- * 'Graphics.GL.Tokens.GL_COMBINER4_NV'
-- * 'Graphics.GL.Tokens.GL_COMBINER5_NV'
-- * 'Graphics.GL.Tokens.GL_COMBINER6_NV'
-- * 'Graphics.GL.Tokens.GL_COMBINER7_NV'
--
-- === #CombinerVariableNV# CombinerVariableNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VARIABLE_A_NV'
-- * 'Graphics.GL.Tokens.GL_VARIABLE_B_NV'
-- * 'Graphics.GL.Tokens.GL_VARIABLE_C_NV'
-- * 'Graphics.GL.Tokens.GL_VARIABLE_D_NV'
-- * 'Graphics.GL.Tokens.GL_VARIABLE_E_NV'
-- * 'Graphics.GL.Tokens.GL_VARIABLE_F_NV'
-- * 'Graphics.GL.Tokens.GL_VARIABLE_G_NV'
--
-- === #ConditionalRenderMode# ConditionalRenderMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_QUERY_WAIT'
-- * 'Graphics.GL.Tokens.GL_QUERY_NO_WAIT'
-- * 'Graphics.GL.Tokens.GL_QUERY_BY_REGION_WAIT'
-- * 'Graphics.GL.Tokens.GL_QUERY_BY_REGION_NO_WAIT'
-- * 'Graphics.GL.Tokens.GL_QUERY_WAIT_INVERTED'
-- * 'Graphics.GL.Tokens.GL_QUERY_NO_WAIT_INVERTED'
-- * 'Graphics.GL.Tokens.GL_QUERY_BY_REGION_WAIT_INVERTED'
-- * 'Graphics.GL.Tokens.GL_QUERY_BY_REGION_NO_WAIT_INVERTED'
--
-- === #ContextFlagMask# ContextFlagMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CONTEXT_FLAG_DEBUG_BIT' (alias: 'Graphics.GL.Tokens.GL_CONTEXT_FLAG_DEBUG_BIT_KHR')
-- * 'Graphics.GL.Tokens.GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT'
-- * 'Graphics.GL.Tokens.GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT' (alias: 'Graphics.GL.Tokens.GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB')
-- * 'Graphics.GL.Tokens.GL_CONTEXT_FLAG_PROTECTED_CONTENT_BIT_EXT'
-- * 'Graphics.GL.Tokens.GL_CONTEXT_FLAG_NO_ERROR_BIT' (alias: 'Graphics.GL.Tokens.GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR')
--
-- === #ContextProfileMask# ContextProfileMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CONTEXT_COMPATIBILITY_PROFILE_BIT'
-- * 'Graphics.GL.Tokens.GL_CONTEXT_CORE_PROFILE_BIT'
--
-- === #ConvolutionBorderModeEXT# ConvolutionBorderModeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_REDUCE' (alias: 'Graphics.GL.Tokens.GL_REDUCE_EXT')
--
-- === #ConvolutionParameterEXT# ConvolutionParameterEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_BORDER_MODE' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_BORDER_MODE_EXT')
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_FILTER_BIAS' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_FILTER_BIAS_EXT')
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_FILTER_SCALE' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_FILTER_SCALE_EXT')
--
-- === #ConvolutionTarget# ConvolutionTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_1D'
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_2D'
--
-- === #ConvolutionTargetEXT# ConvolutionTargetEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_1D' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_1D_EXT')
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_2D' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_2D_EXT')
--
-- === #CopyBufferSubDataTarget# CopyBufferSubDataTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ARRAY_BUFFER'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_COPY_READ_BUFFER'
-- * 'Graphics.GL.Tokens.GL_COPY_WRITE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_DISPATCH_INDIRECT_BUFFER'
-- * 'Graphics.GL.Tokens.GL_DRAW_INDIRECT_BUFFER'
-- * 'Graphics.GL.Tokens.GL_ELEMENT_ARRAY_BUFFER'
-- * 'Graphics.GL.Tokens.GL_PIXEL_PACK_BUFFER'
-- * 'Graphics.GL.Tokens.GL_PIXEL_UNPACK_BUFFER'
-- * 'Graphics.GL.Tokens.GL_QUERY_BUFFER'
-- * 'Graphics.GL.Tokens.GL_SHADER_STORAGE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BUFFER'
--
-- === #CopyImageSubDataTarget# CopyImageSubDataTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_1D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_2D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_3D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_RECTANGLE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_2D_MULTISAMPLE_ARRAY'
--
-- === #CullFaceMode# CullFaceMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BACK'
-- * 'Graphics.GL.Tokens.GL_FRONT'
-- * 'Graphics.GL.Tokens.GL_FRONT_AND_BACK'
--
-- === #CullParameterEXT# CullParameterEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CULL_VERTEX_EYE_POSITION_EXT'
-- * 'Graphics.GL.Tokens.GL_CULL_VERTEX_OBJECT_POSITION_EXT'
--
-- === #DataType# DataType
-- There are no values defined for this enumeration group.
--
--
-- === #DataTypeEXT# DataTypeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SCALAR_EXT'
-- * 'Graphics.GL.Tokens.GL_VECTOR_EXT'
-- * 'Graphics.GL.Tokens.GL_MATRIX_EXT'
--
-- === #DebugSeverity# DebugSeverity
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DEBUG_SEVERITY_LOW'
-- * 'Graphics.GL.Tokens.GL_DEBUG_SEVERITY_MEDIUM'
-- * 'Graphics.GL.Tokens.GL_DEBUG_SEVERITY_HIGH'
-- * 'Graphics.GL.Tokens.GL_DEBUG_SEVERITY_NOTIFICATION'
-- * 'Graphics.GL.Tokens.GL_DONT_CARE'
--
-- === #DebugSource# DebugSource
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DEBUG_SOURCE_API'
-- * 'Graphics.GL.Tokens.GL_DEBUG_SOURCE_WINDOW_SYSTEM'
-- * 'Graphics.GL.Tokens.GL_DEBUG_SOURCE_SHADER_COMPILER'
-- * 'Graphics.GL.Tokens.GL_DEBUG_SOURCE_THIRD_PARTY'
-- * 'Graphics.GL.Tokens.GL_DEBUG_SOURCE_APPLICATION'
-- * 'Graphics.GL.Tokens.GL_DEBUG_SOURCE_OTHER'
-- * 'Graphics.GL.Tokens.GL_DONT_CARE'
--
-- === #DebugType# DebugType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DEBUG_TYPE_ERROR'
-- * 'Graphics.GL.Tokens.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR'
-- * 'Graphics.GL.Tokens.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR'
-- * 'Graphics.GL.Tokens.GL_DEBUG_TYPE_PORTABILITY'
-- * 'Graphics.GL.Tokens.GL_DEBUG_TYPE_PERFORMANCE'
-- * 'Graphics.GL.Tokens.GL_DEBUG_TYPE_MARKER'
-- * 'Graphics.GL.Tokens.GL_DEBUG_TYPE_PUSH_GROUP'
-- * 'Graphics.GL.Tokens.GL_DEBUG_TYPE_POP_GROUP'
-- * 'Graphics.GL.Tokens.GL_DEBUG_TYPE_OTHER'
-- * 'Graphics.GL.Tokens.GL_DONT_CARE'
--
-- === #DepthFunction# DepthFunction
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALWAYS'
-- * 'Graphics.GL.Tokens.GL_EQUAL'
-- * 'Graphics.GL.Tokens.GL_GEQUAL'
-- * 'Graphics.GL.Tokens.GL_GREATER'
-- * 'Graphics.GL.Tokens.GL_LEQUAL'
-- * 'Graphics.GL.Tokens.GL_LESS'
-- * 'Graphics.GL.Tokens.GL_NEVER'
-- * 'Graphics.GL.Tokens.GL_NOTEQUAL'
--
-- === #DrawBufferMode# DrawBufferMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_AUX0'
-- * 'Graphics.GL.Tokens.GL_AUX1'
-- * 'Graphics.GL.Tokens.GL_AUX2'
-- * 'Graphics.GL.Tokens.GL_AUX3'
-- * 'Graphics.GL.Tokens.GL_BACK'
-- * 'Graphics.GL.Tokens.GL_BACK_LEFT'
-- * 'Graphics.GL.Tokens.GL_BACK_RIGHT'
-- * 'Graphics.GL.Tokens.GL_FRONT'
-- * 'Graphics.GL.Tokens.GL_FRONT_AND_BACK'
-- * 'Graphics.GL.Tokens.GL_FRONT_LEFT'
-- * 'Graphics.GL.Tokens.GL_FRONT_RIGHT'
-- * 'Graphics.GL.Tokens.GL_LEFT'
-- * 'Graphics.GL.Tokens.GL_NONE' (alias: 'Graphics.GL.Tokens.GL_NONE_OES')
-- * 'Graphics.GL.Tokens.GL_RIGHT'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT1'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT2'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT3'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT4'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT5'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT6'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT7'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT8'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT9'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT10'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT11'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT12'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT13'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT14'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT15'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT16'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT17'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT18'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT19'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT20'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT21'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT22'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT23'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT24'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT25'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT26'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT27'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT28'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT29'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT30'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT31'
--
-- === #DrawBufferModeATI# DrawBufferModeATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT1_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT2_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT3_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT4_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT5_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT6_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT7_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT8_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT9_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT10_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT11_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT12_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT13_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT14_NV'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT15_NV'
--
-- === #DrawElementsType# DrawElementsType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
--
-- === #ElementPointerTypeATI# ElementPointerTypeATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
--
-- === #EnableCap# EnableCap
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALPHA_TEST'
-- * 'Graphics.GL.Tokens.GL_ASYNC_DRAW_PIXELS_SGIX'
-- * 'Graphics.GL.Tokens.GL_ASYNC_HISTOGRAM_SGIX'
-- * 'Graphics.GL.Tokens.GL_ASYNC_READ_PIXELS_SGIX'
-- * 'Graphics.GL.Tokens.GL_ASYNC_TEX_IMAGE_SGIX'
-- * 'Graphics.GL.Tokens.GL_AUTO_NORMAL'
-- * 'Graphics.GL.Tokens.GL_BLEND'
-- * 'Graphics.GL.Tokens.GL_CALLIGRAPHIC_FRAGMENT_SGIX'
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE0' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE0')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE1' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE1')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE2' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE2')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE3' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE3')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE4' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE4')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE5' (alias: 'Graphics.GL.Tokens.GL_CLIP_PLANE5')
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE6'
-- * 'Graphics.GL.Tokens.GL_CLIP_DISTANCE7'
-- * 'Graphics.GL.Tokens.GL_COLOR_ARRAY'
-- * 'Graphics.GL.Tokens.GL_COLOR_LOGIC_OP'
-- * 'Graphics.GL.Tokens.GL_COLOR_MATERIAL'
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_SGI'
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_1D_EXT'
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_2D_EXT'
-- * 'Graphics.GL.Tokens.GL_CULL_FACE'
-- * 'Graphics.GL.Tokens.GL_DEBUG_OUTPUT'
-- * 'Graphics.GL.Tokens.GL_DEBUG_OUTPUT_SYNCHRONOUS'
-- * 'Graphics.GL.Tokens.GL_DEPTH_CLAMP'
-- * 'Graphics.GL.Tokens.GL_DEPTH_TEST'
-- * 'Graphics.GL.Tokens.GL_DITHER'
-- * 'Graphics.GL.Tokens.GL_EDGE_FLAG_ARRAY'
-- * 'Graphics.GL.Tokens.GL_FOG'
-- * 'Graphics.GL.Tokens.GL_FOG_OFFSET_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_COLOR_MATERIAL_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT0_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT1_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT2_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT3_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT4_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT5_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT6_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT7_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHTING_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_SRGB'
-- * 'Graphics.GL.Tokens.GL_FRAMEZOOM_SGIX'
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM_EXT'
-- * 'Graphics.GL.Tokens.GL_INDEX_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INDEX_LOGIC_OP'
-- * 'Graphics.GL.Tokens.GL_INTERLACE_SGIX'
-- * 'Graphics.GL.Tokens.GL_IR_INSTRUMENT1_SGIX'
-- * 'Graphics.GL.Tokens.GL_LIGHT0'
-- * 'Graphics.GL.Tokens.GL_LIGHT1'
-- * 'Graphics.GL.Tokens.GL_LIGHT2'
-- * 'Graphics.GL.Tokens.GL_LIGHT3'
-- * 'Graphics.GL.Tokens.GL_LIGHT4'
-- * 'Graphics.GL.Tokens.GL_LIGHT5'
-- * 'Graphics.GL.Tokens.GL_LIGHT6'
-- * 'Graphics.GL.Tokens.GL_LIGHT7'
-- * 'Graphics.GL.Tokens.GL_LIGHTING'
-- * 'Graphics.GL.Tokens.GL_LINE_SMOOTH'
-- * 'Graphics.GL.Tokens.GL_LINE_STIPPLE'
-- * 'Graphics.GL.Tokens.GL_MAP1_COLOR_4'
-- * 'Graphics.GL.Tokens.GL_MAP1_INDEX'
-- * 'Graphics.GL.Tokens.GL_MAP1_NORMAL'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_1'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_2'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_3'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_4'
-- * 'Graphics.GL.Tokens.GL_MAP1_VERTEX_3'
-- * 'Graphics.GL.Tokens.GL_MAP1_VERTEX_4'
-- * 'Graphics.GL.Tokens.GL_MAP2_COLOR_4'
-- * 'Graphics.GL.Tokens.GL_MAP2_INDEX'
-- * 'Graphics.GL.Tokens.GL_MAP2_NORMAL'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_1'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_2'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_3'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_4'
-- * 'Graphics.GL.Tokens.GL_MAP2_VERTEX_3'
-- * 'Graphics.GL.Tokens.GL_MAP2_VERTEX_4'
-- * 'Graphics.GL.Tokens.GL_MINMAX_EXT'
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE' (alias: 'Graphics.GL.Tokens.GL_MULTISAMPLE_SGIS')
-- * 'Graphics.GL.Tokens.GL_NORMALIZE'
-- * 'Graphics.GL.Tokens.GL_NORMAL_ARRAY'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEXTURE_SGIS'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_SGIX'
-- * 'Graphics.GL.Tokens.GL_POINT_SMOOTH'
-- * 'Graphics.GL.Tokens.GL_POLYGON_OFFSET_FILL'
-- * 'Graphics.GL.Tokens.GL_POLYGON_OFFSET_LINE'
-- * 'Graphics.GL.Tokens.GL_POLYGON_OFFSET_POINT'
-- * 'Graphics.GL.Tokens.GL_POLYGON_SMOOTH'
-- * 'Graphics.GL.Tokens.GL_POLYGON_STIPPLE'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_COLOR_TABLE_SGI'
-- * 'Graphics.GL.Tokens.GL_PRIMITIVE_RESTART'
-- * 'Graphics.GL.Tokens.GL_PRIMITIVE_RESTART_FIXED_INDEX'
-- * 'Graphics.GL.Tokens.GL_PROGRAM_POINT_SIZE'
-- * 'Graphics.GL.Tokens.GL_RASTERIZER_DISCARD'
-- * 'Graphics.GL.Tokens.GL_REFERENCE_PLANE_SGIX'
-- * 'Graphics.GL.Tokens.GL_RESCALE_NORMAL_EXT'
-- * 'Graphics.GL.Tokens.GL_SAMPLE_ALPHA_TO_COVERAGE' (alias: 'Graphics.GL.Tokens.GL_SAMPLE_ALPHA_TO_MASK_SGIS')
-- * 'Graphics.GL.Tokens.GL_SAMPLE_ALPHA_TO_ONE' (alias: 'Graphics.GL.Tokens.GL_SAMPLE_ALPHA_TO_ONE_SGIS')
-- * 'Graphics.GL.Tokens.GL_SAMPLE_COVERAGE' (alias: 'Graphics.GL.Tokens.GL_SAMPLE_MASK_SGIS')
-- * 'Graphics.GL.Tokens.GL_SAMPLE_MASK'
-- * 'Graphics.GL.Tokens.GL_SAMPLE_SHADING'
-- * 'Graphics.GL.Tokens.GL_SCISSOR_TEST'
-- * 'Graphics.GL.Tokens.GL_SEPARABLE_2D_EXT'
-- * 'Graphics.GL.Tokens.GL_SHARED_TEXTURE_PALETTE_EXT'
-- * 'Graphics.GL.Tokens.GL_SPRITE_SGIX'
-- * 'Graphics.GL.Tokens.GL_STENCIL_TEST'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_1D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_2D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_3D_EXT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_4D_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COLOR_TABLE_SGI'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COORD_ARRAY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_SEAMLESS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEN_Q'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEN_R'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEN_S'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEN_T'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ARRAY'
--
-- === #ErrorCode# ErrorCode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_INVALID_ENUM'
-- * 'Graphics.GL.Tokens.GL_INVALID_FRAMEBUFFER_OPERATION' (aliases: 'Graphics.GL.Tokens.GL_INVALID_FRAMEBUFFER_OPERATION_EXT', 'Graphics.GL.Tokens.GL_INVALID_FRAMEBUFFER_OPERATION_OES')
-- * 'Graphics.GL.Tokens.GL_INVALID_OPERATION'
-- * 'Graphics.GL.Tokens.GL_INVALID_VALUE'
-- * 'Graphics.GL.Tokens.GL_NO_ERROR'
-- * 'Graphics.GL.Tokens.GL_OUT_OF_MEMORY'
-- * 'Graphics.GL.Tokens.GL_STACK_OVERFLOW'
-- * 'Graphics.GL.Tokens.GL_STACK_UNDERFLOW'
-- * 'Graphics.GL.Tokens.GL_TABLE_TOO_LARGE' (alias: 'Graphics.GL.Tokens.GL_TABLE_TOO_LARGE_EXT')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_TOO_LARGE_EXT'
--
-- === #EvalMapsModeNV# EvalMapsModeNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FILL_NV'
--
-- === #EvalTargetNV# EvalTargetNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_EVAL_2D_NV'
-- * 'Graphics.GL.Tokens.GL_EVAL_TRIANGULAR_2D_NV'
--
-- === #ExternalHandleType# ExternalHandleType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_HANDLE_TYPE_OPAQUE_FD_EXT'
-- * 'Graphics.GL.Tokens.GL_HANDLE_TYPE_OPAQUE_WIN32_EXT'
-- * 'Graphics.GL.Tokens.GL_HANDLE_TYPE_OPAQUE_WIN32_KMT_EXT'
-- * 'Graphics.GL.Tokens.GL_HANDLE_TYPE_D3D12_TILEPOOL_EXT'
-- * 'Graphics.GL.Tokens.GL_HANDLE_TYPE_D3D12_RESOURCE_EXT'
-- * 'Graphics.GL.Tokens.GL_HANDLE_TYPE_D3D11_IMAGE_EXT'
-- * 'Graphics.GL.Tokens.GL_HANDLE_TYPE_D3D11_IMAGE_KMT_EXT'
-- * 'Graphics.GL.Tokens.GL_HANDLE_TYPE_D3D12_FENCE_EXT'
--
-- === #FeedBackToken# FeedBackToken
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BITMAP_TOKEN'
-- * 'Graphics.GL.Tokens.GL_COPY_PIXEL_TOKEN'
-- * 'Graphics.GL.Tokens.GL_DRAW_PIXEL_TOKEN'
-- * 'Graphics.GL.Tokens.GL_LINE_RESET_TOKEN'
-- * 'Graphics.GL.Tokens.GL_LINE_TOKEN'
-- * 'Graphics.GL.Tokens.GL_PASS_THROUGH_TOKEN'
-- * 'Graphics.GL.Tokens.GL_POINT_TOKEN'
-- * 'Graphics.GL.Tokens.GL_POLYGON_TOKEN'
--
-- === #FeedbackType# FeedbackType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_2D'
-- * 'Graphics.GL.Tokens.GL_3D'
-- * 'Graphics.GL.Tokens.GL_3D_COLOR'
-- * 'Graphics.GL.Tokens.GL_3D_COLOR_TEXTURE'
-- * 'Graphics.GL.Tokens.GL_4D_COLOR_TEXTURE'
--
-- === #FenceConditionNV# FenceConditionNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALL_COMPLETED_NV'
--
-- === #FenceParameterNameNV# FenceParameterNameNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FENCE_STATUS_NV'
-- * 'Graphics.GL.Tokens.GL_FENCE_CONDITION_NV'
--
-- === #FfdMaskSGIX# FfdMaskSGIX
-- There are no values defined for this enumeration group.
--
--
-- === #FfdTargetSGIX# FfdTargetSGIX
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_DEFORMATION_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_DEFORMATION_SGIX'
--
-- === #FogCoordinatePointerType# FogCoordinatePointerType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
--
-- === #FogMode# FogMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_EXP'
-- * 'Graphics.GL.Tokens.GL_EXP2'
-- * 'Graphics.GL.Tokens.GL_FOG_FUNC_SGIS'
-- * 'Graphics.GL.Tokens.GL_LINEAR'
--
-- === #FogPName# FogPName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FOG_MODE'
-- * 'Graphics.GL.Tokens.GL_FOG_DENSITY'
-- * 'Graphics.GL.Tokens.GL_FOG_START'
-- * 'Graphics.GL.Tokens.GL_FOG_END'
-- * 'Graphics.GL.Tokens.GL_FOG_INDEX'
-- * 'Graphics.GL.Tokens.GL_FOG_COORD_SRC'
--
-- === #FogParameter# FogParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FOG_COLOR'
-- * 'Graphics.GL.Tokens.GL_FOG_DENSITY'
-- * 'Graphics.GL.Tokens.GL_FOG_END'
-- * 'Graphics.GL.Tokens.GL_FOG_INDEX'
-- * 'Graphics.GL.Tokens.GL_FOG_MODE'
-- * 'Graphics.GL.Tokens.GL_FOG_OFFSET_VALUE_SGIX'
-- * 'Graphics.GL.Tokens.GL_FOG_START'
--
-- === #FogPointerTypeEXT# FogPointerTypeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
--
-- === #FogPointerTypeIBM# FogPointerTypeIBM
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
--
-- === #FragmentLightModelParameterSGIX# FragmentLightModelParameterSGIX
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX'
--
-- === #FragmentLightNameSGIX# FragmentLightNameSGIX
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT0_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT1_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT2_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT3_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT4_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT5_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT6_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT7_SGIX'
--
-- === #FragmentLightParameterSGIX# FragmentLightParameterSGIX
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SPOT_EXPONENT'
-- * 'Graphics.GL.Tokens.GL_SPOT_CUTOFF'
-- * 'Graphics.GL.Tokens.GL_CONSTANT_ATTENUATION'
-- * 'Graphics.GL.Tokens.GL_LINEAR_ATTENUATION'
-- * 'Graphics.GL.Tokens.GL_QUADRATIC_ATTENUATION'
-- * 'Graphics.GL.Tokens.GL_AMBIENT'
-- * 'Graphics.GL.Tokens.GL_DIFFUSE'
-- * 'Graphics.GL.Tokens.GL_SPECULAR'
-- * 'Graphics.GL.Tokens.GL_POSITION'
-- * 'Graphics.GL.Tokens.GL_SPOT_DIRECTION'
--
-- === #FragmentOpATI# FragmentOpATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_MOV_ATI'
-- * 'Graphics.GL.Tokens.GL_ADD_ATI'
-- * 'Graphics.GL.Tokens.GL_MUL_ATI'
-- * 'Graphics.GL.Tokens.GL_SUB_ATI'
-- * 'Graphics.GL.Tokens.GL_DOT3_ATI'
-- * 'Graphics.GL.Tokens.GL_DOT4_ATI'
-- * 'Graphics.GL.Tokens.GL_MAD_ATI'
-- * 'Graphics.GL.Tokens.GL_LERP_ATI'
-- * 'Graphics.GL.Tokens.GL_CND_ATI'
-- * 'Graphics.GL.Tokens.GL_CND0_ATI'
-- * 'Graphics.GL.Tokens.GL_DOT2_ADD_ATI'
--
-- === #FramebufferAttachment# FramebufferAttachment
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0_NV', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0_OES')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT1' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT1_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT1_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT2' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT2_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT2_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT3' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT3_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT3_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT4' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT4_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT4_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT5' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT5_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT5_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT6' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT6_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT6_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT7' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT7_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT7_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT8' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT8_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT8_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT9' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT9_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT9_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT10' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT10_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT10_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT11' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT11_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT11_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT12' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT12_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT12_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT13' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT13_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT13_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT14' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT14_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT14_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT15' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT15_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT15_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT16'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT17'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT18'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT19'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT20'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT21'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT22'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT23'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT24'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT25'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT26'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT27'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT28'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT29'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT30'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT31'
-- * 'Graphics.GL.Tokens.GL_DEPTH_ATTACHMENT' (aliases: 'Graphics.GL.Tokens.GL_DEPTH_ATTACHMENT_EXT', 'Graphics.GL.Tokens.GL_DEPTH_ATTACHMENT_OES')
-- * 'Graphics.GL.Tokens.GL_DEPTH_STENCIL_ATTACHMENT'
-- * 'Graphics.GL.Tokens.GL_STENCIL_ATTACHMENT' (aliases: 'Graphics.GL.Tokens.GL_STENCIL_ATTACHMENT_EXT', 'Graphics.GL.Tokens.GL_STENCIL_ATTACHMENT_OES')
--
-- === #FramebufferAttachmentParameterName# FramebufferAttachmentParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE' (alias: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT')
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING' (alias: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT')
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME' (aliases: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT', 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES')
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE' (aliases: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT', 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES')
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL' (aliases: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT', 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES')
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE' (aliases: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT', 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES')
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT' (aliases: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES', 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER', 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT')
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SCALE_IMG'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_LAYERED' (aliases: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB', 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT', 'Graphics.GL.Tokens.GL_FRAMEBUFFER_ATTACHMENT_LAYERED_OES')
--
-- === #FramebufferFetchNoncoherent# FramebufferFetchNoncoherent
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_FETCH_NONCOHERENT_QCOM'
--
-- === #FramebufferParameterName# FramebufferParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_DEFAULT_WIDTH'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_DEFAULT_HEIGHT'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_DEFAULT_LAYERS'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_DEFAULT_SAMPLES'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS'
--
-- === #FramebufferStatus# FramebufferStatus
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_COMPLETE'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_UNDEFINED'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_UNSUPPORTED'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE' (alias: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE')
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE' (alias: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE')
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS'
--
-- === #FramebufferTarget# FramebufferTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER' (alias: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_OES')
-- * 'Graphics.GL.Tokens.GL_DRAW_FRAMEBUFFER'
-- * 'Graphics.GL.Tokens.GL_READ_FRAMEBUFFER'
--
-- === #FrontFaceDirection# FrontFaceDirection
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CCW'
-- * 'Graphics.GL.Tokens.GL_CW'
--
-- === #GetColorTableParameterPNameSGI# GetColorTableParameterPNameSGI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_BIAS' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_BIAS_SGI')
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_SCALE' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_SCALE_SGI')
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_FORMAT' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_FORMAT_SGI')
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_WIDTH' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_WIDTH_SGI')
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_RED_SIZE' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_RED_SIZE_SGI')
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_GREEN_SIZE' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_GREEN_SIZE_SGI')
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_BLUE_SIZE' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_BLUE_SIZE_SGI')
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_ALPHA_SIZE' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_ALPHA_SIZE_SGI')
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_LUMINANCE_SIZE' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_LUMINANCE_SIZE_SGI')
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_INTENSITY_SIZE' (alias: 'Graphics.GL.Tokens.GL_COLOR_TABLE_INTENSITY_SIZE_SGI')
--
-- === #GetConvolutionParameter# GetConvolutionParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_BORDER_MODE' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_BORDER_MODE_EXT')
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_BORDER_COLOR'
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_FILTER_SCALE' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_FILTER_SCALE_EXT')
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_FILTER_BIAS' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_FILTER_BIAS_EXT')
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_FORMAT' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_FORMAT_EXT')
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_WIDTH' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_WIDTH_EXT')
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_HEIGHT' (alias: 'Graphics.GL.Tokens.GL_CONVOLUTION_HEIGHT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAX_CONVOLUTION_WIDTH' (alias: 'Graphics.GL.Tokens.GL_MAX_CONVOLUTION_WIDTH_EXT')
-- * 'Graphics.GL.Tokens.GL_MAX_CONVOLUTION_HEIGHT' (alias: 'Graphics.GL.Tokens.GL_MAX_CONVOLUTION_HEIGHT_EXT')
--
-- === #GetFramebufferParameter# GetFramebufferParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_DEFAULT_WIDTH'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_DEFAULT_HEIGHT'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_DEFAULT_LAYERS'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_DEFAULT_SAMPLES'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS'
-- * 'Graphics.GL.Tokens.GL_DOUBLEBUFFER'
-- * 'Graphics.GL.Tokens.GL_IMPLEMENTATION_COLOR_READ_FORMAT'
-- * 'Graphics.GL.Tokens.GL_IMPLEMENTATION_COLOR_READ_TYPE'
-- * 'Graphics.GL.Tokens.GL_SAMPLES'
-- * 'Graphics.GL.Tokens.GL_SAMPLE_BUFFERS'
-- * 'Graphics.GL.Tokens.GL_STEREO'
--
-- === #GetHistogramParameterPNameEXT# GetHistogramParameterPNameEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM_WIDTH' (aliases: 'Graphics.GL.Tokens.GL_HISTOGRAM_WIDTH_EXT', 'Graphics.GL.Tokens.GL_HISTOGRAM_WIDTH_EXT')
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM_FORMAT' (aliases: 'Graphics.GL.Tokens.GL_HISTOGRAM_FORMAT_EXT', 'Graphics.GL.Tokens.GL_HISTOGRAM_FORMAT_EXT')
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM_RED_SIZE' (aliases: 'Graphics.GL.Tokens.GL_HISTOGRAM_RED_SIZE_EXT', 'Graphics.GL.Tokens.GL_HISTOGRAM_RED_SIZE_EXT')
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM_GREEN_SIZE' (aliases: 'Graphics.GL.Tokens.GL_HISTOGRAM_GREEN_SIZE_EXT', 'Graphics.GL.Tokens.GL_HISTOGRAM_GREEN_SIZE_EXT')
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM_BLUE_SIZE' (aliases: 'Graphics.GL.Tokens.GL_HISTOGRAM_BLUE_SIZE_EXT', 'Graphics.GL.Tokens.GL_HISTOGRAM_BLUE_SIZE_EXT')
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM_ALPHA_SIZE' (aliases: 'Graphics.GL.Tokens.GL_HISTOGRAM_ALPHA_SIZE_EXT', 'Graphics.GL.Tokens.GL_HISTOGRAM_ALPHA_SIZE_EXT')
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM_LUMINANCE_SIZE' (aliases: 'Graphics.GL.Tokens.GL_HISTOGRAM_LUMINANCE_SIZE_EXT', 'Graphics.GL.Tokens.GL_HISTOGRAM_LUMINANCE_SIZE_EXT')
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM_SINK' (aliases: 'Graphics.GL.Tokens.GL_HISTOGRAM_SINK_EXT', 'Graphics.GL.Tokens.GL_HISTOGRAM_SINK_EXT')
--
-- === #GetMapQuery# GetMapQuery
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COEFF'
-- * 'Graphics.GL.Tokens.GL_DOMAIN'
-- * 'Graphics.GL.Tokens.GL_ORDER'
--
-- === #GetMinmaxParameterPNameEXT# GetMinmaxParameterPNameEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_MINMAX_FORMAT' (aliases: 'Graphics.GL.Tokens.GL_MINMAX_FORMAT', 'Graphics.GL.Tokens.GL_MINMAX_FORMAT_EXT')
-- * 'Graphics.GL.Tokens.GL_MINMAX_SINK' (aliases: 'Graphics.GL.Tokens.GL_MINMAX_SINK', 'Graphics.GL.Tokens.GL_MINMAX_SINK_EXT')
-- * 'Graphics.GL.Tokens.GL_MINMAX_FORMAT' (aliases: 'Graphics.GL.Tokens.GL_MINMAX_FORMAT', 'Graphics.GL.Tokens.GL_MINMAX_FORMAT_EXT')
-- * 'Graphics.GL.Tokens.GL_MINMAX_SINK' (aliases: 'Graphics.GL.Tokens.GL_MINMAX_SINK', 'Graphics.GL.Tokens.GL_MINMAX_SINK_EXT')
--
-- === #GetMultisamplePNameNV# GetMultisamplePNameNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SAMPLE_LOCATION_ARB' (alias: 'Graphics.GL.Tokens.GL_SAMPLE_POSITION')
-- * 'Graphics.GL.Tokens.GL_PROGRAMMABLE_SAMPLE_LOCATION_ARB'
--
-- === #GetPName# GetPName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ACCUM_ALPHA_BITS'
-- * 'Graphics.GL.Tokens.GL_ACCUM_BLUE_BITS'
-- * 'Graphics.GL.Tokens.GL_ACCUM_CLEAR_VALUE'
-- * 'Graphics.GL.Tokens.GL_ACCUM_GREEN_BITS'
-- * 'Graphics.GL.Tokens.GL_ACCUM_RED_BITS'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_TEXTURE'
-- * 'Graphics.GL.Tokens.GL_ALIASED_LINE_WIDTH_RANGE'
-- * 'Graphics.GL.Tokens.GL_ALIASED_POINT_SIZE_RANGE'
-- * 'Graphics.GL.Tokens.GL_ALPHA_BIAS'
-- * 'Graphics.GL.Tokens.GL_ALPHA_BITS'
-- * 'Graphics.GL.Tokens.GL_ALPHA_SCALE'
-- * 'Graphics.GL.Tokens.GL_ALPHA_TEST' (alias: 'Graphics.GL.Tokens.GL_ALPHA_TEST_QCOM')
-- * 'Graphics.GL.Tokens.GL_ALPHA_TEST_FUNC' (alias: 'Graphics.GL.Tokens.GL_ALPHA_TEST_FUNC_QCOM')
-- * 'Graphics.GL.Tokens.GL_ALPHA_TEST_REF' (alias: 'Graphics.GL.Tokens.GL_ALPHA_TEST_REF_QCOM')
-- * 'Graphics.GL.Tokens.GL_ARRAY_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_ASYNC_DRAW_PIXELS_SGIX'
-- * 'Graphics.GL.Tokens.GL_ASYNC_HISTOGRAM_SGIX'
-- * 'Graphics.GL.Tokens.GL_ASYNC_MARKER_SGIX'
-- * 'Graphics.GL.Tokens.GL_ASYNC_READ_PIXELS_SGIX'
-- * 'Graphics.GL.Tokens.GL_ASYNC_TEX_IMAGE_SGIX'
-- * 'Graphics.GL.Tokens.GL_ATTRIB_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_AUTO_NORMAL'
-- * 'Graphics.GL.Tokens.GL_AUX_BUFFERS'
-- * 'Graphics.GL.Tokens.GL_BLEND'
-- * 'Graphics.GL.Tokens.GL_BLEND_COLOR' (alias: 'Graphics.GL.Tokens.GL_BLEND_COLOR_EXT')
-- * 'Graphics.GL.Tokens.GL_BLEND_DST'
-- * 'Graphics.GL.Tokens.GL_BLEND_DST_ALPHA'
-- * 'Graphics.GL.Tokens.GL_BLEND_DST_RGB'
-- * 'Graphics.GL.Tokens.GL_BLEND_EQUATION_ALPHA'
-- * 'Graphics.GL.Tokens.GL_BLEND_EQUATION_EXT' (alias: 'Graphics.GL.Tokens.GL_BLEND_EQUATION_RGB')
-- * 'Graphics.GL.Tokens.GL_BLEND_SRC'
-- * 'Graphics.GL.Tokens.GL_BLEND_SRC_ALPHA'
-- * 'Graphics.GL.Tokens.GL_BLEND_SRC_RGB'
-- * 'Graphics.GL.Tokens.GL_BLUE_BIAS'
-- * 'Graphics.GL.Tokens.GL_BLUE_BITS'
-- * 'Graphics.GL.Tokens.GL_BLUE_SCALE'
-- * 'Graphics.GL.Tokens.GL_CALLIGRAPHIC_FRAGMENT_SGIX'
-- * 'Graphics.GL.Tokens.GL_CLIENT_ATTRIB_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_CLIP_PLANE0'
-- * 'Graphics.GL.Tokens.GL_CLIP_PLANE1'
-- * 'Graphics.GL.Tokens.GL_CLIP_PLANE2'
-- * 'Graphics.GL.Tokens.GL_CLIP_PLANE3'
-- * 'Graphics.GL.Tokens.GL_CLIP_PLANE4'
-- * 'Graphics.GL.Tokens.GL_CLIP_PLANE5'
-- * 'Graphics.GL.Tokens.GL_COLOR_ARRAY'
-- * 'Graphics.GL.Tokens.GL_COLOR_ARRAY_COUNT_EXT'
-- * 'Graphics.GL.Tokens.GL_COLOR_ARRAY_SIZE'
-- * 'Graphics.GL.Tokens.GL_COLOR_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_COLOR_ARRAY_TYPE'
-- * 'Graphics.GL.Tokens.GL_COLOR_CLEAR_VALUE'
-- * 'Graphics.GL.Tokens.GL_COLOR_LOGIC_OP'
-- * 'Graphics.GL.Tokens.GL_COLOR_MATERIAL'
-- * 'Graphics.GL.Tokens.GL_COLOR_MATERIAL_FACE'
-- * 'Graphics.GL.Tokens.GL_COLOR_MATERIAL_PARAMETER'
-- * 'Graphics.GL.Tokens.GL_COLOR_MATRIX_SGI'
-- * 'Graphics.GL.Tokens.GL_COLOR_MATRIX_STACK_DEPTH_SGI'
-- * 'Graphics.GL.Tokens.GL_COLOR_TABLE_SGI'
-- * 'Graphics.GL.Tokens.GL_COLOR_WRITEMASK'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_TEXTURE_FORMATS'
-- * 'Graphics.GL.Tokens.GL_CONTEXT_FLAGS'
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_1D_EXT'
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_2D_EXT'
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_HINT_SGIX'
-- * 'Graphics.GL.Tokens.GL_CULL_FACE'
-- * 'Graphics.GL.Tokens.GL_CULL_FACE_MODE'
-- * 'Graphics.GL.Tokens.GL_CURRENT_COLOR'
-- * 'Graphics.GL.Tokens.GL_CURRENT_INDEX'
-- * 'Graphics.GL.Tokens.GL_CURRENT_NORMAL'
-- * 'Graphics.GL.Tokens.GL_CURRENT_PROGRAM'
-- * 'Graphics.GL.Tokens.GL_CURRENT_RASTER_COLOR'
-- * 'Graphics.GL.Tokens.GL_CURRENT_RASTER_DISTANCE'
-- * 'Graphics.GL.Tokens.GL_CURRENT_RASTER_INDEX'
-- * 'Graphics.GL.Tokens.GL_CURRENT_RASTER_POSITION'
-- * 'Graphics.GL.Tokens.GL_CURRENT_RASTER_POSITION_VALID'
-- * 'Graphics.GL.Tokens.GL_CURRENT_RASTER_TEXTURE_COORDS'
-- * 'Graphics.GL.Tokens.GL_CURRENT_TEXTURE_COORDS'
-- * 'Graphics.GL.Tokens.GL_DEBUG_GROUP_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_DEFORMATIONS_MASK_SGIX'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BIAS'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BITS'
-- * 'Graphics.GL.Tokens.GL_DEPTH_CLEAR_VALUE'
-- * 'Graphics.GL.Tokens.GL_DEPTH_FUNC'
-- * 'Graphics.GL.Tokens.GL_DEPTH_RANGE'
-- * 'Graphics.GL.Tokens.GL_DEPTH_SCALE'
-- * 'Graphics.GL.Tokens.GL_DEPTH_TEST'
-- * 'Graphics.GL.Tokens.GL_DEPTH_WRITEMASK'
-- * 'Graphics.GL.Tokens.GL_DETAIL_TEXTURE_2D_BINDING_SGIS'
-- * 'Graphics.GL.Tokens.GL_DEVICE_LUID_EXT'
-- * 'Graphics.GL.Tokens.GL_DEVICE_NODE_MASK_EXT'
-- * 'Graphics.GL.Tokens.GL_DEVICE_UUID_EXT'
-- * 'Graphics.GL.Tokens.GL_DISPATCH_INDIRECT_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_DISTANCE_ATTENUATION_SGIS'
-- * 'Graphics.GL.Tokens.GL_DITHER'
-- * 'Graphics.GL.Tokens.GL_DOUBLEBUFFER'
-- * 'Graphics.GL.Tokens.GL_DRAW_BUFFER' (alias: 'Graphics.GL.Tokens.GL_DRAW_BUFFER_EXT')
-- * 'Graphics.GL.Tokens.GL_DRAW_FRAMEBUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_DRIVER_UUID_EXT'
-- * 'Graphics.GL.Tokens.GL_EDGE_FLAG'
-- * 'Graphics.GL.Tokens.GL_EDGE_FLAG_ARRAY'
-- * 'Graphics.GL.Tokens.GL_EDGE_FLAG_ARRAY_COUNT_EXT'
-- * 'Graphics.GL.Tokens.GL_EDGE_FLAG_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_ELEMENT_ARRAY_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_FEEDBACK_BUFFER_SIZE'
-- * 'Graphics.GL.Tokens.GL_FEEDBACK_BUFFER_TYPE'
-- * 'Graphics.GL.Tokens.GL_FOG'
-- * 'Graphics.GL.Tokens.GL_FOG_COLOR'
-- * 'Graphics.GL.Tokens.GL_FOG_DENSITY'
-- * 'Graphics.GL.Tokens.GL_FOG_END'
-- * 'Graphics.GL.Tokens.GL_FOG_FUNC_POINTS_SGIS'
-- * 'Graphics.GL.Tokens.GL_FOG_HINT'
-- * 'Graphics.GL.Tokens.GL_FOG_INDEX'
-- * 'Graphics.GL.Tokens.GL_FOG_MODE'
-- * 'Graphics.GL.Tokens.GL_FOG_OFFSET_SGIX'
-- * 'Graphics.GL.Tokens.GL_FOG_OFFSET_VALUE_SGIX'
-- * 'Graphics.GL.Tokens.GL_FOG_START'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_COLOR_MATERIAL_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT0_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHTING_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_SHADER_DERIVATIVE_HINT'
-- * 'Graphics.GL.Tokens.GL_FRAMEZOOM_FACTOR_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAMEZOOM_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRONT_FACE'
-- * 'Graphics.GL.Tokens.GL_GENERATE_MIPMAP_HINT_SGIS'
-- * 'Graphics.GL.Tokens.GL_GREEN_BIAS'
-- * 'Graphics.GL.Tokens.GL_GREEN_BITS'
-- * 'Graphics.GL.Tokens.GL_GREEN_SCALE'
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM_EXT'
-- * 'Graphics.GL.Tokens.GL_IMPLEMENTATION_COLOR_READ_FORMAT'
-- * 'Graphics.GL.Tokens.GL_IMPLEMENTATION_COLOR_READ_TYPE'
-- * 'Graphics.GL.Tokens.GL_INDEX_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INDEX_ARRAY_COUNT_EXT'
-- * 'Graphics.GL.Tokens.GL_INDEX_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_INDEX_ARRAY_TYPE'
-- * 'Graphics.GL.Tokens.GL_INDEX_BITS'
-- * 'Graphics.GL.Tokens.GL_INDEX_CLEAR_VALUE'
-- * 'Graphics.GL.Tokens.GL_INDEX_LOGIC_OP' (alias: 'Graphics.GL.Tokens.GL_LOGIC_OP')
-- * 'Graphics.GL.Tokens.GL_INDEX_MODE'
-- * 'Graphics.GL.Tokens.GL_INDEX_OFFSET'
-- * 'Graphics.GL.Tokens.GL_INDEX_SHIFT'
-- * 'Graphics.GL.Tokens.GL_INDEX_WRITEMASK'
-- * 'Graphics.GL.Tokens.GL_INSTRUMENT_MEASUREMENTS_SGIX'
-- * 'Graphics.GL.Tokens.GL_INTERLACE_SGIX'
-- * 'Graphics.GL.Tokens.GL_IR_INSTRUMENT1_SGIX'
-- * 'Graphics.GL.Tokens.GL_LAYER_PROVOKING_VERTEX'
-- * 'Graphics.GL.Tokens.GL_LIGHT0'
-- * 'Graphics.GL.Tokens.GL_LIGHT1'
-- * 'Graphics.GL.Tokens.GL_LIGHT2'
-- * 'Graphics.GL.Tokens.GL_LIGHT3'
-- * 'Graphics.GL.Tokens.GL_LIGHT4'
-- * 'Graphics.GL.Tokens.GL_LIGHT5'
-- * 'Graphics.GL.Tokens.GL_LIGHT6'
-- * 'Graphics.GL.Tokens.GL_LIGHT7'
-- * 'Graphics.GL.Tokens.GL_LIGHTING'
-- * 'Graphics.GL.Tokens.GL_LIGHT_ENV_MODE_SGIX'
-- * 'Graphics.GL.Tokens.GL_LIGHT_MODEL_AMBIENT'
-- * 'Graphics.GL.Tokens.GL_LIGHT_MODEL_COLOR_CONTROL'
-- * 'Graphics.GL.Tokens.GL_LIGHT_MODEL_LOCAL_VIEWER'
-- * 'Graphics.GL.Tokens.GL_LIGHT_MODEL_TWO_SIDE'
-- * 'Graphics.GL.Tokens.GL_LINE_SMOOTH'
-- * 'Graphics.GL.Tokens.GL_LINE_SMOOTH_HINT'
-- * 'Graphics.GL.Tokens.GL_LINE_STIPPLE'
-- * 'Graphics.GL.Tokens.GL_LINE_STIPPLE_PATTERN'
-- * 'Graphics.GL.Tokens.GL_LINE_STIPPLE_REPEAT'
-- * 'Graphics.GL.Tokens.GL_LINE_WIDTH'
-- * 'Graphics.GL.Tokens.GL_LINE_WIDTH_GRANULARITY' (alias: 'Graphics.GL.Tokens.GL_SMOOTH_LINE_WIDTH_GRANULARITY')
-- * 'Graphics.GL.Tokens.GL_LINE_WIDTH_RANGE' (alias: 'Graphics.GL.Tokens.GL_SMOOTH_LINE_WIDTH_RANGE')
-- * 'Graphics.GL.Tokens.GL_LIST_BASE'
-- * 'Graphics.GL.Tokens.GL_LIST_INDEX'
-- * 'Graphics.GL.Tokens.GL_LIST_MODE'
-- * 'Graphics.GL.Tokens.GL_LOGIC_OP_MODE'
-- * 'Graphics.GL.Tokens.GL_MAJOR_VERSION'
-- * 'Graphics.GL.Tokens.GL_MAP1_COLOR_4'
-- * 'Graphics.GL.Tokens.GL_MAP1_GRID_DOMAIN'
-- * 'Graphics.GL.Tokens.GL_MAP1_GRID_SEGMENTS'
-- * 'Graphics.GL.Tokens.GL_MAP1_INDEX'
-- * 'Graphics.GL.Tokens.GL_MAP1_NORMAL'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_1'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_2'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_3'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_4'
-- * 'Graphics.GL.Tokens.GL_MAP1_VERTEX_3'
-- * 'Graphics.GL.Tokens.GL_MAP1_VERTEX_4'
-- * 'Graphics.GL.Tokens.GL_MAP2_COLOR_4'
-- * 'Graphics.GL.Tokens.GL_MAP2_GRID_DOMAIN'
-- * 'Graphics.GL.Tokens.GL_MAP2_GRID_SEGMENTS'
-- * 'Graphics.GL.Tokens.GL_MAP2_INDEX'
-- * 'Graphics.GL.Tokens.GL_MAP2_NORMAL'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_1'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_2'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_3'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_4'
-- * 'Graphics.GL.Tokens.GL_MAP2_VERTEX_3'
-- * 'Graphics.GL.Tokens.GL_MAP2_VERTEX_4'
-- * 'Graphics.GL.Tokens.GL_MAP_COLOR'
-- * 'Graphics.GL.Tokens.GL_MAP_STENCIL'
-- * 'Graphics.GL.Tokens.GL_MATRIX_MODE'
-- * 'Graphics.GL.Tokens.GL_MAX_3D_TEXTURE_SIZE' (alias: 'Graphics.GL.Tokens.GL_MAX_3D_TEXTURE_SIZE_EXT')
-- * 'Graphics.GL.Tokens.GL_MAX_4D_TEXTURE_SIZE_SGIS'
-- * 'Graphics.GL.Tokens.GL_MAX_ACTIVE_LIGHTS_SGIX'
-- * 'Graphics.GL.Tokens.GL_MAX_ARRAY_TEXTURE_LAYERS'
-- * 'Graphics.GL.Tokens.GL_MAX_ASYNC_DRAW_PIXELS_SGIX'
-- * 'Graphics.GL.Tokens.GL_MAX_ASYNC_HISTOGRAM_SGIX'
-- * 'Graphics.GL.Tokens.GL_MAX_ASYNC_READ_PIXELS_SGIX'
-- * 'Graphics.GL.Tokens.GL_MAX_ASYNC_TEX_IMAGE_SGIX'
-- * 'Graphics.GL.Tokens.GL_MAX_ATTRIB_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_MAX_CLIENT_ATTRIB_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_MAX_CLIPMAP_DEPTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_MAX_CLIP_DISTANCES' (alias: 'Graphics.GL.Tokens.GL_MAX_CLIP_PLANES')
-- * 'Graphics.GL.Tokens.GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI'
-- * 'Graphics.GL.Tokens.GL_MAX_COLOR_TEXTURE_SAMPLES'
-- * 'Graphics.GL.Tokens.GL_MAX_COMBINED_ATOMIC_COUNTERS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMBINED_UNIFORM_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMPUTE_ATOMIC_COUNTERS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMPUTE_UNIFORM_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMPUTE_UNIFORM_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMPUTE_WORK_GROUP_COUNT'
-- * 'Graphics.GL.Tokens.GL_MAX_COMPUTE_WORK_GROUP_INVOCATIONS'
-- * 'Graphics.GL.Tokens.GL_MAX_COMPUTE_WORK_GROUP_SIZE'
-- * 'Graphics.GL.Tokens.GL_MAX_CUBE_MAP_TEXTURE_SIZE'
-- * 'Graphics.GL.Tokens.GL_MAX_DEBUG_GROUP_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_MAX_DEPTH_TEXTURE_SAMPLES'
-- * 'Graphics.GL.Tokens.GL_MAX_DRAW_BUFFERS'
-- * 'Graphics.GL.Tokens.GL_MAX_DUAL_SOURCE_DRAW_BUFFERS'
-- * 'Graphics.GL.Tokens.GL_MAX_ELEMENTS_INDICES'
-- * 'Graphics.GL.Tokens.GL_MAX_ELEMENTS_VERTICES'
-- * 'Graphics.GL.Tokens.GL_MAX_ELEMENT_INDEX'
-- * 'Graphics.GL.Tokens.GL_MAX_EVAL_ORDER'
-- * 'Graphics.GL.Tokens.GL_MAX_FOG_FUNC_POINTS_SGIS'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAGMENT_ATOMIC_COUNTERS'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAGMENT_INPUT_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAGMENT_LIGHTS_SGIX'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAGMENT_UNIFORM_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAGMENT_UNIFORM_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAGMENT_UNIFORM_VECTORS'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAMEBUFFER_HEIGHT'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAMEBUFFER_LAYERS'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAMEBUFFER_SAMPLES'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAMEBUFFER_WIDTH'
-- * 'Graphics.GL.Tokens.GL_MAX_FRAMEZOOM_FACTOR_SGIX'
-- * 'Graphics.GL.Tokens.GL_MAX_GEOMETRY_ATOMIC_COUNTERS'
-- * 'Graphics.GL.Tokens.GL_MAX_GEOMETRY_INPUT_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_GEOMETRY_OUTPUT_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS'
-- * 'Graphics.GL.Tokens.GL_MAX_GEOMETRY_UNIFORM_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_GEOMETRY_UNIFORM_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_INTEGER_SAMPLES'
-- * 'Graphics.GL.Tokens.GL_MAX_LABEL_LENGTH'
-- * 'Graphics.GL.Tokens.GL_MAX_LIGHTS'
-- * 'Graphics.GL.Tokens.GL_MAX_LIST_NESTING'
-- * 'Graphics.GL.Tokens.GL_MAX_MODELVIEW_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_MAX_NAME_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_MAX_PIXEL_MAP_TABLE'
-- * 'Graphics.GL.Tokens.GL_MAX_PROGRAM_TEXEL_OFFSET'
-- * 'Graphics.GL.Tokens.GL_MAX_PROJECTION_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_MAX_RECTANGLE_TEXTURE_SIZE'
-- * 'Graphics.GL.Tokens.GL_MAX_RENDERBUFFER_SIZE'
-- * 'Graphics.GL.Tokens.GL_MAX_SAMPLE_MASK_WORDS'
-- * 'Graphics.GL.Tokens.GL_MAX_SERVER_WAIT_TIMEOUT'
-- * 'Graphics.GL.Tokens.GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS'
-- * 'Graphics.GL.Tokens.GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS'
-- * 'Graphics.GL.Tokens.GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS'
-- * 'Graphics.GL.Tokens.GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_TEXTURE_BUFFER_SIZE'
-- * 'Graphics.GL.Tokens.GL_MAX_TEXTURE_IMAGE_UNITS'
-- * 'Graphics.GL.Tokens.GL_MAX_TEXTURE_LOD_BIAS'
-- * 'Graphics.GL.Tokens.GL_MAX_TEXTURE_SIZE'
-- * 'Graphics.GL.Tokens.GL_MAX_TEXTURE_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_MAX_UNIFORM_BLOCK_SIZE'
-- * 'Graphics.GL.Tokens.GL_MAX_UNIFORM_BUFFER_BINDINGS'
-- * 'Graphics.GL.Tokens.GL_MAX_UNIFORM_LOCATIONS'
-- * 'Graphics.GL.Tokens.GL_MAX_VARYING_COMPONENTS' (alias: 'Graphics.GL.Tokens.GL_MAX_VARYING_FLOATS')
-- * 'Graphics.GL.Tokens.GL_MAX_VARYING_VECTORS'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_ATOMIC_COUNTERS'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_ATTRIBS'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_ATTRIB_BINDINGS'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_OUTPUT_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_UNIFORM_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_UNIFORM_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_UNIFORM_VECTORS'
-- * 'Graphics.GL.Tokens.GL_MAX_VIEWPORTS'
-- * 'Graphics.GL.Tokens.GL_MAX_VIEWPORT_DIMS'
-- * 'Graphics.GL.Tokens.GL_MINMAX_EXT'
-- * 'Graphics.GL.Tokens.GL_MINOR_VERSION'
-- * 'Graphics.GL.Tokens.GL_MIN_MAP_BUFFER_ALIGNMENT'
-- * 'Graphics.GL.Tokens.GL_MIN_PROGRAM_TEXEL_OFFSET'
-- * 'Graphics.GL.Tokens.GL_MODELVIEW0_MATRIX_EXT' (alias: 'Graphics.GL.Tokens.GL_MODELVIEW_MATRIX')
-- * 'Graphics.GL.Tokens.GL_MODELVIEW0_STACK_DEPTH_EXT' (alias: 'Graphics.GL.Tokens.GL_MODELVIEW_STACK_DEPTH')
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_SGIS'
-- * 'Graphics.GL.Tokens.GL_NAME_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_NORMALIZE'
-- * 'Graphics.GL.Tokens.GL_NORMAL_ARRAY'
-- * 'Graphics.GL.Tokens.GL_NORMAL_ARRAY_COUNT_EXT'
-- * 'Graphics.GL.Tokens.GL_NORMAL_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_NORMAL_ARRAY_TYPE'
-- * 'Graphics.GL.Tokens.GL_NUM_COMPRESSED_TEXTURE_FORMATS'
-- * 'Graphics.GL.Tokens.GL_NUM_DEVICE_UUIDS_EXT'
-- * 'Graphics.GL.Tokens.GL_NUM_EXTENSIONS'
-- * 'Graphics.GL.Tokens.GL_NUM_PROGRAM_BINARY_FORMATS'
-- * 'Graphics.GL.Tokens.GL_NUM_SHADER_BINARY_FORMATS'
-- * 'Graphics.GL.Tokens.GL_PACK_ALIGNMENT'
-- * 'Graphics.GL.Tokens.GL_PACK_CMYK_HINT_EXT'
-- * 'Graphics.GL.Tokens.GL_PACK_IMAGE_DEPTH_SGIS'
-- * 'Graphics.GL.Tokens.GL_PACK_IMAGE_HEIGHT' (alias: 'Graphics.GL.Tokens.GL_PACK_IMAGE_HEIGHT_EXT')
-- * 'Graphics.GL.Tokens.GL_PACK_LSB_FIRST'
-- * 'Graphics.GL.Tokens.GL_PACK_RESAMPLE_SGIX'
-- * 'Graphics.GL.Tokens.GL_PACK_ROW_LENGTH'
-- * 'Graphics.GL.Tokens.GL_PACK_SKIP_IMAGES' (alias: 'Graphics.GL.Tokens.GL_PACK_SKIP_IMAGES_EXT')
-- * 'Graphics.GL.Tokens.GL_PACK_SKIP_PIXELS'
-- * 'Graphics.GL.Tokens.GL_PACK_SKIP_ROWS'
-- * 'Graphics.GL.Tokens.GL_PACK_SKIP_VOLUMES_SGIS'
-- * 'Graphics.GL.Tokens.GL_PACK_SUBSAMPLE_RATE_SGIX'
-- * 'Graphics.GL.Tokens.GL_PACK_SWAP_BYTES'
-- * 'Graphics.GL.Tokens.GL_PERSPECTIVE_CORRECTION_HINT'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_A_TO_A_SIZE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_B_TO_B_SIZE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_G_TO_G_SIZE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_A_SIZE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_B_SIZE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_G_SIZE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_I_SIZE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_R_SIZE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_R_TO_R_SIZE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_S_TO_S_SIZE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_PACK_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEXTURE_SGIS'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_MODE_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_CACHE_INCREMENT_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_CACHE_SIZE_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_GRID_DEPTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_GRID_HEIGHT_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_GRID_WIDTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_HEIGHT_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_WIDTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_UNPACK_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_POINT_FADE_THRESHOLD_SIZE' (alias: 'Graphics.GL.Tokens.GL_POINT_FADE_THRESHOLD_SIZE_SGIS')
-- * 'Graphics.GL.Tokens.GL_POINT_SIZE'
-- * 'Graphics.GL.Tokens.GL_POINT_SIZE_GRANULARITY' (alias: 'Graphics.GL.Tokens.GL_SMOOTH_POINT_SIZE_GRANULARITY')
-- * 'Graphics.GL.Tokens.GL_POINT_SIZE_MAX_SGIS'
-- * 'Graphics.GL.Tokens.GL_POINT_SIZE_MIN_SGIS'
-- * 'Graphics.GL.Tokens.GL_POINT_SIZE_RANGE' (alias: 'Graphics.GL.Tokens.GL_SMOOTH_POINT_SIZE_RANGE')
-- * 'Graphics.GL.Tokens.GL_POINT_SMOOTH'
-- * 'Graphics.GL.Tokens.GL_POINT_SMOOTH_HINT'
-- * 'Graphics.GL.Tokens.GL_POLYGON_MODE'
-- * 'Graphics.GL.Tokens.GL_POLYGON_OFFSET_BIAS_EXT'
-- * 'Graphics.GL.Tokens.GL_POLYGON_OFFSET_FACTOR'
-- * 'Graphics.GL.Tokens.GL_POLYGON_OFFSET_FILL'
-- * 'Graphics.GL.Tokens.GL_POLYGON_OFFSET_LINE'
-- * 'Graphics.GL.Tokens.GL_POLYGON_OFFSET_POINT'
-- * 'Graphics.GL.Tokens.GL_POLYGON_OFFSET_UNITS'
-- * 'Graphics.GL.Tokens.GL_POLYGON_SMOOTH'
-- * 'Graphics.GL.Tokens.GL_POLYGON_SMOOTH_HINT'
-- * 'Graphics.GL.Tokens.GL_POLYGON_STIPPLE'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_RED_BIAS_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_RED_SCALE_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_ALPHA_BIAS_EXT'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_ALPHA_SCALE_EXT'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_BLUE_BIAS_EXT'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_BLUE_SCALE_EXT'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_COLOR_TABLE_SGI'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_GREEN_BIAS_EXT'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_GREEN_SCALE_EXT'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_RED_BIAS_EXT'
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_RED_SCALE_EXT'
-- * 'Graphics.GL.Tokens.GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX'
-- * 'Graphics.GL.Tokens.GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX'
-- * 'Graphics.GL.Tokens.GL_PRIMITIVE_RESTART_INDEX'
-- * 'Graphics.GL.Tokens.GL_PROGRAM_BINARY_FORMATS'
-- * 'Graphics.GL.Tokens.GL_PROGRAM_PIPELINE_BINDING'
-- * 'Graphics.GL.Tokens.GL_PROGRAM_POINT_SIZE'
-- * 'Graphics.GL.Tokens.GL_PROJECTION_MATRIX'
-- * 'Graphics.GL.Tokens.GL_PROJECTION_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_PROVOKING_VERTEX'
-- * 'Graphics.GL.Tokens.GL_READ_BUFFER' (aliases: 'Graphics.GL.Tokens.GL_READ_BUFFER_EXT', 'Graphics.GL.Tokens.GL_READ_BUFFER_NV')
-- * 'Graphics.GL.Tokens.GL_READ_FRAMEBUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_RED_BIAS'
-- * 'Graphics.GL.Tokens.GL_RED_BITS'
-- * 'Graphics.GL.Tokens.GL_RED_SCALE'
-- * 'Graphics.GL.Tokens.GL_REFERENCE_PLANE_EQUATION_SGIX'
-- * 'Graphics.GL.Tokens.GL_REFERENCE_PLANE_SGIX'
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_RENDER_MODE'
-- * 'Graphics.GL.Tokens.GL_RESCALE_NORMAL_EXT'
-- * 'Graphics.GL.Tokens.GL_RGBA_MODE'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_BINDING'
-- * 'Graphics.GL.Tokens.GL_SAMPLES' (alias: 'Graphics.GL.Tokens.GL_SAMPLES_SGIS')
-- * 'Graphics.GL.Tokens.GL_SAMPLE_ALPHA_TO_MASK_SGIS'
-- * 'Graphics.GL.Tokens.GL_SAMPLE_ALPHA_TO_ONE_SGIS'
-- * 'Graphics.GL.Tokens.GL_SAMPLE_BUFFERS' (alias: 'Graphics.GL.Tokens.GL_SAMPLE_BUFFERS_SGIS')
-- * 'Graphics.GL.Tokens.GL_SAMPLE_COVERAGE_INVERT' (alias: 'Graphics.GL.Tokens.GL_SAMPLE_MASK_INVERT_SGIS')
-- * 'Graphics.GL.Tokens.GL_SAMPLE_COVERAGE_VALUE' (alias: 'Graphics.GL.Tokens.GL_SAMPLE_MASK_VALUE_SGIS')
-- * 'Graphics.GL.Tokens.GL_SAMPLE_MASK_SGIS'
-- * 'Graphics.GL.Tokens.GL_SAMPLE_PATTERN_SGIS'
-- * 'Graphics.GL.Tokens.GL_SCISSOR_BOX'
-- * 'Graphics.GL.Tokens.GL_SCISSOR_TEST'
-- * 'Graphics.GL.Tokens.GL_SELECTION_BUFFER_SIZE'
-- * 'Graphics.GL.Tokens.GL_SEPARABLE_2D_EXT'
-- * 'Graphics.GL.Tokens.GL_SHADER_COMPILER'
-- * 'Graphics.GL.Tokens.GL_SHADER_STORAGE_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT'
-- * 'Graphics.GL.Tokens.GL_SHADER_STORAGE_BUFFER_SIZE'
-- * 'Graphics.GL.Tokens.GL_SHADER_STORAGE_BUFFER_START'
-- * 'Graphics.GL.Tokens.GL_SHADE_MODEL'
-- * 'Graphics.GL.Tokens.GL_SHARED_TEXTURE_PALETTE_EXT'
-- * 'Graphics.GL.Tokens.GL_SPRITE_AXIS_SGIX'
-- * 'Graphics.GL.Tokens.GL_SPRITE_MODE_SGIX'
-- * 'Graphics.GL.Tokens.GL_SPRITE_SGIX'
-- * 'Graphics.GL.Tokens.GL_SPRITE_TRANSLATION_SGIX'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BACK_FAIL'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BACK_FUNC'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BACK_PASS_DEPTH_FAIL'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BACK_PASS_DEPTH_PASS'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BACK_REF'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BACK_VALUE_MASK'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BACK_WRITEMASK'
-- * 'Graphics.GL.Tokens.GL_STENCIL_BITS'
-- * 'Graphics.GL.Tokens.GL_STENCIL_CLEAR_VALUE'
-- * 'Graphics.GL.Tokens.GL_STENCIL_FAIL'
-- * 'Graphics.GL.Tokens.GL_STENCIL_FUNC'
-- * 'Graphics.GL.Tokens.GL_STENCIL_PASS_DEPTH_FAIL'
-- * 'Graphics.GL.Tokens.GL_STENCIL_PASS_DEPTH_PASS'
-- * 'Graphics.GL.Tokens.GL_STENCIL_REF'
-- * 'Graphics.GL.Tokens.GL_STENCIL_TEST'
-- * 'Graphics.GL.Tokens.GL_STENCIL_VALUE_MASK'
-- * 'Graphics.GL.Tokens.GL_STENCIL_WRITEMASK'
-- * 'Graphics.GL.Tokens.GL_STEREO'
-- * 'Graphics.GL.Tokens.GL_SUBPIXEL_BITS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_1D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_2D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_3D_BINDING_EXT' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_BINDING_3D')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_3D_EXT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_4D_BINDING_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_4D_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BINDING_1D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BINDING_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BINDING_2D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BINDING_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BINDING_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BINDING_BUFFER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BINDING_CUBE_MAP'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BINDING_RECTANGLE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COLOR_TABLE_SGI'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPRESSION_HINT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COORD_ARRAY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COORD_ARRAY_COUNT_EXT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COORD_ARRAY_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COORD_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COORD_ARRAY_TYPE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEN_Q'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEN_R'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEN_S'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEN_T'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MATRIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_STACK_DEPTH'
-- * 'Graphics.GL.Tokens.GL_TIMESTAMP'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER_SIZE'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER_START'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BUFFER_SIZE'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BUFFER_START'
-- * 'Graphics.GL.Tokens.GL_UNPACK_ALIGNMENT'
-- * 'Graphics.GL.Tokens.GL_UNPACK_CMYK_HINT_EXT'
-- * 'Graphics.GL.Tokens.GL_UNPACK_IMAGE_DEPTH_SGIS'
-- * 'Graphics.GL.Tokens.GL_UNPACK_IMAGE_HEIGHT' (alias: 'Graphics.GL.Tokens.GL_UNPACK_IMAGE_HEIGHT_EXT')
-- * 'Graphics.GL.Tokens.GL_UNPACK_LSB_FIRST'
-- * 'Graphics.GL.Tokens.GL_UNPACK_RESAMPLE_SGIX'
-- * 'Graphics.GL.Tokens.GL_UNPACK_ROW_LENGTH'
-- * 'Graphics.GL.Tokens.GL_UNPACK_SKIP_IMAGES' (alias: 'Graphics.GL.Tokens.GL_UNPACK_SKIP_IMAGES_EXT')
-- * 'Graphics.GL.Tokens.GL_UNPACK_SKIP_PIXELS'
-- * 'Graphics.GL.Tokens.GL_UNPACK_SKIP_ROWS'
-- * 'Graphics.GL.Tokens.GL_UNPACK_SKIP_VOLUMES_SGIS'
-- * 'Graphics.GL.Tokens.GL_UNPACK_SUBSAMPLE_RATE_SGIX'
-- * 'Graphics.GL.Tokens.GL_UNPACK_SWAP_BYTES'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ARRAY'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ARRAY_BINDING'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ARRAY_COUNT_EXT'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ARRAY_SIZE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ARRAY_TYPE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_BINDING_DIVISOR'
-- * 'Graphics.GL.Tokens.GL_VERTEX_BINDING_OFFSET'
-- * 'Graphics.GL.Tokens.GL_VERTEX_BINDING_STRIDE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_PRECLIP_HINT_SGIX'
-- * 'Graphics.GL.Tokens.GL_VERTEX_PRECLIP_SGIX'
-- * 'Graphics.GL.Tokens.GL_VIEWPORT'
-- * 'Graphics.GL.Tokens.GL_VIEWPORT_BOUNDS_RANGE'
-- * 'Graphics.GL.Tokens.GL_VIEWPORT_INDEX_PROVOKING_VERTEX'
-- * 'Graphics.GL.Tokens.GL_VIEWPORT_SUBPIXEL_BITS'
-- * 'Graphics.GL.Tokens.GL_ZOOM_X'
-- * 'Graphics.GL.Tokens.GL_ZOOM_Y'
--
-- === #GetPixelMap# GetPixelMap
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_A_TO_A'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_B_TO_B'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_G_TO_G'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_A'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_B'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_G'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_I'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_R'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_R_TO_R'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_S_TO_S'
--
-- === #GetPointervPName# GetPointervPName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COLOR_ARRAY_POINTER' (alias: 'Graphics.GL.Tokens.GL_COLOR_ARRAY_POINTER_EXT')
-- * 'Graphics.GL.Tokens.GL_EDGE_FLAG_ARRAY_POINTER' (alias: 'Graphics.GL.Tokens.GL_EDGE_FLAG_ARRAY_POINTER_EXT')
-- * 'Graphics.GL.Tokens.GL_FEEDBACK_BUFFER_POINTER'
-- * 'Graphics.GL.Tokens.GL_INDEX_ARRAY_POINTER' (alias: 'Graphics.GL.Tokens.GL_INDEX_ARRAY_POINTER_EXT')
-- * 'Graphics.GL.Tokens.GL_INSTRUMENT_BUFFER_POINTER_SGIX'
-- * 'Graphics.GL.Tokens.GL_NORMAL_ARRAY_POINTER' (alias: 'Graphics.GL.Tokens.GL_NORMAL_ARRAY_POINTER_EXT')
-- * 'Graphics.GL.Tokens.GL_SELECTION_BUFFER_POINTER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COORD_ARRAY_POINTER' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_COORD_ARRAY_POINTER_EXT')
-- * 'Graphics.GL.Tokens.GL_VERTEX_ARRAY_POINTER' (alias: 'Graphics.GL.Tokens.GL_VERTEX_ARRAY_POINTER_EXT')
-- * 'Graphics.GL.Tokens.GL_DEBUG_CALLBACK_FUNCTION'
-- * 'Graphics.GL.Tokens.GL_DEBUG_CALLBACK_USER_PARAM'
--
-- === #GetTexBumpParameterATI# GetTexBumpParameterATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BUMP_ROT_MATRIX_ATI'
-- * 'Graphics.GL.Tokens.GL_BUMP_ROT_MATRIX_SIZE_ATI'
-- * 'Graphics.GL.Tokens.GL_BUMP_NUM_TEX_UNITS_ATI'
-- * 'Graphics.GL.Tokens.GL_BUMP_TEX_UNITS_ATI'
--
-- === #GetTextureParameter# GetTextureParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS'
-- * 'Graphics.GL.Tokens.GL_DETAIL_TEXTURE_LEVEL_SGIS'
-- * 'Graphics.GL.Tokens.GL_DETAIL_TEXTURE_MODE_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_TEXTURE_SELECT_SGIS'
-- * 'Graphics.GL.Tokens.GL_GENERATE_MIPMAP_SGIS'
-- * 'Graphics.GL.Tokens.GL_POST_TEXTURE_FILTER_BIAS_SGIX'
-- * 'Graphics.GL.Tokens.GL_POST_TEXTURE_FILTER_SCALE_SGIX'
-- * 'Graphics.GL.Tokens.GL_QUAD_TEXTURE_SELECT_SGIS'
-- * 'Graphics.GL.Tokens.GL_SHADOW_AMBIENT_SGIX'
-- * 'Graphics.GL.Tokens.GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_4DSIZE_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_ALPHA_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BASE_LEVEL_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BLUE_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BORDER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BORDER_COLOR' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_BORDER_COLOR_NV')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_CENTER_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_DEPTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_FRAME_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_OFFSET_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPARE_OPERATOR_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPARE_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPONENTS' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_INTERNAL_FORMAT')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_DEPTH_EXT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_FILTER4_SIZE_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEQUAL_R_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GREEN_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_HEIGHT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_INTENSITY_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LEQUAL_R_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LOD_BIAS_R_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LOD_BIAS_S_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LOD_BIAS_T_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LUMINANCE_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAG_FILTER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_CLAMP_R_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_CLAMP_S_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_CLAMP_T_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_LEVEL_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_LOD_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MIN_FILTER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MIN_LOD_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_PRIORITY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_RED_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_RESIDENT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WIDTH'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_Q_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_R_EXT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_S'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_T'
--
-- === #GetVariantValueEXT# GetVariantValueEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VARIANT_VALUE_EXT'
-- * 'Graphics.GL.Tokens.GL_VARIANT_DATATYPE_EXT'
-- * 'Graphics.GL.Tokens.GL_VARIANT_ARRAY_STRIDE_EXT'
-- * 'Graphics.GL.Tokens.GL_VARIANT_ARRAY_TYPE_EXT'
--
-- === #GlslTypeToken# GlslTypeToken
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_FLOAT_VEC2'
-- * 'Graphics.GL.Tokens.GL_FLOAT_VEC3'
-- * 'Graphics.GL.Tokens.GL_FLOAT_VEC4'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_VEC2'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_VEC3'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_VEC4'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_INT_VEC2'
-- * 'Graphics.GL.Tokens.GL_INT_VEC3'
-- * 'Graphics.GL.Tokens.GL_INT_VEC4'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_VEC2'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_VEC3'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_VEC4'
-- * 'Graphics.GL.Tokens.GL_BOOL'
-- * 'Graphics.GL.Tokens.GL_BOOL_VEC2'
-- * 'Graphics.GL.Tokens.GL_BOOL_VEC3'
-- * 'Graphics.GL.Tokens.GL_BOOL_VEC4'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT2'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT3'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT4'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT2x3'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT2x4'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT3x2'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT3x4'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT4x2'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT4x3'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT2'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT3'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT4'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_3D'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D_ARRAY_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_ARRAY_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_RECT_SHADOW'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_1D'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_3D'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_CUBE'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_1D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_3D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_CUBE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_IMAGE_1D'
-- * 'Graphics.GL.Tokens.GL_IMAGE_2D'
-- * 'Graphics.GL.Tokens.GL_IMAGE_3D'
-- * 'Graphics.GL.Tokens.GL_IMAGE_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_IMAGE_CUBE'
-- * 'Graphics.GL.Tokens.GL_IMAGE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_IMAGE_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_IMAGE_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_IMAGE_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_IMAGE_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_IMAGE_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_1D'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_2D'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_3D'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_CUBE'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_1D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_2D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_3D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_CUBE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_BUFFER'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_ATOMIC_COUNTER'
--
-- === #GraphicsResetStatus# GraphicsResetStatus
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NO_ERROR'
-- * 'Graphics.GL.Tokens.GL_GUILTY_CONTEXT_RESET'
-- * 'Graphics.GL.Tokens.GL_INNOCENT_CONTEXT_RESET'
-- * 'Graphics.GL.Tokens.GL_UNKNOWN_CONTEXT_RESET'
--
-- === #HintMode# HintMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DONT_CARE'
-- * 'Graphics.GL.Tokens.GL_FASTEST'
-- * 'Graphics.GL.Tokens.GL_NICEST'
--
-- === #HintTarget# HintTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALLOW_DRAW_FRG_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_ALLOW_DRAW_MEM_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_ALLOW_DRAW_OBJ_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_ALLOW_DRAW_WIN_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_ALWAYS_FAST_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_ALWAYS_SOFT_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_BACK_NORMALS_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_BINNING_CONTROL_HINT_QCOM'
-- * 'Graphics.GL.Tokens.GL_CLIP_FAR_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_CLIP_NEAR_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_CLIP_VOLUME_CLIPPING_HINT_EXT'
-- * 'Graphics.GL.Tokens.GL_CONSERVE_MEMORY_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_CONVOLUTION_HINT_SGIX'
-- * 'Graphics.GL.Tokens.GL_FOG_HINT'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_SHADER_DERIVATIVE_HINT' (aliases: 'Graphics.GL.Tokens.GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB', 'Graphics.GL.Tokens.GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES')
-- * 'Graphics.GL.Tokens.GL_FULL_STIPPLE_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_GENERATE_MIPMAP_HINT' (alias: 'Graphics.GL.Tokens.GL_GENERATE_MIPMAP_HINT_SGIS')
-- * 'Graphics.GL.Tokens.GL_LINE_QUALITY_HINT_SGIX'
-- * 'Graphics.GL.Tokens.GL_LINE_SMOOTH_HINT'
-- * 'Graphics.GL.Tokens.GL_MATERIAL_SIDE_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_MULTISAMPLE_FILTER_HINT_NV'
-- * 'Graphics.GL.Tokens.GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_NATIVE_GRAPHICS_END_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_PACK_CMYK_HINT_EXT'
-- * 'Graphics.GL.Tokens.GL_PERSPECTIVE_CORRECTION_HINT'
-- * 'Graphics.GL.Tokens.GL_PHONG_HINT_WIN'
-- * 'Graphics.GL.Tokens.GL_POINT_SMOOTH_HINT'
-- * 'Graphics.GL.Tokens.GL_POLYGON_SMOOTH_HINT'
-- * 'Graphics.GL.Tokens.GL_PREFER_DOUBLEBUFFER_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_PROGRAM_BINARY_RETRIEVABLE_HINT'
-- * 'Graphics.GL.Tokens.GL_RECLAIM_MEMORY_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_SCALEBIAS_HINT_SGIX'
-- * 'Graphics.GL.Tokens.GL_STRICT_DEPTHFUNC_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_STRICT_LIGHTING_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_STRICT_SCISSOR_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPRESSION_HINT' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_COMPRESSION_HINT_ARB')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MULTI_BUFFER_HINT_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_STORAGE_HINT_APPLE'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_HINT_APPLE'
-- * 'Graphics.GL.Tokens.GL_UNPACK_CMYK_HINT_EXT'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ARRAY_STORAGE_HINT_APPLE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_CONSISTENT_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_VERTEX_DATA_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_VERTEX_PRECLIP_HINT_SGIX'
-- * 'Graphics.GL.Tokens.GL_VERTEX_PRECLIP_SGIX'
-- * 'Graphics.GL.Tokens.GL_WIDE_LINE_HINT_PGI'
--
-- === #HintTargetPGI# HintTargetPGI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VERTEX_DATA_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_VERTEX_CONSISTENT_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_MATERIAL_SIDE_HINT_PGI'
-- * 'Graphics.GL.Tokens.GL_MAX_VERTEX_HINT_PGI'
--
-- === #HistogramTargetEXT# HistogramTargetEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_HISTOGRAM' (alias: 'Graphics.GL.Tokens.GL_HISTOGRAM_EXT')
-- * 'Graphics.GL.Tokens.GL_PROXY_HISTOGRAM' (alias: 'Graphics.GL.Tokens.GL_PROXY_HISTOGRAM_EXT')
--
-- === #IglooFunctionSelectSGIX# IglooFunctionSelectSGIX
-- There are no values defined for this enumeration group.
--
--
-- === #ImageTransformPNameHP# ImageTransformPNameHP
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_IMAGE_SCALE_X_HP'
-- * 'Graphics.GL.Tokens.GL_IMAGE_SCALE_Y_HP'
-- * 'Graphics.GL.Tokens.GL_IMAGE_TRANSLATE_X_HP'
-- * 'Graphics.GL.Tokens.GL_IMAGE_TRANSLATE_Y_HP'
-- * 'Graphics.GL.Tokens.GL_IMAGE_ROTATE_ANGLE_HP'
-- * 'Graphics.GL.Tokens.GL_IMAGE_ROTATE_ORIGIN_X_HP'
-- * 'Graphics.GL.Tokens.GL_IMAGE_ROTATE_ORIGIN_Y_HP'
-- * 'Graphics.GL.Tokens.GL_IMAGE_MAG_FILTER_HP'
-- * 'Graphics.GL.Tokens.GL_IMAGE_MIN_FILTER_HP'
-- * 'Graphics.GL.Tokens.GL_IMAGE_CUBIC_WEIGHT_HP'
--
-- === #ImageTransformTargetHP# ImageTransformTargetHP
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_IMAGE_TRANSFORM_2D_HP'
--
-- === #IndexFunctionEXT# IndexFunctionEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NEVER'
-- * 'Graphics.GL.Tokens.GL_ALWAYS'
-- * 'Graphics.GL.Tokens.GL_LESS'
-- * 'Graphics.GL.Tokens.GL_LEQUAL'
-- * 'Graphics.GL.Tokens.GL_EQUAL'
-- * 'Graphics.GL.Tokens.GL_GEQUAL'
-- * 'Graphics.GL.Tokens.GL_GREATER'
-- * 'Graphics.GL.Tokens.GL_NOTEQUAL'
--
-- === #IndexMaterialParameterEXT# IndexMaterialParameterEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_INDEX_OFFSET'
--
-- === #IndexPointerType# IndexPointerType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_SHORT'
--
-- === #InterleavedArrayFormat# InterleavedArrayFormat
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_C3F_V3F'
-- * 'Graphics.GL.Tokens.GL_C4F_N3F_V3F'
-- * 'Graphics.GL.Tokens.GL_C4UB_V2F'
-- * 'Graphics.GL.Tokens.GL_C4UB_V3F'
-- * 'Graphics.GL.Tokens.GL_N3F_V3F'
-- * 'Graphics.GL.Tokens.GL_T2F_C3F_V3F'
-- * 'Graphics.GL.Tokens.GL_T2F_C4F_N3F_V3F'
-- * 'Graphics.GL.Tokens.GL_T2F_C4UB_V3F'
-- * 'Graphics.GL.Tokens.GL_T2F_N3F_V3F'
-- * 'Graphics.GL.Tokens.GL_T2F_V3F'
-- * 'Graphics.GL.Tokens.GL_T4F_C4F_N3F_V4F'
-- * 'Graphics.GL.Tokens.GL_T4F_V4F'
-- * 'Graphics.GL.Tokens.GL_V2F'
-- * 'Graphics.GL.Tokens.GL_V3F'
--
-- === #InternalFormat# InternalFormat
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALPHA12'
-- * 'Graphics.GL.Tokens.GL_ALPHA16'
-- * 'Graphics.GL.Tokens.GL_ALPHA4'
-- * 'Graphics.GL.Tokens.GL_ALPHA8'
-- * 'Graphics.GL.Tokens.GL_DUAL_ALPHA12_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_ALPHA16_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_ALPHA4_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_ALPHA8_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_INTENSITY12_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_INTENSITY16_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_INTENSITY4_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_INTENSITY8_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_LUMINANCE12_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_LUMINANCE16_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_LUMINANCE4_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_LUMINANCE8_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_LUMINANCE_ALPHA4_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_LUMINANCE_ALPHA8_SGIS'
-- * 'Graphics.GL.Tokens.GL_INTENSITY'
-- * 'Graphics.GL.Tokens.GL_INTENSITY12'
-- * 'Graphics.GL.Tokens.GL_INTENSITY16'
-- * 'Graphics.GL.Tokens.GL_INTENSITY4'
-- * 'Graphics.GL.Tokens.GL_INTENSITY8'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE12'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE12_ALPHA12'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE12_ALPHA4'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE16'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE16_ALPHA16'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE4'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE4_ALPHA4'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE6_ALPHA2'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE8'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE8_ALPHA8'
-- * 'Graphics.GL.Tokens.GL_QUAD_ALPHA4_SGIS'
-- * 'Graphics.GL.Tokens.GL_QUAD_ALPHA8_SGIS'
-- * 'Graphics.GL.Tokens.GL_QUAD_INTENSITY4_SGIS'
-- * 'Graphics.GL.Tokens.GL_QUAD_INTENSITY8_SGIS'
-- * 'Graphics.GL.Tokens.GL_QUAD_LUMINANCE4_SGIS'
-- * 'Graphics.GL.Tokens.GL_QUAD_LUMINANCE8_SGIS'
-- * 'Graphics.GL.Tokens.GL_RED' (alias: 'Graphics.GL.Tokens.GL_RED_EXT')
-- * 'Graphics.GL.Tokens.GL_R8' (alias: 'Graphics.GL.Tokens.GL_R8_EXT')
-- * 'Graphics.GL.Tokens.GL_R8_SNORM'
-- * 'Graphics.GL.Tokens.GL_R16' (alias: 'Graphics.GL.Tokens.GL_R16_EXT')
-- * 'Graphics.GL.Tokens.GL_R16_SNORM' (alias: 'Graphics.GL.Tokens.GL_R16_SNORM_EXT')
-- * 'Graphics.GL.Tokens.GL_R16F' (alias: 'Graphics.GL.Tokens.GL_R16F_EXT')
-- * 'Graphics.GL.Tokens.GL_R32F' (alias: 'Graphics.GL.Tokens.GL_R32F_EXT')
-- * 'Graphics.GL.Tokens.GL_R8I'
-- * 'Graphics.GL.Tokens.GL_R16I'
-- * 'Graphics.GL.Tokens.GL_R32I'
-- * 'Graphics.GL.Tokens.GL_R8UI'
-- * 'Graphics.GL.Tokens.GL_R16UI'
-- * 'Graphics.GL.Tokens.GL_R32UI'
-- * 'Graphics.GL.Tokens.GL_RG'
-- * 'Graphics.GL.Tokens.GL_RG8' (alias: 'Graphics.GL.Tokens.GL_RG8_EXT')
-- * 'Graphics.GL.Tokens.GL_RG8_SNORM'
-- * 'Graphics.GL.Tokens.GL_RG16' (alias: 'Graphics.GL.Tokens.GL_RG16_EXT')
-- * 'Graphics.GL.Tokens.GL_RG16_SNORM' (alias: 'Graphics.GL.Tokens.GL_RG16_SNORM_EXT')
-- * 'Graphics.GL.Tokens.GL_RG16F' (alias: 'Graphics.GL.Tokens.GL_RG16F_EXT')
-- * 'Graphics.GL.Tokens.GL_RG32F' (alias: 'Graphics.GL.Tokens.GL_RG32F_EXT')
-- * 'Graphics.GL.Tokens.GL_RG8I'
-- * 'Graphics.GL.Tokens.GL_RG16I'
-- * 'Graphics.GL.Tokens.GL_RG32I'
-- * 'Graphics.GL.Tokens.GL_RG8UI'
-- * 'Graphics.GL.Tokens.GL_RG16UI'
-- * 'Graphics.GL.Tokens.GL_RG32UI'
-- * 'Graphics.GL.Tokens.GL_RGB'
-- * 'Graphics.GL.Tokens.GL_RGB2_EXT'
-- * 'Graphics.GL.Tokens.GL_RGB4' (alias: 'Graphics.GL.Tokens.GL_RGB4_EXT')
-- * 'Graphics.GL.Tokens.GL_RGB5' (alias: 'Graphics.GL.Tokens.GL_RGB5_EXT')
-- * 'Graphics.GL.Tokens.GL_RGB8' (aliases: 'Graphics.GL.Tokens.GL_RGB8_EXT', 'Graphics.GL.Tokens.GL_RGB8_OES')
-- * 'Graphics.GL.Tokens.GL_RGB8_SNORM'
-- * 'Graphics.GL.Tokens.GL_RGB10' (alias: 'Graphics.GL.Tokens.GL_RGB10_EXT')
-- * 'Graphics.GL.Tokens.GL_RGB12' (alias: 'Graphics.GL.Tokens.GL_RGB12_EXT')
-- * 'Graphics.GL.Tokens.GL_RGB16' (alias: 'Graphics.GL.Tokens.GL_RGB16_EXT')
-- * 'Graphics.GL.Tokens.GL_RGB16F' (aliases: 'Graphics.GL.Tokens.GL_RGB16F_ARB', 'Graphics.GL.Tokens.GL_RGB16F_EXT')
-- * 'Graphics.GL.Tokens.GL_RGB16_SNORM' (alias: 'Graphics.GL.Tokens.GL_RGB16_SNORM_EXT')
-- * 'Graphics.GL.Tokens.GL_RGB32F'
-- * 'Graphics.GL.Tokens.GL_RGB8I'
-- * 'Graphics.GL.Tokens.GL_RGB16I'
-- * 'Graphics.GL.Tokens.GL_RGB32I'
-- * 'Graphics.GL.Tokens.GL_RGB8UI'
-- * 'Graphics.GL.Tokens.GL_RGB16UI'
-- * 'Graphics.GL.Tokens.GL_RGB32UI'
-- * 'Graphics.GL.Tokens.GL_SRGB' (alias: 'Graphics.GL.Tokens.GL_SRGB_EXT')
-- * 'Graphics.GL.Tokens.GL_SRGB_ALPHA' (alias: 'Graphics.GL.Tokens.GL_SRGB_ALPHA_EXT')
-- * 'Graphics.GL.Tokens.GL_SRGB8' (aliases: 'Graphics.GL.Tokens.GL_SRGB8_EXT', 'Graphics.GL.Tokens.GL_SRGB8_NV')
-- * 'Graphics.GL.Tokens.GL_SRGB8_ALPHA8' (alias: 'Graphics.GL.Tokens.GL_SRGB8_ALPHA8_EXT')
-- * 'Graphics.GL.Tokens.GL_R3_G3_B2'
-- * 'Graphics.GL.Tokens.GL_R11F_G11F_B10F' (aliases: 'Graphics.GL.Tokens.GL_R11F_G11F_B10F_APPLE', 'Graphics.GL.Tokens.GL_R11F_G11F_B10F_EXT')
-- * 'Graphics.GL.Tokens.GL_RGB9_E5' (aliases: 'Graphics.GL.Tokens.GL_RGB9_E5_APPLE', 'Graphics.GL.Tokens.GL_RGB9_E5_EXT')
-- * 'Graphics.GL.Tokens.GL_RGBA'
-- * 'Graphics.GL.Tokens.GL_RGBA4' (aliases: 'Graphics.GL.Tokens.GL_RGBA4_EXT', 'Graphics.GL.Tokens.GL_RGBA4_OES')
-- * 'Graphics.GL.Tokens.GL_RGB5_A1' (aliases: 'Graphics.GL.Tokens.GL_RGB5_A1_EXT', 'Graphics.GL.Tokens.GL_RGB5_A1_OES')
-- * 'Graphics.GL.Tokens.GL_RGBA8' (aliases: 'Graphics.GL.Tokens.GL_RGBA8_EXT', 'Graphics.GL.Tokens.GL_RGBA8_OES')
-- * 'Graphics.GL.Tokens.GL_RGBA8_SNORM'
-- * 'Graphics.GL.Tokens.GL_RGB10_A2' (alias: 'Graphics.GL.Tokens.GL_RGB10_A2_EXT')
-- * 'Graphics.GL.Tokens.GL_RGBA12' (alias: 'Graphics.GL.Tokens.GL_RGBA12_EXT')
-- * 'Graphics.GL.Tokens.GL_RGBA16' (alias: 'Graphics.GL.Tokens.GL_RGBA16_EXT')
-- * 'Graphics.GL.Tokens.GL_RGBA16F' (aliases: 'Graphics.GL.Tokens.GL_RGBA16F_ARB', 'Graphics.GL.Tokens.GL_RGBA16F_EXT')
-- * 'Graphics.GL.Tokens.GL_RGBA32F' (aliases: 'Graphics.GL.Tokens.GL_RGBA32F_ARB', 'Graphics.GL.Tokens.GL_RGBA32F_EXT')
-- * 'Graphics.GL.Tokens.GL_RGBA8I'
-- * 'Graphics.GL.Tokens.GL_RGBA16I'
-- * 'Graphics.GL.Tokens.GL_RGBA32I'
-- * 'Graphics.GL.Tokens.GL_RGBA8UI'
-- * 'Graphics.GL.Tokens.GL_RGBA16UI'
-- * 'Graphics.GL.Tokens.GL_RGBA32UI'
-- * 'Graphics.GL.Tokens.GL_RGB10_A2UI'
-- * 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT'
-- * 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT16' (aliases: 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT16_ARB', 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT16_OES', 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT16_SGIX')
-- * 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT24_ARB' (aliases: 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT24_OES', 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT24_SGIX')
-- * 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT32_ARB' (aliases: 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT32_OES', 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT32_SGIX')
-- * 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT32F'
-- * 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT32F_NV'
-- * 'Graphics.GL.Tokens.GL_DEPTH_STENCIL' (aliases: 'Graphics.GL.Tokens.GL_DEPTH_STENCIL_EXT', 'Graphics.GL.Tokens.GL_DEPTH_STENCIL_NV', 'Graphics.GL.Tokens.GL_DEPTH_STENCIL_OES')
-- * 'Graphics.GL.Tokens.GL_DEPTH_STENCIL_MESA'
-- * 'Graphics.GL.Tokens.GL_DEPTH24_STENCIL8' (aliases: 'Graphics.GL.Tokens.GL_DEPTH24_STENCIL8_EXT', 'Graphics.GL.Tokens.GL_DEPTH24_STENCIL8_OES')
-- * 'Graphics.GL.Tokens.GL_DEPTH32F_STENCIL8'
-- * 'Graphics.GL.Tokens.GL_DEPTH32F_STENCIL8_NV'
-- * 'Graphics.GL.Tokens.GL_STENCIL_INDEX' (alias: 'Graphics.GL.Tokens.GL_STENCIL_INDEX_OES')
-- * 'Graphics.GL.Tokens.GL_STENCIL_INDEX1' (aliases: 'Graphics.GL.Tokens.GL_STENCIL_INDEX1_EXT', 'Graphics.GL.Tokens.GL_STENCIL_INDEX1_OES')
-- * 'Graphics.GL.Tokens.GL_STENCIL_INDEX4' (aliases: 'Graphics.GL.Tokens.GL_STENCIL_INDEX4_EXT', 'Graphics.GL.Tokens.GL_STENCIL_INDEX4_OES')
-- * 'Graphics.GL.Tokens.GL_STENCIL_INDEX8' (aliases: 'Graphics.GL.Tokens.GL_STENCIL_INDEX8_EXT', 'Graphics.GL.Tokens.GL_STENCIL_INDEX8_OES')
-- * 'Graphics.GL.Tokens.GL_STENCIL_INDEX16' (alias: 'Graphics.GL.Tokens.GL_STENCIL_INDEX16_EXT')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RED'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RG'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGB'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB_ALPHA'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RED_RGTC1' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RED_RGTC1_EXT')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SIGNED_RED_RGTC1' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SIGNED_RED_RGTC1_EXT')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_R11_EAC'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SIGNED_R11_EAC'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RG_RGTC2'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SIGNED_RG_RGTC2'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_BPTC_UNORM'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGB8_ETC2'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ETC2'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA8_ETC2_EAC'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RG11_EAC'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SIGNED_RG11_EAC'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGB_S3TC_DXT1_EXT'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB_S3TC_DXT1_EXT'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_S3TC_DXT1_EXT'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_S3TC_DXT3_EXT'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_S3TC_DXT5_EXT'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_3x3x3_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_4x3x3_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_4x4' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_4x4_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_4x4x3_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_4x4x4_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_5x4' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_5x4_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_5x4x4_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_5x5' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_5x5_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_5x5x4_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_5x5x5_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_6x5' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_6x5_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_6x5x5_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_6x6' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_6x6_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_6x6x5_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_6x6x6_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_8x5' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_8x5_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_8x6' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_8x6_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_8x8' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_8x8_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_10x10' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_10x10_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_10x5' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_10x5_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_10x6' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_10x6_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_10x8' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_10x8_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_12x10' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_12x10_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_12x12' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_RGBA_ASTC_12x12_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_3x3x3_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x3x3_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x3_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4x4_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4x4_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x4_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5x5_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5x5_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x5_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6x6_OES'
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR')
-- * 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12' (alias: 'Graphics.GL.Tokens.GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR')
--
-- === #InternalFormatPName# InternalFormatPName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NUM_SAMPLE_COUNTS'
-- * 'Graphics.GL.Tokens.GL_SAMPLES'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_SUPPORTED'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_PREFERRED'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_RED_SIZE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_GREEN_SIZE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_BLUE_SIZE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_ALPHA_SIZE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_DEPTH_SIZE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_STENCIL_SIZE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_SHARED_SIZE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_RED_TYPE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_GREEN_TYPE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_BLUE_TYPE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_ALPHA_TYPE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_DEPTH_TYPE'
-- * 'Graphics.GL.Tokens.GL_INTERNALFORMAT_STENCIL_TYPE'
-- * 'Graphics.GL.Tokens.GL_MAX_WIDTH'
-- * 'Graphics.GL.Tokens.GL_MAX_HEIGHT'
-- * 'Graphics.GL.Tokens.GL_MAX_DEPTH'
-- * 'Graphics.GL.Tokens.GL_MAX_LAYERS'
-- * 'Graphics.GL.Tokens.GL_COLOR_COMPONENTS'
-- * 'Graphics.GL.Tokens.GL_COLOR_RENDERABLE'
-- * 'Graphics.GL.Tokens.GL_DEPTH_RENDERABLE'
-- * 'Graphics.GL.Tokens.GL_STENCIL_RENDERABLE'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_RENDERABLE'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_RENDERABLE_LAYERED'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_BLEND'
-- * 'Graphics.GL.Tokens.GL_READ_PIXELS'
-- * 'Graphics.GL.Tokens.GL_READ_PIXELS_FORMAT'
-- * 'Graphics.GL.Tokens.GL_READ_PIXELS_TYPE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_IMAGE_FORMAT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_IMAGE_TYPE'
-- * 'Graphics.GL.Tokens.GL_GET_TEXTURE_IMAGE_FORMAT'
-- * 'Graphics.GL.Tokens.GL_GET_TEXTURE_IMAGE_TYPE'
-- * 'Graphics.GL.Tokens.GL_MIPMAP'
-- * 'Graphics.GL.Tokens.GL_GENERATE_MIPMAP'
-- * 'Graphics.GL.Tokens.GL_AUTO_GENERATE_MIPMAP'
-- * 'Graphics.GL.Tokens.GL_COLOR_ENCODING'
-- * 'Graphics.GL.Tokens.GL_SRGB_READ'
-- * 'Graphics.GL.Tokens.GL_SRGB_WRITE'
-- * 'Graphics.GL.Tokens.GL_FILTER'
-- * 'Graphics.GL.Tokens.GL_VERTEX_TEXTURE'
-- * 'Graphics.GL.Tokens.GL_TESS_CONTROL_TEXTURE'
-- * 'Graphics.GL.Tokens.GL_TESS_EVALUATION_TEXTURE'
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_TEXTURE'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_TEXTURE'
-- * 'Graphics.GL.Tokens.GL_COMPUTE_TEXTURE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_SHADOW'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GATHER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GATHER_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SHADER_IMAGE_LOAD'
-- * 'Graphics.GL.Tokens.GL_SHADER_IMAGE_STORE'
-- * 'Graphics.GL.Tokens.GL_SHADER_IMAGE_ATOMIC'
-- * 'Graphics.GL.Tokens.GL_IMAGE_TEXEL_SIZE'
-- * 'Graphics.GL.Tokens.GL_IMAGE_COMPATIBILITY_CLASS'
-- * 'Graphics.GL.Tokens.GL_IMAGE_PIXEL_FORMAT'
-- * 'Graphics.GL.Tokens.GL_IMAGE_PIXEL_TYPE'
-- * 'Graphics.GL.Tokens.GL_IMAGE_FORMAT_COMPATIBILITY_TYPE'
-- * 'Graphics.GL.Tokens.GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST'
-- * 'Graphics.GL.Tokens.GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST'
-- * 'Graphics.GL.Tokens.GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE'
-- * 'Graphics.GL.Tokens.GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPRESSED'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPRESSED_BLOCK_WIDTH'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPRESSED_BLOCK_SIZE'
-- * 'Graphics.GL.Tokens.GL_CLEAR_BUFFER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_VIEW'
-- * 'Graphics.GL.Tokens.GL_VIEW_COMPATIBILITY_CLASS'
-- * 'Graphics.GL.Tokens.GL_CLEAR_TEXTURE'
--
-- === #InvalidateFramebufferAttachment# InvalidateFramebufferAttachment
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0_NV', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0_OES')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT1' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT1_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT1_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT2' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT2_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT2_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT3' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT3_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT3_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT4' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT4_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT4_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT5' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT5_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT5_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT6' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT6_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT6_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT7' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT7_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT7_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT8' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT8_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT8_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT9' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT9_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT9_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT10' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT10_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT10_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT11' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT11_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT11_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT12' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT12_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT12_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT13' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT13_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT13_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT14' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT14_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT14_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT15' (aliases: 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT15_EXT', 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT15_NV')
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT16'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT17'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT18'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT19'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT20'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT21'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT22'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT23'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT24'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT25'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT26'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT27'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT28'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT29'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT30'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT31'
-- * 'Graphics.GL.Tokens.GL_DEPTH_ATTACHMENT' (aliases: 'Graphics.GL.Tokens.GL_DEPTH_ATTACHMENT_EXT', 'Graphics.GL.Tokens.GL_DEPTH_ATTACHMENT_OES')
-- * 'Graphics.GL.Tokens.GL_DEPTH_STENCIL_ATTACHMENT'
-- * 'Graphics.GL.Tokens.GL_STENCIL' (alias: 'Graphics.GL.Tokens.GL_STENCIL')
-- * 'Graphics.GL.Tokens.GL_STENCIL_ATTACHMENT_EXT' (alias: 'Graphics.GL.Tokens.GL_STENCIL_ATTACHMENT_OES')
-- * 'Graphics.GL.Tokens.GL_COLOR'
-- * 'Graphics.GL.Tokens.GL_DEPTH'
-- * 'Graphics.GL.Tokens.GL_STENCIL' (alias: 'Graphics.GL.Tokens.GL_STENCIL')
--
-- === #LightEnvModeSGIX# LightEnvModeSGIX
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ADD'
-- * 'Graphics.GL.Tokens.GL_MODULATE'
-- * 'Graphics.GL.Tokens.GL_REPLACE'
--
-- === #LightEnvParameterSGIX# LightEnvParameterSGIX
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_LIGHT_ENV_MODE_SGIX'
--
-- === #LightModelColorControl# LightModelColorControl
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SEPARATE_SPECULAR_COLOR' (alias: 'Graphics.GL.Tokens.GL_SEPARATE_SPECULAR_COLOR_EXT')
-- * 'Graphics.GL.Tokens.GL_SINGLE_COLOR' (alias: 'Graphics.GL.Tokens.GL_SINGLE_COLOR_EXT')
--
-- === #LightModelParameter# LightModelParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_LIGHT_MODEL_AMBIENT'
-- * 'Graphics.GL.Tokens.GL_LIGHT_MODEL_COLOR_CONTROL' (alias: 'Graphics.GL.Tokens.GL_LIGHT_MODEL_COLOR_CONTROL_EXT')
-- * 'Graphics.GL.Tokens.GL_LIGHT_MODEL_LOCAL_VIEWER'
-- * 'Graphics.GL.Tokens.GL_LIGHT_MODEL_TWO_SIDE'
--
-- === #LightName# LightName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT0_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT1_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT2_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT3_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT4_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT5_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT6_SGIX'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_LIGHT7_SGIX'
-- * 'Graphics.GL.Tokens.GL_LIGHT0'
-- * 'Graphics.GL.Tokens.GL_LIGHT1'
-- * 'Graphics.GL.Tokens.GL_LIGHT2'
-- * 'Graphics.GL.Tokens.GL_LIGHT3'
-- * 'Graphics.GL.Tokens.GL_LIGHT4'
-- * 'Graphics.GL.Tokens.GL_LIGHT5'
-- * 'Graphics.GL.Tokens.GL_LIGHT6'
-- * 'Graphics.GL.Tokens.GL_LIGHT7'
--
-- === #LightParameter# LightParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_AMBIENT'
-- * 'Graphics.GL.Tokens.GL_CONSTANT_ATTENUATION'
-- * 'Graphics.GL.Tokens.GL_DIFFUSE'
-- * 'Graphics.GL.Tokens.GL_LINEAR_ATTENUATION'
-- * 'Graphics.GL.Tokens.GL_POSITION'
-- * 'Graphics.GL.Tokens.GL_QUADRATIC_ATTENUATION'
-- * 'Graphics.GL.Tokens.GL_SPECULAR'
-- * 'Graphics.GL.Tokens.GL_SPOT_CUTOFF'
-- * 'Graphics.GL.Tokens.GL_SPOT_DIRECTION'
-- * 'Graphics.GL.Tokens.GL_SPOT_EXPONENT'
--
-- === #LightTextureModeEXT# LightTextureModeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_MATERIAL_EXT'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_NORMAL_EXT'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_DEPTH_EXT'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_COLOR_EXT'
--
-- === #LightTexturePNameEXT# LightTexturePNameEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ATTENUATION_EXT'
-- * 'Graphics.GL.Tokens.GL_SHADOW_ATTENUATION_EXT'
--
-- === #ListMode# ListMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COMPILE'
-- * 'Graphics.GL.Tokens.GL_COMPILE_AND_EXECUTE'
--
-- === #ListNameType# ListNameType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_2_BYTES'
-- * 'Graphics.GL.Tokens.GL_3_BYTES'
-- * 'Graphics.GL.Tokens.GL_4_BYTES'
-- * 'Graphics.GL.Tokens.GL_BYTE'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
--
-- === #ListParameterName# ListParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_LIST_PRIORITY_SGIX'
--
-- === #LogicOp# LogicOp
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_AND'
-- * 'Graphics.GL.Tokens.GL_AND_INVERTED'
-- * 'Graphics.GL.Tokens.GL_AND_REVERSE'
-- * 'Graphics.GL.Tokens.GL_CLEAR'
-- * 'Graphics.GL.Tokens.GL_COPY'
-- * 'Graphics.GL.Tokens.GL_COPY_INVERTED'
-- * 'Graphics.GL.Tokens.GL_EQUIV'
-- * 'Graphics.GL.Tokens.GL_INVERT'
-- * 'Graphics.GL.Tokens.GL_NAND'
-- * 'Graphics.GL.Tokens.GL_NOOP'
-- * 'Graphics.GL.Tokens.GL_NOR'
-- * 'Graphics.GL.Tokens.GL_OR'
-- * 'Graphics.GL.Tokens.GL_OR_INVERTED'
-- * 'Graphics.GL.Tokens.GL_OR_REVERSE'
-- * 'Graphics.GL.Tokens.GL_SET'
-- * 'Graphics.GL.Tokens.GL_XOR'
--
-- === #MapAttribParameterNV# MapAttribParameterNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_MAP_ATTRIB_U_ORDER_NV'
-- * 'Graphics.GL.Tokens.GL_MAP_ATTRIB_V_ORDER_NV'
--
-- === #MapBufferAccessMask# MapBufferAccessMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_MAP_COHERENT_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_COHERENT_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_FLUSH_EXPLICIT_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_FLUSH_EXPLICIT_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_INVALIDATE_BUFFER_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_INVALIDATE_BUFFER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_INVALIDATE_RANGE_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_INVALIDATE_RANGE_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_PERSISTENT_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_PERSISTENT_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_READ_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_READ_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_UNSYNCHRONIZED_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_UNSYNCHRONIZED_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_MAP_WRITE_BIT' (alias: 'Graphics.GL.Tokens.GL_MAP_WRITE_BIT_EXT')
--
-- === #MapParameterNV# MapParameterNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_MAP_TESSELLATION_NV'
--
-- === #MapQuery# MapQuery
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COEFF'
-- * 'Graphics.GL.Tokens.GL_ORDER'
-- * 'Graphics.GL.Tokens.GL_DOMAIN'
--
-- === #MapTarget# MapTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_DEFORMATION_SGIX'
-- * 'Graphics.GL.Tokens.GL_MAP1_COLOR_4'
-- * 'Graphics.GL.Tokens.GL_MAP1_INDEX'
-- * 'Graphics.GL.Tokens.GL_MAP1_NORMAL'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_1'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_2'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_3'
-- * 'Graphics.GL.Tokens.GL_MAP1_TEXTURE_COORD_4'
-- * 'Graphics.GL.Tokens.GL_MAP1_VERTEX_3'
-- * 'Graphics.GL.Tokens.GL_MAP1_VERTEX_4'
-- * 'Graphics.GL.Tokens.GL_MAP2_COLOR_4'
-- * 'Graphics.GL.Tokens.GL_MAP2_INDEX'
-- * 'Graphics.GL.Tokens.GL_MAP2_NORMAL'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_1'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_2'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_3'
-- * 'Graphics.GL.Tokens.GL_MAP2_TEXTURE_COORD_4'
-- * 'Graphics.GL.Tokens.GL_MAP2_VERTEX_3'
-- * 'Graphics.GL.Tokens.GL_MAP2_VERTEX_4'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_DEFORMATION_SGIX'
--
-- === #MapTextureFormatINTEL# MapTextureFormatINTEL
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_LAYOUT_DEFAULT_INTEL'
-- * 'Graphics.GL.Tokens.GL_LAYOUT_LINEAR_CPU_CACHED_INTEL'
-- * 'Graphics.GL.Tokens.GL_LAYOUT_LINEAR_INTEL'
--
-- === #MapTypeNV# MapTypeNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
--
-- === #MaterialFace# MaterialFace
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BACK'
-- * 'Graphics.GL.Tokens.GL_FRONT'
-- * 'Graphics.GL.Tokens.GL_FRONT_AND_BACK'
--
-- === #MaterialParameter# MaterialParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_AMBIENT'
-- * 'Graphics.GL.Tokens.GL_AMBIENT_AND_DIFFUSE'
-- * 'Graphics.GL.Tokens.GL_COLOR_INDEXES'
-- * 'Graphics.GL.Tokens.GL_DIFFUSE'
-- * 'Graphics.GL.Tokens.GL_EMISSION'
-- * 'Graphics.GL.Tokens.GL_SHININESS'
-- * 'Graphics.GL.Tokens.GL_SPECULAR'
--
-- === #MatrixIndexPointerTypeARB# MatrixIndexPointerTypeARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
--
-- === #MatrixMode# MatrixMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_MODELVIEW' (alias: 'Graphics.GL.Tokens.GL_MODELVIEW0_EXT')
-- * 'Graphics.GL.Tokens.GL_PROJECTION'
-- * 'Graphics.GL.Tokens.GL_TEXTURE'
--
-- === #MemoryBarrierMask# MemoryBarrierMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALL_BARRIER_BITS' (alias: 'Graphics.GL.Tokens.GL_ALL_BARRIER_BITS_EXT')
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_BUFFER_UPDATE_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_BUFFER_UPDATE_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_COMMAND_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_COMMAND_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_ELEMENT_ARRAY_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_ELEMENT_ARRAY_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_FRAMEBUFFER_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_PIXEL_BUFFER_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_PIXEL_BUFFER_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_QUERY_BUFFER_BARRIER_BIT'
-- * 'Graphics.GL.Tokens.GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_SHADER_STORAGE_BARRIER_BIT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_FETCH_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_FETCH_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_UPDATE_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_UPDATE_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_UNIFORM_BARRIER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT' (alias: 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT_EXT')
--
-- === #MemoryObjectParameterName# MemoryObjectParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DEDICATED_MEMORY_OBJECT_EXT'
-- * 'Graphics.GL.Tokens.GL_PROTECTED_MEMORY_OBJECT_EXT'
--
-- === #MeshMode1# MeshMode1
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_LINE'
-- * 'Graphics.GL.Tokens.GL_POINT'
--
-- === #MeshMode2# MeshMode2
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FILL'
-- * 'Graphics.GL.Tokens.GL_LINE'
-- * 'Graphics.GL.Tokens.GL_POINT'
--
-- === #MinmaxTargetEXT# MinmaxTargetEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_MINMAX' (alias: 'Graphics.GL.Tokens.GL_MINMAX_EXT')
--
-- === #NormalPointerType# NormalPointerType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BYTE'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_SHORT'
--
-- === #ObjectIdentifier# ObjectIdentifier
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BUFFER'
-- * 'Graphics.GL.Tokens.GL_SHADER'
-- * 'Graphics.GL.Tokens.GL_PROGRAM'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ARRAY'
-- * 'Graphics.GL.Tokens.GL_QUERY'
-- * 'Graphics.GL.Tokens.GL_PROGRAM_PIPELINE'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK'
-- * 'Graphics.GL.Tokens.GL_SAMPLER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE'
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER'
-- * 'Graphics.GL.Tokens.GL_FRAMEBUFFER'
--
-- === #ObjectTypeAPPLE# ObjectTypeAPPLE
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DRAW_PIXELS_APPLE'
-- * 'Graphics.GL.Tokens.GL_FENCE_APPLE'
--
-- === #OcclusionQueryEventMaskAMD# OcclusionQueryEventMaskAMD
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_QUERY_DEPTH_PASS_EVENT_BIT_AMD'
-- * 'Graphics.GL.Tokens.GL_QUERY_DEPTH_FAIL_EVENT_BIT_AMD'
-- * 'Graphics.GL.Tokens.GL_QUERY_STENCIL_FAIL_EVENT_BIT_AMD'
-- * 'Graphics.GL.Tokens.GL_QUERY_DEPTH_BOUNDS_FAIL_EVENT_BIT_AMD'
-- * 'Graphics.GL.Tokens.GL_QUERY_ALL_EVENT_BITS_AMD'
--
-- === #OcclusionQueryParameterNameNV# OcclusionQueryParameterNameNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PIXEL_COUNT_NV'
-- * 'Graphics.GL.Tokens.GL_PIXEL_COUNT_AVAILABLE_NV'
--
-- === #PNTrianglesPNameATI# PNTrianglesPNameATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PN_TRIANGLES_POINT_MODE_ATI'
-- * 'Graphics.GL.Tokens.GL_PN_TRIANGLES_NORMAL_MODE_ATI'
-- * 'Graphics.GL.Tokens.GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI'
--
-- === #ParameterRangeEXT# ParameterRangeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NORMALIZED_RANGE_EXT'
-- * 'Graphics.GL.Tokens.GL_FULL_RANGE_EXT'
--
-- === #PatchParameterName# PatchParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PATCH_VERTICES'
-- * 'Graphics.GL.Tokens.GL_PATCH_DEFAULT_OUTER_LEVEL'
-- * 'Graphics.GL.Tokens.GL_PATCH_DEFAULT_INNER_LEVEL'
--
-- === #PathColor# PathColor
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PRIMARY_COLOR'
-- * 'Graphics.GL.Tokens.GL_PRIMARY_COLOR_NV'
-- * 'Graphics.GL.Tokens.GL_SECONDARY_COLOR_NV'
--
-- === #PathColorFormat# PathColorFormat
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NONE'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE'
-- * 'Graphics.GL.Tokens.GL_ALPHA'
-- * 'Graphics.GL.Tokens.GL_INTENSITY'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE_ALPHA'
-- * 'Graphics.GL.Tokens.GL_RGB'
-- * 'Graphics.GL.Tokens.GL_RGBA'
--
-- === #PathCoordType# PathCoordType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CLOSE_PATH_NV'
-- * 'Graphics.GL.Tokens.GL_MOVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_MOVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_LINE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_LINE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_HORIZONTAL_LINE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_HORIZONTAL_LINE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_VERTICAL_LINE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_VERTICAL_LINE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_QUADRATIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_QUADRATIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_CUBIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_CUBIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_SMOOTH_QUADRATIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_SMOOTH_CUBIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_SMALL_CCW_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_SMALL_CCW_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_SMALL_CW_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_SMALL_CW_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_LARGE_CCW_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_LARGE_CCW_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_LARGE_CW_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_LARGE_CW_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_CONIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_CONIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_ROUNDED_RECT_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_ROUNDED_RECT_NV'
-- * 'Graphics.GL.Tokens.GL_ROUNDED_RECT2_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_ROUNDED_RECT2_NV'
-- * 'Graphics.GL.Tokens.GL_ROUNDED_RECT4_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_ROUNDED_RECT4_NV'
-- * 'Graphics.GL.Tokens.GL_ROUNDED_RECT8_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_ROUNDED_RECT8_NV'
-- * 'Graphics.GL.Tokens.GL_RESTART_PATH_NV'
-- * 'Graphics.GL.Tokens.GL_DUP_FIRST_CUBIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_DUP_LAST_CUBIC_CURVE_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RECT_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_RECT_NV'
-- * 'Graphics.GL.Tokens.GL_CIRCULAR_CCW_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_CIRCULAR_CW_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_CIRCULAR_TANGENT_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_ARC_TO_NV'
-- * 'Graphics.GL.Tokens.GL_RELATIVE_ARC_TO_NV'
--
-- === #PathCoverMode# PathCoverMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CONVEX_HULL_NV'
-- * 'Graphics.GL.Tokens.GL_BOUNDING_BOX_NV'
-- * 'Graphics.GL.Tokens.GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_FILL_COVER_MODE_NV'
--
-- === #PathElementType# PathElementType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_UTF8_NV'
-- * 'Graphics.GL.Tokens.GL_UTF16_NV'
--
-- === #PathFillMode# PathFillMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_INVERT'
-- * 'Graphics.GL.Tokens.GL_COUNT_UP_NV'
-- * 'Graphics.GL.Tokens.GL_COUNT_DOWN_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_FILL_MODE_NV'
--
-- === #PathFontStyle# PathFontStyle
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NONE'
-- * 'Graphics.GL.Tokens.GL_BOLD_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_ITALIC_BIT_NV'
--
-- === #PathFontTarget# PathFontTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_STANDARD_FONT_NAME_NV'
-- * 'Graphics.GL.Tokens.GL_SYSTEM_FONT_NAME_NV'
-- * 'Graphics.GL.Tokens.GL_FILE_NAME_NV'
--
-- === #PathGenMode# PathGenMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NONE'
-- * 'Graphics.GL.Tokens.GL_EYE_LINEAR'
-- * 'Graphics.GL.Tokens.GL_OBJECT_LINEAR'
-- * 'Graphics.GL.Tokens.GL_PATH_OBJECT_BOUNDING_BOX_NV'
-- * 'Graphics.GL.Tokens.GL_CONSTANT'
--
-- === #PathHandleMissingGlyphs# PathHandleMissingGlyphs
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SKIP_MISSING_GLYPH_NV'
-- * 'Graphics.GL.Tokens.GL_USE_MISSING_GLYPH_NV'
--
-- === #PathListMode# PathListMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ACCUM_ADJACENT_PAIRS_NV'
-- * 'Graphics.GL.Tokens.GL_ADJACENT_PAIRS_NV'
-- * 'Graphics.GL.Tokens.GL_FIRST_TO_REST_NV'
--
-- === #PathMetricMask# PathMetricMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_GLYPH_WIDTH_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_GLYPH_HEIGHT_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_GLYPH_VERTICAL_BEARING_X_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_GLYPH_HAS_KERNING_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_X_MIN_BOUNDS_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_Y_MIN_BOUNDS_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_X_MAX_BOUNDS_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_Y_MAX_BOUNDS_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_UNITS_PER_EM_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_ASCENDER_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_DESCENDER_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_HEIGHT_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_UNDERLINE_POSITION_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_UNDERLINE_THICKNESS_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_HAS_KERNING_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_FONT_NUM_GLYPH_INDICES_BIT_NV'
--
-- === #PathParameter# PathParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PATH_STROKE_WIDTH_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_INITIAL_END_CAP_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_TERMINAL_END_CAP_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_JOIN_STYLE_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_MITER_LIMIT_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_INITIAL_DASH_CAP_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_TERMINAL_DASH_CAP_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_DASH_OFFSET_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_CLIENT_LENGTH_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_DASH_OFFSET_RESET_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_FILL_MODE_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_FILL_MASK_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_FILL_COVER_MODE_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_STROKE_COVER_MODE_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_STROKE_MASK_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_END_CAPS_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_DASH_CAPS_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_COMMAND_COUNT_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_COORD_COUNT_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_DASH_ARRAY_COUNT_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_COMPUTED_LENGTH_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_OBJECT_BOUNDING_BOX_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_FILL_BOUNDING_BOX_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_STROKE_BOUNDING_BOX_NV'
--
-- === #PathStringFormat# PathStringFormat
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PATH_FORMAT_SVG_NV'
-- * 'Graphics.GL.Tokens.GL_PATH_FORMAT_PS_NV'
--
-- === #PathTransformType# PathTransformType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NONE'
-- * 'Graphics.GL.Tokens.GL_TRANSLATE_X_NV'
-- * 'Graphics.GL.Tokens.GL_TRANSLATE_Y_NV'
-- * 'Graphics.GL.Tokens.GL_TRANSLATE_2D_NV'
-- * 'Graphics.GL.Tokens.GL_TRANSLATE_3D_NV'
-- * 'Graphics.GL.Tokens.GL_AFFINE_2D_NV'
-- * 'Graphics.GL.Tokens.GL_AFFINE_3D_NV'
-- * 'Graphics.GL.Tokens.GL_TRANSPOSE_AFFINE_2D_NV'
-- * 'Graphics.GL.Tokens.GL_TRANSPOSE_AFFINE_3D_NV'
--
-- === #PipelineParameterName# PipelineParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ACTIVE_PROGRAM'
-- * 'Graphics.GL.Tokens.GL_VERTEX_SHADER'
-- * 'Graphics.GL.Tokens.GL_TESS_CONTROL_SHADER'
-- * 'Graphics.GL.Tokens.GL_TESS_EVALUATION_SHADER'
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_SHADER'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_SHADER'
-- * 'Graphics.GL.Tokens.GL_INFO_LOG_LENGTH'
--
-- === #PixelCopyType# PixelCopyType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COLOR' (alias: 'Graphics.GL.Tokens.GL_COLOR_EXT')
-- * 'Graphics.GL.Tokens.GL_DEPTH' (alias: 'Graphics.GL.Tokens.GL_DEPTH_EXT')
-- * 'Graphics.GL.Tokens.GL_STENCIL' (alias: 'Graphics.GL.Tokens.GL_STENCIL_EXT')
--
-- === #PixelDataRangeTargetNV# PixelDataRangeTargetNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_WRITE_PIXEL_DATA_RANGE_NV'
-- * 'Graphics.GL.Tokens.GL_READ_PIXEL_DATA_RANGE_NV'
--
-- === #PixelFormat# PixelFormat
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ABGR_EXT'
-- * 'Graphics.GL.Tokens.GL_ALPHA'
-- * 'Graphics.GL.Tokens.GL_BGR'
-- * 'Graphics.GL.Tokens.GL_BGR_INTEGER'
-- * 'Graphics.GL.Tokens.GL_BGRA'
-- * 'Graphics.GL.Tokens.GL_BGRA_INTEGER'
-- * 'Graphics.GL.Tokens.GL_BLUE'
-- * 'Graphics.GL.Tokens.GL_BLUE_INTEGER'
-- * 'Graphics.GL.Tokens.GL_CMYKA_EXT'
-- * 'Graphics.GL.Tokens.GL_CMYK_EXT'
-- * 'Graphics.GL.Tokens.GL_COLOR_INDEX'
-- * 'Graphics.GL.Tokens.GL_DEPTH_COMPONENT'
-- * 'Graphics.GL.Tokens.GL_DEPTH_STENCIL'
-- * 'Graphics.GL.Tokens.GL_GREEN'
-- * 'Graphics.GL.Tokens.GL_GREEN_INTEGER'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE_ALPHA'
-- * 'Graphics.GL.Tokens.GL_RED' (alias: 'Graphics.GL.Tokens.GL_RED_EXT')
-- * 'Graphics.GL.Tokens.GL_RED_INTEGER'
-- * 'Graphics.GL.Tokens.GL_RG'
-- * 'Graphics.GL.Tokens.GL_RG_INTEGER'
-- * 'Graphics.GL.Tokens.GL_RGB'
-- * 'Graphics.GL.Tokens.GL_RGB_INTEGER'
-- * 'Graphics.GL.Tokens.GL_RGBA'
-- * 'Graphics.GL.Tokens.GL_RGBA_INTEGER'
-- * 'Graphics.GL.Tokens.GL_STENCIL_INDEX'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_YCRCB_422_SGIX'
-- * 'Graphics.GL.Tokens.GL_YCRCB_444_SGIX'
--
-- === #PixelMap# PixelMap
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_A_TO_A'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_B_TO_B'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_G_TO_G'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_A'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_B'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_G'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_I'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_I_TO_R'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_R_TO_R'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAP_S_TO_S'
--
-- === #PixelStoreParameter# PixelStoreParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PACK_ALIGNMENT'
-- * 'Graphics.GL.Tokens.GL_PACK_IMAGE_DEPTH_SGIS'
-- * 'Graphics.GL.Tokens.GL_PACK_IMAGE_HEIGHT' (alias: 'Graphics.GL.Tokens.GL_PACK_IMAGE_HEIGHT_EXT')
-- * 'Graphics.GL.Tokens.GL_PACK_LSB_FIRST'
-- * 'Graphics.GL.Tokens.GL_PACK_RESAMPLE_OML'
-- * 'Graphics.GL.Tokens.GL_PACK_RESAMPLE_SGIX'
-- * 'Graphics.GL.Tokens.GL_PACK_ROW_LENGTH'
-- * 'Graphics.GL.Tokens.GL_PACK_SKIP_IMAGES' (alias: 'Graphics.GL.Tokens.GL_PACK_SKIP_IMAGES_EXT')
-- * 'Graphics.GL.Tokens.GL_PACK_SKIP_PIXELS'
-- * 'Graphics.GL.Tokens.GL_PACK_SKIP_ROWS'
-- * 'Graphics.GL.Tokens.GL_PACK_SKIP_VOLUMES_SGIS'
-- * 'Graphics.GL.Tokens.GL_PACK_SUBSAMPLE_RATE_SGIX'
-- * 'Graphics.GL.Tokens.GL_PACK_SWAP_BYTES'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_CACHE_SIZE_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_GRID_DEPTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_GRID_HEIGHT_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_GRID_WIDTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_HEIGHT_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TILE_WIDTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_UNPACK_ALIGNMENT'
-- * 'Graphics.GL.Tokens.GL_UNPACK_IMAGE_DEPTH_SGIS'
-- * 'Graphics.GL.Tokens.GL_UNPACK_IMAGE_HEIGHT' (alias: 'Graphics.GL.Tokens.GL_UNPACK_IMAGE_HEIGHT_EXT')
-- * 'Graphics.GL.Tokens.GL_UNPACK_LSB_FIRST'
-- * 'Graphics.GL.Tokens.GL_UNPACK_RESAMPLE_OML'
-- * 'Graphics.GL.Tokens.GL_UNPACK_RESAMPLE_SGIX'
-- * 'Graphics.GL.Tokens.GL_UNPACK_ROW_LENGTH' (alias: 'Graphics.GL.Tokens.GL_UNPACK_ROW_LENGTH_EXT')
-- * 'Graphics.GL.Tokens.GL_UNPACK_SKIP_IMAGES' (alias: 'Graphics.GL.Tokens.GL_UNPACK_SKIP_IMAGES_EXT')
-- * 'Graphics.GL.Tokens.GL_UNPACK_SKIP_PIXELS' (alias: 'Graphics.GL.Tokens.GL_UNPACK_SKIP_PIXELS_EXT')
-- * 'Graphics.GL.Tokens.GL_UNPACK_SKIP_ROWS' (alias: 'Graphics.GL.Tokens.GL_UNPACK_SKIP_ROWS_EXT')
-- * 'Graphics.GL.Tokens.GL_UNPACK_SKIP_VOLUMES_SGIS'
-- * 'Graphics.GL.Tokens.GL_UNPACK_SUBSAMPLE_RATE_SGIX'
-- * 'Graphics.GL.Tokens.GL_UNPACK_SWAP_BYTES'
--
-- === #PixelStoreResampleMode# PixelStoreResampleMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_RESAMPLE_DECIMATE_SGIX'
-- * 'Graphics.GL.Tokens.GL_RESAMPLE_REPLICATE_SGIX'
-- * 'Graphics.GL.Tokens.GL_RESAMPLE_ZERO_FILL_SGIX'
--
-- === #PixelStoreSubsampleRate# PixelStoreSubsampleRate
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PIXEL_SUBSAMPLE_2424_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_SUBSAMPLE_4242_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_SUBSAMPLE_4444_SGIX'
--
-- === #PixelTexGenMode# PixelTexGenMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_LUMINANCE'
-- * 'Graphics.GL.Tokens.GL_LUMINANCE_ALPHA'
-- * 'Graphics.GL.Tokens.GL_NONE'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_ALPHA_NO_REPLACE_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_ALPHA_REPLACE_SGIX'
-- * 'Graphics.GL.Tokens.GL_RGB'
-- * 'Graphics.GL.Tokens.GL_RGBA'
--
-- === #PixelTexGenModeSGIX# PixelTexGenModeSGIX
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_Q_CEILING_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_Q_ROUND_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX'
--
-- === #PixelTexGenParameterNameSGIS# PixelTexGenParameterNameSGIS
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS'
-- * 'Graphics.GL.Tokens.GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS'
--
-- === #PixelTransferParameter# PixelTransferParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALPHA_BIAS'
-- * 'Graphics.GL.Tokens.GL_ALPHA_SCALE'
-- * 'Graphics.GL.Tokens.GL_BLUE_BIAS'
-- * 'Graphics.GL.Tokens.GL_BLUE_SCALE'
-- * 'Graphics.GL.Tokens.GL_DEPTH_BIAS'
-- * 'Graphics.GL.Tokens.GL_DEPTH_SCALE'
-- * 'Graphics.GL.Tokens.GL_GREEN_BIAS'
-- * 'Graphics.GL.Tokens.GL_GREEN_SCALE'
-- * 'Graphics.GL.Tokens.GL_INDEX_OFFSET'
-- * 'Graphics.GL.Tokens.GL_INDEX_SHIFT'
-- * 'Graphics.GL.Tokens.GL_MAP_COLOR'
-- * 'Graphics.GL.Tokens.GL_MAP_STENCIL'
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_ALPHA_BIAS' (alias: 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI')
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_ALPHA_SCALE' (alias: 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI')
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_BLUE_BIAS' (alias: 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI')
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_BLUE_SCALE' (alias: 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI')
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_GREEN_BIAS' (alias: 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI')
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_GREEN_SCALE' (alias: 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI')
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_RED_BIAS' (alias: 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_RED_BIAS_SGI')
-- * 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_RED_SCALE' (alias: 'Graphics.GL.Tokens.GL_POST_COLOR_MATRIX_RED_SCALE_SGI')
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_ALPHA_BIAS' (alias: 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_ALPHA_BIAS_EXT')
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_ALPHA_SCALE' (alias: 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_ALPHA_SCALE_EXT')
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_BLUE_BIAS' (alias: 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_BLUE_BIAS_EXT')
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_BLUE_SCALE' (alias: 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_BLUE_SCALE_EXT')
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_GREEN_BIAS' (alias: 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_GREEN_BIAS_EXT')
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_GREEN_SCALE' (alias: 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_GREEN_SCALE_EXT')
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_RED_BIAS' (alias: 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_RED_BIAS_EXT')
-- * 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_RED_SCALE' (alias: 'Graphics.GL.Tokens.GL_POST_CONVOLUTION_RED_SCALE_EXT')
-- * 'Graphics.GL.Tokens.GL_RED_BIAS'
-- * 'Graphics.GL.Tokens.GL_RED_SCALE'
--
-- === #PixelTransformPNameEXT# PixelTransformPNameEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PIXEL_MAG_FILTER_EXT'
-- * 'Graphics.GL.Tokens.GL_PIXEL_MIN_FILTER_EXT'
-- * 'Graphics.GL.Tokens.GL_PIXEL_CUBIC_WEIGHT_EXT'
--
-- === #PixelTransformTargetEXT# PixelTransformTargetEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PIXEL_TRANSFORM_2D_EXT'
--
-- === #PixelType# PixelType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BITMAP'
-- * 'Graphics.GL.Tokens.GL_BYTE'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE_3_3_2' (alias: 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE_3_3_2_EXT')
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_10_10_10_2' (alias: 'Graphics.GL.Tokens.GL_UNSIGNED_INT_10_10_10_2_EXT')
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_8_8_8_8' (alias: 'Graphics.GL.Tokens.GL_UNSIGNED_INT_8_8_8_8_EXT')
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT_4_4_4_4' (alias: 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT_4_4_4_4_EXT')
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT_5_5_5_1' (alias: 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT_5_5_5_1_EXT')
--
-- === #PointParameterNameARB# PointParameterNameARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_POINT_SIZE_MIN_EXT'
-- * 'Graphics.GL.Tokens.GL_POINT_SIZE_MAX_EXT'
-- * 'Graphics.GL.Tokens.GL_POINT_FADE_THRESHOLD_SIZE' (alias: 'Graphics.GL.Tokens.GL_POINT_FADE_THRESHOLD_SIZE_EXT')
--
-- === #PointParameterNameSGIS# PointParameterNameSGIS
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DISTANCE_ATTENUATION_EXT' (aliases: 'Graphics.GL.Tokens.GL_DISTANCE_ATTENUATION_SGIS', 'Graphics.GL.Tokens.GL_POINT_DISTANCE_ATTENUATION', 'Graphics.GL.Tokens.GL_POINT_DISTANCE_ATTENUATION_ARB')
-- * 'Graphics.GL.Tokens.GL_POINT_FADE_THRESHOLD_SIZE' (aliases: 'Graphics.GL.Tokens.GL_POINT_FADE_THRESHOLD_SIZE_ARB', 'Graphics.GL.Tokens.GL_POINT_FADE_THRESHOLD_SIZE_EXT', 'Graphics.GL.Tokens.GL_POINT_FADE_THRESHOLD_SIZE_SGIS')
-- * 'Graphics.GL.Tokens.GL_POINT_SIZE_MAX' (aliases: 'Graphics.GL.Tokens.GL_POINT_SIZE_MAX_ARB', 'Graphics.GL.Tokens.GL_POINT_SIZE_MAX_EXT', 'Graphics.GL.Tokens.GL_POINT_SIZE_MAX_SGIS')
-- * 'Graphics.GL.Tokens.GL_POINT_SIZE_MIN' (aliases: 'Graphics.GL.Tokens.GL_POINT_SIZE_MIN_ARB', 'Graphics.GL.Tokens.GL_POINT_SIZE_MIN_EXT', 'Graphics.GL.Tokens.GL_POINT_SIZE_MIN_SGIS')
--
-- === #PolygonMode# PolygonMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FILL'
-- * 'Graphics.GL.Tokens.GL_LINE'
-- * 'Graphics.GL.Tokens.GL_POINT'
--
-- === #PrecisionType# PrecisionType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_LOW_FLOAT'
-- * 'Graphics.GL.Tokens.GL_MEDIUM_FLOAT'
-- * 'Graphics.GL.Tokens.GL_HIGH_FLOAT'
-- * 'Graphics.GL.Tokens.GL_LOW_INT'
-- * 'Graphics.GL.Tokens.GL_MEDIUM_INT'
-- * 'Graphics.GL.Tokens.GL_HIGH_INT'
--
-- === #PreserveModeATI# PreserveModeATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PRESERVE_ATI'
-- * 'Graphics.GL.Tokens.GL_DISCARD_ATI'
--
-- === #PrimitiveType# PrimitiveType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_LINES'
-- * 'Graphics.GL.Tokens.GL_LINES_ADJACENCY' (aliases: 'Graphics.GL.Tokens.GL_LINES_ADJACENCY_ARB', 'Graphics.GL.Tokens.GL_LINES_ADJACENCY_EXT')
-- * 'Graphics.GL.Tokens.GL_LINE_LOOP'
-- * 'Graphics.GL.Tokens.GL_LINE_STRIP'
-- * 'Graphics.GL.Tokens.GL_LINE_STRIP_ADJACENCY' (aliases: 'Graphics.GL.Tokens.GL_LINE_STRIP_ADJACENCY_ARB', 'Graphics.GL.Tokens.GL_LINE_STRIP_ADJACENCY_EXT')
-- * 'Graphics.GL.Tokens.GL_PATCHES' (alias: 'Graphics.GL.Tokens.GL_PATCHES_EXT')
-- * 'Graphics.GL.Tokens.GL_POINTS'
-- * 'Graphics.GL.Tokens.GL_POLYGON'
-- * 'Graphics.GL.Tokens.GL_QUADS' (alias: 'Graphics.GL.Tokens.GL_QUADS_EXT')
-- * 'Graphics.GL.Tokens.GL_QUAD_STRIP'
-- * 'Graphics.GL.Tokens.GL_TRIANGLES'
-- * 'Graphics.GL.Tokens.GL_TRIANGLES_ADJACENCY' (aliases: 'Graphics.GL.Tokens.GL_TRIANGLES_ADJACENCY_ARB', 'Graphics.GL.Tokens.GL_TRIANGLES_ADJACENCY_EXT')
-- * 'Graphics.GL.Tokens.GL_TRIANGLE_FAN'
-- * 'Graphics.GL.Tokens.GL_TRIANGLE_STRIP'
-- * 'Graphics.GL.Tokens.GL_TRIANGLE_STRIP_ADJACENCY' (aliases: 'Graphics.GL.Tokens.GL_TRIANGLE_STRIP_ADJACENCY_ARB', 'Graphics.GL.Tokens.GL_TRIANGLE_STRIP_ADJACENCY_EXT')
--
-- === #ProgramFormat# ProgramFormat
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PROGRAM_FORMAT_ASCII_ARB'
--
-- === #ProgramInterface# ProgramInterface
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_UNIFORM'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK'
-- * 'Graphics.GL.Tokens.GL_PROGRAM_INPUT'
-- * 'Graphics.GL.Tokens.GL_PROGRAM_OUTPUT'
-- * 'Graphics.GL.Tokens.GL_VERTEX_SUBROUTINE'
-- * 'Graphics.GL.Tokens.GL_TESS_CONTROL_SUBROUTINE'
-- * 'Graphics.GL.Tokens.GL_TESS_EVALUATION_SUBROUTINE'
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_SUBROUTINE'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_SUBROUTINE'
-- * 'Graphics.GL.Tokens.GL_COMPUTE_SUBROUTINE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_SUBROUTINE_UNIFORM'
-- * 'Graphics.GL.Tokens.GL_TESS_CONTROL_SUBROUTINE_UNIFORM'
-- * 'Graphics.GL.Tokens.GL_TESS_EVALUATION_SUBROUTINE_UNIFORM'
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_SUBROUTINE_UNIFORM'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_SUBROUTINE_UNIFORM'
-- * 'Graphics.GL.Tokens.GL_COMPUTE_SUBROUTINE_UNIFORM'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_VARYING'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER'
-- * 'Graphics.GL.Tokens.GL_BUFFER_VARIABLE'
-- * 'Graphics.GL.Tokens.GL_SHADER_STORAGE_BLOCK'
--
-- === #ProgramInterfacePName# ProgramInterfacePName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ACTIVE_RESOURCES'
-- * 'Graphics.GL.Tokens.GL_MAX_NAME_LENGTH'
-- * 'Graphics.GL.Tokens.GL_MAX_NUM_ACTIVE_VARIABLES'
-- * 'Graphics.GL.Tokens.GL_MAX_NUM_COMPATIBLE_SUBROUTINES'
--
-- === #ProgramParameterPName# ProgramParameterPName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PROGRAM_BINARY_RETRIEVABLE_HINT'
-- * 'Graphics.GL.Tokens.GL_PROGRAM_SEPARABLE'
--
-- === #ProgramPropertyARB# ProgramPropertyARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DELETE_STATUS'
-- * 'Graphics.GL.Tokens.GL_LINK_STATUS'
-- * 'Graphics.GL.Tokens.GL_VALIDATE_STATUS'
-- * 'Graphics.GL.Tokens.GL_INFO_LOG_LENGTH'
-- * 'Graphics.GL.Tokens.GL_ATTACHED_SHADERS'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_ATOMIC_COUNTER_BUFFERS'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_ATTRIBUTES'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_UNIFORMS'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_UNIFORM_BLOCKS'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_UNIFORM_MAX_LENGTH'
-- * 'Graphics.GL.Tokens.GL_COMPUTE_WORK_GROUP_SIZE'
-- * 'Graphics.GL.Tokens.GL_PROGRAM_BINARY_LENGTH'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER_MODE'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_VARYINGS'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH'
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_VERTICES_OUT'
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_INPUT_TYPE'
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_OUTPUT_TYPE'
--
-- === #ProgramResourceProperty# ProgramResourceProperty
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ACTIVE_VARIABLES'
-- * 'Graphics.GL.Tokens.GL_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_NUM_ACTIVE_VARIABLES'
-- * 'Graphics.GL.Tokens.GL_ARRAY_SIZE'
-- * 'Graphics.GL.Tokens.GL_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_BLOCK_INDEX'
-- * 'Graphics.GL.Tokens.GL_IS_ROW_MAJOR'
-- * 'Graphics.GL.Tokens.GL_MATRIX_STRIDE'
-- * 'Graphics.GL.Tokens.GL_ATOMIC_COUNTER_BUFFER_INDEX'
-- * 'Graphics.GL.Tokens.GL_BUFFER_DATA_SIZE'
-- * 'Graphics.GL.Tokens.GL_NUM_COMPATIBLE_SUBROUTINES'
-- * 'Graphics.GL.Tokens.GL_COMPATIBLE_SUBROUTINES'
-- * 'Graphics.GL.Tokens.GL_IS_PER_PATCH'
-- * 'Graphics.GL.Tokens.GL_LOCATION'
-- * 'Graphics.GL.Tokens.GL_UNIFORM'
-- * 'Graphics.GL.Tokens.GL_LOCATION_COMPONENT'
-- * 'Graphics.GL.Tokens.GL_LOCATION_INDEX'
-- * 'Graphics.GL.Tokens.GL_NAME_LENGTH'
-- * 'Graphics.GL.Tokens.GL_OFFSET'
-- * 'Graphics.GL.Tokens.GL_REFERENCED_BY_VERTEX_SHADER'
-- * 'Graphics.GL.Tokens.GL_REFERENCED_BY_TESS_CONTROL_SHADER'
-- * 'Graphics.GL.Tokens.GL_REFERENCED_BY_TESS_EVALUATION_SHADER'
-- * 'Graphics.GL.Tokens.GL_REFERENCED_BY_GEOMETRY_SHADER'
-- * 'Graphics.GL.Tokens.GL_REFERENCED_BY_FRAGMENT_SHADER'
-- * 'Graphics.GL.Tokens.GL_REFERENCED_BY_COMPUTE_SHADER'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER_INDEX'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE'
-- * 'Graphics.GL.Tokens.GL_TOP_LEVEL_ARRAY_SIZE'
-- * 'Graphics.GL.Tokens.GL_TOP_LEVEL_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_TYPE'
--
-- === #ProgramStagePName# ProgramStagePName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ACTIVE_SUBROUTINE_UNIFORMS'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_SUBROUTINES'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH'
-- * 'Graphics.GL.Tokens.GL_ACTIVE_SUBROUTINE_MAX_LENGTH'
--
-- === #ProgramStringProperty# ProgramStringProperty
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PROGRAM_STRING_ARB'
--
-- === #ProgramTarget# ProgramTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_PROGRAM_ARB'
-- * 'Graphics.GL.Tokens.GL_VERTEX_PROGRAM_ARB'
-- * 'Graphics.GL.Tokens.GL_TEXT_FRAGMENT_SHADER_ATI'
-- * 'Graphics.GL.Tokens.GL_COMPUTE_PROGRAM_NV'
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_PROGRAM_NV'
-- * 'Graphics.GL.Tokens.GL_TESS_CONTROL_PROGRAM_NV'
-- * 'Graphics.GL.Tokens.GL_TESS_EVALUATION_PROGRAM_NV'
--
-- === #QueryCounterTarget# QueryCounterTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_TIMESTAMP'
--
-- === #QueryObjectParameterName# QueryObjectParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_QUERY_RESULT_AVAILABLE'
-- * 'Graphics.GL.Tokens.GL_QUERY_RESULT'
-- * 'Graphics.GL.Tokens.GL_QUERY_RESULT_NO_WAIT'
-- * 'Graphics.GL.Tokens.GL_QUERY_TARGET'
--
-- === #QueryParameterName# QueryParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CURRENT_QUERY'
-- * 'Graphics.GL.Tokens.GL_QUERY_COUNTER_BITS'
--
-- === #QueryTarget# QueryTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SAMPLES_PASSED'
-- * 'Graphics.GL.Tokens.GL_ANY_SAMPLES_PASSED'
-- * 'Graphics.GL.Tokens.GL_ANY_SAMPLES_PASSED_CONSERVATIVE'
-- * 'Graphics.GL.Tokens.GL_PRIMITIVES_GENERATED'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN'
-- * 'Graphics.GL.Tokens.GL_TIME_ELAPSED'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_OVERFLOW'
-- * 'Graphics.GL.Tokens.GL_VERTICES_SUBMITTED'
-- * 'Graphics.GL.Tokens.GL_PRIMITIVES_SUBMITTED'
-- * 'Graphics.GL.Tokens.GL_VERTEX_SHADER_INVOCATIONS'
--
-- === #ReadBufferMode# ReadBufferMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NONE' (alias: 'Graphics.GL.Tokens.GL_NONE_OES')
-- * 'Graphics.GL.Tokens.GL_AUX0'
-- * 'Graphics.GL.Tokens.GL_AUX1'
-- * 'Graphics.GL.Tokens.GL_AUX2'
-- * 'Graphics.GL.Tokens.GL_AUX3'
-- * 'Graphics.GL.Tokens.GL_BACK'
-- * 'Graphics.GL.Tokens.GL_BACK_LEFT'
-- * 'Graphics.GL.Tokens.GL_BACK_RIGHT'
-- * 'Graphics.GL.Tokens.GL_FRONT'
-- * 'Graphics.GL.Tokens.GL_FRONT_LEFT'
-- * 'Graphics.GL.Tokens.GL_FRONT_RIGHT'
-- * 'Graphics.GL.Tokens.GL_LEFT'
-- * 'Graphics.GL.Tokens.GL_RIGHT'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT0'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT1'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT2'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT3'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT4'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT5'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT6'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT7'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT8'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT9'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT10'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT11'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT12'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT13'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT14'
-- * 'Graphics.GL.Tokens.GL_COLOR_ATTACHMENT15'
--
-- === #RenderbufferParameterName# RenderbufferParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_WIDTH' (aliases: 'Graphics.GL.Tokens.GL_RENDERBUFFER_WIDTH_EXT', 'Graphics.GL.Tokens.GL_RENDERBUFFER_WIDTH_OES')
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_HEIGHT' (aliases: 'Graphics.GL.Tokens.GL_RENDERBUFFER_HEIGHT_EXT', 'Graphics.GL.Tokens.GL_RENDERBUFFER_HEIGHT_OES')
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_INTERNAL_FORMAT' (aliases: 'Graphics.GL.Tokens.GL_RENDERBUFFER_INTERNAL_FORMAT_EXT', 'Graphics.GL.Tokens.GL_RENDERBUFFER_INTERNAL_FORMAT_OES')
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_SAMPLES_IMG'
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_RED_SIZE' (aliases: 'Graphics.GL.Tokens.GL_RENDERBUFFER_RED_SIZE_EXT', 'Graphics.GL.Tokens.GL_RENDERBUFFER_RED_SIZE_OES')
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_GREEN_SIZE' (aliases: 'Graphics.GL.Tokens.GL_RENDERBUFFER_GREEN_SIZE_EXT', 'Graphics.GL.Tokens.GL_RENDERBUFFER_GREEN_SIZE_OES')
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_BLUE_SIZE' (aliases: 'Graphics.GL.Tokens.GL_RENDERBUFFER_BLUE_SIZE_EXT', 'Graphics.GL.Tokens.GL_RENDERBUFFER_BLUE_SIZE_OES')
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_ALPHA_SIZE' (aliases: 'Graphics.GL.Tokens.GL_RENDERBUFFER_ALPHA_SIZE_EXT', 'Graphics.GL.Tokens.GL_RENDERBUFFER_ALPHA_SIZE_OES')
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_DEPTH_SIZE' (aliases: 'Graphics.GL.Tokens.GL_RENDERBUFFER_DEPTH_SIZE_EXT', 'Graphics.GL.Tokens.GL_RENDERBUFFER_DEPTH_SIZE_OES')
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_STENCIL_SIZE' (aliases: 'Graphics.GL.Tokens.GL_RENDERBUFFER_STENCIL_SIZE_EXT', 'Graphics.GL.Tokens.GL_RENDERBUFFER_STENCIL_SIZE_OES')
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_STORAGE_SAMPLES_AMD'
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_COVERAGE_SAMPLES_NV' (aliases: 'Graphics.GL.Tokens.GL_RENDERBUFFER_SAMPLES', 'Graphics.GL.Tokens.GL_RENDERBUFFER_SAMPLES_ANGLE', 'Graphics.GL.Tokens.GL_RENDERBUFFER_SAMPLES_APPLE', 'Graphics.GL.Tokens.GL_RENDERBUFFER_SAMPLES_EXT', 'Graphics.GL.Tokens.GL_RENDERBUFFER_SAMPLES_NV')
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER_COLOR_SAMPLES_NV'
--
-- === #RenderbufferTarget# RenderbufferTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_RENDERBUFFER' (alias: 'Graphics.GL.Tokens.GL_RENDERBUFFER_OES')
--
-- === #RenderingMode# RenderingMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FEEDBACK'
-- * 'Graphics.GL.Tokens.GL_RENDER'
-- * 'Graphics.GL.Tokens.GL_SELECT'
--
-- === #ReplacementCodeTypeSUN# ReplacementCodeTypeSUN
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
--
-- === #SamplePatternEXT# SamplePatternEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_1PASS_EXT'
-- * 'Graphics.GL.Tokens.GL_2PASS_0_EXT'
-- * 'Graphics.GL.Tokens.GL_2PASS_1_EXT'
-- * 'Graphics.GL.Tokens.GL_4PASS_0_EXT'
-- * 'Graphics.GL.Tokens.GL_4PASS_1_EXT'
-- * 'Graphics.GL.Tokens.GL_4PASS_2_EXT'
-- * 'Graphics.GL.Tokens.GL_4PASS_3_EXT'
--
-- === #SamplePatternSGIS# SamplePatternSGIS
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_1PASS_EXT' (alias: 'Graphics.GL.Tokens.GL_1PASS_SGIS')
-- * 'Graphics.GL.Tokens.GL_2PASS_0_EXT' (alias: 'Graphics.GL.Tokens.GL_2PASS_0_SGIS')
-- * 'Graphics.GL.Tokens.GL_2PASS_1_EXT' (alias: 'Graphics.GL.Tokens.GL_2PASS_1_SGIS')
-- * 'Graphics.GL.Tokens.GL_4PASS_0_EXT' (alias: 'Graphics.GL.Tokens.GL_4PASS_0_SGIS')
-- * 'Graphics.GL.Tokens.GL_4PASS_1_EXT' (alias: 'Graphics.GL.Tokens.GL_4PASS_1_SGIS')
-- * 'Graphics.GL.Tokens.GL_4PASS_2_EXT' (alias: 'Graphics.GL.Tokens.GL_4PASS_2_SGIS')
-- * 'Graphics.GL.Tokens.GL_4PASS_3_EXT' (alias: 'Graphics.GL.Tokens.GL_4PASS_3_SGIS')
--
-- === #SamplerParameterF# SamplerParameterF
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BORDER_COLOR'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MIN_LOD'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_LOD'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_ANISOTROPY'
--
-- === #SamplerParameterI# SamplerParameterI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_S'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_T'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_R'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MIN_FILTER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAG_FILTER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPARE_MODE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPARE_FUNC'
--
-- === #ScalarType# ScalarType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
--
-- === #SecondaryColorPointerTypeIBM# SecondaryColorPointerTypeIBM
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SHORT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
--
-- === #SemaphoreParameterName# SemaphoreParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_D3D12_FENCE_VALUE_EXT'
--
-- === #SeparableTargetEXT# SeparableTargetEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SEPARABLE_2D' (alias: 'Graphics.GL.Tokens.GL_SEPARABLE_2D_EXT')
--
-- === #ShaderParameterName# ShaderParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SHADER_TYPE'
-- * 'Graphics.GL.Tokens.GL_DELETE_STATUS'
-- * 'Graphics.GL.Tokens.GL_COMPILE_STATUS'
-- * 'Graphics.GL.Tokens.GL_INFO_LOG_LENGTH'
-- * 'Graphics.GL.Tokens.GL_SHADER_SOURCE_LENGTH'
--
-- === #ShaderType# ShaderType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_COMPUTE_SHADER'
-- * 'Graphics.GL.Tokens.GL_VERTEX_SHADER' (alias: 'Graphics.GL.Tokens.GL_VERTEX_SHADER_ARB')
-- * 'Graphics.GL.Tokens.GL_TESS_CONTROL_SHADER'
-- * 'Graphics.GL.Tokens.GL_TESS_EVALUATION_SHADER'
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_SHADER'
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_SHADER' (alias: 'Graphics.GL.Tokens.GL_FRAGMENT_SHADER_ARB')
--
-- === #ShadingModel# ShadingModel
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FLAT'
-- * 'Graphics.GL.Tokens.GL_SMOOTH'
--
-- === #SpriteParameterNameSGIX# SpriteParameterNameSGIX
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SPRITE_MODE_SGIX'
--
-- === #StencilFaceDirection# StencilFaceDirection
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FRONT'
-- * 'Graphics.GL.Tokens.GL_BACK'
-- * 'Graphics.GL.Tokens.GL_FRONT_AND_BACK'
--
-- === #StencilFunction# StencilFunction
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALWAYS'
-- * 'Graphics.GL.Tokens.GL_EQUAL'
-- * 'Graphics.GL.Tokens.GL_GEQUAL'
-- * 'Graphics.GL.Tokens.GL_GREATER'
-- * 'Graphics.GL.Tokens.GL_LEQUAL'
-- * 'Graphics.GL.Tokens.GL_LESS'
-- * 'Graphics.GL.Tokens.GL_NEVER'
-- * 'Graphics.GL.Tokens.GL_NOTEQUAL'
--
-- === #StencilOp# StencilOp
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DECR'
-- * 'Graphics.GL.Tokens.GL_DECR_WRAP'
-- * 'Graphics.GL.Tokens.GL_INCR'
-- * 'Graphics.GL.Tokens.GL_INCR_WRAP'
-- * 'Graphics.GL.Tokens.GL_INVERT'
-- * 'Graphics.GL.Tokens.GL_KEEP'
-- * 'Graphics.GL.Tokens.GL_REPLACE'
-- * 'Graphics.GL.Tokens.GL_ZERO'
--
-- === #StringName# StringName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_EXTENSIONS'
-- * 'Graphics.GL.Tokens.GL_RENDERER'
-- * 'Graphics.GL.Tokens.GL_VENDOR'
-- * 'Graphics.GL.Tokens.GL_VERSION'
-- * 'Graphics.GL.Tokens.GL_SHADING_LANGUAGE_VERSION'
--
-- === #SubgroupSupportedFeatures# SubgroupSupportedFeatures
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SUBGROUP_FEATURE_BASIC_BIT_KHR'
-- * 'Graphics.GL.Tokens.GL_SUBGROUP_FEATURE_VOTE_BIT_KHR'
-- * 'Graphics.GL.Tokens.GL_SUBGROUP_FEATURE_ARITHMETIC_BIT_KHR'
-- * 'Graphics.GL.Tokens.GL_SUBGROUP_FEATURE_BALLOT_BIT_KHR'
-- * 'Graphics.GL.Tokens.GL_SUBGROUP_FEATURE_SHUFFLE_BIT_KHR'
-- * 'Graphics.GL.Tokens.GL_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT_KHR'
-- * 'Graphics.GL.Tokens.GL_SUBGROUP_FEATURE_CLUSTERED_BIT_KHR'
-- * 'Graphics.GL.Tokens.GL_SUBGROUP_FEATURE_QUAD_BIT_KHR'
-- * 'Graphics.GL.Tokens.GL_SUBGROUP_FEATURE_PARTITIONED_BIT_NV'
--
-- === #SubroutineParameterName# SubroutineParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NUM_COMPATIBLE_SUBROUTINES'
-- * 'Graphics.GL.Tokens.GL_COMPATIBLE_SUBROUTINES'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_SIZE'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_NAME_LENGTH'
--
-- === #SwizzleOpATI# SwizzleOpATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SWIZZLE_STR_ATI'
-- * 'Graphics.GL.Tokens.GL_SWIZZLE_STQ_ATI'
-- * 'Graphics.GL.Tokens.GL_SWIZZLE_STR_DR_ATI'
-- * 'Graphics.GL.Tokens.GL_SWIZZLE_STQ_DQ_ATI'
--
-- === #SyncCondition# SyncCondition
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SYNC_GPU_COMMANDS_COMPLETE'
--
-- === #SyncObjectMask# SyncObjectMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_SYNC_FLUSH_COMMANDS_BIT' (alias: 'Graphics.GL.Tokens.GL_SYNC_FLUSH_COMMANDS_BIT_APPLE')
--
-- === #SyncParameterName# SyncParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_OBJECT_TYPE'
-- * 'Graphics.GL.Tokens.GL_SYNC_STATUS'
-- * 'Graphics.GL.Tokens.GL_SYNC_CONDITION'
-- * 'Graphics.GL.Tokens.GL_SYNC_FLAGS'
--
-- === #SyncStatus# SyncStatus
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ALREADY_SIGNALED'
-- * 'Graphics.GL.Tokens.GL_TIMEOUT_EXPIRED'
-- * 'Graphics.GL.Tokens.GL_CONDITION_SATISFIED'
-- * 'Graphics.GL.Tokens.GL_WAIT_FAILED'
--
-- === #TangentPointerTypeEXT# TangentPointerTypeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BYTE'
-- * 'Graphics.GL.Tokens.GL_SHORT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE' (alias: 'Graphics.GL.Tokens.GL_DOUBLE_EXT')
--
-- === #TexBumpParameterATI# TexBumpParameterATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BUMP_ROT_MATRIX_ATI'
--
-- === #TexCoordPointerType# TexCoordPointerType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_SHORT'
--
-- === #TextureCompareMode# TextureCompareMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_NONE'
-- * 'Graphics.GL.Tokens.GL_COMPARE_REF_TO_TEXTURE' (alias: 'Graphics.GL.Tokens.GL_COMPARE_R_TO_TEXTURE')
--
-- === #TextureCoordName# TextureCoordName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_S'
-- * 'Graphics.GL.Tokens.GL_T'
-- * 'Graphics.GL.Tokens.GL_R'
-- * 'Graphics.GL.Tokens.GL_Q'
--
-- === #TextureEnvMode# TextureEnvMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_ADD'
-- * 'Graphics.GL.Tokens.GL_BLEND'
-- * 'Graphics.GL.Tokens.GL_DECAL'
-- * 'Graphics.GL.Tokens.GL_MODULATE'
-- * 'Graphics.GL.Tokens.GL_REPLACE_EXT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_ENV_BIAS_SGIX'
--
-- === #TextureEnvParameter# TextureEnvParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_TEXTURE_ENV_COLOR'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_ENV_MODE'
--
-- === #TextureEnvTarget# TextureEnvTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_TEXTURE_ENV'
--
-- === #TextureFilterFuncSGIS# TextureFilterFuncSGIS
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FILTER4_SGIS'
--
-- === #TextureFilterSGIS# TextureFilterSGIS
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FILTER4_SGIS'
--
-- === #TextureGenMode# TextureGenMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_EYE_DISTANCE_TO_LINE_SGIS'
-- * 'Graphics.GL.Tokens.GL_EYE_DISTANCE_TO_POINT_SGIS'
-- * 'Graphics.GL.Tokens.GL_EYE_LINEAR'
-- * 'Graphics.GL.Tokens.GL_OBJECT_DISTANCE_TO_LINE_SGIS'
-- * 'Graphics.GL.Tokens.GL_OBJECT_DISTANCE_TO_POINT_SGIS'
-- * 'Graphics.GL.Tokens.GL_OBJECT_LINEAR'
-- * 'Graphics.GL.Tokens.GL_SPHERE_MAP'
--
-- === #TextureGenParameter# TextureGenParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_EYE_LINE_SGIS'
-- * 'Graphics.GL.Tokens.GL_EYE_PLANE'
-- * 'Graphics.GL.Tokens.GL_EYE_POINT_SGIS'
-- * 'Graphics.GL.Tokens.GL_OBJECT_LINE_SGIS'
-- * 'Graphics.GL.Tokens.GL_OBJECT_PLANE'
-- * 'Graphics.GL.Tokens.GL_OBJECT_POINT_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEN_MODE'
--
-- === #TextureLayout# TextureLayout
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_LAYOUT_GENERAL_EXT'
-- * 'Graphics.GL.Tokens.GL_LAYOUT_COLOR_ATTACHMENT_EXT'
-- * 'Graphics.GL.Tokens.GL_LAYOUT_DEPTH_STENCIL_ATTACHMENT_EXT'
-- * 'Graphics.GL.Tokens.GL_LAYOUT_DEPTH_STENCIL_READ_ONLY_EXT'
-- * 'Graphics.GL.Tokens.GL_LAYOUT_SHADER_READ_ONLY_EXT'
-- * 'Graphics.GL.Tokens.GL_LAYOUT_TRANSFER_SRC_EXT'
-- * 'Graphics.GL.Tokens.GL_LAYOUT_TRANSFER_DST_EXT'
-- * 'Graphics.GL.Tokens.GL_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_EXT'
-- * 'Graphics.GL.Tokens.GL_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_EXT'
--
-- === #TextureMagFilter# TextureMagFilter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FILTER4_SGIS'
-- * 'Graphics.GL.Tokens.GL_LINEAR'
-- * 'Graphics.GL.Tokens.GL_LINEAR_DETAIL_ALPHA_SGIS'
-- * 'Graphics.GL.Tokens.GL_LINEAR_DETAIL_COLOR_SGIS'
-- * 'Graphics.GL.Tokens.GL_LINEAR_DETAIL_SGIS'
-- * 'Graphics.GL.Tokens.GL_LINEAR_SHARPEN_ALPHA_SGIS'
-- * 'Graphics.GL.Tokens.GL_LINEAR_SHARPEN_COLOR_SGIS'
-- * 'Graphics.GL.Tokens.GL_LINEAR_SHARPEN_SGIS'
-- * 'Graphics.GL.Tokens.GL_NEAREST'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_Q_CEILING_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_Q_ROUND_SGIX'
--
-- === #TextureMinFilter# TextureMinFilter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FILTER4_SGIS'
-- * 'Graphics.GL.Tokens.GL_LINEAR'
-- * 'Graphics.GL.Tokens.GL_LINEAR_CLIPMAP_LINEAR_SGIX'
-- * 'Graphics.GL.Tokens.GL_LINEAR_CLIPMAP_NEAREST_SGIX'
-- * 'Graphics.GL.Tokens.GL_LINEAR_MIPMAP_LINEAR'
-- * 'Graphics.GL.Tokens.GL_LINEAR_MIPMAP_NEAREST'
-- * 'Graphics.GL.Tokens.GL_NEAREST'
-- * 'Graphics.GL.Tokens.GL_NEAREST_CLIPMAP_LINEAR_SGIX'
-- * 'Graphics.GL.Tokens.GL_NEAREST_CLIPMAP_NEAREST_SGIX'
-- * 'Graphics.GL.Tokens.GL_NEAREST_MIPMAP_LINEAR'
-- * 'Graphics.GL.Tokens.GL_NEAREST_MIPMAP_NEAREST'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_Q_CEILING_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX'
-- * 'Graphics.GL.Tokens.GL_PIXEL_TEX_GEN_Q_ROUND_SGIX'
--
-- === #TextureNormalModeEXT# TextureNormalModeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PERTURB_EXT'
--
-- === #TextureParameterName# TextureParameterName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DETAIL_TEXTURE_LEVEL_SGIS'
-- * 'Graphics.GL.Tokens.GL_DETAIL_TEXTURE_MODE_SGIS'
-- * 'Graphics.GL.Tokens.GL_DUAL_TEXTURE_SELECT_SGIS'
-- * 'Graphics.GL.Tokens.GL_GENERATE_MIPMAP' (alias: 'Graphics.GL.Tokens.GL_GENERATE_MIPMAP_SGIS')
-- * 'Graphics.GL.Tokens.GL_POST_TEXTURE_FILTER_BIAS_SGIX'
-- * 'Graphics.GL.Tokens.GL_POST_TEXTURE_FILTER_SCALE_SGIX'
-- * 'Graphics.GL.Tokens.GL_QUAD_TEXTURE_SELECT_SGIS'
-- * 'Graphics.GL.Tokens.GL_SHADOW_AMBIENT_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BORDER_COLOR' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_BORDER_COLOR_NV')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_CENTER_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_DEPTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_FRAME_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_OFFSET_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPARE_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LOD_BIAS_R_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LOD_BIAS_S_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LOD_BIAS_T_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAG_FILTER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_CLAMP_R_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_CLAMP_S_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_CLAMP_T_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MIN_FILTER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_PRIORITY' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_PRIORITY_EXT')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_Q_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_R' (aliases: 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_R_EXT', 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_R_OES')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_S'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WRAP_T'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BASE_LEVEL' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_BASE_LEVEL_SGIS')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPARE_MODE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPARE_FUNC'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LOD_BIAS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MIN_LOD' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_MIN_LOD_SGIS')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_LOD' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_MAX_LOD_SGIS')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MAX_LEVEL' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_MAX_LEVEL_SGIS')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_SWIZZLE_R'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_SWIZZLE_G'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_SWIZZLE_B'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_SWIZZLE_A'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_SWIZZLE_RGBA'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_TILING_EXT'
-- * 'Graphics.GL.Tokens.GL_DEPTH_STENCIL_TEXTURE_MODE'
-- * 'Graphics.GL.Tokens.GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS'
-- * 'Graphics.GL.Tokens.GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_4DSIZE_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_ALPHA_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BLUE_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_BORDER'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPARE_OPERATOR_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_COMPONENTS' (alias: 'Graphics.GL.Tokens.GL_TEXTURE_INTERNAL_FORMAT')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_DEPTH_EXT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_FILTER4_SIZE_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GEQUAL_R_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_GREEN_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_HEIGHT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_INTENSITY_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LEQUAL_R_SGIX'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_LUMINANCE_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_RED_SIZE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_RESIDENT'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_WIDTH'
--
-- === #TextureStorageMaskAMD# TextureStorageMaskAMD
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_TEXTURE_STORAGE_SPARSE_BIT_AMD'
--
-- === #TextureSwizzle# TextureSwizzle
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_RED'
-- * 'Graphics.GL.Tokens.GL_GREEN'
-- * 'Graphics.GL.Tokens.GL_BLUE'
-- * 'Graphics.GL.Tokens.GL_ALPHA'
-- * 'Graphics.GL.Tokens.GL_ZERO'
-- * 'Graphics.GL.Tokens.GL_ONE'
--
-- === #TextureTarget# TextureTarget
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DETAIL_TEXTURE_2D_SGIS'
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_1D' (alias: 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_1D_EXT')
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_1D_ARRAY' (alias: 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_1D_ARRAY_EXT')
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_2D' (alias: 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_2D_EXT')
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_2D_ARRAY' (alias: 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_2D_ARRAY_EXT')
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_3D' (alias: 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_3D_EXT')
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_4D_SGIS'
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_CUBE_MAP' (aliases: 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_CUBE_MAP_ARB', 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_CUBE_MAP_EXT')
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_CUBE_MAP_ARRAY' (alias: 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB')
-- * 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_RECTANGLE' (aliases: 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_RECTANGLE_ARB', 'Graphics.GL.Tokens.GL_PROXY_TEXTURE_RECTANGLE_NV')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_1D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_2D'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_3D' (aliases: 'Graphics.GL.Tokens.GL_TEXTURE_3D_EXT', 'Graphics.GL.Tokens.GL_TEXTURE_3D_OES')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_4D_SGIS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_RECTANGLE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_POSITIVE_X'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_NEGATIVE_X'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_POSITIVE_Y'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_POSITIVE_Z'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_ARRAY' (aliases: 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_ARRAY_ARB', 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_ARRAY_EXT', 'Graphics.GL.Tokens.GL_TEXTURE_CUBE_MAP_ARRAY_OES')
-- * 'Graphics.GL.Tokens.GL_TEXTURE_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_2D_MULTISAMPLE_ARRAY'
--
-- === #TextureUnit# TextureUnit
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_TEXTURE0'
-- * 'Graphics.GL.Tokens.GL_TEXTURE1'
-- * 'Graphics.GL.Tokens.GL_TEXTURE2'
-- * 'Graphics.GL.Tokens.GL_TEXTURE3'
-- * 'Graphics.GL.Tokens.GL_TEXTURE4'
-- * 'Graphics.GL.Tokens.GL_TEXTURE5'
-- * 'Graphics.GL.Tokens.GL_TEXTURE6'
-- * 'Graphics.GL.Tokens.GL_TEXTURE7'
-- * 'Graphics.GL.Tokens.GL_TEXTURE8'
-- * 'Graphics.GL.Tokens.GL_TEXTURE9'
-- * 'Graphics.GL.Tokens.GL_TEXTURE10'
-- * 'Graphics.GL.Tokens.GL_TEXTURE11'
-- * 'Graphics.GL.Tokens.GL_TEXTURE12'
-- * 'Graphics.GL.Tokens.GL_TEXTURE13'
-- * 'Graphics.GL.Tokens.GL_TEXTURE14'
-- * 'Graphics.GL.Tokens.GL_TEXTURE15'
-- * 'Graphics.GL.Tokens.GL_TEXTURE16'
-- * 'Graphics.GL.Tokens.GL_TEXTURE17'
-- * 'Graphics.GL.Tokens.GL_TEXTURE18'
-- * 'Graphics.GL.Tokens.GL_TEXTURE19'
-- * 'Graphics.GL.Tokens.GL_TEXTURE20'
-- * 'Graphics.GL.Tokens.GL_TEXTURE21'
-- * 'Graphics.GL.Tokens.GL_TEXTURE22'
-- * 'Graphics.GL.Tokens.GL_TEXTURE23'
-- * 'Graphics.GL.Tokens.GL_TEXTURE24'
-- * 'Graphics.GL.Tokens.GL_TEXTURE25'
-- * 'Graphics.GL.Tokens.GL_TEXTURE26'
-- * 'Graphics.GL.Tokens.GL_TEXTURE27'
-- * 'Graphics.GL.Tokens.GL_TEXTURE28'
-- * 'Graphics.GL.Tokens.GL_TEXTURE29'
-- * 'Graphics.GL.Tokens.GL_TEXTURE30'
-- * 'Graphics.GL.Tokens.GL_TEXTURE31'
--
-- === #TextureWrapMode# TextureWrapMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CLAMP'
-- * 'Graphics.GL.Tokens.GL_CLAMP_TO_BORDER' (aliases: 'Graphics.GL.Tokens.GL_CLAMP_TO_BORDER_ARB', 'Graphics.GL.Tokens.GL_CLAMP_TO_BORDER_NV', 'Graphics.GL.Tokens.GL_CLAMP_TO_BORDER_SGIS')
-- * 'Graphics.GL.Tokens.GL_CLAMP_TO_EDGE' (alias: 'Graphics.GL.Tokens.GL_CLAMP_TO_EDGE_SGIS')
-- * 'Graphics.GL.Tokens.GL_REPEAT'
-- * 'Graphics.GL.Tokens.GL_LINEAR_MIPMAP_LINEAR'
-- * 'Graphics.GL.Tokens.GL_MIRRORED_REPEAT'
--
-- === #TransformFeedbackBufferMode# TransformFeedbackBufferMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_INTERLEAVED_ATTRIBS'
-- * 'Graphics.GL.Tokens.GL_SEPARATE_ATTRIBS'
--
-- === #TransformFeedbackPName# TransformFeedbackPName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER_START'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_BUFFER_SIZE'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_PAUSED'
-- * 'Graphics.GL.Tokens.GL_TRANSFORM_FEEDBACK_ACTIVE'
--
-- === #UniformBlockPName# UniformBlockPName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_BINDING'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_DATA_SIZE'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_NAME_LENGTH'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER'
--
-- === #UniformPName# UniformPName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_UNIFORM_TYPE'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_SIZE'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_NAME_LENGTH'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_BLOCK_INDEX'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_OFFSET'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_MATRIX_STRIDE'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_IS_ROW_MAJOR'
-- * 'Graphics.GL.Tokens.GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX'
--
-- === #UniformType# UniformType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
-- * 'Graphics.GL.Tokens.GL_FLOAT_VEC2'
-- * 'Graphics.GL.Tokens.GL_FLOAT_VEC3'
-- * 'Graphics.GL.Tokens.GL_FLOAT_VEC4'
-- * 'Graphics.GL.Tokens.GL_INT_VEC2'
-- * 'Graphics.GL.Tokens.GL_INT_VEC3'
-- * 'Graphics.GL.Tokens.GL_INT_VEC4'
-- * 'Graphics.GL.Tokens.GL_BOOL'
-- * 'Graphics.GL.Tokens.GL_BOOL_VEC2'
-- * 'Graphics.GL.Tokens.GL_BOOL_VEC3'
-- * 'Graphics.GL.Tokens.GL_BOOL_VEC4'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT2'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT3'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT4'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_3D'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_RECT_SHADOW'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT2x3'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT2x4'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT3x2'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT3x4'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT4x2'
-- * 'Graphics.GL.Tokens.GL_FLOAT_MAT4x3'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_1D_ARRAY_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_ARRAY_SHADOW'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE_SHADOW'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_VEC2'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_VEC3'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_VEC4'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_1D'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_3D'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_CUBE'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_1D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_3D'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_CUBE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_RECT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_1D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_BUFFER'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT2'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT3'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT4'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT2x3'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT2x4'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT3x2'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT3x4'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT4x2'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_MAT4x3'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_VEC2'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_VEC3'
-- * 'Graphics.GL.Tokens.GL_DOUBLE_VEC4'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE'
-- * 'Graphics.GL.Tokens.GL_SAMPLER_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY'
--
-- === #UseProgramStageMask# UseProgramStageMask
-- A bitwise combination of several of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VERTEX_SHADER_BIT' (alias: 'Graphics.GL.Tokens.GL_VERTEX_SHADER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_FRAGMENT_SHADER_BIT' (alias: 'Graphics.GL.Tokens.GL_FRAGMENT_SHADER_BIT_EXT')
-- * 'Graphics.GL.Tokens.GL_GEOMETRY_SHADER_BIT' (aliases: 'Graphics.GL.Tokens.GL_GEOMETRY_SHADER_BIT_EXT', 'Graphics.GL.Tokens.GL_GEOMETRY_SHADER_BIT_OES')
-- * 'Graphics.GL.Tokens.GL_TESS_CONTROL_SHADER_BIT' (aliases: 'Graphics.GL.Tokens.GL_TESS_CONTROL_SHADER_BIT_EXT', 'Graphics.GL.Tokens.GL_TESS_CONTROL_SHADER_BIT_OES')
-- * 'Graphics.GL.Tokens.GL_TESS_EVALUATION_SHADER_BIT' (aliases: 'Graphics.GL.Tokens.GL_TESS_EVALUATION_SHADER_BIT_EXT', 'Graphics.GL.Tokens.GL_TESS_EVALUATION_SHADER_BIT_OES')
-- * 'Graphics.GL.Tokens.GL_COMPUTE_SHADER_BIT'
-- * 'Graphics.GL.Tokens.GL_MESH_SHADER_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_TASK_SHADER_BIT_NV'
-- * 'Graphics.GL.Tokens.GL_ALL_SHADER_BITS' (alias: 'Graphics.GL.Tokens.GL_ALL_SHADER_BITS_EXT')
--
-- === #VariantCapEXT# VariantCapEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VARIANT_ARRAY_EXT'
--
-- === #VertexArrayPName# VertexArrayPName
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_ENABLED'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_SIZE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_TYPE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_NORMALIZED'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_INTEGER'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_LONG'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_DIVISOR'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_RELATIVE_OFFSET'
--
-- === #VertexArrayPNameAPPLE# VertexArrayPNameAPPLE
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_STORAGE_CLIENT_APPLE'
-- * 'Graphics.GL.Tokens.GL_STORAGE_CACHED_APPLE'
-- * 'Graphics.GL.Tokens.GL_STORAGE_SHARED_APPLE'
--
-- === #VertexAttribEnum# VertexAttribEnum
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_ENABLED'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_SIZE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_TYPE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_NORMALIZED'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_INTEGER'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_DIVISOR'
-- * 'Graphics.GL.Tokens.GL_CURRENT_VERTEX_ATTRIB'
--
-- === #VertexAttribEnumNV# VertexAttribEnumNV
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_PROGRAM_PARAMETER_NV'
--
-- === #VertexAttribIType# VertexAttribIType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
--
-- === #VertexAttribLType# VertexAttribLType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
--
-- === #VertexAttribPointerPropertyARB# VertexAttribPointerPropertyARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_POINTER' (alias: 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB')
--
-- === #VertexAttribPointerType# VertexAttribPointerType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
-- * 'Graphics.GL.Tokens.GL_HALF_FLOAT'
-- * 'Graphics.GL.Tokens.GL_FIXED'
-- * 'Graphics.GL.Tokens.GL_INT_2_10_10_10_REV'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_2_10_10_10_REV'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_10F_11F_11F_REV'
-- * 'Graphics.GL.Tokens.GL_INT64_ARB' (alias: 'Graphics.GL.Tokens.GL_INT64_NV')
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT64_ARB' (alias: 'Graphics.GL.Tokens.GL_UNSIGNED_INT64_NV')
--
-- === #VertexAttribPropertyARB# VertexAttribPropertyARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_ENABLED'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_SIZE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_STRIDE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_TYPE'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_NORMALIZED'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_INTEGER' (alias: 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_INTEGER_EXT')
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_LONG'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_ARRAY_DIVISOR'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_BINDING'
-- * 'Graphics.GL.Tokens.GL_VERTEX_ATTRIB_RELATIVE_OFFSET'
-- * 'Graphics.GL.Tokens.GL_CURRENT_VERTEX_ATTRIB'
--
-- === #VertexAttribType# VertexAttribType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BYTE'
-- * 'Graphics.GL.Tokens.GL_SHORT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_FIXED'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_HALF_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
-- * 'Graphics.GL.Tokens.GL_INT_2_10_10_10_REV'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_2_10_10_10_REV'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT_10F_11F_11F_REV'
--
-- === #VertexBufferObjectParameter# VertexBufferObjectParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BUFFER_ACCESS'
-- * 'Graphics.GL.Tokens.GL_BUFFER_ACCESS_FLAGS'
-- * 'Graphics.GL.Tokens.GL_BUFFER_IMMUTABLE_STORAGE'
-- * 'Graphics.GL.Tokens.GL_BUFFER_MAPPED'
-- * 'Graphics.GL.Tokens.GL_BUFFER_MAP_LENGTH'
-- * 'Graphics.GL.Tokens.GL_BUFFER_MAP_OFFSET'
-- * 'Graphics.GL.Tokens.GL_BUFFER_SIZE'
-- * 'Graphics.GL.Tokens.GL_BUFFER_STORAGE_FLAGS'
-- * 'Graphics.GL.Tokens.GL_BUFFER_USAGE'
--
-- === #VertexBufferObjectUsage# VertexBufferObjectUsage
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_STREAM_DRAW'
-- * 'Graphics.GL.Tokens.GL_STREAM_READ'
-- * 'Graphics.GL.Tokens.GL_STREAM_COPY'
-- * 'Graphics.GL.Tokens.GL_STATIC_DRAW'
-- * 'Graphics.GL.Tokens.GL_STATIC_READ'
-- * 'Graphics.GL.Tokens.GL_STATIC_COPY'
-- * 'Graphics.GL.Tokens.GL_DYNAMIC_DRAW'
-- * 'Graphics.GL.Tokens.GL_DYNAMIC_READ'
-- * 'Graphics.GL.Tokens.GL_DYNAMIC_COPY'
--
-- === #VertexPointerType# VertexPointerType
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_SHORT'
--
-- === #VertexProvokingMode# VertexProvokingMode
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FIRST_VERTEX_CONVENTION'
-- * 'Graphics.GL.Tokens.GL_LAST_VERTEX_CONVENTION'
--
-- === #VertexShaderCoordOutEXT# VertexShaderCoordOutEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_X_EXT'
-- * 'Graphics.GL.Tokens.GL_Y_EXT'
-- * 'Graphics.GL.Tokens.GL_Z_EXT'
-- * 'Graphics.GL.Tokens.GL_W_EXT'
-- * 'Graphics.GL.Tokens.GL_NEGATIVE_X_EXT'
-- * 'Graphics.GL.Tokens.GL_NEGATIVE_Y_EXT'
-- * 'Graphics.GL.Tokens.GL_NEGATIVE_Z_EXT'
-- * 'Graphics.GL.Tokens.GL_NEGATIVE_W_EXT'
-- * 'Graphics.GL.Tokens.GL_ZERO_EXT'
-- * 'Graphics.GL.Tokens.GL_ONE_EXT'
-- * 'Graphics.GL.Tokens.GL_NEGATIVE_ONE_EXT'
--
-- === #VertexShaderOpEXT# VertexShaderOpEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_OP_INDEX_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_NEGATE_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_DOT3_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_DOT4_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_MUL_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_ADD_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_MADD_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_FRAC_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_MAX_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_MIN_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_SET_GE_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_SET_LT_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_CLAMP_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_FLOOR_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_ROUND_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_EXP_BASE_2_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_LOG_BASE_2_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_POWER_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_RECIP_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_RECIP_SQRT_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_SUB_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_CROSS_PRODUCT_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_MULTIPLY_MATRIX_EXT'
-- * 'Graphics.GL.Tokens.GL_OP_MOV_EXT'
--
-- === #VertexShaderParameterEXT# VertexShaderParameterEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CURRENT_VERTEX_EXT'
-- * 'Graphics.GL.Tokens.GL_MVP_MATRIX_EXT'
--
-- === #VertexShaderStorageTypeEXT# VertexShaderStorageTypeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VARIANT_EXT'
-- * 'Graphics.GL.Tokens.GL_INVARIANT_EXT'
-- * 'Graphics.GL.Tokens.GL_LOCAL_CONSTANT_EXT'
-- * 'Graphics.GL.Tokens.GL_LOCAL_EXT'
--
-- === #VertexShaderTextureUnitParameter# VertexShaderTextureUnitParameter
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_CURRENT_TEXTURE_COORDS'
-- * 'Graphics.GL.Tokens.GL_TEXTURE_MATRIX'
--
-- === #VertexShaderWriteMaskEXT# VertexShaderWriteMaskEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_TRUE'
-- * 'Graphics.GL.Tokens.GL_FALSE'
--
-- === #VertexStreamATI# VertexStreamATI
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_VERTEX_STREAM0_ATI'
-- * 'Graphics.GL.Tokens.GL_VERTEX_STREAM1_ATI'
-- * 'Graphics.GL.Tokens.GL_VERTEX_STREAM2_ATI'
-- * 'Graphics.GL.Tokens.GL_VERTEX_STREAM3_ATI'
-- * 'Graphics.GL.Tokens.GL_VERTEX_STREAM4_ATI'
-- * 'Graphics.GL.Tokens.GL_VERTEX_STREAM5_ATI'
-- * 'Graphics.GL.Tokens.GL_VERTEX_STREAM6_ATI'
-- * 'Graphics.GL.Tokens.GL_VERTEX_STREAM7_ATI'
--
-- === #VertexWeightPointerTypeEXT# VertexWeightPointerTypeEXT
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_FLOAT'
--
-- === #WeightPointerTypeARB# WeightPointerTypeARB
-- One of the following values:
--
-- * 'Graphics.GL.Tokens.GL_BYTE'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_BYTE'
-- * 'Graphics.GL.Tokens.GL_SHORT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_SHORT'
-- * 'Graphics.GL.Tokens.GL_INT'
-- * 'Graphics.GL.Tokens.GL_UNSIGNED_INT'
-- * 'Graphics.GL.Tokens.GL_FLOAT'
-- * 'Graphics.GL.Tokens.GL_DOUBLE'
| haskell-opengl/OpenGLRaw | src/Graphics/GL/Groups.hs | bsd-3-clause | 211,064 | 0 | 3 | 14,509 | 4,488 | 4,485 | 3 | 1 | 0 |
-- Copyright : Daan Leijen (c) 1999, daan@cs.uu.nl
-- HWT Group (c) 2003, haskelldb-users@lists.sourceforge.net
-- License : BSD-style
module Opaleye.Internal.HaskellDB.Sql.Generate (SqlGenerator(..)) where
import Opaleye.Internal.HaskellDB.PrimQuery
import Opaleye.Internal.HaskellDB.Sql
data SqlGenerator = SqlGenerator
{
sqlUpdate :: TableName -> [PrimExpr] -> Assoc -> SqlUpdate,
sqlDelete :: TableName -> [PrimExpr] -> SqlDelete,
sqlInsert :: TableName -> Assoc -> SqlInsert,
sqlExpr :: PrimExpr -> SqlExpr,
sqlLiteral :: Literal -> String,
-- | Turn a string into a quoted string. Quote characters
-- and any escaping are handled by this function.
sqlQuote :: String -> String
}
| silkapp/haskell-opaleye | src/Opaleye/Internal/HaskellDB/Sql/Generate.hs | bsd-3-clause | 792 | 0 | 11 | 197 | 128 | 81 | 47 | 10 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveGeneric #-}
module Market.Types
where
import Control.Applicative
import Control.DeepSeq
import GHC.Generics (Generic)
import Data.Word
import Data.List
import Data.Hashable
-------------------
class (Show coin, RealFrac coin, NFData coin, Hashable coin) => Coin coin where
coinSymbol :: coin -> String
showBare :: coin -> String
readBare :: String -> coin
-------------------
-- Units
newtype Vol a = Vol a deriving (Show, Eq, Ord, Num, Fractional, Real, RealFrac, NFData, Hashable)
newtype Price a = Price a deriving (Show, Eq, Ord, Num, Fractional, Real, RealFrac, NFData, Hashable)
newtype Cost a = Cost a deriving (Show, Eq, Ord, Num, Fractional, Real, RealFrac, NFData, Hashable)
type Revenue = Cost
type Profit = Revenue
type CurrencyVol = Cost
type BTCVol = Vol
type AndOr vol cost = Either vol (Maybe vol, cost)
type TransactionID = Word64
type Timestamp = Word64 -- in posix seconds
newtype Wallet vol = Wallet {address :: String} deriving (Show, Eq)
newtype TransferID = TransferID String deriving (Show, Eq)
-------------------
data OrderSide = Bid | Ask deriving (Show, Eq, Enum, Ord, Generic)
instance NFData OrderSide
instance Hashable OrderSide where
hashWithSalt = hashUsing fromEnum
data Quote p v tail
= Quote
{ side :: OrderSide
, price :: Price p
, volume :: Vol v
, qtail :: tail
} deriving (Show, Eq, Generic)
instance (NFData p, NFData v, NFData t) => NFData (Quote p v t)
data QuoteBook p v qtail counter
= QuoteBook
{ bids::[Quote p v qtail]
, asks::[Quote p v qtail]
, counter :: counter
} deriving (Show, Generic)
instance (NFData p, NFData v, NFData t, NFData c) => NFData (QuoteBook p v t c)
{-------------------------------------------------------------------------------
NOTE: [Order book Comparison]
See QuoteBook type.
1) We do NOT compare 'counter's or timestamps for order book comparisons.
We only look at the book itself.
2) The implementation of the orderbook must allow us to obtain two lists:
- a list of bids in decreasing price order (more specifically, non-increasing)
- a list of asks in increasing price order (more specifically, non-decreasing)
INVARIANT:
** We assume the lists are always ordered as described above **
3) If all orders had distinct prices, comparing two order books would simply
required comparing those lists. However, it is possible for 2 orders to have
exactly the same price and in that case, the order between them is undefined.
So, to compare two orderbooks we need to "normalize" them first. This means
coalescing all volume quote under a single price in a single list element.
----------------------------------------------------------------------------- -}
instance (Eq p, Num p, Eq v, Num v, Eq qtail) => Eq (QuoteBook p v qtail counter) where
x == y = normalizeQuotes (asks x) == normalizeQuotes (asks y) &&
normalizeQuotes (bids x) == normalizeQuotes (bids y)
normalizeQuotes
:: (Eq p, Num p, Num v)
=> [Quote p v tail]
-> [Quote p v ()]
normalizeQuotes xs = fmap coalesce xxs
where
xxs = groupBy (\q q' -> price q == price q') xs
addVols :: (Num price, Num vol) => [Quote price vol tail] -> Vol vol
addVols = sum . fmap volume
getPrice = price . head
getSide = side . head
coalesce qs = Quote{ side = getSide qs
, price = getPrice qs
, volume = addVols qs
, qtail = () }
------------------------ Actions -------------------------
-- Actions that can be performed by trading strategies
{-# DEPRECATED Action "Please use Action type defined at Market.Interface instead" #-}
data Action price vol
= NewLimitOrder
{ acSide :: OrderSide
, acPrice :: Price price
, acVolume :: Vol vol
, acmClientOID :: Maybe OrderID }
| NewMarketOrder
{ acSide :: OrderSide
, acVolAndOrFunds :: AndOr (Vol vol) (Cost price)
, acmClientOID :: Maybe OrderID }
| CancelLimitOrder
{ acClientOID :: OrderID }
| Transfer
{ acVolume :: Vol vol
, acTransferTo :: Wallet vol
}
| PANIC String
deriving (Eq, Show)
type Reasoning = String
newtype StrategyAdvice action = Advice (Reasoning, ZipList action) deriving (Show, Eq)
-- We may need to refine this in the future if we are to combine orders
-- between themselves before issuing them.
instance Semigroup (StrategyAdvice action) where
Advice (l, ZipList ls) <> Advice (r, ZipList rs) = Advice (l <> r, ZipList (ls <> rs))
instance Monoid (StrategyAdvice action) where
mempty = Advice ("", ZipList [])
-- FIX ME! should just derive these, but...
instance Functor StrategyAdvice where
fmap f (Advice (r, as)) = Advice (r, fmap f as)
instance Applicative StrategyAdvice where
pure a = Advice (mempty, pure a)
liftA2 f (Advice (l, as)) (Advice (r, bs)) = Advice (l <> r, liftA2 f as bs)
------------------------- Orders -------------------------
data OrderID = OID { hw :: Word64, lw :: Word64 } deriving (Show, Eq, Ord, Generic)
instance Hashable OrderID
-- | This is a *partition* of the OrderStatus space
data OrderStatus = Active | Inactive | ActivePartiallyExecuted deriving (Show, Eq, Enum, Ord)
----------
data Confirmation price vol
= Conf
{ orderID :: OrderID
, mTimestamp :: Maybe Timestamp -- The Exchanges should, but don't always give me this
-- orders that have been confirmed may be partially executed.
, mExecuted :: Maybe (Price price, Vol vol) -- (average price, vol), nothing means "don't know"
, mOrderStatus :: Maybe OrderStatus -- Nothing means "don't know"
}
deriving (Show, Eq, Ord)
data Order price vol ack
= LimitOrder
{ oSide :: OrderSide
, limitPrice :: Price price
, limitVolume :: Vol vol -- volume requested when order was placed
, aConfirmation :: ack
}
| MarketOrder
{ oSide :: OrderSide
, volumeAndOrFunds :: AndOr (Vol vol) (Cost price)
, aConfirmation :: ack
}
deriving (Show, Eq, Ord)
newtype OrderPlacement p v = Placement {toOrder :: Order p v (Confirmation p v)} deriving (Show, Eq)
newtype OrderCancellation = Cancellation {toOID :: OrderID} deriving (Show, Eq)
newtype OrderFill p v = OrderFilled {toFills :: [Fill p v]} deriving (Show, Eq)
-- unifying wrapper for trading events
data TradingE p v q c
= TP {toPlace :: OrderPlacement p v}
| TC {toCancel :: OrderCancellation }
| TF {toFill :: OrderFill p v}
| TB {toBook :: QuoteBook p v q c}
deriving (Show, Eq)
-------------------
type FillID = Word64
{- The representation was failing in tests because of extreme values represented as Double
I require 5dp precision in comparisons of the fee, but the fee is calculated based on the
volume and price and for very large volumes (fees in the 1E8 range) the mantissa is just not big enough!
-}
data Fill price vol
= Fill
{ fillID :: FillID -- must be unique
, mFillTime :: Maybe Timestamp -- 'Maybe' here is *kinda* wrong, but the exchanges may not return
-- the exact time the fill happened and instead just tell me it did.
-- So, even for a fill that has a FillID, I may not have this information.
-- Ideally, all fills should have a timestamp for when they were executed.
, fillVolume :: Vol vol -- the volume executed in this fill
, fillPrice :: Price price -- the price that was actually used
, fillFee :: Cost price -- the fee charged for this transaction in dollars (or appropriate currency)
, orderId :: OrderID
}
deriving (Show, Ord, Eq)
| dimitri-xyz/market-model | src/Market/Types.hs | bsd-3-clause | 8,048 | 0 | 11 | 2,099 | 1,876 | 1,054 | 822 | 130 | 1 |
{-|
Module: Numeric.Morpheus.Statistics
Description: Statistics Functions
Copyright: (c) Alexander Ignatyev, 2017
License: BSD-3
Stability: experimental
Portability: POSIX
-}
module Numeric.Morpheus.Statistics
(
mean
, stddev_m
, stddev
, columnMean
, rowMean
, columnStddev_m
, rowStddev_m
)
where
import Numeric.Morpheus.Utils(morpheusLayout)
import Numeric.LinearAlgebra
import Numeric.LinearAlgebra.Devel
import System.IO.Unsafe(unsafePerformIO)
import Foreign.C.Types
import Foreign.Ptr(Ptr)
import Foreign.Storable
{- morpheus_mean -}
foreign import ccall unsafe "morpheus_mean"
c_morpheus_mean :: CInt -> Ptr R -> IO R
-- | Calculates mean (average).
mean :: Vector R -> R
mean x = unsafePerformIO $ do
apply x id c_morpheus_mean
{- morpheus_stddev_m -}
foreign import ccall unsafe "morpheus_stddev"
c_morpheus_stddev_m :: R -> CInt -> Ptr R -> IO R
-- | Calculates sample standard deviation using given mean value.
stddev_m :: R -> Vector R -> R
stddev_m m x = unsafePerformIO $ do
apply x id (c_morpheus_stddev_m m)
{- morpheus_stddev -}
foreign import ccall unsafe "morpheus_stddev"
c_morpheus_stddev :: CInt -> Ptr R -> IO R
-- | Calculates sample standard deviation.
stddev :: Vector R -> R
stddev x = unsafePerformIO $ do
apply x id c_morpheus_stddev
{- morpheus_column_mean -}
foreign import ccall unsafe "morpheus_column_mean"
c_morpheus_column_mean :: CInt -> CInt -> CInt -> Ptr R -> Ptr R -> IO ()
call_morpheus_column_mean :: CInt -> CInt -> CInt -> CInt -> Ptr R
-> CInt -> Ptr R
-> IO ()
call_morpheus_column_mean rows cols xRow xCol mat _ means = do
let layout = morpheusLayout xCol cols
c_morpheus_column_mean layout rows cols mat means
-- | Calculates mean (average) for every column.
columnMean :: Matrix R -> Vector R
columnMean m = unsafePerformIO $ do
v <- createVector (cols m)
apply m (apply v id) call_morpheus_column_mean
return v
{- morpheus_row_mean -}
foreign import ccall unsafe "morpheus_row_mean"
c_morpheus_row_mean :: CInt -> CInt -> CInt -> Ptr R -> Ptr R -> IO ()
call_morpheus_row_mean :: CInt -> CInt -> CInt -> CInt -> Ptr R
-> CInt -> Ptr R
-> IO ()
call_morpheus_row_mean rows cols xRow xCol mat _ means = do
let layout = morpheusLayout xCol cols
c_morpheus_row_mean layout rows cols mat means
-- | Calculates mean (average) for every row.
rowMean :: Matrix R -> Vector R
rowMean m = unsafePerformIO $ do
v <- createVector (rows m)
apply m (apply v id) call_morpheus_row_mean
return v
{- morpheus_column_stddev_m -}
foreign import ccall unsafe "morpheus_column_stddev_m"
c_morpheus_column_stddev_m :: CInt -> CInt -> CInt -> Ptr R -> Ptr R -> Ptr R -> IO ()
call_morpheus_column_stddev_m :: CInt -> Ptr R
-> CInt -> CInt -> CInt -> CInt -> Ptr R
-> CInt -> Ptr R
-> IO ()
call_morpheus_column_stddev_m _ means rows cols xRow xCol mat _ stddevs = do
let layout = morpheusLayout xCol cols
c_morpheus_column_stddev_m layout rows cols means mat stddevs
-- | Calculates sample standard deviation using given mean value for every column.
columnStddev_m :: Vector R -> Matrix R -> Vector R
columnStddev_m means m = unsafePerformIO $ do
v <- createVector (cols m)
apply means (apply m (apply v id)) call_morpheus_column_stddev_m
return v
{- morpheus_row_stddev_m -}
foreign import ccall unsafe "morpheus_row_stddev_m"
c_morpheus_row_stddev_m :: CInt -> CInt -> CInt -> Ptr R -> Ptr R -> Ptr R -> IO ()
call_morpheus_row_stddev_m :: CInt -> Ptr R
-> CInt -> CInt -> CInt -> CInt -> Ptr R
-> CInt -> Ptr R
-> IO ()
call_morpheus_row_stddev_m _ means rows cols xRow xCol mat _ stddevs = do
let layout = morpheusLayout xCol cols
c_morpheus_row_stddev_m layout rows cols means mat stddevs
-- | Calculates sample standard deviation using given mean value for every row.
rowStddev_m :: Vector R -> Matrix R -> Vector R
rowStddev_m means m = unsafePerformIO $ do
v <- createVector (rows m)
apply means (apply m (apply v id)) call_morpheus_row_stddev_m
return v
| Alexander-Ignatyev/morpheus | hmatrix-morpheus/src/Numeric/Morpheus/Statistics.hs | bsd-3-clause | 4,310 | 0 | 15 | 1,038 | 1,199 | 585 | 614 | 85 | 1 |
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE QuasiQuotes #-}
-- |
-- Module : Data.Array.Accelerate.C.Acc
-- Copyright : [2009..2013] Manuel M T Chakravarty, Gabriele Keller, Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Manuel M T Chakravarty <chak@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- This module implements the C code generation for Accelerate array computations.
--
module Data.Array.Accelerate.C.Acc (
OpenAccWithName(..), OpenExpWithName, OpenFunWithName,
accToC
) where
-- libraries
import Control.Monad.Trans.State
import Data.List
import qualified
Language.C as C
import Language.C.Quote.C as C
-- accelerate
import Data.Array.Accelerate.Array.Sugar
import Data.Array.Accelerate.AST hiding (Val(..), prj)
import Data.Array.Accelerate.Tuple
-- friends
import Data.Array.Accelerate.C.Base
import Data.Array.Accelerate.C.Exp
import Data.Array.Accelerate.C.Type
-- Code generation monad
-- ---------------------
-- State to generate unique names and collect generated definitions.
--
data CGstate = CGstate
{ unique :: Int
, cdefs :: [C.Definition] -- opposite order in which they are stored
}
initialCGstate :: CGstate
initialCGstate = CGstate 0 []
-- State monad encapsulating the code generator state.
--
type CG = State CGstate
-- Produce a new unique name on the basis of the given base name.
--
newName :: Name -> CG Name
newName name = state $ \s@(CGstate {unique = unique}) -> (name ++ show unique, s {unique = unique + 1})
-- Store a C definition.
--
define :: C.Definition -> CG ()
define cdef = state $ \s -> ((), s {cdefs = cdef : cdefs s})
-- Generating C code from Accelerate computations
-- ----------------------------------------------
-- Name each array computation with the name of the C function that implements it.
--
data OpenAccWithName aenv t = OpenAccWithName Name (PreOpenAcc OpenAccWithName aenv t)
-- Compile an open Accelerate computation into C definitions and an open Accelerate computation, where each array
-- computation has been named. The name of an array computation may correspond to the name of the C definition
-- implementing that array computation.
--
-- The computation may contain free array variables according to the array variable environment passed as a first argument.
--
accToC :: forall arrs aenv. Arrays arrs => Env aenv -> OpenAcc aenv arrs -> ([C.Definition], OpenAccWithName aenv arrs)
accToC aenv acc
= let (acc', state) = runState (accCG aenv acc) initialCGstate
in
(cdefs state, acc')
-- Compile an open Accelerate computation in the 'CG' monad.
--
accCG :: forall arrs aenv. Arrays arrs => Env aenv -> OpenAcc aenv arrs -> CG (OpenAccWithName aenv arrs)
accCG aenv' (OpenAcc (Alet bnd body))
= do
{ bnd' <- accCG aenv' bnd
; body' <- accCG aenv_bnd body
; return $ OpenAccWithName noName (Alet bnd' body')
}
where
(_, aenv_bnd) = aenv' `pushAccEnv` bnd
accCG _aenv' (OpenAcc (Avar ix))
= return $ OpenAccWithName noName (Avar ix)
accCG _aenv' (OpenAcc (Use arr))
= return $ OpenAccWithName noName (Use arr)
accCG aenv' acc@(OpenAcc (Generate sh f))
= do
{ funName <- newName cFunName
; define $
[cedecl|
void $id:funName ( $params:(cresParams ++ cenvParams) )
{
const typename HsWord64 size = $exp:(csize (accDim acc) accSh);
for (typename HsWord64 i = 0; i < size; i++)
{
$items:assigns
}
}
|]
; return $ OpenAccWithName funName (Generate (adaptExp sh) (adaptFun f))
}
where
cresTys = accTypeToC acc
cresNames = accNames "res" [length cresTys - 1]
cresParams = [ [cparam| $ty:t $id:name |] | (t, name) <- zip cresTys cresNames]
--
cenvParams = aenvToCargs aenv'
--
shName = head cresNames
accSh = [cexp| * $id:shName |]
(bnds, es) = fun1ToC aenv' f
assigns = [ [citem| const $ty:argTy $id:arg = $exp:d; |]
| (d, (argTy, arg)) <- zip (fromIndexWithShape shName "i" (length bnds)) bnds
]
++
[ [citem| $id:resArr [i] = $exp:e; |]
| (resArr, e) <- zip (tail cresNames) es -- head is the shape variable
]
accCG aenv' acc@(OpenAcc (Map f arr))
= do
{ arr' <- accCG aenv' arr
; funName <- newName cFunName
; define $
[cedecl|
void $id:funName ( $params:(cresParams ++ cenvParams ++ cargParams) )
{
const typename HsWord64 size = $exp:(csize (accDim arr) argSh);
for (typename HsWord64 i = 0; i < size; i++)
{
$items:assigns
}
}
|]
; return $ OpenAccWithName funName (Map (adaptFun f) arr')
}
where
cresTys = accTypeToC acc
cresNames = accNames "res" [length cresTys - 1]
cresParams = [ [cparam| $ty:t $id:name |] | (t, name) <- zip cresTys cresNames]
--
cenvParams = aenvToCargs aenv'
--
cargTys = accTypeToC arr
cargNames = accNames "arg" [length cargTys - 1]
cargParams = [ [cparam| $ty:t $id:name |] | (t, name) <- zip cargTys cargNames]
--
argSh = [cexp| * $id:(head cargNames) |]
(bnds, es) = fun1ToC aenv' f
assigns = [ [citem| {
const $ty:argTy $id:arg = $id:argArr [i];
$id:resArr [i] = $exp:e;
} |]
| (resArr, argArr, (argTy, arg), e) <- zip4 (tail cresNames) (tail cargNames) -- head is the shape variable
bnds es
]
accCG aenv' acc@(OpenAcc (ZipWith f arr1 arr2))
= do
{ arr1' <- accCG aenv' arr1
; arr2' <- accCG aenv' arr2
; funName <- newName cFunName
; define $
[cedecl|
void $id:funName ( $params:(cresParams ++ cenvParams ++ carg1Params ++ carg2Params) )
{
const typename HsWord64 size = $exp:(csize (accDim acc) accSh);
for (typename HsWord64 i = 0; i < size; i++)
{
$items:assigns
}
}
|]
; return $ OpenAccWithName funName (ZipWith (adaptFun f) arr1' arr2')
}
where
cresTys = accTypeToC acc
cresNames = accNames "res" [length cresTys - 1]
cresParams = [ [cparam| $ty:t $id:name |] | (t, name) <- zip cresTys cresNames]
--
cenvParams = aenvToCargs aenv'
--
carg1Tys = accTypeToC arr1
carg1Names = accNames "arg1_" [length carg1Tys - 1]
carg1Params = [ [cparam| $ty:t $id:name |] | (t, name) <- zip carg1Tys carg1Names]
--
carg2Tys = accTypeToC arr2
carg2Names = accNames "arg2_" [length carg2Tys - 1]
carg2Params = [ [cparam| $ty:t $id:name |] | (t, name) <- zip carg2Tys carg2Names]
--
accSh = [cexp| * $id:(head cresNames) |]
(bnds1,
bnds2,
es) = fun2ToC aenv' f
assigns = [ [citem| {
const $ty:arg1Ty $id:arg1 = $id:arg1Arr [i];
const $ty:arg2Ty $id:arg2 = $id:arg2Arr [i];
$id:resArr [i] = $exp:e;
} |]
| (resArr, arg1Arr, arg2Arr, (arg1Ty, arg1), (arg2Ty, arg2), e)
<- zip6 (tail cresNames) (tail carg1Names) (tail carg2Names) -- head is the shape variable
bnds1 bnds2 es
]
accCG aenv' acc@(OpenAcc (Fold f (z::PreExp OpenAcc aenv e) arr))
= do
{ arr' <- accCG aenv' arr
; funName <- newName cFunName
; define $
-- We iterate over the result shape, and then, execute a separate loop over the innermost dimension of the
-- argument, to fold along that dimension per element of the result.
[cedecl|
void $id:funName ( $params:(cresParams ++ cenvParams ++ cargParams) )
{
const typename HsWord64 resSize = $exp:(csize (accDim acc) accSh);
const typename Ix innerSize = $exp:argSh . a0;
for (typename HsWord64 i = 0; i < resSize; i++)
{
$items:initAccum
for (typename Ix j = 0; j < innerSize; j++)
{
$items:assignsAccum
}
$items:assignsRes
}
}
|]
; return $ OpenAccWithName funName (Fold (adaptFun f) (adaptExp z) arr')
}
where
cresTys = accTypeToC acc
cresNames = accNames "res" [length cresTys - 1]
cresParams = [ [cparam| $ty:t $id:name |] | (t, name) <- zip cresTys cresNames]
--
cenvParams = aenvToCargs aenv'
--
cargTys = accTypeToC arr
cargNames = accNames "arg" [length cargTys - 1]
cargParams = [ [cparam| $ty:t $id:name |] | (t, name) <- zip cargTys cargNames]
--
argSh = [cexp| * $id:(head cargNames) |]
accSh = [cexp| * $id:(head cresNames) |]
(bnds1,
bnds2,
es) = fun2ToC aenv' f
assignsAccum = [ [citem| {
const $ty:argTy $id:arg = $id:argArr [i * innerSize + j];
const $ty:accumTy $id:accum = $id:accumName;
$id:accumName = $exp:e;
} |]
| (resArr, argArr, (argTy, arg), (accumTy, accum), accumName, e)
<- zip6 (tail cresNames) (tail cargNames) -- head is the shape variable
bnds1 bnds2 accumNames es
]
assignsRes = [ [citem| $id:resArr [i] = $id:accumName; |]
| (resArr, accumName) <- zip (tail cresNames) -- head is the shape variable
accumNames
]
--
zTys = tupleTypeToC (eltType (undefined::e))
accumNames = expNames "accum" (length zTys)
zes = openExpToC EmptyEnv aenv' z
initAccum = [ [citem| $ty:zTy $id:accName = $exp:ze; |]
| (zTy, accName, ze) <- zip3 zTys accumNames zes
]
accCG aenv' acc@(OpenAcc (Backpermute sh p arr))
= do
{ arr' <- accCG aenv' arr
; funName <- newName cFunName
; define $
[cedecl|
void $id:funName ( $params:(cresParams ++ cenvParams ++ cargParams) )
{
const typename HsWord64 size = $exp:(csize (accDim acc) accSh);
for (typename HsWord64 i = 0; i < size; i++)
{
$items:assigns
}
}
|]
; return $ OpenAccWithName funName (Backpermute (adaptExp sh) (adaptFun p) arr')
}
where
cresTys = accTypeToC acc
cresNames = accNames "res" [length cresTys - 1]
cresParams = [ [cparam| $ty:t $id:name |] | (t, name) <- zip cresTys cresNames]
--
cenvParams = aenvToCargs aenv'
--
cargTys = accTypeToC arr
cargNames = accNames "arg" [length cargTys - 1]
cargParams = [ [cparam| $ty:t $id:name |] | (t, name) <- zip cargTys cargNames]
--
shName = head cargNames
sh'Name = head cresNames
accSh = [cexp| * $id:shName |]
(bnds, es) = fun1ToC aenv' p
assigns = [ [citem| const $ty:argTy $id:arg = $exp:d; |]
| (d, (argTy, arg)) <- zip (fromIndexWithShape sh'Name "i" (length bnds)) bnds
]
++
[ [citem| {
typename HsWord64 j = $exp:(toIndexWithShape shName es);
$id:resArr [i] = $id:argArr [j];
} |]
| (resArr, argArr) <- zip (tail cresNames) (tail cargNames) -- head is the shape variable
]
accCG _ _ = error "D.A.A.C.Acc: unimplemented array operation"
type OpenExpWithName = PreOpenExp OpenAccWithName
-- Ensure that embedded array computations are of the named variety.
--
adaptExp :: OpenExp env aenv t -> OpenExpWithName env aenv t
adaptExp e
= case e of
Var ix -> Var ix
Let bnd body -> Let (adaptExp bnd) (adaptExp body)
Const c -> Const c
PrimConst c -> PrimConst c
PrimApp f x -> PrimApp f (adaptExp x)
Tuple t -> Tuple (adaptTuple t)
Prj ix e -> Prj ix (adaptExp e)
Cond p t e -> Cond (adaptExp p) (adaptExp t) (adaptExp e)
Iterate n f x -> Iterate (adaptExp n) (adaptExp f) (adaptExp x)
IndexAny -> IndexAny
IndexNil -> IndexNil
IndexCons sh sz -> IndexCons (adaptExp sh) (adaptExp sz)
IndexHead sh -> IndexHead (adaptExp sh)
IndexTail sh -> IndexTail (adaptExp sh)
IndexSlice ix slix sh -> IndexSlice ix (adaptExp slix) (adaptExp sh)
IndexFull ix slix sl -> IndexFull ix (adaptExp slix) (adaptExp sl)
ToIndex sh ix -> ToIndex (adaptExp sh) (adaptExp ix)
FromIndex sh ix -> FromIndex (adaptExp sh) (adaptExp ix)
Intersect sh1 sh2 -> Intersect (adaptExp sh1) (adaptExp sh2)
ShapeSize sh -> ShapeSize (adaptExp sh)
Shape acc -> Shape (adaptAcc acc)
Index acc ix -> Index (adaptAcc acc) (adaptExp ix)
LinearIndex acc ix -> LinearIndex (adaptAcc acc) (adaptExp ix)
Foreign fo f x -> Foreign fo (adaptFun f) (adaptExp x)
where
adaptTuple :: Tuple (OpenExp env aenv) t -> Tuple (OpenExpWithName env aenv) t
adaptTuple NilTup = NilTup
adaptTuple (t `SnocTup` e) = adaptTuple t `SnocTup` adaptExp e
-- No need to traverse embedded arrays as they must have been lifted out as part of sharing recovery.
adaptAcc (OpenAcc (Avar ix)) = OpenAccWithName noName (Avar ix)
adaptAcc _ = error "D.A.A.C: unlifted array computation"
type OpenFunWithName = PreOpenFun OpenAccWithName
adaptFun :: OpenFun env aenv t -> OpenFunWithName env aenv t
adaptFun (Body e) = Body $ adaptExp e
adaptFun (Lam f) = Lam $ adaptFun f
-- Environments
-- ------------
aenvToCargs :: Env aenv -> [C.Param]
aenvToCargs EmptyEnv = []
aenvToCargs (aenv `PushEnv` bnds) = aenvToCargs aenv ++ [ [cparam| $ty:t $id:name |] | (t, name) <- bnds]
-- Shapes
-- ------
-- Determine the dimensionality of an array.
--
arrDim :: forall sh e. (Shape sh, Elt e) => Array sh e -> Int
arrDim _dummy = dim (undefined::sh)
accDim :: forall sh e aenv. (Shape sh, Elt e) => OpenAcc aenv (Array sh e) -> Int
accDim _dummy = arrDim (undefined::Array sh e)
| AccelerateHS/accelerate-c | Data/Array/Accelerate/C/Acc.hs | bsd-3-clause | 14,846 | 0 | 15 | 4,879 | 3,515 | 1,922 | 1,593 | 206 | 26 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Mistral.Parser.LexerCore where
import Mistral.Utils.Source
import Mistral.Utils.Panic ( panic )
import Mistral.Utils.PP
import Data.Bits (shiftR,(.&.))
import Data.Char (ord)
import Data.Word (Word8)
import qualified Data.Text.Lazy as L
-- Lexer Monad -----------------------------------------------------------------
-- | Lexer state.
data AlexInput = AlexInput { aiPos :: !Position
, aiSource :: Range -> Source
, aiChar :: !Char
, aiBytes :: [Word8]
, aiInput :: L.Text
}
initialInput :: Maybe FilePath -> L.Text -> AlexInput
initialInput mb bytes =
AlexInput { aiPos = Position 1 1 0
, aiSource = maybe NoSource Source mb
, aiChar = '\n'
, aiBytes = []
, aiInput = bytes
}
-- | Decode a single character, and dump its octets into the byte buffer.
fillBuffer :: AlexInput -> Maybe AlexInput
fillBuffer ai = do
(c,rest) <- L.uncons (aiInput ai)
return ai { aiPos = moveChar c (aiPos ai)
, aiBytes = utf8Encode c
, aiChar = c
, aiInput = rest
}
-- | Encode a Haskell String to a list of Word8 values, in UTF8 format.
utf8Encode :: Char -> [Word8]
utf8Encode = map fromIntegral . go . ord
where
go oc
| oc <= 0x7f = [oc]
| oc <= 0x7ff = [ 0xc0 + (oc `shiftR` 6)
, 0x80 + oc .&. 0x3f
]
| oc <= 0xffff = [ 0xe0 + ( oc `shiftR` 12)
, 0x80 + ((oc `shiftR` 6) .&. 0x3f)
, 0x80 + oc .&. 0x3f
]
| otherwise = [ 0xf0 + ( oc `shiftR` 18)
, 0x80 + ((oc `shiftR` 12) .&. 0x3f)
, 0x80 + ((oc `shiftR` 6) .&. 0x3f)
, 0x80 + oc .&. 0x3f
]
-- Alex Compatibility ----------------------------------------------------------
alexInputPrevChar :: AlexInput -> Char
alexInputPrevChar = aiChar
alexGetByte :: AlexInput -> Maybe (Word8,AlexInput)
alexGetByte ai = case aiBytes ai of
b : rest -> return (b, ai { aiBytes = rest })
_ -> alexGetByte =<< fillBuffer ai
-- Lexer Actions ---------------------------------------------------------------
data LexState = Normal
| InString String
type Action = Source -> L.Text -> LexState -> (Maybe Lexeme, LexState)
-- | Emit a token.
emit :: Token -> Action
emit tok src _chunk sc = (Just (tok `at` src), sc)
-- | Skip the current input.
skip :: Action
skip _ _ sc = (Nothing,sc)
number :: ReadS Integer -> Int -> Action
number parse base src chunk sc = (Just (tok `at` src), sc)
where
tok = case parse (L.unpack chunk) of
[ (i,_) ] -> Num base i
_ -> Err LexicalError
-- | Generate an identifier token.
mkIdent :: Action
mkIdent src chunk sc = (Just (Ident (L.unpack chunk) `at` src), sc)
mkOperator :: Action
mkOperator src chunk sc = (Just (Operator (L.unpack chunk) `at` src), sc)
mkCIdent :: Action
mkCIdent src chunk sc = (Just (CIdent (L.unpack chunk) `at` src), sc)
-- | Generate an atom token.
mkAtom :: Action
mkAtom src chunk sc = (Just (Atom (tail (L.unpack chunk)) `at` src), sc)
-- | Generate a dot literal (ex: IP address)
mkDotLit :: Action
mkDotLit src chunk sc = (Just (DotT (L.unpack chunk) `at` src), sc)
-- | Generate a colon+dot literal (ex: time with fractional seconds)
mkColonDotLit :: Action
mkColonDotLit src chunk sc = (Just (ColonDotT (L.unpack chunk) `at` src), sc)
-- | Generate a colon+slash literal (ex: IPv6 netmask)
mkColonSlashLit :: Action
mkColonSlashLit src chunk sc = (Just (ColonSlashT (L.unpack chunk) `at` src), sc)
-- | Generate a dot+slash literal (ex: IPv4 netmask)
mkDotSlashLit :: Action
mkDotSlashLit src chunk sc = (Just (DotSlashT (L.unpack chunk) `at` src), sc)
-- | Generate an atom token.
mkColonLit :: Action
mkColonLit src chunk sc = (Just (ColonT (L.unpack chunk) `at` src), sc)
-- String Literals -------------------------------------------------------------
startString :: Action
startString _ _ _ = (Nothing, InString "")
-- | Discard the chunk, and use this string instead.
litString :: String -> Action
litString lit _ _ (InString str) = (Nothing, InString (str ++ lit))
litString _ _ _ _ = panic "Mistral.Parser.Lexer"
[ "Expected string literal state" ]
addString :: Action
addString _ chunk (InString str) = (Nothing, InString (str ++ L.unpack chunk))
addString _ _ _ = panic "Mistral.Parser.Lexer"
[ "Expected string literal state" ]
mkString :: Action
mkString src _ (InString str) = (Just (String str `at` src), Normal)
mkString _ _ _ = panic "Mistral.Parser.Lexer"
[ "Expected string literal state" ]
-- Tokens ----------------------------------------------------------------------
type Lexeme = Located Token
data Token = KW Keyword
| Num Int Integer -- ^ Base and value
| ColonDotT String
| ColonSlashT String
| DotSlashT String
| DotT String
| ColonT String
| String String
| Ident String
| Operator String
| CIdent String
| Atom String
| Sym Symbol
| Virt Virt
| Eof
| Err TokenError
deriving (Show,Eq)
-- | Virtual symbols inserted for layout purposes.
data Virt = VOpen
| VClose
| VSep
deriving (Show,Eq)
data Keyword = KW_topology
| KW_node
| KW_taskSet
| KW_precept
| KW_if
| KW_then
| KW_else
| KW_module
| KW_where
| KW_let
| KW_in
| KW_import
| KW_schedule
| KW_using
| KW_actions
| KW_transitions
| KW_task
| KW_on
| KW_after
| KW_start
| KW_end
| KW_timeout
| KW_at
| KW_match
| KW_tagged
| KW_data
| KW_case
| KW_of
deriving (Show,Eq)
data Symbol = BracketL
| BracketR
| Semi
| SemiClose
| Pipe
| PipePipe
| AndAnd
| BraceL
| BraceR
| ParenL
| ParenR
| Assign
| Comma
| Dot
| Colon
| Hash
| FArrowR
| ArrowR
| ArrowL
| ArrowBi
| DColon
| Plus
| Minus
| Mult
| Div
| Bang
| Lambda
| AtSym
| Question
| Underscore
deriving (Show,Eq)
data TokenError = LexicalError
deriving (Show,Eq)
descTokenError :: TokenError -> String
descTokenError e = case e of
LexicalError -> "lexical error"
instance PP Token where
ppr t = case t of
KW kw -> pp kw
Num _ v -> integer v
ColonDotT s -> text s
ColonSlashT s -> text s
DotSlashT s -> text s
DotT s -> text s
ColonT s -> text s
String s -> text s
Ident s -> text s
Operator s -> parens (text s)
CIdent s -> text s
Atom s -> char '#' <> text s
Sym sym -> pp sym
Virt v -> pp v
Eof -> text "EOF"
Err e -> pp e
instance PP Virt where
ppr v = case v of
VOpen -> text "v{"
VClose -> text "v}"
VSep -> text "v;"
instance PP Keyword where
ppr kw = case kw of
KW_topology -> text "topology"
KW_node -> text "node"
KW_taskSet -> text "taskSet"
KW_precept -> text "precept"
KW_if -> text "if"
KW_then -> text "then"
KW_else -> text "else"
KW_module -> text "module"
KW_where -> text "where"
KW_let -> text "let"
KW_in -> text "in"
KW_schedule -> text "schedule"
KW_using -> text "using"
KW_actions -> text "actions"
KW_transitions -> text "transitions"
KW_task -> text "task"
KW_on -> text "on"
KW_after -> text "after"
KW_start -> text "start"
KW_end -> text "end"
KW_timeout -> text "timeout"
KW_at -> text "at"
KW_import -> text "import"
KW_match -> text "match"
KW_tagged -> text "tagged"
KW_data -> text "data"
KW_case -> text "case"
KW_of -> text "of"
instance PP Symbol where
ppr sym = case sym of
BracketL -> char '['
BracketR -> char ']'
Semi -> char ';'
SemiClose -> text ";}"
BraceL -> char '{'
BraceR -> char '}'
ParenL -> char '('
ParenR -> char ')'
Assign -> char '='
Comma -> char ','
Dot -> char '.'
Colon -> char ':'
Hash -> char '#'
FArrowR -> text "=>"
ArrowR -> text "->"
ArrowL -> text "<-"
ArrowBi -> text "<->"
DColon -> text "::"
Plus -> char '+'
Minus -> char '-'
Mult -> char '*'
Div -> char '/'
Bang -> char '!'
Lambda -> char '\\'
AtSym -> char '@'
Question -> char '?'
Underscore -> char '_'
Pipe -> char '|'
PipePipe -> text "||"
AndAnd -> text "&&"
instance PP TokenError where
ppr _ = text "lexical error"
| GaloisInc/mistral | src/Mistral/Parser/LexerCore.hs | bsd-3-clause | 9,992 | 0 | 14 | 3,899 | 2,710 | 1,433 | 1,277 | 269 | 2 |
module Main(main) where
import Library1
main = exported `seq` print 1
| ndmitchell/weeder | test/foo/src/Main.hs | bsd-3-clause | 73 | 0 | 6 | 14 | 26 | 16 | 10 | 3 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Monadic type operations
This module contains monadic operations over types that contain
mutable type variables.
-}
{-# LANGUAGE CPP, TupleSections, MultiWayIf #-}
{-# OPTIONS_GHC -Wno-incomplete-record-updates #-}
module TcMType (
TcTyVar, TcKind, TcType, TcTauType, TcThetaType, TcTyVarSet,
--------------------------------
-- Creating new mutable type variables
newFlexiTyVar,
newNamedFlexiTyVar,
newFlexiTyVarTy, -- Kind -> TcM TcType
newFlexiTyVarTys, -- Int -> Kind -> TcM [TcType]
newOpenFlexiTyVarTy, newOpenTypeKind,
newMetaKindVar, newMetaKindVars, newMetaTyVarTyAtLevel,
cloneMetaTyVar,
newFmvTyVar, newFskTyVar,
readMetaTyVar, writeMetaTyVar, writeMetaTyVarRef,
newMetaDetails, isFilledMetaTyVar_maybe, isFilledMetaTyVar, isUnfilledMetaTyVar,
--------------------------------
-- Expected types
ExpType(..), ExpSigmaType, ExpRhoType,
mkCheckExpType,
newInferExpType, newInferExpTypeInst, newInferExpTypeNoInst,
readExpType, readExpType_maybe,
expTypeToType, checkingExpType_maybe, checkingExpType,
tauifyExpType, inferResultToType,
--------------------------------
-- Creating new evidence variables
newEvVar, newEvVars, newDict,
newWanted, newWanteds, newHoleCt, cloneWanted, cloneWC,
emitWanted, emitWantedEq, emitWantedEvVar, emitWantedEvVars,
emitDerivedEqs,
newTcEvBinds, newNoTcEvBinds, addTcEvBind,
newCoercionHole, fillCoercionHole, isFilledCoercionHole,
unpackCoercionHole, unpackCoercionHole_maybe,
checkCoercionHole,
newImplication,
--------------------------------
-- Instantiation
newMetaTyVars, newMetaTyVarX, newMetaTyVarsX,
newMetaTyVarTyVars, newMetaTyVarTyVarX,
newTyVarTyVar, cloneTyVarTyVar,
newPatSigTyVar, newSkolemTyVar, newWildCardX,
tcInstType,
tcInstSkolTyVars, tcInstSkolTyVarsX, tcInstSkolTyVarsAt,
tcSkolDFunType, tcSuperSkolTyVars, tcInstSuperSkolTyVarsX,
freshenTyVarBndrs, freshenCoVarBndrsX,
--------------------------------
-- Zonking and tidying
zonkTidyTcType, zonkTidyTcTypes, zonkTidyOrigin,
tidyEvVar, tidyCt, tidySkolemInfo,
zonkTcTyVar, zonkTcTyVars,
zonkTcTyVarToTyVar, zonkTyVarTyVarPairs,
zonkTyCoVarsAndFV, zonkTcTypeAndFV, zonkDTyCoVarSetAndFV,
zonkTyCoVarsAndFVList,
candidateQTyVarsOfType, candidateQTyVarsOfKind,
candidateQTyVarsOfTypes, candidateQTyVarsOfKinds,
CandidatesQTvs(..), delCandidates, candidateKindVars, partitionCandidates,
zonkAndSkolemise, skolemiseQuantifiedTyVar,
defaultTyVar, quantifyTyVars, isQuantifiableTv,
zonkTcType, zonkTcTypes, zonkCo,
zonkTyCoVarKind,
zonkEvVar, zonkWC, zonkSimples,
zonkId, zonkCoVar,
zonkCt, zonkSkolemInfo,
skolemiseUnboundMetaTyVar,
------------------------------
-- Levity polymorphism
ensureNotLevPoly, checkForLevPoly, checkForLevPolyX, formatLevPolyErr
) where
#include "HsVersions.h"
-- friends:
import GhcPrelude
import TyCoRep
import TyCoPpr
import TcType
import Type
import TyCon
import Coercion
import Class
import Var
import Predicate
import TcOrigin
-- others:
import TcRnMonad -- TcType, amongst others
import Constraint
import TcEvidence
import Id
import Name
import VarSet
import TysWiredIn
import TysPrim
import VarEnv
import NameEnv
import PrelNames
import Util
import Outputable
import FastString
import Bag
import Pair
import UniqSet
import DynFlags
import qualified GHC.LanguageExtensions as LangExt
import BasicTypes ( TypeOrKind(..) )
import Control.Monad
import Maybes
import Data.List ( mapAccumL )
import Control.Arrow ( second )
import qualified Data.Semigroup as Semi
{-
************************************************************************
* *
Kind variables
* *
************************************************************************
-}
mkKindName :: Unique -> Name
mkKindName unique = mkSystemName unique kind_var_occ
kind_var_occ :: OccName -- Just one for all MetaKindVars
-- They may be jiggled by tidying
kind_var_occ = mkOccName tvName "k"
newMetaKindVar :: TcM TcKind
newMetaKindVar
= do { details <- newMetaDetails TauTv
; uniq <- newUnique
; let kv = mkTcTyVar (mkKindName uniq) liftedTypeKind details
; traceTc "newMetaKindVar" (ppr kv)
; return (mkTyVarTy kv) }
newMetaKindVars :: Int -> TcM [TcKind]
newMetaKindVars n = replicateM n newMetaKindVar
{-
************************************************************************
* *
Evidence variables; range over constraints we can abstract over
* *
************************************************************************
-}
newEvVars :: TcThetaType -> TcM [EvVar]
newEvVars theta = mapM newEvVar theta
--------------
newEvVar :: TcPredType -> TcRnIf gbl lcl EvVar
-- Creates new *rigid* variables for predicates
newEvVar ty = do { name <- newSysName (predTypeOccName ty)
; return (mkLocalIdOrCoVar name ty) }
newWanted :: CtOrigin -> Maybe TypeOrKind -> PredType -> TcM CtEvidence
-- Deals with both equality and non-equality predicates
newWanted orig t_or_k pty
= do loc <- getCtLocM orig t_or_k
d <- if isEqPrimPred pty then HoleDest <$> newCoercionHole pty
else EvVarDest <$> newEvVar pty
return $ CtWanted { ctev_dest = d
, ctev_pred = pty
, ctev_nosh = WDeriv
, ctev_loc = loc }
newWanteds :: CtOrigin -> ThetaType -> TcM [CtEvidence]
newWanteds orig = mapM (newWanted orig Nothing)
-- | Create a new 'CHoleCan' 'Ct'.
newHoleCt :: HoleSort -> Id -> Type -> TcM Ct
newHoleCt hole ev ty = do
loc <- getCtLocM HoleOrigin Nothing
pure $ CHoleCan { cc_ev = CtWanted { ctev_pred = ty
, ctev_dest = EvVarDest ev
, ctev_nosh = WDeriv
, ctev_loc = loc }
, cc_occ = getOccName ev
, cc_hole = hole }
----------------------------------------------
-- Cloning constraints
----------------------------------------------
cloneWanted :: Ct -> TcM Ct
cloneWanted ct
| ev@(CtWanted { ctev_dest = HoleDest {}, ctev_pred = pty }) <- ctEvidence ct
= do { co_hole <- newCoercionHole pty
; return (mkNonCanonical (ev { ctev_dest = HoleDest co_hole })) }
| otherwise
= return ct
cloneWC :: WantedConstraints -> TcM WantedConstraints
-- Clone all the evidence bindings in
-- a) the ic_bind field of any implications
-- b) the CoercionHoles of any wanted constraints
-- so that solving the WantedConstraints will not have any visible side
-- effect, /except/ from causing unifications
cloneWC wc@(WC { wc_simple = simples, wc_impl = implics })
= do { simples' <- mapBagM cloneWanted simples
; implics' <- mapBagM cloneImplication implics
; return (wc { wc_simple = simples', wc_impl = implics' }) }
cloneImplication :: Implication -> TcM Implication
cloneImplication implic@(Implic { ic_binds = binds, ic_wanted = inner_wanted })
= do { binds' <- cloneEvBindsVar binds
; inner_wanted' <- cloneWC inner_wanted
; return (implic { ic_binds = binds', ic_wanted = inner_wanted' }) }
----------------------------------------------
-- Emitting constraints
----------------------------------------------
-- | Emits a new Wanted. Deals with both equalities and non-equalities.
emitWanted :: CtOrigin -> TcPredType -> TcM EvTerm
emitWanted origin pty
= do { ev <- newWanted origin Nothing pty
; emitSimple $ mkNonCanonical ev
; return $ ctEvTerm ev }
emitDerivedEqs :: CtOrigin -> [(TcType,TcType)] -> TcM ()
-- Emit some new derived nominal equalities
emitDerivedEqs origin pairs
| null pairs
= return ()
| otherwise
= do { loc <- getCtLocM origin Nothing
; emitSimples (listToBag (map (mk_one loc) pairs)) }
where
mk_one loc (ty1, ty2)
= mkNonCanonical $
CtDerived { ctev_pred = mkPrimEqPred ty1 ty2
, ctev_loc = loc }
-- | Emits a new equality constraint
emitWantedEq :: CtOrigin -> TypeOrKind -> Role -> TcType -> TcType -> TcM Coercion
emitWantedEq origin t_or_k role ty1 ty2
= do { hole <- newCoercionHole pty
; loc <- getCtLocM origin (Just t_or_k)
; emitSimple $ mkNonCanonical $
CtWanted { ctev_pred = pty, ctev_dest = HoleDest hole
, ctev_nosh = WDeriv, ctev_loc = loc }
; return (HoleCo hole) }
where
pty = mkPrimEqPredRole role ty1 ty2
-- | Creates a new EvVar and immediately emits it as a Wanted.
-- No equality predicates here.
emitWantedEvVar :: CtOrigin -> TcPredType -> TcM EvVar
emitWantedEvVar origin ty
= do { new_cv <- newEvVar ty
; loc <- getCtLocM origin Nothing
; let ctev = CtWanted { ctev_dest = EvVarDest new_cv
, ctev_pred = ty
, ctev_nosh = WDeriv
, ctev_loc = loc }
; emitSimple $ mkNonCanonical ctev
; return new_cv }
emitWantedEvVars :: CtOrigin -> [TcPredType] -> TcM [EvVar]
emitWantedEvVars orig = mapM (emitWantedEvVar orig)
newDict :: Class -> [TcType] -> TcM DictId
newDict cls tys
= do { name <- newSysName (mkDictOcc (getOccName cls))
; return (mkLocalId name (mkClassPred cls tys)) }
predTypeOccName :: PredType -> OccName
predTypeOccName ty = case classifyPredType ty of
ClassPred cls _ -> mkDictOcc (getOccName cls)
EqPred {} -> mkVarOccFS (fsLit "co")
IrredPred {} -> mkVarOccFS (fsLit "irred")
ForAllPred {} -> mkVarOccFS (fsLit "df")
-- | Create a new 'Implication' with as many sensible defaults for its fields
-- as possible. Note that the 'ic_tclvl', 'ic_binds', and 'ic_info' fields do
-- /not/ have sensible defaults, so they are initialized with lazy thunks that
-- will 'panic' if forced, so one should take care to initialize these fields
-- after creation.
--
-- This is monadic to look up the 'TcLclEnv', which is used to initialize
-- 'ic_env', and to set the -Winaccessible-code flag. See
-- Note [Avoid -Winaccessible-code when deriving] in TcInstDcls.
newImplication :: TcM Implication
newImplication
= do env <- getLclEnv
warn_inaccessible <- woptM Opt_WarnInaccessibleCode
return (implicationPrototype { ic_env = env
, ic_warn_inaccessible = warn_inaccessible })
{-
************************************************************************
* *
Coercion holes
* *
************************************************************************
-}
newCoercionHole :: TcPredType -> TcM CoercionHole
newCoercionHole pred_ty
= do { co_var <- newEvVar pred_ty
; traceTc "New coercion hole:" (ppr co_var)
; ref <- newMutVar Nothing
; return $ CoercionHole { ch_co_var = co_var, ch_ref = ref } }
-- | Put a value in a coercion hole
fillCoercionHole :: CoercionHole -> Coercion -> TcM ()
fillCoercionHole (CoercionHole { ch_ref = ref, ch_co_var = cv }) co
= do {
#if defined(DEBUG)
; cts <- readTcRef ref
; whenIsJust cts $ \old_co ->
pprPanic "Filling a filled coercion hole" (ppr cv $$ ppr co $$ ppr old_co)
#endif
; traceTc "Filling coercion hole" (ppr cv <+> text ":=" <+> ppr co)
; writeTcRef ref (Just co) }
-- | Is a coercion hole filled in?
isFilledCoercionHole :: CoercionHole -> TcM Bool
isFilledCoercionHole (CoercionHole { ch_ref = ref }) = isJust <$> readTcRef ref
-- | Retrieve the contents of a coercion hole. Panics if the hole
-- is unfilled
unpackCoercionHole :: CoercionHole -> TcM Coercion
unpackCoercionHole hole
= do { contents <- unpackCoercionHole_maybe hole
; case contents of
Just co -> return co
Nothing -> pprPanic "Unfilled coercion hole" (ppr hole) }
-- | Retrieve the contents of a coercion hole, if it is filled
unpackCoercionHole_maybe :: CoercionHole -> TcM (Maybe Coercion)
unpackCoercionHole_maybe (CoercionHole { ch_ref = ref }) = readTcRef ref
-- | Check that a coercion is appropriate for filling a hole. (The hole
-- itself is needed only for printing.
-- Always returns the checked coercion, but this return value is necessary
-- so that the input coercion is forced only when the output is forced.
checkCoercionHole :: CoVar -> Coercion -> TcM Coercion
checkCoercionHole cv co
| debugIsOn
= do { cv_ty <- zonkTcType (varType cv)
-- co is already zonked, but cv might not be
; return $
ASSERT2( ok cv_ty
, (text "Bad coercion hole" <+>
ppr cv <> colon <+> vcat [ ppr t1, ppr t2, ppr role
, ppr cv_ty ]) )
co }
| otherwise
= return co
where
(Pair t1 t2, role) = coercionKindRole co
ok cv_ty | EqPred cv_rel cv_t1 cv_t2 <- classifyPredType cv_ty
= t1 `eqType` cv_t1
&& t2 `eqType` cv_t2
&& role == eqRelRole cv_rel
| otherwise
= False
{-
************************************************************************
*
Expected types
*
************************************************************************
Note [ExpType]
~~~~~~~~~~~~~~
An ExpType is used as the "expected type" when type-checking an expression.
An ExpType can hold a "hole" that can be filled in by the type-checker.
This allows us to have one tcExpr that works in both checking mode and
synthesis mode (that is, bidirectional type-checking). Previously, this
was achieved by using ordinary unification variables, but we don't need
or want that generality. (For example, #11397 was caused by doing the
wrong thing with unification variables.) Instead, we observe that these
holes should
1. never be nested
2. never appear as the type of a variable
3. be used linearly (never be duplicated)
By defining ExpType, separately from Type, we can achieve goals 1 and 2
statically.
See also [wiki:typechecking]
Note [TcLevel of ExpType]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data G a where
MkG :: G Bool
foo MkG = True
This is a classic untouchable-variable / ambiguous GADT return type
scenario. But, with ExpTypes, we'll be inferring the type of the RHS.
And, because there is only one branch of the case, we won't trigger
Note [Case branches must never infer a non-tau type] of TcMatches.
We thus must track a TcLevel in an Inferring ExpType. If we try to
fill the ExpType and find that the TcLevels don't work out, we
fill the ExpType with a tau-tv at the low TcLevel, hopefully to
be worked out later by some means. This is triggered in
test gadt/gadt-escape1.
-}
-- actual data definition is in TcType
-- | Make an 'ExpType' suitable for inferring a type of kind * or #.
newInferExpTypeNoInst :: TcM ExpSigmaType
newInferExpTypeNoInst = newInferExpType False
newInferExpTypeInst :: TcM ExpRhoType
newInferExpTypeInst = newInferExpType True
newInferExpType :: Bool -> TcM ExpType
newInferExpType inst
= do { u <- newUnique
; tclvl <- getTcLevel
; traceTc "newOpenInferExpType" (ppr u <+> ppr inst <+> ppr tclvl)
; ref <- newMutVar Nothing
; return (Infer (IR { ir_uniq = u, ir_lvl = tclvl
, ir_ref = ref, ir_inst = inst })) }
-- | Extract a type out of an ExpType, if one exists. But one should always
-- exist. Unless you're quite sure you know what you're doing.
readExpType_maybe :: ExpType -> TcM (Maybe TcType)
readExpType_maybe (Check ty) = return (Just ty)
readExpType_maybe (Infer (IR { ir_ref = ref})) = readMutVar ref
-- | Extract a type out of an ExpType. Otherwise, panics.
readExpType :: ExpType -> TcM TcType
readExpType exp_ty
= do { mb_ty <- readExpType_maybe exp_ty
; case mb_ty of
Just ty -> return ty
Nothing -> pprPanic "Unknown expected type" (ppr exp_ty) }
-- | Returns the expected type when in checking mode.
checkingExpType_maybe :: ExpType -> Maybe TcType
checkingExpType_maybe (Check ty) = Just ty
checkingExpType_maybe _ = Nothing
-- | Returns the expected type when in checking mode. Panics if in inference
-- mode.
checkingExpType :: String -> ExpType -> TcType
checkingExpType _ (Check ty) = ty
checkingExpType err et = pprPanic "checkingExpType" (text err $$ ppr et)
tauifyExpType :: ExpType -> TcM ExpType
-- ^ Turn a (Infer hole) type into a (Check alpha),
-- where alpha is a fresh unification variable
tauifyExpType (Check ty) = return (Check ty) -- No-op for (Check ty)
tauifyExpType (Infer inf_res) = do { ty <- inferResultToType inf_res
; return (Check ty) }
-- | Extracts the expected type if there is one, or generates a new
-- TauTv if there isn't.
expTypeToType :: ExpType -> TcM TcType
expTypeToType (Check ty) = return ty
expTypeToType (Infer inf_res) = inferResultToType inf_res
inferResultToType :: InferResult -> TcM Type
inferResultToType (IR { ir_uniq = u, ir_lvl = tc_lvl
, ir_ref = ref })
= do { rr <- newMetaTyVarTyAtLevel tc_lvl runtimeRepTy
; tau <- newMetaTyVarTyAtLevel tc_lvl (tYPE rr)
-- See Note [TcLevel of ExpType]
; writeMutVar ref (Just tau)
; traceTc "Forcing ExpType to be monomorphic:"
(ppr u <+> text ":=" <+> ppr tau)
; return tau }
{- *********************************************************************
* *
SkolemTvs (immutable)
* *
********************************************************************* -}
tcInstType :: ([TyVar] -> TcM (TCvSubst, [TcTyVar]))
-- ^ How to instantiate the type variables
-> Id -- ^ Type to instantiate
-> TcM ([(Name, TcTyVar)], TcThetaType, TcType) -- ^ Result
-- (type vars, preds (incl equalities), rho)
tcInstType inst_tyvars id
= case tcSplitForAllTys (idType id) of
([], rho) -> let -- There may be overloading despite no type variables;
-- (?x :: Int) => Int -> Int
(theta, tau) = tcSplitPhiTy rho
in
return ([], theta, tau)
(tyvars, rho) -> do { (subst, tyvars') <- inst_tyvars tyvars
; let (theta, tau) = tcSplitPhiTy (substTyAddInScope subst rho)
tv_prs = map tyVarName tyvars `zip` tyvars'
; return (tv_prs, theta, tau) }
tcSkolDFunType :: DFunId -> TcM ([TcTyVar], TcThetaType, TcType)
-- Instantiate a type signature with skolem constants.
-- We could give them fresh names, but no need to do so
tcSkolDFunType dfun
= do { (tv_prs, theta, tau) <- tcInstType tcInstSuperSkolTyVars dfun
; return (map snd tv_prs, theta, tau) }
tcSuperSkolTyVars :: [TyVar] -> (TCvSubst, [TcTyVar])
-- Make skolem constants, but do *not* give them new names, as above
-- Moreover, make them "super skolems"; see comments with superSkolemTv
-- see Note [Kind substitution when instantiating]
-- Precondition: tyvars should be ordered by scoping
tcSuperSkolTyVars = mapAccumL tcSuperSkolTyVar emptyTCvSubst
tcSuperSkolTyVar :: TCvSubst -> TyVar -> (TCvSubst, TcTyVar)
tcSuperSkolTyVar subst tv
= (extendTvSubstWithClone subst tv new_tv, new_tv)
where
kind = substTyUnchecked subst (tyVarKind tv)
new_tv = mkTcTyVar (tyVarName tv) kind superSkolemTv
-- | Given a list of @['TyVar']@, skolemize the type variables,
-- returning a substitution mapping the original tyvars to the
-- skolems, and the list of newly bound skolems.
tcInstSkolTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- See Note [Skolemising type variables]
tcInstSkolTyVars = tcInstSkolTyVarsX emptyTCvSubst
tcInstSkolTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- See Note [Skolemising type variables]
tcInstSkolTyVarsX = tcInstSkolTyVarsPushLevel False
tcInstSuperSkolTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- See Note [Skolemising type variables]
tcInstSuperSkolTyVars = tcInstSuperSkolTyVarsX emptyTCvSubst
tcInstSuperSkolTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- See Note [Skolemising type variables]
tcInstSuperSkolTyVarsX subst = tcInstSkolTyVarsPushLevel True subst
tcInstSkolTyVarsPushLevel :: Bool -> TCvSubst -> [TyVar]
-> TcM (TCvSubst, [TcTyVar])
-- Skolemise one level deeper, hence pushTcLevel
-- See Note [Skolemising type variables]
tcInstSkolTyVarsPushLevel overlappable subst tvs
= do { tc_lvl <- getTcLevel
; let pushed_lvl = pushTcLevel tc_lvl
; tcInstSkolTyVarsAt pushed_lvl overlappable subst tvs }
tcInstSkolTyVarsAt :: TcLevel -> Bool
-> TCvSubst -> [TyVar]
-> TcM (TCvSubst, [TcTyVar])
tcInstSkolTyVarsAt lvl overlappable subst tvs
= freshenTyCoVarsX new_skol_tv subst tvs
where
details = SkolemTv lvl overlappable
new_skol_tv name kind = mkTcTyVar name kind details
------------------
freshenTyVarBndrs :: [TyVar] -> TcM (TCvSubst, [TyVar])
-- ^ Give fresh uniques to a bunch of TyVars, but they stay
-- as TyVars, rather than becoming TcTyVars
-- Used in FamInst.newFamInst, and Inst.newClsInst
freshenTyVarBndrs = freshenTyCoVars mkTyVar
freshenCoVarBndrsX :: TCvSubst -> [CoVar] -> TcM (TCvSubst, [CoVar])
-- ^ Give fresh uniques to a bunch of CoVars
-- Used in FamInst.newFamInst
freshenCoVarBndrsX subst = freshenTyCoVarsX mkCoVar subst
------------------
freshenTyCoVars :: (Name -> Kind -> TyCoVar)
-> [TyVar] -> TcM (TCvSubst, [TyCoVar])
freshenTyCoVars mk_tcv = freshenTyCoVarsX mk_tcv emptyTCvSubst
freshenTyCoVarsX :: (Name -> Kind -> TyCoVar)
-> TCvSubst -> [TyCoVar]
-> TcM (TCvSubst, [TyCoVar])
freshenTyCoVarsX mk_tcv = mapAccumLM (freshenTyCoVarX mk_tcv)
freshenTyCoVarX :: (Name -> Kind -> TyCoVar)
-> TCvSubst -> TyCoVar -> TcM (TCvSubst, TyCoVar)
-- This a complete freshening operation:
-- the skolems have a fresh unique, and a location from the monad
-- See Note [Skolemising type variables]
freshenTyCoVarX mk_tcv subst tycovar
= do { loc <- getSrcSpanM
; uniq <- newUnique
; let old_name = tyVarName tycovar
new_name = mkInternalName uniq (getOccName old_name) loc
new_kind = substTyUnchecked subst (tyVarKind tycovar)
new_tcv = mk_tcv new_name new_kind
subst1 = extendTCvSubstWithClone subst tycovar new_tcv
; return (subst1, new_tcv) }
{- Note [Skolemising type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The tcInstSkolTyVars family of functions instantiate a list of TyVars
to fresh skolem TcTyVars. Important notes:
a) Level allocation. We generally skolemise /before/ calling
pushLevelAndCaptureConstraints. So we want their level to the level
of the soon-to-be-created implication, which has a level ONE HIGHER
than the current level. Hence the pushTcLevel. It feels like a
slight hack.
b) The [TyVar] should be ordered (kind vars first)
See Note [Kind substitution when instantiating]
c) It's a complete freshening operation: the skolems have a fresh
unique, and a location from the monad
d) The resulting skolems are
non-overlappable for tcInstSkolTyVars,
but overlappable for tcInstSuperSkolTyVars
See TcDerivInfer Note [Overlap and deriving] for an example
of where this matters.
Note [Kind substitution when instantiating]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When we instantiate a bunch of kind and type variables, first we
expect them to be topologically sorted.
Then we have to instantiate the kind variables, build a substitution
from old variables to the new variables, then instantiate the type
variables substituting the original kind.
Exemple: If we want to instantiate
[(k1 :: *), (k2 :: *), (a :: k1 -> k2), (b :: k1)]
we want
[(?k1 :: *), (?k2 :: *), (?a :: ?k1 -> ?k2), (?b :: ?k1)]
instead of the buggous
[(?k1 :: *), (?k2 :: *), (?a :: k1 -> k2), (?b :: k1)]
************************************************************************
* *
MetaTvs (meta type variables; mutable)
* *
************************************************************************
-}
{-
Note [TyVarTv]
~~~~~~~~~~~~
A TyVarTv can unify with type *variables* only, including other TyVarTvs and
skolems. Sometimes, they can unify with type variables that the user would
rather keep distinct; see #11203 for an example. So, any client of this
function needs to either allow the TyVarTvs to unify with each other or check
that they don't (say, with a call to findDubTyVarTvs).
Before #15050 this (under the name SigTv) was used for ScopedTypeVariables in
patterns, to make sure these type variables only refer to other type variables,
but this restriction was dropped, and ScopedTypeVariables can now refer to full
types (GHC Proposal 29).
The remaining uses of newTyVarTyVars are
* In kind signatures, see
TcTyClsDecls Note [Inferring kinds for type declarations]
and Note [Kind checking for GADTs]
* In partial type signatures, see Note [Quantified variables in partial type signatures]
-}
newMetaTyVarName :: FastString -> TcM Name
-- Makes a /System/ Name, which is eagerly eliminated by
-- the unifier; see TcUnify.nicer_to_update_tv1, and
-- TcCanonical.canEqTyVarTyVar (nicer_to_update_tv2)
newMetaTyVarName str
= do { uniq <- newUnique
; return (mkSystemName uniq (mkTyVarOccFS str)) }
cloneMetaTyVarName :: Name -> TcM Name
cloneMetaTyVarName name
= do { uniq <- newUnique
; return (mkSystemName uniq (nameOccName name)) }
-- See Note [Name of an instantiated type variable]
{- Note [Name of an instantiated type variable]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
At the moment we give a unification variable a System Name, which
influences the way it is tidied; see TypeRep.tidyTyVarBndr.
-}
metaInfoToTyVarName :: MetaInfo -> FastString
metaInfoToTyVarName meta_info =
case meta_info of
TauTv -> fsLit "t"
FlatMetaTv -> fsLit "fmv"
FlatSkolTv -> fsLit "fsk"
TyVarTv -> fsLit "a"
newAnonMetaTyVar :: MetaInfo -> Kind -> TcM TcTyVar
newAnonMetaTyVar mi = newNamedAnonMetaTyVar (metaInfoToTyVarName mi) mi
newNamedAnonMetaTyVar :: FastString -> MetaInfo -> Kind -> TcM TcTyVar
-- Make a new meta tyvar out of thin air
newNamedAnonMetaTyVar tyvar_name meta_info kind
= do { name <- newMetaTyVarName tyvar_name
; details <- newMetaDetails meta_info
; let tyvar = mkTcTyVar name kind details
; traceTc "newAnonMetaTyVar" (ppr tyvar)
; return tyvar }
-- makes a new skolem tv
newSkolemTyVar :: Name -> Kind -> TcM TcTyVar
newSkolemTyVar name kind
= do { lvl <- getTcLevel
; return (mkTcTyVar name kind (SkolemTv lvl False)) }
newTyVarTyVar :: Name -> Kind -> TcM TcTyVar
-- See Note [TyVarTv]
-- Does not clone a fresh unique
newTyVarTyVar name kind
= do { details <- newMetaDetails TyVarTv
; let tyvar = mkTcTyVar name kind details
; traceTc "newTyVarTyVar" (ppr tyvar)
; return tyvar }
cloneTyVarTyVar :: Name -> Kind -> TcM TcTyVar
-- See Note [TyVarTv]
-- Clones a fresh unique
cloneTyVarTyVar name kind
= do { details <- newMetaDetails TyVarTv
; uniq <- newUnique
; let name' = name `setNameUnique` uniq
tyvar = mkTcTyVar name' kind details
-- Don't use cloneMetaTyVar, which makes a SystemName
-- We want to keep the original more user-friendly Name
-- In practical terms that means that in error messages,
-- when the Name is tidied we get 'a' rather than 'a0'
; traceTc "cloneTyVarTyVar" (ppr tyvar)
; return tyvar }
newPatSigTyVar :: Name -> Kind -> TcM TcTyVar
newPatSigTyVar name kind
= do { details <- newMetaDetails TauTv
; uniq <- newUnique
; let name' = name `setNameUnique` uniq
tyvar = mkTcTyVar name' kind details
-- Don't use cloneMetaTyVar;
-- same reasoning as in newTyVarTyVar
; traceTc "newPatSigTyVar" (ppr tyvar)
; return tyvar }
cloneAnonMetaTyVar :: MetaInfo -> TyVar -> TcKind -> TcM TcTyVar
-- Make a fresh MetaTyVar, basing the name
-- on that of the supplied TyVar
cloneAnonMetaTyVar info tv kind
= do { details <- newMetaDetails info
; name <- cloneMetaTyVarName (tyVarName tv)
; let tyvar = mkTcTyVar name kind details
; traceTc "cloneAnonMetaTyVar" (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar))
; return tyvar }
newFskTyVar :: TcType -> TcM TcTyVar
newFskTyVar fam_ty
= do { details <- newMetaDetails FlatSkolTv
; name <- newMetaTyVarName (fsLit "fsk")
; return (mkTcTyVar name (tcTypeKind fam_ty) details) }
newFmvTyVar :: TcType -> TcM TcTyVar
-- Very like newMetaTyVar, except sets mtv_tclvl to one less
-- so that the fmv is untouchable.
newFmvTyVar fam_ty
= do { details <- newMetaDetails FlatMetaTv
; name <- newMetaTyVarName (fsLit "s")
; return (mkTcTyVar name (tcTypeKind fam_ty) details) }
newMetaDetails :: MetaInfo -> TcM TcTyVarDetails
newMetaDetails info
= do { ref <- newMutVar Flexi
; tclvl <- getTcLevel
; return (MetaTv { mtv_info = info
, mtv_ref = ref
, mtv_tclvl = tclvl }) }
cloneMetaTyVar :: TcTyVar -> TcM TcTyVar
cloneMetaTyVar tv
= ASSERT( isTcTyVar tv )
do { ref <- newMutVar Flexi
; name' <- cloneMetaTyVarName (tyVarName tv)
; let details' = case tcTyVarDetails tv of
details@(MetaTv {}) -> details { mtv_ref = ref }
_ -> pprPanic "cloneMetaTyVar" (ppr tv)
tyvar = mkTcTyVar name' (tyVarKind tv) details'
; traceTc "cloneMetaTyVar" (ppr tyvar)
; return tyvar }
-- Works for both type and kind variables
readMetaTyVar :: TyVar -> TcM MetaDetails
readMetaTyVar tyvar = ASSERT2( isMetaTyVar tyvar, ppr tyvar )
readMutVar (metaTyVarRef tyvar)
isFilledMetaTyVar_maybe :: TcTyVar -> TcM (Maybe Type)
isFilledMetaTyVar_maybe tv
| MetaTv { mtv_ref = ref } <- tcTyVarDetails tv
= do { cts <- readTcRef ref
; case cts of
Indirect ty -> return (Just ty)
Flexi -> return Nothing }
| otherwise
= return Nothing
isFilledMetaTyVar :: TyVar -> TcM Bool
-- True of a filled-in (Indirect) meta type variable
isFilledMetaTyVar tv = isJust <$> isFilledMetaTyVar_maybe tv
isUnfilledMetaTyVar :: TyVar -> TcM Bool
-- True of a un-filled-in (Flexi) meta type variable
-- NB: Not the opposite of isFilledMetaTyVar
isUnfilledMetaTyVar tv
| MetaTv { mtv_ref = ref } <- tcTyVarDetails tv
= do { details <- readMutVar ref
; return (isFlexi details) }
| otherwise = return False
--------------------
-- Works with both type and kind variables
writeMetaTyVar :: TcTyVar -> TcType -> TcM ()
-- Write into a currently-empty MetaTyVar
writeMetaTyVar tyvar ty
| not debugIsOn
= writeMetaTyVarRef tyvar (metaTyVarRef tyvar) ty
-- Everything from here on only happens if DEBUG is on
| not (isTcTyVar tyvar)
= ASSERT2( False, text "Writing to non-tc tyvar" <+> ppr tyvar )
return ()
| MetaTv { mtv_ref = ref } <- tcTyVarDetails tyvar
= writeMetaTyVarRef tyvar ref ty
| otherwise
= ASSERT2( False, text "Writing to non-meta tyvar" <+> ppr tyvar )
return ()
--------------------
writeMetaTyVarRef :: TcTyVar -> TcRef MetaDetails -> TcType -> TcM ()
-- Here the tyvar is for error checking only;
-- the ref cell must be for the same tyvar
writeMetaTyVarRef tyvar ref ty
| not debugIsOn
= do { traceTc "writeMetaTyVar" (ppr tyvar <+> dcolon <+> ppr (tyVarKind tyvar)
<+> text ":=" <+> ppr ty)
; writeTcRef ref (Indirect ty) }
-- Everything from here on only happens if DEBUG is on
| otherwise
= do { meta_details <- readMutVar ref;
-- Zonk kinds to allow the error check to work
; zonked_tv_kind <- zonkTcType tv_kind
; zonked_ty_kind <- zonkTcType ty_kind
; let kind_check_ok = tcIsConstraintKind zonked_tv_kind
|| tcEqKind zonked_ty_kind zonked_tv_kind
-- Hack alert! tcIsConstraintKind: see TcHsType
-- Note [Extra-constraint holes in partial type signatures]
kind_msg = hang (text "Ill-kinded update to meta tyvar")
2 ( ppr tyvar <+> text "::" <+> (ppr tv_kind $$ ppr zonked_tv_kind)
<+> text ":="
<+> ppr ty <+> text "::" <+> (ppr zonked_ty_kind) )
; traceTc "writeMetaTyVar" (ppr tyvar <+> text ":=" <+> ppr ty)
-- Check for double updates
; MASSERT2( isFlexi meta_details, double_upd_msg meta_details )
-- Check for level OK
-- See Note [Level check when unifying]
; MASSERT2( level_check_ok, level_check_msg )
-- Check Kinds ok
; MASSERT2( kind_check_ok, kind_msg )
-- Do the write
; writeMutVar ref (Indirect ty) }
where
tv_kind = tyVarKind tyvar
ty_kind = tcTypeKind ty
tv_lvl = tcTyVarLevel tyvar
ty_lvl = tcTypeLevel ty
level_check_ok = not (ty_lvl `strictlyDeeperThan` tv_lvl)
level_check_msg = ppr ty_lvl $$ ppr tv_lvl $$ ppr tyvar $$ ppr ty
double_upd_msg details = hang (text "Double update of meta tyvar")
2 (ppr tyvar $$ ppr details)
{- Note [Level check when unifying]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When unifying
alpha:lvl := ty
we expect that the TcLevel of 'ty' will be <= lvl.
However, during unflatting we do
fuv:l := ty:(l+1)
which is usually wrong; hence the check isFmmvTyVar in level_check_ok.
See Note [TcLevel assignment] in TcType.
-}
{-
% Generating fresh variables for pattern match check
-}
{-
************************************************************************
* *
MetaTvs: TauTvs
* *
************************************************************************
Note [Never need to instantiate coercion variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With coercion variables sloshing around in types, it might seem that we
sometimes need to instantiate coercion variables. This would be problematic,
because coercion variables inhabit unboxed equality (~#), and the constraint
solver thinks in terms only of boxed equality (~). The solution is that
we never need to instantiate coercion variables in the first place.
The tyvars that we need to instantiate come from the types of functions,
data constructors, and patterns. These will never be quantified over
coercion variables, except for the special case of the promoted Eq#. But,
that can't ever appear in user code, so we're safe!
-}
newFlexiTyVar :: Kind -> TcM TcTyVar
newFlexiTyVar kind = newAnonMetaTyVar TauTv kind
-- | Create a new flexi ty var with a specific name
newNamedFlexiTyVar :: FastString -> Kind -> TcM TcTyVar
newNamedFlexiTyVar fs kind = newNamedAnonMetaTyVar fs TauTv kind
newFlexiTyVarTy :: Kind -> TcM TcType
newFlexiTyVarTy kind = do
tc_tyvar <- newFlexiTyVar kind
return (mkTyVarTy tc_tyvar)
newFlexiTyVarTys :: Int -> Kind -> TcM [TcType]
newFlexiTyVarTys n kind = replicateM n (newFlexiTyVarTy kind)
newOpenTypeKind :: TcM TcKind
newOpenTypeKind
= do { rr <- newFlexiTyVarTy runtimeRepTy
; return (tYPE rr) }
-- | Create a tyvar that can be a lifted or unlifted type.
-- Returns alpha :: TYPE kappa, where both alpha and kappa are fresh
newOpenFlexiTyVarTy :: TcM TcType
newOpenFlexiTyVarTy
= do { kind <- newOpenTypeKind
; newFlexiTyVarTy kind }
newMetaTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- Instantiate with META type variables
-- Note that this works for a sequence of kind, type, and coercion variables
-- variables. Eg [ (k:*), (a:k->k) ]
-- Gives [ (k7:*), (a8:k7->k7) ]
newMetaTyVars = newMetaTyVarsX emptyTCvSubst
-- emptyTCvSubst has an empty in-scope set, but that's fine here
-- Since the tyvars are freshly made, they cannot possibly be
-- captured by any existing for-alls.
newMetaTyVarsX :: TCvSubst -> [TyVar] -> TcM (TCvSubst, [TcTyVar])
-- Just like newMetaTyVars, but start with an existing substitution.
newMetaTyVarsX subst = mapAccumLM newMetaTyVarX subst
newMetaTyVarX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
-- Make a new unification variable tyvar whose Name and Kind come from
-- an existing TyVar. We substitute kind variables in the kind.
newMetaTyVarX subst tyvar = new_meta_tv_x TauTv subst tyvar
newMetaTyVarTyVars :: [TyVar] -> TcM (TCvSubst, [TcTyVar])
newMetaTyVarTyVars = mapAccumLM newMetaTyVarTyVarX emptyTCvSubst
newMetaTyVarTyVarX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
-- Just like newMetaTyVarX, but make a TyVarTv
newMetaTyVarTyVarX subst tyvar = new_meta_tv_x TyVarTv subst tyvar
newWildCardX :: TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
newWildCardX subst tv
= do { new_tv <- newAnonMetaTyVar TauTv (substTy subst (tyVarKind tv))
; return (extendTvSubstWithClone subst tv new_tv, new_tv) }
new_meta_tv_x :: MetaInfo -> TCvSubst -> TyVar -> TcM (TCvSubst, TcTyVar)
new_meta_tv_x info subst tv
= do { new_tv <- cloneAnonMetaTyVar info tv substd_kind
; let subst1 = extendTvSubstWithClone subst tv new_tv
; return (subst1, new_tv) }
where
substd_kind = substTyUnchecked subst (tyVarKind tv)
-- NOTE: #12549 is fixed so we could use
-- substTy here, but the tc_infer_args problem
-- is not yet fixed so leaving as unchecked for now.
-- OLD NOTE:
-- Unchecked because we call newMetaTyVarX from
-- tcInstTyBinder, which is called from tcInferApps
-- which does not yet take enough trouble to ensure
-- the in-scope set is right; e.g. #12785 trips
-- if we use substTy here
newMetaTyVarTyAtLevel :: TcLevel -> TcKind -> TcM TcType
newMetaTyVarTyAtLevel tc_lvl kind
= do { ref <- newMutVar Flexi
; name <- newMetaTyVarName (fsLit "p")
; let details = MetaTv { mtv_info = TauTv
, mtv_ref = ref
, mtv_tclvl = tc_lvl }
; return (mkTyVarTy (mkTcTyVar name kind details)) }
{- *********************************************************************
* *
Finding variables to quantify over
* *
********************************************************************* -}
{- Note [Dependent type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In Haskell type inference we quantify over type variables; but we only
quantify over /kind/ variables when -XPolyKinds is on. Without -XPolyKinds
we default the kind variables to *.
So, to support this defaulting, and only for that reason, when
collecting the free vars of a type (in candidateQTyVarsOfType and friends),
prior to quantifying, we must keep the type and kind variables separate.
But what does that mean in a system where kind variables /are/ type
variables? It's a fairly arbitrary distinction based on how the
variables appear:
- "Kind variables" appear in the kind of some other free variable
or in the kind of a locally quantified type variable
(forall (a :: kappa). ...) or in the kind of a coercion
(a |> (co :: kappa1 ~ kappa2)).
These are the ones we default to * if -XPolyKinds is off
- "Type variables" are all free vars that are not kind variables
E.g. In the type T k (a::k)
'k' is a kind variable, because it occurs in the kind of 'a',
even though it also appears at "top level" of the type
'a' is a type variable, because it doesn't
We gather these variables using a CandidatesQTvs record:
DV { dv_kvs: Variables free in the kind of a free type variable
or of a forall-bound type variable
, dv_tvs: Variables syntactically free in the type }
So: dv_kvs are the kind variables of the type
(dv_tvs - dv_kvs) are the type variable of the type
Note that
* A variable can occur in both.
T k (x::k) The first occurrence of k makes it
show up in dv_tvs, the second in dv_kvs
* We include any coercion variables in the "dependent",
"kind-variable" set because we never quantify over them.
* The "kind variables" might depend on each other; e.g
(k1 :: k2), (k2 :: *)
The "type variables" do not depend on each other; if
one did, it'd be classified as a kind variable!
Note [CandidatesQTvs determinism and order]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Determinism: when we quantify over type variables we decide the
order in which they appear in the final type. Because the order of
type variables in the type can end up in the interface file and
affects some optimizations like worker-wrapper, we want this order to
be deterministic.
To achieve that we use deterministic sets of variables that can be
converted to lists in a deterministic order. For more information
about deterministic sets see Note [Deterministic UniqFM] in UniqDFM.
* Order: as well as being deterministic, we use an
accumulating-parameter style for candidateQTyVarsOfType so that we
add variables one at a time, left to right. That means we tend to
produce the variables in left-to-right order. This is just to make
it bit more predictable for the programmer.
Note [Naughty quantification candidates]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (#14880, dependent/should_compile/T14880-2), suppose
we are trying to generalise this type:
forall arg. ... (alpha[tau]:arg) ...
We have a metavariable alpha whose kind mentions a skolem variable
bound inside the very type we are generalising.
This can arise while type-checking a user-written type signature
(see the test case for the full code).
We cannot generalise over alpha! That would produce a type like
forall {a :: arg}. forall arg. ...blah...
The fact that alpha's kind mentions arg renders it completely
ineligible for generalisation.
However, we are not going to learn any new constraints on alpha,
because its kind isn't even in scope in the outer context (but see Wrinkle).
So alpha is entirely unconstrained.
What then should we do with alpha? During generalization, every
metavariable is either (A) promoted, (B) generalized, or (C) zapped
(according to Note [Recipe for checking a signature] in TcHsType).
* We can't generalise it.
* We can't promote it, because its kind prevents that
* We can't simply leave it be, because this type is about to
go into the typing environment (as the type of some let-bound
variable, say), and then chaos erupts when we try to instantiate.
Previously, we zapped it to Any. This worked, but it had the unfortunate
effect of causing Any sometimes to appear in error messages. If this
kind of signature happens, the user probably has made a mistake -- no
one really wants Any in their types. So we now error. This must be
a hard error (failure in the monad) to avoid other messages from mentioning
Any.
We do this eager erroring in candidateQTyVars, which always precedes
generalisation, because at that moment we have a clear picture of what
skolems are in scope within the type itself (e.g. that 'forall arg').
Wrinkle:
We must make absolutely sure that alpha indeed is not
from an outer context. (Otherwise, we might indeed learn more information
about it.) This can be done easily: we just check alpha's TcLevel.
That level must be strictly greater than the ambient TcLevel in order
to treat it as naughty. We say "strictly greater than" because the call to
candidateQTyVars is made outside the bumped TcLevel, as stated in the
comment to candidateQTyVarsOfType. The level check is done in go_tv
in collect_cand_qtvs. Skipping this check caused #16517.
-}
data CandidatesQTvs
-- See Note [Dependent type variables]
-- See Note [CandidatesQTvs determinism and order]
--
-- Invariants:
-- * All variables are fully zonked, including their kinds
-- * All variables are at a level greater than the ambient level
-- See Note [Use level numbers for quantification]
--
-- This *can* contain skolems. For example, in `data X k :: k -> Type`
-- we need to know that the k is a dependent variable. This is done
-- by collecting the candidates in the kind after skolemising. It also
-- comes up when generalizing a associated type instance, where instance
-- variables are skolems. (Recall that associated type instances are generalized
-- independently from their enclosing class instance, and the associated
-- type instance may be generalized by more, fewer, or different variables
-- than the class instance.)
--
= DV { dv_kvs :: DTyVarSet -- "kind" metavariables (dependent)
, dv_tvs :: DTyVarSet -- "type" metavariables (non-dependent)
-- A variable may appear in both sets
-- E.g. T k (x::k) The first occurrence of k makes it
-- show up in dv_tvs, the second in dv_kvs
-- See Note [Dependent type variables]
, dv_cvs :: CoVarSet
-- These are covars. Included only so that we don't repeatedly
-- look at covars' kinds in accumulator. Not used by quantifyTyVars.
}
instance Semi.Semigroup CandidatesQTvs where
(DV { dv_kvs = kv1, dv_tvs = tv1, dv_cvs = cv1 })
<> (DV { dv_kvs = kv2, dv_tvs = tv2, dv_cvs = cv2 })
= DV { dv_kvs = kv1 `unionDVarSet` kv2
, dv_tvs = tv1 `unionDVarSet` tv2
, dv_cvs = cv1 `unionVarSet` cv2 }
instance Monoid CandidatesQTvs where
mempty = DV { dv_kvs = emptyDVarSet, dv_tvs = emptyDVarSet, dv_cvs = emptyVarSet }
mappend = (Semi.<>)
instance Outputable CandidatesQTvs where
ppr (DV {dv_kvs = kvs, dv_tvs = tvs, dv_cvs = cvs })
= text "DV" <+> braces (pprWithCommas id [ text "dv_kvs =" <+> ppr kvs
, text "dv_tvs =" <+> ppr tvs
, text "dv_cvs =" <+> ppr cvs ])
candidateKindVars :: CandidatesQTvs -> TyVarSet
candidateKindVars dvs = dVarSetToVarSet (dv_kvs dvs)
partitionCandidates :: CandidatesQTvs -> (TyVar -> Bool) -> (DTyVarSet, CandidatesQTvs)
partitionCandidates dvs@(DV { dv_kvs = kvs, dv_tvs = tvs }) pred
= (extracted, dvs { dv_kvs = rest_kvs, dv_tvs = rest_tvs })
where
(extracted_kvs, rest_kvs) = partitionDVarSet pred kvs
(extracted_tvs, rest_tvs) = partitionDVarSet pred tvs
extracted = extracted_kvs `unionDVarSet` extracted_tvs
-- | Gathers free variables to use as quantification candidates (in
-- 'quantifyTyVars'). This might output the same var
-- in both sets, if it's used in both a type and a kind.
-- The variables to quantify must have a TcLevel strictly greater than
-- the ambient level. (See Wrinkle in Note [Naughty quantification candidates])
-- See Note [CandidatesQTvs determinism and order]
-- See Note [Dependent type variables]
candidateQTyVarsOfType :: TcType -- not necessarily zonked
-> TcM CandidatesQTvs
candidateQTyVarsOfType ty = collect_cand_qtvs ty False emptyVarSet mempty ty
-- | Like 'candidateQTyVarsOfType', but over a list of types
-- The variables to quantify must have a TcLevel strictly greater than
-- the ambient level. (See Wrinkle in Note [Naughty quantification candidates])
candidateQTyVarsOfTypes :: [Type] -> TcM CandidatesQTvs
candidateQTyVarsOfTypes tys = foldlM (\acc ty -> collect_cand_qtvs ty False emptyVarSet acc ty)
mempty tys
-- | Like 'candidateQTyVarsOfType', but consider every free variable
-- to be dependent. This is appropriate when generalizing a *kind*,
-- instead of a type. (That way, -XNoPolyKinds will default the variables
-- to Type.)
candidateQTyVarsOfKind :: TcKind -- Not necessarily zonked
-> TcM CandidatesQTvs
candidateQTyVarsOfKind ty = collect_cand_qtvs ty True emptyVarSet mempty ty
candidateQTyVarsOfKinds :: [TcKind] -- Not necessarily zonked
-> TcM CandidatesQTvs
candidateQTyVarsOfKinds tys = foldM (\acc ty -> collect_cand_qtvs ty True emptyVarSet acc ty)
mempty tys
delCandidates :: CandidatesQTvs -> [Var] -> CandidatesQTvs
delCandidates (DV { dv_kvs = kvs, dv_tvs = tvs, dv_cvs = cvs }) vars
= DV { dv_kvs = kvs `delDVarSetList` vars
, dv_tvs = tvs `delDVarSetList` vars
, dv_cvs = cvs `delVarSetList` vars }
collect_cand_qtvs
:: TcType -- original type that we started recurring into; for errors
-> Bool -- True <=> consider every fv in Type to be dependent
-> VarSet -- Bound variables (locals only)
-> CandidatesQTvs -- Accumulating parameter
-> Type -- Not necessarily zonked
-> TcM CandidatesQTvs
-- Key points:
-- * Looks through meta-tyvars as it goes;
-- no need to zonk in advance
--
-- * Needs to be monadic anyway, because it handles naughty
-- quantification; see Note [Naughty quantification candidates]
--
-- * Returns fully-zonked CandidateQTvs, including their kinds
-- so that subsequent dependency analysis (to build a well
-- scoped telescope) works correctly
collect_cand_qtvs orig_ty is_dep bound dvs ty
= go dvs ty
where
is_bound tv = tv `elemVarSet` bound
-----------------
go :: CandidatesQTvs -> TcType -> TcM CandidatesQTvs
-- Uses accumulating-parameter style
go dv (AppTy t1 t2) = foldlM go dv [t1, t2]
go dv (TyConApp _ tys) = foldlM go dv tys
go dv (FunTy _ arg res) = foldlM go dv [arg, res]
go dv (LitTy {}) = return dv
go dv (CastTy ty co) = do dv1 <- go dv ty
collect_cand_qtvs_co orig_ty bound dv1 co
go dv (CoercionTy co) = collect_cand_qtvs_co orig_ty bound dv co
go dv (TyVarTy tv)
| is_bound tv = return dv
| otherwise = do { m_contents <- isFilledMetaTyVar_maybe tv
; case m_contents of
Just ind_ty -> go dv ind_ty
Nothing -> go_tv dv tv }
go dv (ForAllTy (Bndr tv _) ty)
= do { dv1 <- collect_cand_qtvs orig_ty True bound dv (tyVarKind tv)
; collect_cand_qtvs orig_ty is_dep (bound `extendVarSet` tv) dv1 ty }
-----------------
go_tv dv@(DV { dv_kvs = kvs, dv_tvs = tvs }) tv
| tv `elemDVarSet` kvs
= return dv -- We have met this tyvar already
| not is_dep
, tv `elemDVarSet` tvs
= return dv -- We have met this tyvar already
| otherwise
= do { tv_kind <- zonkTcType (tyVarKind tv)
-- This zonk is annoying, but it is necessary, both to
-- ensure that the collected candidates have zonked kinds
-- (#15795) and to make the naughty check
-- (which comes next) works correctly
; let tv_kind_vars = tyCoVarsOfType tv_kind
; cur_lvl <- getTcLevel
; if | tcTyVarLevel tv <= cur_lvl
-> return dv -- this variable is from an outer context; skip
-- See Note [Use level numbers ofor quantification]
| intersectsVarSet bound tv_kind_vars
-- the tyvar must not be from an outer context, but we have
-- already checked for this.
-- See Note [Naughty quantification candidates]
-> do { traceTc "Naughty quantifier" $
vcat [ ppr tv <+> dcolon <+> ppr tv_kind
, text "bound:" <+> pprTyVars (nonDetEltsUniqSet bound)
, text "fvs:" <+> pprTyVars (nonDetEltsUniqSet tv_kind_vars) ]
; let escapees = intersectVarSet bound tv_kind_vars
; naughtyQuantification orig_ty tv escapees }
| otherwise
-> do { let tv' = tv `setTyVarKind` tv_kind
dv' | is_dep = dv { dv_kvs = kvs `extendDVarSet` tv' }
| otherwise = dv { dv_tvs = tvs `extendDVarSet` tv' }
-- See Note [Order of accumulation]
-- See Note [Recurring into kinds for candidateQTyVars]
; collect_cand_qtvs orig_ty True bound dv' tv_kind } }
collect_cand_qtvs_co :: TcType -- original type at top of recursion; for errors
-> VarSet -- bound variables
-> CandidatesQTvs -> Coercion
-> TcM CandidatesQTvs
collect_cand_qtvs_co orig_ty bound = go_co
where
go_co dv (Refl ty) = collect_cand_qtvs orig_ty True bound dv ty
go_co dv (GRefl _ ty mco) = do dv1 <- collect_cand_qtvs orig_ty True bound dv ty
go_mco dv1 mco
go_co dv (TyConAppCo _ _ cos) = foldlM go_co dv cos
go_co dv (AppCo co1 co2) = foldlM go_co dv [co1, co2]
go_co dv (FunCo _ co1 co2) = foldlM go_co dv [co1, co2]
go_co dv (AxiomInstCo _ _ cos) = foldlM go_co dv cos
go_co dv (AxiomRuleCo _ cos) = foldlM go_co dv cos
go_co dv (UnivCo prov _ t1 t2) = do dv1 <- go_prov dv prov
dv2 <- collect_cand_qtvs orig_ty True bound dv1 t1
collect_cand_qtvs orig_ty True bound dv2 t2
go_co dv (SymCo co) = go_co dv co
go_co dv (TransCo co1 co2) = foldlM go_co dv [co1, co2]
go_co dv (NthCo _ _ co) = go_co dv co
go_co dv (LRCo _ co) = go_co dv co
go_co dv (InstCo co1 co2) = foldlM go_co dv [co1, co2]
go_co dv (KindCo co) = go_co dv co
go_co dv (SubCo co) = go_co dv co
go_co dv (HoleCo hole)
= do m_co <- unpackCoercionHole_maybe hole
case m_co of
Just co -> go_co dv co
Nothing -> go_cv dv (coHoleCoVar hole)
go_co dv (CoVarCo cv) = go_cv dv cv
go_co dv (ForAllCo tcv kind_co co)
= do { dv1 <- go_co dv kind_co
; collect_cand_qtvs_co orig_ty (bound `extendVarSet` tcv) dv1 co }
go_mco dv MRefl = return dv
go_mco dv (MCo co) = go_co dv co
go_prov dv UnsafeCoerceProv = return dv
go_prov dv (PhantomProv co) = go_co dv co
go_prov dv (ProofIrrelProv co) = go_co dv co
go_prov dv (PluginProv _) = return dv
go_cv :: CandidatesQTvs -> CoVar -> TcM CandidatesQTvs
go_cv dv@(DV { dv_cvs = cvs }) cv
| is_bound cv = return dv
| cv `elemVarSet` cvs = return dv
-- See Note [Recurring into kinds for candidateQTyVars]
| otherwise = collect_cand_qtvs orig_ty True bound
(dv { dv_cvs = cvs `extendVarSet` cv })
(idType cv)
is_bound tv = tv `elemVarSet` bound
{- Note [Order of accumulation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You might be tempted (like I was) to use unitDVarSet and mappend
rather than extendDVarSet. However, the union algorithm for
deterministic sets depends on (roughly) the size of the sets. The
elements from the smaller set end up to the right of the elements from
the larger one. When sets are equal, the left-hand argument to
`mappend` goes to the right of the right-hand argument.
In our case, if we use unitDVarSet and mappend, we learn that the free
variables of (a -> b -> c -> d) are [b, a, c, d], and we then quantify
over them in that order. (The a comes after the b because we union the
singleton sets as ({a} `mappend` {b}), producing {b, a}. Thereafter,
the size criterion works to our advantage.) This is just annoying to
users, so I use `extendDVarSet`, which unambiguously puts the new
element to the right.
Note that the unitDVarSet/mappend implementation would not be wrong
against any specification -- just suboptimal and confounding to users.
Note [Recurring into kinds for candidateQTyVars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
First, read Note [Closing over free variable kinds] in TyCoFVs, paying
attention to the end of the Note about using an empty bound set when
traversing a variable's kind.
That Note concludes with the recommendation that we empty out the bound
set when recurring into the kind of a type variable. Yet, we do not do
this here. I have two tasks in order to convince you that this code is
right. First, I must show why it is safe to ignore the reasoning in that
Note. Then, I must show why is is necessary to contradict the reasoning in
that Note.
Why it is safe: There can be no
shadowing in the candidateQ... functions: they work on the output of
type inference, which is seeded by the renamer and its insistence to
use different Uniques for different variables. (In contrast, the Core
functions work on the output of optimizations, which may introduce
shadowing.) Without shadowing, the problem studied by
Note [Closing over free variable kinds] in TyCoFVs cannot happen.
Why it is necessary:
Wiping the bound set would be just plain wrong here. Consider
forall k1 k2 (a :: k1). Proxy k2 (a |> (hole :: k1 ~# k2))
We really don't want to think k1 and k2 are free here. (It's true that we'll
never be able to fill in `hole`, but we don't want to go off the rails just
because we have an insoluble coercion hole.) So: why is it wrong to wipe
the bound variables here but right in Core? Because the final statement
in Note [Closing over free variable kinds] in TyCoFVs is wrong: not
every variable is either free or bound. A variable can be a hole, too!
The reasoning in that Note then breaks down.
And the reasoning applies just as well to free non-hole variables, so we
retain the bound set always.
-}
{- *********************************************************************
* *
Quantification
* *
************************************************************************
Note [quantifyTyVars]
~~~~~~~~~~~~~~~~~~~~~
quantifyTyVars is given the free vars of a type that we
are about to wrap in a forall.
It takes these free type/kind variables (partitioned into dependent and
non-dependent variables) skolemises metavariables with a TcLevel greater
than the ambient level (see Note [Use level numbers of quantification]).
* This function distinguishes between dependent and non-dependent
variables only to keep correct defaulting behavior with -XNoPolyKinds.
With -XPolyKinds, it treats both classes of variables identically.
* quantifyTyVars never quantifies over
- a coercion variable (or any tv mentioned in the kind of a covar)
- a runtime-rep variable
Note [Use level numbers for quantification]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The level numbers assigned to metavariables are very useful. Not only
do they track touchability (Note [TcLevel and untouchable type variables]
in TcType), but they also allow us to determine which variables to
generalise. The rule is this:
When generalising, quantify only metavariables with a TcLevel greater
than the ambient level.
This works because we bump the level every time we go inside a new
source-level construct. In a traditional generalisation algorithm, we
would gather all free variables that aren't free in an environment.
However, if a variable is in that environment, it will always have a lower
TcLevel: it came from an outer scope. So we can replace the "free in
environment" check with a level-number check.
Here is an example:
f x = x + (z True)
where
z y = x * x
We start by saying (x :: alpha[1]). When inferring the type of z, we'll
quickly discover that z :: alpha[1]. But it would be disastrous to
generalise over alpha in the type of z. So we need to know that alpha
comes from an outer environment. By contrast, the type of y is beta[2],
and we are free to generalise over it. What's the difference between
alpha[1] and beta[2]? Their levels. beta[2] has the right TcLevel for
generalisation, and so we generalise it. alpha[1] does not, and so
we leave it alone.
Note that not *every* variable with a higher level will get generalised,
either due to the monomorphism restriction or other quirks. See, for
example, the code in TcSimplify.decideMonoTyVars and in
TcHsType.kindGeneralizeSome, both of which exclude certain otherwise-eligible
variables from being generalised.
Using level numbers for quantification is implemented in the candidateQTyVars...
functions, by adding only those variables with a level strictly higher than
the ambient level to the set of candidates.
Note [quantifyTyVars determinism]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The results of quantifyTyVars are wrapped in a forall and can end up in the
interface file. One such example is inferred type signatures. They also affect
the results of optimizations, for example worker-wrapper. This means that to
get deterministic builds quantifyTyVars needs to be deterministic.
To achieve this CandidatesQTvs is backed by deterministic sets which allows them
to be later converted to a list in a deterministic order.
For more information about deterministic sets see
Note [Deterministic UniqFM] in UniqDFM.
-}
quantifyTyVars
:: CandidatesQTvs -- See Note [Dependent type variables]
-- Already zonked
-> TcM [TcTyVar]
-- See Note [quantifyTyVars]
-- Can be given a mixture of TcTyVars and TyVars, in the case of
-- associated type declarations. Also accepts covars, but *never* returns any.
-- According to Note [Use level numbers for quantification] and the
-- invariants on CandidateQTvs, we do not have to filter out variables
-- free in the environment here. Just quantify unconditionally, subject
-- to the restrictions in Note [quantifyTyVars].
quantifyTyVars dvs@(DV{ dv_kvs = dep_tkvs, dv_tvs = nondep_tkvs })
-- short-circuit common case
| isEmptyDVarSet dep_tkvs
, isEmptyDVarSet nondep_tkvs
= do { traceTc "quantifyTyVars has nothing to quantify" empty
; return [] }
| otherwise
= do { traceTc "quantifyTyVars 1" (ppr dvs)
; let dep_kvs = scopedSort $ dVarSetElems dep_tkvs
-- scopedSort: put the kind variables into
-- well-scoped order.
-- E.g. [k, (a::k)] not the other way round
nondep_tvs = dVarSetElems (nondep_tkvs `minusDVarSet` dep_tkvs)
-- See Note [Dependent type variables]
-- The `minus` dep_tkvs removes any kind-level vars
-- e.g. T k (a::k) Since k appear in a kind it'll
-- be in dv_kvs, and is dependent. So remove it from
-- dv_tvs which will also contain k
-- NB kinds of tvs are zonked by zonkTyCoVarsAndFV
-- In the non-PolyKinds case, default the kind variables
-- to *, and zonk the tyvars as usual. Notice that this
-- may make quantifyTyVars return a shorter list
-- than it was passed, but that's ok
; poly_kinds <- xoptM LangExt.PolyKinds
; dep_kvs' <- mapMaybeM (zonk_quant (not poly_kinds)) dep_kvs
; nondep_tvs' <- mapMaybeM (zonk_quant False) nondep_tvs
; let final_qtvs = dep_kvs' ++ nondep_tvs'
-- Because of the order, any kind variables
-- mentioned in the kinds of the nondep_tvs'
-- now refer to the dep_kvs'
; traceTc "quantifyTyVars 2"
(vcat [ text "nondep:" <+> pprTyVars nondep_tvs
, text "dep:" <+> pprTyVars dep_kvs
, text "dep_kvs'" <+> pprTyVars dep_kvs'
, text "nondep_tvs'" <+> pprTyVars nondep_tvs' ])
-- We should never quantify over coercion variables; check this
; let co_vars = filter isCoVar final_qtvs
; MASSERT2( null co_vars, ppr co_vars )
; return final_qtvs }
where
-- zonk_quant returns a tyvar if it should be quantified over;
-- otherwise, it returns Nothing. The latter case happens for
-- * Kind variables, with -XNoPolyKinds: don't quantify over these
-- * RuntimeRep variables: we never quantify over these
zonk_quant default_kind tkv
| not (isTyVar tkv)
= return Nothing -- this can happen for a covar that's associated with
-- a coercion hole. Test case: typecheck/should_compile/T2494
| not (isTcTyVar tkv)
= return (Just tkv) -- For associated types in a class with a standalone
-- kind signature, we have the class variables in
-- scope, and they are TyVars not TcTyVars
| otherwise
= do { deflt_done <- defaultTyVar default_kind tkv
; case deflt_done of
True -> return Nothing
False -> do { tv <- skolemiseQuantifiedTyVar tkv
; return (Just tv) } }
isQuantifiableTv :: TcLevel -- Level of the context, outside the quantification
-> TcTyVar
-> Bool
isQuantifiableTv outer_tclvl tcv
| isTcTyVar tcv -- Might be a CoVar; change this when gather covars separately
= tcTyVarLevel tcv > outer_tclvl
| otherwise
= False
zonkAndSkolemise :: TcTyCoVar -> TcM TcTyCoVar
-- A tyvar binder is never a unification variable (TauTv),
-- rather it is always a skolem. It *might* be a TyVarTv.
-- (Because non-CUSK type declarations use TyVarTvs.)
-- Regardless, it may have a kind that has not yet been zonked,
-- and may include kind unification variables.
zonkAndSkolemise tyvar
| isTyVarTyVar tyvar
-- We want to preserve the binding location of the original TyVarTv.
-- This is important for error messages. If we don't do this, then
-- we get bad locations in, e.g., typecheck/should_fail/T2688
= do { zonked_tyvar <- zonkTcTyVarToTyVar tyvar
; skolemiseQuantifiedTyVar zonked_tyvar }
| otherwise
= ASSERT2( isImmutableTyVar tyvar || isCoVar tyvar, pprTyVar tyvar )
zonkTyCoVarKind tyvar
skolemiseQuantifiedTyVar :: TcTyVar -> TcM TcTyVar
-- The quantified type variables often include meta type variables
-- we want to freeze them into ordinary type variables
-- The meta tyvar is updated to point to the new skolem TyVar. Now any
-- bound occurrences of the original type variable will get zonked to
-- the immutable version.
--
-- We leave skolem TyVars alone; they are immutable.
--
-- This function is called on both kind and type variables,
-- but kind variables *only* if PolyKinds is on.
skolemiseQuantifiedTyVar tv
= case tcTyVarDetails tv of
SkolemTv {} -> do { kind <- zonkTcType (tyVarKind tv)
; return (setTyVarKind tv kind) }
-- It might be a skolem type variable,
-- for example from a user type signature
MetaTv {} -> skolemiseUnboundMetaTyVar tv
_other -> pprPanic "skolemiseQuantifiedTyVar" (ppr tv) -- RuntimeUnk
defaultTyVar :: Bool -- True <=> please default this kind variable to *
-> TcTyVar -- If it's a MetaTyVar then it is unbound
-> TcM Bool -- True <=> defaulted away altogether
defaultTyVar default_kind tv
| not (isMetaTyVar tv)
= return False
| isTyVarTyVar tv
-- Do not default TyVarTvs. Doing so would violate the invariants
-- on TyVarTvs; see Note [Signature skolems] in TcType.
-- #13343 is an example; #14555 is another
-- See Note [Inferring kinds for type declarations] in TcTyClsDecls
= return False
| isRuntimeRepVar tv -- Do not quantify over a RuntimeRep var
-- unless it is a TyVarTv, handled earlier
= do { traceTc "Defaulting a RuntimeRep var to LiftedRep" (ppr tv)
; writeMetaTyVar tv liftedRepTy
; return True }
| default_kind -- -XNoPolyKinds and this is a kind var
= default_kind_var tv -- so default it to * if possible
| otherwise
= return False
where
default_kind_var :: TyVar -> TcM Bool
-- defaultKindVar is used exclusively with -XNoPolyKinds
-- See Note [Defaulting with -XNoPolyKinds]
-- It takes an (unconstrained) meta tyvar and defaults it.
-- Works only on vars of type *; for other kinds, it issues an error.
default_kind_var kv
| isLiftedTypeKind (tyVarKind kv)
= do { traceTc "Defaulting a kind var to *" (ppr kv)
; writeMetaTyVar kv liftedTypeKind
; return True }
| otherwise
= do { addErr (vcat [ text "Cannot default kind variable" <+> quotes (ppr kv')
, text "of kind:" <+> ppr (tyVarKind kv')
, text "Perhaps enable PolyKinds or add a kind signature" ])
-- We failed to default it, so return False to say so.
-- Hence, it'll get skolemised. That might seem odd, but we must either
-- promote, skolemise, or zap-to-Any, to satisfy TcHsType
-- Note [Recipe for checking a signature]
-- Otherwise we get level-number assertion failures. It doesn't matter much
-- because we are in an error situation anyway.
; return False
}
where
(_, kv') = tidyOpenTyCoVar emptyTidyEnv kv
skolemiseUnboundMetaTyVar :: TcTyVar -> TcM TyVar
-- We have a Meta tyvar with a ref-cell inside it
-- Skolemise it, so that we are totally out of Meta-tyvar-land
-- We create a skolem TcTyVar, not a regular TyVar
-- See Note [Zonking to Skolem]
skolemiseUnboundMetaTyVar tv
= ASSERT2( isMetaTyVar tv, ppr tv )
do { when debugIsOn (check_empty tv)
; here <- getSrcSpanM -- Get the location from "here"
-- ie where we are generalising
; kind <- zonkTcType (tyVarKind tv)
; let tv_name = tyVarName tv
-- See Note [Skolemising and identity]
final_name | isSystemName tv_name
= mkInternalName (nameUnique tv_name)
(nameOccName tv_name) here
| otherwise
= tv_name
final_tv = mkTcTyVar final_name kind details
; traceTc "Skolemising" (ppr tv <+> text ":=" <+> ppr final_tv)
; writeMetaTyVar tv (mkTyVarTy final_tv)
; return final_tv }
where
details = SkolemTv (metaTyVarTcLevel tv) False
check_empty tv -- [Sept 04] Check for non-empty.
= when debugIsOn $ -- See note [Silly Type Synonym]
do { cts <- readMetaTyVar tv
; case cts of
Flexi -> return ()
Indirect ty -> WARN( True, ppr tv $$ ppr ty )
return () }
{- Note [Defaulting with -XNoPolyKinds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data Compose f g a = Mk (f (g a))
We infer
Compose :: forall k1 k2. (k2 -> *) -> (k1 -> k2) -> k1 -> *
Mk :: forall k1 k2 (f :: k2 -> *) (g :: k1 -> k2) (a :: k1).
f (g a) -> Compose k1 k2 f g a
Now, in another module, we have -XNoPolyKinds -XDataKinds in effect.
What does 'Mk mean? Pre GHC-8.0 with -XNoPolyKinds,
we just defaulted all kind variables to *. But that's no good here,
because the kind variables in 'Mk aren't of kind *, so defaulting to *
is ill-kinded.
After some debate on #11334, we decided to issue an error in this case.
The code is in defaultKindVar.
Note [What is a meta variable?]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A "meta type-variable", also know as a "unification variable" is a placeholder
introduced by the typechecker for an as-yet-unknown monotype.
For example, when we see a call `reverse (f xs)`, we know that we calling
reverse :: forall a. [a] -> [a]
So we know that the argument `f xs` must be a "list of something". But what is
the "something"? We don't know until we explore the `f xs` a bit more. So we set
out what we do know at the call of `reverse` by instantiating its type with a fresh
meta tyvar, `alpha` say. So now the type of the argument `f xs`, and of the
result, is `[alpha]`. The unification variable `alpha` stands for the
as-yet-unknown type of the elements of the list.
As type inference progresses we may learn more about `alpha`. For example, suppose
`f` has the type
f :: forall b. b -> [Maybe b]
Then we instantiate `f`'s type with another fresh unification variable, say
`beta`; and equate `f`'s result type with reverse's argument type, thus
`[alpha] ~ [Maybe beta]`.
Now we can solve this equality to learn that `alpha ~ Maybe beta`, so we've
refined our knowledge about `alpha`. And so on.
If you found this Note useful, you may also want to have a look at
Section 5 of "Practical type inference for higher rank types" (Peyton Jones,
Vytiniotis, Weirich and Shields. J. Functional Programming. 2011).
Note [What is zonking?]
~~~~~~~~~~~~~~~~~~~~~~~
GHC relies heavily on mutability in the typechecker for efficient operation.
For this reason, throughout much of the type checking process meta type
variables (the MetaTv constructor of TcTyVarDetails) are represented by mutable
variables (known as TcRefs).
Zonking is the process of ripping out these mutable variables and replacing them
with a real Type. This involves traversing the entire type expression, but the
interesting part of replacing the mutable variables occurs in zonkTyVarOcc.
There are two ways to zonk a Type:
* zonkTcTypeToType, which is intended to be used at the end of type-checking
for the final zonk. It has to deal with unfilled metavars, either by filling
it with a value like Any or failing (determined by the UnboundTyVarZonker
used).
* zonkTcType, which will happily ignore unfilled metavars. This is the
appropriate function to use while in the middle of type-checking.
Note [Zonking to Skolem]
~~~~~~~~~~~~~~~~~~~~~~~~
We used to zonk quantified type variables to regular TyVars. However, this
leads to problems. Consider this program from the regression test suite:
eval :: Int -> String -> String -> String
eval 0 root actual = evalRHS 0 root actual
evalRHS :: Int -> a
evalRHS 0 root actual = eval 0 root actual
It leads to the deferral of an equality (wrapped in an implication constraint)
forall a. () => ((String -> String -> String) ~ a)
which is propagated up to the toplevel (see TcSimplify.tcSimplifyInferCheck).
In the meantime `a' is zonked and quantified to form `evalRHS's signature.
This has the *side effect* of also zonking the `a' in the deferred equality
(which at this point is being handed around wrapped in an implication
constraint).
Finally, the equality (with the zonked `a') will be handed back to the
simplifier by TcRnDriver.tcRnSrcDecls calling TcSimplify.tcSimplifyTop.
If we zonk `a' with a regular type variable, we will have this regular type
variable now floating around in the simplifier, which in many places assumes to
only see proper TcTyVars.
We can avoid this problem by zonking with a skolem TcTyVar. The
skolem is rigid (which we require for a quantified variable), but is
still a TcTyVar that the simplifier knows how to deal with.
Note [Skolemising and identity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In some places, we make a TyVarTv for a binder. E.g.
class C a where ...
As Note [Inferring kinds for type declarations] discusses,
we make a TyVarTv for 'a'. Later we skolemise it, and we'd
like to retain its identity, location info etc. (If we don't
retain its identity we'll have to do some pointless swizzling;
see TcTyClsDecls.swizzleTcTyConBndrs. If we retain its identity
but not its location we'll lose the detailed binding site info.
Conclusion: use the Name of the TyVarTv. But we don't want
to do that when skolemising random unification variables;
there the location we want is the skolemisation site.
Fortunately we can tell the difference: random unification
variables have System Names. That's why final_name is
set based on the isSystemName test.
Note [Silly Type Synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this:
type C u a = u -- Note 'a' unused
foo :: (forall a. C u a -> C u a) -> u
foo x = ...
bar :: Num u => u
bar = foo (\t -> t + t)
* From the (\t -> t+t) we get type {Num d} => d -> d
where d is fresh.
* Now unify with type of foo's arg, and we get:
{Num (C d a)} => C d a -> C d a
where a is fresh.
* Now abstract over the 'a', but float out the Num (C d a) constraint
because it does not 'really' mention a. (see exactTyVarsOfType)
The arg to foo becomes
\/\a -> \t -> t+t
* So we get a dict binding for Num (C d a), which is zonked to give
a = ()
[Note Sept 04: now that we are zonking quantified type variables
on construction, the 'a' will be frozen as a regular tyvar on
quantification, so the floated dict will still have type (C d a).
Which renders this whole note moot; happily!]
* Then the \/\a abstraction has a zonked 'a' in it.
All very silly. I think its harmless to ignore the problem. We'll end up with
a \/\a in the final result but all the occurrences of a will be zonked to ()
************************************************************************
* *
Zonking types
* *
************************************************************************
-}
zonkTcTypeAndFV :: TcType -> TcM DTyCoVarSet
-- Zonk a type and take its free variables
-- With kind polymorphism it can be essential to zonk *first*
-- so that we find the right set of free variables. Eg
-- forall k1. forall (a:k2). a
-- where k2:=k1 is in the substitution. We don't want
-- k2 to look free in this type!
zonkTcTypeAndFV ty
= tyCoVarsOfTypeDSet <$> zonkTcType ty
zonkTyCoVar :: TyCoVar -> TcM TcType
-- Works on TyVars and TcTyVars
zonkTyCoVar tv | isTcTyVar tv = zonkTcTyVar tv
| isTyVar tv = mkTyVarTy <$> zonkTyCoVarKind tv
| otherwise = ASSERT2( isCoVar tv, ppr tv )
mkCoercionTy . mkCoVarCo <$> zonkTyCoVarKind tv
-- Hackily, when typechecking type and class decls
-- we have TyVars in scope added (only) in
-- TcHsType.bindTyClTyVars, but it seems
-- painful to make them into TcTyVars there
zonkTyCoVarsAndFV :: TyCoVarSet -> TcM TyCoVarSet
zonkTyCoVarsAndFV tycovars
= tyCoVarsOfTypes <$> mapM zonkTyCoVar (nonDetEltsUniqSet tycovars)
-- It's OK to use nonDetEltsUniqSet here because we immediately forget about
-- the ordering by turning it into a nondeterministic set and the order
-- of zonking doesn't matter for determinism.
zonkDTyCoVarSetAndFV :: DTyCoVarSet -> TcM DTyCoVarSet
zonkDTyCoVarSetAndFV tycovars
= mkDVarSet <$> (zonkTyCoVarsAndFVList $ dVarSetElems tycovars)
-- Takes a list of TyCoVars, zonks them and returns a
-- deterministically ordered list of their free variables.
zonkTyCoVarsAndFVList :: [TyCoVar] -> TcM [TyCoVar]
zonkTyCoVarsAndFVList tycovars
= tyCoVarsOfTypesList <$> mapM zonkTyCoVar tycovars
zonkTcTyVars :: [TcTyVar] -> TcM [TcType]
zonkTcTyVars tyvars = mapM zonkTcTyVar tyvars
----------------- Types
zonkTyCoVarKind :: TyCoVar -> TcM TyCoVar
zonkTyCoVarKind tv = do { kind' <- zonkTcType (tyVarKind tv)
; return (setTyVarKind tv kind') }
zonkTcTypes :: [TcType] -> TcM [TcType]
zonkTcTypes tys = mapM zonkTcType tys
{-
************************************************************************
* *
Zonking constraints
* *
************************************************************************
-}
zonkImplication :: Implication -> TcM Implication
zonkImplication implic@(Implic { ic_skols = skols
, ic_given = given
, ic_wanted = wanted
, ic_info = info })
= do { skols' <- mapM zonkTyCoVarKind skols -- Need to zonk their kinds!
-- as #7230 showed
; given' <- mapM zonkEvVar given
; info' <- zonkSkolemInfo info
; wanted' <- zonkWCRec wanted
; return (implic { ic_skols = skols'
, ic_given = given'
, ic_wanted = wanted'
, ic_info = info' }) }
zonkEvVar :: EvVar -> TcM EvVar
zonkEvVar var = do { ty' <- zonkTcType (varType var)
; return (setVarType var ty') }
zonkWC :: WantedConstraints -> TcM WantedConstraints
zonkWC wc = zonkWCRec wc
zonkWCRec :: WantedConstraints -> TcM WantedConstraints
zonkWCRec (WC { wc_simple = simple, wc_impl = implic })
= do { simple' <- zonkSimples simple
; implic' <- mapBagM zonkImplication implic
; return (WC { wc_simple = simple', wc_impl = implic' }) }
zonkSimples :: Cts -> TcM Cts
zonkSimples cts = do { cts' <- mapBagM zonkCt cts
; traceTc "zonkSimples done:" (ppr cts')
; return cts' }
{- Note [zonkCt behaviour]
~~~~~~~~~~~~~~~~~~~~~~~~~~
zonkCt tries to maintain the canonical form of a Ct. For example,
- a CDictCan should stay a CDictCan;
- a CTyEqCan should stay a CTyEqCan (if the LHS stays as a variable.).
- a CHoleCan should stay a CHoleCan
- a CIrredCan should stay a CIrredCan with its cc_insol flag intact
Why?, for example:
- For CDictCan, the @TcSimplify.expandSuperClasses@ step, which runs after the
simple wanted and plugin loop, looks for @CDictCan@s. If a plugin is in use,
constraints are zonked before being passed to the plugin. This means if we
don't preserve a canonical form, @expandSuperClasses@ fails to expand
superclasses. This is what happened in #11525.
- For CHoleCan, once we forget that it's a hole, we can never recover that info.
- For CIrredCan we want to see if a constraint is insoluble with insolubleWC
NB: we do not expect to see any CFunEqCans, because zonkCt is only
called on unflattened constraints.
NB: Constraints are always re-flattened etc by the canonicaliser in
@TcCanonical@ even if they come in as CDictCan. Only canonical constraints that
are actually in the inert set carry all the guarantees. So it is okay if zonkCt
creates e.g. a CDictCan where the cc_tyars are /not/ function free.
-}
zonkCt :: Ct -> TcM Ct
zonkCt ct@(CHoleCan { cc_ev = ev })
= do { ev' <- zonkCtEvidence ev
; return $ ct { cc_ev = ev' } }
zonkCt ct@(CDictCan { cc_ev = ev, cc_tyargs = args })
= do { ev' <- zonkCtEvidence ev
; args' <- mapM zonkTcType args
; return $ ct { cc_ev = ev', cc_tyargs = args' } }
zonkCt (CTyEqCan { cc_ev = ev })
= mkNonCanonical <$> zonkCtEvidence ev
-- CTyEqCan has some delicate invariants that may be violated by
-- zonking (documented with the Ct type) , so we don't want to create
-- a CTyEqCan here. Besides, this will be canonicalized again anyway,
-- so there is very little benefit in keeping the CTyEqCan constructor.
zonkCt ct@(CIrredCan { cc_ev = ev }) -- Preserve the cc_insol flag
= do { ev' <- zonkCtEvidence ev
; return (ct { cc_ev = ev' }) }
zonkCt ct
= ASSERT( not (isCFunEqCan ct) )
-- We do not expect to see any CFunEqCans, because zonkCt is only called on
-- unflattened constraints.
do { fl' <- zonkCtEvidence (ctEvidence ct)
; return (mkNonCanonical fl') }
zonkCtEvidence :: CtEvidence -> TcM CtEvidence
zonkCtEvidence ctev@(CtGiven { ctev_pred = pred })
= do { pred' <- zonkTcType pred
; return (ctev { ctev_pred = pred'}) }
zonkCtEvidence ctev@(CtWanted { ctev_pred = pred, ctev_dest = dest })
= do { pred' <- zonkTcType pred
; let dest' = case dest of
EvVarDest ev -> EvVarDest $ setVarType ev pred'
-- necessary in simplifyInfer
HoleDest h -> HoleDest h
; return (ctev { ctev_pred = pred', ctev_dest = dest' }) }
zonkCtEvidence ctev@(CtDerived { ctev_pred = pred })
= do { pred' <- zonkTcType pred
; return (ctev { ctev_pred = pred' }) }
zonkSkolemInfo :: SkolemInfo -> TcM SkolemInfo
zonkSkolemInfo (SigSkol cx ty tv_prs) = do { ty' <- zonkTcType ty
; return (SigSkol cx ty' tv_prs) }
zonkSkolemInfo (InferSkol ntys) = do { ntys' <- mapM do_one ntys
; return (InferSkol ntys') }
where
do_one (n, ty) = do { ty' <- zonkTcType ty; return (n, ty') }
zonkSkolemInfo skol_info = return skol_info
{-
%************************************************************************
%* *
\subsection{Zonking -- the main work-horses: zonkTcType, zonkTcTyVar}
* *
* For internal use only! *
* *
************************************************************************
-}
-- zonkId is used *during* typechecking just to zonk the Id's type
zonkId :: TcId -> TcM TcId
zonkId id
= do { ty' <- zonkTcType (idType id)
; return (Id.setIdType id ty') }
zonkCoVar :: CoVar -> TcM CoVar
zonkCoVar = zonkId
-- | A suitable TyCoMapper for zonking a type during type-checking,
-- before all metavars are filled in.
zonkTcTypeMapper :: TyCoMapper () TcM
zonkTcTypeMapper = TyCoMapper
{ tcm_tyvar = const zonkTcTyVar
, tcm_covar = const (\cv -> mkCoVarCo <$> zonkTyCoVarKind cv)
, tcm_hole = hole
, tcm_tycobinder = \_env tv _vis -> ((), ) <$> zonkTyCoVarKind tv
, tcm_tycon = zonkTcTyCon }
where
hole :: () -> CoercionHole -> TcM Coercion
hole _ hole@(CoercionHole { ch_ref = ref, ch_co_var = cv })
= do { contents <- readTcRef ref
; case contents of
Just co -> do { co' <- zonkCo co
; checkCoercionHole cv co' }
Nothing -> do { cv' <- zonkCoVar cv
; return $ HoleCo (hole { ch_co_var = cv' }) } }
zonkTcTyCon :: TcTyCon -> TcM TcTyCon
-- Only called on TcTyCons
-- A non-poly TcTyCon may have unification
-- variables that need zonking, but poly ones cannot
zonkTcTyCon tc
| tcTyConIsPoly tc = return tc
| otherwise = do { tck' <- zonkTcType (tyConKind tc)
; return (setTcTyConKind tc tck') }
-- For unbound, mutable tyvars, zonkType uses the function given to it
-- For tyvars bound at a for-all, zonkType zonks them to an immutable
-- type variable and zonks the kind too
zonkTcType :: TcType -> TcM TcType
zonkTcType = mapType zonkTcTypeMapper ()
-- | "Zonk" a coercion -- really, just zonk any types in the coercion
zonkCo :: Coercion -> TcM Coercion
zonkCo = mapCoercion zonkTcTypeMapper ()
zonkTcTyVar :: TcTyVar -> TcM TcType
-- Simply look through all Flexis
zonkTcTyVar tv
| isTcTyVar tv
= case tcTyVarDetails tv of
SkolemTv {} -> zonk_kind_and_return
RuntimeUnk {} -> zonk_kind_and_return
MetaTv { mtv_ref = ref }
-> do { cts <- readMutVar ref
; case cts of
Flexi -> zonk_kind_and_return
Indirect ty -> do { zty <- zonkTcType ty
; writeTcRef ref (Indirect zty)
-- See Note [Sharing in zonking]
; return zty } }
| otherwise -- coercion variable
= zonk_kind_and_return
where
zonk_kind_and_return = do { z_tv <- zonkTyCoVarKind tv
; return (mkTyVarTy z_tv) }
-- Variant that assumes that any result of zonking is still a TyVar.
-- Should be used only on skolems and TyVarTvs
zonkTcTyVarToTyVar :: HasDebugCallStack => TcTyVar -> TcM TcTyVar
zonkTcTyVarToTyVar tv
= do { ty <- zonkTcTyVar tv
; let tv' = case tcGetTyVar_maybe ty of
Just tv' -> tv'
Nothing -> pprPanic "zonkTcTyVarToTyVar"
(ppr tv $$ ppr ty)
; return tv' }
zonkTyVarTyVarPairs :: [(Name,TcTyVar)] -> TcM [(Name,TcTyVar)]
zonkTyVarTyVarPairs prs
= mapM do_one prs
where
do_one (nm, tv) = do { tv' <- zonkTcTyVarToTyVar tv
; return (nm, tv') }
{- Note [Sharing in zonking]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
alpha :-> beta :-> gamma :-> ty
where the ":->" means that the unification variable has been
filled in with Indirect. Then when zonking alpha, it'd be nice
to short-circuit beta too, so we end up with
alpha :-> zty
beta :-> zty
gamma :-> zty
where zty is the zonked version of ty. That way, if we come across
beta later, we'll have less work to do. (And indeed the same for
alpha.)
This is easily achieved: just overwrite (Indirect ty) with (Indirect
zty). Non-systematic perf comparisons suggest that this is a modest
win.
But c.f Note [Sharing when zonking to Type] in TcHsSyn.
%************************************************************************
%* *
Tidying
* *
************************************************************************
-}
zonkTidyTcType :: TidyEnv -> TcType -> TcM (TidyEnv, TcType)
zonkTidyTcType env ty = do { ty' <- zonkTcType ty
; return (tidyOpenType env ty') }
zonkTidyTcTypes :: TidyEnv -> [TcType] -> TcM (TidyEnv, [TcType])
zonkTidyTcTypes = zonkTidyTcTypes' []
where zonkTidyTcTypes' zs env [] = return (env, reverse zs)
zonkTidyTcTypes' zs env (ty:tys)
= do { (env', ty') <- zonkTidyTcType env ty
; zonkTidyTcTypes' (ty':zs) env' tys }
zonkTidyOrigin :: TidyEnv -> CtOrigin -> TcM (TidyEnv, CtOrigin)
zonkTidyOrigin env (GivenOrigin skol_info)
= do { skol_info1 <- zonkSkolemInfo skol_info
; let skol_info2 = tidySkolemInfo env skol_info1
; return (env, GivenOrigin skol_info2) }
zonkTidyOrigin env orig@(TypeEqOrigin { uo_actual = act
, uo_expected = exp })
= do { (env1, act') <- zonkTidyTcType env act
; (env2, exp') <- zonkTidyTcType env1 exp
; return ( env2, orig { uo_actual = act'
, uo_expected = exp' }) }
zonkTidyOrigin env (KindEqOrigin ty1 m_ty2 orig t_or_k)
= do { (env1, ty1') <- zonkTidyTcType env ty1
; (env2, m_ty2') <- case m_ty2 of
Just ty2 -> second Just <$> zonkTidyTcType env1 ty2
Nothing -> return (env1, Nothing)
; (env3, orig') <- zonkTidyOrigin env2 orig
; return (env3, KindEqOrigin ty1' m_ty2' orig' t_or_k) }
zonkTidyOrigin env (FunDepOrigin1 p1 o1 l1 p2 o2 l2)
= do { (env1, p1') <- zonkTidyTcType env p1
; (env2, p2') <- zonkTidyTcType env1 p2
; return (env2, FunDepOrigin1 p1' o1 l1 p2' o2 l2) }
zonkTidyOrigin env (FunDepOrigin2 p1 o1 p2 l2)
= do { (env1, p1') <- zonkTidyTcType env p1
; (env2, p2') <- zonkTidyTcType env1 p2
; (env3, o1') <- zonkTidyOrigin env2 o1
; return (env3, FunDepOrigin2 p1' o1' p2' l2) }
zonkTidyOrigin env orig = return (env, orig)
----------------
tidyCt :: TidyEnv -> Ct -> Ct
-- Used only in error reporting
-- Also converts it to non-canonical
tidyCt env ct
= case ct of
CHoleCan { cc_ev = ev }
-> ct { cc_ev = tidy_ev env ev }
_ -> mkNonCanonical (tidy_ev env (ctEvidence ct))
where
tidy_ev :: TidyEnv -> CtEvidence -> CtEvidence
-- NB: we do not tidy the ctev_evar field because we don't
-- show it in error messages
tidy_ev env ctev@(CtGiven { ctev_pred = pred })
= ctev { ctev_pred = tidyType env pred }
tidy_ev env ctev@(CtWanted { ctev_pred = pred })
= ctev { ctev_pred = tidyType env pred }
tidy_ev env ctev@(CtDerived { ctev_pred = pred })
= ctev { ctev_pred = tidyType env pred }
----------------
tidyEvVar :: TidyEnv -> EvVar -> EvVar
tidyEvVar env var = setVarType var (tidyType env (varType var))
----------------
tidySkolemInfo :: TidyEnv -> SkolemInfo -> SkolemInfo
tidySkolemInfo env (DerivSkol ty) = DerivSkol (tidyType env ty)
tidySkolemInfo env (SigSkol cx ty tv_prs) = tidySigSkol env cx ty tv_prs
tidySkolemInfo env (InferSkol ids) = InferSkol (mapSnd (tidyType env) ids)
tidySkolemInfo env (UnifyForAllSkol ty) = UnifyForAllSkol (tidyType env ty)
tidySkolemInfo _ info = info
tidySigSkol :: TidyEnv -> UserTypeCtxt
-> TcType -> [(Name,TcTyVar)] -> SkolemInfo
-- We need to take special care when tidying SigSkol
-- See Note [SigSkol SkolemInfo] in Origin
tidySigSkol env cx ty tv_prs
= SigSkol cx (tidy_ty env ty) tv_prs'
where
tv_prs' = mapSnd (tidyTyCoVarOcc env) tv_prs
inst_env = mkNameEnv tv_prs'
tidy_ty env (ForAllTy (Bndr tv vis) ty)
= ForAllTy (Bndr tv' vis) (tidy_ty env' ty)
where
(env', tv') = tidy_tv_bndr env tv
tidy_ty env ty@(FunTy _ arg res)
= ty { ft_arg = tidyType env arg, ft_res = tidy_ty env res }
tidy_ty env ty = tidyType env ty
tidy_tv_bndr :: TidyEnv -> TyCoVar -> (TidyEnv, TyCoVar)
tidy_tv_bndr env@(occ_env, subst) tv
| Just tv' <- lookupNameEnv inst_env (tyVarName tv)
= ((occ_env, extendVarEnv subst tv tv'), tv')
| otherwise
= tidyVarBndr env tv
-------------------------------------------------------------------------
{-
%************************************************************************
%* *
Levity polymorphism checks
* *
*************************************************************************
See Note [Levity polymorphism checking] in DsMonad
-}
-- | According to the rules around representation polymorphism
-- (see https://gitlab.haskell.org/ghc/ghc/wikis/no-sub-kinds), no binder
-- can have a representation-polymorphic type. This check ensures
-- that we respect this rule. It is a bit regrettable that this error
-- occurs in zonking, after which we should have reported all errors.
-- But it's hard to see where else to do it, because this can be discovered
-- only after all solving is done. And, perhaps most importantly, this
-- isn't really a compositional property of a type system, so it's
-- not a terrible surprise that the check has to go in an awkward spot.
ensureNotLevPoly :: Type -- its zonked type
-> SDoc -- where this happened
-> TcM ()
ensureNotLevPoly ty doc
= whenNoErrs $ -- sometimes we end up zonking bogus definitions of type
-- forall a. a. See, for example, test ghci/scripts/T9140
checkForLevPoly doc ty
-- See Note [Levity polymorphism checking] in DsMonad
checkForLevPoly :: SDoc -> Type -> TcM ()
checkForLevPoly = checkForLevPolyX addErr
checkForLevPolyX :: Monad m
=> (SDoc -> m ()) -- how to report an error
-> SDoc -> Type -> m ()
checkForLevPolyX add_err extra ty
| isTypeLevPoly ty
= add_err (formatLevPolyErr ty $$ extra)
| otherwise
= return ()
formatLevPolyErr :: Type -- levity-polymorphic type
-> SDoc
formatLevPolyErr ty
= hang (text "A levity-polymorphic type is not allowed here:")
2 (vcat [ text "Type:" <+> pprWithTYPE tidy_ty
, text "Kind:" <+> pprWithTYPE tidy_ki ])
where
(tidy_env, tidy_ty) = tidyOpenType emptyTidyEnv ty
tidy_ki = tidyType tidy_env (tcTypeKind ty)
{-
%************************************************************************
%* *
Error messages
* *
*************************************************************************
-}
-- See Note [Naughty quantification candidates]
naughtyQuantification :: TcType -- original type user wanted to quantify
-> TcTyVar -- naughty var
-> TyVarSet -- skolems that would escape
-> TcM a
naughtyQuantification orig_ty tv escapees
= do { orig_ty1 <- zonkTcType orig_ty -- in case it's not zonked
; escapees' <- mapM zonkTcTyVarToTyVar $
nonDetEltsUniqSet escapees
-- we'll just be printing, so no harmful non-determinism
; let fvs = tyCoVarsOfTypeWellScoped orig_ty1
env0 = tidyFreeTyCoVars emptyTidyEnv fvs
env = env0 `delTidyEnvList` escapees'
-- this avoids gratuitous renaming of the escaped
-- variables; very confusing to users!
orig_ty' = tidyType env orig_ty1
ppr_tidied = pprTyVars . map (tidyTyCoVarOcc env)
doc = pprWithExplicitKindsWhen True $
vcat [ sep [ text "Cannot generalise type; skolem" <> plural escapees'
, quotes $ ppr_tidied escapees'
, text "would escape" <+> itsOrTheir escapees' <+> text "scope"
]
, sep [ text "if I tried to quantify"
, ppr_tidied [tv]
, text "in this type:"
]
, nest 2 (pprTidiedType orig_ty')
, text "(Indeed, I sometimes struggle even printing this correctly,"
, text " due to its ill-scoped nature.)"
]
; failWithTcM (env, doc) }
| sdiehl/ghc | compiler/typecheck/TcMType.hs | bsd-3-clause | 99,058 | 37 | 21 | 26,080 | 14,883 | 7,827 | 7,056 | -1 | -1 |
-------------------------------------------------------------------------------
-- |
-- Module : Environments.Blackjack
-- Copyright : (c) Sam Stites 2017
-- License : BSD3
-- Maintainer: sam@stites.io
-- Stability : experimental
-- Portability: non-portable
--
-- Simple blackjack environment
--
-- Blackjack is a card game where the goal is to obtain cards that sum to as
-- near as possible to 21 without going over. They're playing against a fixed
-- dealer.
-- Face cards (Jack, Queen, King) have point value 10.
-- Aces can either count as 11 or 1, and it's called 'usable' at 11.
-- This game is placed with an infinite deck (or with replacement).
-- The game starts with each (player and dealer) having one face up and one
-- face down card.
-- The player can request additional cards (hit=1) until they decide to stop
-- (stick=0) or exceed 21 (bust).
-- After the player sticks, the dealer reveals their facedown card, and draws
-- until their sum is 17 or greater. If the dealer goes bust the player wins.
-- If neither player nor dealer busts, the outcome (win, lose, draw) is
-- decided by whose sum is closer to 21. The reward for winning is +1,
-- drawing is 0, and losing is -1.
-- The observation of a 3-tuple of: the players current sum,
-- the dealer's one showing card (1-10 where 1 is ace),
-- and whether or not the player holds a usable ace (0 or 1).
-- This environment corresponds to the version of the blackjack problem
-- described in Example 5.1 in Reinforcement Learning: An Introduction
-- by Sutton and Barto (1998).
-- http://incompleteideas.net/sutton/book/the-book.html
-------------------------------------------------------------------------------
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
module Environments.Blackjack where
import Control.MonadEnv
import GHC.Generics (Generic)
import System.Random.MWC (Seed, save, restore, GenIO, uniformR)
import Data.Hashable (Hashable)
import Data.HashSet (HashSet)
import Control.Monad.State.Strict
import qualified Data.HashSet as HS
data Action = Stay | Hit
data Hand
= Start (Card, Card)
| Extended Card Hand
instance Eq Hand where
a == b = asSet a == asSet b
instance Ord Hand where
compare a b =
case (va > vb, va < vb) of
(False, True) -> LT
(True, False) -> GT
_ -> EQ
where
(va, vb) = (score a, score b)
asSet :: Hand -> HashSet Card
asSet = HS.fromList . asList
asList :: Hand -> [Card]
asList = \case
Start (a, b) -> [a, b]
Extended c h -> c:asList h
first :: Hand -> Card
first (Start (a, _)) = a
first (Extended a _) = a
data Card
= Ace
| C2
| C3
| C4
| C5
| C6
| C7
| C8
| C9
| C10
| Jack
| Queen
| King
deriving stock (Eq, Show, Enum, Bounded, Generic)
deriving anyclass (Hashable)
value :: Card -> Int
value c
| fromEnum c > 10 = 10
| otherwise = fromEnum c
-- 1 = Ace, 2-10 = Number cards, Jack/Queen/King = 10
deck :: [Card]
deck = [minBound .. maxBound]
drawCard :: GenIO -> IO Card
drawCard g = toEnum <$> uniformR (value (minBound::Card), value (maxBound::Card)) g
drawHand :: GenIO -> IO (Card, Card)
drawHand g = (,) <$> drawCard g <*> drawCard g
-- Does this hand have a usable ace?
usableAce :: Hand -> Bool
usableAce h = Ace `elem` cs && sum (fmap value cs) <= 21
where
cs = asList h
-- Return current hand total
sumHand :: Hand -> Int
sumHand h = sum (value <$> asList h) + (if usableAce h then 10 else 0)
isBust :: Hand -> Bool
isBust h = sumHand h > 21
score :: Hand -> Int
score h =
if isBust h
then 0
else sumHand h
isNatural :: Hand -> Bool
isNatural = \case
Start (Ace, C10) -> True
Start (C10, Ace) -> True
_ -> False
newtype BlackJack x = BlackJack (StateT (Seed, Hand, Hand) IO x)
deriving stock (Functor)
deriving newtype (Applicative, Monad, MonadIO, MonadState (Seed, Hand, Hand))
instance MonadEnv BlackJack (Hand, Card) Action Float where
-- slightly redundant but this lets us reset as many times as we want.
reset = do
( _, d) <- lifted (fmap Start . drawHand)
(s', h) <- lifted (fmap Start . drawHand)
put (s', d, h)
pure $ Initial (h, first d)
step Hit = do
(_, d, h) <- get
(s', h') <- lifted (fmap (`Extended` h) . drawCard)
put (s', d, h')
if isBust h'
then pure $ Done (-1) Nothing
else pure $ Next 0 (h', first d)
step Stay = do
(_, d, h) <- get
(s', d') <- lifted (`rollout` d)
let r = fromEnum $ compare (score d') (score h)
put (s', d', h)
if isNatural d && isNatural h && r == 1
then pure $ Done 1.5 Nothing
else pure $ Done (fromIntegral r) Nothing
where
rollout :: GenIO -> Hand -> IO Hand
rollout g h =
if sumHand h < 17
then drawCard g >>= \c -> rollout g (Extended c h)
else pure h
lifted :: (GenIO -> IO x) -> BlackJack (Seed, x)
lifted randact = do
(s, _, _) <- get
g <- liftIO $ restore s
x <- liftIO $ randact g
s' <- liftIO $ save g
pure (s', x)
| stites/reinforce | reinforce-environments/src/Environments/Blackjack.hs | bsd-3-clause | 5,184 | 0 | 14 | 1,172 | 1,463 | 800 | 663 | -1 | -1 |
module Data.Hexagon.RangeSpec where
import SpecHelper
spec :: Spec
spec = do
describe "Data.Hexagon.Range" $ do
context "context" $ do
it "does something" $ do
True `shouldBe` True
main :: IO ()
main = hspec spec
| alios/hexagon | test/Data/Hexagon/RangeSpec.hs | bsd-3-clause | 246 | 0 | 16 | 68 | 77 | 39 | 38 | 10 | 1 |
module Sample2 where
-- start snippet animals
data Animal = Dog | Cat
isAfraidOf :: Animal -> Animal -> Bool
isAfraidOf Cat Dog = True
isAfraidOf _ _ = False
-- end snippet animals
result :: Bool
result = Dog `isAfraidOf` Cat
| owickstrom/owickstrom.github.io | blog/src/_posts/pandoc-beamer-examples/Sample2.hs | mit | 233 | 0 | 6 | 49 | 65 | 38 | 27 | 7 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE CPP #-}
-- | HTTP over TLS support for Warp via the TLS package.
--
-- If HTTP\/2 is negotiated by ALPN, HTTP\/2 over TLS is used.
-- Otherwise HTTP\/1.1 over TLS is used.
--
-- Support for SSL is now obsoleted.
module Network.Wai.Handler.WarpTLS (
-- * Settings
TLSSettings
, defaultTlsSettings
-- * Smart constructors
, tlsSettings
, tlsSettingsMemory
, tlsSettingsChain
, tlsSettingsChainMemory
-- * Accessors
, certFile
, keyFile
, tlsLogging
, tlsAllowedVersions
, tlsCiphers
, tlsWantClientCert
, tlsServerHooks
, onInsecure
, OnInsecure (..)
-- * Runner
, runTLS
, runTLSSocket
-- * Exception
, WarpTLSException (..)
) where
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>))
#endif
import Control.Applicative ((<|>))
import Control.Exception (Exception, throwIO, bracket, finally, handle, fromException, try, IOException, onException, SomeException(..))
import qualified Control.Exception as E
import Control.Monad (void)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Default.Class (def)
import qualified Data.IORef as I
import Data.Streaming.Network (bindPortTCP, safeRecv)
import Data.Typeable (Typeable)
import Network.Socket (Socket, sClose, withSocketsDo, SockAddr, accept)
import Network.Socket.ByteString (sendAll)
import qualified Network.TLS as TLS
import qualified Network.TLS.Extra as TLSExtra
import Network.Wai (Application)
import Network.Wai.Handler.Warp
import Network.Wai.Handler.Warp.Internal
import System.IO.Error (isEOFError)
----------------------------------------------------------------
-- | Settings for WarpTLS.
data TLSSettings = TLSSettings {
certFile :: FilePath
-- ^ File containing the certificate.
, chainCertFiles :: [FilePath]
-- ^ Files containing chain certificates.
, keyFile :: FilePath
-- ^ File containing the key
, certMemory :: Maybe S.ByteString
, chainCertsMemory :: [S.ByteString]
, keyMemory :: Maybe S.ByteString
, onInsecure :: OnInsecure
-- ^ Do we allow insecure connections with this server as well?
--
-- >>> onInsecure defaultTlsSettings
-- DenyInsecure "This server only accepts secure HTTPS connections."
--
-- Since 1.4.0
, tlsLogging :: TLS.Logging
-- ^ The level of logging to turn on.
--
-- Default: 'TLS.defaultLogging'.
--
-- Since 1.4.0
, tlsAllowedVersions :: [TLS.Version]
-- ^ The TLS versions this server accepts.
--
-- >>> tlsAllowedVersions defaultTlsSettings
-- [TLS12,TLS11,TLS10]
--
-- Since 1.4.2
, tlsCiphers :: [TLS.Cipher]
-- ^ The TLS ciphers this server accepts.
--
-- >>> tlsCiphers defaultTlsSettings
-- [ECDHE-RSA-AES128GCM-SHA256,DHE-RSA-AES128GCM-SHA256,DHE-RSA-AES256-SHA256,DHE-RSA-AES128-SHA256,DHE-RSA-AES256-SHA1,DHE-RSA-AES128-SHA1,DHE-DSA-AES128-SHA1,DHE-DSA-AES256-SHA1,RSA-aes128-sha1,RSA-aes256-sha1]
--
-- Since 1.4.2
, tlsWantClientCert :: Bool
-- ^ Whether or not to demand a certificate from the client. If this
-- is set to True, you must handle received certificates in a server hook
-- or all connections will fail.
--
-- >>> tlsWantClientCert defaultTlsSettings
-- False
--
-- Since 3.0.2
, tlsServerHooks :: TLS.ServerHooks
-- ^ The server-side hooks called by the tls package, including actions
-- to take when a client certificate is received. See the "Network.TLS"
-- module for details.
--
-- Default: def
--
-- Since 3.0.2
}
-- | Default 'TLSSettings'. Use this to create 'TLSSettings' with the field record name (aka accessors).
defaultTlsSettings :: TLSSettings
defaultTlsSettings = TLSSettings {
certFile = "certificate.pem"
, chainCertFiles = []
, keyFile = "key.pem"
, certMemory = Nothing
, chainCertsMemory = []
, keyMemory = Nothing
, onInsecure = DenyInsecure "This server only accepts secure HTTPS connections."
, tlsLogging = def
, tlsAllowedVersions = [TLS.TLS12,TLS.TLS11,TLS.TLS10]
, tlsCiphers = ciphers
, tlsWantClientCert = False
, tlsServerHooks = def
}
-- taken from stunnel example in tls-extra
ciphers :: [TLS.Cipher]
ciphers =
[ TLSExtra.cipher_ECDHE_RSA_AES128GCM_SHA256
, TLSExtra.cipher_ECDHE_RSA_AES128CBC_SHA256
, TLSExtra.cipher_ECDHE_RSA_AES128CBC_SHA
, TLSExtra.cipher_DHE_RSA_AES128GCM_SHA256
, TLSExtra.cipher_DHE_RSA_AES256_SHA256
, TLSExtra.cipher_DHE_RSA_AES128_SHA256
, TLSExtra.cipher_DHE_RSA_AES256_SHA1
, TLSExtra.cipher_DHE_RSA_AES128_SHA1
, TLSExtra.cipher_DHE_DSS_AES128_SHA1
, TLSExtra.cipher_DHE_DSS_AES256_SHA1
, TLSExtra.cipher_AES128_SHA1
, TLSExtra.cipher_AES256_SHA1
]
----------------------------------------------------------------
-- | An action when a plain HTTP comes to HTTP over TLS/SSL port.
data OnInsecure = DenyInsecure L.ByteString
| AllowInsecure
deriving (Show)
----------------------------------------------------------------
-- | A smart constructor for 'TLSSettings' based on 'defaultTlsSettings'.
tlsSettings :: FilePath -- ^ Certificate file
-> FilePath -- ^ Key file
-> TLSSettings
tlsSettings cert key = defaultTlsSettings {
certFile = cert
, keyFile = key
}
-- | A smart constructor for 'TLSSettings' that allows specifying
-- chain certificates based on 'defaultTlsSettings'.
--
-- Since 3.0.3
tlsSettingsChain
:: FilePath -- ^ Certificate file
-> [FilePath] -- ^ Chain certificate files
-> FilePath -- ^ Key file
-> TLSSettings
tlsSettingsChain cert chainCerts key = defaultTlsSettings {
certFile = cert
, chainCertFiles = chainCerts
, keyFile = key
}
-- | A smart constructor for 'TLSSettings', but uses in-memory representations
-- of the certificate and key based on 'defaultTlsSettings'.
--
-- Since 3.0.1
tlsSettingsMemory
:: S.ByteString -- ^ Certificate bytes
-> S.ByteString -- ^ Key bytes
-> TLSSettings
tlsSettingsMemory cert key = defaultTlsSettings
{ certMemory = Just cert
, keyMemory = Just key
}
-- | A smart constructor for 'TLSSettings', but uses in-memory representations
-- of the certificate and key based on 'defaultTlsSettings'.
--
-- Since 3.0.3
tlsSettingsChainMemory
:: S.ByteString -- ^ Certificate bytes
-> [S.ByteString] -- ^ Chain certificate bytes
-> S.ByteString -- ^ Key bytes
-> TLSSettings
tlsSettingsChainMemory cert chainCerts key = defaultTlsSettings
{ certMemory = Just cert
, chainCertsMemory = chainCerts
, keyMemory = Just key
}
----------------------------------------------------------------
-- | Running 'Application' with 'TLSSettings' and 'Settings'.
runTLS :: TLSSettings -> Settings -> Application -> IO ()
runTLS tset set app = withSocketsDo $
bracket
(bindPortTCP (getPort set) (getHost set))
sClose
(\sock -> runTLSSocket tset set sock app)
----------------------------------------------------------------
-- | Running 'Application' with 'TLSSettings' and 'Settings' using
-- specified 'Socket'.
runTLSSocket :: TLSSettings -> Settings -> Socket -> Application -> IO ()
runTLSSocket tlsset@TLSSettings{..} set sock app = do
credential <- case (certMemory, keyMemory) of
(Nothing, Nothing) ->
either error id <$>
TLS.credentialLoadX509Chain certFile chainCertFiles keyFile
(mcert, mkey) -> do
cert <- maybe (S.readFile certFile) return mcert
key <- maybe (S.readFile keyFile) return mkey
either error return $
TLS.credentialLoadX509ChainFromMemory cert chainCertsMemory key
runTLSSocket' tlsset set credential sock app
runTLSSocket' :: TLSSettings -> Settings -> TLS.Credential -> Socket -> Application -> IO ()
runTLSSocket' tlsset@TLSSettings{..} set credential sock app =
runSettingsConnectionMakerSecure set get app
where
get = getter tlsset sock params
params = def { -- TLS.ServerParams
TLS.serverWantClientCert = tlsWantClientCert
, TLS.serverCACertificates = []
, TLS.serverDHEParams = Nothing
, TLS.serverHooks = hooks
, TLS.serverShared = shared
, TLS.serverSupported = supported
}
-- Adding alpn to user's tlsServerHooks.
hooks = tlsServerHooks {
TLS.onALPNClientSuggest = TLS.onALPNClientSuggest tlsServerHooks <|>
(if settingsHTTP2Enabled set then Just alpn else Nothing)
}
shared = def {
TLS.sharedCredentials = TLS.Credentials [credential]
}
supported = def { -- TLS.Supported
TLS.supportedVersions = tlsAllowedVersions
, TLS.supportedCiphers = tlsCiphers
, TLS.supportedCompressions = [TLS.nullCompression]
, TLS.supportedHashSignatures = [
-- Safari 8 and go tls have bugs on SHA 512 and SHA 384.
-- So, we don't specify them here at this moment.
(TLS.HashSHA256, TLS.SignatureRSA)
, (TLS.HashSHA224, TLS.SignatureRSA)
, (TLS.HashSHA1, TLS.SignatureRSA)
, (TLS.HashSHA1, TLS.SignatureDSS)
]
, TLS.supportedSecureRenegotiation = True
, TLS.supportedClientInitiatedRenegotiation = False
, TLS.supportedSession = True
, TLS.supportedFallbackScsv = True
}
alpn :: [S.ByteString] -> IO S.ByteString
alpn xs
| "h2" `elem` xs = return "h2"
| "h2-16" `elem` xs = return "h2-16"
| "h2-15" `elem` xs = return "h2-15"
| "h2-14" `elem` xs = return "h2-14"
| otherwise = return "http/1.1"
----------------------------------------------------------------
getter :: TLS.TLSParams params => TLSSettings -> Socket -> params -> IO (IO (Connection, Transport), SockAddr)
getter tlsset@TLSSettings{..} sock params = do
(s, sa) <- accept sock
return (mkConn tlsset s params, sa)
mkConn :: TLS.TLSParams params => TLSSettings -> Socket -> params -> IO (Connection, Transport)
mkConn tlsset s params = do
firstBS <- safeRecv s 4096
(if not (S.null firstBS) && S.head firstBS == 0x16 then
httpOverTls tlsset s firstBS params
else
plainHTTP tlsset s firstBS) `onException` sClose s
----------------------------------------------------------------
httpOverTls :: TLS.TLSParams params => TLSSettings -> Socket -> S.ByteString -> params -> IO (Connection, Transport)
httpOverTls TLSSettings{..} s bs0 params = do
recvN <- makePlainReceiveN s bs0
ctx <- TLS.contextNew (backend recvN) params
TLS.contextHookSetLogging ctx tlsLogging
TLS.handshake ctx
writeBuf <- allocateBuffer bufferSize
-- Creating a cache for leftover input data.
ref <- I.newIORef ""
tls <- getTLSinfo ctx
return (conn ctx writeBuf ref, tls)
where
backend recvN = TLS.Backend {
TLS.backendFlush = return ()
, TLS.backendClose = sClose s
, TLS.backendSend = sendAll' s
, TLS.backendRecv = recvN
}
sendAll' sock bs = sendAll sock bs `E.catch` \(SomeException _) ->
throwIO ConnectionClosedByPeer
conn ctx writeBuf ref = Connection {
connSendMany = TLS.sendData ctx . L.fromChunks
, connSendAll = sendall
, connSendFile = sendfile
, connClose = close
, connRecv = recv ref
, connRecvBuf = recvBuf ref
, connWriteBuffer = writeBuf
, connBufferSize = bufferSize
}
where
sendall = TLS.sendData ctx . L.fromChunks . return
sendfile fid offset len hook headers =
readSendFile writeBuf bufferSize sendall fid offset len hook headers
close = freeBuffer writeBuf `finally`
void (tryIO $ TLS.bye ctx) `finally`
TLS.contextClose ctx
-- TLS version of recv with a cache for leftover input data.
-- The cache is shared with recvBuf.
recv cref = do
cached <- I.readIORef cref
if cached /= "" then do
I.writeIORef cref ""
return cached
else
recv'
-- TLS version of recv (decrypting) without a cache.
recv' = handle onEOF go
where
onEOF e
| Just TLS.Error_EOF <- fromException e = return S.empty
| Just ioe <- fromException e, isEOFError ioe = return S.empty | otherwise = throwIO e
go = do
x <- TLS.recvData ctx
if S.null x then
go
else
return x
-- TLS version of recvBuf with a cache for leftover input data.
recvBuf cref buf siz = do
cached <- I.readIORef cref
(ret, leftover) <- fill cached buf siz recv'
I.writeIORef cref leftover
return ret
fill :: S.ByteString -> Buffer -> BufSize -> Recv -> IO (Bool,S.ByteString)
fill bs0 buf0 siz0 recv
| siz0 <= len0 = do
let (bs, leftover) = S.splitAt siz0 bs0
void $ copy buf0 bs
return (True, leftover)
| otherwise = do
buf <- copy buf0 bs0
loop buf (siz0 - len0)
where
len0 = S.length bs0
loop _ 0 = return (True, "")
loop buf siz = do
bs <- recv
let len = S.length bs
if len == 0 then return (False, "")
else if (len <= siz) then do
buf' <- copy buf bs
loop buf' (siz - len)
else do
let (bs1,bs2) = S.splitAt siz bs
void $ copy buf bs1
return (True, bs2)
getTLSinfo :: TLS.Context -> IO Transport
getTLSinfo ctx = do
proto <- TLS.getNegotiatedProtocol ctx
minfo <- TLS.contextGetInformation ctx
case minfo of
Nothing -> return TCP
Just TLS.Information{..} -> do
let (major, minor) = case infoVersion of
TLS.SSL2 -> (2,0)
TLS.SSL3 -> (3,0)
TLS.TLS10 -> (3,1)
TLS.TLS11 -> (3,2)
TLS.TLS12 -> (3,3)
return TLS {
tlsMajorVersion = major
, tlsMinorVersion = minor
, tlsNegotiatedProtocol = proto
, tlsChiperID = TLS.cipherID infoCipher
}
tryIO :: IO a -> IO (Either IOException a)
tryIO = try
----------------------------------------------------------------
plainHTTP :: TLSSettings -> Socket -> S.ByteString -> IO (Connection, Transport)
plainHTTP TLSSettings{..} s bs0 = case onInsecure of
AllowInsecure -> do
conn' <- socketConnection s
cachedRef <- I.newIORef bs0
let conn'' = conn'
{ connRecv = recvPlain cachedRef (connRecv conn')
}
return (conn'', TCP)
DenyInsecure lbs -> do
-- FIXME: what about HTTP/2?
-- http://tools.ietf.org/html/rfc2817#section-4.2
sendAll s "HTTP/1.1 426 Upgrade Required\
\r\nUpgrade: TLS/1.0, HTTP/1.1\
\r\nConnection: Upgrade\
\r\nContent-Type: text/plain\r\n\r\n"
mapM_ (sendAll s) $ L.toChunks lbs
sClose s
throwIO InsecureConnectionDenied
----------------------------------------------------------------
-- | Modify the given receive function to first check the given @IORef@ for a
-- chunk of data. If present, takes the chunk of data from the @IORef@ and
-- empties out the @IORef@. Otherwise, calls the supplied receive function.
recvPlain :: I.IORef S.ByteString -> IO S.ByteString -> IO S.ByteString
recvPlain ref fallback = do
bs <- I.readIORef ref
if S.null bs
then fallback
else do
I.writeIORef ref S.empty
return bs
----------------------------------------------------------------
data WarpTLSException = InsecureConnectionDenied
deriving (Show, Typeable)
instance Exception WarpTLSException
| erikd/wai | warp-tls/Network/Wai/Handler/WarpTLS.hs | mit | 16,245 | 0 | 18 | 4,240 | 3,352 | 1,835 | 1,517 | 302 | 6 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeApplications #-}
module Main where
import Control.Applicative (empty)
import Control.Concurrent (threadDelay)
import Control.Exception (throwIO)
import Control.Exception.Safe (throwString)
import Control.Monad (unless)
import Data.Functor.Contravariant (contramap)
import Data.Text (Text)
import GHC.IO.Encoding (setLocaleEncoding, utf8)
import Options.Applicative.Simple (simpleOptions)
import System.Random (mkStdGen)
import Bench.Network.Commons (MeasureEvent (..), Ping (..), Pong (..),
loadLogConfig, logMeasure)
import qualified Network.Transport.TCP as TCP
import Node (ConversationActions (..), Listener (..), NodeAction (..),
defaultNodeEnvironment, noReceiveDelay, node,
simpleNodeEndPoint)
import Node.Message.Binary (binaryPacking)
import Pos.Util.Trace (Severity (..), Trace, wlogTrace)
import Pos.Util.Wlog (removeAllHandlers)
import ReceiverOptions (Args (..), argsParser)
main :: IO ()
main = do
(Args {..}, ()) <-
simpleOptions
"bench-receiver"
"Server utility for benches"
"Use it!"
argsParser
empty
lh <- loadLogConfig logsPrefix logConfig
setLocaleEncoding utf8
transport <- do
transportOrError <-
TCP.createTransport (TCP.defaultTCPAddr "127.0.0.1" (show port))
TCP.defaultTCPParameters
either throwIO return transportOrError
let prng = mkStdGen 0
node logTrace (simpleNodeEndPoint transport) (const noReceiveDelay) (const noReceiveDelay) prng binaryPacking () defaultNodeEnvironment $ \_ ->
NodeAction (const [pingListener noPong]) $ \_ -> do
threadDelay (duration * 1000000)
removeAllHandlers lh
where
logTrace :: Trace IO (Severity, Text)
logTrace = wlogTrace "receiver"
logTrace' :: Trace IO Text
logTrace' = contramap ((,) Info) logTrace
pingListener noPong =
Listener $ \_ _ cactions -> do
(mid, payload) <- recv cactions maxBound >>= \case
Just (Ping mid payload) -> return (mid, payload)
_ -> throwString "Expected a ping"
logMeasure logTrace' PingReceived mid payload
unless noPong $ do
logMeasure logTrace' PongSent mid payload
send cactions (Pong mid payload)
| input-output-hk/pos-haskell-prototype | networking/bench/Receiver/Main.hs | mit | 2,769 | 0 | 18 | 819 | 661 | 363 | 298 | 62 | 2 |
{-# LANGUAGE CPP, ConstraintKinds, DeriveDataTypeable, FlexibleContexts, MultiWayIf, NamedFieldPuns,
OverloadedStrings, PackageImports, RankNTypes, RecordWildCards, ScopedTypeVariables,
TemplateHaskell, TupleSections #-}
-- | Run commands in Docker containers
module Stack.Docker
(cleanup
,CleanupOpts(..)
,CleanupAction(..)
,dockerCleanupCmdName
,dockerCmdName
,dockerHelpOptName
,dockerPullCmdName
,entrypoint
,preventInContainer
,pull
,reexecWithOptionalContainer
,reset
,reExecArgName
,StackDockerException(..)
) where
import Control.Applicative
import Control.Concurrent.MVar.Lifted (MVar,modifyMVar_,newMVar)
import Control.Exception.Lifted
import Control.Monad
import Control.Monad.Catch (MonadThrow,throwM,MonadCatch,MonadMask)
import Control.Monad.IO.Class (MonadIO,liftIO)
import Control.Monad.Logger (MonadLogger,logError,logInfo,logWarn)
import Control.Monad.Reader (MonadReader,asks,runReaderT)
import Control.Monad.Writer (execWriter,runWriter,tell)
import Control.Monad.Trans.Control (MonadBaseControl)
import qualified "cryptohash" Crypto.Hash as Hash
import Data.Aeson.Extended (FromJSON(..),(.:),(.:?),(.!=),eitherDecode)
import Data.ByteString.Builder (stringUtf8,charUtf8,toLazyByteString)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import Data.Char (isSpace,toUpper,isAscii,isDigit)
import Data.Conduit.List (sinkNull)
import Data.List (dropWhileEnd,intercalate,isPrefixOf,isInfixOf,foldl')
import Data.List.Extra (trim)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Ord (Down(..))
import Data.Streaming.Process (ProcessExitedUnsuccessfully(..))
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time (UTCTime,LocalTime(..),diffDays,utcToLocalTime,getZonedTime,ZonedTime(..))
import Data.Typeable (Typeable)
import Data.Version (showVersion)
import Distribution.System (Platform (Platform),Arch (X86_64),OS (Linux))
import Distribution.Text (display)
import GHC.Exts (sortWith)
import Network.HTTP.Client.Conduit (HasHttpManager)
import Path
import Path.Extra (toFilePathNoTrailingSep)
import Path.IO hiding (canonicalizePath)
import qualified Paths_stack as Meta
import Prelude -- Fix redundant import warnings
import Stack.Config (getInContainer)
import Stack.Constants
import Stack.Docker.GlobalDB
import Stack.Types
import Stack.Types.Internal
import Stack.Setup (ensureDockerStackExe)
import System.Directory (canonicalizePath,getHomeDirectory)
import System.Environment (getEnv,getEnvironment,getProgName,getArgs,getExecutablePath)
import System.Exit (exitSuccess, exitWith)
import qualified System.FilePath as FP
import System.IO (stderr,stdin,stdout,hIsTerminalDevice)
import System.IO.Error (isDoesNotExistError)
import System.IO.Unsafe (unsafePerformIO)
import qualified System.PosixCompat.User as User
import qualified System.PosixCompat.Files as Files
import System.Process.PagerEditor (editByteString)
import System.Process.Read
import System.Process.Run
import System.Process (CreateProcess(delegate_ctlc))
import Text.Printf (printf)
#ifndef WINDOWS
import Control.Concurrent (threadDelay)
import Control.Monad.Trans.Control (liftBaseWith)
import System.Posix.Signals
import qualified System.Posix.User as PosixUser
#endif
-- | If Docker is enabled, re-runs the currently running OS command in a Docker container.
-- Otherwise, runs the inner action.
--
-- This takes an optional release action which should be taken IFF control is
-- transfering away from the current process to the intra-container one. The main use
-- for this is releasing a lock. After launching reexecution, the host process becomes
-- nothing but an manager for the call into docker and thus may not hold the lock.
reexecWithOptionalContainer
:: M env m
=> Maybe (Path Abs Dir)
-> Maybe (m ())
-> IO ()
-> Maybe (m ())
-> Maybe (m ())
-> m ()
reexecWithOptionalContainer mprojectRoot =
execWithOptionalContainer mprojectRoot getCmdArgs
where
getCmdArgs docker envOverride imageInfo isRemoteDocker = do
config <- asks getConfig
deUser <-
if fromMaybe (not isRemoteDocker) (dockerSetUser docker)
then liftIO $ do
duUid <- User.getEffectiveUserID
duGid <- User.getEffectiveGroupID
duGroups <- User.getGroups
duUmask <- Files.setFileCreationMask 0o022
-- Only way to get old umask seems to be to change it, so set it back afterward
_ <- Files.setFileCreationMask duUmask
return (Just DockerUser{..})
else return Nothing
args <-
fmap
(["--" ++ reExecArgName ++ "=" ++ showVersion Meta.version
,"--" ++ dockerEntrypointArgName
,show DockerEntrypoint{..}] ++)
(liftIO getArgs)
case dockerStackExe (configDocker config) of
Just DockerStackExeHost
| configPlatform config == dockerContainerPlatform -> do
exePath <- liftIO getExecutablePath
cmdArgs args exePath
| otherwise -> throwM UnsupportedStackExeHostPlatformException
Just DockerStackExeImage -> do
progName <- liftIO getProgName
return (FP.takeBaseName progName, args, [], [])
Just (DockerStackExePath path) -> do
exePath <- liftIO $ canonicalizePath (toFilePath path)
cmdArgs args exePath
Just DockerStackExeDownload -> exeDownload args
Nothing
| configPlatform config == dockerContainerPlatform -> do
(exePath,exeTimestamp,misCompatible) <-
liftIO $
do exePath <- liftIO getExecutablePath
exeTimestamp <- resolveFile' exePath >>= getModificationTime
isKnown <-
liftIO $
getDockerImageExe
config
(iiId imageInfo)
exePath
exeTimestamp
return (exePath, exeTimestamp, isKnown)
case misCompatible of
Just True -> cmdArgs args exePath
Just False -> exeDownload args
Nothing -> do
e <-
try $
sinkProcessStderrStdout
Nothing
envOverride
"docker"
[ "run"
, "-v"
, exePath ++ ":" ++ "/tmp/stack"
, iiId imageInfo
, "/tmp/stack"
, "--version"]
sinkNull
sinkNull
let compatible =
case e of
Left (ProcessExitedUnsuccessfully _ _) ->
False
Right _ -> True
liftIO $
setDockerImageExe
config
(iiId imageInfo)
exePath
exeTimestamp
compatible
if compatible
then cmdArgs args exePath
else exeDownload args
Nothing -> exeDownload args
exeDownload args = do
exePath <- ensureDockerStackExe dockerContainerPlatform
cmdArgs args (toFilePath exePath)
cmdArgs args exePath = do
let mountPath = hostBinDir FP.</> FP.takeBaseName exePath
return (mountPath, args, [], [Mount exePath mountPath])
-- | If Docker is enabled, re-runs the OS command returned by the second argument in a
-- Docker container. Otherwise, runs the inner action.
--
-- This takes an optional release action just like `reexecWithOptionalContainer`.
execWithOptionalContainer
:: M env m
=> Maybe (Path Abs Dir)
-> GetCmdArgs env m
-> Maybe (m ())
-> IO ()
-> Maybe (m ())
-> Maybe (m ())
-> m ()
execWithOptionalContainer mprojectRoot getCmdArgs mbefore inner mafter mrelease =
do config <- asks getConfig
inContainer <- getInContainer
isReExec <- asks getReExec
if | inContainer && not isReExec && (isJust mbefore || isJust mafter) ->
throwM OnlyOnHostException
| inContainer ->
liftIO (do inner
exitSuccess)
| not (dockerEnable (configDocker config)) ->
do fromMaybeAction mbefore
liftIO inner
fromMaybeAction mafter
liftIO exitSuccess
| otherwise ->
do fromMaybeAction mrelease
runContainerAndExit
getCmdArgs
mprojectRoot
(fromMaybeAction mbefore)
(fromMaybeAction mafter)
where
fromMaybeAction Nothing = return ()
fromMaybeAction (Just hook) = hook
-- | Error if running in a container.
preventInContainer :: (MonadIO m,MonadThrow m) => m () -> m ()
preventInContainer inner =
do inContainer <- getInContainer
if inContainer
then throwM OnlyOnHostException
else inner
-- | Run a command in a new Docker container, then exit the process.
runContainerAndExit :: M env m
=> GetCmdArgs env m
-> Maybe (Path Abs Dir) -- ^ Project root (maybe)
-> m () -- ^ Action to run before
-> m () -- ^ Action to run after
-> m ()
runContainerAndExit getCmdArgs
mprojectRoot
before
after =
do config <- asks getConfig
let docker = configDocker config
envOverride <- getEnvOverride (configPlatform config)
checkDockerVersion envOverride docker
(env,isStdinTerminal,isStderrTerminal,homeDir) <- liftIO $
(,,,)
<$> getEnvironment
<*> hIsTerminalDevice stdin
<*> hIsTerminalDevice stderr
<*> (parseAbsDir =<< getHomeDirectory)
isStdoutTerminal <- asks getTerminal
let sshDir = homeDir </> sshRelDir
sshDirExists <- doesDirExist sshDir
let dockerHost = lookup "DOCKER_HOST" env
dockerCertPath = lookup "DOCKER_CERT_PATH" env
bamboo = lookup "bamboo_buildKey" env
jenkins = lookup "JENKINS_HOME" env
msshAuthSock = lookup "SSH_AUTH_SOCK" env
muserEnv = lookup "USER" env
isRemoteDocker = maybe False (isPrefixOf "tcp://") dockerHost
image = dockerImage docker
when (isRemoteDocker &&
maybe False (isInfixOf "boot2docker") dockerCertPath)
($logWarn "Warning: Using boot2docker is NOT supported, and not likely to perform well.")
maybeImageInfo <- inspect envOverride image
imageInfo@Inspect{..} <- case maybeImageInfo of
Just ii -> return ii
Nothing
| dockerAutoPull docker ->
do pullImage envOverride docker image
mii2 <- inspect envOverride image
case mii2 of
Just ii2 -> return ii2
Nothing -> throwM (InspectFailedException image)
| otherwise -> throwM (NotPulledException image)
sandboxDir <- projectDockerSandboxDir projectRoot
let ImageConfig {..} = iiConfig
imageEnvVars = map (break (== '=')) icEnv
platformVariant = BS.unpack $ Hash.digestToHexByteString $ hashRepoName image
stackRoot = configStackRoot config
sandboxHomeDir = sandboxDir </> homeDirName
isTerm = not (dockerDetach docker) &&
isStdinTerminal &&
isStdoutTerminal &&
isStderrTerminal
keepStdinOpen = not (dockerDetach docker) &&
-- Workaround for https://github.com/docker/docker/issues/12319
-- This is fixed in Docker 1.9.1, but will leave the workaround
-- in place for now, for users who haven't upgraded yet.
(isTerm || (isNothing bamboo && isNothing jenkins))
newPathEnv <- augmentPath
[ hostBinDir
, toFilePathNoTrailingSep $ sandboxHomeDir
</> $(mkRelDir ".local/bin")]
(T.pack <$> lookupImageEnv "PATH" imageEnvVars)
(cmnd,args,envVars,extraMount) <- getCmdArgs docker envOverride imageInfo isRemoteDocker
pwd <- getCurrentDir
liftIO
(do updateDockerImageLastUsed config iiId (toFilePath projectRoot)
mapM_ (ensureDir) [sandboxHomeDir, stackRoot])
containerID <- (trim . decodeUtf8) <$> readDockerProcess
envOverride
(concat
[["create"
,"--net=host"
,"-e",inContainerEnvVar ++ "=1"
,"-e",stackRootEnvVar ++ "=" ++ toFilePathNoTrailingSep stackRoot
,"-e",platformVariantEnvVar ++ "=dk" ++ platformVariant
,"-e","HOME=" ++ toFilePathNoTrailingSep sandboxHomeDir
,"-e","PATH=" ++ T.unpack newPathEnv
,"-e","PWD=" ++ toFilePathNoTrailingSep pwd
,"-v",toFilePathNoTrailingSep stackRoot ++ ":" ++ toFilePathNoTrailingSep stackRoot
,"-v",toFilePathNoTrailingSep projectRoot ++ ":" ++ toFilePathNoTrailingSep projectRoot
,"-v",toFilePathNoTrailingSep sandboxHomeDir ++ ":" ++ toFilePathNoTrailingSep sandboxHomeDir
,"-w",toFilePathNoTrailingSep pwd]
,case muserEnv of
Nothing -> []
Just userEnv -> ["-e","USER=" ++ userEnv]
,if sshDirExists
then ["-v",toFilePathNoTrailingSep sshDir ++ ":" ++
toFilePathNoTrailingSep (sandboxHomeDir </> sshRelDir)]
else []
,case msshAuthSock of
Nothing -> []
Just sshAuthSock ->
["-e","SSH_AUTH_SOCK=" ++ sshAuthSock
,"-v",sshAuthSock ++ ":" ++ sshAuthSock]
-- Disable the deprecated entrypoint in FP Complete-generated images
,["--entrypoint=/usr/bin/env"
| isJust (lookupImageEnv oldSandboxIdEnvVar imageEnvVars) &&
(icEntrypoint == ["/usr/local/sbin/docker-entrypoint"] ||
icEntrypoint == ["/root/entrypoint.sh"])]
,concatMap (\(k,v) -> ["-e", k ++ "=" ++ v]) envVars
,concatMap mountArg (extraMount ++ dockerMount docker)
,concatMap (\nv -> ["-e", nv]) (dockerEnv docker)
,case dockerContainerName docker of
Just name -> ["--name=" ++ name]
Nothing -> []
,["-t" | isTerm]
,["-i" | keepStdinOpen]
,dockerRunArgs docker
,[image]
,[cmnd]
,args])
before
#ifndef WINDOWS
runInBase <- liftBaseWith $ \run -> return (void . run)
oldHandlers <- forM [sigINT,sigABRT,sigHUP,sigPIPE,sigTERM,sigUSR1,sigUSR2] $ \sig -> do
let sigHandler = runInBase $ do
readProcessNull Nothing envOverride "docker"
["kill","--signal=" ++ show sig,containerID]
when (sig `elem` [sigTERM,sigABRT]) $ do
-- Give the container 30 seconds to exit gracefully, then send a sigKILL to force it
liftIO $ threadDelay 30000000
readProcessNull Nothing envOverride "docker" ["kill",containerID]
oldHandler <- liftIO $ installHandler sig (Catch sigHandler) Nothing
return (sig, oldHandler)
#endif
let cmd = Cmd Nothing
"docker"
envOverride
(concat [["start"]
,["-a" | not (dockerDetach docker)]
,["-i" | keepStdinOpen]
,[containerID]])
e <- finally
(try $ callProcess'
(\cp -> cp { delegate_ctlc = False })
cmd)
(do unless (dockerPersist docker || dockerDetach docker) $
catch
(readProcessNull Nothing envOverride "docker" ["rm","-f",containerID])
(\(_::ReadProcessException) -> return ())
#ifndef WINDOWS
forM_ oldHandlers $ \(sig,oldHandler) ->
liftIO $ installHandler sig oldHandler Nothing
#endif
)
case e of
Left (ProcessExitedUnsuccessfully _ ec) -> liftIO (exitWith ec)
Right () -> do after
liftIO exitSuccess
where
-- This is using a hash of the Docker repository (without tag or digest) to ensure
-- binaries/libraries aren't shared between Docker and host (or incompatible Docker images)
hashRepoName :: String -> Hash.Digest Hash.MD5
hashRepoName = Hash.hash . BS.pack . takeWhile (\c -> c /= ':' && c /= '@')
lookupImageEnv name vars =
case lookup name vars of
Just ('=':val) -> Just val
_ -> Nothing
mountArg (Mount host container) = ["-v",host ++ ":" ++ container]
projectRoot = fromMaybeProjectRoot mprojectRoot
sshRelDir = $(mkRelDir ".ssh/")
-- | Clean-up old docker images and containers.
cleanup :: M env m
=> CleanupOpts -> m ()
cleanup opts =
do config <- asks getConfig
let docker = configDocker config
envOverride <- getEnvOverride (configPlatform config)
checkDockerVersion envOverride docker
let runDocker = readDockerProcess envOverride
imagesOut <- runDocker ["images","--no-trunc","-f","dangling=false"]
danglingImagesOut <- runDocker ["images","--no-trunc","-f","dangling=true"]
runningContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=running"]
restartingContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=restarting"]
exitedContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=exited"]
pausedContainersOut <- runDocker ["ps","-a","--no-trunc","-f","status=paused"]
let imageRepos = parseImagesOut imagesOut
danglingImageHashes = Map.keys (parseImagesOut danglingImagesOut)
runningContainers = parseContainersOut runningContainersOut ++
parseContainersOut restartingContainersOut
stoppedContainers = parseContainersOut exitedContainersOut ++
parseContainersOut pausedContainersOut
inspectMap <- inspects envOverride
(Map.keys imageRepos ++
danglingImageHashes ++
map fst stoppedContainers ++
map fst runningContainers)
(imagesLastUsed,curTime) <-
liftIO ((,) <$> getDockerImagesLastUsed config
<*> getZonedTime)
let planWriter = buildPlan curTime
imagesLastUsed
imageRepos
danglingImageHashes
stoppedContainers
runningContainers
inspectMap
plan = toLazyByteString (execWriter planWriter)
plan' <- case dcAction opts of
CleanupInteractive ->
liftIO (editByteString (intercalate "-" [stackProgName
,dockerCmdName
,dockerCleanupCmdName
,"plan"])
plan)
CleanupImmediate -> return plan
CleanupDryRun -> do liftIO (LBS.hPut stdout plan)
return LBS.empty
mapM_ (performPlanLine envOverride)
(reverse (filter filterPlanLine (lines (LBS.unpack plan'))))
allImageHashesOut <- runDocker ["images","-aq","--no-trunc"]
liftIO (pruneDockerImagesLastUsed config (lines (decodeUtf8 allImageHashesOut)))
where
filterPlanLine line =
case line of
c:_ | isSpace c -> False
_ -> True
performPlanLine envOverride line =
case filter (not . null) (words (takeWhile (/= '#') line)) of
[] -> return ()
(c:_):t:v:_ ->
do args <- if | toUpper c == 'R' && t == imageStr ->
do $logInfo (concatT ["Removing image: '",v,"'"])
return ["rmi",v]
| toUpper c == 'R' && t == containerStr ->
do $logInfo (concatT ["Removing container: '",v,"'"])
return ["rm","-f",v]
| otherwise -> throwM (InvalidCleanupCommandException line)
e <- try (readDockerProcess envOverride args)
case e of
Left ex@ReadProcessException{} ->
$logError (concatT ["Could not remove: '",v,"': ", show ex])
Left e' -> throwM e'
Right _ -> return ()
_ -> throwM (InvalidCleanupCommandException line)
parseImagesOut = Map.fromListWith (++) . map parseImageRepo . drop 1 . lines . decodeUtf8
where parseImageRepo :: String -> (String, [String])
parseImageRepo line =
case words line of
repo:tag:hash:_
| repo == "<none>" -> (hash,[])
| tag == "<none>" -> (hash,[repo])
| otherwise -> (hash,[repo ++ ":" ++ tag])
_ -> throw (InvalidImagesOutputException line)
parseContainersOut = map parseContainer . drop 1 . lines . decodeUtf8
where parseContainer line =
case words line of
hash:image:rest -> (hash,(image,last rest))
_ -> throw (InvalidPSOutputException line)
buildPlan curTime
imagesLastUsed
imageRepos
danglingImageHashes
stoppedContainers
runningContainers
inspectMap =
do case dcAction opts of
CleanupInteractive ->
do buildStrLn
(concat
["# STACK DOCKER CLEANUP PLAN"
,"\n#"
,"\n# When you leave the editor, the lines in this plan will be processed."
,"\n#"
,"\n# Lines that begin with 'R' denote an image or container that will be."
,"\n# removed. You may change the first character to/from 'R' to remove/keep"
,"\n# and image or container that would otherwise be kept/removed."
,"\n#"
,"\n# To cancel the cleanup, delete all lines in this file."
,"\n#"
,"\n# By default, the following images/containers will be removed:"
,"\n#"])
buildDefault dcRemoveKnownImagesLastUsedDaysAgo "Known images last used"
buildDefault dcRemoveUnknownImagesCreatedDaysAgo "Unknown images created"
buildDefault dcRemoveDanglingImagesCreatedDaysAgo "Dangling images created"
buildDefault dcRemoveStoppedContainersCreatedDaysAgo "Stopped containers created"
buildDefault dcRemoveRunningContainersCreatedDaysAgo "Running containers created"
buildStrLn
(concat
["#"
,"\n# The default plan can be adjusted using command-line arguments."
,"\n# Run '" ++ unwords [stackProgName, dockerCmdName, dockerCleanupCmdName] ++
" --help' for details."
,"\n#"])
_ -> buildStrLn
(unlines
["# Lines that begin with 'R' denote an image or container that will be."
,"# removed."])
buildSection "KNOWN IMAGES (pulled/used by stack)"
imagesLastUsed
buildKnownImage
buildSection "UNKNOWN IMAGES (not managed by stack)"
(sortCreated (Map.toList (foldl' (\m (h,_) -> Map.delete h m)
imageRepos
imagesLastUsed)))
buildUnknownImage
buildSection "DANGLING IMAGES (no named references and not depended on by other images)"
(sortCreated (map (,()) danglingImageHashes))
buildDanglingImage
buildSection "STOPPED CONTAINERS"
(sortCreated stoppedContainers)
(buildContainer (dcRemoveStoppedContainersCreatedDaysAgo opts))
buildSection "RUNNING CONTAINERS"
(sortCreated runningContainers)
(buildContainer (dcRemoveRunningContainersCreatedDaysAgo opts))
where
buildDefault accessor description =
case accessor opts of
Just days -> buildStrLn ("# - " ++ description ++ " at least " ++ showDays days ++ ".")
Nothing -> return ()
sortCreated =
sortWith (\(_,_,x) -> Down x) .
mapMaybe (\(h,r) ->
case Map.lookup h inspectMap of
Nothing -> Nothing
Just ii -> Just (h,r,iiCreated ii))
buildSection sectionHead items itemBuilder =
do let (anyWrote,b) = runWriter (forM items itemBuilder)
when (or anyWrote) $
do buildSectionHead sectionHead
tell b
buildKnownImage (imageHash,lastUsedProjects) =
case Map.lookup imageHash imageRepos of
Just repos@(_:_) ->
do case lastUsedProjects of
(l,_):_ -> forM_ repos (buildImageTime (dcRemoveKnownImagesLastUsedDaysAgo opts) l)
_ -> forM_ repos buildKeepImage
forM_ lastUsedProjects buildProject
buildInspect imageHash
return True
_ -> return False
buildUnknownImage (hash, repos, created) =
case repos of
[] -> return False
_ -> do forM_ repos (buildImageTime (dcRemoveUnknownImagesCreatedDaysAgo opts) created)
buildInspect hash
return True
buildDanglingImage (hash, (), created) =
do buildImageTime (dcRemoveDanglingImagesCreatedDaysAgo opts) created hash
buildInspect hash
return True
buildContainer removeAge (hash,(image,name),created) =
do let disp = name ++ " (image: " ++ image ++ ")"
buildTime containerStr removeAge created disp
buildInspect hash
return True
buildProject (lastUsedTime, projectPath) =
buildInfo ("Last used " ++
showDaysAgo lastUsedTime ++
" in " ++
projectPath)
buildInspect hash =
case Map.lookup hash inspectMap of
Just Inspect{iiCreated,iiVirtualSize} ->
buildInfo ("Created " ++
showDaysAgo iiCreated ++
maybe ""
(\s -> " (size: " ++
printf "%g" (fromIntegral s / 1024.0 / 1024.0 :: Float) ++
"M)")
iiVirtualSize)
Nothing -> return ()
showDays days =
case days of
0 -> "today"
1 -> "yesterday"
n -> show n ++ " days ago"
showDaysAgo oldTime = showDays (daysAgo oldTime)
daysAgo oldTime =
let ZonedTime (LocalTime today _) zone = curTime
LocalTime oldDay _ = utcToLocalTime zone oldTime
in diffDays today oldDay
buildImageTime = buildTime imageStr
buildTime t removeAge time disp =
case removeAge of
Just d | daysAgo time >= d -> buildStrLn ("R " ++ t ++ " " ++ disp)
_ -> buildKeep t disp
buildKeep t d = buildStrLn (" " ++ t ++ " " ++ d)
buildKeepImage = buildKeep imageStr
buildSectionHead s = buildStrLn ("\n#\n# " ++ s ++ "\n#\n")
buildInfo = buildStrLn . (" # " ++)
buildStrLn l = do buildStr l
tell (charUtf8 '\n')
buildStr = tell . stringUtf8
imageStr = "image"
containerStr = "container"
-- | Inspect Docker image or container.
inspect :: (MonadIO m,MonadThrow m,MonadLogger m,MonadBaseControl IO m,MonadCatch m)
=> EnvOverride -> String -> m (Maybe Inspect)
inspect envOverride image =
do results <- inspects envOverride [image]
case Map.toList results of
[] -> return Nothing
[(_,i)] -> return (Just i)
_ -> throwM (InvalidInspectOutputException "expect a single result")
-- | Inspect multiple Docker images and/or containers.
inspects :: (MonadIO m, MonadThrow m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> EnvOverride -> [String] -> m (Map String Inspect)
inspects _ [] = return Map.empty
inspects envOverride images =
do maybeInspectOut <-
try (readDockerProcess envOverride ("inspect" : images))
case maybeInspectOut of
Right inspectOut ->
-- filtering with 'isAscii' to workaround @docker inspect@ output containing invalid UTF-8
case eitherDecode (LBS.pack (filter isAscii (decodeUtf8 inspectOut))) of
Left msg -> throwM (InvalidInspectOutputException msg)
Right results -> return (Map.fromList (map (\r -> (iiId r,r)) results))
Left (ReadProcessException _ _ _ err)
| "Error: No such image" `LBS.isPrefixOf` err -> return Map.empty
Left e -> throwM e
-- | Pull latest version of configured Docker image from registry.
pull :: M env m => m ()
pull =
do config <- asks getConfig
let docker = configDocker config
envOverride <- getEnvOverride (configPlatform config)
checkDockerVersion envOverride docker
pullImage envOverride docker (dockerImage docker)
-- | Pull Docker image from registry.
pullImage :: (MonadLogger m,MonadIO m,MonadThrow m,MonadBaseControl IO m)
=> EnvOverride -> DockerOpts -> String -> m ()
pullImage envOverride docker image =
do $logInfo (concatT ["Pulling image from registry: '",image,"'"])
when (dockerRegistryLogin docker)
(do $logInfo "You may need to log in."
callProcess $ Cmd
Nothing
"docker"
envOverride
(concat
[["login"]
,maybe [] (\n -> ["--username=" ++ n]) (dockerRegistryUsername docker)
,maybe [] (\p -> ["--password=" ++ p]) (dockerRegistryPassword docker)
,[takeWhile (/= '/') image]]))
e <- try (callProcess (Cmd Nothing "docker" envOverride ["pull",image]))
case e of
Left (ProcessExitedUnsuccessfully _ _) -> throwM (PullFailedException image)
Right () -> return ()
-- | Check docker version (throws exception if incorrect)
checkDockerVersion
:: (MonadIO m, MonadThrow m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> EnvOverride -> DockerOpts -> m ()
checkDockerVersion envOverride docker =
do dockerExists <- doesExecutableExist envOverride "docker"
unless dockerExists (throwM DockerNotInstalledException)
dockerVersionOut <- readDockerProcess envOverride ["--version"]
case words (decodeUtf8 dockerVersionOut) of
(_:_:v:_) ->
case parseVersionFromString (stripVersion v) of
Just v'
| v' < minimumDockerVersion ->
throwM (DockerTooOldException minimumDockerVersion v')
| v' `elem` prohibitedDockerVersions ->
throwM (DockerVersionProhibitedException prohibitedDockerVersions v')
| not (v' `withinRange` dockerRequireDockerVersion docker) ->
throwM (BadDockerVersionException (dockerRequireDockerVersion docker) v')
| otherwise ->
return ()
_ -> throwM InvalidVersionOutputException
_ -> throwM InvalidVersionOutputException
where minimumDockerVersion = $(mkVersion "1.6.0")
prohibitedDockerVersions = []
stripVersion v = fst $ break (== '-') $ dropWhileEnd (not . isDigit) v
-- | Remove the project's Docker sandbox.
reset :: (MonadIO m, MonadReader env m, HasConfig env)
=> Maybe (Path Abs Dir) -> Bool -> m ()
reset maybeProjectRoot keepHome = do
dockerSandboxDir <- projectDockerSandboxDir projectRoot
liftIO (removeDirectoryContents
dockerSandboxDir
[homeDirName | keepHome]
[])
where projectRoot = fromMaybeProjectRoot maybeProjectRoot
-- | The Docker container "entrypoint": special actions performed when first entering
-- a container, such as switching the UID/GID to the "outside-Docker" user's.
entrypoint :: (MonadIO m, MonadBaseControl IO m, MonadCatch m, MonadLogger m)
=> Config -> DockerEntrypoint -> m ()
entrypoint config@Config{..} DockerEntrypoint{..} =
modifyMVar_ entrypointMVar $ \alreadyRan -> do
-- Only run the entrypoint once
unless alreadyRan $ do
envOverride <- getEnvOverride configPlatform
homeDir <- parseAbsDir =<< liftIO (getEnv "HOME")
-- Get the UserEntry for the 'stack' user in the image, if it exists
estackUserEntry0 <- liftIO $ tryJust (guard . isDoesNotExistError) $
User.getUserEntryForName stackUserName
-- Switch UID/GID if needed, and update user's home directory
case deUser of
Nothing -> return ()
Just (DockerUser 0 _ _ _) -> return ()
Just du -> updateOrCreateStackUser envOverride estackUserEntry0 homeDir du
case estackUserEntry0 of
Left _ -> return ()
Right ue -> do
-- If the 'stack' user exists in the image, copy any build plans and package indices from
-- its original home directory to the host's stack root, to avoid needing to download them
origStackHomeDir <- parseAbsDir (User.homeDirectory ue)
let origStackRoot = origStackHomeDir </> $(mkRelDir ("." ++ stackProgName))
buildPlanDirExists <- doesDirExist (buildPlanDir origStackRoot)
when buildPlanDirExists $ do
(_, buildPlans) <- listDir (buildPlanDir origStackRoot)
forM_ buildPlans $ \srcBuildPlan -> do
let destBuildPlan = buildPlanDir configStackRoot </> filename srcBuildPlan
exists <- doesFileExist destBuildPlan
unless exists $ do
ensureDir (parent destBuildPlan)
copyFile srcBuildPlan destBuildPlan
forM_ configPackageIndices $ \pkgIdx -> do
msrcIndex <- flip runReaderT (config{configStackRoot = origStackRoot}) $ do
srcIndex <- configPackageIndex (indexName pkgIdx)
exists <- doesFileExist srcIndex
return $ if exists
then Just srcIndex
else Nothing
case msrcIndex of
Nothing -> return ()
Just srcIndex -> do
flip runReaderT config $ do
destIndex <- configPackageIndex (indexName pkgIdx)
exists <- doesFileExist destIndex
unless exists $ do
ensureDir (parent destIndex)
copyFile srcIndex destIndex
return True
where
updateOrCreateStackUser envOverride estackUserEntry homeDir DockerUser{..} = do
case estackUserEntry of
Left _ -> do
-- If no 'stack' user in image, create one with correct UID/GID and home directory
readProcessNull Nothing envOverride "groupadd"
["-o"
,"--gid",show duGid
,stackUserName]
readProcessNull Nothing envOverride "useradd"
["-oN"
,"--uid",show duUid
,"--gid",show duGid
,"--home",toFilePathNoTrailingSep homeDir
,stackUserName]
Right _ -> do
-- If there is already a 'stack' user in the image, adjust its UID/GID and home directory
readProcessNull Nothing envOverride "usermod"
["-o"
,"--uid",show duUid
,"--home",toFilePathNoTrailingSep homeDir
,stackUserName]
readProcessNull Nothing envOverride "groupmod"
["-o"
,"--gid",show duGid
,stackUserName]
forM_ duGroups $ \gid -> do
readProcessNull Nothing envOverride "groupadd"
["-o"
,"--gid",show gid
,"group" ++ show gid]
-- 'setuid' to the wanted UID and GID
liftIO $ do
User.setGroupID duGid
#ifndef WINDOWS
PosixUser.setGroups duGroups
#endif
User.setUserID duUid
_ <- Files.setFileCreationMask duUmask
return ()
stackUserName = "stack"::String
-- | MVar used to ensure the Docker entrypoint is performed exactly once
entrypointMVar :: MVar Bool
{-# NOINLINE entrypointMVar #-}
entrypointMVar = unsafePerformIO (newMVar False)
-- | Remove the contents of a directory, without removing the directory itself.
-- This is used instead of 'FS.removeTree' to clear bind-mounted directories, since
-- removing the root of the bind-mount won't work.
removeDirectoryContents :: Path Abs Dir -- ^ Directory to remove contents of
-> [Path Rel Dir] -- ^ Top-level directory names to exclude from removal
-> [Path Rel File] -- ^ Top-level file names to exclude from removal
-> IO ()
removeDirectoryContents path excludeDirs excludeFiles =
do isRootDir <- doesDirExist path
when isRootDir
(do (lsd,lsf) <- listDir path
forM_ lsd
(\d -> unless (dirname d `elem` excludeDirs)
(removeDirRecur d))
forM_ lsf
(\f -> unless (filename f `elem` excludeFiles)
(removeFile f)))
-- | Produce a strict 'S.ByteString' from the stdout of a
-- process. Throws a 'ReadProcessException' exception if the
-- process fails. Logs process's stderr using @$logError@.
readDockerProcess
:: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> EnvOverride -> [String] -> m BS.ByteString
readDockerProcess envOverride = readProcessStdout Nothing envOverride "docker"
-- | Name of home directory within docker sandbox.
homeDirName :: Path Rel Dir
homeDirName = $(mkRelDir "_home/")
-- | Directory where 'stack' executable is bind-mounted in Docker container
hostBinDir :: FilePath
hostBinDir = "/opt/host/bin"
-- | Convenience function to decode ByteString to String.
decodeUtf8 :: BS.ByteString -> String
decodeUtf8 bs = T.unpack (T.decodeUtf8 bs)
-- | Convenience function constructing message for @$log*@.
concatT :: [String] -> Text
concatT = T.pack . concat
-- | Fail with friendly error if project root not set.
fromMaybeProjectRoot :: Maybe (Path Abs Dir) -> Path Abs Dir
fromMaybeProjectRoot = fromMaybe (throw CannotDetermineProjectRootException)
-- | Environment variable that contained the old sandbox ID.
-- | Use of this variable is deprecated, and only used to detect old images.
oldSandboxIdEnvVar :: String
oldSandboxIdEnvVar = "DOCKER_SANDBOX_ID"
-- | Command-line argument for "docker"
dockerCmdName :: String
dockerCmdName = "docker"
dockerHelpOptName :: String
dockerHelpOptName = dockerCmdName ++ "-help"
-- | Command-line argument for @docker pull@.
dockerPullCmdName :: String
dockerPullCmdName = "pull"
-- | Command-line argument for @docker cleanup@.
dockerCleanupCmdName :: String
dockerCleanupCmdName = "cleanup"
-- | Command-line option for @--internal-re-exec-version@.
reExecArgName :: String
reExecArgName = "internal-re-exec-version"
-- | Platform that Docker containers run
dockerContainerPlatform :: Platform
dockerContainerPlatform = Platform X86_64 Linux
-- | Options for 'cleanup'.
data CleanupOpts = CleanupOpts
{ dcAction :: !CleanupAction
, dcRemoveKnownImagesLastUsedDaysAgo :: !(Maybe Integer)
, dcRemoveUnknownImagesCreatedDaysAgo :: !(Maybe Integer)
, dcRemoveDanglingImagesCreatedDaysAgo :: !(Maybe Integer)
, dcRemoveStoppedContainersCreatedDaysAgo :: !(Maybe Integer)
, dcRemoveRunningContainersCreatedDaysAgo :: !(Maybe Integer) }
deriving (Show)
-- | Cleanup action.
data CleanupAction = CleanupInteractive
| CleanupImmediate
| CleanupDryRun
deriving (Show)
-- | Parsed result of @docker inspect@.
data Inspect = Inspect
{iiConfig :: ImageConfig
,iiCreated :: UTCTime
,iiId :: String
,iiVirtualSize :: Maybe Integer}
deriving (Show)
-- | Parse @docker inspect@ output.
instance FromJSON Inspect where
parseJSON v =
do o <- parseJSON v
Inspect <$> o .: "Config"
<*> o .: "Created"
<*> o .: "Id"
<*> o .:? "VirtualSize"
-- | Parsed @Config@ section of @docker inspect@ output.
data ImageConfig = ImageConfig
{icEnv :: [String]
,icEntrypoint :: [String]}
deriving (Show)
-- | Parse @Config@ section of @docker inspect@ output.
instance FromJSON ImageConfig where
parseJSON v =
do o <- parseJSON v
ImageConfig
<$> fmap join (o .:? "Env") .!= []
<*> fmap join (o .:? "Entrypoint") .!= []
-- | Exceptions thrown by Stack.Docker.
data StackDockerException
= DockerMustBeEnabledException
-- ^ Docker must be enabled to use the command.
| OnlyOnHostException
-- ^ Command must be run on host OS (not in a container).
| InspectFailedException String
-- ^ @docker inspect@ failed.
| NotPulledException String
-- ^ Image does not exist.
| InvalidCleanupCommandException String
-- ^ Input to @docker cleanup@ has invalid command.
| InvalidImagesOutputException String
-- ^ Invalid output from @docker images@.
| InvalidPSOutputException String
-- ^ Invalid output from @docker ps@.
| InvalidInspectOutputException String
-- ^ Invalid output from @docker inspect@.
| PullFailedException String
-- ^ Could not pull a Docker image.
| DockerTooOldException Version Version
-- ^ Installed version of @docker@ below minimum version.
| DockerVersionProhibitedException [Version] Version
-- ^ Installed version of @docker@ is prohibited.
| BadDockerVersionException VersionRange Version
-- ^ Installed version of @docker@ is out of range specified in config file.
| InvalidVersionOutputException
-- ^ Invalid output from @docker --version@.
| HostStackTooOldException Version (Maybe Version)
-- ^ Version of @stack@ on host is too old for version in image.
| ContainerStackTooOldException Version Version
-- ^ Version of @stack@ in container/image is too old for version on host.
| CannotDetermineProjectRootException
-- ^ Can't determine the project root (where to put docker sandbox).
| DockerNotInstalledException
-- ^ @docker --version@ failed.
| UnsupportedStackExeHostPlatformException
-- ^ Using host stack-exe on unsupported platform.
deriving (Typeable)
-- | Exception instance for StackDockerException.
instance Exception StackDockerException
-- | Show instance for StackDockerException.
instance Show StackDockerException where
show DockerMustBeEnabledException =
"Docker must be enabled in your configuration file to use this command."
show OnlyOnHostException =
"This command must be run on host OS (not in a Docker container)."
show (InspectFailedException image) =
concat ["'docker inspect' failed for image after pull: ",image,"."]
show (NotPulledException image) =
concat ["The Docker image referenced by your configuration file"
," has not\nbeen downloaded:\n "
,image
,"\n\nRun '"
,unwords [stackProgName, dockerCmdName, dockerPullCmdName]
,"' to download it, then try again."]
show (InvalidCleanupCommandException line) =
concat ["Invalid line in cleanup commands: '",line,"'."]
show (InvalidImagesOutputException line) =
concat ["Invalid 'docker images' output line: '",line,"'."]
show (InvalidPSOutputException line) =
concat ["Invalid 'docker ps' output line: '",line,"'."]
show (InvalidInspectOutputException msg) =
concat ["Invalid 'docker inspect' output: ",msg,"."]
show (PullFailedException image) =
concat ["Could not pull Docker image:\n "
,image
,"\nThere may not be an image on the registry for your resolver's LTS version in\n"
,"your configuration file."]
show (DockerTooOldException minVersion haveVersion) =
concat ["Minimum docker version '"
,versionString minVersion
,"' is required by "
,stackProgName
," (you have '"
,versionString haveVersion
,"')."]
show (DockerVersionProhibitedException prohibitedVersions haveVersion) =
concat ["These Docker versions are incompatible with "
,stackProgName
," (you have '"
,versionString haveVersion
,"'): "
,intercalate ", " (map versionString prohibitedVersions)
,"."]
show (BadDockerVersionException requiredRange haveVersion) =
concat ["The version of 'docker' you are using ("
,show haveVersion
,") is outside the required\n"
,"version range specified in stack.yaml ("
,T.unpack (versionRangeText requiredRange)
,")."]
show InvalidVersionOutputException =
"Cannot get Docker version (invalid 'docker --version' output)."
show (HostStackTooOldException minVersion (Just hostVersion)) =
concat ["The host's version of '"
,stackProgName
,"' is too old for this Docker image.\nVersion "
,versionString minVersion
," is required; you have "
,versionString hostVersion
,"."]
show (HostStackTooOldException minVersion Nothing) =
concat ["The host's version of '"
,stackProgName
,"' is too old.\nVersion "
,versionString minVersion
," is required."]
show (ContainerStackTooOldException requiredVersion containerVersion) =
concat ["The Docker container's version of '"
,stackProgName
,"' is too old.\nVersion "
,versionString requiredVersion
," is required; the container has "
,versionString containerVersion
,"."]
show CannotDetermineProjectRootException =
"Cannot determine project root directory for Docker sandbox."
show DockerNotInstalledException =
"Cannot find 'docker' in PATH. Is Docker installed?"
show UnsupportedStackExeHostPlatformException = concat
[ "Using host's "
, stackProgName
, " executable in Docker container is only supported on "
, display dockerContainerPlatform
, " platform" ]
-- | Function to get command and arguments to run in Docker container
type GetCmdArgs env m
= M env m
=> DockerOpts
-> EnvOverride
-> Inspect
-> Bool
-> m (FilePath,[String],[(String,String)],[Mount])
type M env m = (MonadIO m,MonadReader env m,MonadLogger m,MonadBaseControl IO m,MonadCatch m
,HasConfig env,HasTerminal env,HasReExec env,HasHttpManager env,MonadMask m)
| narrative/stack | src/Stack/Docker.hs | bsd-3-clause | 48,535 | 0 | 45 | 15,541 | 10,275 | 5,262 | 5,013 | 953 | 22 |
module Main where
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Glade
import Data.IORef
import qualified CalcModel as Calc
main = do
initGUI
-- load up the glade file
calcXmlM <- xmlNew "calc.glade"
let calcXml = case calcXmlM of
(Just calcXml) -> calcXml
Nothing -> error "can't find the glade file \"calc.glade\" \
\in the current directory"
-- get a handle on a some widgets from the glade file
window <- xmlGetWidget calcXml castToWindow "calcwindow"
display <- xmlGetWidget calcXml castToLabel "display"
-- a list of the names of the buttons and the actions associated with them
let buttonNamesAndOperations = numbericButtons ++ otherButtons
numbericButtons = [ ("num-" ++ show n, Calc.enterDigit n)
| n <- [0..9] ]
otherButtons =
[("decimal", Calc.enterDecimalPoint)
,("op-plus", Calc.enterBinOp Calc.plus)
,("op-minus", Calc.enterBinOp Calc.minus)
,("op-times", Calc.enterBinOp Calc.times)
,("op-divide", Calc.enterBinOp Calc.divide)
,("equals", Calc.evaluate)
,("clear", \_ -> Just ("0", Calc.clearCalc))]
-- action to do when a button corresponding to a calculator operation gets
-- pressed: we update the calculator state and display the new result.
-- These calculator operations can return Nothing for when the operation
-- makes no sense, we do nothing in this case.
calcRef <- newIORef Calc.clearCalc
let calcOperation operation = do
calc <- readIORef calcRef
case operation calc of
Nothing -> return ()
Just (result, calc') -> do
display `labelSetLabel` ("<big>" ++ result ++ "</big>")
writeIORef calcRef calc'
-- get a reference to a button from the glade file and attach the
-- handler for when the button is pressed
connectButtonToOperation name operation = do
button <- xmlGetWidget calcXml castToButton name
button `onClicked` calcOperation operation
-- connect up all the buttons with their actions.
mapM_ (uncurry connectButtonToOperation) buttonNamesAndOperations
-- make the program exit when the main window is closed
window `onDestroy` mainQuit
-- show everything and run the main loop
widgetShowAll window
mainGUI
| mariefarrell/Hets | glade-0.12.5.0/demo/calc/Calc.hs | gpl-2.0 | 2,355 | 0 | 20 | 606 | 454 | 239 | 215 | 39 | 3 |
{-# LANGUAGE DeriveDataTypeable, MultiParamTypeClasses, PatternGuards, RankNTypes, TypeSynonymInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Layout.Navigation2D
-- Copyright : (c) 2011 Norbert Zeh <nzeh@cs.dal.ca>
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : Norbert Zeh <nzeh@cs.dal.ca>
-- Stability : unstable
-- Portability : unportable
--
-- Navigation2D is an xmonad extension that allows easy directional
-- navigation of windows and screens (in a multi-monitor setup).
-----------------------------------------------------------------------------
module XMonad.Actions.Navigation2D ( -- * Usage
-- $usage
-- * Finer points
-- $finer_points
-- * Alternative directional navigation modules
-- $alternatives
-- * Incompatibilities
-- $incompatibilities
-- * Detailed technical discussion
-- $technical
-- * Exported functions and types
-- #Exports#
navigation2D
, navigation2DP
, additionalNav2DKeys
, additionalNav2DKeysP
, withNavigation2DConfig
, Navigation2DConfig(..)
, def
, defaultNavigation2DConfig
, Navigation2D
, lineNavigation
, centerNavigation
, fullScreenRect
, singleWindowRect
, switchLayer
, windowGo
, windowSwap
, windowToScreen
, screenGo
, screenSwap
, Direction2D(..)
) where
import Control.Applicative
import qualified Data.List as L
import qualified Data.Map as M
import Data.Maybe
import XMonad hiding (Screen)
import qualified XMonad.StackSet as W
import qualified XMonad.Util.ExtensibleState as XS
import XMonad.Util.EZConfig (additionalKeys, additionalKeysP)
import XMonad.Util.Types
-- $usage
-- #Usage#
-- Navigation2D provides directional navigation (go left, right, up, down) for
-- windows and screens. It treats floating and tiled windows as two separate
-- layers and provides mechanisms to navigate within each layer and to switch
-- between layers. Navigation2D provides two different navigation strategies
-- (see <#Technical_Discussion> for details): /Line navigation/ feels rather
-- natural but may make it impossible to navigate to a given window from the
-- current window, particularly in the floating layer. /Center navigation/
-- feels less natural in certain situations but ensures that all windows can be
-- reached without the need to involve the mouse. Navigation2D allows different
-- navigation strategies to be used in the two layers and allows customization
-- of the navigation strategy for the tiled layer based on the layout currently
-- in effect.
--
-- You can use this module with (a subset of) the following in your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Actions.Navigation2D
--
-- Then add the configuration of the module to your main function:
--
-- > main = xmonad $ navigation2D def
-- > (xK_Up, xK_Left, xK_Down, xK_Right)
-- > [(mod4Mask, windowGo ),
-- > (mod4Mask .|. shiftMask, windowSwap)]
-- > False
-- > $ def
--
-- Alternatively, you can use navigation2DP:
--
-- > main = xmonad $ navigation2D def
-- > ("<Up>", "<Left>", "<Down>", "<Right>")
-- > [("M-", windowGo ),
-- > ("M-S-", windowSwap)]
-- > False
-- > $ def
--
-- That's it. If instead you'd like more control, you can combine
-- withNavigation2DConfig and additionalNav2DKeys or additionalNav2DKeysP:
--
-- > main = xmonad $ withNavigation2DConfig def
-- > $ additionalNav2DKeys (xK_Up, xK_Left, xK_Down, xK_Right)
-- > [(mod4Mask, windowGo ),
-- > (mod4Mask .|. shiftMask, windowSwap)]
-- > False
-- > $ additionalNav2DKeys (xK_u, xK_l, xK_d, xK_r)
-- > [(mod4Mask, screenGo ),
-- > (mod4Mask .|. shiftMask, screenSwap)]
-- > False
-- > $ def
--
-- Or you can add the configuration of the module to your main function:
--
-- > main = xmonad $ withNavigation2DConfig def $ def
--
-- And specify your keybindings normally:
--
-- > -- Switch between layers
-- > , ((modm, xK_space), switchLayer)
-- >
-- > -- Directional navigation of windows
-- > , ((modm, xK_Right), windowGo R False)
-- > , ((modm, xK_Left ), windowGo L False)
-- > , ((modm, xK_Up ), windowGo U False)
-- > , ((modm, xK_Down ), windowGo D False)
-- >
-- > -- Swap adjacent windows
-- > , ((modm .|. controlMask, xK_Right), windowSwap R False)
-- > , ((modm .|. controlMask, xK_Left ), windowSwap L False)
-- > , ((modm .|. controlMask, xK_Up ), windowSwap U False)
-- > , ((modm .|. controlMask, xK_Down ), windowSwap D False)
-- >
-- > -- Directional navigation of screens
-- > , ((modm, xK_r ), screenGo R False)
-- > , ((modm, xK_l ), screenGo L False)
-- > , ((modm, xK_u ), screenGo U False)
-- > , ((modm, xK_d ), screenGo D False)
-- >
-- > -- Swap workspaces on adjacent screens
-- > , ((modm .|. controlMask, xK_r ), screenSwap R False)
-- > , ((modm .|. controlMask, xK_l ), screenSwap L False)
-- > , ((modm .|. controlMask, xK_u ), screenSwap U False)
-- > , ((modm .|. controlMask, xK_d ), screenSwap D False)
-- >
-- > -- Send window to adjacent screen
-- > , ((modm .|. mod1Mask, xK_r ), windowToScreen R False)
-- > , ((modm .|. mod1Mask, xK_l ), windowToScreen L False)
-- > , ((modm .|. mod1Mask, xK_u ), windowToScreen U False)
-- > , ((modm .|. mod1Mask, xK_d ), windowToScreen D False)
--
-- For detailed instruction on editing the key binding see:
--
-- "XMonad.Doc.Extending#Editing_key_bindings".
-- $finer_points
-- #Finer_Points#
-- The above should get you started. Here are some finer points:
--
-- Navigation2D has the ability to wrap around at screen edges. For example, if
-- you navigated to the rightmost window on the rightmost screen and you
-- continued to go right, this would get you to the leftmost window on the
-- leftmost screen. This feature may be useful for switching between screens
-- that are far apart but may be confusing at least to novice users. Therefore,
-- it is disabled in the above example (e.g., navigation beyond the rightmost
-- window on the rightmost screen is not possible and trying to do so will
-- simply not do anything.) If you want this feature, change all the 'False'
-- values in the above example to 'True'. You could also decide you want
-- wrapping only for a subset of the operations and no wrapping for others.
--
-- By default, all layouts use the 'defaultTiledNavigation' strategy specified
-- in the 'Navigation2DConfig' (by default, line navigation is used). To
-- override this behaviour for some layouts, add a pair (\"layout name\",
-- navigation strategy) to the 'layoutNavigation' list in the
-- 'Navigation2DConfig', where \"layout name\" is the string reported by the
-- layout's description method (normally what is shown as the layout name in
-- your status bar). For example, all navigation strategies normally allow only
-- navigation between mapped windows. The first step to overcome this, for
-- example, for the Full layout, is to switch to center navigation for the Full
-- layout:
--
-- > myNavigation2DConfig = def { layoutNavigation = [("Full", centerNavigation)] }
-- >
-- > main = xmonad $ withNavigation2DConfig myNavigation2DConfig
-- > $ def
--
-- The navigation between windows is based on their screen rectangles, which are
-- available /and meaningful/ only for mapped windows. Thus, as already said,
-- the default is to allow navigation only between mapped windows. However,
-- there are layouts that do not keep all windows mapped. One example is the
-- Full layout, which unmaps all windows except the one that has the focus,
-- thereby preventing navigation to any other window in the layout. To make
-- navigation to unmapped windows possible, unmapped windows need to be assigned
-- rectangles to pretend they are mapped, and a natural way to do this for the
-- Full layout is to pretend all windows occupy the full screen and are stacked
-- on top of each other so that only the frontmost one is visible. This can be
-- done as follows:
--
-- > myNavigation2DConfig = def { layoutNavigation = [("Full", centerNavigation)]
-- > , unmappedWindowRect = [("Full", singleWindowRect)]
-- > }
-- >
-- > main = xmonad $ withNavigation2DConfig myNavigation2DConfig
-- > $ def
--
-- With this setup, Left/Up navigation behaves like standard
-- 'XMonad.StackSet.focusUp' and Right/Down navigation behaves like
-- 'XMonad.StackSet.focusDown', thus allowing navigation between windows in the
-- layout.
--
-- In general, each entry in the 'unmappedWindowRect' association list is a pair
-- (\"layout description\", function), where the function computes a rectangle
-- for each unmapped window from the screen it is on and the window ID.
-- Currently, Navigation2D provides only two functions of this type:
-- 'singleWindowRect' and 'fullScreenRect'.
--
-- With per-layout navigation strategies, if different layouts are in effect on
-- different screens in a multi-monitor setup, and different navigation
-- strategies are defined for these active layouts, the most general of these
-- navigation strategies is used across all screens (because Navigation2D does
-- not distinguish between windows on different workspaces), where center
-- navigation is more general than line navigation, as discussed formally under
-- <#Technical_Discussion>.
-- $alternatives
-- #Alternatives#
--
-- There exist two alternatives to Navigation2D:
-- "XMonad.Actions.WindowNavigation" and "XMonad.Layout.WindowNavigation".
-- X.L.WindowNavigation has the advantage of colouring windows to indicate the
-- window that would receive the focus in each navigation direction, but it does
-- not support navigation across multiple monitors, does not support directional
-- navigation of floating windows, and has a very unintuitive definition of
-- which window receives the focus next in each direction. X.A.WindowNavigation
-- does support navigation across multiple monitors but does not provide window
-- colouring while retaining the unintuitive navigational semantics of
-- X.L.WindowNavigation. This makes it very difficult to predict which window
-- receives the focus next. Neither X.A.WindowNavigation nor
-- X.L.WindowNavigation supports directional navigation of screens.
-- $technical
-- #Technical_Discussion#
-- An in-depth discussion of the navigational strategies implemented in
-- Navigation2D, including formal proofs of their properties, can be found
-- at <http://www.cs.dal.ca/~nzeh/xmonad/Navigation2D.pdf>.
-- $incompatibilities
-- #Incompatibilities#
-- Currently Navigation2D is known not to play nicely with tabbed layouts, but
-- it should work well with any other tiled layout. My hope is to address the
-- incompatibility with tabbed layouts in a future version. The navigation to
-- unmapped windows, for example in a Full layout, by assigning rectangles to
-- unmapped windows is more a workaround than a clean solution. Figuring out
-- how to deal with tabbed layouts may also lead to a more general and cleaner
-- solution to query the layout for a window's rectangle that may make this
-- workaround unnecessary. At that point, the 'unmappedWindowRect' field of the
-- 'Navigation2DConfig' will disappear.
-- | A rectangle paired with an object
type Rect a = (a, Rectangle)
-- | A shorthand for window-rectangle pairs. Reduces typing.
type WinRect = Rect Window
-- | A shorthand for workspace-rectangle pairs. Reduces typing.
type WSRect = Rect WorkspaceId
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- --
-- PUBLIC INTERFACE --
-- --
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- | Encapsulates the navigation strategy
data Navigation2D = N Generality (forall a . Eq a => Direction2D -> Rect a -> [Rect a] -> Maybe a)
runNav :: forall a . Eq a => Navigation2D -> (Direction2D -> Rect a -> [Rect a] -> Maybe a)
runNav (N _ nav) = nav
-- | Score that indicates how general a navigation strategy is
type Generality = Int
instance Eq Navigation2D where
(N x _) == (N y _) = x == y
instance Ord Navigation2D where
(N x _) <= (N y _) = x <= y
-- | Line navigation. To illustrate this navigation strategy, consider
-- navigating to the left from the current window. In this case, we draw a
-- horizontal line through the center of the current window and consider all
-- windows that intersect this horizontal line and whose right boundaries are to
-- the left of the left boundary of the current window. From among these
-- windows, we choose the one with the rightmost right boundary.
lineNavigation :: Navigation2D
lineNavigation = N 1 doLineNavigation
-- | Center navigation. Again, consider navigating to the left. Then we
-- consider the cone bounded by the two rays shot at 45-degree angles in
-- north-west and south-west direction from the center of the current window. A
-- window is a candidate to receive the focus if its center lies in this cone.
-- We choose the window whose center has minimum L1-distance from the current
-- window center. The tie breaking strategy for windows with the same distance
-- is a bit complicated (see <#Technical_Discussion>) but ensures that all
-- windows can be reached and that windows with the same center are traversed in
-- their order in the window stack, that is, in the order
-- 'XMonad.StackSet.focusUp' and 'XMonad.StackSet.focusDown' would traverse
-- them.
centerNavigation :: Navigation2D
centerNavigation = N 2 doCenterNavigation
-- | Stores the configuration of directional navigation. The 'Default' instance
-- uses line navigation for the tiled layer and for navigation between screens,
-- and center navigation for the float layer. No custom navigation strategies
-- or rectangles for unmapped windows are defined for individual layouts.
data Navigation2DConfig = Navigation2DConfig
{ defaultTiledNavigation :: Navigation2D -- ^ default navigation strategy for the tiled layer
, floatNavigation :: Navigation2D -- ^ navigation strategy for the float layer
, screenNavigation :: Navigation2D -- ^ strategy for navigation between screens
, layoutNavigation :: [(String, Navigation2D)] -- ^ association list of customized navigation strategies
-- for different layouts in the tiled layer. Each pair
-- is of the form (\"layout description\", navigation
-- strategy). If there is no pair in this list whose first
-- component is the name of the current layout, the
-- 'defaultTiledNavigation' strategy is used.
, unmappedWindowRect :: [(String, Screen -> Window -> X (Maybe Rectangle))]
-- ^ list associating functions to calculate rectangles
-- for unmapped windows with layouts to which they are
-- to be applied. Each pair in this list is of
-- the form (\"layout description\", function), where the
-- function calculates a rectangle for a given unmapped
-- window from the screen it is on and its window ID.
-- See <#Finer_Points> for how to use this.
} deriving Typeable
-- | Shorthand for the tedious screen type
type Screen = W.Screen WorkspaceId (Layout Window) Window ScreenId ScreenDetail
-- | Convenience function for enabling Navigation2D with typical keybindings.
-- Takes a Navigation2DConfig, an (up, left, down, right) tuple, a mapping from
-- modifier key to action, and a bool to indicate if wrapping should occur, and
-- returns a function from XConfig to XConfig.
-- Example:
--
-- > navigation2D def (xK_w, xK_a, xK_s, xK_d) [(mod4Mask, windowGo), (mod4Mask .|. shiftMask, windowSwap)] False myConfig
navigation2D :: Navigation2DConfig -> (KeySym, KeySym, KeySym, KeySym) -> [(ButtonMask, Direction2D -> Bool -> X ())] ->
Bool -> XConfig l -> XConfig l
navigation2D navConfig (u, l, d, r) modifiers wrap xconfig =
additionalNav2DKeys (u, l, d, r) modifiers wrap $
withNavigation2DConfig navConfig xconfig
-- | Convenience function for enabling Navigation2D with typical keybindings,
-- using the syntax defined in 'XMonad.Util.EZConfig.mkKeymap'. Takes a
-- Navigation2DConfig, an (up, left, down, right) tuple, a mapping from key
-- prefix to action, and a bool to indicate if wrapping should occur, and
-- returns a function from XConfig to XConfig. Example:
--
-- > navigation2DP def ("w", "a", "s", "d") [("M-", windowGo), ("M-S-", windowSwap)] False myConfig
navigation2DP :: Navigation2DConfig -> (String, String, String, String) -> [(String, Direction2D -> Bool -> X ())] ->
Bool -> XConfig l -> XConfig l
navigation2DP navConfig (u, l, d, r) modifiers wrap xconfig =
additionalNav2DKeysP (u, l, d, r) modifiers wrap $
withNavigation2DConfig navConfig xconfig
-- | Convenience function for adding keybindings. Takes an (up, left, down,
-- right) tuple, a mapping from key prefix to action, and a bool to indicate if
-- wrapping should occur, and returns a function from XConfig to XConfig.
-- Example:
--
-- > additionalNav2DKeys (xK_w, xK_a, xK_s, xK_d) [(mod4Mask, windowGo), (mod4Mask .|. shiftMask, windowSwap)] False myConfig
additionalNav2DKeys :: (KeySym, KeySym, KeySym, KeySym) -> [(ButtonMask, Direction2D -> Bool -> X ())] ->
Bool -> XConfig l -> XConfig l
additionalNav2DKeys (u, l, d, r) modifiers wrap =
flip additionalKeys [((modif, k), func dir wrap) | (modif, func) <- modifiers, (k, dir) <- dirKeys]
where dirKeys = [(u, U), (l, L), (d, D), (r, R)]
-- | Convenience function for adding keybindings, using the syntax defined in
-- 'XMonad.Util.EZConfig.mkKeymap'. Takes an (up, left, down, right) tuple, a
-- mapping from key prefix to action, and a bool to indicate if wrapping should
-- occur, and returns a function from XConfig to XConfig. Example:
--
-- > additionalNav2DKeysP def ("w", "a", "s", "d") [("M-", windowGo), ("M-S-", windowSwap)] False myConfig
additionalNav2DKeysP :: (String, String, String, String) -> [(String, Direction2D -> Bool -> X ())] ->
Bool -> XConfig l -> XConfig l
additionalNav2DKeysP (u, l, d, r) modifiers wrap =
flip additionalKeysP [(modif ++ k, func dir wrap) | (modif, func) <- modifiers, (k, dir) <- dirKeys]
where dirKeys = [(u, U), (l, L), (d, D), (r, R)]
-- So we can store the configuration in extensible state
instance ExtensionClass Navigation2DConfig where
initialValue = def
-- | Modifies the xmonad configuration to store the Navigation2D configuration
withNavigation2DConfig :: Navigation2DConfig -> XConfig a -> XConfig a
withNavigation2DConfig conf2d xconf = xconf { startupHook = startupHook xconf
>> XS.put conf2d
}
{-# DEPRECATED defaultNavigation2DConfig "Use def (from Data.Default, and re-exported from XMonad.Actions.Navigation2D) instead." #-}
defaultNavigation2DConfig :: Navigation2DConfig
defaultNavigation2DConfig = def
instance Default Navigation2DConfig where
def = Navigation2DConfig { defaultTiledNavigation = lineNavigation
, floatNavigation = centerNavigation
, screenNavigation = lineNavigation
, layoutNavigation = []
, unmappedWindowRect = []
}
-- | Switches focus to the closest window in the other layer (floating if the
-- current window is tiled, tiled if the current window is floating). Closest
-- means that the L1-distance between the centers of the windows is minimized.
switchLayer :: X ()
switchLayer = actOnLayer otherLayer
( \ _ cur wins -> windows
$ doFocusClosestWindow cur wins
)
( \ _ cur wins -> windows
$ doFocusClosestWindow cur wins
)
( \ _ _ _ -> return () )
False
-- | Moves the focus to the next window in the given direction and in the same
-- layer as the current window. The second argument indicates whether
-- navigation should wrap around (e.g., from the left edge of the leftmost
-- screen to the right edge of the rightmost screen).
windowGo :: Direction2D -> Bool -> X ()
windowGo dir wrap = actOnLayer thisLayer
( \ conf cur wins -> windows
$ doTiledNavigation conf dir W.focusWindow cur wins
)
( \ conf cur wins -> windows
$ doFloatNavigation conf dir W.focusWindow cur wins
)
( \ conf cur wspcs -> windows
$ doScreenNavigation conf dir W.view cur wspcs
)
wrap
-- | Swaps the current window with the next window in the given direction and in
-- the same layer as the current window. (In the floating layer, all that
-- changes for the two windows is their stacking order if they're on the same
-- screen. If they're on different screens, each window is moved to the other
-- window's screen but retains its position and size relative to the screen.)
-- The second argument indicates wrapping (see 'windowGo').
windowSwap :: Direction2D -> Bool -> X ()
windowSwap dir wrap = actOnLayer thisLayer
( \ conf cur wins -> windows
$ doTiledNavigation conf dir swap cur wins
)
( \ conf cur wins -> windows
$ doFloatNavigation conf dir swap cur wins
)
( \ _ _ _ -> return () )
wrap
-- | Moves the current window to the next screen in the given direction. The
-- second argument indicates wrapping (see 'windowGo').
windowToScreen :: Direction2D -> Bool -> X ()
windowToScreen dir wrap = actOnScreens ( \ conf cur wspcs -> windows
$ doScreenNavigation conf dir W.shift cur wspcs
)
wrap
-- | Moves the focus to the next screen in the given direction. The second
-- argument indicates wrapping (see 'windowGo').
screenGo :: Direction2D -> Bool -> X ()
screenGo dir wrap = actOnScreens ( \ conf cur wspcs -> windows
$ doScreenNavigation conf dir W.view cur wspcs
)
wrap
-- | Swaps the workspace on the current screen with the workspace on the screen
-- in the given direction. The second argument indicates wrapping (see
-- 'windowGo').
screenSwap :: Direction2D -> Bool -> X ()
screenSwap dir wrap = actOnScreens ( \ conf cur wspcs -> windows
$ doScreenNavigation conf dir W.greedyView cur wspcs
)
wrap
-- | Maps each window to a fullscreen rect. This may not be the same rectangle the
-- window maps to under the Full layout or a similar layout if the layout
-- respects statusbar struts. In such cases, it may be better to use
-- 'singleWindowRect'.
fullScreenRect :: Screen -> Window -> X (Maybe Rectangle)
fullScreenRect scr _ = return (Just . screenRect . W.screenDetail $ scr)
-- | Maps each window to the rectangle it would receive if it was the only
-- window in the layout. Useful, for example, for determining the default
-- rectangle for unmapped windows in a Full layout that respects statusbar
-- struts.
singleWindowRect :: Screen -> Window -> X (Maybe Rectangle)
singleWindowRect scr win = listToMaybe
. map snd
. fst
<$> runLayout ((W.workspace scr) { W.stack = W.differentiate [win] })
(screenRect . W.screenDetail $ scr)
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- --
-- PRIVATE X ACTIONS --
-- --
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- | Acts on the appropriate layer using the given action functions
actOnLayer :: ([WinRect] -> [WinRect] -> [WinRect]) -- ^ Chooses which layer to operate on, relative
-- to the current window (same or other layer)
-> (Navigation2DConfig -> WinRect -> [WinRect] -> X ()) -- ^ The action for the tiled layer
-> (Navigation2DConfig -> WinRect -> [WinRect] -> X ()) -- ^ The action for the float layer
-> (Navigation2DConfig -> WSRect -> [WSRect] -> X ()) -- ^ The action if the current workspace is empty
-> Bool -- ^ Should navigation wrap around screen edges?
-> X ()
actOnLayer choice tiledact floatact wsact wrap = withWindowSet $ \winset -> do
conf <- XS.get
(floating, tiled) <- navigableWindows conf wrap winset
let cur = W.peek winset
case cur of
Nothing -> actOnScreens wsact wrap
Just w | Just rect <- L.lookup w tiled -> tiledact conf (w, rect) (choice tiled floating)
| Just rect <- L.lookup w floating -> floatact conf (w, rect) (choice floating tiled)
| otherwise -> return ()
-- | Returns the list of windows on the currently visible workspaces
navigableWindows :: Navigation2DConfig -> Bool -> WindowSet -> X ([WinRect], [WinRect])
navigableWindows conf wrap winset = L.partition (\(win, _) -> M.member win (W.floating winset))
. addWrapping winset wrap
. catMaybes
. concat
<$>
( mapM ( \scr -> mapM (maybeWinRect scr)
$ W.integrate'
$ W.stack
$ W.workspace scr
)
. sortedScreens
) winset
where
maybeWinRect scr win = do
winrect <- windowRect win
rect <- case winrect of
Just _ -> return winrect
Nothing -> maybe (return Nothing)
(\f -> f scr win)
(L.lookup (description . W.layout . W.workspace $ scr) (unmappedWindowRect conf))
return ((,) win <$> rect)
-- | Returns the current rectangle of the given window, Nothing if the window isn't mapped
windowRect :: Window -> X (Maybe Rectangle)
windowRect win = withDisplay $ \dpy -> do
mp <- isMapped win
if mp then do (_, x, y, w, h, bw, _) <- io $ getGeometry dpy win
return $ Just $ Rectangle x y (w + 2 * bw) (h + 2 * bw)
`catchX` return Nothing
else return Nothing
-- | Acts on the screens using the given action function
actOnScreens :: (Navigation2DConfig -> WSRect -> [WSRect] -> X ())
-> Bool -- ^ Should wrapping be used?
-> X ()
actOnScreens act wrap = withWindowSet $ \winset -> do
conf <- XS.get
let wsrects = visibleWorkspaces winset wrap
cur = W.tag . W.workspace . W.current $ winset
rect = fromJust $ L.lookup cur wsrects
act conf (cur, rect) wsrects
-- | Determines whether a given window is mapped
isMapped :: Window -> X Bool
isMapped win = withDisplay
$ \dpy -> io
$ (waIsUnmapped /=)
. wa_map_state
<$> getWindowAttributes dpy win
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- --
-- PRIVATE PURE FUNCTIONS --
-- --
----------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------
-- | Finds the window closest to the given window and focuses it. Ties are
-- broken by choosing the first window in the window stack among the tied
-- windows. (The stack order is the one produced by integrate'ing each visible
-- workspace's window stack and concatenating these lists for all visible
-- workspaces.)
doFocusClosestWindow :: WinRect
-> [WinRect]
-> (WindowSet -> WindowSet)
doFocusClosestWindow (cur, rect) winrects
| null winctrs = id
| otherwise = W.focusWindow . fst $ L.foldl1' closer winctrs
where
ctr = centerOf rect
winctrs = filter ((cur /=) . fst)
$ map (\(w, r) -> (w, centerOf r)) winrects
closer wc1@(_, c1) wc2@(_, c2) | lDist ctr c1 > lDist ctr c2 = wc2
| otherwise = wc1
-- | Implements navigation for the tiled layer
doTiledNavigation :: Navigation2DConfig
-> Direction2D
-> (Window -> WindowSet -> WindowSet)
-> WinRect
-> [WinRect]
-> (WindowSet -> WindowSet)
doTiledNavigation conf dir act cur winrects winset
| Just win <- runNav nav dir cur winrects = act win winset
| otherwise = winset
where
layouts = map (description . W.layout . W.workspace)
$ W.screens winset
nav = maximum
$ map ( fromMaybe (defaultTiledNavigation conf)
. flip L.lookup (layoutNavigation conf)
)
$ layouts
-- | Implements navigation for the float layer
doFloatNavigation :: Navigation2DConfig
-> Direction2D
-> (Window -> WindowSet -> WindowSet)
-> WinRect
-> [WinRect]
-> (WindowSet -> WindowSet)
doFloatNavigation conf dir act cur winrects
| Just win <- runNav nav dir cur winrects = act win
| otherwise = id
where
nav = floatNavigation conf
-- | Implements navigation between screens
doScreenNavigation :: Navigation2DConfig
-> Direction2D
-> (WorkspaceId -> WindowSet -> WindowSet)
-> WSRect
-> [WSRect]
-> (WindowSet -> WindowSet)
doScreenNavigation conf dir act cur wsrects
| Just ws <- runNav nav dir cur wsrects = act ws
| otherwise = id
where
nav = screenNavigation conf
-- | Implements line navigation. For layouts without overlapping windows, there
-- is no need to break ties between equidistant windows. When windows do
-- overlap, even the best tie breaking rule cannot make line navigation feel
-- natural. Thus, we fairly arbtitrarily break ties by preferring the window
-- that comes first in the window stack. (The stack order is the one produced
-- by integrate'ing each visible workspace's window stack and concatenating
-- these lists for all visible workspaces.)
doLineNavigation :: Eq a => Direction2D -> Rect a -> [Rect a] -> Maybe a
doLineNavigation dir (cur, rect) winrects
| null winrects' = Nothing
| otherwise = Just . fst $ L.foldl1' closer winrects'
where
-- The current window's center
ctr@(xc, yc) = centerOf rect
-- The list of windows that are candidates to receive focus.
winrects' = filter dirFilter
$ filter ((cur /=) . fst)
$ winrects
-- Decides whether a given window matches the criteria to be a candidate to
-- receive the focus.
dirFilter (_, r) = (dir == L && leftOf r rect && intersectsY yc r)
|| (dir == R && leftOf rect r && intersectsY yc r)
|| (dir == U && above r rect && intersectsX xc r)
|| (dir == D && above rect r && intersectsX xc r)
-- Decide whether r1 is left of/above r2.
leftOf r1 r2 = rect_x r1 + fi (rect_width r1) <= rect_x r2
above r1 r2 = rect_y r1 + fi (rect_height r1) <= rect_y r2
-- Check whether r's x-/y-range contains the given x-/y-coordinate.
intersectsX x r = rect_x r <= x && rect_x r + fi (rect_width r) >= x
intersectsY y r = rect_y r <= y && rect_y r + fi (rect_height r) >= y
-- Decides whether r1 is closer to the current window's center than r2
closer wr1@(_, r1) wr2@(_, r2) | dist ctr r1 > dist ctr r2 = wr2
| otherwise = wr1
-- Returns the distance of r from the point (x, y)
dist (x, y) r | dir == L = x - rect_x r - fi (rect_width r)
| dir == R = rect_x r - x
| dir == U = y - rect_y r - fi (rect_height r)
| otherwise = rect_y r - y
-- | Implements center navigation
doCenterNavigation :: Eq a => Direction2D -> Rect a -> [Rect a] -> Maybe a
doCenterNavigation dir (cur, rect) winrects
| ((w, _):_) <- onCtr' = Just w
| otherwise = closestOffCtr
where
-- The center of the current window
(xc, yc) = centerOf rect
-- All the windows with their center points relative to the current
-- center rotated so the right cone becomes the relevant cone.
-- The windows are ordered in the order they should be preferred
-- when they are otherwise tied.
winctrs = map (\(w, r) -> (w, dirTransform . centerOf $ r))
$ stackTransform
$ winrects
-- Give preference to windows later in the stack for going left or up and to
-- windows earlier in the stack for going right or down. (The stack order
-- is the one produced by integrate'ing each visible workspace's window
-- stack and concatenating these lists for all visible workspaces.)
stackTransform | dir == L || dir == U = reverse
| otherwise = id
-- Transform a point into a difference to the current window center and
-- rotate it so that the relevant cone becomes the right cone.
dirTransform (x, y) | dir == R = ( x - xc , y - yc )
| dir == L = (-(x - xc), -(y - yc))
| dir == D = ( y - yc , x - xc )
| otherwise = (-(y - yc), -(x - xc))
-- Partition the points into points that coincide with the center
-- and points that do not.
(onCtr, offCtr) = L.partition (\(_, (x, y)) -> x == 0 && y == 0) winctrs
-- All the points that coincide with the current center and succeed it
-- in the (appropriately ordered) window stack.
onCtr' = L.tail $ L.dropWhile ((cur /=) . fst) onCtr
-- tail should be safe here because cur should be in onCtr
-- All the points that do not coincide with the current center and which
-- lie in the (rotated) right cone.
offCtr' = L.filter (\(_, (x, y)) -> x > 0 && y < x && y >= -x) offCtr
-- The off-center point closest to the center and
-- closest to the bottom ray of the cone. Nothing if no off-center
-- point is in the cone
closestOffCtr = if null offCtr' then Nothing
else Just $ fst $ L.foldl1' closest offCtr'
closest wp@(_, p@(_, yp)) wq@(_, q@(_, yq))
| lDist (0, 0) q < lDist (0, 0) p = wq -- q is closer than p
| lDist (0, 0) p < lDist (0, 0) q = wp -- q is farther away than p
| yq < yp = wq -- q is closer to the bottom ray than p
| otherwise = wp -- q is farther away from the bottom ray than p
-- or it has the same distance but comes later
-- in the window stack
-- | Swaps the current window with the window given as argument
swap :: Window -> WindowSet -> WindowSet
swap win winset = W.focusWindow cur
$ L.foldl' (flip W.focusWindow) newwinset newfocused
where
-- The current window
cur = fromJust $ W.peek winset
-- All screens
scrs = W.screens winset
-- All visible workspaces
visws = map W.workspace scrs
-- The focused windows of the visible workspaces
focused = mapMaybe (\ws -> W.focus <$> W.stack ws) visws
-- The window lists of the visible workspaces
wins = map (W.integrate' . W.stack) visws
-- Update focused windows and window lists to reflect swap of windows.
newfocused = map swapWins focused
newwins = map (map swapWins) wins
-- Replaces the current window with the argument window and vice versa.
swapWins x | x == cur = win
| x == win = cur
| otherwise = x
-- Reconstruct the workspaces' window stacks to reflect the swap.
newvisws = zipWith (\ws wns -> ws { W.stack = W.differentiate wns }) visws newwins
newscrs = zipWith (\scr ws -> scr { W.workspace = ws }) scrs newvisws
newwinset = winset { W.current = head newscrs
, W.visible = tail newscrs
}
-- | Calculates the center of a rectangle
centerOf :: Rectangle -> (Position, Position)
centerOf r = (rect_x r + fi (rect_width r) `div` 2, rect_y r + fi (rect_height r) `div` 2)
-- | Shorthand for integer conversions
fi :: (Integral a, Num b) => a -> b
fi = fromIntegral
-- | Functions to choose the subset of windows to operate on
thisLayer, otherLayer :: a -> a -> a
thisLayer = curry fst
otherLayer = curry snd
-- | Returns the list of visible workspaces and their screen rects
visibleWorkspaces :: WindowSet -> Bool -> [WSRect]
visibleWorkspaces winset wrap = addWrapping winset wrap
$ map ( \scr -> ( W.tag . W.workspace $ scr
, screenRect . W.screenDetail $ scr
)
)
$ sortedScreens winset
-- | Creates five copies of each (window/workspace, rect) pair in the input: the
-- original and four offset one desktop size (desktop = collection of all
-- screens) to the left, to the right, up, and down. Wrap-around at desktop
-- edges is implemented by navigating into these displaced copies.
addWrapping :: WindowSet -- ^ The window set, used to get the desktop size
-> Bool -- ^ Should wrapping be used? Do nothing if not.
-> [Rect a] -- ^ Input set of (window/workspace, rect) pairs
-> [Rect a]
addWrapping _ False wrects = wrects
addWrapping winset True wrects = [ (w, r { rect_x = rect_x r + fi x
, rect_y = rect_y r + fi y
}
)
| (w, r) <- wrects
, (x, y) <- [(0, 0), (-xoff, 0), (xoff, 0), (0, -yoff), (0, yoff)]
]
where
(xoff, yoff) = wrapOffsets winset
-- | Calculates the offsets for window/screen coordinates for the duplication
-- of windows/workspaces that implements wrap-around.
wrapOffsets :: WindowSet -> (Integer, Integer)
wrapOffsets winset = (max_x - min_x, max_y - min_y)
where
min_x = fi $ minimum $ map rect_x rects
min_y = fi $ minimum $ map rect_y rects
max_x = fi $ maximum $ map (\r -> rect_x r + (fi $ rect_width r)) rects
max_y = fi $ maximum $ map (\r -> rect_y r + (fi $ rect_height r)) rects
rects = map snd $ visibleWorkspaces winset False
-- | Returns the list of screens sorted primarily by their centers'
-- x-coordinates and secondarily by their y-coordinates.
sortedScreens :: WindowSet -> [Screen]
sortedScreens winset = L.sortBy cmp
$ W.screens winset
where
cmp s1 s2 | x1 < x2 = LT
| x1 > x2 = GT
| y1 < x2 = LT
| y1 > y2 = GT
| otherwise = EQ
where
(x1, y1) = centerOf (screenRect . W.screenDetail $ s1)
(x2, y2) = centerOf (screenRect . W.screenDetail $ s2)
-- | Calculates the L1-distance between two points.
lDist :: (Position, Position) -> (Position, Position) -> Int
lDist (x1, y1) (x2, y2) = abs (fi $ x1 - x2) + abs (fi $ y1 - y2)
| pjones/xmonad-test | vendor/xmonad-contrib/XMonad/Actions/Navigation2D.hs | bsd-2-clause | 44,392 | 0 | 20 | 14,556 | 6,149 | 3,418 | 2,731 | 340 | 2 |
-- This test exposes the bug in GHC 7.0.1 (and earlier)
-- which did the following rule rewrite:
--
-- f (let v = 2 in g v) (let v = 3 in g v)
-- ---> let v = 2 in let v = 3 in g v + g v
--
-- which is wrong because of the shadowing of v
module Main where
foo :: Int -> Int
{-# INLINE foo #-}
foo x = g (bar (x,x))
bar :: (Int,Int) -> Int
{-# NOINLINE bar #-}
bar (x,y) = x
baz :: Int -> Int
{-# NOINLINE baz #-}
baz x = x
f :: Int -> Int -> Int
{-# NOINLINE f #-}
f x y = x+y
g :: Int -> Int
{-# NOINLINE g #-}
g x = x
{-# RULES
"f/g" [1] forall x y. f (g x) (g y) = x + y
#-}
main = print $ f (foo (baz 1)) (foo (baz 2))
-- Should print 3
-- Bug means that it prints 4
| ghc-android/ghc | testsuite/tests/simplCore/should_run/T4814.hs | bsd-3-clause | 690 | 0 | 10 | 194 | 179 | 103 | 76 | 19 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS -fno-warn-name-shadowing #-}
import Options.Applicative
import Options.Applicative.Types
import Cabal.Simple
import Cabal.Haddock
import Control.Monad hiding (forM_)
import qualified Data.Set as Set
import Text.Printf
import System.Directory
import System.FilePath
import Data.Foldable (forM_)
import Distribution.Simple.Compiler hiding (Flag)
import Distribution.Package --must not specify imports, since we're exporting moule.
import Distribution.PackageDescription
import Distribution.PackageDescription.Parse
import Distribution.Simple.Program
import Distribution.Simple.Setup
import qualified Distribution.Simple.Setup as Setup
import Distribution.Simple.Utils hiding (info)
import Distribution.Verbosity
import Distribution.Text
data SHFlags = SHFlags
{ shPkgDbArgs :: [String]
, shHyperlinkSource :: Bool
, shVerbosity :: Verbosity
, shDest :: String
, shPkgDirs :: [String]
}
optParser :: Parser SHFlags
optParser =
SHFlags
<$> many (strOption (long "package-db" <> metavar "DB-PATH" <> help "Additional package database"))
<*> switch (long "hyperlink-source" <> help "Generate source links in documentation")
<*> option ( auto >>= maybe (readerError "Bad verbosity") return . intToVerbosity )
( long "verbosity"
<> short 'v'
<> value normal
<> metavar "N"
<> help "Verbosity (number from 0 to 3)"
)
<*> strOption (short 'o' <> metavar "OUTPUT-PATH" <> help "Directory where html files will be placed")
<*> many (argument str (metavar "PACKAGE-PATH"))
where
readEither s = case reads s of [(n, "")] -> Just n; _ -> Nothing
getPackageNames
:: Verbosity
-> [FilePath] -- ^ package directories
-> IO [PackageName] -- ^ package names
getPackageNames v = mapM $ \dir -> do
cabalFile <- either error id <$> findPackageDesc dir
desc <- readPackageDescription v cabalFile
let
name = pkgName . package . packageDescription $ desc
return name
-- Depending on whether PackageId refers to a "local" package, return
-- a relative path or the hackage url
computePath :: [PackageName] -> (PackageId -> FilePath)
computePath names =
let pkgSet = Set.fromList names in \pkgId ->
if pkgName pkgId `Set.member` pkgSet
then
".." </> (display $ pkgName pkgId)
else
printf "http://hackage.haskell.org/packages/archive/%s/%s/doc/html"
(display $ pkgName pkgId)
(display $ pkgVersion pkgId)
main :: IO ()
main = do
SHFlags{..} <- execParser $
info (helper <*> optParser) idm
-- make all paths absolute, since we'll be changing directories
-- but first create dest — canonicalizePath will throw an exception if
-- it's not there
createDirectoryIfMissing True {- also parents -} shDest
shDest <- canonicalizePath shDest
shPkgDirs <- mapM canonicalizePath shPkgDirs
pkgNames <- getPackageNames shVerbosity shPkgDirs
let
configFlags =
(defaultConfigFlags defaultProgramConfiguration)
{ configPackageDBs = map (Just . SpecificPackageDB) shPkgDbArgs
, configVerbosity = Setup.Flag shVerbosity
}
haddockFlags =
defaultHaddockFlags
{ haddockDistPref = Setup.Flag shDest
, haddockHscolour = Setup.Flag shHyperlinkSource
}
-- generate docs for every package
forM_ shPkgDirs $ \dir -> do
setCurrentDirectory dir
lbi <- configureAction simpleUserHooks configFlags []
haddockAction lbi simpleUserHooks haddockFlags [] (computePath pkgNames)
-- generate documentation index
regenerateHaddockIndex normal defaultProgramConfiguration shDest
[(iface, html)
| pkg <- pkgNames
, let pkgStr = display pkg
html = pkgStr
iface = shDest </> pkgStr </> pkgStr <.> "haddock"
]
| Teino1978-Corp/Teino1978-Corp-standalone-haddock | src/Main.hs | mit | 3,831 | 0 | 16 | 810 | 905 | 475 | 430 | 87 | 2 |
module Feature.Auth.HTTP where
import ClassyPrelude
import Feature.Auth.Types
import Feature.Common.Util (orThrow)
import Feature.Common.HTTP
import Control.Monad.Except
import Web.Scotty.Trans
import Network.HTTP.Types.Status
class Monad m => Service m where
resolveToken :: Token -> m (Either TokenError CurrentUser)
getCurrentUser :: (Service m) => ActionT LText m (Either TokenError CurrentUser)
getCurrentUser = do
mayHeaderVal <- header "Authorization"
runExceptT $ do
headerVal <- ExceptT $ pure mayHeaderVal `orThrow` TokenErrorNotFound
let token = toStrict $ drop 6 headerVal
ExceptT $ lift $ resolveToken token
optionalUser :: (Service m) => ActionT LText m (Maybe CurrentUser)
optionalUser =
either (const Nothing) Just <$> getCurrentUser
requireUser :: (Service m) => ActionT LText m CurrentUser
requireUser = do
result <- getCurrentUser
stopIfError tokenErrorHandler (pure result)
where
tokenErrorHandler e = do
status status401
json e
| eckyputrady/haskell-scotty-realworld-example-app | src/Feature/Auth/HTTP.hs | mit | 997 | 0 | 14 | 170 | 307 | 157 | 150 | 27 | 1 |
module ProjectEuler.Problem27
( problem
) where
import Math.NumberTheory.Primes.Testing (isPrime)
import Data.List
import Data.Ord
import Petbox
import ProjectEuler.Types
problem :: Problem
problem = pureProblem 27 Solved result
consePrimeLen :: Int -> Int -> Int
consePrimeLen a b =
length $ takeWhile (isPrime . fromIntegral) [ (n+a)*n+b | n <- [0..] ]
result :: Int
result = u*v
where
((u,v), _) = maximumBy (comparing snd) searchSpace
searchSpace =
[ ((c,d), consePrimeLen c d)
| a <- [0..1000]
, b <- takeWhile (<1000) primes
, gcd a b == 1
, c <-[-a,a]
, d <-[-b,b]
, c + d > 0
]
| Javran/Project-Euler | src/ProjectEuler/Problem27.hs | mit | 655 | 0 | 11 | 169 | 283 | 157 | 126 | 23 | 1 |
module Haskrypto.ElGamal
where
import Haskrypto.Modular hiding (field)
import Haskrypto.EllipticCurve
import System.Random
data ElGamalKey = ElGamalKey{
curve :: EllipticCurve Integer,
p :: Point Integer,
password :: Integer,
public :: Point Integer
} deriving (Show)
constructKey :: (EllipticCurve Integer) -> (Point Integer) -> Integer -> ElGamalKey
constructKey c p' pass = ElGamalKey {
curve = c,
p = p',
password = pass,
public = multiply c p' pass
}
crypt :: Point Integer -> ElGamalKey -> Point Integer -> Point Integer
crypt m_point (ElGamalKey curve@(EllipticCurve _ _ primo) public_p password _) public_key = coded
where
coded = add curve noise m_point
noise = multiply curve public_key password
decrypt :: Point Integer -> ElGamalKey -> Point Integer -> Point Integer
decrypt coded (ElGamalKey curve@(EllipticCurve _ _ field) p pass _) public_key = message
where
message = add curve noise coded
noise = negative $ multiply curve public_key pass
calculateNoise :: ElGamalKey -> Point Integer -> Point Integer
calculateNoise (ElGamalKey curve _ password _) public_key = multiply curve public_key password
| TachoMex/Haskrypto | src/Haskrypto/ElGamal.hs | mit | 1,211 | 0 | 10 | 263 | 380 | 199 | 181 | 26 | 1 |
{-# LANGUAGE QuasiQuotes, OverloadedStrings, ScopedTypeVariables,
RecordWildCards, TemplateHaskell, MultiParamTypeClasses,
FlexibleContexts#-}
import Prelude hiding (product)
import Data.Text.Lazy (pack)
import Control.Applicative ((<$>), (<*>))
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger
import Data.Monoid (mconcat)
import Web.Scotty (scotty, Param, get, post, html, notFound, redirect, params, status, param)
import Network.HTTP.Types
import qualified Database.Persist.Sqlite as Db
import qualified Database.Persist.Class
import Chapter12.Database
import Text.Hamlet (HtmlUrl, hamlet)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Data.Text (Text)
import qualified Data.Text.Lazy as T (toStrict)
-- import Data.Text.Read
import Text.Digestive
import Text.Digestive.Util
import qualified Text.Blaze.Html5 as H
import Text.Digestive.Blaze.Html5
import GHC.Int (Int64)
import Data.Maybe (fromJust)
data MyRoute = Products | About
render :: MyRoute ->[(Text, Text)] -> Text
render About _ = "/about"
render Products _ = "/products"
countryForm :: Monad m => Form String m Country
countryForm = Country <$> "name" .: string Nothing
<*> "send" .: bool (Just True)
productForm :: Monad m => Form String m Product
productForm = Product <$> "name" .: string Nothing
<*> "description" .: string Nothing
<*> "price" .: validate isANumber (string Nothing)
<*> "inStock" .: check "Must be >= 0" (>= 0)
(validate isANumber (string Nothing))
isANumber :: (Num a, Read a) => String -> Result String a
isANumber = maybe (Error "Not a number") Success . readMaybe
productView :: View H.Html -> H.Html
productView view = do
form view "/new-product" $ do
label "name" view "Name:"
inputText "name" view
H.br
label "description" view "Descriptipn:"
inputTextArea Nothing Nothing "description" view
H.br
label "price" view "Price:"
inputText "price" view
errorList "price" view
H.br
label "inStock" view "# in Stock:"
inputText "inStock" view
errorList "inStock" view
H.br
inputSubmit "Submit"
-- data CountryType = China | Japan | USA deriving (Show, Eq, Ord, Read)
-- data ClientProxy = ClientProxy String String String CountryType Int deriving (Show, Eq, Ord)
-- xxx :: Monad m => Formlet String m (Db.Key Country)
-- xxx (Just x) = CountryKey <$> Db.SqlBackendKey x <*> CountryKey
data Thing = ThingOne | ThingTwo
deriving (Show, Eq)
data XXX = XXX { thething :: Thing, number :: Int } deriving (Show, Eq)
thingForm :: (Monad m) => Form Text m XXX
thingForm = XXX <$> "thething" .: choice [(ThingOne, "t1"), (ThingTwo, "t2")] Nothing
<*> "number" .: stringRead "fail to parse number" Nothing
thingView :: View H.Html -> H.Html
thingView view = do
form view "/thing" $ do
label "thething" view "The Thing:"
inputSelect "thething" view
foo :: String
foo = "Foo"
bar :: String
bar = "Foo"
clientForm :: Monad m => Form String m Client
clientForm = Client <$> "firstName" .: string Nothing
<*> "lastName" .: string Nothing
<*> "address" .: string Nothing
-- <*> "country" .: stringRead "Cannot parse country" Nothing
-- <*> (CountryKey . Db.SqlBackendKey) <$> stringRead "xxx" Nothing
-- (CountryKey . Db.SqlBackendKey) <$> stringRead "xxx" Nothing
-- <*> (Db.toSqlKey <$> "country" .: stringRead "xxx" Nothing)
<*> (Db.toSqlKey <$> "country" .: choice [(1, "USA"), (2, "CHINA")] Nothing)
-- <*> (Db.toSqlKey <$> "country" .: choice [(1, "USA"), (2, "CHINA")] Nothing)
<*> "age" .: optionalStringRead "Cannot parse age" Nothing
clientView :: View H.Html -> H.Html
clientView view = do
form view "/register" $ do
label "firstName" view "First Name:"
inputText "firstName" view
errorList "firstName" view
H.br
label "lastName" view "Last Name:"
inputText "lastName" view
errorList "lastName" view
H.br
label "address" view "Address:"
inputText "address" view
errorList "address" view
H.br
label "country" view "Country:"
-- inputRadio True "country" view
inputSelect "country" view
errorList "country" view
H.br
label "age" view "Age:"
inputText "age" view
errorList "age" view
H.br
inputSubmit "Submit"
main :: IO ()
main = do
Db.runSqlite "example.db" $ Db.runMigration migrateAll
runNoLoggingT $ Db.withSqlitePool "example.db" 10 $ \pool -> NoLoggingT $
scotty 3000 $ do
get "/about" $
html $ mconcat [ "<html><body>"
, " <h1>Hello Beginning Haskell!</h1>"
, "</body></html>" ]
get "/products" $ do
(products :: [Db.Entity Product]) <-
liftIO $ flip Db.runSqlPersistMPool pool $ Db.selectList [] []
html $ renderHtml $ [hamlet|
<table>
<tr>
<th>Name
<th>Description
$forall Db.Entity _ p <- products
<tr>
<td>#{productName p}
<td>#{productDescription p}
|] render
get "/product/:productId" $ do
(productId :: Integer) <- param "productId"
product <- liftIO $ flip Db.runSqlPersistMPool pool $
-- get $ Key (Db.PersistInt64 $ fromIntegral productId)
Db.get $ Db.toSqlKey (fromIntegral productId)
case product of
Just (Product {..}) -> html $ mconcat [ "<html><body>"
, " <h1>"
, pack productName
, " </h1>"
, " <p>"
, pack productDescription
, " </p>"
, "</html></body>" ]
Nothing -> do
status notFound404
html "<h1>Not found :( product</h1>"
get "/new-product" $ do
view <- getForm "product" productForm
let view' = fmap H.toHtml view
html $ renderHtml $
H.html $ do
H.head $ H.title "Grocery Store"
H.body $ productView view'
post "/new-product" $ do
params' <- params
(view, product) <- postForm "product" productForm (\_ -> return (paramsToEnv params'))
case product of
Just p -> do
key <- liftIO $ Db.runSqlPersistMPool (Db.insert p) pool
let newId = Db.fromSqlKey key
redirect $ mconcat ["/product/", pack $ show newId]
Nothing -> do
let view' = fmap H.toHtml view
html $ renderHtml $
H.html $ do
H.head $ H.title "Grocery Store"
H.body $ productView view'
get "/thing" $ do
view <- getForm "thing" thingForm
let view' = fmap H.toHtml view
html $ renderHtml $
H.html $ do
H.head $ H.title "Thing"
H.body $ thingView view'
get "/client/:clientId" $ do
(clientId :: Integer) <- param "clientId"
client <- liftIO $ flip Db.runSqlPersistMPool pool $
Db.get $ Db.toSqlKey (fromIntegral clientId)
case client of
Just (Client {..}) -> html $ mconcat [ "<html><body>"
, " <h1>"
, pack clientFirstName
, " </h1>"
, " <h1>"
, pack clientLastName
, " </h1>"
, " <h1>"
, pack $ show $ Db.unSqlBackendKey $ unCountryKey $ clientCountry
, " </h1>"
, " <h1>"
, pack $ show clientAge
, " </h1>"
, "</html></body>" ]
Nothing -> do
status notFound404
html "<h1> Not found</h1>"
get "/register" $ do
view <- getForm "client" clientForm
let view' = fmap H.toHtml view
html $ renderHtml $
H.html $ do
H.head $ H.title "New Client"
H.body $ clientView view'
post "/register" $ do
params' <- params
(view, client) <- postForm "client" clientForm (\_ -> return (paramsToEnv params'))
case client of
Just c -> do
key <- liftIO $ Db.runSqlPersistMPool (Db.insert c) pool
let newId = Db.fromSqlKey key
redirect $ mconcat ["/client/", pack $ show newId]
Nothing -> do
let view' = fmap H.toHtml view
html $ renderHtml $
H.html $ do
H.head $ H.title "Register client"
H.body $ clientView view'
notFound $ do
status notFound404
html "<h1>Not found :(</h1>"
paramsToEnv :: Monad m => [Param] -> Env m
paramsToEnv [] _ = fail "Parameter not found"
paramsToEnv ((k,v):rest) t = if T.toStrict k == fromPath t
then return [TextInput $ T.toStrict v]
else paramsToEnv rest t
| hnfmr/beginning_haskell | chapter12/src/Main.hs | mit | 10,029 | 0 | 25 | 3,867 | 2,410 | 1,182 | 1,228 | 211 | 5 |
{-# LANGUAGE OverloadedStrings #-}
module Yesod.Form.I18n.Chinese where
import Yesod.Form.Types (FormMessage (..))
import Data.Monoid (mappend)
import Data.Text (Text)
chineseFormMessage :: FormMessage -> Text
chineseFormMessage (MsgInvalidInteger t) = "无效的整数: " `Data.Monoid.mappend` t
chineseFormMessage (MsgInvalidNumber t) = "无效的数字: " `mappend` t
chineseFormMessage (MsgInvalidEntry t) = "无效的条目: " `mappend` t
chineseFormMessage MsgInvalidTimeFormat = "无效的时间, 必须符合HH:MM[:SS]格式"
chineseFormMessage MsgInvalidDay = "无效的日期, 必须符合YYYY-MM-DD格式"
chineseFormMessage (MsgInvalidUrl t) = "无效的链接: " `mappend` t
chineseFormMessage (MsgInvalidEmail t) = "无效的邮箱地址: " `mappend` t
chineseFormMessage (MsgInvalidHour t) = "无效的小时: " `mappend` t
chineseFormMessage (MsgInvalidMinute t) = "无效的分钟: " `mappend` t
chineseFormMessage (MsgInvalidSecond t) = "无效的秒: " `mappend` t
chineseFormMessage MsgCsrfWarning = "为了防备跨站请求伪造, 请确认表格提交."
chineseFormMessage MsgValueRequired = "此项必填"
chineseFormMessage (MsgInputNotFound t) = "输入找不到: " `mappend` t
chineseFormMessage MsgSelectNone = "<空>"
chineseFormMessage (MsgInvalidBool t) = "无效的逻辑值: " `mappend` t
chineseFormMessage MsgBoolYes = "是"
chineseFormMessage MsgBoolNo = "否"
chineseFormMessage MsgDelete = "删除?"
chineseFormMessage (MsgInvalidHexColorFormat t) = "颜色无效,必须为 #rrggbb 十六进制格式: " `mappend` t
| yesodweb/yesod | yesod-form/Yesod/Form/I18n/Chinese.hs | mit | 1,558 | 0 | 7 | 149 | 340 | 189 | 151 | 25 | 1 |
-- vim: set ts=2 sw=2 sts=0 ff=unix foldmethod=indent:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main where
import Options.Applicative
import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Text.EditDistance as ED
import qualified Text.Parsec as P
import qualified Text.Parsec.Text as P
import qualified Text.Read as R
import MixKenallGeocode.Csv
import MixKenallGeocode.Util
main :: IO()
main = do
optsInfo <- execParser opts
kenAllStr <- getContents
withCsv (_geoCsv optsInfo) $ \geoCsv -> do
mapM_ (\x -> T.putStr x >> putStr "\r\n")
$ map mixedCsvRowToText
$ mix (csvToAreaGeoInfo geoCsv)
$ normalizeKenAllCsv
$ parseCsv kenAllStr
{- オプション -}
data Options = Options { _geoCsv :: FilePath }
deriving Show
options :: Parser Options
options = Options
<$> strOption (short 'g' <> long "geo-csv" <> metavar "PATH" <> help "国土交通省の位置情報が記載されたCSVのパス")
opts :: ParserInfo Options
opts =
info
(helper <*> options)
(
fullDesc
<> progDesc "出力フォーマット: 都道府県名,市町村名,郵便番号,緯度,経度"
<> header "Tableauに郵便番号と位置情報を登録するためのCSVを生成するたえのコマンド"
)
{- 型定義 -}
type StateName = String
type CityName = String
type AreaName = String
type Latitude = Double
type Longitude = Double
type PostalCode = String
data NormalizedCsvRow =
NormalizedCsvRow
{
_StateName :: StateName
, _CityName :: CityName
, _PostalCode :: PostalCode
, _AreaName :: AreaName
, _Latitude :: Maybe(Latitude)
, _Longitude :: Maybe(Longitude)
}
deriving (Eq, Show)
data KenAllCsvRow = KenAllCsvRow
{ _postalCode :: PostalCode
, _stateName :: StateName
, _cityName :: CityName
, _areaName :: ParsedAreaName
, _latitude :: Maybe Latitude
, _longitude :: Maybe Longitude
}
deriving (Show, Eq)
type AreaOptionParser = P.Parsec T.Text ()
-- 町域名
data ParsedAreaName =
AreaNameNoOpt String
| AreaNameOpt String String
| AreaNameBeginOpt String String
| AreaNameEndOpt String
| AreaNameParsedOpt String [AreaOptAddr]
deriving (Show, Eq)
data AreaOptAddr =
AreaOptAddr AreaRange
| AreaOptAddrWithBranch { _left :: AreaRange, _right :: AreaRange }
deriving (Eq, Show)
data AreaRange =
AreaRangeNumOnly AreaNumNm
| AreaRange { _from :: AreaNumNm, _to :: AreaNumNm }
deriving (Eq, Show)
data AreaNumNm =
NoareaNumNm
| AreaNumNm
{ _prefix :: String
, _num :: AreaNum
, _unit :: String
, _notes :: [AreaNote]
}
deriving (Eq, Show)
data AreaNum = AreaNum Int | NoNum
deriving (Eq, Show)
data AreaNote =
AreaRawNote String
| AreaParsedNote ParsedNote
deriving (Eq, Show)
-- data ParsedNote =
-- ExceptionNote [AreaOptAddr]
-- | ParsedNote [AreaOptAddr]
-- deriving (Eq, Show)
data ParsedNote =
ExceptionNote String
| ParsedNote String
deriving (Eq, Show)
parsedAreaName :: P.Parser ParsedAreaName
parsedAreaName =
areaNameOpt
<#> areaNameBeginOpt
<#> areaNameEndOpt
<#> areaNameNoOpt
notOptionField :: P.Parser String
notOptionField = P.many $ P.noneOf "()"
areaNameNoOpt :: P.Parser ParsedAreaName
areaNameNoOpt = AreaNameNoOpt <$> notOptionField
areaNameOpt :: P.Parser ParsedAreaName
areaNameOpt = do
areaNm <- notOptionField
opt <- (P.char '(') *> notOptionField <* (P.char ')')
return $ AreaNameOpt areaNm opt
areaNameBeginOpt :: P.Parser ParsedAreaName
areaNameBeginOpt = do
areaNm <- notOptionField
opt <- (P.char '(') *> notOptionField
return $ AreaNameBeginOpt areaNm opt
areaNameEndOpt :: P.Parser ParsedAreaName
areaNameEndOpt = do
opt <- notOptionField <* (P.char ')')
return $ AreaNameEndOpt opt
reduceKenAllCsv :: Csv -> [KenAllCsvRow]
reduceKenAllCsv = map reduceKenAllCsvRow
reduceKenAllCsvRow :: CsvRow -> KenAllCsvRow
reduceKenAllCsvRow r =
KenAllCsvRow
{ _postalCode = r !! 0
, _stateName = r !! 1
, _cityName = r !! 2
, _areaName = parsedArNm
, _latitude = (R.readMaybe (r !! 4)) :: Maybe Latitude
, _longitude = (R.readMaybe (r !! 5)) :: Maybe Longitude
}
where
arNm = r!!3
parsedArNm =
case P.parse parsedAreaName "* Parse Error *" (T.pack arNm) of
Left err -> error $ show err
Right x -> x
{- 複数行に渡る行をマージ -}
margeRows :: [KenAllCsvRow] -> [KenAllCsvRow]
margeRows [] = []
margeRows (r:rs) =
case (_areaName r) of
AreaNameBeginOpt _ _ ->
let (mr, rest) = splitMargedRowAndRest r rs
in mr:(margeRows rest)
_ -> r:(margeRows rs)
splitMargedRowAndRest :: KenAllCsvRow -> [KenAllCsvRow] -> (KenAllCsvRow, [KenAllCsvRow])
splitMargedRowAndRest r rs = (r{_areaName = marged_r}, tail rest)
where
(xs, rest) = break hasAreaNameEndOpt rs
marged_r = margeParsedAreaNames (_areaName r) $ map _areaName $ xs ++ [head rest]
hasAreaNameEndOpt :: KenAllCsvRow -> Bool
hasAreaNameEndOpt (KenAllCsvRow {..}) =
case _areaName of
(AreaNameEndOpt _) -> True
_ -> False
margeParsedAreaNames :: ParsedAreaName -> [ParsedAreaName] -> ParsedAreaName
margeParsedAreaNames (AreaNameBeginOpt an opt) as = AreaNameOpt an $ concat $ opt:(map takeOptStr as)
where
takeOptStr :: ParsedAreaName -> String
takeOptStr (AreaNameNoOpt x) = x
takeOptStr (AreaNameEndOpt x) = x
takeOptStr _ = ""
margeParsedAreaNames _ _ = AreaNameOpt "" ""
parseAreaOptions :: [KenAllCsvRow] -> [KenAllCsvRow]
parseAreaOptions = map parseAreaOption
parseAreaOption :: KenAllCsvRow -> KenAllCsvRow
parseAreaOption r@(KenAllCsvRow {..}) = r{_areaName = parsedOpt}
where
parsedOpt :: ParsedAreaName
parsedOpt =
case _areaName of
(AreaNameOpt nm opt) ->
case P.parse areaOptAddrs "" (T.pack opt) of
Left err -> error $ show err -- TODO
Right y -> (AreaNameParsedOpt nm y)
_ -> _areaName
areaOptAddrs :: AreaOptionParser [AreaOptAddr]
areaOptAddrs = areaOptAddr `P.sepBy` (P.char '、')
areaOptAddr :: AreaOptionParser AreaOptAddr
areaOptAddr = _areaOptAddrWithBranch <#> _areaOptAddr
where
_areaOptAddrWithBranch :: AreaOptionParser AreaOptAddr
_areaOptAddrWithBranch =
(AreaOptAddrWithBranch <$> (areaRange <* P.char '-') <*> areaRange)
<#> (AreaOptAddrWithBranch <$> (areaRange <* P.char 'の') <*> areaRange)
_areaOptAddr :: AreaOptionParser AreaOptAddr
_areaOptAddr = AreaOptAddr <$> areaRange
areaNumNm :: AreaOptionParser AreaNumNm
areaNumNm = AreaNumNm <$> areaPrefix <*> areaNum <*> areaUnit <*> areaNotes
areaRange :: AreaOptionParser AreaRange
areaRange = _areaRange <#> _areaRangeNumOnly
where
_areaRangeNumOnly :: AreaOptionParser AreaRange
_areaRangeNumOnly = AreaRangeNumOnly <$> areaNumNm
_areaRange :: AreaOptionParser AreaRange
_areaRange = AreaRange <$> (areaNumNm <* P.char '~') <*> areaNumNm
areaPrefix :: AreaOptionParser String
areaPrefix =
P.many $
P.noneOf $
['0'..'9'] ++ (concat [[l, r] | (l, r) <- noteBrackets])
areaNum :: AreaOptionParser AreaNum
areaNum = _areaNum <#> (return NoNum)
where
_areaNum :: AreaOptionParser AreaNum
_areaNum = do
txt <- P.many1 $ P.oneOf ['0'..'9']
return $ AreaNum $ fullWidthNumToInt txt
units :: [String]
units = ["丁目", "番地", "番", "林班", "地割", "区"]
areaUnit :: AreaOptionParser String
areaUnit = (P.choice [P.string x | x <- units]) <#> P.string ""
areaNotes :: AreaOptionParser [AreaNote]
areaNotes = P.many areaNote
noteBrackets :: [(Char, Char)]
noteBrackets = [('「', '」'), ('〔', '〕')]
areaNote :: AreaOptionParser AreaNote
areaNote =
AreaParsedNote <$>
(P.choice $ genNoteParsers noteBrackets)
excTerm :: P.Parser String
excTerm = P.string "を除く" <#> P.string "以外"
sepStrs :: P.Parser String
sepStrs = P.choice $ concat [[P.string [x], P.string [y]] | (x, y) <- noteBrackets]
noteField :: P.Parser String
noteField = P.many $ P.noneOf $ concat [[x, y] | (x, y) <- noteBrackets]
mkNoteParser :: (Char, Char) -> P.Parser ParsedNote
mkNoteParser (lsep, rsep) =
--[ ExceptionNote <$> ((lp *> noteField <* excTerm) <* rp)
--, ExceptionNote <$> ((lp *> noteField <* rp) <* excTerm)
--, ParsedNote <$> (lp *> noteField <* rp)
--]
(ExceptionNote <$> ((P.between lp rp noteField) <* excTerm))
<#> (ParsedNote <$> (P.between lp rp noteField))
where
lp = P.char lsep
rp = P.char rsep
genNoteParsers :: [(Char, Char)] -> [AreaOptionParser ParsedNote]
genNoteParsers seps = map mkNoteParser seps
excludeSym :: AreaOptionParser String
excludeSym = P.string "を除く"
{-.オプションを単一化する -}
-- | 住所単位を振り分ける
normalizeAreaUnits :: [KenAllCsvRow] -> [KenAllCsvRow]
normalizeAreaUnits = map normalizeAreaUnit
normalizeAreaUnit :: KenAllCsvRow -> KenAllCsvRow
normalizeAreaUnit r = r{_areaName=aos}
where
an :: ParsedAreaName
an = _areaName r
aos =
case an of
(AreaNameParsedOpt nm os) -> AreaNameParsedOpt nm $ normalizeAreaUnitAux os
_ -> an
normalizeAreaUnitAux :: [AreaOptAddr] -> [AreaOptAddr]
normalizeAreaUnitAux [] = []
normalizeAreaUnitAux addrs = map (modifyUnit lastAreaUnit) addrs
where
lastAddr = last addrs
lastRange =
case lastAddr of
(AreaOptAddr range) -> range
(AreaOptAddrWithBranch _ right) -> right
lastAreaNumNm =
case lastRange of
(AreaRangeNumOnly x) -> x
(AreaRange _ x) -> x
lastAreaUnit =
case lastAreaNumNm of
(AreaNumNm _ _ u _) -> u
_ -> ""
modifyUnit :: String -> AreaOptAddr -> AreaOptAddr
modifyUnit u (AreaOptAddr range) = (AreaOptAddr (modifyUnit' u range))
modifyUnit u a@(AreaOptAddrWithBranch {..}) = a{_right=modifyUnit' u _right}
modifyUnit' :: String -> AreaRange -> AreaRange
modifyUnit' u (AreaRangeNumOnly numnm) = AreaRangeNumOnly $ modifyUnit'' u numnm
modifyUnit' u r@(AreaRange {..}) = r{_from=modifyUnit'' u _from, _to=modifyUnit'' u _to}
modifyUnit'' :: String -> AreaNumNm -> AreaNumNm
modifyUnit'' _ NoareaNumNm = NoareaNumNm
modifyUnit'' u ann@(AreaNumNm {..}) = ann{_unit=u}
normalizeLeftAreaRange :: KenAllCsvRow -> KenAllCsvRow
normalizeLeftAreaRange =
normalizeAreaRange _left (\_ r rngs -> [AreaOptAddr r' | r' <- init rngs] ++ [AreaOptAddrWithBranch (last rngs) r])
normalizeRightAreaRange :: KenAllCsvRow -> KenAllCsvRow
normalizeRightAreaRange =
normalizeAreaRange _right (\l _ rngs -> [AreaOptAddrWithBranch l r' | r' <- rngs])
normalizeAreaRange :: (AreaOptAddr -> AreaRange) -> (AreaRange -> AreaRange -> [AreaRange] -> [AreaOptAddr]) -> KenAllCsvRow -> KenAllCsvRow
normalizeAreaRange accessor mergeFunc r =
case (_areaName r) of
(AreaNameParsedOpt nm os) ->
r{_areaName=AreaNameParsedOpt nm $ normalizeAreaRangeAux accessor mergeFunc os}
_ -> r
normalizeAreaRangeAux :: (AreaOptAddr -> AreaRange) -> (AreaRange -> AreaRange -> [AreaRange] -> [AreaOptAddr]) -> [AreaOptAddr] -> [AreaOptAddr]
normalizeAreaRangeAux _ _ [] = []
normalizeAreaRangeAux bnchAccessor mergeFunc addrs = concatMap normalizeAreaRangeAux' addrs
where
normalizeAreaRangeAux' :: AreaOptAddr -> [AreaOptAddr]
normalizeAreaRangeAux' (AreaOptAddr r) =
[AreaOptAddr r' | r' <- normalizeAreaRangeAux'' r]
normalizeAreaRangeAux' a@(AreaOptAddrWithBranch {..}) = mergeFunc _left _right $ normalizeAreaRangeAux'' $ bnchAccessor a
normalizeAreaRangeAux'' :: AreaRange -> [AreaRange]
normalizeAreaRangeAux'' l@(AreaRangeNumOnly _) = [l]
normalizeAreaRangeAux'' (AreaRange f t) =
[AreaRangeNumOnly areaNm | areaNm <- normalizeAreaRangeAux''' f t]
normalizeAreaRangeAux''' :: AreaNumNm -> AreaNumNm -> [AreaNumNm]
normalizeAreaRangeAux''' NoareaNumNm to = [to]
normalizeAreaRangeAux''' from NoareaNumNm = [from]
normalizeAreaRangeAux''' from to =
[from{_num=(AreaNum i)} | i <- rng (_num from) (_num to)]
where
rng :: AreaNum -> AreaNum -> [Int]
rng NoNum NoNum = []
rng (AreaNum fi) NoNum = [fi]
rng NoNum (AreaNum ti) = [ti]
rng (AreaNum fi) (AreaNum ti) = [fi..ti]
normalizeAreaOptAddrs :: [KenAllCsvRow] -> [KenAllCsvRow]
normalizeAreaOptAddrs = concatMap normalizeAreaOptAddr
normalizeAreaOptAddr :: KenAllCsvRow -> [KenAllCsvRow]
normalizeAreaOptAddr r =
case (_areaName r) of
(AreaNameParsedOpt nm os) -> [r{_areaName=AreaNameParsedOpt nm [o]} | o <- os]
_ -> [r]
normalizeAreaRanges :: [KenAllCsvRow] -> [KenAllCsvRow]
normalizeAreaRanges = map (normalizeRightAreaRange . normalizeLeftAreaRange)
normalizeAreaOpts :: [KenAllCsvRow] -> [KenAllCsvRow]
normalizeAreaOpts =
normalizeAreaOptAddrs
. normalizeAreaRanges
. normalizeAreaUnits
. parseAreaOptions
parsedAreaNameToAreaName :: ParsedAreaName -> AreaName
parsedAreaNameToAreaName (AreaNameNoOpt s) = s
parsedAreaNameToAreaName (AreaNameOpt s1 s2) = s1 ++ s2
parsedAreaNameToAreaName (AreaNameBeginOpt s1 s2) = s1 ++ s2
parsedAreaNameToAreaName (AreaNameEndOpt s) = s
parsedAreaNameToAreaName (AreaNameParsedOpt s os) =
concat (s:(map areaOptAddrToText os))
where
areaOptAddrToText :: AreaOptAddr -> String
areaOptAddrToText (AreaOptAddr r) = areaRangeToText r
areaOptAddrToText (AreaOptAddrWithBranch{..}) =
concat [areaRangeToText _left, "-", areaRangeToText _right]
areaRangeToText :: AreaRange -> String
areaRangeToText (AreaRangeNumOnly n) = areaNumNmToText n
areaRangeToText (AreaRange{..}) =
concat [areaNumNmToText _from, "~", areaNumNmToText _to]
areaNumNmToText :: AreaNumNm -> String
areaNumNmToText NoareaNumNm = ""
areaNumNmToText (AreaNumNm{..}) =
concat [_prefix, areaNumToText _num, _unit]
areaNumToText :: AreaNum -> String
areaNumToText NoNum = ""
areaNumToText (AreaNum n) = show n
convertToNormalizedCsvRow :: KenAllCsvRow -> NormalizedCsvRow
convertToNormalizedCsvRow (KenAllCsvRow{..}) =
NormalizedCsvRow _stateName _cityName _postalCode (parsedAreaNameToAreaName _areaName) _latitude _longitude
normalizeKenAllCsv :: Csv -> [NormalizedCsvRow]
normalizeKenAllCsv =
(map convertToNormalizedCsvRow)
. normalizeAreaOpts
. margeRows
. reduceKenAllCsv
type AreaGeoMap = M.Map String [AreaGeoInfo]
type AreaGeoInfo = (AreaName, Latitude, Longitude)
csvToAreaGeoInfo :: Csv -> AreaGeoMap
csvToAreaGeoInfo cs = M.fromListWith (++) [(stateNm r ++ cityNm r, [(areaNm r, lat r, lon r)]) | r <- cs]
where
stateNm :: CsvRow -> StateName
stateNm r = r !! 0
cityNm :: CsvRow -> CityName
cityNm r = r !! 1
areaNm :: CsvRow -> AreaName
areaNm r = r !! 2
lat :: CsvRow -> Latitude
lat r = read (r !! 7) :: Latitude
lon :: CsvRow -> Longitude
lon r = read (r !! 8) :: Longitude
mixedCsvRowToText :: NormalizedCsvRow -> T.Text
mixedCsvRowToText (NormalizedCsvRow {..}) =
T.intercalate (T.pack ",")
[
T.pack _PostalCode
, T.pack _StateName
, T.pack _CityName
, T.pack _AreaName
, T.pack lat
, T.pack lon
]
where
lat = case _Latitude of
Just x -> show x
Nothing -> ""
lon = case _Longitude of
Just x -> show x
Nothing -> ""
hasLocation :: NormalizedCsvRow -> Bool
hasLocation (NormalizedCsvRow{..}) = _Latitude /= Nothing && _Longitude /= Nothing
mix :: AreaGeoMap -> [NormalizedCsvRow] -> [NormalizedCsvRow]
mix sgi = map (mixRow sgi)
mixRow :: AreaGeoMap -> NormalizedCsvRow -> NormalizedCsvRow
mixRow sgi row
| hasLocation row = row
| otherwise =
case (lookupAreaGeoInfoList sgi (_StateName row) (_CityName row)) of
Nothing -> row
Just x ->
case findMinEditDistanceAreaName x (_AreaName row) of
Nothing -> row
Just (_, lat, lon) ->
row{_Latitude = (Just lat), _Longitude = (Just lon)}
lookupAreaGeoInfoList :: AreaGeoMap -> StateName -> CityName -> Maybe([AreaGeoInfo])
lookupAreaGeoInfoList t sn cn = M.lookup (sn ++ cn) t
findMinEditDistanceAreaName :: [AreaGeoInfo] -> AreaName -> Maybe(AreaGeoInfo)
findMinEditDistanceAreaName [] _ = Nothing
findMinEditDistanceAreaName ax n =
Just $ fst $ L.minimumBy cmp [(a, editDist an n) | a@(an, _, _) <- ax]
where
cmp :: (a, Int) -> (b, Int) -> Ordering
cmp (_, c1) (_, c2)
| c1 < c2 = LT
| otherwise = GT
editDist :: String -> String -> Int
editDist = ED.levenshteinDistance ED.defaultEditCosts
| eji/mix-kenall-geocode | src/cli/Main.hs | mit | 16,640 | 0 | 20 | 3,320 | 5,063 | 2,701 | 2,362 | 398 | 8 |
{-# LANGUAGE FlexibleContexts #-}
module Rx.Logger.Core where
import Control.Concurrent (myThreadId)
import Data.Text.Format (Format, format)
import Data.Text.Format.Params (Params)
import Data.Time (getCurrentTime)
import Rx.Observable (onNext)
import Rx.Subject (newPublishSubject)
import Rx.Logger.Types
--------------------------------------------------------------------------------
newLogger :: IO Logger
newLogger = newPublishSubject
logMsg :: (ToLogger logger, ToLogMsg msg)
=> LogLevel
-> logger
-> msg
-> IO ()
logMsg level logger0 msg = do
let logger = toLogger logger0
time <- getCurrentTime
tid <- myThreadId
onNext logger $! LogEntry time (LogMsg msg) level tid
trace :: (ToLogger logger, ToLogMsg msg) => logger -> msg -> IO ()
trace = logMsg TRACE
loud :: (ToLogger logger, ToLogMsg msg) => logger -> msg -> IO ()
loud = logMsg LOUD
noisy :: (ToLogger logger, ToLogMsg msg) => logger -> msg -> IO ()
noisy = logMsg NOISY
config :: (ToLogger logger, ToLogMsg msg) => logger -> msg -> IO ()
config = logMsg CONFIG
info :: (ToLogger logger, ToLogMsg msg) => logger -> msg -> IO ()
info = logMsg INFO
warn :: (ToLogger logger, ToLogMsg msg) => logger -> msg -> IO ()
warn = logMsg WARNING
severe :: (ToLogger logger, ToLogMsg msg) => logger -> msg -> IO ()
severe = logMsg SEVERE
logF ::
(ToLogger logger, Params params)
=> LogLevel -> logger -> Format -> params -> IO ()
logF level logger txtFormat params =
logMsg level logger (format txtFormat params)
traceF ::
(ToLogger logger, Params params) => logger -> Format -> params -> IO ()
traceF = logF TRACE
loudF ::
(ToLogger logger, Params params) => logger -> Format -> params -> IO ()
loudF = logF LOUD
noisyF ::
(ToLogger logger, Params params) => logger -> Format -> params -> IO ()
noisyF = logF NOISY
configF ::
(ToLogger logger, Params params) => logger -> Format -> params -> IO ()
configF = logF CONFIG
infoF ::
(ToLogger logger, Params params) => logger -> Format -> params -> IO ()
infoF = logF INFO
warnF ::
(ToLogger logger, Params params) => logger -> Format -> params -> IO ()
warnF = logF WARNING
severeF ::
(ToLogger logger, Params params) => logger -> Format -> params -> IO ()
severeF = logF SEVERE
| roman/Haskell-Reactive-Extensions | rx-logger/src/Rx/Logger/Core.hs | mit | 2,289 | 0 | 11 | 466 | 866 | 449 | 417 | 61 | 1 |
main = do
let a = 20
let b = 10
let c = 15
let d = 5
putStrLn $ show (a+b*c-a+b*d)
putStrLn $ show (a+(b*c)-a+(b*d))
let e = (a+b)*c/d
putStrLn $ "(a+b)*c/d = " ++ show e
let e = ((a+b)*c)/d
putStrLn $ "((a+b)*c)/d = " ++ show e
let e = (a+b)*(c/d)
putStrLn $ "(a+b)*(c/d) = " ++ show e
let e = a+(b*c/d)
putStrLn $ "a + (b*c/d) = " ++ show e
| folivetti/PI-UFABC | AULA_01/Haskell/operadores_precedencia.hs | mit | 443 | 0 | 14 | 177 | 272 | 131 | 141 | 15 | 1 |
{-# LANGUAGE OverloadedStrings , BangPatterns #-}
module Autorotate where
import Data.Maybe ( isNothing , isJust , catMaybes )
import Data.Ratio ( Ratio , (%) , numerator , denominator )
import Data.List ( intersperse , findIndex , transpose , maximumBy )
import Data.Tuple ( swap )
import Control.Applicative ( many , empty )
import Control.Monad ( liftM )
import Control.Monad.IO.Class ( liftIO )
import Control.Monad.Trans.Resource ( release )
import System.Environment
import Text.Printf
import Data.Text as Text ( pack )
import Data.Text.Encoding ( encodeUtf8 )
import qualified Data.Vector.Storable as Vector
import Graphics.ImageMagick.MagickWand
-- load an image file, trim, rotate and save it
autorotate
:: String -- name of original file
-> String -- name of output file
-> Rational -- imagemagick fuzz for rotation and trim operations
-> Rational -- resize factor to reduce edge detection work
-> Int -- slot count for edge detection algorithm
-> String -- background color for rotation and trim operations
-> IO ()
autorotate in_file out_file fuzz resize slots bg_color = withMagickWandGenesis $ do
let in_file' = pack in_file
out_file' = pack out_file
bg_color' = encodeUtf8 $ pack bg_color
background <- pixelWand
background `setColor` bg_color'
(_,original_image) <- magickWand
readImage original_image in_file'
depth <- getImageDepth original_image >>= (return . fromIntegral)
-- to do: is this always the correct maximum intensity?
-- 2^16 works for my scanned images (8-bit depth)
let fuzz' = fromRational $ fuzz * (2^(2 * depth))
trimImage original_image fuzz'
width <- return . fromIntegral =<< getImageWidth original_image
height <- return . fromIntegral =<< getImageHeight original_image
-- duplicating and scaling the image prevents the edge detection algorithms
-- from taking too much memory and time
let max_length = 400 -- good for a ghc default 8MB stack
scale' = minimum [ resize , max_length % height , max_length % width ]
width' = truncate $ (toRational width) * scale'
height' = truncate $ (toRational height) * scale'
(_,scaled_image) <- cloneMagickWand original_image
resizeImage scaled_image width' height' gaussianFilter 1
transparentPaintImage scaled_image background 0 fuzz' False
edges <- getSlopesHaskell scaled_image
let slopes = concat $ map all_slopes edges
-- the lowest slope value should be 1 (i.e. a 45 degree rotation)
-- using 1.2 scale to allow grouping above, but close to, a slope of 1
-- but 1.0 should work perfectly
distr = makeDistribution slots 1.2 slopes
compare_length a b = compare (length a) (length b)
max_distr = maximumBy compare_length distr
avg_m = (sum max_distr) / (fromIntegral $ length max_distr)
theta = (atan $ fromRational avg_m) * 180 / pi
-- liftIO $ putStrLn $ "theta: " ++ (show theta)
rotateImage original_image background theta
-- using fuzz' * 3 works pretty well; need to trim more aggressively for the final result
trimImage original_image (fuzz' * 2)
writeImage original_image (Just out_file')
return ()
lift_fst (Nothing,s) = Nothing
lift_fst (Just f, s) = Just (f,s)
lift_snd (f,Nothing) = Nothing
lift_snd (f, Just s) = Just (f,s)
-- get the index (x-coord) of the first non-trasparent point in a row
find_left_edges :: [[Bool]] -> [Maybe Integer]
find_left_edges = map (liftM fromIntegral . findIndex id)
-- same idea, but using a row iterator in the image monad
find_left_edgesM it = do
row <- pixelGetNextIteratorRow it
case row of Nothing -> return []
Just row -> do alphas <- Vector.mapM getAlphaQuantum row
let edge = maybe Nothing (Just . fromIntegral) $ Vector.findIndex (/= 0) alphas
edges <- find_left_edgesM it
return $ edge:edges
-- calculate the slope (actually, its reciprocal) of every combination of points in a list of them
all_slopes :: [(Integer,Integer)] -> [Rational]
all_slopes [] = []
all_slopes (pt:pts) = slopes ++ all_slopes pts
where
slopes = map (get_slope pt) pts
get_slope (x1,y1) (x2,y2) = (x1 - x2) % (y1 - y2)
-- gather a list of Rationals into a list of lists, grouping close values
makeDistribution :: Int -> Rational -> [Rational] -> [[Rational]]
makeDistribution resolution scale values = groups
where
offset = resolution `div` 2
res' = fromIntegral resolution
mk_val_pair v = ((round $ v * res' / scale) + offset , v)
val_pairs = map mk_val_pair values
groups = map (\i -> map snd $ filter ((==i) . fst) val_pairs) [0..resolution]
-- turn rows of pixels into a transparency mask
mk_mask it = do
let mask_row row = do
alphas <- Vector.mapM getAlphaQuantum row
let mask = Vector.toList $ Vector.map (/=0) alphas
masks <- mk_mask it
return $ mask:masks
row <- pixelGetNextIteratorRow it
maybe (return []) mask_row row
-- use a Haskell matrix to do edge detection
getSlopesHaskell scaled_image = do
mask <- mk_mask =<< (return . snd) =<< pixelIterator scaled_image
let
mask' = transpose mask
mask0 = mask
mask90 = map reverse mask'
mask180 = reverse $ map reverse mask
mask270 = reverse $ mask'
left_edges = map lift_fst $ zip (find_left_edges mask0 ) [0..]
bottom_edges = map lift_fst $ zip (find_left_edges mask90 ) [0..]
right_edges = map lift_fst $ zip (find_left_edges mask180) [0..]
top_edges = map lift_fst $ zip (find_left_edges mask270) [0..]
return $ map catMaybes [left_edges, bottom_edges, right_edges, top_edges]
-- use imagemagick flip and flop rather than matrix manipulation
getSlopesFlipFlop background scaled_image = do
-- writeImage scaled_image (Just "s-left.png")
left_edges <- return . map lift_fst =<< return . flip zip [0..] =<< find_left_edgesM =<< return . snd =<< pixelIterator scaled_image
flopImage scaled_image
flipImage scaled_image
-- writeImage scaled_image (Just "s-right.png")
right_edges <- return . map lift_fst =<< return . flip zip [0..] =<< find_left_edgesM =<< return . snd =<< pixelIterator scaled_image
rotateImage scaled_image background 90
-- writeImage scaled_image (Just "s-top.png")
top_edges <- return . map lift_fst =<< return . flip zip [0..] =<< find_left_edgesM =<< return . snd =<< pixelIterator scaled_image
flopImage scaled_image
flipImage scaled_image
-- writeImage scaled_image (Just "s-bottom.png")
bottom_edges <- return . map lift_fst =<< return . flip zip [0..] =<< find_left_edgesM =<< return . snd =<< pixelIterator scaled_image
return $ map catMaybes [left_edges, bottom_edges, right_edges, top_edges]
-- use imagemagick rotation rather than matrix manipulation
getEdgesRotate background scaled_image = do
-- writeImage scaled_image (Just "s0.png")
left_edges <- return . map lift_fst =<< return . flip zip [0..] =<< find_left_edgesM =<< return . snd =<< pixelIterator scaled_image
rotateImage scaled_image background 90
-- writeImage scaled_image (Just "s90.png")
bottom_edges <- return . map lift_fst =<< return . flip zip [0..] =<< find_left_edgesM =<< return . snd =<< pixelIterator scaled_image
rotateImage scaled_image background 90
-- writeImage scaled_image (Just "s180.png")
right_edges <- return . map lift_fst =<< return . flip zip [0..] =<< find_left_edgesM =<< return . snd =<< pixelIterator scaled_image
rotateImage scaled_image background 90
-- writeImage scaled_image (Just "s270.png")
top_edges <- return . map lift_fst =<< return . flip zip [0..] =<< find_left_edgesM =<< return . snd =<< pixelIterator scaled_image
return $ map catMaybes [left_edges, bottom_edges, right_edges, top_edges]
-- below are some unmaintained ways to help visualize what the algorithm is doing
drawDistribution hw_ratio values = do
let width = length values
height = fromIntegral $ fst $ properFraction $ (fromIntegral width) * hw_ratio
offset = length $ takeWhile ((< 0) . fst) values
max_value = fromIntegral $ foldl1 max $ map snd values
liftIO $ putStrLn $ "max_value: " ++ (show max_value)
(_,w) <- magickWand
(_,dw) <- drawingWand
c <- pixelWand
setColor c "white"
newImage w width height c
setStrokeOpacity dw 1
setStrokeWidth dw 1
setStrokeAntialias dw True
setColor c "black"
let draw_value x v = drawLine dw x' h' x' v'
where
x' = fromIntegral x
h' = fromIntegral height
v' = fromRational $ ((fromIntegral height) * (fromIntegral v)) % max_value
--height - ((fromIntegral v) * (fromIntegral height) % max_value)
mapM (uncurry draw_value) $ zip [0..] $ map snd values
drawImage w dw
return w
drawFreqs :: Integer -> Integer -> Rational -> [Rational] -> IO Double
drawFreqs width height scale xs = withMagickWandGenesis $ do
let xs' = map ((+(width `div` 2)).floor.(/ scale).(*(fromIntegral width))) xs
freq as a = fromIntegral $ length $ filter (==a) as
freqs = map (freq xs') [0..(2 * width)]
let max_snd lhs rhs | (snd rhs) > (snd lhs) = rhs
| otherwise = lhs
major = foldl1 max_snd $ zip [0..] freqs
m' = (fst major) + 50
m = (fromIntegral $ m' - (width `div` 2)) * scale / (fromIntegral width)
theta = if m == 0 then 0 else atan $ fromRational $ recip m
let --theta = 2.5 :: Double
m2 = tan theta
y_m2 = (floor $ (realToFrac m2) / scale * (fromIntegral width)) + (width `div` 2)
(_,w) <- magickWand
(_,dw) <- drawingWand
c <- pixelWand
c `setColor` "white"
newImage w (fromInteger width) (fromInteger height) c
dw `setStrokeOpacity` 1
dw `setStrokeWidth` 1
dw `setStrokeAntialias` True
c `setColor` "red"
dw `setStrokeColor` c
drawLine dw (fromIntegral $ width `div` 2) (fromIntegral height) (fromIntegral $ width `div` 2) 0
c `setColor` "red"
dw `setStrokeColor` c
drawLine dw (fromIntegral $ y_m2) (fromIntegral height) (fromIntegral $ y_m2) 0
c `setColor` "black"
dw `setStrokeColor` c
let v_scale = height % (snd major)
let draw_freq dw x f = drawLine dw (fromIntegral x) (fromRational ((fromIntegral height) - ((fromIntegral f)*v_scale))) (fromIntegral x) (fromIntegral height)
mapM (uncurry $ draw_freq dw) $ zip [0..] freqs
drawImage w dw
writeImage w (Just "data.png")
liftIO $ putStrLn $ "m': " ++ (show m')
liftIO $ putStrLn $ "m: " ++ (show m)
liftIO $ putStrLn $ "width: " ++ (show $ width `div` 2)
liftIO $ putStrLn $ "scale: " ++ (show scale)
liftIO $ putStrLn $ "theta': " ++ (show theta)
return theta
{- drawEdge coords
-
- visualize the left edge
-
-}
drawEdge edges = do
let right_margin = 100
width = right_margin + (foldl1 max $ map fst $ catMaybes edges)
height = length edges
width' = fromIntegral width
(_,w) <- magickWand
(_,dw) <- drawingWand
c <- pixelWand
setColor c "white"
newImage w width height c
setColor c "black"
setStrokeColor dw c
setStrokeWidth dw 1
setStrokeOpacity dw 1
let draw_edge (x,y) = drawLine dw x' y' width' y'
where
x' = fromIntegral x
y' = fromIntegral y
mapM draw_edge $ catMaybes edges
drawImage w dw
return w
drawMask rows = do
(_,w) <- magickWand
(_,dw) <- drawingWand
black <- pixelWand
white <- pixelWand
setColor black "black"
setColor white "white"
let height = length rows
width = length $ head rows
newImage w width height white
setStrokeColor dw black
setStrokeWidth dw 1
setStrokeOpacity dw 1
let rows' = zip [0..] rows
pts = concat $ map (uncurry mk_pts) $ zip [0..] rows
mk_pts y row = map (uncurry (mk_pt y)) $ zip [0..] row
mk_pt y x c = ((x,y),c)
black_pts = filter snd pts
mapM (\(x,y) -> drawPoint dw (fromIntegral x) (fromIntegral y)) $ map fst $ filter snd pts
drawImage w dw
return w
| mikehat/autorotate-image | Autorotate.hs | mit | 12,843 | 2 | 19 | 3,545 | 3,756 | 1,883 | 1,873 | 225 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad.Catch
import Codec.Binary.UTF8.String (decode)
import Config
import Control.Applicative
import Control.Concurrent
import Control.Monad.Except
import Control.Monad.Reader
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import Diaspora
import Network.HTTP.Conduit
import RSS
import Safe
import qualified System.IO.Strict as Strict
import System.Environment
import Text.Feed.Import
import Text.Feed.Query
import Text.Feed.Types
main :: IO ()
main =
do args <- getArgs
if length args < 1
then putStrLn "usage: ./rssbot path/to/config"
else do conffile <- readConfigFile (head args)
case conffile of
Right conf ->
forever $
flip runReaderT conf $
do rssStr <- lift $
simpleHttp (rssURL conf) `catch`
networkHandler
replaced <- replaceIfNecessary rssStr
case replaced of
Nothing -> lift sleep
Just text ->
do _ <- post text `catch`
(lift . networkHandler)
lift sleep
Left e -> print e
networkHandler :: HttpException -> IO BL.ByteString
networkHandler e =
print e >>
return ""
sleep :: IO ()
sleep =
threadDelay
(300 * 10 ^
(6 :: Int))
replaceIfNecessary :: BL.ByteString -> ReaderT ConfigFile IO (Maybe T.Text)
replaceIfNecessary rssStr =
do let maybeItem = getFirstFeedItem rssStr
case maybeItem of
Nothing -> return Nothing
Just item ->
do let maybeId = getItemId item
case maybeId of
Nothing -> replaceFeedItem' item
Just (_,itemId) ->
replaceIfNew item itemId
readHandler :: IOError -> IO String
readHandler _ =
putStrLn "feed item id could not be read" >>
return ""
writeHandler :: IOError -> IO ()
writeHandler e = putStrLn $ "feed item id could not be written" ++ show e
replaceIfNew :: Item -> String -> ReaderT ConfigFile IO (Maybe T.Text)
replaceIfNew item itemId = do
old <- lift $ Strict.readFile "itemid" `catch` readHandler
if itemId == old
then return Nothing
else do lift $ writeFile "itemid" itemId `catch` writeHandler
replaceFeedItem' item
getFirstFeedItem :: BL.ByteString -> Maybe Item
getFirstFeedItem rssStr = do feed <- parseFeedString . decode $ BL.unpack rssStr
headMay . getFeedItems $ feed
replaceFeedItem' :: Item -> ReaderT ConfigFile IO (Maybe T.Text)
replaceFeedItem' item =
replaceFeedItem item <$>
asks absPath <*>
asks tags
| cocreature/rss2diaspora-hs | Bot.hs | mit | 2,973 | 0 | 24 | 1,050 | 755 | 382 | 373 | 82 | 4 |
import GarbageHat.Analysis
import GarbageHat.Domain
import GarbageHat.Parser
import System.Environment (getArgs)
import Control.Monad (mapM_)
import Data.Decimal (roundTo)
import Data.List (intercalate)
import Data.Set (toList)
main :: IO ()
main = do
args <- getArgs
case args of
[] -> usageHelp
["-parse", filename] -> report parseOnly filename
["-summary", filename] -> report reportSummary filename
[filename] -> report reportSummary filename
_ -> usageHelp
usageHelp = do
putStrLn "garbagehat filename"
report :: ([Event] -> IO ()) -> String -> IO ()
report f filename = do
input <- readFile filename
case (parseInput filename input) of
Left err -> putStrLn $ show err
Right events -> f events
parseOnly :: [Event] -> IO ()
parseOnly events = mapM_ (putStrLn . show) $ expandStoppedEvents events
reportSummary :: [Event] -> IO ()
reportSummary events = do
printSummary
printAnalysis
where
statistics = statisticsSummary events
printSummary = do
putStrLn "========================================"
putStrLn "SUMMARY:"
putStrLn "========================================"
putStrLn $ "# GC Events: " ++ show (eventCount statistics)
putStrLn $ "GC Event Types: " ++ (intercalate ", " $ toList $ eventTypes statistics)
putStrLn $ "Max Heap Space: " ++ show (maxHeapCapacity statistics) ++ "K"
putStrLn $ "Max Heap Occupancy: " ++ show (maxHeapUsage statistics) ++ "K"
putStrLn $ "Max Perm Space: " ++ show (maxPermCapacity statistics) ++ "K"
putStrLn $ "Max Perm Occupancy: " ++ show (maxPermUsage statistics) ++ "K"
case (throughput statistics) of
Just t -> putStrLn $ "Throughput: " ++ show (roundTo 2 $ t * 100) ++ "%"
Nothing -> return ()
putStrLn $ "Max Pause: " ++ show (getDuration $ maxPause statistics) ++ "ms"
putStrLn $ "Total Pause: " ++ show (getDuration $ totalPause statistics) ++ "ms"
case (firstTimestamp statistics, lastTimestamp statistics) of
(Timestamp (Just ft) _, Timestamp (Just lt) _) -> do
putStrLn $ "First Timestamp: " ++ show ft ++ "ms"
putStrLn $ "Last Timestamp: " ++ show lt ++ "ms"
_ -> putStrLn "No timestamps"
printAnalysis = do
putStrLn "========================================"
putStrLn "ANALYSIS:"
putStrLn "========================================"
| doctau/garbagehat | Main.hs | epl-1.0 | 2,400 | 0 | 18 | 528 | 753 | 361 | 392 | 56 | 5 |
{- |
Module : $Header$
Description : Helper functions for dealing with terms
(mainly for pretty printing which is
directly adapted from hollight)
Copyright : (c) Jonathan von Schroeder, DFKI GmbH 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : jonathan.von_schroeder@dfki.de
Stability : experimental
Portability : portable
-}
module HolLight.Helper where
import Data.Maybe (fromJust, isJust, catMaybes)
import HolLight.Term
import Data.List (union, (\\), find)
import Common.Doc
import Data.Char as Char
names :: [String]
names =
let
nextName [] = "a"
nextName (x : xs) = if Char.ord x >= 122
then 'a' : nextName xs
else Char.chr (Char.ord x + 1) : xs
in iterate (reverse . nextName . reverse) "a"
freeName :: [String] -> String
freeName ns = head (filter (\ x -> case find (== x) ns
of Nothing -> True
_ -> False) names)
fromRight :: Either t t1 -> t1
fromRight e = case e of
Right t -> t
Left _ -> error "fromRight"
isPrefix :: Term -> Bool
isPrefix tm = case tm of
Var _ _ (HolTermInfo (Prefix, _)) -> True
Const _ _ (HolTermInfo (Prefix, _)) -> True
_ -> False
ppPrintType :: HolType -> Doc
ppPrintType = sot 0
soc :: String -> Bool -> [Doc] -> Doc
soc sep' flag ss = if null ss then empty
else let s = foldr1 (\ s1 s2 -> hcat [s1, text sep', s2]) ss
in if flag then parens s else s
sot :: Int -> HolType -> Doc
sot pr ty = case (destVartype ty, destType ty) of
-- exactly one of these is not Nothing
(Just vtype, _) -> text vtype
(_, Just t) -> case t of
(con, []) -> text con
("fun", [ty1, ty2]) -> soc "->" (pr > 0) [sot 1 ty1, sot 0 ty2]
("sum", [ty1, ty2]) -> soc "+" (pr > 2) [sot 3 ty1, sot 2 ty2]
("prod", [ty1, ty2]) -> soc "#" (pr > 4) [sot 5 ty1, sot 4 ty2]
("cart", [ty1, ty2]) -> soc "^" (pr > 6) [sot 6 ty1, sot 7 ty2]
(con, args) -> hcat [soc "," True (map (sot 0) args), text con]
_ -> empty -- doesn't happen
-- lib.ml
revAssocd :: Eq t1 => t1 -> [(t, t1)] -> t -> t
revAssocd a l d = case l of
[] -> d
(x, y) : t -> if y == a then x
else revAssocd a t d
-- fusion.ml
destVar :: Term -> Maybe (String, HolType)
destVar v = case v of
Var s ty _ -> Just (s, ty)
_ -> Nothing
isVar :: Term -> Bool
isVar v = isJust (destVar v)
frees :: Term -> [Term]
frees tm = case tm of
Var {} -> [tm]
Const {} -> []
Abs bv bod -> frees bod \\ [bv]
Comb s t -> frees s `union` frees t
vfreeIn :: Term -> Term -> Bool
vfreeIn v tm = case tm of
Abs bv bod -> v /= bv && vfreeIn v bod
Comb s t -> vfreeIn v s || vfreeIn v t
_ -> tm == v
variant :: [Term] -> Term -> Maybe Term
variant avoid v = if not (any (vfreeIn v) avoid) then Just v
else case v of
Var s ty p -> variant avoid (Var (s ++ "'") ty p)
_ -> Nothing
vsubst :: [(Term, Term)] -> Term -> Maybe Term
vsubst =
let vsubst' ilist tm = case tm of
Var {} -> Just $ revAssocd tm ilist tm
Const {} -> Just tm
Comb s t -> case (vsubst' ilist s, vsubst ilist t) of
(Just s', Just t') -> Just $ if s' == s && t' == t
then tm
else Comb s' t'
_ -> Nothing
Abs v s -> let ilist' = filter (\ (_, x) -> x /= v)
ilist
in if null ilist' then Just tm
else case vsubst ilist' s of
Just s' | s' == s -> Just tm
| any (\ (t, x) -> vfreeIn v t
&& vfreeIn x s)
ilist' ->
case variant [s'] v of
Just v' -> case vsubst
((v', v) : ilist') s of
Just t' ->
Just (Abs v' t')
_ -> Nothing
_ -> Nothing
| otherwise -> Just (Abs v s')
_ -> Nothing
in \ theta ->
if null theta then Just else
if all (\ (t, x) -> case (typeOf t, destVar x) of
(Just t', Just (_, x')) -> t' == x'
_ -> False) theta then vsubst' theta
else const Nothing
destComb :: Term -> Maybe (Term, Term)
destComb c = case c of
Comb f x -> Just (f, x)
_ -> Nothing
isComb :: Term -> Bool
isComb c = isJust (destComb c)
destConst :: Term -> Maybe (String, HolType)
destConst c = case c of
Const s ty _ -> Just (s, ty)
_ -> Nothing
isConst :: Term -> Bool
isConst c = isJust (destConst c)
destAbs :: Term -> Maybe (Term, Term)
destAbs a = case a of
Abs v b -> Just (v, b)
_ -> Nothing
isAbs :: Term -> Bool
isAbs a = isJust (destAbs a)
rator :: Term -> Maybe Term
rator tm = fmap fst (destComb tm)
rand :: Term -> Maybe Term
rand tm = fmap snd (destComb tm)
splitlist :: (t -> Maybe (a, t)) -> t -> ([a], t)
splitlist dest x = case dest x of
Just (l, r) -> let (ls, res) = splitlist dest r
in (l : ls, res)
_ -> ([], x)
revSplitlist :: (t -> Maybe (t, t1)) -> t -> (t, [t1])
revSplitlist dest x =
let rsplist ls x' = case dest x' of
Just (l, r) -> rsplist (r : ls) l
_ -> (x', ls)
in rsplist [] x
typeOf :: Term -> Maybe HolType
typeOf tm = case tm of
Var _ ty _ -> Just ty
Const _ ty _ -> Just ty
Comb s _ -> case typeOf s of
Just t -> case destType t of
Just (_, _ : x1 : _) -> Just x1
_ -> Nothing
_ -> Nothing
Abs (Var _ ty _) t -> case typeOf t of
Just t' -> Just (TyApp "fun" [ty, t'])
_ -> Nothing
_ -> Nothing
destType :: HolType -> Maybe (String, [HolType])
destType a = case a of
TyApp s ty -> Just (s, ty)
_ -> Nothing
destVartype :: HolType -> Maybe String
destVartype t = case t of
TyVar s -> Just s
_ -> Nothing
typeSubst :: [(HolType, HolType)] -> HolType -> HolType
typeSubst i ty = case ty of
TyApp tycon args -> let args' = map (typeSubst i) args
in if args' == args then ty else TyApp tycon args'
_ -> revAssocd ty i ty
mkEq :: (Term, Term) -> Maybe Term
mkEq (l, r) = case (typeOf l, mkConst ("=", [])) of
(Just ty, Just eq) -> case inst [(ty, TyVar "A")] eq of
Right eq_tm -> case mkComb (eq_tm, l) of
Just m1 -> mkComb (m1, r)
_ -> Nothing
_ -> Nothing
_ -> Nothing
inst :: [(HolType, HolType)] -> Term -> Either Term Term
inst =
let inst' env tyin tm = case tm of
Var n ty at -> let ty' = typeSubst tyin ty
in let tm' = if ty' == ty then tm
else Var n ty' at
in if revAssocd tm' env tm == tm
then Right tm'
else Left tm'
Const c ty at -> let ty' = typeSubst tyin ty
in Right $ if ty' == ty
then tm
else Const c ty' at
Comb f x -> case (inst' env tyin f,
inst' env tyin x) of
(Right f', Right x') ->
Right $ if f' == f && x' == x
then tm else Comb f' x'
(Left c, _) -> Left c
(_, Left c) -> Left c
Abs y t -> case inst' [] tyin y of
Right y' -> let env' = (y, y') : env
in case inst' env' tyin t of
Right t' ->
Right $ if y' == y && t' == t
then tm else Abs y' t'
Left w' -> if w' /= y'
then Left w'
else let ifrees = map (fromRight .
inst' [] tyin)
(frees t) in
case variant ifrees y' of
Just y'' ->
case (destVar y'', destVar y) of
(Just (v1, _), Just (_, v2)) ->
let z = Var v1 v2
(HolTermInfo
(Normal, Nothing))
in case vsubst [(z, y)] t of
Just s -> inst' env tyin
(Abs z s)
_ -> Left w'
_ -> Left w'
_ -> Left w'
_ -> Left tm
in (\ tyin -> if null tyin then Right else inst' [] tyin)
mkComb :: (Term, Term) -> Maybe Term
mkComb (f, a) = case typeOf f of
Just (TyApp "fun" [ty, _]) -> case typeOf a of
Just t -> if ty == t then Just (Comb f a) else Nothing
_ -> Nothing
_ -> Nothing
eqType :: HolType
eqType = TyApp "fun" [
TyVar "A",
TyApp "fun" [
TyVar "A",
TyApp "bool" []
]]
mkConst :: (String, [(HolType, HolType)]) -> Maybe Term
mkConst (name, theta) = if name == "="
then Just (Const name
(typeSubst theta eqType)
(HolTermInfo (InfixR 12, Nothing)))
else Nothing
-- basics.ml
destBinder :: String -> Term -> Maybe (Term, Term)
destBinder s tm = case tm of
Comb (Const s' _ _) (Abs x t) ->
if s' == s then Just (x, t)
else Nothing
_ -> Nothing
destExists :: Term -> Maybe (Term, Term)
destExists = destBinder "?"
stripExists :: Term -> ([Term], Term)
stripExists = splitlist destExists
destForall :: Term -> Maybe (Term, Term)
destForall = destBinder "!"
stripForall :: Term -> ([Term], Term)
stripForall = splitlist destForall
stripComb :: Term -> (Term, [Term])
stripComb = revSplitlist destComb
body :: Term -> Maybe Term
body tm = case destAbs tm of
Just (_, ret) -> Just ret
_ -> Nothing
destNumeral :: Term -> Maybe Integer
destNumeral tm' =
let dest_num tm = case destConst tm of
Just ("_0", _) -> Just (toInteger (0 :: Int))
_ -> case destComb tm of
Just (l, r) -> case dest_num r of
Just i ->
let n = toInteger (2 :: Int) * i
in case destConst l of
Just ("BIT0", _) -> Just n
Just ("BIT1", _) -> Just (n
+ toInteger (1 :: Int))
_ -> Nothing
_ -> Nothing
_ -> Nothing
in case destComb tm' of
Just (l, r) -> case destConst l of
Just ("NUMERAL", _) -> dest_num r
_ -> Nothing
_ -> Nothing
destBinary' :: String -> Term -> Maybe (Term, Term)
destBinary' s tm = case tm of
Comb (Comb (Const s' _ _) l) r -> if s' == s then Just (l, r)
else Nothing
_ -> Nothing
destCons :: Term -> Maybe (Term, Term)
destCons = destBinary' "CONS"
destList :: Term -> Maybe [Term]
destList tm = let (tms, nil) = splitlist destCons tm
in case destConst nil of
Just ("NIL", _) -> Just tms
_ -> Nothing
destGabs :: Term -> Maybe (Term, Term)
destGabs tm =
let dest_geq = destBinary' "GEQ"
in if isAbs tm then destAbs tm
else case destComb tm of
Just (l, r) -> case destConst l of
Just ("GABS", _) -> case body r of
Just b -> case dest_geq (snd (stripForall b)) of
Just (ltm, rtm) -> case rand ltm of
Just r' -> Just (r', rtm)
_ -> Nothing
_ -> Nothing
_ -> Nothing
_ -> Nothing
_ -> Nothing
isGabs :: Term -> Bool
isGabs tm = isJust (destGabs tm)
stripGabs :: Term -> ([Term], Term)
stripGabs = splitlist destGabs
destFunTy :: HolType -> Maybe (HolType, HolType)
destFunTy ty = case ty of
TyApp "fun" [ty1, ty2] -> Just (ty1, ty2)
_ -> Nothing
destLet :: Term -> Maybe ([(Term, Term)], Term)
destLet tm = let (l, aargs) = stripComb tm
in case (aargs, destConst l) of
(a : as, Just ("LET", _)) ->
let (vars, lebod) = stripGabs a
in let eqs = zip vars as
in case destComb lebod of
Just (le, bod) -> case destConst le of
Just ("LET_END", _) -> Just (eqs, bod)
_ -> Nothing
_ -> Nothing
_ -> Nothing
-- printer.ml
nameOf :: Term -> String
nameOf tm = case tm of
Var x _ _ -> x
Const x _ _ -> x
_ -> ""
-- printer.ml - pp_print_term
reverseInterface :: (String, Term) -> (String, Maybe HolParseType)
reverseInterface (s, tm) = case tm of
Var _ _ ti -> case ti of
HolTermInfo (_, Just (s'', pt)) -> (s'', Just pt)
_ -> (s, Nothing)
Const _ _ ti -> case ti of
HolTermInfo (_, Just (s'', pt)) -> (s'', Just pt)
_ -> (s, Nothing)
_ -> (s, Nothing)
destBinary :: Term -> Term -> Maybe (Term, Term)
destBinary c tm = case destComb tm of -- original name: DEST_BINARY
Just (il, r) -> case destComb il of
Just (i, l) -> if (i == c) ||
(isConst i && isConst c &&
(fst (reverseInterface (fst (fromJust (destConst i)), i))
== fst (reverseInterface (fst (fromJust (destConst c)), i))))
then Just (l, r)
else Nothing
_ -> Nothing
_ -> Nothing
powerof10 :: Integer -> Bool
powerof10 n = (10 * div n 10) == n
boolOfTerm :: Term -> Maybe Bool
boolOfTerm t = case t of
Const "T" _ _ -> Just True
Const "F" _ _ -> Just False
_ -> Nothing
codeOfTerm :: Num b => Term -> Maybe b
codeOfTerm t =
let (f, tms) = stripComb t in
if not (isConst f && fst (fromJust (destConst f)) == "ASCII")
|| length tms /= 8
then Nothing
else let bools = map boolOfTerm (reverse tms)
in if notElem Nothing bools then
Just (foldr (\ b f' -> if b then 1 + 2 * f' else 2 * f')
0 (catMaybes bools))
else Nothing
randRator :: Term -> Maybe Term
randRator v = case rator v of
Just v1 -> rand v1
_ -> Nothing
destClause :: Term -> Maybe [Term]
destClause tm = case fmap stripExists (maybe Nothing body (body tm)) of
Just (_, pbod) -> let (s, args) = stripComb pbod
in case (nameOf s, length args) of
("_UNGUARDED_PATTERN", 2) ->
case (randRator (head args),
randRator (args !! 1)) of
(Just _1, Just _2) -> Just [_1, _2]
_ -> Nothing
("_GUARDED_PATTERN", 3) ->
case (randRator (head args),
randRator (args !! 2)) of
(Just _1, Just _3) -> Just [_1, args !! 1, _3]
_ -> Nothing
_ -> Nothing
_ -> Nothing
destClauses :: Term -> Maybe [[Term]]
destClauses tm = let (s, args) = stripComb tm
in if nameOf s == "_SEQPATTERN" && length args == 2
then case destClauses (args !! 1) of
Just cs -> case destClause (head args) of
Just c -> Just (c : cs)
_ -> Nothing
_ -> Nothing
else case destClause tm of
Just c -> Just [c]
_ -> Nothing
aright :: Term -> Bool
aright tm = case tm of
Var _ _ (HolTermInfo (InfixR _, _)) -> True
Const _ _ (HolTermInfo (InfixR _, _)) -> True
_ -> False
getPrec :: Term -> Int
getPrec tm = case tm of
Var _ _ (HolTermInfo (InfixR i, _)) -> i
Const _ _ (HolTermInfo (InfixR i, _)) -> i
_ -> 0
parsesAsBinder :: Term -> Bool
parsesAsBinder tm = case tm of
Var _ _ (HolTermInfo (Binder, _)) -> True
Const _ _ (HolTermInfo (Binder, _)) -> True
_ -> False
canGetInfixStatus :: Term -> Bool
canGetInfixStatus tm = case tm of
Var _ _ (HolTermInfo (InfixR _, _)) -> True
Var _ _ (HolTermInfo (InfixL _, _)) -> True
Const _ _ (HolTermInfo (InfixR _, _)) -> True
Const _ _ (HolTermInfo (InfixL _, _)) -> True
_ -> False
| nevrenato/HetsAlloy | HolLight/Helper.hs | gpl-2.0 | 18,130 | 218 | 27 | 8,294 | 6,428 | 3,371 | 3,057 | 418 | 18 |
main :: IO ()
main = readLn >>= print . solve
solve :: Integer -> Int
solve = sum . map (read . (\c -> [c])) . show . (2^)
| NorfairKing/project-euler | 016/haskell/solution.hs | gpl-2.0 | 124 | 1 | 13 | 31 | 84 | 42 | 42 | 4 | 1 |
{-# LANGUAGE MagicHash #-}
module Main where
import Control.Monad
import Data.Word (Word64)
import qualified Data.ByteString.Char8 as BS8
import Control.DeepSeq
import qualified Data.Text.Array as A
import GHC.Prim
import GHC.Base (Int(..))
import Control.Exception (evaluate)
type BA = A.Array
makeBAs n = replicate n (A.run $ A.new 100)
instance NFData A.Array where
rnf x = I# i `seq` ()
where i = indexInt8Array# (A.aBA x) 0#
bs = force $ BS8.pack $ show [1..100]
makeBSs n = replicate n (BS8.reverse bs)
doIt ::
(Num a, Traversable t, NFData b, NFData (t b)) =>
(a -> IO (t b)) -> IO ()
doIt makeItems = do
forM_ [1..(50 :: Int)] $ \i -> do
let n = 100000
bas <- makeItems n
fbas <- mapM (evaluate . force) bas
putStrLn $ fbas `deepseq` show i
main :: IO ()
main = do
-- doIt (return . makeBAs)
doIt (return . makeBSs)
return ()
| sinelaw/bytestrings-gc-analysis | gc.hs | gpl-2.0 | 874 | 0 | 14 | 189 | 388 | 206 | 182 | 30 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Data.Glome.Triangle (Triangle(..), triangle, triangle_raw, triangles, trianglenorm, TriangleNorm(..), trianglesnorms, rayint_triangle, rayint_trianglenorm) where
import Data.Glome.Vec
import Data.Glome.Solid
import Data.List(foldl1')
-- Simple triangles, and triangles with normal vectors
-- specified at each vertex.
data Triangle t m = Triangle Vec Vec Vec deriving Show
data TriangleNorm t m = TriangleNorm Vec Vec Vec Vec Vec Vec deriving Show
-- | Create a simple triangle from its 3 corners.
-- The normals are computed automatically.
triangle :: Vec -> Vec -> Vec -> SolidItem t m
triangle v1 v2 v3 =
SolidItem (Triangle v1 v2 v3)
-- | Create a simple triangle from its 3 corners.
-- The normals are computed automatically.
triangle_raw :: Vec -> Vec -> Vec -> Triangle t m
triangle_raw = Triangle
-- | Create a triangle fan from a list of verticies.
triangles :: [Vec] -> [SolidItem t m]
triangles (v1:vs) =
zipWith (\v2 v3 -> triangle v1 v2 v3) vs (tail vs)
-- | Create a triangle from a list of verticies, and
-- a list of normal vectors (one for each vertex).
trianglenorm v1 v2 v3 n1 n2 n3 =
SolidItem (TriangleNorm v1 v2 v3 n1 n2 n3)
-- | Create a triangle fan from a list of verticies and normals.
trianglesnorms :: [(Vec,Vec)] -> [SolidItem t m]
trianglesnorms (vn1:vns) =
zipWith (\vn2 vn3 -> trianglenorm (fst vn1) (fst vn2) (fst vn3)
(snd vn1) (snd vn2) (snd vn3))
vns (tail vns)
-- adaptation of Moller and Trumbore from pbrt page 127
rayint_triangle :: Triangle tag mat -> Ray -> Flt -> [Texture tag mat] -> [tag] -> Rayint tag mat
rayint_triangle (Triangle p1 p2 p3) ray@(Ray o dir) dist tex tags =
let e1 = vsub p2 p1
e2 = vsub p3 p1
s1 = vcross dir e2
divisor = vdot s1 e1
in
if divisor == 0
then RayMiss
else
let invdivisor = 1.0 / divisor
d = vsub o p1
b1 = (vdot d s1) * invdivisor
in
if b1 < 0 || b1 > 1
then RayMiss
else
let s2 = vcross d e1
b2 = (vdot dir s2) * invdivisor
in
if b2 < 0 || b1 + b2 > 1
then RayMiss
else
let t = (vdot e2 s2) * invdivisor
in
if t < 0 || t > dist
then RayMiss
else
RayHit t (vscaleadd o dir t) (vnorm $ vcross e1 e2) ray vzero tex tags
packetint_triangle :: Triangle tag mat -> Ray -> Ray -> Ray -> Ray -> Flt -> [Texture tag mat] -> [tag] -> PacketResult tag mat
packetint_triangle tri ray1 ray2 ray3 ray4 dist tex tags =
PacketResult (rayint_triangle tri ray1 dist tex tags)
(rayint_triangle tri ray2 dist tex tags)
(rayint_triangle tri ray3 dist tex tags)
(rayint_triangle tri ray4 dist tex tags)
shadow_triangle :: Triangle tag mat -> Ray -> Flt -> Bool
shadow_triangle (Triangle p1 p2 p3) (Ray o dir) dist =
let e1 = vsub p2 p1
e2 = vsub p3 p1
s1 = vcross dir e2
divisor = vdot s1 e1
in
if (divisor == 0)
then False
else
let invdivisor = 1.0 / divisor
d = vsub o p1
b1 = (vdot d s1) * invdivisor
in
if (b1 < 0) || (b1 > 1)
then False
else
let s2 = vcross d e1
b2 = (vdot dir s2) * invdivisor
in
if (b2 < 0) || (b1 + b2 > 1)
then False
else
let t = (vdot e2 s2) * invdivisor
in
(t >= 0) && (t <= dist)
rayint_trianglenorm :: TriangleNorm tag mat -> Ray -> Flt -> [Texture tag mat] -> [tag] -> Rayint tag mat
rayint_trianglenorm (TriangleNorm p1 p2 p3 n1 n2 n3) ray@(Ray o dir) dist tex tags =
let e1 = vsub p2 p1
e2 = vsub p3 p1
s1 = vcross dir e2
divisor = vdot s1 e1
in
if (divisor == 0)
then RayMiss
else
let invdivisor = 1.0 / divisor
d = vsub o p1
b1 = (vdot d s1) * invdivisor
in
if (b1 < 0) || (b1 > 1)
then RayMiss
else
let s2 = vcross d e1
b2 = (vdot dir s2) * invdivisor
in
if (b2 < 0) || (b1 + b2 > 1)
then RayMiss
else
let t = (vdot e2 s2) * invdivisor
in
if (t < 0) || (t > dist)
then RayMiss
else
let n1scaled = (vscale n1 (1-(b1+b2)))
n2scaled = (vscale n2 b1)
n3scaled = (vscale n3 b2)
norm = vnorm $ vadd3 n1scaled n2scaled n3scaled
in RayHit t (vscaleadd o dir t) norm ray vzero tex tags
shadow_trianglenorm :: TriangleNorm tag mat -> Ray -> Flt -> Bool
shadow_trianglenorm (TriangleNorm p1 p2 p3 n1 n2 n3) r d =
shadow_triangle (Triangle p1 p2 p3) r d
bound_triangle :: Triangle t m -> Bbox
bound_triangle (Triangle (Vec v1x v1y v1z)
(Vec v2x v2y v2z)
(Vec v3x v3y v3z)) =
Bbox
(Vec ((fmin (fmin v1x v2x) v3x) - delta)
((fmin (fmin v1y v2y) v3y) - delta)
((fmin (fmin v1z v2z) v3z) - delta) )
(Vec ((fmax (fmax v1x v2x) v3x) + delta)
((fmax (fmax v1y v2y) v3y) + delta)
((fmax (fmax v1z v2z) v3z) + delta) )
bound_trianglenorm :: TriangleNorm t m -> Bbox
bound_trianglenorm (TriangleNorm v1 v2 v3 n1 n2 n3) =
bound (Triangle v1 v2 v3)
transform_triangle :: Triangle t m -> [Xfm] -> SolidItem t m
transform_triangle (Triangle p1 p2 p3) xfms =
SolidItem $ Triangle (xfm_point (compose xfms) p1)
(xfm_point (compose xfms) p2)
(xfm_point (compose xfms) p3)
transform_trianglenorm :: TriangleNorm t m -> [Xfm] -> SolidItem t m
transform_trianglenorm (TriangleNorm p1 p2 p3 n1 n2 n3) xfms =
SolidItem $ TriangleNorm (xfm_point (compose xfms) p1)
(xfm_point (compose xfms) p2)
(xfm_point (compose xfms) p3)
(vnorm $ xfm_vec (compose xfms) n1)
(vnorm $ xfm_vec (compose xfms) n2)
(vnorm $ xfm_vec (compose xfms) n3)
instance Solid (Triangle t m) t m where
rayint = rayint_triangle
packetint = packetint_triangle
shadow = shadow_triangle
inside _ _ = False
bound = bound_triangle
transform = transform_triangle
instance Solid (TriangleNorm t m) t m where
rayint = rayint_trianglenorm
shadow = shadow_trianglenorm
inside _ _ = False
bound = bound_trianglenorm
transform = transform_trianglenorm
| jimsnow/glome | GlomeTrace/Data/Glome/Triangle.hs | gpl-2.0 | 6,524 | 0 | 26 | 2,099 | 2,322 | 1,204 | 1,118 | 137 | 5 |
import System.Random
main = do
gen <- getStdGen
putStrLn $ take 20 (randomRs ('a', 'z') gen)
gen <- getStdGen
putStrLn $ take 20 (randomRs ('a', 'z') gen) -- Same result
putStrLn "----------------"
let randomChars = randomRs ('a', 'z') gen
(first20, rest) = splitAt 20 randomChars
(second20, _) = splitAt 20 rest
putStrLn first20
putStrLn second20
putStrLn "----------------"
gen' <- getStdGen
putStrLn $ take 20 (randomRs ('a', 'z') gen')
gen'' <- newStdGen
putStrLn $ take 20 (randomRs ('a', 'z') gen'')
| lamontu/learning_haskell | random_string.hs | gpl-3.0 | 579 | 1 | 11 | 152 | 225 | 107 | 118 | 17 | 1 |
subsets :: [a] -> [[a]]
subsets [] = [[]]
subsets (x:xs) = let ys = subsets xs
in (map (x:) ys) ++ ys
| marcosfede/algorithms | backtrack/subsets.hs | gpl-3.0 | 117 | 2 | 10 | 38 | 81 | 43 | 38 | 4 | 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.Logging.Organizations.Sinks.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists sinks.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.organizations.sinks.list@.
module Network.Google.Resource.Logging.Organizations.Sinks.List
(
-- * REST Resource
OrganizationsSinksListResource
-- * Creating a Request
, organizationsSinksList
, OrganizationsSinksList
-- * Request Lenses
, oslParent
, oslXgafv
, oslUploadProtocol
, oslAccessToken
, oslUploadType
, oslPageToken
, oslPageSize
, oslCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.organizations.sinks.list@ method which the
-- 'OrganizationsSinksList' request conforms to.
type OrganizationsSinksListResource =
"v2" :>
Capture "parent" Text :>
"sinks" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListSinksResponse
-- | Lists sinks.
--
-- /See:/ 'organizationsSinksList' smart constructor.
data OrganizationsSinksList =
OrganizationsSinksList'
{ _oslParent :: !Text
, _oslXgafv :: !(Maybe Xgafv)
, _oslUploadProtocol :: !(Maybe Text)
, _oslAccessToken :: !(Maybe Text)
, _oslUploadType :: !(Maybe Text)
, _oslPageToken :: !(Maybe Text)
, _oslPageSize :: !(Maybe (Textual Int32))
, _oslCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OrganizationsSinksList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'oslParent'
--
-- * 'oslXgafv'
--
-- * 'oslUploadProtocol'
--
-- * 'oslAccessToken'
--
-- * 'oslUploadType'
--
-- * 'oslPageToken'
--
-- * 'oslPageSize'
--
-- * 'oslCallback'
organizationsSinksList
:: Text -- ^ 'oslParent'
-> OrganizationsSinksList
organizationsSinksList pOslParent_ =
OrganizationsSinksList'
{ _oslParent = pOslParent_
, _oslXgafv = Nothing
, _oslUploadProtocol = Nothing
, _oslAccessToken = Nothing
, _oslUploadType = Nothing
, _oslPageToken = Nothing
, _oslPageSize = Nothing
, _oslCallback = Nothing
}
-- | Required. The parent resource whose sinks are to be listed:
-- \"projects\/[PROJECT_ID]\" \"organizations\/[ORGANIZATION_ID]\"
-- \"billingAccounts\/[BILLING_ACCOUNT_ID]\" \"folders\/[FOLDER_ID]\"
oslParent :: Lens' OrganizationsSinksList Text
oslParent
= lens _oslParent (\ s a -> s{_oslParent = a})
-- | V1 error format.
oslXgafv :: Lens' OrganizationsSinksList (Maybe Xgafv)
oslXgafv = lens _oslXgafv (\ s a -> s{_oslXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
oslUploadProtocol :: Lens' OrganizationsSinksList (Maybe Text)
oslUploadProtocol
= lens _oslUploadProtocol
(\ s a -> s{_oslUploadProtocol = a})
-- | OAuth access token.
oslAccessToken :: Lens' OrganizationsSinksList (Maybe Text)
oslAccessToken
= lens _oslAccessToken
(\ s a -> s{_oslAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
oslUploadType :: Lens' OrganizationsSinksList (Maybe Text)
oslUploadType
= lens _oslUploadType
(\ s a -> s{_oslUploadType = a})
-- | Optional. If present, then retrieve the next batch of results from the
-- preceding call to this method. pageToken must be the value of
-- nextPageToken from the previous response. The values of other method
-- parameters should be identical to those in the previous call.
oslPageToken :: Lens' OrganizationsSinksList (Maybe Text)
oslPageToken
= lens _oslPageToken (\ s a -> s{_oslPageToken = a})
-- | Optional. The maximum number of results to return from this request.
-- Non-positive values are ignored. The presence of nextPageToken in the
-- response indicates that more results might be available.
oslPageSize :: Lens' OrganizationsSinksList (Maybe Int32)
oslPageSize
= lens _oslPageSize (\ s a -> s{_oslPageSize = a}) .
mapping _Coerce
-- | JSONP
oslCallback :: Lens' OrganizationsSinksList (Maybe Text)
oslCallback
= lens _oslCallback (\ s a -> s{_oslCallback = a})
instance GoogleRequest OrganizationsSinksList where
type Rs OrganizationsSinksList = ListSinksResponse
type Scopes OrganizationsSinksList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read"]
requestClient OrganizationsSinksList'{..}
= go _oslParent _oslXgafv _oslUploadProtocol
_oslAccessToken
_oslUploadType
_oslPageToken
_oslPageSize
_oslCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy :: Proxy OrganizationsSinksListResource)
mempty
| brendanhay/gogol | gogol-logging/gen/Network/Google/Resource/Logging/Organizations/Sinks/List.hs | mpl-2.0 | 6,123 | 0 | 18 | 1,398 | 894 | 520 | 374 | 127 | 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.AppEngine.Apps.AuthorizedCertificates.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists all SSL certificates the user is authorized to administer.
--
-- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ App Engine Admin API Reference> for @appengine.apps.authorizedCertificates.list@.
module Network.Google.Resource.AppEngine.Apps.AuthorizedCertificates.List
(
-- * REST Resource
AppsAuthorizedCertificatesListResource
-- * Creating a Request
, appsAuthorizedCertificatesList
, AppsAuthorizedCertificatesList
-- * Request Lenses
, aaclXgafv
, aaclUploadProtocol
, aaclAccessToken
, aaclUploadType
, aaclAppsId
, aaclView
, aaclPageToken
, aaclPageSize
, aaclCallback
) where
import Network.Google.AppEngine.Types
import Network.Google.Prelude
-- | A resource alias for @appengine.apps.authorizedCertificates.list@ method which the
-- 'AppsAuthorizedCertificatesList' request conforms to.
type AppsAuthorizedCertificatesListResource =
"v1" :>
"apps" :>
Capture "appsId" Text :>
"authorizedCertificates" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "view" AppsAuthorizedCertificatesListView
:>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListAuthorizedCertificatesResponse
-- | Lists all SSL certificates the user is authorized to administer.
--
-- /See:/ 'appsAuthorizedCertificatesList' smart constructor.
data AppsAuthorizedCertificatesList =
AppsAuthorizedCertificatesList'
{ _aaclXgafv :: !(Maybe Xgafv)
, _aaclUploadProtocol :: !(Maybe Text)
, _aaclAccessToken :: !(Maybe Text)
, _aaclUploadType :: !(Maybe Text)
, _aaclAppsId :: !Text
, _aaclView :: !(Maybe AppsAuthorizedCertificatesListView)
, _aaclPageToken :: !(Maybe Text)
, _aaclPageSize :: !(Maybe (Textual Int32))
, _aaclCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AppsAuthorizedCertificatesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aaclXgafv'
--
-- * 'aaclUploadProtocol'
--
-- * 'aaclAccessToken'
--
-- * 'aaclUploadType'
--
-- * 'aaclAppsId'
--
-- * 'aaclView'
--
-- * 'aaclPageToken'
--
-- * 'aaclPageSize'
--
-- * 'aaclCallback'
appsAuthorizedCertificatesList
:: Text -- ^ 'aaclAppsId'
-> AppsAuthorizedCertificatesList
appsAuthorizedCertificatesList pAaclAppsId_ =
AppsAuthorizedCertificatesList'
{ _aaclXgafv = Nothing
, _aaclUploadProtocol = Nothing
, _aaclAccessToken = Nothing
, _aaclUploadType = Nothing
, _aaclAppsId = pAaclAppsId_
, _aaclView = Nothing
, _aaclPageToken = Nothing
, _aaclPageSize = Nothing
, _aaclCallback = Nothing
}
-- | V1 error format.
aaclXgafv :: Lens' AppsAuthorizedCertificatesList (Maybe Xgafv)
aaclXgafv
= lens _aaclXgafv (\ s a -> s{_aaclXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
aaclUploadProtocol :: Lens' AppsAuthorizedCertificatesList (Maybe Text)
aaclUploadProtocol
= lens _aaclUploadProtocol
(\ s a -> s{_aaclUploadProtocol = a})
-- | OAuth access token.
aaclAccessToken :: Lens' AppsAuthorizedCertificatesList (Maybe Text)
aaclAccessToken
= lens _aaclAccessToken
(\ s a -> s{_aaclAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
aaclUploadType :: Lens' AppsAuthorizedCertificatesList (Maybe Text)
aaclUploadType
= lens _aaclUploadType
(\ s a -> s{_aaclUploadType = a})
-- | Part of \`parent\`. Name of the parent Application resource. Example:
-- apps\/myapp.
aaclAppsId :: Lens' AppsAuthorizedCertificatesList Text
aaclAppsId
= lens _aaclAppsId (\ s a -> s{_aaclAppsId = a})
-- | Controls the set of fields returned in the LIST response.
aaclView :: Lens' AppsAuthorizedCertificatesList (Maybe AppsAuthorizedCertificatesListView)
aaclView = lens _aaclView (\ s a -> s{_aaclView = a})
-- | Continuation token for fetching the next page of results.
aaclPageToken :: Lens' AppsAuthorizedCertificatesList (Maybe Text)
aaclPageToken
= lens _aaclPageToken
(\ s a -> s{_aaclPageToken = a})
-- | Maximum results to return per page.
aaclPageSize :: Lens' AppsAuthorizedCertificatesList (Maybe Int32)
aaclPageSize
= lens _aaclPageSize (\ s a -> s{_aaclPageSize = a})
. mapping _Coerce
-- | JSONP
aaclCallback :: Lens' AppsAuthorizedCertificatesList (Maybe Text)
aaclCallback
= lens _aaclCallback (\ s a -> s{_aaclCallback = a})
instance GoogleRequest AppsAuthorizedCertificatesList
where
type Rs AppsAuthorizedCertificatesList =
ListAuthorizedCertificatesResponse
type Scopes AppsAuthorizedCertificatesList =
'["https://www.googleapis.com/auth/appengine.admin",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient AppsAuthorizedCertificatesList'{..}
= go _aaclAppsId _aaclXgafv _aaclUploadProtocol
_aaclAccessToken
_aaclUploadType
_aaclView
_aaclPageToken
_aaclPageSize
_aaclCallback
(Just AltJSON)
appEngineService
where go
= buildClient
(Proxy ::
Proxy AppsAuthorizedCertificatesListResource)
mempty
| brendanhay/gogol | gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/AuthorizedCertificates/List.hs | mpl-2.0 | 6,628 | 0 | 20 | 1,549 | 969 | 559 | 410 | 141 | 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.Compute.TargetTCPProxies.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes the specified TargetTcpProxy resource.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetTcpProxies.delete@.
module Network.Google.Resource.Compute.TargetTCPProxies.Delete
(
-- * REST Resource
TargetTCPProxiesDeleteResource
-- * Creating a Request
, targetTCPProxiesDelete
, TargetTCPProxiesDelete
-- * Request Lenses
, ttpdRequestId
, ttpdProject
, ttpdTargetTCPProxy
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.targetTcpProxies.delete@ method which the
-- 'TargetTCPProxiesDelete' request conforms to.
type TargetTCPProxiesDeleteResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"targetTcpProxies" :>
Capture "targetTcpProxy" Text :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] Operation
-- | Deletes the specified TargetTcpProxy resource.
--
-- /See:/ 'targetTCPProxiesDelete' smart constructor.
data TargetTCPProxiesDelete =
TargetTCPProxiesDelete'
{ _ttpdRequestId :: !(Maybe Text)
, _ttpdProject :: !Text
, _ttpdTargetTCPProxy :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TargetTCPProxiesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ttpdRequestId'
--
-- * 'ttpdProject'
--
-- * 'ttpdTargetTCPProxy'
targetTCPProxiesDelete
:: Text -- ^ 'ttpdProject'
-> Text -- ^ 'ttpdTargetTCPProxy'
-> TargetTCPProxiesDelete
targetTCPProxiesDelete pTtpdProject_ pTtpdTargetTCPProxy_ =
TargetTCPProxiesDelete'
{ _ttpdRequestId = Nothing
, _ttpdProject = pTtpdProject_
, _ttpdTargetTCPProxy = pTtpdTargetTCPProxy_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
ttpdRequestId :: Lens' TargetTCPProxiesDelete (Maybe Text)
ttpdRequestId
= lens _ttpdRequestId
(\ s a -> s{_ttpdRequestId = a})
-- | Project ID for this request.
ttpdProject :: Lens' TargetTCPProxiesDelete Text
ttpdProject
= lens _ttpdProject (\ s a -> s{_ttpdProject = a})
-- | Name of the TargetTcpProxy resource to delete.
ttpdTargetTCPProxy :: Lens' TargetTCPProxiesDelete Text
ttpdTargetTCPProxy
= lens _ttpdTargetTCPProxy
(\ s a -> s{_ttpdTargetTCPProxy = a})
instance GoogleRequest TargetTCPProxiesDelete where
type Rs TargetTCPProxiesDelete = Operation
type Scopes TargetTCPProxiesDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient TargetTCPProxiesDelete'{..}
= go _ttpdProject _ttpdTargetTCPProxy _ttpdRequestId
(Just AltJSON)
computeService
where go
= buildClient
(Proxy :: Proxy TargetTCPProxiesDeleteResource)
mempty
| brendanhay/gogol | gogol-compute/gen/Network/Google/Resource/Compute/TargetTCPProxies/Delete.hs | mpl-2.0 | 4,526 | 0 | 16 | 971 | 477 | 287 | 190 | 77 | 1 |
{-# LANGUAGE OverloadedStrings, RankNTypes #-}
module View.Form
( FormHtml
, field
, inputText
, inputTextarea
, inputPassword
, inputCheckbox
, inputSelect
, inputEnum
, inputDate
, inputFile
, inputHidden
, csrfForm
, htmlForm
) where
import Control.Applicative ((<|>))
import Control.Monad (when)
import Control.Monad.Reader (reader)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Control (liftWith)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.Foldable (fold)
import qualified Data.Text as T
import Data.Time.Format (formatTime, defaultTimeLocale)
import qualified Text.Blaze.Internal as M
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as HA
import Ops
import Has (view)
import Model.Enum
import Model.Time
import Model.Token
import Model.Identity
import Action
import HTTP.Form
import HTTP.Form.Errors
import HTTP.Form.View
import View.Html
import View.Template
import {-# SOURCE #-} Controller.Angular
type FormHtmlM f = FormViewT f M.MarkupM
type FormHtml f = FormHtmlM f ()
pathId :: FormHtmlM f H.AttributeValue
pathId = reader (byteStringValue . formPathBS)
value :: FormHtmlM f (Maybe BS.ByteString)
value = do
val <- reader formDatum
return $ case val of
FormDatumNone -> Nothing
FormDatumJSON _ -> Nothing -- that's weird
FormDatumBS b -> (BS.null b) `unlessUse` b
FormDatumFlag -> Nothing
errorList :: [FormErrorMessage] -> H.Html
errorList [] = mempty
errorList err =
H.ul H.! HA.class_ "error-list" $ mapM_
((H.li H.! HA.class_ "error") . H.toHtml) err
errorLists :: [(FormPath, FormErrorMessage)] -> H.Html
errorLists [] = mempty
errorLists err =
H.dl H.! HA.class_ "error-list" $ mapM_ (\(p,e) -> do
H.dt $ H.toHtml (formPathText p)
H.dd H.! HA.class_ "error" $ H.toHtml e) err
_label :: H.AttributeValue -> H.Html -> H.Html
_label ref = H.label
H.! HA.for ref
type Field = H.AttributeValue -> Maybe BS.ByteString -> H.Html
field :: T.Text -> Field -> FormHtml f
field k sub = k .:> do
ref <- pathId
err <- formViewErrors
val <- value
lift $ H.label $ do
H.toHtml k
sub ref val
errorList err
H.br
inputText :: H.ToValue a => Maybe a -> Field
inputText val ref dat = H.input
H.! HA.type_ "text"
H.! HA.id ref
H.! HA.name ref
!? (HA.value <$> (fmap byteStringValue dat <|> fmap H.toValue val))
inputTextarea :: H.ToMarkup a => Maybe a -> Field
inputTextarea val ref dat = H.textarea
H.! HA.id ref
H.! HA.name ref
$ fold $ fmap byteStringHtml dat <|> fmap H.toHtml val
inputPassword :: Field
inputPassword ref _ = H.input
H.! HA.type_ "password"
H.! HA.id ref
H.! HA.name ref
inputCheckbox :: Bool -> Field
inputCheckbox val ref dat = H.input
H.! HA.type_ "checkbox"
H.! HA.id ref
H.! HA.name ref
H.!? (maybe val (const True) dat, HA.checked "checked")
inputSelect :: H.ToMarkup b => Maybe BS.ByteString -> [(BS.ByteString, b)] -> Field
inputSelect val choices ref dat = H.select
H.! HA.id ref
H.! HA.name ref
$ mapM_ (\(v, c) -> H.option
H.! HA.value (byteStringValue v)
H.!? (any (v ==) (dat <|> val), HA.selected "selected")
$ H.toHtml c) choices
inputEnum :: forall a . DBEnum a => Bool -> Maybe a -> Field
inputEnum req val =
inputSelect (bshow <$> val) $ (if req then id else (("", "") :)) $ map (\(x, v) -> (bshow (x :: a), v)) pgEnumValues
where bshow = BSC.pack . show . fromEnum
inputDate :: Maybe Date -> Field
inputDate val ref dat = H.input
H.! HA.type_ "date"
H.! HA.id ref
H.! HA.name ref
!? (HA.value <$> (fmap byteStringValue dat <|> fmap (H.toValue . formatTime defaultTimeLocale "%F") val))
inputFile :: Field
inputFile ref _ = H.input
H.! HA.type_ "file"
H.! HA.id ref
H.! HA.name ref
inputHidden :: H.ToValue a => a -> Field
inputHidden val ref dat = H.input
H.! HA.type_ "hidden"
H.! HA.id ref
H.! HA.name ref
H.! HA.value (maybe (H.toValue val) byteStringValue dat)
csrfForm :: RequestContext -> FormHtml f
csrfForm =
lift . extractFromIdentifiedSessOrDefault mempty (\s -> inputHidden (byteStringValue $ sessionVerf s) "csverf" Nothing) . view
htmlForm :: T.Text -> ActionRoute a -> a -> FormHtml f -> (JSOpt -> H.Html) -> RequestContext -> FormHtml f
htmlForm title act arg form body req = liftWith $ \run ->
htmlTemplate req (Just title) $ \js -> do
actionForm act arg js $ do
(_, err) <- run $ when (actionMethod act arg /= GET) (csrfForm req) >> form
errorLists $ allFormErrors err
H.input
H.! HA.type_ "submit"
body js
| databrary/databrary | src/View/Form.hs | agpl-3.0 | 4,628 | 0 | 20 | 939 | 1,840 | 955 | 885 | 141 | 4 |
{- |
Module : $Header$
Description : QuickCheck generators and mutators for authochan.
Copyright : (c) plaimi 2014
License : AGPL-3
Maintainer : tempuhs@plaimi.net
-} module Authochan.Tests.Gen where
import Control.Applicative
(
(<$>),
(<*>),
liftA,
)
import Control.Monad.CryptoRandom
(
evalCRand,
)
import Crypto.Hash
(
HMAC (HMAC),
digestFromByteString,
)
import Crypto.Random.DRBG
(
HashDRBG,
ByteLength,
genSeedLength,
newGen,
)
import Data.Byteable
(
toBytes,
)
import qualified Data.ByteString as B
import Data.Maybe
(
fromJust,
isJust,
)
import Data.Tagged
(
Tagged,
unTagged,
)
import qualified Data.Text as T
import Database.Persist
(
Key,
PersistEntity,
PersistValue (PersistInt64),
keyFromValues,
)
import Test.QuickCheck
(
Gen,
arbitrary,
arbitraryBoundedIntegral,
suchThat,
vectorOf,
)
import Authochan.Database
(
Client (Client),
)
import Authochan.Key
(
newClientHandle,
newClientSecret,
newSessionID,
)
import Authochan.Message
(
SignedMessage (MkSignedMessage),
signMessage,
)
import Test.MutableGen
(
mutateSized,
)
genRandom :: Gen HashDRBG
genRandom = do
let b = unTagged (genSeedLength :: Tagged HashDRBG ByteLength)
Right e <- newGen <$> B.pack <$> vectorOf b arbitraryBoundedIntegral
return e
genKey :: PersistEntity r => Gen (Key r)
genKey = do
k <- arbitrary
return $ either (error . T.unpack) id $ keyFromValues [PersistInt64 k]
genClient :: Gen Client
genClient = do
g <- genRandom
let Right (h, s) = evalCRand ((,) <$> newClientHandle <*> newClientSecret) g
k <- genKey
n <- arbitraryBoundedIntegral
d <- T.pack <$> arbitrary
return $ Client h s n k d
genMessage :: Client -> Gen SignedMessage
genMessage c = do
g <- genRandom
n <- arbitraryBoundedIntegral
let Right s = evalCRand newSessionID g
b <- B.pack <$> arbitrary
return $ signMessage c s n b
mutateMessage :: SignedMessage -> Gen SignedMessage
mutateMessage (MkSignedMessage k sid n s b) = liftA fromJust g
where g = suchThat gm isJust
gm = do
(k', sid', n', s', b') <- mutateSized (k, sid, n, toBytes s, b)
return $ do
s'' <- HMAC <$> digestFromByteString s'
Just $ MkSignedMessage k' sid' n' s'' b'
| plaimi/authochan | test/Authochan/Tests/Gen.hs | agpl-3.0 | 2,314 | 0 | 14 | 535 | 699 | 381 | 318 | 92 | 1 |
module Ch_09_Standard where
myOr :: [Bool] -> Bool
myOr [] = False
myOr (x:xs) = x || myOr xs
myAny :: (a -> Bool) -> [a] -> Bool
myAny _ [] = False
myAny f (x:xs) = f x || myAny f xs
myElem :: Eq a => a -> [a] -> Bool
myElem _ [] = False
myElem e (x:xs)
| e == x = True
| otherwise = myElem e xs
-- Alternativlösung mit "any"
myElem2 :: Eq a => a -> [a] -> Bool
myElem2 e es = myAny ((==) e) es
| m3mitsuppe/haskell | exercises/Programming Haskell Book Exercises.hsproj/Ch_09_Standard.hs | unlicense | 438 | 0 | 8 | 135 | 235 | 121 | 114 | 14 | 1 |
{-# LANGUAGE MagicHash #-}
module PopCount where
import CLaSH.Prelude
import GHC.Word
import Data.Bits
topEntity :: Word -> Int
topEntity = popCount
testInput :: Signal Word
testInput = stimuliGenerator $(v [1::Word,3,8,50,0])
expectedOutput :: Signal Int -> Signal Bool
expectedOutput = outputVerifier $(v ([1,2,1,3,0]::[Int]))
| ggreif/clash-compiler | tests/shouldwork/Basic/PopCount.hs | bsd-2-clause | 333 | 0 | 10 | 46 | 129 | 74 | 55 | 11 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UnicodeSyntax #-}
import Control.Applicative
import System.Console.CmdTheLine
import LogicGrowsOnTrees.Parallel.Main
import LogicGrowsOnTrees.Parallel.Adapter.Processes
import LogicGrowsOnTrees.Utils.PerfectTree
import LogicGrowsOnTrees.Utils.WordSum
main =
mainForExploreTree
driver
(makeArityAndDepthTermAtPositions 0 1)
(defTI { termDoc = "count the leaves of a tree" })
(\_ (RunOutcome _ termination_reason) → do
case termination_reason of
Aborted _ → error "search aborted"
Completed (WordSum count) → print count
Failure _ message → error $ "error: " ++ message
)
(trivialPerfectTree <$> arity <*> depth)
| gcross/LogicGrowsOnTrees-processes | examples/count-all-trivial-tree-leaves.hs | bsd-2-clause | 783 | 1 | 15 | 191 | 162 | 86 | 76 | 19 | 3 |
{-|
Module : Numeric.LinearAlgebra.Repa
License : BSD3
Maintainer : marcin.jan.mrotek@gmail.com
Stability : experimental
HMatrix linear algebra functions wrapped to accept Repa arrays.
* Unqualified functions use raw 'F' arrays.
* "-S" functions precompute 'D' arrays sequentially.
* "-SIO" functions precompute 'D' arrays sequentially in the 'IO' monad.
* "-P" functions precompute 'D' arrays in parralel in any monad.
* "-PIO" functions precompute 'D' arrays in parralel in the 'IO' monad.
-}
{-# LANGUAGE FlexibleContexts #-}
module Numeric.LinearAlgebra.Repa
(
-- * Typeclasses
Numeric
, Field
, Product
, LSDiv
-- * Shape-polymorphic conversion
, HShape(..)
-- * Data types
, Vector
, H.Matrix
, RandDist(..)
, Seed
-- * Special types
, H.Herm
, H.LU
, H.LDL
-- * Dot product
, dot
, dotS
, dotSIO
, dotP
, dotPIO
-- * Dense matrix-vector product.
, app
, appS
, appSIO
, appP
, appPIO
-- * Dense matrix-matrix product.
, mul
, mulS
, mulSIO
, mulP
, mulPIO
-- * Vector outer product.
, outer
, outerS
, outerSIO
, outerP
, outerPIO
-- * Kronecker product.
, kronecker
, kroneckerS
, kroneckerSIO
, kroneckerP
, kroneckerPIO
-- * Cross product.
, cross
, crossS
, crossSIO
-- * Sum of elements.
, sumElements
, sumElementsS
, sumElementsSIO
, sumElementsP
, sumElementsPIO
-- * Product of elements.
, prodElements
, prodElementsS
, prodElementsSIO
, prodElementsP
, prodElementsPIO
-- * Linear systems.
, (<\>)
, solve
, solveS
, solveSIO
, solveP
, solvePIO
, linearSolve
, linearSolveS
, linearSolveSIO
, linearSolveP
, linearSolvePIO
, linearSolveLS
, linearSolveLS_S
, linearSolveLS_SIO
, linearSolveLS_P
, linearSolveLS_PIO
, linearSolveSVD
, linearSolveSVD_S
, linearSolveSVD_SIO
, linearSolveSVD_P
, linearSolveSVD_PIO
, luSolve
, luSolveS
, luSolveSIO
, luSolveP
, luSolvePIO
, cholSolve
, cholSolveS
, cholSolveSIO
, cholSolveP
, cholSolvePIO
-- * Inverse and pseudoinverse
, inv
, invS
, invSIO
, invP
, invPIO
, pinv
, pinvS
, pinvSIO
, pinvP
, pinvPIO
, pinvTol
, pinvTolS
, pinvTolSIO
, pinvTolP
, pinvTolPIO
-- * Determinant and rank
, rcond
, rcondS
, rcondSIO
, rcondP
, rcondPIO
, rank
, rankS
, rankSIO
, rankP
, rankPIO
, det
, detS
, detSIO
, detP
, detPIO
, invlndet
, invlndetS
, invlndetSIO
, invlndetP
, invlndetPIO
-- * Norms
, norm_Frob
, norm_FrobS
, norm_FrobSIO
, norm_FrobP
, norm_FrobPIO
, norm_nuclear
, norm_nuclearS
, norm_nuclearSIO
, norm_nuclearP
, norm_nuclearPIO
-- * Nullspace and range
, orth
, orthS
, orthSIO
, orthP
, orthPIO
, nullspace
, nullspaceS
, nullspaceSIO
, nullspaceP
, nullspacePIO
, null1
, null1S
, null1SIO
, null1P
, null1PIO
, null1sym
-- * SVD
, svd
, svdS
, svdSIO
, svdP
, svdPIO
, thinSVD
, thinSVD_S
, thinSVD_SIO
, thinSVD_P
, thinSVD_PIO
, compactSVD
, compactSVD_S
, compactSVD_SIO
, compactSVD_P
, compactSVD_PIO
, singularValues
, singularValuesS
, singularValuesSIO
, singularValuesP
, singularValuesPIO
, leftSV
, leftSV_S
, leftSV_SIO
, leftSV_P
, leftSV_PIO
, rightSV
, rightSV_S
, rightSV_SIO
, rightSV_P
, rightSV_PIO
-- * Eigensystems
, eig
, eigS
, eigSIO
, eigP
, eigPIO
, eigSH
, eigenvalues
, eigenvaluesS
, eigenvaluesSIO
, eigenvaluesP
, eigenvaluesPIO
, eigenvaluesSH
, geigSH
-- * QR
, qr
, qrS
, qrSIO
, qrP
, qrPIO
, rq
, rqS
, rqSIO
, rqP
, rqPIO
, qrRaw
, qrRawS
, qrRawSIO
, qrRawP
, qrRawPIO
, qrgr
-- * Cholesky
, chol
, mbChol
-- * Hessenberg
, hess
, hessS
, hessSIO
, hessP
, hessPIO
-- * Schur
, schur
, schurS
, schurSIO
, schurP
, schurPIO
-- * LU
, lu
, luS
, luSIO
, luP
, luPIO
, luPacked
, luPackedS
, luPackedSIO
, luPackedP
, luPackedPIO
, luFact
-- * Symmetric indefinite
, ldlSolve
, ldlSolveS
, ldlSolveSIO
, ldlSolveP
, ldlSolvePIO
, ldlPacked
-- * Matrix functions
, expm
, expmS
, expmSIO
, expmP
, expmPIO
, sqrtm
, sqrtmS
, sqrtmSIO
, sqrtmP
, sqrtmPIO
, matFunc
, matFuncS
, matFuncSIO
, matFuncP
, matFuncPIO
-- *Correlation and convolution
, corr
, corrS
, corrSIO
, corrP
, corrPIO
, conv
, convS
, convSIO
, convP
, convPIO
, corrMin
, corrMinS
, corrMinSIO
, corrMinP
, corrMinPIO
, corr2
, corr2S
, corr2SIO
, corr2P
, corr2PIO
, conv2
, conv2S
, conv2SIO
, conv2P
, conv2PIO
-- *Random vectors and matrices
, randomVector
, randomMatrix
, gaussianSample
, uniformSample
-- *Misc
, meanCov
, rowOuters
, sym
, symS
, symSIO
, symP
, symPIO
, mTm
, mTmS
, mTmSIO
, mTmP
, mTmPIO
, trustSym
, trustSymS
, trustSymSIO
, trustSymP
, trustSymPIO
, unSym
) where
import Numeric.LinearAlgebra.Repa.Conversion
import Data.Array.Repa hiding (rank)
import Data.Array.Repa.Repr.ForeignPtr
import qualified Numeric.LinearAlgebra.HMatrix as H
import Numeric.LinearAlgebra.HMatrix (Complex, Numeric, Field, LSDiv, Normed, Product, Vector, RealElement, RandDist(..), Seed)
-- Dot product
dot :: Numeric t => Array F DIM1 t -> Array F DIM1 t -> t
-- ^Vector dot product.
dot v u = repa2hv v `H.dot` repa2hv u
dotS :: Numeric t => Array D DIM1 t -> Array D DIM1 t -> t
-- ^Vector dot product. Arguments computed sequentially.
dotS v u = repa2hvS v `H.dot` repa2hvS u
dotSIO :: Numeric t => Array D DIM1 t -> Array D DIM1 t -> IO t
-- ^Vector dot product. Arguments computed sequentially inside the IO monad.
dotSIO v u = H.dot <$> repa2hvSIO v <*> repa2hvSIO u
dotP :: (Numeric t, Monad m) => Array D DIM1 t -> Array D DIM1 t -> m t
-- ^Vector dot product. Arguments computed in parallel.
dotP v u = H.dot <$> repa2hvP v <*> repa2hvP u
dotPIO :: Numeric t => Array D DIM1 t -> Array D DIM1 t -> IO t
-- ^Vector dot product. Arguments computed in parallel inside the IO monad.
dotPIO v u = H.dot <$> repa2hvPIO v <*> repa2hvPIO u
-- Dense matrix-vector product
app :: Numeric t => Array F DIM2 t -> Array F DIM1 t -> Array F DIM1 t
-- ^Dense matrix-vector product.
app m v = hv2repa $ repa2hm m `H.app` repa2hv v
appS :: Numeric t => Array D DIM2 t -> Array D DIM1 t -> Array F DIM1 t
-- ^Dense matrix-vector product. Arguments computed sequentially.
appS m v = hv2repa $ repa2hmS m `H.app` repa2hvS v
appSIO :: Numeric t => Array D DIM2 t -> Array D DIM1 t -> IO (Array F DIM1 t)
-- ^Dense matrix-vector product. Arguments computed sequentially inside the IO monad.
appSIO m v = hv2repa <$> (H.app <$> repa2hmSIO m <*> repa2hvSIO v)
appP :: (Numeric t, Monad m) => Array D DIM2 t -> Array D DIM1 t -> m (Array F DIM1 t)
-- ^Dense matrix-vector product. Arguments computed in parallel.
appP m v = hv2repa <$> (H.app <$> repa2hmP m <*> repa2hvP v)
appPIO :: Numeric t => Array D DIM2 t -> Array D DIM1 t -> IO (Array F DIM1 t)
-- ^Dense matrix-vector product. Arguments computed in parallel inside the IO monad.
appPIO m v = hv2repa <$> (H.app <$> repa2hmPIO m <*> repa2hvPIO v)
-- Dense matrix-matrix product
mul :: Numeric t => Array F DIM2 t -> Array F DIM2 t -> Array F DIM2 t
-- ^Dense matrix-matrix product.
mul m n = hm2repa $ repa2hm m `H.mul` repa2hm n
mulS :: Numeric t => Array D DIM2 t -> Array D DIM2 t -> Array F DIM2 t
-- ^Dense matrix-matrix product. Arguments computed sequentially.
mulS m n = hm2repa $ repa2hmS m `H.mul` repa2hmS n
mulSIO :: Numeric t => Array D DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
-- ^Dense matrix-matrix product. Arguments computed sequentially inside the IO monad
mulSIO m n = hm2repa <$> (H.mul <$> repa2hmSIO m <*> repa2hmSIO n)
mulP :: (Numeric t, Monad m) => Array D DIM2 t -> Array D DIM2 t -> m (Array F DIM2 t)
-- ^Dense matrix-matrix product. Arguments computed in parallel.
mulP m n = hm2repa <$> (H.mul <$> repa2hmP m <*> repa2hmP n)
mulPIO :: Numeric t => Array D DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
-- ^Dense matrix-matrix product. Arguments computed in parallel inside the IO monad
mulPIO m n = hm2repa <$> (H.mul <$> repa2hmPIO m <*> repa2hmPIO n)
-- Outer product of two vectors
outer :: (Product t, Numeric t) => Array F DIM1 t -> Array F DIM1 t -> Array F DIM2 t
-- |Outer product of two vectors.
outer v u = hm2repa $ repa2hv v `H.outer` repa2hv u
outerS :: (Product t, Numeric t) => Array D DIM1 t -> Array D DIM1 t -> Array F DIM2 t
-- |Outer product of two vectors. Arguments computed sequentially.
outerS v u = hm2repa $ repa2hvS v `H.outer` repa2hvS u
outerSIO :: (Product t, Numeric t) => Array D DIM1 t -> Array D DIM1 t -> IO (Array F DIM2 t)
-- |Outer product of two vectors. Arguments computed sequentially inside the IO monad.
outerSIO v u = hm2repa <$> (H.outer <$> repa2hvSIO v <*> repa2hvSIO u)
outerP :: (Product t, Numeric t, Monad m) => Array D DIM1 t -> Array D DIM1 t -> m (Array F DIM2 t)
-- |Outer product of two vectors. Arguments computed in parallel.
outerP v u = hm2repa <$> (H.outer <$> repa2hvP v <*> repa2hvP u)
outerPIO :: (Product t, Numeric t) => Array D DIM1 t -> Array D DIM1 t -> IO (Array F DIM2 t)
-- |Outer product of two vectors. Arguments computed in parallel inside the IO monad.
outerPIO v u = hm2repa <$> (H.outer <$> repa2hvPIO v <*> repa2hvPIO u)
-- Kronecker product of two matrices
kronecker :: (Product t, Numeric t) => Array F DIM2 t -> Array F DIM2 t -> Array F DIM2 t
-- ^Kronecker product of two matrices.
kronecker m n = hm2repa $ repa2hm m `H.kronecker` repa2hm n
kroneckerS :: (Product t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> Array F DIM2 t
-- ^Kronecker product of two matrices. Arguments computed sequentially.
kroneckerS m n = hm2repa $ repa2hmS m `H.kronecker` repa2hmS n
kroneckerSIO :: (Product t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
-- ^Kronecker product of two matrices. Arguments computed sequentially inside the IO monad.
kroneckerSIO m n = hm2repa <$> (H.kronecker <$> repa2hmSIO m <*> repa2hmSIO n)
kroneckerP :: (Product t, Numeric t, Monad m) => Array D DIM2 t -> Array D DIM2 t -> m (Array F DIM2 t)
-- ^Kronecker product of two matrices. Arguments computed in parallel.
kroneckerP m n = hm2repa <$> (H.kronecker <$> repa2hmP m <*> repa2hmP n)
kroneckerPIO :: (Product t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
-- ^Kronecker product of two matrices. Arguments computed in parallel inside the IO monad.
kroneckerPIO m n = hm2repa <$> (H.kronecker <$> repa2hmPIO m <*> repa2hmPIO n)
-- Cross product
cross :: Array F DIM1 Double -> Array F DIM1 Double -> Array F DIM1 Double
-- ^Vector cross product.
cross v u = hv2repa $ repa2hv v `H.cross` repa2hv u
crossS :: Array D DIM1 Double -> Array D DIM1 Double -> Array F DIM1 Double
-- ^Vector cross product. Arguments computed sequentially.
crossS v u = hv2repa $ repa2hvS v `H.cross` repa2hvS u
crossSIO :: Array D DIM1 Double -> Array D DIM1 Double -> IO (Array F DIM1 Double)
-- ^Vector cross product. Arguments computed sequentially inside the IO monad.
crossSIO v u = hv2repa <$> (H.cross <$> repa2hvSIO v <*> repa2hvSIO u)
-- Sum of elements
sumElements :: (Numeric t, HShape sh, Container (HType sh) t) => Array F sh t -> t
-- ^Sum elements of a matrix or a vector.
sumElements = H.sumElements . fromRepa
sumElementsS :: (Numeric t, HShape sh, Container (HType sh) t) => Array D sh t -> t
-- ^Sum elements of a matrix or a vector. Argument computed sequentially.
sumElementsS = H.sumElements . fromRepaS
sumElementsSIO :: (Numeric t, HShape sh, Container (HType sh) t) => Array D sh t -> IO t
-- ^Sum elements of a matrix or a vector. Argument computed sequentially in the IO monad.
sumElementsSIO = fmap H.sumElements . fromRepaSIO
sumElementsP :: (Numeric t, HShape sh, Container (HType sh) t, Monad m) => Array D sh t -> m t
-- ^Sum elements of a matrix or a vector. Argument computed in parallel.
sumElementsP = fmap H.sumElements . fromRepaP
sumElementsPIO :: (Numeric t, HShape sh, Container (HType sh) t) => Array D sh t -> IO t
-- ^Sum elements of a matrix or a vector. Argument computed in parallel in the IO monad.
sumElementsPIO = fmap H.sumElements . fromRepaPIO
-- Product of elements
prodElements :: (Numeric t, HShape sh, Container (HType sh) t) => Array F sh t -> t
-- ^Multiply elements of a matrix or a vector.
prodElements = H.prodElements . fromRepa
prodElementsS :: (Numeric t, HShape sh, Container (HType sh) t) => Array D sh t -> t
-- ^Multiply elements of a matrix or a vector. Argument computed sequentially.
prodElementsS = H.prodElements . fromRepaS
prodElementsSIO :: (Numeric t, HShape sh, Container (HType sh) t) => Array D sh t -> IO t
-- ^Multiply elements of a matrix or a vector. Argument computed sequentially inside the IO monad.
prodElementsSIO = fmap H.prodElements . fromRepaSIO
prodElementsP :: (Numeric t, HShape sh, Container (HType sh) t, Monad m) => Array D sh t -> m t
-- ^Multiply elements of a matrix or a vector. Argument computed in parallel.
prodElementsP = fmap H.prodElements . fromRepaP
prodElementsPIO :: (Numeric t, HShape sh, Container (HType sh) t) => Array D sh t -> IO t
-- ^Multiply elements of a matrix or a vector. Argument computed in parallel inside the IO monad.
prodElementsPIO = fmap H.prodElements . fromRepaPIO
-- Linear systems.
(<\>) :: (Field t, Numeric t, HShape sh, LSDiv (HType sh)) => Array F DIM2 t -> Array F sh t -> Array F sh t
-- ^Infix alias for 'solve'.
(<\>) = solve
solve :: (Field t, Numeric t, HShape sh, LSDiv (HType sh)) => Array F DIM2 t -> Array F sh t -> Array F sh t
-- ^Least squares solution of a linear system, similar to the \ operator of Matlab/Octave (based on linearSolveSD).
solve m n = toRepa $ repa2hm m H.<\> fromRepa n
solveS :: (Field t, Numeric t, HShape sh, LSDiv (HType sh)) => Array D DIM2 t -> Array D sh t -> Array F sh t
-- ^Least squares solution of a linear system, similar to the \ operator of Matlab/Octave (based on linearSolveSD). Arguments are computed sequentially.
solveS m n = toRepa $ repa2hmS m H.<\> fromRepaS n
solveSIO :: (Field t, Numeric t, HShape sh, LSDiv (HType sh)) => Array D DIM2 t -> Array D sh t -> IO (Array F sh t)
-- ^Least squares solution of a linear system, similar to the \ operator of Matlab/Octave (based on linearSolveSD). Arguments are computed sequentially inside the IO monad.
solveSIO m n = toRepa <$> ((H.<\>) <$> repa2hmSIO m <*> fromRepaSIO n)
solveP :: (Field t, Numeric t, HShape sh, LSDiv (HType sh), Monad m) => Array D DIM2 t -> Array D sh t -> m (Array F sh t)
-- ^Least squares solution of a linear system, similar to the \ operator of Matlab/Octave (based on linearSolveSD). Arguments are computed in parallel.
solveP m n = toRepa <$> ((H.<\>) <$> repa2hmP m <*> fromRepaP n)
solvePIO :: (Field t, Numeric t, HShape sh, LSDiv (HType sh)) => Array D DIM2 t -> Array D sh t -> IO (Array F sh t)
-- ^Least squares solution of a linear system, similar to the \ operator of Matlab/Octave (based on linearSolveSD). Arguments are computed in parallel inside the IO monad.
solvePIO m n = toRepa <$> ((H.<\>) <$> repa2hmPIO m <*> fromRepaPIO n)
linearSolve :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM2 t -> Maybe (Array F DIM2 t)
-- ^Solve a linear system (for square coefficient matrix and several right hand sides) using the LU decomposition, returning Nothing for a singular system. For underconstrained or overconstrained systems use 'linearSolveLS' or 'linearSolveSVD'.
linearSolve m n = hm2repa <$> H.linearSolve (repa2hm m) (repa2hm n)
linearSolveS :: (Field t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> Maybe (Array F DIM2 t)
-- ^Solve a linear system using the LU decomposition. Arguments computed sequentially.
linearSolveS m n = hm2repa <$> H.linearSolve (repa2hmS m) (repa2hmS n)
linearSolveP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> Array D DIM2 t -> m (Maybe (Array F DIM2 t))
-- ^Solve a linear system using the LU decomposition. Arguments computed in parallel.
linearSolveP m n = (hm2repa <$>) <$> (H.linearSolve <$> repa2hmP m <*> repa2hmP n)
linearSolveSIO :: (Field t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> IO (Maybe (Array F DIM2 t))
-- ^Solve a linear system using the LU decomposition. Arguments computed sequentially inside the IO monad.
linearSolveSIO m n = (hm2repa <$>) <$> (H.linearSolve <$> repa2hmSIO m <*> repa2hmSIO n)
linearSolvePIO :: (Field t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> IO (Maybe (Array F DIM2 t))
-- ^Solve a linear system using the LU decomposition. Arguments computed in parallel inside the IO monad.
linearSolvePIO m n = (hm2repa <$>) <$> (H.linearSolve <$> repa2hmPIO m <*> repa2hmPIO n)
linearSolveLS :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM2 t -> Array F DIM2 t
-- ^Least squared error solution of an overcompensated system, or the minimum norm solution of an undercompensated system. For rank-deficient systems use 'linearSolveSVD'.
linearSolveLS m n = hm2repa $ H.linearSolveLS (repa2hm m) (repa2hm n)
linearSolveLS_S :: (Field t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> Array F DIM2 t
linearSolveLS_S m n = hm2repa $ H.linearSolveLS (repa2hmS m) (repa2hmS n)
linearSolveLS_SIO :: (Field t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
linearSolveLS_SIO m n = hm2repa <$> (H.linearSolveLS <$> repa2hmSIO m <*> repa2hmSIO n)
linearSolveLS_P :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> Array D DIM2 t -> m (Array F DIM2 t)
linearSolveLS_P m n = hm2repa <$> (H.linearSolveLS <$> repa2hmP m <*> repa2hmP n)
linearSolveLS_PIO :: (Field t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
linearSolveLS_PIO m n = hm2repa <$> (H.linearSolveLS <$> repa2hmPIO m <*> repa2hmPIO n)
linearSolveSVD :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM2 t -> Array F DIM2 t
-- ^Minimum norm solution of a general linear least squares problem Ax=b using the SVD. Admits rank-deficient systems but is slower than 'linearSolveLS'. The effective rank of A is determined by treating as zero those singular values which are less than eps times the largest singular value.
linearSolveSVD m n = hm2repa $ H.linearSolveSVD (repa2hm m) (repa2hm n)
linearSolveSVD_S :: (Field t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> Array F DIM2 t
linearSolveSVD_S m n = hm2repa $ H.linearSolveSVD (repa2hmS m) (repa2hmS n)
linearSolveSVD_SIO :: (Field t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
linearSolveSVD_SIO m n = hm2repa <$> (H.linearSolveSVD <$> repa2hmSIO m <*> repa2hmSIO n)
linearSolveSVD_P :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> Array D DIM2 t -> m (Array F DIM2 t)
linearSolveSVD_P m n = hm2repa <$> (H.linearSolveSVD <$> repa2hmP m <*> repa2hmP n)
linearSolveSVD_PIO :: (Field t, Numeric t) => Array D DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
linearSolveSVD_PIO m n = hm2repa <$> (H.linearSolveLS <$> repa2hmPIO m <*> repa2hmPIO n)
luSolve :: (Field t, Numeric t) => H.LU t -> Array F DIM2 t -> Array F DIM2 t
-- ^Solution of a linear system (for several right hand sides) from the precomputed LU factorization obtained by 'luPacked'.
luSolve lu' m = hm2repa $ H.luSolve lu' (repa2hm m)
luSolveS :: (Field t, Numeric t) => H.LU t -> Array D DIM2 t -> Array F DIM2 t
luSolveS lu' m = hm2repa $ H.luSolve lu' (repa2hmS m)
luSolveSIO :: (Field t, Numeric t) => H.LU t -> Array D DIM2 t -> IO (Array F DIM2 t)
luSolveSIO lu' m = hm2repa . H.luSolve lu' <$> repa2hmSIO m
luSolveP :: (Field t, Numeric t, Monad m) => H.LU t -> Array D DIM2 t -> m (Array F DIM2 t)
luSolveP lu' m = hm2repa . H.luSolve lu' <$> repa2hmP m
luSolvePIO :: (Field t, Numeric t) => H.LU t -> Array D DIM2 t -> IO (Array F DIM2 t)
luSolvePIO lu' m = hm2repa . H.luSolve lu' <$> repa2hmPIO m
cholSolve :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM2 t -> Array F DIM2 t
-- ^Solve a symmetric or Herimitian positive definite linear system using a precomputed Cholesky decomposition obtained by 'chol'.
cholSolve ch m = hm2repa $ H.cholSolve (repa2hm ch) (repa2hm m)
cholSolveS :: (Field t, Numeric t) => Array F DIM2 t -> Array D DIM2 t -> Array F DIM2 t
cholSolveS ch m = hm2repa $ H.cholSolve (repa2hm ch) (repa2hmS m)
cholSolveSIO :: (Field t, Numeric t) => Array F DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
cholSolveSIO ch m = hm2repa . H.cholSolve (repa2hm ch) <$> repa2hmSIO m
cholSolveP :: (Field t, Numeric t, Monad m) => Array F DIM2 t -> Array D DIM2 t -> m (Array F DIM2 t)
cholSolveP ch m = hm2repa . H.cholSolve (repa2hm ch) <$> repa2hmP m
cholSolvePIO :: (Field t, Numeric t) => Array F DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
cholSolvePIO ch m = hm2repa . H.cholSolve (repa2hm ch) <$> repa2hmPIO m
-- Inverse and pseudoinverse
inv :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM2 t
-- ^Inverse of a square matrix.
inv = hm2repa . H.inv . repa2hm
invS :: (Field t, Numeric t) => Array D DIM2 t -> Array F DIM2 t
invS = hm2repa . H.inv . repa2hmS
invSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
invSIO = fmap (hm2repa . H.inv) . repa2hmSIO
invP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t)
invP = fmap (hm2repa . H.inv) . repa2hmP
invPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
invPIO = fmap (hm2repa . H.inv) . repa2hmPIO
pinv :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM2 t
-- ^Pseudoinverse of a general matrix, with default tolerance ('pinvTol' 1, similar to GNU-Octave)
pinv = hm2repa . H.pinv . repa2hm
pinvS :: (Field t, Numeric t) => Array D DIM2 t -> Array F DIM2 t
pinvS = hm2repa . H.pinv . repa2hmS
pinvSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
pinvSIO = fmap (hm2repa . H.pinv) . repa2hmSIO
pinvP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t)
pinvP = fmap (hm2repa . H.pinv) . repa2hmP
pinvPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
pinvPIO = fmap (hm2repa . H.pinv) . repa2hmPIO
pinvTol :: (Field t, Numeric t) => Double -> Array F DIM2 t -> Array F DIM2 t
-- ^pinvTol r computes the pseudoinverse of a matrix with tolerance tol=r*g*eps*(max rows cols), where g is the greatest singular value.
pinvTol r = hm2repa . H.pinvTol r . repa2hm
pinvTolS :: (Field t, Numeric t) => Double -> Array D DIM2 t -> Array F DIM2 t
pinvTolS r = hm2repa . H.pinvTol r . repa2hmS
pinvTolSIO :: (Field t, Numeric t) => Double -> Array D DIM2 t -> IO (Array F DIM2 t)
pinvTolSIO r= fmap (hm2repa . H.pinvTol r) . repa2hmSIO
pinvTolP :: (Field t, Numeric t, Monad m) => Double -> Array D DIM2 t -> m (Array F DIM2 t)
pinvTolP r = fmap (hm2repa . H.pinvTol r) . repa2hmP
pinvTolPIO :: (Field t, Numeric t) => Double -> Array D DIM2 t -> IO (Array F DIM2 t)
pinvTolPIO r = fmap (hm2repa . H.pinvTol r) . repa2hmPIO
-- Determinant and rank
rcond :: (Field t, Numeric t) => Array F DIM2 t -> Double
-- ^Reciprocal of the 2-norm condition number of a matrix, computed from the singular values.
rcond = H.rcond . repa2hm
rcondS :: (Field t, Numeric t) => Array D DIM2 t -> Double
rcondS = H.rcond . repa2hmS
rcondSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO Double
rcondSIO = fmap H.rcond . repa2hmSIO
rcondP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m Double
rcondP = fmap H.rcond . repa2hmP
rcondPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO Double
rcondPIO = fmap H.rcond . repa2hmPIO
rank :: (Field t, Numeric t) => Array F DIM2 t -> Int
-- ^Number of linearly independent rows or columns. See also 'ranksv'.
rank = H.rank . repa2hm
rankS :: (Field t, Numeric t) => Array D DIM2 t -> Int
rankS = H.rank . repa2hmS
rankSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO Int
rankSIO = fmap H.rank . repa2hmSIO
rankP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m Int
rankP = fmap H.rank . repa2hmP
rankPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO Int
rankPIO = fmap H.rank . repa2hmPIO
det :: (Field t, Numeric t) => Array F DIM2 t -> t
-- ^Determinant of a square matrix. To avoid possible overflow or underflow use 'invlndet'.
det = H.det . repa2hm
detS :: (Field t, Numeric t) => Array D DIM2 t -> t
detS = H.det . repa2hmS
detSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO t
detSIO = fmap H.det . repa2hmSIO
detP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m t
detP = fmap H.det . repa2hmP
detPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO t
detPIO = fmap H.det . repa2hmPIO
invlndet :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM2 t, (t, t)) -- ^(inverse, (log abs det, sign or phase of det))
-- ^Joint computation of inverse and logarithm of determinant of a square matrix.
invlndet m = let (h, r) = H.invlndet $ repa2hm m in (hm2repa h, r)
invlndetS :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM2 t, (t, t))
invlndetS m = let (h, r) = H.invlndet $ repa2hmS m in (hm2repa h, r)
invlndetSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, (t, t))
invlndetSIO m = do
(h, r) <- H.invlndet <$> repa2hmSIO m
return (hm2repa h, r)
invlndetP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t, (t, t))
invlndetP m = do
(h, r) <- H.invlndet <$> repa2hmP m
return (hm2repa h, r)
invlndetPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, (t, t))
invlndetPIO m = do
(h, r) <- H.invlndet <$> repa2hmPIO m
return (hm2repa h, r)
-- Norms
norm_Frob :: (Normed (Vector t), Element t) => Array F DIM2 t -> Double
norm_Frob = H.norm_Frob . repa2hm
norm_FrobS :: (Normed (Vector t), Element t) => Array D DIM2 t -> Double
norm_FrobS = H.norm_Frob . repa2hmS
norm_FrobSIO :: (Normed (Vector t), Element t) => Array D DIM2 t -> IO Double
norm_FrobSIO = fmap H.norm_Frob . repa2hmSIO
norm_FrobP :: (Normed (Vector t), Element t, Monad m) => Array D DIM2 t -> m Double
norm_FrobP = fmap H.norm_Frob . repa2hmP
norm_FrobPIO :: (Normed (Vector t), Element t) => Array D DIM2 t -> IO Double
norm_FrobPIO = fmap H.norm_Frob . repa2hmPIO
norm_nuclear :: (Field t, Numeric t) => Array F DIM2 t -> Double
norm_nuclear = H.norm_nuclear . repa2hm
norm_nuclearS :: (Field t, Numeric t) => Array D DIM2 t -> Double
norm_nuclearS = H.norm_nuclear . repa2hmS
norm_nuclearSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO Double
norm_nuclearSIO = fmap H.norm_nuclear . repa2hmSIO
norm_nuclearP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m Double
norm_nuclearP = fmap H.norm_nuclear . repa2hmP
norm_nuclearPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO Double
norm_nuclearPIO = fmap H.norm_nuclear . repa2hmPIO
-- Nullspace and range
orth :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM2 t
-- ^An orthonormal basis of the range space of a matrix. See also 'orthSVD'.
orth = hm2repa . H.orth . repa2hm
orthS :: (Field t, Numeric t) => Array D DIM2 t -> Array F DIM2 t
orthS = hm2repa . H.orth . repa2hmS
orthSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
orthSIO = fmap (hm2repa . H.orth) . repa2hmSIO
orthP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t)
orthP = fmap (hm2repa . H.orth) . repa2hmP
orthPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
orthPIO = fmap (hm2repa . H.orth) . repa2hmPIO
nullspace :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM2 t
-- ^An orthonormal basis of the null space of a matrix. See also 'nullspaceSVD'.
nullspace = hm2repa . H.nullspace . repa2hm
nullspaceS :: (Field t, Numeric t) => Array D DIM2 t -> Array F DIM2 t
nullspaceS = hm2repa . H.nullspace . repa2hmS
nullspaceSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
nullspaceSIO = fmap (hm2repa . H.nullspace) . repa2hmSIO
nullspaceP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t)
nullspaceP = fmap (hm2repa . H.nullspace) . repa2hmP
nullspacePIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
nullspacePIO = fmap (hm2repa . H.nullspace) . repa2hmPIO
null1 :: Array F DIM2 Double -> Array F DIM1 Double
-- ^Solution of an overconstrained homogenous linear system.
null1 = hv2repa . H.null1 . repa2hm
null1S :: Array D DIM2 Double -> Array F DIM1 Double
null1S = hv2repa . H.null1 . repa2hmS
null1SIO :: Array D DIM2 Double -> IO (Array F DIM1 Double)
null1SIO = fmap (hv2repa . H.null1) . repa2hmSIO
null1P :: Monad m => Array D DIM2 Double -> m (Array F DIM1 Double)
null1P = fmap (hv2repa . H.null1) . repa2hmP
null1PIO :: Array D DIM2 Double -> IO (Array F DIM1 Double)
null1PIO = fmap (hv2repa . H.null1) . repa2hmPIO
null1sym :: H.Herm Double -> Array F DIM1 Double
-- ^Solution of an overconstrained homogenous symmetric linear system.
null1sym = hv2repa . H.null1sym
-- SVD
svd :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
-- ^Full singular value decomposition.
svd m = let (u,s,v) = H.svd $ repa2hm m in (hm2repa u, hv2repa s, hm2repa v)
svdS :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
svdS m = let (u,s,v) = H.svd $ repa2hmS m in (hm2repa u, hv2repa s, hm2repa v)
svdSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
svdSIO m = do
(u,s,v) <- H.svd <$> repa2hmSIO m
return (hm2repa u, hv2repa s, hm2repa v)
svdP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
svdP m = do
(u,s,v) <- H.svd <$> repa2hmP m
return (hm2repa u, hv2repa s, hm2repa v)
svdPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
svdPIO m = do
(u,s,v) <- H.svd <$> repa2hmPIO m
return (hm2repa u, hv2repa s, hm2repa v)
thinSVD :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
-- ^A version of 'svd' which returns only the min (rows m) (cols m) singular vectors of m. (u,s,v) = thinSVD m ==> m == u * diag s * tr v
thinSVD m = let (u,s,v) = H.thinSVD $ repa2hm m in (hm2repa u, hv2repa s, hm2repa v)
thinSVD_S :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
thinSVD_S m = let (u,s,v) = H.thinSVD $ repa2hmS m in (hm2repa u, hv2repa s, hm2repa v)
thinSVD_SIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
thinSVD_SIO m = do
(u,s,v) <- H.thinSVD <$> repa2hmSIO m
return (hm2repa u, hv2repa s, hm2repa v)
thinSVD_P :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
thinSVD_P m = do
(u,s,v) <- H.thinSVD <$> repa2hmP m
return (hm2repa u, hv2repa s, hm2repa v)
thinSVD_PIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
thinSVD_PIO m = do
(u,s,v) <- H.thinSVD <$> repa2hmPIO m
return (hm2repa u, hv2repa s, hm2repa v)
compactSVD :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
-- ^Similar to 'thinSVD', returning only the nonzero singular values and the corresponding singular vectors.
compactSVD m = let (u,s,v) = H.compactSVD $ repa2hm m in (hm2repa u, hv2repa s, hm2repa v)
compactSVD_S :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
compactSVD_S m = let (u,s,v) = H.compactSVD $ repa2hmS m in (hm2repa u, hv2repa s, hm2repa v)
compactSVD_SIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
compactSVD_SIO m = do
(u,s,v) <- H.compactSVD <$> repa2hmSIO m
return (hm2repa u, hv2repa s, hm2repa v)
compactSVD_P :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
compactSVD_P m = do
(u,s,v) <- H.compactSVD <$> repa2hmP m
return (hm2repa u, hv2repa s, hm2repa v)
compactSVD_PIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM1 Double, Array F DIM2 t)
compactSVD_PIO m = do
(u,s,v) <- H.compactSVD <$> repa2hmPIO m
return (hm2repa u, hv2repa s, hm2repa v)
singularValues :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM1 Double
-- ^Singular values only.
singularValues = hv2repa . H.singularValues . repa2hm
singularValuesS :: (Field t, Numeric t) => Array D DIM2 t -> Array F DIM1 Double
singularValuesS = hv2repa . H.singularValues . repa2hmS
singularValuesSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM1 Double)
singularValuesSIO = fmap (hv2repa . H.singularValues) . repa2hmSIO
singularValuesP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM1 Double)
singularValuesP = fmap (hv2repa . H.singularValues) . repa2hmP
singularValuesPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM1 Double)
singularValuesPIO = fmap (hv2repa . H.singularValues) . repa2hmPIO
leftSV :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM2 t, Array F DIM1 Double)
-- ^Singular values and all left singular vectors (as columns).
leftSV m = let (u,s) = H.leftSV $ repa2hm m in (hm2repa u, hv2repa s)
leftSV_S :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM2 t, Array F DIM1 Double)
leftSV_S m = let (u,s) = H.leftSV $ repa2hmS m in (hm2repa u, hv2repa s)
leftSV_SIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM1 Double)
leftSV_SIO m = do
(u,s) <- H.leftSV <$> repa2hmSIO m
return (hm2repa u, hv2repa s)
leftSV_P :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t, Array F DIM1 Double)
leftSV_P m = do
(u,s) <- H.leftSV <$> repa2hmP m
return (hm2repa u, hv2repa s)
leftSV_PIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM1 Double)
leftSV_PIO m = do
(u,s) <- H.leftSV <$> repa2hmPIO m
return (hm2repa u, hv2repa s)
rightSV :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM1 Double, Array F DIM2 t)
-- ^Singular values and all right singular vectors (as columns).
rightSV m = let (s,v) = H.rightSV $ repa2hm m in (hv2repa s, hm2repa v)
rightSV_S :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM1 Double, Array F DIM2 t)
rightSV_S m = let (s,v) = H.rightSV $ repa2hmS m in (hv2repa s, hm2repa v)
rightSV_SIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM1 Double, Array F DIM2 t)
rightSV_SIO m = do
(s,v) <- H.rightSV <$> repa2hmSIO m
return (hv2repa s, hm2repa v)
rightSV_P :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM1 Double, Array F DIM2 t)
rightSV_P m = do
(s,v) <- H.rightSV <$> repa2hmP m
return (hv2repa s, hm2repa v)
rightSV_PIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM1 Double, Array F DIM2 t)
rightSV_PIO m = do
(s,v) <- H.rightSV <$> repa2hmPIO m
return (hv2repa s, hm2repa v)
-- Eigensystems
eig :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM1 (Complex Double), Array F DIM2 (Complex Double))
-- ^Eigenvalues (not ordered) and eigenvectors (as columns) of a general square matrix. (s,v) = eig m ==> m * v = v == v <> diag s
eig m = let (s,v) = H.eig $ repa2hm m in (hv2repa s, hm2repa v)
eigS :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM1 (Complex Double), Array F DIM2 (Complex Double))
eigS m = let (s,v) = H.eig $ repa2hmS m in (hv2repa s, hm2repa v)
eigSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM1 (Complex Double), Array F DIM2 (Complex Double))
eigSIO m = do
(s,v) <- H.eig <$> repa2hmSIO m
return (hv2repa s, hm2repa v)
eigP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM1 (Complex Double), Array F DIM2 (Complex Double))
eigP m = do
(s,v) <- H.eig <$> repa2hmP m
return (hv2repa s, hm2repa v)
eigPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM1 (Complex Double), Array F DIM2 (Complex Double))
eigPIO m = do
(s,v) <- H.eig <$> repa2hmPIO m
return (hv2repa s, hm2repa v)
eigSH :: (Field t, Numeric t) => H.Herm t -> (Array F DIM1 Double, Array F DIM2 t)
-- ^Eigenvalues and eigenvectors (as columns) of a complex hermitian or a real symmetric matrix, in descending order.
eigSH h = let (s,v) = H.eigSH h in (hv2repa s, hm2repa v)
eigenvalues :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM1 (Complex Double)
-- ^Eigenvalues (not ordered) of a general square matrix.
eigenvalues = hv2repa . H.eigenvalues . repa2hm
eigenvaluesS :: (Field t, Numeric t) => Array D DIM2 t -> Array F DIM1 (Complex Double)
eigenvaluesS = hv2repa . H.eigenvalues . repa2hmS
eigenvaluesSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM1 (Complex Double))
eigenvaluesSIO = fmap (hv2repa . H.eigenvalues) . repa2hmSIO
eigenvaluesP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM1 (Complex Double))
eigenvaluesP = fmap (hv2repa . H.eigenvalues) . repa2hmP
eigenvaluesPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM1 (Complex Double))
eigenvaluesPIO = fmap (hv2repa . H.eigenvalues) . repa2hmPIO
eigenvaluesSH :: (Field t, Numeric t) => H.Herm t -> Array F DIM1 Double
-- ^Eigenvalues (in descending order) of a complex hermitian or real symmetric matrix.
eigenvaluesSH = hv2repa . H.eigenvaluesSH
geigSH :: (Field t, Numeric t) => H.Herm t -> H.Herm t -> (Array F DIM1 Double, Array F DIM2 t)
-- ^Generalized symmetric positive definite eigensystem Av = IBv, for A and B symmetric, B positive definite.
geigSH a b = let (s,v) = H.geigSH a b in (hv2repa s, hm2repa v)
-- QR
qr :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM2 t, Array F DIM2 t)
-- ^QR factorization. (q,r) = qr m ==> m = q * r where q is unitary and r is upper triangular.
qr m = let (q,r) = H.qr $ repa2hm m in (hm2repa q, hm2repa r)
qrS :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM2 t, Array F DIM2 t)
qrS m = let (q,r) = H.qr $ repa2hmS m in (hm2repa q, hm2repa r)
qrSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM2 t)
qrSIO m = do
(q,r) <- H.qr <$> repa2hmSIO m
return (hm2repa q, hm2repa r)
qrP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t, Array F DIM2 t)
qrP m = do
(q,r) <- H.qr <$> repa2hmP m
return (hm2repa q, hm2repa r)
qrPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM2 t)
qrPIO m = do
(q,r) <- H.qr <$> repa2hmPIO m
return (hm2repa q, hm2repa r)
rq :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM2 t, Array F DIM2 t)
-- ^RQ factorization. (r,q) = rq m ==> m = r * q where q is unitary and r is upper triangular.
rq m = let (r,q) = H.rq $ repa2hm m in (hm2repa r, hm2repa q)
rqS :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM2 t, Array F DIM2 t)
rqS m = let (r,q) = H.rq $ repa2hmS m in (hm2repa r, hm2repa q)
rqSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM2 t)
rqSIO m = do
(r,q) <- H.rq <$> repa2hmSIO m
return (hm2repa r, hm2repa q)
rqP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t, Array F DIM2 t)
rqP m = do
(r,q) <- H.rq <$> repa2hmP m
return (hm2repa r, hm2repa q)
rqPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM2 t)
rqPIO m = do
(r,q) <- H.rq <$> repa2hmPIO m
return (hm2repa r, hm2repa q)
qrRaw :: (Field t, Numeric t) => Array F DIM2 t -> H.QR t
qrRaw m = H.qrRaw $ repa2hm m
qrRawS :: (Field t, Numeric t) => Array D DIM2 t -> H.QR t
qrRawS m = H.qrRaw $ repa2hmS m
qrRawSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (H.QR t)
qrRawSIO m = H.qrRaw <$> repa2hmSIO m
qrRawP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (H.QR t)
qrRawP m = H.qrRaw <$> repa2hmP m
qrRawPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (H.QR t)
qrRawPIO m = H.qrRaw <$> repa2hmPIO m
qrgr :: (Field t, Numeric t) => Int -> H.QR t -> Array F DIM2 t
-- ^Generate a matrix with k othogonal columns from the output of 'qrRaw'.
qrgr k qr' = hm2repa $ H.qrgr k qr'
-- Cholesky
chol :: Field t => H.Herm t -> Array F DIM2 t
-- ^Cholesky factorization of a positive definite hermitian or symmetric matrix. c = chol m ==> m == c' * c where c is upper triangular.
chol = hm2repa . H.chol
mbChol :: Field t => H.Herm t -> Maybe (Array F DIM2 t)
-- ^Similar to chol, but instead of an error (e.g., caused by a matrix not positive definite) it returns Nothing.
mbChol h = hm2repa <$> H.mbChol h
-- Hessenberg
hess :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM2 t, Array F DIM2 t)
-- ^Hessenberg factorization. (p,h) == hess m ==> p * h * p' where p is unitary and h is in upper Hessenberg form (zero entries below the first subdiagonal).
hess m = let (p,h) = H.hess $ repa2hm m in (hm2repa p, hm2repa h)
hessS :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM2 t, Array F DIM2 t)
hessS m = let (p,h) = H.hess $ repa2hmS m in (hm2repa p, hm2repa h)
hessSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM2 t)
hessSIO m = do
(p,h) <- H.hess <$> repa2hmSIO m
return (hm2repa p, hm2repa h)
hessP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t, Array F DIM2 t)
hessP m = do
(p,h) <- H.hess <$> repa2hmP m
return (hm2repa p, hm2repa h)
hessPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM2 t)
hessPIO m = do
(p,h) <- H.hess <$> repa2hmPIO m
return (hm2repa p, hm2repa h)
-- Schur
schur :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM2 t, Array F DIM2 t)
-- ^Schur factorization. (u,s) = schur m ==> m == u * s * u' where u is unitary and s is a Schur matrix. A complex Schur matrix is upper triangular. A real Schur matrix is upper triangular in 2x2 blocks.
schur m = let (u,s) = H.schur $ repa2hm m in (hm2repa u, hm2repa s)
schurS :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM2 t, Array F DIM2 t)
schurS m = let (u,s) = H.schur $ repa2hmS m in (hm2repa u, hm2repa s)
schurSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM2 t)
schurSIO m = do
(u,s) <- H.schur <$> repa2hmSIO m
return (hm2repa u, hm2repa s)
schurP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t, Array F DIM2 t)
schurP m = do
(u,s) <- H.schur <$> repa2hmP m
return (hm2repa u, hm2repa s)
schurPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM2 t)
schurPIO m = do
(u,s) <- H.schur <$> repa2hmPIO m
return (hm2repa u, hm2repa s)
-- LU
lu :: (Field t, Numeric t) => Array F DIM2 t -> (Array F DIM2 t, Array F DIM2 t, Array F DIM2 t, t)
-- ^Explicit LU factorization of a general matrix. (l,u,p,s) = lu m ==> m = p * l * u where l is lower triangular, u is upper triangular, p is a permutation matrix, and s is the signature of the permutation.
lu m = let (l,u,p,s) = H.lu $ repa2hm m in (hm2repa l, hm2repa u, hm2repa p, s)
luS :: (Field t, Numeric t) => Array D DIM2 t -> (Array F DIM2 t, Array F DIM2 t, Array F DIM2 t, t)
luS m = let (l,u,p,s) = H.lu $ repa2hmS m in (hm2repa l, hm2repa u, hm2repa p, s)
luSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM2 t, Array F DIM2 t, t)
luSIO m = do
(l,u,p,s) <- H.lu <$> repa2hmSIO m
return (hm2repa l, hm2repa u, hm2repa p, s)
luP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t, Array F DIM2 t, Array F DIM2 t, t)
luP m = do
(l,u,p,s) <- H.lu <$> repa2hmP m
return (hm2repa l, hm2repa u, hm2repa p, s)
luPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t, Array F DIM2 t, Array F DIM2 t, t)
luPIO m = do
(l,u,p,s) <- H.lu <$> repa2hmPIO m
return (hm2repa l, hm2repa u, hm2repa p, s)
luPacked :: (Field t, Numeric t) => Array F DIM2 t -> H.LU t
-- ^Obtains the LU decomposition in a packed data structure suitable for 'luSolve'.
luPacked m = H.luPacked $ repa2hm m
luPackedS :: (Field t, Numeric t) => Array D DIM2 t -> H.LU t
luPackedS m = H.luPacked $ repa2hmS m
luPackedSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (H.LU t)
luPackedSIO m = H.luPacked <$> repa2hmSIO m
luPackedP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (H.LU t)
luPackedP m = H.luPacked <$> repa2hmP m
luPackedPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (H.LU t)
luPackedPIO m = H.luPacked <$> repa2hmPIO m
luFact :: Numeric t => H.LU t -> (Array F DIM2 t, Array F DIM2 t, Array F DIM2 t, t)
-- ^Compute the explicit LU decomposition from the compact one obtained by luPacked.
luFact lu' = let (l,u,p,s) = H.luFact lu' in (hm2repa l, hm2repa u, hm2repa p, s)
-- Symmetric indefinite
ldlSolve :: Field t => H.LDL t -> Array F DIM2 t -> Array F DIM2 t
{- ^
Solution of a linear system (for several right hand sides) from a precomputed LDL factorization obtained by 'ldlPacked'.
Note: this can be slower than the general solver based on the LU decomposition.
-}
ldlSolve l = hm2repa . H.ldlSolve l . repa2hm
ldlSolveS :: Field t => H.LDL t -> Array D DIM2 t -> Array F DIM2 t
ldlSolveS l = hm2repa . H.ldlSolve l . repa2hmS
ldlSolveSIO :: Field t => H.LDL t -> Array D DIM2 t -> IO (Array F DIM2 t)
ldlSolveSIO l m = hm2repa . H.ldlSolve l <$> repa2hmSIO m
ldlSolveP :: (Field t, Monad m) => H.LDL t -> Array D DIM2 t -> m (Array F DIM2 t)
ldlSolveP l m = hm2repa . H.ldlSolve l <$> repa2hmP m
ldlSolvePIO :: Field t => H.LDL t -> Array D DIM2 t -> IO (Array F DIM2 t)
ldlSolvePIO l m = hm2repa . H.ldlSolve l <$> repa2hmPIO m
ldlPacked :: Field t => H.Herm t -> H.LDL t
-- ^Obtains the LDL decomposition of a matrix in a compact data structure suitable for 'ldlSolve'.
ldlPacked = H.ldlPacked
-- Matrix functions
expm :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM2 t
-- ^Matrix exponential. It uses a direct translation of Algorithm 11.3.1 in Golub & Val Loan, based on a scaled Pade approximation.
expm = hm2repa . H.expm . repa2hm
expmS :: (Field t, Numeric t) => Array D DIM2 t -> Array F DIM2 t
expmS = hm2repa . H.expm . repa2hmS
expmSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
expmSIO = fmap (hm2repa . H.expm) . repa2hmSIO
expmP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t)
expmP = fmap (hm2repa . H.expm) . repa2hmP
expmPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
expmPIO = fmap (hm2repa . H.expm) . repa2hmPIO
sqrtm :: (Field t, Numeric t) => Array F DIM2 t -> Array F DIM2 t
-- ^Matrix square root. Currently it uses a simple iterative algorithm described in Wikipedia. It only works with invertible matrices that have a real solution.
sqrtm = hm2repa . H.sqrtm . repa2hm
sqrtmS :: (Field t, Numeric t) => Array D DIM2 t -> Array F DIM2 t
sqrtmS = hm2repa . H.sqrtm . repa2hmS
sqrtmSIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
sqrtmSIO = fmap (hm2repa . H.sqrtm) . repa2hmSIO
sqrtmP :: (Field t, Numeric t, Monad m) => Array D DIM2 t -> m (Array F DIM2 t)
sqrtmP = fmap (hm2repa . H.sqrtm) . repa2hmP
sqrtmPIO :: (Field t, Numeric t) => Array D DIM2 t -> IO (Array F DIM2 t)
sqrtmPIO = fmap (hm2repa . H.sqrtm) . repa2hmPIO
matFunc :: (Complex Double -> Complex Double) -> Array F DIM2 (Complex Double) -> Array F DIM2 (Complex Double)
-- Generic matrix function for diagonalizable matrices.
matFunc f = hm2repa . H.matFunc f . repa2hm
matFuncS :: (Complex Double -> Complex Double) -> Array D DIM2 (Complex Double) -> Array F DIM2 (Complex Double)
matFuncS f = hm2repa . H.matFunc f . repa2hmS
matFuncSIO :: (Complex Double -> Complex Double) -> Array D DIM2 (Complex Double) -> IO (Array F DIM2 (Complex Double))
matFuncSIO f = fmap (hm2repa . H.matFunc f) . repa2hmSIO
matFuncP :: Monad m => (Complex Double -> Complex Double) -> Array D DIM2 (Complex Double) -> m (Array F DIM2 (Complex Double))
matFuncP f = fmap (hm2repa . H.matFunc f) . repa2hmP
matFuncPIO :: (Complex Double -> Complex Double) -> Array D DIM2 (Complex Double) -> IO (Array F DIM2 (Complex Double))
matFuncPIO f = fmap (hm2repa . H.matFunc f) . repa2hmPIO
-- Correlation and convolution
corr :: (Product t, Numeric t) => Array F DIM1 t -> Array F DIM1 t -> Array F DIM1 t
-- ^Correlation.
corr k = hv2repa . H.corr (repa2hv k) . repa2hv
corrS :: (Product t, Numeric t) => Array F DIM1 t -> Array D DIM1 t -> Array F DIM1 t
corrS k = hv2repa . H.corr (repa2hv k) . repa2hvS
corrSIO :: (Product t, Numeric t) => Array F DIM1 t -> Array D DIM1 t -> IO (Array F DIM1 t)
corrSIO k = fmap (hv2repa . H.corr (repa2hv k)) . repa2hvSIO
corrP :: (Product t, Numeric t, Monad m) => Array F DIM1 t -> Array D DIM1 t -> m (Array F DIM1 t)
corrP k = fmap (hv2repa . H.corr (repa2hv k)) . repa2hvP
corrPIO :: (Product t, Numeric t) => Array F DIM1 t -> Array D DIM1 t -> IO (Array F DIM1 t)
corrPIO k = fmap (hv2repa . H.corr (repa2hv k)) . repa2hvPIO
conv :: (Product t, Numeric t) => Array F DIM1 t -> Array F DIM1 t -> Array F DIM1 t
-- ^Convolution - 'corr' with reversed kernel and padded input, equivalent to polynomial multiplication.
conv k = hv2repa . H.conv (repa2hv k) . repa2hv
convS :: (Product t, Numeric t) => Array F DIM1 t -> Array D DIM1 t -> Array F DIM1 t
convS k = hv2repa . H.conv (repa2hv k) . repa2hvS
convSIO :: (Product t, Numeric t) => Array F DIM1 t -> Array D DIM1 t -> IO (Array F DIM1 t)
convSIO k = fmap (hv2repa . H.conv (repa2hv k)) . repa2hvSIO
convP :: (Product t, Numeric t, Monad m) => Array F DIM1 t -> Array D DIM1 t -> m (Array F DIM1 t)
convP k = fmap (hv2repa . H.conv (repa2hv k)) . repa2hvP
convPIO :: (Product t, Numeric t) => Array F DIM1 t -> Array D DIM1 t -> IO (Array F DIM1 t)
convPIO k = fmap (hv2repa . H.conv (repa2hv k)) . repa2hvPIO
corrMin :: (Product t, Numeric t, RealElement t) => Array F DIM1 t -> Array F DIM1 t -> Array F DIM1 t
-- ^Similar to 'corr' but using 'min' instead of (*).
corrMin k = hv2repa . H.corrMin (repa2hv k) . repa2hv
corrMinS :: (Product t, Numeric t, RealElement t) => Array F DIM1 t -> Array D DIM1 t -> Array F DIM1 t
corrMinS k = hv2repa . H.corrMin (repa2hv k) . repa2hvS
corrMinSIO :: (Product t, Numeric t, RealElement t) => Array F DIM1 t -> Array D DIM1 t -> IO (Array F DIM1 t)
corrMinSIO k = fmap (hv2repa . H.corrMin (repa2hv k)) . repa2hvSIO
corrMinP :: (Product t, Numeric t, RealElement t, Monad m) => Array F DIM1 t -> Array D DIM1 t -> m (Array F DIM1 t)
corrMinP k = fmap (hv2repa . H.corrMin (repa2hv k)) . repa2hvP
corrMinPIO :: (Product t, Numeric t, RealElement t) => Array F DIM1 t -> Array D DIM1 t -> IO (Array F DIM1 t)
corrMinPIO k = fmap (hv2repa . H.corrMin (repa2hv k)) . repa2hvPIO
corr2 :: (Product t, Numeric t) => Array F DIM2 t -> Array F DIM2 t -> Array F DIM2 t
-- ^2D correlation (without padding).
corr2 k = hm2repa . H.corr2 (repa2hm k) . repa2hm
corr2S :: (Product t, Numeric t) => Array F DIM2 t -> Array D DIM2 t -> Array F DIM2 t
corr2S k = hm2repa . H.corr2 (repa2hm k) . repa2hmS
corr2SIO :: (Product t, Numeric t) => Array F DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
corr2SIO k = fmap (hm2repa . H.corr2 (repa2hm k)) . repa2hmSIO
corr2P :: (Product t, Numeric t, Monad m) => Array F DIM2 t -> Array D DIM2 t -> m (Array F DIM2 t)
corr2P k = fmap (hm2repa . H.corr2 (repa2hm k)) . repa2hmP
corr2PIO :: (Product t, Numeric t) => Array F DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
corr2PIO k = fmap (hm2repa . H.corr2 (repa2hm k)) . repa2hmPIO
conv2 :: (Product t, Numeric t, Num (Vector t)) => Array F DIM2 t -> Array F DIM2 t -> Array F DIM2 t
-- ^2D convolution.
conv2 k = hm2repa . H.conv2 (repa2hm k) . repa2hm
conv2S :: (Product t, Numeric t, Num (Vector t)) => Array F DIM2 t -> Array D DIM2 t -> Array F DIM2 t
conv2S k = hm2repa . H.conv2 (repa2hm k) . repa2hmS
conv2SIO :: (Product t, Numeric t, Num (Vector t)) => Array F DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
conv2SIO k = fmap (hm2repa . H.conv2 (repa2hm k)) . repa2hmSIO
conv2P :: (Product t, Numeric t, Num (Vector t), Monad m) => Array F DIM2 t -> Array D DIM2 t -> m (Array F DIM2 t)
conv2P k = fmap (hm2repa . H.conv2 (repa2hm k)) . repa2hmP
conv2PIO :: (Product t, Numeric t, Num (Vector t)) => Array F DIM2 t -> Array D DIM2 t -> IO (Array F DIM2 t)
conv2PIO k = fmap (hm2repa . H.conv2 (repa2hm k)) . repa2hmPIO
-- Random arrays
randomVector :: Seed -> RandDist -> Int -> Array F DIM1 Double
-- ^Pseudorandom vector of na given size. Usee 'randomIO' to get a random seed.
randomVector s d n = hv2repa $ H.randomVector s d n
randomMatrix :: RandDist -> Int -> Int -> IO (Array F DIM2 Double)
randomMatrix d a b = fmap hm2repa
$ case d of
Uniform -> H.rand a b
Gaussian -> H.randn a b
gaussianSample :: Seed -> Int -> Array F DIM1 Double -> H.Herm Double -> Array F DIM2 Double
-- ^A matrix whose rows are pseudorandom samples from a multivariate Gaussian distribution.
gaussianSample s r mean = hm2repa . H.gaussianSample s r (repa2hv mean)
uniformSample :: Seed -> Int -> [(Double,Double)] -> Array F DIM2 Double
-- ^A matrix whose rows are pseudorandom samples from a multivariate uniform distribution.
uniformSample s r rng = hm2repa $ H.uniformSample s r rng
-- misc
meanCov :: Array F DIM2 Double -> (Array F DIM1 Double, H.Herm Double)
-- ^Compute mean vector and a covariance matrix of the rows of a matrix.
meanCov m = let (v,c) = H.meanCov $ repa2hm m in (hv2repa v, c)
rowOuters :: Array F DIM2 Double -> Array F DIM2 Double -> Array F DIM2 Double
-- ^Outer product of the rows of the matrices.
rowOuters m n = hm2repa $ H.rowOuters (repa2hm m) (repa2hm n)
sym :: Field t => Array F DIM2 t -> H.Herm t
-- ^Compute the complex Hermitian or real symmetric part of a square matrix ((x + tr x)/2).
sym = H.sym . repa2hm
symS :: Field t => Array D DIM2 t -> H.Herm t
symS = H.sym . repa2hmS
symSIO :: Field t => Array D DIM2 t -> IO (H.Herm t)
symSIO m = H.sym <$> repa2hmSIO m
symP :: (Field t, Monad m) => Array D DIM2 t -> m (H.Herm t)
symP m = H.sym <$> repa2hmP m
symPIO :: Field t => Array D DIM2 t -> IO (H.Herm t)
symPIO m = H.sym <$> repa2hmPIO m
mTm :: Field t => Array F DIM2 t -> H.Herm t
-- ^Compute the contraction tr x <> x of a general matrix.
mTm = H.mTm . repa2hm
mTmS :: Field t => Array D DIM2 t -> H.Herm t
mTmS = H.mTm . repa2hmS
mTmSIO :: Field t => Array D DIM2 t -> IO (H.Herm t)
mTmSIO m = H.mTm <$> repa2hmSIO m
mTmP :: (Field t, Monad m) => Array D DIM2 t -> m (H.Herm t)
mTmP m = H.mTm <$> repa2hmP m
mTmPIO :: Field t => Array D DIM2 t -> IO (H.Herm t)
mTmPIO m = H.mTm <$> repa2hmPIO m
trustSym :: Field t => Array F DIM2 t -> H.Herm t
-- ^At your own risk, declare that a matrix is complex Hermitian or real symmetric for usage in 'chol', 'eigSH', etc. Only a triangular part of the matrix will be used.
trustSym = H.trustSym . repa2hm
trustSymS :: Field t => Array D DIM2 t -> H.Herm t
trustSymS = H.trustSym . repa2hmS
trustSymSIO :: Field t => Array D DIM2 t -> IO (H.Herm t)
trustSymSIO m = H.trustSym <$> repa2hmSIO m
trustSymP :: (Field t, Monad m) => Array D DIM2 t -> m (H.Herm t)
trustSymP m = H.trustSym <$> repa2hmP m
trustSymPIO :: Field t => Array D DIM2 t -> IO (H.Herm t)
trustSymPIO m = H.trustSym <$> repa2hmPIO m
unSym :: Numeric t => H.Herm t -> Array F DIM2 t
-- ^Extract the general matrix from a Herm structure, forgetting its symmetric or Hermitian property.
unSym = hm2repa . H.unSym
| marcinmrotek/repa-linear-algebra | src/Numeric/LinearAlgebra/Repa.hs | bsd-3-clause | 55,329 | 0 | 12 | 11,801 | 22,732 | 11,504 | 11,228 | 935 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Build.Macros
-- Copyright : Simon Marlow 2008
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- Generate cabal_macros.h - CPP macros for package version testing
--
-- When using CPP you get
--
-- > VERSION_<package>
-- > MIN_VERSION_<package>(A,B,C)
--
-- for each /package/ in @build-depends@, which is true if the version of
-- /package/ in use is @>= A.B.C@, using the normal ordering on version
-- numbers.
--
module Distribution.Simple.Build.Macros (
generate,
generatePackageVersionMacros,
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Package
import Distribution.Version
import Distribution.PackageDescription
import Distribution.Simple.LocalBuildInfo
import Distribution.Simple.Program.Db
import Distribution.Simple.Program.Types
import Distribution.Text
-- ------------------------------------------------------------
-- * Generate cabal_macros.h
-- ------------------------------------------------------------
-- Invariant: HeaderLines always has a trailing newline
type HeaderLines = String
line :: String -> HeaderLines
line str = str ++ "\n"
ifndef :: String -> HeaderLines -> HeaderLines
ifndef macro body =
line ("#ifndef " ++ macro) ++
body ++
line ("#endif /* " ++ macro ++ " */")
define :: String -> Maybe [String] -> String -> HeaderLines
define macro params val =
line ("#define " ++ macro ++ f params ++ " " ++ val)
where
f Nothing = ""
f (Just xs) = "(" ++ intercalate "," xs ++ ")"
defineStr :: String -> String -> HeaderLines
defineStr macro str = define macro Nothing (show str)
ifndefDefine :: String -> Maybe [String] -> String -> HeaderLines
ifndefDefine macro params str =
ifndef macro (define macro params str)
ifndefDefineStr :: String -> String -> HeaderLines
ifndefDefineStr macro str =
ifndef macro (defineStr macro str)
-- | The contents of the @cabal_macros.h@ for the given configured package.
--
generate :: PackageDescription -> LocalBuildInfo -> ComponentLocalBuildInfo -> String
generate pkg_descr lbi clbi =
"/* DO NOT EDIT: This file is automatically generated by Cabal */\n\n" ++
generatePackageVersionMacros
(package pkg_descr : map snd (componentPackageDeps clbi)) ++
generateToolVersionMacros (configuredPrograms . withPrograms $ lbi) ++
generateComponentIdMacro lbi clbi
-- | Helper function that generates just the @VERSION_pkg@ and @MIN_VERSION_pkg@
-- macros for a list of package ids (usually used with the specific deps of
-- a configured package).
--
generatePackageVersionMacros :: [PackageIdentifier] -> String
generatePackageVersionMacros pkgids = concat
[ line ("/* package " ++ display pkgid ++ " */")
++ generateMacros "" pkgname version
| pkgid@(PackageIdentifier name version) <- pkgids
, let pkgname = map fixchar (display name)
]
-- | Helper function that generates just the @TOOL_VERSION_pkg@ and
-- @MIN_TOOL_VERSION_pkg@ macros for a list of configured programs.
--
generateToolVersionMacros :: [ConfiguredProgram] -> String
generateToolVersionMacros progs = concat
[ line ("/* tool " ++ progid ++ " */")
++ generateMacros "TOOL_" progname version
| prog <- progs
, isJust . programVersion $ prog
, let progid = programId prog ++ "-" ++ display version
progname = map fixchar (programId prog)
Just version = programVersion prog
]
-- | Common implementation of 'generatePackageVersionMacros' and
-- 'generateToolVersionMacros'.
--
generateMacros :: String -> String -> Version -> String
generateMacros macro_prefix name version =
concat
[ifndefDefineStr (macro_prefix ++ "VERSION_" ++ name) (display version)
,ifndefDefine ("MIN_" ++ macro_prefix ++ "VERSION_" ++ name)
(Just ["major1","major2","minor"])
$ concat [
"(\\\n"
," (major1) < ",major1," || \\\n"
," (major1) == ",major1," && (major2) < ",major2," || \\\n"
," (major1) == ",major1," && (major2) == ",major2," && (minor) <= ",minor,")"
]
,"\n"]
where
(major1:major2:minor:_) = map show (versionBranch version ++ repeat 0)
-- | Generate the @CURRENT_COMPONENT_ID@ definition for the component ID
-- of the current package.
generateComponentIdMacro :: LocalBuildInfo -> ComponentLocalBuildInfo -> String
generateComponentIdMacro _lbi clbi =
concat $
[case clbi of
LibComponentLocalBuildInfo{} ->
ifndefDefineStr "CURRENT_PACKAGE_KEY" (componentCompatPackageKey clbi)
_ -> ""
,ifndefDefineStr "CURRENT_COMPONENT_ID" (display (componentComponentId clbi))
]
fixchar :: Char -> Char
fixchar '-' = '_'
fixchar c = c
| sopvop/cabal | Cabal/Distribution/Simple/Build/Macros.hs | bsd-3-clause | 4,760 | 0 | 13 | 862 | 1,008 | 544 | 464 | 79 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Language.Haskell.Exts.Annotated (Module,Decl(..),ModuleName(ModuleName))
import Language.Haskell.Exts (defaultParseMode,ParseMode(..),ParseResult(ParseOk,ParseFailed))
import Language.Haskell.Names (
Symbol,annotateModule,Scoped(Scoped),
NameInfo(GlobalSymbol),getInterfaces,ppError)
import Language.Haskell.Names.Interfaces
import Language.Haskell.Exts.Extension
import Language.Haskell.Exts.SrcLoc
import Data.Version
import Data.Proxy
import Data.Tagged
import Data.Maybe
import qualified Data.Foldable as F
import System.FilePath
import Text.Printf
import Data.List.Split (splitOn)
import Data.Aeson (encode,ToJSON(toJSON),object,(.=))
import qualified Data.ByteString.Lazy as ByteString (writeFile)
import Language.Haskell.Exts.Pretty (prettyPrint)
import Distribution.HaskellSuite
import qualified Distribution.HaskellSuite.Compiler as Compiler
import Distribution.Package (PackageIdentifier(pkgName),PackageName(PackageName))
import Distribution.ModuleName (toFilePath,fromString)
import Distribution.Simple.Utils
import Distribution.Verbosity
import Distribution.Text (display)
import Language.Haskell.Names.ModuleSymbols (getTopDeclSymbols)
import qualified Language.Haskell.Names.GlobalSymbolTable as GlobalTable (empty)
import Control.Monad (forM_)
import Data.Foldable (foldMap)
import Language.Haskell.Exts.Annotated.CPP
import Language.Haskell.Names.SyntaxUtils
import Control.Exception (catch,SomeException)
main :: IO ()
main =
Compiler.main theTool
version :: Data.Version.Version
version = Data.Version.Version [0,1] []
data DeclarationsDB = DeclarationsDB
instance IsDBName DeclarationsDB where
getDBName = Tagged "haskell-declarations"
theTool :: Compiler.Simple (StandardDB DeclarationsDB)
theTool =
Compiler.simple
"haskell-declarations"
version
knownLanguages
knownExtensions
compile
["names","declarations"]
fixCppOpts :: CpphsOptions -> CpphsOptions
fixCppOpts opts =
opts {
defines =
("__GLASGOW_HASKELL__", "706") :
("INTEGER_SIMPLE", "1") :
defines opts,
preInclude = "cabal_macros.h" : preInclude opts,
includes =
"/usr/lib/ghc/include/" :
"/home/pschuster/.haskell-packages/base-4.7.0.0/include/" :
includes opts,
boolopts = fixBoolOpts (boolopts opts)
}
fixBoolOpts :: BoolOptions -> BoolOptions
fixBoolOpts boolopts =
boolopts {
lang = False
}
fixCppOptsForParsec :: CpphsOptions -> CpphsOptions
fixCppOptsForParsec opts =
opts {
defines = ("__GLASGOW_HASKELL__", "706") : ("INTEGER_SIMPLE", "1") : defines opts,
includes = "/usr/lib/ghc/include/": includes opts,
boolopts = fixBoolOptsForParsec (boolopts opts)
}
fixBoolOptsForParsec :: BoolOptions -> BoolOptions
fixBoolOptsForParsec boolopts =
boolopts {
lang = False,
stripC89 = False
}
fixExtensions :: [Extension] -> [Extension]
fixExtensions extensions =
(EnableExtension MultiParamTypeClasses):
(EnableExtension NondecreasingIndentation):
(EnableExtension TypeOperators):
(EnableExtension BangPatterns):
(EnableExtension TemplateHaskell):
extensions
parse :: Language -> [Extension] -> CpphsOptions -> FilePath -> IO (Module SrcSpan)
parse language extensions cppoptions filename = do
parseresult <- parseFileWithCommentsAndCPP cppoptions mode filename
case parseresult of
ParseOk (ast,_) -> return (fmap srcInfoSpan ast)
ParseFailed loc msg -> error ("PARSE FAILED: " ++ show loc ++ " " ++ show msg)
where
mode = defaultParseMode
{ parseFilename = filename
, baseLanguage = language
, extensions = fixExtensions extensions
, ignoreLanguagePragmas = False
, ignoreLinePragmas = False
, fixities = Just []
}
compile :: Compiler.CompileFn
compile builddirectory maybelanguage extensions cppoptions packagename packagedbs dependencies files = (do
let language = fromMaybe Haskell98 maybelanguage
let isParsec = pkgName packagename == PackageName "parsec"
cppoptions' = if isParsec then fixCppOptsForParsec cppoptions else fixCppOpts cppoptions
moduleasts <- mapM (parse language extensions cppoptions') files
packages <- readPackagesInfo (Proxy :: Proxy (StandardDB DeclarationsDB)) packagedbs dependencies
(interfaces, errors) <- evalModuleT (getInterfaces language extensions moduleasts) packages "names" readInterface
F.for_ errors $ \e -> printf "Warning: %s" (ppError e)
let installation = do
installedpackageid <- dependencies
let installedpackageidparts = splitOn "-" (display installedpackageid)
dependencyname = intercalate "-" (reverse (drop 1 (reverse installedpackageidparts)))
dependencyversion = head (reverse installedpackageidparts)
return (Dependency dependencyname dependencyversion)
installationfilename = "/home/pschuster/Projects/symbols/installations" </> display packagename
createDirectoryIfMissingVerbose silent True (dropFileName installationfilename)
ByteString.writeFile installationfilename (encode installation)
forM_ (zip moduleasts interfaces) (\(moduleast, symbols) -> do
annotatedmoduleast <- evalNamesModuleT (annotateModule language extensions moduleast) packages
let declarations = extractDeclarations annotatedmoduleast
ModuleName _ modulename = getModuleName moduleast
interfacefilename = builddirectory </> toFilePath (fromString modulename) <.> "names"
declarationsfilename = builddirectory </> toFilePath (fromString modulename) <.> "declarations"
createDirectoryIfMissingVerbose silent True (dropFileName interfacefilename)
createDirectoryIfMissingVerbose silent True (dropFileName declarationsfilename)
writeInterface interfacefilename symbols
ByteString.writeFile declarationsfilename (encode declarations)))
`catch`
(print :: SomeException -> IO ())
extractDeclarations :: Module (Scoped SrcSpan) -> [Declaration]
extractDeclarations annotatedast =
mapMaybe (declToDeclaration modulnameast) (getModuleDecls annotatedast) where
modulnameast = getModuleName annotatedast
declToDeclaration :: ModuleName (Scoped SrcSpan) -> Decl (Scoped SrcSpan) -> Maybe Declaration
declToDeclaration modulnameast annotatedast = do
let genre = declGenre annotatedast
case genre of
Other -> Nothing
_ -> return (Declaration
genre
(prettyPrint annotatedast)
(declaredSymbols modulnameast annotatedast)
(usedSymbols annotatedast))
declGenre :: Decl (Scoped SrcSpan) -> Genre
declGenre (TypeDecl _ _ _) = Type
declGenre (TypeFamDecl _ _ _) = Type
declGenre (DataDecl _ _ _ _ _ _) = Type
declGenre (GDataDecl _ _ _ _ _ _ _) = Type
declGenre (DataFamDecl _ _ _ _) = Type
declGenre (TypeInsDecl _ _ _) = Type
declGenre (DataInsDecl _ _ _ _ _) = Type
declGenre (GDataInsDecl _ _ _ _ _ _) = Type
declGenre (ClassDecl _ _ _ _ _) = TypeClass
declGenre (InstDecl _ _ _ _) = ClassInstance
declGenre (DerivDecl _ _ _) = ClassInstance
declGenre (TypeSig _ _ _) = TypeSignature
declGenre (FunBind _ _) = Value
declGenre (PatBind _ _ _ _) = Value
declGenre (ForImp _ _ _ _ _ _) = Value
declGenre (InfixDecl _ _ _ _) = InfixFixity
declGenre _ = Other
declaredSymbols :: ModuleName (Scoped SrcSpan) -> Decl (Scoped SrcSpan) -> [Symbol]
declaredSymbols modulenameast annotateddeclast = getTopDeclSymbols GlobalTable.empty modulenameast annotateddeclast
usedSymbols :: Decl (Scoped SrcSpan) -> [Symbol]
usedSymbols annotatedmoduleast = foldMap externalSymbol annotatedmoduleast
externalSymbol :: Scoped SrcSpan -> [Symbol]
externalSymbol (Scoped (GlobalSymbol symbol _) _) = [symbol]
externalSymbol _ = []
data Declaration = Declaration Genre DeclarationAST DeclaredSymbols UsedSymbols
deriving (Show,Eq)
data Genre = Value | TypeSignature | Type | TypeClass | ClassInstance | InfixFixity | Other
deriving (Show,Eq,Read)
type DeclarationAST = String
type DeclaredSymbols = [Symbol]
type UsedSymbols = [Symbol]
instance ToJSON Declaration where
toJSON (Declaration genre declarationast declaredsymbols usedsymbols) = object [
"declarationgenre" .= show genre,
"declarationast" .= declarationast,
"declaredsymbols" .= declaredsymbols,
"mentionedsymbols" .= usedsymbols]
data Dependency = Dependency String String
deriving (Show,Eq,Ord)
instance ToJSON Dependency where
toJSON (Dependency dependencyname dependencyversion) = object [
"dependencyname" .= dependencyname,
"dependencyversion" .= dependencyversion]
| phischu/haskell-declarations | src/haskell-declarations.hs | bsd-3-clause | 8,796 | 0 | 23 | 1,616 | 2,361 | 1,259 | 1,102 | 189 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module SourceSpan where
import Prelude hiding (length)
import GHC
import Data.Aeson.TH
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.Text (Text)
import qualified Data.Text as T
type Offset = Int
type Length = Int
data SourceSpan = SourceSpan
{ offset :: Offset
, length :: Length
} deriving (Show,Eq,Ord)
$(deriveJSON defaultOptions ''SourceSpan)
-- | This type is used to translate line and column based
-- to offset and length based position information.
-- The document text is split up by lines to make it faster
-- to find the correct line.
data Document = Document (Vector Offset) deriving Show
fromText :: Text -> Document
fromText txt =
let ls = T.lines txt
offs = scanl (\off t -> off + T.length t + 1) 0 ls
in Document $ V.fromList offs
lineColumnToOffsetLength :: Document -> SrcSpan -> Maybe SourceSpan
lineColumnToOffsetLength (Document vec) (RealSrcSpan sp) =
let startOff = (vec V.! (srcSpanStartLine sp - 1)) + srcSpanStartCol sp - 1
endOff = (vec V.! (srcSpanEndLine sp - 1)) + srcSpanEndCol sp - 1
in Just SourceSpan
{ offset = startOff
, length = endOff - startOff
}
lineColumnToOffsetLength _ _ = Nothing
| monto-editor/services-haskell | src/SourceSpan.hs | bsd-3-clause | 1,285 | 0 | 15 | 295 | 365 | 201 | 164 | 30 | 1 |
-- | This module provides a unified \graph interface\.
module Tct.Common.Graph
(
-- * Unified Graph Interface
-- ** Datatypes
Graph
, NodeId
, empty
, mkGraph
-- | A node in the graph. Most operations work on @NodeId@s.
-- Use @lookupNodeLabel@ to get the label of the node
-- ** Operations
, context
-- | Returns the context of a given node.
, nodes
-- | Returns the set of nodes.
, lnodes
-- | Returns the set of nodes together with their labels.
, roots
-- | Returns the list of nodes without predecessor.
, leafs
-- | Returns the list of nodes without successor.
, lookupNodeLabel
-- | Returns the label of the given node, if present.
, lookupNodeLabel'
-- | Returns the label of the given node, if present.
-- Otherwise an exception is raised
, lookupNode
-- | Returns the node with given label.
, lookupNode'
-- | Returns the node with given label.
-- Otherwise an exception is raised
, withNodeLabels
-- | List version of @lookupNodeLabel@.
, withNodeLabels'
-- | List version of @lookupNodeLabel'@.
, inverse
-- | Returns the same graph with edges inversed.
, topsort
-- | returns a /topologically sorted/ set of nodes.
, sccs
-- | returns the list of /strongly connected components/, including trivial ones.
, undirect
-- | Make the graph undirected, i.e. for every edge from A to B, there exists an edge from B to A.
, successors
-- | Returns the list of successors in a given node.
, reachablesDfs
-- | @reachable gr ns@ closes the list of nodes @ns@ under
-- the successor relation with respect to @ns@ in a depth-first manner.
, reachablesBfs
-- | @reachable gr ns@ closes the list of nodes @ns@ under
-- the successor relation with respect to @ns@ in a breath-first manner.
, lsuccessors
-- | Returns the list of successors in a given node, including their labels.
, predecessors
-- | Returns the list of predecessors in a given node.
, lpredecessors
-- | Returns the list of predecessors in a given node, including their labels.
, isEdgeTo
-- | @isEdgeTo dg n1 n2@ checks wheter @n2@ is a successor of @n1@ in
-- the dependency graph @dg@
, isLEdgeTo
-- | @isLEdgeTo dg n1 l n2@ checks wheter @n2@ is a successor of @n1@ in
-- the dependency graph @dg@, where the edge from @n1@ to @n2@ is
-- labeled by @l@.
, subGraph
-- | Computes the subgraph based on the given nodes.
, removeNodes
-- | Removes nodes.
, removeEdges
-- | Removes edges.
, updateLabels
-- | Update labels.
-- -- ** Utilities
-- , pprintCWDGNode
-- -- | @pprintCWDGNode cdg sig vars node@ is a default printer for the
-- -- CDG-node @node@. It shows the nodes of the dependency graph denoted by @node@ as a set.
-- , pprintCWDG
-- -- | Default pretty printer for CDGs. Prints the given CDG in a tree-like shape.
-- , pprintNodeSet
-- -- | Default pretty printer for set of nodes.
-- , toXml
-- -- | Xml representation of given 'DG'.
-- , toGraphViz
-- -- | translates 'DG' into a GraphViz graph.
-- , saveGraphViz
-- -- | output 'DG' as Svg.
-- , graphVizSVG
-- -- | return 'DG' as Svg string.
-- , graphvizShowDG
-- -- | show a 'DG' in a GraphViz canvas.
-- -- * Misc
-- , pprintLabeledRules
) where
import Data.Graph.Inductive.Basic (undir)
import qualified Data.Graph.Inductive.Graph as Gr
import Data.Graph.Inductive.Query.BFS (bfsn)
import Data.Graph.Inductive.Query.DFS (dfs)
import qualified Data.Graph.Inductive.Query.DFS as DFS
import qualified Data.Graph.Inductive.Tree as Gr
-- import qualified Data.GraphViz.Types.Monadic as GV
-- import qualified Data.GraphViz.Attributes as GVattribs
-- import qualified Data.GraphViz.Attributes.Complete as GVattribsc
-- import Data.GraphViz.Types.Generalised
-- import qualified Data.GraphViz.Commands as GVcommands
-- import System.IO
-- import System.IO.Unsafe (unsafePerformIO)
-- import qualified Data.ByteString as BS
-- import qualified Data.ByteString.Char8 as BSC
-- import Control.Monad (liftM)
-- import qualified Control.Monad.State.Lazy as State
-- import Control.Monad.Trans (lift)
-- import Data.List (delete, sortBy)
import qualified Data.List as List
-- import qualified Data.Map as Map
import Data.Maybe (fromMaybe)
-- import Data.Typeable
type Graph nl el = Gr.Gr nl el
type NodeId = Gr.Node
empty :: Graph nl el
empty = Gr.empty
mkGraph :: [(NodeId,nl)] -> [(NodeId,NodeId,el)] -> Graph nl el
mkGraph = Gr.mkGraph
--- * graph inspection -----------------------------------------------------------------------------------------------
context :: Graph nl el -> NodeId -> ([(el,NodeId)],NodeId,nl,[(el,NodeId)])
context = Gr.context
nodes :: Graph nl el -> [NodeId]
nodes = Gr.nodes
lnodes :: Graph nl el -> [(NodeId,nl)]
lnodes = Gr.labNodes
roots :: Graph nl el -> [NodeId]
roots gr = [n | n <- Gr.nodes gr, Gr.indeg gr n == 0]
leafs :: Graph nl el -> [NodeId]
leafs gr = [n | n <- Gr.nodes gr, Gr.outdeg gr n == 0]
lookupNodeLabel :: Graph nl el -> NodeId -> Maybe nl
lookupNodeLabel = Gr.lab
lookupNodeLabel' :: Graph nl el -> NodeId -> nl
lookupNodeLabel' gr n = err `fromMaybe` lookupNodeLabel gr n
where err = error "Graph.lookupNodeLabel': node id not found"
withNodeLabels :: Graph nl el -> [NodeId] -> [(NodeId, Maybe nl)]
withNodeLabels gr ns = [(n,lookupNodeLabel gr n) | n <- ns]
withNodeLabels' :: Graph nl el -> [NodeId] -> [(NodeId, nl)]
withNodeLabels' gr ns = [(n,lookupNodeLabel' gr n) | n <- ns]
lookupNode :: Eq nl => Graph nl el -> nl -> Maybe NodeId
lookupNode gr n = lookup n [(n',i) | (i,n') <- Gr.labNodes gr]
lookupNode' :: Eq nl => Graph nl el -> nl -> NodeId
lookupNode' gr n = err `fromMaybe` lookupNode gr n
where err = error "Graph.lookupNodeLabel': label not found"
inverse :: Graph nl el -> Graph nl el
inverse gr = Gr.mkGraph ns es
where ns = Gr.labNodes gr
es = [ (n2, n1, i) | (n1,n2,i) <- Gr.labEdges gr ]
topsort :: Graph nl el -> [NodeId]
topsort = DFS.topsort
sccs :: Graph nl el -> [[NodeId]]
sccs = DFS.scc
undirect :: Eq el => Graph nl el -> Graph nl el
undirect = undir
successors :: Graph nl el -> NodeId -> [NodeId]
successors = Gr.suc
reachablesBfs :: Graph nl el -> [NodeId] -> [NodeId]
reachablesBfs = flip bfsn
reachablesDfs :: Graph nl el -> [NodeId] -> [NodeId]
reachablesDfs = flip dfs
predecessors :: Graph nl el -> NodeId -> [NodeId]
predecessors = Gr.pre
lsuccessors :: Graph nl el -> NodeId -> [(NodeId, nl, el)]
lsuccessors gr nde = [(n, lookupNodeLabel' gr n, e) | (n,e) <- Gr.lsuc gr nde]
lpredecessors :: Graph nl el -> NodeId -> [(NodeId, nl, el)]
lpredecessors gr nde = [(n, lookupNodeLabel' gr n, e) | (n,e) <- Gr.lpre gr nde]
isEdgeTo :: Graph nl el -> NodeId -> NodeId -> Bool
isEdgeTo g n1 n2 = n2 `elem` successors g n1
isLEdgeTo :: Eq el => Graph nl el -> NodeId -> el -> NodeId -> Bool
isLEdgeTo g n1 e n2 = n2 `elem` [n | (n, _, e2) <- lsuccessors g n1, e == e2]
subGraph :: Graph nl el -> [NodeId] -> Graph nl el
subGraph g ns = Gr.delNodes (nodes g List.\\ ns) g
removeNodes :: Graph nl el -> [NodeId] -> Graph nl el
removeNodes = flip Gr.delNodes
removeEdges :: Graph nl el -> [(NodeId,NodeId)] -> Graph nl el
removeEdges = flip Gr.delEdges
updateLabels :: (nl -> ml) -> Graph nl el -> Graph ml el
updateLabels = Gr.nmap
{-
----------------------------------------------------------------------
--- pretty printing
pprintNodeSet :: [NodeId] -> Doc
pprintNodeSet ns = braces $ hcat $ punctuate (text ",") [ text $ show n | n <- ns]
pprintCWDGNode :: CDG -> F.Signature -> V.Variables -> NodeId -> Doc
-- pprintCWDGNode cwdg _ _ n = text (show n) <> (text ":") <> pprintNodeSet (congruence cwdg n)
pprintCWDGNode cwdg _ _ n = pprintNodeSet (congruence cwdg n)
pprintCWDG :: CDG -> F.Signature -> V.Variables -> ([NodeId] -> NodeId -> Doc) -> Doc
pprintCWDG cwdg sig vars ppLabel | isEmpty = text "empty"
| otherwise =
printTree 45 ppNode ppLabel pTree
$+$ text ""
$+$ text "Here dependency-pairs are as follows:"
$+$ text ""
$+$ pprintLabeledRules "Strict DPs" sig vars (rs StrictDP)
$+$ pprintLabeledRules "Weak DPs" sig vars (rs WeakDP)
where isEmpty = null $ allRulesFromNodes cwdg (nodes cwdg)
ppNode _ n = printNodeId n
pTree = PPTree { pptRoots = sortBy compareLabel $ roots cwdg
, pptSuc = sortBy compareLabel . snub . successors cwdg}
compareLabel n1 n2 = congruence cwdg n1 `compare` congruence cwdg n2
printNodeId = pprintCWDGNode cwdg sig vars
rs strictness = sortBy compFst $ concatMap (\ (_, cn) -> [ (n, rule) | (n, (s, rule)) <- theSCC cn, s == strictness]) (Graph.labNodes cwdg)
where (a1,_) `compFst` (a2,_) = a1 `compare` a2
instance PrettyPrintable (CDG, F.Signature, V.Variables) where
pprint (cwdg, sig, vars) = pprintCWDG cwdg sig vars (\ _ _ -> PP.empty)
pprintLabeledRules :: PrettyPrintable l => String -> F.Signature -> V.Variables -> [(l,R.Rule)] -> Doc
pprintLabeledRules _ _ _ [] = PP.empty
pprintLabeledRules name sig vars rs = text name <> text ":"
$+$ indent (pprintTrs pprule rs)
where pprule (l,r) = pprint l <> text ":" <+> pprint (r, sig, vars)
-- graphviz output of dgs
toGraphViz :: [(DG,F.Signature,V.Variables)] -> Bool -> DotGraph String
toGraphViz dgs showLabels = GV.digraph' $ mapM digraph $ zip [(1::Int)..] dgs
where digraph (i,(dg,sig,vars)) = do
GV.graphAttrs [GVattribsc.Size size]
GV.cluster (Str $ pack $ "dg_" ++ show i) $
if showLabels then graphM >> labelM else graphM
where nds = nodes dg
size = GVattribsc.GSize {
GVattribsc.width = 12.0
, GVattribsc.height = Just 6.0
, GVattribsc.desiredSize = True }
graphM = do
mapM_ sccToGV $ zip [(1::Int)..] (DFS.scc dg)
mapM_ edgesToGV nds
labelM = GV.graphAttrs [GVattribs.toLabel pplabel]
lrules = [(n,r) | (n,(_,r)) <- withNodeLabels' dg nds]
pprule r = st (R.lhs r) ++ " -> " ++ st (R.rhs r) ++ "\\l"
where st t = [c | c <- show $ pprint (t,sig,vars), c /= '\n']
pplabel = "Below rules are as follows:\\l" ++ concatMap (\ (n,r) -> " " ++ show n ++ ": " ++ pprule r) lrules
sccToGV (j,scc) = GV.cluster (Str $ pack $ show i ++ "_" ++ show j) $ mapM nodesToGV $ withNodeLabels' dg scc
nodesToGV (n,(strictness,r)) = GV.node (nde n) attribs
where
attribs = [ GVattribs.toLabel (show n)
, GVattribsc.Tooltip (pack $ pprule r) ]
++ shape strictness
shape StrictDP = [GVattribs.shape GVattribs.Circle]
shape WeakDP = [GVattribs.shape GVattribs.Circle, GVattribs.style GVattribs.dotted]
edgesToGV n = mapM (\ (m,_,k) -> GV.edge (nde n) (nde m) [GVattribs.toLabel (show k)]) (lsuccessors dg n)
nde n = show i ++ "_" ++ show n
saveGraphViz :: [(DG,F.Signature,V.Variables)] -> Bool -> FilePath -> IO FilePath
saveGraphViz dgs showLabels = GVcommands.runGraphvizCommand GVcommands.Dot (toGraphViz dgs showLabels) GVcommands.Svg
graphVizSVG :: [(DG,F.Signature,V.Variables)] -> Bool -> String
graphVizSVG dgs showLabels = unsafePerformIO $
GVcommands.graphvizWithHandle GVcommands.Dot (toGraphViz dgs showLabels) GVcommands.Svg rd
where rd h = do
bs <- BS.hGetContents h
hClose h
return $! BSC.unpack bs
graphvizShowDG :: [(DG,F.Signature,V.Variables)] -> IO ()
graphvizShowDG dgs = GVcommands.runGraphvizCanvas GVcommands.Dot (toGraphViz dgs True) GVcommands.Gtk
toXml :: (DG, F.Signature, V.Variables) -> Xml.XmlContent
toXml (dg,sig,vs) =
Xml.elt "dependencygraph" []
[
-- Xml.elt "svg" [] [ Xml.text $ graphVizSVG [(dg,sig,vs)] False ]
Xml.elt "nodes" [] [ XmlE.rule r (Just n) sig vs | (n,(_,r)) <- lnodes dg ]
, Xml.elt "edges" [] [ Xml.elt "edge" [] $
Xml.elt "source" [] [Xml.int n] : [ Xml.elt "target" [] [Xml.int m] | m <- successors dg n ]
| n <- nodes dg] ]
-- , Xml.elt "edges" [] [ Xml.elt "edge" [] $
-- Xml.elt "source" [] [Xml.rule r (Just n) sig vs]
-- : [ Xml.elt "targets" [] [Xml.rule s (Just m) sig vs | (m,(_,s),_) <- lsuccessors dg n ] ]
-- | (n,(_,r)) <- lnodes dg] ]
-- -}
| ComputationWithBoundedResources/tct-common | src/Tct/Common/Graph.hs | bsd-3-clause | 13,266 | 0 | 11 | 3,699 | 1,648 | 941 | 707 | 105 | 1 |
module PrintingTest where
import Data.List
import Debug.Trace
import Driving
import Eval
import Program.List
import Program.Num
import Prelude hiding (succ)
import Residualization
import Program.Sort
import Stream
import Syntax
import Test hiding (main)
import Tree
import Printer.Tree
import Program.Stlc
import Program.Programs
import Text.Printf
import Util.ConjRetriever
import Util.Miscellaneous
import Printer.Dot
upTo d x =
-- trace (printf "\nDepth: %s" $ show d) $
if d == 0 then Fail
else upToDepth x
where
upToDepth (Gen id gen t goal sigma) = Gen id gen (upTo (d-1) t) goal sigma
upToDepth (Call id t goal sigma) = Call id (upTo (d-1) t) goal sigma
upToDepth (Split id ts goal sigma) = Split id (map (\t -> upTo (d-1) t) ts) goal sigma
upToDepth (Or t1 t2 goal sigma) = Or (upTo (d-1) t1) (upTo (d-1) t2) goal sigma
upToDepth (Fail) = Fail
upToDepth (Success s) = Success s
upToDepth (Rename id g s r ts) = Rename id g s r ts
accumCalls :: Tree -> [[G S]]
accumCalls (Or t1 t2 _ _) = accumCalls t1 ++ accumCalls t2
accumCalls (Split _ ts _ _) = concatMap accumCalls ts
accumCalls (Gen _ _ t _ _) = accumCalls t
accumCalls (Call _ t goal _) = map (\xs -> goal : xs) $ accumCalls t
accumCalls (Prune [g]) = [[g]]
--accumCalls (Prune gs) = [[conj gs]]
accumCalls _ = []
showConjStack :: [[G S]] -> String
showConjStack gss = unlines $ map (\gs -> '\n' : '\n' : (unlines $ map (\g -> '\n' : (unwords $ map show $ unconj g)) gs) ) gss where
unconj (g1 :/\: g2) = unconj g1 ++ unconj g2
unconj g@(Invoke _ _) = [g]
unconj _ = error "Here could only be conjunctions"
runTest name goal =
do
let tree = snd3 $ drive $ goal
printTree (printf "%s.dot" name) tree
runTestSimplified name goal =
do
putStr $ printf "Running %s\n" name
let tree = simpl $ snd3 $ drive $ goal
writeFile (printf "%s.log" name) $ showConjStack $ retrieve tree
printTree (printf "%s.dot" name) tree
putStr $ printf "Finished %s\n" name
test_palindromo = runTestSimplified "palindromo" $ Program palindromo $ fresh ["x"] (call "palindromo" [V "x"])
test_doubleAppendo = runTestSimplified "doubleAppendo" $ Program doubleAppendo $ fresh ["x", "y", "z", "r"] (call "doubleAppendo" [V "x", V "y", V "z", V "r"])
test_eveno = runTestSimplified "eveno" $ Program eveno $ fresh ["x"] (call "eveno" [V "x"])
test_doubleo = runTestSimplified "doubleo" $ Program doubleo $ fresh ["x", "xx"] (call "doubleo" [V "x", V "xx"])
test_empty_appendo = runTestSimplified "emptyAppendo" $ Program emptyAppendo $ fresh ["x", "y"] (call "emptyAppendo" [V "x", V "y"])
test_singletonReverso = runTestSimplified "singletonReverso" $ Program singletonReverso $ fresh ["x", "y"] (call "singletonReverso" [V "x", V "y"])
tc = drive (Program appendo
(fresh ["q", "r", "s", "t", "p"]
(call "appendo" [V "q", V "r", V "s"] &&&
call "appendo" [V "s", V "t", V "p"])
)
)
tc' = drive (Program reverso $ fresh ["q", "r"] (call "reverso" [V "q", V "r"]))
tc'' = drive (Program revAcco $ fresh ["q", "s"] (call "revacco" [V "q", nil, V "s"]))
tree = snd3 tc
tree' = snd3 tc'
tree'' = snd3 tc''
main =
do
-- test_doubleAppendo
{-printTree "appendo2.dot" tree
printTree "reverso.dot" tree'
printTree "revacco.dot" tree''
-}
{-let (_, t, _) = drive $ sorto $ fresh ["q", "r"] $ call "sorto" [V "q", V "r"]
printTree "sorto.dot" (simpl t)
-}
--runTest "evalo" $ evalo $ fresh ["q", "p"] (call "evalo" [V "q", V "p"])
--test_palindromo
--test_doubleo
--test_palindromo
test_doubleAppendo
test_eveno
test_doubleo
test_empty_appendo
test_singletonReverso
{-let (_, t, _) = drive $ smallesto $ fresh ["q", "r", "s"] $ call "smallesto" [V "q", V "r", V "s"]
putStrLn "\n\n\n"
putStrLn (intercalate "\n\n" $ map (\x -> intercalate "\n" $ map show x) (accumCalls t))
printTree "smallesto.dot" (simpl t) -- (upTo 10 t)
-}
{-
let (_, t, _) = drive $ sorto $ fresh ["q"] $ call "sorto" [(peanify 0 % (peanify 1 % (peanify 1 % (peanify 0 % nil)))), V "q"]
printTree "sort.dot" t
printTree "ehm.dot" tree
-}
{-let (_, t', _) = drive (reverso $ fresh ["q", "r"] (call "reverso" [V "q", V "r"]))
let t'' = simpl t'
printTree "reverso.dot" t'
printTree "reversoSimple.dot" t''-}
{-
let ra@(_, t', _) = drive (revAcco $ fresh ["q", "s"] (call "revacco" [V "q", nil, V "s"]))
let t'' = simpl t'
printTree "revaccoSimpl.dot" t''
printTree "revacco.dot" t'
-}
| kajigor/uKanren_transformations | test/PrintingTest.hs | bsd-3-clause | 4,837 | 0 | 19 | 1,286 | 1,410 | 723 | 687 | 76 | 8 |
{-# LANGUAGE FlexibleInstances #-}
module Sodium.Haskell.Convert (convert) where
import Data.List (genericReplicate)
import Control.Monad
import Control.Applicative
import qualified Data.Map as M
-- S for Src, D for Dest
import qualified Sodium.Chloride.Program.Vector as S
import qualified Sodium.Haskell.Program as D
convert :: S.Program -> D.Program
convert = maybe (error "Sodium.Haskell.Convert") id . conv
class Conv s d | s -> d where
conv :: s -> Maybe d
instance Conv S.Program D.Program where
conv (S.Program funcs) = do
funcDefs <- mapM conv funcs
return $ D.Program (map D.Def funcDefs)
[ "Control.Monad"
, "Control.Applicative"
]
[ "LambdaCase"
, "TupleSections"
]
transformName :: S.Name -> D.Name
transformName = \case
S.NameMain -> "main"
S.Name cs
-> (if reserved cs
then ("_'"++)
else id) cs
S.NameGen u -> "_'" ++ show u
S.NameUnique name -> transformName name ++ "'_"
where reserved = flip elem
[ "let"
, "show"
, "read"
, "readLn"
, "getLine"
, "return"
, "foldl"
, "map"
, "filter"
, "undefined"
, "main"
, "import"
, "_"
]
data Name = Name S.Name S.Index
deriving (Eq)
instance Conv Name D.Name where
conv (Name name i) = case i of
S.Index n -> return
$ transformName name ++ genericReplicate n '\''
S.Immutable -> return $ "const'" ++ transformName name
S.Uninitialized -> return "undefined"
instance Conv S.ClType D.HsType where
conv = return . \case
S.ClInteger -> D.HsType "Int"
S.ClDouble -> D.HsType "Double"
S.ClBoolean -> D.HsType "Bool"
S.ClString -> D.HsType "String"
S.ClVoid -> D.HsUnit
newtype Pure a = Pure a
instance Conv S.Body D.Expression where
conv (S.Body _ statements resultExprs) = do
hsStatements <- mapM conv statements
hsRetValues <- mapM conv resultExprs
let hsStatement
= D.DoExecute
$ D.Beta (D.Access "return")
$ D.Tuple hsRetValues
return $ D.DoExpression (hsStatements ++ [hsStatement])
instance Conv S.ForCycle D.Expression where
conv (S.ForCycle argIndices argExprs name exprRange clBody) = do
hsRange <- conv exprRange
hsArgExpr <- D.Tuple <$> mapM conv argExprs
hsFoldLambda <- conv (FoldLambda argIndices name) <*> conv clBody
return $ beta
[ D.Access "foldM"
, hsFoldLambda
, hsArgExpr
, hsRange
]
instance Conv S.MultiIfBranch D.Expression where
conv (S.MultiIfBranch leafs bodyElse) = do
let convLeaf (expr, body)
= D.IfExpression
<$> conv expr
<*> conv body
leafGens <- mapM convLeaf leafs
hsBodyElse <- conv bodyElse
return $ foldr ($) hsBodyElse leafGens
--TODO: Bind/Let inference
instance Conv (S.IndicesList, S.Statement) D.DoStatement where
conv (retIndices, S.Execute (S.OpReadLn t) [])
= D.DoBind
<$> (D.PatTuple <$> conv (IndicesList retIndices))
<*> if t == S.ClString
then return $ D.Access "getLine"
else do
hsType <- conv t
return $ D.Access "readLn" `D.Typed` D.HsIO hsType
conv (retIndices, S.Execute S.OpPrintLn args)
| null retIndices
= case args of
[S.Call S.OpShow [arg]]
-> D.DoExecute . D.Beta (D.Access "print") <$> conv arg
args -> (<$> mapM conv args) $ \case
[] -> D.DoExecute
$ D.Beta (D.Access "putStrLn") (D.Primary (D.Quote ""))
hsExprs
-> D.DoExecute
$ D.Beta (D.Access "putStrLn")
$ foldl1 (\x y -> beta [D.Access "++", x, y])
$ hsExprs
conv (retIndices, S.Assign expr)
= D.DoLet
<$> (D.PatTuple <$> conv (IndicesList retIndices))
<*> conv expr
conv (retIndices, S.ForStatement forCycle)
= D.DoBind
<$> (D.PatTuple <$> conv (IndicesList retIndices))
<*> conv forCycle
conv (retIndices, S.MultiIfStatement multiIfBranch)
= D.DoBind
<$> (D.PatTuple <$> conv (IndicesList retIndices))
<*> conv multiIfBranch
conv (retIndices, S.BodyStatement body)
= D.DoBind
<$> (D.PatTuple <$> conv (IndicesList retIndices))
<*> conv body
instance Conv S.Func D.ValueDef where
conv (S.Func (S.FuncSig S.NameMain params S.ClVoid) clBody) = do
guard $ M.null params
hsBody <- conv clBody
return $ D.ValueDef (D.PatFunc "main" []) hsBody
conv (S.Func (S.FuncSig name params _) clBody)
= D.ValueDef (D.PatFunc (transformName name) paramNames)
<$> conv (Pure clBody)
where paramNames = map transformName (M.keys params)
data FoldLambda = FoldLambda S.IndicesList S.Name
instance Conv FoldLambda (D.Expression -> D.Expression) where
conv (FoldLambda indices name) = do
hsNames <- conv (IndicesList indices)
hsName <- conv (Name name S.Immutable)
return $ D.Lambda [D.PatTuple hsNames, D.PatTuple [hsName]]
instance Conv (Pure S.Body) D.Expression where
conv (Pure (S.Body _ statements resultExprs)) = msum
[ do
name1 <- case resultExprs of
[S.Access name i] -> return $ Name name i
_ -> mzero
let appToLast f xs = case reverse xs of
(x:xs') -> (, reverse xs') <$> f x
_ -> mzero
let extractIndex = \case
[(name, i)] -> return (Name name i)
_ -> mzero
let convStatement (indices, statement)
= (,)
<$> extractIndex indices
<*> case statement of
S.Assign expr -> conv expr
S.ForStatement forCycle -> conv (Pure forCycle)
S.MultiIfStatement multiIfBranch -> conv (Pure multiIfBranch)
S.BodyStatement body -> conv (Pure body)
_ -> mzero
((name2, hsExpr), statements) <- appToLast convStatement statements
guard $ name1 == name2
hsValueDefs <- mapM conv (map Pure statements)
return $ pureLet hsValueDefs hsExpr
, do
hsValueDefs <- mapM conv (map Pure statements)
hsRetValues <- mapM conv resultExprs
return $ pureLet hsValueDefs (D.Tuple hsRetValues)
]
instance Conv (Pure S.MultiIfBranch) D.Expression where
conv (Pure (S.MultiIfBranch leafs bodyElse)) = do
let convLeaf (expr, body)
= D.IfExpression
<$> conv expr
<*> conv (Pure body)
leafGens <- mapM convLeaf leafs
hsBodyElse <- conv (Pure bodyElse)
return $ foldr ($) hsBodyElse leafGens
instance Conv (Pure S.ForCycle) D.Expression where
conv (Pure (S.ForCycle argIndices argExprs name exprRange clBody)) = do
hsRange <- conv exprRange
hsArgExpr <- D.Tuple <$> mapM conv argExprs
hsFoldLambda
<- conv (FoldLambda argIndices name)
<*> conv (Pure clBody)
return $ beta [D.Access "foldl", hsFoldLambda, hsArgExpr, hsRange]
instance Conv (Pure (S.IndicesList, S.Statement)) D.ValueDef where
conv (Pure (retIndices, statement))
= D.ValueDef
<$> (D.PatTuple <$> conv (IndicesList retIndices))
<*> case statement of
S.Assign expr -> conv expr
S.ForStatement forCycle -> conv (Pure forCycle)
S.MultiIfStatement multiIfBranch -> conv (Pure multiIfBranch)
S.BodyStatement body -> conv (Pure body)
_ -> mzero
beta = foldl1 D.Beta
pureLet [] = id
pureLet defs = D.PureLet defs
newtype IndicesList = IndicesList S.IndicesList
instance Conv IndicesList [D.Name] where
conv (IndicesList xs) = mapM (conv . uncurry Name) xs
instance Conv S.Expression D.Expression where
conv (S.Primary prim) = return $ case prim of
S.Quote cs -> D.Primary (D.Quote cs)
S.INumber intSection -> D.Primary (D.INumber intSection)
S.FNumber intSection fracSection
-> D.Primary (D.FNumber intSection fracSection)
S.ENumber intSection fracSection eSign eSection
-> D.Primary (D.ENumber intSection fracSection eSign eSection)
S.BTrue -> D.Access "True"
S.BFalse -> D.Access "False"
S.Void -> D.Tuple []
conv (S.Access name i) = D.Access <$> conv (Name name i)
conv (S.Call op exprs) = do
hsExprs <- mapM conv exprs
return $ beta (D.Access (convOp op) : hsExprs)
conv (S.Fold op exprs range) = do
hsArgExpr <- D.Tuple <$> mapM conv exprs
hsRange <- conv range
return $ beta [D.Access "foldl", D.Access (convOp op), hsArgExpr, hsRange]
convOp = \case
S.OpNegate -> "negate"
S.OpShow -> "show"
S.OpProduct -> "product"
S.OpSum -> "sum"
S.OpAnd' -> "and"
S.OpOr' -> "or"
S.OpAdd -> "+"
S.OpSubtract -> "-"
S.OpMultiply -> "*"
S.OpDivide -> "/"
S.OpMore -> ">"
S.OpLess -> "<"
S.OpEquals -> "=="
S.OpAnd -> "&&"
S.OpOr -> "||"
S.OpElem -> "elem"
S.OpRange -> "enumFromTo"
S.OpId -> "id"
S.OpName name -> transformName name
| kirbyfan64/sodium | src/Sodium/Haskell/Convert.hs | bsd-3-clause | 8,130 | 83 | 22 | 1,653 | 3,262 | 1,613 | 1,649 | -1 | -1 |
import Book
main :: IO ()
main = interact $ maybe "" ((++ "\n") . show) . booklist
| YoshikuniJujo/funpaala | samples/25_nml/decodeBooks.hs | bsd-3-clause | 84 | 0 | 10 | 19 | 43 | 23 | 20 | 3 | 1 |
{-# LANGUAGE CPP, RecursiveDo, OverloadedStrings, ScopedTypeVariables #-}
module JavaScript.Dropzone.Reflex (
reflexDropzoneOptions,
-- * Functions
newDropzoneOn,
eventWhenReady,
-- * Events with different callback arities
dropzoneEventFor0,
dropzoneEventFor1,
dropzoneEventFor2,
-- * Events with different callback Types
dropzoneEventForObj,
dropzoneEventForFile,
dropzoneEventForDOMEvent,
dropzoneEventForFileText,
-- * Specific Events
dropzoneAddedFile,
dropzoneCancelled,
dropzoneComplete,
dropzoneMaxFilesExceeded,
dropzoneProcessing,
dropzoneRemovedFile,
dropzoneDragEnd,
dropzoneDragEnter,
dropzoneDragLeave,
dropzoneDragOver,
dropzoneDragStart,
dropzoneDrop,
dropzonePaste,
dropzoneEventForFiles,
dropzoneError,
dropzoneSuccess,
dropzoneThumbnail,
dropzoneAddedFiles,
dropzoneCanceledMultiple,
dropzoneCompleteMultiple,
dropzoneProcessingMultiple,
dropzoneQueueComplete,
dropzoneReset
)
where
import JavaScript.Dropzone.Core
import Control.Monad.IO.Class
import Data.Aeson ((.=))
import GHCJS.DOM.File
import GHCJS.DOM.HTMLElement
import GHCJS.DOM.Types hiding (Event) -- Clashes with Reflex
import Reflex
import Reflex.Dom
import qualified Data.Aeson as Aeson
import qualified Data.Text as T
import qualified GHCJS.DOM.Types as GJST
#ifdef ghcjs_HOST_OS
import Control.Arrow ((***))
import Control.Monad.Trans.Reader
import GHCJS.Foreign
import GHCJS.Types
#endif
-- "{ autoProcessQueue: false, addRemoveLinks: true, url: \"/file/post\"}"
reflexDropzoneOptions :: Aeson.Value
reflexDropzoneOptions = Aeson.object [
"autoProcessQueue" .= False,
"addRemoveLinks" .= True,
"url" .= Aeson.String "/file/post"
]
-- | Dropzone seems to be unhappy if it's created too early
-- eg Errors like this after adding files by 'click':
-- >
-- > "null is not an object (evaluating '_this.hiddenFileInput.parentNode.removeChild')"
-- >
-- ... so instead of exposing 'private_newDropzone' directly, we expose
-- a Reflex 'Event' which will supply the 'Dropzone' once it has been
-- safely constructed.
-- Sample usage:
--
-- > count <=< eventWhenReady dropzoneAddedFile <=< newDropzoneOn dze $ opts
--
newDropzoneOn :: MonadWidget t m => HTMLElement -> Aeson.Value -> m (Event t Dropzone)
newDropzoneOn elt opts = do
pb <- getPostBuild
edz <- performEvent $ (liftIO $ private_newDropzone elt opts) <$ pb
return edz
-- | Delayed-initialization wrapper
-- Dropzone doesn't like being initialized too early.
-- This helper function can 'lift' event constructors to build their
-- events from an 'Event t Dropzone' rather than from a plain 'Dropzone'.
-- This allows them to be driven off the Reflex 'post build' event - eg by 'newDropzoneOn'
eventWhenReady :: forall t m dz e . MonadWidget t m => (dz -> m (Event t e)) -> Event t dz -> m (Event t e)
eventWhenReady ctr edropzone = do
let eefile = ctr <$> edropzone :: Event t (m (Event t e))
ddzadd <- widgetHold (return never) eefile :: m (Dynamic t (Event t e))
return $ switchPromptlyDyn ddzadd :: m (Event t e)
------------------------------------------------------------------------
-- Reflex Events - Different Arities
-- Register for File events on the Dropzone
#ifdef ghcjs_HOST_OS
-- | Callbacks with arity 0
dropzoneEventFor0 :: forall t m . (MonadWidget t m) => String -> Dropzone -> m (Event t ())
dropzoneEventFor0 ename elt = wrapDomEvent elt (connect ename) (return ())
where
connect :: String -> Dropzone -> ReaderT (Dropzone, ()) IO () -> IO (IO ())
connect eventName target callback =
dropzoneRegisterListener0 target eventName $ \dz -> runReaderT callback (dz, ())
#else
-- | Callbacks with arity 0
dropzoneEventFor0 :: forall t m . (MonadWidget t m) => String -> Dropzone -> m (Event t ())
dropzoneEventFor0 _ _ = return never
#endif
#ifdef ghcjs_HOST_OS
-- | Callbacks with arity 1
dropzoneEventFor1 :: forall t m a . (MonadWidget t m) => String -> Dropzone -> m (Event t (JSRef a))
dropzoneEventFor1 ename elt = wrapDomEvent elt (connect ename) (asks snd) -- "asks snd": use the obj as value of Reflex Event
where
connect :: String -> Dropzone -> ReaderT (Dropzone, (JSRef a)) IO () -> IO (IO ())
connect eventName target callback =
dropzoneRegisterListener1 target eventName $ \dz a -> runReaderT callback (dz, a)
#else
-- | Callbacks with arity 1
dropzoneEventFor1 :: forall t m a . (MonadWidget t m) => String -> Dropzone -> m (Event t a)
dropzoneEventFor1 _ _ = return never
#endif
#ifdef ghcjs_HOST_OS
-- | Callbacks with arity 2
dropzoneEventFor2 :: forall t m a b . (MonadWidget t m) => String -> Dropzone -> m (Event t (JSRef a, JSRef b))
dropzoneEventFor2 ename elt = wrapDomEvent elt (connect ename) (asks snd) -- "asks snd": use the objs as value of Reflex Event
where
connect :: String -> Dropzone -> ReaderT (Dropzone, (JSRef a, JSRef b)) IO () -> IO (IO ())
connect eventName target callback =
dropzoneRegisterListener2 target eventName $ \dz a b -> runReaderT callback (dz, (a, b))
#else
-- | Callbacks with arity 2
dropzoneEventFor2 :: forall t m a b . (MonadWidget t m) => String -> Dropzone -> m (Event t (a, b))
dropzoneEventFor2 _ _ = return never
#endif
------------------------------------------------------------------------
-- Reflex Events - Different Types
dropzoneEventForObj :: forall t m a . (MonadWidget t m, GObjectClass a) => String -> Dropzone -> m (Event t a)
dropzoneEventForObj eventName self = fmap (unsafeCastGObject . GObject) <$> dropzoneEventFor1 eventName self
dropzoneEventForFile :: MonadWidget t m => String -> Dropzone -> m (Event t File)
dropzoneEventForFile = dropzoneEventForObj
dropzoneEventForDOMEvent :: MonadWidget t m => String -> Dropzone -> m (Event t GJST.Event)
dropzoneEventForDOMEvent = dropzoneEventForObj
#ifdef ghcjs_HOST_OS
dropzoneEventForFiles :: MonadWidget t m => String -> Dropzone -> m (Event t [File])
dropzoneEventForFiles eventName self = do
eref <- dropzoneEventFor1 eventName self
erefs <- performEvent (liftIO . fromArray <$> eref)
return $ map (unsafeCastGObject . GObject) <$> erefs
#else
dropzoneEventForFiles :: MonadWidget t m => String -> Dropzone -> m (Event t [File])
dropzoneEventForFiles _ _ = return never
#endif
#ifdef ghcjs_HOST_OS
dropzoneEventForFileText :: MonadWidget t m => String -> Dropzone -> m (Event t (File, T.Text))
dropzoneEventForFileText ename dz = fmap ((unsafeCastGObject . GObject) *** fromJSString) <$> dropzoneEventFor2 ename dz
#else
dropzoneEventForFileText :: MonadWidget t m => String -> Dropzone -> m (Event t (File, T.Text))
dropzoneEventForFileText _ _ = return never
#endif
------------------------------------------------------------------------
-- Specific Dropzone Events
-- File Events
-- | Register for "addedfile" events on the Dropzone
dropzoneAddedFile :: forall t m . MonadWidget t m => Dropzone -> m (Event t File)
dropzoneAddedFile = dropzoneEventForFile "addedfile"
dropzoneCancelled :: forall t m . MonadWidget t m => Dropzone -> m (Event t File)
dropzoneCancelled = dropzoneEventForFile "cancelled"
dropzoneComplete :: forall t m . MonadWidget t m => Dropzone -> m (Event t File)
dropzoneComplete = dropzoneEventForFile "complete"
dropzoneMaxFilesExceeded :: forall t m . MonadWidget t m => Dropzone -> m (Event t File)
dropzoneMaxFilesExceeded = dropzoneEventForFile "maxfilesexceeded"
dropzoneProcessing :: forall t m . MonadWidget t m => Dropzone -> m (Event t File)
dropzoneProcessing = dropzoneEventForFile "processing"
dropzoneRemovedFile :: forall t m . MonadWidget t m => Dropzone -> m (Event t File)
dropzoneRemovedFile = dropzoneEventForFile "removedfile"
-- File+Text Events
dropzoneError :: forall t m . MonadWidget t m => Dropzone -> m (Event t (File, T.Text))
dropzoneError = dropzoneEventForFileText "error"
dropzoneSuccess :: forall t m . MonadWidget t m => Dropzone -> m (Event t (File, T.Text))
dropzoneSuccess = dropzoneEventForFileText "success"
dropzoneThumbnail :: forall t m . MonadWidget t m => Dropzone -> m (Event t (File, T.Text))
dropzoneThumbnail = dropzoneEventForFileText "thumbnail"
-- Multiple File Events
dropzoneAddedFiles :: forall t m . MonadWidget t m => Dropzone -> m (Event t [File])
dropzoneAddedFiles = dropzoneEventForFiles "addedfiles"
dropzoneCanceledMultiple :: forall t m . MonadWidget t m => Dropzone -> m (Event t [File])
dropzoneCanceledMultiple = dropzoneEventForFiles "canceledmultiple"
dropzoneCompleteMultiple :: forall t m . MonadWidget t m => Dropzone -> m (Event t [File])
dropzoneCompleteMultiple = dropzoneEventForFiles "completemultiple"
dropzoneProcessingMultiple :: forall t m . MonadWidget t m => Dropzone -> m (Event t [File])
dropzoneProcessingMultiple = dropzoneEventForFiles "processingmultiple"
-- DOM Events
dropzoneDragEnd :: forall t m . MonadWidget t m => Dropzone -> m (Event t GJST.Event)
dropzoneDragEnd = dropzoneEventForDOMEvent "dragend"
dropzoneDragEnter :: forall t m . MonadWidget t m => Dropzone -> m (Event t GJST.Event)
dropzoneDragEnter = dropzoneEventForDOMEvent "dragenter"
dropzoneDragLeave :: forall t m . MonadWidget t m => Dropzone -> m (Event t GJST.Event)
dropzoneDragLeave = dropzoneEventForDOMEvent "dragleave"
dropzoneDragOver :: forall t m . MonadWidget t m => Dropzone -> m (Event t GJST.Event)
dropzoneDragOver = dropzoneEventForDOMEvent "dragover"
dropzoneDragStart :: forall t m . MonadWidget t m => Dropzone -> m (Event t GJST.Event)
dropzoneDragStart = dropzoneEventForDOMEvent "dragstart"
dropzoneDrop :: forall t m . MonadWidget t m => Dropzone -> m (Event t GJST.Event)
dropzoneDrop = dropzoneEventForDOMEvent "drop"
dropzonePaste :: forall t m . MonadWidget t m => Dropzone -> m (Event t GJST.Event)
dropzonePaste = dropzoneEventForDOMEvent "paste"
-- Other
-- "sending"
-- "uploadprogress"
-- "totaluploadprogress"
-- "sendingmultiple"
dropzoneQueueComplete :: forall t m . MonadWidget t m => Dropzone -> m (Event t GJST.Event)
dropzoneQueueComplete = dropzoneEventForDOMEvent "queuecomplete"
dropzoneReset :: forall t m . MonadWidget t m => Dropzone -> m (Event t GJST.Event)
dropzoneReset = dropzoneEventForDOMEvent "reset"
| benmos/reflex-dropzone | src/JavaScript/Dropzone/Reflex.hs | bsd-3-clause | 10,217 | 0 | 14 | 1,690 | 2,430 | 1,307 | 1,123 | 121 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Server (session) where
import Control.Monad
import Control.Monad.Remote.JSON
import Control.Applicative
import Data.Monoid
import Data.Aeson
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text.IO as IO
import System.Random
session :: Session -- sync async
session = defaultSession Weak (fmap (fromMaybe Null) . router db) (void . router db)
db :: [(Text, [Value] -> IO Value)]
db = [ ("say", say)
, ("temperature", temperature)
, ("fib", fib)
]
where
say :: [Value] -> IO Value
say [ String txt ] = do
IO.putStrLn $ "remote: " <> txt
return Null
temperature :: [Value] -> IO Value
temperature _ = do
t <- randomRIO (50, 100 :: Int)
IO.putStr $ "temperature: "
return $ toJSON t
fib :: [Value] -> IO Value
fib [Number x] = return $ toJSON (fibhelper x :: Int)
fibhelper x
|x <= 1 = 1
|otherwise = fibhelper (x-2) + fibhelper (x-1)
| roboguy13/remote-json | example/Weak/Server.hs | bsd-3-clause | 1,164 | 0 | 11 | 389 | 377 | 204 | 173 | 32 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
module Juno.Consensus.Handle.HeartbeatTimeout
(handle)
where
import Control.Lens
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Writer
import Juno.Consensus.Handle.Types
import Juno.Runtime.Sender (sendAllAppendEntries)
import Juno.Runtime.Timer (resetHeartbeatTimer, hasElectionTimerLeaderFired)
import Juno.Util.Util (debug,enqueueEvent)
import qualified Juno.Types as JT
data HeartbeatTimeoutEnv = HeartbeatTimeoutEnv {
_nodeRole :: Role
, _leaderWithoutFollowers :: Bool
}
makeLenses ''HeartbeatTimeoutEnv
data HeartbeatTimeoutOut = IsLeader | NotLeader | NoFollowers
handleHeartbeatTimeout :: (MonadReader HeartbeatTimeoutEnv m, MonadWriter [String] m) => String -> m HeartbeatTimeoutOut
handleHeartbeatTimeout s = do
tell ["heartbeat timeout: " ++ s]
role' <- view nodeRole
leaderWithoutFollowers' <- view leaderWithoutFollowers
case role' of
Leader -> if leaderWithoutFollowers'
then tell ["Leader found to not have followers"] >> return NoFollowers
else return IsLeader
_ -> return NotLeader
handle :: Monad m => String -> JT.Raft m ()
handle msg = do
s <- get
leaderWithoutFollowers' <- hasElectionTimerLeaderFired
(out,l) <- runReaderT (runWriterT (handleHeartbeatTimeout msg)) $
HeartbeatTimeoutEnv
(JT._nodeRole s)
leaderWithoutFollowers'
mapM_ debug l
case out of
IsLeader -> do
sendAllAppendEntries
resetHeartbeatTimer
hbMicrosecs <- view (JT.cfg . JT.heartbeatTimeout)
JT.timeSinceLastAER %= (+ hbMicrosecs)
NotLeader -> JT.timeSinceLastAER .= 0 -- probably overkill, but nice to know this gets set to 0 if not leader
NoFollowers -> do
timeout' <- return $ JT._timeSinceLastAER s
enqueueEvent $ ElectionTimeout $ "Leader has not hear from followers in: " ++ show (timeout' `div` 1000) ++ "ms"
| buckie/juno | src/Juno/Consensus/Handle/HeartbeatTimeout.hs | bsd-3-clause | 2,003 | 0 | 16 | 382 | 475 | 250 | 225 | 48 | 3 |
-- | Utility functions for parsing refs and loading things from them.
module Horse.Refs
( refToHash
, isBranchRef
, loadBranchFromRef
) where
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Either
import Data.Char (isDigit)
import Data.List (find)
import qualified Data.ByteString as BS (take)
import Horse.Utils (hashToString, note)
import Horse.Types
import qualified Horse.IO as HIO
import qualified Horse.Filesystem as HF
-- | Syntax for specifying a parent: '^'.
parentSyntax :: Char
parentSyntax = '^'
-- | Syntax for specifying an ancestor: '~'.
ancestorSyntax :: Char
ancestorSyntax = '~'
-- | Given any string, attempt to convert it to a hash.
-- Succeeds if the string is in a hash format, even if
-- the hash is not a key in the database (no commits / diffs
-- have been hashed with that key yet). Fails if the format
-- is unexpected. Acceptable formats are listed in user-facing
-- documentation.
refToHash :: String -> EIO Hash
refToHash unparsedRef = do
liftIO HF.assertCurrDirIsRepo
base <- case baseRef of
"HEAD" -> HIO.loadHeadHash
someHash -> untruncateBaseRef someHash
hoistEither (toAncestorDistance relatives) >>= applyRelatives base
where
-- throws exception if `read` fails
toAncestorDistance :: String -> Either Error Int
toAncestorDistance r
| Prelude.null r = Right 0
| all (parentSyntax ==) r = Right $ length r
| parentSyntax `elem` r =
Left $ "Fatal: cannot combine '" ++ [parentSyntax] ++ "' and '" ++ [ancestorSyntax] ++ "' syntax."
| all isDigit (tail r) = Right (read (tail r))
| otherwise = Left ("Fatal: unrecognized syntax: " ++ r)
applyRelatives :: Hash -> Int -> EIO Hash
applyRelatives h ancestorDistance = do
history <- HIO.loadCommit h >>= HIO.loadHistory
when (ancestorDistance >= length history) $
left "Fatal: specified relative commit is too far back in history; no commits exist there."
right $ hash (history !! ancestorDistance)
baseRef :: String
baseRef = takeWhile (not . isRelativeSyntax) unparsedRef
relatives :: String
relatives = dropWhile (not . isRelativeSyntax) unparsedRef
isRelativeSyntax :: Char -> Bool
isRelativeSyntax ch
= (ch == parentSyntax) || (ch == ancestorSyntax)
untruncateBaseRef :: String -> EIO Hash
untruncateBaseRef baseRef = do
when (Prelude.null baseRef) $
left "Fatal: can't untruncate the empty hash."
allHashes <- HIO.loadAllHashes
let matchingHashes = filter ((==) baseRef . hashToString . BS.take (length baseRef)) allHashes
allBranches <- HIO.loadAllBranches
let matchingBranches = filter ((==) baseRef . branchName) allBranches
let matching = matchingHashes ++ map branchHash matchingBranches
case length matching of
0 -> left $ "Fatal: ref " ++ baseRef ++ " does not match any branch names or stored hashes"
1 -> right $ head matching
_ -> left $ "Fatal: multiple hashes or branch names match specified ref: " ++ Prelude.show matching
isBranchRef :: String -> EIO Bool
isBranchRef ref = liftM (any ((==) ref . branchName)) HIO.loadAllBranches
loadBranchFromRef :: String -> EIO Branch
loadBranchFromRef ref
= HIO.loadAllBranches
>>= hoistEither
. note ("Could not load branch from ref: " ++ ref)
. find ((==) ref . branchName)
| bgwines/horse-control | src/Horse/Refs.hs | bsd-3-clause | 3,636 | 0 | 17 | 972 | 837 | 431 | 406 | 67 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Tasty.HUnit
import Control.Applicative ((<$>))
import Control.Monad
import Archive.Nar.UTF8
newtype UtfTest = UtfTest String
deriving (Show,Eq)
instance Arbitrary UtfTest where
arbitrary = UtfTest <$> (choose (0,38) >>= flip replicateM arbitraryChar)
where arbitraryChar = frequency
[ (1, toEnum <$> choose (0, 127))
, (2, toEnum <$> choose (128, 0x10ffff))
]
knownChars =
[ ("$", ([0x0024], "$"))
, ("¢", ([0x00A2], "\xc2\xa2"))
, ("€", ([0x20AC], "\xe2\x82\xac"))
]
knownCases = concatMap toTC knownChars
where toTC (s, (uniPoint, encoded)) =
[ testCase ("code point " ++ s) (uniPoint @=? map fromEnum s)
, testCase ("encoding " ++ s) (encoded @=? utf8Encode s)
, testCase ("decoding " ++ s) (s @=? utf8Decode encoded)
]
main :: IO ()
main = defaultMain $ testGroup "NAR"
[ testGroup "utf8"
( knownCases ++
[ testProperty "decode . encode == id" (\(UtfTest s) -> utf8Decode (utf8Encode s) == s)
])
]
| nar-org/hs-nar | tests/Tests.hs | bsd-3-clause | 1,232 | 0 | 18 | 367 | 398 | 227 | 171 | 29 | 1 |
module Control.Monad.Syntax.Five where
(=====<<) :: Monad m =>
(a -> b -> c -> d -> e -> m f)
-> m a
-> b -> c -> d -> e -> m f
(=====<<) mf x b c d e = x >>= (\a -> mf a b c d e)
infixr 1 =====<<
(=.===<<) :: Monad m =>
(a -> b -> c -> d -> e -> m f)
-> m b
-> a -> c -> d -> e -> m f
(=.===<<) mf x a c d e = x >>= (\b -> mf a b c d e)
infixr 1 =.===<<
(==.==<<) :: Monad m =>
(a -> b -> c -> d -> e -> m f)
-> m c
-> a -> b -> d -> e -> m f
(==.==<<) mf x a b d e = x >>= (\c -> mf a b c d e)
infixr 1 ==.==<<
(===.=<<) :: Monad m =>
(a -> b -> c -> d -> e -> m f)
-> m d
-> a -> b -> c -> e -> m f
(===.=<<) mf x a b c e = x >>= (\d -> mf a b c d e)
infixr 1 ===.=<<
(====.<<) :: Monad m =>
(a -> b -> c -> d -> e -> m f)
-> m e
-> a -> b -> c -> d -> m f
(====.<<) mf x a b c d = x >>= mf a b c d
infixr 1 ====.<<
| athanclark/composition-extra | src/Control/Monad/Syntax/Five.hs | bsd-3-clause | 995 | 0 | 13 | 436 | 588 | 305 | 283 | 31 | 1 |
{-# LANGUAGE TemplateHaskell, StandaloneDeriving, DeriveGeneric, TypeFamilies, FlexibleInstances #-}
module QueryArrow.Remote.Serialization where
import QueryArrow.Remote.Definitions
import QueryArrow.DB.NoTranslation
import Data.Scientific
import Data.MessagePack
import GHC.Generics
import QueryArrow.Serialization ()
import Foreign.StablePtr
import Foreign.Ptr
import GHC.Fingerprint
import GHC.StaticPtr
import Data.Map.Strict
import QueryArrow.Syntax.Term
import Data.Maybe (fromJust)
import System.IO.Unsafe (unsafePerformIO)
import Data.Binary.Get
import Data.Binary.Put
import Data.ByteString.Lazy
deriving instance Generic Fingerprint
deriving instance Generic a => Generic (NTDBQuery a)
instance MessagePack (Ptr a) where
fromObject (ObjectBin n) =
let i = runGet getWord64be (fromStrict n) in return (intPtrToPtr (fromIntegral i))
toObject sptr =
ObjectBin (toStrict (runPut (putWord64be (fromIntegral (ptrToIntPtr sptr)))))
instance MessagePack (StablePtr a) where
fromObject js = castPtrToStablePtr <$> fromObject js
toObject sptr =
toObject (castStablePtrToPtr sptr)
instance MessagePack Fingerprint
instance (MessagePack a, Generic a) => MessagePack (NTDBQuery a)
-- instance FromJSON (StaticPtr a) where
-- parseJSON js = do
-- sk <- parseJSON js
-- return (fromJust (unsafePerformIO (unsafeLookupStaticPtr sk)))
--
-- instance ToJSON (StaticPtr a) where
-- toJSON sptr =
-- toJSON (staticKey sptr)
| xu-hao/QueryArrow | QueryArrow-db-remote/src/QueryArrow/Remote/Serialization.hs | bsd-3-clause | 1,459 | 0 | 16 | 202 | 338 | 185 | 153 | 32 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Game.GameItemsGlobals where
import Control.Lens (makeLenses)
import Types
import Game.GItemArmorT
import qualified Constants
makeLenses ''GameItemsGlobals
initialGameItemsGlobals :: GameItemsGlobals
initialGameItemsGlobals =
GameItemsGlobals { _giJacketArmorInfo = GItemArmorT 25 50 0.30 0 Constants.armorJacket
, _giCombatArmorInfo = GItemArmorT 50 100 0.60 0.30 Constants.armorCombat
, _giBodyArmorInfo = GItemArmorT 100 200 0.80 0.60 Constants.armorBody
, _giQuakeDropTimeoutHack = 0
, _giJacketArmorIndex = GItemReference 0
, _giCombatArmorIndex = GItemReference 0
, _giBodyArmorIndex = GItemReference 0
, _giPowerScreenIndex = GItemReference 0
, _giPowerShieldIndex = GItemReference 0
}
| ksaveljev/hake-2 | src/Game/GameItemsGlobals.hs | bsd-3-clause | 948 | 0 | 8 | 298 | 157 | 88 | 69 | 18 | 1 |
import Test.Hspec
import Test.Lexer
main :: IO ()
main = do
Test.Lexer.test
| YLiLarry/parser241-lexer | test/Spec.hs | bsd-3-clause | 81 | 0 | 7 | 17 | 32 | 17 | 15 | 5 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Ordinal.HU.Rules
( rules ) where
import Control.Monad (join)
import Data.HashMap.Strict ( HashMap)
import Data.String
import Data.Text (Text)
import Prelude
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers (parseInt)
import Duckling.Ordinal.Helpers
import Duckling.Regex.Types
import Duckling.Types
ordinalsMap :: HashMap Text Int
ordinalsMap = HashMap.fromList
[ ( "első", 1 )
, ( "második", 2 )
, ( "harmadik", 3 )
, ( "negyedik", 4 )
, ( "ötödik", 5 )
, ( "hatodik", 6 )
, ( "hetedik", 7 )
, ( "nyolcadik", 8 )
, ( "kilencedik", 9 )
, ( "tizedik", 10 )
, ( "huszadik", 20 )
, ( "harmincadik", 30 )
, ( "negyvenedik", 40 )
, ( "ötvenedik", 50 )
, ( "hatvanadik", 60 )
, ( "hetvenedik", 70 )
, ( "nyolcvanadik", 80 )
, ( "kilencvenedik", 90 )
]
ordinalsMap2 :: HashMap Text Int
ordinalsMap2 = HashMap.fromList
[ ( "egyedik", 1 )
, ( "kettedik", 2 )
, ( "harmadik", 3 )
, ( "negyedik", 4 )
, ( "ötödik", 5 )
, ( "hatodik", 6 )
, ( "hetedik", 7 )
, ( "nyolcadik", 8 )
, ( "kilencedik", 9 )
]
cardinalsMap :: HashMap Text Int
cardinalsMap = HashMap.fromList
[ ( "tizen", 10 )
, ( "huszon", 20 )
, ( "harminc", 30 )
, ( "negyven", 40 )
, ( "ötven", 50 )
, ( "hatvan", 60 )
, ( "hetven", 70 )
, ( "nyolcvan", 80 )
, ( "kilencven", 90 )
]
ruleOrdinals :: Rule
ruleOrdinals = Rule
{ name = "ordinals (first..twentieth,thirtieth,...)"
, pattern =
[ regex "(első|második|harmadik|negyedik|ötödik|hatodik|hetedik|nyolcadik|kilencedik|tizedik|huszadik|harmincadik|negyvenedik|ötvenedik|hatvanadik|hetvenedik|nyolcvanadik|kilencvenedik)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
ordinal <$> HashMap.lookup (Text.toLower match) ordinalsMap
_ -> Nothing
}
ruleCompositeOrdinals :: Rule
ruleCompositeOrdinals = Rule
{ name = "ordinals (composite, e.g., eighty-seven)"
, pattern =
[ regex "(tizen|huszon|harminc|negyven|ötven|hatvan|hetven|nyolcvan|kilencven)\\-?(egyedik|kettedik|harmadik|negyedik|ötödik|hatodik|hetedik|nyolcadik|kilencedik)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (tens:units:_)):_) -> do
tt <- HashMap.lookup (Text.toLower tens) cardinalsMap
uu <- HashMap.lookup (Text.toLower units) ordinalsMap2
Just . ordinal $ tt + uu
_ -> Nothing
}
ruleOrdinalDigits :: Rule
ruleOrdinalDigits = Rule
{ name = "ordinal (digits)"
, pattern =
[ regex "0*(\\d+)\\."
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> ordinal <$> parseInt match
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleOrdinals
, ruleCompositeOrdinals
, ruleOrdinalDigits
]
| facebookincubator/duckling | Duckling/Ordinal/HU/Rules.hs | bsd-3-clause | 3,170 | 0 | 18 | 678 | 851 | 514 | 337 | 91 | 2 |
module Language.Hudson.PrettyPrinter where
import Text.PrettyPrint.HughesPJ
import Control.Monad (liftM2)
import Language.Hudson.AST
import Language.Hudson.Parser (parseFile, parseString', parseString)
import Control.Applicative ((<$>))
-- TODO
--
-- Allow withCode to use single line if-stmts, functions, etc.
--
-- Write a combinator that automatically adds continuation comments
-- for parameters.
prettyBlocks :: [Block] -> Doc
prettyBlocks bs | null bs = empty
| otherwise = vsep (map prettyBlock bs) <> newline
defaultHudsonIndent :: Int
defaultHudsonIndent = 4
withCode :: Doc -> [Block] -> Doc
withCode doc code = case code of
[] -> doc
-- Maybe use one line declarations. Need to
-- ensure that it is not applied to multiline
-- statements
--
-- [_c] -> doc <+> nestedBlocks
_ -> doc $+$ nestedBlocks
where
nestedBlocks = vcat $ map (nest defaultHudsonIndent . prettyBlock) code
keyNameSep :: String -- ^ keyword
-> String -- ^ name
-> Doc -- ^ middle part
-> String -- ^ separator
-> (Doc -> Doc -> Doc) -- ^ how to combine the name and middle
-> Doc
keyNameSep keyword name middle separator combine =
(text keyword <+> text name) `combine` middle <+> text separator
newline :: Doc
newline = char '\n'
prettyBlock :: Block -> Doc
prettyBlock b = case b of
(BlockStmt s) -> prettyStmt s
(BlockDecl d) -> prettyDecl d
vsep :: [Doc] -> Doc
vsep = foldl1 ($+$)
prettyStmt :: Stmt -> Doc
prettyStmt s =
case s of
Assignment v e -> prettyExpr v <+> text ":=" <+> prettyExpr e
ProcCall v ps -> text v <> (parens . commaDelimit $ map prettyExpr ps)
ObjCall e -> prettyExpr e
If {} -> prettyIf s
While cond ws -> (text "while" <+> prettyExpr cond <+> text "do")
`withCode` ws <> newline
Return m -> maybe (text "return")
(\v -> text "return" <+> prettyExpr v)
m
Assert e -> text "assert" <+> prettyExpr e
Null -> text "null"
BlockComment c -> text c -- TODO: maybe reflow text?
-- | Handle else-if chain so the if statementes aren't nested each
-- time.
prettyIf :: Stmt -> Doc -- TODO: Limit this to if, might need GADTs
prettyIf (If cond ts elses elseDoc) =
ifStart $$ case elses of
[] -> empty
-- To place an else-if chain on one line, the else
-- clause may only contain one statement, the
-- if-statement. This limitation arises because the
-- if-statment takes over the scope from the
-- else-statement and there is no clean way to dedent
-- to get back to the else-statement's scope.
BlockStmt i@If{} : [] -> prettyElseIf i
_otherwise -> comment $$ text "else" `withCode` elses
where
ifStart = (text "if" <+> prettyExpr cond <+> text "then") `withCode` ts
comment = maybe empty text elseDoc
prettyIf _ = error "May only use if statement for pretty if."
-- We need a separate function because @nest@, and therefore
-- @withCode@, will only unnest (given a negative argument) until it
-- bumps into another doc. In other words, the most negative value
-- for nest is the horizontal distance between the current doc and
-- preceeding doc.
prettyElseIf :: Stmt -> Doc
prettyElseIf (If cond ts elses elseDoc) =
elseIfStart $$ case elses of
[] -> empty
BlockStmt i@If{} : [] -> prettyElseIf i
_otherwise -> comment $$ text "else" `withCode` elses
where
elseIfStart = (text "else if" <+> prettyExpr cond <+> text "then") `withCode` ts
comment = maybe empty text elseDoc
prettyElseIf _ = error "May only if statement for prettyElseIf"
prettyType :: Maybe String -> Doc
prettyType t = maybe empty (\s -> colon <+> text s) t
commaDelimit :: [Doc] -> Doc
commaDelimit = hsep . punctuate (char ',')
prettyParams :: [Param] -> Doc
prettyParams = parens . commaDelimit . map prettyParam
prettyParam :: Param -> Doc
prettyParam (Param isRef name ptype) =
case isRef of
False -> text name <> prettyType ptype
True -> text "ref" <+> text name <+> prettyType ptype
prettyDecl :: Decl -> Doc
prettyDecl d =
case d of
VarDecl name vtype expr -> pVar "variable" name vtype expr
ConstDecl name ctype expr -> pVar "constant" name ctype expr
FuncDecl name params code -> pMethod "function" name params code
ProcDecl name params code -> pMethod "procedure" name params code
ClassDecl name parent
implements code -> pClass name parent implements code
where
pVar keyword name vtype expr =
let exprDoc = maybe empty (\e -> text ":=" <+> prettyExpr e) expr
in keyNameSep keyword name (prettyType vtype) "" (<>) <> exprDoc
pMethod method name params code =
keyNameSep method name (prettyParams params) "is" (<>)
`withCode` code <> newline
pClass name parent implements code =
keyNameSep "class" name (pInherit parent <+> pSubs implements) "is" (<+>)
`withCode` code <> newline
pInherit i = maybe empty (\x -> text "inherit" <+> text x) i
pSubs xs | null xs = empty
| otherwise = char '<' <+> commaDelimit (map text xs)
prettyActuals :: [Expr] -> Doc
prettyActuals = parens . commaDelimit . map prettyExpr
-- TODO: Doesn't handle precedence rules correctly
prettyExpr :: Expr -> Doc
prettyExpr x =
case x of
LiteralInt i -> integer i
LiteralStr s -> doubleQuotes $ text s
LiteralBool True -> text "true"
LiteralBool False -> text "false"
LiteralNull -> text "null"
LiteralThis -> text "this"
ClassLookup c -> text c
Negate e -> char '-' <> prettyExpr e
Not e -> text "not" <+> prettyExpr e
Binary TypeTest l r -> prettyExpr l <> char '?' <> prettyExpr r
Binary b l r -> hsep [prettyExpr l, prettyBinary b, prettyExpr r]
VarLookup s -> text s
FuncCall f as -> text f <> prettyActuals as
ClassCall c as -> text c <> prettyActuals as
ParenExpr e -> parens $ prettyExpr e
ObjFieldExpr n e -> prettyExpr e <> text n
ObjMethodExpr n as e -> hcat [prettyExpr e, text n, prettyActuals as]
LambdaExpr ps e -> hsep [text "fun", prettyParams ps,
text "is", prettyExpr e]
prettyBinary :: BinaryOp -> Doc
prettyBinary b =
case b of
Add -> char '+'
Sub -> char '-'
Mult -> char '*'
Div -> char '/'
Mod -> char '%'
Equal -> char '='
NotEqual -> text "/="
LessThan -> char '<'
TypeTest -> char '?'
LessThanEqual -> text "<="
GreaterThan -> text ">"
GreaterThanEqual -> text ">="
And -> text "and"
Or -> text "or"
Concat -> char '&'
prettifyString :: String -> Either String String
prettifyString ss = render . prettyBlocks <$> parseString ss
-- printString = putStrLn . prettifyString
prettifyFile :: FilePath -> IO (Either String String)
prettifyFile fname = do
ps <- parseFile fname
return $ render . prettyBlocks <$> ps
printPretty :: FilePath -> IO ()
printPretty fname = prettifyFile fname >>= either putStrLn putStrLn
roundTripTest :: FilePath -> IO (Bool)
roundTripTest fname = liftM2 (==) p1 p2
where
p1 :: IO (Either String [Block])
p1 = do ps <- parseFile fname
writeFile "p1.out" (show ps)
return ps
p2 :: IO (Either String [Block])
p2 = do p <- prettifyFile fname
let es = case p of
Left err -> Left err
Right ps -> parseString' fname ps
writeFile "p2.hud" (either id id p)
writeFile "p2.out" (show es)
return es
| jschaf/hudson-dev | src/Language/Hudson/PrettyPrinter.hs | bsd-3-clause | 8,601 | 0 | 15 | 3,001 | 2,330 | 1,145 | 1,185 | 161 | 18 |
myFavoriteFruit = "banana"
| YoshikuniJujo/funpaala | samples/05_function/fruits1.hs | bsd-3-clause | 27 | 0 | 4 | 3 | 6 | 3 | 3 | 1 | 1 |
-- | Functions for working with CSV files.
module Analyze.Csv where
import Analyze.Conversions (projectRows)
import Analyze.RFrame (RFrame (..), RFrameUpdate (..), empty, fromUpdate)
import Control.Monad.Catch (Exception, MonadThrow (..))
import qualified Data.Binary.Builder as B
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Char8 as LBS8
import qualified Data.Csv as C
import qualified Data.Csv.Builder as CB
import Data.Text (Text)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.Typeable (Typeable)
import qualified Data.Vector as V
-- | Exception to wrap Cassava error strings.
data CsvError = CsvError String deriving (Eq, Show, Typeable)
instance Exception CsvError
-- | Decode CSV bytes as an 'RFrame' with a header row.
decodeWithHeader :: MonadThrow m => LBS.ByteString -> m (RFrame Text Text)
decodeWithHeader bs =
case C.decodeByName bs of
Left err -> throwM (CsvError err)
Right (header, rows) -> do
let ks = decodeUtf8 <$> header
projectRows ks rows
-- | Decode CSV bytes as an 'RFrame' without a header row.
decodeWithoutHeader :: MonadThrow m => LBS.ByteString -> m (RFrame Int Text)
decodeWithoutHeader bs =
case C.decode C.NoHeader bs of
Left err -> throwM (CsvError err)
Right rows ->
if V.null rows
then return empty
else do
let ks = V.imap const (V.head rows)
update = RFrameUpdate ks rows
fromUpdate update
-- | Encode an 'RFrame' as CSV bytes with a header row.
encodeWithHeader :: RFrame Text Text -> LBS.ByteString
encodeWithHeader (RFrame ks _ vs) =
let header = CB.encodeHeader (encodeUtf8 <$> ks)
rows = header `mappend` foldMap (CB.encodeRecord . (encodeUtf8 <$>)) vs
in B.toLazyByteString header
-- | Encode an 'RFrame' as CSV bytes without header row.
encodeWithoutHeader :: RFrame k Text -> LBS.ByteString
encodeWithoutHeader (RFrame _ _ vs) =
B.toLazyByteString (foldMap (CB.encodeRecord . (encodeUtf8 <$>)) vs)
loadCSVFileWithHeader :: FilePath -> IO (RFrame Text Text)
loadCSVFileWithHeader fileName = do
contents <- readFile fileName
decodeWithHeader (LBS8.pack contents)
loadCSVFileWithoutHeader :: FilePath -> IO (RFrame Int Text)
loadCSVFileWithoutHeader fileName = do
contents <- readFile fileName
decodeWithoutHeader (LBS8.pack contents)
| ejconlon/analyze | src/Analyze/Csv.hs | bsd-3-clause | 2,533 | 0 | 17 | 614 | 673 | 359 | 314 | 49 | 3 |
{-# LINE 1 "Control.Monad.Fix.hs" #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Fix
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Monadic fixpoints.
--
-- For a detailed discussion, see Levent Erkok's thesis,
-- /Value Recursion in Monadic Computations/, Oregon Graduate Institute, 2002.
--
-----------------------------------------------------------------------------
module Control.Monad.Fix (
MonadFix(mfix),
fix
) where
import Data.Either
import Data.Function ( fix )
import Data.Maybe
import Data.Monoid ( Dual(..), Sum(..), Product(..)
, First(..), Last(..), Alt(..) )
import GHC.Base ( Monad, errorWithoutStackTrace, (.) )
import GHC.Generics
import GHC.List ( head, tail )
import GHC.ST
import System.IO
-- | Monads having fixed points with a \'knot-tying\' semantics.
-- Instances of 'MonadFix' should satisfy the following laws:
--
-- [/purity/]
-- @'mfix' ('return' . h) = 'return' ('fix' h)@
--
-- [/left shrinking/ (or /tightening/)]
-- @'mfix' (\\x -> a >>= \\y -> f x y) = a >>= \\y -> 'mfix' (\\x -> f x y)@
--
-- [/sliding/]
-- @'mfix' ('Control.Monad.liftM' h . f) = 'Control.Monad.liftM' h ('mfix' (f . h))@,
-- for strict @h@.
--
-- [/nesting/]
-- @'mfix' (\\x -> 'mfix' (\\y -> f x y)) = 'mfix' (\\x -> f x x)@
--
-- This class is used in the translation of the recursive @do@ notation
-- supported by GHC and Hugs.
class (Monad m) => MonadFix m where
-- | The fixed point of a monadic computation.
-- @'mfix' f@ executes the action @f@ only once, with the eventual
-- output fed back as the input. Hence @f@ should not be strict,
-- for then @'mfix' f@ would diverge.
mfix :: (a -> m a) -> m a
-- Instances of MonadFix for Prelude monads
instance MonadFix Maybe where
mfix f = let a = f (unJust a) in a
where unJust (Just x) = x
unJust Nothing = errorWithoutStackTrace "mfix Maybe: Nothing"
instance MonadFix [] where
mfix f = case fix (f . head) of
[] -> []
(x:_) -> x : mfix (tail . f)
instance MonadFix IO where
mfix = fixIO
instance MonadFix ((->) r) where
mfix f = \ r -> let a = f a r in a
instance MonadFix (Either e) where
mfix f = let a = f (unRight a) in a
where unRight (Right x) = x
unRight (Left _) = errorWithoutStackTrace "mfix Either: Left"
instance MonadFix (ST s) where
mfix = fixST
-- Instances of Data.Monoid wrappers
instance MonadFix Dual where
mfix f = Dual (fix (getDual . f))
instance MonadFix Sum where
mfix f = Sum (fix (getSum . f))
instance MonadFix Product where
mfix f = Product (fix (getProduct . f))
instance MonadFix First where
mfix f = First (mfix (getFirst . f))
instance MonadFix Last where
mfix f = Last (mfix (getLast . f))
instance MonadFix f => MonadFix (Alt f) where
mfix f = Alt (mfix (getAlt . f))
-- Instances for GHC.Generics
instance MonadFix Par1 where
mfix f = Par1 (fix (unPar1 . f))
instance MonadFix f => MonadFix (Rec1 f) where
mfix f = Rec1 (mfix (unRec1 . f))
instance MonadFix f => MonadFix (M1 i c f) where
mfix f = M1 (mfix (unM1. f))
instance (MonadFix f, MonadFix g) => MonadFix (f :*: g) where
mfix f = (mfix (fstP . f)) :*: (mfix (sndP . f))
where
fstP (a :*: _) = a
sndP (_ :*: b) = b
| phischu/fragnix | builtins/base/Control.Monad.Fix.hs | bsd-3-clause | 3,815 | 0 | 12 | 967 | 935 | 511 | 424 | 61 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module LargeNumberTest where
import Init
import Data.Word
#ifdef WITH_NOSQL
mkPersist persistSettings [persistUpperCase|
#else
share [mkPersist sqlSettings, mkMigrate "numberMigrate"] [persistLowerCase|
#endif
Number
intx Int
int32 Int32
word32 Word32
int64 Int64
word64 Word64
deriving Show Eq
|]
#ifdef WITH_NOSQL
cleanDB :: (MonadIO m, PersistQuery backend, PersistEntityBackend Number ~ backend) => ReaderT backend m ()
cleanDB = do
deleteWhere ([] :: [Filter Number])
db :: Action IO () -> Assertion
db = db' cleanDB
#endif
specs :: Spec
specs = describe "persistent" $ do
it "large numbers" $ db $ do
let go x = do
xid <- insert x
x' <- get xid
liftIO $ x' @?= Just x
go $ Number maxBound 0 0 0 0
go $ Number 0 maxBound 0 0 0
go $ Number 0 0 maxBound 0 0
go $ Number 0 0 0 maxBound 0
go $ Number 0 0 0 0 maxBound
go $ Number minBound 0 0 0 0
go $ Number 0 minBound 0 0 0
go $ Number 0 0 minBound 0 0
go $ Number 0 0 0 minBound 0
go $ Number 0 0 0 0 minBound
| plow-technologies/persistent | persistent-test/src/LargeNumberTest.hs | mit | 1,464 | 0 | 17 | 376 | 384 | 188 | 196 | 32 | 1 |
string = "# ¬ 水 😴"
| evolutics/haskell-formatter | testsuite/resources/source/literals/does_not_escape_characters/Output.hs | gpl-3.0 | 25 | 0 | 4 | 6 | 6 | 3 | 3 | 1 | 1 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Data.Map (fromList)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import ETL (transform)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "etl" $
-- As of 2016-07-27, there was no reference file
-- for the test cases in `exercism/x-common`.
describe "transform" $ do
it "transform one value" $
transform (fromList [(1, "A")])
`shouldBe` fromList [('a', 1)]
it "transform multiple keys from one value" $
transform (fromList [(1, "AE")])
`shouldBe` fromList [('a', 1), ('e', 1)]
it "transform multiple keys from multiple values" $
transform (fromList [(1, "A"), (4, "B")])
`shouldBe` fromList [('a', 1), ('b', 4)]
it "full dataset" $
transform (fromList fullInput)
`shouldBe` fromList fullOutput
where
fullInput = [ ( 1, "AEIOULNRST")
, ( 2, "DG" )
, ( 3, "BCMP" )
, ( 4, "FHVWY" )
, ( 5, "K" )
, ( 8, "JX" )
, (10, "QZ" ) ]
fullOutput = [ ('a', 1) , ('b', 3) , ('c', 3) , ('d', 2)
, ('e', 1) , ('f', 4) , ('g', 2) , ('h', 4)
, ('i', 1) , ('j', 8) , ('k', 5) , ('l', 1)
, ('m', 3) , ('n', 1) , ('o', 1) , ('p', 3)
, ('q', 10) , ('r', 1) , ('s', 1) , ('t', 1)
, ('u', 1) , ('v', 4) , ('w', 4) , ('x', 8)
, ('y', 4) , ('z', 10) ]
| daewon/til | exercism/haskell/etl/test/Tests.hs | mpl-2.0 | 1,674 | 0 | 14 | 609 | 612 | 375 | 237 | 36 | 1 |
{-
Copyright 2016,2017 Markus Ongyerth
This file is part of Monky.
Monky is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Monky 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Monky. If not, see <http://www.gnu.org/licenses/>.
-}
{-|
Module : Monky.Examples.Wifi
Description : Backwards compatability module for "Monky.Examples.Wifi.Event"
Maintainer : ongy
Stability : experimental
Portability : Linux
-}
module Monky.Examples.Wifi
( getWifiHandle
, getWifiHandle'
, WifiEvtHandle
, WifiFormat(..)
)
where
import Monky.Examples.Wifi.Event
| monky-hs/monky | Monky/Examples/Wifi.hs | lgpl-3.0 | 1,065 | 0 | 5 | 223 | 34 | 24 | 10 | 6 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
module Language.K3.Interpreter.Context (
NetworkPeer,
VirtualizedMessageProcessor,
SingletonMessageProcessor,
runInterpretation,
runExpression,
runExpression_,
prepareProgram,
runProgram,
prepareNetwork,
runNetwork,
emptyState,
getResultVal,
emptyStaticEnv
-- #ifdef TEST
-- TODO When the ifdef is uncommented, the dataspace tests don't compile
, throwE
-- #endif
) where
import Control.Arrow hiding ( (+++) )
import Control.Concurrent
import Control.Monad.Identity
import Control.Monad.Reader
import Data.Function
import Data.List
import Language.K3.Core.Annotation
import Language.K3.Core.Common
import Language.K3.Core.Declaration
import Language.K3.Core.Expression
import Language.K3.Core.Type
import Language.K3.Core.Utils
import Language.K3.Interpreter.Data.Types
import Language.K3.Interpreter.Data.Accessors
import Language.K3.Interpreter.Values
import Language.K3.Interpreter.Collection
import Language.K3.Interpreter.Utils
import Language.K3.Interpreter.Builtins
import Language.K3.Interpreter.Evaluation
import Language.K3.Runtime.Common ( PeerBootstrap, SystemEnvironment )
import Language.K3.Runtime.Dispatch
import Language.K3.Runtime.Engine
import Language.K3.Analysis.Interpreter.BindAlias ( labelBindAliases )
import Language.K3.Utils.Pretty
import Language.K3.Utils.Logger
$(loggingFunctions)
$(customLoggingFunctions ["RegisterGlobal"])
{- Program initialization methods -}
-- | Constructs a static environment for all globals and annotation
-- combinations by interpreting the program declarations.
-- By ensuring that global and annotation member functions use
-- static initializers (i.e. initializers that do not depend on runtime values),
-- we can simply populate the static environment from the interpreter
-- environment resulting immediately after declaration initialization.
staticEnvironment :: PrintConfig -> K3 Declaration -> EngineM Value (SEnvironment Value)
staticEnvironment pc prog = do
initSt <- initState pc emptyAnnotationEnv prog
staticR <- runInterpretation' initSt (declaration prog)
logIStateM "PRE STATIC " Nothing $ getResultState staticR
let st = getResultState staticR
funEnv <- staticFunctions st
annotEnv <- staticAnnotations st
liftIO (staticStateIO (funEnv, annotEnv)) >>= logIStateM "STATIC " Nothing
return (funEnv, annotEnv)
where
staticFunctions :: IState -> EngineM Value (IEnvironment Value)
staticFunctions st = do
resultIEnv <- runInterpretation' st
(emptyEnv >>= \nenv -> foldEnv insertIfFunction nenv $ getEnv st)
>>= liftError "(constructing static function environment)"
case getResultVal resultIEnv of
Left err -> throwEngineError . EngineError $ show err
Right ienv -> return ienv
insertIfFunction acc n e@(IVal (VFunction _)) = insertEnvIO n e acc
insertIfFunction acc n e@(MVal mv) = readMVar mv >>= \case
VFunction _ -> insertEnvIO n e acc
_ -> return acc
insertIfFunction acc _ _ = return acc
staticAnnotations :: IState -> EngineM Value (AEnvironment Value)
staticAnnotations st = do
let annProvs = undefined -- annotationProvides prog
let flatADefs = flattenADefinitions annProvs (definitions $ getAnnotEnv st)
let newAEnv = AEnvironment flatADefs []
let annEnvI = foldM addRealization newAEnv $ nub $ declCombos prog
resultAEnv <- liftIO (annotationStateIO newAEnv)
>>= \est -> runInterpretation' est annEnvI
>>= liftError "(constructing static annotation environment)"
case getResultVal resultAEnv of
Left err -> throwEngineError . EngineError $ show err
Right (AEnvironment d r) -> return $ AEnvironment d $ nubBy ((==) `on` fst) r
flattenADefinitions :: [(Identifier, Identifier)] -> AnnotationDefinitions Value
-> AnnotationDefinitions Value
flattenADefinitions provides aDefs = foldl addProvidesMembers aDefs provides
addProvidesMembers aDefs (s,t) = case (lookup s aDefs, lookup t aDefs) of
(Just sMems, Just tMems) -> replaceAssoc aDefs s $ mergeMembers sMems tMems
_ -> aDefs
addRealization :: AEnvironment Value -> [Identifier] -> Interpretation (AEnvironment Value)
addRealization aEnv@(AEnvironment d r) annNames = do
comboIdOpt <- getComposedAnnotation annNames
case comboIdOpt of
Nothing -> return aEnv
Just cId -> lookupACombo cId >>= return . AEnvironment d . (:r) . (cId,)
declCombos :: K3 Declaration -> [[Identifier]]
declCombos = runIdentity . foldTree extractDeclCombos []
typeCombos :: K3 Type -> [[Identifier]]
typeCombos = runIdentity . foldTree extractTypeCombos []
exprCombos :: K3 Expression -> [[Identifier]]
exprCombos = runIdentity . foldTree extractExprCombos []
extractDeclCombos :: [[Identifier]] -> K3 Declaration -> Identity [[Identifier]]
extractDeclCombos st (tag -> DGlobal _ t eOpt) = return $ st ++ typeCombos t ++ (maybe [] exprCombos eOpt)
extractDeclCombos st (tag -> DTrigger _ t e) = return $ st ++ typeCombos t ++ exprCombos e
extractDeclCombos st (tag -> DDataAnnotation _ _ mems) = return $ st ++ concatMap memCombos mems
extractDeclCombos st _ = return st
extractTypeCombos :: [[Identifier]] -> K3 Type -> Identity [[Identifier]]
extractTypeCombos c (tag &&& annotations -> (TCollection, tAnns)) =
case namedTAnnotations tAnns of
[] -> return c
namedAnns -> return $ namedAnns:c
extractTypeCombos c _ = return c
extractExprCombos :: [[Identifier]] -> K3 Expression -> Identity [[Identifier]]
extractExprCombos c (tag &&& annotations -> (EConstant (CEmpty et), eAnns)) =
case namedEAnnotations eAnns of
[] -> return $ c ++ typeCombos et
namedAnns -> return $ (namedAnns:c) ++ typeCombos et
extractExprCombos c _ = return c
memCombos :: AnnMemDecl -> [[Identifier]]
memCombos (Lifted _ _ t eOpt _) = typeCombos t ++ (maybe [] exprCombos eOpt)
memCombos (Attribute _ _ t eOpt _) = typeCombos t ++ (maybe [] exprCombos eOpt)
memCombos _ = []
initEnvironment :: K3 Declaration -> IState -> EngineM Value IState
initEnvironment decl st =
let declGState = runIdentity $ foldTree registerDecl st decl
in initDecl declGState decl
where
initDecl st' (tag &&& children -> (DGlobal n t eOpt, ch)) = initGlobal st' n t eOpt >>= flip (foldM initDecl) ch
initDecl st' (tag &&& children -> (DTrigger n _ _, ch)) = initTrigger st' n >>= flip (foldM initDecl) ch
initDecl st' (tag &&& children -> (DRole _, ch)) = foldM initDecl st' ch
initDecl st' _ = return st'
-- | Global initialization for cyclic dependencies.
-- This partially initializes sinks and functions (to their defining lambda expression).
initGlobal :: IState -> Identifier -> K3 Type -> Maybe (K3 Expression) -> EngineM Value IState
initGlobal st' n (tag -> TSink) _ = initTrigger st' n
initGlobal st' n t@(isTFunction -> True) eOpt = initFunction st' n t eOpt
initGlobal st' _ _ _ = return st'
initTrigger st' n = initializeBinding st'
(memEntTag Nothing >>= \tg -> insertE n $ IVal $ VTrigger (n, Nothing, tg))
-- Functions create lambda expressions, thus they are safe to initialize during
-- environment construction. This way, all global functions can be mutually recursive.
-- Note that since we only initialize functions, no declaration can force function
-- evaluation during initialization (e.g., as would be the case with variable initializers).
initFunction st' n t (Just e) = initializeExpr st' n t e
initFunction st' n t Nothing = initializeBinding st' $ builtin n t
initializeExpr st' n t e = initializeBinding st' (expression e >>= entryOfValueT (t @~ isTQualified) >>= insertE n)
initializeBinding st' interp = runInterpretation' st' interp
>>= liftError "(initializing environment)"
>>= return . getResultState
-- | Global identifier registration
registerGlobal :: Identifier -> IState -> IState
registerGlobal n istate = modifyStateGlobals ((:) n) istate
registerDecl :: IState -> K3 Declaration -> Identity IState
registerDecl st' (tag -> DGlobal n _ _) = debugRegDecl ("Registering global "++n) $ registerGlobal n st'
registerDecl st' (tag -> DTrigger n _ _) = debugRegDecl ("Registering global "++n) $ registerGlobal n st'
registerDecl st' _ = debugRegDecl ("Skipping global registration") $ st'
debugRegDecl s a = return $ _debugI_RegisterGlobal s a
initState :: PrintConfig -> AEnvironment Value -> K3 Declaration -> EngineM Value IState
initState pc aEnv prog = liftIO (annotationStatePCIO pc aEnv) >>= initEnvironment prog
{- Program initialization and finalization via the atInit and atExit triggers -}
atInitTrigger :: IResult () -> EngineM Value (IResult Value)
atInitTrigger ((Left err, s), ilog) = return ((Left err, s), ilog)
atInitTrigger ((Right _, st), ilog) = do
vOpt <- liftIO (lookupEnvIO "atInit" (getEnv st) >>= valueOfEntryOptIO)
case vOpt of
Just (VFunction (f, _, _)) -> runInterpretation' st (f vunit)
_ -> return ((unknownTrigger, st), ilog)
where
unknownTrigger = Left $ RunTimeTypeError "Could not find atInit trigger" Nothing
atExitTrigger :: IState -> EngineM Value (IResult Value)
atExitTrigger st = do
atExitVOpt <- liftIO (lookupEnvIO "atExit" (getEnv st) >>= valueOfEntryOptIO)
runInterpretation' st $ maybe unknownTrigger runFinal atExitVOpt
where runFinal (VFunction (f,_,_)) = f vunit >>= \r -> syncE >> return r
runFinal _ = throwE $ RunTimeTypeError "Invalid atExit trigger"
unknownTrigger = throwE $ RunTimeTypeError "Could not find atExit trigger"
-- TODO: determine qualifier when creating environment entry for literals
initBootstrap :: PeerBootstrap -> AEnvironment Value -> EngineM Value (IEnvironment Value)
initBootstrap bootstrap aEnv = do
st <- liftIO $ annotationStateIO aEnv
namedLiterals <- mapM (interpretLiteral st) bootstrap
liftIO $ envFromListIO namedLiterals
where
interpretLiteral st (n,l) = runInterpretation' st (literal l)
>>= liftError "(initializing bootstrap)"
>>= either invalidErr (return . (n,) . IVal) . getResultVal
invalidErr = const $ throwEngineError $ EngineError "Invalid result"
injectBootstrap :: PeerBootstrap -> IResult a -> EngineM Value (IResult a)
injectBootstrap _ r@((Left _, _), _) = return r
injectBootstrap bootstrap ((Right val, st), rLog) = do
bootEnv <- initBootstrap bootstrap (getAnnotEnv st)
nEnv <- liftIO emptyEnvIO
nvEnv <- liftIO $ foldEnvIO (addFromBoostrap bootEnv) nEnv $ getEnv st
nSt <- liftIO $ modifyStateEnvIO (const $ return nvEnv) st
return ((Right val, nSt), rLog)
where addFromBoostrap bootEnv acc n e = lookupEnvIO n bootEnv >>= flip (insertEnvIO n) acc . maybe e id
initProgram :: PrintConfig -> PeerBootstrap -> SEnvironment Value -> K3 Declaration -> EngineM Value (IResult Value)
initProgram pc bootstrap staticEnv prog = do
initSt <- initState pc (snd staticEnv) prog
staticSt <- liftIO $ modifyStateSEnvIO (const $ return staticEnv) initSt
declR <- runInterpretation' staticSt (declaration prog)
bootR <- injectBootstrap bootstrap declR
atInitTrigger bootR
{- Standalone (i.e., single peer) evaluation -}
standaloneInterpreter :: (IEngine -> IO a) -> IO a
standaloneInterpreter f = simpleEngine >>= f
runExpression :: K3 Expression -> IO (Maybe Value)
runExpression e = standaloneInterpreter $ \engine -> do
st <- liftIO $ emptyStateIO
rv <- runEngineM (valueOfInterpretation st $ expression e) engine
return $ either (const Nothing) id rv
runExpression_ :: K3 Expression -> IO ()
runExpression_ e = runExpression e >>= putStrLn . show
{- Distributed program execution -}
-- | Programs prepared for execution as a simulation.
type PreparedProgram = (K3 Declaration, Engine Value, VirtualizedMessageProcessor)
-- | Programs prepared for execution as virtualized network peers.
type PreparedNetwork = (K3 Declaration, [(Address, Engine Value, VirtualizedMessageProcessor)])
-- | Network peer information for a K3 engine running in network mode.
type NetworkPeer = (Address, Engine Value, ThreadId, VirtualizedMessageProcessor)
-- | Single-machine system simulation.
prepareProgram :: PrintConfig -> Bool -> SystemEnvironment -> K3 Declaration
-> IO (Either EngineError PreparedProgram)
prepareProgram pc isPar systemEnv prog =
buildStaticEnv >>= \case
Left err -> return $ Left err
Right sEnv -> do
trigs <- return $ getTriggerIds tProg
engine <- simulationEngine trigs isPar systemEnv $ syntaxValueWD sEnv
msgProc <- virtualizedProcessor pc sEnv
return $ Right (tProg, engine, msgProc)
where buildStaticEnv = do
trigs <- return $ getTriggerIds tProg
sEnv <- emptyStaticEnvIO
preEngine <- simulationEngine trigs isPar systemEnv $ syntaxValueWD sEnv
flip runEngineM preEngine $ staticEnvironment pc tProg
tProg = labelBindAliases prog
runProgram :: PrintConfig -> PreparedProgram -> IO (Either EngineError [NetworkPeer])
runProgram pc (prog, engine, msgProc) = do
eStatus <- runEngineM (runEngine pc msgProc prog) engine
either (return . Left) (const $ peerStatuses) eStatus
where peerStatuses = do
tid <- myThreadId
lastRes <- readMVar (snapshot msgProc)
return . Right $ map (\(addr, _) -> (addr, engine, tid, msgProc)) lastRes
-- | Single-machine network deployment.
-- Takes a system deployment and forks a network engine for each peer.
prepareNetwork :: PrintConfig -> Bool -> SystemEnvironment -> K3 Declaration
-> IO (Either EngineError PreparedNetwork)
prepareNetwork pc isPar systemEnv prog =
let nodeBootstraps = map (:[]) systemEnv in
buildStaticEnv (getTriggerIds tProg) >>= \case
Left err -> return $ Left err
Right sEnv -> do
trigs <- return $ getTriggerIds tProg
engines <- mapM (flip (networkEngine trigs isPar) $ syntaxValueWD sEnv) nodeBootstraps
namedEngines <- return . map pairWithAddress $ zip engines nodeBootstraps
peers <- mapM (preparePeer sEnv) namedEngines
return $ Right (tProg, peers)
where
buildStaticEnv trigs = do
sEnv <- emptyStaticEnvIO
preEngine <- simulationEngine trigs isPar systemEnv $ syntaxValueWD sEnv
flip runEngineM preEngine $ staticEnvironment pc tProg
pairWithAddress (engine, bootstrap) = (fst . head $ bootstrap, engine)
preparePeer staticEnv (addr, engine) =
virtualizedProcessor pc staticEnv >>= return . (addr, engine,)
tProg = labelBindAliases prog
runNetwork :: PrintConfig -> PreparedNetwork -> IO [Either EngineError NetworkPeer]
runNetwork pc (prog, peers) = mapM fork peers
where fork (addr, engine, msgProc) = do
threadId <- flip runEngineM engine $ forkEngine pc msgProc prog
return $ either Left (\tid -> Right (addr, engine, tid, msgProc)) threadId
{- Message processing -}
runTrigger :: Address -> IResult Value -> Identifier -> Value -> Value
-> EngineM Value (IResult Value)
runTrigger addr result nm arg = \case
(VTrigger (_, Just f, _)) -> do
-- Interpret the trigger function and refresh any cached collections in the environment.
((v,st),lg) <- runInterpretation' (getResultState result) (f arg)
st' <- liftIO $ syncIState st
logTriggerM addr nm arg st' (Just v) "AFTER"
return ((v,st'),lg)
(VTrigger _) -> return $ iError ("Uninitialized trigger " ++ nm) Nothing
_ -> return $ tError ("Invalid trigger or sink value for " ++ nm) Nothing
where iError s m = mkError result $ RunTimeInterpretationError s m
tError s m = mkError result $ RunTimeTypeError s m
mkError ((_,st), ilog) v = ((Left v, st), ilog)
-- | Message processing for multiple (virtualized) peers.
type VirtualizedMessageProcessor =
MessageProcessor (K3 Declaration) Value [(Address, IResult Value)] [(Address, IResult Value)]
virtualizedProcessor :: PrintConfig -> SEnvironment Value -> IO VirtualizedMessageProcessor
virtualizedProcessor pc staticEnv = do
snapshotMV <- newEmptyMVar
return $ MessageProcessor {
initialize = initializeVP snapshotMV,
process = processVP snapshotMV,
finalize = finalizeVP snapshotMV,
status = statusVP,
report = reportVP,
snapshot = snapshotMV
}
where
initializeVP snapshotMV program = do
engine <- ask
res <- sequence [initNode node program (deployment engine) | node <- nodes engine]
void $ liftIO $ putMVar snapshotMV res
return res
initNode node program systemEnv = do
initEnv <- return $ maybe [] id $ lookup node systemEnv
initIResult <- initProgram pc initEnv staticEnv program
logIResultM "INIT " (Just node) initIResult
return (node, initIResult)
processVP snapshotMV (addr, name, args) ps = do
res <- fmap snd $ runDispatchT (dispatch addr (\s -> runPeerTrigger s addr name args)) ps
void $ liftIO $ modifyMVar_ snapshotMV $ const $ return res
return res
runPeerTrigger s addr nm arg = do
-- void $ logTriggerM addr nm arg s None "BEFORE"
entryOpt <- liftIO $ lookupEnvIO nm $ getEnv $ getResultState s
vOpt <- liftIO $ valueOfEntryOptIO entryOpt
case vOpt of
Nothing -> return (Just (), unknownTrigger s nm)
Just ft -> fmap (Just (),) $ runTrigger addr s nm arg ft
unknownTrigger ((_,st), ilog) n =
((Left $ RunTimeTypeError ("Unknown trigger " ++ n) Nothing, st), ilog)
-- TODO: Fix status computation to use rest of list.
statusVP [] = Left []
statusVP is@(p:_) = case sStatus p of
Left _ -> Left is
Right _ -> Right is
sStatus (node, res) =
either (const $ Left (node, res)) (const $ Right (node, res)) $ getResultVal res
finalizeVP snapshotMV ps = do
res <- mapM sFinalize ps
void $ liftIO $ modifyMVar_ snapshotMV $ const $ return res
return res
sFinalize (node, res) = do
let (st, val) = (getResultState res, getResultVal res)
res' <- either (const $ return res) (const $ atExitTrigger st) val
return (node, res')
reportVP (Left err) = mapM_ reportNodeIResult err
reportVP (Right res) = mapM_ reportNodeIResult res
reportNodeIResult (addr, r) = do
void $ liftIO (putStrLn ("[" ++ show addr ++ "]"))
void $ prettyIResultM r >>= liftIO . putStr . boxToString . indent 2
-- | Message processing for a single peer.
type SingletonMessageProcessor =
MessageProcessor (K3 Declaration) Value (IResult Value) (IResult Value)
{-
uniProcessor :: PrintConfig -> SEnvironment Value -> IO SingletonMessageProcessor
uniProcessor pc staticEnv = do
snapshotMV <- newEmptyMVar
return $ MessageProcessor {
initialize = initUP snapshotMV,
process = processUP snapshotMV,
finalize = finalizeUP snapshotMV,
status = statusUP,
report = reportUP,
snapshot = snapshotMV
}
where
initUP snapshotMV prog = do
egn <- ask
res <- initProgram pc (uniBootstrap $ deployment egn) staticEnv prog
void $ liftIO $ putMVar snapshotMV res
return res
uniBootstrap [] = []
uniBootstrap ((_,is):_) = is
finalizeUP snapshotMV res = do
void $ liftIO $ modifyMVar_ snapshotMV $ const $ return res
either (\_ -> return res) (\_ -> atExitTrigger $ getResultState res) $ getResultVal res
statusUP res = either (const $ Left res) (const $ Right res) $ getResultVal res
reportUP (Left err) = showIResultM err >>= liftIO . putStr
reportUP (Right res) = showIResultM res >>= liftIO . putStr
processUP snapshotMV (_, n, args) r = do
entryOpt <- liftIO $ lookupEnvIO n $ getEnv $ getResultState r
vOpt <- liftIO $ valueOfEntryOptIO entryOpt
res <- maybe (return $ unknownTrigger r n) (run r n args) vOpt
void $ liftIO $ modifyMVar_ snapshotMV $ const $ return res
return res
run r n args trig = do
void $ logTriggerM defaultAddress n args (getResultState r) Nothing "BEFORE"
result <- runTrigger defaultAddress r n args trig
void $ logTriggerM defaultAddress n args (getResultState result) (Just $ getResultVal result) "AFTER"
return result
unknownTrigger ((_,st), ilog) n = ((Left $ RunTimeTypeError ("Unknown trigger " ++ n) Nothing, st), ilog)
-}
| DaMSL/K3 | src/Language/K3/Interpreter/Context.hs | apache-2.0 | 21,332 | 0 | 19 | 5,012 | 5,720 | 2,876 | 2,844 | 321 | 17 |
{-|
This module exports the underlying Attoparsec row parser. This is helpful if
you want to do some ad-hoc CSV string parsing.
-}
module Data.CSV.Conduit.Parser.Text
( parseCSV
, parseRow
, row
, csv
) where
-------------------------------------------------------------------------------
import Control.Applicative
import Control.Monad (mzero)
import Data.Attoparsec.Text as P hiding (take)
import qualified Data.Attoparsec.Text as T
import Data.Text (Text)
import qualified Data.Text as T
-------------------------------------------------------------------------------
import Data.CSV.Conduit.Types
-------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- | Try to parse given string as CSV
parseCSV :: CSVSettings -> Text -> Either String [Row Text]
parseCSV s = parseOnly $ csv s
------------------------------------------------------------------------------
-- | Try to parse given string as 'Row Text'
parseRow :: CSVSettings -> Text -> Either String (Maybe (Row Text))
parseRow s = parseOnly $ row s
------------------------------------------------------------------------------
-- | Parse CSV
csv :: CSVSettings -> Parser [Row Text]
csv s = do
r <- row s
end <- atEnd
if end
then case r of
Just x -> return [x]
Nothing -> return []
else do
rest <- csv s
return $ case r of
Just x -> x : rest
Nothing -> rest
------------------------------------------------------------------------------
-- | Parse a CSV row
row :: CSVSettings -> Parser (Maybe (Row Text))
row csvs = csvrow csvs <|> badrow
badrow :: Parser (Maybe (Row Text))
badrow = P.takeWhile (not . T.isEndOfLine) *>
(T.endOfLine <|> T.endOfInput) *> return Nothing
csvrow :: CSVSettings -> Parser (Maybe (Row Text))
csvrow c =
let rowbody = (quotedField' <|> field c) `sepBy` T.char (csvSep c)
properrow = rowbody <* (T.endOfLine <|> P.endOfInput)
quotedField' = case csvQuoteChar c of
Nothing -> mzero
Just q' -> try (quotedField q')
in do
res <- properrow
return $ Just res
field :: CSVSettings -> Parser Text
field s = P.takeWhile (isFieldChar s)
isFieldChar :: CSVSettings -> Char -> Bool
isFieldChar s = notInClass xs'
where xs = csvSep s : "\n\r"
xs' = case csvQuoteChar s of
Nothing -> xs
Just x -> x : xs
quotedField :: Char -> Parser Text
quotedField c = do
let quoted = string dbl *> return c
dbl = T.pack [c,c]
_ <- T.char c
f <- many (T.notChar c <|> quoted)
_ <- T.char c
return $ T.pack f
| mohsen3/csv-conduit | src/Data/CSV/Conduit/Parser/Text.hs | bsd-3-clause | 2,758 | 0 | 14 | 645 | 762 | 391 | 371 | 60 | 4 |
import System.Exit (exitFailure)
import Data.List
import Tuura.Concept.STG
import Tuura.Concept.STG.Translation
import Tuura.Plato.Translate.Translation
main :: IO ()
main = do
testDotGOutput
testHandshakeConcept
testOrGateConcept
testTwoAndGates
testTwoDifferentCElements
testBooleanFunctionConcepts
testDotGOutput :: IO ()
testDotGOutput = do
putStrLn "=== testDotGOutput"
assertEq (snd threeSignalsConcept) expected
where
threeSignalsConcept = translate (inputs [a] <> outputs [b] <> internals [c]
<> initialise0 [a, c] <> initialise1 [b]) signs
a = Signal 0
b = Signal 1
c = Signal 2
signs = [a, b, c]
expected = unlines [ ".model out"
, ".inputs A"
, ".outputs B"
, ".internal C"
, ".graph"
, "A0 A+"
, "A+ A1"
, "A1 A-"
, "A- A0"
, "B0 B+"
, "B+ B1"
, "B1 B-"
, "B- B0"
, "C0 C+"
, "C+ C1"
, "C1 C-"
, "C- C0"
, ".marking {A0 B1 C0}"
, ".end"
, ""]
testHandshakeConcept :: IO ()
testHandshakeConcept = do
putStrLn "===testHandshakeConcept"
assertEq (sort (arcs handshakeConcept)) (sort expected)
where
handshakeConcept = inputs[a] <> outputs [b] <> handshake00 a b
expected = [Causality [rise a] (rise b), Causality [rise b] (fall a),
Causality [fall a] (fall b), Causality [fall b] (rise a)]
[a, b] = map Signal [0 .. 1]
testOrGateConcept :: IO ()
testOrGateConcept = do
putStrLn "===testOrGateConcept"
assertEq (sort (arcs orGateConcept)) (sort expected)
where
orGateConcept = inputs [a, b] <> outputs [c]
<> initialise0 [a, b, c] <> orGate a b c
expected = [Causality [rise a, rise b] (rise c),
Causality [fall a] (fall c), Causality [fall b] (fall c)]
[a, b, c] = map Signal [0..2]
testTwoAndGates :: IO ()
testTwoAndGates = do
putStrLn "===testTwoAndGates"
assertEq (sort (arcs twoAndGatesConcept)) (sort expected)
where
twoAndGatesConcept = inputs [a, b, c, d] <> outputs [out]
<> initialise0 [a, b, c, d, out] <> andGate a b out
<> andGate c d out
expected = [Causality [rise a] (rise out), Causality [rise b] (rise out),
Causality [rise c] (rise out), Causality [rise d] (rise out),
Causality [fall a, fall b] (fall out),
Causality [fall c, fall d] (fall out)]
[a, b, c, d, out] = map Signal [0..4]
testTwoDifferentCElements :: IO ()
testTwoDifferentCElements = do
putStrLn "===testTwoDifferentCElements"
assertEq (sort (arcs cElementConcept))
(sort (arcs cElementConceptFromBuffers))
where
cElementConcept = inputs [a, b] <> outputs [c]
<> initialise0 [a, b, c] <> cElement a b c
cElementConceptFromBuffers = inputs [a, b] <> outputs [c]
<> initialise0 [a, b, c] <> buffer a c
<> buffer b c
[a, b, c] = map Signal [0..2]
testBooleanFunctionConcepts :: IO ()
testBooleanFunctionConcepts = do
putStrLn "===testBooleanFunctionConcepts"
assertEq (sort (arcs andGateFunction))
(sort (arcs andGateConcept))
where
andGateFunction = combinationalGate (And (Var x) (Var y)) z
andGateConcept = andGate x y z
[x, y, z] = map Signal [0..2]
assertEq :: (Eq a, Show a) => a -> a -> IO ()
assertEq have need
| need /= have = do
putStrLn $ "--- FAIL:\nneed: " ++ show need
putStrLn $ "have: " ++ show have
exitFailure
| otherwise = putStrLn $ "OK " ++ show need
| tuura/concepts | TransTest.hs | bsd-3-clause | 3,978 | 0 | 14 | 1,408 | 1,363 | 701 | 662 | 98 | 1 |
{-# OPTIONS_HADDOCK hide #-}
module Graphics.Vty.Inline.Unsafe where
import Graphics.Vty
import Data.IORef
import GHC.IO.Handle (hDuplicate)
import System.IO (stdin, stdout, hSetBuffering, BufferMode(NoBuffering))
import System.IO.Unsafe
import System.Posix.IO (handleToFd)
globalVty :: IORef (Maybe Vty)
{-# NOINLINE globalVty #-}
globalVty = unsafePerformIO $ newIORef Nothing
globalOutput :: IORef (Maybe Output)
{-# NOINLINE globalOutput #-}
globalOutput = unsafePerformIO $ newIORef Nothing
mkDupeConfig :: IO Config
mkDupeConfig = do
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
stdinDupe <- hDuplicate stdin >>= handleToFd
stdoutDupe <- hDuplicate stdout >>= handleToFd
return $ defaultConfig { inputFd = Just stdinDupe, outputFd = Just stdoutDupe }
-- | This will create a Vty instance using 'mkVty' and execute an IO
-- action provided that instance. The created Vty instance will be
-- stored to the unsafe 'IORef' 'globalVty'.
--
-- This instance will use duplicates of the stdin and stdout Handles.
withVty :: (Vty -> IO b) -> IO b
withVty f = do
mvty <- readIORef globalVty
vty <- case mvty of
Nothing -> do
vty <- mkDupeConfig >>= mkVty
writeIORef globalVty (Just vty)
return vty
Just vty -> return vty
f vty
withOutput :: (Output -> IO b) -> IO b
withOutput f = do
mout <- readIORef globalOutput
out <- case mout of
Nothing -> do
config <- mappend <$> userConfig <*> mkDupeConfig
out <- outputForConfig config
writeIORef globalOutput (Just out)
return out
Just out -> return out
f out
| jtdaugherty/vty | src/Graphics/Vty/Inline/Unsafe.hs | bsd-3-clause | 1,692 | 0 | 15 | 402 | 439 | 218 | 221 | 42 | 2 |
data Foo = Foo
{ foo :: Int
-- comment
, bar :: Int
}
| ruchee/vimrc | vimfiles/bundle/vim-haskell/tests/indent/test001/expected.hs | mit | 60 | 0 | 8 | 21 | 23 | 14 | 9 | 3 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
-- partain: the failure (crashing) was w/ -prof-auto compilation
module Main where
import Control.Exception (IOException, catch)
xreff :: Int -> [String] -> Table -> Int -> String -> String
xreff cc exs stab lineno [] = display (foldl delete stab exs)
xreff cc exs stab lineno ('\n':cs) = xreff cc exs stab (lineno+1) cs
xreff cc exs stab lineno (c:cs)
= if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') then
case getRestWord cs of
(word, rest) -> if (cc :: Int) == 0
then if stab == stab
then
xreff 1000 exs
(enter lineno stab (c:word)) lineno rest
else error "Force failed?!"
else xreff (cc-1) exs
(enter lineno stab (c:word)) lineno rest
else xreff cc exs stab lineno cs
xref exceptions source = xreff 1000 exceptions ALeaf 1 source
getRestWord [] = ([], [])
getRestWord xs@(x:xs')
| (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z') || (x >= '0' && x <= '9')
= case getRestWord xs' of
(ys,zs) -> if (x >= 'A' && x <= 'Z')
then (toEnum (fromEnum x + (32::Int)):ys, zs)
else (x:ys, zs)
| otherwise
= ([],xs)
data Table = ALeaf | ABranch Table String [Int] Table deriving (Eq)
enter n ALeaf w = ABranch ALeaf w [n] ALeaf
enter n (ABranch l k ns r) w
= if w < k then ABranch (enter n l w) k ns r else
if w > k then ABranch l k ns (enter n r w) else
ABranch l k (n:ns) r
delete ALeaf w = ALeaf
delete (ABranch l k ns r) w
= if w < k then ABranch (delete l w) k ns r else
if w > k then ABranch l k ns (delete r w) else
ABranch l k [] r
display :: Table -> String
display t = display_a t ""
display_a :: Table -> String -> String
display_a ALeaf acc = acc
display_a (ABranch l k ns r) acc
= display_a l (dispLine k ns ++ display_a r acc)
dispLine k [] = ""
dispLine k ns = k ++ ":" ++ dispNos ns ++ "\n"
dispNos :: [Int] -> String
dispNos [] = ""
dispNos (n:ns) = ' ':(show n ++ dispNos ns)
main = do
input <- getContents
exceptions <- catch (readFile "exceptions") (\(e :: IOException) -> return "")
putStr (xref (lines exceptions) input)
{- OLD 1.2:
main = readChan stdin abort (\input ->
readFile "exceptions"
(\errors -> output (xref [] input))
(\exceptions -> output (xref (lines exceptions) input)))
where output s = appendChan stdout s abort done
-}
| urbanslug/ghc | testsuite/tests/programs/jules_xref2/Main.hs | bsd-3-clause | 2,563 | 0 | 15 | 811 | 1,030 | 535 | 495 | 53 | 4 |
{-# LANGUAGE RecordWildCards #-}
module Game
( module Game
, module Game.Types
) where
import Control.Lens ((^.))
import Control.Monad (guard)
import Data.List (find)
import Game.Types
import qualified HttpApp.Model as Model
-- play now mode
findHumanPlayer :: [Player] -> Maybe Player
findHumanPlayer = find (\p -> p ^. plKind == HumanPlayNow)
-- to model
playerToModel
:: Model.GameId
-> Maybe Model.BotKeyId
-> Maybe Model.UserId
-> Player
-> Maybe Model.Player
playerToModel playerFkGame playerFkBotKey playerFkUser Player{..} = do
guard $ case (_plKind, playerFkBotKey, playerFkUser) of
(HumanPlayNow, Nothing, Just _) -> True
(BotUser, Just _, Nothing) -> True
(BotLaplace, Nothing, Nothing) -> True
_ -> False
let playerKey = _plKey
playerVictory = _plVictory
playerAlive = _plAlive
Agent{..} = _plAgent
playerHand = _aHand
playerStack = _aStack
playerBetState = _aBetState
playerHandLimit = _aHandLimit
pure Model.Player{..}
playerFromModel
:: GameKey
-> Model.Player
-> Maybe Player
playerFromModel _plGameKey Model.Player{..} = do
let _plKey = playerKey
_plVictory = playerVictory
_plAlive = playerAlive
_aHand = playerHand
_aStack = playerStack
_aBetState = playerBetState
_aHandLimit = playerHandLimit
_plAgent = Agent{..}
_plKind <- case (playerFkUser, playerFkBotKey) of
(Just _, Nothing) -> Just HumanPlayNow
(Nothing, Just _) -> Just BotUser
(Nothing, Nothing) -> Just BotLaplace
_ -> Nothing
pure Player{..}
gameToModel
:: Model.UserId
-> Game
-> Model.Game
gameToModel gameFkUser Game{..} =
let gameKey = _gKey
gameState = _gState
gamePhase = _gPhase
gameRound = _gRound
gameStartPlayerKey = _gStartPlayer ^. plKey
in Model.Game{..}
gameFromModel
:: [Player]
-> Player
-> Model.Game
-> Game
gameFromModel _gPlayers _gStartPlayer Model.Game{..} =
let _gKey = gameKey
_gState = gameState
_gPhase = gamePhase
_gRound = gameRound
in Game{..}
| rubenmoor/skull | skull-server/src/Game.hs | mit | 2,226 | 0 | 12 | 624 | 620 | 337 | 283 | 73 | 4 |
--------------------------------------------------------------------------
-- Copyright (c) 2007-2010, ETH Zurich.
-- All rights reserved.
--
-- This file is distributed under the terms in the attached LICENSE file.
-- If you do not find this file, copies can be found by writing to:
-- ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
--
-- Default architecture-specific definitions for Barrelfish
--
--------------------------------------------------------------------------
module ArchDefaults where
import Data.List
import HakeTypes
import Path
import qualified Config
commonFlags = [ Str s | s <- [ "-fno-builtin",
"-nostdinc",
"-U__linux__",
"-Ulinux",
"-Wall",
"-Wshadow",
"-Wmissing-declarations",
"-Wmissing-field-initializers",
"-Wredundant-decls",
"-Werror" ] ]
commonCFlags = [ Str s | s <- [ "-std=c99",
"-U__STRICT_ANSI__", -- for newlib headers
"-Wstrict-prototypes",
"-Wold-style-definition",
"-Wmissing-prototypes" ] ]
++ [ ContStr Config.use_fp "-fno-omit-frame-pointer" ""]
commonCxxFlags = [ Str s | s <- [ "-nostdinc++",
"-fexceptions",
"-nodefaultlibs",
"-fasynchronous-unwind-tables",
"-DLIBCXX_CXX_ABI=libcxxabi",
"-I" ] ]
++ [ NoDep SrcTree "src" "/include/cxx" ]
++ [ ContStr Config.use_fp "-fno-omit-frame-pointer" ""]
cFlags = [ Str s | s <- [ "-Wno-packed-bitfield-compat" ] ]
++ commonCFlags
cxxFlags = [ Str s | s <- [ "-Wno-packed-bitfield-compat" ] ]
++ commonCxxFlags
cDefines options = [ Str ("-D"++s) | s <- [ "BARRELFISH", "BF_BINARY_PREFIX=\\\"\\\"" ] ]
++ Config.defines
++ Config.arch_defines options
cStdIncs arch archFamily =
[ NoDep SrcTree "src" "/include",
NoDep SrcTree "src" ("/include/arch" ./. archFamily),
NoDep SrcTree "src" Config.libcInc,
NoDep SrcTree "src" "/include/c",
NoDep SrcTree "src" ("/include/target" ./. archFamily),
NoDep SrcTree "src" Config.lwipxxxInc, -- XXX
NoDep SrcTree "src" Config.lwipInc,
NoDep InstallTree arch "/include",
NoDep SrcTree "src" ".",
NoDep BuildTree arch "." ]
ldFlags arch =
[ Str Config.cOptFlags,
In InstallTree arch "/lib/crt0.o",
In InstallTree arch "/lib/crtbegin.o",
Str "-fno-builtin",
Str "-nostdlib" ]
ldCxxFlags arch =
[ Str Config.cOptFlags,
In InstallTree arch "/lib/crt0.o",
In InstallTree arch "/lib/crtbegin.o",
Str "-fno-builtin",
Str "-nostdlib" ]
-- Libraries that are linked to all applications.
stdLibs arch =
[ In InstallTree arch "/lib/libbarrelfish.a",
In InstallTree arch "/lib/libterm_client.a",
In InstallTree arch "/lib/liboctopus_parser.a", -- XXX: For NS client in libbarrelfish
In InstallTree arch "/errors/errno.o",
In InstallTree arch ("/lib/lib" ++ Config.libc ++ ".a"),
--In InstallTree arch "/lib/libposixcompat.a",
--In InstallTree arch "/lib/libvfs.a",
--In InstallTree arch "/lib/libnfs.a",
--In InstallTree arch "/lib/liblwip.a",
--In InstallTree arch "/lib/libbarrelfish.a",
--In InstallTree arch "/lib/libcontmng.a",
--In InstallTree arch "/lib/libprocon.a",
In InstallTree arch "/lib/crtend.o" ,
In InstallTree arch "/lib/libcollections.a" ]
stdCxxLibs arch =
[ In InstallTree arch "/lib/libcxx.a" ]
++ stdLibs arch
options arch archFamily = Options {
optArch = arch,
optArchFamily = archFamily,
optFlags = cFlags,
optCxxFlags = cxxFlags,
optDefines = [ Str "-DBARRELFISH" ] ++ Config.defines,
optIncludes = cStdIncs arch archFamily,
optDependencies =
[ PreDep InstallTree arch "/include/errors/errno.h",
PreDep InstallTree arch "/include/barrelfish_kpi/capbits.h",
PreDep InstallTree arch "/include/asmoffsets.h",
PreDep InstallTree arch "/include/trace_definitions/trace_defs.h" ],
optLdFlags = ldFlags arch,
optLdCxxFlags = ldCxxFlags arch,
optLibs = stdLibs arch,
optCxxLibs = stdCxxLibs arch,
optInterconnectDrivers = ["lmp", "ump", "multihop"],
optFlounderBackends = ["lmp", "ump", "multihop"],
extraFlags = [],
extraCxxFlags = [],
extraDefines = [],
extraIncludes = [],
extraDependencies = [],
extraLdFlags = [],
optSuffix = []
}
------------------------------------------------------------------------
--
-- Now, commands to actually do something
--
------------------------------------------------------------------------
--
-- C compiler
--
cCompiler arch compiler opts phase src obj =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
deps = (optDependencies opts) ++ (extraDependencies opts)
in
[ Str compiler ] ++ flags ++ [ Str Config.cOptFlags ]
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ [ Str "-o", Out arch obj,
Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src ]
++ deps
--
-- the C preprocessor, like C compiler but with -E
--
cPreprocessor arch compiler opts phase src obj =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
deps = (optDependencies opts) ++ (extraDependencies opts)
cOptFlags = unwords ((words Config.cOptFlags) \\ ["-g"])
in
[ Str compiler ] ++ flags ++ [ Str cOptFlags ]
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ [ Str "-o", Out arch obj,
Str "-E", In (if phase == "src" then SrcTree else BuildTree) phase src ]
++ deps
--
-- C++ compiler
--
cxxCompiler arch cxxcompiler opts phase src obj =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optCxxFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraCxxFlags opts ]
++ [ Str f | f <- extraDefines opts ]
deps = (optDependencies opts) ++ (extraDependencies opts)
in
[ Str cxxcompiler ] ++ flags ++ [ Str Config.cOptFlags ]
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ [ Str "-o", Out arch obj,
Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src ]
++ deps
--
-- Create C file dependencies
--
makeDepend arch compiler opts phase src obj depfile =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
in
[ Str ('@':compiler) ] ++ flags
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ (optDependencies opts) ++ (extraDependencies opts)
++ [ Str "-M -MF",
Out arch depfile,
Str "-MQ", NoDep BuildTree arch obj,
Str "-MQ", NoDep BuildTree arch depfile,
Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src
]
--
-- Create C++ file dependencies
--
makeCxxDepend arch cxxcompiler opts phase src obj depfile =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optCxxFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraCxxFlags opts ]
++ [ Str f | f <- extraDefines opts ]
in
[ Str ('@':cxxcompiler) ] ++ flags
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ (optDependencies opts) ++ (extraDependencies opts)
++ [ Str "-M -MF",
Out arch depfile,
Str "-MQ", NoDep BuildTree arch obj,
Str "-MQ", NoDep BuildTree arch depfile,
Str "-c", In (if phase == "src" then SrcTree else BuildTree) phase src
]
--
-- Compile a C program to assembler
--
cToAssembler :: String -> String -> Options -> String -> String -> String -> String -> [ RuleToken ]
cToAssembler arch compiler opts phase src afile objdepfile =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
deps = [ Dep BuildTree arch objdepfile ] ++ (optDependencies opts) ++ (extraDependencies opts)
in
[ Str compiler ] ++ flags ++ [ Str Config.cOptFlags ]
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ [ Str "-o ", Out arch afile,
Str "-S ", In (if phase == "src" then SrcTree else BuildTree) phase src ]
++ deps
--
-- Assemble an assembly language file
--
assembler :: String -> String -> Options -> String -> String -> [ RuleToken ]
assembler arch compiler opts src obj =
let incls = (optIncludes opts) ++ (extraIncludes opts)
flags = (optFlags opts)
++ (optDefines opts)
++ [ Str f | f <- extraFlags opts ]
++ [ Str f | f <- extraDefines opts ]
deps = (optDependencies opts) ++ (extraDependencies opts)
in
[ Str compiler ] ++ flags ++ [ Str Config.cOptFlags ]
++ concat [ [ NStr "-I", i ] | i <- incls ]
++ [ Str "-o ", Out arch obj, Str "-c ", In SrcTree "src" src ]
++ deps
--
-- Create a library from a set of object files
--
archive :: String -> Options -> [String] -> [String] -> String -> String -> [ RuleToken ]
archive arch opts objs libs name libname =
[ Str "rm -f ", Out arch libname ]
++
[ NL, Str "ar cr ", Out arch libname ]
++
[ In BuildTree arch o | o <- objs ]
++
if libs == [] then []
else (
[ NL, Str ("rm -fr tmp-" ++ arch ++ name ++ "; mkdir tmp-" ++ arch ++ name) ]
++
[ NL, Str ("cd tmp-" ++ arch ++ name ++ "; for i in ") ]
++
[ In BuildTree arch a | a <- libs ]
++
[ Str "; do mkdir `basename $$i`; (cd `basename $$i`; ar x ../../$$i); done" ]
++
[ NL, Str "ar q ", Out arch libname, Str (" tmp-" ++ arch ++ name ++ "/*/*.o") ]
++
[ NL, Str ("rm -fr tmp-" ++ arch ++ name) ]
)
++
[ NL, Str "ranlib ", Out arch libname ]
--
-- Link an executable
--
linker :: String -> String -> Options -> [String] -> [String] -> String -> [RuleToken]
linker arch compiler opts objs libs bin =
[ Str compiler ]
++ (optLdFlags opts)
++
(extraLdFlags opts)
++
[ Str "-o", Out arch bin ]
++
[ In BuildTree arch o | o <- objs ]
++
[ In BuildTree arch l | l <- libs ]
++
(optLibs opts)
--
-- Link an executable
--
cxxlinker :: String -> String -> Options -> [String] -> [String] -> String -> [RuleToken]
cxxlinker arch cxxcompiler opts objs libs bin =
[ Str cxxcompiler ]
++ (optLdCxxFlags opts)
++
(extraLdFlags opts)
++
[ Str "-o", Out arch bin ]
++
[ In BuildTree arch o | o <- objs ]
++
[ In BuildTree arch l | l <- libs ]
++
(optCxxLibs opts)
| utsav2601/cmpe295A | hake/ArchDefaults.hs | mit | 11,997 | 0 | 21 | 3,973 | 3,294 | 1,740 | 1,554 | 236 | 2 |
-----------------------------------------------------------------------------
--
-- Module : Drool.Utils.FeatureExtraction
-- Copyright : Tobias Fuchs
-- License : AllRightsReserved
--
-- Maintainer : twh.fuchs@gmail.com
-- Stability : experimental
-- Portability : POSIX
--
-- |
--
-----------------------------------------------------------------------------
{-# OPTIONS -O2 -Wall #-}
module Drool.Utils.FeatureExtraction (
extractSignalFeatures,
SignalFeatures(..),
SignalFeaturesList(..),
FeatureExtractionSettings(..),
emptyFeatures,
FeatureTarget(..),
featureTargetIndex,
featureTargetFromIndex
) where
import Drool.Utils.SigGen as SigGen ( SValue, SignalGenerator(..) )
data SignalFeatures = SignalFeatures { totalEnergy :: Float,
bassEnergy :: Float }
data FeatureExtractionSettings = FeatureExtractionSettings { maxBeatBand :: Int }
data FeatureTarget = NoTarget | LocalTarget | GlobalTarget | GlobalAndLocalTarget
deriving ( Eq, Show )
newtype SignalFeaturesList = SignalFeaturesList { signalFeaturesList :: [SignalFeatures] }
-- Extract features from given signal, depending on settings of extraction
-- and signal generator.
-- Very simplicistic, just a minimal implementation of the interface.
extractSignalFeatures :: [SValue] -> FeatureExtractionSettings -> SigGen.SignalGenerator -> SignalFeatures
extractSignalFeatures samples settings siggen = SignalFeatures { totalEnergy = tEnergy, bassEnergy = bEnergy }
where tEnergy = realToFrac $ (sum samples) / ( fromIntegral (SigGen.numSamples siggen) )
bEnergy = realToFrac $ (sum $ take nBassSamples samples ) / ( fromIntegral nBassSamples )
nBassSamples = maxBeatBand settings
emptyFeatures :: SignalFeatures
emptyFeatures = SignalFeatures { totalEnergy = 0, bassEnergy = 0 }
featureTargetIndex :: FeatureTarget -> Int
featureTargetIndex target = case target of
NoTarget -> 0
LocalTarget -> 1
GlobalTarget -> 2
GlobalAndLocalTarget -> 3
featureTargetFromIndex :: Int -> FeatureTarget
featureTargetFromIndex idx = case idx of
0 -> NoTarget
1 -> LocalTarget
2 -> GlobalTarget
3 -> GlobalAndLocalTarget
_ -> NoTarget
| fuchsto/drool | src/Drool/Utils/FeatureExtraction.hs | mit | 2,267 | 0 | 12 | 437 | 407 | 243 | 164 | 37 | 5 |
module Foundation where
-- Prelude.
import ClassyPrelude hiding (Handler, keys)
import Control.Lens hiding (scribe)
import Control.Monad.Except (ExceptT (..))
import Control.Monad.Trans.Maybe (MaybeT (MaybeT), runMaybeT)
import qualified Data.ByteString.Char8 as BS8
import Data.Time (NominalDiffTime)
import Database.Persist.Postgresql
import System.Environment (lookupEnv)
-- Logging imports.
import Katip hiding (Environment)
import qualified Katip as K
import Logging
-- Servant and related imports.
import Servant ((:~>) (NT), Handler (Handler))
import Servant.Auth.Server (JWTSettings, ThrowAll(..))
--------------------------------------------------------------------------------
-- | Concrete representation of our app's transformer stack.
type App = AppT IO
-- | Data type representing the most general effects our application should be
-- able to perform.
newtype AppT m a
= AppT
{ unAppT :: ReaderT Ctx m a
} deriving ( Functor, Applicative, Monad
, MonadIO, MonadCatch, MonadThrow
, MonadReader Ctx
)
instance MonadThrow m => ThrowAll (AppT m a) where
throwAll = throwM
-- | Embed a function from some @Ctx@ to an arbitrary monad in @AppT@.
mkAppT :: (Ctx -> m a) -> AppT m a
mkAppT = AppT . ReaderT
-- | Run an 'AppT' using the given 'Ctx'.
runAppT :: Ctx -> AppT m a -> m a
runAppT ctx app = runReaderT (unAppT app) ctx
--------------------------------------------------------------------------------
-- | Read-only configuration information for our application.
data Ctx
= Ctx
{ _connPool :: !ConnectionPool
, _jwtSettings :: !JWTSettings
, _jwtTimeout :: !NominalDiffTime
, _katipLogState :: !LogState
}
-- | Generate lenses for our @Env@.
makeLenses ''Ctx
--------------------------------------------------------------------------------
-- | Implement a @HasLogState@ instance for our @Ctx@ record, allowing the
-- @Katip@ to access the underlying logging context.
instance HasLogState Ctx where
logState = katipLogState
-- | Implement a @Katip@ instance for our @App@ monad.
instance MonadIO m => Katip (AppT m) where
getLogEnv = view lsLogEnv
-- | Implement a @KatipContext@ instance for our @App@ monad.
instance MonadIO m => KatipContext (AppT m) where
getKatipContext = view lsContext
getKatipNamespace = view lsNamespace
--------------------------------------------------------------------------------
-- | Convert our 'App' type to a 'Servant.Handler', for a given 'Ctx'.
appToHandler :: Ctx -> App :~> Handler
appToHandler ctx = NT $ Handler . ExceptT . try . runAppT ctx
--------------------------------------------------------------------------------
-- | Application environment.
data Environment
= Development
| Testing
| Staging
| Production
deriving (Eq, Read, Show)
--------------------------------------------------------------------------------
-- | Given an @Environment@, return a @LogState@ for our application.
makeLogger :: Environment -> IO LogState
makeLogger env = do
let katipEnv = K.Environment $ tshow env
let logLevel = case env of
Production -> InfoS
_ -> DebugS
scribe <- mkHandleScribe ColorIfTerminal stdout logLevel V2
logger <- initLogEnv mempty katipEnv
let logEnv = registerScribe "stdout" scribe logger
pure $ LogState mempty mempty logEnv
--------------------------------------------------------------------------------
-- | Make a Postgresql @ConnectionPool@ for a given environment; logging the
-- events with @Katip@ using the provided @LogState@ context.
makePool :: Environment -> LogState -> IO ConnectionPool
makePool env logger = do
connStr <- getConnStr env
let poolSize = getPoolSize env
let logLoudness = case env of
Testing -> noLogging
_ -> id
runLoggingT logger
$ logLoudness
$ addNamespace "psql"
$ createPostgresqlPool connStr poolSize
-- | Determine the number of connections in our @ConnectionPool@ based on the
-- operating environment.
getPoolSize :: Environment -> Int
getPoolSize Production = 8
getPoolSize _ = 1
-- | Make a @ConnectionString@ from environment variables, throwing an error if
-- any cannot be found.
getConnStr :: Environment -> IO ConnectionString
getConnStr Development
= pure $ "host=localhost port=5432 user=jkachmar password= dbname=macchina"
getConnStr Testing
= pure $ "host=localhost port=5432 user=jkachmar password= dbname=macchina-test"
getConnStr _ = do
maybePool <- runMaybeT $ do
let keys = [ "host="
, " port="
, " user="
, " password="
, " dbname="
]
envs = [ "PGHOST"
, "PGPORT"
, "PGUSER"
, "PGPASS"
, "PGDATABASE"
]
envVars <- traverse (MaybeT . lookupEnv) envs
pure $ mconcat . zipWith (<>) keys $ BS8.pack <$> envVars
case maybePool of
Nothing ->
throwIO $ userError $ "Database configuration not present in environment!"
Just pool -> pure pool
| jkachmar/servant-persistent-realworld | src/Foundation.hs | mit | 5,309 | 0 | 14 | 1,291 | 969 | 527 | 442 | -1 | -1 |
module U.Util.Monoid where
import Data.Foldable (toList)
import Data.List (intersperse)
import Control.Monad (foldM)
-- List.intercalate extended to any monoid
-- "The type that intercalate should have had to begin with."
intercalateMap :: (Foldable t, Monoid a) => a -> (b -> a) -> t b -> a
intercalateMap separator renderer elements =
mconcat $ intersperse separator (renderer <$> toList elements)
fromMaybe :: Monoid a => Maybe a -> a
fromMaybe Nothing = mempty
fromMaybe (Just a) = a
whenM, unlessM :: Monoid a => Bool -> a -> a
whenM True a = a
whenM False _ = mempty
unlessM = whenM . not
isEmpty, nonEmpty :: (Eq a, Monoid a) => a -> Bool
isEmpty a = a == mempty
nonEmpty = not . isEmpty
foldMapM :: (Monad m, Foldable f, Monoid b) => (a -> m b) -> f a -> m b
foldMapM f as = foldM (\b a -> fmap (b <>) (f a)) mempty as
| unisonweb/platform | codebase2/util/U/Util/Monoid.hs | mit | 835 | 0 | 10 | 167 | 343 | 182 | 161 | 19 | 1 |
{-# LANGUAGE OverloadedStrings, CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Web.Twitter.Feed
-- License : MIT (see the file LICENSE)
-- Maintainer : Justin Leitgeb <justin@stackbuilders.com>
--
-- Functions for fetching (and linkifying) timelines of Twitter users.
--
-----------------------------------------------------------------------------
module Web.Twitter.Feed
( timeline
, addLink
, timelineUrl
, sortLinks
) where
import qualified Data.ByteString.Lazy as BS
import Network.HTTP.Conduit
import Network.HTTP.Client.Conduit (defaultManagerSettings)
import Web.Authenticate.OAuth
import Data.Aeson
import Data.List (elemIndices, sort)
import Data.Char (toLower)
import Web.Twitter.Types
-- | Get and decode a user timeline.
timeline :: OAuth -- ^ OAuth client (consumer)
-> Credential -- ^ OAuth credential
-> Int -- ^ Count
-> Bool -- ^ Exclude replies?
-> String -- ^ Screen name
-> IO (Either String [SimpleTweet]) -- ^ Either an error or
-- the list of tweets
timeline oauth credential count excludeReplies username = do
req <- createRequest username count excludeReplies
res <- getResponse oauth credential req
return $
case decodeTweets res of
Left message -> Left message
Right ts -> Right $ map (simplifyTweet . linkifyTweet) ts
createRequest :: String -> Int -> Bool -> IO Request
createRequest username count excludeReplies = parseUrlThrow $ timelineUrl username count excludeReplies
#if (!MIN_VERSION_http_conduit(2,1,11))
where
parseUrlThrow = parseUrl
#endif
getResponse :: OAuth -> Credential -> Request -> IO (Response BS.ByteString)
getResponse oauth credential req = do
m <- newManager defaultManagerSettings
signedreq <- signOAuth oauth credential req
httpLbs signedreq m
decodeTweets :: Response BS.ByteString -> Either String [Tweet]
decodeTweets = eitherDecode . responseBody
-- | Returns the URL for requesting a user timeline.
timelineUrl :: String -- ^ Screen name
-> Int -- ^ Count
-> Bool -- ^ Exclude replies?
-> String -- ^ The URL for requesting the user timeline
timelineUrl user count excludeReplies =
"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" ++
user ++ "&count=" ++ show count ++ "&exclude_replies=" ++
map toLower (show excludeReplies)
linkifyTweet :: Tweet -> Tweet
linkifyTweet tweet = Tweet (processText (text tweet)
(userEntities $ entities tweet)
(urlEntities $ entities tweet)
(mediaEntities $ entities tweet))
(createdAt tweet)
(idStr tweet)
(entities tweet)
processText :: String -> [UserEntity] -> [URLEntity] -> [MediaEntity] -> String
processText message users urls medias = foldr addLink message sortedLinks
where sortedLinks = sortLinks urls users medias
-- | Sort lists of URL, user mention, and media entities.
sortLinks :: [URLEntity] -- ^ A list of URL entities
-> [UserEntity] -- ^ A list of user mention entities
-> [MediaEntity] -- ^ A list of media entities
-> [Link] -- ^ The sorted list of links
sortLinks urls users medias = sort (map makeURLLink urls ++
map makeUserLink users ++
map makeMediaLink medias)
makeURLLink :: URLEntity -> Link
makeURLLink urlEntity = Link x y url
where (x, y) = urlIndices urlEntity
urlText = displayUrl urlEntity
href = urlMessage urlEntity
url = "<a target=\"_blank\" href=\"" ++ href ++ "\">"
++ urlText ++ "</a>"
makeMediaLink :: MediaEntity -> Link
makeMediaLink mediaEntity = Link x y url
where (x, y) = mediaIndices mediaEntity
urlText = displayMediaUrl mediaEntity
href = mediaUrl mediaEntity
url = "<a target=\"_blank\" href=\"" ++ href ++ "\">"
++ urlText ++ "</a>"
makeUserLink :: UserEntity -> Link
makeUserLink userEntity = Link x y mention
where (x, y) = userIndices userEntity
username = screenName userEntity
mention = "<a target=\"_blank\" href=\"//twitter.com/" ++ username
++ "\">@" ++ username ++ "</a>"
simplifyTweet :: Tweet -> SimpleTweet
simplifyTweet tweet =
SimpleTweet { body = text tweet
, tweetId = idStr tweet
, created_at = createdAt tweet }
-- | Add a link to the text of a tweet.
addLink :: Link -- ^ A link
-> String -- ^ The text of a tweet without the link
-> String -- ^ The text of the tweet with the link
addLink (Link 139 140 link) tweet = before ++ " " ++ link ++ after
where before = fst (splitAt (lastBlank tweet) tweet)
after = snd (splitAt 140 tweet)
lastBlank = last . elemIndices ' '
addLink (Link start end link) tweet = before ++ link ++ after
where before = fst (splitAt start tweet)
after = snd (splitAt end tweet)
| stackbuilders/twitter-feed | src/Web/Twitter/Feed.hs | mit | 5,354 | 0 | 14 | 1,570 | 1,130 | 597 | 533 | 98 | 2 |
module TeX.Token
( Token(CharToken, ControlSequence)
, extractChar, extractControlSequence, charCode
)
where
import Data.Char (ord)
import TeX.Category
data Token = CharToken Char Category
| ControlSequence [Char]
deriving (Show, Eq)
extractChar :: Token -> Char
extractChar (CharToken c _) = c
extractChar _ = error "Can't extract character from control sequence"
extractControlSequence :: Token -> [Char]
extractControlSequence (ControlSequence s) = s
extractControlSequence _ = error "Can't extract control sequence from token"
charCode :: Token -> Maybe Integer
charCode (CharToken c _)
| c >= '0' && c <= '9' = Just $ fromIntegral $ (ord c) - (ord '0')
| c >= 'A' && c <= 'F' = Just $ fromIntegral $ (ord c) - (ord 'A')
| otherwise = Nothing
charCode _ = Nothing
| spicyj/tex-parser | src/TeX/Token.hs | mit | 793 | 0 | 10 | 148 | 276 | 145 | 131 | 22 | 1 |
module Main where
import Control.Applicative
import Control.Monad.Fix
data Term
= Number Int
| Boolean Bool
| Ident Int
| Abstr Term
| App Term Term
| AppPrim Prim [Term]
deriving (Eq)
data Prim
= If
| Equal
| Minus
| Multi
deriving (Show, Eq)
fromAbstr :: Term -> Term
fromAbstr (Abstr t) = t
instance Show Term where
show (Number i) = show i
show (Boolean b) = show b
show (Ident i) = "%" ++ show i
show (Abstr t) = "(\\. " ++ show t ++ ")"
show (App t1 t2) = show t1 ++ " " ++ show t2
show (AppPrim If [c, t, e]) =
"if " ++ show c
++ " then " ++ show t
++ " else " ++ show e
show (AppPrim Equal [a, b]) =
show a ++ " = " ++ show b
show (AppPrim Minus [a, b]) =
"(" ++ show a ++ " - " ++ show b ++ ")"
show (AppPrim Multi [a, b]) =
"(" ++ show a ++ " * " ++ show b ++ ")"
shiftBy :: Int -> Int -> Term -> Term
shiftBy n c (Ident i) =
if i < c
then Ident i
else Ident (i + n)
shiftBy n c (Abstr t) =
Abstr (shiftBy n (c + 1) t)
shiftBy n c (App t1 t2) =
App (shiftBy n c t1) (shiftBy n c t2)
shiftBy n c (AppPrim p ts) =
AppPrim p (map (shiftBy n c) ts)
shiftBy n c t = t
shiftUp :: Term -> Term
shiftUp = shiftBy 1 0
shiftDown :: Term -> Term
shiftDown = shiftBy (-1) 0
subtitude :: Int -> Term -> Term -> Term
subtitude a b (Ident x) =
if a == x
then b
else Ident x
subtitude a b (Abstr t) =
Abstr . subtitude (a + 1) (shiftUp b) $ t
subtitude a b (App t1 t2) =
App (subtitude a b t1) (subtitude a b t2)
subtitude a b (AppPrim p ts) =
AppPrim p (map (subtitude a b) ts)
subtitude a b t = t
callByName :: Term -> Maybe Term
callByName (App t1 t2) =
case callByName t1 of
Just t1' -> Just (App t1' t2)
Nothing ->
case t1 of
Abstr _ -> Just (fromAbstr (shiftDown (subtitude (-1) t2 t1)))
_ -> error "not function!"
callByName (AppPrim If [s, t, e]) =
case callByName s of
Nothing ->
case s of
Boolean True -> Just t
Boolean False -> Just e
_ -> error "not boolean!"
Just s' -> Just (AppPrim If [s', t, e])
callByName (AppPrim prim xs) =
case walk xs of
Nothing -> Just (op xs)
Just xs' -> Just (AppPrim prim xs')
where walk (t:ts) =
case callByName t of
Nothing -> (t:) <$> walk ts
Just t' -> Just (t':ts)
walk [] = Nothing
op [Number a, Number b] =
case prim of
Minus -> Number (a - b)
Multi -> Number (a * b)
Equal -> Boolean (a == b)
op [a, b] =
case prim of
Equal -> Boolean (a == b)
_ -> error "not numbers!"
callByName _ = Nothing
bigStep :: (Term -> Maybe Term) -> Term -> Term
bigStep f t = loop t (f t)
where loop a Nothing = a
loop a (Just b) = loop b (f b)
lamY :: Term
lamY =
Abstr (App (Abstr (App (Ident 1) (App (Ident 0) (Ident 0))))
(Abstr (App (Ident 1) (App (Ident 0) (Ident 0)))))
-- Y = \f. (\x. f (x x)) (\x. f (x x))
lamFact :: Term
lamFact =
Abstr (Abstr (AppPrim If [AppPrim Equal [Ident 0, Number 0],
Number 1,
AppPrim Multi [Ident 0,
App (Ident 1)
(AppPrim Minus [Ident 0, Number 1])]]))
-- fact = \self. \x. if x == 0 then 1 else x * self (x-1)
lamProgram :: Term
lamProgram = App (App lamY lamFact) (Number 4)
main :: IO ()
main = flip fix lamProgram $ \self prog -> do
putStrLn . show $ prog
case callByName prog of
Nothing -> return ()
Just prog' -> self prog'
| nicball/playground | NamelessLam.hs | mit | 3,625 | 0 | 19 | 1,221 | 1,699 | 852 | 847 | 121 | 13 |
{-# LANGUAGE OverloadedStrings #-}
-- | \"Low-level\" user administration.
module Imageboard.Moderation.Users
( -- * Creating users
createAdministrator
, createUser
, createAdministrator'
, createUser'
-- * Deactivating users
, deactivateUser
, reactivateUser
-- * Querying users
, findUserById
, findUserByName
-- * Authentication
, getUserFromSession
, logIn
, logOut
-- * Types
, SessionId
, LoginId
, Username
, EmailAddress
, PlainPassword
, User(..)
, Password(..)
, PasswordPlain(..)
-- ** Errors
, CreateUserError(..)
, UpdateUserError(..)
) where
import Control.Monad.Trans.Reader (ask)
import Database.Esqueleto
import Web.Users.Persistent (Persistent(..))
import Web.Users.Types ( CreateUserError(..), UpdateUserError(..), User(..)
, Password(..), PasswordPlain(..), SessionId)
import qualified Web.Users.Types as U
import Imageboard.Database
import Imageboard.Moderation.Capabilities
-------------------------------------------------------------------------------
-- Creating users
type Username = Text
type EmailAddress = Text
type PlainPassword = Text
-- | Create a new user with no capability restrictions.
createAdministrator :: Username -> EmailAddress -> PlainPassword -> SqlPersistT IO (Either CreateUserError LoginId)
createAdministrator username email password = createAdministrator'
User { u_name = username
, u_email = email
, u_password = U.makePassword (PasswordPlain password)
, u_active = True
, u_more = ()
}
-- | Variant of 'createAdministrator' that takes a 'User'.
createAdministrator' :: User () -> SqlPersistT IO (Either CreateUserError LoginId)
createAdministrator' user = do
persistent <- getPersistent
create <- lift $ U.createUser persistent user
case create of
Right loginid -> traverse_ (grantCapability loginid loginid) adminCapabilities
_ -> pure ()
pure create
-- | Create a new user with the given set of capability restrictions.
createUser :: Foldable f => LoginId -> Username -> EmailAddress -> PlainPassword -> f Cap -> SqlPersistT IO (Either CreateUserError LoginId)
createUser actor username email password = createUser' actor
User { u_name = username
, u_email = email
, u_password = U.makePassword (PasswordPlain password)
, u_active = True
, u_more = ()
}
-- | Variant of 'createUser' that takes a 'User'.
createUser' :: Foldable f => LoginId -> User () -> f Cap -> SqlPersistT IO (Either CreateUserError LoginId)
createUser' actor user restrictions = do
persistent <- getPersistent
create <- lift $ U.createUser persistent user
case create of
Right loginid -> traverse_ (grantCapability actor loginid) restrictions
_ -> pure ()
pure create
-------------------------------------------------------------------------------
-- Deactivating users
-- | Deactivate a user. Note that 'authUser' will still
-- succeed after this, all it does is mark the user inactive. Make
-- sure to use 'withAuthUser' and check the active field.
deactivateUser :: LoginId -> SqlPersistT IO (Maybe UpdateUserError)
deactivateUser loginid = do
persistent <- getPersistent
lift $ either Just (const Nothing) <$> U.updateUser persistent loginid (\u -> (u :: User ()) { u_active = False })
-- | Reactivate a user.
reactivateUser :: LoginId -> SqlPersistT IO (Maybe UpdateUserError)
reactivateUser loginid = do
persistent <- getPersistent
lift $ either Just (const Nothing) <$> U.updateUser persistent loginid (\u -> (u :: User ()) { u_active = True })
-------------------------------------------------------------------------------
-- Querying users
-- | Attempt to find a user by ID.
findUserById :: LoginId -> SqlPersistT IO (Maybe (User ()))
findUserById loginid = do
persistent <- getPersistent
lift $ U.getUserById persistent loginid
-- | Attempt to find a user by name.
findUserByName :: Username -> SqlPersistT IO (Maybe LoginId)
findUserByName username = do
persistent <- getPersistent
lift $ U.getUserIdByName persistent username
-------------------------------------------------------------------------------
-- Authentication
-- | Check that a session is valid and that the user is not
-- deactivated. If valid, this will extend the sesison timeout to 24
-- hours from now.
getUserFromSession :: SessionId -> SqlPersistT IO (Maybe LoginId)
getUserFromSession sessid = do
persistent <- getPersistent
lift $ do
verify <- U.verifySession persistent sessid (24 * 60 * 60)
case verify of
Just loginid -> do
user <- U.getUserById persistent loginid
pure $ case (user :: Maybe (User ())) of
Just user'
| u_active user' -> Just loginid
| otherwise -> Nothing
Nothing -> Nothing
Nothing -> pure Nothing
-- | Start a new session for a user, if the credentials are
-- correct.
logIn :: Username -> PlainPassword -> SqlPersistT IO (Maybe SessionId)
logIn username password = do
persistent <- getPersistent
lift $ U.housekeepBackend persistent
sessid <- lift $ U.authUser persistent username (PasswordPlain password) 60
-- If the log in was successful, add to the staff log.
case sessid of
Just sessionid -> do
now <- getCurrentTime
user <- lift $ U.verifySession persistent sessionid 60
case user of
Just loginid -> void $ insert (StaffLog now loginid "logged in")
Nothing -> pure ()
Nothing -> pure ()
pure sessid
-- | Terminate a session, even if it is still valid.
logOut :: SessionId -> SqlPersistT IO ()
logOut sessid = do
persistent <- getPersistent
lift $ U.housekeepBackend persistent
lift $ U.destroySession persistent sessid
-------------------------------------------------------------------------------
-- Utilities
-- | Handle to the user backend.
getPersistent :: SqlPersistT IO Persistent
getPersistent = do
conn <- ask
pure $ Persistent (`runSqlConn` conn)
| barrucadu/nagi | lib/Imageboard/Moderation/Users.hs | mit | 6,012 | 0 | 22 | 1,203 | 1,424 | 745 | 679 | 118 | 3 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings, TupleSections #-}
import Data.Monoid
import qualified Data.Set as S
import Hakyll
import Text.Pandoc.Options
import System.FilePath (takeBaseName, takeDirectory, joinPath, splitPath, replaceExtension)
import Control.Lens hiding (Context)
import Control.Monad
import Data.List
import qualified Data.Map as M
import qualified Data.MultiMap as MM
import Text.Printf
--import qualified Data.Tree as T
import Debug.Trace
import Utilities
import FunTree
import HakyllUtils
import NestedCategories
import TableOfContents
siteURL :: String
siteURL = "http://holdenlee.github.io/notebook"
{-| Main method -}
main :: IO ()
main = hakyll $ do
--IMAGES: copy
match "images/**" $ do
route idRoute
compile copyFileCompiler
--CSS: compress
match ("css/*.css"
.||. "*/css/*.css") $ do
route idRoute
compile compressCssCompiler
--JS: copy
match ("js/*.js"
.||. "*/js/*.js"
.||. "MathJax/config/local/local.js") $ do
route idRoute
compile copyFileCompiler
--TEMPLATES
match "templates/*" $ compile templateCompiler
--TAGS @ http://javran.github.io/posts/2014-03-01-add-tags-to-your-hakyll-blog.html
tags <- buildTags (postPattern .&&. hasNoVersion) (fromCapture "tags/*.html")
tagsRules tags $ \tag pattern -> do
let title = "Posts tagged \"" ++ tag ++ "\""
route idRoute
compile $ do
posts <- recentFirst =<< loadAll pattern
let ctx = constField "title" title <>
listField "posts" postCtx (return posts) <>
basicCtx
makeItem ""
>>= loadAndApplyTemplate "templates/tag.html" ctx
>>= loadAndApplyTemplate "templates/post.html" ctx
>>= loadAndApplyTemplate "templates/default.html" ctx
>>= relativizeUrls
--CATEGORIES (exclude uncategorized items)
(pt, categories) <- makePostTreeAndCategories (postPattern .&&. (complement "posts/*.md") .&&. hasNoVersion) (fromCapture "posts/**/index.html")
--buildNestedCategories (postPattern .&&. (complement "posts/*.md") .&&. hasNoVersion) (fromCapture "posts/**/index.html")
tagsRules categories $ \tag pattern -> do
let title = "Posts in category \"" ++ tag ++ "\""
route idRoute
compile $ do
posts <- recentFirst =<< loadAll pattern
let ctx = constField "title" title <>
listField "posts" postCtx (return posts) <>
basicCtx
makeItem ""
>>= loadAndApplyTemplate "templates/tag.html" ctx
>>= loadAndApplyTemplate "templates/post.html" ctx
>>= loadAndApplyTemplate "templates/default.html" ctx
>>= relativizeUrls
--POSTS
match postPattern $ postRules tags
--TOP-LEVEL PAGES
match "pages/*.md" $ pageRules
--INDEX
match "index.html" $ do
route idRoute
compile $ do
pandocMathCompiler
posts <- recentFirst =<< loadAll (postPattern .&&. hasNoVersion)
let indexCtx =
listField "posts" postCtx (return posts) <>
constField "title" "Research notebook" <>
basicCtx
getResourceBody
>>= applyAsTemplate indexCtx
>>= loadAndApplyTemplate "templates/post.html" indexCtx
>>= loadAndApplyTemplate "templates/default.html" indexCtx
>>= relativizeUrls
--SITEMAP
create ["sitemap.html"] $ do
route idRoute
compile $ do
let mapCtx = constField "title" "Sitemap" <> basicCtx
outline <- compileTree (blankTOCCtx <> postCtx) pt
makeItem outline
>>= loadAndApplyTemplate "templates/post.html" mapCtx
>>= loadAndApplyTemplate "templates/default.html" mapCtx
>>= loadAndApplyTemplate "templates/sitemap.html" mapCtx
>>= relativizeUrls
--TOC for posts
match postPattern $ compileTOCVersion
--FEED
atomCompiler "content" tags
postPattern :: Pattern
postPattern = "posts/**.md"
pageRules :: Rules ()
pageRules = do
route $ takeFileNameRoute "html"
defaultRules postCtx
postRules :: Tags -> Rules ()
postRules tags = do
route $ setExtension "html"
defaultRules (tocCtx <> postCtxWithTags tags <> constField "isPost" "true")
defaultRules :: Context String -> Rules ()
defaultRules ctx = do
compile $ pandocMathCompiler
>>= return . fmap demoteHeaders -- h1 -> h2; h2 -> h3; etc
>>= loadAndApplyTemplate "templates/post.html" ctx
--before applying the website template, save a snapshot to send to Atom feed. saveSnapshot :: String -> Item a -> Compiler (Item a)
>>= saveSnapshot "content"
>>= loadAndApplyTemplate "templates/default.html" ctx
>>= relativizeUrls
{-| Math compiler. See http://jdreaver.com/posts/2014-06-22-math-programming-blog-hakyll.html. -}
pandocMathCompiler =
let mathExtensions = [Ext_tex_math_dollars, Ext_tex_math_double_backslash,
Ext_latex_macros]
defaultExtensions = writerExtensions defaultHakyllWriterOptions
newExtensions = foldr S.insert defaultExtensions mathExtensions
writerOptions = defaultHakyllWriterOptions {
writerReferenceLinks = True,
writerHtml5 = True,
writerHighlight = True,
writerExtensions = newExtensions,
writerHTMLMathMethod = MathJax ""
}
in pandocCompilerWith defaultHakyllReaderOptions writerOptions
--------------------------------------------------------------------------------
basicCtx :: Context String
basicCtx = constField "siteURL" siteURL <> defaultContext
postCtx :: Context String
postCtx =
--"%B %e, %Y" see https://hackage.haskell.org/package/time-1.5.0.1/docs/Data-Time-Format.html for how to format date
dateField "date" "%F" <>
basicCtx
postCtxWithTags :: Tags -> Context String
postCtxWithTags tags = tagsField "tags" tags <>
postCtx
{-| Feed configuration -}
myFeedConfiguration :: FeedConfiguration
myFeedConfiguration = FeedConfiguration
{ feedTitle = "Research Notebook"
, feedDescription = "Holden Lee's Blog"
, feedAuthorName = "Holden Lee"
, feedAuthorEmail = "oldheneel@gmail.com"
, feedRoot = "http://holdenlee.github.io/notebook"
}
{-| Compiler for feed -}
feedCompiler :: [Identifier] -> (FeedConfiguration -> Context String -> [Item String] -> Compiler (Item String)) -> String -> Tags -> Rules ()
feedCompiler li renderer content tags =
create li $ do
route idRoute
compile $ do
let feedCtx = tocCtx <> (postCtxWithTags tags) <>
bodyField "description"
--take 10 most recent posts
posts <- fmap (take 10) . recentFirst =<< loadAllSnapshots (postPattern .&&. hasNoVersion) content
renderer myFeedConfiguration feedCtx posts
{-| Why use Atom? http://nullprogram.com/blog/2013/09/23/ -}
atomCompiler = feedCompiler ["atom.xml"] renderAtom
--rssCompiler = feedCompiler ["rss.xml"] renderRss
| holdenlee/notebook | site.hs | mit | 7,418 | 0 | 22 | 1,957 | 1,405 | 693 | 712 | 147 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Codec.Soten.PostProcess.FlipUVsTest where
import Test.Hspec
import Control.Lens ((&), (^.), (%~), (.~))
import qualified Data.Vector as V
import Linear
import Codec.Soten.PostProcess.FlipUVs
import Codec.Soten.Scene
import Codec.Soten.Scene.Mesh
import Codec.Soten.Scene.Material
validMesh = newMesh & meshTextureCoords .~ V.singleton (V3 1 1 1)
material transform = addProperty newMaterial (MaterialUVTransform transform)
originTransform = newUVTransform
& uvTransformTranslation .~ V2 1 1
& uvRotation .~ 0.5
flippedTransform = newUVTransform
& uvTransformTranslation .~ V2 (-1) (-1)
& uvRotation .~ -0.5
flipUVsTest :: Spec
flipUVsTest =
describe "Flip UVs post process" $
context "Flips" $ do
let scene = newScene
& sceneMeshes .~ V.singleton validMesh
& sceneMaterials .~ V.singleton (material originTransform)
fixedSceneMesh = V.head $ apply scene ^. sceneMeshes
fixedSceneMaterial = V.head $ apply scene ^. sceneMaterials
it "Material" $
(fixedSceneMesh ^. meshTextureCoords) `shouldBe` V.singleton (V3 1 0 1)
it "Adds primitive type triange" $
fixedSceneMaterial `shouldBe` material flippedTransform
| triplepointfive/soten | test/Codec/Soten/PostProcess/FlipUVsTest.hs | mit | 1,258 | 0 | 15 | 250 | 348 | 190 | 158 | 31 | 1 |
module NetHack.Control.ItemListing
(updateInventoryIfNecessary,
itemsOnScreen)
where
import Control.Monad
import Control.Monad.IO.Class(liftIO)
import Data.Maybe(fromJust)
import NetHack.Data.NetHackState
import NetHack.Monad.NHAction
import NetHack.Data.Item
import qualified Data.Map as M
import qualified Terminal.Data as T
import qualified Terminal.Terminal as T
import qualified Regex as R
import NetHack.Control.Screen(isSomewhereOnScreen)
resetInventoryNeedsUpdate :: NHAction Bool
resetInventoryNeedsUpdate = do
ns <- get
let up = inventoryNeedsUpdate ns
putInventoryNeedsUpdateM False
return up
updateInventoryIfNecessary :: NHAction ()
updateInventoryIfNecessary = do
needsUpdate <- resetInventoryNeedsUpdate
when needsUpdate $ do
answer 'i'
emptyInventory <- isSomewhereOnScreen "Not carrying anything."
if emptyInventory
then putInventoryM M.empty
else updateInventoryFromScreen
itemsOnScreen :: (Item -> Bool) -> NHAction (M.Map Char [Item])
itemsOnScreen select = do
t <- getTerminalM
readOutItems select $ detectItemListingPosition t
updateInventoryFromScreen :: NHAction ()
updateInventoryFromScreen = do
t <- getTerminalM
items <- readOutItems never $ detectItemListingPosition t
putInventoryM items
where
never _ = False
readOutItems :: (Item -> Bool) -> (Int, Int, Int) -> NHAction (M.Map Char
[Item])
readOutItems select (xStart, yStart, yEnd) = do
t <- getTerminalM
readOutItem t yStart M.empty
where
readOutItem t y accum
| y > yEnd = return accum
| fromJust $ R.match "^\\((end)\\) " line = do answer ' '
return accum
| fromJust $ R.match "^\\(([0-9]+) of [0-9]+\\) " line =
do answer ' '
let continues = concat
[T.isSomewhereOnScreenPosWithAttributes
"(end) " T.defaultAttributes t,
T.isSomewhereOnScreenPosWithAttributesRegex
"^\\(([0-9]+) of [0-9]+\\) "
T.defaultAttributes t]
if length continues > 0 then readOutItem t yStart accum
else return $ accum
| fromJust $ R.match regex line =
let letter = head line
itemname = fromJust $ (R.match regex line :: Maybe String)
in do let item = canonicalizeItemName itemname
let items = canonicalizeItemToInventory accum letter item
when (select item) $ answer letter
readOutItem t (y+1) items
| otherwise = readOutItem t (y+1) accum
where
regex = "^[a-zA-Z] \\- (.+)$"
line = drop (xStart - 1) $ T.lineAt y t
canonicalizeItemToInventory :: M.Map Char [Item] -> Char -> Item ->
M.Map Char [Item]
canonicalizeItemToInventory map ch item =
M.insertWith (\new old -> new ++ old) ch [item] map
detectItemListingPosition :: T.Terminal -> (Int, Int, Int)
detectItemListingPosition t =
-- We try the most 'reliable' methods first, then trying less reliable
-- ones. For actual inventory screen (from using the 'i' key) there are
-- captions with "Weapons", "Armor" and so on. However, it will end in
-- either "(end) X" or "(x of y)X" where X is the position of the cursor.
case testW "(end) " of
[(x, y)] -> if T.coords t == (x+6,y)
then (x, 1, y)
else detectItemListingPosition2
_ -> detectItemListingPosition2
where
testW =
(\x -> T.isSomewhereOnScreenPosWithAttributes x T.defaultAttributes t)
detectItemListingPosition2 =
-- This one appears in 'i' when there is more than one page of items.
case T.isSomewhereOnScreenPosWithAttributesRegex "^\\(([0-9]+) of [0-9]+\\) "
T.defaultAttributes t of
[(x, y)] -> if snd (T.coords t) == y
then (x, 1, y)
else error $ "Cursor is not where I'd expect it to be in "
++ "item listing."
_ -> error "I could not detect an item listing."
{- Disabled for now; the item listing is different when this happens.
- We'll use different ways to read items.
detectItemListingPosition3 =
-- This appears when : is pressed on top of an item pile.
case testW "Things that are here:" of
[(x, y)] -> (x, 1, snd (T.coords t) - 1)
_ -> error "I could not detect an item listing." -}
| Noeda/Megaman | src/NetHack/Control/ItemListing.hs | mit | 4,569 | 14 | 13 | 1,352 | 1,004 | 523 | 481 | 89 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.