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 -Wall #-}
module ElmFormat.Render.Box where
import Elm.Utils ((|>))
import Box
import ElmVersion (ElmVersion(..))
import AST.V0_16
import qualified AST.Declaration
import qualified AST.Expression
import qualified AST.Module
import qualified AST.Pattern
import qualified AST.Variable
import qualified Cheapskate.Types as Markdown
import qualified Control.Monad as Monad
import qualified Data.Char as Char
import qualified Data.List as List
import qualified Data.Map.Strict as Map
import qualified Data.Maybe as Maybe
import Data.Maybe (fromMaybe, maybeToList)
import qualified Data.Text as Text
import qualified ElmFormat.Render.ElmStructure as ElmStructure
import qualified ElmFormat.Render.Markdown
import qualified ElmFormat.Version
import qualified Parse.Parse as Parse
import qualified Reporting.Annotation as RA
import qualified Reporting.Region as Region
import qualified Reporting.Result as Result
import Text.Printf (printf)
import Util.List
pleaseReport' :: String -> String -> Line
pleaseReport' what details =
keyword $ "<elm-format-short-" ++ ElmFormat.Version.asString ++ ": "++ what ++ ": " ++ details ++ " -- please report this at https://github.com/nukisman/elm-format-short/issues >"
pleaseReport :: String -> String -> Box
pleaseReport what details =
line $ pleaseReport' what details
surround :: Char -> Char -> Box -> Box
surround left right b =
let
left' = punc (left : [])
right' = punc (right : [])
in
case b of
SingleLine b' ->
line $ row [ left', b', right' ]
_ ->
stack1
[ b
|> prefix left'
, line $ right'
]
parens :: Box -> Box
parens = surround '(' ')'
formatBinary :: Bool -> Box -> [ ( Bool, Comments, Box, Box ) ] -> Box
formatBinary multiline left ops =
case ops of
[] ->
left
( isLeftPipe, comments, op, next ) : rest ->
if isLeftPipe then
ElmStructure.forceableSpaceSepOrIndented multiline
(ElmStructure.spaceSepOrStack left $
concat
[ Maybe.maybeToList $ formatComments comments
, [op]
]
)
[formatBinary multiline next rest]
else
formatBinary
multiline
(ElmStructure.forceableSpaceSepOrIndented multiline left [formatCommented' comments id $ ElmStructure.spaceSepOrPrefix op next])
rest
splitWhere :: (a -> Bool) -> [a] -> [[a]]
splitWhere predicate list =
let
merge acc result =
(reverse acc):result
step (acc,result) next =
if predicate next then
([], merge (next:acc) result)
else
(next:acc, result)
in
list
|> foldl step ([],[])
|> uncurry merge
|> dropWhile null
|> reverse
data DeclarationType
= DComment
| DStarter
| DCloser
| DDefinition (Maybe AST.Variable.Ref)
| DDocComment
deriving (Show)
declarationType :: AST.Declaration.Decl -> DeclarationType
declarationType decl =
case decl of
AST.Declaration.Decl adecl ->
case RA.drop adecl of
AST.Declaration.Definition pat _ _ _ ->
case RA.drop pat of
AST.Pattern.VarPattern name ->
DDefinition $ Just $ AST.Variable.VarRef [] name
AST.Pattern.OpPattern name ->
DDefinition $ Just $ AST.Variable.OpRef name
_ ->
DDefinition Nothing
AST.Declaration.Datatype (Commented _ (name, _) _) _ ->
DDefinition $ Just $ AST.Variable.TagRef [] name
AST.Declaration.TypeAlias _ (Commented _ (name, _) _) _ ->
DDefinition $ Just $ AST.Variable.TagRef [] name
AST.Declaration.PortDefinition (Commented _ name _) _ _ ->
DDefinition $ Just $ AST.Variable.VarRef [] name
AST.Declaration.TypeAnnotation (name, _) _ ->
DDefinition $ Just name
AST.Declaration.PortAnnotation (Commented _ name _) _ _ ->
DDefinition $ Just $ AST.Variable.VarRef [] name
AST.Declaration.Fixity _ _ _ _ name ->
DDefinition $ Just name
AST.Declaration.DocComment _ ->
DDocComment
AST.Declaration.BodyComment CommentTrickOpener ->
DStarter
AST.Declaration.BodyComment CommentTrickCloser ->
DCloser
AST.Declaration.BodyComment _ ->
DComment
formatModuleHeader :: ElmVersion -> AST.Module.Module -> Box
formatModuleHeader elmVersion modu =
let
header =
AST.Module.header modu
moduleLine =
case elmVersion of
Elm_0_16 ->
formatModuleLine_0_16 header
Elm_0_17 ->
formatModuleLine elmVersion header
Elm_0_18 ->
formatModuleLine elmVersion header
Elm_0_18_Upgrade ->
formatModuleLine elmVersion header
docs =
fmap (formatModuleDocs elmVersion) $ RA.drop $ AST.Module.docs modu
imports =
formatImports elmVersion modu
mapIf fn m a =
case m of
Just x ->
fn x a
Nothing ->
a
in
moduleLine
|> mapIf (\x -> andThen [ blankLine, x ]) docs
|> (if null imports then id else andThen imports . andThen [blankLine])
|> andThen [ blankLine ]
formatImports :: ElmVersion -> AST.Module.Module -> [Box]
formatImports elmVersion modu =
let
(comments, imports) =
AST.Module.imports modu
in
[ formatComments comments
|> maybeToList
, imports
|> Map.assocs
|> fmap (\(name, (pre, method)) -> formatImport elmVersion ((pre, name), method))
]
|> List.filter (not . List.null)
|> List.intersperse [blankLine]
|> concat
formatModuleLine_0_16 :: AST.Module.Header -> Box
formatModuleLine_0_16 header =
let
elmVersion = Elm_0_16
formatExports =
case AST.Module.exports header of
KeywordCommented _ _ value ->
case formatListing (formatDetailedListing elmVersion) value of
Just listing ->
listing
_ ->
pleaseReport "UNEXPECTED MODULE DECLARATION" "empty listing"
whereClause =
case AST.Module.exports header of
KeywordCommented pre post _ ->
formatCommented (line . keyword) (Commented pre "where" post)
in
case
( formatCommented (line . formatQualifiedUppercaseIdentifier elmVersion) $ AST.Module.name header
, formatExports
, whereClause
)
of
(SingleLine name', SingleLine exports', SingleLine where') ->
line $ row
[ keyword "module"
, space
, name'
, row [ space, exports' ]
, space
, where'
]
(name', exports', _) ->
stack1
[ line $ keyword "module"
, indent $ name'
, indent $ exports'
, indent $ whereClause
]
formatModuleLine :: ElmVersion -> AST.Module.Header -> Box
formatModuleLine elmVersion header =
let
tag =
case AST.Module.srcTag header of
AST.Module.Normal ->
line $ keyword "module"
AST.Module.Port comments ->
ElmStructure.spaceSepOrIndented
(formatTailCommented (line . keyword) ("port", comments))
[ line $ keyword "module" ]
AST.Module.Effect comments ->
ElmStructure.spaceSepOrIndented
(formatTailCommented (line . keyword) ("effect", comments))
[ line $ keyword "module" ]
exports list =
case formatListing (formatDetailedListing elmVersion) $ list of
Just listing ->
listing
_ ->
pleaseReport "UNEXPECTED MODULE DECLARATION" "empty listing"
formatSetting (k, v) =
formatRecordPair elmVersion "=" (line . formatUppercaseIdentifier elmVersion) (k, v, False)
formatSettings settings =
map formatSetting settings
|> ElmStructure.group True "{" "," "}" False
whereClause =
AST.Module.moduleSettings header
|> fmap (formatKeywordCommented "where" formatSettings)
|> fmap (\x -> [x])
|> Maybe.fromMaybe []
exposingClause =
formatKeywordCommented "exposing" exports $ AST.Module.exports header
nameClause = -- todo: contain trailing "exposing -- dsdsd" or "where -- dsdsd"
case
( tag
, formatCommented (line . formatQualifiedUppercaseIdentifier elmVersion) $ AST.Module.name header
)
of
(SingleLine tag', SingleLine name') ->
line $ row
[ tag'
, space
, name'
]
(tag', name') ->
stack1
[ tag'
, indent $ name'
]
in
ElmStructure.spaceSepOrIndented
nameClause
(whereClause ++ [exposingClause])
formatModule :: ElmVersion -> AST.Module.Module -> Box
formatModule elmVersion modu =
let
initialComments' =
case AST.Module.initialComments modu of
[] ->
[]
comments ->
(map formatComment comments)
++ [ blankLine, blankLine ]
in
stack1 $
initialComments'
++ (formatModuleHeader elmVersion modu)
: maybeToList (formatModuleBody 1 elmVersion modu)
formatModuleBody :: Int -> ElmVersion -> AST.Module.Module -> Maybe Box
formatModuleBody linesBetween elmVersion modu =
let
spacer first second =
case (declarationType first, declarationType second) of
(DStarter, _) ->
[]
(_, DCloser) ->
[]
(DComment, DComment) ->
[]
(_, DComment) ->
List.replicate linesBetween blankLine
(DComment, _) ->
List.replicate linesBetween blankLine
(DDocComment, DDefinition _) ->
[]
(DDefinition Nothing, DDefinition (Just _)) ->
List.replicate linesBetween blankLine
(DDefinition _, DStarter) ->
List.replicate linesBetween blankLine
(DDefinition a, DDefinition b) ->
if a == b then
[]
else
List.replicate linesBetween blankLine
(DCloser, _) ->
List.replicate linesBetween blankLine
(_, DDocComment) ->
List.replicate linesBetween blankLine
(DDocComment, DStarter) ->
[]
boxes =
intersperseMap spacer (formatDeclaration elmVersion) $
AST.Module.body modu
in
case boxes of
[] -> Nothing
_ -> Just $ stack1 boxes
formatModuleDocs :: ElmVersion -> Markdown.Blocks -> Box
formatModuleDocs elmVersion blocks =
let
format :: AST.Module.Module -> String
format modu =
let
box =
case
( formatImports elmVersion modu
, formatModuleBody 1 elmVersion modu
)
of
( [], Nothing ) -> Nothing
( imports, Nothing ) -> Just $ stack1 imports
( [], Just body) -> Just body
( imports, Just body ) -> Just $ stack1 (imports ++ [blankLine, body])
in
box
|> fmap (Text.unpack . Box.render)
|> fromMaybe ""
reformat :: String -> Maybe String
reformat source =
source
|> Parse.parseSource
|> Result.toMaybe
|> fmap format
content :: String
content =
ElmFormat.Render.Markdown.formatMarkdown reformat blocks
in
formatDocComment content
formatDocComment :: String -> Box
formatDocComment docs =
case lines docs of
[] ->
line $ row [ punc "{-|", space, punc "-}" ]
(first:[]) ->
stack1
[ line $ row [ punc "{-|", space, literal first ]
, line $ punc "-}"
]
(first:rest) ->
(line $ row [ punc "{-|", space, literal first ])
|> andThen (map (line . literal) rest)
|> andThen [ line $ punc "-}" ]
formatImport :: ElmVersion -> AST.Module.UserImport -> Box
formatImport elmVersion (name, method) =
let
as =
(AST.Module.alias method)
|> fmap (formatImportClause
(Just . line . formatUppercaseIdentifier elmVersion)
"as")
|> Monad.join
(exposingPreKeyword, exposingPostKeywordAndListing)
= AST.Module.exposedVars method
exposing =
formatImportClause
(formatListing (formatDetailedListing elmVersion))
"exposing"
(exposingPreKeyword, exposingPostKeywordAndListing)
formatImportClause :: (a -> Maybe Box) -> String -> (Comments, (Comments, a)) -> Maybe Box
formatImportClause format keyw input =
case
fmap (fmap format) $ input
of
([], ([], Nothing)) ->
Nothing
(preKeyword, (postKeyword, Just listing')) ->
case
( formatHeadCommented (line . keyword) (preKeyword, keyw)
, formatHeadCommented id (postKeyword, listing')
)
of
(SingleLine keyword', SingleLine listing'') ->
Just $ line $ row
[ keyword'
, space
, listing''
]
(keyword', listing'') ->
Just $ stack1
[ keyword'
, indent listing''
]
_ ->
Just $ pleaseReport "UNEXPECTED IMPORT" "import clause comments with no clause"
in
case
( formatHeadCommented (line . formatQualifiedUppercaseIdentifier elmVersion) name
, as
, exposing
)
of
( SingleLine name', Just (SingleLine as'), Just (SingleLine exposing') ) ->
line $ row
[ keyword "import"
, space
, name'
, space
, as'
, space
, exposing'
]
(SingleLine name', Just (SingleLine as'), Nothing) ->
line $ row
[ keyword "import"
, space
, name'
, space
, as'
]
(SingleLine name', Nothing, Just (SingleLine exposing')) ->
line $ row
[ keyword "import"
, space
, name'
, space
, exposing'
]
(SingleLine name', Nothing, Nothing) ->
line $ row
[ keyword "import"
, space
, name'
]
( SingleLine name', Just (SingleLine as'), Just exposing' ) ->
stack1
[ line $ row
[ keyword "import"
, space
, name'
, space
, as'
]
, indent exposing'
]
( SingleLine name', Just as', Just exposing' ) ->
stack1
[ line $ row
[ keyword "import"
, space
, name'
]
, indent as'
, indent exposing'
]
( SingleLine name', Nothing, Just exposing' ) ->
stack1
[ line $ row
[ keyword "import"
, space
, name'
]
, indent exposing'
]
( name', Just as', Just exposing' ) ->
stack1
[ line $ keyword "import"
, indent name'
, indent $ indent as'
, indent $ indent exposing'
]
( name', Nothing, Just exposing' ) ->
stack1
[ line $ keyword "import"
, indent name'
, indent $ indent exposing'
]
( name', Just as', Nothing ) ->
stack1
[ line $ keyword "import"
, indent name'
, indent $ indent as'
]
( name', Nothing, Nothing ) ->
stack1
[ line $ keyword "import"
, indent name'
]
formatListing :: (a -> [Box]) -> AST.Variable.Listing a -> Maybe Box
formatListing format listing =
case listing of
AST.Variable.ClosedListing ->
Nothing
AST.Variable.OpenListing comments ->
Just $ parens $ formatCommented (line . keyword) $ fmap (const "..") comments
AST.Variable.ExplicitListing vars multiline ->
Just $ ElmStructure.group False "(" "," ")" multiline $ format vars
formatDetailedListing :: ElmVersion -> AST.Module.DetailedListing -> [Box]
formatDetailedListing elmVersion listing =
concat
[ formatCommentedMap
(\name () -> AST.Variable.OpValue name)
(formatVarValue elmVersion)
(AST.Module.operators listing)
, formatCommentedMap
(\name (inner, listing) -> AST.Variable.Union (name, inner) listing)
(formatVarValue elmVersion)
(AST.Module.types listing)
, formatCommentedMap
(\name () -> AST.Variable.Value name)
(formatVarValue elmVersion)
(AST.Module.values listing)
]
formatCommentedMap :: (k -> v -> a) -> (a -> Box) -> AST.Variable.CommentedMap k v -> [Box]
formatCommentedMap construct format values =
let
format' (k, Commented pre v post)
= formatCommented format $ Commented pre (construct k v) post
in
values
|> Map.assocs
|> map format'
formatVarValue :: ElmVersion -> AST.Variable.Value -> Box
formatVarValue elmVersion aval =
case aval of
AST.Variable.Value val ->
line $ formatLowercaseIdentifier elmVersion [] val
AST.Variable.OpValue (SymbolIdentifier name) ->
line $ identifier $ "(" ++ name ++ ")"
AST.Variable.Union name listing ->
case
( formatListing
(formatCommentedMap
(\name () -> name)
(line . formatUppercaseIdentifier elmVersion)
)
listing
, formatTailCommented (line . formatUppercaseIdentifier elmVersion) name
, snd name
)
of
(Just (SingleLine listing'), SingleLine name', []) ->
line $ row
[ name'
, listing'
]
(Just (SingleLine listing'), SingleLine name', _) ->
line $ row
[ name'
, space
, listing'
]
(Just listing', name', _) ->
stack1
[ name'
, indent $ listing'
]
(Nothing, name', _) ->
name'
formatDeclaration :: ElmVersion -> AST.Declaration.Decl -> Box
formatDeclaration elmVersion decl =
case decl of
AST.Declaration.DocComment docs ->
formatModuleDocs elmVersion docs
AST.Declaration.BodyComment c ->
formatComment c
AST.Declaration.Decl adecl ->
case RA.drop adecl of
AST.Declaration.Definition name args comments expr ->
formatDefinition elmVersion name args comments expr
AST.Declaration.TypeAnnotation name typ ->
formatTypeAnnotation elmVersion name typ
AST.Declaration.Datatype nameWithArgs tags ->
let
ctor (tag,args') =
case allSingles $ map (formatHeadCommented $ formatType' elmVersion ForCtor) args' of
Right args'' ->
line $ row $ List.intersperse space $ (formatUppercaseIdentifier elmVersion tag):args''
Left [] ->
line $ formatUppercaseIdentifier elmVersion tag
Left args'' ->
stack1
[ line $ formatUppercaseIdentifier elmVersion tag
, stack1 args''
|> indent
]
in
case
formatOpenCommentedList ctor tags
of
[] -> error "List can't be empty"
first:rest ->
case formatCommented (formatNameWithArgs elmVersion) nameWithArgs of
SingleLine nameWithArgs' ->
stack1
[ line $ row
[ keyword "type"
, space
, nameWithArgs'
]
, first
|> prefix (row [punc "=", space])
|> andThen (map (prefix (row [punc "|", space])) rest)
|> indent
]
nameWithArgs' ->
stack1
[ line $ keyword "type"
, indent $ nameWithArgs'
, first
|> prefix (row [punc "=", space])
|> andThen (map (prefix (row [punc "|", space])) rest)
|> indent
]
AST.Declaration.TypeAlias preAlias nameWithArgs typ ->
ElmStructure.definition "=" False
(line $ keyword "type")
[ formatHeadCommented (line . keyword) (preAlias, "alias")
, formatCommented (formatNameWithArgs elmVersion) nameWithArgs
]
(formatHeadCommentedStack (formatType elmVersion) typ)
AST.Declaration.PortAnnotation name typeComments typ ->
ElmStructure.definition ":" False
(line $ keyword "port")
[ formatCommented (line . formatLowercaseIdentifier elmVersion []) name ]
(formatCommented' typeComments (formatType elmVersion) typ)
AST.Declaration.PortDefinition name bodyComments expr ->
ElmStructure.definition "=" False
(line $ keyword "port")
[formatCommented (line . formatLowercaseIdentifier elmVersion []) name]
(formatCommented' bodyComments (formatExpression elmVersion SyntaxSeparated) expr)
AST.Declaration.Fixity assoc precedenceComments precedence nameComments name ->
case
( formatCommented' nameComments (line . formatInfixVar elmVersion) name
, formatCommented' precedenceComments (line . literal . show) precedence
)
of
(SingleLine name', SingleLine precedence') ->
line $ row
[ case assoc of
AST.Declaration.L -> keyword "infixl"
AST.Declaration.R -> keyword "infixr"
AST.Declaration.N -> keyword "infix"
, space
, precedence'
, space
, name'
]
_ ->
pleaseReport "TODO" "multiline fixity declaration"
formatNameWithArgs :: ElmVersion -> (UppercaseIdentifier, [(Comments, LowercaseIdentifier)]) -> Box
formatNameWithArgs elmVersion (name, args) =
case allSingles $ map (formatHeadCommented (line . formatLowercaseIdentifier elmVersion [])) args of
Right args' ->
line $ row $ List.intersperse space $ ((formatUppercaseIdentifier elmVersion name):args')
Left args' ->
stack1 $
[ line $ formatUppercaseIdentifier elmVersion name ]
++ (map indent args')
formatDefinition :: ElmVersion -> AST.Pattern.Pattern
-> [(Comments, AST.Pattern.Pattern)]
-> [Comment]
-> AST.Expression.Expr
-> Box
formatDefinition elmVersion name args comments expr =
let
body =
stack1 $ concat
[ map formatComment comments
, [ formatExpression elmVersion SyntaxSeparated expr ]
]
in
ElmStructure.definition "=" False
(formatPattern elmVersion True name)
(map (\(x,y) -> formatCommented' x (formatPattern elmVersion True) y) args)
body
formatTypeAnnotation :: ElmVersion -> (AST.Variable.Ref, Comments) -> (Comments, Type) -> Box
formatTypeAnnotation elmVersion name typ =
ElmStructure.definition ":" False
(formatTailCommented (line . formatVar elmVersion) name)
[]
(formatHeadCommented (formatType elmVersion) typ)
formatPattern :: ElmVersion -> Bool -> AST.Pattern.Pattern -> Box
formatPattern elmVersion parensRequired apattern =
case RA.drop apattern of
AST.Pattern.Anything ->
line $ keyword "_"
AST.Pattern.UnitPattern comments ->
formatUnit '(' ')' comments
AST.Pattern.Literal lit ->
formatLiteral lit
AST.Pattern.VarPattern var ->
line $ formatLowercaseIdentifier elmVersion [] var
AST.Pattern.OpPattern (SymbolIdentifier name) ->
line $ identifier $ "(" ++ name ++ ")"
AST.Pattern.ConsPattern first rest ->
let
formatRight (preOp, postOp, term, eol) =
( False
, preOp
, line $ punc "::"
, formatCommented
(formatEolCommented $ formatPattern elmVersion True)
(Commented postOp (term, eol) [])
)
in
formatBinary False
(formatEolCommented (formatPattern elmVersion True) first)
(map formatRight rest)
|> if parensRequired then parens else id
AST.Pattern.Data ctor [] ->
line (formatQualifiedUppercaseIdentifier elmVersion ctor)
|>
case (elmVersion, ctor) of
(Elm_0_16, [_]) ->
id
(Elm_0_16, _) ->
if parensRequired then parens else id
_ ->
id
AST.Pattern.Data ctor patterns ->
ElmStructure.application
(FAJoinFirst JoinAll)
(line $ formatQualifiedUppercaseIdentifier elmVersion ctor)
(map (formatHeadCommented $ formatPattern elmVersion True) patterns)
|> if parensRequired then parens else id
AST.Pattern.PatternParens pattern ->
formatCommented (formatPattern elmVersion False) pattern
|> parens
AST.Pattern.Tuple patterns ->
ElmStructure.group True "(" "," ")" False $ map (formatCommented $ formatPattern elmVersion False) patterns
AST.Pattern.EmptyListPattern comments ->
formatUnit '[' ']' comments
AST.Pattern.List patterns ->
ElmStructure.group True "[" "," "]" False $ map (formatCommented $ formatPattern elmVersion False) patterns
AST.Pattern.Record fields ->
ElmStructure.group True "{" "," "}" False $ map (formatCommented $ line . formatLowercaseIdentifier elmVersion []) fields
AST.Pattern.Alias pattern name ->
case
( formatTailCommented (formatPattern elmVersion True) pattern
, formatHeadCommented (line . formatLowercaseIdentifier elmVersion []) name
)
of
(SingleLine pattern', SingleLine name') ->
line $ row
[ pattern'
, space
, keyword "as"
, space
, name'
]
(pattern', name') ->
stack1
[ pattern'
, line $ keyword "as"
, indent name'
]
|> (if parensRequired then parens else id)
formatRecordPair :: ElmVersion -> String -> (v -> Box) -> (Commented LowercaseIdentifier, Commented v, Bool) -> Box
formatRecordPair elmVersion delim formatValue (Commented pre k postK, v, forceMultiline) =
ElmStructure.equalsPair delim forceMultiline
(formatCommented (line . formatLowercaseIdentifier elmVersion []) $ Commented [] k postK)
(formatCommented formatValue v)
|> (\x -> Commented pre x []) |> formatCommented id
formatPair :: (a -> Line) -> String -> (b -> Box) -> Pair a b -> Box
formatPair formatA delim formatB (Pair a b (ForceMultiline forceMultiline)) =
ElmStructure.equalsPair delim forceMultiline
(formatTailCommented (line . formatA) a)
(formatHeadCommented formatB b)
negativeCasePatternWorkaround :: Commented AST.Pattern.Pattern -> Box -> Box
negativeCasePatternWorkaround (Commented _ (RA.A _ pattern) _) =
case pattern of
AST.Pattern.Literal (IntNum i _) | i < 0 -> parens
AST.Pattern.Literal (FloatNum f _) | f < 0 -> parens
_ -> id
data ExpressionContext
= SyntaxSeparated
| InfixSeparated
| SpaceSeparated
| AmbiguousEnd
expressionParens :: ExpressionContext -> ExpressionContext -> Box -> Box
expressionParens inner outer =
case (inner, outer) of
(SpaceSeparated, SpaceSeparated) -> parens
(InfixSeparated, SpaceSeparated) -> parens
(InfixSeparated, InfixSeparated) -> parens
(AmbiguousEnd, SpaceSeparated) -> parens
(AmbiguousEnd, InfixSeparated) -> parens
(InfixSeparated, AmbiguousEnd) -> parens
_ -> id
formatExpression :: ElmVersion -> ExpressionContext -> AST.Expression.Expr -> Box
formatExpression elmVersion context aexpr =
case RA.drop aexpr of
AST.Expression.Literal lit ->
formatLiteral lit
AST.Expression.VarExpr v ->
line $ formatVar elmVersion v
AST.Expression.Range left right multiline ->
case elmVersion of
Elm_0_16 -> formatRange_0_17 elmVersion left right multiline
Elm_0_17 -> formatRange_0_17 elmVersion left right multiline
Elm_0_18 -> formatRange_0_17 elmVersion left right multiline
Elm_0_18_Upgrade -> formatRange_0_18 elmVersion context left right
AST.Expression.ExplicitList exprs trailing multiline ->
formatSequence '[' ',' (Just ']')
(formatExpression elmVersion SyntaxSeparated)
multiline
trailing
exprs
AST.Expression.Binops left ops multiline ->
case elmVersion of
Elm_0_16 -> formatBinops_0_17 elmVersion left ops multiline
Elm_0_17 -> formatBinops_0_17 elmVersion left ops multiline
Elm_0_18 -> formatBinops_0_17 elmVersion left ops multiline
Elm_0_18_Upgrade -> formatBinops_0_18 elmVersion left ops multiline
|> expressionParens InfixSeparated context
AST.Expression.Lambda patterns bodyComments expr multiline ->
case
( multiline
, allSingles $ map (formatCommented (formatPattern elmVersion True) . (\(c,p) -> Commented c p [])) patterns
, bodyComments == []
, formatExpression elmVersion SyntaxSeparated expr
)
of
(False, Right patterns', True, SingleLine expr') ->
line $ row
[ punc "\\"
, row $ List.intersperse space $ patterns'
, space
, punc "->"
, space
, expr'
]
(_, Right patterns', _, expr') ->
stack1
[ line $ row
[ punc "\\"
, row $ List.intersperse space $ patterns'
, space
, punc "->"
]
, indent $ stack1 $
(map formatComment bodyComments)
++ [ expr' ]
]
(_, Left [], _, _) ->
pleaseReport "UNEXPECTED LAMBDA" "no patterns"
(_, Left patterns', _, expr') ->
stack1
[ prefix (punc "\\") $ stack1 patterns'
, line $ punc "->"
, indent $ stack1 $
(map formatComment bodyComments)
++ [ expr' ]
]
|> expressionParens AmbiguousEnd context
AST.Expression.Unary AST.Expression.Negative e ->
prefix (punc "-") $ formatExpression elmVersion SpaceSeparated e -- TODO: This might need something stronger than SpaceSeparated?
AST.Expression.App left args multiline ->
ElmStructure.application
multiline
(formatExpression elmVersion InfixSeparated left)
(map (\(x,y) -> formatCommented' x (formatExpression elmVersion SpaceSeparated) y) args)
|> expressionParens SpaceSeparated context
AST.Expression.If if' elseifs (elsComments, els) ->
let
-- opening key cond =
-- case (key, cond) of
-- (SingleLine key', SingleLine cond') ->
-- line $ row
-- [ key'
-- , space
-- , cond'
-- , space
-- ]
-- (SingleLine key', _) ->
-- prefix (row [key', space]) cond
-- _ ->
-- stack1
-- [ key
-- , cond |> indent
-- ]
opening key cond =
case (key, cond) of
(SingleLine key', SingleLine cond') ->
line $ row
[ key'
, space
, cond'
, space
]
(SingleLine key', _) ->
prefix (row [key', space]) cond
_ ->
stack1
[ key
, cond |> indent
]
formatIf (cond, body) =
stack1
[ opening
(line $ keyword "if")
(formatCommented (formatExpression elmVersion SyntaxSeparated) cond)
, prefix (row [keyword "then", space])
$ formatCommented_ False (formatExpression elmVersion SyntaxSeparated) body
]
formatElseIf (ifComments, (cond, body)) =
let
ifCond =
case (formatHeadCommented id (ifComments, line $ keyword "if")) of
SingleLine key' ->
opening
(line $ row [ keyword "else", space, key' ])
$ formatCommented (formatExpression elmVersion SyntaxSeparated) cond
Stack l1 l2 [] ->
opening
(line $ keyword "else")
$ stack1
[ line l1 -- $ row [l1, keyword "!1"]
, prefix
(row [l2, space])
$ formatCommented (formatExpression elmVersion SyntaxSeparated) cond
]
key' ->
opening
(line $ row [keyword "else", space])
$ stack1
[ key'
, formatCommented (formatExpression elmVersion SyntaxSeparated) cond
]
in
stack1
[ ifCond
, prefix
(row [keyword "then", space])
$ formatCommented_ False (formatExpression elmVersion SyntaxSeparated) body
]
in formatIf if'
|> andThen (map formatElseIf elseifs)
|> andThen
[ prefix
(row [keyword "else", space])
$ formatCommented_ False (formatExpression elmVersion SyntaxSeparated) (Commented elsComments els [])
]
|> expressionParens AmbiguousEnd context
AST.Expression.Let defs bodyComments expr ->
let
spacer first _ =
case first of
AST.Expression.LetDefinition _ _ _ _ ->
[] -- todo: Prepend with blankLine for LetDeclaration only
_ ->
[]
formatDefinition' def =
case def of
AST.Expression.LetDefinition name args comments expr' ->
formatDefinition elmVersion name args comments expr'
AST.Expression.LetAnnotation name typ ->
formatTypeAnnotation elmVersion name typ
AST.Expression.LetComment comment ->
formatComment comment
letBlock :: Box
letBlock =
let letKey :: Line
letKey = keyword "let"
letDefs :: [Box]
letDefs = defs |> intersperseMap spacer formatDefinition'
letDefsNew :: [Box]
letDefsNew = [prefix (row [letKey, space]) (stack1 letDefs)]
in stack1 letDefsNew
inBlock :: Box
inBlock =
let inKey :: Line
inKey = keyword "in"
inDefs :: [Box]
inDefs = (map formatComment bodyComments)
++ [formatExpression elmVersion SyntaxSeparated expr]
inDefsNew :: [Box]
inDefsNew = [prefix (row [inKey, space, space]) (stack1 inDefs)]
in stack1 inDefsNew
in
stack1 [letBlock, inBlock]
|> expressionParens AmbiguousEnd context -- TODO: not tested
AST.Expression.Case (subject,multiline) clauses ->
let
opening =
case
( multiline
, formatCommented (formatExpression elmVersion SyntaxSeparated) subject
)
of
(False, SingleLine subject') ->
line $ row
[ keyword "case"
, space
, subject'
, space
, keyword "of"
]
(_, subject') ->
stack1
[ line $ keyword "case"
, indent subject'
, line $ keyword "of"
]
clause (pat, expr) =
case
( pat
, (formatPattern elmVersion False $ (\(Commented _ x _) -> x) pat)
|> negativeCasePatternWorkaround pat
, formatCommentedStack (formatPattern elmVersion False) pat
|> negativeCasePatternWorkaround pat
, formatHeadCommentedStack (formatExpression elmVersion SyntaxSeparated) expr
)
of
(_, _, SingleLine pat', body') ->
stack1
[ line pat'
, prefix (row [ space, keyword "->", space]) body'
]
(Commented pre _ [], SingleLine pat', _, body') ->
stack1 $
(map formatComment pre)
++ [ line pat'
, prefix (row [ space, keyword "->", space]) body'
]
(_, _, pat', body') ->
stack1 $
[ pat'
, prefix (row [ space, keyword "->", space]) body'
]
in
opening
|> andThen (clauses |> map clause |> map indent)
|> expressionParens AmbiguousEnd context -- TODO: not tested
AST.Expression.Tuple exprs multiline ->
ElmStructure.group True "(" "," ")" multiline $ map (formatCommented (formatExpression elmVersion SyntaxSeparated)) exprs
AST.Expression.TupleFunction n ->
line $ keyword $ "(" ++ (List.replicate (n-1) ',') ++ ")"
AST.Expression.Access expr field ->
formatExpression elmVersion SpaceSeparated expr -- TODO: does this need a different context than SpaceSeparated?
|> addSuffix (row $ [punc ".", formatLowercaseIdentifier elmVersion [] field])
AST.Expression.AccessFunction (LowercaseIdentifier field) ->
line $ identifier $ "." ++ (formatVarName' elmVersion field)
AST.Expression.Record base fields trailing multiline ->
formatRecordLike
(line . formatLowercaseIdentifier elmVersion [])
(formatLowercaseIdentifier elmVersion [])
"="
(formatExpression elmVersion SyntaxSeparated)
base fields trailing multiline
AST.Expression.Parens expr ->
case expr of
Commented [] expr' [] ->
formatExpression elmVersion context expr'
_ ->
formatCommented (formatExpression elmVersion SyntaxSeparated) expr
|> parens
AST.Expression.Unit comments ->
formatUnit '(' ')' comments
AST.Expression.GLShader src ->
line $ row
[ punc "[glsl|"
, literal $ src
, punc "|]"
]
formatRecordLike ::
(base -> Box) -> (key -> Line) -> String -> (value -> Box)
-> Maybe (Commented base) -> Sequence (Pair key value)-> Comments -> ForceMultiline
-> Box
formatRecordLike formatBase formatKey fieldSep formatValue base' fields trailing multiline =
case (base', fields) of
( Just base, pairs' ) ->
ElmStructure.extensionGroup'
((\(ForceMultiline b) -> b) multiline)
(formatCommented formatBase base)
(formatSequence '|' ',' Nothing
(formatPair formatKey fieldSep formatValue)
multiline
trailing
pairs')
( Nothing, pairs' ) ->
formatSequence '{' ',' (Just '}')
(formatPair formatKey fieldSep formatValue)
multiline
trailing
pairs'
formatSequence :: Char -> Char -> Maybe Char -> (a -> Box) -> ForceMultiline -> Comments -> Sequence a -> Box
formatSequence left delim right formatA (ForceMultiline multiline) trailing (first:rest) =
let
formatItem delim (pre, item) =
maybe id (stack' . stack' blankLine) (formatComments pre) $
prefix (row [ punc [delim], space ]) $
formatHeadCommented (formatEolCommented formatA) item
in
ElmStructure.forceableSpaceSepOrStack multiline
(ElmStructure.forceableRowOrStack multiline
(formatItem left first)
(map (formatItem delim) rest)
)
(maybe [] (flip (:) [] . stack' blankLine) (formatComments trailing) ++ (Maybe.maybeToList $ fmap (line . punc . flip (:) []) right))
formatSequence left _ (Just right) _ _ trailing [] =
formatUnit left right trailing
formatSequence left _ Nothing _ _ trailing [] =
formatUnit left ' ' trailing
mapIsLast :: (Bool -> a -> b) -> [a] -> [b]
mapIsLast _ [] = []
mapIsLast f (last:[]) = f True last : []
mapIsLast f (next:rest) = f False next : mapIsLast f rest
formatBinops_0_17 ::
ElmVersion
-> AST.Expression.Expr
-> [(Comments, AST.Variable.Ref, Comments, AST.Expression.Expr)]
-> Bool
-> Box
formatBinops_0_17 elmVersion left ops multiline =
formatBinops_common (,) elmVersion left ops multiline
formatBinops_0_18 ::
ElmVersion
-> AST.Expression.Expr
-> [(Comments, AST.Variable.Ref, Comments, AST.Expression.Expr)]
-> Bool
-> Box
formatBinops_0_18 elmVersion left ops multiline =
formatBinops_common removeBackticks elmVersion left ops multiline
formatBinops_common ::
(AST.Expression.Expr
-> [(Comments, AST.Variable.Ref, Comments, AST.Expression.Expr)]
-> ( AST.Expression.Expr
, [(Comments, AST.Variable.Ref, Comments, AST.Expression.Expr)]
)
)
-> ElmVersion
-> AST.Expression.Expr
-> [(Comments, AST.Variable.Ref, Comments, AST.Expression.Expr)]
-> Bool
-> Box
formatBinops_common transform elmVersion left ops multiline =
let
(left', ops') = transform left ops
formatPair isLast ( po, o, pe, e ) =
let
isLeftPipe =
o == AST.Variable.OpRef (SymbolIdentifier "<|")
formatContext =
if isLeftPipe && isLast
then AmbiguousEnd
else InfixSeparated
in
( isLeftPipe
, po
, (line . formatInfixVar elmVersion) o
, formatCommented' pe (formatExpression elmVersion formatContext) e
)
in
formatBinary
multiline
(formatExpression elmVersion InfixSeparated left')
(mapIsLast formatPair ops')
removeBackticks ::
AST.Expression.Expr
-> [(Comments, AST.Variable.Ref, Comments, AST.Expression.Expr)]
-> (AST.Expression.Expr, [(Comments, AST.Variable.Ref, Comments, AST.Expression.Expr)])
removeBackticks left ops =
case ops of
[] -> (left, ops)
(pre, AST.Variable.VarRef v' v, post, e):rest
| v == LowercaseIdentifier "andThen" || v == LowercaseIdentifier "onError"
->
-- Convert `andThen` to |> andThen
let
e' = noRegion $ AST.Expression.App
(noRegion $ AST.Expression.VarExpr $ AST.Variable.VarRef v' v)
[ (post, e)
]
(FAJoinFirst JoinAll)
(e'', rest') = removeBackticks e' rest
in
(left, (pre, AST.Variable.OpRef $ SymbolIdentifier "|>", [], e''):rest')
(pre, AST.Variable.VarRef v' v, post, e):rest ->
-- Convert other backtick operators to normal function application
removeBackticks
(noRegion $ AST.Expression.App
(noRegion $ AST.Expression.VarExpr $ AST.Variable.VarRef v' v)
[ (pre, left)
, (post, e)
]
(FAJoinFirst JoinAll)
)
rest
(pre, op, post, e):rest ->
-- Preserve symbolic infix operators
let
(e', rest') = removeBackticks e rest
in
(left, (pre, op, post, e'):rest')
formatRange_0_17 :: ElmVersion -> Commented AST.Expression.Expr -> Commented AST.Expression.Expr -> Bool -> Box
formatRange_0_17 elmVersion left right multiline =
case
( multiline
, formatCommented (formatExpression elmVersion SyntaxSeparated) left
, formatCommented (formatExpression elmVersion SyntaxSeparated) right
)
of
(False, SingleLine left', SingleLine right') ->
line $ row
[ punc "["
, left'
, punc ".."
, right'
, punc "]"
]
(_, left', right') ->
stack1
[ line $ punc "["
, indent left'
, line $ punc ".."
, indent right'
, line $ punc "]"
]
nowhere :: Region.Position
nowhere =
Region.Position 0 0
noRegion :: a -> RA.Located a
noRegion =
RA.at nowhere nowhere
formatRange_0_18 :: ElmVersion -> ExpressionContext -> Commented AST.Expression.Expr -> Commented AST.Expression.Expr -> Box
formatRange_0_18 elmVersion context left right =
case (left, right) of
(Commented preLeft left' [], Commented preRight right' []) ->
AST.Expression.App
(noRegion $ AST.Expression.VarExpr $ AST.Variable.VarRef [UppercaseIdentifier "List"] $ LowercaseIdentifier "range")
[ (preLeft, left')
, (preRight, right')
]
(FAJoinFirst JoinAll)
|> noRegion
|> formatExpression elmVersion context
_ ->
AST.Expression.App
(noRegion $ AST.Expression.VarExpr $ AST.Variable.VarRef [UppercaseIdentifier "List"] $ LowercaseIdentifier "range")
[ ([], noRegion $ AST.Expression.Parens left)
, ([], noRegion $ AST.Expression.Parens right)
]
(FAJoinFirst JoinAll)
|> noRegion
|> formatExpression elmVersion context
formatUnit :: Char -> Char -> Comments -> Box
formatUnit left right comments =
case (left, comments) of
(_, []) ->
line $ punc (left : right : [])
('{', (LineComment _):_) ->
surround left right $ prefix space $ stack1 $ map formatComment comments
_ ->
surround left right $
case allSingles $ map formatComment comments of
Right comments' ->
line $ row $ List.intersperse space comments'
Left comments' ->
stack1 comments'
formatComments :: Comments -> Maybe Box
formatComments comments =
case fmap formatComment comments of
[] ->
Nothing
(first:rest) ->
Just $ ElmStructure.spaceSepOrStack first rest
formatCommented_ :: Bool -> (a -> Box) -> Commented a -> Box
formatCommented_ forceMultiline format (Commented pre inner post) =
ElmStructure.forceableSpaceSepOrStack1 forceMultiline $
concat
[ Maybe.maybeToList $ formatComments pre
, [format inner]
, Maybe.maybeToList $ formatComments post
]
formatCommented :: (a -> Box) -> Commented a -> Box
formatCommented =
formatCommented_ False
-- TODO: rename to formatPreCommented
formatHeadCommented :: (a -> Box) -> (Comments, a) -> Box
formatHeadCommented format (pre, inner) =
formatCommented' pre format inner
formatCommented' :: Comments -> (a -> Box) -> a -> Box
formatCommented' pre format inner =
formatCommented format (Commented pre inner [])
formatTailCommented :: (a -> Box) -> (a, Comments) -> Box
formatTailCommented format (inner, post) =
formatCommented format (Commented [] inner post)
formatEolCommented :: (a -> Box) -> WithEol a -> Box
formatEolCommented format (inner, post) =
case (post, format inner) of
(Nothing, box) -> box
(Just eol, SingleLine result) ->
mustBreak $ row [ result, space, punc "--", literal eol ]
(Just eol, box) ->
stack1 [ box, formatComment $ LineComment eol ]
formatCommentedStack :: (a -> Box) -> Commented a -> Box
formatCommentedStack format (Commented pre inner post) =
stack1 $
(map formatComment pre)
++ [ format inner ]
++ (map formatComment post)
formatHeadCommentedStack :: (a -> Box) -> (Comments, a) -> Box
formatHeadCommentedStack format (pre, inner) =
formatCommentedStack format (Commented pre inner [])
formatKeywordCommented :: String -> (a -> Box) -> KeywordCommented a -> Box
formatKeywordCommented word format (KeywordCommented pre post value) =
ElmStructure.spaceSepOrIndented
(formatCommented (line . keyword) (Commented pre word post))
[ format value ]
formatOpenCommentedList :: (a -> Box) -> OpenCommentedList a -> [Box]
formatOpenCommentedList format (OpenCommentedList rest (preLst, lst)) =
(fmap (formatCommented $ formatEolCommented format) rest)
++ [formatCommented (formatEolCommented format) $ Commented preLst lst []]
formatComment :: Comment -> Box
formatComment comment =
case comment of
BlockComment c ->
case c of
[] ->
line $ punc "{- -}"
[l] ->
line $ row
[ punc "{-"
, space
, literal l
, space
, punc "-}"
]
ls ->
stack1
[ prefix
(row [ punc "{-", space ])
(stack1 $ map (line . literal) ls)
, line $ punc "-}"
]
LineComment c ->
mustBreak $ row [ punc "--", literal c ]
CommentTrickOpener ->
mustBreak $ punc "{--}"
CommentTrickCloser ->
mustBreak $ punc "--}"
CommentTrickBlock c ->
mustBreak $ row [ punc "{--", literal c, punc "-}" ]
formatLiteral :: Literal -> Box
formatLiteral lit =
case lit of
IntNum i DecimalInt ->
line $ literal $ show i
IntNum i HexadecimalInt ->
line $ literal $
if i <= 0xFF then
printf "0x%02X" i
else if i <= 0xFFFF then
printf "0x%04X" i
else if i <= 0xFFFFFFFF then
printf "0x%08X" i
else
printf "0x%016X" i
FloatNum f DecimalFloat ->
line $ literal $ printf "%f" f
FloatNum f ExponentFloat ->
line $ literal $ printf "%e" f
Chr c ->
formatString SChar [c]
Str s multi ->
formatString (if multi then SMulti else SString) s
Boolean b ->
line $ literal $ show b
data StringStyle
= SChar
| SString
| SMulti
deriving (Eq)
formatString :: StringStyle -> String -> Box
formatString style s =
case style of
SChar ->
stringBox "\'" id
SString ->
stringBox "\"" id
SMulti ->
stringBox "\"\"\"" escapeMultiQuote
where
stringBox quotes escaper =
line $ row
[ punc quotes
, literal $ escaper $ concatMap fix s
, punc quotes
]
fix c =
if (style == SMulti) && c == '\n' then
[c]
else if c == '\n' then
"\\n"
else if c == '\t' then
"\\t"
else if c == '\\' then
"\\\\"
else if (style == SString) && c == '\"' then
"\\\""
else if (style == SChar) && c == '\'' then
"\\\'"
else if not $ Char.isPrint c then
hex c
else if c == ' ' then
[c]
else if c == '\xA0' then
[c] -- Workaround for https://github.com/elm-lang/elm-compiler/issues/1279
else if Char.isSpace c then
hex c
else
[c]
hex char =
"\\x" ++ (printf fmt $ Char.ord char)
where
fmt =
if Char.ord char <= 0xFF then
"%02X"
else
"%04X"
escapeMultiQuote =
let
step okay quotes remaining =
case remaining of
[] ->
reverse $ (concat $ replicate quotes "\"\\") ++ okay
next : rest ->
if next == '"' then
step okay (quotes + 1) rest
else if quotes >= 3 then
step (next : (concat $ replicate quotes "\"\\") ++ okay) 0 rest
else if quotes > 0 then
step (next : (replicate quotes '"') ++ okay) 0 rest
else
step (next : okay) 0 rest
in
step "" 0
data TypeParensRequired
= ForLambda
| ForCtor
| NotRequired
deriving (Eq)
formatType :: ElmVersion -> Type -> Box
formatType elmVersion =
formatType' elmVersion NotRequired
commaSpace :: Line
commaSpace =
row
[ punc ","
, space
]
formatTypeConstructor :: ElmVersion -> TypeConstructor -> Box
formatTypeConstructor elmVersion ctor =
case ctor of
NamedConstructor name ->
line $ formatQualifiedUppercaseIdentifier elmVersion name
TupleConstructor n ->
line $ keyword $ "(" ++ (List.replicate (n-1) ',') ++ ")"
formatType' :: ElmVersion -> TypeParensRequired -> Type -> Box
formatType' elmVersion requireParens atype =
case RA.drop atype of
UnitType comments ->
formatUnit '(' ')' comments
FunctionType first rest (ForceMultiline forceMultiline) ->
let
formatRight (preOp, postOp, term, eol) =
ElmStructure.forceableSpaceSepOrStack1
False
$ concat
[ Maybe.maybeToList $ formatComments preOp
, [ ElmStructure.prefixOrIndented
(line $ punc "->")
(formatCommented
(formatEolCommented $ formatType' elmVersion ForLambda)
(Commented postOp (term, eol) [])
)
]
]
in
ElmStructure.forceableSpaceSepOrStack
forceMultiline
(formatEolCommented (formatType' elmVersion ForLambda) first)
(map formatRight rest)
|> if requireParens /= NotRequired then parens else id
TypeVariable var ->
line $ identifier $ formatVarName elmVersion var
TypeConstruction ctor args ->
ElmStructure.application
(FAJoinFirst JoinAll)
(formatTypeConstructor elmVersion ctor)
(map (formatHeadCommented $ formatType' elmVersion ForCtor) args)
|> (if args /= [] && requireParens == ForCtor then parens else id)
TypeParens type' ->
parens $ formatCommented (formatType elmVersion) type'
TupleType types ->
ElmStructure.group True "(" "," ")" False (map (formatCommented (formatEolCommented $ formatType elmVersion)) types)
RecordType base fields trailing multiline ->
formatRecordLike
(line . formatLowercaseIdentifier elmVersion [])
(formatLowercaseIdentifier elmVersion [])
":"
(formatType elmVersion)
base fields trailing multiline
formatVar :: ElmVersion -> AST.Variable.Ref -> Line
formatVar elmVersion var =
case var of
AST.Variable.VarRef namespace name ->
formatLowercaseIdentifier elmVersion namespace name
AST.Variable.TagRef namespace name ->
case namespace of
[] -> identifier $ formatVarName'' elmVersion name
_ ->
row
[ formatQualifiedUppercaseIdentifier elmVersion namespace
, punc "."
, identifier $ formatVarName'' elmVersion name
]
AST.Variable.OpRef (SymbolIdentifier name) ->
identifier $ "(" ++ name ++ ")"
formatInfixVar :: ElmVersion -> AST.Variable.Ref -> Line
formatInfixVar elmVersion var =
case var of
AST.Variable.VarRef _ _ ->
row [ punc "`"
, formatVar elmVersion var
, punc "`"
]
AST.Variable.TagRef _ _ ->
row [ punc "`"
, formatVar elmVersion var
, punc "`"
]
AST.Variable.OpRef (SymbolIdentifier name) ->
identifier name
formatLowercaseIdentifier :: ElmVersion -> [UppercaseIdentifier] -> LowercaseIdentifier -> Line
formatLowercaseIdentifier elmVersion namespace (LowercaseIdentifier name) =
case (elmVersion, namespace, name) of
(Elm_0_18_Upgrade, [], "fst") -> identifier "Tuple.first"
(Elm_0_18_Upgrade, [UppercaseIdentifier "Basics"], "fst") -> identifier "Tuple.first"
(Elm_0_18_Upgrade, [], "snd") -> identifier "Tuple.second"
(Elm_0_18_Upgrade, [UppercaseIdentifier "Basics"], "snd") -> identifier "Tuple.second"
(_, [], _) -> identifier $ formatVarName' elmVersion name
_ ->
row
[ formatQualifiedUppercaseIdentifier elmVersion namespace
, punc "."
, identifier $ formatVarName' elmVersion name
]
formatUppercaseIdentifier :: ElmVersion -> UppercaseIdentifier -> Line
formatUppercaseIdentifier elmVersion (UppercaseIdentifier name) =
identifier $ formatVarName' elmVersion name
formatQualifiedUppercaseIdentifier :: ElmVersion -> [UppercaseIdentifier] -> Line
formatQualifiedUppercaseIdentifier elmVersion names =
identifier $ List.intercalate "." $
map (\(UppercaseIdentifier name) -> formatVarName' elmVersion name) names
formatVarName :: ElmVersion -> LowercaseIdentifier -> String
formatVarName elmVersion (LowercaseIdentifier name) =
formatVarName' elmVersion name
formatVarName' :: ElmVersion -> String -> String
formatVarName' elmVersion name =
case elmVersion of
Elm_0_18_Upgrade -> map (\x -> if x == '\'' then '_' else x) name
_ -> name
formatVarName'' :: ElmVersion -> UppercaseIdentifier -> String
formatVarName'' elmVersion (UppercaseIdentifier name) =
formatVarName' elmVersion name
|
nukisman/elm-format-short
|
src/ElmFormat/Render/Box.hs
|
bsd-3-clause
| 64,566
| 0
| 31
| 26,504
| 15,615
| 8,091
| 7,524
| 1,418
| 39
|
module Hugs.Storable where
import Hugs.Prelude
foreign import ccall unsafe "Storable_aux.h" readIntOffPtr :: Ptr Int -> Int -> IO Int
foreign import ccall unsafe "Storable_aux.h" readCharOffPtr :: Ptr Char -> Int -> IO Char
-- foreign import ccall unsafe "Storable_aux.h" readWideCharOffPtr :: Ptr Char -> Int -> IO Char
-- foreign import ccall unsafe "Storable_aux.h" readWordOffPtr :: Ptr Word -> Int -> IO Word
foreign import ccall unsafe "Storable_aux.h" readPtrOffPtr :: Ptr (Ptr a) -> Int -> IO (Ptr a)
foreign import ccall unsafe "Storable_aux.h" readFunPtrOffPtr :: Ptr (FunPtr a) -> Int -> IO (FunPtr a)
foreign import ccall unsafe "Storable_aux.h" readFloatOffPtr :: Ptr Float -> Int -> IO Float
foreign import ccall unsafe "Storable_aux.h" readDoubleOffPtr :: Ptr Double -> Int -> IO Double
foreign import ccall unsafe "Storable_aux.h" readStablePtrOffPtr :: Ptr (StablePtr a) -> Int -> IO (StablePtr a)
foreign import ccall unsafe "Storable_aux.h" readInt8OffPtr :: Ptr Int8 -> Int -> IO Int8
foreign import ccall unsafe "Storable_aux.h" readInt16OffPtr :: Ptr Int16 -> Int -> IO Int16
foreign import ccall unsafe "Storable_aux.h" readInt32OffPtr :: Ptr Int32 -> Int -> IO Int32
foreign import ccall unsafe "Storable_aux.h" readInt64OffPtr :: Ptr Int64 -> Int -> IO Int64
foreign import ccall unsafe "Storable_aux.h" readWord8OffPtr :: Ptr Word8 -> Int -> IO Word8
foreign import ccall unsafe "Storable_aux.h" readWord16OffPtr :: Ptr Word16 -> Int -> IO Word16
foreign import ccall unsafe "Storable_aux.h" readWord32OffPtr :: Ptr Word32 -> Int -> IO Word32
foreign import ccall unsafe "Storable_aux.h" readWord64OffPtr :: Ptr Word64 -> Int -> IO Word64
foreign import ccall unsafe "Storable_aux.h" writeIntOffPtr :: Ptr Int -> Int -> Int -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeCharOffPtr :: Ptr Char -> Int -> Char -> IO ()
-- foreign import ccall unsafe "Storable_aux.h" writeWideCharOffPtr :: Ptr Char -> Int -> Char -> IO ()
-- foreign import ccall unsafe "Storable_aux.h" writeWordOffPtr :: Ptr Word -> Int -> Word -> IO ()
foreign import ccall unsafe "Storable_aux.h" writePtrOffPtr :: Ptr (Ptr a) -> Int -> Ptr a -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeFunPtrOffPtr :: Ptr (FunPtr a) -> Int -> FunPtr a -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeFloatOffPtr :: Ptr Float -> Int -> Float -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeDoubleOffPtr :: Ptr Double -> Int -> Double -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeStablePtrOffPtr :: Ptr (StablePtr a) -> Int -> StablePtr a -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeInt8OffPtr :: Ptr Int8 -> Int -> Int8 -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeInt16OffPtr :: Ptr Int16 -> Int -> Int16 -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeInt32OffPtr :: Ptr Int32 -> Int -> Int32 -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeInt64OffPtr :: Ptr Int64 -> Int -> Int64 -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeWord8OffPtr :: Ptr Word8 -> Int -> Word8 -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeWord16OffPtr :: Ptr Word16 -> Int -> Word16 -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeWord32OffPtr :: Ptr Word32 -> Int -> Word32 -> IO ()
foreign import ccall unsafe "Storable_aux.h" writeWord64OffPtr :: Ptr Word64 -> Int -> Word64 -> IO ()
|
OS2World/DEV-UTIL-HUGS
|
libraries/Hugs/Storable.hs
|
bsd-3-clause
| 3,867
| 0
| 10
| 1,002
| 1,008
| 506
| 502
| 32
| 0
|
-- | A Compiler manages targets and dependencies between targets
--
-- The most distinguishing property of a 'Compiler' is that it is an Arrow. A
-- compiler of the type @Compiler a b@ is simply a compilation phase which takes
-- an @a@ as input, and produces a @b@ as output.
--
-- Compilers are chained using the '>>>' arrow operation. If we have a compiler
--
-- > getResourceString :: Compiler Resource String
--
-- which reads the resource, and a compiler
--
-- > readPage :: Compiler String (Page String)
--
-- we can chain these two compilers to get a
--
-- > (getResourceString >>> readPage) :: Compiler Resource (Page String)
--
-- Most compilers can be created by combining smaller compilers using '>>>'.
--
-- More advanced constructions are also possible using arrow, and sometimes
-- these are needed. For a good introduction to arrow, you can refer to
--
-- <http://en.wikibooks.org/wiki/Haskell/Understanding_arrows>
--
-- A construction worth writing a few paragraphs about here are the 'require'
-- functions. Different variants of this function are exported here, but they
-- all serve more or less the same goal.
--
-- When you use only '>>>' to chain your compilers, you get a linear pipeline --
-- it is not possible to add extra items from other compilers along the way.
-- This is where the 'require' functions come in.
--
-- This function allows you to reference other items, which are then added to
-- the pipeline. Let's look at this crappy ASCII illustration which represents
-- a pretty common scenario:
--
-- > read resource >>> pandoc render >>> layout >>> relativize URL's
-- >
-- > @templates/fancy.html@
--
-- We want to construct a pipeline of compilers to go from our resource to a
-- proper webpage. However, the @layout@ compiler takes more than just the
-- rendered page as input: it needs the @templates/fancy.html@ template as well.
--
-- This is an example of where we need the @require@ function. We can solve
-- this using a construction that looks like:
--
-- > ... >>> pandoc render >>> require >>> layout >>> ...
-- > |
-- > @templates/fancy.html@ ------/
--
-- This illustration can help us understand the type signature of 'require'.
--
-- > require :: (Binary a, Typeable a, Writable a)
-- > => Identifier a
-- > -> (b -> a -> c)
-- > -> Compiler b c
--
-- Let's look at it in detail:
--
-- > (Binary a, Typeable a, Writable a)
--
-- These are constraints for the @a@ type. @a@ (the template) needs to have
-- certain properties for it to be required.
--
-- > Identifier a
--
-- This is simply @templates/fancy.html@: the 'Identifier' of the item we want
-- to 'require', in other words, the name of the item we want to add to the
-- pipeline somehow.
--
-- > (b -> a -> c)
--
-- This is a function given by the user, specifying /how/ the two items shall be
-- merged. @b@ is the output of the previous compiler, and @a@ is the item we
-- just required -- the template. This means @c@ will be the final output of the
-- 'require' combinator.
--
-- > Compiler b c
--
-- Indeed, we have now constructed a compiler which takes a @b@ and produces a
-- @c@. This means that we have a linear pipeline again, thanks to the 'require'
-- function. So, the 'require' function actually helps to reduce to complexity
-- of Hakyll applications!
--
-- Note that require will fetch a previously compiled item: in our example of
-- the type @a@. It is /very/ important that the compiler which produced this
-- value, produced the right type as well!
--
{-# LANGUAGE GeneralizedNewtypeDeriving, ScopedTypeVariables #-}
module Hakyll.Core.Compiler
( Compiler
, runCompiler
, getIdentifier
, getResource
, getRoute
, getRouteFor
, getResourceString
, getResourceLBS
, getResourceWith
, fromDependency
, require_
, require
, requireA
, requireAll_
, requireAll
, requireAllA
, cached
, unsafeCompiler
, traceShowCompiler
, mapCompiler
, timedCompiler
, byPattern
, byExtension
) where
import Prelude hiding ((.), id)
import Control.Arrow ((>>>), (&&&), arr, first)
import Control.Applicative ((<$>))
import Control.Exception (SomeException, handle)
import Control.Monad.Reader (ask)
import Control.Monad.Trans (liftIO)
import Control.Monad.Error (throwError)
import Control.Category (Category, (.), id)
import Data.List (find)
import System.FilePath (takeExtension)
import Data.Binary (Binary)
import Data.Typeable (Typeable)
import Data.ByteString.Lazy (ByteString)
import Hakyll.Core.Identifier
import Hakyll.Core.Identifier.Pattern
import Hakyll.Core.CompiledItem
import Hakyll.Core.Writable
import Hakyll.Core.Resource
import Hakyll.Core.Resource.Provider
import Hakyll.Core.Compiler.Internal
import Hakyll.Core.Store
import Hakyll.Core.Rules.Internal
import Hakyll.Core.Routes
import Hakyll.Core.Logger
-- | Run a compiler, yielding the resulting target and it's dependencies. This
-- version of 'runCompilerJob' also stores the result
--
runCompiler :: Compiler () CompileRule -- ^ Compiler to run
-> Identifier () -- ^ Target identifier
-> ResourceProvider -- ^ Resource provider
-> [Identifier ()] -- ^ Universe
-> Routes -- ^ Route
-> Store -- ^ Store
-> Bool -- ^ Was the resource modified?
-> Logger -- ^ Logger
-> IO (Throwing CompileRule) -- ^ Resulting item
runCompiler compiler id' provider universe routes store modified logger = do
-- Run the compiler job
result <- handle (\(e :: SomeException) -> return $ Left $ show e) $
runCompilerJob compiler id' provider universe routes store modified
logger
-- Inspect the result
case result of
-- In case we compiled an item, we will store a copy in the cache first,
-- before we return control. This makes sure the compiled item can later
-- be accessed by e.g. require.
Right (CompileRule (CompiledItem x)) ->
storeSet store "Hakyll.Core.Compiler.runCompiler"
(castIdentifier id') x
-- Otherwise, we do nothing here
_ -> return ()
return result
-- | Get the identifier of the item that is currently being compiled
--
getIdentifier :: Compiler a (Identifier b)
getIdentifier = fromJob $ const $ CompilerM $
castIdentifier . compilerIdentifier <$> ask
-- | Get the resource that is currently being compiled
--
getResource :: Compiler a Resource
getResource = getIdentifier >>> arr fromIdentifier
-- | Get the route we are using for this item
--
getRoute :: Compiler a (Maybe FilePath)
getRoute = getIdentifier >>> getRouteFor
-- | Get the route for a specified item
--
getRouteFor :: Compiler (Identifier a) (Maybe FilePath)
getRouteFor = fromJob $ \identifier -> CompilerM $ do
routes <- compilerRoutes <$> ask
return $ runRoutes routes identifier
-- | Get the resource we are compiling as a string
--
getResourceString :: Compiler Resource String
getResourceString = getResourceWith resourceString
-- | Get the resource we are compiling as a lazy bytestring
--
getResourceLBS :: Compiler Resource ByteString
getResourceLBS = getResourceWith resourceLBS
-- | Overloadable function for 'getResourceString' and 'getResourceLBS'
--
getResourceWith :: (ResourceProvider -> Resource -> IO a)
-> Compiler Resource a
getResourceWith reader = fromJob $ \r -> CompilerM $ do
let filePath = unResource r
provider <- compilerResourceProvider <$> ask
if resourceExists provider r
then liftIO $ reader provider r
else throwError $ error' filePath
where
error' id' = "Hakyll.Core.Compiler.getResourceWith: resource "
++ show id' ++ " not found"
-- | Auxiliary: get a dependency
--
getDependency :: (Binary a, Writable a, Typeable a)
=> Identifier a -> CompilerM a
getDependency id' = CompilerM $ do
store <- compilerStore <$> ask
result <- liftIO $ storeGet store "Hakyll.Core.Compiler.runCompiler" id'
case result of
NotFound -> throwError notFound
WrongType e r -> throwError $ wrongType e r
Found x -> return x
where
notFound =
"Hakyll.Core.Compiler.getDependency: " ++ show id' ++ " was " ++
"not found in the cache, the cache might be corrupted or " ++
"the item you are referring to might not exist"
wrongType e r =
"Hakyll.Core.Compiler.getDependency: " ++ show id' ++ " was found " ++
"in the cache, but does not have the right type: expected " ++ show e ++
" but got " ++ show r
-- | Variant of 'require' which drops the current value
--
require_ :: (Binary a, Typeable a, Writable a)
=> Identifier a
-> Compiler b a
require_ identifier =
fromDependency identifier >>> fromJob (const $ getDependency identifier)
-- | Require another target. Using this function ensures automatic handling of
-- dependencies
--
require :: (Binary a, Typeable a, Writable a)
=> Identifier a
-> (b -> a -> c)
-> Compiler b c
require identifier = requireA identifier . arr . uncurry
-- | Arrow-based variant of 'require'
--
requireA :: (Binary a, Typeable a, Writable a)
=> Identifier a
-> Compiler (b, a) c
-> Compiler b c
requireA identifier = (id &&& require_ identifier >>>)
-- | Variant of 'requireAll' which drops the current value
--
requireAll_ :: (Binary a, Typeable a, Writable a)
=> Pattern a
-> Compiler b [a]
requireAll_ pattern = fromDependencies (const getDeps) >>> fromJob requireAll_'
where
getDeps = map castIdentifier . filterMatches pattern . map castIdentifier
requireAll_' = const $ CompilerM $ do
deps <- getDeps . compilerUniverse <$> ask
mapM (unCompilerM . getDependency) deps
-- | Require a number of targets. Using this function ensures automatic handling
-- of dependencies
--
requireAll :: (Binary a, Typeable a, Writable a)
=> Pattern a
-> (b -> [a] -> c)
-> Compiler b c
requireAll pattern = requireAllA pattern . arr . uncurry
-- | Arrow-based variant of 'requireAll'
--
requireAllA :: (Binary a, Typeable a, Writable a)
=> Pattern a
-> Compiler (b, [a]) c
-> Compiler b c
requireAllA pattern = (id &&& requireAll_ pattern >>>)
cached :: (Binary a, Typeable a, Writable a)
=> String
-> Compiler Resource a
-> Compiler Resource a
cached name (Compiler d j) = Compiler d $ const $ CompilerM $ do
logger <- compilerLogger <$> ask
identifier <- castIdentifier . compilerIdentifier <$> ask
store <- compilerStore <$> ask
modified <- compilerResourceModified <$> ask
report logger $ "Checking cache: " ++ if modified then "modified" else "OK"
if modified
then do v <- unCompilerM $ j $ fromIdentifier identifier
liftIO $ storeSet store name identifier v
return v
else do v <- liftIO $ storeGet store name identifier
case v of Found v' -> return v'
_ -> throwError error'
where
error' = "Hakyll.Core.Compiler.cached: Cache corrupt!"
-- | Create an unsafe compiler from a function in IO
--
unsafeCompiler :: (a -> IO b) -- ^ Function to lift
-> Compiler a b -- ^ Resulting compiler
unsafeCompiler f = fromJob $ CompilerM . liftIO . f
-- | Compiler for debugging purposes
--
traceShowCompiler :: Show a => Compiler a a
traceShowCompiler = fromJob $ \x -> CompilerM $ do
logger <- compilerLogger <$> ask
report logger $ show x
return x
-- | Map over a compiler
--
mapCompiler :: Compiler a b
-> Compiler [a] [b]
mapCompiler (Compiler d j) = Compiler d $ mapM j
-- | Log and time a compiler
--
timedCompiler :: String -- ^ Message
-> Compiler a b -- ^ Compiler to time
-> Compiler a b -- ^ Resulting compiler
timedCompiler msg (Compiler d j) = Compiler d $ \x -> CompilerM $ do
logger <- compilerLogger <$> ask
timed logger msg $ unCompilerM $ j x
-- | Choose a compiler by identifier
--
-- For example, assume that most content files need to be compiled
-- normally, but a select few need an extra step in the pipeline:
--
-- > compile $ pageCompiler >>> byPattern id
-- > [ ("projects.md", addProjectListCompiler)
-- > , ("sitemap.md", addSiteMapCompiler)
-- > ]
--
byPattern :: Compiler a b -- ^ Default compiler
-> [(Pattern (), Compiler a b)] -- ^ Choices
-> Compiler a b -- ^ Resulting compiler
byPattern defaultCompiler choices = Compiler deps job
where
-- Lookup the compiler, give an error when it is not found
lookup' identifier = maybe defaultCompiler snd $
find (\(p, _) -> matches p identifier) choices
-- Collect the dependencies of the choice
deps = do
identifier <- castIdentifier . dependencyIdentifier <$> ask
compilerDependencies $ lookup' identifier
-- Collect the job of the choice
job x = CompilerM $ do
identifier <- castIdentifier . compilerIdentifier <$> ask
unCompilerM $ compilerJob (lookup' identifier) x
-- | Choose a compiler by extension
--
-- Example:
--
-- > match "css/*" $ do
-- > route $ setExtension "css"
-- > compile $ byExtension (error "Not a (S)CSS file")
-- > [ (".css", compressCssCompiler)
-- > , (".scss", sass)
-- > ]
--
-- This piece of code will select the @compressCssCompiler@ for @.css@ files,
-- and the @sass@ compiler (defined elsewhere) for @.scss@ files.
--
byExtension :: Compiler a b -- ^ Default compiler
-> [(String, Compiler a b)] -- ^ Choices
-> Compiler a b -- ^ Resulting compiler
byExtension defaultCompiler = byPattern defaultCompiler . map (first extPattern)
where
extPattern c = predicate $ (== c) . takeExtension . toFilePath
|
sol/hakyll
|
src/Hakyll/Core/Compiler.hs
|
bsd-3-clause
| 14,153
| 0
| 15
| 3,503
| 2,460
| 1,345
| 1,115
| 195
| 4
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
module Delorean.Duration (
Duration (..)
, durationToSeconds
, renderDuration
, parseDuration
, durationParser
) where
import Data.Attoparsec.Text
import Data.Data (Data)
import Data.String (String)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Typeable (Typeable)
import P
data Duration =
Seconds !Int
| Minutes !Int
| Hours !Int
deriving (Read, Show, Typeable, Data)
instance Eq Duration where
(==) = on (==) durationToSeconds
instance Ord Duration where
compare a b = on compare durationToSeconds a b
instance Monoid Duration where
mempty = Seconds 0
mappend a b = Seconds $ durationToSeconds a + durationToSeconds b
durationToSeconds :: Duration -> Int
durationToSeconds (Seconds n) =
n
durationToSeconds (Minutes n) =
n * 60
durationToSeconds (Hours n) =
n * 60 * 60
renderDuration :: Duration -> Text
renderDuration (Seconds n) =
(T.pack . show) n <> "s"
renderDuration (Minutes n) =
(T.pack . show) n <> "m"
renderDuration (Hours n) =
(T.pack . show) n <> "h"
parseDuration :: Text -> Either String Duration
parseDuration =
parseOnly durationParser
durationParser :: Parser Duration
durationParser =
decimal >>= \n -> choice [
"s" *> pure (Seconds n)
, "m" *> pure (Minutes n)
, "h" *> pure (Hours n)
]
|
ambiata/delorean
|
src/Delorean/Duration.hs
|
bsd-3-clause
| 1,516
| 0
| 12
| 347
| 475
| 254
| 221
| 58
| 1
|
{-# LANGUAGE ForeignFunctionInterface, CPP #-}
-- |
-- Module : Foreign.OpenCL.Bindings.Internal.Finalizers
-- Copyright : (c) 2011, Martin Dybdal
-- License : BSD3
--
-- Maintainer : Martin Dybdal <dybber@dybber.dk>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Foreign.OpenCL.Bindings.Internal.Finalizers (
attachFinalizer, attachRetainFinalizer
)
where
import Foreign.Ptr
import Foreign.C.Types (CInt(..))
import Foreign.ForeignPtr (ForeignPtr)
import Foreign.Concurrent (newForeignPtr)
import Foreign.OpenCL.Bindings.Internal.Types
import Foreign.OpenCL.Bindings.Internal.Logging as Log
attachFinalizer :: Finalizable a => Ptr a -> IO (ForeignPtr a)
attachFinalizer ptr = do
Log.debug $ "Adding finalizer to " ++ (finalizableName ptr)
newForeignPtr ptr (Log.debug ("releasing " ++ (finalizableName ptr)) >> release ptr)
attachRetainFinalizer :: Finalizable a => Ptr a -> IO (ForeignPtr a)
attachRetainFinalizer ptr = retain ptr >> attachFinalizer ptr
class Finalizable a where
finalizableName :: Ptr a -> String
release :: Ptr a -> IO ()
retain :: Ptr a -> IO ClInt
-- Context --
instance Finalizable CContext where
finalizableName _ = "Context"
release ctx = clReleaseContext ctx
retain ctx = clRetainContext ctx
-- CommandQueue --
instance Finalizable CCommandQueue where
finalizableName _ = "CommandQueue"
release queue = clReleaseCommandQueue queue
retain queue = clRetainCommandQueue queue
-- Program --
instance Finalizable CProgram where
finalizableName _ = "Program"
release prog = clReleaseProgram prog
retain prog = clRetainProgram prog
-- Kernel --
instance Finalizable CKernel where
finalizableName _ = "Kernel"
release kernel = clReleaseKernel kernel
retain kernel = clRetainKernel kernel
-- Event --
instance Finalizable CEvent where
finalizableName _ = "Event"
release event = clReleaseEvent event
retain event = clRetainEvent event
foreign import CALLCONV "CL/cl.h clRetainContext" clRetainContext
:: (ClContext -> IO ClInt)
foreign import CALLCONV "CL/cl.h clRetainCommandQueue" clRetainCommandQueue
:: (ClCommandQueue -> IO ClInt)
foreign import CALLCONV "CL/cl.h clRetainProgram" clRetainProgram
:: (ClProgram -> IO ClInt)
foreign import CALLCONV "CL/cl.h clRetainKernel" clRetainKernel
:: (ClKernel -> IO ClInt)
foreign import CALLCONV "CL/cl.h clRetainEvent" clRetainEvent
:: (ClEvent -> IO ClInt)
foreign import CALLCONV "CL/cl.h clReleaseContext" clReleaseContext
:: (ClContext -> IO ())
foreign import CALLCONV "CL/cl.h clReleaseCommandQueue" clReleaseCommandQueue
:: (ClCommandQueue -> IO ())
foreign import CALLCONV "CL/cl.h clReleaseProgram" clReleaseProgram
:: (ClProgram -> IO ())
foreign import CALLCONV "CL/cl.h clReleaseKernel" clReleaseKernel
:: ClKernel -> IO ()
foreign import CALLCONV "CL/cl.h clReleaseEvent" clReleaseEvent
:: (ClEvent -> IO ())
|
HIPERFIT/hopencl
|
Foreign/OpenCL/Bindings/Internal/Finalizers.hs
|
bsd-3-clause
| 2,968
| 11
| 15
| 499
| 717
| 368
| 349
| -1
| -1
|
module Data.Functor.Algebra where
import Control.Monad.Free
class Functor f => Algebra f where
alg :: f a -> a
instance Algebra ((,) e) where
alg (_, a) = a
instance Algebra f => Algebra (Free f) where
alg (Pure a) = a
alg (Free f) = alg (alg f)
|
jwiegley/functors
|
Data/Functor/Algebra.hs
|
bsd-3-clause
| 266
| 0
| 8
| 68
| 130
| 67
| 63
| 9
| 0
|
module Nets.Util.QueueSuite (tests) where
import Test.Framework
import Test.Framework.Providers.HUnit
import qualified Test.HUnit.Base as HU
import Test.Framework.Providers.QuickCheck2
import qualified Nets.Util.Queue as Q
tests :: [Test]
tests =
[
testGroup "Queue suite"
[
testGroup "Dequeue null is nothing" $ hUnitTestToTests dequeueEmptyIsNothing,
testProperty "Enqueue-ing n elements results in queue of length n" queueSize
]
]
dequeueEmptyIsNothing :: HU.Test
dequeueEmptyIsNothing =
"Dequeue null queue is Nothing" HU.~: Q.dequeue (Q.empty :: Q.Queue Int) HU.@=? Nothing
queueSize :: [Int] -> Bool
queueSize xs = Q.length (enqueueList xs) == length xs
-- Helpers
enqueueList :: [Int] -> Q.Queue Int
enqueueList = foldr Q.enqueue Q.empty
|
adelbertc/nets-hs
|
test/Nets/Util/QueueSuite.hs
|
bsd-3-clause
| 814
| 0
| 10
| 165
| 203
| 115
| 88
| 20
| 1
|
module MinIR.Types ( Score
) where
import Numeric.Log
type Score = Log Double
|
bgamari/minir
|
MinIR/Types.hs
|
bsd-3-clause
| 99
| 0
| 5
| 34
| 25
| 15
| 10
| 3
| 0
|
module League.Actions
( module Actions ) where
import League.Actions.Champion as Actions
import League.Actions.Match as Actions
import League.Actions.StaticData as Actions
import League.Actions.Summoner as Actions
|
intolerable/league-of-legends
|
src/League/Actions.hs
|
bsd-3-clause
| 217
| 0
| 4
| 26
| 44
| 32
| 12
| 6
| 0
|
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
module BSP
( Process
, Step
-- run
-- , read -- TODO: change names to not conflict with prelude
, step
-- , peerId
-- , thisId
-- , write
) where
import BSP.Util.CountDown
import BSP.Util.InitOnce
import Control.Category
import Control.Monad
import Control.Monad.Fix
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Data.IORef
import Prelude hiding (read, (.))
-- Предположения для структуры данных для шага.
-- 1. Будет производиться много записей в shared state пира с разрешением по id,
-- операция записи должна производится максимально быстро.
-- 2. Будет мало шагов и мало пиров внутри шага, скорость перехода от шага к шагу
-- не критична.
-- Исходя из этого:
-- 1. Можно строить специализированные структуры данных для выполнения шага.
-- 2. Комбинация двух шагов шагом не является, построение для неё специализированной
-- структуры смысла не имеет.
-- 3. Переиспользовать нитки или вызывать forkIO на каждом шаге - не критично.
-- Проблемы:
-- 1. Нужно уметь восстанавливать исходную структуру из массива.
-- Решение:
-- Для этого можно использовать исходную структуру при условии что она Traversable.
-- 2. Использовать fmap и zip (zip может быть неестественным для шардов)
-- 3. Чистый fmap. Единственная проблема с восстановлением структуры в том, что её
-- ноды имеют рекурсивные ссылки на саму структуру. Это решается через fix.
-- _peers можно вообще вынести за пределы структуры и фмапнуть отдельно.
data PeerState t i o = PeerState
{ _currentState :: !i
, _sharedState :: !(t (IORef o))
}
newtype Step t i o r = Step { unStep :: ReaderT (PeerState t i o) IO r }
deriving (Functor, Applicative, Monad, MonadIO)
runStep :: ( Traversable t, Monoid o ) => (a -> Step t i o r) -> t (i, a) -> IO (t (o, r))
runStep step t = do
counter <- newCountDown $ length t
mfix $ \s -> forM t $ \(i, a) -> do
let peerState = PeerState i s
runReaderT (unStep $ step a) peerState
newIORef mempty
return undefined
type family Fst a where Fst (a, b) = a
type family Snd a where Snd (a, b) = b
-- IO нужна для создания примитивов синхронизации, используемых процессом.
data Process (t :: * -> *) a b = Process { unProcess :: IO (Snd a -> Step t (Fst a) (Fst b) (Snd b)) }
step :: (a -> Step t i o r) -> Process t (i, a) (o, r)
step = Process . return
data SyncPoint t a i o r = SyncPoint
{ _firstStep :: a -> Step t i o r
}
instance Category (Process t) where
id = Process $ return return
f . g = Process $ do
syncPointOnce <- newInitOnce
return $ \a -> do
syncPoint <- liftIO $ getInitOnce syncPointOnce $ do
firstStep <- unProcess g
return SyncPoint
{ _firstStep = firstStep
}
let process = _firstStep syncPoint a
undefined
|
schernichkin/BSPM
|
bsp/src/BSP.hs
|
bsd-3-clause
| 3,924
| 0
| 19
| 791
| 676
| 380
| 296
| 52
| 1
|
import qualified Data.Text as T
import Data.Binary
import Data.Hashable (Hashable)
import Data.List (foldl')
import Data.Text.Binary
import System.Environment (getArgs)
import Data.Function (on)
import MinIR.SequentialDependence as SD
import MinIR.Dictionary as D
import MinIR.Types
import Types
import NLP.Stemmer
main = do
terms <- getArgs
idx <- decodeFile "index" :: IO (SeqDepIndex T.Text T.Text)
--termDict <- decodeFile "terms.dict" :: IO (SeqDepIndex Doc Term)
--let terms' = D.lookupTerm key
mapM_ print $ maxN (compare `on` snd) 20
$ scoreTerms defaultParams idx $ map T.pack $ stemWords English terms
maxN :: (a -> a -> Ordering) -> Int -> [a] -> [a]
maxN f n = foldl' go []
where go xs x = let (as,bs) = break (\y->f x y == GT) xs
in take n $ as++[x]++bs
|
bgamari/minir
|
tools/Query.hs
|
bsd-3-clause
| 826
| 0
| 15
| 182
| 301
| 162
| 139
| 21
| 1
|
-- Compile this with 'ghc -o Game Game.hs' and run it with './Game'.
{-# LANGUAGE RecordWildCards #-}
import Graphics.Gloss.Game
import QuadTree
import Tiles
import Debug.Trace
import Control.Exception.Base (assert)
-- A sprite representing our character
slimeSprite :: Picture
slimeSprite = bmp "Slime.bmp"
grassSprite :: Picture
grassSprite = bmp "Grass.bmp"
waterSprite :: Picture
waterSprite = bmp "Water.bmp"
-- Our game world consists purely of the location of our character.
-- data World = World Point
data World = World {
playerPos :: Point,
tiles :: QuadTree TileContent
}
data TileContent = Grass | Rock | Water | Empty deriving Show
tileSprite Grass = grassSprite
tileSprite Rock = error "No rock sprite"
tileSprite Water = waterSprite
tileSprite Empty = error "No empty sprite"
-- This starts our gamein a window with a give size, running at 30 frames per second.
--
-- The argument 'World (0, 0)' is the initial state of our game world, where our character is at the centre of the
-- window.
--
initWorld = let playerPos = (0,0)
maxtile = (2 ^ 32) `div` 2
mintile = - maxtile
worldRegion = fromTiles (mintile,mintile) (maxtile,maxtile)
tiles = setRegion (newQuadTree worldRegion Grass) Water (fromTiles (0,0) (1,1))
in trace (show tiles) $ World {..}
main = play (InWindow "Fun game!" (600, 400) (50, 50)) white 60 initWorld draw handle [slide]
-- To draw a frame, we position the character sprite at the location as determined by the current state of the world.
-- We shrink the sprite by 50%.
drawOld (World (x, y) _) = translate x y (scale 0.5 0.5 grassSprite)
draw :: World -> Picture
draw (World (playerx, playery) tiles) = pictures $
[translate ((fromIntegral x)*64) ((fromIntegral y)*64) (scale 0.5 0.5 (tileSprite (fst (tiles `getElemAt` (x,y))))) | x <- [-20..20], y <- [-12..12]] ++ [translate playerx playery (scale 0.5 0.5 slimeSprite)]
slide time (World (x,y) tiles) = World (x,y + time*10) tiles
-- Whenever any of the keys 'a', 'd', 'w', or 's' have been pushed down, move our character in the corresponding
-- direction.
handle (EventKey (Char 'a') Down _ _) (World (x, y) tiles) = World (x - 10, y) tiles
handle (EventKey (Char 'd') Down _ _) (World (x, y) tiles) = World (x + 10, y) tiles
handle (EventKey (Char 'w') Down _ _) (World (x, y) tiles) = World (x, y + 10) tiles
handle (EventKey (Char 's') Down _ _) (World (x, y) tiles) = World (x, y - 10) tiles
handle event world = world -- don't change the world in case of any other events
|
chm90/FunGame
|
Game.hs
|
bsd-3-clause
| 2,585
| 0
| 17
| 537
| 818
| 449
| 369
| 37
| 1
|
{-# LANGUAGE CPP #-}
module Test.CloseFileHandles(main) where
import Test.Type
#ifdef mingw32_HOST_OS
main = testNone -- don't know how to do this on windows
#else
import Development.Shake
import Development.Shake.FilePath
import System.Posix.IO
import Control.Monad.Extra
import System.Exit
import System.IO
main = testBuild test $ do
let helper = toNative $ "helper/close_file_handles_helper" <.> exe
let name !> test = do want [name]
name ~> do need ["helper/close_file_handles_helper" <.> exe]; test
let helper_source = unlines
["import System.Environment"
,"import System.Posix.IO"
,"import System.IO"
,"import System.Exit"
,""
,"main = do"
," args <- getArgs"
," case args of"
," [fdString] -> do"
," handle <- fdToHandle (read fdString)"
," hClose handle"
," exitSuccess"
," _ -> do"
," progName <- getProgName"
," hPutStrLn stderr (\"usage: \" ++ progName ++ \" <file descriptor number>\\n tries closing the file descriptor number\\n exits successful, if the file descriptor was open\")"
," exitWith (ExitFailure 3)"]
"close_file_handles_helper.hs" %> \out -> do
need ["../../src/Test/CloseFileHandles.hs"]
writeFileChanged out helper_source
["helper/close_file_handles_helper"<.>exe, "close_file_handles_helper.hi", "close_file_handles_helper.o"] &%> \_ -> do
need ["close_file_handles_helper.hs"]
cmd "ghc --make" "close_file_handles_helper.hs -o helper/close_file_handles_helper"
let callWithOpenFile cmdWithOpts = withTempFile $
\file -> actionBracket (openFile file AppendMode) hClose $
\h -> do fd <- liftIO $ handleToFd h
(Exit c, Stdout _, Stderr _) <- cmdWithOpts helper (show fd) :: Action (Exit, Stdout String, Stderr String)
pure c
"defaultbehaviour" !> do
c <- callWithOpenFile cmd
liftIO $ assertBool (c == ExitSuccess) "handle closed without option CloseFileHandles"
"closing" !> do
c <- callWithOpenFile (cmd CloseFileHandles)
liftIO $ assertBool (c /= ExitSuccess) "handle not closed with option CloseFileHandles"
test build = do
whenM hasTracker $
build ["-j4", "--no-lint"]
build ["-j4"]
#endif
|
ndmitchell/shake
|
src/Test/CloseFileHandles.hs
|
bsd-3-clause
| 2,491
| 0
| 4
| 731
| 26
| 18
| 8
| 51
| 1
|
-- | css 2.1 identifiers
module Language.Css.Build.Idents (
above,
absolute,
absoluteSize,
always,
armenian,
auto,
avoid,
azimuth,
background,
backgroundAttachment,
backgroundColor,
backgroundImage,
backgroundPosition,
backgroundRepeat,
baseline,
behind,
below,
bidiOverride,
blink,
block,
bold,
bolder,
border,
borderBottom,
borderBottomColor,
borderBottomStyle,
borderBottomWidth,
borderCollapse,
borderColor,
borderLeft,
borderLeftColor,
borderLeftStyle,
borderLeftWidth,
borderRight,
borderRightColor,
borderRightStyle,
borderRightWidth,
borderSpacing,
borderStyle,
borderTop,
borderTopColor,
borderTopStyle,
borderTopWidth,
borderWidth,
both,
bottom,
capitalize,
caption,
captionSide,
center,
centerLeft,
centerRight,
child,
circle,
clear,
clip,
closeQuote,
code,
collapse,
color,
content,
continuous,
counterIncrement,
counterReset,
crosshair,
cue,
cueAfter,
cueBefore,
cursive,
cursor,
dashed,
decimal,
decimalLeadingZero,
default',
digits,
direction,
disc,
display,
dotted,
double,
eResize,
elevation,
embed,
emptyCells,
familyName,
fantasy,
farLeft,
farRight,
fast,
faster,
female,
fixed,
float,
font,
fontFamily,
fontSize,
fontStyle,
fontVariant,
fontWeight,
genericFamily,
genericVoice,
georgian,
groove,
height,
help,
hidden,
hide,
high,
higher,
icon,
inherit,
inline,
inlineBlock,
inlineTable,
inset,
inside,
invert,
italic,
justify,
large,
larger,
left,
leftSide,
leftwards,
letterSpacing,
level,
lighter,
lineHeight,
lineThrough,
listItem,
listStyle,
listStyleImage,
listStylePosition,
listStyleType,
loud,
low,
lower,
lowerAlpha,
lowerGreek,
lowerLatin,
lowerRoman,
lowercase,
ltr,
male,
margin,
marginBottom,
marginLeft,
marginRight,
marginTop,
marginWidth,
maxHeight,
maxWidth,
medium,
menu,
messageBox,
middle,
minHeight,
minWidth,
mix,
monospace,
move,
nResize,
neResize,
noCloseQuote,
noOpenQuote,
noRepeat,
none,
normal,
nowrap,
nwResize,
oblique,
once,
openQuote,
orphans,
outline,
outlineColor,
outlineStyle,
outlineWidth,
outset,
outside,
overflow,
overline,
padding,
paddingBottom,
paddingLeft,
paddingRight,
paddingTop,
paddingWidth,
pageBreakAfter,
pageBreakBefore,
pageBreakInside,
pause,
pauseAfter,
pauseBefore,
pitch,
pitchRange,
playDuring,
pointer,
position,
pre,
preLine,
preWrap,
progress,
quotes,
relative,
relativeSize,
repeat,
repeatX,
repeatY,
richness,
ridge,
right,
rightSide,
rightwards,
rtl,
runIn,
sResize,
sansSerif,
scroll,
seResize,
separate,
serif,
show,
silent,
slow,
slower,
small,
smallCaps,
smallCaption,
smaller,
soft,
solid,
speak,
speakHeader,
speakNumeral,
speakPunctuation,
specificVoice,
speechRate,
spellOut,
square,
static,
statusBar,
stress,
sub,
super,
swResize,
table,
tableCaption,
tableCell,
tableColumn,
tableColumnGroup,
tableFooterGroup,
tableHeaderGroup,
tableLayout,
tableRow,
tableRowGroup,
text,
textAlign,
textBottom,
textDecoration,
textIndent,
textTop,
textTransform,
thick,
thin,
top,
transparent,
underline,
unicodeBidi,
upperAlpha,
upperLatin,
upperRoman,
uppercase,
verticalAlign,
visibility,
visible,
voiceFamily,
volume,
wResize,
wait,
whiteSpace,
widows,
width,
wordSpacing,
xFast,
xHigh,
xLarge,
xLoud,
xLow,
xSlow,
xSmall,
xSoft,
xxLarge,
xxSmall,
zIndex
) where
import Language.Css.Syntax
import Language.Css.Build
import Prelude ()
-- | above
above :: Idents a => a
above = ident "above"
-- | absolute
absolute :: Idents a => a
absolute = ident "absolute"
-- | absolute-size
absoluteSize :: Idents a => a
absoluteSize = ident "absolute-size"
-- | always
always :: Idents a => a
always = ident "always"
-- | armenian
armenian :: Idents a => a
armenian = ident "armenian"
-- | auto
auto :: Idents a => a
auto = ident "auto"
-- | avoid
avoid :: Idents a => a
avoid = ident "avoid"
-- | azimuth
azimuth :: Idents a => a
azimuth = ident "azimuth"
-- | background
background :: Idents a => a
background = ident "background"
-- | background-attachment
backgroundAttachment :: Idents a => a
backgroundAttachment = ident "background-attachment"
-- | background-color
backgroundColor :: Idents a => a
backgroundColor = ident "background-color"
-- | background-image
backgroundImage :: Idents a => a
backgroundImage = ident "background-image"
-- | background-position
backgroundPosition :: Idents a => a
backgroundPosition = ident "background-position"
-- | background-repeat
backgroundRepeat :: Idents a => a
backgroundRepeat = ident "background-repeat"
-- | baseline
baseline :: Idents a => a
baseline = ident "baseline"
-- | behind
behind :: Idents a => a
behind = ident "behind"
-- | below
below :: Idents a => a
below = ident "below"
-- | bidi-override
bidiOverride :: Idents a => a
bidiOverride = ident "bidi-override"
-- | blink
blink :: Idents a => a
blink = ident "blink"
-- | block
block :: Idents a => a
block = ident "block"
-- | bold
bold :: Idents a => a
bold = ident "bold"
-- | bolder
bolder :: Idents a => a
bolder = ident "bolder"
-- | border
border :: Idents a => a
border = ident "border"
-- | border-bottom
borderBottom :: Idents a => a
borderBottom = ident "border-bottom"
-- | border-bottom-color
borderBottomColor :: Idents a => a
borderBottomColor = ident "border-bottom-color"
-- | border-bottom-style
borderBottomStyle :: Idents a => a
borderBottomStyle = ident "border-bottom-style"
-- | border-bottom-width
borderBottomWidth :: Idents a => a
borderBottomWidth = ident "border-bottom-width"
-- | border-collapse
borderCollapse :: Idents a => a
borderCollapse = ident "border-collapse"
-- | border-color
borderColor :: Idents a => a
borderColor = ident "border-color"
-- | border-left
borderLeft :: Idents a => a
borderLeft = ident "border-left"
-- | border-left-color
borderLeftColor :: Idents a => a
borderLeftColor = ident "border-left-color"
-- | border-left-style
borderLeftStyle :: Idents a => a
borderLeftStyle = ident "border-left-style"
-- | border-left-width
borderLeftWidth :: Idents a => a
borderLeftWidth = ident "border-left-width"
-- | border-right
borderRight :: Idents a => a
borderRight = ident "border-right"
-- | border-right-color
borderRightColor :: Idents a => a
borderRightColor = ident "border-right-color"
-- | border-right-style
borderRightStyle :: Idents a => a
borderRightStyle = ident "border-right-style"
-- | border-right-width
borderRightWidth :: Idents a => a
borderRightWidth = ident "border-right-width"
-- | border-spacing
borderSpacing :: Idents a => a
borderSpacing = ident "border-spacing"
-- | border-style
borderStyle :: Idents a => a
borderStyle = ident "border-style"
-- | border-top
borderTop :: Idents a => a
borderTop = ident "border-top"
-- | border-top-color
borderTopColor :: Idents a => a
borderTopColor = ident "border-top-color"
-- | border-top-style
borderTopStyle :: Idents a => a
borderTopStyle = ident "border-top-style"
-- | border-top-width
borderTopWidth :: Idents a => a
borderTopWidth = ident "border-top-width"
-- | border-width
borderWidth :: Idents a => a
borderWidth = ident "border-width"
-- | both
both :: Idents a => a
both = ident "both"
-- | bottom
bottom :: Idents a => a
bottom = ident "bottom"
-- | capitalize
capitalize :: Idents a => a
capitalize = ident "capitalize"
-- | caption
caption :: Idents a => a
caption = ident "caption"
-- | caption-side
captionSide :: Idents a => a
captionSide = ident "caption-side"
-- | center
center :: Idents a => a
center = ident "center"
-- | center-left
centerLeft :: Idents a => a
centerLeft = ident "center-left"
-- | center-right
centerRight :: Idents a => a
centerRight = ident "center-right"
-- | child
child :: Idents a => a
child = ident "child"
-- | circle
circle :: Idents a => a
circle = ident "circle"
-- | clear
clear :: Idents a => a
clear = ident "clear"
-- | clip
clip :: Idents a => a
clip = ident "clip"
-- | close-quote
closeQuote :: Idents a => a
closeQuote = ident "close-quote"
-- | code
code :: Idents a => a
code = ident "code"
-- | collapse
collapse :: Idents a => a
collapse = ident "collapse"
-- | color
color :: Idents a => a
color = ident "color"
-- | content
content :: Idents a => a
content = ident "content"
-- | continuous
continuous :: Idents a => a
continuous = ident "continuous"
-- | counter-increment
counterIncrement :: Idents a => a
counterIncrement = ident "counter-increment"
-- | counter-reset
counterReset :: Idents a => a
counterReset = ident "counter-reset"
-- | crosshair
crosshair :: Idents a => a
crosshair = ident "crosshair"
-- | cue
cue :: Idents a => a
cue = ident "cue"
-- | cue-after
cueAfter :: Idents a => a
cueAfter = ident "cue-after"
-- | cue-before
cueBefore :: Idents a => a
cueBefore = ident "cue-before"
-- | cursive
cursive :: Idents a => a
cursive = ident "cursive"
-- | cursor
cursor :: Idents a => a
cursor = ident "cursor"
-- | dashed
dashed :: Idents a => a
dashed = ident "dashed"
-- | decimal
decimal :: Idents a => a
decimal = ident "decimal"
-- | decimal-leading-zero
decimalLeadingZero :: Idents a => a
decimalLeadingZero = ident "decimal-leading-zero"
-- | default
default' :: Idents a => a
default' = ident "default"
-- | digits
digits :: Idents a => a
digits = ident "digits"
-- | direction
direction :: Idents a => a
direction = ident "direction"
-- | disc
disc :: Idents a => a
disc = ident "disc"
-- | display
display :: Idents a => a
display = ident "display"
-- | dotted
dotted :: Idents a => a
dotted = ident "dotted"
-- | double
double :: Idents a => a
double = ident "double"
-- | e-resize
eResize :: Idents a => a
eResize = ident "e-resize"
-- | elevation
elevation :: Idents a => a
elevation = ident "elevation"
-- | embed
embed :: Idents a => a
embed = ident "embed"
-- | empty-cells
emptyCells :: Idents a => a
emptyCells = ident "empty-cells"
-- | family-name
familyName :: Idents a => a
familyName = ident "family-name"
-- | fantasy
fantasy :: Idents a => a
fantasy = ident "fantasy"
-- | far-left
farLeft :: Idents a => a
farLeft = ident "far-left"
-- | far-right
farRight :: Idents a => a
farRight = ident "far-right"
-- | fast
fast :: Idents a => a
fast = ident "fast"
-- | faster
faster :: Idents a => a
faster = ident "faster"
-- | female
female :: Idents a => a
female = ident "female"
-- | fixed
fixed :: Idents a => a
fixed = ident "fixed"
-- | float
float :: Idents a => a
float = ident "float"
-- | font
font :: Idents a => a
font = ident "font"
-- | font-family
fontFamily :: Idents a => a
fontFamily = ident "font-family"
-- | font-size
fontSize :: Idents a => a
fontSize = ident "font-size"
-- | font-style
fontStyle :: Idents a => a
fontStyle = ident "font-style"
-- | font-variant
fontVariant :: Idents a => a
fontVariant = ident "font-variant"
-- | font-weight
fontWeight :: Idents a => a
fontWeight = ident "font-weight"
-- | generic-family
genericFamily :: Idents a => a
genericFamily = ident "generic-family"
-- | generic-voice
genericVoice :: Idents a => a
genericVoice = ident "generic-voice"
-- | georgian
georgian :: Idents a => a
georgian = ident "georgian"
-- | groove
groove :: Idents a => a
groove = ident "groove"
-- | height
height :: Idents a => a
height = ident "height"
-- | help
help :: Idents a => a
help = ident "help"
-- | hidden
hidden :: Idents a => a
hidden = ident "hidden"
-- | hide
hide :: Idents a => a
hide = ident "hide"
-- | high
high :: Idents a => a
high = ident "high"
-- | higher
higher :: Idents a => a
higher = ident "higher"
-- | icon
icon :: Idents a => a
icon = ident "icon"
-- | inherit
inherit :: Idents a => a
inherit = ident "inherit"
-- | inline
inline :: Idents a => a
inline = ident "inline"
-- | inline-block
inlineBlock :: Idents a => a
inlineBlock = ident "inline-block"
-- | inline-table
inlineTable :: Idents a => a
inlineTable = ident "inline-table"
-- | inset
inset :: Idents a => a
inset = ident "inset"
-- | inside
inside :: Idents a => a
inside = ident "inside"
-- | invert
invert :: Idents a => a
invert = ident "invert"
-- | italic
italic :: Idents a => a
italic = ident "italic"
-- | justify
justify :: Idents a => a
justify = ident "justify"
-- | large
large :: Idents a => a
large = ident "large"
-- | larger
larger :: Idents a => a
larger = ident "larger"
-- | left
left :: Idents a => a
left = ident "left"
-- | left-side
leftSide :: Idents a => a
leftSide = ident "left-side"
-- | leftwards
leftwards :: Idents a => a
leftwards = ident "leftwards"
-- | letter-spacing
letterSpacing :: Idents a => a
letterSpacing = ident "letter-spacing"
-- | level
level :: Idents a => a
level = ident "level"
-- | lighter
lighter :: Idents a => a
lighter = ident "lighter"
-- | line-height
lineHeight :: Idents a => a
lineHeight = ident "line-height"
-- | line-through
lineThrough :: Idents a => a
lineThrough = ident "line-through"
-- | list-item
listItem :: Idents a => a
listItem = ident "list-item"
-- | list-style
listStyle :: Idents a => a
listStyle = ident "list-style"
-- | list-style-image
listStyleImage :: Idents a => a
listStyleImage = ident "list-style-image"
-- | list-style-position
listStylePosition :: Idents a => a
listStylePosition = ident "list-style-position"
-- | list-style-type
listStyleType :: Idents a => a
listStyleType = ident "list-style-type"
-- | loud
loud :: Idents a => a
loud = ident "loud"
-- | low
low :: Idents a => a
low = ident "low"
-- | lower
lower :: Idents a => a
lower = ident "lower"
-- | lower-alpha
lowerAlpha :: Idents a => a
lowerAlpha = ident "lower-alpha"
-- | lower-greek
lowerGreek :: Idents a => a
lowerGreek = ident "lower-greek"
-- | lower-latin
lowerLatin :: Idents a => a
lowerLatin = ident "lower-latin"
-- | lower-roman
lowerRoman :: Idents a => a
lowerRoman = ident "lower-roman"
-- | lowercase
lowercase :: Idents a => a
lowercase = ident "lowercase"
-- | ltr
ltr :: Idents a => a
ltr = ident "ltr"
-- | male
male :: Idents a => a
male = ident "male"
-- | margin
margin :: Idents a => a
margin = ident "margin"
-- | margin-bottom
marginBottom :: Idents a => a
marginBottom = ident "margin-bottom"
-- | margin-left
marginLeft :: Idents a => a
marginLeft = ident "margin-left"
-- | margin-right
marginRight :: Idents a => a
marginRight = ident "margin-right"
-- | margin-top
marginTop :: Idents a => a
marginTop = ident "margin-top"
-- | margin-width
marginWidth :: Idents a => a
marginWidth = ident "margin-width"
-- | max-height
maxHeight :: Idents a => a
maxHeight = ident "max-height"
-- | max-width
maxWidth :: Idents a => a
maxWidth = ident "max-width"
-- | medium
medium :: Idents a => a
medium = ident "medium"
-- | menu
menu :: Idents a => a
menu = ident "menu"
-- | message-box
messageBox :: Idents a => a
messageBox = ident "message-box"
-- | middle
middle :: Idents a => a
middle = ident "middle"
-- | min-height
minHeight :: Idents a => a
minHeight = ident "min-height"
-- | min-width
minWidth :: Idents a => a
minWidth = ident "min-width"
-- | mix
mix :: Idents a => a
mix = ident "mix"
-- | monospace
monospace :: Idents a => a
monospace = ident "monospace"
-- | move
move :: Idents a => a
move = ident "move"
-- | n-resize
nResize :: Idents a => a
nResize = ident "n-resize"
-- | ne-resize
neResize :: Idents a => a
neResize = ident "ne-resize"
-- | no-close-quote
noCloseQuote :: Idents a => a
noCloseQuote = ident "no-close-quote"
-- | no-open-quote
noOpenQuote :: Idents a => a
noOpenQuote = ident "no-open-quote"
-- | no-repeat
noRepeat :: Idents a => a
noRepeat = ident "no-repeat"
-- | none
none :: Idents a => a
none = ident "none"
-- | normal
normal :: Idents a => a
normal = ident "normal"
-- | nowrap
nowrap :: Idents a => a
nowrap = ident "nowrap"
-- | nw-resize
nwResize :: Idents a => a
nwResize = ident "nw-resize"
-- | oblique
oblique :: Idents a => a
oblique = ident "oblique"
-- | once
once :: Idents a => a
once = ident "once"
-- | open-quote
openQuote :: Idents a => a
openQuote = ident "open-quote"
-- | orphans
orphans :: Idents a => a
orphans = ident "orphans"
-- | outline
outline :: Idents a => a
outline = ident "outline"
-- | outline-color
outlineColor :: Idents a => a
outlineColor = ident "outline-color"
-- | outline-style
outlineStyle :: Idents a => a
outlineStyle = ident "outline-style"
-- | outline-width
outlineWidth :: Idents a => a
outlineWidth = ident "outline-width"
-- | outset
outset :: Idents a => a
outset = ident "outset"
-- | outside
outside :: Idents a => a
outside = ident "outside"
-- | overflow
overflow :: Idents a => a
overflow = ident "overflow"
-- | overline
overline :: Idents a => a
overline = ident "overline"
-- | padding
padding :: Idents a => a
padding = ident "padding"
-- | padding-bottom
paddingBottom :: Idents a => a
paddingBottom = ident "padding-bottom"
-- | padding-left
paddingLeft :: Idents a => a
paddingLeft = ident "padding-left"
-- | padding-right
paddingRight :: Idents a => a
paddingRight = ident "padding-right"
-- | padding-top
paddingTop :: Idents a => a
paddingTop = ident "padding-top"
-- | padding-width
paddingWidth :: Idents a => a
paddingWidth = ident "padding-width"
-- | page-break-after
pageBreakAfter :: Idents a => a
pageBreakAfter = ident "page-break-after"
-- | page-break-before
pageBreakBefore :: Idents a => a
pageBreakBefore = ident "page-break-before"
-- | page-break-inside
pageBreakInside :: Idents a => a
pageBreakInside = ident "page-break-inside"
-- | pause
pause :: Idents a => a
pause = ident "pause"
-- | pause-after
pauseAfter :: Idents a => a
pauseAfter = ident "pause-after"
-- | pause-before
pauseBefore :: Idents a => a
pauseBefore = ident "pause-before"
-- | pitch
pitch :: Idents a => a
pitch = ident "pitch"
-- | pitch-range
pitchRange :: Idents a => a
pitchRange = ident "pitch-range"
-- | play-during
playDuring :: Idents a => a
playDuring = ident "play-during"
-- | pointer
pointer :: Idents a => a
pointer = ident "pointer"
-- | position
position :: Idents a => a
position = ident "position"
-- | pre
pre :: Idents a => a
pre = ident "pre"
-- | pre-line
preLine :: Idents a => a
preLine = ident "pre-line"
-- | pre-wrap
preWrap :: Idents a => a
preWrap = ident "pre-wrap"
-- | progress
progress :: Idents a => a
progress = ident "progress"
-- | quotes
quotes :: Idents a => a
quotes = ident "quotes"
-- | relative
relative :: Idents a => a
relative = ident "relative"
-- | relative-size
relativeSize :: Idents a => a
relativeSize = ident "relative-size"
-- | repeat
repeat :: Idents a => a
repeat = ident "repeat"
-- | repeat-x
repeatX :: Idents a => a
repeatX = ident "repeat-x"
-- | repeat-y
repeatY :: Idents a => a
repeatY = ident "repeat-y"
-- | richness
richness :: Idents a => a
richness = ident "richness"
-- | ridge
ridge :: Idents a => a
ridge = ident "ridge"
-- | right
right :: Idents a => a
right = ident "right"
-- | right-side
rightSide :: Idents a => a
rightSide = ident "right-side"
-- | rightwards
rightwards :: Idents a => a
rightwards = ident "rightwards"
-- | rtl
rtl :: Idents a => a
rtl = ident "rtl"
-- | run-in
runIn :: Idents a => a
runIn = ident "run-in"
-- | s-resize
sResize :: Idents a => a
sResize = ident "s-resize"
-- | sans-serif
sansSerif :: Idents a => a
sansSerif = ident "sans-serif"
-- | scroll
scroll :: Idents a => a
scroll = ident "scroll"
-- | se-resize
seResize :: Idents a => a
seResize = ident "se-resize"
-- | separate
separate :: Idents a => a
separate = ident "separate"
-- | serif
serif :: Idents a => a
serif = ident "serif"
-- | show
show :: Idents a => a
show = ident "show"
-- | silent
silent :: Idents a => a
silent = ident "silent"
-- | slow
slow :: Idents a => a
slow = ident "slow"
-- | slower
slower :: Idents a => a
slower = ident "slower"
-- | small
small :: Idents a => a
small = ident "small"
-- | small-caps
smallCaps :: Idents a => a
smallCaps = ident "small-caps"
-- | small-caption
smallCaption :: Idents a => a
smallCaption = ident "small-caption"
-- | smaller
smaller :: Idents a => a
smaller = ident "smaller"
-- | soft
soft :: Idents a => a
soft = ident "soft"
-- | solid
solid :: Idents a => a
solid = ident "solid"
-- | speak
speak :: Idents a => a
speak = ident "speak"
-- | speak-header
speakHeader :: Idents a => a
speakHeader = ident "speak-header"
-- | speak-numeral
speakNumeral :: Idents a => a
speakNumeral = ident "speak-numeral"
-- | speak-punctuation
speakPunctuation :: Idents a => a
speakPunctuation = ident "speak-punctuation"
-- | specific-voice
specificVoice :: Idents a => a
specificVoice = ident "specific-voice"
-- | speech-rate
speechRate :: Idents a => a
speechRate = ident "speech-rate"
-- | spell-out
spellOut :: Idents a => a
spellOut = ident "spell-out"
-- | square
square :: Idents a => a
square = ident "square"
-- | static
static :: Idents a => a
static = ident "static"
-- | status-bar
statusBar :: Idents a => a
statusBar = ident "status-bar"
-- | stress
stress :: Idents a => a
stress = ident "stress"
-- | sub
sub :: Idents a => a
sub = ident "sub"
-- | super
super :: Idents a => a
super = ident "super"
-- | sw-resize
swResize :: Idents a => a
swResize = ident "sw-resize"
-- | table
table :: Idents a => a
table = ident "table"
-- | table-caption
tableCaption :: Idents a => a
tableCaption = ident "table-caption"
-- | table-cell
tableCell :: Idents a => a
tableCell = ident "table-cell"
-- | table-column
tableColumn :: Idents a => a
tableColumn = ident "table-column"
-- | table-column-group
tableColumnGroup :: Idents a => a
tableColumnGroup = ident "table-column-group"
-- | table-footer-group
tableFooterGroup :: Idents a => a
tableFooterGroup = ident "table-footer-group"
-- | table-header-group
tableHeaderGroup :: Idents a => a
tableHeaderGroup = ident "table-header-group"
-- | table-layout
tableLayout :: Idents a => a
tableLayout = ident "table-layout"
-- | table-row
tableRow :: Idents a => a
tableRow = ident "table-row"
-- | table-row-group
tableRowGroup :: Idents a => a
tableRowGroup = ident "table-row-group"
-- | text
text :: Idents a => a
text = ident "text"
-- | text-align
textAlign :: Idents a => a
textAlign = ident "text-align"
-- | text-bottom
textBottom :: Idents a => a
textBottom = ident "text-bottom"
-- | text-decoration
textDecoration :: Idents a => a
textDecoration = ident "text-decoration"
-- | text-indent
textIndent :: Idents a => a
textIndent = ident "text-indent"
-- | text-top
textTop :: Idents a => a
textTop = ident "text-top"
-- | text-transform
textTransform :: Idents a => a
textTransform = ident "text-transform"
-- | thick
thick :: Idents a => a
thick = ident "thick"
-- | thin
thin :: Idents a => a
thin = ident "thin"
-- | top
top :: Idents a => a
top = ident "top"
-- | transparent
transparent :: Idents a => a
transparent = ident "transparent"
-- | underline
underline :: Idents a => a
underline = ident "underline"
-- | unicode-bidi
unicodeBidi :: Idents a => a
unicodeBidi = ident "unicode-bidi"
-- | upper-alpha
upperAlpha :: Idents a => a
upperAlpha = ident "upper-alpha"
-- | upper-latin
upperLatin :: Idents a => a
upperLatin = ident "upper-latin"
-- | upper-roman
upperRoman :: Idents a => a
upperRoman = ident "upper-roman"
-- | uppercase
uppercase :: Idents a => a
uppercase = ident "uppercase"
-- | vertical-align
verticalAlign :: Idents a => a
verticalAlign = ident "vertical-align"
-- | visibility
visibility :: Idents a => a
visibility = ident "visibility"
-- | visible
visible :: Idents a => a
visible = ident "visible"
-- | voice-family
voiceFamily :: Idents a => a
voiceFamily = ident "voice-family"
-- | volume
volume :: Idents a => a
volume = ident "volume"
-- | w-resize
wResize :: Idents a => a
wResize = ident "w-resize"
-- | wait
wait :: Idents a => a
wait = ident "wait"
-- | white-space
whiteSpace :: Idents a => a
whiteSpace = ident "white-space"
-- | widows
widows :: Idents a => a
widows = ident "widows"
-- | width
width :: Idents a => a
width = ident "width"
-- | word-spacing
wordSpacing :: Idents a => a
wordSpacing = ident "word-spacing"
-- | x-fast
xFast :: Idents a => a
xFast = ident "x-fast"
-- | x-high
xHigh :: Idents a => a
xHigh = ident "x-high"
-- | x-large
xLarge :: Idents a => a
xLarge = ident "x-large"
-- | x-loud
xLoud :: Idents a => a
xLoud = ident "x-loud"
-- | x-low
xLow :: Idents a => a
xLow = ident "x-low"
-- | x-slow
xSlow :: Idents a => a
xSlow = ident "x-slow"
-- | x-small
xSmall :: Idents a => a
xSmall = ident "x-small"
-- | x-soft
xSoft :: Idents a => a
xSoft = ident "x-soft"
-- | xx-large
xxLarge :: Idents a => a
xxLarge = ident "xx-large"
-- | xx-small
xxSmall :: Idents a => a
xxSmall = ident "xx-small"
-- | z-index
zIndex :: Idents a => a
zIndex = ident "z-index"
|
anton-k/language-css
|
src/Language/Css/Build/Idents.hs
|
bsd-3-clause
| 25,628
| 0
| 6
| 5,622
| 7,109
| 3,855
| 3,254
| 889
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
-- {-# OPTIONS_GHC -cpp -DPiForallInstalled #-}
--------------------------------------------------------------------
-- |
-- Copyright : (c) Andreas Reuleaux 2015
-- License : BSD2
-- Maintainer: Andreas Reuleaux <rx@a-rx.info>
-- Stability : experimental
-- Portability: non-portable
--
-- This module tests Pire's parser, forget, and untie functionality
--------------------------------------------------------------------
{-
toggle w/ opts in cabal file
cpp-options: -DPiForallInstalled
cf
http://stackoverflow.com/questions/6361846/where-can-i-learn-about-ifdef
+ setting ghc/ghci cmd line options (from man ghci)
-cpp -Dsymbol=value -U -Usymbol ...
thus eg.
ghci -cpp -DPiForallInstalled
these seem not to work (?)
cabal repl --ghc-options="-cpp -DPiForallInstalled"
anyway NOT cabal repl --ghc-options="--cpp-options=-DPiForallInstalled"
can the -cpp be set on the cabal repl cmd line at all?
but better just toggle w/
-- {-# OPTIONS_GHC -cpp -DPiForallInstalled #-}
-}
{-
usage
./tests.hs
./tests.hs -p sorting
etc
./tests.hs -h
resp.
Pire.Tests.main'
eg.
:l Pire.Tests
main' "*"
or
main' "basic"
main' "nat"
meanwhile just
runhaskell -package-db=.cabal-sandbox/x86_64-linux-ghc-7.6.3-packages.conf.d tests.hs -p parsing
-}
module ParserTests.If where
import Test.Tasty
import Test.Tasty.HUnit
import Pire.Syntax.Token
import Pire.Syntax.Ws
import Pire.Syntax
import Pire.NoPos
import Pire.Parser.Expr
import Pire.Forget
import Data.Either.Combinators (fromRight')
import Pire.Untie
import Pire.Parser.ParseUtils
import Pire.Parser.PiParseUtils
#ifdef PiForallInstalled
import qualified PiForall.Parser as P
#endif
-- main' "if -"
ifU = testGroup "parsing if - unit tests" $ tail [
undefined
, let s = "if{-i-}a{-i'-}then{-t-}b{-t'-}else{-e-}c{-e'-}"
in
testGroup ("parsing '"++s++"'...") $ tail [
undefined
-- if
, testCase ("parse ifExpr '"++s++"'")
$ (nopos $ parse ifExpr s) @?= If (V "a") (V "b") (V "c") (Annot Nothing)
, testCase ("parse ifExpr_ '"++s++"'")
$ (nopos $ parse ifExpr_ s)
-- @?= If_ (IfTok "if" $ Ws "{-i-}") (V_ "a" (Ws "{-i'-}")) (ThenTok $ Ws "{-t-}") (V_ "b" (Ws "{-t'-}")) (ElseTok $ Ws "{-e-}") (V_ "c" (Ws "{-e'-}")) (Annot_ Nothing (Ws ""))
@?= If_ (IfTok "if" $ Ws "{-i-}") (Ws_ (V "a") (Ws "{-i'-}")) (ThenTok "then" $ Ws "{-t-}") (Ws_ (V "b") (Ws "{-t'-}")) (ElseTok "else" $ Ws "{-e-}") (Ws_ (V "c") (Ws "{-e'-}")) (Annot_ Nothing (Ws ""))
, testCase ("parse & forget ifExpr_ '"++s++"'")
$ (forget $ parse ifExpr_ s) @?= (parse ifExpr s)
]
#ifdef PiForallInstalled
++ tail [
undefined
, testCase ("parse & untie ifExpr_ '"++s++"'")
$ (untie $ parse ifExpr_ s) @?= (piParse P.ifExpr s)
, testCase ("parse & untie expr_ '"++s++"'")
$ (untie $ parse expr_ s) @?= (piParse P.expr s)
, testCase ("parse & untie expr '"++s++"'")
$ (untie $ parse expr s) @?= (fromRight' $ P.parseExpr s)
]
#endif
, let s = "\\ x . if a then b else c "
in
testGroup (">>= for If/If_: \""++s++"\"") $ tail [
undefined
-- make sure, the bind op for If/If_ is defined
-- trivial equality
, testCase ("parsing expr '"++s++"'")
$ (parseP expr s) @?= (parseP expr s)
, testCase ("parsing expr_ '"++s++"'")
$ (parseP expr_ s) @?= (parseP expr_ s)
]
#ifdef PiForallInstalled
#endif
-- indentation!
]
|
reuleaux/pire
|
tests/ParserTests/If.hs
|
bsd-3-clause
| 3,839
| 0
| 19
| 1,041
| 722
| 389
| 333
| 34
| 1
|
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..))
import System.Exit (ExitCode(..), exitWith)
import Robot (Bearing(..), Robot, mkRobot,
coordinates, simulate,
bearing, turnRight, turnLeft)
exitProperly :: IO Counts -> IO ()
exitProperly m = do
counts <- m
exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
main :: IO ()
main = exitProperly $ runTestTT $ TestList
[ TestList robotTests ]
robotTests :: [Test]
robotTests =
[ testCase "turning edge cases" $ do
North @=? turnRight West
West @=? turnLeft North
, testCase "robbie" $ do
let robbie :: Robot
robbie = mkRobot East (-2, 1)
East @=? bearing robbie
(-2, 1) @=? coordinates robbie
let movedRobbie = simulate robbie "RLAALAL"
West @=? bearing movedRobbie
(0, 2) @=? coordinates movedRobbie
mkRobot West (0, 2) @=? movedRobbie
, testCase "clutz" $ do
let clutz = mkRobot North (0, 0)
mkRobot West (-4, 1) @=? simulate clutz "LAAARALA"
, testCase "sphero" $ do
let sphero = mkRobot East (2, -7)
mkRobot South (-3, -8) @=? simulate sphero "RRAAAAALA"
, testCase "roomba" $ do
let roomba = mkRobot South (8, 4)
mkRobot North (11, 5) @=? simulate roomba "LAAARRRALLLL"
]
|
pminten/xhaskell
|
robot-simulator/robot-simulator_test.hs
|
mit
| 1,407
| 0
| 14
| 326
| 550
| 282
| 268
| 37
| 2
|
module Cipher where
import System.Console.CmdTheLine
import Control.Applicative
import Data.Char ( isUpper, isAlpha, isAlphaNum, isSpace
, toLower
)
import Data.List ( intersperse )
import System.IO
import System.Exit
infixr 2 <||>
-- Split a value between predicates and 'or' the results together
(<||>) :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
p <||> p' = (||) <$> p <*> p'
--
-- Rot
--
data Cycle a = Cycle
{ backward :: (Cycle a)
, at :: a
, forward :: (Cycle a)
}
fromList :: [a] -> Cycle a
fromList [] = error "Cycle must have at least one element"
fromList xs = first
where
( first, last ) = go last xs first
go :: Cycle a -> [a] -> Cycle a -> ( Cycle a, Cycle a )
go prev [] next = ( next, prev )
go prev (x : xs) next = ( this, last )
where
this = Cycle prev x rest
(rest,last) = go this xs next
-- Return a Cycle centered on x.
seekTo :: Eq a => a -> Cycle a -> Cycle a
seekTo x xs
| x == at xs = xs
| otherwise = seekTo x $ forward xs
-- Seek n places forwards or backwards.
seek :: Bool -> Int -> Cycle a -> Cycle a
seek _ 0 xs = xs
seek back n xs = seek back (n - 1) (dir xs)
where
dir = if back then backward else forward
lowers, uppers :: Cycle Char
lowers = fromList ['a'..'z']
uppers = fromList ['A'..'Z']
rot :: Bool -> Int -> Maybe String -> IO ()
rot back n mStr = do
input <- case mStr of
Nothing -> getContents
Just str -> return str
putStrLn $ map rotChar input
where
rotChar c = if isAlpha c then c' else c
where
c' = at . seek back n $ seekTo c cycle
cycle = if isUpper c then uppers else lowers
--
-- Morse
--
switch :: ( a, b ) -> ( b, a )
switch ( x, y ) = ( y, x )
fromCode :: [( String, Char )]
fromCode = map switch toCode
toCode :: [( Char, String )]
toCode =
[ ( 'a', ".-" ), ( 'b', "-..." ), ( 'c', "-.-." ), ( 'd', "-.." )
, ( 'e', "." ), ( 'f', "..-." ), ( 'g', "--." ), ( 'h', "...." )
, ( 'i', ".." ), ( 'j', ".---" ), ( 'k', "-.-" ), ( 'l', ".-.." )
, ( 'm', "--" ), ( 'n', "-." ), ( 'o', "---" ), ( 'p', ".--." )
, ( 'q', "--.-" ), ( 'r', ".-." ), ( 's', "..." ), ( 't', "-" )
, ( 'u', "..-" ), ( 'v', "...-" ), ( 'w', ".--" ), ( 'x', "-..-" )
, ( 'y', "-.--" ), ( 'z', "--.." ), ( '1', ".----" ), ( '2', "..---" )
, ( '3', "...--" ), ( '4', "....-" ), ( '5', "....." ), ( '6', "-...." )
, ( '7', "--..." ), ( '8', "---.." ), ( '9', "----." ), ( '0', "-----" )
, ( ' ', "/" )
]
fromMorse, toMorse :: [String] -> Maybe String
fromMorse = mapM (`lookup` fromCode)
toMorse strs = sepCat " / " <$> mapM convertLetters strs
where
convertLetters chars = sepCat " " <$> mapM (`lookup` toCode) chars
sepCat sep = concat . intersperse sep
morse :: Bool -> Maybe String -> IO ()
morse from mStr = do
input <- case mStr of
Nothing -> getContents
Just str -> return str
if all pred input
then return ()
else do hPutStrLn stderr err
exitFailure
convert input
where
pred = if from then (== '/') <||> (== '-') <||> (== '.') <||> isSpace
else isAlphaNum <||> isSpace
err = if from
then "cipher: morse input must be all spaces, '/'s, '-'s, and '.'s."
else "cipher: morse input must be alphanumeric and/or spaces"
convert str = maybe badConvert putStrLn . convert' . words $ map toLower str
where
badConvert = hPutStrLn stderr err >> exitFailure
where
err = if from then "cipher: could not convert from morse"
else "cipher: could not convert to morse"
convert' = if from then fromMorse else toMorse
--
-- Terms
--
-- The heading under which to place common options.
comOpts :: String
comOpts = "COMMON OPTIONS"
-- A modified default 'TermInfo' to be shared by commands.
defTI' :: TermInfo
defTI' = defTI
{ man =
[ S comOpts
, P "These options are common to all commands."
, S "MORE HELP"
, P "Use '$(mname) $(i,COMMAND) --help' for help on a single command."
, S "BUGS"
, P "Email bug reports to <snideHighland@example.com>"
]
, stdOptSec = comOpts
}
-- 'input' is a common option. We set its 'optSec' field to 'comOpts' so
-- that it is placed under that section instead of the default '"OPTIONS"'
-- section, which we will reserve for command-specific options.
input :: Term (Maybe String)
input = value $ opt Nothing (optInfo [ "input", "i" ])
{ optName = "INPUT"
, optDoc = "For specifying input on the command line. If present, "
++ "input is not read form standard-in."
, optSec = comOpts
}
rotTerm :: ( Term (IO ()), TermInfo )
rotTerm = ( rot <$> back <*> n <*> input, termInfo )
where
back = value $ flag (optInfo [ "back", "b" ])
{ optName = "BACK"
, optDoc = "Rotate backwards instead of forwards."
}
n = value $ opt 13 (optInfo [ "n" ])
{ optName = "N"
, optDoc = "How many places to rotate by."
}
termInfo = defTI'
{ termName = "rot"
, termDoc = "Rotate the input characters by N."
, man = [ S "DESCRIPTION"
, P $ "Rotate input gathered from INPUT or standard-in N "
++ "places. The input must be composed totally of "
++ "alphabetic characters and spaces."
] ++ man defTI'
}
morseTerm :: ( Term (IO ()), TermInfo )
morseTerm = ( morse <$> from <*> input, termInfo )
where
from = value $ flag (optInfo [ "from", "f" ])
{ optName = "FROM"
, optDoc = "Convert from morse-code to the Latin alphabet. "
++ "If absent, convert from Latin alphabet to morse-code."
}
termInfo = defTI'
{ termName = "morse"
, termDoc = "Convert to and from morse-code."
, man = [ S "DESCRIPTION"
, P desc
] ++ man defTI'
}
desc = concat
[ "Converts input gathered from INPUT or standard in to and from morse "
, "code. 'dah' is represented by '-', 'dit' by '.'. Each morse character "
, "is separated from the next by one or more ' '. Morse words are "
, "separated by a '/'."
]
defaultTerm :: ( Term a, TermInfo )
defaultTerm = ( ret $ const (helpFail Pager Nothing) <$> input
, termInfo
)
where
termInfo = defTI'
{ termName = "cipher"
, version = "v1.0"
, termDoc = doc
}
doc = "An implementation of the morse-code and rotational(Caesar) ciphers."
|
glutamate/cmdtheline
|
test/Cipher.hs
|
mit
| 6,571
| 0
| 13
| 1,986
| 1,948
| 1,105
| 843
| 144
| 7
|
a :: Bool
(a, True) = (True, True)
|
roberth/uu-helium
|
test/staticwarnings/Binding1.hs
|
gpl-3.0
| 36
| 0
| 5
| 9
| 24
| 14
| 10
| 2
| 1
|
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Main
-- Copyright : (c) 2013-2015 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)
--
module Main (main) where
import Test.Tasty
import Test.AWS.ImportExport
import Test.AWS.ImportExport.Internal
main :: IO ()
main = defaultMain $ testGroup "ImportExport"
[ testGroup "tests" tests
, testGroup "fixtures" fixtures
]
|
olorin/amazonka
|
amazonka-importexport/test/Main.hs
|
mpl-2.0
| 549
| 0
| 8
| 103
| 76
| 47
| 29
| 9
| 1
|
{-|
Module : $Header$
Copyright : (c) 2014 Edward O'Callaghan
License : LGPL-2.1
Maintainer : eocallaghan@alterapraxis.com
Stability : provisional
Portability : portable
This module collects together libbladeRF high-level
actions and primitives into a common namespace.
-}
{-# OPTIONS_HADDOCK hide, prune #-}
module LibBladeRF (module X) where
import LibBladeRF.LibBladeRF as X
import LibBladeRF.Utils as X
import LibBladeRF.Flash as X
--import LibBladeRF.Si5338 as X
import LibBladeRF.Sync as X
--import LibBladeRF.Lms as X
import LibBladeRF.Gpio as X
import LibBladeRF.Gain as X
import LibBladeRF.Types as X
|
adamwalker/hlibBladeRF
|
src/LibBladeRF.hs
|
lgpl-2.1
| 644
| 0
| 4
| 116
| 63
| 46
| 17
| 9
| 0
|
-- * Tagless Typed Interpreters, introduction
module Intro1 where
-- We would like to embed an (object) language whose expressions
-- look like
-- -(1 + 2)
-- * 8 + (- (1+2))
-- The expressions are built of integer literals, negation and addition.
-- The latter is one of our running example, please take note.
-- * Deep/initial embedding
-- The data type of expressions
data Exp = Lit Int
| Neg Exp
| Add Exp Exp
-- A sample expression: our first running example
ti1 = Add (Lit 8) (Neg (Add (Lit 1) (Lit 2)))
-- * //
-- The evaluator
-- It proceeds by case analysis on the expression
eval:: Exp -> Int
eval (Lit n) = n
eval (Neg e) = - eval e
eval (Add e1 e2) = eval e1 + eval e2
ti1_eval = eval ti1
-- 5
-- * //
-- A different way to write the evaluator:
-- using the `constructor functions'
type Repr = Int
lit :: Int -> Repr
lit n = n
neg :: Repr -> Repr
neg e = - e
-- What is the inferred type for add? What type should we rather assign?
add e1 e2 = e1 + e2
-- Perhaps this already reminds someone of the denotational semantics.
-- More reminders to come.
-- Our sample expression in the final form:
-- I just downcased ti1
tf1 = add (lit 8) (neg (add (lit 1) (lit 2)))
-- 5
-- * Shallow (metacircular) embedding (to be called final)
-- * //
-- But the datatype way (initial way) lets us `evaluate' ti1
-- in a different way: to pretty-print it
view:: Exp -> String
view (Lit n) = show n
view (Neg e) = "(-" ++ view e ++ ")"
view (Add e1 e2) = "(" ++ view e1 ++ " + " ++ view e2 ++ ")"
ti1_view = view ti1
-- "(8 + (-(1 + 2)))"
-- How can we evaluate tf1 differently? It seems that the evaluator
-- is hard-wired into tf1...
-- Indeed, the constructor functions lit, neg, and add all have
-- return type that is set to Int. The evaluator `view' returns a string.
-- So, at the very least we must find a way to parameterize the constructor
-- functions by the result type.
main = do
print ti1_eval
print tf1
print ti1_view
|
mjhopkins/ttfi
|
src/haskell/Intro1.hs
|
apache-2.0
| 1,992
| 1
| 11
| 460
| 395
| 214
| 181
| 26
| 1
|
{-# OPTIONS_GHC -fglasgow-exts #-}
import qualified System.IO.UTF8 as UIO
import System.IO (stderr)
import Prelude hiding (readFile, writeFile, getContents)
import GramLab.Morfette.Utils
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified GramLab.Data.MultiSet as MSet
import Data.Maybe
import System(getArgs)
import GramLab.Utils
import System
import GramLab.Commands
import System.Console.GetOpt
import Text.Printf
import GramLab.Morfette.LZipper
import qualified GramLab.Morfette.LZipper as LZ (fromList)
import Debug.Trace
import qualified Prelude
import Control.Exception
import Control.Arrow (second)
import Control.Monad (when)
import Data.List (sortBy,transpose)
import Data.Ord
import qualified GramLab.Maxent.ZhangLe.Model as M
--import qualified GramLab.Morfette.Features.Lemma1 as LF1
import qualified GramLab.Morfette.Features.Lemma8 as LF
--import qualified GramLab.Morfette.Features.Lemma8simple as LF
--import qualified GramLab.Morfette.Features.Lemma8flip as LF
import GramLab.Morfette.Features.LemmaUtil
import qualified GramLab.Morfette.Features.Tagging3 as TF
--import qualified GramLab.Morfette.Features.Tagging3simple as TF
--import qualified GramLab.Morfette.Features.Tagging3flip as TF
--import qualified GramLab.Morfette.Features.Tagging3joint as TF
--import qualified GramLab.Morfette.ES.Tagging3 as TF
import GramLab.Morfette.Features.Common
import GramLab.Morfette.Config6
main = defaultMain commands "Usage: morfette command [OPTION...] [ARG...]"
commands = [
("train" , CommandSpec train
"train maxent model"
[ Option [] ["model-prefix"] (ReqArg ModelPrefix "STRING")
"path prefix to model files"
, Option [] ["config-file"] (ReqArg ConfigFile "PATH")
"path to config file"
, Option [] ["mode"] (ReqArg Mode "STRING")
"lemma|postag|combined"
] )
, ("predict" , CommandSpec predict
"predict lemmas using saved model data"
[ Option [] ["config-file"] (ReqArg ConfigFile "PATH")
"path to config file"
, Option [] ["output"] (ReqArg OutputPath "PATH")
"path to output file"
, Option [] ["beam"] (ReqArg (BeamSize . read) "+INT")
"beam size to use"
, Option [] ["preprune","preprune-threshold"] (ReqArg (Preprune . read) "[0..1]")
"prepruning threshold"
, Option [] ["eval"] (NoArg Eval)
"evaluate lemmatization accuracy"
, Option [] ["pos-prefix-for-eval","pos-eval"] (ReqArg (POSPrefixEval . read) "+INT")
"POS prefix to consider in evaluation"
, Option [] ["mode"] (ReqArg Mode "STRING")
"lemma|postag"
] )
, ("eval" , CommandSpec eval
"evaluate morpho-tagging and lemmatization results"
[])
]
data Flag = OutputPath FilePath
| ModelPrefix String
| POSPrefixEval Int
| Eval
| BeamSize Int
| Preprune Double
| ConfigFile FilePath
| Mode String
deriving Eq
modelFile prefix = prefix ++ ".model"
lemmaModelFile prefix = prefix ++ ".lemma-model"
posModelFile prefix = prefix ++ ".pos-model"
paramFile prefix = prefix ++ ".param"
getParams flags = do
params <- case [f | ConfigFile f <- flags] of
[] -> return defaults
[f] -> fmap Prelude.read (UIO.readFile f)
return params
configFromParams params flags =
case [f | Mode f <- flags ] of
["postag"] -> getPOSParams params
["lemma"] -> getLemmaParams params
["joint"] -> getPOSParams params
getLemmaParams params = (LF.makeFeatureSpec (fst . lemmaConfig $ params),snd . lemmaConfig $ params)
getPOSParams params = (TF.makeFeatureSpec (fst . taggingConfig $ params),snd . taggingConfig $ params)
train :: Command Flag
train flags args@(path:_) = do
case [f | Mode f <- flags ] of
["combined"] -> train2 flags args
[mode] -> do
let f | mode == "lemma" = justSES
| mode == "postag" = justPOS
| mode == "joint" = justBoth
params <- getParams flags
let (featSpec, trainParams) = configFromParams params flags
toks <- fmap (map parseToken . lines) (UIO.readFile path)
let sentences = splitWith isNullToken toks
modelprefix = case [f | ModelPrefix f <- flags ] of { [f] -> f ; _ -> path }
examples = (concatMap (map (exampleToPair f) . extractFeatures featSpec) $ sentences)
UIO.writeFile (paramFile modelprefix) (show params)
model <- M.train trainParams examples
M.save (modelFile modelprefix) model
train2 flags (path:_) = do
params <- getParams flags
let (lemmaFeatSpec,lemmaTrainParams) = getLemmaParams params
(posFeatSpec, posTrainParams) = getPOSParams params
toks <- fmap (map parseToken . lines) (UIO.readFile path)
let sentences = splitWith isNullToken toks
modelprefix = case [f | ModelPrefix f <- flags ] of { [f] -> f ; _ -> path }
lemmaExamples = makeExamples justSES lemmaFeatSpec sentences
posExamples = makeExamples justPOS posFeatSpec sentences
UIO.writeFile (paramFile modelprefix) (show params)
UIO.hPutStrLn stderr "Training POS-tagger"
posModel <- M.train posTrainParams posExamples
M.save (posModelFile modelprefix) posModel
UIO.hPutStrLn stderr "Training lemmatizer"
lemmaModel <- M.train lemmaTrainParams lemmaExamples
M.save (lemmaModelFile modelprefix) lemmaModel
makeExamples f spec = concatMap (map (exampleToPair f) . extractFeatures spec)
extractFrequent i = MSet.foldOccur (\x j z -> if j >= i then Set.insert x z else z) Set.empty
. MSet.fromList
. map lowercase
predict :: Command Flag
predict flags args@(modelprefix:_) = do
case [f | Mode f <- flags ] of
["combined"] -> predict2 flags args
[mode] -> do
let f | mode == "lemma" = justSES
| mode == "postag" = justPOS
| mode == "joint" = justBoth
toks <- fmap (map parseToken . lines) UIO.getContents
let sentences = splitWith isNullToken toks
defaultBeamSize = 3
params <- fmap Prelude.read $ UIO.readFile (paramFile modelprefix)
let (featSpec,trainParams) = configFromParams params flags
n = case [f | BeamSize f <- flags ] of { [f] -> f ; _ -> defaultBeamSize }
model <- M.load (modelFile modelprefix)
let { classifier = mkClassifier f model featSpec
; sws = map (LZ.fromList . map (tokenToExample featSpec)) sentences
; nbests = map (classifyBeam n classifier (*) . (\z -> [(1,z)])) sws -- cool: (\z -> [(1,z)]) == return . (,) 1
; doJoint = do {
let { predicted_pos = map (map getPOS . bestClassSeq . unzip) nbests
; predicted_lemmas = (flip . flip zipWith) nbests sentences
$ (\z toks ->
zipWith applyScript
(map getSES . bestClassSeq . unzip $ z)
(map tokenForm toks))
; predicted_sents = map (\(forms,lemmas,postags) -> zip3 forms lemmas postags)
(zip3 (map (map tokenForm) sentences)
predicted_lemmas
predicted_pos)
{- ; gold_pos = map (map (fromMaybe (assert False undefined) . tokenPOS)) sentences
; gold_lemmas = map (map (fromMaybe (assert False undefined) . tokenLemma)) sentences
; total_pos = sum (map length gold_pos)
; correct_pos = length . filter (uncurry (==)) $ zip (concat predicted_pos) (concat gold_pos)
; total_lemmas = sum (map length gold_lemmas)
; correct_lemmas = length . filter (uncurry (==)) $ zip (concat predicted_lemmas) (concat gold_lemmas)
-}
}
in do mapM_ (UIO.putStrLn . unlines . map formatTriple) predicted_sents }
-- in do {when (Eval `elem` flags) (do { UIO.hPutStrLn stderr $ showAcc (correct_pos,total_pos);
-- UIO.hPutStrLn stderr $ showAcc (correct_lemmas, total_lemmas) })}
}
case [f | Mode f <- flags ] of
["joint"] -> doJoint
f -> do {
let { (predicted,gold) =
case f of
["lemma"] -> let predicted = (flip . flip zipWith) nbests sentences
$ (\z toks ->
zipWith applyScript
(map getSES . bestClassSeq . unzip $ z)
(map tokenForm toks))
gold = map (map (lowercase . fromMaybe (assert False undefined) . tokenLemma)) sentences
in (predicted,gold)
["postag"] -> let predicted = map (map getPOS . bestClassSeq . unzip) nbests
gold = map (map (fromMaybe (assert False undefined) . tokenPOS)) sentences
in (predicted,gold)
; total = sum (map length gold)
; correct = length . filter (uncurry (==)) $ zip (concat predicted) (concat gold) }
in do { mapM_ (UIO.putStrLn . unlines) predicted
; when (Eval `elem` flags) (UIO.hPutStrLn stderr $ showAcc (correct,total)) } }
predict2 flags (modelprefix:_) = do
toks <- fmap (map parseToken . lines) UIO.getContents
let sentences = splitWith isNullToken toks
defaultBeamSize = 3
defaultPpruneTh = 0.3
params <- fmap Prelude.read $ UIO.readFile (paramFile modelprefix)
let (lemmaFeatSpec,lemmaTrainParams) = getLemmaParams params
(posFeatSpec, posTrainParams) = getPOSParams params
n = case [f | BeamSize f <- flags ] of { [f] -> f ; _ -> defaultBeamSize }
c = case [f | Preprune f <- flags ] of { [f] -> f ; _ -> defaultPpruneTh }
lemmaModel <- M.load (lemmaModelFile modelprefix) -- has to be possible to load from different files
posModel <- M.load (posModelFile modelprefix)
let lemmatizer = mkClassifier justSES lemmaModel lemmaFeatSpec
postagger = mkClassifier justPOS posModel posFeatSpec
zs = map (\s -> ( LZ.fromList . map (tokenToExample lemmaFeatSpec) $ s
, LZ.fromList . map (tokenToExample posFeatSpec) $ s)) sentences
nbests = map (classifyBeam3 n c lemmatizer postagger . (\zp -> [(1,zp)])) zs
sentences' = zipWith bestTokSeq sentences nbests
mapM_ (UIO.putStrLn . unlines . map formatToken) sentences'
when (Eval `elem` flags) $ UIO.hPutStrLn stderr $ showAccuracy $ tokAccuracy' (concat sentences) (concat sentences')
eval _ (paramf:trainf:goldf:testf:_) = do
params <- fmap Prelude.read $ UIO.readFile paramf
train <- getToks trainf
gold <- getToks goldf
test <- getToks testf
let (lemmaFeatSpec,lemmaTrainParams) = getLemmaParams params
seen = Set.fromList (map tokenForm train)
isUnseen (form,_,_) = not (form `Set.member` seen)
all_acc = tokAccuracy' gold test
unseen_acc = tokAccuracy' (filter isUnseen gold) (filter isUnseen test)
goldses g = map (fromSES . justSES . tokenClass lemmaFeatSpec) g
uniqueSES = fromIntegral $ Set.size $ Set.fromList $ goldses gold
uniquePOS = fromIntegral $ Set.size $ Set.fromList $ map tokenPOS gold
bs_lemma_acc gs = (fromIntegral (length (filter isNullLemmaClass gs))
/ fromIntegral (length gs))
UIO.putStrLn $ "Accuracy all:\n" ++ showAccuracy all_acc
UIO.putStrLn $ "Accuracy unseen:\n" ++ showAccuracy unseen_acc
UIO.putStrLn $ "Baseline lemma all acc: " ++ show (bs_lemma_acc (goldses gold))
UIO.putStrLn $ "Baseline lemma unseen acc: " ++ show (bs_lemma_acc (goldses (filter isUnseen gold)))
UIO.putStrLn $ "Unique lemma-class: " ++ show uniqueSES
UIO.putStrLn $ "Unique morpho-tag: " ++ show uniquePOS
where getToks f = fmap (filter (not . isNullToken) . map parseToken . lines) (UIO.readFile f)
-- nbest::[(Double,[(Label,Label)])] -- nbest list of pairs of labels
bestTokSeq toks nbest = zipWith (\(f,ml,mp) (ses,pos) -> (f
, Just $ applyScript (getSES ses) f
, Just (getPOS pos)))
toks
best
where best = let x:_ = nbest in snd x
formatToken (f,ml,mp) = unwords [f,fromMaybe "" ml,fromMaybe "" mp]
formatTriple (f,ml,mp) = unwords [f,ml,mp]
bestClassSeq (_,xs:xss) = xs
seqProb x = product . map fst . left $ x
showPair (form,lemma) = unwords [form, lemma]
data Accuracy = Acc { lemmaAcc :: (Int,Int)
, posAcc :: (Int,Int) }
tokAccuracy' xs ys = tokAccuracy (map tokToPair xs) (map tokToPair ys)
where tokToPair (form,lemma,pos) = (fromMaybe form lemma,pos)
tokAccuracy xs ys = Acc { lemmaAcc = (correct $ lowercase . fst,total)
, posAcc = (correct snd,total) }
where total = length xs
correct f = length $ filter id $ zipWith (\x y -> f x == f y) xs ys
showAccuracy acc = unlines [ "Lemma acc: " ++ (showAcc . lemmaAcc) acc
, "POS acc: " ++ (showAcc . posAcc ) acc ]
showAcc (correct,total) = printf "%.2f%% (%d / %d)"
(100* (fromIntegral correct::Double)/(fromIntegral total::Double))
correct
total
|
gchrupala/morfette
|
src/GramLab/Morfette/OldMain.hs
|
bsd-2-clause
| 14,982
| 2
| 35
| 5,291
| 3,979
| 2,061
| 1,918
| 237
| 5
|
module Model where
import Model.Feed.Internal
import Model.Resource.Internal
import Data.ByteString (ByteString)
import Data.Text (Text)
import Data.Time (UTCTime)
import Data.Typeable (Typeable)
import Database.Persist.Quasi
import Prelude (Bool, Eq, Int, Ord)
import Yesod
import Yesod.Markdown (Markdown)
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
share [ mkPersist sqlSettings
, mkMigrate "migrateAll"
, mkDeleteCascade sqlSettings
]
$(persistFileWith lowerCaseSettings "config/models")
|
duplode/dohaskell
|
src/Model.hs
|
bsd-3-clause
| 735
| 0
| 8
| 167
| 131
| 78
| 53
| -1
| -1
|
module Helper where
import Diagrams.Prelude
import Diagrams.Backend.SVG
import Text.Blaze.Internal
spike :: Trail R2
spike = fromOffsets . map r2 $ [(1,3), (1,-3)]
burst = mconcat . take 13 . iterate (rotateBy (-1/13)) $ spike
colors = cycle [aqua, orange, deeppink, blueviolet, crimson, darkgreen]
example :: Diagram Diagrams.Backend.SVG.SVG R2
example = lw 1.0 . mconcat . zipWith lc colors . map stroke . explodeTrail origin $ burst
bar = renderDia SVG (SVGOptions "output.file" (Dims 200 200)) example
|
ekmett/ghclive
|
prototypes/multimport/cache/Helper.hs
|
bsd-3-clause
| 513
| 0
| 12
| 83
| 210
| 114
| 96
| 11
| 1
|
module UnitTests.Distribution.Utils.NubList
( tests
) where
import Data.Monoid
import Distribution.Utils.NubList
import Test.Framework
import Test.Framework.Providers.HUnit (testCase)
import Test.Framework.Providers.QuickCheck2
import Test.HUnit (Assertion, assertBool)
tests :: [Test]
tests =
[ testCase "Numlist retains ordering" testOrdering
, testCase "Numlist removes duplicates" testDeDupe
, testProperty "Monoid Numlist Identity" prop_Identity
, testProperty "Monoid Numlist Associativity" prop_Associativity
]
someIntList :: [Int]
-- This list must not have duplicate entries.
someIntList = [ 1, 3, 4, 2, 0, 7, 6, 5, 9, -1 ]
testOrdering :: Assertion
testOrdering =
assertBool "Maintains element ordering:" $
fromNubList (toNubList someIntList) == someIntList
testDeDupe :: Assertion
testDeDupe =
assertBool "De-duplicates a list:" $
fromNubList (toNubList (someIntList ++ someIntList)) == someIntList
-- ---------------------------------------------------------------------------
-- QuickCheck properties for NubList
prop_Identity :: [Int] -> Bool
prop_Identity xs =
mempty `mappend` toNubList xs == toNubList xs `mappend` mempty
prop_Associativity :: [Int] -> [Int] -> [Int] -> Bool
prop_Associativity xs ys zs =
(toNubList xs `mappend` toNubList ys) `mappend` toNubList zs
== toNubList xs `mappend` (toNubList ys `mappend` toNubList zs)
|
plumlife/cabal
|
Cabal/tests/UnitTests/Distribution/Utils/NubList.hs
|
bsd-3-clause
| 1,428
| 0
| 11
| 243
| 353
| 202
| 151
| 31
| 1
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Keymap.Vim.Common
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
--
-- Common types used by the vim keymap.
module Yi.Keymap.Vim.Common
( VimMode(..)
, VimBinding(..)
, GotoCharCommand(..)
, VimState(..)
, Register(..)
, RepeatToken(..)
, RepeatableAction(..)
, MatchResult(..)
, EventString(..), unEv
, OperatorName(..), unOp
, RegisterName
, module Yi.Keymap.Vim.MatchResult
, lookupBestMatch, matchesString
) where
import GHC.Generics (Generic)
import Control.Applicative (Alternative ((<|>)), (<$>))
import Control.Lens (makeLenses)
import Data.Binary (Binary (..))
import Data.Default (Default (..))
import qualified Data.HashMap.Strict as HM (HashMap)
import Data.Monoid (Monoid (mappend, mempty), (<>))
import Data.String (IsString (..))
import qualified Data.Text as T (Text, isPrefixOf, pack)
import qualified Data.Text.Encoding as E (decodeUtf8, encodeUtf8)
import Data.Typeable (Typeable)
import Yi.Buffer.Adjusted (Direction, Point, RegionStyle)
import Yi.Editor (EditorM)
import Yi.Keymap (YiM)
import Yi.Keymap.Vim.MatchResult (MatchResult (..))
import Yi.Rope (YiString)
import Yi.Types (YiVariable)
newtype EventString = Ev { _unEv :: T.Text } deriving (Show, Eq, Ord)
instance IsString EventString where
fromString = Ev . T.pack
newtype OperatorName = Op { _unOp :: T.Text } deriving (Show, Eq)
instance IsString OperatorName where
fromString = Op . T.pack
instance Monoid EventString where
mempty = Ev mempty
Ev t `mappend` Ev t' = Ev $ t <> t'
instance Monoid OperatorName where
mempty = Op mempty
Op t `mappend` Op t' = Op $ t <> t'
instance Binary EventString where
get = Ev . E.decodeUtf8 <$> get
put (Ev t) = put $ E.encodeUtf8 t
instance Binary OperatorName where
get = Op . E.decodeUtf8 <$> get
put (Op t) = put $ E.encodeUtf8 t
makeLenses ''EventString
makeLenses ''OperatorName
-- 'lookupBestMatch' and 'matchesString' pulled out of MatchResult
-- module to prevent cyclic dependencies. Screw more bootfiles.
lookupBestMatch :: EventString -> [(EventString, a)] -> MatchResult a
lookupBestMatch key = foldl go NoMatch
where go m (k, x) = m <|> fmap (const x) (key `matchesString` k)
matchesString :: EventString -> EventString -> MatchResult ()
matchesString (Ev got) (Ev expected)
| expected == got = WholeMatch ()
| got `T.isPrefixOf` expected = PartialMatch
| otherwise = NoMatch
type RegisterName = Char
type MacroName = Char
data RepeatableAction = RepeatableAction
{ raPreviousCount :: !Int
, raActionString :: !EventString
} deriving (Typeable, Eq, Show, Generic)
data Register = Register
{ regRegionStyle :: RegionStyle
, regContent :: YiString
} deriving (Generic)
data VimMode
= Normal
| NormalOperatorPending OperatorName
| Insert Char -- ^ char denotes how state got into insert mode ('i', 'a', etc.)
| Replace
| ReplaceSingleChar
| InsertNormal -- ^ after C-o
| InsertVisual -- ^ after C-o and one of v, V, C-v
| Visual RegionStyle
| Ex
| Search { previousMode :: VimMode, direction :: Direction }
deriving (Typeable, Eq, Show, Generic)
data GotoCharCommand = GotoCharCommand !Char !Direction !RegionStyle
deriving (Generic)
data VimState = VimState
{ vsMode :: !VimMode
, vsCount :: !(Maybe Int)
, vsAccumulator :: !EventString -- ^ for repeat and potentially macros
, vsTextObjectAccumulator :: !EventString
, vsRegisterMap :: !(HM.HashMap RegisterName Register)
, vsActiveRegister :: !RegisterName
, vsRepeatableAction :: !(Maybe RepeatableAction)
, vsStringToEval :: !EventString -- ^ see Yi.Keymap.Vim.vimEval comment
, vsStickyEol :: !Bool -- ^ is set on $, allows j and k walk the right edge of lines
, vsOngoingInsertEvents :: !EventString
, vsLastGotoCharCommand :: !(Maybe GotoCharCommand)
, vsBindingAccumulator :: !EventString
, vsSecondaryCursors :: ![Point]
, vsPaste :: !Bool -- ^ like vim's :help paste
, vsCurrentMacroRecording :: !(Maybe (MacroName, EventString))
} deriving (Typeable, Generic)
instance Binary RepeatableAction
instance Binary Register
instance Binary GotoCharCommand
instance Default VimMode where
def = Normal
instance Binary VimMode
instance Default VimState where
def = VimState
Normal -- mode
Nothing -- count
mempty -- accumulator
mempty -- textobject accumulator
mempty -- register map
'\0' -- active register
Nothing -- repeatable action
mempty -- string to eval
False -- sticky eol
mempty -- ongoing insert events
Nothing -- last goto char command
mempty -- binding accumulator
mempty -- secondary cursors
False -- :set paste
Nothing -- current macro recording
instance Binary VimState
instance YiVariable VimState
-- Whether an action can be repeated through the use of the '.' key.
--
-- Actions with a RepeatToken of:
--
-- - Finish are repeatable.
-- - Drop are not repeatable.
-- - Continue are currently in progress. They will become repeatable when
-- completed. It is possible to cancel a in progress action, in which case
-- it will not be repeatable.
data RepeatToken = Finish
| Drop
| Continue
deriving Show
-- Distinction between YiM and EditorM variants is for testing.
data VimBinding
= VimBindingY (EventString -> VimState -> MatchResult (YiM RepeatToken))
| VimBindingE (EventString -> VimState -> MatchResult (EditorM RepeatToken))
|
TOSPIO/yi
|
src/library/Yi/Keymap/Vim/Common.hs
|
gpl-2.0
| 6,378
| 0
| 12
| 1,777
| 1,351
| 788
| 563
| 177
| 1
|
module Language.Haskell.Refact.Utils.Synonyms where
import GHC
{-
This file has synonyms for commonly used AST parser types.
-}
type UnlocParsedHsBind = HsBindLR RdrName RdrName
type ParsedGRHSs = GRHSs RdrName (LHsExpr RdrName)
type ParsedMatchGroup = MatchGroup RdrName (LHsExpr RdrName)
type ParsedLMatch = LMatch RdrName (LHsExpr RdrName)
type ParsedExpr = HsExpr RdrName
type ParsedLExpr = LHsExpr RdrName
type ParsedLStmt = LStmt RdrName (LHsExpr RdrName)
type ParsedBind = HsBind RdrName
|
RefactoringTools/HaRe
|
src/Language/Haskell/Refact/Utils/Synonyms.hs
|
bsd-3-clause
| 535
| 0
| 7
| 106
| 119
| 67
| 52
| 10
| 0
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="pt-BR">
<title>SVN Digger Files</title>
<maps>
<homeID>svndigger</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/svndigger/src/main/javahelp/help_pt_BR/helpset_pt_BR.hs
|
apache-2.0
| 967
| 77
| 66
| 157
| 409
| 207
| 202
| -1
| -1
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="tr-TR">
<title>FuzzDB Files</title>
<maps>
<homeID>fuzzdb</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
denniskniep/zap-extensions
|
addOns/fuzzdb/src/main/javahelp/help_tr_TR/helpset_tr_TR.hs
|
apache-2.0
| 960
| 77
| 66
| 156
| 407
| 206
| 201
| -1
| -1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
#ifndef MIN_VERSION_base
#define MIN_VERSION_base(x,y,z) 0
#endif
module Data.Machine.Runner
( foldrT
, foldlT
, foldMapT
, foldT
, runT1
-- Re-exports
, runT
, runT_ ) where
import Data.Machine.Type
import Control.Monad (liftM)
#if !MIN_VERSION_base (4,8,0)
import Data.Monoid (Monoid (..))
#endif
-- | Right fold over a stream. This will be lazy if the underlying
-- monad is.
--
-- @runT = foldrT (:) []@
foldrT :: Monad m => (o -> b -> b) -> b -> MachineT m k o -> m b
foldrT c n = go
where
go m = do
step <- runMachineT m
case step of
Stop -> return n
Yield o m' -> c o `liftM` go m'
Await _ _ m' -> go m'
-- | Strict left fold over a stream.
foldlT :: Monad m => (b -> o -> b) -> b -> MachineT m k o -> m b
foldlT f = go
where
go !b m = do
step <- runMachineT m
case step of
Stop -> return b
Yield o m' -> go (f b o) m'
Await _ _ m' -> go b m'
-- | Strict fold over a stream. Items are accumulated on the right:
--
-- @... ((f o1 <> f o2) <> f o3) ...@
--
-- Where this is expensive, use the dual monoid instead.
foldMapT :: (Monad m, Monoid r) => (o -> r) -> MachineT m k o -> m r
foldMapT f = foldlT (\b o -> mappend b (f o)) mempty
-- | Strict fold over a monoid stream. Items are accumulated on the
-- right:
--
-- @... ((o1 <> o2) <> o3) ...@
--
-- Where this is expensive, use the dual monoid instead.
--
-- @foldT = foldMapT id@
foldT :: (Monad m, Monoid o) => MachineT m k o -> m o
foldT = foldlT mappend mempty
-- | Run a machine with no input until it yields for the first time,
-- then stop it. This is intended primarily for use with accumulating
-- machines, such as the ones produced by 'fold' or 'fold1'
--
-- @runT1 m = getFirst <$> foldMapT (First . Just) (m ~> taking 1)@
runT1 :: Monad m => MachineT m k o -> m (Maybe o)
runT1 m = do
step <- runMachineT m
case step of
Stop -> return Nothing
Yield o _ -> return $ Just o
Await _ _ m' -> runT1 m'
|
bitemyapp/machines
|
src/Data/Machine/Runner.hs
|
bsd-3-clause
| 2,089
| 0
| 14
| 583
| 578
| 300
| 278
| 40
| 3
|
module Case3 where
data T = C1 Int Int | C2 Int
f (C1 x y) = 56
caseIt x = case x of
42 -> 1 + f (C1 1 2)
where
f (C1 x y) = x + y
f x = 9
|
kmate/HaRe
|
old/testing/removeCon/Case3.hs
|
bsd-3-clause
| 217
| 0
| 12
| 123
| 99
| 51
| 48
| 7
| 2
|
module PfeBrowserMonad where
import Maybe(isJust)
import Monad(when)
import MT(lift)
import AbstractIO
import FudgetIOMonad1
import PfePlumbing
import PfeBrowserMenu(WindowCmd,ViewCmd,MenuCmd(..),WindowCmd(..))
import PfeBrowserGUI
import PNT(PNT)
import SimpleGraphs(Graph)
import PropParser(parse)
import PropLexer({-LexerFlags,-}pLexerPass0)
import PPU(PPHsMode)
import TiPropDecorate(TiDecls) -- to choose result type from the type checker
import PropPosSyntax(Id,HsName,HsDecl)
import FreeNamesProp()
import ScopeNamesProp()
import NameMapsProp()
import ReAssocProp()
import MapDeclMProp() -- for removing pattern bindings in Pfe3Cmds.
--import TiModule() -- instance ValueId PNT
import TiProp()
import PFE4
import PFEdeps
import PFE0
import PFE_Certs
import CertCmd(CertCmd)
type Opts = ({-LexerFlags,-}((Bool, PPHsMode), String, [String]))
-- PFE Browser monad:
--type PfeFM = PFE0MT Id HsName [HsDecl] () (WithState PfeBrowserState FIOM)
--type PfeFM = WithState PfeBrowserState (PFE0MT Id HsName [HsDecl] () FIOM)
type PfeFM = PFE5MT Id HsName PNT [HsDecl] (TiDecls PNT) PfeBrowserState FIOM
runPfeFM pfeFM ({-lexeropts,-}opts) =
runPFE5 undefined (\n a->pfeFM) (pLexerPass0 {-lexeropts-},parse) opts
pfeGet = lift getFM :: PfeFM In
pfePut = lift . putFM
pfeQuit = lift quitFM
withWaitCursor :: PfeFM a -> PfeFM a -- polymorphic recursion...
withWaitCursor cmd =
do pfePut (toSource setwaitcursor)
tryThen cmd $ pfePut (toSource setnormalcursor)
putInfoWindow (w,x) = pfePut . toInfoWindows $ (w,Right x)
popupInfoWindow (w,up) =
do pfePut (toMenuBar (Windows (WindowCmd w up)))
when (not up && w==CertInfo) $
updStBr $ \ st ->st{certDisplay=Nothing}
popupCertInfo qcert info =
do putInfoWindow (CertInfo,info)
popupInfoWindow (CertInfo,True)
updStBr $ \ st -> st{certDisplay=Just qcert}
getStBr :: PfeFM PfeBrowserState
updStBr :: (PfeBrowserState->PfeBrowserState)->PfeFM ()
getStBr = getSt5ext
updStBr = updSt5ext
setStBr = updStBr . const
type TInfo = PFE4Info PNT (TiDecls PNT)
type ViewMode = ViewCmd
data PfeBrowserState
= St { -- Mode
viewMode :: ViewMode,
-- The selected module:
modnode::ModuleNode,
mrefs::[XRefInfo],hilbls::[Label],
types::Maybe TInfo,
certs::[CertInfo],
-- Project info:
revgraph::Graph ModuleName,
-- Cert display/state info:
certDisplay :: Maybe QCertName, -- currently displayed cert
certInProgress :: [CertCmd], -- server command in progress or queued
-- Project independent info:
certServers :: CertServers,
certIcons :: CertIcons,
sadIcon :: PixmapImage }
haveTypes = isJust . types
modname = fst . snd . modnode
noModuleNode = ("",(undefined,[])) -- for the initial state
isNoModule (path,_) = null path
--sccs = fst . snd . pfe2info
--graph = concat . sccs
icons st = (sadIcon st,certIcons st)
|
forste/haReFork
|
tools/pfe/Browser/PfeBrowserMonad.hs
|
bsd-3-clause
| 2,860
| 22
| 13
| 470
| 826
| 479
| 347
| 72
| 1
|
module CaesarCipher_Test ( main ) where
import CaesarCipher
main = do
putStrLn "The message \"Haskell is awesome\" encoded with a shift of 5 characters: "
putStrLn $ encode 5 "Haskell is awesome"
putStrLn "The message \"Mfxpjqq%nx%f|jxtrj\" decoded with a shift of 5 characters: "
putStrLn $ decode 5 "Mfxpjqq%nx%f|jxtrj"
|
kennyledet/Algorithm-Implementations
|
Caesar_Cipher/Haskell/warreee/CaesarCipher_test.hs
|
mit
| 339
| 0
| 8
| 66
| 53
| 25
| 28
| 7
| 1
|
module B043.C where
|
urbanslug/ghc
|
testsuite/tests/driver/B043/C.hs
|
bsd-3-clause
| 20
| 0
| 3
| 3
| 6
| 4
| 2
| 1
| 0
|
{-# LANGUAGE GADTs #-}
{-# OPTIONS_GHC -Wall #-}
module W where
import T5424a
data D a where
C1 :: D X
C2 :: D Y
f :: D X -> Int
f C1 = 1
|
wxwxwwxxx/ghc
|
testsuite/tests/gadt/T5424.hs
|
bsd-3-clause
| 152
| 0
| 6
| 49
| 50
| 29
| 21
| 9
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module DiG.GitCmd where
import System.Process (createProcess, CreateProcess(..), StdStream(CreatePipe, UseHandle), proc, shell)
import System.IO (Handle)
import Data.ByteString.Char8 (ByteString, hGetContents, append, unpack)
(~~) :: ByteString -> ByteString -> ByteString
(~~) = append
(~+) :: ByteString -> ByteString -> String
a ~+ b = unpack $ a ~~ b
data Repo = Repo String
posProcessor :: Handle -> ByteString -> IO Handle
posProcessor out cmd = do
(_ , Just hOut, _, _) <-
createProcess cmd' { std_in = UseHandle out
, std_out = CreatePipe }
return hOut
where
cmd' = shell $ unpack cmd
fileAtTag :: Repo -> ByteString -> Maybe ByteString -> ByteString -> Maybe ByteString -> IO ByteString
fileAtTag (Repo dir) tag root file posProc = do
(_ , Just hOut, _, _) <-
createProcess (proc "git" ["show", fileRef root file])
{ cwd = Just dir
, std_out = CreatePipe }
hOut' <- maybe (return hOut) (posProcessor hOut) posProc
putStrLn $ "Getting contents for: " ++ fileRef root file
hGetContents hOut'
where
fileRef (Just r) f = (tag ~~ ":" ~~ r ~~ "/") ~+ f
fileRef Nothing f = (tag ~~ ":") ~+ f
fileAtTagWithPrefixSuffix :: Repo -> ByteString -> ByteString -> Maybe ByteString -> ByteString -> Maybe ByteString -> IO ByteString
fileAtTagWithPrefixSuffix repo prefix suffix root file posProc = fileAtTag repo tag root file posProc
where
tag = prefix ~~ "-" ~~ suffix
|
oforero/DiG
|
src/DiG/GitCmd.hs
|
mit
| 1,603
| 0
| 13
| 432
| 527
| 279
| 248
| 31
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Lib
(
-- * Data Structures
Suite,
Doc,
System,
Module,
-- * Main function
suiteParser
) where
-- import Control.Applicative ((<$>), (<*>), (<*), (*>), (<|>), many, (<$))
import Control.Monad
import Data.Char (isDigit, isLetter)
import Data.String.Utils
import Text.Parsec
import Text.Parsec.String
import Text.ParserCombinators.Parsec
-- |Full test suite
data Suite = Suite
{
suiteId :: Integer
, suiteName :: String
, doc :: Doc
, systems :: [System]
} deriving (Show)
data Doc = Doc
{
title :: String
, comments :: String
} deriving (Show)
data System = System
{
systemId :: Integer
, systemName :: String
, modules :: [Module]
} deriving (Show)
data Module = Module
{
moduleId :: Integer
, moduleTec :: String
, moduleName :: String
, functions :: [Function]
} deriving(Show)
data Function = Function
{
functionId :: Integer
, functionDesc :: String
} deriving (Show)
data TestCase = TestCase
{
testCaseId :: Integer
, testCaseDesc :: String
, testCaseComment :: String
--, preCond :: [String]
--, steps :: [Steps]
} deriving (Show)
data Steps = SimpleStep
{
stepNumber :: Integer
, stepComment :: String
, sets :: [TwoFoldStep]
}
| ExecStep
{
execContent :: String
}
| TestStep
{
set :: TwoFoldStep
}
deriving (Show)
data TwoFoldStep = TwoFoldStepS String String
| TwoFoldStepI String Integer
deriving (Show)
-- |Full parser, returns a Suite if received a correct input
suiteParser :: Parser Suite
suiteParser = do
n <- identifyCode "Suite"
name <- ident
_ <- endOfLine
doc <- parseDoc
syst <- many systemParser
return (Suite n (rstrip name) doc syst)
-- |Test Case
testCaseParser :: Parser TestCase
testCaseParser = TestCase
<$> identifyCode "C"
<*> (lexeme (string "=>") *> ident)
<*> parseTitle
-- |Function
functionParser :: Parser Function
functionParser = Function
<$> identifyCode "F"
<*> (lexeme (string "=>") *> ident)
-- |Module
moduleParser :: Parser Module
moduleParser = Module
<$> identifyCode "M"
<*> lexeme (char '(' *> ident <* char ')')
<*> (lexeme (string "=>") *> ident)
<*> many functionParser
-- |System, a parser...
systemParser :: Parser System
systemParser = System
<$> identifyCode "SYST"
<*> (lexeme (string "=>") *> ident)
<*> many moduleParser
-- |Documentation, a title and a bunch of lines.
parseDoc :: Parser Doc
parseDoc = Doc
<$> parseTitle
<*> parseComs
-- |Parsing a title or a one line comment
parseTitle :: Parser String
parseTitle = whitespace
*> symbol "#"
*> identifier
<* optional endOfLine
-- |Parsing a line for a multine comment
parseComs' :: Parser String
parseComs' = whitespace
*> symbol "--"
*> identifier
<* endOfLine
parseComs :: Parser String
parseComs = concat
<$> many1 parseComs'
-- From here, the utilities
-- |Starts with spaces, a keyword and a number....
identifyCode :: String -> Parser Integer
identifyCode t = whitespaceBeg
*> lexeme (string t)
*> integer
-- |A id with spaces (multi-word). As a non desired effect, this returns all
-- all trailling spaces to EOL
ident :: Parser String
ident = (++) <$> many1 alphaNum <*> many (oneOf " \t" <|> alphaNum)
-- |Clean the whitespace, beggining of line
whitespaceBeg :: Parser ()
whitespaceBeg = void $ many $ oneOf " \t\n"
-- |Clean the whitespace...
whitespace :: Parser ()
whitespace = void $ many $ oneOf " \t"
-- |Left the whitespaces for hungries gnomes
lexeme :: Parser a -> Parser a
lexeme p = p <* whitespace
-- |Reading an number, an integer
integer :: Parser Integer
integer = read <$> lexeme (many1 digit)
-- |An identifier
identifier :: Parser String
identifier = (:) <$> firstChar <*> many nonFirstChar
where
firstChar = letter <|> char '_' <|> westEuropeLetter
nonFirstChar = digit <|> firstChar <|> punctuationMark <|> oneOf " \t"
-- |Well, this is a parser mainly for european audiences...
westEuropeLetter :: Parser Char
westEuropeLetter = oneOf "áéíóúÁÉÍÓÚñÑçÇ"
-- |More letters
punctuationMark :: Parser Char
punctuationMark = oneOf ".¡!¿?.-_()/\"'&%$ºª"
-- |A parser for a String with a lexeme
symbol :: String -> Parser String
symbol s = lexeme $ string s
-- |A number
num :: Parser Integer
num = read <$> many1 digit
regularParse :: Parser a -> String -> Either ParseError a
regularParse p = parse p ""
|
gargoris/SpiderBike
|
src/Lib.hs
|
mit
| 5,494
| 0
| 12
| 1,978
| 1,125
| 613
| 512
| 129
| 1
|
-- This module defines the internal language syntax.
{-# LANGUAGE DeriveFunctor #-}
module Ast (
Type(..),
Term(..),
Command(..),
Prog(..)
) where
import Data.List (intercalate)
import Symtab (Id(..))
-------
-- Types
data Type =
TyBool
| TyNat
| TyArrow Type Type
deriving (Eq)
-------
-- Terms
-- Terms are parameterized by the type of extra information (their type,
-- location in source file, etc)
data Term info =
TmVar info Id
| TmAbs info Id Type (Term info)
| TmApp info (Term info) (Term info)
| TmTrue info
| TmFalse info
| TmIf info (Term info) (Term info) (Term info)
| TmZero info
| TmSucc info (Term info)
| TmPred info (Term info)
| TmIszero info (Term info)
| TmFix info (Term info)
deriving (Eq, Functor)
-----------
-- Commands
-- A command either binds a term to an Id in the global context, or
-- evaluates a term to a normal form.
data Command info =
CBind info Id (Term info)
| CEval info (Term info)
deriving (Eq, Functor)
----------
-- Program
data Prog info =
Prog { pinfo_of :: info,
prog_of :: [Command info] }
deriving (Eq, Functor)
----------------------
-- Typeclass Instances
instance Show Type where
show TyBool = "bool"
show TyNat = "nat"
show (TyArrow t1 t2) = show t1 ++ "->" ++ show t2
instance Show (Term info) where
show (TmVar _ id) = show id
show (TmAbs _ id ty t) = "(\\" ++ show id ++ ":" ++ show ty ++
" => " ++ show t ++ ")"
show (TmApp _ t1 t2) = "(" ++ show t1 ++ " " ++ show t2 ++ ")"
show (TmTrue _) = "true"
show (TmFalse _) = "false"
show (TmIf _ t1 t2 t3) = "if " ++ show t1 ++ " then " ++
show t2 ++ " else " ++ show t3
show (TmZero _) = "0"
show (TmSucc _ t) = "(succ " ++ show t ++ ")"
show (TmPred _ t) = "(pred " ++ show t ++ ")"
show (TmIszero _ t) = "(iszero " ++ show t ++ ")"
show (TmFix _ t) = "(fix " ++ show t ++ ")"
-- instance Show (Term info) where
-- show (TmVar _ id) = show id
-- show (TmAbs _ id ty t) = "(TmAbs " ++ show id ++ " " ++ show ty ++
-- " " ++ show t ++ ")"
-- show (TmApp _ t1 t2) = "(TmApp " ++ show t1 ++ " " ++ show t2 ++ ")"
-- show (TmTrue _) = "true"
-- show (TmFalse _) = "false"
-- show (TmIf _ t1 t2 t3) = "(TmIf " ++ show t1 ++ " " ++ show t2 ++
-- " " ++ show t3 ++ ")"
-- show (TmZero _) = "0"
-- show (TmSucc _ t) = "(succ " ++ show t ++ ")"
-- show (TmPred _ t) = "(pred " ++ show t ++ ")"
-- show (TmIszero _ t) = "(iszero " ++ show t ++ ")"
-- show (TmFix _ t) = "(fix " ++ show t ++ ")"
instance Show (Command info) where
show (CBind _ (Id s) t) = s ++ " = " ++ show t
show (CEval _ t) = "eval " ++ show t
instance Show (Prog info) where
show (Prog { prog_of = p }) = intercalate ", " (map show p)
|
bagnalla/PCF
|
src/Ast.hs
|
mit
| 2,952
| 0
| 12
| 923
| 848
| 455
| 393
| 57
| 0
|
{-|
Module: Flaw.Audio
Description: Audio abstraction.
License: MIT
-}
{-# LANGUAGE LambdaCase, TypeFamilies #-}
module Flaw.Audio
( Device(..)
, SoundFormat(..)
, SoundSampleType(..)
, soundSampleSize
) where
import Control.Concurrent.STM
import qualified Data.ByteString as B
import Flaw.ByteStream
import Flaw.Math
class Device d where
-- | Sound type.
data SoundId d :: *
-- | Type of sound player.
data SoundPlayerId d :: *
-- | Create buffered sound.
createSound :: d -> SoundFormat -> B.ByteString -> IO (SoundId d, IO ())
-- | Create streaming sound.
-- Streaming sound player pulls sound data from bounded queue.
createStreamingSound :: d -> IO ((SoundFormat, ByteStream), IO ()) -> IO (SoundId d, IO ())
-- | Create player for a sound.
createSoundPlayer :: SoundId d -> IO (SoundPlayerId d, IO ())
-- | Apply deferred updates to all sound objects simultaneously.
tickAudio :: d -> IO ()
-- | Start playing.
playSound :: SoundPlayerId d -> STM ()
-- | Start playing a loop.
playLoopSound :: SoundPlayerId d -> STM ()
-- | Pause playing.
pauseSound :: SoundPlayerId d -> STM ()
-- | Stop playing.
stopSound :: SoundPlayerId d -> STM ()
-- | Set position of sound player.
setSoundPosition :: SoundPlayerId d -> Float3 -> STM ()
-- | Set direction of sound player.
setSoundDirection :: SoundPlayerId d -> Float3 -> STM ()
-- | Set velocity of sound player.
setSoundVelocity :: SoundPlayerId d -> Float3 -> STM ()
-- | Sound format type.
data SoundFormat = SoundFormat
{ soundFormatSamplesPerSecond :: {-# UNPACK #-} !Int
, soundFormatSampleType :: !SoundSampleType
, soundFormatChannelsCount :: {-# UNPACK #-} !Int
} deriving Show
-- | Sound sample type.
data SoundSampleType
= SoundSampleByte
| SoundSampleShort
| SoundSampleInt
| SoundSampleFloat
| SoundSampleDouble
deriving Show
-- | Size of a single sample.
soundSampleSize :: SoundSampleType -> Int
soundSampleSize = \case
SoundSampleByte -> 1
SoundSampleShort -> 2
SoundSampleInt -> 4
SoundSampleFloat -> 4
SoundSampleDouble -> 8
|
quyse/flaw
|
flaw-audio/Flaw/Audio.hs
|
mit
| 2,095
| 0
| 13
| 417
| 461
| 257
| 204
| 45
| 5
|
module Main where
import Types
import Instances
import Usage
main :: IO ()
main = return ()
|
mkloczko/derive-storable-plugin
|
test/ids/NewTypeParam/Main.hs
|
mit
| 95
| 0
| 6
| 20
| 33
| 19
| 14
| 6
| 1
|
-- REMOVE THIS DECLARATION WHEN UPLOADING THE FILE TO www.codeeval.com!!!
module FizzBuzz where
import System.Environment (getArgs)
main :: IO ()
main = do
[file] <- getArgs
input <- readFile file
mapM_ (putStrLn . fizzBuzz) $ lines input
fizzBuzz :: String -> String
fizzBuzz line = toSpacedString . process $ parse line
data Input = Input Int Int Int
data Output = Number Int | F | B | FB
instance Show Output where
show (Number num) = show num
show F = "F"
show B = "B"
show FB = "FB"
parse :: String -> Input
parse line = Input x y n
where [x, y, n] = map read $ words line
process :: Input -> [Output]
process (Input x y n) = map checkFizzBuzz [1..n]
where checkFizzBuzz i | i `rem` x == 0 && i `rem` y == 0 = FB
| i `rem` x == 0 = F
| i `rem` y == 0 = B
| otherwise = Number i
toSpacedString :: (Show a) => [a] -> String
toSpacedString [] = ""
toSpacedString [x] = show x
toSpacedString (x : xs) = show x ++ " " ++ toSpacedString xs
|
RaphMad/CodeEval
|
src/FizzBuzz.hs
|
mit
| 1,139
| 0
| 14
| 395
| 433
| 223
| 210
| 29
| 1
|
module FluxSyntax where
type Name = String
data Expr
= Float Double
| BinOp Op Expr Expr
| UnOp Op Expr
| Var String
| Call Name [Expr]
| Function Name [Expr] Expr
| Extern Name [Expr]
| If Expr Expr Expr
| For Name Expr Expr Expr Expr
| Let Name Expr Expr
| Flow Name Expr
deriving (Eq, Ord, Show)
data Op
= Plus
| Minus
| Times
| Divide
| LessThan
deriving (Eq, Ord, Show)
|
chris-wood/flux
|
src/FluxSyntax.hs
|
mit
| 450
| 0
| 7
| 153
| 159
| 92
| 67
| 22
| 0
|
module Config where
--------------------
-- Global Imports --
import Graphics.Rendering.OpenGL
import Linear.V2
----------
-- Code --
-- | The render width of the screen.
renderWidth :: Int
renderWidth = 640
-- | The render width of the screen in an OpenGL format.
glRenderWidth :: GLint
glRenderWidth = fromIntegral renderWidth
-- | The render height of the screen.
renderHeight :: Int
renderHeight = 640
-- | The render height of the screen in an OpenGL format.
glRenderHeight :: GLint
glRenderHeight = fromIntegral renderHeight
-- | The render size of the screen.
renderSize :: V2 Int
renderSize = V2 renderWidth renderHeight
-- | A float version of @'renderSize'@.
renderSizeF :: V2 Float
renderSizeF = fmap fromIntegral renderSize
-- | The width of the grid.
gridWidth :: Int
gridWidth = 20
-- | The height of the grid.
gridHeight :: Int
gridHeight = 20
-- | The size of the grid.
gridSize :: V2 Int
gridSize = V2 gridWidth gridHeight
-- | The width of a block in the grid.
blockWidth :: Float
blockWidth = (fromIntegral renderWidth) / (fromIntegral gridWidth)
-- | The height of a block in the grid.
blockHeight :: Float
blockHeight = (fromIntegral renderHeight) / (fromIntegral gridHeight)
-- | The size of a block in the grid.
blockSize :: V2 Float
blockSize = V2 blockWidth blockHeight
-- | The time between updating the game (in seconds).
updateStep :: Fractional a => a
updateStep = 0.3
|
crockeo/netwire-vinyl
|
src/Config.hs
|
mit
| 1,413
| 0
| 7
| 250
| 239
| 138
| 101
| 29
| 1
|
import Text.ParserCombinators.Parsec
import Data.Char
main = do {putStr "\nExpressao:";
e <- getLine;
case avaliarExpr e of
Left err -> putStr ((show err)++ "\n")
Right r -> putStr ((show r) ++ "\n")}
avaliarExpr e = parse expr "Erro:" e
ret v1 Nothing = v1
ret v1 (Just (op, v2)) = op v1 v2
-- Especificacao sintatica
expr = do v1 <- term -- E -> TE'
e <- expr'
return (ret v1 e)
expr' = do {char '+'; -- E' -> +TE'
v1 <- term;
e <- expr';
return (Just ((+), ret v1 e))}
<|>
do {char '-'; -- E' -> -TE'
v1 <- term;
e <- expr';
return (Just ((-), ret v1 e))}
<|> return Nothing -- E' -> vazio
term = do v1 <- fator -- T -> FT'
e <- term'
return (ret v1 e)
term' = do {char '*'; -- T' -> *FT'
v1 <- fator;
e <- term';
return (Just ((*), ret v1 e))}
<|>
do {char '/'; -- T' -> /FT'
v1 <- fator;
e <- term';
return (Just ((/), ret v1 e))}
<|> return Nothing -- T' -> vazio
fator = num -- F -> numero
<|> do {char '('; e <- expr; char ')'; return e} -- F -> (E)
-- Especificacao lexica
num = floating <|> decimal
floating
= do {n <- decimal;
frac <- fraction;
return (n+frac)}
decimal
= do digits <- many1 digit;
let n = foldl (\x d -> 10*x + toInteger (digitToInt d)) 0 digits
return (fromIntegral n)
fraction = do {char '.';
digits <- many1 digit;
return (foldr op 0.0 digits)}
<|> return 0
where
op d f = (f + fromIntegral (digitToInt d))/10.0
|
AndressaUmetsu/PapaEhPop
|
parser/exprParsec.hs
|
mit
| 1,711
| 35
| 16
| 645
| 728
| 371
| 357
| 52
| 2
|
{-# LANGUAGE CPP, NoImplicitPrelude, PackageImports #-}
module Data.Either.Compat (
module Base
) where
import "base-compat" Data.Either.Compat as Base
|
haskell-compat/base-compat
|
base-compat-batteries/src/Data/Either/Compat.hs
|
mit
| 155
| 0
| 4
| 21
| 23
| 17
| 6
| 4
| 0
|
module Functions.Product (productFunctionS) where
import Notes
import Functions.Application.Macro
import Functions.Basics.Macro
import Functions.Basics.Terms
import Functions.Product.Macro
import Functions.Product.Terms
productFunctionS :: Note
productFunctionS = section "Product functions" $ do
directProductFunctionDefinition
focussedProductFunctionDefinition
directProductFunctionDefinition :: Note
directProductFunctionDefinition = de $ do
lab directProductDefinitionLabel
lab directProductFunctionDefinitionLabel
let i = "i"
a = ("A" !:)
ai = a i
b = ("B" !:)
bi = b i
f_ = ("f" !:)
f i = fn (f_ i)
fi_ = f_ i
fl = list (f_ 1) (f_ 2) (f_ i)
s ["Let", m fl, "be a list of", functions, m $ fun fi_ ai bi]
let pf = dprodfunlist (f_ 1) (f_ 2) (f_ i)
s [the, directProduct', or, directProductFunction, m pf, "of the", functions, m fl, "is defined as the following", function]
let as = tuplelist (a 1) (a 2) (a i)
bs = tuplelist (b 1) (b 2) (b i)
aa = ("a" !:)
aas = tuplelist (aa 1) (aa 2) (aa i)
bbs = tuplelist (f 1 $ aa 1) (f 2 $ aa 2) (f i $ aa i)
ma $ func pf as bs aas bbs
focussedProductFunctionDefinition :: Note
focussedProductFunctionDefinition = de $ do
lab focussedProductDefinitionLabel
lab focussedProductFunctionDefinitionLabel
let i = "i"
a = "A"
b = ("B" !:)
bi = b i
f_ = ("f" !:)
f i = fn (f_ i)
fi_ = f_ i
fl = list (f_ 1) (f_ 2) (f_ i)
s ["Let", m fl, "be a list of", functions, m $ fun fi_ a bi]
let pf = fprodfunlist (f_ 1) (f_ 2) (f_ i)
s [the, focussedProduct', or, focussedProductFunction, m pf, "of the", functions, m fl, "is defined as the following", function]
let bs = tuplelist (b 1) (b 2) (b i)
aa = "a"
bbs = tuplelist (f 1 aa) (f 2 aa) (f i aa)
ma $ func pf a bs aa bbs
|
NorfairKing/the-notes
|
src/Functions/Product.hs
|
gpl-2.0
| 2,020
| 0
| 14
| 625
| 808
| 416
| 392
| 52
| 1
|
module E2ASM.Assembler.Parser
( parse
, parseDirective
, parseInstruction
, ParserState
, mkParserState
) where
import qualified Data.Map as Map
import qualified Data.Text as T
import qualified Data.Word as W
import qualified Text.Parsec as P
import qualified E2ASM.Assembler.AST as AST
import qualified E2ASM.Assembler.Diagnostics as Diag
import qualified E2ASM.Assembler.Directive as Dir
import qualified E2ASM.Assembler.Instruction as Instr
import qualified E2ASM.Assembler.Label as Lab
import qualified E2ASM.Assembler.Number as Num
import qualified E2ASM.Assembler.Predicate as Pred
import qualified E2ASM.Assembler.Register as Reg
import qualified E2ASM.Assembler.Token as Tok
data ParserState =
ParserState (Map.Map T.Text W.Word32) W.Word32
deriving (Eq, Show)
mkParserState :: ParserState
mkParserState = ParserState Map.empty 0
type Parser = P.Parsec [Tok.Token] ParserState
parse :: Parser (AST.AST, ParserState)
parse = do
nodes <- P.many parsers
state <- P.getState
return (AST.AST nodes, state)
where
parsers :: Parser AST.Node
parsers = P.choice
[parseLabel, parseDirective, parseInstruction]
parseLabel :: Parser AST.Node
parseLabel = do
lab <- labelDef
ParserState m pc <- P.getState
let t = Lab.getLabelText lab
if t `Map.member` m then do
Diag.fatal $ "Label " ++ show t ++ " already defined."
else do
let m' = Map.insert t pc m
P.putState (ParserState m' pc)
return . AST.NLabel $ lab
parseDirective :: Parser AST.Node
parseDirective = do
dir <- directive
args <- parseArgument `P.sepBy1` separator
ParserState m pc <- P.getState
let
len = fromIntegral $ length args
pc' = pc + case dir of
Dir.DB -> 1 * len
Dir.DH -> 2 * len
Dir.DW -> 4 * len
P.putState (ParserState m pc')
return $ AST.NDirective dir args
where
parseArgument :: Parser AST.Argument
parseArgument = number >>= \n -> return $ AST.ANumber n
parseInstruction :: Parser AST.Node
parseInstruction = do
maybePred <- P.optionMaybe parseParenPred
instr <- instruction
args <- parseArgument `P.sepBy1` separator
ParserState m pc <- P.getState
let p = maybe Pred.p0 id maybePred
if pc `mod` 4 /= 0 then do
Diag.fatal $ "The address is not aligned."
else do
P.putState (ParserState m (pc + 4))
return $ AST.NInstruction instr p args
where
parseParenPred :: Parser Pred.Predicate
parseParenPred = lparen *> predicate <* rparen
parseArgument :: Parser AST.Argument
parseArgument = regArg P.<|> predArg P.<|> labelArg P.<|> numArg
where
labelArg :: Parser AST.Argument
labelArg = labelRef >>= \l -> return $ AST.ALabel l
regArg :: Parser AST.Argument
regArg = register >>= \r -> return $ AST.ARegister r
predArg :: Parser AST.Argument
predArg = predicate >>= \p -> return $ AST.APredicate p
numArg :: Parser AST.Argument
numArg = number >>= \n -> return $ AST.ANumber n
labelDef :: Parser Lab.Label
labelDef = P.token show getPos check
where
check :: Tok.Token -> Maybe Lab.Label
check (Tok.Token (Tok.TLabelDef l) _) = Just l
check _ = Nothing
labelRef :: Parser Lab.Label
labelRef = P.token show getPos check
where
check :: Tok.Token -> Maybe Lab.Label
check (Tok.Token (Tok.TLabelRef l) _) = Just l
check _ = Nothing
directive :: Parser Dir.Directive
directive = P.token show getPos check
where
check :: Tok.Token -> Maybe Dir.Directive
check (Tok.Token (Tok.TDir d) _) = Just d
check _ = Nothing
instruction :: Parser Instr.Instruction
instruction = P.token show getPos check
where
check :: Tok.Token -> Maybe Instr.Instruction
check (Tok.Token (Tok.TInstr i) _) = Just i
check _ = Nothing
predicate :: Parser Pred.Predicate
predicate = P.token show getPos check
where
check :: Tok.Token -> Maybe Pred.Predicate
check (Tok.Token (Tok.TPred p) _) = Just p
check _ = Nothing
register :: Parser Reg.Register
register = P.token show getPos check
where
check :: Tok.Token -> Maybe Reg.Register
check (Tok.Token (Tok.TReg r) _) = Just r
check _ = Nothing
number :: Parser Num.Number
number = P.token show getPos check
where
check :: Tok.Token -> Maybe Num.Number
check (Tok.Token (Tok.TNum n) _) = Just n
check _ = Nothing
separator :: Parser ()
separator = P.token show getPos check
where
check :: Tok.Token -> Maybe ()
check (Tok.Token (Tok.TSep _) _) = Just ()
check _ = Nothing
lparen :: Parser ()
lparen = P.token show getPos check
where
check :: Tok.Token -> Maybe ()
check (Tok.Token (Tok.TLParen _) _) = Just ()
check _ = Nothing
rparen :: Parser ()
rparen = P.token show getPos check
where
check :: Tok.Token -> Maybe ()
check (Tok.Token (Tok.TRParen _) _) = Just ()
check _ = Nothing
getPos :: Tok.Token -> P.SourcePos
getPos (Tok.Token _ p) = p
|
E2LP/e2asm
|
src/E2ASM/Assembler/Parser.hs
|
gpl-3.0
| 5,375
| 0
| 14
| 1,552
| 1,786
| 920
| 866
| 135
| 3
|
-- Leftist heap definition similar to that in PFDS Appendix A, p 197, but using
-- Maybe for operations that might fail.
{-# OPTIONS_GHC -XMultiParamTypeClasses #-}
{-# OPTIONS_GHC -XFlexibleInstances #-}
module LeftistHeap(
LeftistHeap(E, T), empty, isEmpty, insert, merge,
findMin, deleteMin, rank, makeT, sampleHeap
) where
import Heap
data LeftistHeap a =
E |
T Int a (LeftistHeap a) (LeftistHeap a)
deriving Show
rank E = 0
rank (T r _ _ _) = r
makeT x a b =
if rank a >= rank b then T ((rank b) + 1) x a b
else T ((rank a) + 1) x b a
instance Heap LeftistHeap where
empty = E
isEmpty E = True
isEmpty _ = False
merge h1 E = h1
merge E h2 = h2
merge h1@(T _ x a1 b1) h2@(T _ y a2 b2) =
if x <= y then makeT x a1 (merge b1 h2)
else makeT y a2 (merge h1 b2)
insert x h = merge (T 1 x E E) h
findMin E = Nothing
findMin (T _ x _ _) = Just x
deleteMin E = Nothing
deleteMin (T _ x a b) = Just (merge a b)
-- Sample data: a heap containing characters.
sampleHeap :: LeftistHeap Char
sampleHeap = foldl (\h -> \c -> insert c h) E ['a', 'b', 'c', 'd', 'g', 'f', 'h']
|
fishbee/pfds-haskell
|
chapter3/LeftistHeap.hs
|
gpl-3.0
| 1,135
| 0
| 10
| 296
| 473
| 254
| 219
| 34
| 2
|
{-# LANGUAGE InstanceSigs #-}
class Monad m => MonadFix m where
mfix :: (a -> m a) -> m a
-- my solution is wrong? seems to have the same effect...
instance MonadFix [] where
mfix :: (a -> [a]) -> [a]
mfix f = ma
where
ma = f (head ma)
-- from prelude
-- instance MonadFix [] where
-- mfix :: (a -> [a]) -> [a]
-- mfix f = case fix (f . head) of
-- [] -> []
-- (x:_) -> x : mfix (tail . f)
-- fix f = let x = f x in x
|
thalerjonathan/phd
|
coding/learning/haskell/typeclassopedia/MonadFix.hs
|
gpl-3.0
| 472
| 0
| 10
| 156
| 104
| 57
| 47
| 7
| 0
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.KMS.EnableKeyRotation
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Enables rotation of the specified customer master key.
--
-- <http://docs.aws.amazon.com/kms/latest/APIReference/API_EnableKeyRotation.html>
module Network.AWS.KMS.EnableKeyRotation
(
-- * Request
EnableKeyRotation
-- ** Request constructor
, enableKeyRotation
-- ** Request lenses
, ekrKeyId
-- * Response
, EnableKeyRotationResponse
-- ** Response constructor
, enableKeyRotationResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.KMS.Types
import qualified GHC.Exts
newtype EnableKeyRotation = EnableKeyRotation
{ _ekrKeyId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'EnableKeyRotation' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ekrKeyId' @::@ 'Text'
--
enableKeyRotation :: Text -- ^ 'ekrKeyId'
-> EnableKeyRotation
enableKeyRotation p1 = EnableKeyRotation
{ _ekrKeyId = p1
}
-- | A unique identifier for the customer master key. This value can be a globally
-- unique identifier or the fully specified ARN to a key. Key ARN Example -
-- arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012 Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012
--
ekrKeyId :: Lens' EnableKeyRotation Text
ekrKeyId = lens _ekrKeyId (\s a -> s { _ekrKeyId = a })
data EnableKeyRotationResponse = EnableKeyRotationResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'EnableKeyRotationResponse' constructor.
enableKeyRotationResponse :: EnableKeyRotationResponse
enableKeyRotationResponse = EnableKeyRotationResponse
instance ToPath EnableKeyRotation where
toPath = const "/"
instance ToQuery EnableKeyRotation where
toQuery = const mempty
instance ToHeaders EnableKeyRotation
instance ToJSON EnableKeyRotation where
toJSON EnableKeyRotation{..} = object
[ "KeyId" .= _ekrKeyId
]
instance AWSRequest EnableKeyRotation where
type Sv EnableKeyRotation = KMS
type Rs EnableKeyRotation = EnableKeyRotationResponse
request = post "EnableKeyRotation"
response = nullResponse EnableKeyRotationResponse
|
romanb/amazonka
|
amazonka-kms/gen/Network/AWS/KMS/EnableKeyRotation.hs
|
mpl-2.0
| 3,245
| 0
| 9
| 676
| 359
| 220
| 139
| 48
| 1
|
-- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Network.Kafka.Protocol.Request
where
import Control.Applicative
import qualified Data.ByteString as BS
import Data.Int
import Data.Proxy
import Data.Serialize
import GHC.Generics
import GHC.TypeLits
import Network.Kafka.Protocol.Primitive
import Network.Kafka.Protocol.Universe
data Request a = Request
{ rq_apiKey :: !ApiKey
, rq_apiVersion :: !ApiVersion
, rq_correlationId :: !Int32
, rq_clientId :: !ShortString
, rq_request :: !a
} deriving (Eq, Show)
instance Serialize a => Serialize (Request a) where
put rq = do
put (fromIntegral (BS.length rq') :: Int32)
put rq'
where
rq' = runPut (put rq)
get = do
len <- get :: Get Int32
bs <- getBytes (fromIntegral len)
either fail return $ runGet get' bs
where
get' = Request <$> get <*> get <*> get <*> get <*> get
mkRequest :: (KnownNat key, KnownNat version)
=> Int32
-> ShortString
-> Req key version a
-> Request (Req key version a)
mkRequest correlationId clientId rq = Request
{ rq_apiKey = apiKey rq
, rq_apiVersion = apiVersion rq
, rq_correlationId = correlationId
, rq_clientId = clientId
, rq_request = rq
}
newtype ApiKey = ApiKey Int16
deriving (Eq, Show, Generic)
instance Serialize ApiKey
apiKey :: forall key version a. (KnownNat key, KnownNat version)
=> Req key version a
-> ApiKey
apiKey _ = ApiKey . fromInteger $ natVal (Proxy :: Proxy key)
newtype ApiVersion = ApiVersion Int16
deriving (Eq, Show, Generic)
instance Serialize ApiVersion
apiVersion :: forall key version a. (KnownNat key, KnownNat version)
=> Req key version a
-> ApiVersion
apiVersion _ = ApiVersion . fromInteger $ natVal (Proxy :: Proxy version)
|
kim/kafka-protocol
|
src/Network/Kafka/Protocol/Request.hs
|
mpl-2.0
| 2,272
| 43
| 16
| 676
| 588
| 312
| 276
| 65
| 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.VPNGateways.SetLabels
-- 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)
--
-- Sets the labels on a VpnGateway. To learn more about labels, read the
-- Labeling Resources documentation.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.vpnGateways.setLabels@.
module Network.Google.Resource.Compute.VPNGateways.SetLabels
(
-- * REST Resource
VPNGatewaysSetLabelsResource
-- * Creating a Request
, vpnGatewaysSetLabels
, VPNGatewaysSetLabels
-- * Request Lenses
, vgslRequestId
, vgslProject
, vgslPayload
, vgslResource
, vgslRegion
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.vpnGateways.setLabels@ method which the
-- 'VPNGatewaysSetLabels' request conforms to.
type VPNGatewaysSetLabelsResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"regions" :>
Capture "region" Text :>
"vpnGateways" :>
Capture "resource" Text :>
"setLabels" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] RegionSetLabelsRequest :>
Post '[JSON] Operation
-- | Sets the labels on a VpnGateway. To learn more about labels, read the
-- Labeling Resources documentation.
--
-- /See:/ 'vpnGatewaysSetLabels' smart constructor.
data VPNGatewaysSetLabels =
VPNGatewaysSetLabels'
{ _vgslRequestId :: !(Maybe Text)
, _vgslProject :: !Text
, _vgslPayload :: !RegionSetLabelsRequest
, _vgslResource :: !Text
, _vgslRegion :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'VPNGatewaysSetLabels' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'vgslRequestId'
--
-- * 'vgslProject'
--
-- * 'vgslPayload'
--
-- * 'vgslResource'
--
-- * 'vgslRegion'
vpnGatewaysSetLabels
:: Text -- ^ 'vgslProject'
-> RegionSetLabelsRequest -- ^ 'vgslPayload'
-> Text -- ^ 'vgslResource'
-> Text -- ^ 'vgslRegion'
-> VPNGatewaysSetLabels
vpnGatewaysSetLabels pVgslProject_ pVgslPayload_ pVgslResource_ pVgslRegion_ =
VPNGatewaysSetLabels'
{ _vgslRequestId = Nothing
, _vgslProject = pVgslProject_
, _vgslPayload = pVgslPayload_
, _vgslResource = pVgslResource_
, _vgslRegion = pVgslRegion_
}
-- | 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).
vgslRequestId :: Lens' VPNGatewaysSetLabels (Maybe Text)
vgslRequestId
= lens _vgslRequestId
(\ s a -> s{_vgslRequestId = a})
-- | Project ID for this request.
vgslProject :: Lens' VPNGatewaysSetLabels Text
vgslProject
= lens _vgslProject (\ s a -> s{_vgslProject = a})
-- | Multipart request metadata.
vgslPayload :: Lens' VPNGatewaysSetLabels RegionSetLabelsRequest
vgslPayload
= lens _vgslPayload (\ s a -> s{_vgslPayload = a})
-- | Name or id of the resource for this request.
vgslResource :: Lens' VPNGatewaysSetLabels Text
vgslResource
= lens _vgslResource (\ s a -> s{_vgslResource = a})
-- | The region for this request.
vgslRegion :: Lens' VPNGatewaysSetLabels Text
vgslRegion
= lens _vgslRegion (\ s a -> s{_vgslRegion = a})
instance GoogleRequest VPNGatewaysSetLabels where
type Rs VPNGatewaysSetLabels = Operation
type Scopes VPNGatewaysSetLabels =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient VPNGatewaysSetLabels'{..}
= go _vgslProject _vgslRegion _vgslResource
_vgslRequestId
(Just AltJSON)
_vgslPayload
computeService
where go
= buildClient
(Proxy :: Proxy VPNGatewaysSetLabelsResource)
mempty
|
brendanhay/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/VPNGateways/SetLabels.hs
|
mpl-2.0
| 5,375
| 0
| 19
| 1,257
| 638
| 380
| 258
| 100
| 1
|
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
module Model.Volume.SQL
( selectVolumeRow
-- , selectPermissionVolume
, selectVolume
, updateVolume
, insertVolume
-- for expanded queries
, setCreation
, makeVolume
, makePermInfo
) where
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import qualified Language.Haskell.TH as TH
import Model.Time
import Model.SQL.Select
import Model.Id.Types
import Model.Permission.Types
import Model.Audit.SQL
import Model.Volume.Types
parseOwner :: T.Text -> VolumeOwner
parseOwner t = (Id $ read $ T.unpack i, T.tail n) where
(i, n) = T.breakOn ":" t
setCreation :: VolumeRow -> Maybe Timestamp -> [VolumeOwner] -> VolumeRolePolicy -> Volume
setCreation r mCreate owners rolePolicy =
Volume r (fromMaybe (volumeCreation blankVolume) mCreate) owners rolePolicy
makePermInfo :: Maybe Permission -> Maybe Bool -> VolumeRolePolicy
makePermInfo mPerm mShareFull =
let
perm = fromMaybe PermissionNONE mPerm
in
volumeAccessPolicyWithDefault perm mShareFull
makeVolume
:: ([VolumeOwner] -> VolumeRolePolicy -> a)
-> Maybe [Maybe T.Text]
-> VolumeRolePolicy
-> a
makeVolume vol own rolePolicy =
vol
(maybe [] (map (parseOwner . fromMaybe (error "NULL volume.owner"))) own)
rolePolicy
selectVolumeRow :: Selector -- ^ @'VolumeRow'@
selectVolumeRow = selectColumns 'VolumeRow "volume" ["id", "name", "body", "alias", "doi"]
selectPermissionVolume :: Selector -- ^ @'Permission' -> 'Volume'@
selectPermissionVolume = addSelects 'setCreation -- setCreation will be waiting on [VolumeOwner] and Permission
selectVolumeRow
[SelectExpr "volume_creation(volume.id)"] -- XXX explicit table references (throughout)
selectVolume :: TH.Name -- ^ @'Identity'@
-> Selector -- ^ @'Volume'@
selectVolume i = selectJoin 'makeVolume
[ selectPermissionVolume
, maybeJoinOn "volume.id = volume_owners.volume" -- join in Maybe [Maybe Text] of owners
$ selectColumn "volume_owners" "owners"
, joinOn "volume_permission.permission >= 'PUBLIC'::permission" -- join in Maybe Permission
(selector
("LATERAL \
\ (VALUES \
\ ( CASE WHEN ${identitySuperuser " ++ is ++ "} \
\ THEN enum_last(NULL::permission) \
\ ELSE volume_access_check(volume.id, ${view " ++ is ++ " :: Id Party}) END \
\ , CASE WHEN ${identitySuperuser " ++ is ++ "} \
\ THEN null \
\ ELSE (select share_full \
\ from volume_access_view \
\ where volume = volume.id and party = ${view " ++ is ++ " :: Id Party} \
\ limit 1) END ) \
\ ) AS volume_permission (permission, share_full)")
-- get rid of "volume_access_check", use query directly
(OutputJoin
False
'makePermInfo
[ SelectColumn "volume_permission" "permission"
, SelectColumn "volume_permission" "share_full"]))
]
where is = nameRef i
volumeKeys :: String -- ^ @'Volume'@
-> [(String, String)]
volumeKeys v =
[ ("id", "${volumeId $ volumeRow " ++ v ++ "}") ]
volumeSets :: String -- ^ @'Volume@
-> [(String, String)]
volumeSets v =
[ ("name", "${volumeName $ volumeRow " ++ v ++ "}")
, ("alias", "${volumeAlias $ volumeRow " ++ v ++ "}")
, ("body", "${volumeBody $ volumeRow " ++ v ++ "}")
]
updateVolume :: TH.Name -- ^ @'AuditIdentity'
-> TH.Name -- ^ @'Volume'@
-> TH.ExpQ -- ()
updateVolume ident v = auditUpdate ident "volume"
(volumeSets vs)
(whereEq $ volumeKeys vs)
Nothing
where vs = nameRef v
insertVolume
:: TH.Name -- ^ @'AuditIdentity'
-> TH.Name -- ^ @'Volume'@
-> TH.ExpQ -- ^ @'Permission' -> 'Volume'@
insertVolume ident v = auditInsert ident "!volume"
(volumeSets vs)
(Just $ selectOutput selectPermissionVolume)
where vs = nameRef v
|
databrary/databrary
|
src/Model/Volume/SQL.hs
|
agpl-3.0
| 3,923
| 0
| 18
| 925
| 821
| 452
| 369
| 89
| 1
|
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
--------------------------------------------------------------------------------
{-|
Module : Draw
Copyright : (c) Daan Leijen 2003
License : wxWindows
Maintainer : wxhaskell-devel@lists.sourceforge.net
Stability : provisional
Portability : portable
Drawing.
A /Device Context/ or 'DC', is an instance of 'Drawn', 'Brushed',
'Literate', and 'Colored'.
-}
--------------------------------------------------------------------------------
module Graphics.UI.WX.Draw
(
-- * Classes
Drawn, pen, penKind, penWidth, penCap, penJoin, penColor
, Brushed, brush, brushKind, brushColor
-- * Types
, DC, Bitmap
-- * Drawing
, circle, arc, ellipse, ellipticArc
, line, polyline, polygon
, drawPoint, drawRect, roundedRect
, drawText, rotatedText, drawBitmap, drawImage
-- * Internal
, dcWith, dcClear
) where
import Graphics.UI.WXCore
import Graphics.UI.WX.Types
import Graphics.UI.WX.Attributes
import Graphics.UI.WX.Layout
import Graphics.UI.WX.Classes
import Graphics.UI.WX.Window
{--------------------------------------------------------------------------------
--------------------------------------------------------------------------------}
class Drawn w where
pen :: Attr w PenStyle
penKind :: Attr w PenKind
penWidth :: Attr w Int
penCap :: Attr w CapStyle
penJoin :: Attr w JoinStyle
penColor :: Attr w Color
class Brushed w where
brush :: Attr w BrushStyle
brushKind :: Attr w BrushKind
brushColor :: Attr w Color
instance Drawn (DC a) where
pen
= newAttr "pen" dcGetPenStyle dcSetPenStyle
penKind
= mapAttr _penKind (\pstyle x -> pstyle{ _penKind = x }) pen
penWidth
= mapAttr _penWidth (\pstyle x -> pstyle{ _penWidth = x }) pen
penCap
= mapAttr _penCap (\pstyle x -> pstyle{ _penCap = x }) pen
penJoin
= mapAttr _penJoin (\pstyle x -> pstyle{ _penJoin = x }) pen
penColor
= mapAttr _penColor (\pstyle color -> pstyle{ _penColor = color }) pen
instance Brushed (DC a) where
brush
= newAttr "brush" dcGetBrushStyle dcSetBrushStyle
brushKind
= mapAttr _brushKind (\bstyle x -> bstyle{ _brushKind = x }) brush
brushColor
= mapAttr _brushColor (\bstyle color -> bstyle{ _brushColor = color }) brush
instance Literate (DC a) where
font
= newAttr "font" dcGetFontStyle dcSetFontStyle
textColor
= newAttr "textcolor" dcGetTextForeground dcSetTextForeground
textBgcolor
= newAttr "textbgcolor" dcGetTextBackground dcSetTextForeground
instance Colored (DC a) where
color
= newAttr "color" (\dc -> get dc penColor) (\dc c -> set dc [penColor := c, textColor := c])
bgcolor
= newAttr "bgcolor" (\dc -> get dc brushColor) (\dc c -> set dc [brushColor := c, textBgcolor := c])
-- Save pen/font/brush efficiently.
dcWith :: DC a -> [Prop (DC a)] -> IO b -> IO b
dcWith dc props io
| null props = io
| otherwise = dcEncapsulate dc (do set dc props; io)
-- | Draw a circle given a center point and radius.
circle :: DC a -> Point -> Int -> [Prop (DC a)] -> IO ()
circle dc center radius props
= dcWith dc props (dcDrawCircle dc center radius)
-- | Draw an arc of a circle. Takes the center of the circle,
-- its radius and a starting and ending point relative to the
-- three-o\'clock position. Angles are in degrees and positive
-- values denote a counter clockwise motion. If the angles are
-- equal, an entire circle is drawn.
arc :: DC a -> Point -> Int -> Double -> Double -> [Prop (DC a)] -> IO ()
arc dc center radius start end props
= ellipticArc dc bounds start end props
where
bounds
= rect (pt (pointX center - radius) (pointY center - radius)) (sz (2*radius) (2*radius))
{-
= dcWith dc props (dcDrawArc dc center (point start) (point end) )
where
point angle
= let radians = (2*pi*angle)/360
x = px center + round (cos radians * fromIntegral radius)
y = py center - round (sin radians * fromIntegral radius)
in (pt x y)
-}
-- | Draw an ellipse, bounded by a certain rectangle.
ellipse :: DC a -> Rect -> [Prop (DC a)] -> IO ()
ellipse dc rect props
= dcWith dc props (dcDrawEllipse dc rect)
-- | Draw an elliptic arc. Takes the bounding rectangle,
-- and a starting and ending point relative to the
-- three-o\'clock position from the center of the rectangle.
-- Angles are in degrees and positive
-- values denote a counter clockwise motion. If the angles are
-- equal, an entire ellipse is drawn.
ellipticArc :: DC a -> Rect -> Double -> Double -> [Prop (DC a)] -> IO ()
ellipticArc dc rect start end props
= dcWith dc props (dcDrawEllipticArc dc rect start end)
-- | Draw a line.
line :: DC a -> Point -> Point -> [Prop (DC a)] -> IO ()
line dc start end props
= dcWith dc props (dcDrawLine dc start end)
-- | Draw a polyline.
polyline :: DC a -> [Point] -> [Prop (DC a)] -> IO ()
polyline dc points props
= dcWith dc props (drawLines dc points)
-- | Draw a polygon. The polygon is filled with the odd-even rule.
-- Note that the polygon is automatically closed.
polygon :: DC a -> [Point] -> [Prop (DC a)] -> IO ()
polygon dc points props
= dcWith dc props (drawPolygon dc points)
-- | Draw a single point.
drawPoint :: DC a -> Point -> [Prop (DC a)] -> IO ()
drawPoint dc center props
= dcWith dc props (dcDrawPoint dc center)
-- | Draw a rectangle.
drawRect :: DC a -> Rect -> [Prop (DC a)] -> IO ()
drawRect dc rect props
= dcWith dc props (dcDrawRectangle dc rect)
-- | Draw a rectangle with rounded corners. The corners are
-- quarter circles with the given radius.
-- If radius is positive, the value is assumed to be the radius of the rounded corner.
-- If radius is negative, the absolute value is assumed to be the proportion of the smallest
-- dimension of the rectangle. This means that the corner can be a sensible size relative to
-- the size of the rectangle, and also avoids the strange effects X produces when the corners
-- are too big for the rectangle.
roundedRect :: DC a -> Rect -> Double -> [Prop (DC a)] -> IO ()
roundedRect dc rect radius props
= dcWith dc props (dcDrawRoundedRectangle dc rect radius)
-- | Draw text.
drawText :: DC a -> String -> Point -> [Prop (DC a)] -> IO ()
drawText dc text point props
= dcWith dc props (dcDrawText dc text point)
-- | Draw rotated text. Takes an angle in degrees relative to the
-- three-o\'clock position.
rotatedText :: DC a -> String -> Point -> Double -> [Prop (DC a)] -> IO ()
rotatedText dc text point angle props
= dcWith dc props (dcDrawRotatedText dc text point angle)
-- | Draw a bitmap. Takes a bitmap, a point and a boolean
-- that is 'True' when the bitmap is drawn with a transparency mask.
drawBitmap :: DC a -> Bitmap () -> Point -> Bool -> [Prop (DC a)] -> IO ()
drawBitmap dc bitmap point transparent props
= if bitmap == nullBitmap || objectIsNull bitmap
then return ()
else do ok <- bitmapIsOk bitmap
if not ok
then return ()
else dcWith dc props (dcDrawBitmap dc bitmap point transparent)
-- | Draw an image.
drawImage :: DC a -> Image b -> Point -> [Prop (DC a)] -> IO ()
drawImage dc image pt props
= do bm <- bitmapCreateFromImage image (-1)
drawBitmap dc bm pt False props
bitmapDelete bm
|
sherwoodwang/wxHaskell
|
wx/src/Graphics/UI/WX/Draw.hs
|
lgpl-2.1
| 7,371
| 0
| 14
| 1,616
| 1,958
| 1,022
| 936
| 115
| 3
|
import Control.Applicative
import Control.Monad
import Data.Maybe
import Data.Monoid
import System.Directory
import System.FilePath.Posix
import System.IO
import System.Posix.Files
import System.Process
main :: IO ()
main = do
judge <- check >>= affirmation
when judge allOrderRename
affirmation :: Bool -> IO Bool
affirmation False = putStrLn "no jobs" >> return False
affirmation True = do
putStr "Do you want to run ? (y/n):"
hFlush stdout
input <- getChar
case input of
'y' -> return True
'n' -> return False
_ -> return False
check :: IO Bool
check = do
currdir <- getCurrentDirectory
depth <- maxDepth currdir
putStrLn ("max depth = " <> show depth)
oldNames <- shellFind currdir
case oldNames of
[] -> return False
_ -> mapM_ (\(o, n) -> diffLikePut o n) (zip oldNames newNames) >> return True
where newNames = map toSafeString oldNames
diffLikePut :: String -> String -> IO ()
diffLikePut o n = do
putStrLn ("-" <> o)
putStrLn ("+" <> n)
allOrderRename :: IO ()
allOrderRename = do
currdir <- getCurrentDirectory
maxdepth <- maxDepth currdir
recursion currdir 1 maxdepth
where recursion currdir depth maxdepth = do
shellFindDepth currdir depth >>= mapM_ renameToSafe
when (depth < maxdepth) $ recursion currdir (depth + 1) maxdepth
maxDepth :: FilePath -> IO Int
maxDepth dir = do
dirList <- lines <$> readProcess "find" [dir] []
return $ foldr (\s n -> max (countSlash s) n) 0 dirList - countSlash dir
countSlash :: String -> Int
countSlash = foldr (\s n -> case s of
'/' -> n + 1
_ -> n)
0
shellFind :: FilePath -> IO [String]
shellFind dir = lines <$> readProcess "find" [dir, "-regex", illRegex] []
shellFindDepth :: FilePath -> Int -> IO [String]
shellFindDepth dir depthLevel = lines <$> readProcess "find" [dir, "-maxdepth", show depthLevel, "-regex", illRegex] []
illRegex :: String
illRegex = ".*[" ++ foldr ((:) . fst) "" replaceTable ++ "].*"
renameToSafe :: FilePath -> IO ()
renameToSafe name = rename name (pathToSafeFile name)
pathToSafeFile :: FilePath -> FilePath
pathToSafeFile path =
let safeFileName = toSafeString $ takeFileName path
dirName = takeDirectory path
in
dirName ++ "/" ++ safeFileName
toSafeString :: String -> String
toSafeString = map toSafeChar
toSafeChar :: Char -> Char
toSafeChar key = fromMaybe key (lookup key replaceTable)
replaceTable :: [(Char, Char)]
replaceTable = [ ('\\', '\')
, ('?', '?')
, (':', ':')
, ('*', '*')
, ('"', '”')
, ('>', '>')
, ('<', '<')
, ('|', '|')
, (' ', ' ')
]
|
ncaq/to-safe-name
|
src/Main.hs
|
unlicense
| 2,907
| 0
| 14
| 854
| 964
| 493
| 471
| 81
| 3
|
module Lycopene.Database.HDBC.Query where
import Database.HDBC
import Lycopene.Core (Lycopene(..), ProjectF(..))
import Lycopene.Freer (foldFreer)
import Lycopene.Database.DataSource (DataSource)
import Lycopene.Database.Persist (Persist(..))
import Lycopene.Database.HDBC.Project (persistProject)
-- Lift method
-- ----------------------------------------------------------------
-- | Lift 'relational-record' 'Insert' DSL into Persist monad
-- Integer means count of record inserted
--insertPersist :: (ToSql SqlValue p) => Insert p -> p -> Persist Integer
--insertPersist i p = Persist (\conn -> runInsert conn i p)
-- | Lift 'relational-record' 'InsertQuery' DSL into Persist monad
-- Integer means count of record inserted
-- insertQueryPersist :: (ToSql SqlValue p) => InsertQuery p -> p -> Persist Integer
-- insertQueryPersist i p = Persist (\conn -> runInsertQuery conn i p)
-- | Lift 'relational-record' 'Update' DSL into Persist monad
-- Integer means count of record updated
-- updatePersist :: (ToSql SqlValue p) => Update p -> p -> Persist Integer
-- updatePersist u p = Persist (\conn -> runUpdate conn u p)
-- | Lift 'relational-record' 'KeyUpdate' DSL into Persist monad
-- Integer means count of record updated
-- kupdatePersist :: (ToSql SqlValue a) => KeyUpdate p a -> a -> Persist Integer
-- kupdatePersist u k = Persist (\conn -> runKeyUpdate conn u k)
-- | Lift 'relational-record' 'Delete' DSL into Persist monad
-- Integer means count of record deleted
-- deletePersist :: (ToSql SqlValue p) => Delete p -> p -> Persist Integer
-- deletePersist d p = Persist (\conn -> runDelete conn d p)
-- | Lift 'relational-record' 'Relation' DSL into Persist monad.
-- Apply query parameter @p@ to 'Relation'
-- selectPersist :: (ToSql SqlValue p, FromSql SqlValue a) => Relation p a -> p -> Persist [a]
-- selectPersist q p = Persist (\conn -> runQuery conn (relationalQuery q) p)
|
utky/lycopene
|
src/Lycopene/Database/HDBC/Query.hs
|
apache-2.0
| 1,963
| 0
| 6
| 350
| 108
| 80
| 28
| 7
| 0
|
-- http://stackoverflow.com/questions/9732084/how-do-you-represent-a-graph-in-haskell
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
import Data.Reify
import Control.Applicative
import Data.Traversable
--Pointer-based graph representation
data PtrNode = PtrNode [PtrNode] deriving Show
--Label-based graph representation
data LblNode lbl = LblNode [lbl] deriving Show
--Convenience functions for our DSL
leaf = PtrNode []
node1 a = PtrNode [a]
node2 a b = PtrNode [a, b]
-- This looks scary but we're just telling data-reify where the pointers are
-- in our graph representation so they can be turned to labels
instance MuRef PtrNode where
type DeRef PtrNode = LblNode
mapDeRef f (PtrNode as) = LblNode <$> (traverse f as)
-- Graph we want to represent:
-- .----> a <----.
-- / \
-- b <------------. \
-- \ \ /
-- `----> c ----> d
-- Code for the graph:
a = leaf
b = node2 a c
c = node1 d
d = node2 a b
-- Yes, it's that simple!
-- If you want to convert the graph to a Node-Label format:
main = do
g <- reifyGraph b --can't use 'a' because not all nodes are reachable
print g
|
egaburov/funstuff
|
Haskell/sharing/observable3.hs
|
apache-2.0
| 1,169
| 3
| 8
| 260
| 215
| 117
| 98
| 20
| 1
|
-- Copyright 2010 Google Inc.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Barley.Project
( ProjectDir(..)
, enter
, init
) where
import Control.Monad (unless, when)
import Paths_barley -- generated by cabal
import Prelude hiding (init)
import System.Directory
import System.Exit
import System.FilePath
-- | A specification of a project directory
data ProjectDir = CurrentDir | ProjectDir FilePath
projectPath :: ProjectDir -> FilePath
projectPath CurrentDir = "." -- FIXME: The use of "." is probably not right
projectPath (ProjectDir fp) = fp
-- | The presence of this file indicates a directory is a barley project.
-- In the future we might store information in it.
markerFile :: FilePath
markerFile = ".barley-project"
-- | Change into the project directory.
-- Fails if the directory can't be entered.
enter :: ProjectDir -> IO ()
enter projectDir = do
exists <- case projectDir of
CurrentDir -> return True
ProjectDir fp -> doesDirectoryExist fp
unless exists $
putStrLn ("Project directory doesn't exist: " ++ pdPath) >>
exitFailure
hasMarker <- doesFileExist (pdPath </> markerFile)
unless hasMarker $
putStrLn "Directory doesn't appear to be a Barely project." >>
putStrLn ("Missing .barley-project file in directory: " ++ pdPath) >>
exitFailure
case projectDir of
CurrentDir -> return ()
ProjectDir fp -> setCurrentDirectory fp
where
pdPath = projectPath projectDir
-- | Create a project directory structure.
init :: Bool -> ProjectDir -> IO ()
init warnIfNotEmpty projectDir = nothingHere >>= \b -> if b
then copyInitialProject projectDir
else when warnIfNotEmpty $
putStrLn "** This directory is not empty. Not initializing."
where
nothingHere = whatsHere >>= return . null . filter notDot
whatsHere = case projectDir of
CurrentDir -> getCurrentDirectory >>= getDirectoryContents
ProjectDir fp -> do
exists <- doesDirectoryExist fp
if exists
then getDirectoryContents fp
else return []
notDot ('.':_) = False
notDot _ = True
-- | Copy the initial project skeleton to the project directory.
copyInitialProject :: ProjectDir -> IO ()
copyInitialProject projectDir = do
fromDir <- getSeedDir
let toDir = projectPath projectDir
putStrLn "Creating default project files..."
copyTree fromDir toDir
writeFile (toDir </> markerFile) ""
putStrLn "...done."
-- | Locate seed dir in current dir, or data dir, or if neither, fail.
getSeedDir :: IO FilePath
getSeedDir = findFirstSeed [ getCurrentDirectory, getDataDir ]
where
findFirstSeed (g:gs) = do
s <- g >>= return . (</> "seed")
exists <- doesDirectoryExist s
if exists
then return s
else findFirstSeed gs
findFirstSeed [] = do
putStrLn "** No seed directory found."
putStrLn "** You should try reinstalling Barley."
exitFailure
-- | Copy a directory tree from one place to another. The destination, or
-- the subtrees needn't exist. If they do, existing files with the same names
-- as the source will be overwritten. Other files will be left alone.
copyTree :: FilePath -> FilePath -> IO ()
copyTree from to = pick
[(doesFileExist, doFile),
(doesDirectoryExist, doDir)]
where
pick ((test, act):rest) = do
bool <- test from
if bool
then putStrLn (" " ++ to) >> act
else pick rest
pick [] =
putStrLn $ "** Skipping funny thing in skeleton tree: " ++ from
doFile = copyFile from to
doDir = do
createDirectoryIfMissing False to
getDirectoryContents from >>= mapM_ dive . filter notSpecial
dive item = copyTree (from </> item) (to </> item)
notSpecial item = item /= "." && item /= ".."
|
mzero/barley
|
src/Barley/Project.hs
|
apache-2.0
| 4,428
| 0
| 14
| 1,098
| 870
| 445
| 425
| 85
| 5
|
{-# LANGUAGE TemplateHaskell #-}
module Rest.Types
( Error(..)
) where
import Data.Aeson.TH
import Data.Text.Lazy
data Error = Error { errorStatus :: Int
, errorMessage :: Text
, errorException :: Maybe Text
}
deriving (Read, Show)
$(deriveJSON defaultOptions ''Error)
|
jotrk/rest-service
|
src/Rest/Types.hs
|
bsd-2-clause
| 342
| 0
| 9
| 111
| 83
| 49
| 34
| 10
| 0
|
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ARB.GetProgramBinary
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ARB/get_program_binary.txt ARB_get_program_binary> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ARB.GetProgramBinary (
-- * Enums
gl_NUM_PROGRAM_BINARY_FORMATS,
gl_PROGRAM_BINARY_FORMATS,
gl_PROGRAM_BINARY_LENGTH,
gl_PROGRAM_BINARY_RETRIEVABLE_HINT,
-- * Functions
glGetProgramBinary,
glProgramBinary,
glProgramParameteri
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/ARB/GetProgramBinary.hs
|
bsd-3-clause
| 899
| 0
| 4
| 103
| 64
| 50
| 14
| 10
| 0
|
module Input
( AppInput(inpClockTime)
, parseWinInput
, mousePos
, lbp
, lbpPos
, lbDown
, rbp
, rbpPos
, rbDown
, keyPress
, keyPressed
, quitEvent
, clockTimeInput
, module SDL.Input.Keyboard.Codes
) where
import Data.Maybe
import FRP.Yampa
import Linear (V2(..))
import Linear.Affine (Point(..))
import SDL.Input.Keyboard.Codes
import qualified SDL
import Types
-- <| Signal Functions |> --
-- | Current mouse position
mousePos :: SF AppInput (Double,Double)
mousePos = arr inpMousePos
-- | Events that indicate left button click
lbp :: SF AppInput (Event ())
lbp = lbpPos >>^ tagWith ()
-- | Events that indicate left button click and are tagged with mouse position
lbpPos :: SF AppInput (Event (Double,Double))
lbpPos = inpMouseLeft ^>> edgeJust
-- | Is left button down
lbDown :: SF AppInput Bool
lbDown = arr (isJust . inpMouseLeft)
-- | Events that indicate right button click
rbp :: SF AppInput (Event ())
rbp = rbpPos >>^ tagWith ()
-- | Events that indicate right button click and are tagged with mouse position
rbpPos :: SF AppInput (Event (Double,Double))
rbpPos = inpMouseRight ^>> edgeJust
-- | Is right button down
rbDown :: SF AppInput Bool
rbDown = arr (isJust . inpMouseRight)
keyPress :: SF AppInput (Event SDL.Scancode)
keyPress = inpKeyPressed ^>> edgeJust
keyPressed :: SDL.Scancode -> SF AppInput (Event ())
keyPressed code = keyPress >>^ filterE (code ==) >>^ tagWith ()
quitEvent :: SF AppInput (Event ())
quitEvent = arr inpQuit >>> edge
clockTimeInput :: SF AppInput ClockTime
clockTimeInput = arr inpClockTime
-- | Exported as abstract type. Fields are accessed with signal functions.
data AppInput = AppInput
{ inpMousePos :: (Double, Double) -- ^ Current mouse position
, inpMouseLeft :: Maybe (Double, Double) -- ^ Left button currently down
, inpMouseRight :: Maybe (Double, Double) -- ^ Right button currently down
, inpKeyPressed :: Maybe SDL.Scancode
, inpQuit :: Bool -- ^ SDL's QuitEvent
, inpClockTime :: ClockTime
}
initAppInput :: AppInput
initAppInput = AppInput { inpMousePos = (0, 0)
, inpMouseLeft = Nothing
, inpMouseRight = Nothing
, inpKeyPressed = Nothing
, inpQuit = False
, inpClockTime = ClockTime 0 0 0
}
-- | Filter and transform SDL events into events which are relevant to our
-- application
parseWinInput :: SF WinInput AppInput
parseWinInput = accumHoldBy nextAppInput initAppInput
nextAppInput :: AppInput -> WinInputEvent -> AppInput
nextAppInput inp evt@(_, clockTime) = updateClockTime (nextAppInputSDL inp evt) clockTime
-- | Compute next input
-- FIXME: I am reinventing lenses once again
nextAppInputSDL :: AppInput -> WinInputEvent -> AppInput
nextAppInputSDL inp (Just SDL.QuitEvent, _) = inp { inpQuit = True }
nextAppInputSDL inp (Just (SDL.MouseMotionEvent ev), _) =
inp { inpMousePos = (fromIntegral x, fromIntegral y) }
where P (V2 x y) = SDL.mouseMotionEventPos ev
nextAppInputSDL inp (Just (SDL.KeyboardEvent ev), _)
| SDL.keyboardEventKeyMotion ev == SDL.Pressed
= inp { inpKeyPressed = Just $ SDL.keysymScancode $ SDL.keyboardEventKeysym ev }
| SDL.keyboardEventKeyMotion ev == SDL.Released
= inp { inpKeyPressed = Nothing }
nextAppInputSDL inp (Just (SDL.MouseButtonEvent ev), _) = inp { inpMouseLeft = lmb
, inpMouseRight = rmb }
where motion = SDL.mouseButtonEventMotion ev
button = SDL.mouseButtonEventButton ev
pos = inpMousePos inp
inpMod = case (motion,button) of
(SDL.Released, SDL.ButtonLeft) -> first (const Nothing)
(SDL.Pressed, SDL.ButtonLeft) -> first (const (Just pos))
(SDL.Released, SDL.ButtonRight) -> second (const Nothing)
(SDL.Pressed, SDL.ButtonRight) -> second (const (Just pos))
_ -> id
(lmb,rmb) = inpMod $ (inpMouseLeft &&& inpMouseRight) inp
nextAppInputSDL inp _ = inp
updateClockTime :: AppInput -> ClockTime -> AppInput
updateClockTime inp clockTime = inp { inpClockTime = clockTime }
|
flomerz/yampa-uhr
|
src/Input.hs
|
bsd-3-clause
| 4,385
| 0
| 14
| 1,170
| 1,130
| 625
| 505
| 89
| 5
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Image
( createImage
, latestImageByName
, launch
, terminate
) where
import Control.Arrow
import Control.Lens
import Control.Monad.Except
import Control.Monad.Morph
import Control.Monad.Trans.AWS
import Data.Function (on)
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Network.AWS.EC2 as EC2
latestImageByName :: Text -> AWST (ExceptT Text IO) Text
latestImageByName name = do
images <- view EC2.dirImages <$> send req
let pairs = map (view EC2.iImageId &&& view EC2.iCreationDate) images
case sortByDescendingDate pairs of
[] -> lift (throwError "no such image")
(p:_) -> return (fst p)
where
req = EC2.describeImages
& EC2.di2Owners .~ ["self"]
& EC2.di2Filters .~ [filters]
filters = EC2.filter' "tag:Name" & EC2.fValues .~ [name]
sortByDescendingDate = sortBy (flip compare `on` snd)
launch :: Text -> Text -> Maybe Text -> AWST (ExceptT Text IO) Text
launch name key elasticIp = do
imageId <- latestImageByName name
instanceId <- runInstance imageId key <&> view EC2.i1InstanceId
hoist lift (assignName instanceId name)
reservations <- view EC2.dirReservations <$> waitForInstance instanceId
let runningInstances = concatMap (^. EC2.rInstances) reservations
publicIPs = mapMaybe (^. EC2.i1PublicIpAddress) runningInstances
case publicIPs of
[] -> lift (throwError "no IP address returned")
[ip] -> case elasticIp of
Just eIp -> do assignIP instanceId eIp
return eIp
Nothing -> return ip
_ -> lift (throwError "multiple IP addresses returned")
where
waitForInstance instanceId = await EC2.instanceRunning $
EC2.describeInstances & EC2.di1InstanceIds .~ [instanceId]
assignIP instanceId ip = send_ $ EC2.associateAddress
& EC2.aa1InstanceId ?~ instanceId
& EC2.aa1PublicIp ?~ ip
runInstance :: Text -> Text -> AWST (ExceptT Text IO) EC2.Instance
runInstance imageId key = do
instances <- view EC2.rirInstances <$> send runInstanceRq
case instances of
[i] -> return i
[] -> lift (throwError "runInstance returned zero instances")
_ -> lift (throwError "runInstance returned multiple instances")
where
runInstanceRq = EC2.runInstances imageId 1 1
& EC2.riInstanceType ?~ EC2.T2_Medium
& EC2.riKeyName ?~ key
assignName :: Text -> Text -> AWST IO ()
assignName resourceIds name =
send_ $ EC2.createTags
& EC2.ct1Resources .~ [resourceIds]
& EC2.ct1Tags .~ [EC2.tag "Name" name]
getTimestamp :: IO Text
getTimestamp = (T.pack . show) <$> getPOSIXTime
type ImageId = Text
createImage :: Text -> AWST (ExceptT Text IO) ImageId
createImage name = do
inst <- getRunningInstance name
ts <- liftIO getTimestamp
let rs = send (EC2.createImage (view EC2.i1InstanceId inst) $ name <> "-" <> ts)
imageId <- view EC2.cirImageId <$> rs
case imageId of
Nothing -> lift (throwError "EC2.createImage did not return an image id.")
Just i -> do hoist lift (assignName i name)
return i
getRunningInstance :: Text -> AWST (ExceptT Text IO) EC2.Instance
getRunningInstance name = do
reservations <- view EC2.dirReservations <$> send describeInstancesRq
let instances = concatMap (^. EC2.rInstances) reservations
case instances of
[i] -> return i
[] -> lift (throwError "instance not found")
_ -> lift (throwError "multiple instances found")
where
describeInstancesRq = EC2.describeInstances
& EC2.di1Filters .~ filters
filters = [EC2.filter' "tag:Name" & EC2.fValues .~ [name]
,EC2.filter' "instance-state-name" & EC2.fValues .~ ["running"]
]
terminate :: Text -> AWST (ExceptT Text IO) ()
terminate instanceName = do
_ <- createImage instanceName
instanceId <- view EC2.i1InstanceId <$> getRunningInstance instanceName
send_ (EC2.terminateInstances & EC2.tiInstanceIds .~ [instanceId])
|
lbodor/amazonia
|
src/Image.hs
|
bsd-3-clause
| 4,432
| 0
| 18
| 1,160
| 1,303
| 649
| 654
| 98
| 4
|
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
module Bits (runBits, cmodule) where
import Ivory.Compile.C.CmdlineFrontend
import Ivory.Language hiding (setBit, clearBit, runBits)
import MonadLib.Monads (runState, sets)
runBits :: IO ()
runBits = runCompiler [cmodule] [] initialOpts {outDir = Nothing}
cmodule :: Module
cmodule = package "Bits" $ do
incl test1
incl test2
incl test3
incl test4
incl test5
incl test6
test1 :: Def ('[Uint8, Uint16, Uint32, Uint64] ':-> Uint64)
test1 = proc "test1" $ \u8 u16 u32 u64 -> body $ do
a <- assign $ u8 .& 0xFF
b <- assign $ u16 .& 0xFF00
c <- assign $ u32 .& 0xFF0000
d <- assign $ u64 .& 0xFF000000
ret $ (safeCast a) .| (safeCast b) .| (safeCast c) .| d
-- | Convert an array of four 8-bit integers into a 32-bit integer.
test2 :: Def ('[Ref s ('Array 4 ('Stored Uint8))] ':-> Uint32)
test2 = proc "test2" $ \arr -> body $ do
a <- deref (arr ! 0)
b <- deref (arr ! 1)
c <- deref (arr ! 2)
d <- deref (arr ! 3)
ret $ ((safeCast a) `iShiftL` 24) .|
((safeCast b) `iShiftL` 16) .|
((safeCast c) `iShiftL` 8) .|
((safeCast d) `iShiftL` 0)
-- | Example of using "extractByte" with a state monad.
extractUint32 :: Uint32 -> (Uint8, Uint8, Uint8, Uint8)
extractUint32 x = fst $ runState x $ do
a <- sets extractByte
b <- sets extractByte
c <- sets extractByte
d <- sets extractByte
return (a, b, c, d)
-- | Convert a 32-bit integer to an array of 8-bit integers.
test3 :: Def ('[Uint32, Ref s ('Array 4 ('Stored Uint8))] ':-> ())
test3 = proc "test3" $ \n arr -> body $ do
let (a, b, c, d) = extractUint32 n
store (arr ! 0) d
store (arr ! 1) c
store (arr ! 2) b
store (arr ! 3) a
setBit :: (IvoryBits a, IvoryStore a)
=> (Ref s ('Stored a)) -> Int -> Ivory eff ()
setBit ref bit = do
val <- deref ref
store ref (val .| (1 `iShiftL` (fromIntegral bit)))
clearBit :: (IvoryBits a, IvoryStore a)
=> (Ref s ('Stored a)) -> Int -> Ivory eff ()
clearBit ref bit = do
val <- deref ref
store ref (val .& (iComplement (1 `iShiftL` (fromIntegral bit))))
test4 :: Def ('[] ':-> Uint32)
test4 = proc "test4" $ body $ do
n <- local (ival 0)
setBit n 1
setBit n 3
setBit n 5
setBit n 8
clearBit n 3
ret =<< deref n
test5 :: Def ('[Sint8] ':-> Uint8)
test5 = proc "test5" $ \s -> body $
ret (twosComplementRep s)
test6 :: Def ('[Uint8] ':-> Sint8)
test6 = proc "test6" $ \s -> body $
ret (twosComplementCast s)
|
GaloisInc/ivory
|
ivory-examples/examples/Bits.hs
|
bsd-3-clause
| 2,479
| 0
| 17
| 587
| 1,181
| 597
| 584
| 72
| 1
|
{-# LANGUAGE OverloadedStrings, StandaloneDeriving, DeriveDataTypeable #-}
{-# LANGUAGE CPP #-}
module Github.Private where
import Github.Data
import Data.Aeson
import Data.Attoparsec.ByteString.Lazy
import Data.Data
import Data.Monoid
import Control.Applicative
import Data.List
import Data.CaseInsensitive (mk)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import Network.HTTP.Types (Status(..))
import Network.HTTP.Conduit
-- import Data.Conduit (ResourceT)
import qualified Control.Exception as E
import Data.Maybe (fromMaybe)
-- | user/password for HTTP basic access authentication
data GithubAuth = GithubBasicAuth BS.ByteString BS.ByteString
| GithubOAuth String
deriving (Show, Data, Typeable, Eq, Ord)
githubGet :: (FromJSON b, Show b) => [String] -> IO (Either Error b)
githubGet = githubGet' Nothing
githubGet' :: (FromJSON b, Show b) => Maybe GithubAuth -> [String] -> IO (Either Error b)
githubGet' auth paths =
githubAPI (BS.pack "GET")
(buildUrl paths)
auth
(Nothing :: Maybe Value)
githubGetWithQueryString :: (FromJSON b, Show b) => [String] -> String -> IO (Either Error b)
githubGetWithQueryString = githubGetWithQueryString' Nothing
githubGetWithQueryString' :: (FromJSON b, Show b) => Maybe GithubAuth -> [String] -> String -> IO (Either Error b)
githubGetWithQueryString' auth paths qs =
githubAPI (BS.pack "GET")
(buildUrl paths ++ "?" ++ qs)
auth
(Nothing :: Maybe Value)
githubPost :: (ToJSON a, Show a, FromJSON b, Show b) => GithubAuth -> [String] -> a -> IO (Either Error b)
githubPost auth paths body =
githubAPI (BS.pack "POST")
(buildUrl paths)
(Just auth)
(Just body)
githubPatch :: (ToJSON a, Show a, FromJSON b, Show b) => GithubAuth -> [String] -> a -> IO (Either Error b)
githubPatch auth paths body =
githubAPI (BS.pack "PATCH")
(buildUrl paths)
(Just auth)
(Just body)
buildUrl :: [String] -> String
buildUrl paths = "https://api.github.com/" ++ intercalate "/" paths
githubAPI :: (ToJSON a, Show a, FromJSON b, Show b) => BS.ByteString -> String
-> Maybe GithubAuth -> Maybe a -> IO (Either Error b)
githubAPI apimethod url auth body = do
result <- doHttps apimethod url auth (encodeBody body)
case result of
Left e -> return (Left (HTTPConnectionError e))
Right resp -> either Left (\x -> jsonResultToE (LBS.pack (show x))
(fromJSON x))
<$> handleBody resp
where
encodeBody = Just . RequestBodyLBS . encode . toJSON
handleBody resp = either (return . Left) (handleJson resp)
(parseJsonRaw (responseBody resp))
-- This is an "escaping" version of "for", which returns (Right esc) if
-- the value 'v' is Nothing; otherwise, it extracts the value from the
-- Maybe, applies f, and return an IO (Either Error b).
forE :: b -> Maybe a -> (a -> IO (Either Error b))
-> IO (Either Error b)
forE = flip . maybe . return . Right
handleJson resp gotjson@(Array ary) =
-- Determine whether the output was paginated, and if so, we must
-- recurse to obtain the subsequent pages, and append those result
-- bodies to the current one. The aggregate will then be parsed.
forE gotjson (lookup "Link" (responseHeaders resp)) $ \l ->
forE gotjson (getNextUrl (BS.unpack l)) $ \nu ->
either (return . Left . HTTPConnectionError)
(\nextResp -> do
nextJson <- handleBody nextResp
return $ (\(Array x) -> Array (ary <> x))
<$> nextJson)
=<< doHttps apimethod nu auth Nothing
handleJson _ gotjson = return (Right gotjson)
getNextUrl l =
if "rel=\"next\"" `isInfixOf` l
then let s = l
s' = Data.List.tail $ Data.List.dropWhile (/= '<') s
in Just (Data.List.takeWhile (/= '>') s')
else Nothing
-- doHttps :: Method -> String -> Maybe GithubAuth
-- -> Maybe (RequestBody (ResourceT IO))
-- -> IO (Either E.SomeException (Response LBS.ByteString))
doHttps reqMethod url auth body = do
let reqBody = fromMaybe (RequestBodyBS $ BS.pack "") body
reqHeaders = maybe [] getOAuth auth
Just uri = parseUrl url
request = uri { method = reqMethod
, secure = True
, port = 443
, requestBody = reqBody
, responseTimeout = Just 20000000
, requestHeaders = reqHeaders <>
[("User-Agent", "github.hs/0.7.4")]
<> [("Accept", "application/vnd.github.preview")]
, checkStatus = successOrMissing
}
authRequest = getAuthRequest auth request
(getResponse authRequest >>= return . Right) `E.catches` [
-- Re-throw AsyncException, otherwise execution will not terminate on
-- SIGINT (ctrl-c). All AsyncExceptions are re-thrown (not just
-- UserInterrupt) because all of them indicate severe conditions and
-- should not occur during normal operation.
E.Handler (\e -> E.throw (e :: E.AsyncException)),
E.Handler (\e -> (return . Left) (e :: E.SomeException))
]
where
getAuthRequest (Just (GithubBasicAuth user pass)) = applyBasicAuth user pass
getAuthRequest _ = id
getOAuth (GithubOAuth token) = [(mk (BS.pack "Authorization"),
BS.pack ("token " ++ token))]
getOAuth _ = []
getResponse request = withManager $ \manager -> httpLbs request manager
#if MIN_VERSION_http_conduit(1, 9, 0)
successOrMissing s@(Status sci _) hs cookiejar
#else
successOrMissing s@(Status sci _) hs
#endif
| (200 <= sci && sci < 300) || sci == 404 = Nothing
#if MIN_VERSION_http_conduit(1, 9, 0)
| otherwise = Just $ E.toException $ StatusCodeException s hs cookiejar
#else
| otherwise = Just $ E.toException $ StatusCodeException s hs
#endif
parseJsonRaw :: LBS.ByteString -> Either Error Value
parseJsonRaw jsonString =
let parsed = parse json jsonString in
case parsed of
Data.Attoparsec.ByteString.Lazy.Done _ jsonResult -> Right jsonResult
(Fail _ _ e) -> Left $ ParseError e
jsonResultToE :: Show b => LBS.ByteString -> Data.Aeson.Result b
-> Either Error b
jsonResultToE jsonString result = case result of
Success s -> Right s
Error e -> Left $ JsonError $
e ++ " on the JSON: " ++ LBS.unpack jsonString
parseJson :: (FromJSON b, Show b) => LBS.ByteString -> Either Error b
parseJson jsonString = either Left (jsonResultToE jsonString . fromJSON)
(parseJsonRaw jsonString)
|
mavenraven/github
|
Github/Private.hs
|
bsd-3-clause
| 7,028
| 0
| 23
| 2,023
| 1,936
| 1,013
| 923
| 122
| 4
|
{-# LANGUAGE PatternGuards #-}
module Idris.Elab.Record(elabRecord) where
import Idris.AbsSyntax
import Idris.ASTUtils
import Idris.DSL
import Idris.Error
import Idris.Delaborate
import Idris.Imports
import Idris.ElabTerm
import Idris.Coverage
import Idris.DataOpts
import Idris.Providers
import Idris.Primitives
import Idris.Inliner
import Idris.PartialEval
import Idris.DeepSeq
import Idris.Output (iputStrLn, pshow, iWarn)
import IRTS.Lang
import Idris.Elab.Type
import Idris.Elab.Data
import Idris.Elab.Utils
import Idris.Core.TT
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.Execute
import Idris.Core.Typecheck
import Idris.Core.CaseTree
import Idris.Docstrings
import Prelude hiding (id, (.))
import Control.Category
import Control.Applicative hiding (Const)
import Control.DeepSeq
import Control.Monad
import Control.Monad.State.Strict as State
import Data.List
import Data.Maybe
import Debug.Trace
import qualified Data.Map as Map
import qualified Data.Set as S
import qualified Data.Text as T
import Data.Char(isLetter, toLower)
import Data.List.Split (splitOn)
import Util.Pretty(pretty, text)
elabRecord :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) -> FC -> Name ->
PTerm -> DataOpts -> Docstring (Either Err PTerm) -> Name -> PTerm -> Idris ()
elabRecord info syn doc fc tyn ty opts cdoc cn cty_in
= do elabData info syn doc [] fc opts (PDatadecl tyn ty [(cdoc, [], cn, cty_in, fc, [])])
-- TODO think: something more in info?
cty' <- implicit info syn cn cty_in
i <- getIState
-- get bound implicits and propagate to setters (in case they
-- provide useful information for inference)
let extraImpls = getBoundImpls cty'
cty <- case lookupTy cn (tt_ctxt i) of
[t] -> return (delab i t)
_ -> ifail "Something went inexplicably wrong"
cimp <- case lookupCtxt cn (idris_implicits i) of
[imps] -> return imps
ppos <- case lookupCtxt tyn (idris_datatypes i) of
[ti] -> return $ param_pos ti
let cty_imp = renameBs cimp cty
let ptys = getProjs [] cty_imp
let ptys_u = getProjs [] cty
let recty = getRecTy cty_imp
let recty_u = getRecTy cty
let paramNames = getPNames recty ppos
-- rename indices when we generate the getter/setter types, so
-- that they don't clash with the names of the projections
-- we're generating
let index_names_in = getRecNameMap "_in" ppos recty
let recty_in = substMatches index_names_in recty
logLvl 3 $ show (recty, recty_u, ppos, paramNames, ptys)
-- Substitute indices with projection functions, and parameters with
-- the updated parameter name
let substs = map (\ (n, _) ->
if n `elem` paramNames
then (n, PRef fc (mkp n))
else (n, PApp fc (PRef fc n)
[pexp (PRef fc rec)]))
ptys
-- Generate projection functions
proj_decls <- mapM (mkProj recty_in substs cimp) (zip ptys [0..])
logLvl 3 $ show proj_decls
let nonImp = mapMaybe isNonImp (zip cimp ptys_u)
let implBinds = getImplB id cty'
-- Generate update functions
update_decls <- mapM (mkUpdate recty_u index_names_in extraImpls
(getFieldNames cty')
implBinds (length nonImp)) (zip nonImp [0..])
mapM_ (rec_elabDecl info EAll info) (concat proj_decls)
logLvl 3 $ show update_decls
mapM_ (tryElabDecl info) (update_decls)
where
-- syn = syn_in { syn_namespace = show (nsroot tyn) : syn_namespace syn_in }
isNonImp (PExp _ _ _ _, a) = Just a
isNonImp _ = Nothing
getPNames (PApp _ _ as) ppos = getpn as ppos
where
getpn as [] = []
getpn as (i:is) | length as > i,
PRef _ n <- getTm (as!!i) = n : getpn as is
| otherwise = getpn as is
getPNames _ _ = []
tryElabDecl info (fn, ty, val)
= do i <- getIState
idrisCatch (do rec_elabDecl info EAll info ty
rec_elabDecl info EAll info val)
(\v -> do iputStrLn $ show fc ++
":Warning - can't generate setter for " ++
show fn ++ " (" ++ show ty ++ ")"
-- ++ "\n" ++ pshow i v
putIState i)
getBoundImpls (PPi (Imp _ _ _) n ty sc) = (n, ty) : getBoundImpls sc
getBoundImpls _ = []
getImplB k (PPi (Imp l s _) n Placeholder sc)
= getImplB k sc
getImplB k (PPi (Imp l s p) n ty sc)
= getImplB (\x -> k (PPi (Imp l s p) n ty x)) sc
getImplB k (PPi _ n ty sc)
= getImplB k sc
getImplB k _ = k
renameBs (PImp _ _ _ _ _ : ps) (PPi p n ty s)
= PPi p (mkImp n) ty (renameBs ps (substMatch n (PRef fc (mkImp n)) s))
renameBs (_:ps) (PPi p n ty s) = PPi p n ty (renameBs ps s)
renameBs _ t = t
getProjs acc (PPi _ n ty s) = getProjs ((n, ty) : acc) s
getProjs acc r = reverse acc
getFieldNames (PPi (Exp _ _ _) n _ s) = n : getFieldNames s
getFieldNames (PPi _ _ _ s) = getFieldNames s
getFieldNames _ = []
getRecTy (PPi _ n ty s) = getRecTy s
getRecTy t = t
-- make sure we pick a consistent name for parameters; any name will do
-- otherwise
getRecNameMap x ppos (PApp fc t args)
= mapMaybe toMN (zip [0..] (map getTm args))
where
toMN (i, PRef fc n)
| i `elem` ppos = Just (n, PRef fc (mkp n))
| otherwise = Just (n, PRef fc (sMN 0 (show n ++ x)))
toMN _ = Nothing
getRecNameMap x _ _ = []
rec = sMN 0 "rec"
-- only UNs propagate properly as parameters (bit of a hack then...)
mkp (UN n) = sUN ("_p_" ++ str n)
mkp (MN i n) = sMN i ("p_" ++ str n)
mkp (NS n s) = NS (mkp n) s
mkImp (UN n) = sUN ("implicit_" ++ str n)
mkImp (MN i n) = sMN i ("implicit_" ++ str n)
mkImp (NS n s) = NS (mkImp n) s
mkType (UN n) = sUN ("set_" ++ str n)
mkType (MN i n) = sMN i ("set_" ++ str n)
mkType (NS n s) = NS (mkType n) s
mkProj recty substs cimp ((pn_in, pty), pos)
= do let pn = expandNS syn pn_in -- projection name
-- use pn_in in the indices, consistently, to avoid clash
let pfnTy = PTy emptyDocstring [] defaultSyntax fc [] pn
(PPi expl rec recty
(substMatches substs pty))
let pls = repeat Placeholder
let before = pos
let after = length substs - (pos + 1)
let args = take before pls ++ PRef fc (mkp pn_in) : take after pls
let iargs = map implicitise (zip cimp args)
let lhs = PApp fc (PRef fc pn)
[pexp (PApp fc (PRef fc cn) iargs)]
let rhs = PRef fc (mkp pn_in)
let pclause = PClause fc pn lhs [] rhs []
return [pfnTy, PClauses fc [] pn [pclause]]
implicitise (pa, t) = pa { getTm = t }
-- If the 'pty' we're updating includes anything in 'substs', we're
-- updating the type as well, so use recty', otherwise just use
-- recty
mkUpdate recty inames extras fnames k num ((pn, pty), pos)
= do let setname = expandNS syn $ mkType pn
let valname = sMN 0 "updateval"
let pn_out = sMN 0 (show pn ++ "_out")
let pn_in = sMN 0 (show pn ++ "_in")
let recty_in = substMatches [(pn, PRef fc pn_in)] recty
let recty_out = substMatches [(pn, PRef fc pn_out)] recty
let pt = substMatches inames $
k (implBindUp extras inames (PPi expl pn_out pty
(PPi expl rec recty_in recty_out)))
let pfnTy = PTy emptyDocstring [] defaultSyntax fc [] setname pt
-- let pls = map (\x -> PRef fc (sMN x ("field" ++ show x))) [0..num-1]
let inames_imp = map (\ (x,_) -> (x, Placeholder)) inames
let pls = map (\x -> substMatches inames_imp (PRef fc x)) fnames
let lhsArgs = pls
let rhsArgs = take pos pls ++ (PRef fc valname) :
drop (pos + 1) pls
let before = pos
let pclause = PClause fc setname (PApp fc (PRef fc setname)
[pexp (PRef fc valname),
pexp (PApp fc (PRef fc cn)
(map pexp lhsArgs))])
[]
(PApp fc (PRef fc cn)
(map pexp rhsArgs)) []
return (pn, pfnTy, PClauses fc [] setname [pclause])
implBindUp [] is t = t
implBindUp ((n, ty):ns) is t
= let n' = case lookup n is of
Just (PRef _ x) -> x
_ -> n in
if n `elem` allNamesIn t
then PPi impl n' ty (implBindUp ns is t)
else implBindUp ns is t
|
andyarvanitis/Idris-dev
|
src/Idris/Elab/Record.hs
|
bsd-3-clause
| 9,510
| 3
| 25
| 3,502
| 3,214
| 1,630
| 1,584
| 184
| 27
|
-- | Definition of HTML content type.
module HiCkevInServant.API.Internal
( HTML
) where
import Network.HTTP.Media ((//), (/:))
import Servant.API (Accept(..))
-- | HTML content type.
data HTML
instance Accept HTML where
contentType _ = "text" // "html" /: ("charset", "utf-8")
|
zchn/hi-ckev-in-servant
|
hi-ckev-in-servant-api/src/HiCkevInServant/API/Internal.hs
|
bsd-3-clause
| 287
| 0
| 7
| 49
| 79
| 50
| 29
| -1
| -1
|
module Obsidian.GCDObsidian.Globs where
------------------------------------------------------------------------------
-- Aliases
type Name = String
|
svenssonjoel/GCDObsidian
|
Obsidian/GCDObsidian/Globs.hs
|
bsd-3-clause
| 153
| 0
| 4
| 14
| 15
| 11
| 4
| 2
| 0
|
{-# LANGUAGE RecordWildCards #-}
-- | read/write ImpulseTracker samples
module Codec.Tracker.IT.Sample (
SampleHeader (..)
, getSampleHeader
, putSampleHeader
) where
import Control.Monad
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
-- | ImpulseTracker sample header
data SampleHeader = SampleHeader { magicNumber :: Word32 -- ^ "IMPS"
, fileName :: [Word8] -- ^ 12 bytes
, spad0 :: Word8 -- ^ padding
, globalVolume :: Word8 -- ^ global volume (0-64)
, flags :: Word8 -- ^ bit 0: sample associated with header, bit 1: 16 bit/8 bit,
-- bit 2: stereo/mono, bit 3: sample compression, bit 4: loop,
-- bit 5: sustain loop, bit 6: ping-pong loop/forwards loop,
-- bit 7: ping-pong sustain loop/forwards sustain loop
, defaultVolume :: Word8 -- ^ default volume
, name :: [Word8] -- ^ sample name (26 bytes)
, convert :: Word16 -- ^ bit 0: signed/unsigned samples,
-- bit 1: intel lo-hi byte order/ motorola hi-lo byte order,
-- bit 2: pcm/delta values, bit 3: byte delta values,
-- bit 4: tx-wave 12-bit values
, sampleLength :: Word32 -- ^ sample length
, loopBegin :: Word32 -- ^ loop begin
, loopEnd :: Word32 -- ^ loop end
, c5Speed :: Word32 -- ^ tuning
, susLoopBegin :: Word32 -- ^ sustain loop begin
, susLoopEnd :: Word32 -- ^ sustain loop end
, samplePointer :: Word32 -- ^ pointer to sample data
, vibratoSpeed :: Word8 -- ^ vibrato speed
, vibratoDepth :: Word8 -- ^ vibrato depth
, vibratoRate :: Word8 -- ^ vibrato rate
, vibratoType :: Word8 -- ^ vibrato waveform (0: sine, 1: ramp down, 2: square, 3: random)
-- cache file: , fileSize :: Word32
-- , date :: Word16
-- , time :: Word16
-- , format :: Word8
--
}
deriving (Show, Eq)
-- | Read a `SampleHeader` from the monad state.
getSampleHeader :: Get SampleHeader
getSampleHeader = label "IT.Sample SampleHeader" $
SampleHeader <$> getWord32le <*> replicateM 12 getWord8
<*> getWord8 <*> getWord8 <*> getWord8
<*> getWord8 <*> replicateM 26 getWord8
<*> getWord16le <*> getWord32le <*> getWord32le
<*> getWord32le <*> getWord32le <*> getWord32le
<*> getWord32le <*> getWord32le <*> getWord8
<*> getWord8 <*> getWord8 <*> getWord8
-- | Write a `SampleHeader` to the buffer.
putSampleHeader :: SampleHeader -> Put
putSampleHeader SampleHeader{..} = do
putWord32le magicNumber
mapM_ putWord8 (fileName ++ [spad0, globalVolume, flags, defaultVolume] ++ name)
putWord16le convert
mapM_ putWord32le [ sampleLength, loopBegin, loopEnd, c5Speed, susLoopBegin, susLoopEnd, samplePointer ]
mapM_ putWord8 [ vibratoSpeed, vibratoDepth, vibratoRate, vibratoType ]
|
riottracker/modfile
|
src/Codec/Tracker/IT/Sample.hs
|
bsd-3-clause
| 4,099
| 0
| 25
| 1,971
| 441
| 269
| 172
| 45
| 1
|
--
-- Finder.hs
--
module Finder where
findSame :: [String] -> [[String]]
findSame fs = map toPair fs
toPair :: String -> [String]
toPair f = [f, f]
|
eijian/picfinder
|
src/Finder1.hs
|
bsd-3-clause
| 152
| 0
| 7
| 31
| 64
| 38
| 26
| 5
| 1
|
-- The @FamInst@ type: family instance heads
{-# LANGUAGE CPP, GADTs #-}
module FamInst (
FamInstEnvs, tcGetFamInstEnvs,
checkFamInstConsistency, tcExtendLocalFamInstEnv,
tcLookupDataFamInst, tcLookupDataFamInst_maybe,
tcInstNewTyCon_maybe, tcTopNormaliseNewTypeTF_maybe,
newFamInst,
-- * Injectivity
makeInjectivityErrors, injTyVarsOfType, injTyVarsOfTypes
) where
import GhcPrelude
import HscTypes
import FamInstEnv
import InstEnv( roughMatchTcs )
import Coercion
import TcEvidence
import LoadIface
import TcRnMonad
import SrcLoc
import TyCon
import TcType
import CoAxiom
import DynFlags
import Module
import Outputable
import Util
import RdrName
import DataCon ( dataConName )
import Maybes
import Type
import TyCoRep
import TcMType
import Name
import Pair
import Panic
import VarSet
import Bag( Bag, unionBags, unitBag )
import Control.Monad
#include "HsVersions.h"
{-
Note [The type family instance consistency story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To preserve type safety we must ensure that for any given module, all
the type family instances used either in that module or in any module
it directly or indirectly imports are consistent. For example, consider
module F where
type family F a
module A where
import F( F )
type instance F Int = Bool
f :: F Int -> Bool
f x = x
module B where
import F( F )
type instance F Int = Char
g :: Char -> F Int
g x = x
module Bad where
import A( f )
import B( g )
bad :: Char -> Int
bad c = f (g c)
Even though module Bad never mentions the type family F at all, by
combining the functions f and g that were type checked in contradictory
type family instance environments, the function bad is able to coerce
from one type to another. So when we type check Bad we must verify that
the type family instances defined in module A are consistent with those
defined in module B.
How do we ensure that we maintain the necessary consistency?
* Call a module which defines at least one type family instance a
"family instance module". This flag `mi_finsts` is recorded in the
interface file.
* For every module we calculate the set of all of its direct and
indirect dependencies that are family instance modules. This list
`dep_finsts` is also recorded in the interface file so we can compute
this list for a module from the lists for its direct dependencies.
* When type checking a module M we check consistency of all the type
family instances that are either provided by its `dep_finsts` or
defined in the module M itself. This is a pairwise check, i.e., for
every pair of instances we must check that they are consistent.
- For family instances coming from `dep_finsts`, this is checked in
checkFamInstConsistency, called from tcRnImports. See Note
[Checking family instance consistency] for details on this check (and
in particular how we avoid having to do all these checks for every
module we compile).
- That leaves checking the family instances defined in M itself
against instances defined in either M or its `dep_finsts`. This is
checked in `tcExtendLocalFamInstEnv'.
There are two subtle points in this scheme which have not been
addressed yet.
* We have checked consistency of the family instances *defined* by M
or its imports, but this is not by definition the same thing as the
family instances *used* by M or its imports. Specifically, we need to
ensure when we use a type family instance while compiling M that this
instance was really defined from either M or one of its imports,
rather than being an instance that we happened to know about from
reading an interface file in the course of compiling an unrelated
module. Otherwise, we'll end up with no record of the fact that M
depends on this family instance and type safety will be compromised.
See #13102.
* It can also happen that M uses a function defined in another module
which is not transitively imported by M. Examples include the
desugaring of various overloaded constructs, and references inserted
by Template Haskell splices. If that function's definition makes use
of type family instances which are not checked against those visible
from M, type safety can again be compromised. See #13251.
* When a module C imports a boot module B.hs-boot, we check that C's
type family instances are compatible with those visible from
B.hs-boot. However, C will eventually be linked against a different
module B.hs, which might define additional type family instances which
are inconsistent with C's. This can also lead to loss of type safety.
See #9562.
-}
{-
************************************************************************
* *
Making a FamInst
* *
************************************************************************
-}
-- All type variables in a FamInst must be fresh. This function
-- creates the fresh variables and applies the necessary substitution
-- It is defined here to avoid a dependency from FamInstEnv on the monad
-- code.
newFamInst :: FamFlavor -> CoAxiom Unbranched -> TcRnIf gbl lcl FamInst
-- Freshen the type variables of the FamInst branches
-- Called from the vectoriser monad too, hence the rather general type
newFamInst flavor axiom@(CoAxiom { co_ax_tc = fam_tc })
= ASSERT2( tyCoVarsOfTypes lhs `subVarSet` tcv_set, text "lhs" <+> pp_ax )
ASSERT2( tyCoVarsOfType rhs `subVarSet` tcv_set, text "rhs" <+> pp_ax )
ASSERT2( lhs_kind `eqType` rhs_kind, text "kind" <+> pp_ax $$ ppr lhs_kind $$ ppr rhs_kind )
do { (subst, tvs') <- freshenTyVarBndrs tvs
; (subst, cvs') <- freshenCoVarBndrsX subst cvs
; return (FamInst { fi_fam = tyConName fam_tc
, fi_flavor = flavor
, fi_tcs = roughMatchTcs lhs
, fi_tvs = tvs'
, fi_cvs = cvs'
, fi_tys = substTys subst lhs
, fi_rhs = substTy subst rhs
, fi_axiom = axiom }) }
where
lhs_kind = typeKind (mkTyConApp fam_tc lhs)
rhs_kind = typeKind rhs
tcv_set = mkVarSet (tvs ++ cvs)
pp_ax = pprCoAxiom axiom
CoAxBranch { cab_tvs = tvs
, cab_cvs = cvs
, cab_lhs = lhs
, cab_rhs = rhs } = coAxiomSingleBranch axiom
{-
************************************************************************
* *
Optimised overlap checking for family instances
* *
************************************************************************
Note [Checking family instance consistency]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For any two family instance modules that we import directly or indirectly, we
check whether the instances in the two modules are consistent, *unless* we can
be certain that the instances of the two modules have already been checked for
consistency during the compilation of modules that we import.
Why do we need to check? Consider
module X1 where module X2 where
data T1 data T2
type instance F T1 b = Int type instance F a T2 = Char
f1 :: F T1 a -> Int f2 :: Char -> F a T2
f1 x = x f2 x = x
Now if we import both X1 and X2 we could make (f2 . f1) :: Int -> Char.
Notice that neither instance is an orphan.
How do we know which pairs of modules have already been checked? For each
module M we directly import, we look up the family instance modules that M
imports (directly or indirectly), say F1, ..., FN. For any two modules
among M, F1, ..., FN, we know that the family instances defined in those
two modules are consistent--because we checked that when we compiled M.
For every other pair of family instance modules we import (directly or
indirectly), we check that they are consistent now. (So that we can be
certain that the modules in our `HscTypes.dep_finsts' are consistent.)
There is some fancy footwork regarding hs-boot module loops, see
Note [Don't check hs-boot type family instances too early]
Note [Checking family instance optimization]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As explained in Note [Checking family instance consistency]
we need to ensure that every pair of transitive imports that define type family
instances is consistent.
Let's define df(A) = transitive imports of A that define type family instances
+ A, if A defines type family instances
Then for every direct import A, df(A) is already consistent.
Let's name the current module M.
We want to make sure that df(M) is consistent.
df(M) = df(D_1) U df(D_2) U ... U df(D_i) where D_1 .. D_i are direct imports.
We perform the check iteratively, maintaining a set of consistent modules 'C'
and trying to add df(D_i) to it.
The key part is how to ensure that the union C U df(D_i) is consistent.
Let's consider two modules: A and B from C U df(D_i).
There are nine possible ways to choose A and B from C U df(D_i):
| A in C only | A in C and B in df(D_i) | A in df(D_i) only
--------------------------------------------------------------------------------
B in C only | Already checked | Already checked | Needs to be checked
| when checking C | when checking C |
--------------------------------------------------------------------------------
B in C and | Already checked | Already checked | Already checked when
B in df(D_i) | when checking C | when checking C | checking df(D_i)
--------------------------------------------------------------------------------
B in df(D_i) | Needs to be | Already checked | Already checked when
only | checked | when checking df(D_i) | checking df(D_i)
That means to ensure that C U df(D_i) is consistent we need to check every
module from C - df(D_i) against every module from df(D_i) - C and
every module from df(D_i) - C against every module from C - df(D_i).
But since the checks are symmetric it suffices to pick A from C - df(D_i)
and B from df(D_i) - C.
In other words these are the modules we need to check:
[ (m1, m2) | m1 <- C, m1 not in df(D_i)
, m2 <- df(D_i), m2 not in C ]
One final thing to note here is that if there's lot of overlap between
subsequent df(D_i)'s then we expect those set differences to be small.
That situation should be pretty common in practice, there's usually
a set of utility modules that every module imports directly or indirectly.
This is basically the idea from #13092, comment:14.
-}
-- This function doesn't check ALL instances for consistency,
-- only ones that aren't involved in recursive knot-tying
-- loops; see Note [Don't check hs-boot type family instances too early].
-- We don't need to check the current module, this is done in
-- tcExtendLocalFamInstEnv.
-- See Note [The type family instance consistency story].
checkFamInstConsistency :: [Module] -> TcM ()
checkFamInstConsistency directlyImpMods
= do { dflags <- getDynFlags
; (eps, hpt) <- getEpsAndHpt
; traceTc "checkFamInstConsistency" (ppr directlyImpMods)
; let { -- Fetch the iface of a given module. Must succeed as
-- all directly imported modules must already have been loaded.
modIface mod =
case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of
Nothing -> panicDoc "FamInst.checkFamInstConsistency"
(ppr mod $$ pprHPT hpt)
Just iface -> iface
-- Which family instance modules were checked for consistency
-- when we compiled `mod`?
-- Itself (if a family instance module) and its dep_finsts.
-- This is df(D_i) from
-- Note [Checking family instance optimization]
; modConsistent :: Module -> [Module]
; modConsistent mod =
if mi_finsts (modIface mod) then mod:deps else deps
where
deps = dep_finsts . mi_deps . modIface $ mod
; hmiModule = mi_module . hm_iface
; hmiFamInstEnv = extendFamInstEnvList emptyFamInstEnv
. md_fam_insts . hm_details
; hpt_fam_insts = mkModuleEnv [ (hmiModule hmi, hmiFamInstEnv hmi)
| hmi <- eltsHpt hpt]
}
; checkMany hpt_fam_insts modConsistent directlyImpMods
}
where
-- See Note [Checking family instance optimization]
checkMany
:: ModuleEnv FamInstEnv -- home package family instances
-> (Module -> [Module]) -- given A, modules checked when A was checked
-> [Module] -- modules to process
-> TcM ()
checkMany hpt_fam_insts modConsistent mods = go [] emptyModuleSet mods
where
go :: [Module] -- list of consistent modules
-> ModuleSet -- set of consistent modules, same elements as the
-- list above
-> [Module] -- modules to process
-> TcM ()
go _ _ [] = return ()
go consistent consistent_set (mod:mods) = do
sequence_
[ check hpt_fam_insts m1 m2
| m1 <- to_check_from_mod
-- loop over toCheckFromMod first, it's usually smaller,
-- it may even be empty
, m2 <- to_check_from_consistent
]
go consistent' consistent_set' mods
where
mod_deps_consistent = modConsistent mod
mod_deps_consistent_set = mkModuleSet mod_deps_consistent
consistent' = to_check_from_mod ++ consistent
consistent_set' =
extendModuleSetList consistent_set to_check_from_mod
to_check_from_consistent =
filterOut (`elemModuleSet` mod_deps_consistent_set) consistent
to_check_from_mod =
filterOut (`elemModuleSet` consistent_set) mod_deps_consistent
-- Why don't we just minusModuleSet here?
-- We could, but doing so means one of two things:
--
-- 1. When looping over the cartesian product we convert
-- a set into a non-deterministicly ordered list. Which
-- happens to be fine for interface file determinism
-- in this case, today, because the order only
-- determines the order of deferred checks. But such
-- invariants are hard to keep.
--
-- 2. When looping over the cartesian product we convert
-- a set into a deterministically ordered list - this
-- adds some additional cost of sorting for every
-- direct import.
--
-- That also explains why we need to keep both 'consistent'
-- and 'consistentSet'.
--
-- See also Note [ModuleEnv performance and determinism].
check hpt_fam_insts m1 m2
= do { env1' <- getFamInsts hpt_fam_insts m1
; env2' <- getFamInsts hpt_fam_insts m2
-- We're checking each element of env1 against env2.
-- The cost of that is dominated by the size of env1, because
-- for each instance in env1 we look it up in the type family
-- environment env2, and lookup is cheap.
-- The code below ensures that env1 is the smaller environment.
; let sizeE1 = famInstEnvSize env1'
sizeE2 = famInstEnvSize env2'
(env1, env2) = if sizeE1 < sizeE2 then (env1', env2')
else (env2', env1')
-- Note [Don't check hs-boot type family instances too early]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Family instance consistency checking involves checking that
-- the family instances of our imported modules are consistent with
-- one another; this might lead you to think that this process
-- has nothing to do with the module we are about to typecheck.
-- Not so! Consider the following case:
--
-- -- A.hs-boot
-- type family F a
--
-- -- B.hs
-- import {-# SOURCE #-} A
-- type instance F Int = Bool
--
-- -- A.hs
-- import B
-- type family F a
--
-- When typechecking A, we are NOT allowed to poke the TyThing
-- for for F until we have typechecked the family. Thus, we
-- can't do consistency checking for the instance in B
-- (checkFamInstConsistency is called during renaming).
-- Failing to defer the consistency check lead to #11062.
--
-- Additionally, we should also defer consistency checking when
-- type from the hs-boot file of the current module occurs on
-- the left hand side, as we will poke its TyThing when checking
-- for overlap.
--
-- -- F.hs
-- type family F a
--
-- -- A.hs-boot
-- import F
-- data T
--
-- -- B.hs
-- import {-# SOURCE #-} A
-- import F
-- type instance F T = Int
--
-- -- A.hs
-- import B
-- data T = MkT
--
-- In fact, it is even necessary to defer for occurrences in
-- the RHS, because we may test for *compatibility* in event
-- of an overlap.
--
-- Why don't we defer ALL of the checks to later? Well, many
-- instances aren't involved in the recursive loop at all. So
-- we might as well check them immediately; and there isn't
-- a good time to check them later in any case: every time
-- we finish kind-checking a type declaration and add it to
-- a context, we *then* consistency check all of the instances
-- which mentioned that type. We DO want to check instances
-- as quickly as possible, so that we aren't typechecking
-- values with inconsistent axioms in scope.
--
-- See also Note [Tying the knot] and Note [Type-checking inside the knot]
-- for why we are doing this at all.
; let check_now = famInstEnvElts env1
; mapM_ (checkForConflicts (emptyFamInstEnv, env2)) check_now
; mapM_ (checkForInjectivityConflicts (emptyFamInstEnv,env2)) check_now
}
getFamInsts :: ModuleEnv FamInstEnv -> Module -> TcM FamInstEnv
getFamInsts hpt_fam_insts mod
| Just env <- lookupModuleEnv hpt_fam_insts mod = return env
| otherwise = do { _ <- initIfaceTcRn (loadSysInterface doc mod)
; eps <- getEps
; return (expectJust "checkFamInstConsistency" $
lookupModuleEnv (eps_mod_fam_inst_env eps) mod) }
where
doc = ppr mod <+> text "is a family-instance module"
{-
************************************************************************
* *
Lookup
* *
************************************************************************
-}
-- | If @co :: T ts ~ rep_ty@ then:
--
-- > instNewTyCon_maybe T ts = Just (rep_ty, co)
--
-- Checks for a newtype, and for being saturated
-- Just like Coercion.instNewTyCon_maybe, but returns a TcCoercion
tcInstNewTyCon_maybe :: TyCon -> [TcType] -> Maybe (TcType, TcCoercion)
tcInstNewTyCon_maybe = instNewTyCon_maybe
-- | Like 'tcLookupDataFamInst_maybe', but returns the arguments back if
-- there is no data family to unwrap.
-- Returns a Representational coercion
tcLookupDataFamInst :: FamInstEnvs -> TyCon -> [TcType]
-> (TyCon, [TcType], Coercion)
tcLookupDataFamInst fam_inst_envs tc tc_args
| Just (rep_tc, rep_args, co)
<- tcLookupDataFamInst_maybe fam_inst_envs tc tc_args
= (rep_tc, rep_args, co)
| otherwise
= (tc, tc_args, mkRepReflCo (mkTyConApp tc tc_args))
tcLookupDataFamInst_maybe :: FamInstEnvs -> TyCon -> [TcType]
-> Maybe (TyCon, [TcType], Coercion)
-- ^ Converts a data family type (eg F [a]) to its representation type (eg FList a)
-- and returns a coercion between the two: co :: F [a] ~R FList a.
tcLookupDataFamInst_maybe fam_inst_envs tc tc_args
| isDataFamilyTyCon tc
, match : _ <- lookupFamInstEnv fam_inst_envs tc tc_args
, FamInstMatch { fim_instance = rep_fam@(FamInst { fi_axiom = ax
, fi_cvs = cvs })
, fim_tys = rep_args
, fim_cos = rep_cos } <- match
, let rep_tc = dataFamInstRepTyCon rep_fam
co = mkUnbranchedAxInstCo Representational ax rep_args
(mkCoVarCos cvs)
= ASSERT( null rep_cos ) -- See Note [Constrained family instances] in FamInstEnv
Just (rep_tc, rep_args, co)
| otherwise
= Nothing
-- | 'tcTopNormaliseNewTypeTF_maybe' gets rid of top-level newtypes,
-- potentially looking through newtype /instances/.
--
-- It is only used by the type inference engine (specifically, when
-- solving representational equality), and hence it is careful to unwrap
-- only if the relevant data constructor is in scope. That's why
-- it get a GlobalRdrEnv argument.
--
-- It is careful not to unwrap data/newtype instances if it can't
-- continue unwrapping. Such care is necessary for proper error
-- messages.
--
-- It does not look through type families.
-- It does not normalise arguments to a tycon.
--
-- If the result is Just (rep_ty, (co, gres), rep_ty), then
-- co : ty ~R rep_ty
-- gres are the GREs for the data constructors that
-- had to be in scope
tcTopNormaliseNewTypeTF_maybe :: FamInstEnvs
-> GlobalRdrEnv
-> Type
-> Maybe ((Bag GlobalRdrElt, TcCoercion), Type)
tcTopNormaliseNewTypeTF_maybe faminsts rdr_env ty
-- cf. FamInstEnv.topNormaliseType_maybe and Coercion.topNormaliseNewType_maybe
= topNormaliseTypeX stepper plus ty
where
plus :: (Bag GlobalRdrElt, TcCoercion) -> (Bag GlobalRdrElt, TcCoercion)
-> (Bag GlobalRdrElt, TcCoercion)
plus (gres1, co1) (gres2, co2) = ( gres1 `unionBags` gres2
, co1 `mkTransCo` co2 )
stepper :: NormaliseStepper (Bag GlobalRdrElt, TcCoercion)
stepper = unwrap_newtype `composeSteppers` unwrap_newtype_instance
-- For newtype instances we take a double step or nothing, so that
-- we don't return the representation type of the newtype instance,
-- which would lead to terrible error messages
unwrap_newtype_instance rec_nts tc tys
| Just (tc', tys', co) <- tcLookupDataFamInst_maybe faminsts tc tys
= mapStepResult (\(gres, co1) -> (gres, co `mkTransCo` co1)) $
unwrap_newtype rec_nts tc' tys'
| otherwise = NS_Done
unwrap_newtype rec_nts tc tys
| Just con <- newTyConDataCon_maybe tc
, Just gre <- lookupGRE_Name rdr_env (dataConName con)
-- This is where we check that the
-- data constructor is in scope
= mapStepResult (\co -> (unitBag gre, co)) $
unwrapNewTypeStepper rec_nts tc tys
| otherwise
= NS_Done
{-
************************************************************************
* *
Extending the family instance environment
* *
************************************************************************
-}
-- Add new locally-defined family instances, checking consistency with
-- previous locally-defined family instances as well as all instances
-- available from imported modules. This requires loading all of our
-- imports that define family instances (if we haven't loaded them already).
tcExtendLocalFamInstEnv :: [FamInst] -> TcM a -> TcM a
-- If we weren't actually given any instances to add, then we don't want
-- to go to the bother of loading family instance module dependencies.
tcExtendLocalFamInstEnv [] thing_inside = thing_inside
-- Otherwise proceed...
tcExtendLocalFamInstEnv fam_insts thing_inside
= do { env <- getGblEnv
; let this_mod = tcg_mod env
imports = tcg_imports env
-- Optimization: If we're only defining type family instances
-- for type families *defined in the home package*, then we
-- only have to load interface files that belong to the home
-- package. The reason is that there's no recursion between
-- packages, so modules in other packages can't possibly define
-- instances for our type families.
--
-- (Within the home package, we could import a module M that
-- imports us via an hs-boot file, and thereby defines an
-- instance of a type family defined in this module. So we can't
-- apply the same logic to avoid reading any interface files at
-- all, when we define an instances for type family defined in
-- the current module.)
home_fams_only = all (nameIsHomePackage this_mod . fi_fam) fam_insts
want_module mod
| mod == this_mod = False
| home_fams_only = moduleUnitId mod == moduleUnitId this_mod
| otherwise = True
; loadModuleInterfaces (text "Loading family-instance modules")
(filter want_module (imp_finsts imports))
; (inst_env', fam_insts') <- foldlM addLocalFamInst
(tcg_fam_inst_env env, tcg_fam_insts env)
fam_insts
; let env' = env { tcg_fam_insts = fam_insts'
, tcg_fam_inst_env = inst_env' }
; setGblEnv env' thing_inside
}
-- Check that the proposed new instance is OK,
-- and then add it to the home inst env
-- This must be lazy in the fam_inst arguments, see Note [Lazy axiom match]
-- in FamInstEnv.hs
addLocalFamInst :: (FamInstEnv,[FamInst])
-> FamInst
-> TcM (FamInstEnv, [FamInst])
addLocalFamInst (home_fie, my_fis) fam_inst
-- home_fie includes home package and this module
-- my_fies is just the ones from this module
= do { traceTc "addLocalFamInst" (ppr fam_inst)
-- Unlike the case of class instances, don't override existing
-- instances in GHCi; it's unsound. See #7102.
; mod <- getModule
; traceTc "alfi" (ppr mod)
-- Fetch imported instances, so that we report
-- overlaps correctly.
-- Really we ought to only check consistency with
-- those instances which are transitively imported
-- by the current module, rather than every instance
-- we've ever seen. Fixing this is part of #13102.
; eps <- getEps
; let inst_envs = (eps_fam_inst_env eps, home_fie)
home_fie' = extendFamInstEnv home_fie fam_inst
-- Check for conflicting instance decls and injectivity violations
; no_conflict <- checkForConflicts inst_envs fam_inst
; injectivity_ok <- checkForInjectivityConflicts inst_envs fam_inst
; if no_conflict && injectivity_ok then
return (home_fie', fam_inst : my_fis)
else
return (home_fie, my_fis) }
{-
************************************************************************
* *
Checking an instance against conflicts with an instance env
* *
************************************************************************
Check whether a single family instance conflicts with those in two instance
environments (one for the EPS and one for the HPT).
-}
checkForConflicts :: FamInstEnvs -> FamInst -> TcM Bool
checkForConflicts inst_envs fam_inst
= do { let conflicts = lookupFamInstEnvConflicts inst_envs fam_inst
no_conflicts = null conflicts
; traceTc "checkForConflicts" $
vcat [ ppr (map fim_instance conflicts)
, ppr fam_inst
-- , ppr inst_envs
]
; unless no_conflicts $ conflictInstErr fam_inst conflicts
; return no_conflicts }
-- | Check whether a new open type family equation can be added without
-- violating injectivity annotation supplied by the user. Returns True when
-- this is possible and False if adding this equation would violate injectivity
-- annotation.
checkForInjectivityConflicts :: FamInstEnvs -> FamInst -> TcM Bool
checkForInjectivityConflicts instEnvs famInst
| isTypeFamilyTyCon tycon
-- type family is injective in at least one argument
, Injective inj <- tyConInjectivityInfo tycon = do
{ let axiom = coAxiomSingleBranch fi_ax
conflicts = lookupFamInstEnvInjectivityConflicts inj instEnvs famInst
-- see Note [Verifying injectivity annotation] in FamInstEnv
errs = makeInjectivityErrors fi_ax axiom inj conflicts
; mapM_ (\(err, span) -> setSrcSpan span $ addErr err) errs
; return (null errs)
}
-- if there was no injectivity annotation or tycon does not represent a
-- type family we report no conflicts
| otherwise = return True
where tycon = famInstTyCon famInst
fi_ax = fi_axiom famInst
-- | Build a list of injectivity errors together with their source locations.
makeInjectivityErrors
:: CoAxiom br -- ^ Type family for which we generate errors
-> CoAxBranch -- ^ Currently checked equation (represented by axiom)
-> [Bool] -- ^ Injectivity annotation
-> [CoAxBranch] -- ^ List of injectivity conflicts
-> [(SDoc, SrcSpan)]
makeInjectivityErrors fi_ax axiom inj conflicts
= ASSERT2( any id inj, text "No injective type variables" )
let lhs = coAxBranchLHS axiom
rhs = coAxBranchRHS axiom
are_conflicts = not $ null conflicts
unused_inj_tvs = unusedInjTvsInRHS (coAxiomTyCon fi_ax) inj lhs rhs
inj_tvs_unused = not $ and (isEmptyVarSet <$> unused_inj_tvs)
tf_headed = isTFHeaded rhs
bare_variables = bareTvInRHSViolated lhs rhs
wrong_bare_rhs = not $ null bare_variables
err_builder herald eqns
= ( hang herald
2 (vcat (map (pprCoAxBranch fi_ax) eqns))
, coAxBranchSpan (head eqns) )
errorIf p f = if p then [f err_builder axiom] else []
in errorIf are_conflicts (conflictInjInstErr conflicts )
++ errorIf inj_tvs_unused (unusedInjectiveVarsErr unused_inj_tvs)
++ errorIf tf_headed tfHeadedErr
++ errorIf wrong_bare_rhs (bareVariableInRHSErr bare_variables)
-- | Return a list of type variables that the function is injective in and that
-- do not appear on injective positions in the RHS of a family instance
-- declaration. The returned Pair includes invisible vars followed by visible ones
unusedInjTvsInRHS :: TyCon -> [Bool] -> [Type] -> Type -> Pair TyVarSet
-- INVARIANT: [Bool] list contains at least one True value
-- See Note [Verifying injectivity annotation]. This function implements fourth
-- check described there.
-- In theory, instead of implementing this whole check in this way, we could
-- attempt to unify equation with itself. We would reject exactly the same
-- equations but this method gives us more precise error messages by returning
-- precise names of variables that are not mentioned in the RHS.
unusedInjTvsInRHS tycon injList lhs rhs =
(`minusVarSet` injRhsVars) <$> injLHSVars
where
-- set of type and kind variables in which type family is injective
(invis_pairs, vis_pairs)
= partitionInvisibles tycon snd (zipEqual "unusedInjTvsInRHS" injList lhs)
invis_lhs = uncurry filterByList $ unzip invis_pairs
vis_lhs = uncurry filterByList $ unzip vis_pairs
invis_vars = tyCoVarsOfTypes invis_lhs
Pair invis_vars' vis_vars = splitVisVarsOfTypes vis_lhs
injLHSVars
= Pair (invis_vars `minusVarSet` vis_vars `unionVarSet` invis_vars')
vis_vars
-- set of type variables appearing in the RHS on an injective position.
-- For all returned variables we assume their associated kind variables
-- also appear in the RHS.
injRhsVars = injTyVarsOfType rhs
injTyVarsOfType :: TcTauType -> TcTyVarSet
-- Collect all type variables that are either arguments to a type
-- constructor or to /injective/ type families.
-- Determining the overall type determines thes variables
--
-- E.g. Suppose F is injective in its second arg, but not its first
-- then injVarOfType (Either a (F [b] (a,c))) = {a,c}
-- Determining the overall type determines a,c but not b.
injTyVarsOfType (TyVarTy v)
= unitVarSet v `unionVarSet` injTyVarsOfType (tyVarKind v)
injTyVarsOfType (TyConApp tc tys)
| isTypeFamilyTyCon tc
= case tyConInjectivityInfo tc of
NotInjective -> emptyVarSet
Injective inj -> injTyVarsOfTypes (filterByList inj tys)
| otherwise
= injTyVarsOfTypes tys
injTyVarsOfType (LitTy {})
= emptyVarSet
injTyVarsOfType (FunTy arg res)
= injTyVarsOfType arg `unionVarSet` injTyVarsOfType res
injTyVarsOfType (AppTy fun arg)
= injTyVarsOfType fun `unionVarSet` injTyVarsOfType arg
-- No forall types in the RHS of a type family
injTyVarsOfType (CastTy ty _) = injTyVarsOfType ty
injTyVarsOfType (CoercionTy {}) = emptyVarSet
injTyVarsOfType (ForAllTy {}) =
panic "unusedInjTvsInRHS.injTyVarsOfType"
injTyVarsOfTypes :: [Type] -> VarSet
injTyVarsOfTypes tys = mapUnionVarSet injTyVarsOfType tys
-- | Is type headed by a type family application?
isTFHeaded :: Type -> Bool
-- See Note [Verifying injectivity annotation]. This function implements third
-- check described there.
isTFHeaded ty | Just ty' <- coreView ty
= isTFHeaded ty'
isTFHeaded ty | (TyConApp tc args) <- ty
, isTypeFamilyTyCon tc
= args `lengthIs` tyConArity tc
isTFHeaded _ = False
-- | If a RHS is a bare type variable return a set of LHS patterns that are not
-- bare type variables.
bareTvInRHSViolated :: [Type] -> Type -> [Type]
-- See Note [Verifying injectivity annotation]. This function implements second
-- check described there.
bareTvInRHSViolated pats rhs | isTyVarTy rhs
= filter (not . isTyVarTy) pats
bareTvInRHSViolated _ _ = []
conflictInstErr :: FamInst -> [FamInstMatch] -> TcRn ()
conflictInstErr fam_inst conflictingMatch
| (FamInstMatch { fim_instance = confInst }) : _ <- conflictingMatch
= let (err, span) = makeFamInstsErr
(text "Conflicting family instance declarations:")
[fam_inst, confInst]
in setSrcSpan span $ addErr err
| otherwise
= panic "conflictInstErr"
-- | Type of functions that use error message and a list of axioms to build full
-- error message (with a source location) for injective type families.
type InjErrorBuilder = SDoc -> [CoAxBranch] -> (SDoc, SrcSpan)
-- | Build injecivity error herald common to all injectivity errors.
injectivityErrorHerald :: Bool -> SDoc
injectivityErrorHerald isSingular =
text "Type family equation" <> s isSingular <+> text "violate" <>
s (not isSingular) <+> text "injectivity annotation" <>
if isSingular then dot else colon
-- Above is an ugly hack. We want this: "sentence. herald:" (note the dot and
-- colon). But if herald is empty we want "sentence:" (note the colon). We
-- can't test herald for emptiness so we rely on the fact that herald is empty
-- only when isSingular is False. If herald is non empty it must end with a
-- colon.
where
s False = text "s"
s True = empty
-- | Build error message for a pair of equations violating an injectivity
-- annotation.
conflictInjInstErr :: [CoAxBranch] -> InjErrorBuilder -> CoAxBranch
-> (SDoc, SrcSpan)
conflictInjInstErr conflictingEqns errorBuilder tyfamEqn
| confEqn : _ <- conflictingEqns
= errorBuilder (injectivityErrorHerald False) [confEqn, tyfamEqn]
| otherwise
= panic "conflictInjInstErr"
-- | Build error message for equation with injective type variables unused in
-- the RHS.
unusedInjectiveVarsErr :: Pair TyVarSet -> InjErrorBuilder -> CoAxBranch
-> (SDoc, SrcSpan)
unusedInjectiveVarsErr (Pair invis_vars vis_vars) errorBuilder tyfamEqn
= errorBuilder (injectivityErrorHerald True $$ msg)
[tyfamEqn]
where
tvs = invis_vars `unionVarSet` vis_vars
has_types = not $ isEmptyVarSet vis_vars
has_kinds = not $ isEmptyVarSet invis_vars
doc = sep [ what <+> text "variable" <>
pluralVarSet tvs <+> pprVarSet tvs (pprQuotedList . toposortTyVars)
, text "cannot be inferred from the right-hand side." ]
what = case (has_types, has_kinds) of
(True, True) -> text "Type and kind"
(True, False) -> text "Type"
(False, True) -> text "Kind"
(False, False) -> pprPanic "mkUnusedInjectiveVarsErr" $ ppr tvs
print_kinds_info = ppWhen has_kinds ppSuggestExplicitKinds
msg = doc $$ print_kinds_info $$
text "In the type family equation:"
-- | Build error message for equation that has a type family call at the top
-- level of RHS
tfHeadedErr :: InjErrorBuilder -> CoAxBranch
-> (SDoc, SrcSpan)
tfHeadedErr errorBuilder famInst
= errorBuilder (injectivityErrorHerald True $$
text "RHS of injective type family equation cannot" <+>
text "be a type family:") [famInst]
-- | Build error message for equation that has a bare type variable in the RHS
-- but LHS pattern is not a bare type variable.
bareVariableInRHSErr :: [Type] -> InjErrorBuilder -> CoAxBranch
-> (SDoc, SrcSpan)
bareVariableInRHSErr tys errorBuilder famInst
= errorBuilder (injectivityErrorHerald True $$
text "RHS of injective type family equation is a bare" <+>
text "type variable" $$
text "but these LHS type and kind patterns are not bare" <+>
text "variables:" <+> pprQuotedList tys) [famInst]
makeFamInstsErr :: SDoc -> [FamInst] -> (SDoc, SrcSpan)
makeFamInstsErr herald insts
= ASSERT( not (null insts) )
( hang herald
2 (vcat [ pprCoAxBranchHdr (famInstAxiom fi) 0
| fi <- sorted ])
, srcSpan )
where
getSpan = getSrcLoc . famInstAxiom
sorted = sortWith getSpan insts
fi1 = head sorted
srcSpan = coAxBranchSpan (coAxiomSingleBranch (famInstAxiom fi1))
-- The sortWith just arranges that instances are dislayed in order
-- of source location, which reduced wobbling in error messages,
-- and is better for users
tcGetFamInstEnvs :: TcM FamInstEnvs
-- Gets both the external-package inst-env
-- and the home-pkg inst env (includes module being compiled)
tcGetFamInstEnvs
= do { eps <- getEps; env <- getGblEnv
; return (eps_fam_inst_env eps, tcg_fam_inst_env env) }
|
ezyang/ghc
|
compiler/typecheck/FamInst.hs
|
bsd-3-clause
| 39,872
| 0
| 17
| 11,135
| 4,680
| 2,541
| 2,139
| -1
| -1
|
module Main where
import ABS
(n_div:x:main_ret:i:f:n:obj:reminder:res:the_end) = [0..]
main_ :: Method
main_ [] this wb k =
Assign n (Val (I 4000)) $
Assign x (Sync primality_test [n]) $
k
primality_test :: Method
primality_test [pn] this wb k =
Assign i (Val (I 1)) $
Assign n (Val (I pn)) $
While (ILTE (Attr i) (Attr n)) (\k' ->
Assign obj New $
Assign f (Async obj divides [i,n]) $
Assign i (Val (Add (Attr i) (I 1))) $
k'
) $
Return i wb k
divides :: Method
divides [pd, pn] this wb k =
Assign reminder (Val (Mod (I pn) (I pd)) ) $
If (IEq (Attr reminder) (I 0))
(\k' -> Assign res (Val (I 1)) k')
(\k' -> Assign res (Val (I 0)) k' ) $
Return res wb k
main' :: IO ()
main' = run' 1000000 main_ (head the_end)
main :: IO ()
main = printHeap =<< run 1000000 main_ (head the_end)
|
abstools/abs-haskell-formal
|
benchmarks/3_primality_test_parallel/progs/4000.hs
|
bsd-3-clause
| 846
| 0
| 18
| 222
| 506
| 256
| 250
| 30
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Challenges.Set1 as S1
import Challenges.Set2 as S2
import Utils.Elmify ((|>))
import qualified Stats.Frequency as Frequency
--import qualified Data.ByteString as B
-- import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString as B
import Text.Printf
import Prelude
import System.Random (getStdGen)
import Utils.Bytes (stringToByteString)
main :: IO ()
main = do
--s1ch1
--s1ch2
--s1ch3
--s1ch4
--s1ch5
--s1ch6
--s1ch7
--s1ch8
--s2ch10
s2ch11
s2ch12
s2ch13
s1ch1 :: IO ()
s1ch1 =
do
putStrLn "Set 1, challenge 1"
putStrLn $ show $ S1.challenge1 hexString
putStrLn ""
where
hexString =
"49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
s1ch2 :: IO ()
s1ch2 =
showRes res
where
res =
S1.challenge2 "1c0111001f010100061a024b53535009181c" "686974207468652062756c6c277320657965"
showRes c =
do
putStrLn "Set 1, challenge 2"
putStrLn $ show c
putStrLn ""
s1ch3 :: IO ()
s1ch3 =
showRes res
where
res =
S1.challenge3 resultStr
-- |> C3.bestMatch
showRes c =
do
putStrLn "Set 1, challenge 3"
putStrLn $ show c
putStrLn ""
resultStr =
"1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"
--"1c0111001f010100061a024b53535009181c"
s1ch4 :: IO ()
s1ch4 =
do
putStrLn "Set 1, challenge 4"
fileContents <- readFile "./static/4.txt"
putStrLn $ show $ S1.challenge4 $ lines fileContents
putStrLn ""
s1ch5 :: IO ()
s1ch5 =
do
putStrLn "Set 1, challenge 5"
putStrLn $ S1.challenge5 stringToCipher "ICE"
putStrLn ""
where
stringToCipher = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
s1ch6 ::IO ()
s1ch6 =
do
putStrLn "Set 1, challenge 6"
fileContents <- B.readFile "./static/6.txt"
mapM_ (putStrLn . showRes) $ S1.challenge6 fileContents
putStrLn ""
where
showRes (key, res) =
(show key) ++ " : " ++ (show (B.take 64 res))
s1ch6b :: IO ()
s1ch6b =
do
putStrLn "Set 1, challenge 6, using the input from challenge 5"
mapM_ (putStrLn . showRes) $ S1.challenge6 str2decrypt
putStrLn ""
where
showRes (key, res) =
(show key) ++ " : " ++ (show (B.take 64 res))
str2decrypt =
"CzY3JyorLmNiLC5paSojaToqPGMkIC1iPWM0PComImMkJydlJyooKy8gQwplLixlKjEkMzplPisgJ2MMaSsgKDFlKGMmMC4nKC8="
-- "AAsDBgMHAgcCCgILAg4GAwYCAgwCDgYJBgkCCgIDBgkDCgIKAwwGAwIEAgACDQYCAw0GAwMEAwwCCgIGAgIGAwIEAgcCBwYFAgcCCgIIAgsCDwIABAMACgYFAg4CDAYFAgoDAQIEAwMDCgYFAw4CCwIAAgcGAwAMBgkCCwIAAggDAQYFAggGAwIGAwACDgIHAggCDw=="
s1ch7 ::IO ()
s1ch7 =
do
putStrLn "Set 1, challenge 7"
fileContents <- B.readFile "./static/7.txt"
putStrLn $ showRes $ S1.challenge7 "YELLOW SUBMARINE" fileContents
putStrLn ""
where
showRes res =
show (B.take 64 res)
s1ch8 ::IO ()
s1ch8 =
do
putStrLn "Set 1, challenge 8 "
putStrLn "Shows a tuple consisting of "
putStrLn " * the minimum hamming distance of any set of blocks with keysize 16"
putStrLn " * the string in which that was found"
fileContents <- readFile "./static/8.txt"
putStrLn $ showRes $ S1.challenge8 16 $ lines fileContents
putStrLn ""
where
showRes res =
show res
--show (B.take 64 res)
s2ch10 ::IO ()
s2ch10 =
do
putStrLn "Set 2, challenge 10 "
fileContents <- B.readFile "./static/10.txt"
putStrLn $ showRes $ S2.challenge10 key fileContents
putStrLn ""
where
key =
"YELLOW SUBMARINE"::B.ByteString
showRes res =
--show res
show (B.take 64 res)
s2ch11::IO ()
s2ch11 =
do
putStrLn "Set 2, challenge 11 "
fileContents <- B.readFile "./static/11.txt"
generator <- getStdGen
mapM_ (putStrLn . showRes) $ S2.challenge11 generator fileContents
putStrLn ""
where
showRes (i, res) =
-- B.concat [(toBs i), " : ", (l res), " - ", (firstBytes res), " | ", (lastBytes res)]
B.concat [(toBs i), " : ", (l res), " - ", (firstBytes res), "[...]"]
|> show
firstBytes x =
B.take 24 x
lastBytes x =
B.drop ((B.length x) - 24) x
l x =
B.length x
|> show
|> stringToByteString
toBs =
stringToByteString . show
s2ch12::IO ()
s2ch12 =
do
putStrLn "Set 2, challenge 12 "
generator <- getStdGen
-- mapM_ (putStrLn . show) $ S2.challenge12 generator
(putStrLn . show) $ S2.challenge12 generator
putStrLn ""
s2ch13::IO ()
s2ch13 =
do
putStrLn "Set 2, challenge 13 "
generator <- getStdGen
(putStrLn . show) $ S2.challenge13 generator "fool1@bar.com"
putStrLn ""
|
eelcoh/cryptochallenge
|
app/Main.hs
|
bsd-3-clause
| 4,859
| 0
| 12
| 1,259
| 1,181
| 575
| 606
| 146
| 1
|
{-# LANGUAGE RankNTypes, GeneralizedNewtypeDeriving #-}
module Types where
import Data.Text (Text)
import System.Exit
import Control.Monad.IO.Class
import Control.Applicative
import System.Posix.Process.ByteString
import Data.ByteString.Char8 (ByteString)
data Command = Command Exp [Exp]
deriving (Read, Show, Eq)
data ExtCommand = ExtCommand ByteString [ByteString]
deriving (Read, Show, Eq)
data Exp = StrExp Text
| ConcatExp [Exp]
| QuoteExp Exp
| ParenExp Exp
| BraceExp Exp
| BracketExp Exp
| BackTickExp Exp
| DollarExp Exp
deriving (Read, Show, Eq)
data SuccessState = CommandResult ProcessStatus
| InternalResult Bool String
deriving (Show, Eq)
newtype Shell a = Sh (IO a)
deriving (Monad, MonadIO, Functor, Applicative)
runShell :: Shell a -> IO a
runShell (Sh f) = liftIO f
|
firefrorefiddle/hssh
|
src/Types.hs
|
bsd-3-clause
| 967
| 0
| 7
| 291
| 263
| 150
| 113
| 28
| 1
|
module Main where
check :: Maybe (Int,Int,Int,Int) -> Char -> Maybe (Int,Int,Int,Int)
check Nothing c = Nothing
check (Just (r,g,y,b)) c
| 1 < (abs (nr - ng)) = Nothing
| 1 < (abs (ny - nb)) = Nothing
| otherwise = Just (nr, ng, ny, nb)
where (nr,ng,ny,nb) = case c of
'R' -> (r+1,g,y,b)
'G' -> (r,g+1,y,b)
'Y' -> (r,g,y+1,b)
'B' -> (r,g,y,b+1)
check2 :: Maybe (Int,Int,Int,Int) -> Maybe Bool
check2 Nothing = Nothing
check2 (Just (r,g,y,b)) = if r == g && y == b then Just True else Nothing
main :: IO ()
main = do tStr <- getLine
let t = read tStr :: Int
mapM_ (\_ -> getLine >>= \s -> let r = check2 $ foldl check (Just (0,0,0,0)) s
in case r of
Just _ -> putStrLn "True"
Nothing -> putStrLn "False"
) [1..t]
|
everyevery/programming_study
|
hackerrank/functional/sequence-full-of-colors/sequence-full-of-colors.hs
|
mit
| 1,036
| 0
| 20
| 466
| 486
| 264
| 222
| 23
| 4
|
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DataKinds, FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE StandaloneDeriving #-}
module CustomConstraintTest where
import MyInit
import qualified Data.Text as T
share [mkPersist sqlSettings, mkMigrate "customConstraintMigrate"] [persistLowerCase|
CustomConstraint1
some_field Text
deriving Show
CustomConstraint2
cc_id CustomConstraint1Id constraint=custom_constraint
deriving Show
CustomConstraint3
-- | This will lead to a constraint with the name custom_constraint3_cc_id1_fkey
cc_id1 CustomConstraint1Id
cc_id2 CustomConstraint1Id
deriving Show
|]
clean :: MonadUnliftIO m => SqlPersistT m ()
clean = do
rawExecute "drop table custom_constraint3" []
rawExecute "drop table custom_constraint2" []
rawExecute "drop table custom_constraint1" []
specs :: (MonadUnliftIO m, MonadFail m) => RunDb SqlBackend m -> Spec
specs runDb = do
describe "custom constraint used in migration" $ before_ (runDb $ void $ runMigrationSilent customConstraintMigrate) $ after_ (runDb clean) $ do
it "custom constraint is actually created" $ runDb $ do
void $ runMigrationSilent customConstraintMigrate -- run a second time to ensure the constraint isn't dropped
let query = T.concat ["SELECT COUNT(*) "
,"FROM information_schema.key_column_usage "
,"WHERE ordinal_position=1 "
,"AND referenced_table_name=? "
,"AND referenced_column_name=? "
,"AND table_name=? "
,"AND column_name=? "
,"AND constraint_name=?"]
[Single exists_] <- rawSql query
[ PersistText "custom_constraint1"
, PersistText "id"
, PersistText "custom_constraint2"
, PersistText "cc_id"
, PersistText "custom_constraint"
]
liftIO $ 1 @?= (exists_ :: Int)
it "allows multiple constraints on a single column" $ runDb $ do
-- Here we add another foreign key on the same column where the
-- default one already exists. In practice, this could be
-- a compound key with another field.
rawExecute "ALTER TABLE custom_constraint3 ADD CONSTRAINT extra_constraint FOREIGN KEY(cc_id1) REFERENCES custom_constraint1(id)" []
-- This is where the error is thrown in `getColumn`
_ <- getMigration customConstraintMigrate
pure ()
|
yesodweb/persistent
|
persistent-mysql/test/CustomConstraintTest.hs
|
mit
| 2,946
| 0
| 17
| 819
| 361
| 186
| 175
| 46
| 1
|
{-# LANGUAGE LambdaCase, FlexibleContexts #-}
module Commands.Plugins.Spiros.Edit.Run where
import Commands.Plugins.Spiros.Edit.Types
import Commands.Plugins.Spiros.Emacs
import Commands.Plugins.Spiros.Extra
import Commands.Backends.Workflow as W
rankMove :: Move -> Int
rankMove _m = 0
rankEdit :: Edit -> Int
rankEdit (Edit a s r) = (sum . fmap fromEnum) [a /= defaultAction, s /= defaultSlice, r /= defaultRegion]
-- defaults have lower rank
-- disambiguates "cop fuss line" into [cop fuss line], not [cop] [fuss line] which comes first in the order
runMove :: MonadWorkflow m => Move -> m()
runMove = moveEmacs
-- the indirection (i.e. @data 'Move'@, not just a @String@) makes it easy to reinterpret in many ways (e.g. moveEmacs, moveIntelliJ, moveChromd , etc).
moveEmacs :: MonadWorkflow m => Move -> m ()
moveEmacs = \case
Move Left_ Character -> press "C-b"
Move Right_ Character -> press "C-f"
Move Left_ Word_ -> press "M-b"
Move Right_ Word_ -> press "M-f"
Move Left_ Group -> press "C-M-b"
Move Right_ Group -> press "C-M-f"
Move Up_ Line -> press "C-p"
Move Down_ Line -> press "C-n"
Move Up_ Block -> press "C-<up>"
Move Down_ Block -> press "C-<down>"
Move Up_ Screen -> runEmacs "scroll-up-command"
Move Down_ Screen -> press "C-v"
Move Up_ Page -> runEmacs "backward-page"
Move Down_ Page -> runEmacs "forward-page"
MoveTo Beginning Line -> press "C-a"
MoveTo Ending Line -> press "C-e"
MoveTo Beginning Everything -> press "M-<up>"
MoveTo Ending Everything -> press "M-<down>"
-- Move -> press
-- MoveTo -> press
_ -> nothing
-- gets the given region of text from Emacs
selected :: MonadWorkflow m => Slice -> Region -> m String
selected s r = do
-- editEmacs (Edit Select s r)
select r s
copy
select :: MonadWorkflow m => Region -> Slice -> m ()
select That = \case
_ -> nothing -- (should be) already selected
-- select Character = \case
-- _ -> nothing
select r = \case
Whole -> beg_of r >> mark >> end_of r
Backwards -> mark >> beg_of r
Forwards -> mark >> end_of r
{-
idempotent means
idempotent means unchainable.
instead of [3 select word], how about [select 3 word]
where the first selection is idempotent, and the next two Move Right.
In Emacs, this preserves the mark.
-}
-- | should be idempotent (in Emacs, not Haskell).
beg_of :: MonadWorkflow m => Region -> m ()
beg_of = \case
-- runEmacs
That -> evalEmacs "(goto-char (region-beginning))"
Character -> nothing
Word_ -> evalEmacs "(beginning-of-thing 'word)"
Group -> evalEmacs "(beginning-of-thing 'list)"
Line -> press "C-a"
Block -> evalEmacs "(beginning-of-thing 'block)"
Page -> evalEmacs "(beginning-of-thing 'page)"
Screen -> evalEmacs "(goto-char (window-start))"
Everything -> runEmacs "beginning-of-buffer"
_ -> nothing
-- | should be idempotent (in Emacs, not Haskell).
end_of :: MonadWorkflow m => Region -> m ()
end_of = \case
-- runEmacs
That -> evalEmacs "(goto-char (region-end))"
Character -> nothing -- [press C f] is not idempotent, but [nothing] fails on [beg_of r >> mark >> end_of r]
Word_ -> evalEmacs "(end-of-thing 'word)"
Group -> evalEmacs "(end-of-thing 'list)"
Line -> press "C-e"
Block -> evalEmacs "(end-of-thing 'block)" -- non-standard: expects forward-block
Page -> evalEmacs "(end-of-thing 'page)"
Screen -> evalEmacs "(goto-char (window-end))"
Everything -> runEmacs "end-of-buffer"
_ -> nothing
runEdit :: MonadWorkflow m => Edit -> m()
runEdit = editEmacs
-- | vim's composeability would keep the number of cases linear (not quadratic in 'Action's times 'Region's).
-- in Emacs, we can use <http://www.emacswiki.org/emacs/ThingAtPoint thingatpt.el>.
editEmacs :: MonadWorkflow m => Edit -> m ()
editEmacs = \case
Edit Select Whole Line -> do -- special behavior
select Line Whole
press "<right>"
Edit Select _ Character -> do -- special behavior
mark
press "<right>"
Edit Select s r -> do
select r s -- generic behavior
activate_mark
-- some Regions need a { press right } for idempotency of their beg_of/end_of
Edit Google s r -> do
google =<< selected s r
Edit Delete s r -> do
select r s
press "<del>"
Edit Copy s r -> do
select r s
press "M-c" -- like Cua-mode for Mac
Edit Cut s r -> do
select r s
press "M-x" -- like Cua-mode for Mac
Edit Transpose _ Character -> press "C-t"
Edit Transpose _ Word_ -> press "M-t"
Edit Transpose _ Group -> press "C-M-t"
Edit Transpose _ Line -> press "C-x-t"
Edit Transpose _ Block -> runEmacs "transpose-block" -- nonstandard
-- Edit Transpose _ ->
-- That
-- Character
-- Word_
-- Token
-- Group
-- Line
-- Rectangle
-- Block
-- Page
-- Screen
-- Everything
-- Definition
-- Function_
-- Reference
-- Structure
_ -> nothing
|
sboosali/commands-spiros
|
config/Commands/Plugins/Spiros/Edit/Run.hs
|
gpl-2.0
| 5,004
| 0
| 11
| 1,170
| 1,156
| 560
| 596
| 98
| 19
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.ECS.DescribeTasks
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Describes a specified task or tasks.
--
-- <http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_DescribeTasks.html>
module Network.AWS.ECS.DescribeTasks
(
-- * Request
DescribeTasks
-- ** Request constructor
, describeTasks
-- ** Request lenses
, dtCluster
, dtTasks
-- * Response
, DescribeTasksResponse
-- ** Response constructor
, describeTasksResponse
-- ** Response lenses
, dtrFailures
, dtrTasks
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.ECS.Types
import qualified GHC.Exts
data DescribeTasks = DescribeTasks
{ _dtCluster :: Maybe Text
, _dtTasks :: List "tasks" Text
} deriving (Eq, Ord, Read, Show)
-- | 'DescribeTasks' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dtCluster' @::@ 'Maybe' 'Text'
--
-- * 'dtTasks' @::@ ['Text']
--
describeTasks :: DescribeTasks
describeTasks = DescribeTasks
{ _dtCluster = Nothing
, _dtTasks = mempty
}
-- | The short name or full Amazon Resource Name (ARN) of the cluster that hosts
-- the task you want to describe. If you do not specify a cluster, the default
-- cluster is assumed.
dtCluster :: Lens' DescribeTasks (Maybe Text)
dtCluster = lens _dtCluster (\s a -> s { _dtCluster = a })
-- | A space-separated list of task UUIDs or full Amazon Resource Name (ARN)
-- entries.
dtTasks :: Lens' DescribeTasks [Text]
dtTasks = lens _dtTasks (\s a -> s { _dtTasks = a }) . _List
data DescribeTasksResponse = DescribeTasksResponse
{ _dtrFailures :: List "failures" Failure
, _dtrTasks :: List "tasks" Task
} deriving (Eq, Read, Show)
-- | 'DescribeTasksResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dtrFailures' @::@ ['Failure']
--
-- * 'dtrTasks' @::@ ['Task']
--
describeTasksResponse :: DescribeTasksResponse
describeTasksResponse = DescribeTasksResponse
{ _dtrTasks = mempty
, _dtrFailures = mempty
}
dtrFailures :: Lens' DescribeTasksResponse [Failure]
dtrFailures = lens _dtrFailures (\s a -> s { _dtrFailures = a }) . _List
-- | The list of tasks.
dtrTasks :: Lens' DescribeTasksResponse [Task]
dtrTasks = lens _dtrTasks (\s a -> s { _dtrTasks = a }) . _List
instance ToPath DescribeTasks where
toPath = const "/"
instance ToQuery DescribeTasks where
toQuery = const mempty
instance ToHeaders DescribeTasks
instance ToJSON DescribeTasks where
toJSON DescribeTasks{..} = object
[ "cluster" .= _dtCluster
, "tasks" .= _dtTasks
]
instance AWSRequest DescribeTasks where
type Sv DescribeTasks = ECS
type Rs DescribeTasks = DescribeTasksResponse
request = post "DescribeTasks"
response = jsonResponse
instance FromJSON DescribeTasksResponse where
parseJSON = withObject "DescribeTasksResponse" $ \o -> DescribeTasksResponse
<$> o .:? "failures" .!= mempty
<*> o .:? "tasks" .!= mempty
|
romanb/amazonka
|
amazonka-ecs/gen/Network/AWS/ECS/DescribeTasks.hs
|
mpl-2.0
| 4,053
| 0
| 13
| 910
| 610
| 365
| 245
| 67
| 1
|
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE Rank2Types #-}
module Language.K3.Runtime.FileDataspace (
FileDataspace(..),
getFile, -- Should this really be exported? Used to pack dataspace
initDataDir,
generateCollectionFilename,
emptyFile,
initialFile,
copyFile,
peekFile,
foldFile,
mapFile,
mapFile_,
filterFile,
insertFile,
deleteFile,
updateFile,
combineFile,
splitFile,
sortFile
) where
import Control.Concurrent.MVar
import qualified Control.Monad.Reader as M
import qualified System.IO as IO
import qualified System.Directory as DIR
import qualified System.FilePath as FP
import Language.K3.Core.Common
import Language.K3.Runtime.Engine
newtype FileDataspace v = FileDataspace String deriving (Eq, Read, Show)
getFile :: FileDataspace v -> String
getFile (FileDataspace name) = name
rootDataPath :: IO.FilePath
rootDataPath = "_DATA"
engineDataPath :: Engine a -> IO.FilePath
engineDataPath engine =
FP.joinPath [ rootDataPath, validAddr ]
where
rawAddr = show $ address $ config engine
noColonAddr = map ( \ch -> if ch == ':' then '_' else ch ) rawAddr
validAddr = FP.makeValid noColonAddr
createDataDir :: IO.FilePath -> EngineM b ()
createDataDir path = do
dirExists <- M.liftIO $ DIR.doesDirectoryExist path
M.unless dirExists $ do
isFile <- M.liftIO $ DIR.doesFileExist path
if isFile then
throwEngineError $ EngineError $ path ++ " exists but is not a directory, so it cannot be used to store external collections."
else
M.liftIO $ DIR.createDirectory path
initDataDir :: EngineM b ()
initDataDir = do
createDataDir rootDataPath
engine <- M.ask
createDataDir $ engineDataPath engine
-- Put these into _DATA/peerID/collection_name
generateCollectionFilename :: EngineM b Identifier
generateCollectionFilename = do
engine <- M.ask
-- TODO move creating the data dir into atInit
initDataDir
let counter = collectionCount engine
number <- M.liftIO $ readMVar counter
let filename = "collection_" ++ (show number)
M.liftIO $ modifyMVar_ counter $ \c -> return (c + 1)
return $ FP.joinPath [engineDataPath engine, filename]
emptyFile :: () -> EngineM a (FileDataspace a)
emptyFile _ = do
file_id <- generateCollectionFilename
_ <- openCollectionFile file_id "w"
close file_id
return $ FileDataspace file_id
openCollectionFile :: String -> String -> EngineM a String
openCollectionFile name mode =
do
engine <- M.ask
let wd = valueFormat engine
openFile name name wd Nothing mode
return name
copyFile :: FileDataspace v -> EngineM v (FileDataspace v)
copyFile old_id = do
new_id <- generateCollectionFilename
_ <- openCollectionFile new_id "w"
foldFile id (\_ val -> do
doWrite new_id val -- TODO hasWrite
return ()
) () old_id
close new_id
return $ FileDataspace new_id
initialFile :: (Monad m) => (forall c. EngineM b c -> m c) -> [b] -> m (FileDataspace b)
initialFile liftM vals = do
new_id <- liftM generateCollectionFilename
_ <- liftM $ openCollectionFile new_id "w"
M.foldM (\_ val -> do
liftM $ doWrite new_id val -- TODO hasWrite
return ()
) () vals
liftM $ close new_id
return $ FileDataspace new_id
peekFile :: (Monad m) => (forall c. EngineM b c -> m c) -> FileDataspace b -> m (Maybe b)
peekFile liftM (FileDataspace file_id) = do
_ <- liftM $ openCollectionFile file_id "r"
can_read <- liftM $ hasRead file_id
result <-
case can_read of
Nothing -> return Nothing
Just False -> return Nothing
Just True ->
liftM $ doRead file_id
liftM $ close file_id
return result
-- Pass a lift into these functions, so that "inner loop" can be in
-- some Monad m. foldDS etc. can know which lift to use, since they
-- are in the instance of the typeclass.
foldFile :: forall (m :: * -> *) a b.
Monad m =>
(forall c. EngineM b c -> m c)
-> (a -> b -> m a) -> a -> FileDataspace b -> m a
foldFile liftM accumulation initial_accumulator file_ds@(FileDataspace file_id) = do
_ <- liftM $ openCollectionFile file_id "r"
result <- foldOpenFile liftM accumulation initial_accumulator file_ds
liftM $ close file_id
return result
foldOpenFile :: forall (m :: * -> *) a b.
Monad m =>
(forall c. EngineM b c -> m c)
-> (a -> b -> m a) -> a -> FileDataspace b -> m a
foldOpenFile liftM accumulation initial_accumulator file_ds@(FileDataspace file_id) =
do
file_over <- liftM $ hasRead file_id
case file_over of
Nothing -> return initial_accumulator -- Hiding an error...
Just False -> return initial_accumulator
Just True ->
do
cur_val <- liftM $ doRead file_id
case cur_val of
Nothing -> return initial_accumulator
Just val -> do
new_acc <- accumulation initial_accumulator val
foldOpenFile liftM accumulation new_acc file_ds
mapFile :: (Monad m) => (forall c. EngineM b c -> m c) -> (b -> m b) -> FileDataspace b -> m (FileDataspace b)
mapFile liftM function file_ds = do
-- Map over a copy of the dataspace, instead of the original
-- This way, any modifications to the dataspace that occur inside the
-- body of the map do not affect the length of iteration, but
-- are in effect upon exiting the map
tmp_ds <- liftM $ copyFile file_ds
new_id <- liftM generateCollectionFilename
_ <- liftM $ openCollectionFile new_id "w"
foldFile liftM (inner_func new_id) () tmp_ds
liftM $ close new_id
return $ FileDataspace new_id
where
--The typechecker didn't think the b here and the b in mapFile
--were the same b, so it didn't typecheck. Letting it infer
--everything lets the typechecker figure it out
--inner_func :: [Char] -> () -> b -> EngineM b ()
inner_func new_id _ v = do
new_val <- function v
liftM $ doWrite new_id new_val
return ()
mapFile_ :: (Monad m) => (forall c. EngineM b c -> m c) -> (b -> m a) -> FileDataspace b -> m ()
mapFile_ liftM function file_id = do
tmp_ds <- liftM $ copyFile file_id
foldFile liftM inner_func () tmp_ds
where
--inner_func :: () -> b -> EngineM b ()
inner_func _ v = do
_ <- function v
return ()
filterFile :: (Monad m) => (forall c. EngineM b c -> m c) -> (b -> m Bool) -> FileDataspace b -> m (FileDataspace b)
filterFile liftM predicate old_id = do
new_id <- liftM generateCollectionFilename
tmp_ds <- liftM $ copyFile old_id
_ <- liftM $ openCollectionFile new_id "w"
foldFile liftM (inner_func new_id) () tmp_ds
liftM $ close new_id
return $ FileDataspace new_id
where
--inner_func :: [Char] -> () -> Value -> EngineM b ()
inner_func new_id _ v = do
include <- predicate v
if include then
liftM $ doWrite new_id v
else
return ()
insertFile :: (Monad m) => (forall c. EngineM b c -> m c) -> FileDataspace b -> b -> m (FileDataspace b)
insertFile liftM file_ds@(FileDataspace file_id) v = do
_ <- liftM $ openCollectionFile file_id "a"
-- can_write <- hasWrite ext_id -- TODO handle errors here
liftM $ doWrite file_id v
liftM $ close file_id
return file_ds
deleteFile :: (Monad m, Eq b) => (forall c. EngineM b c -> m c) -> b -> FileDataspace b -> m (FileDataspace b)
deleteFile liftM v file_ds@(FileDataspace file_id) = do
deleted_id <- liftM generateCollectionFilename
_ <- liftM $ openCollectionFile deleted_id "w"
_ <- foldFile liftM (\truth val -> do
if truth == False && val == v
then return True
else do
liftM $ doWrite deleted_id val --TODO error check
return truth
) False file_ds
liftM $ close deleted_id
liftM $ M.liftIO $ DIR.renameFile deleted_id file_id -- What's with the double lift?
return file_ds
updateFile :: (Monad m, Eq b) => (forall c. EngineM b c -> m c) -> b -> b -> FileDataspace b -> m (FileDataspace b)
updateFile liftM v v' file_ds@(FileDataspace file_id) = do
new_id <- liftM $ generateCollectionFilename >>= flip openCollectionFile "w"
did_update <-
foldFile liftM (\truth val -> do
if truth == False && val == v
then do
liftM $ doWrite new_id v'
return True
else do
liftM $ doWrite new_id val --TODO error check
return truth
) False file_ds
M.unless did_update $ liftM $ doWrite new_id v'
liftM $ close new_id
liftM $ M.liftIO $ DIR.renameFile new_id file_id -- Double lift?
return file_ds
combineFile :: (Monad m) => (forall c. EngineM b c -> m c) -> (FileDataspace b) -> (FileDataspace b) -> m (FileDataspace b)
combineFile liftM self values = do
(FileDataspace new_id) <- liftM $ Language.K3.Runtime.FileDataspace.copyFile self
_ <- liftM $ openCollectionFile new_id "a"
foldFile liftM (\_ v -> do
liftM $ doWrite new_id v
return ()
) () values
liftM $ close new_id
return $ FileDataspace new_id
splitFile :: (Monad m) => (forall c. EngineM b c -> m c) -> FileDataspace b -> m (FileDataspace b, FileDataspace b)
splitFile liftM self = do
left <- liftM $ generateCollectionFilename
right <- liftM $ generateCollectionFilename
_ <- liftM $ openCollectionFile left "w"
_ <- liftM $ openCollectionFile right "w"
_ <- foldFile liftM (\file cur_val -> do
liftM $ doWrite file cur_val
return ( if file == left then right else left )
) left self
liftM $ close left
liftM $ close right
return (FileDataspace left, FileDataspace right)
sortFile :: (Monad m) => (forall c. EngineM b c -> m c) -> (b -> b -> m Ordering) -> FileDataspace b -> m (FileDataspace b)
sortFile liftM sortF old_id = do
-- First phase: partition into sorted runs
(_, remainder_v, some_runs) <- foldFile liftM partition_runs (0,[],[]) old_id
remainder_id <- sorted_run remainder_v
let runs = remainder_id:some_runs
case runs of
[] -> liftM $ throwEngineError $ EngineError $ "Invalid sortFile did not create any runs."
[x] -> return $ FileDataspace x
_ -> do
merged_opt <- merge_runs runs -- Second phase: merge runs.
case merged_opt of
Just merged_id -> return $ FileDataspace merged_id
Nothing -> liftM $ throwEngineError $ EngineError $ "Invalid sortFile did not merge any runs."
where
block_size = 1000000 :: Int
partition_runs (cnt, v_acc, id_acc) v
| cnt < block_size = return (cnt+1, v:v_acc, id_acc)
| otherwise = do
-- Write out a sorted run.
new_id <- sorted_run v_acc
return (0, [v], new_id:id_acc)
sorted_run l = do
-- Write out a sorted run.
new_id <- liftM generateCollectionFilename
_ <- liftM $ openCollectionFile new_id "w"
sorted_l <- sort_in_mem sortF l
mapM_ (\v -> liftM $ doWrite new_id v) sorted_l
liftM $ close new_id
return new_id
-- Balanced binary tree of merge operations.
merge_runs [] = return Nothing
merge_runs [x] = return $ Just x
merge_runs ls = do
let (a,b) = splitAt (length ls `quot` 2) ls
a_opt <- merge_runs a
b_opt <- merge_runs b
merge_pair a_opt b_opt
-- For now, just read in the two runs and sort in memory.
-- TODO: ideally we want to step through the two runs and merge.
merge_pair Nothing Nothing = return Nothing
merge_pair (Just a_id) Nothing = return $ Just a_id
merge_pair Nothing (Just b_id) = return $ Just b_id
merge_pair (Just a_id) (Just b_id) =
do
a_vals <- foldFile liftM (\acc v -> return $ acc++[v]) [] $ FileDataspace a_id
b_vals <- foldFile liftM (\acc v -> return $ acc++[v]) [] $ FileDataspace b_id
sorted_vals <- sort_in_mem sortF $ a_vals ++ b_vals
return . Just =<< sorted_run sorted_vals
-- | Sort an in memory list of values. For now, we use the same implementation as the InMemory dataspace.
-- Since the comparator can have side effects, we must write our own sorting algorithm.
-- TODO: improve performance.
sort_in_mem _ [] = return []
sort_in_mem _ [x] = return [x]
sort_in_mem cmpF ls = do
let (a, b) = splitAt (length ls `quot` 2) ls
a' <- sort_in_mem cmpF a
b' <- sort_in_mem cmpF b
merge a' b'
where merge [] bs = return bs
merge as [] = return as
merge (a:as) (b:bs) = cmpF a b >>= \case
LT -> return . (a:) =<< merge as (b:bs)
_ -> return . (b:) =<< merge (a:as) bs
|
DaMSL/K3
|
src/Language/K3/Runtime/FileDataspace.hs
|
apache-2.0
| 12,552
| 0
| 18
| 3,111
| 4,040
| 1,964
| 2,076
| 281
| 14
|
-- | The Console process has two main purposes. It is a telnet-like
-- interface with the user and it is our first simple logging device
-- for what happens inside the system.
{-# LANGUAGE ScopedTypeVariables #-}
module Process.Console
( start
)
where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad.Reader
import Prelude hiding (catch)
import Process
import qualified Process.Status as St
import Supervisor
data Cmd = Quit -- ^ Quit the program
| Show -- ^ Show current state
| Help -- ^ Print Help message
| Unknown String -- ^ Unknown command
deriving (Eq, Show)
type CmdChannel = TChan Cmd
data CF = CF { cmdCh :: CmdChannel
, wrtCh :: TChan String }
instance Logging CF where
logName _ = "Process.Console"
-- | Start the logging process and return a channel to it. Sending on this
-- Channel means writing stuff out on stdOut
start :: TMVar () -> St.StatusChannel -> SupervisorChannel -> IO ThreadId
start waitC statusC supC = do
cmdC <- readerP -- We shouldn't be doing this in the long run
wrtC <- writerP
spawnP (CF cmdC wrtC) () ({-# SCC "Console" #-}
catchP eventLoop (defaultStopHandler supC))
where
eventLoop = do
c <- asks cmdCh
o <- asks wrtCh
m <- liftIO . atomically $ readTChan c
case m of
Quit -> liftIO . atomically $ putTMVar waitC ()
Help -> liftIO . atomically $ writeTChan o helpMessage
(Unknown n) -> liftIO . atomically $ writeTChan o $ "Uknown command: " ++ n
Show -> do
v <- liftIO newEmptyTMVarIO
liftIO . atomically $ writeTChan statusC (St.RequestAllTorrents v)
sts <- liftIO . atomically $ takeTMVar v
liftIO . atomically $ writeTChan o (show sts)
eventLoop
helpMessage :: String
helpMessage = concat
[ "Command Help:\n"
, "\n"
, " help - Show this help\n"
, " quit - Quit the program\n"
, " show - Show the current downloading status\n"
]
writerP :: IO (TChan String)
writerP = do wrt <- newTChanIO
_ <- forkIO $ lp wrt
return wrt
where lp wCh = {-# SCC "writerP" #-}
forever (do m <- atomically $ readTChan wCh
putStrLn m)
readerP :: IO CmdChannel
readerP = do cmd <- newTChanIO
_ <- forkIO $ lp cmd
return cmd
where lp cmd = {-# SCC "readerP" #-} forever $
do l <- getLine
atomically $ writeTChan cmd
(case l of
"help" -> Help
"quit" -> Quit
"show" -> Show
c -> Unknown c)
|
beni55/combinatorrent
|
src/Process/Console.hs
|
bsd-2-clause
| 2,785
| 0
| 18
| 952
| 653
| 331
| 322
| 66
| 4
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
-- | Extract Haskell values from running STG programs.
module Stg.Marshal.FromStg (
FromStg(..),
FromStgError(..),
) where
import Data.Bifunctor
import Stg.Language
import qualified Stg.Machine.Env as Env
import qualified Stg.Machine.Heap as H
import Stg.Machine.Types
import Stg.Util
-- | Look up the value of a global variable.
--
-- Instances of this class should have a corresponding 'ToStg' instance to
-- inject a value into the program, with the two being inverse to each other (up
-- to forcing the generated thunks).
class FromStg value where
-- | Retrieve the value of a global variable.
fromStg
:: StgState
-> Var -- ^ Name of the global, e.g. @main@
-> Either FromStgError value
fromStg stgState = globalVal stgState (\case
PrimInt{} -> Left TypeMismatch
Addr addr -> fromStgAddr stgState addr )
-- | Retrieve the value of a heap address.
fromStgAddr
:: StgState
-> MemAddr
-> Either FromStgError value
-- | Used only for looking up primitive integers.
fromStgPrim
:: Integer
-> Either FromStgError value
fromStgPrim _ = Left TypeMismatch
{-# MINIMAL fromStgAddr #-}
-- | Classifies the different errors that can happen when extracting a value
-- from an STG state.
data FromStgError =
TypeMismatch -- ^ e.g. asking for an @Int#@ at an address
-- that contains a @Cons@
| IsWrongLambdaType LambdaType -- ^ Tried retrieving a non-constructor
| IsBlackhole -- ^ Tried retrieving a black hole
| BadArity -- ^ e.g. @Cons x y z@
| NotFound NotInScope -- ^ An unsuccessful variable lookup
| AddrNotOnHeap
| NoConstructorMatch -- ^ None of the given alternatives matched the given
-- constructor, e.g. when trying to receive a 'Left'
-- as a 'Just'
deriving (Eq, Ord, Show)
-- | Look up the global of a variable and handle the result.
--
-- Slighly bent version of 'Env.globalVal' to fit the types in this module
-- better.
globalVal
:: StgState
-> (Value -> Either FromStgError value) -- ^ What to do with the value if found
-> Var -- ^ Name of the global value to inspect
-> Either FromStgError value
globalVal stgState f var = case Env.globalVal (stgGlobals stgState) (AtomVar var) of
Failure _ -> Left (NotFound (NotInScope [var]))
Success v -> f v
-- | Create a local environment.
--
-- Slighly bent version of 'Env.makeLocals' to fit the types in this module
-- better.
makeLocals :: [Var] -> [Value] -> Locals
makeLocals freeVars freeVals = Env.makeLocals (zipWith Mapping freeVars freeVals)
-- | Look up the value of an 'Atom' in a state, given a local environment.
atomVal
:: FromStg value
=> StgState
-> Locals
-> Atom
-> Either FromStgError value
atomVal stgState locals var = case Env.val locals (stgGlobals stgState) var of
Failure notInScope -> Left (NotFound notInScope)
Success (Addr addr) -> fromStgAddr stgState addr
Success (PrimInt i) -> fromStgPrim i
-- | Inspect whether a closure at a certain memory address matches the desired
-- criteria.
inspect
:: StgState
-> (Closure -> [Either (Maybe FromStgError) value])
-- ^ List of possible matches, e.g. Nil and Cons in the list case.
-- See e.g. @matchCon2@ in order to implement these matchers.
-> MemAddr
-> Either FromStgError value
inspect stgState inspectClosure addr = case H.lookup addr (stgHeap stgState) of
Nothing -> Left AddrNotOnHeap
Just heapObject -> case heapObject of
Blackhole{} -> Left IsBlackhole
HClosure closure -> firstMatch (inspectClosure closure)
where
firstMatch :: [Either (Maybe FromStgError) b] -> Either FromStgError b
firstMatch (Right r : _) = Right r
firstMatch (Left Nothing : rest) = firstMatch rest
firstMatch (Left (Just err) : _) = Left err
firstMatch [] = Left NoConstructorMatch
instance FromStg () where
fromStgAddr stgState = inspect stgState (\closure ->
[matchCon0 "Unit" closure])
instance FromStg Bool where
fromStgAddr stgState = inspect stgState (\closure ->
[ True <$ matchCon0 "True" closure
, False <$ matchCon0 "False" closure ])
-- | Works for both boxed (@Int\# 1\#@) and unboxed (@1#@) integers.
instance FromStg Integer where
fromStg stgState var = case Env.globalVal (stgGlobals stgState) (AtomVar var) of
Failure _ -> Left (NotFound (NotInScope [var]))
Success val -> case val of
PrimInt i -> Right i
Addr addr -> fromStgAddr stgState addr
fromStgAddr stgState = inspect stgState (\closure ->
[ matchCon1 "Int#" closure >>= \(x, locals) ->
liftToMatcher (atomVal stgState locals x) ])
fromStgPrim i = Right i
instance (FromStg a, FromStg b) => FromStg (a,b) where
fromStgAddr stgState = inspect stgState (\closure ->
[ matchCon2 "Pair" closure >>= \((x,y), locals) ->
(,) <$> liftToMatcher (atomVal stgState locals x)
<*> liftToMatcher (atomVal stgState locals y) ])
instance (FromStg a, FromStg b, FromStg c) => FromStg (a,b,c) where
fromStgAddr stgState = inspect stgState (\closure ->
[ matchCon3 "Triple" closure >>= \((x,y,z), locals) ->
(,,) <$> liftToMatcher (atomVal stgState locals x)
<*> liftToMatcher (atomVal stgState locals y)
<*> liftToMatcher (atomVal stgState locals z) ])
instance (FromStg a, FromStg b, FromStg c, FromStg d) => FromStg (a,b,c,d) where
fromStgAddr stgState = inspect stgState (\closure ->
[ matchCon4 "Quadruple" closure >>= \((x,y,z,w), locals) ->
(,,,) <$> liftToMatcher (atomVal stgState locals x)
<*> liftToMatcher (atomVal stgState locals y)
<*> liftToMatcher (atomVal stgState locals z)
<*> liftToMatcher (atomVal stgState locals w) ])
instance (FromStg a, FromStg b, FromStg c, FromStg d, FromStg e) => FromStg (a,b,c,d,e) where
fromStgAddr stgState = inspect stgState (\closure ->
[ matchCon5 "Quintuple" closure >>= \((x,y,z,w,v), locals) ->
(,,,,) <$> liftToMatcher (atomVal stgState locals x)
<*> liftToMatcher (atomVal stgState locals y)
<*> liftToMatcher (atomVal stgState locals z)
<*> liftToMatcher (atomVal stgState locals w)
<*> liftToMatcher (atomVal stgState locals v) ])
instance FromStg a => FromStg (Maybe a) where
fromStgAddr stgState = inspect stgState (\closure ->
[ Nothing <$ matchCon0 "Nothing" closure
, matchCon1 "Just" closure >>= \(arg, locals) ->
Just <$> liftToMatcher (atomVal stgState locals arg) ])
instance (FromStg a, FromStg b) => FromStg (Either a b) where
fromStgAddr stgState = inspect stgState (\closure ->
[ matchCon1 "Left" closure >>= \(arg, locals) ->
Left <$> liftToMatcher (atomVal stgState locals arg)
, matchCon1 "Right" closure >>= \(arg, locals) ->
Right <$> liftToMatcher (atomVal stgState locals arg) ])
instance FromStg a => FromStg [a] where
fromStgAddr stgState = inspect stgState (\closure ->
[ [] <$ matchCon0 "Nil" closure
, matchCon2 "Cons" closure >>= \((x,xs), locals) ->
(:) <$> liftToMatcher (atomVal stgState locals x)
<*> liftToMatcher (atomVal stgState locals xs) ])
-- | Lift an errable value into a context where the specific error is not
-- necessarily present.
liftToMatcher :: Either e a -> Either (Maybe e) a
liftToMatcher = first Just
-- | Like @matchCon2@, but for nullary 'Constr'uctors.
matchCon0 :: Constr -> Closure -> Either (Maybe FromStgError) ()
matchCon0 _ (Closure lambdaForm _)
| classify lambdaForm == LambdaThunk = Left (Just (IsWrongLambdaType LambdaThunk))
| classify lambdaForm == LambdaFun = Left (Just (IsWrongLambdaType LambdaFun))
matchCon0 wantedCon (Closure (LambdaForm _ _ _ (AppC actualCon args)) _)
| wantedCon == actualCon = case args of
[] -> Right ()
_xs -> Left (Just BadArity)
matchCon0 _ _ = Left Nothing
-- | Like @matchCon2@, but for unary 'Constr'uctors.
matchCon1 :: Constr -> Closure -> Either (Maybe FromStgError) (Atom, Locals)
matchCon1 _ (Closure lambdaForm _)
| classify lambdaForm == LambdaThunk = Left (Just (IsWrongLambdaType LambdaThunk))
| classify lambdaForm == LambdaFun = Left (Just (IsWrongLambdaType LambdaFun))
matchCon1 wantedCon (Closure (LambdaForm freeVars _ _ (AppC actualCon args)) freeVals)
| wantedCon == actualCon = case args of
[x] -> Right (x, makeLocals freeVars freeVals)
_xs -> Left (Just BadArity)
matchCon1 _ _ = Left Nothing
-- | Match a 'Closure' for a binary 'Constr'uctor.
--
-- * If the constructor matches, return its arguments, and the local environment
-- stored in the closure.
-- * If the constructor does not match, return 'Nothing' as error, indicating
-- to the caller that the next matcher should be tried.
-- * If the constructor fails due to a non-recoverable error, such as wrong
-- arity, abort with the corresponding error.
matchCon2 :: Constr -> Closure -> Either (Maybe FromStgError) ((Atom, Atom), Locals)
matchCon2 _ (Closure lambdaForm _)
| classify lambdaForm == LambdaThunk = Left (Just (IsWrongLambdaType LambdaThunk))
| classify lambdaForm == LambdaFun = Left (Just (IsWrongLambdaType LambdaFun))
matchCon2 wantedCon (Closure (LambdaForm freeVars _ _ (AppC actualCon args)) freeVals)
| wantedCon == actualCon = case args of
[x,y] -> Right ((x,y), makeLocals freeVars freeVals)
_xs -> Left (Just BadArity)
matchCon2 _ _ = Left Nothing
-- | Like @matchCon2@, but for ternary 'Constr'uctors.
matchCon3 :: Constr -> Closure -> Either (Maybe FromStgError) ((Atom, Atom, Atom), Locals)
matchCon3 _ (Closure lambdaForm _)
| classify lambdaForm == LambdaThunk = Left (Just (IsWrongLambdaType LambdaThunk))
| classify lambdaForm == LambdaFun = Left (Just (IsWrongLambdaType LambdaFun))
matchCon3 wantedCon (Closure (LambdaForm freeVars _ _ (AppC actualCon args)) freeVals)
| wantedCon == actualCon = case args of
[x,y,z] -> Right ((x,y,z), makeLocals freeVars freeVals)
_xs -> Left (Just BadArity)
matchCon3 _ _ = Left Nothing
-- | Like @matchCon2@, but for 4-ary 'Constr'uctors.
matchCon4 :: Constr -> Closure -> Either (Maybe FromStgError) ((Atom, Atom, Atom, Atom), Locals)
matchCon4 _ (Closure lambdaForm _)
| classify lambdaForm == LambdaThunk = Left (Just (IsWrongLambdaType LambdaThunk))
| classify lambdaForm == LambdaFun = Left (Just (IsWrongLambdaType LambdaFun))
matchCon4 wantedCon (Closure (LambdaForm freeVars _ _ (AppC actualCon args)) freeVals)
| wantedCon == actualCon = case args of
[x,y,z,w] -> Right ((x,y,z,w), makeLocals freeVars freeVals)
_xs -> Left (Just BadArity)
matchCon4 _ _ = Left Nothing
-- | Like @matchCon2@, but for 5-ary 'Constr'uctors.
matchCon5 :: Constr -> Closure -> Either (Maybe FromStgError) ((Atom, Atom, Atom, Atom, Atom), Locals)
matchCon5 _ (Closure lambdaForm _)
| classify lambdaForm == LambdaThunk = Left (Just (IsWrongLambdaType LambdaThunk))
| classify lambdaForm == LambdaFun = Left (Just (IsWrongLambdaType LambdaFun))
matchCon5 wantedCon (Closure (LambdaForm freeVars _ _ (AppC actualCon args)) freeVals)
| wantedCon == actualCon = case args of
[x,y,z,w,v] -> Right ((x,y,z,w,v), makeLocals freeVars freeVals)
_xs -> Left (Just BadArity)
matchCon5 _ _ = Left Nothing
|
quchen/stg
|
src/Stg/Marshal/FromStg.hs
|
bsd-3-clause
| 11,901
| 0
| 19
| 2,884
| 3,431
| 1,768
| 1,663
| 189
| 6
|
module Renderer (UIEvents(..), setup, shutdown, onlyEvery, fps, frameCounter,
onlyEveryN, module Graphics.UI.GLFW, rateLimitHz) where
import Control.Applicative
import Control.Arrow ((***))
import Control.Concurrent (threadDelay)
import Control.Concurrent.MVar
import Control.Monad (when)
import Control.Monad.IO.Class
import Data.IORef (newIORef, readIORef, writeIORef, modifyIORef)
import Graphics.UI.GLFW
import qualified Data.Set as S
import Linear.V2
data UIEvents = UIEvents { keys :: ([(Key,Bool)], S.Set Key)
, mouseButtons :: [(MouseButton,Bool)]
, mousePos :: V2 Int }
-- We provide callback functions to GLFW that buffer keyboard and
-- mouse button presses that the client of 'loop' eventually receives.
-- We track presses and toggle states (in the form of a list of
-- currently depressed keys). The client can decide which is more
-- useful.
type KeyBuffer = MVar ([(Key,Bool)], S.Set Key)
type MouseBuffer = MVar [(MouseButton,Bool)]
type UIBuffer = (KeyBuffer, MouseBuffer)
bufferKey :: KeyBuffer -> Key -> Bool -> IO ()
bufferKey keyBuffer k p = modifyMVar_ keyBuffer (return . (((k,p):)***toggle))
where toggle | p = S.insert k
| otherwise = S.delete k
bufferMB :: MouseBuffer -> MouseButton -> Bool -> IO ()
bufferMB mbBuffer m p = modifyMVar_ mbBuffer (return . ((m,p):))
loop :: MonadIO m => UIBuffer -> MVar Double ->
(a -> Double -> UIEvents -> m b) -> (a -> m ()) -> a -> m b
loop (keyBuffer, mbBuffer) lastTime eventHandler draw = go
where updateKeys = modifyMVar keyBuffer
(\(p,s) -> return (([],s), (p, s)))
go s = do draw s
liftIO swapBuffers
ui <- liftIO $ pollEvents >>
UIEvents <$> updateKeys
<*> swapMVar mbBuffer []
<*> (uncurry V2 <$> getMousePosition)
dt <- liftIO $ do t' <- getTime
dt <- (t' -) <$> takeMVar lastTime
putMVar lastTime t'
return dt
eventHandler s dt ui
setup :: MonadIO m =>
IO ((a -> Double -> UIEvents -> m b) -> (a -> m ()) -> a -> m b)
setup = do _ <- initialize
_ <- openWindow opts
setWindowTitle "PCD Viewer"
kb <- newMVar ([],S.empty)
mb <- newMVar []
setKeyCallback $ bufferKey kb
setMouseButtonCallback $ bufferMB mb
setWindowBufferSwapInterval 0
loop (kb,mb) <$> (getTime >>= newMVar)
where opts = defaultDisplayOptions { displayOptions_width = 512 -- 640
, displayOptions_height = 512 -- 480
, displayOptions_numDepthBits = 24
, displayOptions_refreshRate = Just 100 }
shutdown :: IO ()
shutdown = terminate
-- Some utility functions for people using a renderer
-- |@onlyEveryN n@: Return a function that only runs the given action
-- every @n@ calls.
onlyEveryN :: Int -> IO(IO () -> IO ())
onlyEveryN n = do tmp <- newIORef 0
return $ \m -> do old <- readIORef tmp
if old == n
then m >> writeIORef tmp 0
else writeIORef tmp (old+1)
-- |@onlyEvery t@: Return a function that only runs the given action
-- every @t@ seconds.
onlyEvery :: Double -> IO (IO () -> IO ())
onlyEvery dt = do tmp <- getTime >>= newIORef
return $ \m -> do t <- getTime
dt' <- (t -) <$> readIORef tmp
when (dt' >= dt)
(writeIORef tmp t >> m)
-- |Returns an action that sleeps the calling thread until at least
-- the specified inter-call time span (in seconds) has lapsed.
rateLimit :: Double -> IO (IO ())
rateLimit period = do prev <- getTime >>= newIORef
return $ do t <- readIORef prev
t' <- getTime
writeIORef prev t'
let dt = floor $ 1000000 * (t' - t)
when (dt < period')
(threadDelay (period' - dt))
where period' = floor $ period * 1000000
-- Re. the above: GLFW-b's 'sleep' function doesn't seem to work?
-- |Returns an action that sleeps the calling thread in order to
-- prevent calls to the action from occurring at higher than the given
-- maximum rate (in Hz).
rateLimitHz :: Double -> IO (IO ())
rateLimitHz = rateLimit . (1 /)
strictInc :: Int -> Int
strictInc n = n `seq` n + 1
-- |Returns two actions: one to increment a frame count, and a second
-- to get the current frame count and reset that count to zero.
frameCounter :: IO (IO (), IO Int)
frameCounter = do tmp <- newIORef 0
let getCount = do c <- readIORef tmp
writeIORef tmp 0
return c
return (modifyIORef tmp (+ 1), getCount)
fps :: IO (IO (), IO Double)
fps = do startTime <- getTime >>= newIORef
frameCount <- newIORef 0
let getRate = do t <- getTime
dt <- (t -) <$> readIORef startTime
n <- readIORef frameCount
writeIORef frameCount 0
writeIORef startTime t
return $ fromIntegral n / dt
return (modifyIORef frameCount strictInc, getRate)
|
acowley/PcdViewer
|
src/Renderer.hs
|
bsd-3-clause
| 5,763
| 0
| 15
| 2,155
| 1,547
| 801
| 746
| 98
| 2
|
{-@ LIQUID "--real" @-}
{-# LANGUAGE CPP #-}
#define DISCOUNT_PERCENTAGE 2
#define BOOK_THRESHOLD 2
module Books where
calculateDiscount' :: Customer -> Int -> Int
---------------------------------------------------------------------------------------
-- 1. Define: Types of customers
---------------------------------------------------------------------------------------
data Customer = Vip | Reg deriving (Eq)
---------------------------------------------------------------------------------------
-- 2. Define: Discountable Customers and Discounts
---------------------------------------------------------------------------------------
{-@ inline customerGetsDiscount @-}
customerGetsDiscount :: Customer -> Int -> Bool
customerGetsDiscount c i = c == Vip && i >= BOOK_THRESHOLD
{-@ inline discount @-}
discount :: Int -> Int
discount bookCount = (bookCount - BOOK_THRESHOLD) * DISCOUNT_PERCENTAGE
{-@ type Discount i = {v:Int | v == discount i} @-}
---------------------------------------------------------------------------------------
-- 3. Policy: Only compute discounts for discountable customers
---------------------------------------------------------------------------------------
{-@ calculateDiscount' :: c:Customer -> i:{Int | customerGetsDiscount c i} -> Discount i @-}
calculateDiscount' c i = discount i
---------------------------------------------------------------------------------------
-- 4. Implement: Code to compute discounts, if suitable, is accepted
---------------------------------------------------------------------------------------
{-@ calculateDiscount :: Int -> Nat -> Nat @-}
calculateDiscount userId bookCount
| getsDiscount = calculateDiscount' c bookCount
| otherwise = 0
where
getsDiscount = customerGetsDiscount c bookCount
c = customerType userId
---------------------------------------------------------------------------------------
-- 5. Buggy Implementation, with wrong check, is rejected
---------------------------------------------------------------------------------------
{-@ misCalculateDiscount :: Int -> Nat -> Nat @-}
misCalculateDiscount userId bookCount
| getsDiscount = calculateDiscount' c bookCount
| otherwise = 0
where
getsDiscount = c == Vip
c = customerType userId
customerType :: Int -> Customer
customerType = undefined
|
abakst/liquidhaskell
|
tests/neg/Books.hs
|
bsd-3-clause
| 2,371
| 0
| 7
| 309
| 248
| 138
| 110
| 21
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL
-- Copyright : (c) Sven Panne 2002-2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- A Haskell binding for OpenGL, the industry\'s most widely used and
-- supported 2D and 3D graphics API.
--
-----------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL (
-- * OpenGL Fundamentals
module Graphics.Rendering.OpenGL.Raw.Types,
module Graphics.Rendering.OpenGL.GL.FlushFinish,
module Graphics.Rendering.OpenGL.GL.ObjectName,
-- * Event Model
module Graphics.Rendering.OpenGL.GL.SyncObjects,
module Graphics.Rendering.OpenGL.GL.QueryObjects,
-- * Vertex Specification and Drawing Commands
module Graphics.Rendering.OpenGL.GL.BeginEnd,
module Graphics.Rendering.OpenGL.GL.Rectangles,
module Graphics.Rendering.OpenGL.GL.ConditionalRendering,
-- * OpenGL Operation
module Graphics.Rendering.OpenGL.GL.VertexSpec,
module Graphics.Rendering.OpenGL.GL.VertexArrays,
module Graphics.Rendering.OpenGL.GL.VertexArrayObjects,
module Graphics.Rendering.OpenGL.GL.BufferObjects,
module Graphics.Rendering.OpenGL.GL.CoordTrans,
module Graphics.Rendering.OpenGL.GL.Clipping,
module Graphics.Rendering.OpenGL.GL.RasterPos,
module Graphics.Rendering.OpenGL.GL.Colors,
module Graphics.Rendering.OpenGL.GL.Shaders,
-- * Rasterization
module Graphics.Rendering.OpenGL.GL.Antialiasing,
module Graphics.Rendering.OpenGL.GL.FramebufferObjects,
module Graphics.Rendering.OpenGL.GL.Points,
module Graphics.Rendering.OpenGL.GL.LineSegments,
module Graphics.Rendering.OpenGL.GL.Polygons,
module Graphics.Rendering.OpenGL.GL.PixelRectangles,
module Graphics.Rendering.OpenGL.GL.Bitmaps,
module Graphics.Rendering.OpenGL.GL.Texturing,
module Graphics.Rendering.OpenGL.GL.ColorSum,
module Graphics.Rendering.OpenGL.GL.Fog,
-- * Per-Fragment Operations and the Framebuffer
module Graphics.Rendering.OpenGL.GL.PerFragment,
module Graphics.Rendering.OpenGL.GL.Framebuffer,
module Graphics.Rendering.OpenGL.GL.ReadCopyPixels,
-- * Special Functions
module Graphics.Rendering.OpenGL.GL.Evaluators,
module Graphics.Rendering.OpenGL.GL.Selection,
module Graphics.Rendering.OpenGL.GL.Feedback,
module Graphics.Rendering.OpenGL.GL.DisplayLists,
module Graphics.Rendering.OpenGL.GL.Hints,
module Graphics.Rendering.OpenGL.GL.PixellikeObject,
module Graphics.Rendering.OpenGL.GL.TransformFeedback,
-- * State and State Requests
module Graphics.Rendering.OpenGL.GL.StateVar,
module Graphics.Rendering.OpenGL.GL.Tensor,
module Graphics.Rendering.OpenGL.GL.StringQueries,
module Graphics.Rendering.OpenGL.GL.SavingState
) where
import Graphics.Rendering.OpenGL.Raw.Types
import Graphics.Rendering.OpenGL.GL.FlushFinish
import Graphics.Rendering.OpenGL.GL.ObjectName
import Graphics.Rendering.OpenGL.GL.SyncObjects
import Graphics.Rendering.OpenGL.GL.QueryObjects
import Graphics.Rendering.OpenGL.GL.BeginEnd
import Graphics.Rendering.OpenGL.GL.Rectangles
import Graphics.Rendering.OpenGL.GL.ConditionalRendering
import Graphics.Rendering.OpenGL.GL.VertexSpec
import Graphics.Rendering.OpenGL.GL.VertexArrays
import Graphics.Rendering.OpenGL.GL.VertexArrayObjects
import Graphics.Rendering.OpenGL.GL.BufferObjects
import Graphics.Rendering.OpenGL.GL.CoordTrans
import Graphics.Rendering.OpenGL.GL.Clipping
import Graphics.Rendering.OpenGL.GL.RasterPos
import Graphics.Rendering.OpenGL.GL.Colors
import Graphics.Rendering.OpenGL.GL.Shaders
import Graphics.Rendering.OpenGL.GL.Antialiasing
import Graphics.Rendering.OpenGL.GL.FramebufferObjects
import Graphics.Rendering.OpenGL.GL.Points
import Graphics.Rendering.OpenGL.GL.LineSegments
import Graphics.Rendering.OpenGL.GL.Polygons
import Graphics.Rendering.OpenGL.GL.PixelRectangles
import Graphics.Rendering.OpenGL.GL.Bitmaps
import Graphics.Rendering.OpenGL.GL.Texturing
import Graphics.Rendering.OpenGL.GL.ColorSum
import Graphics.Rendering.OpenGL.GL.Fog
import Graphics.Rendering.OpenGL.GL.PerFragment
import Graphics.Rendering.OpenGL.GL.Framebuffer
import Graphics.Rendering.OpenGL.GL.ReadCopyPixels
import Graphics.Rendering.OpenGL.GL.Evaluators
import Graphics.Rendering.OpenGL.GL.Selection
import Graphics.Rendering.OpenGL.GL.Feedback
import Graphics.Rendering.OpenGL.GL.DisplayLists
import Graphics.Rendering.OpenGL.GL.Hints
import Graphics.Rendering.OpenGL.GL.PixellikeObject
import Graphics.Rendering.OpenGL.GL.TransformFeedback
import Graphics.Rendering.OpenGL.GL.StateVar
import Graphics.Rendering.OpenGL.GL.Tensor
import Graphics.Rendering.OpenGL.GL.StringQueries
import Graphics.Rendering.OpenGL.GL.SavingState
|
IreneKnapp/direct-opengl
|
Graphics/Rendering/OpenGL/GL.hs
|
bsd-3-clause
| 4,866
| 0
| 5
| 446
| 729
| 562
| 167
| 83
| 0
|
{-# LANGUAGE BangPatterns #-}
-- | This module defines a type for mutable, integer-valued counters.
-- Counters are non-negative, monotonically increasing values and can
-- be used to track e.g. the number of requests served since program
-- start. All operations on counters are thread-safe.
module System.Remote.Counter
(
Counter
, inc
, add
) where
import Data.IORef (atomicModifyIORef)
import Prelude hiding (subtract)
import System.Remote.Counter.Internal
-- | Increase the counter by one.
inc :: Counter -> IO ()
inc (C ref) = do
!_ <- atomicModifyIORef ref $ \ n -> let n' = n + 1 in (n', n')
return ()
-- | Increase the counter by the given amount.
add :: Counter -> Int -> IO ()
add (C ref) i = do
!_ <- atomicModifyIORef ref $ \ n -> let n' = n + i in (n', n')
return ()
|
fpco/ekg
|
System/Remote/Counter.hs
|
bsd-3-clause
| 824
| 0
| 14
| 186
| 211
| 113
| 98
| 17
| 1
|
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[PrelNames]{Definitions of prelude modules and names}
Nota Bene: all Names defined in here should come from the base package
- ModuleNames for prelude modules,
e.g. pREL_BASE_Name :: ModuleName
- Modules for prelude modules
e.g. pREL_Base :: Module
- Uniques for Ids, DataCons, TyCons and Classes that the compiler
"knows about" in some way
e.g. intTyConKey :: Unique
minusClassOpKey :: Unique
- Names for Ids, DataCons, TyCons and Classes that the compiler
"knows about" in some way
e.g. intTyConName :: Name
minusName :: Name
One of these Names contains
(a) the module and occurrence name of the thing
(b) its Unique
The may way the compiler "knows about" one of these things is
where the type checker or desugarer needs to look it up. For
example, when desugaring list comprehensions the desugarer
needs to conjure up 'foldr'. It does this by looking up
foldrName in the environment.
- RdrNames for Ids, DataCons etc that the compiler may emit into
generated code (e.g. for deriving). It's not necessary to know
the uniques for these guys, only their names
Note [Known-key names]
~~~~~~~~~~~~~~~~~~~~~~
It is *very* important that the compiler gives wired-in things and
things with "known-key" names the correct Uniques wherever they
occur. We have to be careful about this in exactly two places:
1. When we parse some source code, renaming the AST better yield an
AST whose Names have the correct uniques
2. When we read an interface file, the read-in gubbins better have
the right uniques
This is accomplished through a combination of mechanisms:
1. When parsing source code, the RdrName-decorated AST has some
RdrNames which are Exact. These are wired-in RdrNames where the
we could directly tell from the parsed syntax what Name to
use. For example, when we parse a [] in a type we can just insert
an Exact RdrName Name with the listTyConKey.
Currently, I believe this is just an optimisation: it would be
equally valid to just output Orig RdrNames that correctly record
the module etc we expect the final Name to come from. However,
were we to eliminate isBuiltInOcc_maybe it would become essential
(see point 3).
2. The knownKeyNames (which consist of the basicKnownKeyNames from
the module, and those names reachable via the wired-in stuff from
TysWiredIn) are used to initialise the "OrigNameCache" in
IfaceEnv. This initialization ensures that when the type checker
or renamer (both of which use IfaceEnv) look up an original name
(i.e. a pair of a Module and an OccName) for a known-key name
they get the correct Unique.
This is the most important mechanism for ensuring that known-key
stuff gets the right Unique, and is why it is so important to
place your known-key names in the appropriate lists.
3. For "infinite families" of known-key names (i.e. tuples), we have
to be extra careful. Because there are an infinite number of
these things, we cannot add them to the list of known-key names
used to initialise the OrigNameCache. Instead, we have to
rely on never having to look them up in that cache.
This is accomplished through a variety of mechanisms:
a) The parser recognises them specially and generates an
Exact Name (hence not looked up in the orig-name cache)
b) The known infinite families of names are specially
serialised by BinIface.putName, with that special treatment
detected when we read back to ensure that we get back to the
correct uniques.
Most of the infinite families cannot occur in source code,
so mechanisms (a,b) sufficies to ensure that they always have
the right Unique. In particular, implicit param TyCon names,
constraint tuples and Any TyCons cannot be mentioned by the
user.
c) IfaceEnv.lookupOrigNameCache uses isBuiltInOcc_maybe to map
built-in syntax directly onto the corresponding name, rather
than trying to find it in the original-name cache.
See also Note [Built-in syntax and the OrigNameCache]
-}
{-# LANGUAGE CPP #-}
module PrelNames (
Unique, Uniquable(..), hasKey, -- Re-exported for convenience
-----------------------------------------------------------
module PrelNames, -- A huge bunch of (a) Names, e.g. intTyConName
-- (b) Uniques e.g. intTyConKey
-- (c) Groups of classes and types
-- (d) miscellaneous things
-- So many that we export them all
) where
#include "HsVersions.h"
import Module
import OccName
import RdrName
import Unique
import Name
import SrcLoc
import FastString
import Config ( cIntegerLibraryType, IntegerLibrary(..) )
import Panic ( panic )
{-
************************************************************************
* *
allNameStrings
* *
************************************************************************
-}
allNameStrings :: [String]
-- Infinite list of a,b,c...z, aa, ab, ac, ... etc
allNameStrings = [ c:cs | cs <- "" : allNameStrings, c <- ['a'..'z'] ]
{-
************************************************************************
* *
\subsection{Local Names}
* *
************************************************************************
This *local* name is used by the interactive stuff
-}
itName :: Unique -> SrcSpan -> Name
itName uniq loc = mkInternalName uniq (mkOccNameFS varName (fsLit "it")) loc
-- mkUnboundName makes a place-holder Name; it shouldn't be looked at except possibly
-- during compiler debugging.
mkUnboundName :: RdrName -> Name
mkUnboundName rdr_name = mkInternalName unboundKey (rdrNameOcc rdr_name) noSrcSpan
isUnboundName :: Name -> Bool
isUnboundName name = name `hasKey` unboundKey
{-
************************************************************************
* *
\subsection{Known key Names}
* *
************************************************************************
This section tells what the compiler knows about the association of
names with uniques. These ones are the *non* wired-in ones. The
wired in ones are defined in TysWiredIn etc.
The names for DPH can come from one of multiple backend packages. At the point where
'basicKnownKeyNames' is used, we don't know which backend it will be. Hence, we list
the names for multiple backends. That works out fine, although they use the same uniques,
as we are guaranteed to only load one backend; hence, only one of the different names
sharing a unique will be used.
-}
basicKnownKeyNames :: [Name]
basicKnownKeyNames
= genericTyConNames
++ [ -- Type constructors (synonyms especially)
ioTyConName, ioDataConName,
runMainIOName,
rationalTyConName,
stringTyConName,
ratioDataConName,
ratioTyConName,
integerTyConName,
-- Classes. *Must* include:
-- classes that are grabbed by key (e.g., eqClassKey)
-- classes in "Class.standardClassKeys" (quite a few)
eqClassName, -- mentioned, derivable
ordClassName, -- derivable
boundedClassName, -- derivable
numClassName, -- mentioned, numeric
enumClassName, -- derivable
monadClassName,
functorClassName,
realClassName, -- numeric
integralClassName, -- numeric
fractionalClassName, -- numeric
floatingClassName, -- numeric
realFracClassName, -- numeric
realFloatClassName, -- numeric
dataClassName,
isStringClassName,
applicativeClassName,
alternativeClassName,
foldableClassName,
traversableClassName,
-- Typeable
typeableClassName,
typeRepTyConName,
mkTyConName,
mkPolyTyConAppName,
mkAppTyName,
typeLitTypeRepName,
-- Numeric stuff
negateName, minusName, geName, eqName,
-- Conversion functions
fromRationalName, fromIntegerName,
toIntegerName, toRationalName,
fromIntegralName, realToFracName,
-- String stuff
fromStringName,
-- Enum stuff
enumFromName, enumFromThenName,
enumFromThenToName, enumFromToName,
-- Applicative/Alternative stuff
pureAName,
apAName,
-- Monad stuff
thenIOName, bindIOName, returnIOName, failIOName,
failMName, bindMName, thenMName, returnMName,
fmapName,
joinMName,
-- MonadRec stuff
mfixName,
-- Arrow stuff
arrAName, composeAName, firstAName,
appAName, choiceAName, loopAName,
-- Ix stuff
ixClassName,
-- Show stuff
showClassName,
-- Read stuff
readClassName,
-- Stable pointers
newStablePtrName,
-- GHC Extensions
groupWithName,
-- Strings and lists
unpackCStringName,
unpackCStringFoldrName, unpackCStringUtf8Name,
-- Overloaded lists
isListClassName,
fromListName,
fromListNName,
toListName,
-- List operations
concatName, filterName, mapName,
zipName, foldrName, buildName, augmentName, appendName,
-- FFI primitive types that are not wired-in.
stablePtrTyConName, ptrTyConName, funPtrTyConName,
int8TyConName, int16TyConName, int32TyConName, int64TyConName,
word8TyConName, word16TyConName, word32TyConName, word64TyConName,
-- Others
otherwiseIdName, inlineIdName,
eqStringName, assertName, breakpointName, breakpointCondName,
breakpointAutoName, opaqueTyConName,
assertErrorName, runSTRepName,
printName, fstName, sndName,
-- Integer
integerTyConName, mkIntegerName,
integerToWord64Name, integerToInt64Name,
word64ToIntegerName, int64ToIntegerName,
plusIntegerName, timesIntegerName, smallIntegerName,
wordToIntegerName,
integerToWordName, integerToIntName, minusIntegerName,
negateIntegerName, eqIntegerPrimName, neqIntegerPrimName,
absIntegerName, signumIntegerName,
leIntegerPrimName, gtIntegerPrimName, ltIntegerPrimName, geIntegerPrimName,
compareIntegerName, quotRemIntegerName, divModIntegerName,
quotIntegerName, remIntegerName, divIntegerName, modIntegerName,
floatFromIntegerName, doubleFromIntegerName,
encodeFloatIntegerName, encodeDoubleIntegerName,
decodeDoubleIntegerName,
gcdIntegerName, lcmIntegerName,
andIntegerName, orIntegerName, xorIntegerName, complementIntegerName,
shiftLIntegerName, shiftRIntegerName,
-- Float/Double
rationalToFloatName,
rationalToDoubleName,
-- MonadFix
monadFixClassName, mfixName,
-- Other classes
randomClassName, randomGenClassName, monadPlusClassName,
-- Type-level naturals
knownNatClassName, knownSymbolClassName,
-- Implicit parameters
ipClassName,
-- Source locations
callStackDataConName, callStackTyConName,
srcLocDataConName,
-- Annotation type checking
toAnnotationWrapperName
-- The Ordering type
, orderingTyConName, ltDataConName, eqDataConName, gtDataConName
-- The SPEC type for SpecConstr
, specTyConName
-- The Either type
, eitherTyConName, leftDataConName, rightDataConName
-- Plugins
, pluginTyConName
-- Generics
, genClassName, gen1ClassName
, datatypeClassName, constructorClassName, selectorClassName
-- Monad comprehensions
, guardMName
, liftMName
, mzipName
-- GHCi Sandbox
, ghciIoClassName, ghciStepIoMName
-- StaticPtr
, staticPtrTyConName
, staticPtrDataConName, staticPtrInfoDataConName
-- Fingerprint
, fingerprintDataConName
] ++ case cIntegerLibraryType of
IntegerGMP -> [integerSDataConName]
IntegerSimple -> []
genericTyConNames :: [Name]
genericTyConNames = [
v1TyConName, u1TyConName, par1TyConName, rec1TyConName,
k1TyConName, m1TyConName, sumTyConName, prodTyConName,
compTyConName, rTyConName, pTyConName, dTyConName,
cTyConName, sTyConName, rec0TyConName, par0TyConName,
d1TyConName, c1TyConName, s1TyConName, noSelTyConName,
repTyConName, rep1TyConName
]
{-
************************************************************************
* *
\subsection{Module names}
* *
************************************************************************
--MetaHaskell Extension Add a new module here
-}
pRELUDE :: Module
pRELUDE = mkBaseModule_ pRELUDE_NAME
gHC_PRIM, gHC_TYPES, gHC_GENERICS, gHC_MAGIC,
gHC_CLASSES, gHC_BASE, gHC_ENUM, gHC_GHCI, gHC_CSTRING,
gHC_SHOW, gHC_READ, gHC_NUM, gHC_INTEGER_TYPE, gHC_LIST,
gHC_TUPLE, dATA_TUPLE, dATA_EITHER, dATA_STRING, dATA_FOLDABLE, dATA_TRAVERSABLE, dATA_MONOID,
gHC_CONC, gHC_IO, gHC_IO_Exception,
gHC_ST, gHC_ARR, gHC_STABLE, gHC_PTR, gHC_ERR, gHC_REAL,
gHC_FLOAT, gHC_TOP_HANDLER, sYSTEM_IO, dYNAMIC,
tYPEABLE, tYPEABLE_INTERNAL, gENERICS,
rEAD_PREC, lEX, gHC_INT, gHC_WORD, mONAD, mONAD_FIX, mONAD_ZIP,
aRROW, cONTROL_APPLICATIVE, gHC_DESUGAR, rANDOM, gHC_EXTS,
cONTROL_EXCEPTION_BASE, gHC_TYPELITS :: Module
gHC_PRIM = mkPrimModule (fsLit "GHC.Prim") -- Primitive types and values
gHC_TYPES = mkPrimModule (fsLit "GHC.Types")
gHC_MAGIC = mkPrimModule (fsLit "GHC.Magic")
gHC_CSTRING = mkPrimModule (fsLit "GHC.CString")
gHC_CLASSES = mkPrimModule (fsLit "GHC.Classes")
gHC_BASE = mkBaseModule (fsLit "GHC.Base")
gHC_ENUM = mkBaseModule (fsLit "GHC.Enum")
gHC_GHCI = mkBaseModule (fsLit "GHC.GHCi")
gHC_SHOW = mkBaseModule (fsLit "GHC.Show")
gHC_READ = mkBaseModule (fsLit "GHC.Read")
gHC_NUM = mkBaseModule (fsLit "GHC.Num")
gHC_INTEGER_TYPE= mkIntegerModule (fsLit "GHC.Integer.Type")
gHC_LIST = mkBaseModule (fsLit "GHC.List")
gHC_TUPLE = mkPrimModule (fsLit "GHC.Tuple")
dATA_TUPLE = mkBaseModule (fsLit "Data.Tuple")
dATA_EITHER = mkBaseModule (fsLit "Data.Either")
dATA_STRING = mkBaseModule (fsLit "Data.String")
dATA_FOLDABLE = mkBaseModule (fsLit "Data.Foldable")
dATA_TRAVERSABLE= mkBaseModule (fsLit "Data.Traversable")
dATA_MONOID = mkBaseModule (fsLit "Data.Monoid")
gHC_CONC = mkBaseModule (fsLit "GHC.Conc")
gHC_IO = mkBaseModule (fsLit "GHC.IO")
gHC_IO_Exception = mkBaseModule (fsLit "GHC.IO.Exception")
gHC_ST = mkBaseModule (fsLit "GHC.ST")
gHC_ARR = mkBaseModule (fsLit "GHC.Arr")
gHC_STABLE = mkBaseModule (fsLit "GHC.Stable")
gHC_PTR = mkBaseModule (fsLit "GHC.Ptr")
gHC_ERR = mkBaseModule (fsLit "GHC.Err")
gHC_REAL = mkBaseModule (fsLit "GHC.Real")
gHC_FLOAT = mkBaseModule (fsLit "GHC.Float")
gHC_TOP_HANDLER = mkBaseModule (fsLit "GHC.TopHandler")
sYSTEM_IO = mkBaseModule (fsLit "System.IO")
dYNAMIC = mkBaseModule (fsLit "Data.Dynamic")
tYPEABLE = mkBaseModule (fsLit "Data.Typeable")
tYPEABLE_INTERNAL = mkBaseModule (fsLit "Data.Typeable.Internal")
gENERICS = mkBaseModule (fsLit "Data.Data")
rEAD_PREC = mkBaseModule (fsLit "Text.ParserCombinators.ReadPrec")
lEX = mkBaseModule (fsLit "Text.Read.Lex")
gHC_INT = mkBaseModule (fsLit "GHC.Int")
gHC_WORD = mkBaseModule (fsLit "GHC.Word")
mONAD = mkBaseModule (fsLit "Control.Monad")
mONAD_FIX = mkBaseModule (fsLit "Control.Monad.Fix")
mONAD_ZIP = mkBaseModule (fsLit "Control.Monad.Zip")
aRROW = mkBaseModule (fsLit "Control.Arrow")
cONTROL_APPLICATIVE = mkBaseModule (fsLit "Control.Applicative")
gHC_DESUGAR = mkBaseModule (fsLit "GHC.Desugar")
rANDOM = mkBaseModule (fsLit "System.Random")
gHC_EXTS = mkBaseModule (fsLit "GHC.Exts")
cONTROL_EXCEPTION_BASE = mkBaseModule (fsLit "Control.Exception.Base")
gHC_GENERICS = mkBaseModule (fsLit "GHC.Generics")
gHC_TYPELITS = mkBaseModule (fsLit "GHC.TypeLits")
gHC_PARR' :: Module
gHC_PARR' = mkBaseModule (fsLit "GHC.PArr")
gHC_SRCLOC :: Module
gHC_SRCLOC = mkBaseModule (fsLit "GHC.SrcLoc")
gHC_STACK :: Module
gHC_STACK = mkBaseModule (fsLit "GHC.Stack")
gHC_STATICPTR :: Module
gHC_STATICPTR = mkBaseModule (fsLit "GHC.StaticPtr")
gHC_FINGERPRINT_TYPE :: Module
gHC_FINGERPRINT_TYPE = mkBaseModule (fsLit "GHC.Fingerprint.Type")
mAIN, rOOT_MAIN :: Module
mAIN = mkMainModule_ mAIN_NAME
rOOT_MAIN = mkMainModule (fsLit ":Main") -- Root module for initialisation
mkInteractiveModule :: Int -> Module
-- (mkInteractiveMoudule 9) makes module 'interactive:M9'
mkInteractiveModule n = mkModule interactivePackageKey (mkModuleName ("Ghci" ++ show n))
pRELUDE_NAME, mAIN_NAME :: ModuleName
pRELUDE_NAME = mkModuleNameFS (fsLit "Prelude")
mAIN_NAME = mkModuleNameFS (fsLit "Main")
dATA_ARRAY_PARALLEL_NAME, dATA_ARRAY_PARALLEL_PRIM_NAME :: ModuleName
dATA_ARRAY_PARALLEL_NAME = mkModuleNameFS (fsLit "Data.Array.Parallel")
dATA_ARRAY_PARALLEL_PRIM_NAME = mkModuleNameFS (fsLit "Data.Array.Parallel.Prim")
mkPrimModule :: FastString -> Module
mkPrimModule m = mkModule primPackageKey (mkModuleNameFS m)
mkIntegerModule :: FastString -> Module
mkIntegerModule m = mkModule integerPackageKey (mkModuleNameFS m)
mkBaseModule :: FastString -> Module
mkBaseModule m = mkModule basePackageKey (mkModuleNameFS m)
mkBaseModule_ :: ModuleName -> Module
mkBaseModule_ m = mkModule basePackageKey m
mkThisGhcModule :: FastString -> Module
mkThisGhcModule m = mkModule thisGhcPackageKey (mkModuleNameFS m)
mkThisGhcModule_ :: ModuleName -> Module
mkThisGhcModule_ m = mkModule thisGhcPackageKey m
mkMainModule :: FastString -> Module
mkMainModule m = mkModule mainPackageKey (mkModuleNameFS m)
mkMainModule_ :: ModuleName -> Module
mkMainModule_ m = mkModule mainPackageKey m
{-
************************************************************************
* *
RdrNames
* *
************************************************************************
-}
main_RDR_Unqual :: RdrName
main_RDR_Unqual = mkUnqual varName (fsLit "main")
-- We definitely don't want an Orig RdrName, because
-- main might, in principle, be imported into module Main
forall_tv_RDR, dot_tv_RDR :: RdrName
forall_tv_RDR = mkUnqual tvName (fsLit "forall")
dot_tv_RDR = mkUnqual tvName (fsLit ".")
eq_RDR, ge_RDR, ne_RDR, le_RDR, lt_RDR, gt_RDR, compare_RDR,
ltTag_RDR, eqTag_RDR, gtTag_RDR :: RdrName
eq_RDR = nameRdrName eqName
ge_RDR = nameRdrName geName
ne_RDR = varQual_RDR gHC_CLASSES (fsLit "/=")
le_RDR = varQual_RDR gHC_CLASSES (fsLit "<=")
lt_RDR = varQual_RDR gHC_CLASSES (fsLit "<")
gt_RDR = varQual_RDR gHC_CLASSES (fsLit ">")
compare_RDR = varQual_RDR gHC_CLASSES (fsLit "compare")
ltTag_RDR = dataQual_RDR gHC_TYPES (fsLit "LT")
eqTag_RDR = dataQual_RDR gHC_TYPES (fsLit "EQ")
gtTag_RDR = dataQual_RDR gHC_TYPES (fsLit "GT")
eqClass_RDR, numClass_RDR, ordClass_RDR, enumClass_RDR, monadClass_RDR
:: RdrName
eqClass_RDR = nameRdrName eqClassName
numClass_RDR = nameRdrName numClassName
ordClass_RDR = nameRdrName ordClassName
enumClass_RDR = nameRdrName enumClassName
monadClass_RDR = nameRdrName monadClassName
map_RDR, append_RDR :: RdrName
map_RDR = varQual_RDR gHC_BASE (fsLit "map")
append_RDR = varQual_RDR gHC_BASE (fsLit "++")
foldr_RDR, build_RDR, returnM_RDR, bindM_RDR, failM_RDR :: RdrName
foldr_RDR = nameRdrName foldrName
build_RDR = nameRdrName buildName
returnM_RDR = nameRdrName returnMName
bindM_RDR = nameRdrName bindMName
failM_RDR = nameRdrName failMName
left_RDR, right_RDR :: RdrName
left_RDR = nameRdrName leftDataConName
right_RDR = nameRdrName rightDataConName
fromEnum_RDR, toEnum_RDR :: RdrName
fromEnum_RDR = varQual_RDR gHC_ENUM (fsLit "fromEnum")
toEnum_RDR = varQual_RDR gHC_ENUM (fsLit "toEnum")
enumFrom_RDR, enumFromTo_RDR, enumFromThen_RDR, enumFromThenTo_RDR :: RdrName
enumFrom_RDR = nameRdrName enumFromName
enumFromTo_RDR = nameRdrName enumFromToName
enumFromThen_RDR = nameRdrName enumFromThenName
enumFromThenTo_RDR = nameRdrName enumFromThenToName
ratioDataCon_RDR, plusInteger_RDR, timesInteger_RDR :: RdrName
ratioDataCon_RDR = nameRdrName ratioDataConName
plusInteger_RDR = nameRdrName plusIntegerName
timesInteger_RDR = nameRdrName timesIntegerName
ioDataCon_RDR :: RdrName
ioDataCon_RDR = nameRdrName ioDataConName
eqString_RDR, unpackCString_RDR, unpackCStringFoldr_RDR,
unpackCStringUtf8_RDR :: RdrName
eqString_RDR = nameRdrName eqStringName
unpackCString_RDR = nameRdrName unpackCStringName
unpackCStringFoldr_RDR = nameRdrName unpackCStringFoldrName
unpackCStringUtf8_RDR = nameRdrName unpackCStringUtf8Name
newStablePtr_RDR :: RdrName
newStablePtr_RDR = nameRdrName newStablePtrName
bindIO_RDR, returnIO_RDR :: RdrName
bindIO_RDR = nameRdrName bindIOName
returnIO_RDR = nameRdrName returnIOName
fromInteger_RDR, fromRational_RDR, minus_RDR, times_RDR, plus_RDR :: RdrName
fromInteger_RDR = nameRdrName fromIntegerName
fromRational_RDR = nameRdrName fromRationalName
minus_RDR = nameRdrName minusName
times_RDR = varQual_RDR gHC_NUM (fsLit "*")
plus_RDR = varQual_RDR gHC_NUM (fsLit "+")
fromString_RDR :: RdrName
fromString_RDR = nameRdrName fromStringName
fromList_RDR, fromListN_RDR, toList_RDR :: RdrName
fromList_RDR = nameRdrName fromListName
fromListN_RDR = nameRdrName fromListNName
toList_RDR = nameRdrName toListName
compose_RDR :: RdrName
compose_RDR = varQual_RDR gHC_BASE (fsLit ".")
not_RDR, getTag_RDR, succ_RDR, pred_RDR, minBound_RDR, maxBound_RDR,
and_RDR, range_RDR, inRange_RDR, index_RDR,
unsafeIndex_RDR, unsafeRangeSize_RDR :: RdrName
and_RDR = varQual_RDR gHC_CLASSES (fsLit "&&")
not_RDR = varQual_RDR gHC_CLASSES (fsLit "not")
getTag_RDR = varQual_RDR gHC_BASE (fsLit "getTag")
succ_RDR = varQual_RDR gHC_ENUM (fsLit "succ")
pred_RDR = varQual_RDR gHC_ENUM (fsLit "pred")
minBound_RDR = varQual_RDR gHC_ENUM (fsLit "minBound")
maxBound_RDR = varQual_RDR gHC_ENUM (fsLit "maxBound")
range_RDR = varQual_RDR gHC_ARR (fsLit "range")
inRange_RDR = varQual_RDR gHC_ARR (fsLit "inRange")
index_RDR = varQual_RDR gHC_ARR (fsLit "index")
unsafeIndex_RDR = varQual_RDR gHC_ARR (fsLit "unsafeIndex")
unsafeRangeSize_RDR = varQual_RDR gHC_ARR (fsLit "unsafeRangeSize")
readList_RDR, readListDefault_RDR, readListPrec_RDR, readListPrecDefault_RDR,
readPrec_RDR, parens_RDR, choose_RDR, lexP_RDR, expectP_RDR :: RdrName
readList_RDR = varQual_RDR gHC_READ (fsLit "readList")
readListDefault_RDR = varQual_RDR gHC_READ (fsLit "readListDefault")
readListPrec_RDR = varQual_RDR gHC_READ (fsLit "readListPrec")
readListPrecDefault_RDR = varQual_RDR gHC_READ (fsLit "readListPrecDefault")
readPrec_RDR = varQual_RDR gHC_READ (fsLit "readPrec")
parens_RDR = varQual_RDR gHC_READ (fsLit "parens")
choose_RDR = varQual_RDR gHC_READ (fsLit "choose")
lexP_RDR = varQual_RDR gHC_READ (fsLit "lexP")
expectP_RDR = varQual_RDR gHC_READ (fsLit "expectP")
punc_RDR, ident_RDR, symbol_RDR :: RdrName
punc_RDR = dataQual_RDR lEX (fsLit "Punc")
ident_RDR = dataQual_RDR lEX (fsLit "Ident")
symbol_RDR = dataQual_RDR lEX (fsLit "Symbol")
step_RDR, alt_RDR, reset_RDR, prec_RDR, pfail_RDR :: RdrName
step_RDR = varQual_RDR rEAD_PREC (fsLit "step")
alt_RDR = varQual_RDR rEAD_PREC (fsLit "+++")
reset_RDR = varQual_RDR rEAD_PREC (fsLit "reset")
prec_RDR = varQual_RDR rEAD_PREC (fsLit "prec")
pfail_RDR = varQual_RDR rEAD_PREC (fsLit "pfail")
showList_RDR, showList___RDR, showsPrec_RDR, shows_RDR, showString_RDR,
showSpace_RDR, showParen_RDR :: RdrName
showList_RDR = varQual_RDR gHC_SHOW (fsLit "showList")
showList___RDR = varQual_RDR gHC_SHOW (fsLit "showList__")
showsPrec_RDR = varQual_RDR gHC_SHOW (fsLit "showsPrec")
shows_RDR = varQual_RDR gHC_SHOW (fsLit "shows")
showString_RDR = varQual_RDR gHC_SHOW (fsLit "showString")
showSpace_RDR = varQual_RDR gHC_SHOW (fsLit "showSpace")
showParen_RDR = varQual_RDR gHC_SHOW (fsLit "showParen")
typeRep_RDR, mkTyCon_RDR, mkTyConApp_RDR :: RdrName
typeRep_RDR = varQual_RDR tYPEABLE_INTERNAL (fsLit "typeRep#")
mkTyCon_RDR = varQual_RDR tYPEABLE_INTERNAL (fsLit "mkTyCon")
mkTyConApp_RDR = varQual_RDR tYPEABLE_INTERNAL (fsLit "mkTyConApp")
undefined_RDR :: RdrName
undefined_RDR = varQual_RDR gHC_ERR (fsLit "undefined")
error_RDR :: RdrName
error_RDR = varQual_RDR gHC_ERR (fsLit "error")
-- Generics (constructors and functions)
u1DataCon_RDR, par1DataCon_RDR, rec1DataCon_RDR,
k1DataCon_RDR, m1DataCon_RDR, l1DataCon_RDR, r1DataCon_RDR,
prodDataCon_RDR, comp1DataCon_RDR,
unPar1_RDR, unRec1_RDR, unK1_RDR, unComp1_RDR,
from_RDR, from1_RDR, to_RDR, to1_RDR,
datatypeName_RDR, moduleName_RDR, packageName_RDR, isNewtypeName_RDR,
conName_RDR, conFixity_RDR, conIsRecord_RDR,
noArityDataCon_RDR, arityDataCon_RDR, selName_RDR,
prefixDataCon_RDR, infixDataCon_RDR, leftAssocDataCon_RDR,
rightAssocDataCon_RDR, notAssocDataCon_RDR :: RdrName
u1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "U1")
par1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Par1")
rec1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Rec1")
k1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "K1")
m1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "M1")
l1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "L1")
r1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "R1")
prodDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit ":*:")
comp1DataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Comp1")
unPar1_RDR = varQual_RDR gHC_GENERICS (fsLit "unPar1")
unRec1_RDR = varQual_RDR gHC_GENERICS (fsLit "unRec1")
unK1_RDR = varQual_RDR gHC_GENERICS (fsLit "unK1")
unComp1_RDR = varQual_RDR gHC_GENERICS (fsLit "unComp1")
from_RDR = varQual_RDR gHC_GENERICS (fsLit "from")
from1_RDR = varQual_RDR gHC_GENERICS (fsLit "from1")
to_RDR = varQual_RDR gHC_GENERICS (fsLit "to")
to1_RDR = varQual_RDR gHC_GENERICS (fsLit "to1")
datatypeName_RDR = varQual_RDR gHC_GENERICS (fsLit "datatypeName")
moduleName_RDR = varQual_RDR gHC_GENERICS (fsLit "moduleName")
packageName_RDR = varQual_RDR gHC_GENERICS (fsLit "packageName")
isNewtypeName_RDR = varQual_RDR gHC_GENERICS (fsLit "isNewtype")
selName_RDR = varQual_RDR gHC_GENERICS (fsLit "selName")
conName_RDR = varQual_RDR gHC_GENERICS (fsLit "conName")
conFixity_RDR = varQual_RDR gHC_GENERICS (fsLit "conFixity")
conIsRecord_RDR = varQual_RDR gHC_GENERICS (fsLit "conIsRecord")
noArityDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "NoArity")
arityDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Arity")
prefixDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Prefix")
infixDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "Infix")
leftAssocDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "LeftAssociative")
rightAssocDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "RightAssociative")
notAssocDataCon_RDR = dataQual_RDR gHC_GENERICS (fsLit "NotAssociative")
fmap_RDR, pure_RDR, ap_RDR, foldable_foldr_RDR, foldMap_RDR,
traverse_RDR, mempty_RDR, mappend_RDR :: RdrName
fmap_RDR = varQual_RDR gHC_BASE (fsLit "fmap")
pure_RDR = nameRdrName pureAName
ap_RDR = nameRdrName apAName
foldable_foldr_RDR = varQual_RDR dATA_FOLDABLE (fsLit "foldr")
foldMap_RDR = varQual_RDR dATA_FOLDABLE (fsLit "foldMap")
traverse_RDR = varQual_RDR dATA_TRAVERSABLE (fsLit "traverse")
mempty_RDR = varQual_RDR gHC_BASE (fsLit "mempty")
mappend_RDR = varQual_RDR gHC_BASE (fsLit "mappend")
----------------------
varQual_RDR, tcQual_RDR, clsQual_RDR, dataQual_RDR
:: Module -> FastString -> RdrName
varQual_RDR mod str = mkOrig mod (mkOccNameFS varName str)
tcQual_RDR mod str = mkOrig mod (mkOccNameFS tcName str)
clsQual_RDR mod str = mkOrig mod (mkOccNameFS clsName str)
dataQual_RDR mod str = mkOrig mod (mkOccNameFS dataName str)
{-
************************************************************************
* *
\subsection{Known-key names}
* *
************************************************************************
Many of these Names are not really "built in", but some parts of the
compiler (notably the deriving mechanism) need to mention their names,
and it's convenient to write them all down in one place.
--MetaHaskell Extension add the constrs and the lower case case
-- guys as well (perhaps) e.g. see trueDataConName below
-}
wildCardName :: Name
wildCardName = mkSystemVarName wildCardKey (fsLit "wild")
runMainIOName :: Name
runMainIOName = varQual gHC_TOP_HANDLER (fsLit "runMainIO") runMainKey
orderingTyConName, ltDataConName, eqDataConName, gtDataConName :: Name
orderingTyConName = tcQual gHC_TYPES (fsLit "Ordering") orderingTyConKey
ltDataConName = conName gHC_TYPES (fsLit "LT") ltDataConKey
eqDataConName = conName gHC_TYPES (fsLit "EQ") eqDataConKey
gtDataConName = conName gHC_TYPES (fsLit "GT") gtDataConKey
specTyConName :: Name
specTyConName = tcQual gHC_TYPES (fsLit "SPEC") specTyConKey
eitherTyConName, leftDataConName, rightDataConName :: Name
eitherTyConName = tcQual dATA_EITHER (fsLit "Either") eitherTyConKey
leftDataConName = conName dATA_EITHER (fsLit "Left") leftDataConKey
rightDataConName = conName dATA_EITHER (fsLit "Right") rightDataConKey
-- Generics (types)
v1TyConName, u1TyConName, par1TyConName, rec1TyConName,
k1TyConName, m1TyConName, sumTyConName, prodTyConName,
compTyConName, rTyConName, pTyConName, dTyConName,
cTyConName, sTyConName, rec0TyConName, par0TyConName,
d1TyConName, c1TyConName, s1TyConName, noSelTyConName,
repTyConName, rep1TyConName :: Name
v1TyConName = tcQual gHC_GENERICS (fsLit "V1") v1TyConKey
u1TyConName = tcQual gHC_GENERICS (fsLit "U1") u1TyConKey
par1TyConName = tcQual gHC_GENERICS (fsLit "Par1") par1TyConKey
rec1TyConName = tcQual gHC_GENERICS (fsLit "Rec1") rec1TyConKey
k1TyConName = tcQual gHC_GENERICS (fsLit "K1") k1TyConKey
m1TyConName = tcQual gHC_GENERICS (fsLit "M1") m1TyConKey
sumTyConName = tcQual gHC_GENERICS (fsLit ":+:") sumTyConKey
prodTyConName = tcQual gHC_GENERICS (fsLit ":*:") prodTyConKey
compTyConName = tcQual gHC_GENERICS (fsLit ":.:") compTyConKey
rTyConName = tcQual gHC_GENERICS (fsLit "R") rTyConKey
pTyConName = tcQual gHC_GENERICS (fsLit "P") pTyConKey
dTyConName = tcQual gHC_GENERICS (fsLit "D") dTyConKey
cTyConName = tcQual gHC_GENERICS (fsLit "C") cTyConKey
sTyConName = tcQual gHC_GENERICS (fsLit "S") sTyConKey
rec0TyConName = tcQual gHC_GENERICS (fsLit "Rec0") rec0TyConKey
par0TyConName = tcQual gHC_GENERICS (fsLit "Par0") par0TyConKey
d1TyConName = tcQual gHC_GENERICS (fsLit "D1") d1TyConKey
c1TyConName = tcQual gHC_GENERICS (fsLit "C1") c1TyConKey
s1TyConName = tcQual gHC_GENERICS (fsLit "S1") s1TyConKey
noSelTyConName = tcQual gHC_GENERICS (fsLit "NoSelector") noSelTyConKey
repTyConName = tcQual gHC_GENERICS (fsLit "Rep") repTyConKey
rep1TyConName = tcQual gHC_GENERICS (fsLit "Rep1") rep1TyConKey
-- Base strings Strings
unpackCStringName, unpackCStringFoldrName,
unpackCStringUtf8Name, eqStringName, stringTyConName :: Name
unpackCStringName = varQual gHC_CSTRING (fsLit "unpackCString#") unpackCStringIdKey
unpackCStringFoldrName = varQual gHC_CSTRING (fsLit "unpackFoldrCString#") unpackCStringFoldrIdKey
unpackCStringUtf8Name = varQual gHC_CSTRING (fsLit "unpackCStringUtf8#") unpackCStringUtf8IdKey
eqStringName = varQual gHC_BASE (fsLit "eqString") eqStringIdKey
stringTyConName = tcQual gHC_BASE (fsLit "String") stringTyConKey
-- The 'inline' function
inlineIdName :: Name
inlineIdName = varQual gHC_MAGIC (fsLit "inline") inlineIdKey
-- Base classes (Eq, Ord, Functor)
fmapName, eqClassName, eqName, ordClassName, geName, functorClassName :: Name
eqClassName = clsQual gHC_CLASSES (fsLit "Eq") eqClassKey
eqName = varQual gHC_CLASSES (fsLit "==") eqClassOpKey
ordClassName = clsQual gHC_CLASSES (fsLit "Ord") ordClassKey
geName = varQual gHC_CLASSES (fsLit ">=") geClassOpKey
functorClassName = clsQual gHC_BASE (fsLit "Functor") functorClassKey
fmapName = varQual gHC_BASE (fsLit "fmap") fmapClassOpKey
-- Class Monad
monadClassName, thenMName, bindMName, returnMName, failMName :: Name
monadClassName = clsQual gHC_BASE (fsLit "Monad") monadClassKey
thenMName = varQual gHC_BASE (fsLit ">>") thenMClassOpKey
bindMName = varQual gHC_BASE (fsLit ">>=") bindMClassOpKey
returnMName = varQual gHC_BASE (fsLit "return") returnMClassOpKey
failMName = varQual gHC_BASE (fsLit "fail") failMClassOpKey
-- Classes (Applicative, Foldable, Traversable)
applicativeClassName, foldableClassName, traversableClassName :: Name
applicativeClassName = clsQual gHC_BASE (fsLit "Applicative") applicativeClassKey
foldableClassName = clsQual dATA_FOLDABLE (fsLit "Foldable") foldableClassKey
traversableClassName = clsQual dATA_TRAVERSABLE (fsLit "Traversable") traversableClassKey
-- AMP additions
joinMName, apAName, pureAName, alternativeClassName :: Name
joinMName = varQual gHC_BASE (fsLit "join") joinMIdKey
apAName = varQual gHC_BASE (fsLit "<*>") apAClassOpKey
pureAName = varQual gHC_BASE (fsLit "pure") pureAClassOpKey
alternativeClassName = clsQual mONAD (fsLit "Alternative") alternativeClassKey
joinMIdKey, apAClassOpKey, pureAClassOpKey, alternativeClassKey :: Unique
joinMIdKey = mkPreludeMiscIdUnique 750
apAClassOpKey = mkPreludeMiscIdUnique 751 -- <*>
pureAClassOpKey = mkPreludeMiscIdUnique 752
alternativeClassKey = mkPreludeMiscIdUnique 753
-- Functions for GHC extensions
groupWithName :: Name
groupWithName = varQual gHC_EXTS (fsLit "groupWith") groupWithIdKey
-- Random PrelBase functions
fromStringName, otherwiseIdName, foldrName, buildName, augmentName,
mapName, appendName, assertName,
breakpointName, breakpointCondName, breakpointAutoName,
opaqueTyConName :: Name
fromStringName = varQual dATA_STRING (fsLit "fromString") fromStringClassOpKey
otherwiseIdName = varQual gHC_BASE (fsLit "otherwise") otherwiseIdKey
foldrName = varQual gHC_BASE (fsLit "foldr") foldrIdKey
buildName = varQual gHC_BASE (fsLit "build") buildIdKey
augmentName = varQual gHC_BASE (fsLit "augment") augmentIdKey
mapName = varQual gHC_BASE (fsLit "map") mapIdKey
appendName = varQual gHC_BASE (fsLit "++") appendIdKey
assertName = varQual gHC_BASE (fsLit "assert") assertIdKey
breakpointName = varQual gHC_BASE (fsLit "breakpoint") breakpointIdKey
breakpointCondName= varQual gHC_BASE (fsLit "breakpointCond") breakpointCondIdKey
breakpointAutoName= varQual gHC_BASE (fsLit "breakpointAuto") breakpointAutoIdKey
opaqueTyConName = tcQual gHC_BASE (fsLit "Opaque") opaqueTyConKey
breakpointJumpName :: Name
breakpointJumpName
= mkInternalName
breakpointJumpIdKey
(mkOccNameFS varName (fsLit "breakpointJump"))
noSrcSpan
breakpointCondJumpName :: Name
breakpointCondJumpName
= mkInternalName
breakpointCondJumpIdKey
(mkOccNameFS varName (fsLit "breakpointCondJump"))
noSrcSpan
breakpointAutoJumpName :: Name
breakpointAutoJumpName
= mkInternalName
breakpointAutoJumpIdKey
(mkOccNameFS varName (fsLit "breakpointAutoJump"))
noSrcSpan
-- PrelTup
fstName, sndName :: Name
fstName = varQual dATA_TUPLE (fsLit "fst") fstIdKey
sndName = varQual dATA_TUPLE (fsLit "snd") sndIdKey
-- Module GHC.Num
numClassName, fromIntegerName, minusName, negateName :: Name
numClassName = clsQual gHC_NUM (fsLit "Num") numClassKey
fromIntegerName = varQual gHC_NUM (fsLit "fromInteger") fromIntegerClassOpKey
minusName = varQual gHC_NUM (fsLit "-") minusClassOpKey
negateName = varQual gHC_NUM (fsLit "negate") negateClassOpKey
integerTyConName, mkIntegerName, integerSDataConName,
integerToWord64Name, integerToInt64Name,
word64ToIntegerName, int64ToIntegerName,
plusIntegerName, timesIntegerName, smallIntegerName,
wordToIntegerName,
integerToWordName, integerToIntName, minusIntegerName,
negateIntegerName, eqIntegerPrimName, neqIntegerPrimName,
absIntegerName, signumIntegerName,
leIntegerPrimName, gtIntegerPrimName, ltIntegerPrimName, geIntegerPrimName,
compareIntegerName, quotRemIntegerName, divModIntegerName,
quotIntegerName, remIntegerName, divIntegerName, modIntegerName,
floatFromIntegerName, doubleFromIntegerName,
encodeFloatIntegerName, encodeDoubleIntegerName,
decodeDoubleIntegerName,
gcdIntegerName, lcmIntegerName,
andIntegerName, orIntegerName, xorIntegerName, complementIntegerName,
shiftLIntegerName, shiftRIntegerName :: Name
integerTyConName = tcQual gHC_INTEGER_TYPE (fsLit "Integer") integerTyConKey
integerSDataConName = conName gHC_INTEGER_TYPE (fsLit n) integerSDataConKey
where n = case cIntegerLibraryType of
IntegerGMP -> "S#"
IntegerSimple -> panic "integerSDataConName evaluated for integer-simple"
mkIntegerName = varQual gHC_INTEGER_TYPE (fsLit "mkInteger") mkIntegerIdKey
integerToWord64Name = varQual gHC_INTEGER_TYPE (fsLit "integerToWord64") integerToWord64IdKey
integerToInt64Name = varQual gHC_INTEGER_TYPE (fsLit "integerToInt64") integerToInt64IdKey
word64ToIntegerName = varQual gHC_INTEGER_TYPE (fsLit "word64ToInteger") word64ToIntegerIdKey
int64ToIntegerName = varQual gHC_INTEGER_TYPE (fsLit "int64ToInteger") int64ToIntegerIdKey
plusIntegerName = varQual gHC_INTEGER_TYPE (fsLit "plusInteger") plusIntegerIdKey
timesIntegerName = varQual gHC_INTEGER_TYPE (fsLit "timesInteger") timesIntegerIdKey
smallIntegerName = varQual gHC_INTEGER_TYPE (fsLit "smallInteger") smallIntegerIdKey
wordToIntegerName = varQual gHC_INTEGER_TYPE (fsLit "wordToInteger") wordToIntegerIdKey
integerToWordName = varQual gHC_INTEGER_TYPE (fsLit "integerToWord") integerToWordIdKey
integerToIntName = varQual gHC_INTEGER_TYPE (fsLit "integerToInt") integerToIntIdKey
minusIntegerName = varQual gHC_INTEGER_TYPE (fsLit "minusInteger") minusIntegerIdKey
negateIntegerName = varQual gHC_INTEGER_TYPE (fsLit "negateInteger") negateIntegerIdKey
eqIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "eqInteger#") eqIntegerPrimIdKey
neqIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "neqInteger#") neqIntegerPrimIdKey
absIntegerName = varQual gHC_INTEGER_TYPE (fsLit "absInteger") absIntegerIdKey
signumIntegerName = varQual gHC_INTEGER_TYPE (fsLit "signumInteger") signumIntegerIdKey
leIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "leInteger#") leIntegerPrimIdKey
gtIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "gtInteger#") gtIntegerPrimIdKey
ltIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "ltInteger#") ltIntegerPrimIdKey
geIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "geInteger#") geIntegerPrimIdKey
compareIntegerName = varQual gHC_INTEGER_TYPE (fsLit "compareInteger") compareIntegerIdKey
quotRemIntegerName = varQual gHC_INTEGER_TYPE (fsLit "quotRemInteger") quotRemIntegerIdKey
divModIntegerName = varQual gHC_INTEGER_TYPE (fsLit "divModInteger") divModIntegerIdKey
quotIntegerName = varQual gHC_INTEGER_TYPE (fsLit "quotInteger") quotIntegerIdKey
remIntegerName = varQual gHC_INTEGER_TYPE (fsLit "remInteger") remIntegerIdKey
divIntegerName = varQual gHC_INTEGER_TYPE (fsLit "divInteger") divIntegerIdKey
modIntegerName = varQual gHC_INTEGER_TYPE (fsLit "modInteger") modIntegerIdKey
floatFromIntegerName = varQual gHC_INTEGER_TYPE (fsLit "floatFromInteger") floatFromIntegerIdKey
doubleFromIntegerName = varQual gHC_INTEGER_TYPE (fsLit "doubleFromInteger") doubleFromIntegerIdKey
encodeFloatIntegerName = varQual gHC_INTEGER_TYPE (fsLit "encodeFloatInteger") encodeFloatIntegerIdKey
encodeDoubleIntegerName = varQual gHC_INTEGER_TYPE (fsLit "encodeDoubleInteger") encodeDoubleIntegerIdKey
decodeDoubleIntegerName = varQual gHC_INTEGER_TYPE (fsLit "decodeDoubleInteger") decodeDoubleIntegerIdKey
gcdIntegerName = varQual gHC_INTEGER_TYPE (fsLit "gcdInteger") gcdIntegerIdKey
lcmIntegerName = varQual gHC_INTEGER_TYPE (fsLit "lcmInteger") lcmIntegerIdKey
andIntegerName = varQual gHC_INTEGER_TYPE (fsLit "andInteger") andIntegerIdKey
orIntegerName = varQual gHC_INTEGER_TYPE (fsLit "orInteger") orIntegerIdKey
xorIntegerName = varQual gHC_INTEGER_TYPE (fsLit "xorInteger") xorIntegerIdKey
complementIntegerName = varQual gHC_INTEGER_TYPE (fsLit "complementInteger") complementIntegerIdKey
shiftLIntegerName = varQual gHC_INTEGER_TYPE (fsLit "shiftLInteger") shiftLIntegerIdKey
shiftRIntegerName = varQual gHC_INTEGER_TYPE (fsLit "shiftRInteger") shiftRIntegerIdKey
-- GHC.Real types and classes
rationalTyConName, ratioTyConName, ratioDataConName, realClassName,
integralClassName, realFracClassName, fractionalClassName,
fromRationalName, toIntegerName, toRationalName, fromIntegralName,
realToFracName :: Name
rationalTyConName = tcQual gHC_REAL (fsLit "Rational") rationalTyConKey
ratioTyConName = tcQual gHC_REAL (fsLit "Ratio") ratioTyConKey
ratioDataConName = conName gHC_REAL (fsLit ":%") ratioDataConKey
realClassName = clsQual gHC_REAL (fsLit "Real") realClassKey
integralClassName = clsQual gHC_REAL (fsLit "Integral") integralClassKey
realFracClassName = clsQual gHC_REAL (fsLit "RealFrac") realFracClassKey
fractionalClassName = clsQual gHC_REAL (fsLit "Fractional") fractionalClassKey
fromRationalName = varQual gHC_REAL (fsLit "fromRational") fromRationalClassOpKey
toIntegerName = varQual gHC_REAL (fsLit "toInteger") toIntegerClassOpKey
toRationalName = varQual gHC_REAL (fsLit "toRational") toRationalClassOpKey
fromIntegralName = varQual gHC_REAL (fsLit "fromIntegral")fromIntegralIdKey
realToFracName = varQual gHC_REAL (fsLit "realToFrac") realToFracIdKey
-- PrelFloat classes
floatingClassName, realFloatClassName :: Name
floatingClassName = clsQual gHC_FLOAT (fsLit "Floating") floatingClassKey
realFloatClassName = clsQual gHC_FLOAT (fsLit "RealFloat") realFloatClassKey
-- other GHC.Float functions
rationalToFloatName, rationalToDoubleName :: Name
rationalToFloatName = varQual gHC_FLOAT (fsLit "rationalToFloat") rationalToFloatIdKey
rationalToDoubleName = varQual gHC_FLOAT (fsLit "rationalToDouble") rationalToDoubleIdKey
-- Class Ix
ixClassName :: Name
ixClassName = clsQual gHC_ARR (fsLit "Ix") ixClassKey
-- Class Typeable, and functions for constructing `Typeable` dictionaries
typeableClassName
, typeRepTyConName
, mkTyConName
, mkPolyTyConAppName
, mkAppTyName
, typeLitTypeRepName
:: Name
typeableClassName = clsQual tYPEABLE_INTERNAL (fsLit "Typeable") typeableClassKey
typeRepTyConName = tcQual tYPEABLE_INTERNAL (fsLit "TypeRep") typeRepTyConKey
mkTyConName = varQual tYPEABLE_INTERNAL (fsLit "mkTyCon") mkTyConKey
mkPolyTyConAppName = varQual tYPEABLE_INTERNAL (fsLit "mkPolyTyConApp") mkPolyTyConAppKey
mkAppTyName = varQual tYPEABLE_INTERNAL (fsLit "mkAppTy") mkAppTyKey
typeLitTypeRepName = varQual tYPEABLE_INTERNAL (fsLit "typeLitTypeRep") typeLitTypeRepKey
-- Class Data
dataClassName :: Name
dataClassName = clsQual gENERICS (fsLit "Data") dataClassKey
-- Error module
assertErrorName :: Name
assertErrorName = varQual gHC_IO_Exception (fsLit "assertError") assertErrorIdKey
-- Enum module (Enum, Bounded)
enumClassName, enumFromName, enumFromToName, enumFromThenName,
enumFromThenToName, boundedClassName :: Name
enumClassName = clsQual gHC_ENUM (fsLit "Enum") enumClassKey
enumFromName = varQual gHC_ENUM (fsLit "enumFrom") enumFromClassOpKey
enumFromToName = varQual gHC_ENUM (fsLit "enumFromTo") enumFromToClassOpKey
enumFromThenName = varQual gHC_ENUM (fsLit "enumFromThen") enumFromThenClassOpKey
enumFromThenToName = varQual gHC_ENUM (fsLit "enumFromThenTo") enumFromThenToClassOpKey
boundedClassName = clsQual gHC_ENUM (fsLit "Bounded") boundedClassKey
-- List functions
concatName, filterName, zipName :: Name
concatName = varQual gHC_LIST (fsLit "concat") concatIdKey
filterName = varQual gHC_LIST (fsLit "filter") filterIdKey
zipName = varQual gHC_LIST (fsLit "zip") zipIdKey
-- Overloaded lists
isListClassName, fromListName, fromListNName, toListName :: Name
isListClassName = clsQual gHC_EXTS (fsLit "IsList") isListClassKey
fromListName = varQual gHC_EXTS (fsLit "fromList") fromListClassOpKey
fromListNName = varQual gHC_EXTS (fsLit "fromListN") fromListNClassOpKey
toListName = varQual gHC_EXTS (fsLit "toList") toListClassOpKey
-- Class Show
showClassName :: Name
showClassName = clsQual gHC_SHOW (fsLit "Show") showClassKey
-- Class Read
readClassName :: Name
readClassName = clsQual gHC_READ (fsLit "Read") readClassKey
-- Classes Generic and Generic1, Datatype, Constructor and Selector
genClassName, gen1ClassName, datatypeClassName, constructorClassName,
selectorClassName :: Name
genClassName = clsQual gHC_GENERICS (fsLit "Generic") genClassKey
gen1ClassName = clsQual gHC_GENERICS (fsLit "Generic1") gen1ClassKey
datatypeClassName = clsQual gHC_GENERICS (fsLit "Datatype") datatypeClassKey
constructorClassName = clsQual gHC_GENERICS (fsLit "Constructor") constructorClassKey
selectorClassName = clsQual gHC_GENERICS (fsLit "Selector") selectorClassKey
genericClassNames :: [Name]
genericClassNames = [genClassName, gen1ClassName]
-- GHCi things
ghciIoClassName, ghciStepIoMName :: Name
ghciIoClassName = clsQual gHC_GHCI (fsLit "GHCiSandboxIO") ghciIoClassKey
ghciStepIoMName = varQual gHC_GHCI (fsLit "ghciStepIO") ghciStepIoMClassOpKey
-- IO things
ioTyConName, ioDataConName, thenIOName, bindIOName, returnIOName,
failIOName :: Name
ioTyConName = tcQual gHC_TYPES (fsLit "IO") ioTyConKey
ioDataConName = conName gHC_TYPES (fsLit "IO") ioDataConKey
thenIOName = varQual gHC_BASE (fsLit "thenIO") thenIOIdKey
bindIOName = varQual gHC_BASE (fsLit "bindIO") bindIOIdKey
returnIOName = varQual gHC_BASE (fsLit "returnIO") returnIOIdKey
failIOName = varQual gHC_IO (fsLit "failIO") failIOIdKey
-- IO things
printName :: Name
printName = varQual sYSTEM_IO (fsLit "print") printIdKey
-- Int, Word, and Addr things
int8TyConName, int16TyConName, int32TyConName, int64TyConName :: Name
int8TyConName = tcQual gHC_INT (fsLit "Int8") int8TyConKey
int16TyConName = tcQual gHC_INT (fsLit "Int16") int16TyConKey
int32TyConName = tcQual gHC_INT (fsLit "Int32") int32TyConKey
int64TyConName = tcQual gHC_INT (fsLit "Int64") int64TyConKey
-- Word module
word8TyConName, word16TyConName, word32TyConName, word64TyConName :: Name
word8TyConName = tcQual gHC_WORD (fsLit "Word8") word8TyConKey
word16TyConName = tcQual gHC_WORD (fsLit "Word16") word16TyConKey
word32TyConName = tcQual gHC_WORD (fsLit "Word32") word32TyConKey
word64TyConName = tcQual gHC_WORD (fsLit "Word64") word64TyConKey
-- PrelPtr module
ptrTyConName, funPtrTyConName :: Name
ptrTyConName = tcQual gHC_PTR (fsLit "Ptr") ptrTyConKey
funPtrTyConName = tcQual gHC_PTR (fsLit "FunPtr") funPtrTyConKey
-- Foreign objects and weak pointers
stablePtrTyConName, newStablePtrName :: Name
stablePtrTyConName = tcQual gHC_STABLE (fsLit "StablePtr") stablePtrTyConKey
newStablePtrName = varQual gHC_STABLE (fsLit "newStablePtr") newStablePtrIdKey
-- PrelST module
runSTRepName :: Name
runSTRepName = varQual gHC_ST (fsLit "runSTRep") runSTRepIdKey
-- Recursive-do notation
monadFixClassName, mfixName :: Name
monadFixClassName = clsQual mONAD_FIX (fsLit "MonadFix") monadFixClassKey
mfixName = varQual mONAD_FIX (fsLit "mfix") mfixIdKey
-- Arrow notation
arrAName, composeAName, firstAName, appAName, choiceAName, loopAName :: Name
arrAName = varQual aRROW (fsLit "arr") arrAIdKey
composeAName = varQual gHC_DESUGAR (fsLit ">>>") composeAIdKey
firstAName = varQual aRROW (fsLit "first") firstAIdKey
appAName = varQual aRROW (fsLit "app") appAIdKey
choiceAName = varQual aRROW (fsLit "|||") choiceAIdKey
loopAName = varQual aRROW (fsLit "loop") loopAIdKey
-- Monad comprehensions
guardMName, liftMName, mzipName :: Name
guardMName = varQual mONAD (fsLit "guard") guardMIdKey
liftMName = varQual mONAD (fsLit "liftM") liftMIdKey
mzipName = varQual mONAD_ZIP (fsLit "mzip") mzipIdKey
-- Annotation type checking
toAnnotationWrapperName :: Name
toAnnotationWrapperName = varQual gHC_DESUGAR (fsLit "toAnnotationWrapper") toAnnotationWrapperIdKey
-- Other classes, needed for type defaulting
monadPlusClassName, randomClassName, randomGenClassName,
isStringClassName :: Name
monadPlusClassName = clsQual mONAD (fsLit "MonadPlus") monadPlusClassKey
randomClassName = clsQual rANDOM (fsLit "Random") randomClassKey
randomGenClassName = clsQual rANDOM (fsLit "RandomGen") randomGenClassKey
isStringClassName = clsQual dATA_STRING (fsLit "IsString") isStringClassKey
-- Type-level naturals
knownNatClassName :: Name
knownNatClassName = clsQual gHC_TYPELITS (fsLit "KnownNat") knownNatClassNameKey
knownSymbolClassName :: Name
knownSymbolClassName = clsQual gHC_TYPELITS (fsLit "KnownSymbol") knownSymbolClassNameKey
-- Implicit parameters
ipClassName :: Name
ipClassName = clsQual gHC_CLASSES (fsLit "IP") ipClassNameKey
-- Source Locations
callStackDataConName, callStackTyConName, srcLocDataConName :: Name
callStackDataConName
= conName gHC_STACK (fsLit "CallStack") callStackDataConKey
callStackTyConName
= tcQual gHC_STACK (fsLit "CallStack") callStackTyConKey
srcLocDataConName
= conName gHC_SRCLOC (fsLit "SrcLoc") srcLocDataConKey
-- plugins
pLUGINS :: Module
pLUGINS = mkThisGhcModule (fsLit "Plugins")
pluginTyConName :: Name
pluginTyConName = tcQual pLUGINS (fsLit "Plugin") pluginTyConKey
-- Static pointers
staticPtrInfoTyConName :: Name
staticPtrInfoTyConName =
tcQual gHC_STATICPTR (fsLit "StaticPtrInfo") staticPtrInfoTyConKey
staticPtrInfoDataConName :: Name
staticPtrInfoDataConName =
conName gHC_STATICPTR (fsLit "StaticPtrInfo") staticPtrInfoDataConKey
staticPtrTyConName :: Name
staticPtrTyConName =
tcQual gHC_STATICPTR (fsLit "StaticPtr") staticPtrTyConKey
staticPtrDataConName :: Name
staticPtrDataConName =
conName gHC_STATICPTR (fsLit "StaticPtr") staticPtrDataConKey
fingerprintDataConName :: Name
fingerprintDataConName =
conName gHC_FINGERPRINT_TYPE (fsLit "Fingerprint") fingerprintDataConKey
{-
************************************************************************
* *
\subsection{Local helpers}
* *
************************************************************************
All these are original names; hence mkOrig
-}
varQual, tcQual, clsQual :: Module -> FastString -> Unique -> Name
varQual = mk_known_key_name varName
tcQual = mk_known_key_name tcName
clsQual = mk_known_key_name clsName
mk_known_key_name :: NameSpace -> Module -> FastString -> Unique -> Name
mk_known_key_name space modu str unique
= mkExternalName unique modu (mkOccNameFS space str) noSrcSpan
conName :: Module -> FastString -> Unique -> Name
conName modu occ unique
= mkExternalName unique modu (mkOccNameFS dataName occ) noSrcSpan
{-
************************************************************************
* *
\subsubsection[Uniques-prelude-Classes]{@Uniques@ for wired-in @Classes@}
* *
************************************************************************
--MetaHaskell extension hand allocate keys here
-}
boundedClassKey, enumClassKey, eqClassKey, floatingClassKey,
fractionalClassKey, integralClassKey, monadClassKey, dataClassKey,
functorClassKey, numClassKey, ordClassKey, readClassKey, realClassKey,
realFloatClassKey, realFracClassKey, showClassKey, ixClassKey :: Unique
boundedClassKey = mkPreludeClassUnique 1
enumClassKey = mkPreludeClassUnique 2
eqClassKey = mkPreludeClassUnique 3
floatingClassKey = mkPreludeClassUnique 5
fractionalClassKey = mkPreludeClassUnique 6
integralClassKey = mkPreludeClassUnique 7
monadClassKey = mkPreludeClassUnique 8
dataClassKey = mkPreludeClassUnique 9
functorClassKey = mkPreludeClassUnique 10
numClassKey = mkPreludeClassUnique 11
ordClassKey = mkPreludeClassUnique 12
readClassKey = mkPreludeClassUnique 13
realClassKey = mkPreludeClassUnique 14
realFloatClassKey = mkPreludeClassUnique 15
realFracClassKey = mkPreludeClassUnique 16
showClassKey = mkPreludeClassUnique 17
ixClassKey = mkPreludeClassUnique 18
typeableClassKey, typeable1ClassKey, typeable2ClassKey, typeable3ClassKey,
typeable4ClassKey, typeable5ClassKey, typeable6ClassKey, typeable7ClassKey
:: Unique
typeableClassKey = mkPreludeClassUnique 20
typeable1ClassKey = mkPreludeClassUnique 21
typeable2ClassKey = mkPreludeClassUnique 22
typeable3ClassKey = mkPreludeClassUnique 23
typeable4ClassKey = mkPreludeClassUnique 24
typeable5ClassKey = mkPreludeClassUnique 25
typeable6ClassKey = mkPreludeClassUnique 26
typeable7ClassKey = mkPreludeClassUnique 27
monadFixClassKey :: Unique
monadFixClassKey = mkPreludeClassUnique 28
monadPlusClassKey, randomClassKey, randomGenClassKey :: Unique
monadPlusClassKey = mkPreludeClassUnique 30
randomClassKey = mkPreludeClassUnique 31
randomGenClassKey = mkPreludeClassUnique 32
isStringClassKey :: Unique
isStringClassKey = mkPreludeClassUnique 33
applicativeClassKey, foldableClassKey, traversableClassKey :: Unique
applicativeClassKey = mkPreludeClassUnique 34
foldableClassKey = mkPreludeClassUnique 35
traversableClassKey = mkPreludeClassUnique 36
genClassKey, gen1ClassKey, datatypeClassKey, constructorClassKey,
selectorClassKey :: Unique
genClassKey = mkPreludeClassUnique 37
gen1ClassKey = mkPreludeClassUnique 38
datatypeClassKey = mkPreludeClassUnique 39
constructorClassKey = mkPreludeClassUnique 40
selectorClassKey = mkPreludeClassUnique 41
-- KnownNat: see Note [KnowNat & KnownSymbol and EvLit] in TcEvidence
knownNatClassNameKey :: Unique
knownNatClassNameKey = mkPreludeClassUnique 42
-- KnownSymbol: see Note [KnownNat & KnownSymbol and EvLit] in TcEvidence
knownSymbolClassNameKey :: Unique
knownSymbolClassNameKey = mkPreludeClassUnique 43
ghciIoClassKey :: Unique
ghciIoClassKey = mkPreludeClassUnique 44
ipClassNameKey :: Unique
ipClassNameKey = mkPreludeClassUnique 45
{-
************************************************************************
* *
\subsubsection[Uniques-prelude-TyCons]{@Uniques@ for wired-in @TyCons@}
* *
************************************************************************
-}
addrPrimTyConKey, arrayPrimTyConKey, arrayArrayPrimTyConKey, boolTyConKey, byteArrayPrimTyConKey,
charPrimTyConKey, charTyConKey, doublePrimTyConKey, doubleTyConKey,
floatPrimTyConKey, floatTyConKey, funTyConKey, intPrimTyConKey,
intTyConKey, int8TyConKey, int16TyConKey, int32PrimTyConKey,
int32TyConKey, int64PrimTyConKey, int64TyConKey,
integerTyConKey,
listTyConKey, foreignObjPrimTyConKey, weakPrimTyConKey,
mutableArrayPrimTyConKey, mutableArrayArrayPrimTyConKey, mutableByteArrayPrimTyConKey,
orderingTyConKey, mVarPrimTyConKey, ratioTyConKey, rationalTyConKey,
realWorldTyConKey, stablePtrPrimTyConKey, stablePtrTyConKey,
anyTyConKey, eqTyConKey, smallArrayPrimTyConKey,
smallMutableArrayPrimTyConKey :: Unique
addrPrimTyConKey = mkPreludeTyConUnique 1
arrayPrimTyConKey = mkPreludeTyConUnique 3
boolTyConKey = mkPreludeTyConUnique 4
byteArrayPrimTyConKey = mkPreludeTyConUnique 5
charPrimTyConKey = mkPreludeTyConUnique 7
charTyConKey = mkPreludeTyConUnique 8
doublePrimTyConKey = mkPreludeTyConUnique 9
doubleTyConKey = mkPreludeTyConUnique 10
floatPrimTyConKey = mkPreludeTyConUnique 11
floatTyConKey = mkPreludeTyConUnique 12
funTyConKey = mkPreludeTyConUnique 13
intPrimTyConKey = mkPreludeTyConUnique 14
intTyConKey = mkPreludeTyConUnique 15
int8TyConKey = mkPreludeTyConUnique 16
int16TyConKey = mkPreludeTyConUnique 17
int32PrimTyConKey = mkPreludeTyConUnique 18
int32TyConKey = mkPreludeTyConUnique 19
int64PrimTyConKey = mkPreludeTyConUnique 20
int64TyConKey = mkPreludeTyConUnique 21
integerTyConKey = mkPreludeTyConUnique 22
listTyConKey = mkPreludeTyConUnique 24
foreignObjPrimTyConKey = mkPreludeTyConUnique 25
weakPrimTyConKey = mkPreludeTyConUnique 27
mutableArrayPrimTyConKey = mkPreludeTyConUnique 28
mutableByteArrayPrimTyConKey = mkPreludeTyConUnique 29
orderingTyConKey = mkPreludeTyConUnique 30
mVarPrimTyConKey = mkPreludeTyConUnique 31
ratioTyConKey = mkPreludeTyConUnique 32
rationalTyConKey = mkPreludeTyConUnique 33
realWorldTyConKey = mkPreludeTyConUnique 34
stablePtrPrimTyConKey = mkPreludeTyConUnique 35
stablePtrTyConKey = mkPreludeTyConUnique 36
anyTyConKey = mkPreludeTyConUnique 37
eqTyConKey = mkPreludeTyConUnique 38
arrayArrayPrimTyConKey = mkPreludeTyConUnique 39
mutableArrayArrayPrimTyConKey = mkPreludeTyConUnique 40
statePrimTyConKey, stableNamePrimTyConKey, stableNameTyConKey,
mutVarPrimTyConKey, ioTyConKey,
wordPrimTyConKey, wordTyConKey, word8TyConKey, word16TyConKey,
word32PrimTyConKey, word32TyConKey, word64PrimTyConKey, word64TyConKey,
liftedConKey, unliftedConKey, anyBoxConKey, kindConKey, boxityConKey,
typeConKey, threadIdPrimTyConKey, bcoPrimTyConKey, ptrTyConKey,
funPtrTyConKey, tVarPrimTyConKey, eqPrimTyConKey,
eqReprPrimTyConKey, voidPrimTyConKey :: Unique
statePrimTyConKey = mkPreludeTyConUnique 50
stableNamePrimTyConKey = mkPreludeTyConUnique 51
stableNameTyConKey = mkPreludeTyConUnique 52
eqPrimTyConKey = mkPreludeTyConUnique 53
eqReprPrimTyConKey = mkPreludeTyConUnique 54
mutVarPrimTyConKey = mkPreludeTyConUnique 55
ioTyConKey = mkPreludeTyConUnique 56
voidPrimTyConKey = mkPreludeTyConUnique 57
wordPrimTyConKey = mkPreludeTyConUnique 58
wordTyConKey = mkPreludeTyConUnique 59
word8TyConKey = mkPreludeTyConUnique 60
word16TyConKey = mkPreludeTyConUnique 61
word32PrimTyConKey = mkPreludeTyConUnique 62
word32TyConKey = mkPreludeTyConUnique 63
word64PrimTyConKey = mkPreludeTyConUnique 64
word64TyConKey = mkPreludeTyConUnique 65
liftedConKey = mkPreludeTyConUnique 66
unliftedConKey = mkPreludeTyConUnique 67
anyBoxConKey = mkPreludeTyConUnique 68
kindConKey = mkPreludeTyConUnique 69
boxityConKey = mkPreludeTyConUnique 70
typeConKey = mkPreludeTyConUnique 71
threadIdPrimTyConKey = mkPreludeTyConUnique 72
bcoPrimTyConKey = mkPreludeTyConUnique 73
ptrTyConKey = mkPreludeTyConUnique 74
funPtrTyConKey = mkPreludeTyConUnique 75
tVarPrimTyConKey = mkPreludeTyConUnique 76
-- Parallel array type constructor
parrTyConKey :: Unique
parrTyConKey = mkPreludeTyConUnique 82
-- dotnet interop
objectTyConKey :: Unique
objectTyConKey = mkPreludeTyConUnique 83
eitherTyConKey :: Unique
eitherTyConKey = mkPreludeTyConUnique 84
-- Super Kinds constructors
superKindTyConKey :: Unique
superKindTyConKey = mkPreludeTyConUnique 85
-- Kind constructors
liftedTypeKindTyConKey, anyKindTyConKey, openTypeKindTyConKey,
unliftedTypeKindTyConKey, constraintKindTyConKey :: Unique
anyKindTyConKey = mkPreludeTyConUnique 86
liftedTypeKindTyConKey = mkPreludeTyConUnique 87
openTypeKindTyConKey = mkPreludeTyConUnique 88
unliftedTypeKindTyConKey = mkPreludeTyConUnique 89
constraintKindTyConKey = mkPreludeTyConUnique 92
-- Coercion constructors
symCoercionTyConKey, transCoercionTyConKey, leftCoercionTyConKey,
rightCoercionTyConKey, instCoercionTyConKey, unsafeCoercionTyConKey,
csel1CoercionTyConKey, csel2CoercionTyConKey, cselRCoercionTyConKey
:: Unique
symCoercionTyConKey = mkPreludeTyConUnique 93
transCoercionTyConKey = mkPreludeTyConUnique 94
leftCoercionTyConKey = mkPreludeTyConUnique 95
rightCoercionTyConKey = mkPreludeTyConUnique 96
instCoercionTyConKey = mkPreludeTyConUnique 97
unsafeCoercionTyConKey = mkPreludeTyConUnique 98
csel1CoercionTyConKey = mkPreludeTyConUnique 99
csel2CoercionTyConKey = mkPreludeTyConUnique 100
cselRCoercionTyConKey = mkPreludeTyConUnique 101
pluginTyConKey :: Unique
pluginTyConKey = mkPreludeTyConUnique 102
unknownTyConKey, unknown1TyConKey, unknown2TyConKey, unknown3TyConKey,
opaqueTyConKey :: Unique
unknownTyConKey = mkPreludeTyConUnique 129
unknown1TyConKey = mkPreludeTyConUnique 130
unknown2TyConKey = mkPreludeTyConUnique 131
unknown3TyConKey = mkPreludeTyConUnique 132
opaqueTyConKey = mkPreludeTyConUnique 133
stringTyConKey :: Unique
stringTyConKey = mkPreludeTyConUnique 134
-- Generics (Unique keys)
v1TyConKey, u1TyConKey, par1TyConKey, rec1TyConKey,
k1TyConKey, m1TyConKey, sumTyConKey, prodTyConKey,
compTyConKey, rTyConKey, pTyConKey, dTyConKey,
cTyConKey, sTyConKey, rec0TyConKey, par0TyConKey,
d1TyConKey, c1TyConKey, s1TyConKey, noSelTyConKey,
repTyConKey, rep1TyConKey :: Unique
v1TyConKey = mkPreludeTyConUnique 135
u1TyConKey = mkPreludeTyConUnique 136
par1TyConKey = mkPreludeTyConUnique 137
rec1TyConKey = mkPreludeTyConUnique 138
k1TyConKey = mkPreludeTyConUnique 139
m1TyConKey = mkPreludeTyConUnique 140
sumTyConKey = mkPreludeTyConUnique 141
prodTyConKey = mkPreludeTyConUnique 142
compTyConKey = mkPreludeTyConUnique 143
rTyConKey = mkPreludeTyConUnique 144
pTyConKey = mkPreludeTyConUnique 145
dTyConKey = mkPreludeTyConUnique 146
cTyConKey = mkPreludeTyConUnique 147
sTyConKey = mkPreludeTyConUnique 148
rec0TyConKey = mkPreludeTyConUnique 149
par0TyConKey = mkPreludeTyConUnique 150
d1TyConKey = mkPreludeTyConUnique 151
c1TyConKey = mkPreludeTyConUnique 152
s1TyConKey = mkPreludeTyConUnique 153
noSelTyConKey = mkPreludeTyConUnique 154
repTyConKey = mkPreludeTyConUnique 155
rep1TyConKey = mkPreludeTyConUnique 156
-- Type-level naturals
typeNatKindConNameKey, typeSymbolKindConNameKey,
typeNatAddTyFamNameKey, typeNatMulTyFamNameKey, typeNatExpTyFamNameKey,
typeNatLeqTyFamNameKey, typeNatSubTyFamNameKey
, typeSymbolCmpTyFamNameKey, typeNatCmpTyFamNameKey
:: Unique
typeNatKindConNameKey = mkPreludeTyConUnique 160
typeSymbolKindConNameKey = mkPreludeTyConUnique 161
typeNatAddTyFamNameKey = mkPreludeTyConUnique 162
typeNatMulTyFamNameKey = mkPreludeTyConUnique 163
typeNatExpTyFamNameKey = mkPreludeTyConUnique 164
typeNatLeqTyFamNameKey = mkPreludeTyConUnique 165
typeNatSubTyFamNameKey = mkPreludeTyConUnique 166
typeSymbolCmpTyFamNameKey = mkPreludeTyConUnique 167
typeNatCmpTyFamNameKey = mkPreludeTyConUnique 168
ntTyConKey:: Unique
ntTyConKey = mkPreludeTyConUnique 174
coercibleTyConKey :: Unique
coercibleTyConKey = mkPreludeTyConUnique 175
proxyPrimTyConKey :: Unique
proxyPrimTyConKey = mkPreludeTyConUnique 176
specTyConKey :: Unique
specTyConKey = mkPreludeTyConUnique 177
smallArrayPrimTyConKey = mkPreludeTyConUnique 178
smallMutableArrayPrimTyConKey = mkPreludeTyConUnique 179
staticPtrTyConKey :: Unique
staticPtrTyConKey = mkPreludeTyConUnique 180
staticPtrInfoTyConKey :: Unique
staticPtrInfoTyConKey = mkPreludeTyConUnique 181
callStackTyConKey :: Unique
callStackTyConKey = mkPreludeTyConUnique 182
-- Typeables
typeRepTyConKey :: Unique
typeRepTyConKey = mkPreludeTyConUnique 183
---------------- Template Haskell -------------------
-- USES TyConUniques 200-299
-----------------------------------------------------
----------------------- SIMD ------------------------
-- USES TyConUniques 300-399
-----------------------------------------------------
#include "primop-vector-uniques.hs-incl"
{-
************************************************************************
* *
\subsubsection[Uniques-prelude-DataCons]{@Uniques@ for wired-in @DataCons@}
* *
************************************************************************
-}
charDataConKey, consDataConKey, doubleDataConKey, falseDataConKey,
floatDataConKey, intDataConKey, integerSDataConKey, nilDataConKey,
ratioDataConKey, stableNameDataConKey, trueDataConKey, wordDataConKey,
ioDataConKey, integerDataConKey, eqBoxDataConKey, coercibleDataConKey :: Unique
charDataConKey = mkPreludeDataConUnique 1
consDataConKey = mkPreludeDataConUnique 2
doubleDataConKey = mkPreludeDataConUnique 3
falseDataConKey = mkPreludeDataConUnique 4
floatDataConKey = mkPreludeDataConUnique 5
intDataConKey = mkPreludeDataConUnique 6
integerSDataConKey = mkPreludeDataConUnique 7
nilDataConKey = mkPreludeDataConUnique 11
ratioDataConKey = mkPreludeDataConUnique 12
stableNameDataConKey = mkPreludeDataConUnique 14
trueDataConKey = mkPreludeDataConUnique 15
wordDataConKey = mkPreludeDataConUnique 16
ioDataConKey = mkPreludeDataConUnique 17
integerDataConKey = mkPreludeDataConUnique 18
eqBoxDataConKey = mkPreludeDataConUnique 19
-- Generic data constructors
crossDataConKey, inlDataConKey, inrDataConKey, genUnitDataConKey :: Unique
crossDataConKey = mkPreludeDataConUnique 20
inlDataConKey = mkPreludeDataConUnique 21
inrDataConKey = mkPreludeDataConUnique 22
genUnitDataConKey = mkPreludeDataConUnique 23
-- Data constructor for parallel arrays
parrDataConKey :: Unique
parrDataConKey = mkPreludeDataConUnique 24
leftDataConKey, rightDataConKey :: Unique
leftDataConKey = mkPreludeDataConUnique 25
rightDataConKey = mkPreludeDataConUnique 26
ltDataConKey, eqDataConKey, gtDataConKey :: Unique
ltDataConKey = mkPreludeDataConUnique 27
eqDataConKey = mkPreludeDataConUnique 28
gtDataConKey = mkPreludeDataConUnique 29
coercibleDataConKey = mkPreludeDataConUnique 32
staticPtrDataConKey :: Unique
staticPtrDataConKey = mkPreludeDataConUnique 33
staticPtrInfoDataConKey :: Unique
staticPtrInfoDataConKey = mkPreludeDataConUnique 34
fingerprintDataConKey :: Unique
fingerprintDataConKey = mkPreludeDataConUnique 35
callStackDataConKey, srcLocDataConKey :: Unique
callStackDataConKey = mkPreludeDataConUnique 36
srcLocDataConKey = mkPreludeDataConUnique 37
{-
************************************************************************
* *
\subsubsection[Uniques-prelude-Ids]{@Uniques@ for wired-in @Ids@ (except @DataCons@)}
* *
************************************************************************
-}
wildCardKey, absentErrorIdKey, augmentIdKey, appendIdKey,
buildIdKey, errorIdKey, foldrIdKey, recSelErrorIdKey,
seqIdKey, irrefutPatErrorIdKey, eqStringIdKey,
noMethodBindingErrorIdKey, nonExhaustiveGuardsErrorIdKey,
runtimeErrorIdKey, patErrorIdKey, voidPrimIdKey,
realWorldPrimIdKey, recConErrorIdKey,
unpackCStringUtf8IdKey, unpackCStringAppendIdKey,
unpackCStringFoldrIdKey, unpackCStringIdKey :: Unique
wildCardKey = mkPreludeMiscIdUnique 0 -- See Note [WildCard binders]
absentErrorIdKey = mkPreludeMiscIdUnique 1
augmentIdKey = mkPreludeMiscIdUnique 2
appendIdKey = mkPreludeMiscIdUnique 3
buildIdKey = mkPreludeMiscIdUnique 4
errorIdKey = mkPreludeMiscIdUnique 5
foldrIdKey = mkPreludeMiscIdUnique 6
recSelErrorIdKey = mkPreludeMiscIdUnique 7
seqIdKey = mkPreludeMiscIdUnique 8
irrefutPatErrorIdKey = mkPreludeMiscIdUnique 9
eqStringIdKey = mkPreludeMiscIdUnique 10
noMethodBindingErrorIdKey = mkPreludeMiscIdUnique 11
nonExhaustiveGuardsErrorIdKey = mkPreludeMiscIdUnique 12
runtimeErrorIdKey = mkPreludeMiscIdUnique 13
patErrorIdKey = mkPreludeMiscIdUnique 14
realWorldPrimIdKey = mkPreludeMiscIdUnique 15
recConErrorIdKey = mkPreludeMiscIdUnique 16
unpackCStringUtf8IdKey = mkPreludeMiscIdUnique 17
unpackCStringAppendIdKey = mkPreludeMiscIdUnique 18
unpackCStringFoldrIdKey = mkPreludeMiscIdUnique 19
unpackCStringIdKey = mkPreludeMiscIdUnique 20
voidPrimIdKey = mkPreludeMiscIdUnique 21
unsafeCoerceIdKey, concatIdKey, filterIdKey, zipIdKey, bindIOIdKey,
returnIOIdKey, newStablePtrIdKey,
printIdKey, failIOIdKey, nullAddrIdKey, voidArgIdKey,
fstIdKey, sndIdKey, otherwiseIdKey, assertIdKey, runSTRepIdKey :: Unique
unsafeCoerceIdKey = mkPreludeMiscIdUnique 30
concatIdKey = mkPreludeMiscIdUnique 31
filterIdKey = mkPreludeMiscIdUnique 32
zipIdKey = mkPreludeMiscIdUnique 33
bindIOIdKey = mkPreludeMiscIdUnique 34
returnIOIdKey = mkPreludeMiscIdUnique 35
newStablePtrIdKey = mkPreludeMiscIdUnique 36
printIdKey = mkPreludeMiscIdUnique 37
failIOIdKey = mkPreludeMiscIdUnique 38
nullAddrIdKey = mkPreludeMiscIdUnique 39
voidArgIdKey = mkPreludeMiscIdUnique 40
fstIdKey = mkPreludeMiscIdUnique 41
sndIdKey = mkPreludeMiscIdUnique 42
otherwiseIdKey = mkPreludeMiscIdUnique 43
assertIdKey = mkPreludeMiscIdUnique 44
runSTRepIdKey = mkPreludeMiscIdUnique 45
mkIntegerIdKey, smallIntegerIdKey, wordToIntegerIdKey,
integerToWordIdKey, integerToIntIdKey,
integerToWord64IdKey, integerToInt64IdKey,
word64ToIntegerIdKey, int64ToIntegerIdKey,
plusIntegerIdKey, timesIntegerIdKey, minusIntegerIdKey,
negateIntegerIdKey,
eqIntegerPrimIdKey, neqIntegerPrimIdKey, absIntegerIdKey, signumIntegerIdKey,
leIntegerPrimIdKey, gtIntegerPrimIdKey, ltIntegerPrimIdKey, geIntegerPrimIdKey,
compareIntegerIdKey, quotRemIntegerIdKey, divModIntegerIdKey,
quotIntegerIdKey, remIntegerIdKey, divIntegerIdKey, modIntegerIdKey,
floatFromIntegerIdKey, doubleFromIntegerIdKey,
encodeFloatIntegerIdKey, encodeDoubleIntegerIdKey,
decodeDoubleIntegerIdKey,
gcdIntegerIdKey, lcmIntegerIdKey,
andIntegerIdKey, orIntegerIdKey, xorIntegerIdKey, complementIntegerIdKey,
shiftLIntegerIdKey, shiftRIntegerIdKey :: Unique
mkIntegerIdKey = mkPreludeMiscIdUnique 60
smallIntegerIdKey = mkPreludeMiscIdUnique 61
integerToWordIdKey = mkPreludeMiscIdUnique 62
integerToIntIdKey = mkPreludeMiscIdUnique 63
integerToWord64IdKey = mkPreludeMiscIdUnique 64
integerToInt64IdKey = mkPreludeMiscIdUnique 65
plusIntegerIdKey = mkPreludeMiscIdUnique 66
timesIntegerIdKey = mkPreludeMiscIdUnique 67
minusIntegerIdKey = mkPreludeMiscIdUnique 68
negateIntegerIdKey = mkPreludeMiscIdUnique 69
eqIntegerPrimIdKey = mkPreludeMiscIdUnique 70
neqIntegerPrimIdKey = mkPreludeMiscIdUnique 71
absIntegerIdKey = mkPreludeMiscIdUnique 72
signumIntegerIdKey = mkPreludeMiscIdUnique 73
leIntegerPrimIdKey = mkPreludeMiscIdUnique 74
gtIntegerPrimIdKey = mkPreludeMiscIdUnique 75
ltIntegerPrimIdKey = mkPreludeMiscIdUnique 76
geIntegerPrimIdKey = mkPreludeMiscIdUnique 77
compareIntegerIdKey = mkPreludeMiscIdUnique 78
quotIntegerIdKey = mkPreludeMiscIdUnique 79
remIntegerIdKey = mkPreludeMiscIdUnique 80
divIntegerIdKey = mkPreludeMiscIdUnique 81
modIntegerIdKey = mkPreludeMiscIdUnique 82
divModIntegerIdKey = mkPreludeMiscIdUnique 83
quotRemIntegerIdKey = mkPreludeMiscIdUnique 84
floatFromIntegerIdKey = mkPreludeMiscIdUnique 85
doubleFromIntegerIdKey = mkPreludeMiscIdUnique 86
encodeFloatIntegerIdKey = mkPreludeMiscIdUnique 87
encodeDoubleIntegerIdKey = mkPreludeMiscIdUnique 88
gcdIntegerIdKey = mkPreludeMiscIdUnique 89
lcmIntegerIdKey = mkPreludeMiscIdUnique 90
andIntegerIdKey = mkPreludeMiscIdUnique 91
orIntegerIdKey = mkPreludeMiscIdUnique 92
xorIntegerIdKey = mkPreludeMiscIdUnique 93
complementIntegerIdKey = mkPreludeMiscIdUnique 94
shiftLIntegerIdKey = mkPreludeMiscIdUnique 95
shiftRIntegerIdKey = mkPreludeMiscIdUnique 96
wordToIntegerIdKey = mkPreludeMiscIdUnique 97
word64ToIntegerIdKey = mkPreludeMiscIdUnique 98
int64ToIntegerIdKey = mkPreludeMiscIdUnique 99
decodeDoubleIntegerIdKey = mkPreludeMiscIdUnique 100
rootMainKey, runMainKey :: Unique
rootMainKey = mkPreludeMiscIdUnique 101
runMainKey = mkPreludeMiscIdUnique 102
thenIOIdKey, lazyIdKey, assertErrorIdKey, oneShotKey :: Unique
thenIOIdKey = mkPreludeMiscIdUnique 103
lazyIdKey = mkPreludeMiscIdUnique 104
assertErrorIdKey = mkPreludeMiscIdUnique 105
oneShotKey = mkPreludeMiscIdUnique 106
breakpointIdKey, breakpointCondIdKey, breakpointAutoIdKey,
breakpointJumpIdKey, breakpointCondJumpIdKey,
breakpointAutoJumpIdKey :: Unique
breakpointIdKey = mkPreludeMiscIdUnique 110
breakpointCondIdKey = mkPreludeMiscIdUnique 111
breakpointAutoIdKey = mkPreludeMiscIdUnique 112
breakpointJumpIdKey = mkPreludeMiscIdUnique 113
breakpointCondJumpIdKey = mkPreludeMiscIdUnique 114
breakpointAutoJumpIdKey = mkPreludeMiscIdUnique 115
inlineIdKey :: Unique
inlineIdKey = mkPreludeMiscIdUnique 120
mapIdKey, groupWithIdKey, dollarIdKey :: Unique
mapIdKey = mkPreludeMiscIdUnique 121
groupWithIdKey = mkPreludeMiscIdUnique 122
dollarIdKey = mkPreludeMiscIdUnique 123
coercionTokenIdKey :: Unique
coercionTokenIdKey = mkPreludeMiscIdUnique 124
rationalToFloatIdKey, rationalToDoubleIdKey :: Unique
rationalToFloatIdKey = mkPreludeMiscIdUnique 130
rationalToDoubleIdKey = mkPreludeMiscIdUnique 131
-- dotnet interop
unmarshalObjectIdKey, marshalObjectIdKey, marshalStringIdKey,
unmarshalStringIdKey, checkDotnetResNameIdKey :: Unique
unmarshalObjectIdKey = mkPreludeMiscIdUnique 150
marshalObjectIdKey = mkPreludeMiscIdUnique 151
marshalStringIdKey = mkPreludeMiscIdUnique 152
unmarshalStringIdKey = mkPreludeMiscIdUnique 153
checkDotnetResNameIdKey = mkPreludeMiscIdUnique 154
undefinedKey :: Unique
undefinedKey = mkPreludeMiscIdUnique 155
magicDictKey :: Unique
magicDictKey = mkPreludeMiscIdUnique 156
coerceKey :: Unique
coerceKey = mkPreludeMiscIdUnique 157
{-
Certain class operations from Prelude classes. They get their own
uniques so we can look them up easily when we want to conjure them up
during type checking.
-}
-- Just a place holder for unbound variables produced by the renamer:
unboundKey :: Unique
unboundKey = mkPreludeMiscIdUnique 160
fromIntegerClassOpKey, minusClassOpKey, fromRationalClassOpKey,
enumFromClassOpKey, enumFromThenClassOpKey, enumFromToClassOpKey,
enumFromThenToClassOpKey, eqClassOpKey, geClassOpKey, negateClassOpKey,
failMClassOpKey, bindMClassOpKey, thenMClassOpKey, returnMClassOpKey,
fmapClassOpKey
:: Unique
fromIntegerClassOpKey = mkPreludeMiscIdUnique 160
minusClassOpKey = mkPreludeMiscIdUnique 161
fromRationalClassOpKey = mkPreludeMiscIdUnique 162
enumFromClassOpKey = mkPreludeMiscIdUnique 163
enumFromThenClassOpKey = mkPreludeMiscIdUnique 164
enumFromToClassOpKey = mkPreludeMiscIdUnique 165
enumFromThenToClassOpKey = mkPreludeMiscIdUnique 166
eqClassOpKey = mkPreludeMiscIdUnique 167
geClassOpKey = mkPreludeMiscIdUnique 168
negateClassOpKey = mkPreludeMiscIdUnique 169
failMClassOpKey = mkPreludeMiscIdUnique 170
bindMClassOpKey = mkPreludeMiscIdUnique 171 -- (>>=)
thenMClassOpKey = mkPreludeMiscIdUnique 172 -- (>>)
fmapClassOpKey = mkPreludeMiscIdUnique 173
returnMClassOpKey = mkPreludeMiscIdUnique 174
-- Recursive do notation
mfixIdKey :: Unique
mfixIdKey = mkPreludeMiscIdUnique 175
-- Arrow notation
arrAIdKey, composeAIdKey, firstAIdKey, appAIdKey, choiceAIdKey,
loopAIdKey :: Unique
arrAIdKey = mkPreludeMiscIdUnique 180
composeAIdKey = mkPreludeMiscIdUnique 181 -- >>>
firstAIdKey = mkPreludeMiscIdUnique 182
appAIdKey = mkPreludeMiscIdUnique 183
choiceAIdKey = mkPreludeMiscIdUnique 184 -- |||
loopAIdKey = mkPreludeMiscIdUnique 185
fromStringClassOpKey :: Unique
fromStringClassOpKey = mkPreludeMiscIdUnique 186
-- Annotation type checking
toAnnotationWrapperIdKey :: Unique
toAnnotationWrapperIdKey = mkPreludeMiscIdUnique 187
-- Conversion functions
fromIntegralIdKey, realToFracIdKey, toIntegerClassOpKey, toRationalClassOpKey :: Unique
fromIntegralIdKey = mkPreludeMiscIdUnique 190
realToFracIdKey = mkPreludeMiscIdUnique 191
toIntegerClassOpKey = mkPreludeMiscIdUnique 192
toRationalClassOpKey = mkPreludeMiscIdUnique 193
-- Monad comprehensions
guardMIdKey, liftMIdKey, mzipIdKey :: Unique
guardMIdKey = mkPreludeMiscIdUnique 194
liftMIdKey = mkPreludeMiscIdUnique 195
mzipIdKey = mkPreludeMiscIdUnique 196
-- GHCi
ghciStepIoMClassOpKey :: Unique
ghciStepIoMClassOpKey = mkPreludeMiscIdUnique 197
-- Overloaded lists
isListClassKey, fromListClassOpKey, fromListNClassOpKey, toListClassOpKey :: Unique
isListClassKey = mkPreludeMiscIdUnique 198
fromListClassOpKey = mkPreludeMiscIdUnique 199
fromListNClassOpKey = mkPreludeMiscIdUnique 500
toListClassOpKey = mkPreludeMiscIdUnique 501
proxyHashKey :: Unique
proxyHashKey = mkPreludeMiscIdUnique 502
---------------- Template Haskell -------------------
-- USES IdUniques 200-499
-----------------------------------------------------
-- Used to make `Typeable` dictionaries
mkTyConKey
, mkPolyTyConAppKey
, mkAppTyKey
, typeLitTypeRepKey
:: Unique
mkTyConKey = mkPreludeMiscIdUnique 503
mkPolyTyConAppKey = mkPreludeMiscIdUnique 504
mkAppTyKey = mkPreludeMiscIdUnique 505
typeLitTypeRepKey = mkPreludeMiscIdUnique 506
{-
************************************************************************
* *
\subsection[Class-std-groups]{Standard groups of Prelude classes}
* *
************************************************************************
NOTE: @Eq@ and @Text@ do need to appear in @standardClasses@
even though every numeric class has these two as a superclass,
because the list of ambiguous dictionaries hasn't been simplified.
-}
numericClassKeys :: [Unique]
numericClassKeys =
[ numClassKey
, realClassKey
, integralClassKey
]
++ fractionalClassKeys
fractionalClassKeys :: [Unique]
fractionalClassKeys =
[ fractionalClassKey
, floatingClassKey
, realFracClassKey
, realFloatClassKey
]
-- The "standard classes" are used in defaulting (Haskell 98 report 4.3.4),
-- and are: "classes defined in the Prelude or a standard library"
standardClassKeys :: [Unique]
standardClassKeys = derivableClassKeys ++ numericClassKeys
++ [randomClassKey, randomGenClassKey,
functorClassKey,
monadClassKey, monadPlusClassKey,
isStringClassKey,
applicativeClassKey, foldableClassKey,
traversableClassKey, alternativeClassKey
]
{-
@derivableClassKeys@ is also used in checking \tr{deriving} constructs
(@TcDeriv@).
-}
derivableClassKeys :: [Unique]
derivableClassKeys
= [ eqClassKey, ordClassKey, enumClassKey, ixClassKey,
boundedClassKey, showClassKey, readClassKey ]
|
fmthoma/ghc
|
compiler/prelude/PrelNames.hs
|
bsd-3-clause
| 86,446
| 0
| 10
| 20,048
| 13,256
| 7,549
| 5,707
| 1,303
| 2
|
{-# LANGUAGE GADTs #-}
module CmmSwitch (
SwitchTargets,
mkSwitchTargets,
switchTargetsCases, switchTargetsDefault, switchTargetsRange, switchTargetsSigned,
mapSwitchTargets, switchTargetsToTable, switchTargetsFallThrough,
switchTargetsToList, eqSwitchTargetWith,
SwitchPlan(..),
targetSupportsSwitch,
createSwitchPlan,
) where
import Outputable
import DynFlags
import Compiler.Hoopl (Label)
import Data.Maybe
import Data.List (groupBy)
import Data.Function (on)
import qualified Data.Map as M
-- Note [Cmm Switches, the general plan]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Compiling a high-level switch statement, as it comes out of a STG case
-- expression, for example, allows for a surprising amount of design decisions.
-- Therefore, we cleanly separated this from the Stg → Cmm transformation, as
-- well as from the actual code generation.
--
-- The overall plan is:
-- * The Stg → Cmm transformation creates a single `SwitchTargets` in
-- emitSwitch and emitCmmLitSwitch in StgCmmUtils.hs.
-- At this stage, they are unsuitable for code generation.
-- * A dedicated Cmm transformation (CmmImplementSwitchPlans) replaces these
-- switch statements with code that is suitable for code generation, i.e.
-- a nice balanced tree of decisions with dense jump tables in the leafs.
-- The actual planning of this tree is performed in pure code in createSwitchPlan
-- in this module. See Note [createSwitchPlan].
-- * The actual code generation will not do any further processing and
-- implement each CmmSwitch with a jump tables.
--
-- When compiling to LLVM or C, CmmImplementSwitchPlans leaves the switch
-- statements alone, as we can turn a SwitchTargets value into a nice
-- switch-statement in LLVM resp. C, and leave the rest to the compiler.
--
-- See Note [CmmSwitch vs. CmmImplementSwitchPlans] why the two module are
-- separated.
-----------------------------------------------------------------------------
-- Magic Constants
--
-- There are a lot of heuristics here that depend on magic values where it is
-- hard to determine the "best" value (for whatever that means). These are the
-- magic values:
-- | Number of consecutive default values allowed in a jump table. If there are
-- more of them, the jump tables are split.
--
-- Currently 7, as it costs 7 words of additional code when a jump table is
-- split (at least on x64, determined experimentally).
maxJumpTableHole :: Integer
maxJumpTableHole = 7
-- | Minimum size of a jump table. If the number is smaller, the switch is
-- implemented using conditionals.
-- Currently 5, because an if-then-else tree of 4 values is nice and compact.
minJumpTableSize :: Int
minJumpTableSize = 5
-- | Minimum non-zero offset for a jump table. See Note [Jump Table Offset].
minJumpTableOffset :: Integer
minJumpTableOffset = 2
-----------------------------------------------------------------------------
-- Switch Targets
-- Note [SwitchTargets]:
-- ~~~~~~~~~~~~~~~~~~~~~
--
-- The branches of a switch are stored in a SwitchTargets, which consists of an
-- (optional) default jump target, and a map from values to jump targets.
--
-- If the default jump target is absent, the behaviour of the switch outside the
-- values of the map is undefined.
--
-- We use an Integer for the keys the map so that it can be used in switches on
-- unsigned as well as signed integers.
--
-- The map may be empty (we prune out-of-range branches here, so it could be us
-- emptying it).
--
-- Before code generation, the table needs to be brought into a form where all
-- entries are non-negative, so that it can be compiled into a jump table.
-- See switchTargetsToTable.
-- | A value of type SwitchTargets contains the alternatives for a 'CmmSwitch'
-- value, and knows whether the value is signed, the possible range, an
-- optional default value and a map from values to jump labels.
data SwitchTargets =
SwitchTargets
Bool -- Signed values
(Integer, Integer) -- Range
(Maybe Label) -- Default value
(M.Map Integer Label) -- The branches
deriving (Show, Eq)
-- | The smart constructr mkSwitchTargets normalises the map a bit:
-- * No entries outside the range
-- * No entries equal to the default
-- * No default if all elements have explicit values
mkSwitchTargets :: Bool -> (Integer, Integer) -> Maybe Label -> M.Map Integer Label -> SwitchTargets
mkSwitchTargets signed range@(lo,hi) mbdef ids
= SwitchTargets signed range mbdef' ids'
where
ids' = dropDefault $ restrict ids
mbdef' | defaultNeeded = mbdef
| otherwise = Nothing
-- Drop entries outside the range, if there is a range
restrict = M.filterWithKey (\x _ -> lo <= x && x <= hi)
-- Drop entries that equal the default, if there is a default
dropDefault | Just l <- mbdef = M.filter (/= l)
| otherwise = id
-- Check if the default is still needed
defaultNeeded = fromIntegral (M.size ids') /= hi-lo+1
-- | Changes all labels mentioned in the SwitchTargets value
mapSwitchTargets :: (Label -> Label) -> SwitchTargets -> SwitchTargets
mapSwitchTargets f (SwitchTargets signed range mbdef branches)
= SwitchTargets signed range (fmap f mbdef) (fmap f branches)
-- | Returns the list of non-default branches of the SwitchTargets value
switchTargetsCases :: SwitchTargets -> [(Integer, Label)]
switchTargetsCases (SwitchTargets _ _ _ branches) = M.toList branches
-- | Return the default label of the SwitchTargets value
switchTargetsDefault :: SwitchTargets -> Maybe Label
switchTargetsDefault (SwitchTargets _ _ mbdef _) = mbdef
-- | Return the range of the SwitchTargets value
switchTargetsRange :: SwitchTargets -> (Integer, Integer)
switchTargetsRange (SwitchTargets _ range _ _) = range
-- | Return whether this is used for a signed value
switchTargetsSigned :: SwitchTargets -> Bool
switchTargetsSigned (SwitchTargets signed _ _ _) = signed
-- | switchTargetsToTable creates a dense jump table, usable for code generation.
-- Returns an offset to add to the value; the list is 0-based on the result.
-- The conversion from Integer to Int is a bit of a wart, but works due to
-- wrap-around arithmetic (as verified by the CmmSwitchTest test case).
switchTargetsToTable :: SwitchTargets -> (Int, [Maybe Label])
switchTargetsToTable (SwitchTargets _ (lo,hi) mbdef branches)
= (fromIntegral (-start), [ labelFor i | i <- [start..hi] ])
where
labelFor i = case M.lookup i branches of Just l -> Just l
Nothing -> mbdef
start | lo >= 0 && lo < minJumpTableOffset = 0 -- See Note [Jump Table Offset]
| otherwise = lo
-- Note [Jump Table Offset]
-- ~~~~~~~~~~~~~~~~~~~~~~~~
--
-- Usually, the code for a jump table starting at x will first subtract x from
-- the value, to avoid a large amount of empty entries. But if x is very small,
-- the extra entries are no worse than the subtraction in terms of code size, and
-- not having to do the subtraction is quicker.
--
-- I.e. instead of
-- _u20N:
-- leaq -1(%r14),%rax
-- jmp *_n20R(,%rax,8)
-- _n20R:
-- .quad _c20p
-- .quad _c20q
-- do
-- _u20N:
-- jmp *_n20Q(,%r14,8)
--
-- _n20Q:
-- .quad 0
-- .quad _c20p
-- .quad _c20q
-- .quad _c20r
-- | The list of all labels occuring in the SwitchTargets value.
switchTargetsToList :: SwitchTargets -> [Label]
switchTargetsToList (SwitchTargets _ _ mbdef branches)
= maybeToList mbdef ++ M.elems branches
-- | Groups cases with equal targets, suitable for pretty-printing to a
-- c-like switch statement with fall-through semantics.
switchTargetsFallThrough :: SwitchTargets -> ([([Integer], Label)], Maybe Label)
switchTargetsFallThrough (SwitchTargets _ _ mbdef branches) = (groups, mbdef)
where
groups = map (\xs -> (map fst xs, snd (head xs))) $
groupBy ((==) `on` snd) $
M.toList branches
-- | Custom equality helper, needed for "CmmCommonBlockElim"
eqSwitchTargetWith :: (Label -> Label -> Bool) -> SwitchTargets -> SwitchTargets -> Bool
eqSwitchTargetWith eq (SwitchTargets signed1 range1 mbdef1 ids1) (SwitchTargets signed2 range2 mbdef2 ids2) =
signed1 == signed2 && range1 == range2 && goMB mbdef1 mbdef2 && goList (M.toList ids1) (M.toList ids2)
where
goMB Nothing Nothing = True
goMB (Just l1) (Just l2) = l1 `eq` l2
goMB _ _ = False
goList [] [] = True
goList ((i1,l1):ls1) ((i2,l2):ls2) = i1 == i2 && l1 `eq` l2 && goList ls1 ls2
goList _ _ = False
-----------------------------------------------------------------------------
-- Code generation for Switches
-- | A SwitchPlan abstractly descries how a Switch statement ought to be
-- implemented. See Note [createSwitchPlan]
data SwitchPlan
= Unconditionally Label
| IfEqual Integer Label SwitchPlan
| IfLT Bool Integer SwitchPlan SwitchPlan
| JumpTable SwitchTargets
deriving Show
--
-- Note [createSwitchPlan]
-- ~~~~~~~~~~~~~~~~~~~~~~~
--
-- A SwitchPlan describes how a Switch statement is to be broken down into
-- smaller pieces suitable for code generation.
--
-- createSwitchPlan creates such a switch plan, in these steps:
-- 1. it splits the switch statement at segments of non-default values that
-- are too large. See splitAtHoles and Note [When to split SwitchTargets]
-- 2. Too small jump tables should be avoided, so we break up smaller pieces
-- in breakTooSmall.
-- 3. We will in the segments between those pieces with a jump to the default
-- label (if there is one), returning a SeparatedList in mkFlatSwitchPlan
-- 4. We find replace two less-than branches by a single equal-to-test in
-- findSingleValues
-- 5. The thus collected pieces are assembled to a balanced binary tree.
type FlatSwitchPlan = SeparatedList Integer SwitchPlan
-- | Does the target support switch out of the box? Then leave this to the
-- target!
targetSupportsSwitch :: HscTarget -> Bool
targetSupportsSwitch HscC = True
targetSupportsSwitch HscLlvm = True
targetSupportsSwitch _ = False
-- | This function creates a SwitchPlan from a SwitchTargets value, breaking it
-- down into smaller pieces suitable for code generation.
createSwitchPlan :: SwitchTargets -> SwitchPlan
createSwitchPlan (SwitchTargets signed mbdef range m) =
-- pprTrace "createSwitchPlan" (text (show ids) $$ text (show (range,m)) $$ text (show pieces) $$ text (show flatPlan) $$ text (show plan)) $
plan
where
pieces = concatMap breakTooSmall $ splitAtHoles maxJumpTableHole m
flatPlan = findSingleValues $ mkFlatSwitchPlan signed range mbdef pieces
plan = buildTree signed $ flatPlan
---
--- Step 1: Splitting at large holes
---
splitAtHoles :: Integer -> M.Map Integer a -> [M.Map Integer a]
splitAtHoles _ m | M.null m = []
splitAtHoles holeSize m = map (\range -> restrictMap range m) nonHoles
where
holes = filter (\(l,h) -> h - l > holeSize) $ zip (M.keys m) (tail (M.keys m))
nonHoles = reassocTuples lo holes hi
(lo,_) = M.findMin m
(hi,_) = M.findMax m
---
--- Step 2: Avoid small jump tables
---
-- We do not want jump tables below a certain size. This breaks them up
-- (into singleton maps, for now).
breakTooSmall :: M.Map Integer a -> [M.Map Integer a]
breakTooSmall m
| M.size m > minJumpTableSize = [m]
| otherwise = [M.singleton k v | (k,v) <- M.toList m]
---
--- Step 3: Fill in the blanks
---
-- A FlatSwitchPlan is a list of SwitchPlans, seperated by a integer dividing the range.
-- So if we have [plan1] n [plan2], then we use plan1 if the expression is <
-- n, and plan2 otherwise.
mkFlatSwitchPlan :: Bool -> Maybe Label -> (Integer, Integer) -> [M.Map Integer Label] -> FlatSwitchPlan
-- If we have no default (i.e. undefined where there is no entry), we can
-- branch at the minimum of each map
mkFlatSwitchPlan _ Nothing _ [] = pprPanic "mkFlatSwitchPlan with nothing left to do" empty
mkFlatSwitchPlan signed Nothing _ (m:ms)
= (mkLeafPlan signed Nothing m , [ (fst (M.findMin m'), mkLeafPlan signed Nothing m') | m' <- ms ])
-- If we have a default, we have to interleave segments that jump
-- to the default between the maps
mkFlatSwitchPlan signed (Just l) r ms = let ((_,p1):ps) = go r ms in (p1, ps)
where
go (lo,hi) []
| lo > hi = []
| otherwise = [(lo, Unconditionally l)]
go (lo,hi) (m:ms)
| lo < min
= (lo, Unconditionally l) : go (min,hi) (m:ms)
| lo == min
= (lo, mkLeafPlan signed (Just l) m) : go (max+1,hi) ms
| otherwise
= pprPanic "mkFlatSwitchPlan" (integer lo <+> integer min)
where
min = fst (M.findMin m)
max = fst (M.findMax m)
mkLeafPlan :: Bool -> Maybe Label -> M.Map Integer Label -> SwitchPlan
mkLeafPlan signed mbdef m
| [(_,l)] <- M.toList m -- singleton map
= Unconditionally l
| otherwise
= JumpTable $ mkSwitchTargets signed (min,max) mbdef m
where
min = fst (M.findMin m)
max = fst (M.findMax m)
---
--- Step 4: Reduce the number of branches using ==
---
-- A seqence of three unconditional jumps, with the outer two pointing to the
-- same value and the bounds off by exactly one can be improved
findSingleValues :: FlatSwitchPlan -> FlatSwitchPlan
findSingleValues (Unconditionally l, (i, Unconditionally l2) : (i', Unconditionally l3) : xs)
| l == l3 && i + 1 == i'
= findSingleValues (IfEqual i l2 (Unconditionally l), xs)
findSingleValues (p, (i,p'):xs)
= (p,i) `consSL` findSingleValues (p', xs)
findSingleValues (p, [])
= (p, [])
---
--- Step 5: Actually build the tree
---
-- Build a balanced tree from a separated list
buildTree :: Bool -> FlatSwitchPlan -> SwitchPlan
buildTree _ (p,[]) = p
buildTree signed sl = IfLT signed m (buildTree signed sl1) (buildTree signed sl2)
where
(sl1, m, sl2) = divideSL sl
--
-- Utility data type: Non-empty lists with extra markers in between each
-- element:
--
type SeparatedList b a = (a, [(b,a)])
consSL :: (a, b) -> SeparatedList b a -> SeparatedList b a
consSL (a, b) (a', xs) = (a, (b,a'):xs)
divideSL :: SeparatedList b a -> (SeparatedList b a, b, SeparatedList b a)
divideSL (_,[]) = error "divideSL: Singleton SeparatedList"
divideSL (p,xs) = ((p, xs1), m, (p', xs2))
where
(xs1, (m,p'):xs2) = splitAt (length xs `div` 2) xs
--
-- Other Utilities
--
restrictMap :: Integral a => (a,a) -> M.Map a b -> M.Map a b
restrictMap (lo,hi) m = mid
where (_, mid_hi) = M.split (lo-1) m
(mid, _) = M.split (hi+1) mid_hi
-- for example: reassocTuples a [(b,c),(d,e)] f == [(a,b),(c,d),(e,f)]
reassocTuples :: a -> [(a,a)] -> a -> [(a,a)]
reassocTuples initial [] last
= [(initial,last)]
reassocTuples initial ((a,b):tuples) last
= (initial,a) : reassocTuples b tuples last
-- Note [CmmSwitch vs. CmmImplementSwitchPlans]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- I (Joachim) separated the two somewhat closely related modules
--
-- - CmmSwitch, which provides the CmmSwitchTargets type and contains the strategy
-- for implementing a Cmm switch (createSwitchPlan), and
-- - CmmImplementSwitchPlans, which contains the actuall Cmm graph modification,
--
-- for these reasons:
--
-- * CmmSwitch is very low in the dependency tree, i.e. does not depend on any
-- GHC specific modules at all (with the exception of Output and Hoople
-- (Literal)). CmmImplementSwitchPlans is the Cmm transformation and hence very
-- high in the dependency tree.
-- * CmmSwitch provides the CmmSwitchTargets data type, which is abstract, but
-- used in CmmNodes.
-- * Because CmmSwitch is low in the dependency tree, the separation allows
-- for more parallelism when building GHC.
-- * The interaction between the modules is very explicit and easy to
-- understand, due to the small and simple interface.
|
urbanslug/ghc
|
compiler/cmm/CmmSwitch.hs
|
bsd-3-clause
| 16,040
| 0
| 15
| 3,366
| 3,001
| 1,680
| 1,321
| 156
| 5
|
module PatIn1 where
--Default parameters can be added to definition of functions and simple constants.
--In this example: add parameter 'x' to 'foo'
foo :: Int
foo = h + t where (h,t) = head $ zip [1..10] [3..15]
main :: Int
main = foo
|
mpickering/HaRe
|
old/testing/addOneParameter/PatIn1.hs
|
bsd-3-clause
| 239
| 0
| 9
| 48
| 63
| 37
| 26
| 5
| 1
|
module Scope2 where
-- import qualified Control.Parallel.Strategies as T
import qualified Control.Parallel.Strategies as S
-- should fail, as there are two possible qualifiers...
f = let n1 = S.runEval (do n1' <- S.rpar n11
return n1')
in n1 + n22
where
n11 = f
n22 = f
|
RefactoringTools/HaRe
|
old/testing/evalAddEvalMon/Scope2.hs
|
bsd-3-clause
| 336
| 0
| 15
| 113
| 73
| 40
| 33
| 7
| 1
|
{-# LANGUAGE TypeInType, ExistentialQuantification #-}
module T16221a where
data SameKind :: k -> k -> *
data T2 a = forall k (b :: k). MkT2 (SameKind a b) !Int
|
sdiehl/ghc
|
testsuite/tests/polykinds/T16221a.hs
|
bsd-3-clause
| 164
| 0
| 8
| 33
| 52
| 31
| 21
| -1
| -1
|
module Main where
import Data.Char
{-# NOINLINE f #-}
f :: Int -> String
f x = "NOT FIRED"
{-# NOINLINE neg #-}
neg :: Int -> Int
neg = negate
{-# RULES
"f" forall (c::Char->Int) (x::Char). f (c x) = "RULE FIRED"
#-}
main = do { print (f (ord 'a')) -- Rule should fire
; print (f (neg 1)) } -- Rule should not fire
|
snoyberg/ghc
|
testsuite/tests/simplCore/should_run/simplrun008.hs
|
bsd-3-clause
| 352
| 0
| 11
| 104
| 89
| 50
| 39
| 12
| 1
|
module Reverse where
-- Sym p q == x:a, y:a<p x> |- { v:a | v = x} <: a<q y>
{- rgo :: (Sym p q) => x:a -> [a<q x>]<q> -> [a<p x>]<p> -> [a]<q> @-}
{-@ rev :: forall <p :: a -> a -> Prop, q :: a -> a -> Prop, q1 :: a -> a -> Prop>.
{x::a, y::a<p x> |- {v:a|v=x} <: a<q y>}
x:a -> [a<p x>]<p> -> [a<q x>]<q> ->[a]<q> @-}
rev :: a -> [a] -> [a] -> [a]
rev z [] a = z:a
rev z (x:xs) (ax:axs) = x : ax : [] -- a -- rev x xs (z:a)
-- x :: p z
-- a ::
|
ssaavedra/liquidhaskell
|
benchmarks/icfp15/todo/Reverse.hs
|
bsd-3-clause
| 464
| 0
| 8
| 138
| 90
| 52
| 38
| 4
| 1
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, ExistentialQuantification #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Exception
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (extended exceptions)
--
-- This module provides support for raising and catching both built-in
-- and user-defined exceptions.
--
-- In addition to exceptions thrown by 'IO' operations, exceptions may
-- be thrown by pure code (imprecise exceptions) or by external events
-- (asynchronous exceptions), but may only be caught in the 'IO' monad.
-- For more details, see:
--
-- * /A semantics for imprecise exceptions/, by Simon Peyton Jones,
-- Alastair Reid, Tony Hoare, Simon Marlow, Fergus Henderson,
-- in /PLDI'99/.
--
-- * /Asynchronous exceptions in Haskell/, by Simon Marlow, Simon Peyton
-- Jones, Andy Moran and John Reppy, in /PLDI'01/.
--
-- * /An Extensible Dynamically-Typed Hierarchy of Exceptions/,
-- by Simon Marlow, in /Haskell '06/.
--
-----------------------------------------------------------------------------
module Control.Exception (
-- * The Exception type
#ifdef __HUGS__
SomeException,
#else
SomeException(..),
#endif
Exception(..), -- class
IOException, -- instance Eq, Ord, Show, Typeable, Exception
ArithException(..), -- instance Eq, Ord, Show, Typeable, Exception
ArrayException(..), -- instance Eq, Ord, Show, Typeable, Exception
AssertionFailed(..),
AsyncException(..), -- instance Eq, Ord, Show, Typeable, Exception
#if __GLASGOW_HASKELL__ || __HUGS__
NonTermination(..),
NestedAtomically(..),
#endif
#ifdef __NHC__
System.ExitCode(), -- instance Exception
#endif
BlockedIndefinitelyOnMVar(..),
BlockedIndefinitelyOnSTM(..),
Deadlock(..),
NoMethodError(..),
PatternMatchFail(..),
RecConError(..),
RecSelError(..),
RecUpdError(..),
ErrorCall(..),
-- * Throwing exceptions
throw,
throwIO,
ioError,
#ifdef __GLASGOW_HASKELL__
throwTo,
#endif
-- * Catching Exceptions
-- $catching
-- ** Catching all exceptions
-- $catchall
-- ** The @catch@ functions
catch,
catches, Handler(..),
catchJust,
-- ** The @handle@ functions
handle,
handleJust,
-- ** The @try@ functions
try,
tryJust,
-- ** The @evaluate@ function
evaluate,
-- ** The @mapException@ function
mapException,
-- * Asynchronous Exceptions
-- $async
-- ** Asynchronous exception control
-- |The following functions allow a thread to control delivery of
-- asynchronous exceptions during a critical region.
mask,
#ifndef __NHC__
mask_,
uninterruptibleMask,
uninterruptibleMask_,
MaskingState(..),
getMaskingState,
allowInterrupt,
#endif
-- ** (deprecated) Asynchronous exception control
block,
unblock,
blocked,
-- *** Applying @mask@ to an exception handler
-- $block_handler
-- *** Interruptible operations
-- $interruptible
-- * Assertions
assert,
-- * Utilities
bracket,
bracket_,
bracketOnError,
finally,
onException,
) where
import Control.Exception.Base
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.IO (unsafeUnmask)
import Data.Maybe
#else
import Prelude hiding (catch)
#endif
#ifdef __NHC__
import System (ExitCode())
#endif
-- | You need this when using 'catches'.
data Handler a = forall e . Exception e => Handler (e -> IO a)
{- |
Sometimes you want to catch two different sorts of exception. You could
do something like
> f = expr `catch` \ (ex :: ArithException) -> handleArith ex
> `catch` \ (ex :: IOException) -> handleIO ex
However, there are a couple of problems with this approach. The first is
that having two exception handlers is inefficient. However, the more
serious issue is that the second exception handler will catch exceptions
in the first, e.g. in the example above, if @handleArith@ throws an
@IOException@ then the second exception handler will catch it.
Instead, we provide a function 'catches', which would be used thus:
> f = expr `catches` [Handler (\ (ex :: ArithException) -> handleArith ex),
> Handler (\ (ex :: IOException) -> handleIO ex)]
-}
catches :: IO a -> [Handler a] -> IO a
catches io handlers = io `catch` catchesHandler handlers
catchesHandler :: [Handler a] -> SomeException -> IO a
catchesHandler handlers e = foldr tryHandler (throw e) handlers
where tryHandler (Handler handler) res
= case fromException e of
Just e' -> handler e'
Nothing -> res
-- -----------------------------------------------------------------------------
-- Catching exceptions
{- $catching
There are several functions for catching and examining
exceptions; all of them may only be used from within the
'IO' monad.
Here's a rule of thumb for deciding which catch-style function to
use:
* If you want to do some cleanup in the event that an exception
is raised, use 'finally', 'bracket' or 'onException'.
* To recover after an exception and do something else, the best
choice is to use one of the 'try' family.
* ... unless you are recovering from an asynchronous exception, in which
case use 'catch' or 'catchJust'.
The difference between using 'try' and 'catch' for recovery is that in
'catch' the handler is inside an implicit 'block' (see \"Asynchronous
Exceptions\") which is important when catching asynchronous
exceptions, but when catching other kinds of exception it is
unnecessary. Furthermore it is possible to accidentally stay inside
the implicit 'block' by tail-calling rather than returning from the
handler, which is why we recommend using 'try' rather than 'catch' for
ordinary exception recovery.
A typical use of 'tryJust' for recovery looks like this:
> do r <- tryJust (guard . isDoesNotExistError) $ getEnv "HOME"
> case r of
> Left e -> ...
> Right home -> ...
-}
-- -----------------------------------------------------------------------------
-- Asynchronous exceptions
-- | When invoked inside 'mask', this function allows a blocked
-- asynchronous exception to be raised, if one exists. It is
-- equivalent to performing an interruptible operation (see
-- #interruptible#), but does not involve any actual blocking.
--
-- When called outside 'mask', or inside 'uninterruptibleMask', this
-- function has no effect.
allowInterrupt :: IO ()
allowInterrupt = unsafeUnmask $ return ()
{- $async
#AsynchronousExceptions# Asynchronous exceptions are so-called because they arise due to
external influences, and can be raised at any point during execution.
'StackOverflow' and 'HeapOverflow' are two examples of
system-generated asynchronous exceptions.
The primary source of asynchronous exceptions, however, is
'throwTo':
> throwTo :: ThreadId -> Exception -> IO ()
'throwTo' (also 'Control.Concurrent.killThread') allows one
running thread to raise an arbitrary exception in another thread. The
exception is therefore asynchronous with respect to the target thread,
which could be doing anything at the time it receives the exception.
Great care should be taken with asynchronous exceptions; it is all too
easy to introduce race conditions by the over zealous use of
'throwTo'.
-}
{- $block_handler
There\'s an implied 'mask' around every exception handler in a call
to one of the 'catch' family of functions. This is because that is
what you want most of the time - it eliminates a common race condition
in starting an exception handler, because there may be no exception
handler on the stack to handle another exception if one arrives
immediately. If asynchronous exceptions are masked on entering the
handler, though, we have time to install a new exception handler
before being interrupted. If this weren\'t the default, one would have
to write something like
> mask $ \restore ->
> catch (restore (...))
> (\e -> handler)
If you need to unblock asynchronous exceptions again in the exception
handler, 'restore' can be used there too.
Note that 'try' and friends /do not/ have a similar default, because
there is no exception handler in this case. Don't use 'try' for
recovering from an asynchronous exception.
-}
{- $interruptible
#interruptible#
Some operations are /interruptible/, which means that they can receive
asynchronous exceptions even in the scope of a 'mask'. Any function
which may itself block is defined as interruptible; this includes
'Control.Concurrent.MVar.takeMVar'
(but not 'Control.Concurrent.MVar.tryTakeMVar'),
and most operations which perform
some I\/O with the outside world. The reason for having
interruptible operations is so that we can write things like
> mask $ \restore -> do
> a <- takeMVar m
> catch (restore (...))
> (\e -> ...)
if the 'Control.Concurrent.MVar.takeMVar' was not interruptible,
then this particular
combination could lead to deadlock, because the thread itself would be
blocked in a state where it can\'t receive any asynchronous exceptions.
With 'Control.Concurrent.MVar.takeMVar' interruptible, however, we can be
safe in the knowledge that the thread can receive exceptions right up
until the point when the 'Control.Concurrent.MVar.takeMVar' succeeds.
Similar arguments apply for other interruptible operations like
'System.IO.openFile'.
It is useful to think of 'mask' not as a way to completely prevent
asynchronous exceptions, but as a way to switch from asynchronous mode
to polling mode. The main difficulty with asynchronous
exceptions is that they normally can occur anywhere, but within a
'mask' an asynchronous exception is only raised by operations that are
interruptible (or call other interruptible operations). In many cases
these operations may themselves raise exceptions, such as I\/O errors,
so the caller will usually be prepared to handle exceptions arising from the
operation anyway. To perfom an explicit poll for asynchronous exceptions
inside 'mask', use 'allowInterrupt'.
Sometimes it is too onerous to handle exceptions in the middle of a
critical piece of stateful code. There are three ways to handle this
kind of situation:
* Use STM. Since a transaction is always either completely executed
or not at all, transactions are a good way to maintain invariants
over state in the presence of asynchronous (and indeed synchronous)
exceptions.
* Use 'mask', and avoid interruptible operations. In order to do
this, we have to know which operations are interruptible. It is
impossible to know for any given library function whether it might
invoke an interruptible operation internally; so instead we give a
list of guaranteed-not-to-be-interruptible operations below.
* Use 'uninterruptibleMask'. This is generally not recommended,
unless you can guarantee that any interruptible operations invoked
during the scope of 'uninterruptibleMask' can only ever block for
a short time. Otherwise, 'uninterruptibleMask' is a good way to
make your program deadlock and be unresponsive to user interrupts.
The following operations are guaranteed not to be interruptible:
* operations on 'IORef' from "Data.IORef"
* STM transactions that do not use 'retry'
* everything from the @Foreign@ modules
* everything from @Control.Exception@
* @tryTakeMVar@, @tryPutMVar@, @isEmptyMVar@
* @takeMVar@ if the @MVar@ is definitely full, and conversely @putMVar@ if the @MVar@ is definitely empty
* @newEmptyMVar@, @newMVar@
* @forkIO@, @forkIOUnmasked@, @myThreadId@
-}
{- $catchall
It is possible to catch all exceptions, by using the type 'SomeException':
> catch f (\e -> ... (e :: SomeException) ...)
HOWEVER, this is normally not what you want to do!
For example, suppose you want to read a file, but if it doesn't exist
then continue as if it contained \"\". You might be tempted to just
catch all exceptions and return \"\" in the handler. However, this has
all sorts of undesirable consequences. For example, if the user
presses control-C at just the right moment then the 'UserInterrupt'
exception will be caught, and the program will continue running under
the belief that the file contains \"\". Similarly, if another thread
tries to kill the thread reading the file then the 'ThreadKilled'
exception will be ignored.
Instead, you should only catch exactly the exceptions that you really
want. In this case, this would likely be more specific than even
\"any IO exception\"; a permissions error would likely also want to be
handled differently. Instead, you would probably want something like:
> e <- tryJust (guard . isDoesNotExistError) (readFile f)
> let str = either (const "") id e
There are occassions when you really do need to catch any sort of
exception. However, in most cases this is just so you can do some
cleaning up; you aren't actually interested in the exception itself.
For example, if you open a file then you want to close it again,
whether processing the file executes normally or throws an exception.
However, in these cases you can use functions like 'bracket', 'finally'
and 'onException', which never actually pass you the exception, but
just call the cleanup functions at the appropriate points.
But sometimes you really do need to catch any exception, and actually
see what the exception is. One example is at the very top-level of a
program, you may wish to catch any exception, print it to a logfile or
the screen, and then exit gracefully. For these cases, you can use
'catch' (or one of the other exception-catching functions) with the
'SomeException' type.
-}
|
abakst/liquidhaskell
|
benchmarks/base-4.5.1.0/Control/Exception.hs
|
bsd-3-clause
| 14,225
| 0
| 10
| 2,959
| 552
| 371
| 181
| 60
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Parser.Expression (
expression
) where
import Core
expression :: SpecWith ()
expression = describe "expr" $ do
-- define some shorthands to save some keystrokes
let parseExpr = parseOnly (fmap bareExpr $ expr >>= unSemiP)
let var = Fix . Variable
let float = Fix . Literal . FloatLit
let str = Fix . Literal . StringLit
let bin o x y = Fix $ BinaryOp o x y
let un o e = Fix $ UnaryOp o e
let conv t f = Fix $ Conversion t f
let intSlice = Fix $ SliceType (Fix $ NamedType "int")
let sel e i = Fix $ Selector e i
let ta e t = Fix $ TypeAssertion e t
it "parses variables" $ do
parseExpr "a" `shouldBe` r (var "a")
it "parses raw literals" $ do
parseExpr "3" `shouldBe` r (int 3)
parseExpr "3.0" `shouldBe` r (float 3.0)
parseExpr "\"Hello, world!\"" `shouldBe` r (str "Hello, world!")
parseExpr "`Hello,\nworld!`" `shouldBe` r (str "Hello,\nworld!")
parseExpr "'a'" `shouldBe` r ((Fix . Literal . RuneLit) 'a')
it "parses selectors" $ do
parseExpr "a.b" `shouldBe` r (sel (var "a") "b")
parseExpr "3.a" `shouldBe` r (sel (int 3) "a")
parseExpr "3..a" `shouldBe` r (sel (float 3.0) "a")
it "parses conversions" $ do
parseExpr "[]int(a)" `shouldBe` r (conv intSlice (var "a"))
it "parses indexing operators" $ do
parseExpr "t[2]" `shouldBe` r (Fix $ Index (var "t") (int 2))
parseExpr "t[a]" `shouldBe` r (Fix $ Index (var "t") (var "a"))
parseExpr "t[f[0]]" `shouldBe` r (Fix $ Index (var "t")
(Fix $ Index (var "f") (int (0))))
it "parses unary minus" $ do
parseExpr "-010" `shouldBe` r (un Negative $ int 8)
parseExpr "-.7" `shouldBe` r (un Negative $ float 0.7)
parseExpr "-\"hello\"" `shouldBe` r (un Negative $ str "hello")
it "parses slices" $ do
parseExpr "a[1:2]" `shouldBe` r
(slice (var "a") (Just $ int 1) (Just $ int 2) Nothing)
parseExpr "a[:1]" `shouldBe` r
(slice (var "a") Nothing (Just $ int 1) Nothing)
parseExpr "a[1:]" `shouldBe` r
(slice (var "a") (Just $ int 1) Nothing Nothing)
parseExpr "a[:]" `shouldBe` r
(slice (var "a") Nothing Nothing Nothing)
parseExpr "a[0:10:2]" `shouldBe` r
(slice (var "a") (Just $ int 0) (Just $ int 10) (Just $ int 2))
parseExpr "a[:10:2]" `shouldBe` r
(slice (var "a") Nothing (Just $ int 10) (Just $ int 2))
parseExpr "a[::2]" `shouldSatisfy` isLeft
parseExpr "a[:2:]" `shouldSatisfy` isLeft
parseExpr "a[::]" `shouldSatisfy` isLeft
it "parses type assertions" $ do
parseExpr "x.([]int)" `shouldBe`
r (typeAssertion (var "x") (intSlice))
it "parses function calls with normal arguments" $ do
parseExpr "a(3, 4, b)"
`shouldBe`
r (call
(var "a")
Nothing
[int 3, int 4, var "b"])
parseExpr "complicatedFunction13()"
`shouldBe`
r (call
(var "complicatedFunction13")
Nothing
[])
parseExpr "a(b(a), c(b), d(c))"
`shouldBe`
r (call (var "a")
Nothing
[ call (var "b") Nothing [var "a"]
, call (var "c") Nothing [var "b"]
, call (var "d") Nothing [var "c"]
])
parseExpr "(3 + 4)(4 / a)"
`shouldBe`
r (call
(bin Plus (int 3) (int 4))
Nothing
[bin Divide (int 4) (var "a")])
it "parses calls chained with other postfix operators" $ do
parseExpr "f(a)(b)(c)"
`shouldBe`
r (call
(call
(call
(var "f")
Nothing
[var "a"])
Nothing
[var "b"])
Nothing
[var "c"])
parseExpr "[]int(a)(1)"
`shouldBe`
r (call (conv intSlice (var "a")) Nothing [int 1])
parseExpr "x.f(2)"
`shouldBe`
r (call (sel (var "x") "f") Nothing [int 2])
parseExpr "fs[0](a)"
`shouldBe`
r (call (index (var "fs") (int 0)) Nothing [var "a"])
parseExpr "fs[1:2](a)"
`shouldBe`
r (call
(slice (var "fs") (Just $ int 1) (Just $ int 2) Nothing)
Nothing [var "a"])
parseExpr "f.([]int)(2)"
`shouldBe`
r (call
(typeAssertion (var "f") intSlice)
Nothing [int 2])
it "parses conversions chained with other postfix operators" $ do
parseExpr "[]int([]float(a))" `shouldBe`
r (conv intSlice
(conv (sliceType (namedType "float"))
(var "a")))
parseExpr "[]int(a.x)" `shouldBe`
r (conv intSlice
(sel (var "a") "x"))
parseExpr "[]int(a[0])" `shouldBe`
r (conv intSlice
(index (var "a") (int 0)))
parseExpr "[]int(a[:])" `shouldBe`
r (conv intSlice
(slice (var "a") Nothing Nothing Nothing))
parseExpr "[]int(a.([]int))" `shouldBe`
r (conv intSlice (ta (var "a") intSlice))
parseExpr "[]int(f())" `shouldBe`
r (conv intSlice
(call (var "f") Nothing []))
it "parses selectors chained with other postfix operators" $ do
parseExpr "[]int(a).x" `shouldBe` -- TODO Check golang
r (sel (conv intSlice (var "a")) "x")
parseExpr "a.x.y" `shouldBe` r (sel (sel (var "a") "x") "y")
parseExpr "a[0].x" `shouldBe` r (sel (index (var "a") (int 0)) "x")
parseExpr "a[:].x" `shouldBe`
r (sel (slice (var "a") Nothing Nothing Nothing) "x")
parseExpr "a.([]int).x" `shouldBe` -- TODO Check golang
r (sel (ta (var "a") intSlice) "x")
parseExpr "f().x" `shouldBe` r (sel (call (var "f") Nothing []) "x")
it "parses indices chained with other postfix operators" $ do
parseExpr "[]int(a)[0]" `shouldBe`
r (index (conv intSlice (var "a")) (int 0))
parseExpr "a.x[0]" `shouldBe` r (index (sel (var "a") "x") (int 0))
parseExpr "a[0][1]" `shouldBe`
r (index (index (var "a") (int 0)) (int 1))
parseExpr "a[:][0]" `shouldBe`
r (index (slice (var "a") Nothing Nothing Nothing) (int 0))
parseExpr "a.([]int)[0]" `shouldBe`
r (index (ta (var "a") intSlice) (int 0))
parseExpr "f()[0]" `shouldBe` r (index (call (var "f") Nothing []) (int 0))
it "parses slices chained with other postfix operators" $ do
parseExpr "[]int(a)[:]" `shouldBe`
r (slice (conv intSlice (var "a")) Nothing Nothing Nothing)
parseExpr "a.x[:]" `shouldBe`
r (slice (sel (var "a") "x") Nothing Nothing Nothing)
parseExpr "a[0][:]" `shouldBe`
r (slice (index (var "a") (int 0)) Nothing Nothing Nothing)
parseExpr "a.([]int)[:]" `shouldBe`
r (slice (ta (var "a") intSlice) Nothing Nothing Nothing)
parseExpr "f()[:]" `shouldBe`
r (slice (call (var "f") Nothing []) Nothing Nothing Nothing)
it "parses type assertions chained with other postfix operators" $ do
parseExpr "[]int(a).([]int)" `shouldBe`
r (ta (conv intSlice (var ("a"))) intSlice)
parseExpr "a.x.([]int)" `shouldBe` r (ta (sel (var "a") "x") intSlice)
parseExpr "a[0].([]int)" `shouldBe`
r (ta (index (var "a") (int 0)) intSlice)
parseExpr "a.([]int).([]int)" `shouldBe`
r (ta (ta (var ("a")) intSlice) intSlice)
parseExpr "f().([]int)" `shouldBe`
r (ta (call (var "f") Nothing []) intSlice)
-- Fred: disabled for now, it generates quite a lot of errors.
{- prop "parses all kinds of valid expressions" $ do
forAll exprGen $
\e -> parseOnly (fmap bareExpr $ expr >>= unSemiP)
(renderGoLite $ pretty e) `shouldBe` Right e -}
|
djeik/goto
|
test/Parser/Expression.hs
|
mit
| 8,371
| 0
| 21
| 2,928
| 2,985
| 1,442
| 1,543
| 177
| 1
|
{-# LANGUAGE OverloadedStrings #-}
---------------------------------------------------------------
--
-- Module: Quark.Buffer
-- Author: Stefan Peterson
-- License: MIT License
--
-- Maintainer: Stefan Peterson (stefan.j.peterson@gmail.com)
-- Stability: Stable
-- Portability: Portable
--
-- ----------------------------------------------------------
--
-- Module for quark buffers.
--
---------------------------------------------------------------
module Quark.Buffer ( Buffer ( Buffer
, LockedBuffer )
, ExtendedBuffer
, ebEmpty
, ebContents
, ebSelection
, ebCursors
, ebNew
, ebFirst
, setPath
, path
, offset
, setOffset
, language
, tabToSpaces
, tokens
, bracketPair
, writeProtected
, condense
, editHistory
, cursor
, selectionCursor
, input
, insert
, nlAutoIndent
, paste
, tab
, unTab
, delete
, backspace
, selection
, undo
, redo
, moveCursor
, moveCursorN
, selectMoveCursor
, endOfLine
, startOfLine
, endOfFile
, startOfFile
, selectAll
, deselect
, ebUnsaved
, bufferFind ) where
import Data.Bifunctor ( second )
import qualified Data.Text as T
import Quark.Types ( Cursor
, Direction ( Backward
, Forward )
, BracketType ( OpeningBracket
, ClosingBracket )
, Index
, Selection
, Language
, Token
, Offset )
import Quark.Settings ( tabWidth
, tabToSpacesDefault )
import Quark.History ( Edit ( Edit
, IndentLine
, EditGroup )
, EditHistory
, doEdit
, undoEdit'
, editIndex
, editSelection
, emptyEditHistory
, addEditToHistory
, undoEdit
, redoEdit )
import Quark.Cursor ( move
, distance
, ixToCursor
, cursorToIx )
import Quark.Lexer.Core ( tokenLines )
import Quark.Lexer.Language ( tokenize )
import Quark.Helpers ( lnIndent
, lnIndent'
, tabbedLength
, findIx
, xnor
, orderTwo )
-- The Buffer data type
data Buffer = LockedBuffer String
| Buffer { contents :: T.Text
, editHistory :: EditHistory
, cursor :: Cursor
, selectionCursor :: Cursor } deriving (Eq, Show)
data BufferMetaData = BufferMetaData { path' :: FilePath
, language' :: Language
, tokenLines' :: [[Token]]
, offset' :: Offset
, writeProtected' :: Bool
, tabToSpaces' :: Bool } deriving Eq
type ExtendedBuffer = (Buffer, BufferMetaData)
-- Some functions that should eventually be replaced with lenses
language :: ExtendedBuffer -> Language
language (_, bufferMetaData) = language' bufferMetaData
writeProtected :: ExtendedBuffer -> Bool
writeProtected (_, bufferMetaData) = writeProtected' bufferMetaData
path :: ExtendedBuffer -> FilePath
path (_, bufferMetaData) = path' bufferMetaData
tabToSpaces :: ExtendedBuffer -> Bool
tabToSpaces (_, bufferMetaData) = tabToSpaces' bufferMetaData
setPath :: FilePath -> ExtendedBuffer -> ExtendedBuffer
setPath path'' b =
second (\bufferMetaData -> bufferMetaData {path' = path''}) b
setTokenLines' :: [[Token]] -> BufferMetaData -> BufferMetaData
setTokenLines' tokenLines'' bufferMetaData =
bufferMetaData {tokenLines' = tokenLines''}
offset :: ExtendedBuffer -> Offset
offset (_, bufferMetaData) = offset' bufferMetaData
setOffset :: Offset -> ExtendedBuffer -> ExtendedBuffer
setOffset offset'' b =
second (\bufferMetaData -> bufferMetaData {offset' = offset''}) b
tokens :: ExtendedBuffer -> [[Token]]
tokens (_, bufferMetaData) = tokenLines' bufferMetaData
bracketPair :: ExtendedBuffer -> [Cursor]
bracketPair (b, _) = bracketPair' b
ebContents :: ExtendedBuffer -> T.Text
ebContents (b, _) = contents b
-- Basic buffer functions
emptyBuffer :: Buffer
emptyBuffer = Buffer "" emptyEditHistory (0, 0) (0, 0)
newBuffer :: T.Text -> Buffer
newBuffer bufferContents = Buffer bufferContents emptyEditHistory (0,0) (0,0)
unsaved :: Buffer -> Bool
unsaved (Buffer _ (k, _, _) _ _) = case k of
0 -> False
_ -> True
unsaved _ = False
input :: Char -> Bool -> Buffer -> Buffer
input c m = insert (T.cons c "") m True
paste :: T.Text -> Buffer -> Buffer
paste s = insert s False False
tab' :: Bool -> Buffer -> Buffer
tab' tabToSpaces'' b@(Buffer s h crs@(r, c) sel@(rr, cc))
| crs == sel =
if tabToSpaces''
then (insert (T.replicate n $ T.singleton ' ') False True) b
else (insert "\t" False True) b
| otherwise = Buffer newS newH (r, c + n0) (rr, cc + n0)
where
n = tabWidth - (mod c tabWidth)
newH = addEditToHistory tabEdit h
tabEdit = EditGroup [ IndentLine r' n0 c' 0 0
| r' <- [r0..r1] ] ix sel'
(ix, sel') = ixAndSel b
c' = if tabToSpaces'' then ' ' else '\t'
n0 = tabWidth - mod (lnIndent ' ' r0 s) tabWidth
r0 = min r rr
r1 = max r rr
newS = doEdit tabEdit s
tab' _ b = b
unTab' :: Bool -> Buffer -> Buffer
unTab' tabToSpaces'' b@(Buffer s h (r, c) (rr, cc))
| all (== 0) n = b
| otherwise = Buffer newS newH (r, c + cAdd r) (rr, cc + cAdd rr)
where
newH = addEditToHistory unTabEdit h
unTabEdit = EditGroup [ IndentLine r' n' c' 0 0
| (r', n') <- zip [r0..r1] n ] ix sel
(ix, sel) = ixAndSel b
c' = if tabToSpaces'' then ' ' else '\t'
r0 = min r rr
r1 = max r rr
n = [ unTabWidth r' | r' <- [r0..r1] ]
cAdd r'' = if tabToSpaces'' then unTabWidth r''
else tabWidth * unTabWidth r''
unTabWidth r'' = if thisIndent == 0
then 0
else if tabToSpaces''
then (-tabWidth) + mod (-thisIndent) tabWidth
else (-1)
where
thisIndent = lnIndent c' r'' s
newS = doEdit unTabEdit s
unTab' _ b = b
nlAutoIndent :: Buffer -> Buffer
nlAutoIndent b@(Buffer s _ crs sel) =
insert (T.cons '\n' $ lnIndent' r s) False True b
where
(r, _) = min crs sel
nlAutoIndent b = b
ixAndSel :: Buffer -> (Index, Selection)
ixAndSel (Buffer s _ crs sel) = ((cursorToIx crs s), (distance crs sel s))
ixAndSel _ = (0, 0)
-- Generic insert string at current selection
insert :: T.Text -> Bool -> Bool -> Buffer -> Buffer
insert s m fusible b@(Buffer s0 h crs sel) = Buffer newS newH newCrs newCrs
where
newH = addEditToHistory edit h
edit = Edit (0, 0) s ix sel' fusible $ selection b
(ix, sel'') = ixAndSel b
sel' = if m && sel'' == 0 && doInsert then 1 else sel''
doInsert = if T.take 1 s0' == "\n" then False else True
(_, s0') = T.splitAt ix s0
newCrs = ixToCursor newIx newS
newIx = (cursorToIx (min crs sel) s0) + (T.length s)
newS = doEdit edit s0
insert _ _ _ b = b
-- Delete
delete :: Buffer -> Buffer
delete = genericDelete 0
-- Backspace
backspace :: Buffer -> Buffer
backspace = genericDelete 1
-- Generic forward or backward deletion (not exported)
genericDelete :: Int -> Buffer -> Buffer
genericDelete d (Buffer s h crs sel) = Buffer newS newH newCrs newCrs
where
newH = addEditToHistory edit h
newCrs = if c0 && d == 1 then move Backward s crs
else (\(x, _) -> x) $ orderTwo crs sel
edit = Edit (n, m) "" (cursorToIx crs s) (distance crs sel s) True delS
(n, m) = if c0 then (d, 1 - d) else (0, 0)
c0 = (distance crs sel s) == 0
delS = T.take (l + n + m) $ T.drop (k - n) s
l = abs $ distance crs sel s
k = cursorToIx (min crs sel) s
newS = doEdit edit s
genericDelete _ b = b
-- Copy selection
selection :: Buffer -> T.Text
selection (Buffer s _ crs sel) = T.take l $ T.drop k s
where
l = abs $ distance crs sel s
k = cursorToIx (min crs sel) s
selection _ = ""
-- Perform undo on buffer, moving cursor to the beginning of the undone edit
undo :: Buffer -> Buffer
undo buffer@(Buffer s h@(_, past, _) crs sel) = case past of
(x:_) -> alignCursor True $ Buffer newS (undoEdit h) crs sel
where
newS = undoEdit' x s
_ -> buffer
undo b = b
-- Perform redo on buffer, moving cursor to the end of the redone edit
redo :: Buffer -> Buffer
redo buffer@(Buffer s h@(_, _, future) crs sel) = case future of
(x:_) -> alignCursor False $ Buffer newS (redoEdit h) crs sel
where
newS = doEdit x s
_ -> buffer
redo b = b
alignCursor :: Bool -> Buffer -> Buffer
alignCursor True (Buffer s h@(_, _, y:_) _ _) = Buffer s h newCrs newSel
where
newCrs = ixToCursor (editIndex y) s
newSel = ixToCursor (editIndex y + editSelection y) s
alignCursor False (Buffer s h@(_, x:_, _) crs sel) =
Buffer s h newCrs newSel
where
newCrs = case x of
(Edit (n, _) s' ix sel' _ _) ->
ixToCursor (ix - n + T.length s' + sel') s
(IndentLine _ n ' ' ix _) -> ixToCursor (ix + n) s
_ -> crs
newSel = case x of
(Edit _ _ _ _ _ _) -> newCrs
(IndentLine _ n ' ' ix sel') -> ixToCursor (ix + sel' + n) s
_ -> sel
alignCursor _ b = b
-- End and Home functions
endOfLine :: Bool -> Buffer -> Buffer
endOfLine moveSel (Buffer s h (r, _) sel) = Buffer s h newCrs newSel
where
newCrs = case drop r $ T.lines s of (x:_) -> (r, tabbedLength tabWidth x)
_ -> ixToCursor (T.length s - 1) s
newSel = case moveSel of True -> newCrs
False -> sel
endOfLine _ b = b
startOfLine :: Bool -> Buffer -> Buffer
startOfLine moveSel (Buffer s h (r, c) sel) = Buffer s h (r, newC) newSel
where
newC = if c == c' then 0 else c'
c' = T.length $ lnIndent' r s
newSel = case moveSel of True -> (r, newC)
False -> sel
startOfLine _ b = b
endOfFile :: Bool -> Buffer -> Buffer
endOfFile moveSel (Buffer s h _ sel) = Buffer s h newCrs newSel
where
newCrs = ixToCursor (T.length s) s
newSel = case moveSel of True -> newCrs
False -> sel
endOfFile _ b = b
startOfFile :: Bool -> Buffer -> Buffer
startOfFile moveSel (Buffer s h _ sel) = Buffer s h (0, 0) newSel
where
newSel = case moveSel of True -> (0, 0)
False -> sel
startOfFile _ b = b
selectAll :: Buffer -> Buffer
selectAll (Buffer s h _ _) = Buffer s h (0, 0) $ ixToCursor (T.length s) s
selectAll b = b
deselect :: Buffer -> Buffer
deselect (Buffer s h crs _) = Buffer s h crs crs
deselect b = b
-- Move the cursor one step, set selection cursor to same
moveCursor :: Direction -> Buffer -> Buffer
moveCursor = moveCursorN 1
moveCursorN :: Int -> Direction -> Buffer -> Buffer
moveCursorN = genericMoveCursor True
-- Move the cursor, keeping selection cursor in place
selectMoveCursor :: Direction -> Buffer -> Buffer
selectMoveCursor = genericMoveCursor False 1
-- Generic move cursor (not exported)
genericMoveCursor :: Bool -> Int -> Direction -> Buffer -> Buffer
genericMoveCursor moveSel n d (Buffer s h crs sel)
| n == 1 = Buffer s h newCrs newSel
| otherwise = genericMoveCursor moveSel (n - 1) d (Buffer s h newCrs newSel)
where
newCrs
| moveSel == False = move d s crs
| crs == sel = move d s crs
| d == Backward = minCrs
| d == Forward = maxCrs
| otherwise = move d s crs
newSel = case moveSel of
True -> newCrs
False -> sel
(minCrs, maxCrs) = orderTwo crs sel
genericMoveCursor _ _ _ b = b
bufferFind :: Bool -> Bool -> T.Text -> Buffer -> Buffer
bufferFind next doStep findString b@(Buffer s h crs _) =
Buffer s h foundCrs foundSel
where
foundIx = findIx k next findString s
foundCrs = ixToCursor foundIx s
foundSel = ixToCursor (foundIx + T.length findString) s
k = (cursorToIx crs s) + ixStep
ixStep = if (selection b == findString) && (xnor next doStep) then 1 else 0
bufferFind _ _ _ b = b
bracketPair' :: Buffer -> [Cursor]
bracketPair' buffer@(Buffer s _ crs _) = case bracketAtCursor buffer of
Just (OpeningBracket b) -> case closingBracket b of
Just crs' -> [crs, crs']
Nothing -> []
Just (ClosingBracket b) -> case openingBracket b of
Just crs' -> [crs', crs]
Nothing -> []
_ -> []
where
closingBracket b =
(\x -> ixToCursor (k + x) s) <$> (otherBracket s' b (antiB b) 1 1)
openingBracket b =
(\x -> ixToCursor (k - x) s) <$> (otherBracket s'' b (antiB b) 1 1)
antiB b = case b of
'(' -> ')'
'[' -> ']'
'{' -> '}'
')' -> '('
']' -> '['
'}' -> '{'
k = cursorToIx crs s
s' = T.drop (k + 1) s
s'' = T.reverse $ T.take k s
otherBracket :: T.Text -> Char -> Char -> Int -> Int -> Maybe Int
otherBracket _ _ _ 0 k = Just (k - 1)
otherBracket s b antiB count k = case T.uncons s of
Just (c, s') -> otherBracket s' b antiB (newCount c) (k + 1)
Nothing -> Nothing
where
newCount c'
| c' == b = count + 1
| c' == antiB = count - 1
| otherwise = count
bracketAtCursor :: Buffer -> Maybe BracketType
bracketAtCursor (Buffer s _ crs _)
| k >= T.length s = Nothing
| elem c ['(', '{', '['] = Just (OpeningBracket c)
| elem c [')', '}', ']'] = Just (ClosingBracket c)
| otherwise = Nothing
where
k = cursorToIx crs s
c = T.head $ T.drop k s
-- Basic functions for extended buffers
ebEmpty :: FilePath -> Language -> ExtendedBuffer
ebEmpty p l =
( emptyBuffer
, BufferMetaData { path' = p'
, language' = l'
, tokenLines' = []
, offset' = (0, 0)
, writeProtected' = False
, tabToSpaces' = tabToSpacesDefault } )
where
p' = if p == "" then "Untitled" else p
l' = if l == "" then "Unknown" else l
-- TODO: convert to Buffer -> (Index, Selection)
ebSelection :: ExtendedBuffer -> (Index, Selection)
ebSelection ((Buffer s _ crs sel), _) =
(cursorToIx selectionStart s, distance selectionStart selectionEnd s)
where
(selectionStart, selectionEnd) = orderTwo crs sel
ebSelection _ = (0, 0)
ebNew :: FilePath -> T.Text -> Language -> ExtendedBuffer
ebNew path'' fileContents language'' =
( newBuffer fileContents
, BufferMetaData { path' = path''
, language' = language''
, tokenLines' = tokenLines''
, offset' = (0, 0)
, writeProtected' = False
, tabToSpaces' = tabToSpaces'' })
where
tokenLines'' = tokenLines $ tokenize language'' fileContents
tabToSpaces'' = if (T.isInfixOf (T.singleton '\t') fileContents)
then False
else tabToSpacesDefault
-- TODO: convert to Buffer -> (Cursor, Cursor)
ebCursors :: ExtendedBuffer -> (Cursor, Cursor)
ebCursors ((Buffer _ _ crs sel), _) = (crs, sel)
ebCursors _ = ((0, 0), (0, 0))
ebFirst :: (Buffer -> Buffer) -> ExtendedBuffer -> ExtendedBuffer
ebFirst f (b, bufferMetaData) = (b', bufferMetaData')
where
b' = f b
bufferMetaData' = if editHistory b' == editHistory b
then bufferMetaData
else setTokenLines' tokenLines'' bufferMetaData
tokenLines'' = tokenLines $ tokenize (language' bufferMetaData') s'
s' = contents b'
condense :: ExtendedBuffer -> Buffer
condense (b, _) = b
ebUnsaved :: ExtendedBuffer -> Bool
ebUnsaved = unsaved . condense
tab :: ExtendedBuffer -> ExtendedBuffer
tab (b, bufferMetaData) = (newB, newBufferMetaData)
where
newB = tab' (tabToSpaces' bufferMetaData) b
newBufferMetaData = setTokenLines' tokenLines'' bufferMetaData
tokenLines'' = tokenLines $ tokenize (language' bufferMetaData) s
s = contents newB
unTab :: ExtendedBuffer -> ExtendedBuffer
unTab (b, bufferMetaData) = (newB, newBufferMetaData)
where
newB = unTab' (tabToSpaces' bufferMetaData) b
newBufferMetaData = setTokenLines' tokenLines'' bufferMetaData
tokenLines'' = tokenLines $ tokenize (language' bufferMetaData) s
s = contents newB
|
sjpet/quark
|
src/Quark/Buffer.hs
|
mit
| 17,803
| 0
| 15
| 6,271
| 5,536
| 2,971
| 2,565
| 403
| 10
|
module Systat.Module.DateTime (dateTime) where
import Systat.Module
dateTime :: Module
dateTime = Module {
name = "datetime"
, prefix = "🕐: "
, command = "date"
, args = ["+%d/%m %H:%M:%S"]
, parse = \x -> return (Neutral, x)
}
|
mfaerevaag/systat
|
src/Systat/Module/DateTime.hs
|
mit
| 244
| 0
| 9
| 52
| 76
| 48
| 28
| 9
| 1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Data.Vector.Generic.Sized
-- Description : Type-indexed vectors
-- Copyright : (C) 2015 Nicolas Trangez
-- License : MIT (see the file LICENSE)
-- Maintainer : Nicolas Trangez <ikke@nicolast.be>
-- Stability : experimental
--
-- This module implements type-indexed fixed-size generic vectors and related
-- utility functions.
module Data.Vector.Generic.Sized (
Vector, SVector, UVector
, fromVector
, toVector
, length
, Bounded(..)
, index
, unsafeWith
, generate
, replicateM
) where
import Prelude hiding (Bounded, length)
import qualified Prelude
import Data.Maybe (fromMaybe)
#if !MIN_VERSION_base(4, 8, 0)
import Data.Monoid (mconcat)
#endif
import Data.Proxy
import Data.Typeable
import Data.Word
import Foreign.Ptr (Ptr)
import GHC.Exts (IsList(..))
import GHC.TypeLits
import qualified Data.Vector.Generic as V
import qualified Data.Vector.Storable as SV
import qualified Data.Vector.Unboxed as UV
-- | Length-indexed generic vectors.
newtype Vector v (n :: Nat) a = Vector (v a)
deriving (Show, Eq, Ord, Typeable)
instance (V.Vector v a, KnownNat n) => IsList (Vector v n a) where
type Item (Vector v n a) = a
fromList l = fromMaybe exc $ fromVector $ V.fromList l
where
exc = error $ mconcat [ "fromList: Size mismatch, "
, show (Prelude.length l)
, " /= "
, show (natVal (Proxy :: Proxy n))
]
{-# INLINE fromList #-}
fromListN n l =
if n == fromInteger (natVal (Proxy :: Proxy n))
then Vector (V.fromListN n l)
else error $ mconcat [ "fromListN: Size mismatch, "
, show n
, " /= "
, show (natVal (Proxy :: Proxy n))
]
{-# INLINE fromListN #-}
toList (Vector v) = V.toList v
{-# INLINE toList #-}
-- | Type-indexed storable 'Data.Vector.Storable.Vector's.
type SVector n a = Vector SV.Vector n a
-- | Type-indexed unboxed 'Data.Vector.Unboxed.Vector's.
type UVector n a = Vector UV.Vector n a
-- | Turn a plain vector into a type-indexed 'Vector'.
--
-- If the length of the given vector doesn't match, 'Nothing' is returned.
--
-- O(1).
fromVector :: forall n v a. (KnownNat n, V.Vector v a)
=> v a -- ^ Plain vector
-> Maybe (Vector v n a)
fromVector v =
if V.length v == fromInteger (natVal (Proxy :: Proxy n))
then Just (Vector v)
else Nothing
{-# INLINE fromVector #-}
-- | Turn a type-indexed 'Vector' into a plain vector.
--
-- O(1).
toVector :: Vector v n a -> v a
toVector (Vector v) = v
{-# INLINE toVector #-}
-- | Retrieve the length of a type-indexed 'Vector'.
--
-- This is non-strict in the argument: the length calculation is
-- a compile-time operation based on the type of the 'Vector'.
--
-- O(0).
length :: forall n v a. KnownNat n => Vector v n a -> Word
length _ = fromInteger $ natVal (Proxy :: Proxy n)
{-# INLINE length #-}
-- | Type-level ('Nat') bounds of values of a type.
class (MinBound t <= MaxBound t) => Bounded t where
type MinBound t :: Nat
type MaxBound t :: Nat
instance Bounded Word8 where
type MinBound Word8 = 0
type MaxBound Word8 = 255
type a < b = CmpNat a b ~ 'LT
type a >= b = b <= a
-- | Safe indexing.
--
-- This function allows unchecked indexing into a 'Vector' whose length
-- must match at least the bounds of the given index type.
--
-- Assuming a correct 'Bounded' instance for 't', the lookup can never be
-- out-of-bounds, by construction.
--
-- O(1).
index :: (KnownNat n, MinBound t >= 0, MaxBound t < n, V.Vector v a, Integral t)
=> Vector v n a
-> t -- ^ Index
-> a
index (Vector v) !t = V.unsafeIndex v $ fromIntegral t
{-# INLINE index #-}
-- | Retrieve a pointer to a sized 'Data.Vector.Storable.Vector'.
--
-- See 'Data.Vector.Storable.unsafeWith'.
unsafeWith :: SV.Storable a => SVector n a -> (Ptr a -> IO b) -> IO b
unsafeWith (Vector v) = SV.unsafeWith v
{-# INLINE unsafeWith #-}
-- | Construct a sized 'Vector' by applying the function to each index.
--
-- O(n).
generate :: forall n v a. (V.Vector v a, KnownNat n) => (Int -> a) -> Vector v n a
generate = Vector . V.generate (fromInteger $ natVal (Proxy :: Proxy n))
{-# INLINE generate #-}
-- | Execute the monadic action to fill a new sized 'Vector'.
--
-- O(n).
replicateM :: forall m n v a. (Functor m, Monad m, V.Vector v a, KnownNat n) => m a -> m (Vector v n a)
replicateM = fmap Vector . V.replicateM (fromInteger $ natVal (Proxy :: Proxy n))
{-# INLINE replicateM #-}
|
NicolasT/reedsolomon
|
src/Data/Vector/Generic/Sized.hs
|
mit
| 5,002
| 0
| 15
| 1,237
| 1,177
| 668
| 509
| -1
| -1
|
module Source
(
Source,
create,
table
)
where
import Table (Table)
import qualified Table
data Source =
Source Table
deriving (Eq, Ord, Show)
create :: Table -> Source
create t = Source t
table :: Source -> Table
table (Source t) = t
|
rcook/hqdsl
|
src/lib/Source.hs
|
mit
| 249
| 0
| 7
| 58
| 94
| 53
| 41
| 14
| 1
|
nodes1 = [[3]
,[7, 4]
,[2, 4, 6]
,[8, 5, 9, 3]]
nodes2 = [[75]
,[95, 64]
,[17, 47, 82]
,[18, 35, 87, 10]
,[20, 04, 82, 47, 65]
,[19, 01, 23, 75, 03, 34]
,[88, 02, 77, 73, 07, 63, 67]
,[99, 65, 04, 28, 06, 16, 70, 92]
,[41, 41, 26, 56, 83, 40, 80, 70, 33]
,[41, 48, 72, 33, 47, 32, 37, 16, 94, 29]
,[53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14]
,[70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57]
,[91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48]
,[63, 66, 04, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31]
,[04, 62, 98, 27, 23, 09, 70, 98, 73, 93, 38, 53, 60, 04, 23]]
euler :: [[Int]] -> [Int]
euler = foldl update []
where
update :: [Int] -> [Int] -> [Int]
update acc row = zipWith (+) row acc'''
where
acc' = 0:acc
acc'' = acc ++ [0]
acc''' = zipWith max acc' acc''
main = do
print $ maximum $ euler nodes1
print $ maximum $ euler nodes2
|
dpieroux/euler
|
0/0018.hs
|
mit
| 1,045
| 0
| 10
| 395
| 599
| 379
| 220
| 29
| 1
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
-----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (c) 2015, Jakub Dominik Kozlowski
-- License : MIT
--
-- Maintainer : mail@jakub-kozlowski.com
--
-- Main for the bot.
-----------------------------------------------------------------------------
module Main where
import BookSlot
import Control.Exception (SomeException (..))
import Control.Lens
import Control.Monad
import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow,
catch, onException, throwM)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Logger
import Control.Retry (RetryPolicyM (..), constantDelay,
getRetryPolicyM, limitRetries,
recoverAll)
import qualified Data.ByteString.Char8 as S8
import Data.Char (toLower)
import Data.List (concatMap)
import Data.List.Lens
import qualified Data.Map.Strict as Map
import Data.Monoid ((<>))
import Data.Text (Text, pack)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Encoding.Error as T
import qualified Data.Text.IO as T
import qualified Data.Time.Calendar as Time
import qualified Data.Time.Calendar.WeekDate as Time
import qualified Data.Time.Clock as Time
import qualified Data.Time.Format as Time
import qualified Data.Time.LocalTime as Time
import GHC.Stack (whoCreated)
import Language.Haskell.TH.Syntax
import Network.Better.Session
import Network.Better.Types
import qualified Network.Wreq.Session as S
import Options.Applicative (execParser)
import System.Exit (exitFailure, exitSuccess)
import System.IO (Handle, stdout)
import System.Log.FastLogger (fromLogStr)
import qualified Text.Show.Pretty as Pretty
import Types (BookingConfig, Config, DayOfWeek,
Opts (..), bookingConfig,
bookingConfigConfig,
bookingConfigSlots, configEmail,
configPassword,
dayOfWeekFromUTCTime,
optionsConfigFile, optsParserInfo,
readConfig, _Password, _Slots)
main :: IO ()
main = execParser optsParserInfo >>= \opts -> do
maybeConfig <- readConfig (opts ^. optionsConfigFile)
case maybeConfig of
Left e -> exitWithError e
Right c -> runAppLogging $ do
$(logInfo) $ "Running with opts: " <> (pack . show $ opts)
$(logInfo) $ "Running with config: " <> (pack . Pretty.ppShow $ c)
case opts of
Opts (Just date) _ _ -> withParticularDay c date
Opts Nothing _ _ -> withCurrentTime c
withCurrentTime :: (MonadCatch m, MonadMask m, MonadLoggerIO m)
=> [BookingConfig]
-> m ()
withCurrentTime c = do
currentTime <- liftIO Time.getCurrentTime
let currentDay = Time.utctDay currentTime
let sameDayNextWeek = Time.addDays 7 currentDay
let dayOfWeek = dayOfWeekFromUTCTime currentDay
let sameDayNextWeekDayOfWeek = dayOfWeekFromUTCTime sameDayNextWeek
$(logInfo) $ "Today is " <> (pack . Time.showGregorian $ currentDay)
$(logInfo) $ "Next week is " <> (pack . Time.showGregorian $ sameDayNextWeek)
$(logInfo) $ "Day of week is " <> (pack . show $ dayOfWeek)
when (dayOfWeek /= sameDayNextWeekDayOfWeek) $
exitWithError ("Day of week for today (" <>
show dayOfWeek <> ") " <>
"is not the same as day of week for next week (" <>
show sameDayNextWeekDayOfWeek <> ")")
withParticularDay c sameDayNextWeek
withParticularDay :: (MonadCatch m, MonadMask m, MonadLoggerIO m)
=> [BookingConfig] -> Time.Day -> m ()
withParticularDay c currentDay = do
let dayOfWeek = dayOfWeekFromUTCTime currentDay
let slots = findSlots dayOfWeek c
when (null slots) $ do
$(logInfo) $ "No slots found for " <> (pack . show $ dayOfWeek)
liftIO exitSuccess
$(logInfo) $ "Found slots " <> (pack . Pretty.ppShow $ slots)
retry $ forM_ slots $ \(c, slot) -> do
let email = c ^. configEmail
let pass = c ^. configPassword . _Password
s <- createSession email pass
bookActivity s c currentDay slot
`catch` \e@SomeException {} ->
do stack <- unlines <$> liftIO (whoCreated e)
$(logError) $ "Could not book: " <> T.pack (show e) <> "\n" <> T.pack stack
throwM e
findSlots :: DayOfWeek -> [BookingConfig] -> [(Config, Text)]
findSlots day = concatMap go
where go bc = case Map.lookup day (bc ^. bookingConfigSlots . _Slots) of
Just slot -> [(bc ^. bookingConfigConfig, slot)]
Nothing -> []
-- retries
retry :: (MonadIO m, MonadMask m) => m a -> m a
retry m = recoverAll (retryUpToTime (Time.TimeOfDay 22 2 0) $ constantDelay delayMicros) (const m)
where delayMicros = 2 * microsInSeconds
microsInSeconds = 1000000
-- TODO: Take the timeout time as param
retryUpToTime :: MonadIO m => Time.TimeOfDay -> RetryPolicyM m -> RetryPolicyM m
retryUpToTime timeout (RetryPolicyM p) = RetryPolicyM $ \rs -> do
currentDateTime <- liftIO Time.getCurrentTime
let time = Time.utctDayTime currentDateTime
shouldTimeout = Time.timeToTimeOfDay time > timeout
if shouldTimeout
then return Nothing
else p rs
-- Logging setup
runAppLogging :: MonadIO m => LoggingT m a -> m a
runAppLogging = (`runLoggingT` loggerFunc)
-- | Logging function takes the log level into account - stolen from stack.
loggerFunc :: (MonadIO m, ToLogStr msg)
=> Loc -> Text -> LogLevel -> msg -> m ()
loggerFunc loc _src level msg =
liftIO (getOutput >>= T.hPutStrLn outputChannel)
where outputChannel = stdout
getOutput =
do date <- getDate
l <- getLevel
lc <- getLoc
return (T.pack date <> T.pack l <> T.decodeUtf8 (fromLogStr (toLogStr msg)) <> T.pack lc)
where getDate =
do now <- Time.getCurrentTime
return (Time.formatTime Time.defaultTimeLocale "%Y-%m-%d %T%Q" now ++
": ")
getLevel =
return ("[" ++
map toLower (drop 5 (show level)) ++
"] ")
getLoc =
return (" @(" ++ fileLocStr ++ ")")
fileLocStr =
loc_package loc ++
':' :
loc_module loc ++
' ' :
loc_filename loc ++
':' :
line loc ++
':' :
char loc
where line = show . fst . loc_start
char = show . snd . loc_start
|
jkozlowski/better-bot
|
app/Main.hs
|
mit
| 7,805
| 14
| 20
| 2,828
| 1,824
| 979
| 845
| -1
| -1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
-- | Manipulate @GenericPackageDescription@ from Cabal into something more
-- useful for us.
module Stackage.PackageDescription
( SimpleDesc (..)
, toSimpleDesc
, CheckCond (..)
, Component (..)
, DepInfo (..)
) where
import Control.Monad.Writer.Strict (MonadWriter, execWriterT,
tell)
import Data.Semigroup (Option (..), Max (..))
import Distribution.Compiler (CompilerFlavor)
import Distribution.Package (Dependency (..))
import Distribution.PackageDescription
import Distribution.Types.CondTree (CondBranch (..))
import Distribution.System (Arch, OS)
import Stackage.PackageIndex
import Stackage.Prelude
-- | Convert a 'GenericPackageDescription' into a 'SimpleDesc' by following the
-- constraints in the provided 'CheckCond'.
toSimpleDesc :: MonadThrow m
=> CheckCond
-> SimplifiedPackageDescription
-> m SimpleDesc
toSimpleDesc cc spd = adjustForInternalLibDeps $ execWriterT $ do
forM_ (spdCondLibrary spd) $ tellTree cc CompLibrary
forM_ (spdCondExecutables spd) $ tellTree cc CompExecutable . snd
tell mempty { sdProvidedExes = setFromList
$ map (fromString . fst)
$ spdCondExecutables spd
, sdCabalVersion = Option $ Just $ Max $ spdCabalVersion spd
, sdPackages = unionsWith (<>) $ maybe [] (map
$ \(Dependency x y) -> singletonMap x DepInfo
{ diComponents = setFromList [minBound..maxBound]
, diRange = simplifyVersionRange y
}) (spdSetupDeps spd)
, sdSetupDeps =
case spdSetupDeps spd of
Nothing -> Nothing
Just deps -> Just $ setFromList $ map (\(Dependency x _) -> x) deps
}
when (ccIncludeTests cc) $ forM_ (spdCondTestSuites spd)
$ tellTree cc CompTestSuite . snd
when (ccIncludeBenchmarks cc) $ forM_ (spdCondBenchmarks spd)
$ tellTree cc CompBenchmark . snd
where
adjustForInternalLibDeps :: (MonadThrow m) => m SimpleDesc -> m SimpleDesc
adjustForInternalLibDeps = removeInternalLibsAsDeps . addDepsFromInternalLibs
removeInternalLibsAsDeps :: (MonadThrow m) => m SimpleDesc -> m SimpleDesc
removeInternalLibsAsDeps mdesc = do
desc <- mdesc
let removeUs :: [PackageName]
removeUs = map (mkPackageName . fst) $ spdCondSubLibraries spd
pure (foldr deleteDep desc removeUs) -- TODO: fixme
-- TODO: address known shortcoming:
-- Includes all internal lib transitive deps,
-- whether they are used by the main lib or not
addDepsFromInternalLibs :: (MonadThrow m) => m SimpleDesc -> m SimpleDesc
addDepsFromInternalLibs mdesc = do
desc <- mdesc
desc' <- mdesc'
pure (desc <> desc')
where
mdesc' = execWriterT $ do
forM_ (spdCondSubLibraries spd) $ \ (libName, libCondTree) -> do
tellTree cc CompLibrary libCondTree
-- | Delete a single dependency from a SimpleDesc
deleteDep :: PackageName -> SimpleDesc -> SimpleDesc
deleteDep pkgName d = d { sdPackages = deleteMap pkgName (sdPackages d) }
-- | Convert a single CondTree to a 'SimpleDesc'.
tellTree :: (MonadWriter SimpleDesc m, MonadThrow m)
=> CheckCond
-> Component
-> CondTree ConfVar [Dependency] SimplifiedComponentInfo
-> m ()
tellTree cc component =
loop
where
loop (CondNode dat deps comps) = do
tell mempty
{ sdPackages = unionsWith (<>) $ flip map deps
$ \(Dependency x y) -> singletonMap x DepInfo
{ diComponents = singletonSet component
, diRange = simplifyVersionRange y
}
, sdTools = unionsWith (<>) $ flip map (sciBuildTools dat)
$ \(name, range) -> singletonMap
-- In practice, cabal files refer to the exe name, not the
-- package name.
name
DepInfo
{ diComponents = singletonSet component
, diRange = simplifyVersionRange range
}
, sdModules = sciModules dat
}
forM_ comps $ \(CondBranch cond ontrue onfalse) -> do
b <- checkCond cc cond
if b
then loop ontrue
else maybe (return ()) loop onfalse
-- | Resolve a condition to a boolean based on the provided 'CheckCond'.
checkCond :: MonadThrow m => CheckCond -> Condition ConfVar -> m Bool
checkCond CheckCond {..} cond0 =
go cond0
where
go (Var (OS os)) = return $ os == ccOS
go (Var (Arch arch)) = return $ arch == ccArch
go (Var (Flag flag)) =
case lookup flag ccFlags of
Nothing -> throwM $ FlagNotDefined ccPackageName flag cond0
Just b -> return b
go (Var (Impl flavor range)) = return
$ flavor == ccCompilerFlavor
&& ccCompilerVersion `withinRange` range
go (Lit b) = return b
go (CNot c) = not `liftM` go c
go (CAnd x y) = (&&) `liftM` go x `ap` go y
go (COr x y) = (||) `liftM` go x `ap` go y
data CheckCondException = FlagNotDefined PackageName FlagName (Condition ConfVar)
deriving (Show, Typeable)
instance Exception CheckCondException
data CheckCond = CheckCond
{ ccPackageName :: PackageName -- for debugging only
, ccOS :: OS
, ccArch :: Arch
, ccFlags :: Map FlagName Bool
, ccCompilerFlavor :: CompilerFlavor
, ccCompilerVersion :: Version
, ccIncludeTests :: Bool
, ccIncludeBenchmarks :: Bool
}
|
fpco/stackage-curator
|
src/Stackage/PackageDescription.hs
|
mit
| 6,332
| 0
| 20
| 2,121
| 1,499
| 791
| 708
| 120
| 9
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.