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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-- Copyright (C) 2013-2015 Moritz Schulte <[email protected]>
module Main (main) where
import qualified Data.Map as M
import Data.Maybe
import System.Environment -- Commandline Arguments.
import Jeopardy.Data
import Jeopardy.Utils
dumpJDataItem :: JDataTable -> Category -> Integer -> IO ()
dumpJDataItem table category n = do
let pair = (category, n)
let jitem = M.lookup pair table
-- abort if jitem is nothing
let jitem' = fromJust jitem
putStr $ " " ++ show n ++ ": [A] " ++ jitemAnswer jitem' ++ "\n" ++
" [Q] " ++ jitemQuestion jitem' ++ "\n"
dumpJDataCategory :: JData -> Category -> IO ()
dumpJDataCategory jdata category = do
let table = jdataTable jdata
let catIdx = categoryIdx category
putStr $ "\nCategory: " ++ jdataCategories jdata !! catIdx ++ "\n--------------------\n"
mapM_ (dumpJDataItem table category) [1..5]
dumpJDataTable :: JData -> IO ()
dumpJDataTable jdata =
mapM_ (\ category -> dumpJDataCategory jdata [category]) ['a'..'e']
dumpJData :: JData -> IO ()
dumpJData jdata = do
putStr $ "Datasheet: " ++ jdataName jdata ++ "\n" ++ "====================" ++ "\n"
dumpJDataTable jdata
main :: IO ()
main = do
args <- getArgs
case args of
[fileIn] -> do src <- readFile fileIn
let jdata = maybeRead src
maybe (putStrLn "failed to parse input") dumpJData jdata
_ -> putStrLn "Usage: dump <data file>"
| mtesseract/silverratio-jeopardy | src/jeopardy-dump.hs | gpl-2.0 | 1,444 | 0 | 15 | 323 | 443 | 217 | 226 | 34 | 2 |
{- |
Module : $Header$
Description : String constants for CASL keywords to be used for parsing
and printing
Copyright : (c) Christian Maeder and Uni Bremen 2002-2003
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
String constants for keywords to be used for parsing and printing
- all identifiers are mixed case (i.e. the keyword followed by a capital S)
- see <http://www.cofi.info/Documents/CASL/Summary/> from 25 March 2001,
C.4 Lexical Syntax
-}
module Common.Keywords where
-- * context dependend keywords
-- | sub sort indicator
lessS :: String
lessS = "<"
-- | modifier for 'existsS'
exMark :: String
exMark = "!"
-- | modifier for 'funS' or 'colonS'
quMark :: String
quMark = "?"
-- * type constructors
-- | total function arrow
funS :: String
funS = "->"
-- | partial function arrow
pFun :: String
pFun = funS ++ quMark
-- | ascii product type sign
prodS :: String
prodS = "*"
-- | alternative latin1 product type sign
timesS :: String
timesS = "\215"
-- * symbol keywords
-- | the colon sign
colonS :: String
colonS = ":"
equiS :: String
equiS = "<->"
-- | the dot sign (ascii)
dotS :: String
dotS = "."
-- | the alternative latin1 centered dot sign
cDot :: String
cDot = "\183"
-- | the vertical bar
barS :: String
barS = "|"
-- | arrow started with a bar
mapsTo :: String
mapsTo = "|->"
-- | two colons and an equal sign
defnS :: String
defnS = "::="
-- | a colon with a question mark
colonQuMark :: String
colonQuMark = colonS ++ quMark
-- | the exists keyword with an exclamation mark
existsUnique :: String
existsUnique = existsS ++ exMark
-- * comment keywords
-- | one percent sign
percentS :: String
percentS = "%"
-- | two percent signs (for line comments)
percents :: String
percents = percentS ++ percentS
-- * formula symbols
-- | implication arrow (equal and greater)
implS :: String
implS = "=>"
-- | equivalent sign
equivS :: String
equivS = "<=>"
-- | the alternative latin1 negation sign for not
negS :: String
negS = "\172"
-- | logical and using slashes
lAnd :: String
lAnd = "/\\"
-- | logical or using slashes
lOr :: String
lOr = "\\/"
-- * further HasCASL key signs
-- | assign sign (colon and equal)
assignS :: String
assignS = ":="
-- | minus sign (for variance)
minusS :: String
minusS = "-"
-- | plus sign (for variance)
plusS :: String
plusS = "+"
-- | total continuous function arrow
contFun :: String
contFun = minusS ++ funS
-- | partial continuous function arrow
pContFun :: String
pContFun = minusS ++ pFun
-- | lambda sign (backslash)
lamS :: String
lamS = "\\"
-- | at sign (for as pattern)
asP :: String
asP = "@"
-- | Here sign
hereP :: String
hereP = "Here"
-- | Bind sign
bindP :: String
bindP = "Bind"
-- | assign sign in monad notation
rightArrow :: String
rightArrow = "<-"
-- * further HasCASL keywords
-- | the new keyword fun ('funS' is already defined differently)
functS :: String
functS = "fun"
-- * CoCasl key signs
-- | the diamond sign (less and greater)
diamondS :: String
diamondS = "<>"
-- | the greater sign
greaterS :: String
greaterS = ">"
-- * OWL key signs
lessEq :: String
lessEq = "<="
greaterEq :: String
greaterEq = ">="
-- * CspCasl key signs
-- | Prefix processes
prefix_procS :: String
prefix_procS = "->"
-- | sequential process operator
sequentialS :: String
sequentialS = ";"
-- | interleaving parallel operator
interleavingS :: String
interleavingS = "|||"
-- | synchronous parallel operator
synchronousS :: String
synchronousS = "||"
-- | Open generalised parallel
genpar_openS :: String
genpar_openS = "[|"
-- | Close generalised parallel
genpar_closeS :: String
genpar_closeS = "|]"
-- | Open alpabetised parallel
alpar_openS :: String
alpar_openS = "["
-- | Separator in alpabetised parallel
alpar_sepS :: String
alpar_sepS = "||"
-- | Close alpabetised parallel
alpar_closeS :: String
alpar_closeS = "]"
-- | External choice
external_choiceS :: String
external_choiceS = "[]"
-- | Internal choice
internal_choiceS :: String
internal_choiceS = "|~|"
-- | Hiding (process)
hiding_procS :: String
hiding_procS = "\\"
-- | Open a renaming (process)
ren_proc_openS :: String
ren_proc_openS = "[["
-- | Close a renaming (process)
ren_proc_closeS :: String
ren_proc_closeS = "]]"
-- * logic definition symbols
newlogicS :: String
newlogicS = "newlogic"
metaS :: String
metaS = "meta"
foundationS :: String
foundationS = "foundation"
syntaxS :: String
syntaxS = "syntax"
patternsS :: String
patternsS = "patterns"
modelsS :: String
modelsS = "models"
proofsS :: String
proofsS = "proofs"
newcomorphismS :: String
newcomorphismS = "newcomorphism"
sourceS :: String
sourceS = "source"
targetS :: String
targetS = "target"
-- * DOL keywords
alignArityBackwardS :: String
alignArityBackwardS = "align-arity-backward"
alignArityForwardS :: String
alignArityForwardS = "align-arity-forward"
alignmentS :: String
alignmentS = "alignment"
combineS :: String
combineS = "combine"
distributedOntologyS :: String
distributedOntologyS = "distributed-ontology"
excludingS :: String
excludingS = "excluding"
forS :: String
forS = "for"
interpretationS :: String
interpretationS = "interpretation"
moduleS :: String
moduleS = "module"
ontologyS :: String
ontologyS = "ontology"
diagramS :: String
diagramS = "diagram"
relationS :: String
relationS = "relation"
serializationS :: String
serializationS = "serialization"
-- * frameworks
lfS :: String
lfS = "LF"
isabelleS :: String
isabelleS = "Isabelle"
maudeS :: String
maudeS = "Maude"
-- * MMT symbols
sigDelimS :: String
sigDelimS = ".."
structDelimS :: String
structDelimS = "/"
-- * Twelf conventions
-- non breaking space
whiteChars :: String
whiteChars = "\n\r\t\v\f \160"
-- special characters permitted in a Twelf symbol name
twelfSymChars :: String
twelfSymChars = "_-+*/<=>@^"
-- special characters permitted in a Twelf declaration
twelfDeclChars :: String
twelfDeclChars = twelfSymChars ++ ":{}[]()"
-- special characters permitted in a Twelf declaration of multiple symbols
twelfMultDeclChars :: String
twelfMultDeclChars = twelfDeclChars ++ ","
-- * letter keywords taken from Keywords.txt
andS :: String
andS = "and"
archS :: String
archS = "arch"
asS :: String
asS = "as"
assocS :: String
assocS = "assoc"
axiomS :: String
axiomS = "axiom"
behaviourallyS :: String
behaviourallyS = "behaviourally"
caseS :: String
caseS = "case"
classS :: String
classS = "class"
closedS :: String
closedS = "closed"
closedworldS :: String
closedworldS = "closed-world"
cofreeS :: String
cofreeS = "cofree"
cogeneratedS :: String
cogeneratedS = "cogenerated"
commS :: String
commS = "comm"
cotypeS :: String
cotypeS = "cotype"
dataS :: String
dataS = "data"
defS :: String
defS = "def"
derivingS :: String
derivingS = "deriving"
displayS :: String
displayS = "display"
doS :: String
doS = "do"
elseS :: String
elseS = "else"
emptyS :: String
emptyS = "empty"
endS :: String
endS = "end"
equivalenceS :: String
equivalenceS = "equivalence"
esortS :: String
esortS = "esort"
etypeS :: String
etypeS = "etype"
existsS :: String
existsS = "exists"
falseS :: String
falseS = "false"
fitS :: String
fitS = "fit"
flexibleS :: String
flexibleS = "flexible"
floatingS :: String
floatingS = "floating"
forallS :: String
forallS = "forall"
freeS :: String
freeS = "free"
fromS :: String
fromS = "from"
generatedS :: String
generatedS = "generated"
getS :: String
getS = "get"
givenS :: String
givenS = "given"
hideS :: String
hideS = "hide"
approximateS :: String
approximateS = "approximate"
idemS :: String
idemS = "idem"
ifS :: String
ifS = "if"
inS :: String
inS = "in"
instanceS :: String
instanceS = "instance"
internalS :: String
internalS = "internal"
lambdaS :: String
lambdaS = "lambda"
left_assocS :: String
left_assocS = "left_assoc"
letS :: String
letS = "let"
libraryS :: String
libraryS = "library"
listS :: String
listS = "list"
localS :: String
localS = "local"
logicS :: String
logicS = "logic"
minimizeS :: String
minimizeS = "minimize"
modalitiesS :: String
modalitiesS = "modalities"
modalityS :: String
modalityS = "modality"
notS :: String
notS = "not"
numberS :: String
numberS = "number"
ofS :: String
ofS = "of"
opS :: String
opS = "op"
precS :: String
precS = "prec"
predS :: String
predS = "pred"
prefixS :: String
prefixS = "prefix"
programS :: String
programS = "program"
propS :: String
propS = "prop"
refinedS :: String
refinedS = "refined"
refinementS :: String
refinementS = "refinement"
resultS :: String
resultS = "result"
revealS :: String
revealS = "reveal"
right_assocS :: String
right_assocS = "right_assoc"
rigidS :: String
rigidS = "rigid"
sS :: String
sS = "s"
sortS :: String
sortS = "sort"
specS :: String
specS = "spec"
stringS :: String
stringS = "string"
structS :: String
structS = "struct"
termS :: String
termS = "term"
thenS :: String
thenS = "then"
toS :: String
toS = "to"
trueS :: String
trueS = "true"
typeS :: String
typeS = "type"
unitS :: String
unitS = "unit"
varS :: String
varS = "var"
varsS :: String
varsS = "vars"
versionS :: String
versionS = "version"
viaS :: String
viaS = "via"
viewS :: String
viewS = "view"
whenS :: String
whenS = "when"
whereS :: String
whereS = "where"
withS :: String
withS = "with"
withinS :: String
withinS = "within"
| nevrenato/HetsAlloy | Common/Keywords.hs | gpl-2.0 | 9,412 | 0 | 5 | 1,751 | 1,828 | 1,122 | 706 | 345 | 1 |
{- |
Module : ./SoftFOL/Translate.hs
Description : utility to create valid identifiers for atp provers
Copyright : (c) Klaus Luettich, Uni Bremen 2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
collection of functions used by "Comorphisms.SuleCFOL2SoftFOL" and
"SoftFOL.ProveSPASS" for the translation of CASL identifiers and axiom labels
into valid SoftFOL identifiers -}
module TPTP.Translate
( transId
, transSenName
, checkIdentifier
, CKType (..)
) where
import Data.Char
import qualified Data.Set as Set
import Common.Id
import Common.ProofUtils
data CKType = CKSort | CKVar | CKPred | CKOp
transSenName :: String -> String
transSenName = transIdString CKSort . concatMap transToSPChar
{- |
SPASS Identifiers may contain letters, digits, and underscores only; but
for TPTP the allowed starting letters are different for each sort of
identifier.
-}
checkIdentifier :: CKType -> String -> Bool
checkIdentifier t str = case str of
"" -> False
c : _ -> all checkSPChar str && case t of
CKVar -> isUpper c -- for TPTP
_ -> isLower c
{- |
Allowed SPASS characters are letters, digits, and underscores.
Warning:
Data.Char.isAlphaNum includes all kinds of isolatin1 characters!! -}
checkSPChar :: Char -> Bool
checkSPChar c = isAlphaNum c && isAscii c || '_' == c
transId :: CKType -> Id -> Token
transId t = mkSimpleId . transIdString t . concatMap transToSPChar . show
transIdString :: CKType -> String -> String
transIdString t str = case str of
"" -> error "TPTP.Translate.transIdString: empty string not allowed"
c : r -> if isDigit c then transIdString t $ substDigit c ++ r
else case t of
CKOp | '_' == c -> 'o' : str
CKPred | '_' == c -> 'p' : str
CKVar -> toUpper c : r
_ -> let lstr = toLower c : r in lstr
transToSPChar :: Char -> String
transToSPChar c
| checkSPChar c = [c]
| elem c " \n" = "_"
| otherwise = lookupCharMap c
substDigit :: Char -> String
substDigit c = case c of
'0' -> "zero"
'1' -> "one"
'2' -> "two"
'3' -> "three"
'4' -> "four"
'5' -> "five"
'6' -> "six"
'7' -> "seven"
'8' -> "eight"
'9' -> "nine"
_ -> [c]
| spechub/Hets | TPTP/Translate.hs | gpl-2.0 | 2,264 | 0 | 17 | 504 | 536 | 272 | 264 | 49 | 11 |
{-# LANGUAGE NoImplicitPrelude, RecordWildCards, OverloadedStrings, TemplateHaskell #-}
module Graphics.UI.Bottle.Widgets.TextEdit
( Cursor
, Style(..)
, sCursorColor, sCursorWidth, sBGColor, sEmptyUnfocusedString
, sEmptyFocusedString, sTextViewStyle
, make
, defaultCursorColor
, defaultCursorWidth
) where
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Lens.Tuple
import qualified Data.Binary.Utils as BinUtils
import qualified Data.ByteString.Char8 as SBS8
import Data.Char (isSpace)
import Data.List (genericLength)
import Data.List.Split (splitWhen)
import Data.List.Utils (minimumOn)
import qualified Data.Map as Map
import Data.Maybe (mapMaybe)
import Data.Monoid ((<>))
import qualified Data.Monoid as Monoid
import qualified Data.Set as Set
import Data.Vector.Vector2 (Vector2(..))
import qualified Graphics.DrawingCombinators as Draw
import Graphics.DrawingCombinators.Utils (TextSize(..))
import qualified Graphics.UI.Bottle.Animation as Anim
import qualified Graphics.UI.Bottle.Direction as Direction
import qualified Graphics.UI.Bottle.EventMap as E
import Graphics.UI.Bottle.ModKey (ModKey(..))
import qualified Graphics.UI.Bottle.ModKey as ModKey
import Graphics.UI.Bottle.Rect (Rect(..))
import qualified Graphics.UI.Bottle.Rect as Rect
import Graphics.UI.Bottle.View (View(..))
import Graphics.UI.Bottle.Widget (Widget(..))
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Graphics.UI.Bottle.Widgets.TextView as TextView
import qualified Graphics.UI.GLFW as GLFW
import Prelude.Compat
type Cursor = Int
data Style = Style
{ _sCursorColor :: Draw.Color
, _sCursorWidth :: Widget.R
, _sBGColor :: Draw.Color
, _sEmptyUnfocusedString :: String
, _sEmptyFocusedString :: String
, _sTextViewStyle :: TextView.Style
}
Lens.makeLenses ''Style
-- TODO: Replace with a defaultStyle :: TextViewStyle -> .. -> Style
defaultCursorColor :: Draw.Color
defaultCursorColor = Draw.Color 0 1 0 1
defaultCursorWidth :: Widget.R
defaultCursorWidth = 4
tillEndOfWord :: String -> String
tillEndOfWord xs = spaces ++ nonSpaces
where
spaces = takeWhile isSpace xs
nonSpaces = takeWhile (not . isSpace) . dropWhile isSpace $ xs
makeDisplayStr :: String -> String -> String
makeDisplayStr empty "" = empty
makeDisplayStr _ str = str
cursorTranslate :: Style -> Anim.Frame -> Anim.Frame
cursorTranslate Style{..} = Anim.translate $ Vector2 (_sCursorWidth / 2) 0
encodeCursor :: Widget.Id -> Int -> Widget.Id
encodeCursor myId = Widget.joinId myId . (:[]) . BinUtils.encodeS
rightSideOfRect :: Rect -> Rect
rightSideOfRect rect =
rect
& Rect.left .~ rect ^. Rect.right
& Rect.width .~ 0
cursorRects :: TextView.Style -> String -> [Rect]
cursorRects style str =
concat .
-- A bit ugly: letterRects returns rects for all but newlines, and
-- returns a list of lines. Then addFirstCursor adds the left-most
-- cursor of each line, thereby the number of rects becomes the
-- original number of letters which can be used to match the
-- original string index-wise.
zipWith addFirstCursor (iterate (+lineHeight) 0) .
(map . map) rightSideOfRect $
TextView.letterRects style str
where
addFirstCursor y = (Rect (Vector2 0 y) (Vector2 0 lineHeight) :)
lineHeight = TextView.lineHeight style
makeUnfocused ::
Style -> String -> Widget.Id -> Widget (String, Widget.EventResult)
makeUnfocused Style{..} str myId =
TextView.makeWidget _sTextViewStyle displayStr animId
& Widget.animFrame %~ cursorTranslate Style{..}
& Widget.width +~ cursorWidth
& makeFocusable Style{..} str myId
where
animId = Widget.toAnimId myId
cursorWidth = _sCursorWidth
displayStr = makeDisplayStr _sEmptyUnfocusedString str
minimumIndex :: Ord a => [a] -> Int
minimumIndex xs =
xs ^@.. Lens.traversed & minimumOn snd & fst
cursorNearRect :: TextView.Style -> String -> Rect -> Int
cursorNearRect style str fromRect =
cursorRects style str <&> Rect.distance fromRect
& minimumIndex -- cursorRects(TextView.letterRects) should never return an empty list
enterFromDirection ::
Style -> String -> Widget.Id ->
Direction.Direction -> Widget.EnterResult (String, Widget.EventResult)
enterFromDirection Style{..} str myId dir =
Widget.EnterResult cursorRect .
(,) str . Widget.eventResultFromCursor $
encodeCursor myId cursor
where
cursor =
case dir of
Direction.Outside -> length str
Direction.PrevFocalArea rect -> cursorNearRect _sTextViewStyle str rect
Direction.Point x -> cursorNearRect _sTextViewStyle str $ Rect x 0
cursorRect = mkCursorRect Style{..} cursor str
makeFocusable ::
Style -> String -> Widget.Id ->
Widget (String, Widget.EventResult) -> Widget (String, Widget.EventResult)
makeFocusable style str myId =
Widget.mEnter .~ Just (enterFromDirection style str myId)
readM :: Read a => String -> Maybe a
readM str =
case reads str of
[(x, "")] -> Just x
_ -> Nothing
eventResult ::
Widget.Id -> [(Maybe Int, Char)] -> [(Maybe Int, Char)] ->
Int -> (String, Widget.EventResult)
eventResult myId strWithIds newText newCursor =
(map snd newText,
Widget.EventResult {
Widget._eCursor = Monoid.Last . Just $ encodeCursor myId newCursor,
Widget._eAnimIdMapping = Monoid.Endo mapping
})
where
myAnimId = Widget.toAnimId myId
mapping animId = maybe animId (Anim.joinId myAnimId . translateId) $ Anim.subId myAnimId animId
translateId [subId] = (:[]) . maybe subId (SBS8.pack . show) $ (`Map.lookup` dict) =<< readM (SBS8.unpack subId)
translateId x = x
dict = mappend movedDict deletedDict
movedDict =
map fst newText ^@.. Lens.traversed
<&> posMapping
& (^.. Lens.traversed . Lens._Just)
& Map.fromList
deletedDict = Map.fromList . map (flip (,) (-1)) $ Set.toList deletedKeys
posMapping (_, Nothing) = Nothing
posMapping (newPos, Just oldPos) = Just (oldPos, newPos)
deletedKeys =
Set.fromList (mapMaybe fst strWithIds) `Set.difference`
Set.fromList (mapMaybe fst newText)
-- | Note: maxLines prevents the *user* from exceeding it, not the
-- | given text...
makeFocused ::
Cursor -> Style -> String -> Widget.Id ->
Widget (String, Widget.EventResult)
makeFocused cursor Style{..} str myId =
makeFocusable Style{..} str myId widget
where
widget =
Widget
{ _view = View reqSize $ img <> cursorFrame
, _mEnter = Nothing
, _mFocus =
Just Widget.Focus
{ _focalArea = cursorRect
, _eventMap = eventMap cursor str displayStr myId
}
}
reqSize = Vector2 (_sCursorWidth + tlWidth) tlHeight
myAnimId = Widget.toAnimId myId
img = cursorTranslate Style{..} $ frameGen myAnimId
displayStr = makeDisplayStr _sEmptyFocusedString str
Vector2 tlWidth tlHeight = bounding renderedSize
(TextView.RenderedText renderedSize frameGen) =
TextView.drawTextAsSingleLetters _sTextViewStyle displayStr
cursorRect = mkCursorRect Style{..} cursor str
cursorFrame =
Anim.unitSquare (Widget.cursorAnimId ++ ["text"])
& Anim.unitImages %~ Draw.tint _sCursorColor
& Anim.unitIntoRect cursorRect
& Anim.layers +~ 2 -- TODO: 2?!
mkCursorRect :: Style -> Int -> String -> Rect
mkCursorRect Style{..} cursor str = Rect cursorPos cursorSize
where
beforeCursorLines = splitWhen (== '\n') $ take cursor str
lineHeight = TextView.lineHeight _sTextViewStyle
cursorPos = Vector2 cursorPosX cursorPosY
cursorSize = Vector2 _sCursorWidth lineHeight
cursorPosX =
TextView.drawTextAsSingleLetters _sTextViewStyle (last beforeCursorLines) ^.
TextView.renderedTextSize . Lens.to advance . _1
cursorPosY = lineHeight * (genericLength beforeCursorLines - 1)
eventMap ::
Int -> String -> String -> Widget.Id ->
Widget.EventMap (String, Widget.EventResult)
eventMap cursor str displayStr myId =
mconcat . concat $ [
[ keys (moveDoc ["left"]) [noMods GLFW.Key'Left] $
moveRelative (-1)
| cursor > 0 ],
[ keys (moveDoc ["right"]) [noMods GLFW.Key'Right] $
moveRelative 1
| cursor < textLength ],
[ keys (moveDoc ["word", "left"]) [ctrl GLFW.Key'Left]
backMoveWord
| cursor > 0 ],
[ keys (moveDoc ["word", "right"]) [ctrl GLFW.Key'Right] moveWord
| cursor < textLength ],
[ keys (moveDoc ["up"]) [noMods GLFW.Key'Up] $
moveRelative (- cursorX - 1 - length (drop cursorX prevLine))
| cursorY > 0 ],
[ keys (moveDoc ["down"]) [noMods GLFW.Key'Down] $
moveRelative (length curLineAfter + 1 + min cursorX (length nextLine))
| cursorY < lineCount - 1 ],
[ keys (moveDoc ["beginning of line"]) homeKeys $
moveRelative (-cursorX)
| cursorX > 0 ],
[ keys (moveDoc ["end of line"]) endKeys $
moveRelative (length curLineAfter)
| not . null $ curLineAfter ],
[ keys (moveDoc ["beginning of text"]) homeKeys $
moveAbsolute 0
| cursorX == 0 && cursor > 0 ],
[ keys (moveDoc ["end of text"]) endKeys $
moveAbsolute textLength
| null curLineAfter && cursor < textLength ],
[ keys (deleteDoc ["backwards"]) [noMods GLFW.Key'Backspace] $
backDelete 1
| cursor > 0 ],
[ keys (deleteDoc ["word", "backwards"]) [ctrl GLFW.Key'W]
backDeleteWord
| cursor > 0 ],
let swapPoint = min (textLength - 2) (cursor - 1)
(beforeSwap, x:y:afterSwap) = splitAt swapPoint strWithIds
swapLetters = eventRes (beforeSwap ++ y:x:afterSwap) $ min textLength (cursor + 1)
in
[ keys (editDoc ["Swap letters"]) [ctrl GLFW.Key'T]
swapLetters
| cursor > 0 && textLength >= 2 ],
[ keys (deleteDoc ["forward"]) [noMods GLFW.Key'Delete] $
delete 1
| cursor < textLength ],
[ keys (deleteDoc ["word", "forward"]) [alt GLFW.Key'D]
deleteWord
| cursor < textLength ],
[ keys (deleteDoc ["till", "end of line"]) [ctrl GLFW.Key'K] $
delete (length curLineAfter)
| not . null $ curLineAfter ],
[ keys (deleteDoc ["newline"]) [ctrl GLFW.Key'K] $
delete 1
| null curLineAfter && cursor < textLength ],
[ keys (deleteDoc ["till", "beginning of line"]) [ctrl GLFW.Key'U] $
backDelete (length curLineBefore)
| not . null $ curLineBefore ],
[ E.filterChars (`notElem` (" \n" :: String)) .
E.allChars "Character" (insertDoc ["character"]) $
insert . (: [])
],
[ keys (insertDoc ["Newline"])
[noMods GLFW.Key'Enter, ModKey.shift GLFW.Key'Enter] (insert "\n") ],
[ keys (insertDoc ["Space"])
[noMods GLFW.Key'Space, ModKey.shift GLFW.Key'Space] (insert " ") ],
[ E.pasteOnKey (ctrl GLFW.Key'V) (E.Doc ["Clipboard", "Paste"]) insert ]
]
where
editDoc = E.Doc . ("Edit" :)
deleteDoc = editDoc . ("Delete" :)
insertDoc = editDoc . ("Insert" :)
moveDoc = E.Doc . ("Navigation" :) . ("Move" :)
splitLines = splitWhen ((== '\n') . snd)
linesBefore = reverse (splitLines before)
linesAfter = splitLines after
prevLine = linesBefore !! 1
nextLine = linesAfter !! 1
curLineBefore = head linesBefore
curLineAfter = head linesAfter
cursorX = length curLineBefore
cursorY = length linesBefore - 1
eventRes = eventResult myId strWithIds
moveAbsolute a = eventRes strWithIds . max 0 $ min (length str) a
moveRelative d = moveAbsolute (cursor + d)
backDelete n = eventRes (take (cursor-n) strWithIds ++ drop cursor strWithIds) (cursor-n)
delete n = eventRes (before ++ drop n after) cursor
insert l = eventRes str' cursor'
where
cursor' = cursor + length l
str' = concat [before, map ((,) Nothing) l, after]
backDeleteWord = backDelete . length . tillEndOfWord . reverse $ map snd before
deleteWord = delete . length . tillEndOfWord $ map snd after
backMoveWord = moveRelative . negate . length . tillEndOfWord . reverse $ map snd before
moveWord = moveRelative . length . tillEndOfWord $ map snd after
keys = flip E.keyPresses
noMods = ModKey mempty
ctrl = ModKey.ctrl
alt = ModKey.alt
homeKeys = [noMods GLFW.Key'Home, ctrl GLFW.Key'A]
endKeys = [noMods GLFW.Key'End, ctrl GLFW.Key'E]
textLength = length str
lineCount = length $ splitWhen (== '\n') displayStr
strWithIds = str ^@.. Lens.traversed <&> _1 %~ Just
(before, after) = splitAt cursor strWithIds
make ::
Style -> String -> Widget.Id -> Widget.Env ->
Widget (String, Widget.EventResult)
make style str myId env =
makeFunc style str myId
where
makeFunc =
case Widget.subId myId (env ^. Widget.envCursor) of
Nothing -> makeUnfocused
Just suffix -> makeFocused (decodeCursor suffix)
decodeCursor [x] = min (length str) $ BinUtils.decodeS x
decodeCursor _ = length str
| da-x/lamdu | bottlelib/Graphics/UI/Bottle/Widgets/TextEdit.hs | gpl-3.0 | 13,931 | 0 | 16 | 3,769 | 4,137 | 2,213 | 1,924 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-- | A simple fileserver with caching:
--
-- - receive and parse the incoming request,
--
-- - if the requested file is in the cache, read the cached contents,
--
-- - otherwise, read the requested file's contents as a 'ByteString',
-- insert it into the cache, and
--
-- - send the contents.
--
-- Rather than handling cache expiry ourselves, we @mmap(2)@ the file
-- to memory. This way, the OS is responsible for swapping the file
-- in and out of memory, and Haskell's garbage collector is
-- responsible for unmmaping the file when it's no longer needed.
--
module Main where
import Control.Concurrent.MVar ( MVar, newMVar, modifyMVar )
import Data.ByteString.Char8 ( ByteString )
import Data.Map ( Map )
import qualified Data.Map as M
import Network.Socket ( Socket )
import Network.Socket.ByteString ( sendAll )
import System.IO.MMap ( mmapFileByteString )
import Utils ( runAcceptLoop, bindPort, readRequestUri )
main :: IO ()
main = do
lsocket <- bindPort 5000
cache <- newMVar M.empty
runAcceptLoop lsocket (handleRequest cache)
handleRequest :: MVar (Map String ByteString) -> Socket -> IO ()
handleRequest cacheVar sock = do
text <- modifyMVar cacheVar $ \cache -> do
uri <- readRequestUri sock
case M.lookup uri cache of
Nothing -> do
-- fileText <- readFile uri
fileText <- mmapFileByteString uri Nothing
return (M.insert uri fileText cache, fileText)
Just fileText -> do
return (cache, fileText)
sendAll sock "HTTP/1.1 200 OK\r\n\r\n"
sendAll sock text
| scvalex/dissemina2 | Cached.hs | gpl-3.0 | 1,629 | 0 | 20 | 367 | 323 | 175 | 148 | 27 | 2 |
{-# LANGUAGE DeriveGeneric #-}
module System.DevUtils.Sys.Memory (
Memory(..)
) where
import GHC.Generics
data Memory a = B a | K a | M a | G a | T a | P a | UNKNOWN a
deriving (Show, Read, Generic)
| adarqui/DevUtils-Sys | src/System/DevUtils/Sys/Memory.hs | gpl-3.0 | 203 | 0 | 6 | 44 | 78 | 48 | 30 | 6 | 0 |
{-# LANGUAGE UnicodeSyntax #-}
module Paths where
import Prelude.Unicode
import Development.Shake.FilePath
-- NB for simplicity we assume the build is always run from the build/ dir.
-- This holds true because the build is run by invoking build.sh, which cd
-- in the build/ dir before running Shakefile.hs.
baseDir = "../../"
srcDir = baseDir </> "src"
buildDir = "."
binDir = baseDir </> "bin"
-- NB /tmp has tmpfs, so it's contents will go when the system halts/reboots.
baseTmpDir = "/tmp/archlinux-vm"
hakyllTmpDir = baseTmpDir </> "hakyll"
shakeTmpDir = baseTmpDir </> "shake/"
siteBuilder = baseTmpDir </> "site"
| c0c0n3/archlinux | vm/src/build/Paths.hs | gpl-3.0 | 636 | 0 | 5 | 112 | 80 | 49 | 31 | 12 | 1 |
{-# LANGUAGE QuasiQuotes, OverloadedStrings #-}
module InterpreterSpec (spec) where
import Test.Hspec
import Language.Mulang.Interpreter
import Language.Mulang.Interpreter.Internals (Reference (..))
import Language.Mulang.Transform.Normalizer
import qualified Data.Map.Strict as Map
import Language.Mulang.Parsers.JavaScript
import Language.Mulang.Parsers.Python
import Data.Text (unpack)
import NeatInterpolation (text)
lastRef result = (\(ref, ctx) -> (Map.! ref) . globalObjects $ ctx) <$> result
run language code = eval defaultContext . language . unpack $ code
runjs = run (normalize (unnormalized { convertObjectIntoDict = True }) . js')
runpy = run py
spec :: Spec
spec = do
describe "evalExpr" $ do
context "javascript" $ do
it "rejects logic on number" $ do
lastRef (runjs "1 || 2") `shouldThrow` (errorCall "Exception thrown outside try: Type error: expected two booleans but got (number) 1.0, (number) 2.0")
it "rejects math on bools" $ do
lastRef (runjs "true + false") `shouldThrow` (errorCall "Exception thrown outside try: Type error: expected two numbers but got (boolean) true, (boolean) false")
it "evals addition" $ do
lastRef (runjs "1 + 2") `shouldReturn` MuNumber 3
it "evals subtraction" $ do
lastRef (runjs "2 - 1") `shouldReturn` MuNumber 1
it "evals multiplication" $ do
lastRef (runjs "2 * 3") `shouldReturn` MuNumber 6
it "evals mod" $ do
lastRef (runjs "7 % 4") `shouldReturn` MuNumber 3
it "evals and" $ do
lastRef (runjs "true && true") `shouldReturn` MuBool True
it "evals or" $ do
lastRef (runjs "false || false") `shouldReturn` MuBool False
it "evals not" $ do
lastRef (runjs "!false") `shouldReturn` MuBool True
it "evals comparison" $ do
lastRef (runjs "7 > 4") `shouldReturn` MuBool True
it "evals list length" $ do
lastRef (runjs "[1, 2, 3].length") `shouldReturn` MuNumber 3
it "evals dict get" $ do
lastRef (runjs "({x: 3})['x']") `shouldReturn` MuNumber 3
lastRef (runjs "({x: 3, y: 4})['x']") `shouldReturn` MuNumber 3
it "evals dict get with field access" $ do
lastRef (runjs "({x: 3}).x") `shouldReturn` MuNumber 3
lastRef (runjs "({x: 3, y: 4}).x") `shouldReturn` MuNumber 3
it "evals dict set" $ do
-- lastRef (runjs "let dict = {x: 3}; dict['x'] = 4") `shouldReturn` MuNumber 4
-- lastRef (runjs "let dict = {x: 3}; dict['x'] = 4; dict['x']") `shouldReturn` MuNumber 4
-- lastRef (runjs "let dict = {x: 3}; dict['y'] = 4; dict['x']") `shouldReturn` MuNumber 3
pending
it "evals dict set with field access" $ do
lastRef (runjs "let dict = {x: 3}; dict.x = 4") `shouldReturn` MuNumber 4
lastRef (runjs "let dict = {x: 3}; dict.x = 4; dict.x") `shouldReturn` MuNumber 4
lastRef (runjs "let dict = {x: 3}; dict.y = 4; dict.x") `shouldReturn` MuNumber 3
context "evals equal" $ do
it "is false when values are different" $ do
lastRef (runjs "123 == 321") `shouldReturn` MuBool False
it "is true when values are the same" $ do
lastRef (runjs "'123' == '123'") `shouldReturn` MuBool True
it "is false when values are of different types" $ do
lastRef (runjs "'123' == 123") `shouldReturn` MuBool False
context "evals if" $ do
it "condition is true then evals first branch" $ do
lastRef (runjs [text|
if(true){
123
} else {
456
}|]) `shouldReturn` MuNumber 123
it "condition is false then evals second branch" $ do
lastRef (runjs [text|
if(false){
123
} else {
456
}|]) `shouldReturn` MuNumber 456
it "condition is non bool, fails" $ do
lastRef (runjs "if (6) { 123 } else { 456 }") `shouldThrow` (errorCall "Exception thrown outside try: Type error: expected boolean but got (number) 6.0")
it "evals functions" $ do
lastRef (runjs [text|
function a() {
return 123;
}
a()|]) `shouldReturn` MuNumber 123
it "evals functions with for" $ do
lastRef (runjs [text|
function shortPubs(nick,thread){
let result=[];
for(let p of thread){
if((p.message.length)<20&&nick===p.nick){
result.push(p);
}
}
return result;
}
let aThread = [
{ nick: "tommy", message: "hello" },
{ nick: "tommy", message: "world" },
{ nick: "danny", message: "we are running" },
{ nick: "tommy", message: "another message" },
{ nick: "tommy", message: "another looooooooooooooooooooooooong message" },
]
shortPubs("tommy", aThread);
|]) `shouldReturn` (MuList [Reference 7, Reference 12, Reference 22])
it "handles scopes" $ do
lastRef (runjs [text|
function a() {
function b(){}
}
b()|]) `shouldThrow` (errorCall "Exception thrown outside try: Reference not found for name 'b'")
it "handles whiles" $ do
lastRef (runjs [text|
let a = 0;
while(a < 10) a = a + 1;
a;|]) `shouldReturn` MuNumber 10
it "handles fors" $ do
lastRef (runjs [text|
let a = 0;
let i = 0;
for(i = 0; i <= 10; i++) a = a + i;
a;|]) `shouldReturn` MuNumber 55
context "python" $ do
it "evals addition" $ do
lastRef (runpy "1 + 2") `shouldReturn` MuNumber 3
it "evals subtraction" $ do
lastRef (runpy "2 - 1") `shouldReturn` MuNumber 1
it "evals multiplication" $ do
lastRef (runpy "2 * 3") `shouldReturn` MuNumber 6
it "evals mod" $ do
lastRef (runpy "7 % 4") `shouldReturn` MuNumber 3
it "evals and" $ do
lastRef (runpy "True and True") `shouldReturn` MuBool True
it "evals or" $ do
lastRef (runpy "False or False") `shouldReturn` MuBool False
it "evals comparison" $ do
lastRef (runpy "7 > 4") `shouldReturn` MuBool True
context "evals equal" $ do
it "is false when values are different" $ do
lastRef (runpy "123 == 321") `shouldReturn` MuBool False
it "is true when values are the same" $ do
lastRef (runpy "'123' == '123'") `shouldReturn` MuBool True
it "is false when values are of different types" $ do
lastRef (runpy "'123' == 123") `shouldReturn` MuBool False
context "evals if" $ do
it "condition is true then evals first branch" $ do
lastRef (runpy [text|
if True: 123
else: 456|]) `shouldReturn` MuNumber 123
it "condition is false then evals second branch" $ do
lastRef (runpy [text|
if False: 123
else: 456|]) `shouldReturn` MuNumber 456
it "condition is non bool, fails" $ do
lastRef (runpy [text|
if 6: 123
else: 456|]) `shouldThrow` (errorCall "Exception thrown outside try: Type error: expected boolean but got (number) 6.0")
it "evals functions" $ do
lastRef (runpy [text|
def a():
return 123
a()|]) `shouldReturn` MuNumber 123
it "handles whiles" $ do
lastRef (runpy [text|
a = 0
while(a < 10): a = a + 1
a|]) `shouldReturn` MuNumber 10
it "evals not" $ do
lastRef (runpy "not False") `shouldReturn` MuBool True
| mumuki/mulang | spec/InterpreterSpec.hs | gpl-3.0 | 7,802 | 0 | 22 | 2,508 | 1,722 | 838 | 884 | 124 | 1 |
module HEP.Automation.MadGraph.Dataset.Set20110710set5 where
import HEP.Storage.WebDAV.Type
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Model.C8S
import HEP.Automation.MadGraph.Dataset.Processes
import HEP.Automation.JobQueue.JobType
processSetup :: ProcessSetup C8S
processSetup = PS {
model = C8S
, process = preDefProcess TTBar0or1J
, processBrief = "TTBar0or1J"
, workname = "710_C8S_TTBar0or1J_TEV"
}
paramSet :: [ModelParam C8S]
paramSet = [ C8SParam { mnp = m,
gnpR = g,
gnpL = 0 } | m <- [600], g <- [1] ]
sets :: [Int]
sets = [1]
ucut :: UserCut
ucut = UserCut {
uc_metcut = 15.0
, uc_etacutlep = 2.7
, uc_etcutlep = 18.0
, uc_etacutjet = 2.7
, uc_etcutjet = 15.0
}
eventsets :: [EventSet]
eventsets =
[ EventSet processSetup
(RS { param = p
, numevent = 1000
, machine = TeVatron
, rgrun = Fixed
, rgscale = 200.0
, match = MLM
, cut = DefCut
, pythia = RunPYTHIA
, usercut = UserCutDef ucut -- NoUserCutDef --
, pgs = RunPGS
, jetalgo = Cone 0.4
, uploadhep = NoUploadHEP
, setnum = num
})
| p <- paramSet , num <- sets ]
webdavdir :: WebDAVRemoteDir
webdavdir = WebDAVRemoteDir "paper3/test"
| wavewave/madgraph-auto-dataset | src/HEP/Automation/MadGraph/Dataset/Set20110710set5.hs | gpl-3.0 | 1,623 | 0 | 10 | 563 | 368 | 232 | 136 | 47 | 1 |
module Web
( WebFilePath
, webFileRel
, webFileAbs
, withWebDir
, splitWebExtensions
, splitWebExtension
, replaceWebExtension
, makeWebFilePath
) where
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import Data.Function (on)
import Data.Hashable (Hashable(..))
import qualified System.Posix.FilePath as RFP
import Paths_databrary (getDataFileName)
import Files
data WebFilePath = WebFilePath
{ webFileRel :: RawFilePath
, webFileAbs :: RawFilePath
}
deriving (Show)
instance Eq WebFilePath where
(==) = (==) `on` webFileRel
(/=) = (/=) `on` webFileRel
instance Ord WebFilePath where
compare = compare `on` webFileRel
instance Hashable WebFilePath where
hashWithSalt n = hashWithSalt n . webFileRel
hash = hash . webFileRel
type WebDir = RawFilePath
getWebDir :: IO WebDir
getWebDir = do
webDir <- getDataFileName "web"
rawFilePath webDir
withWebDir :: (WebDir -> IO a) -> IO a
withWebDir f = getWebDir >>= f
-- | Convert a relative path from the web root into an expanded path including web root
makeWebFilePath :: RawFilePath -> IO WebFilePath
makeWebFilePath r = withWebDir $ \webDirRaw ->
return $ WebFilePath r (webDirRaw RFP.</> r)
splitWebExtensions :: WebFilePath -> IO (WebFilePath, BS.ByteString)
splitWebExtensions f = do
let (fn, ext) = RFP.splitExtensions $ webFileRel f
wfp <- makeWebFilePath fn
return (wfp, ext)
splitWebExtension :: WebFilePath -> IO (WebFilePath, BS.ByteString)
splitWebExtension f = do
let (fn, ext) = RFP.splitExtension $ webFileRel f
wfp <- makeWebFilePath fn
return (wfp, ext)
replaceWebExtension :: String -> WebFilePath -> WebFilePath
replaceWebExtension e (WebFilePath r ra) = WebFilePath (RFP.replaceExtension r re) (RFP.replaceExtension ra re)
where re = BSC.pack e
| databrary/databrary | src/Web.hs | agpl-3.0 | 1,814 | 0 | 11 | 313 | 543 | 299 | 244 | 51 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE PatternSynonyms #-}
{-|
Module : TypedFlow.Learn
Description : Loss functions and optimization strategies
Copyright : (c) Jean-Philippe Bernardy, 2017
License : LGPL-3
Maintainer : [email protected]
Stability : experimental
-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.KnownNat.Solver #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE UndecidableSuperClasses #-}
{-# LANGUAGE UnicodeSyntax #-}
module TypedFlow.Learn
(-- losses:
sparseCategorical, binary, timedCategorical, categoricalDistribution,sparseCategoricalDensePredictions,
-- types
Options(..), defaultOptions,
Function(..),Model,ModelOutput,
PreparedFunction(..), PreparedModel(..),
-- other
simpleModel, modelFunction, probeFunction,
addRegularizer,
prepare,
-- utils
placeholderName,
) where
import Data.Proxy
import TypedFlow.Types
import TypedFlow.Types.Proofs (knownAppend, (?>), )
import TypedFlow.Broadcast (doBroadcast, mapPlaceHolders, ConsSh,doBroadcastSingle)
import TypedFlow.Abstract (doExtractVars)
import TypedFlow.TF
import Prelude hiding (RealFrac(..))
import GHC.TypeLits
-- | Triple of values that are always output in a model: prediction, loss and accuracy.
-- @t@ is the type of the prediction.
-- @s@ is the shape of the loss and accuracy
type ModelOutput t predictionShape s
= Placeholders '[ '("loss",s,Float32) -- loss associated with the prediction
, '("accuracy",s,Float32) -- is the prediction correct?
, '("y_",s++predictionShape,t) -- prediction (which can contain prediction-shaped info)
]
pattern ModelOutput :: T (s++predictionShape) t -> T s Float32 -> T s Float32 -> ModelOutput t predictionShape s
pattern ModelOutput y loss accur = PHT loss :* PHT accur :* PHT y :* Unit
-- | A standard modelling function: (input value, gold value) ↦ (prediction, accuracy, loss).
-- input is the shape of the input.
-- output is the shape of the output (one element per individual loss and accuracy)
-- p is the shape of each output element.
-- g is the shape of each gold output --- often equal to p.
type Model input tIn g p output tOut
= T input tIn -> T (g++output) tOut -> ModelOutput tOut p output
-- | First type argument is the number of classes. @categorical
-- logits gold@ return (prediction, accuraccy, loss)
sparseCategorical :: forall nCat. KnownNat nCat => Model '[nCat] Float32 '[] '[] '[] Int32
sparseCategorical logits y =
let y_ = argmax0 logits
modelCorrect = cast (equal y_ y)
modelLoss = sparseSoftmaxCrossEntropyWithLogits y logits
in ModelOutput y_ modelLoss modelCorrect
-- | First type argument is the number of classes. @categorical
-- logits gold@ return (prediction, accuracy, loss)
sparseCategoricalDensePredictions :: forall nCat. KnownNat nCat
=> Tensor '[nCat] Float32
-> Tensor '[] Int32
-> ModelOutput Float32 '[nCat] '[]
sparseCategoricalDensePredictions logits y =
let y_ :: T '[nCat] Float32
y_ = softmax0 logits
modelCorrect = cast (equal (argmax0 logits) y)
modelLoss = sparseSoftmaxCrossEntropyWithLogits y logits
in ModelOutput y_ modelLoss modelCorrect
-- | First type argument is the number of classes.
-- @categoricalDistribution logits gold@ return (prediction,
-- accuraccy, loss) accuracy is reported as predicting the same class
-- as the input 'winning' class.
categoricalDistribution :: forall nCat. KnownNat nCat => Model '[nCat] Float32 '[nCat] '[nCat] '[] Float32
categoricalDistribution logits y =
ModelOutput (softmax0 logits)
(softmaxCrossEntropyWithLogits y logits)
(cast (equal (argmax0 @'B32 logits) (argmax0 y)))
-- | @timedCategorical targetWeights logits y@
--
-- targetWeights: a zero-one matrix of the same size as
-- decoder_outputs. It is intended to mask padding positions outside
-- of the target sequence lengths with values 0.
--
-- Note that the accuracy is computed by multiplying the accuracies at
-- individual time steps with the targetWeights.
timedCategorical :: forall len nCat bits. KnownNat nCat => KnownNat len => KnownBits bits =>
Tensor '[len] (Flt bits) -> Tensor '[len,nCat] (Flt bits) -> Tensor '[len] Int32 -> ModelOutput (Flt bits) '[len,nCat] '[]
timedCategorical targetWeights logits y =
let y_ :: Tensor '[len] Int32
y_ = argmax1 logits
modelY = softmax1 logits
-- correct prediction for each position
correctPrediction :: Tensor '[len] TFBool
correctPrediction = equal y_ y
-- total number of correct predictions
correctPredictionWeighted :: Tensor '[] (Flt bits)
correctPredictionWeighted = reduceSumAll (cast @(Flt bits) correctPrediction ⊙ targetWeights)
weightSum = reduceSumAll targetWeights
modelCorrect :: Tensor '[] Float32
modelCorrect = cast (correctPredictionWeighted / weightSum)
crossEntropies = zipWithT sparseSoftmaxCrossEntropyWithLogits y logits
modelLoss = cast @Float32 (reduceSumAll (crossEntropies ⊙ targetWeights) / weightSum)
in ModelOutput modelY modelLoss modelCorrect
-- | Model with @n@ binary outputs.
binary :: KnownNat n => Model '[n] Float32 '[] '[] '[n] Int32
binary logits y =
let y_ = cast @Int32 (round sigy_)
sigy_ = sigmoid logits
in ModelOutput (y_)
(sigmoidCrossEntropyWithLogits (cast @Float32 y) logits)
(cast (equal y_ y))
-- | Model compiler options
data Options = Options {maxGradientNorm :: Maybe Prelude.Float -- ^ apply gradient clipping
}
-- | default model compiler options
defaultOptions :: Options
defaultOptions = Options {maxGradientNorm = Nothing}
type family Concatenate xs where
Concatenate (x ': xs) = x ++ Concatenate xs
Concatenate '[] = '[]
genPlaceholders :: All KnownPlaceholder shapesAndTypes => SList shapesAndTypes -> Placeholders shapesAndTypes
genPlaceholders Unit = Unit
genPlaceholders (ph :* names) = PHT (T (ExternalVar (Ref (placeholderName ph) typeSShape typeSTyp))) :* genPlaceholders names
placeholderName :: forall (ph :: PH) p. KnownPlaceholder ph => p ph -> String
placeholderName proxy = refName (placeHolderRef proxy)
simpleModel :: forall p sx tx sy ty sy_ ty_.
(KnownShape sy_, KnownShape p, KnownShape sx, KnownTyp ty_, KnownShape sy, KnownTyp tx, KnownTyp ty)
=> (Tensor sx tx -> Tensor sy ty -> ModelOutput ty_ p sy_)
-> Function
simpleModel f = knownAppend @sy_ @p ?> modelFunction "runModel" f'
where f' :: Placeholders '[ '("x",sx,tx), '("y",sy,ty)] -> ModelOutput ty_ p sy_
f' (PHT x :* PHT y :* Unit) = f x y
-- | Add a term to the loss. This function is intendend to add
-- regularizers, ie. losses that do not depend on the predicted
-- output, but rather on the structure of a parameter.
addRegularizer :: Scalar Float32 -> Gen ()
addRegularizer r = GPState $ \GState{..} -> ((),GState{genRegularizers=r:genRegularizers,..})
knownBatchModel :: forall n ps. KnownNat n => NP (Sat KnownPlaceholder) ps -> NP (Sat KnownPlaceholder) (Ap (FMap (ConsSh n)) ps)
knownBatchModel Unit = Unit
knownBatchModel (Comp Dict :* xs) = Sat :* knownBatchModel @n xs
-- | take the mean of loss/accur over the batch, etc. and add regulariser to loss
consolidate :: forall s rest. KnownShape s
=> Scalar Float32
-> Placeholders ( '("loss",s ,Float32) ': '("accuracy",s ,Float32) ': rest)
-> Placeholders ( '("loss",'[],Float32) ': '("accuracy",'[],Float32) ': rest)
consolidate extraLoss (PHT loss :* PHT accur :* rest) = (PHT (reduceMeanAll loss + extraLoss) :* PHT (reduceMeanAll accur) :* rest)
class (All KnownPlaceholder ps, KnownLen ps) => KnownPHS ps
instance (All KnownPlaceholder ps, KnownLen ps) => KnownPHS ps
data PreparedFunction = PreparedFunction {pfName :: String,
pfBatched :: Bool,
pfInputs, pfOutputs :: SomeSuch KnownPHS Placeholders}
data PreparedModel = PreparedModel {pmBatchSize :: Integer,
pmParams :: [VarInfo],
pmFunctions :: [PreparedFunction]
}
-- | Prepare compilation of a model by:
-- extracting and exposing parameters
-- batching the model
-- exposing placeholders
-- consolidating loss and accuracy
-- adding regularizers to the loss
prepare :: forall bs. (KnownNat bs)
=> Gen [Function]
-> PreparedModel
prepare fGen =
PreparedModel
{pmBatchSize = natVal (Proxy @bs)
,pmParams = [VarInfo{varInitial=fmap doBroadcastSingle varInitial,..} | VarInfo{..} <- filter varTrainable vars]
,pmFunctions = flip map fs $ \case
ModelFn nm st1 st2 f ->
knownAll (knownBatchModel @bs st1) $
knownAll (knownBatchModel @bs st2) $
knownAll st1 $
knownAll st2 $
let placeHolders = genPlaceholders typeSList
u = -777 -- magic unique identifier for the batch dimension
in PreparedFunction nm
True
(SomeSuch placeHolders)
(SomeSuch $ doBroadcast (consolidate {-@(bs ': s) @(BPH bs st2)-} regular (mapPlaceHolders @bs u True f placeHolders)))
ProbeFn nm st1 st2 f ->
knownAll st1 $
knownAll st2 $
let placeHolders = genPlaceholders typeSList
in PreparedFunction nm False (SomeSuch placeHolders) (SomeSuch (doBroadcast (f placeHolders)))
}
where (fs,finalState,vars) = doExtractVars fGen
regular = sum (genRegularizers finalState)
data Function where
ModelFn :: (KnownShape s, KnownLen st1, KnownLen st2)
=> String
-> NP (Sat KnownPlaceholder) st1 -> NP (Sat KnownPlaceholder) st2
-> (Placeholders st1 -> Placeholders ('("loss",s,Float32) ': '("accuracy",s,Float32) ': st2)) -> Function
ProbeFn :: (KnownLen st1, KnownLen st2, All KnownPlaceholder st1, All KnownPlaceholder st2)
=> String
-> NP (Sat KnownPlaceholder) st1 -> NP (Sat KnownPlaceholder) st2
-> (Placeholders st1 -> Placeholders st2) -> Function
modelFunction :: (KnownShape s, KnownLen st1, KnownLen st2, All KnownPlaceholder st1, All KnownPlaceholder st2)
=> String
-> (Placeholders st1 -> Placeholders ('("loss",s,Float32) ': '("accuracy",s,Float32) ': st2)) -> Function
modelFunction nm f = ModelFn nm (allKnown @KnownPlaceholder) (allKnown @KnownPlaceholder) f
probeFunction :: (KnownLen st1, KnownLen st2, All KnownPlaceholder st1, All KnownPlaceholder st2)
=> String
-> (Placeholders st1 -> Placeholders st2) -> Function
probeFunction nm f = ProbeFn nm (allKnown @KnownPlaceholder) (allKnown @KnownPlaceholder) f
| GU-CLASP/TypedFlow | TypedFlow/Learn.hs | lgpl-3.0 | 11,520 | 0 | 22 | 2,484 | 2,893 | 1,551 | 1,342 | -1 | -1 |
{-# LANGUAGE TypeFamilies #-}
module Lupo.Backends.View.Views
( singleDayView
, multiDaysView
, monthView
, searchResultView
, loginView
, initAccountView
, adminView
, entryEditorView
, entryPreviewView
, entriesFeed
) where
import qualified Data.List as L
import Data.Maybe
import Data.Monoid
import qualified Data.Text as T
import qualified Data.Text.Encoding as Encoding
import Snap
import qualified Snap.Snaplet.Heist as SH
import Text.Shakespeare.Text hiding (toText)
import qualified Heist as H
import qualified Heist.Interpreted as H
import Text.XmlHtml hiding (render)
import Lupo.Application
import qualified Lupo.Backends.View.Internal as I
import Lupo.Config
import qualified Lupo.Entry as E
import Lupo.Import
import qualified Lupo.Locale as L
import qualified Lupo.Navigation as N
import qualified Lupo.Syntax as S
import qualified Lupo.URLMapper as U
import Lupo.Util
import qualified Lupo.View as V
singleDayView :: m ~ H.HeistT LupoHandler LupoHandler => E.Page -> N.Navigation m -> E.Comment -> [T.Text] -> [T.Text] -> V.View LupoHandler
singleDayView page nav c notice errs =
makeView renderPublic $ ViewRep (fromJust pageTitle) $ H.callTemplate "day"
[ ("lupo:day-title", I.dayTitle reqDay)
, ("lupo:entries", pure entriesTemplate)
, ("lupo:if-commented", ifCommented)
, ("lupo:comments-caption", H.textSplice =<< L.localize "Comments")
, ("lupo:comments", H.mapSplices I.comment $ page ^. E.pageComments)
, ("lupo:page-navigation", I.singleDayNavigation nav)
, ("lupo:new-comment-caption", H.textSplice =<< L.localize "New Comment")
, ("lupo:new-comment-notice", newCommentNotice)
, ("lupo:new-comment-errors", newCommentErrors)
, ("lupo:new-comment-url", U.urlSplice $ U.commentPostPath reqDay)
, ("lupo:comment-name", H.textSplice $ c ^. E.commentName)
, ("lupo:comment-body", H.textSplice $ c ^. E.commentBody)
, ("lupo:name-label", H.textSplice =<< L.localize "Name")
, ("lupo:content-label", H.textSplice =<< L.localize "Content")
] where
pageTitle = page ^? E.pageEntries . ix 0 . E.savedContent . E.entryTitle
reqDay = page ^. E.pageDay
entriesTemplate = concat $ snd $ L.mapAccumL accum 1 $ page ^. E.pageEntries where
accum i e = (succ i, I.anEntry (Just i) e)
ifCommented
| page ^. E.numOfComments > 0 = childNodes <$> H.getParamNode
| otherwise = pure []
newCommentNotice
| null notice = pure []
| otherwise = H.callTemplate "_notice"
[ ("lupo:notice-class", H.textSplice "notice success")
, ("lupo:notice-messages", H.mapSplices mkRow notice)
]
newCommentErrors
| null errs = pure []
| otherwise = H.callTemplate "_notice"
[ ("lupo:notice-class", H.textSplice "notice error")
, ("lupo:notice-messages", H.mapSplices mkRow errs)
]
mkRow txt = do
txt' <- L.localize txt
pure $ [Element "li" [] [TextNode txt']]
multiDaysView :: m ~ H.HeistT LupoHandler LupoHandler => N.Navigation m -> [E.Page] -> V.View LupoHandler
multiDaysView nav pages = makeView renderPublic $ ViewRep title $ do
daysPerPage <- refLupoConfig lcDaysPerPage
H.callTemplate "multi-days"
[ ("lupo:page-navigation", I.multiDaysNavigation daysPerPage nav)
, ("lupo:day-summaries", H.mapSplices I.daySummary pages)
] where
title = case pages of
ds@((view E.pageDay -> d) : _) -> [st|#{formatTime "%Y-%m-%d" d}-#{toText $ length ds}|]
_ -> ""
monthView :: m ~ H.HeistT LupoHandler LupoHandler => N.Navigation m -> [E.Page] -> V.View LupoHandler
monthView nav pages = makeView renderPublic $ ViewRep (formatTime "%Y-%m" $ nav ^. N.getThisMonth) $ do
H.callTemplate "multi-days"
[ ("lupo:page-navigation", I.monthNavigation nav)
, ("lupo:day-summaries", if null pages then
I.emptyMonth
else
H.mapSplices I.daySummary pages)
]
searchResultView :: T.Text -> [E.Saved E.Entry] -> V.View LupoHandler
searchResultView word es = makeView renderPublic $ ViewRep word $ H.callTemplate "search-result"
[ ("lupo:search-word", H.textSplice word)
, ("lupo:search-results", H.mapSplices I.searchResult es)
]
loginView :: T.Text -> V.View LupoHandler
loginView challenge = makeView renderPlain $ ViewRep "Login" $ H.callTemplate "login"
[ ("lupo:login-url", U.urlSplice U.loginPath)
, ("lupo:challenge", H.textSplice challenge)
, ("lupo:js-libs", H.mapSplices scriptSplice ["sha1", "lupo"])
] where
scriptSplice name = do
src <- Encoding.decodeUtf8 <$> U.getURL (U.fullPath $ "js/" <> name <> ".js")
pure $ [Element "script" [("src", src)] []]
initAccountView :: V.View LupoHandler
initAccountView = makeView renderPlain $ ViewRep "Init Account" $ H.callTemplate "init-account"
[ ("lupo:init-account-url", U.urlSplice U.initAccountPath)
]
adminView :: [E.Page] -> V.View LupoHandler
adminView days = makeView renderAdmin $ ViewRep "Lupo Admin" $ H.callTemplate "admin"
[ ("lupo:days", H.mapSplices makeDayRow days)
, ("lupo:new-entry-url", U.urlSplice (U.fullPath "admin/new"))
] where
makeDayRow E.Page { E._pageEntries = []
} = pure []
makeDayRow [email protected] { E._pageEntries = e : es
} = do
headRow <- (dateTh :) <$> makeEntryRow e
tailRows <- sequence $ makeEntryRow <$> es
pure $ tr <$> headRow : tailRows
where
tr t = Element "tr" [] t
dateTh = Element "th" [("class", "date"), ("rowspan", toText $ length $ e : es)]
[ TextNode $ formatTime "%Y-%m-%d" $ p ^. E.pageDay
]
makeEntryRow e' = do
showPath <- Encoding.decodeUtf8 <$> U.getURL (U.entryPath e')
editPath <- Encoding.decodeUtf8 <$> U.getURL (U.entryEditPath e')
deletePath <- Encoding.decodeUtf8 <$> U.getURL (U.entryDeletePath e')
pure
[ Element "td" [] [TextNode $ e' ^. E.savedContent . E.entryTitle]
, Element "td" [("class", "action")]
[ Element "a" [("href", showPath)] [TextNode "Show"]
, TextNode " "
, Element "a" [("href", editPath)] [TextNode "Edit"]
, TextNode " "
, Element "a"
[ ("href", deletePath)
, ("onclick", "return confirm(\"Are you sure you want to delete?\");")
]
[ TextNode "Delete"
]
]
]
entryEditorView :: E.Saved E.Entry -> T.Text -> Getter U.URLMapper U.Path -> V.View LupoHandler
entryEditorView s editType editPath = makeView renderAdmin $
ViewRep editorTitle $ H.callTemplate "entry-editor"
[ ("lupo:editor-title", H.textSplice [st|#{editType}: #{editorTitle}: #{entryTitle}|])
, ("lupo:edit-path", U.urlSplice editPath)
, ("lupo:entry-title", H.textSplice $ s ^. E.savedContent . E.entryTitle)
, ("lupo:entry-body", H.textSplice $ s ^. E.savedContent . E.entryBody)
] where
entryTitle = s ^. E.savedContent . E.entryTitle
editorTitle = formatTime "%Y-%m-%d" $ s ^. E.createdAt
entryPreviewView :: E.Saved E.Entry -> T.Text -> Getter U.URLMapper U.Path -> V.View LupoHandler
entryPreviewView e editType editPath = makeView renderAdmin $
ViewRep previewTitle $ H.callTemplate "entry-preview"
[ ( "lupo:preview-title"
, H.textSplice [st|#{editType}: #{previewTitle}: #{entryTitle}|]
)
, ("lupo:preview-body", pure $ I.anEntry Nothing e)
, ("lupo:edit-path", U.urlSplice editPath)
, ("lupo:entry-title", H.textSplice $ e ^. E.savedContent . E.entryTitle)
, ("lupo:entry-body", H.textSplice $ e ^. E.savedContent . E.entryBody)
] where
entryTitle = e ^. E.savedContent . E.entryTitle
previewTitle = formatTime "%Y-%m-%d" $ e ^. E.createdAt
entriesFeed :: [E.Saved E.Entry] -> V.View LupoHandler
entriesFeed entries = V.View $ do
title <- refLupoConfig lcSiteTitle
author <- refLupoConfig lcAuthorName
SH.withSplices
[ ("lupo:feed-title", textSplice title)
, ("lupo:last-updated", textSplice $ maybe "" formatTimeForAtom lastUpdated)
, ("lupo:index-path", U.urlSplice $ U.fullPath "")
, ("lupo:feed-path", U.urlSplice U.feedPath)
, ("lupo:author-name", textSplice author)
, ("lupo:entries", H.mapSplices entryToFeed entries)
] $ SH.renderAs "application/atom+xml" "feed"
where
lastUpdated = view E.modifiedAt <$> listToMaybe entries
entryToFeed :: E.Saved E.Entry -> H.Splice LupoHandler
entryToFeed e = H.callTemplate "_feed-entry"
[ ("lupo:title", textSplice $ e ^. E.savedContent . E.entryTitle)
, ("lupo:link", urlSplice)
, ("lupo:entry-id", urlSplice)
, ("lupo:published", textSplice $ formatTimeForAtom $ e ^. E.createdAt)
, ("lupo:updated", textSplice $ formatTimeForAtom $ e ^. E.modifiedAt)
, ("lupo:summary", textSplice $ getSummary $ e ^. E.savedContent . E.entryBody)
] where
getSummary = summarize . nodesToPlainText . S.renderBody where
summarize t = if T.length t <= 140
then t
else T.take 140 t <> "..."
nodesToPlainText = L.foldl' (\l r -> l <> nodeText r) ""
urlSplice = do
urls <- U.getURLMapper
textSplice $ Encoding.decodeUtf8 $ urls ^. U.entryPath e
data ViewRep m = ViewRep
{ viewTitle :: T.Text
, viewSplice :: H.Splice m
}
makeView :: (ViewRep m -> m ()) -> ViewRep m -> V.View m
makeView renderer rep = V.View $ renderer rep
renderPublic :: ( h ~ H.HeistT (Handler b b) (Handler b b), SH.HasHeist b, GetLupoConfig h, U.HasURLMapper h) => ViewRep (Handler b b) -> Handler b v ()
renderPublic rep = SH.heistLocal bindSplices $ SH.render "public" where
bindSplices =
H.bindSplices
[ ("lupo:page-title", H.textSplice =<< makePageTitle rep)
, ("lupo:site-title", H.textSplice =<< refLupoConfig lcSiteTitle)
, ("lupo:style-sheet", U.urlSplice $ U.cssPath "diary.css")
, ("lupo:footer-body", refLupoConfig lcFooterBody)
, ("lupo:feed-path", U.urlSplice U.feedPath)
, ("lupo:feed-icon-path", U.urlSplice $ U.fullPath "images/feed.png")
]
. H.bindSplice "lupo:main-body" (viewSplice rep)
renderPlain :: (h ~ (Handler b b), SH.HasHeist b, U.HasURLMapper (H.HeistT h h)) => ViewRep h -> Handler b v ()
renderPlain rep = SH.heistLocal bindSplices $ SH.render "default" where
bindSplices = H.bindSplices
[ ("lupo:page-title", H.textSplice $ viewTitle rep)
, ("lupo:style-sheet", U.urlSplice $ U.cssPath "plain.css")
, ("apply-content", viewSplice rep)
]
renderAdmin :: ( h ~ H.HeistT (Handler b b) (Handler b b), SH.HasHeist b, GetLupoConfig h, U.HasURLMapper h) => ViewRep (Handler b b) -> Handler b v ()
renderAdmin v = SH.heistLocal bindSplices $ SH.render "admin-frame" where
bindSplices = H.bindSplices
[ ("lupo:page-title", H.textSplice =<< makePageTitle v)
, ("lupo:site-title", H.textSplice =<< refLupoConfig lcSiteTitle)
, ("lupo:style-sheet", U.urlSplice $ U.cssPath "admin.css")
, ("lupo:admin-url", U.urlSplice U.adminPath)
, ("lupo:footer-body", refLupoConfig lcFooterBody)
]
. H.bindSplice "lupo:main-body" (viewSplice v)
makePageTitle :: GetLupoConfig n => ViewRep m -> n T.Text
makePageTitle rep = do
siteTitle <- refLupoConfig lcSiteTitle
pure $
case viewTitle rep of
"" -> siteTitle
t -> [st| #{t} - #{siteTitle}|]
| keitax/lupo | src/Lupo/Backends/View/Views.hs | lgpl-3.0 | 11,425 | 7 | 20 | 2,464 | 3,623 | 1,911 | 1,712 | -1 | -1 |
{-
Created : 2014 Feb by Harold Carr.
Last Modified : 2014 Jun 30 (Mon) 02:45:04 by Harold Carr.
-}
module Main where
import Data.List (foldl')
-- profiling with GHC - p. 122
{-
cabal clean
cabal configure --enable-executable-profiling
cabal build
dist/build/profiling-example/profiling-example +RTS -p -RTS
profiling-example.prof
dist/build/profiling-example/profiling-example +RTS -h -RTS
dist/build/profiling-example/profiling-example +RTS -hy -RTS
hp2ps profiling-example.hp
open /Applications/Preview.app profiling-example.ps
-}
main :: IO ()
main = putStrLn $ show (length (show result))
result :: Integer
result = foldr (*) 1 [1 .. 100000]
{-
main :: IO ()
main = do
print $ foldl' (+) 0 ([1 .. 1000000000] :: [Integer]) -- 500000000500000000
-}
-- End of file.
| haroldcarr/learn-haskell-coq-ml-etc | haskell/book/2014-Alejandro_Serrano_Mena-Beginning_Haskell/old/code/src/C05/Main.hs | unlicense | 820 | 0 | 10 | 159 | 78 | 46 | 32 | 6 | 1 |
-- file Ch01/WC.hs
-- NOTE lines beginning with "--" are comments
-- NOTE In GHCI, :set (prompt/ +t)
-- NOTE :show bindings, show 'it' bindings
main :: IO ()
main = interact wordCount
where wordCount input = show (length (lines input)) ++ "\n"
exercise1 :: IO ()
exercise1 = do
let a = succ 7 + pred 7 + round (sqrt 15)
b = sqrt 16
c = truncate pi
d = round pi + ceiling pi + floor 4.3
print $ a
print $ b
print $ c
print $ d
filePath = "Ch01/text.txt"
exercise2 :: IO ()
exercise2 = do
content <- readFile filePath
let num = length $ words content
print $ num
exercise3 :: IO ()
exercise3 = do
content <- readFile filePath
let num = length content
print $ num
| Numberartificial/Realworld-Haskell | code/Ch01/WC.hs | apache-2.0 | 709 | 0 | 13 | 183 | 262 | 124 | 138 | 24 | 1 |
-- |
-- Module : Data.Time.Zones.TH
-- Copyright : (C) 2014 Mihaly Barasz
-- License : Apache-2.0, see LICENSE
-- Maintainer : Mihaly Barasz <[email protected]>
-- Stability : experimental
--
-- /Example usage:/
--
-- >
-- >{-# LANGUAGE TemplateHaskell #-}
-- >
-- >import Data.Time
-- >import Data.Time.Zones
-- >import Data.Time.Zones.TH
-- >
-- >tzBudapest :: TZ
-- >tzBudapest = $(includeTZFromDB "Europe/Budapest")
-- >
-- >tzLosAngeles :: TZ
-- >tzLosAngeles = $(includeTZFromDB "America/Los_Angeles")
-- >
-- >main :: IO ()
-- >main = do
-- > t <- getCurrentTime
-- > putStrLn $ "Time in Budapest: " ++ show (utcToLocalTimeTZ tzBudapest t)
-- > putStrLn $ "Time in Los Angeles: " ++ show (utcToLocalTimeTZ tzLosAngeles t)
--
{-# LANGUAGE TemplateHaskell #-}
module Data.Time.Zones.TH (
includeTZFromDB,
includeSystemTZ,
includeTZFromFile,
) where
import Control.DeepSeq
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Time.Zones.Files
import Data.Time.Zones.Read
import Language.Haskell.TH
-- | Generate a `TZ` definition from an entry out of the time zone
-- database shipped with this package.
includeTZFromDB :: String -> Q Exp
includeTZFromDB tzName = do
desc <- runIO $ timeZonePathFromDB tzName >>= BL.readFile
parseTZ desc
-- | Generate a `TZ` definition from a system time zone information file.
--
-- See also: `loadSystemTZ` for details on how system time zone files
-- are located.
--
-- Note, this is unlikely to work on non-posix systems (e.g.,
-- Windows), use `includeTZFromDB` or `includeTZFromFile` instead.
includeSystemTZ :: String -> Q Exp
includeSystemTZ tzName = do
desc <- runIO $ pathForSystemTZ tzName >>= BL.readFile
parseTZ desc
-- | Generate a `TZ` definition from the given time zone information file.
includeTZFromFile :: FilePath -> Q Exp
includeTZFromFile fname = do
desc <- runIO $ BL.readFile fname
parseTZ desc
--------------------------------------------------------------------------------
-- Template Haskell helper functions.
-- Why the round-trip through `String`? Why don't we generate a fully
-- expanded definition of `TZ`?
--
-- First, we want a definition that is stored compactly in the
-- resulting binary, and 'String' literals are stored as C strings.
--
-- Secondly, vectors (which are the internal representation of TZ)
-- don't have literal representation, so we couldn't produce a
-- fully-evaluated representation anyway. Also, it would be much more
-- complicated.
--
parseTZ :: BL.ByteString -> Q Exp
parseTZ desc = do
-- Check that the description actually parses, so if there's a bug
-- we fail at compile time and not at run time:
parseOlson desc `deepseq` return ()
[| parseOlson (BL.pack $(stringE $ BL.unpack desc)) |]
| nilcons/haskell-tz | Data/Time/Zones/TH.hs | apache-2.0 | 2,754 | 0 | 10 | 462 | 288 | 177 | 111 | 26 | 1 |
-- http://www.codewars.com/kata/5326ef17b7320ee2e00001df
module EscapeTheMines where
import Data.Maybe
import Control.Arrow
import Data.List
type XY = (Int,Int)
data Move = U | D | R | L deriving (Eq, Show)
rev :: Move -> Move
rev U = D
rev D = U
rev R = L
rev L = R
move :: Move -> XY -> XY
move U = second pred
move D = second succ
move R = first succ
move L = first pred
solve :: [[Bool]] -> XY -> XY -> [Move]
solve grid m = reverse . fromJust . path [U, D, R, L] where
lenX = length grid
lenY = length (head grid)
unmined (x, y) = x >= 0 && y >= 0 && x < lenX && y < lenY && grid !! x !! y
path dirs p
| p==m = Just []
| not (unmined p) = Nothing
| otherwise = listToMaybe $ mapMaybe f dirs where
f dir = fmap (rev dir : ) $ path (delete (rev dir) [U, D, R, L]) (move dir p)
| Bodigrim/katas | src/haskell/3-Escape-the-Mines-.hs | bsd-2-clause | 831 | 0 | 16 | 227 | 418 | 218 | 200 | 26 | 1 |
{-# LANGUAGE GADTs, DataKinds, KindSignatures, TypeOperators, TypeFamilies,
MultiParamTypeClasses, FlexibleInstances, PolyKinds,
FlexibleContexts, UndecidableInstances, ConstraintKinds,
ScopedTypeVariables, TypeInType #-}
module Data.Type.Set (Set(..), Union, Unionable, union, quicksort, append,
Sort, Sortable, (:++), Split(..), Cmp, Filter, Flag(..),
Nub, Nubable(..), AsSet, asSet, IsSet, Subset(..),
Delete(..), Proxy(..), remove, Remove, (:\),
Elem(..), Member(..), MemberP, NonMember) where
import GHC.TypeLits
import Data.Type.Bool
import Data.Type.Equality
data Proxy (p :: k) = Proxy
-- Value-level 'Set' representation, essentially a list
--type Set :: [k] -> Type
data Set (n :: [k]) where
{--| Construct an empty set -}
Empty :: Set '[]
{--| Extend a set with an element -}
Ext :: e -> Set s -> Set (e ': s)
instance Show (Set '[]) where
show Empty = "{}"
instance (Show e, Show' (Set s)) => Show (Set (e ': s)) where
show (Ext e s) = "{" ++ show e ++ (show' s) ++ "}"
class Show' t where
show' :: t -> String
instance Show' (Set '[]) where
show' Empty = ""
instance (Show' (Set s), Show e) => Show' (Set (e ': s)) where
show' (Ext e s) = ", " ++ show e ++ (show' s)
instance Eq (Set '[]) where
(==) _ _ = True
instance (Eq e, Eq (Set s)) => Eq (Set (e ': s)) where
(Ext e m) == (Ext e' m') = e == e' && m == m'
instance Ord (Set '[]) where
compare _ _ = EQ
instance (Ord a, Ord (Set s)) => Ord (Set (a ': s)) where
compare (Ext a as) (Ext a' as') = case compare a a' of
EQ ->
compare as as'
other ->
other
{-| At the type level, normalise the list form to the set form -}
type AsSet s = Nub (Sort s)
{-| At the value level, noramlise the list form to the set form -}
asSet :: (Sortable s, Nubable (Sort s)) => Set s -> Set (AsSet s)
asSet x = nub (quicksort x)
{-| Predicate to check if in the set form -}
type IsSet s = (s ~ Nub (Sort s))
{-| Useful properties to be able to refer to someties -}
type SetProperties (f :: [k]) =
( Union f ('[] :: [k]) ~ f,
Split f ('[] :: [k]) f,
Union ('[] :: [k]) f ~ f,
Split ('[] :: [k]) f f,
Union f f ~ f,
Split f f f,
Unionable f ('[] :: [k]),
Unionable ('[] :: [k]) f
)
{-- Union --}
{-| Union of sets -}
type Union s t = Nub (Sort (s :++ t))
union :: (Unionable s t) => Set s -> Set t -> Set (Union s t)
union s t = nub (quicksort (append s t))
type Unionable s t = (Sortable (s :++ t), Nubable (Sort (s :++ t)))
{-| List append (essentially set disjoint union) -}
type family (:++) (x :: [k]) (y :: [k]) :: [k] where
'[] :++ xs = xs
(x ': xs) :++ ys = x ': (xs :++ ys)
infixr 5 :++
append :: Set s -> Set t -> Set (s :++ t)
append Empty x = x
append (Ext e xs) ys = Ext e (append xs ys)
{-| Delete elements from a set -}
type family (m :: [k]) :\ (x :: k) :: [k] where
'[] :\ x = '[]
(x ': xs) :\ x = xs :\ x
(y ': xs) :\ x = y ': (xs :\ x)
class Remove s t where
remove :: Set s -> Proxy t -> Set (s :\ t)
instance Remove '[] t where
remove Empty Proxy = Empty
instance {-# OVERLAPS #-} Remove xs x => Remove (x ': xs) x where
remove (Ext _ xs) x@Proxy = remove xs x
instance {-# OVERLAPPABLE #-} (((y : xs) :\ x) ~ (y : (xs :\ x)), Remove xs x)
=> Remove (y ': xs) x where
remove (Ext y xs) (x@Proxy) = Ext y (remove xs x)
{-| Splitting a union a set, given the sets we want to split it into -}
class Split s t st where
-- where st ~ Union s t
split :: Set st -> (Set s, Set t)
instance Split '[] '[] '[] where
split Empty = (Empty, Empty)
instance {-# OVERLAPPABLE #-} Split s t st => Split (x ': s) (x ': t) (x ': st) where
split (Ext x st) = let (s, t) = split st
in (Ext x s, Ext x t)
instance {-# OVERLAPS #-} Split s t st => Split (x ': s) t (x ': st) where
split (Ext x st) = let (s, t) = split st
in (Ext x s, t)
instance {-# OVERLAPS #-} (Split s t st) => Split s (x ': t) (x ': st) where
split (Ext x st) = let (s, t) = split st
in (s, Ext x t)
{-| Remove duplicates from a sorted list -}
type family Nub t where
Nub '[] = '[]
Nub '[e] = '[e]
Nub (e ': e ': s) = Nub (e ': s)
Nub (e ': f ': s) = e ': Nub (f ': s)
{-| Value-level counterpart to the type-level 'Nub'
Note: the value-level case for equal types is not define here,
but should be given per-application, e.g., custom 'merging' behaviour may be required -}
class Nubable t where
nub :: Set t -> Set (Nub t)
instance Nubable '[] where
nub Empty = Empty
instance Nubable '[e] where
nub (Ext x Empty) = Ext x Empty
instance Nubable (e ': s) => Nubable (e ': e ': s) where
nub (Ext _ (Ext e s)) = nub (Ext e s)
instance {-# OVERLAPS #-} (Nub (e ': f ': s) ~ (e ': Nub (f ': s)),
Nubable (f ': s)) => Nubable (e ': f ': s) where
nub (Ext e (Ext f s)) = Ext e (nub (Ext f s))
{-| Construct a subsetset 's' from a superset 't' -}
class Subset s t where
subset :: Set t -> Set s
instance Subset '[] '[] where
subset xs = Empty
instance {-# OVERLAPPABLE #-} Subset s t => Subset s (x ': t) where
subset (Ext _ xs) = subset xs
instance {-# OVERLAPS #-} Subset s t => Subset (x ': s) (x ': t) where
subset (Ext x xs) = Ext x (subset xs)
{-| Type-level quick sort for normalising the representation of sets -}
type family Sort (xs :: [k]) :: [k] where
Sort '[] = '[]
Sort (x ': xs) = ((Sort (Filter FMin x xs)) :++ '[x]) :++ (Sort (Filter FMax x xs))
data Flag = FMin | FMax
type family Filter (f :: Flag) (p :: k) (xs :: [k]) :: [k] where
Filter f p '[] = '[]
Filter FMin p (x ': xs) = If (Cmp x p == LT) (x ': (Filter FMin p xs)) (Filter FMin p xs)
Filter FMax p (x ': xs) = If (Cmp x p == GT || Cmp x p == EQ) (x ': (Filter FMax p xs)) (Filter FMax p xs)
type family DeleteFromList (e :: elem) (list :: [elem]) where
DeleteFromList elem '[] = '[]
DeleteFromList elem (x ': xs) = If (Cmp elem x == EQ)
xs
(x ': DeleteFromList elem xs)
type family Delete elem set where
Delete elem (Set xs) = Set (DeleteFromList elem xs)
{-| Value-level quick sort that respects the type-level ordering -}
class Sortable xs where
quicksort :: Set xs -> Set (Sort xs)
instance Sortable '[] where
quicksort Empty = Empty
instance (Sortable (Filter FMin p xs),
Sortable (Filter FMax p xs), FilterV FMin p xs, FilterV FMax p xs) => Sortable (p ': xs) where
quicksort (Ext p xs) = ((quicksort (less p xs)) `append` (Ext p Empty)) `append` (quicksort (more p xs))
where less = filterV (Proxy::(Proxy FMin))
more = filterV (Proxy::(Proxy FMax))
{- Filter out the elements less-than or greater-than-or-equal to the pivot -}
class FilterV (f::Flag) p xs where
filterV :: Proxy f -> p -> Set xs -> Set (Filter f p xs)
instance FilterV f p '[] where
filterV _ p Empty = Empty
instance (Conder ((Cmp x p) == LT), FilterV FMin p xs) => FilterV FMin p (x ': xs) where
filterV f@Proxy p (Ext x xs) = cond (Proxy::(Proxy ((Cmp x p) == LT)))
(Ext x (filterV f p xs)) (filterV f p xs)
instance (Conder (((Cmp x p) == GT) || ((Cmp x p) == EQ)), FilterV FMax p xs) => FilterV FMax p (x ': xs) where
filterV f@Proxy p (Ext x xs) = cond (Proxy::(Proxy (((Cmp x p) == GT) || ((Cmp x p) == EQ))))
(Ext x (filterV f p xs)) (filterV f p xs)
class Conder g where
cond :: Proxy g -> Set s -> Set t -> Set (If g s t)
instance Conder True where
cond _ s t = s
instance Conder False where
cond _ s t = t
{-| Open-family for the ordering operation in the sort -}
type family Cmp (a :: k) (b :: k) :: Ordering
{-| Access the value at a type present in a set. -}
class Elem a s where
project :: Proxy a -> Set s -> a
instance {-# OVERLAPS #-} Elem a (a ': s) where
project _ (Ext x _) = x
instance {-# OVERLAPPABLE #-} Elem a s => Elem a (b ': s) where
project p (Ext _ xs) = project p xs
-- | Value level type list membership predicate: does the type 'a' show up in
-- the type list 's'?
class Member a s where
member :: Proxy a -> Set s -> Bool
instance Member a '[] where
member _ Empty = False
instance {-# OVERLAPS #-} Member a (a ': s) where
member _ (Ext x _) = True
instance {-# OVERLAPPABLE #-} Member a s => Member a (b ': s) where
member p (Ext _ xs) = member p xs
-- | Type level type list membership predicate: does the type 'a' show up in the
-- type list 's'?
--type MemberP :: k -> [k] -> Bool
type family MemberP a s :: Bool where
MemberP a '[] = False
MemberP a (a ': s) = True
MemberP a (b ': s) = MemberP a s
type NonMember a s = MemberP a s ~ False
| dorchard/type-level-sets | src/Data/Type/Set.hs | bsd-2-clause | 9,099 | 6 | 15 | 2,701 | 4,087 | 2,171 | 1,916 | 172 | 1 |
{-# LANGUAGE DeriveDataTypeable,
EmptyDataDecls,
FlexibleContexts,
FlexibleInstances,
MultiParamTypeClasses,
OverloadedStrings,
QuasiQuotes,
ScopedTypeVariables,
TemplateHaskell,
TypeFamilies #-}
module Application.WebCanvas.Server.Yesod where
--
import Control.Monad
import Data.Acid
import Data.Attoparsec as P
import Data.Aeson as A
import Data.Conduit
import qualified Data.Conduit.List as CL
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as SC
import Data.Function (on)
import Data.List (sortBy)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Time.Clock
import Data.UUID
import Data.UUID.V5
import Network.HTTP.Types (urlDecode)
import Network.Wai
import System.FilePath
import System.IO
import Yesod hiding (update)
--
import Application.WebCanvas.Type
--
import Application.WebCanvas.Server.Type
--
mkYesod "WebCanvasServer" [parseRoutes|
/ HomeR GET
/listwebcanvas ListWebCanvasR GET
/uploadwebcanvas UploadWebCanvasR POST
/recent RecentR GET
/webcanvas/#UUID WebCanvasR
|]
instance Yesod WebCanvasServer where
-- approot _ = ""
maximumContentLength _ _ = 100000000
getHomeR :: Handler RepHtml
getHomeR = do
liftIO $ putStrLn "getHomeR called"
defaultLayout [whamlet|
$newline always
!!!
<html>
<head>
<title> test
<body>
<h1> hello world
|]
defhlet :: GWidget s m ()
defhlet = [whamlet|
<h1> HTML output not supported
|]
getListWebCanvasR :: Handler RepHtmlJson
getListWebCanvasR = do
setHeader "Access-Control-Allow-Origin" "*"
setHeader "Access-Control-Allow-Methods" "POST, GET"
setHeader "X-Requested-With" "XmlHttpRequest"
setHeader "Access-Control-Allow-Headers" "X-Requested-With, Content-Type"
liftIO $ putStrLn "getListWebCanvasR called"
acid <- return.server_acid =<< getYesod
r <- liftIO $ query acid QueryAll
let nr = reverse (sortBy (compare `on` webcanvas_creationtime) r )
liftIO $ putStrLn $ show nr
defaultLayoutJson defhlet (A.toJSON (Just nr))
recentPNG :: T.Text -> GWidget s m ()
recentPNG content = [whamlet|
<img src="#{content}">
|]
getRecentR :: Handler RepHtml
getRecentR = do
content <- liftIO $ S.readFile "recent.png.base64"
defaultLayout (recentPNG (T.decodeUtf8 content))
-- |
nextUUID :: UTCTime -> IO UUID
nextUUID ctime = return . generateNamed namespaceURL . S.unpack . SC.pack $ show ctime
-- |
cvsItemFileName :: WebCanvasItem -> FilePath
cvsItemFileName (WebCanvasItem uuid _) = "data" </> show uuid ++ ".png" ++ ".base64"
-- |
postUploadWebCanvasR :: Handler RepHtmlJson
postUploadWebCanvasR = do
setHeader "Access-Control-Allow-Origin" "*"
setHeader "Access-Control-Allow-Methods" "POST, GET"
setHeader "X-Requested-With" "XmlHttpRequest"
setHeader "Access-Control-Allow-Headers" "X-Requested-With, Content-Type"
ctime <- liftIO $ getCurrentTime
uuid <- liftIO (nextUUID ctime)
let ncvsitem = WebCanvasItem uuid ctime
liftIO $ putStrLn ""
liftIO $ putStrLn $ show ctime
liftIO $ putStrLn $ show uuid
liftIO $ putStrLn "postQueueR called"
acid <- liftM server_acid getYesod
wr <- liftM reqWaiRequest getRequest
bs' <- liftIO $ runResourceT (requestBody wr $$ CL.consume)
let bs = S.concat bs'
decoded' = urlDecode True bs
decoded = SC.drop 4 decoded'
liftIO $ withFile (cvsItemFileName ncvsitem) WriteMode $
\h -> S.hPutStr h decoded
minfo <- liftIO $ update acid (AddWebCanvasItem ncvsitem)
defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebCanvasItem))
-- |
handleWebCanvasR :: UUID -> Handler RepHtmlJson
handleWebCanvasR name = do
setHeader "Access-Control-Allow-Origin" "*"
setHeader "Access-Control-Allow-Methods" "POST, GET"
setHeader "X-Requested-With" "XmlHttpRequest"
setHeader "Access-Control-Allow-Headers" "X-Requested-With, Content-Type"
wr <- liftM reqWaiRequest getRequest
case requestMethod wr of
"GET" -> getWebCanvasR name
"PUT" -> putWebCanvasR name
"DELETE" -> deleteWebCanvasR name
x -> error ("No such action " ++ show x ++ " in handlerWebCanvasR")
-- |
getWebCanvasR :: UUID -> Handler RepHtmlJson
getWebCanvasR idee = do
liftIO $ putStrLn "getWebCanvasR called"
acid <- liftM server_acid getYesod
r <- liftIO $ query acid (QueryWebCanvasItem idee)
liftIO $ putStrLn $ show r
case r of
Nothing -> defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe T.Text))
Just item -> do
content <- liftIO $ S.readFile (cvsItemFileName item)
defaultLayoutJson defhlet (A.toJSON (Just (T.decodeUtf8 content) :: Maybe T.Text))
-- |
putWebCanvasR :: UUID -> Handler RepHtmlJson
putWebCanvasR idee = do
liftIO $ putStrLn "putWebCanvasR called"
acid <- liftM server_acid getYesod
wr <- liftM reqWaiRequest getRequest
bs' <- liftIO $ runResourceT $ (requestBody wr $$ CL.consume )
let bs = S.concat bs'
let parsed = parse json bs
liftIO $ print parsed
case parsed of
Done _ parsedjson -> do
case (A.fromJSON parsedjson :: A.Result WebCanvasItem) of
Success minfo -> do
if idee == webcanvas_uuid minfo
then do r <- liftIO $ update acid (UpdateWebCanvasItem minfo)
defaultLayoutJson defhlet (A.toJSON (Just r))
else do liftIO $ putStrLn "webcanvasname mismatched"
defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebCanvasItem))
Error err -> do
liftIO $ putStrLn err
defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebCanvasItem))
Fail _ ctxts err -> do
liftIO $ putStrLn (concat ctxts++err)
defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebCanvasItem))
Partial _ -> do
liftIO $ putStrLn "partial"
defaultLayoutJson defhlet (A.toJSON (Nothing :: Maybe WebCanvasItem))
deleteWebCanvasR :: UUID -> Handler RepHtmlJson
deleteWebCanvasR idee = do
acid <- return.server_acid =<< getYesod
r <- liftIO $ update acid (DeleteWebCanvasItem idee)
liftIO $ putStrLn $ show r
defaultLayoutJson defhlet (A.toJSON (Just r))
| wavewave/webcanvas-server | lib/Application/WebCanvas/Server/Yesod.hs | bsd-2-clause | 6,367 | 0 | 24 | 1,443 | 1,691 | 824 | 867 | 143 | 5 |
module Main
( main -- :: IO ()
) where
import Control.Monad (void, when)
import Control.Monad.Trans.Resource
import Test.Hspec
import Test.HUnit
import Text.Search.Whistlepig
import qualified Text.Search.Whistlepig.Direct as IO
main :: IO ()
main = hspec $ do
-------------------------------------------------------------------------------
-- Indexes
describe "indexes" $ do
they "can be created" $ runResourceT (void $ create "test")
they "do exist, unlike unicorns" $ indexExists "test" >>= (@?= True)
they "can be loaded" $ runResourceT (void $ load "test")
it "should be empty right now" $ withIndex "test" $ \idx -> do
sz <- indexSize idx
when (sz /= 0) $ do
monadThrow (userError "index size is not zero!")
they "can be destroyed" $
deleteIndex "test" >>= errJust "could not delete"
-------------------------------------------------------------------------------
-- Entries
describe "entries" $ return ()
-------------------------------------------------------------------------------
-- Queries
describe "queries" $ do
they "can be shown" $ do
x <- IO.stringToQuery "body" "bob ~funny"
q <- errLeft "Could not create query!" x
print q
-------------------------------------------------------------------------------
-- Searching
describe "searching" $ return ()
-- helpers
errLeft :: String -> Either a b -> IO b
errLeft x (Left _) = error x
errLeft _ (Right a) = return a
errJust :: String -> Maybe a -> IO ()
errJust _ Nothing = return ()
errJust x (Just _) = error x
they :: String -> IO () -> Spec
they = it -- plural
| thoughtpolice/hs-whistlepig | tests/Properties.hs | bsd-3-clause | 1,646 | 0 | 20 | 340 | 462 | 226 | 236 | 35 | 1 |
{-# language Rank2Types #-}
{-# language ScopedTypeVariables #-}
{-# language DataKinds #-}
{-# language TypeOperators #-}
{-# language TypeFamilies #-}
{-# language FlexibleInstances #-}
{-# language FlexibleContexts #-}
{-# language MultiParamTypeClasses #-}
{-# language PolyKinds #-}
{-# language GADTs #-}
{-# language ConstraintKinds #-}
{-# language GeneralizedNewtypeDeriving #-}
module Feldspar.Software.Verify.Primitive where
import Feldspar.Sugar
import Feldspar.Representation
import Feldspar.Software.Primitive
import Feldspar.Software.Expression
import Feldspar.Software.Representation hiding (Nil)
import Feldspar.Software.Verify.Command
import Feldspar.Verify.Arithmetic
import Feldspar.Verify.Monad (Verify)
import qualified Feldspar.Verify.FirstOrder as FO
import qualified Feldspar.Verify.Monad as V
import qualified Feldspar.Verify.SMT as SMT
import qualified Feldspar.Verify.Abstract as A
import Data.Struct
import qualified Data.Map.Strict as Map
import qualified Control.Monad.RWS.Strict as S
import qualified SimpleSMT as SMT hiding (not, declareFun)
import qualified Language.Embedded.Expression as Imp
import qualified Language.Embedded.Imperative.CMD as Imp
import qualified Data.Bits as Bits
import qualified Data.Complex as Complex
import Data.Constraint hiding (Sub)
import Data.Int
import Data.Word
import Data.Typeable
import Language.Syntactic
import GHC.Stack
--------------------------------------------------------------------------------
-- *
--------------------------------------------------------------------------------
newtype Symbolic a = Symbolic { unSymbolic :: Rat }
deriving (Eq, Ord, Show, V.TypedSExpr, V.SMTOrd)
instance V.Fresh (Symbolic a)
where
fresh = V.freshSExpr
symbCast :: Symbolic a -> Symbolic b
symbCast = Symbolic . unSymbolic
symbFun :: SymbParam a => String -> [Symbolic a] -> Symbolic a
symbFun name (args :: [Symbolic a]) = V.fromSMT $
SMT.fun (symbType (undefined :: a) ++ "-" ++ name) (map V.toSMT args)
fromComplexConstant :: (RealFrac a, SymbParam b) => Complex.Complex a -> Symbolic b
fromComplexConstant c = symbFun "complex" [real, imag]
where
real = Symbolic $ fromRational $ toRational $ Complex.realPart c
imag = Symbolic $ fromRational $ toRational $ Complex.imagPart c
--------------------------------------------------------------------------------
data SymbFloat
data SymbDouble
data SymbComplexFloat
data SymbComplexDouble
class SymbParam a
where
symbType :: a -> String
instance SymbParam SymbFloat where symbType _ = "float"
instance SymbParam SymbDouble where symbType _ = "double"
instance SymbParam SymbComplexFloat where symbType _ = "cfloat"
instance SymbParam SymbComplexDouble where symbType _ = "cdouble"
instance SymbParam a => Num (Symbolic a)
where
fromInteger = Symbolic . fromInteger
x + y = symbFun "+" [x, y]
x - y = symbFun "-" [x, y]
x * y = symbFun "*" [x, y]
abs = smtAbs
signum = smtSignum
instance SymbParam a => Fractional (Symbolic a) where
fromRational = Symbolic . fromRational
x / y = symbFun "/" [x, y]
instance SymbParam a => Floating (Symbolic a) where
pi = fromRational (toRational pi)
exp x = symbFun "exp" [x]
log x = symbFun "log" [x]
sqrt x = symbFun "sqrt" [x]
x ** y = symbFun "pow" [x, y]
sin x = symbFun "sin" [x]
cos x = symbFun "cos" [x]
tan x = symbFun "tan" [x]
asin x = symbFun "asin" [x]
acos x = symbFun "acos" [x]
atan x = symbFun "atan" [x]
sinh x = symbFun "sinh" [x]
cosh x = symbFun "cosh" [x]
tanh x = symbFun "tanh" [x]
asinh x = symbFun "asinh" [x]
acosh x = symbFun "acosh" [x]
atanh x = symbFun "atanh" [x]
--------------------------------------------------------------------------------
class Floating a => Complex a
where
type RealPart a
complex :: RealPart a -> RealPart a -> a
polar :: RealPart a -> RealPart a -> a
real :: a -> RealPart a
imag :: a -> RealPart a
magnitude :: a -> RealPart a
phase :: a -> RealPart a
conjugate :: a -> a
instance Complex (V.SMTExpr Prim (Complex.Complex Float))
where
type RealPart (V.SMTExpr Prim (Complex.Complex Float)) = V.SMTExpr Prim Float
complex (Float x) (Float y) = ComplexFloat (complex x y)
polar (Float x) (Float y) = ComplexFloat (polar x y)
real (ComplexFloat x) = Float (real x)
imag (ComplexFloat x) = Float (imag x)
magnitude (ComplexFloat x) = Float (magnitude x)
phase (ComplexFloat x) = Float (phase x)
conjugate (ComplexFloat x) = ComplexFloat (conjugate x)
instance Complex (V.SMTExpr Prim (Complex.Complex Double))
where
type RealPart (V.SMTExpr Prim (Complex.Complex Double)) = V.SMTExpr Prim Double
complex (Double x) (Double y) = ComplexDouble (complex x y)
polar (Double x) (Double y) = ComplexDouble (polar x y)
real (ComplexDouble x) = Double (real x)
imag (ComplexDouble x) = Double (imag x)
magnitude (ComplexDouble x) = Double (magnitude x)
phase (ComplexDouble x) = Double (phase x)
conjugate (ComplexDouble x) = ComplexDouble (conjugate x)
witnessComplex :: (SoftwarePrimType a, SoftwarePrimType (Complex.Complex a)) =>
Prim (Complex.Complex a) ->
Dict ( Floating (V.SMTExpr Prim a)
, Complex (V.SMTExpr Prim (Complex.Complex a))
, RealPart (V.SMTExpr Prim (Complex.Complex a)) ~ V.SMTExpr Prim a)
witnessComplex (_ :: Prim (Complex.Complex a)) =
case softwareRep :: SoftwarePrimTypeRep (Complex.Complex a) of
ComplexFloatST -> Dict
ComplexDoubleST -> Dict
witnessFractional :: (SoftwarePrimType a, Fractional a) =>
Prim a ->
Dict (Floating (V.SMTExpr Prim a))
witnessFractional (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of
FloatST -> Dict
DoubleST -> Dict
ComplexFloatST -> Dict
ComplexDoubleST -> Dict
witnessIntegral :: (SoftwarePrimType a, Integral a) =>
Prim a ->
Dict (Integral (V.SMTExpr Prim a), Bits (V.SMTExpr Prim a))
witnessIntegral (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of
Int8ST -> Dict
Int16ST -> Dict
Int32ST -> Dict
Int64ST -> Dict
Word8ST -> Dict
Word16ST -> Dict
Word32ST -> Dict
Word64ST -> Dict
witnessBits :: (SoftwarePrimType a, Bits.Bits a) =>
Prim a ->
Dict ( Num a
, Integral (V.SMTExpr Prim a)
, Bits (V.SMTExpr Prim a))
witnessBits (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of
Int8ST -> Dict
Int16ST -> Dict
Int32ST -> Dict
Int64ST -> Dict
Word8ST -> Dict
Word16ST -> Dict
Word32ST -> Dict
Word64ST -> Dict
--------------------------------------------------------------------------------
toRat :: (SoftwarePrimType a, Fractional a) => V.SMTExpr Prim a -> Rat
toRat (x :: V.SMTExpr Prim a) = case softwareRep :: SoftwarePrimTypeRep a of
FloatST -> let Float (Symbolic y) = x in y
DoubleST -> let Double (Symbolic y) = x in y
ComplexFloatST -> let ComplexFloat (Symbolic y) = x in y
ComplexDoubleST -> let ComplexDouble (Symbolic y) = x in y
fromRat :: forall a. (SoftwarePrimType a, Num a) => Rat -> V.SMTExpr Prim a
fromRat x = case softwareRep :: SoftwarePrimTypeRep a of Int8ST -> Int8 (f2i x)
where
f2i :: forall s w. (Sign s, Width w) => Rat -> BV s w
f2i (Rat x) = BV $ SMT.List [SMT.fam "int2bv" [width (undefined :: w)], SMT.fun "to_int" [x]]
i2n :: forall a b.
( V.SMTEval Prim a, SoftwarePrimType a, Integral a
, V.SMTEval Prim b, SoftwarePrimType b, Num b) =>
V.SMTExpr Prim a ->
V.SMTExpr Prim b
i2n x = toBV x $ case softwareRep :: SoftwarePrimTypeRep b of
Int8ST -> Int8 . i2i
Int16ST -> Int16 . i2i
Int32ST -> Int32 . i2i
Int64ST -> Int64 . i2i
Word8ST -> Word8 . i2i
Word16ST -> Word16 . i2i
Word32ST -> Word32 . i2i
Word64ST -> Word64 . i2i
FloatST -> Float . Symbolic . i2f
DoubleST -> Double . Symbolic . i2f
ComplexFloatST -> ComplexFloat . Symbolic . i2f
ComplexDoubleST -> ComplexDouble . Symbolic . i2f
where
toBV :: forall a b. (V.SMTEval Prim a, SoftwarePrimType a, Integral a) =>
V.SMTExpr Prim a -> (forall s w. (Sign s, Width w) => BV s w -> b) -> b
toBV (x :: V.SMTExpr Prim a) k = case softwareRep :: SoftwarePrimTypeRep a of
Int8ST -> let Int8 y = x in k y
Int16ST -> let Int16 y = x in k y
Int32ST -> let Int32 y = x in k y
Int64ST -> let Int64 y = x in k y
Word8ST -> let Word8 y = x in k y
Word16ST -> let Word16 y = x in k y
Word32ST -> let Word32 y = x in k y
Word64ST -> let Word64 y = x in k y
i2f :: (Sign s, Width w) => BV s w -> Rat
i2f (BV x) = Rat (SMT.fun "to_real" [SMT.fun "bv2int" [x]])
i2i :: forall s1 w1 s2 w2. (Sign s1, Width w1, Sign s2, Width w2) => BV s1 w1 -> BV s2 w2
i2i x = case compare m n of
LT | isSigned x -> V.fromSMT (SMT.signExtend (n-m) (V.toSMT x))
| otherwise -> V.fromSMT (SMT.zeroExtend (n-m) (V.toSMT x))
EQ -> V.fromSMT (V.toSMT x)
GT -> V.fromSMT (SMT.extract (V.toSMT x) (n-1) 0)
where
m = width (undefined :: w1)
n = width (undefined :: w2)
--------------------------------------------------------------------------------
class SymbParam a => SymbComplex a
where
type SymbRealPart a
instance SymbComplex SymbComplexFloat
where
type SymbRealPart SymbComplexFloat = SymbFloat
instance SymbComplex SymbComplexDouble
where
type SymbRealPart SymbComplexDouble = SymbDouble
instance SymbComplex a => Complex (Symbolic a)
where
type RealPart (Symbolic a) = Symbolic (SymbRealPart a)
complex x y = symbFun "complex" [symbCast x, symbCast y]
polar x y = symbFun "polar" [symbCast x, symbCast y]
real x = symbCast (symbFun "real" [x])
imag x = symbCast (symbFun "imag" [x])
magnitude x = symbCast (symbFun "magnitude" [x])
phase x = symbCast (symbFun "phase" [x])
conjugate x = symbFun "conjugate" [x]
--------------------------------------------------------------------------------
declareSymbFun :: SymbParam a => String -> a ->
[SMT.SExpr] -> SMT.SExpr -> SMT.SMT ()
declareSymbFun name (_ :: a) args res =
S.void $ SMT.declareFun (symbType (undefined :: a) ++ "-" ++ name) args res
declareSymbArith :: SymbParam a => a -> SMT.SMT ()
declareSymbArith x = do
declareSymbFun "+" x [SMT.tReal, SMT.tReal] SMT.tReal
declareSymbFun "-" x [SMT.tReal, SMT.tReal] SMT.tReal
declareSymbFun "*" x [SMT.tReal, SMT.tReal] SMT.tReal
declareSymbFun "/" x [SMT.tReal, SMT.tReal] SMT.tReal
declareSymbFun "exp" x [SMT.tReal] SMT.tReal
declareSymbFun "log" x [SMT.tReal] SMT.tReal
declareSymbFun "sqrt" x [SMT.tReal] SMT.tReal
declareSymbFun "pow" x [SMT.tReal, SMT.tReal] SMT.tReal
declareSymbFun "sin" x [SMT.tReal] SMT.tReal
declareSymbFun "cos" x [SMT.tReal] SMT.tReal
declareSymbFun "tan" x [SMT.tReal] SMT.tReal
declareSymbFun "asin" x [SMT.tReal] SMT.tReal
declareSymbFun "acos" x [SMT.tReal] SMT.tReal
declareSymbFun "atan" x [SMT.tReal] SMT.tReal
declareSymbFun "sinh" x [SMT.tReal] SMT.tReal
declareSymbFun "cosh" x [SMT.tReal] SMT.tReal
declareSymbFun "tanh" x [SMT.tReal] SMT.tReal
declareSymbFun "asinh" x [SMT.tReal] SMT.tReal
declareSymbFun "acosh" x [SMT.tReal] SMT.tReal
declareSymbFun "atanh" x [SMT.tReal] SMT.tReal
declareSymbComplex :: SymbParam a => a -> SMT.SMT ()
declareSymbComplex x = do
declareSymbArith x
declareSymbFun "complex" x [SMT.tReal, SMT.tReal] SMT.tReal
declareSymbFun "polar" x [SMT.tReal, SMT.tReal] SMT.tReal
declareSymbFun "real" x [SMT.tReal] SMT.tReal
declareSymbFun "imag" x [SMT.tReal] SMT.tReal
declareSymbFun "magnitude" x [SMT.tReal] SMT.tReal
declareSymbFun "phase" x [SMT.tReal] SMT.tReal
declareSymbFun "conjugate" x [SMT.tReal] SMT.tReal
declareFeldsparGlobals :: SMT.SMT ()
declareFeldsparGlobals = do
declareSymbArith (undefined :: SymbFloat)
declareSymbArith (undefined :: SymbDouble)
declareSymbComplex (undefined :: SymbComplexFloat)
declareSymbComplex (undefined :: SymbComplexDouble)
SMT.declareFun "skolem-int8" [] (SMT.tBits 8)
SMT.declareFun "skolem-int16" [] (SMT.tBits 16)
SMT.declareFun "skolem-int32" [] (SMT.tBits 32)
SMT.declareFun "skolem-int64" [] (SMT.tBits 64)
SMT.declareFun "skolem-word8" [] (SMT.tBits 8)
SMT.declareFun "skolem-word16" [] (SMT.tBits 16)
SMT.declareFun "skolem-word32" [] (SMT.tBits 32)
SMT.declareFun "skolem-word64" [] (SMT.tBits 64)
return ()
instance FO.Substitute Prim
where
type SubstPred Prim = SoftwarePrimType
subst sub (Prim exp) = Prim (everywhereUp f exp)
where
f :: ASTF SoftwarePrimDomain a -> ASTF SoftwarePrimDomain a
f (Sym (FreeVar x :&: ty)) = case FO.lookupSubst sub (Imp.ValComp x) of
Imp.ValComp y -> Sym (FreeVar y :&: ty)
Imp.ValRun z -> Sym (Lit z :&: ty)
f (Sym (ArrIx iarr :&: ty) :$ i) = Sym (ArrIx iarr' :&: ty) :$ i
where iarr' = FO.lookupSubst sub iarr
f x = x
instance FO.TypeablePred SoftwarePrimType
where
witnessTypeable Dict = Dict
--------------------------------------------------------------------------------
instance V.SMTEval Prim Bool where
fromConstant = Bool . SMT.bool
witnessOrd _ = Dict
instance V.SMTEval Prim Int8 where
fromConstant = Int8 . fromIntegral
witnessNum _ = Dict
witnessOrd _ = Dict
skolemIndex = V.fromSMT (SMT.fun "skolem-int8" [])
instance V.SMTEval Prim Int16 where
fromConstant = Int16 . fromIntegral
witnessNum _ = Dict
witnessOrd _ = Dict
skolemIndex = V.fromSMT (SMT.fun "skolem-int16" [])
instance V.SMTEval Prim Int32 where
fromConstant = Int32 . fromIntegral
witnessNum _ = Dict
witnessOrd _ = Dict
skolemIndex = V.fromSMT (SMT.fun "skolem-int32" [])
instance V.SMTEval Prim Int64 where
fromConstant = Int64 . fromIntegral
witnessNum _ = Dict
witnessOrd _ = Dict
skolemIndex = V.fromSMT (SMT.fun "skolem-int64" [])
instance V.SMTEval Prim Word8 where
fromConstant = Word8 . fromIntegral
witnessNum _ = Dict
witnessOrd _ = Dict
skolemIndex = V.fromSMT (SMT.fun "skolem-word8" [])
instance V.SMTEval Prim Word16 where
fromConstant = Word16 . fromIntegral
witnessNum _ = Dict
witnessOrd _ = Dict
skolemIndex = V.fromSMT (SMT.fun "skolem-word16" [])
instance V.SMTEval Prim Word32 where
fromConstant = Word32 . fromIntegral
witnessNum _ = Dict
witnessOrd _ = Dict
skolemIndex = V.fromSMT (SMT.fun "skolem-word32" [])
instance V.SMTEval Prim Word64 where
fromConstant = Word64 . fromIntegral
witnessNum _ = Dict
witnessOrd _ = Dict
skolemIndex = V.fromSMT (SMT.fun "skolem-word64" [])
instance V.SMTEval Prim Float where
fromConstant = Float . fromRational . toRational
witnessOrd _ = Dict
witnessNum _ = Dict
instance V.SMTEval Prim Double where
fromConstant = Double . fromRational . toRational
witnessOrd _ = Dict
witnessNum _ = Dict
instance V.SMTEval Prim (Complex.Complex Float) where
fromConstant = ComplexFloat . fromComplexConstant
witnessNum _ = Dict
instance V.SMTEval Prim (Complex.Complex Double) where
fromConstant = ComplexDouble . fromComplexConstant
witnessNum _ = Dict
--------------------------------------------------------------------------------
instance V.SMTEval1 Prim where
type Pred Prim = SoftwarePrimType
newtype SMTExpr Prim Bool = Bool SMT.SExpr
deriving (Typeable)
newtype SMTExpr Prim Float = Float (Symbolic SymbFloat)
deriving (Typeable, Num, Fractional, Floating, V.SMTOrd, V.TypedSExpr)
newtype SMTExpr Prim Double = Double (Symbolic SymbDouble)
deriving (Typeable, Num, Fractional, Floating, V.SMTOrd, V.TypedSExpr)
newtype SMTExpr Prim (Complex.Complex Float) =
ComplexFloat (Symbolic SymbComplexFloat)
deriving (Typeable, Num, Fractional, Floating, V.TypedSExpr)
newtype SMTExpr Prim (Complex.Complex Double) =
ComplexDouble (Symbolic SymbComplexDouble)
deriving (Typeable, Num, Fractional, Floating, V.TypedSExpr)
newtype SMTExpr Prim Int8 = Int8 (BV Signed W8)
deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
newtype SMTExpr Prim Int16 = Int16 (BV Signed W16)
deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
newtype SMTExpr Prim Int32 = Int32 (BV Signed W32)
deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
newtype SMTExpr Prim Int64 = Int64 (BV Signed W64)
deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
newtype SMTExpr Prim Word8 = Word8 (BV Unsigned W8)
deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
newtype SMTExpr Prim Word16 = Word16 (BV Unsigned W16)
deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
newtype SMTExpr Prim Word32 = Word32 (BV Unsigned W32)
deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
newtype SMTExpr Prim Word64 = Word64 (BV Unsigned W64)
deriving (Typeable, Num, Real, Enum, Integral, Bits, V.SMTOrd, V.TypedSExpr)
eval (Prim exp :: Prim a) =
simpleMatch (\(exp :&: ty) -> case softwarePrimWitType ty of
Dict -> case V.witnessPred (undefined :: Prim a) of
Dict -> verifyPrim exp) exp
witnessPred (_ :: Prim a) = case softwareRep :: SoftwarePrimTypeRep a of
BoolST -> Dict
Int8ST -> Dict
Int16ST -> Dict
Int32ST -> Dict
Int64ST -> Dict
Word8ST -> Dict
Word16ST -> Dict
Word32ST -> Dict
Word64ST -> Dict
FloatST -> Dict
DoubleST -> Dict
ComplexFloatST -> Dict
ComplexDoubleST -> Dict
instance V.SMTOrd (V.SMTExpr Prim Bool) where
Bool x .<. Bool y = SMT.not x SMT..&&. y
Bool x .>. Bool y = x SMT..&&. SMT.not y
Bool x .<=. Bool y = SMT.not x SMT..||. y
Bool x .>=. Bool y = x SMT..||. SMT.not y
instance V.TypedSExpr (V.SMTExpr Prim Bool) where
smtType _ = SMT.tBool
toSMT (Bool x) = x
fromSMT x = Bool x
--------------------------------------------------------------------------------
verifyPrim :: forall a .
(SoftwarePrimType (DenResult a), V.SMTEval Prim (DenResult a), HasCallStack) =>
SoftwarePrim a ->
Args (AST SoftwarePrimDomain) a ->
V.Verify (V.SMTExpr Prim (DenResult a))
verifyPrim (FreeVar x) _ = peekValue x
verifyPrim (Lit x) _ = return (V.fromConstant x)
verifyPrim Add (x :* y :* Nil)
| Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
S.liftM2 (+) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Sub (x :* y :* Nil)
| Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
S.liftM2 (-) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Mul (x :* y :* Nil)
| Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
S.liftM2 (*) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Neg (x :* Nil)
| Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
fmap negate (V.eval (Prim x))
verifyPrim Abs (x :* Nil)
| Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
fmap abs (V.eval (Prim x))
verifyPrim Sign (x :* Nil)
| Dict <- V.witnessNum (undefined :: Prim (DenResult a)) =
fmap signum (V.eval (Prim x))
verifyPrim Div (x :* y :* Nil)
| Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =
S.liftM2 div (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Mod (x :* y :* Nil)
| Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =
S.liftM2 mod (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Quot (x :* y :* Nil)
| Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =
S.liftM2 quot (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Rem (x :* y :* Nil)
| Dict <- witnessIntegral (undefined :: Prim (DenResult a)) =
S.liftM2 rem (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim FDiv (x :* y :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
S.liftM2 (/) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Pi Nil
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
return pi
verifyPrim Exp (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap exp (V.eval (Prim x))
verifyPrim Log (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap log (V.eval (Prim x))
verifyPrim Sqrt (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap sqrt (V.eval (Prim x))
verifyPrim Pow (x :* y :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
S.liftM2 (**) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Sin (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap sin (V.eval (Prim x))
verifyPrim Cos (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap cos (V.eval (Prim x))
verifyPrim Tan (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap tan (V.eval (Prim x))
verifyPrim Asin (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap asin (V.eval (Prim x))
verifyPrim Acos (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap acos (V.eval (Prim x))
verifyPrim Atan (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap atan (V.eval (Prim x))
verifyPrim Sinh (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap sinh (V.eval (Prim x))
verifyPrim Cosh (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap cosh (V.eval (Prim x))
verifyPrim Tanh (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap tanh (V.eval (Prim x))
verifyPrim Asinh (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap asinh (V.eval (Prim x))
verifyPrim Acosh (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap acosh (V.eval (Prim x))
verifyPrim Atanh (x :* Nil)
| Dict <- witnessFractional (undefined :: Prim (DenResult a)) =
fmap atanh (V.eval (Prim x))
verifyPrim Complex (x :* y :* Nil)
| Dict <- witnessComplex (undefined :: Prim (DenResult a)) =
S.liftM2 complex (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Polar (x :* y :* Nil)
| Dict <- witnessComplex (undefined :: Prim (DenResult a)) =
S.liftM2 polar (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim Real ((x :: ASTF SoftwarePrimDomain b) :* Nil)
| Dict <- witnessComplex (undefined :: Prim b) =
fmap real (V.eval (Prim x))
verifyPrim Imag ((x :: ASTF SoftwarePrimDomain b) :* Nil)
| Dict <- witnessComplex (undefined :: Prim b) =
fmap imag (V.eval (Prim x))
verifyPrim Magnitude ((x :: ASTF SoftwarePrimDomain b) :* Nil)
| Dict <- witnessComplex (undefined :: Prim b) =
fmap magnitude (V.eval (Prim x))
verifyPrim Phase ((x :: ASTF SoftwarePrimDomain b) :* Nil)
| Dict <- witnessComplex (undefined :: Prim b) =
fmap phase (V.eval (Prim x))
verifyPrim Conjugate ((x :: ASTF SoftwarePrimDomain b) :* Nil)
| Dict <- witnessComplex (undefined :: Prim b) =
fmap conjugate (V.eval (Prim x))
verifyPrim I2N ((x :: ASTF SoftwarePrimDomain b) :* Nil)
| Dict <- V.witnessPred (undefined :: Prim b),
Dict <- V.witnessNum (undefined :: Prim b) = do
fmap i2n (V.eval (Prim x))
verifyPrim I2B ((x :: ASTF SoftwarePrimDomain b) :* Nil)
| Dict <- V.witnessPred (undefined :: Prim b),
Dict <- V.witnessNum (undefined :: Prim b) = do
x <- V.eval (Prim x)
return (V.fromSMT (SMT.not (x V..==. 0)))
verifyPrim B2I (x :* Nil)
| Dict <- V.witnessNum (undefined :: Prim (DenResult a)) = do
x <- V.eval (Prim x)
return (V.smtIte (V.toSMT x) 1 0)
verifyPrim Round ((x :: ASTF SoftwarePrimDomain b) :* Nil) = do
x <- V.eval (Prim x)
return (fromRat (toRat x))
verifyPrim Not (x :* Nil) =
fmap (V.fromSMT . SMT.not . V.toSMT) (V.eval (Prim x))
verifyPrim And (x :* y :* Nil) = do
x <- V.eval (Prim x)
y <- V.eval (Prim y)
return (V.fromSMT (V.toSMT x SMT..&&. V.toSMT y))
verifyPrim Or (x :* y :* Nil) = do
x <- V.eval (Prim x)
y <- V.eval (Prim y)
return (V.fromSMT (V.toSMT x SMT..||. V.toSMT y))
verifyPrim Eq ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
| Dict <- V.witnessPred (undefined :: Prim b) =
fmap V.fromSMT (S.liftM2 (V..==.) (V.eval (Prim x)) (V.eval (Prim y)))
verifyPrim Neq ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
| Dict <- V.witnessPred (undefined :: Prim b) =
fmap V.fromSMT (S.liftM2 (./=.) (V.eval (Prim x)) (V.eval (Prim y)))
where
x ./=. y = SMT.not (x V..==. y)
verifyPrim Lt ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
| Dict <- V.witnessPred (undefined :: Prim b),
Dict <- V.witnessOrd (undefined :: Prim b) =
fmap V.fromSMT (S.liftM2 (V..<.) (V.eval (Prim x)) (V.eval (Prim y)))
verifyPrim Gt ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
| Dict <- V.witnessPred (undefined :: Prim b),
Dict <- V.witnessOrd (undefined :: Prim b) =
fmap V.fromSMT (S.liftM2 (V..>.) (V.eval (Prim x)) (V.eval (Prim y)))
verifyPrim Lte ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
| Dict <- V.witnessPred (undefined :: Prim b),
Dict <- V.witnessOrd (undefined :: Prim b) =
fmap V.fromSMT (S.liftM2 (V..<=.) (V.eval (Prim x)) (V.eval (Prim y)))
verifyPrim Gte ((x :: ASTF SoftwarePrimDomain b) :* y :* Nil)
| Dict <- V.witnessPred (undefined :: Prim b),
Dict <- V.witnessOrd (undefined :: Prim b) =
fmap V.fromSMT (S.liftM2 (V..>=.) (V.eval (Prim x)) (V.eval (Prim y)))
verifyPrim BitAnd (x :* y :* Nil)
| Dict <- witnessBits (undefined :: Prim (DenResult a)) =
S.liftM2 (.&.) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim BitOr (x :* y :* Nil)
| Dict <- witnessBits (undefined :: Prim (DenResult a)) =
S.liftM2 (.|.) (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim BitXor (x :* y :* Nil)
| Dict <- witnessBits (undefined :: Prim (DenResult a)) =
S.liftM2 xor (V.eval (Prim x)) (V.eval (Prim y))
verifyPrim BitCompl (x :* Nil)
| Dict <- witnessBits (undefined :: Prim (DenResult a)) =
fmap complement (V.eval (Prim x))
verifyPrim ShiftL (x :* (y :: ASTF SoftwarePrimDomain b) :* Nil)
| Dict <- witnessBits (undefined :: Prim (DenResult a)),
Dict <- V.witnessPred (undefined :: Prim b),
Dict <- witnessIntegral (undefined :: Prim b) = do
-- todo: should check for undefined behaviour
x <- V.eval (Prim x)
y <- V.eval (Prim y)
return (shiftL x (i2n y))
verifyPrim ShiftR (x :* (y :: ASTF SoftwarePrimDomain b) :* Nil)
| Dict <- witnessBits (undefined :: Prim (DenResult a)),
Dict <- V.witnessPred (undefined :: Prim b),
Dict <- witnessIntegral (undefined :: Prim b) = do
-- todo: should check for undefined behaviour
x <- V.eval (Prim x)
y <- V.eval (Prim y)
return (shiftR x (i2n y))
verifyPrim (ArrIx (Imp.IArrComp name :: Imp.IArr Index b)) (i :* Nil) = do
i <- V.eval (Prim i)
readArray name i
verifyPrim Cond (cond :* x :* y :* Nil) =
S.liftM3 V.smtIte
(fmap V.toSMT (V.eval (Prim cond)))
(V.eval (Prim x))
(V.eval (Prim y))
verifyPrim exp _ = error ("Unimplemented: " ++ show exp)
--------------------------------------------------------------------------------
| markus-git/co-feldspar | src/Feldspar/Software/Verify/Primitive.hs | bsd-3-clause | 27,307 | 0 | 16 | 5,734 | 11,493 | 5,714 | 5,779 | -1 | -1 |
module Main where
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Glade
import System.Glib.MainLoop
import System.IO
import System.Process
import GHC.Handle
import GHC.IOBase
import Control.Concurrent.MVar
import Control.Concurrent
main = do
unsafeInitGUIForThreadedRTS
dialogXmlM <- xmlNew "gtkconsole.glade"
let dialogXml = case dialogXmlM of
(Just dialogXml) -> dialogXml
Nothing -> error "Can't find the glade file \"gtkconsole.glade\""
wnd <- xmlGetWidget dialogXml castToWindow "wnd"
cmd <- xmlGetWidget dialogXml castToButton "cmd"
txt <- xmlGetWidget dialogXml castToTextView "txt"
txtData <- textViewGetBuffer txt
wnd `onDestroy` mainQuit
widgetShowAll wnd
cmd `onClicked` (setupProcess txt >> appendText txt "hello!")
mainGUI
setupProcess txt = do
(inp,out,err,pid) <- runInteractiveCommand "ghci"
putStrLn "Starting interactive command"
hSetBuffering out NoBuffering
hSetBuffering err NoBuffering
hSetBuffering inp NoBuffering
hSetBinaryMode out True
hSetBinaryMode err True
forkIO (readFrom out inp txt)
forkIO (readFrom err inp txt)
return ()
appendText :: TextView -> String -> IO ()
appendText txtOut s = do
buf <- textViewGetBuffer txtOut
end <- textBufferGetEndIter buf
textBufferInsert buf end s
readFrom hndl x txt = do
c <- hGetChar hndl
postGUIAsync $ appendText txt [c]
readFrom hndl x txt
| ndmitchell/guihaskell | gtkconsole/Main.hs | bsd-3-clause | 1,645 | 0 | 14 | 501 | 421 | 198 | 223 | 44 | 2 |
-- | Test the Fibonacci function
module FibSpec (main, spec) where
-- import Control.Applicative
import Control.Exception
import System.Timeout
import Test.Hspec
import Test.QuickCheck -- for Queckcheck example
import Fib
-- small non-negative integers
newtype Small' = Small' Int
deriving Show
instance Arbitrary Small' where
arbitrary = Small' . (`mod` 10) <$> arbitrary
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "fib" $ do
it "calculates arbitrary Fibonacci numbers" $ do
property $ \(Small' n) ->
fib n == fib (n + 2) - fib (n + 1)
it "is efficient" $ do
timeout 10000 (evaluate $ fib 32)
`shouldReturn` Just 2178309
it "returns 0 on negative input" $ do
property $ \n -> n < 0 ==>
fib n == 0
| emaphis/Haskell-Practice | testing-project/test/FibSpec.hs | bsd-3-clause | 809 | 0 | 19 | 217 | 248 | 130 | 118 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-tabs #-}
{- $Id: TestsReact.hs,v 1.2 2003/11/10 21:28:58 antony Exp $
******************************************************************************
* Y A M P A *
* *
* Module: TestsReact *
* Purpose: Test cases for reactimation *
* Authors: Antony Courtney and Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
module TestsReact (react_tr, react_trs) where
import System.IO.Unsafe (unsafePerformIO)
import Data.IORef (newIORef, writeIORef, readIORef)
import FRP.Yampa
import TestsCommon
------------------------------------------------------------------------------
-- Test cases for reactimation
------------------------------------------------------------------------------
react_t0 :: [(Double, Double)]
react_t0 = unsafePerformIO $ do
countr <- newIORef undefined
inputr <- newIORef undefined
outputsr <- newIORef []
let init = do
writeIORef countr 1
let input0 = 0.0
writeIORef inputr input0
return input0
sense _ = do
count <- readIORef countr
if count >= 5 then do
writeIORef countr 1
input <- readIORef inputr
let input' = input + 0.5
writeIORef inputr input'
return (0.1, Just input')
else do
writeIORef countr (count + 1)
return (0.1, Nothing)
actuate _ output = do
outputs <- readIORef outputsr
writeIORef outputsr (output : outputs)
input <- readIORef inputr
return (input > 5.0)
reactimate init sense actuate (arr dup >>> second integral)
outputs <- readIORef outputsr
return (take 25 (reverse outputs))
react_t0r :: [(Double, Double)]
react_t0r = [
(0.0,0.00), (0.0,0.00), (0.0,0.00), (0.0,0.00), (0.0,0.00),
(0.5,0.00), (0.5,0.05), (0.5,0.10), (0.5,0.15), (0.5,0.20),
(1.0,0.25), (1.0,0.35), (1.0,0.45), (1.0,0.55), (1.0,0.65),
(1.5,0.75), (1.5,0.90), (1.5,1.05), (1.5,1.20), (1.5,1.35),
(2.0,1.50), (2.0,1.70), (2.0,1.90), (2.0,2.10), (2.0,2.30)]
react_trs = [ react_t0 ~= react_t0r ]
react_tr = and react_trs
| ivanperez-keera/Yampa | yampa/tests/TestsReact.hs | bsd-3-clause | 2,498 | 3 | 23 | 791 | 632 | 353 | 279 | 44 | 2 |
{- Copyright (c) 2008 the authors listed at the following URL, and/or
the authors of referenced articles or incorporated external code:
http://en.literateprograms.org/Priority_Queue_(Haskell)?action=history&offset=20080608152146
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Retrieved from: http://en.literateprograms.org/Priority_Queue_(Haskell)?oldid=13634
-}
{-# LANGUAGE DatatypeContexts #-}
module Control.CP.PriorityQueue (
PriorityQueue,
empty,
is_empty,
minKey,
minKeyValue,
insert,
deleteMin,
deleteMinAndInsert
) where
import Prelude
-- Declare the data type constructors.
data Ord k => PriorityQueue k a = Nil | Branch k a (PriorityQueue k a) (PriorityQueue k a)
-- Declare the exported interface functions.
-- Return an empty priority queue.
is_empty Nil = True
is_empty _ = False
empty :: Ord k => PriorityQueue k a
empty = Nil
-- Return the highest-priority key.
minKey :: Ord k => PriorityQueue k a -> k
minKey = fst . minKeyValue
-- Return the highest-priority key plus its associated value.
minKeyValue :: Ord k => PriorityQueue k a -> (k, a)
minKeyValue Nil = error "empty queue"
minKeyValue (Branch k a _ _) = (k, a)
-- Insert a key/value pair into a queue.
insert :: Ord k => k -> a -> PriorityQueue k a -> PriorityQueue k a
insert k a q = union (singleton k a) q
deleteMin :: Ord k => PriorityQueue k a -> ((k,a), PriorityQueue k a)
deleteMin(Branch k a l r) = ((k,a),union l r)
-- Delete the highest-priority key/value pair and insert a new key/value pair into the queue.
deleteMinAndInsert :: Ord k => k -> a -> PriorityQueue k a -> PriorityQueue k a
deleteMinAndInsert k a Nil = singleton k a
deleteMinAndInsert k a (Branch _ _ l r) = union (insert k a l) r
-- Declare the private helper functions.
-- Join two queues in sorted order.
union :: Ord k => PriorityQueue k a -> PriorityQueue k a -> PriorityQueue k a
union l Nil = l
union Nil r = r
union l@(Branch kl _ _ _) r@(Branch kr _ _ _)
| kl <= kr = link l r
| otherwise = link r l
-- Join two queues without regard to order.
-- (This is a helper to the union helper.)
link (Branch k a Nil m) r = Branch k a r m
link (Branch k a ll lr) r = Branch k a lr (union ll r)
-- Return a queue with a single item from a key/value pair.
singleton :: Ord k => k -> a -> PriorityQueue k a
singleton k a = Branch k a Nil Nil
| neothemachine/monadiccp | src/Control/CP/PriorityQueue.hs | bsd-3-clause | 3,376 | 0 | 9 | 681 | 687 | 353 | 334 | 38 | 1 |
{-|
Description : a minimal PolyPaver problem
Copyright : (c) Jan Duracz, Michal Konecny
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
A few small PolyPaver problems.
Example parameters that work:
sinsin2: -d 2 -e 30
-}
module Main where
import PolyPaver
main =
-- defaultMain problem_exp
-- defaultMain test_skew
-- defaultMain sqrt_sin
-- defaultMain sinsin
-- defaultMain sinsin2
defaultMain absNonneg
exp_shift =
Problem box conjecture
where
box = [(0, (-1,1), False)]
x = termVar 0 "x"
conjecture = exp x |<=| exp (x+0.0001)
test_skew =
Problem box conjecture
where
box = [(0, (0,4), False), (1, (0,4), False)]
x = termVar 0 "x"
y = termVar 1 "y"
conjecture =
x |<=| y*y
--->
x |<=| y*y + 0.025
-- exp x |<=| exp (y*y) + 0.1
sqrt_sin =
Problem box conjecture
where
box = [(0, (0.000001,1), False)]
x = termVar 0 "x"
conjecture =
2 * (sqrt(x+1) - 1) |<=| sin(x)
sinsin =
Problem box conjecture
where
box = [(0, (0.2,1), False)]
x = termVar 0 "x"
conjecture =
sin(3*x+1) |<=| sin(sin(3*x)+1)
--sinDebug =
-- Problem box conjecture
-- where
-- box = [(0, (0.2,1), False)]
-- x = termVar 0 "x"
-- conjecture =
-- sin arg |<=| -1000
-- where
-- arg = hull lower upper
-- lower = 1.6
-- upper = 4
sinsin2 =
Problem box conjecture
where
box = [(0, (0.1,0.19), False)]
x = termVar 0 "x"
conjecture =
sin(sin(3*x)+1) |<=| sin(3*x+1)
absNonneg =
Problem box conjecture
where
box = [(0, (-1,1), False), (1, (-1,1), False)]
x = termVar 0 "x"
y = termVar 1 "y"
conjecture =
-0.01 |<=| (termOp1 (FSqrt 24 126) $ abs (x *: y))
| michalkonecny/polypaver | examples/haskell/mini.hs | bsd-3-clause | 1,948 | 0 | 13 | 665 | 577 | 329 | 248 | 43 | 1 |
module P009 where
import Data.Foldable (find)
import Data.Maybe (fromJust, mapMaybe)
run :: IO ()
run = print . mult $ triple
where
triple = fromJust . find (\(a,b,c) -> a+b+c == 1000) $ triples
mult (a,b,c) = a*b*c
triples :: [(Integer, Integer, Integer)]
triples = mapMaybe maybeTriple . filter (uncurry (<)) $ pairs
where
maybeTriple (a,b) = case perfectRoot (a^2 + b^2) of
Just c -> Just (a,b,c)
Nothing -> Nothing
-- Will not work if the input is large enough
perfectRoot :: Integer -> Maybe Integer
perfectRoot n | root^2 == n = Just root
| otherwise = Nothing
where
root = floor . sqrt . fromIntegral $ n
pairs :: [(Integer, Integer)]
pairs = concatMap row [2..]
where
row total = map (\diff -> (diff, total-diff)) [1..total-1]
| tyehle/euler-haskell | src/P009.hs | bsd-3-clause | 796 | 0 | 14 | 190 | 366 | 199 | 167 | 19 | 2 |
{-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, FlexibleInstances,
MultiParamTypeClasses, FlexibleContexts, StandaloneDeriving,
UndecidableInstances #-}
module FRP.Sodium.GameEngine2D.Platform where
import FRP.Sodium.GameEngine2D.Geometry
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import Data.Default
import Data.Monoid
import Data.Sequence (Seq)
import Data.Text (Text)
import qualified Data.Text as T
import FRP.Sodium
import System.FilePath
import System.Random (StdGen)
data MouseEvent p =
MouseDown { meTouch :: Touch p, mePosition :: Point } |
MouseMove { meTouch :: Touch p, mePosition :: Point } |
MouseUp { meTouch :: Touch p, mePosition :: Point }
deriving instance Show (Touch p) => Show (MouseEvent p)
mouseTouch :: MouseEvent p -> Touch p
mouseTouch (MouseDown to _) = to
mouseTouch (MouseMove to _) = to
mouseTouch (MouseUp to _) = to
mousePosition :: MouseEvent p -> Point
mousePosition (MouseDown _ pt) = pt
mousePosition (MouseMove _ pt) = pt
mousePosition (MouseUp _ pt) = pt
-- | Like 'gate' except it only blocks mouse down events, otherwise we get weird
-- effects.
gateMouse :: Event (MouseEvent p) -> Behavior Bool -> Event (MouseEvent p)
gateMouse e b = filterJust $ snapshot fmouse e b
where
fmouse (MouseDown _ _) False = Nothing
fmouse m _ = Just m
data GameInput p = GameInput {
giAspect :: Behavior Coord,
giMouse :: Event (MouseEvent p),
giTime :: Behavior Double,
giRNG0 :: StdGen
}
data GameOutput p = GameOutput {
goSprite :: Behavior (Sprite p),
goMusic :: Behavior (Text, [Sound p]),
goEffects :: Event (Sound p)
}
instance Platform p => Default (GameOutput p) where
def = GameOutput (pure mempty) (pure (T.empty, [])) never
data TouchPhase = TouchBegan | TouchMoved | TouchEnded | TouchCancelled deriving (Eq, Ord, Show, Enum)
type Touched p = Touch p -> TouchPhase -> Coord -> Coord -> IO ()
type Drawable p = Rect -> Sprite p
data Key = NullKey
| BoolKey Bool
| ByteStringKey ByteString
| TextKey Text
| CompositeKey Key Key
deriving (Eq, Ord, Read, Show)
appendKey :: Key -> Key -> Key
appendKey NullKey k = k
appendKey k NullKey = k
appendKey k1 k2 = CompositeKey k1 k2
engine :: Platform p =>
Args p -> (GameInput p -> Reactive (GameOutput p)) -> IO ()
engine args game = engine' args $ \gi run -> sync (game gi) >>= run
class (Monoid (Sprite p),
Eq (Touch p),
Ord (Touch p)) => Platform p where
data Args p
data Internals p
data Sprite p
data Font p
data Sound p
type Touch p
engine' :: Args p -> (GameInput p -> (GameOutput p -> IO ()) -> IO ()) -> IO ()
nullDrawable :: Drawable p
image :: FilePath -> IO (Drawable p)
backgroundImage :: FilePath -> IO (Sprite p)
sound :: FilePath -> IO (Sound p)
retainSound :: Args p -> Sound p -> IO ()
translateSprite :: (Coord, Coord) -> Sprite p -> Sprite p
createFont :: FilePath
-> Float -- Y correction upwards fraction of 1.
-> IO (Font p)
key :: Key -> Sprite p -> Sprite p
keyOf :: Drawable p -> Key
-- Normally the bounding rectangle (used in caching) is caculated from all components.
-- This allows you to set it explicitly.
setBoundingBox :: Rect -> Sprite p -> Sprite p
-- True if it should multisample
cache :: Bool -> Sprite p -> Sprite p
--uncachedLabel :: Rect -> Color4 GLfloat -> Text -> Sprite p
fade :: Coord -> Sprite p -> Sprite p
shrink :: Coord -> Sprite p -> Sprite p
preRunSprite :: Internals p -> Int -> Sprite p -> IO ()
runSprite :: Internals p -> Int -> Sprite p -> Bool -> IO ()
audioThread :: Internals p -> [(Behavior [Sound p], Float)] -> IO ()
-- Rotate the sprite 90 degrees clockwise
clockwiseSprite :: Sprite p -> Sprite p
-- Rotate the sprite 90 degrees anti-clockwise
anticlockwiseSprite :: Sprite p -> Sprite p
rotateSprite :: Coord -> Sprite p -> Sprite p
-- Make this sprite invisible, but allow it to cache anything in the invisible sprite
invisible :: Sprite p -> Sprite p
launchURL :: p -> ByteString -> IO ()
getSystemLanguage :: p -> IO ByteString
{-
label :: Platform p => Rect -> Color4 GLfloat -> Text -> Sprite p
label r col txt = cache True $ uncachedLabel r col txt
-}
| the-real-blackh/sodium-2d-game-engine | FRP/Sodium/GameEngine2D/Platform.hs | bsd-3-clause | 4,447 | 0 | 15 | 1,116 | 1,389 | 727 | 662 | 93 | 2 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE JavaScriptFFI #-}
{-| This module provides implementations of cryptographic utilities that only
work for GHCJS
-}
module Dhall.Crypto (
SHA256Digest(..)
, sha256DigestFromByteString
, sha256Hash
) where
import Control.DeepSeq (NFData)
import Data.ByteString (ByteString)
import GHC.Generics (Generic)
import JavaScript.TypedArray.ArrayBuffer (ArrayBuffer)
import System.IO.Unsafe (unsafePerformIO)
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Base16 as Base16
import qualified Data.ByteString.Char8 as ByteString.Char8
import qualified GHCJS.Buffer as Buffer
-- | A SHA256 digest
newtype SHA256Digest = SHA256Digest { unSHA256Digest :: ByteString }
deriving (Eq, Generic, Ord, NFData)
instance Show SHA256Digest where
show (SHA256Digest bytes) = ByteString.Char8.unpack $ Base16.encode bytes
{-| Attempt to interpret a `ByteString` as a `SHA256Digest`, returning
`Nothing` if the conversion fails
-}
sha256DigestFromByteString :: ByteString -> Maybe SHA256Digest
sha256DigestFromByteString bytes
| ByteString.length bytes == 32 = Just (SHA256Digest bytes)
| otherwise = Nothing
-- Use NodeJS' crypto module if there's a 'process' module, e.g. we're running
-- inside GHCJS' THRunner. If we're running in the browser, use the WebCrypto
-- interface.
foreign import javascript interruptible
"if (typeof process === 'undefined') { \
\ crypto.subtle.digest('SHA-256', $1).then($c) \
\} else { \
\ $c(require('crypto').createHash('sha256').update(Buffer.from($1)).digest().buffer) \
\}"
js_sha256Hash :: ArrayBuffer -> IO ArrayBuffer
byteStringToArrayBuffer :: ByteString -> ArrayBuffer
byteStringToArrayBuffer b =
js_arrayBufferSlice offset len $ Buffer.getArrayBuffer buffer
where
(buffer, offset, len) = Buffer.fromByteString b
foreign import javascript unsafe "$3.slice($1, $1 + $2)"
js_arrayBufferSlice :: Int -> Int -> ArrayBuffer -> ArrayBuffer
arrayBufferToByteString :: ArrayBuffer -> ByteString
arrayBufferToByteString =
Buffer.toByteString 0 Nothing . Buffer.createFromArrayBuffer
-- | Hash a `ByteString` and return the hash as a `SHA256Digest`
sha256Hash :: ByteString -> SHA256Digest
sha256Hash bytes
| ByteString.length out == 32 = SHA256Digest out
| otherwise = error "sha256Hash: didn't produce 32 bytes"
where
out =
arrayBufferToByteString $
unsafePerformIO $ js_sha256Hash (byteStringToArrayBuffer bytes)
| Gabriel439/Haskell-Dhall-Library | dhall/ghcjs-src/Dhall/Crypto.hs | bsd-3-clause | 2,674 | 12 | 10 | 524 | 440 | 242 | 198 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
-- | This is a simple text widget that updates its contents by calling
-- a callback at a set interval.
module System.Taffybar.Widgets.PollingLabel ( pollingLabelNew ) where
import Control.Concurrent ( forkIO, threadDelay )
import Control.Exception.Enclosed as E
import Control.Monad ( forever )
import Graphics.UI.Gtk
-- | Create a new widget that updates itself at regular intervals. The
-- function
--
-- > pollingLabelNew initialString cmd interval
--
-- returns a widget with initial text @initialString@. The widget
-- forks a thread to update its contents every @interval@ seconds.
-- The command should return a string with any HTML entities escaped.
-- This is not checked by the function, since Pango markup shouldn't
-- be escaped. Proper input sanitization is up to the caller.
--
-- If the IO action throws an exception, it will be swallowed and the
-- label will not update until the update interval expires.
pollingLabelNew :: String -- ^ Initial value for the label
-> Double -- ^ Update interval (in seconds)
-> IO String -- ^ Command to run to get the input string
-> IO Widget
pollingLabelNew initialString interval cmd = do
l <- labelNew (Nothing :: Maybe String)
labelSetMarkup l initialString
_ <- on l realize $ do
_ <- forkIO $ forever $ do
estr <- E.tryAny cmd
case estr of
Left _ -> return ()
Right str -> postGUIAsync $ labelSetMarkup l str
threadDelay $ floor (interval * 1000000)
return ()
return (toWidget l)
| Undeterminant/taffybar | src/System/Taffybar/Widgets/PollingLabel.hs | bsd-3-clause | 1,600 | 0 | 19 | 371 | 250 | 133 | 117 | 22 | 2 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, TypeFamilies #-}
module Data.NumKell.Memo
( FMemoIdx(..), fFromList, fMemo
) where
import Control.Applicative ((<$>), (<*>))
import Data.Array (Ix, (!), listArray)
import Data.HList (HCons(..), HNil(..))
import Data.NumKell.Funk (Funk(..))
data FMemoIdxFuncs i = FMemoIdxFuncs
{ fMemoArrIdx :: i -> FMemoArrIdx i
, fMemoArrBounds :: i -> (FMemoArrIdx i, FMemoArrIdx i)
, fAllIdxs :: i -> [i]
}
type family FFromListType i a
type instance FFromListType HNil a = a
type instance FFromListType (HCons a as) b
= [FFromListType as b]
class FMemoIdx i where
type FMemoArrIdx i
fMemoIdxFuncs :: FMemoIdxFuncs i
fFromListArgs :: FFromListType i e -> (i, [e])
fMemo :: (FMemoIdx i, Ix (FMemoArrIdx i)) => Funk i e -> Funk i e
fMemo funk =
Funk
{ funkSize = funkSize funk
, funkIndex = (arr !) . fMemoArrIdx tbl
}
where
tbl = fMemoIdxFuncs
arr
= listArray (fMemoArrBounds tbl (funkSize funk))
. map (funkIndex funk) . fAllIdxs tbl . funkSize $ funk
fFromList :: (FMemoIdx i, Ix (FMemoArrIdx i))
=> FFromListType i e -> Funk i e
fFromList lst =
Funk
{ funkSize = sz
, funkIndex = (arr !) . fMemoArrIdx tbl
}
where
tbl = fMemoIdxFuncs
(sz, elems) = fFromListArgs lst
arr = listArray (fMemoArrBounds tbl sz) elems
instance FMemoIdx HNil where
type FMemoArrIdx HNil = ()
fMemoIdxFuncs = FMemoIdxFuncs (const ()) (const ((), ())) (const [HNil])
fFromListArgs x = (HNil, [x])
instance (FMemoIdx as, Integral a)
=> FMemoIdx (HCons a as) where
type FMemoArrIdx (HCons a as)
= (Int, FMemoArrIdx as)
fMemoIdxFuncs =
FMemoIdxFuncs ix bnds allIdx
where
tbl = fMemoIdxFuncs
ix (HCons x xs) = (fromIntegral x, fMemoArrIdx tbl xs)
bnds (HCons x xs) =
((0, inStart), (fromIntegral x - 1, inEnd))
where
(inStart, inEnd) = fMemoArrBounds tbl xs
allIdx (HCons x xs) =
HCons <$> [0 .. fromIntegral x - 1] <*> fAllIdxs tbl xs
fFromListArgs lst =
( HCons
((fromIntegral . length) lst)
((fst . head) elemArgs)
, elemArgs >>= snd)
where
elemArgs = map fFromListArgs lst
| yairchu/numkell | src/Data/NumKell/Memo.hs | bsd-3-clause | 2,185 | 0 | 15 | 525 | 839 | 461 | 378 | 60 | 1 |
-- Echo server program
module Main where
import Control.Monad (unless,when)
import Network.Socket hiding (recv)
import qualified Data.ByteString as S
import Data.Word(Word8)
import Control.Concurrent(threadDelay)
import Data.List
import Numeric
import Network.Socket.ByteString (recv, sendAll)
main = withSocketsDo $
do addrinfos <- getAddrInfo
(Just (defaultHints {addrFlags = [AI_PASSIVE]}))
Nothing (Just "6666")
let serveraddr = head addrinfos
sock <- socket (addrFamily serveraddr) Stream defaultProtocol
bindSocket sock (addrAddress serveraddr)
listen sock 1
loop sock
where
loop s = do
(connSock, _) <- accept s
talk connSock
loop s
whenM a b = a >>= (flip when) b
talk :: Socket -> IO ()
talk connSock = do
putStrLn "now we are talking..."
whenM (sIsConnected connSock) (putStrLn "connected!")
whenM (sIsReadable connSock) (putStrLn "readable!")
whenM (sIsWritable connSock) (putStrLn "writable!")
msg <- recv connSock 1024
print $ "received over the wire: " ++ (show msg)
unless (S.null msg) $ do
threadDelay(500*1000)
sendAll connSock $ replyTo msg
putStrLn "sent back response, starting to listen again..."
talk connSock
replyTo = S.reverse
| marcmo/hsDiagnosis | other/echoServer.hs | bsd-3-clause | 1,441 | 0 | 15 | 449 | 429 | 210 | 219 | 37 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Plugins.Date
-- Copyright : (c) Andrea Rossato
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Andrea Rossato <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- A date plugin for Xmobar
--
-- Usage example: in template put
--
-- > Run Date "%a %b %_d %Y <fc=#ee9a00> %H:%M:%S</fc>" "Mydate" 10
--
-----------------------------------------------------------------------------
module Plugins.Date where
import Plugins
import System.Locale
import System.Time
data Date = Date String String Int
deriving (Read, Show)
instance Exec Date where
alias (Date _ a _) = a
run (Date f _ _) = date f
rate (Date _ _ r) = r
date :: String -> IO String
date format = do
t <- toCalendarTime =<< getClockTime
return $ formatCalendarTime defaultTimeLocale format t
| neglectedvalue/xmobar-freebsd | Plugins/Date.hs | bsd-3-clause | 931 | 0 | 8 | 178 | 170 | 95 | 75 | 14 | 1 |
{-# LANGUAGE FlexibleContexts #-}
-- | Alias analysis of a full Futhark program. Takes as input a
-- program with an arbitrary lore and produces one with aliases. This
-- module does not implement the aliasing logic itself, and derives
-- its information from definitions in
-- "Futhark.Representation.AST.Attributes.Aliases" and
-- "Futhark.Representation.Aliases".
module Futhark.Analysis.Alias
( aliasAnalysis
-- * Ad-hoc utilities
, analyseFun
, analyseBinding
, analyseExp
, analyseBody
, analyseLambda
, analyseExtLambda
)
where
import Data.Monoid
import Futhark.Representation.AST.Syntax
import Futhark.Representation.Aliases
import Prelude
-- | Perform alias analysis on a Futhark program.
aliasAnalysis :: (Attributes lore, CanBeAliased (Op lore)) =>
Prog lore -> Prog (Aliases lore)
aliasAnalysis = Prog . map analyseFun . progFunctions
analyseFun :: (Attributes lore, CanBeAliased (Op lore)) =>
FunDef lore -> FunDef (Aliases lore)
analyseFun (FunDef entry fname restype params body) =
FunDef entry fname restype params body'
where body' = analyseBody body
analyseBody :: (Attributes lore,
CanBeAliased (Op lore)) =>
Body lore -> Body (Aliases lore)
analyseBody (Body lore origbnds result) =
let bnds' = map analyseBinding origbnds
in mkAliasedBody lore bnds' result
analyseBinding :: (Attributes lore,
CanBeAliased (Op lore)) =>
Binding lore -> Binding (Aliases lore)
analyseBinding (Let pat lore e) =
let e' = analyseExp e
pat' = addAliasesToPattern pat e'
lore' = (Names' $ consumedInPattern pat' <> consumedInExp e',
lore)
in Let pat' lore' e'
analyseExp :: (Attributes lore, CanBeAliased (Op lore)) =>
Exp lore -> Exp (Aliases lore)
analyseExp = mapExp analyse
where analyse =
Mapper { mapOnSubExp = return
, mapOnCertificates = return
, mapOnVName = return
, mapOnBody = return . analyseBody
, mapOnRetType = return
, mapOnFParam = return
, mapOnOp = return . addOpAliases
}
analyseLambda :: (Attributes lore, CanBeAliased (Op lore)) =>
Lambda lore -> Lambda (Aliases lore)
analyseLambda lam =
let body = analyseBody $ lambdaBody lam
in lam { lambdaBody = body
, lambdaParams = lambdaParams lam
}
analyseExtLambda :: (Attributes lore, CanBeAliased (Op lore)) =>
ExtLambda lore -> ExtLambda (Aliases lore)
analyseExtLambda lam =
let body = analyseBody $ extLambdaBody lam
in lam { extLambdaBody = body
, extLambdaParams = extLambdaParams lam
}
| mrakgr/futhark | src/Futhark/Analysis/Alias.hs | bsd-3-clause | 2,835 | 0 | 12 | 823 | 681 | 359 | 322 | 59 | 1 |
-- |
-- Module: Main
-- Copyright: (c) 2013 Ertugrul Soeylemez
-- License: BSD3
-- Maintainer: Ertugrul Soeylemez <[email protected]>
--
-- Benchmark for the instinct package.
module Main where
import Criterion.Main
main :: IO ()
main = defaultMain []
| ertes/instinct | test/Bench.hs | bsd-3-clause | 258 | 0 | 6 | 51 | 36 | 23 | 13 | 4 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Hulk.Types
(Config (..)
,Nick (..) -- FIXME:
,nickText
,UserName (..) -- FIXME:
,userText
,ChannelName (..) -- FIXME:
,nickToUserName
,channelNameText
,Channel (..)
,Client (..)
,User (..)
,UnregUser (..)
,RegUser (..)
,Ref (..)
,mkRef
,UserData (..)
,Conn (..)
,Event (..)
,RPL (..)
,QuitType (..)
,ChannelReplyType (..)
,Hulk
,HulkT
,runHulk
,HulkReader(..)
,HulkWriter(..)
,HulkState(..))
where
import Control.Monad.Identity
import Control.Monad.RWS
import Data.Aeson
import Data.CaseInsensitive
import Data.Map (Map)
import Data.Ord
import Data.Set (Set)
import Data.Text (Text)
import Data.Time
import GHC.Generics
import Network
import Network.FastIRC (Message)
import System.IO
--------------------------------------------------------------------------------
-- Configuration
-- | Server configuration.
data Config = Config
{ configListen :: !PortNumber
, configHostname :: !Text
, configMotd :: !(Maybe FilePath)
, configPreface :: !(Maybe FilePath)
, configPasswd :: !FilePath
, configPasswdKey :: !FilePath
, configUserData :: !FilePath
, configLogFile :: !FilePath
, configLogChans :: ![Text]
} deriving (Show)
--------------------------------------------------------------------------------
-- Fundamental IRC data types
-- | A case-insensitive nickname.
newtype Nick = NickName (CI Text)
deriving (Show,Eq,Ord)
-- | Extract the text of a nickname for use in output.
nickText :: Nick -> Text
nickText (NickName ci) = original ci
-- | A case-insensitive username.
newtype UserName = UserName (CI Text)
deriving (Show,Eq,Ord,Generic)
instance ToJSON UserName where
toJSON (UserName ci) = toJSON (original ci)
instance FromJSON UserName where
parseJSON = fmap (UserName . mk) . parseJSON
-- | Extract the text of a username for use in output.
userText :: UserName -> Text
userText (UserName ci) = original ci
-- | Convert a nick to a username.
nickToUserName :: Nick -> UserName
nickToUserName = UserName . mk . nickText
-- | A case-insensitive channel name.
newtype ChannelName = ChannelName (CI Text)
deriving (Show,Eq,Ord)
-- | Extract the text of a channelname for use in output.
channelNameText :: ChannelName -> Text
channelNameText (ChannelName ci) = original ci
--------------------------------------------------------------------------------
-- Server state types
-- | A channel.
data Channel = Channel
{ channelName :: !ChannelName
, channelTopic :: !(Maybe Text)
, channelUsers :: !(Set Ref)
} deriving (Show)
--------------------------------------------------------------------------------
-- Client data types
-- | A connected client.
data Client = Client
{ clientRef :: !Ref
, clientUser :: !User
, clientHostname :: !Text
, clientLastPong :: !UTCTime
, clientAwayMsg :: !(Maybe Text)
} deriving (Show)
-- | Some user, either unregistered or registered.
data User
= Unregistered UnregUser
| Registered RegUser
deriving Show
-- | An unregistered user.
data UnregUser = UnregUser
{ unregUserName :: !(Maybe Text)
, unregUserNick :: !(Maybe Nick)
, unregUserUser :: !(Maybe UserName)
, unregUserPass :: !(Maybe Text)
} deriving (Show)
-- | A registered user.
data RegUser = RegUser
{ regUserName :: !Text
, regUserNick :: !Nick
, regUserUser :: !UserName
, regUserPass :: !Text
} deriving (Show)
-- | A reference for a client.
newtype Ref = Ref { unRef :: Handle }
deriving (Show,Eq)
-- | Make a ref.
mkRef :: Handle -> Ref
mkRef = Ref
-- | Use for refs in maps.
instance Ord Ref where
compare = comparing show
-- | Data saved about a user for later actions like log recall.
data UserData = UserData
{ userDataUser :: !UserName
, userDataLastSeen :: !UTCTime
} deriving (Show,Generic)
instance ToJSON UserData
instance FromJSON UserData
--------------------------------------------------------------------------------
-- Client handling types
-- | The Hulk client monad.
newtype HulkT m a = Hulk { runHulk :: RWST HulkReader [HulkWriter] HulkState m a }
deriving (Monad,
Functor,
Applicative,
MonadReader HulkReader,
MonadWriter [HulkWriter],
MonadState HulkState)
type Hulk = HulkT Identity
-- | Configuration/environment information for running the client
-- handler.
data HulkReader = HulkReader
{ readTime :: !UTCTime
, readConn :: !Conn
, readConfig :: !Config
, readMotd :: !(Maybe Text)
, readAuth :: !(String,String)
} deriving (Show)
-- | State of the whole server, which the client handles.
data HulkState = HulkState
{ stateClients :: !(Map Ref Client)
, stateNicks :: !(Map Nick Ref)
, stateChannels :: !(Map ChannelName Channel)
} deriving (Show)
-- | Replies are generated by the client after some messages.
data HulkWriter
= MessageReply !Ref !Message
| LogReply !Text
| Close
| Bump !Ref
| UpdateUserData !UserData
| SaveLog !Text !RPL ![Text]
| SendEvents !Ref !UserName
deriving (Show)
-- | Used when handling a line from a client.
data Conn = Conn
{ connRef :: !Ref
, connHostname :: !Text
, connServerName :: !Text
, connTime :: !UTCTime
} deriving (Show)
-- | An incoming client message.
data Event
= PASS
| USER
| NICK
| PING
| QUIT
| TELL
| JOIN
| PART
| PRIVMSG
| NOTICE
| ISON
| WHOIS
| TOPIC
| CONNECT
| DISCONNECT
| PINGPONG
| PONG
| NAMES
| NOTHING
deriving (Show,Read)
-- | An outgoing server reply.
data RPL
= RPL_WHOISUSER
| RPL_NICK
| RPL_PONG
| RPL_JOIN
| RPL_QUIT
| RPL_NOTICE
| RPL_PART
| RPL_PRIVMSG
| RPL_ISON
| RPL_JOINS
| RPL_TOPIC
| RPL_NAMEREPLY
| RPL_ENDOFNAMES
| ERR_NICKNAMEINUSE
| RPL_WELCOME
| RPL_MOTDSTART
| RPL_MOTD
| RPL_ENDOFMOTD
| RPL_WHOISIDLE
| RPL_ENDOFWHOIS
| RPL_WHOISCHANNELS
| ERR_NOSUCHNICK
| ERR_NOSUCHCHANNEL
| RPL_PING
deriving (Show,Generic)
instance ToJSON RPL
instance FromJSON RPL
-- | When quitting it can either be due to user request, ping timeout,
-- or the socket was closed.
data QuitType
= RequestedQuit
| SocketQuit
deriving (Show,Eq)
-- | When sending a channel reply, it can either include the current
-- client or exclude them (e.g. when the client sends a message, it's
-- no use echoing it back to that user).
data ChannelReplyType
= IncludeMe
| ExcludeMe
deriving (Show,Eq)
| chrisdone/hulk | src/Hulk/Types.hs | bsd-3-clause | 6,702 | 0 | 11 | 1,455 | 1,500 | 886 | 614 | 305 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.InstallDirs
-- Copyright : Isaac Jones 2003-2004
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This manages everything to do with where files get installed (though does
-- not get involved with actually doing any installation). It provides an
-- 'InstallDirs' type which is a set of directories for where to install
-- things. It also handles the fact that we use templates in these install
-- dirs. For example most install dirs are relative to some @$prefix@ and by
-- changing the prefix all other dirs still end up changed appropriately. So it
-- provides a 'PathTemplate' type and functions for substituting for these
-- templates.
module Distribution.Simple.InstallDirs (
InstallDirs(..),
InstallDirTemplates,
defaultInstallDirs,
combineInstallDirs,
absoluteInstallDirs,
CopyDest(..),
prefixRelativeInstallDirs,
substituteInstallDirTemplates,
PathTemplate,
PathTemplateVariable(..),
PathTemplateEnv,
toPathTemplate,
fromPathTemplate,
substPathTemplate,
initialPathTemplateEnv,
platformTemplateEnv,
compilerTemplateEnv,
packageTemplateEnv,
abiTemplateEnv,
installDirsTemplateEnv,
) where
import Distribution.Compat.Binary (Binary)
import Distribution.Compat.Semigroup as Semi
import Distribution.Package
import Distribution.System
import Distribution.Compiler
import Distribution.Text
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe)
import GHC.Generics (Generic)
import System.Directory (getAppUserDataDirectory)
import System.FilePath ((</>), isPathSeparator, pathSeparator)
import System.FilePath (dropDrive)
#if mingw32_HOST_OS
import Foreign
import Foreign.C
#endif
-- ---------------------------------------------------------------------------
-- Installation directories
-- | The directories where we will install files for packages.
--
-- We have several different directories for different types of files since
-- many systems have conventions whereby different types of files in a package
-- are installed in different directories. This is particularly the case on
-- Unix style systems.
--
data InstallDirs dir = InstallDirs {
prefix :: dir,
bindir :: dir,
libdir :: dir,
libsubdir :: dir,
dynlibdir :: dir,
libexecdir :: dir,
includedir :: dir,
datadir :: dir,
datasubdir :: dir,
docdir :: dir,
mandir :: dir,
htmldir :: dir,
haddockdir :: dir,
sysconfdir :: dir
} deriving (Eq, Read, Show, Functor, Generic)
instance Binary dir => Binary (InstallDirs dir)
instance (Semigroup dir, Monoid dir) => Monoid (InstallDirs dir) where
mempty = gmempty
mappend = (Semi.<>)
instance Semigroup dir => Semigroup (InstallDirs dir) where
(<>) = gmappend
combineInstallDirs :: (a -> b -> c)
-> InstallDirs a
-> InstallDirs b
-> InstallDirs c
combineInstallDirs combine a b = InstallDirs {
prefix = prefix a `combine` prefix b,
bindir = bindir a `combine` bindir b,
libdir = libdir a `combine` libdir b,
libsubdir = libsubdir a `combine` libsubdir b,
dynlibdir = dynlibdir a `combine` dynlibdir b,
libexecdir = libexecdir a `combine` libexecdir b,
includedir = includedir a `combine` includedir b,
datadir = datadir a `combine` datadir b,
datasubdir = datasubdir a `combine` datasubdir b,
docdir = docdir a `combine` docdir b,
mandir = mandir a `combine` mandir b,
htmldir = htmldir a `combine` htmldir b,
haddockdir = haddockdir a `combine` haddockdir b,
sysconfdir = sysconfdir a `combine` sysconfdir b
}
appendSubdirs :: (a -> a -> a) -> InstallDirs a -> InstallDirs a
appendSubdirs append dirs = dirs {
libdir = libdir dirs `append` libsubdir dirs,
datadir = datadir dirs `append` datasubdir dirs,
libsubdir = error "internal error InstallDirs.libsubdir",
datasubdir = error "internal error InstallDirs.datasubdir"
}
-- | The installation directories in terms of 'PathTemplate's that contain
-- variables.
--
-- The defaults for most of the directories are relative to each other, in
-- particular they are all relative to a single prefix. This makes it
-- convenient for the user to override the default installation directory
-- by only having to specify --prefix=... rather than overriding each
-- individually. This is done by allowing $-style variables in the dirs.
-- These are expanded by textual substitution (see 'substPathTemplate').
--
-- A few of these installation directories are split into two components, the
-- dir and subdir. The full installation path is formed by combining the two
-- together with @\/@. The reason for this is compatibility with other Unix
-- build systems which also support @--libdir@ and @--datadir@. We would like
-- users to be able to configure @--libdir=\/usr\/lib64@ for example but
-- because by default we want to support installing multiple versions of
-- packages and building the same package for multiple compilers we append the
-- libsubdir to get: @\/usr\/lib64\/$libname\/$compiler@.
--
-- An additional complication is the need to support relocatable packages on
-- systems which support such things, like Windows.
--
type InstallDirTemplates = InstallDirs PathTemplate
-- ---------------------------------------------------------------------------
-- Default installation directories
defaultInstallDirs :: CompilerFlavor -> Bool -> Bool -> IO InstallDirTemplates
defaultInstallDirs comp userInstall _hasLibs = do
installPrefix <-
if userInstall
then getAppUserDataDirectory "cabal"
else case buildOS of
Windows -> do windowsProgramFilesDir <- getWindowsProgramFilesDir
return (windowsProgramFilesDir </> "Haskell")
_ -> return "/usr/local"
installLibDir <-
case buildOS of
Windows -> return "$prefix"
_ -> case comp of
LHC | userInstall -> getAppUserDataDirectory "lhc"
_ -> return ("$prefix" </> "lib")
return $ fmap toPathTemplate $ InstallDirs {
prefix = installPrefix,
bindir = "$prefix" </> "bin",
libdir = installLibDir,
libsubdir = case comp of
JHC -> "$compiler"
LHC -> "$compiler"
UHC -> "$pkgid"
_other -> "$abi" </> "$libname",
dynlibdir = "$libdir" </> case comp of
JHC -> "$compiler"
LHC -> "$compiler"
UHC -> "$pkgid"
_other -> "$abi",
libexecdir = case buildOS of
Windows -> "$prefix" </> "$libname"
_other -> "$prefix" </> "libexec",
includedir = "$libdir" </> "$libsubdir" </> "include",
datadir = case buildOS of
Windows -> "$prefix"
_other -> "$prefix" </> "share",
datasubdir = "$abi" </> "$pkgid",
docdir = "$datadir" </> "doc" </> "$abi" </> "$pkgid",
mandir = "$datadir" </> "man",
htmldir = "$docdir" </> "html",
haddockdir = "$htmldir",
sysconfdir = "$prefix" </> "etc"
}
-- ---------------------------------------------------------------------------
-- Converting directories, absolute or prefix-relative
-- | Substitute the install dir templates into each other.
--
-- To prevent cyclic substitutions, only some variables are allowed in
-- particular dir templates. If out of scope vars are present, they are not
-- substituted for. Checking for any remaining unsubstituted vars can be done
-- as a subsequent operation.
--
-- The reason it is done this way is so that in 'prefixRelativeInstallDirs' we
-- can replace 'prefix' with the 'PrefixVar' and get resulting
-- 'PathTemplate's that still have the 'PrefixVar' in them. Doing this makes it
-- each to check which paths are relative to the $prefix.
--
substituteInstallDirTemplates :: PathTemplateEnv
-> InstallDirTemplates -> InstallDirTemplates
substituteInstallDirTemplates env dirs = dirs'
where
dirs' = InstallDirs {
-- So this specifies exactly which vars are allowed in each template
prefix = subst prefix [],
bindir = subst bindir [prefixVar],
libdir = subst libdir [prefixVar, bindirVar],
libsubdir = subst libsubdir [],
dynlibdir = subst dynlibdir [prefixVar, bindirVar, libdirVar],
libexecdir = subst libexecdir prefixBinLibVars,
includedir = subst includedir prefixBinLibVars,
datadir = subst datadir prefixBinLibVars,
datasubdir = subst datasubdir [],
docdir = subst docdir prefixBinLibDataVars,
mandir = subst mandir (prefixBinLibDataVars ++ [docdirVar]),
htmldir = subst htmldir (prefixBinLibDataVars ++ [docdirVar]),
haddockdir = subst haddockdir (prefixBinLibDataVars ++
[docdirVar, htmldirVar]),
sysconfdir = subst sysconfdir prefixBinLibVars
}
subst dir env' = substPathTemplate (env'++env) (dir dirs)
prefixVar = (PrefixVar, prefix dirs')
bindirVar = (BindirVar, bindir dirs')
libdirVar = (LibdirVar, libdir dirs')
libsubdirVar = (LibsubdirVar, libsubdir dirs')
datadirVar = (DatadirVar, datadir dirs')
datasubdirVar = (DatasubdirVar, datasubdir dirs')
docdirVar = (DocdirVar, docdir dirs')
htmldirVar = (HtmldirVar, htmldir dirs')
prefixBinLibVars = [prefixVar, bindirVar, libdirVar, libsubdirVar]
prefixBinLibDataVars = prefixBinLibVars ++ [datadirVar, datasubdirVar]
-- | Convert from abstract install directories to actual absolute ones by
-- substituting for all the variables in the abstract paths, to get real
-- absolute path.
absoluteInstallDirs :: PackageIdentifier
-> UnitId
-> CompilerInfo
-> CopyDest
-> Platform
-> InstallDirs PathTemplate
-> InstallDirs FilePath
absoluteInstallDirs pkgId libname compilerId copydest platform dirs =
(case copydest of
CopyTo destdir -> fmap ((destdir </>) . dropDrive)
_ -> id)
. appendSubdirs (</>)
. fmap fromPathTemplate
$ substituteInstallDirTemplates env dirs
where
env = initialPathTemplateEnv pkgId libname compilerId platform
-- |The location prefix for the /copy/ command.
data CopyDest
= NoCopyDest
| CopyTo FilePath
deriving (Eq, Show)
-- | Check which of the paths are relative to the installation $prefix.
--
-- If any of the paths are not relative, ie they are absolute paths, then it
-- prevents us from making a relocatable package (also known as a \"prefix
-- independent\" package).
--
prefixRelativeInstallDirs :: PackageIdentifier
-> UnitId
-> CompilerInfo
-> Platform
-> InstallDirTemplates
-> InstallDirs (Maybe FilePath)
prefixRelativeInstallDirs pkgId libname compilerId platform dirs =
fmap relative
. appendSubdirs combinePathTemplate
$ -- substitute the path template into each other, except that we map
-- \$prefix back to $prefix. We're trying to end up with templates that
-- mention no vars except $prefix.
substituteInstallDirTemplates env dirs {
prefix = PathTemplate [Variable PrefixVar]
}
where
env = initialPathTemplateEnv pkgId libname compilerId platform
-- If it starts with $prefix then it's relative and produce the relative
-- path by stripping off $prefix/ or $prefix
relative dir = case dir of
PathTemplate cs -> fmap (fromPathTemplate . PathTemplate) (relative' cs)
relative' (Variable PrefixVar : Ordinary (s:rest) : rest')
| isPathSeparator s = Just (Ordinary rest : rest')
relative' (Variable PrefixVar : rest) = Just rest
relative' _ = Nothing
-- ---------------------------------------------------------------------------
-- Path templates
-- | An abstract path, possibly containing variables that need to be
-- substituted for to get a real 'FilePath'.
--
newtype PathTemplate = PathTemplate [PathComponent]
deriving (Eq, Ord, Generic)
instance Binary PathTemplate
data PathComponent =
Ordinary FilePath
| Variable PathTemplateVariable
deriving (Eq, Ord, Generic)
instance Binary PathComponent
data PathTemplateVariable =
PrefixVar -- ^ The @$prefix@ path variable
| BindirVar -- ^ The @$bindir@ path variable
| LibdirVar -- ^ The @$libdir@ path variable
| LibsubdirVar -- ^ The @$libsubdir@ path variable
| DynlibdirVar -- ^ The @$dynlibdir@ path variable
| DatadirVar -- ^ The @$datadir@ path variable
| DatasubdirVar -- ^ The @$datasubdir@ path variable
| DocdirVar -- ^ The @$docdir@ path variable
| HtmldirVar -- ^ The @$htmldir@ path variable
| PkgNameVar -- ^ The @$pkg@ package name path variable
| PkgVerVar -- ^ The @$version@ package version path variable
| PkgIdVar -- ^ The @$pkgid@ package Id path variable, eg @foo-1.0@
| LibNameVar -- ^ The @$libname@ path variable
| CompilerVar -- ^ The compiler name and version, eg @ghc-6.6.1@
| OSVar -- ^ The operating system name, eg @windows@ or @linux@
| ArchVar -- ^ The CPU architecture name, eg @i386@ or @x86_64@
| AbiVar -- ^ The Compiler's ABI identifier, $arch-$os-$compiler-$abitag
| AbiTagVar -- ^ The optional ABI tag for the compiler
| ExecutableNameVar -- ^ The executable name; used in shell wrappers
| TestSuiteNameVar -- ^ The name of the test suite being run
| TestSuiteResultVar -- ^ The result of the test suite being run, eg
-- @pass@, @fail@, or @error@.
| BenchmarkNameVar -- ^ The name of the benchmark being run
deriving (Eq, Ord, Generic)
instance Binary PathTemplateVariable
type PathTemplateEnv = [(PathTemplateVariable, PathTemplate)]
-- | Convert a 'FilePath' to a 'PathTemplate' including any template vars.
--
toPathTemplate :: FilePath -> PathTemplate
toPathTemplate = PathTemplate . read
-- | Convert back to a path, any remaining vars are included
--
fromPathTemplate :: PathTemplate -> FilePath
fromPathTemplate (PathTemplate template) = show template
combinePathTemplate :: PathTemplate -> PathTemplate -> PathTemplate
combinePathTemplate (PathTemplate t1) (PathTemplate t2) =
PathTemplate (t1 ++ [Ordinary [pathSeparator]] ++ t2)
substPathTemplate :: PathTemplateEnv -> PathTemplate -> PathTemplate
substPathTemplate environment (PathTemplate template) =
PathTemplate (concatMap subst template)
where subst component@(Ordinary _) = [component]
subst component@(Variable variable) =
case lookup variable environment of
Just (PathTemplate components) -> components
Nothing -> [component]
-- | The initial environment has all the static stuff but no paths
initialPathTemplateEnv :: PackageIdentifier
-> UnitId
-> CompilerInfo
-> Platform
-> PathTemplateEnv
initialPathTemplateEnv pkgId libname compiler platform =
packageTemplateEnv pkgId libname
++ compilerTemplateEnv compiler
++ platformTemplateEnv platform
++ abiTemplateEnv compiler platform
packageTemplateEnv :: PackageIdentifier -> UnitId -> PathTemplateEnv
packageTemplateEnv pkgId libname =
[(PkgNameVar, PathTemplate [Ordinary $ display (packageName pkgId)])
,(PkgVerVar, PathTemplate [Ordinary $ display (packageVersion pkgId)])
,(LibNameVar, PathTemplate [Ordinary $ display libname])
,(PkgIdVar, PathTemplate [Ordinary $ display pkgId])
]
compilerTemplateEnv :: CompilerInfo -> PathTemplateEnv
compilerTemplateEnv compiler =
[(CompilerVar, PathTemplate [Ordinary $ display (compilerInfoId compiler)])
]
platformTemplateEnv :: Platform -> PathTemplateEnv
platformTemplateEnv (Platform arch os) =
[(OSVar, PathTemplate [Ordinary $ display os])
,(ArchVar, PathTemplate [Ordinary $ display arch])
]
abiTemplateEnv :: CompilerInfo -> Platform -> PathTemplateEnv
abiTemplateEnv compiler (Platform arch os) =
[(AbiVar, PathTemplate [Ordinary $ display arch ++ '-':display os ++
'-':display (compilerInfoId compiler) ++
case compilerInfoAbiTag compiler of
NoAbiTag -> ""
AbiTag tag -> '-':tag])
,(AbiTagVar, PathTemplate [Ordinary $ abiTagString (compilerInfoAbiTag compiler)])
]
installDirsTemplateEnv :: InstallDirs PathTemplate -> PathTemplateEnv
installDirsTemplateEnv dirs =
[(PrefixVar, prefix dirs)
,(BindirVar, bindir dirs)
,(LibdirVar, libdir dirs)
,(LibsubdirVar, libsubdir dirs)
,(DynlibdirVar, dynlibdir dirs)
,(DatadirVar, datadir dirs)
,(DatasubdirVar, datasubdir dirs)
,(DocdirVar, docdir dirs)
,(HtmldirVar, htmldir dirs)
]
-- ---------------------------------------------------------------------------
-- Parsing and showing path templates:
-- The textual format is that of an ordinary Haskell String, eg
-- "$prefix/bin"
-- and this gets parsed to the internal representation as a sequence of path
-- spans which are either strings or variables, eg:
-- PathTemplate [Variable PrefixVar, Ordinary "/bin" ]
instance Show PathTemplateVariable where
show PrefixVar = "prefix"
show LibNameVar = "libname"
show BindirVar = "bindir"
show LibdirVar = "libdir"
show LibsubdirVar = "libsubdir"
show DynlibdirVar = "dynlibdir"
show DatadirVar = "datadir"
show DatasubdirVar = "datasubdir"
show DocdirVar = "docdir"
show HtmldirVar = "htmldir"
show PkgNameVar = "pkg"
show PkgVerVar = "version"
show PkgIdVar = "pkgid"
show CompilerVar = "compiler"
show OSVar = "os"
show ArchVar = "arch"
show AbiTagVar = "abitag"
show AbiVar = "abi"
show ExecutableNameVar = "executablename"
show TestSuiteNameVar = "test-suite"
show TestSuiteResultVar = "result"
show BenchmarkNameVar = "benchmark"
instance Read PathTemplateVariable where
readsPrec _ s =
take 1
[ (var, drop (length varStr) s)
| (varStr, var) <- vars
, varStr `isPrefixOf` s ]
-- NB: order matters! Longer strings first
where vars = [("prefix", PrefixVar)
,("bindir", BindirVar)
,("libdir", LibdirVar)
,("libsubdir", LibsubdirVar)
,("dynlibdir", DynlibdirVar)
,("datadir", DatadirVar)
,("datasubdir", DatasubdirVar)
,("docdir", DocdirVar)
,("htmldir", HtmldirVar)
,("pkgid", PkgIdVar)
,("libname", LibNameVar)
,("pkgkey", LibNameVar) -- backwards compatibility
,("pkg", PkgNameVar)
,("version", PkgVerVar)
,("compiler", CompilerVar)
,("os", OSVar)
,("arch", ArchVar)
,("abitag", AbiTagVar)
,("abi", AbiVar)
,("executablename", ExecutableNameVar)
,("test-suite", TestSuiteNameVar)
,("result", TestSuiteResultVar)
,("benchmark", BenchmarkNameVar)]
instance Show PathComponent where
show (Ordinary path) = path
show (Variable var) = '$':show var
showList = foldr (\x -> (shows x .)) id
instance Read PathComponent where
-- for some reason we collapse multiple $ symbols here
readsPrec _ = lex0
where lex0 [] = []
lex0 ('$':'$':s') = lex0 ('$':s')
lex0 ('$':s') = case [ (Variable var, s'')
| (var, s'') <- reads s' ] of
[] -> lex1 "$" s'
ok -> ok
lex0 s' = lex1 [] s'
lex1 "" "" = []
lex1 acc "" = [(Ordinary (reverse acc), "")]
lex1 acc ('$':'$':s) = lex1 acc ('$':s)
lex1 acc ('$':s) = [(Ordinary (reverse acc), '$':s)]
lex1 acc (c:s) = lex1 (c:acc) s
readList [] = [([],"")]
readList s = [ (component:components, s'')
| (component, s') <- reads s
, (components, s'') <- readList s' ]
instance Show PathTemplate where
show (PathTemplate template) = show (show template)
instance Read PathTemplate where
readsPrec p s = [ (PathTemplate template, s')
| (path, s') <- readsPrec p s
, (template, "") <- reads path ]
-- ---------------------------------------------------------------------------
-- Internal utilities
getWindowsProgramFilesDir :: IO FilePath
getWindowsProgramFilesDir = do
#if mingw32_HOST_OS
m <- shGetFolderPath csidl_PROGRAM_FILES
#else
let m = Nothing
#endif
return (fromMaybe "C:\\Program Files" m)
#if mingw32_HOST_OS
shGetFolderPath :: CInt -> IO (Maybe FilePath)
shGetFolderPath n =
allocaArray long_path_size $ \pPath -> do
r <- c_SHGetFolderPath nullPtr n nullPtr 0 pPath
if (r /= 0)
then return Nothing
else do s <- peekCWString pPath; return (Just s)
where
long_path_size = 1024 -- MAX_PATH is 260, this should be plenty
csidl_PROGRAM_FILES :: CInt
csidl_PROGRAM_FILES = 0x0026
-- csidl_PROGRAM_FILES_COMMON :: CInt
-- csidl_PROGRAM_FILES_COMMON = 0x002b
#ifdef x86_64_HOST_ARCH
#define CALLCONV ccall
#else
#define CALLCONV stdcall
#endif
foreign import CALLCONV unsafe "shlobj.h SHGetFolderPathW"
c_SHGetFolderPath :: Ptr ()
-> CInt
-> Ptr ()
-> CInt
-> CWString
-> IO CInt
#endif
| tolysz/prepare-ghcjs | spec-lts8/cabal/Cabal/Distribution/Simple/InstallDirs.hs | bsd-3-clause | 22,821 | 2 | 16 | 6,271 | 4,287 | 2,397 | 1,890 | 370 | 13 |
module Geometry.Segment
( Segment
, translateSegment
, splitSegmentsOnY
, splitSegmentsOnX
, chooseSplitX
, chooseClippingSegment
, polarOfRectSeg)
where
import Geometry.Point
import Geometry.Intersection
import qualified Data.Vector.Unboxed as V
import Data.Vector.Unboxed (Vector)
import Data.Maybe
import Data.Function
-- | A line segement in the 2D plane.
type Segment coord
= (Int, (Double, Double), (Double, Double))
-- | Translate both endpoints of a segment.
translateSegment :: Double -> Double -> Segment c -> Segment c
translateSegment tx ty (n, (x1, y1), (x2, y2))
= (n, (x1 + tx, y1 + ty), (x2 + tx, y2 + ty))
-- | Split segments that cross the line y = y0, for some y0.
splitSegmentsOnY :: Double -> Vector (Segment c) -> Vector (Segment c)
splitSegmentsOnY y0 segs
= let
-- TODO: we only need to know IF the seg crosse the line here,
-- not the actual intersection point. Do a faster test.
(segsCross, segsOther)
= V.unstablePartition
(\(_, p1, p2) -> isJust $ intersectSegHorzLine p1 p2 y0)
segs
-- TODO: going via lists here is bad.
splitCrossingSeg :: Segment c -> Vector (Segment c)
splitCrossingSeg (n, p1, p2)
= let Just pCross = intersectSegHorzLine p1 p2 y0
in V.fromList [(n, p1, pCross), (n, pCross, p2)]
-- TODO: vector append requires a copy.
in segsOther V.++ (V.concat $ map splitCrossingSeg $ V.toList segsCross)
-- | Split segments that cross the line x = x0, for some x0.
splitSegmentsOnX :: Double -> Vector (Segment c) -> Vector (Segment c)
splitSegmentsOnX x0 segs
= let
-- TODO: we only need to know IF the seg crosse the line here,
-- not the actual intersection point. Do a faster test.
(segsCross, segsOther)
= V.unstablePartition
(\(_, p1, p2) -> isJust $ intersectSegVertLine p1 p2 x0)
segs
-- TODO: going via lists here is bad.
splitCrossingSeg :: Segment c -> Vector (Segment c)
splitCrossingSeg (n, p1, p2)
= let Just pCross = intersectSegVertLine p1 p2 x0
in V.fromList [(n, p1, pCross), (n, pCross, p2)]
-- TODO: vector append requires a copy.
in segsOther V.++ (V.concat $ map splitCrossingSeg $ V.toList segsCross)
-- | Decide where to split the plane.
-- TODO: We're just taking the first point of the segment in the middle of the vector.
-- It might be better to base the split on:
-- - the closest segment
-- - the widest sgement
-- - the one closes to the middle of the field.
-- - some combination of above.
--
chooseSplitX :: Vector (Segment c) -> Double
chooseSplitX segments
= let Just (_, (x1, _), _) = segments V.!? (V.length segments `div` 2)
in x1
-- | Choose a segement to use for clipping.
chooseClippingSegment :: Vector (Segment Polar) -> Segment Polar
chooseClippingSegment segs
= V.maximumBy (compare `on` clippingScoreOfPolarSegment) segs
-- | Heuristic to estimate how good this segement will be for clipping.
clippingScoreOfPolarSegment :: Segment Polar -> Double
clippingScoreOfPolarSegment (_, (x1, y1), (x2, y2))
= (abs (x2 - x1)) / (y1 + y2)
-- | Convert a segment from rectangular to polar coordinates.
polarOfRectSeg :: Segment Rect -> Segment Polar
polarOfRectSeg (n, p1@(x1, y1), p2@(x2, y2))
| y2 == 0 && x2 > 0
= if y1 >= 0
then (n, polarOfRectPoint p1, (magPoint p2, 0))
else (n, polarOfRectPoint p1, (magPoint p2, 2 * pi))
| y1 == 0 && x1 > 0
= if y2 >= 0
then (n, (magPoint p1, 0), polarOfRectPoint p2)
else (n, (magPoint p1, 2 * pi), polarOfRectPoint p2)
| otherwise
= (n, polarOfRectPoint p1, polarOfRectPoint p2)
| mainland/dph | dph-examples/broken/Visibility/Geometry/Segment.hs | bsd-3-clause | 3,536 | 70 | 13 | 712 | 1,118 | 617 | 501 | 65 | 3 |
{- |
Module : $Header$
Description : Static analysis for the Edinburgh Logical Framework
Copyright : (c) Kristina Sojakova, DFKI Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module LF.Analysis where
import LF.AS
import LF.Sign
import LF.Twelf2GR
import Common.ExtSign
import Common.GlobalAnnotations
import Common.AS_Annotation
import Common.Result
import Common.DocUtils
import Data.List
import qualified Data.Map as Map
import qualified Data.Set as Set
import System.IO.Unsafe
sen_type_exp :: EXP
sen_type_exp = Type
gen_file :: String
gen_file = gen_base
gen_sig1 :: String
gen_sig1 = gen_module
gen_sig2 :: String
gen_sig2 = gen_module ++ "'"
gen :: String
gen = "gen_"
genPref :: String -> String
genPref s = gen ++ s
gen_ax :: String
gen_ax = genPref "ax"
numSuf :: String -> Int -> String
numSuf s i = s ++ "_" ++ show i
mkSig :: String -> String -> String
mkSig n cont = "%sig " ++ n ++ " = {\n" ++ cont ++ "}.\n"
mkIncl :: String -> String
mkIncl n = "%include " ++ n ++ " %open.\n"
mkRead :: String -> String
mkRead n = "%read \"" ++ n ++ "\".\n"
getSigItems :: [Annoted BASIC_ITEM] -> [Annoted BASIC_ITEM]
getSigItems = filter ( \ (Annoted i _ _ _) ->
case i of
Decl _ -> True
Form _ -> False )
getSenItems :: [Annoted BASIC_ITEM] -> [Annoted BASIC_ITEM]
getSenItems = filter ( \ (Annoted i _ _ _) ->
case i of
Decl _ -> False
Form _ -> True )
printSigItems :: [Annoted BASIC_ITEM] -> String
printSigItems =
concatMap (\ (Annoted i _ _ _) ->
case i of
Decl d -> d ++ ".\n"
_ -> ""
)
printSenItems :: String -> [Annoted BASIC_ITEM] -> String
printSenItems sen_type = printSenItemsH sen_type 0
printSenItemsH :: String -> Int -> [Annoted BASIC_ITEM] -> String
printSenItemsH _ _ [] = ""
printSenItemsH sen_type num (i : is) =
case i of
Annoted (Form f) _ _ _ ->
let lab = getRLabel i
lab' = if null lab then numSuf gen_ax num else lab
num' = if null lab then num + 1 else num
in lab' ++ " : " ++ sen_type ++ " = " ++ f ++ ".\n" ++
printSenItemsH sen_type num' is
_ -> printSenItemsH sen_type num is
makeNamedForms :: [(NAME, Sentence)] -> [[Annotation]] -> [Named Sentence]
makeNamedForms = zipWith (curry makeNamedForm)
makeNamedForm :: ((NAME, Sentence), [Annotation]) -> Named Sentence
makeNamedForm ((n, s), annos) =
let implies = any isImplies annos
implied = any isImplied annos
isTheorem = implies || implied
in (makeNamed n s) {isAxiom = not isTheorem}
getSigFromLibs :: MODULE -> LIBS -> IO Sign
getSigFromLibs n libs = do
lname <- toLibName HETS gen_file
let (sigs, _) = Map.findWithDefault (error badLibError) lname libs
return $ Map.findWithDefault (error $ badSigError n) n sigs
getUnknownSyms :: [RAW_SYM] -> Sign -> [RAW_SYM]
getUnknownSyms syms sig =
syms \\ Set.toList (Set.map symName $ getLocalSyms sig)
{- ---------------------------------------------------------------
--------------------------------------------------------------- -}
-- basic analysis for LF
basicAnalysis :: (BASIC_SPEC, Sign, GlobalAnnos) ->
Result (BASIC_SPEC, ExtSign Sign Symbol, [Named EXP])
basicAnalysis (bs@(Basic_spec items), initsig, _) = do
let (sig, sens) = unsafePerformIO $ makeSigSen initsig items
let syms = getSymbols sig
let fs = makeNamedForms sens $ map r_annos $ getSenItems items
return (bs, ExtSign sig syms, fs)
-- constructs the signatures and sentences
makeSigSen :: Sign -> [Annoted BASIC_ITEM] -> IO (Sign, [(NAME, Sentence)])
makeSigSen sig items = do
-- make a Twelf file
let sen_type = show $ pretty sen_type_exp
let cont1 = if null (getDefs sig) then "" else show (pretty sig) ++ "\n"
let cont2 = printSigItems $ getSigItems items
let cont3 = printSenItems sen_type $ getSenItems items
let s1 = mkSig gen_sig1 $ cont1 ++ cont2
let s2 = mkSig gen_sig2 $ mkIncl gen_sig1 ++ cont3
let contents = s1 ++ "\n" ++ s2
writeFile gen_file contents
-- run Twelf on the created file
libs <- twelf2SigMor HETS gen_file
-- construct the signature and sentences
sig1 <- getSigFromLibs gen_sig1 libs
sig2 <- getSigFromLibs gen_sig2 libs
let sens = getSens sig2
return (sig1, sens)
getSens :: Sign -> [(NAME, Sentence)]
getSens sig =
map (\ (Def s _ v) ->
case v of
Nothing -> error $ badValError $ symName s
Just v' -> (symName s, v')
) $ getLocalDefs sig
{- ---------------------------------------------------------------
--------------------------------------------------------------- -}
-- symbol analysis for LF
symbAnalysis :: [SYMB_ITEMS] -> Result [RAW_SYM]
symbAnalysis ss = Result [] $ Just $ concatMap (\ (Symb_items s) -> s) ss
-- symbol map analysis for LF
symbMapAnalysis :: [SYMB_MAP_ITEMS] -> Result (Map.Map RAW_SYM RAW_SYM)
symbMapAnalysis ss = Result [] $ Just $
foldl (\ m s -> Map.union m (makeSymbMap s)) Map.empty ss
makeSymbMap :: SYMB_MAP_ITEMS -> Map.Map RAW_SYM RAW_SYM
makeSymbMap (Symb_map_items ss) =
foldl (\ m s -> case s of
Symb s1 -> Map.insert s1 s1 m
Symb_map s1 s2 -> Map.insert s1 s2 m
) Map.empty ss
{- ---------------------------------------------------------------
--------------------------------------------------------------- -}
-- converts a mapping of raw symbols to a mapping of symbols
renamMapAnalysis :: Map.Map RAW_SYM RAW_SYM -> Sign -> Map.Map Symbol Symbol
renamMapAnalysis m sig =
let syms1 = getUnknownSyms (Map.keys m) sig
syms2 = filter (not . isSym) $ Map.elems m
syms = syms1 ++ syms2
in if not (null syms) then error $ badSymsError syms else
Map.fromList $ map (\ (k, v) -> (toSym k, toSym v)) $ Map.toList m
{- converts a mapping of raw symbols to a mapping of symbols to expressions
annotated with their type -}
translMapAnalysis :: Map.Map RAW_SYM RAW_SYM -> Sign -> Sign ->
Map.Map Symbol (EXP, EXP)
translMapAnalysis m sig1 sig2 =
let syms = getUnknownSyms (Map.keys m) sig1
in if not (null syms) then error $ badSymsError syms else
unsafePerformIO $ codAnalysis m sig2
codAnalysis :: Map.Map RAW_SYM RAW_SYM -> Sign -> IO (Map.Map Symbol (EXP, EXP))
codAnalysis m sig2 = do
-- make a Twelf file
let cont1 = show (pretty sig2) ++ "\n"
let cont2 = concatMap (\ (k, v) -> genPref k ++ " = " ++ v ++ ".\n") $
Map.toList m
let s1 = mkSig gen_sig1 cont1
let s2 = mkSig gen_sig2 $ mkIncl gen_sig1 ++ cont2
let contents = s1 ++ "\n" ++ s2
writeFile gen_file contents
-- run Twelf on the created file
libs <- twelf2SigMor HETS gen_file
-- construct the mapping
sig' <- getSigFromLibs gen_sig2 libs
return $ getMap sig'
getMap :: Sign -> Map.Map Symbol (EXP, EXP)
getMap sig = Map.fromList $ map
(\ (Def s t v) ->
case v of
Nothing -> error $ badValError $ symName s
Just v' -> let Just n = stripPrefix gen $ symName s
in (toSym n, (v', t))
) $ getLocalDefs sig
{- -------------------------------------------------------------------------
------------------------------------------------------------------------- -}
-- ERROR MESSAGES
badLibError :: String
badLibError = "Library " ++ gen_file ++ " not found."
badSigError :: MODULE -> String
badSigError n = "Signature " ++ n ++ " not found."
badSymsError :: [String] -> String
badSymsError ss = "Symbols " ++ show ss ++
" are unknown or are not locally accessible."
badValError :: String -> String
badValError s = "Symbol " ++ s ++ "does not have a value."
| keithodulaigh/Hets | LF/Analysis.hs | gpl-2.0 | 7,718 | 0 | 18 | 1,716 | 2,472 | 1,256 | 1,216 | 162 | 4 |
{-# LANGUAGE CPP #-}
-- Vectorise a modules type and class declarations.
--
-- This produces new type constructors and family instances top be included in the module toplevel
-- as well as bindings for worker functions, dfuns, and the like.
module Vectorise.Type.Env (
vectTypeEnv,
) where
#include "HsVersions.h"
import Vectorise.Env
import Vectorise.Vect
import Vectorise.Monad
import Vectorise.Builtins
import Vectorise.Type.TyConDecl
import Vectorise.Type.Classify
import Vectorise.Generic.PADict
import Vectorise.Generic.PAMethods
import Vectorise.Generic.PData
import Vectorise.Generic.Description
import Vectorise.Utils
import CoreSyn
import CoreUtils
import CoreUnfold
import DataCon
import TyCon
import CoAxiom
import Type
import FamInstEnv
import Id
import MkId
import NameEnv
import NameSet
import UniqFM
import OccName
import Unique
import Util
import Outputable
import DynFlags
import FastString
import MonadUtils
import Control.Monad
import Data.Maybe
import Data.List
-- Note [Pragmas to vectorise tycons]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- All imported type constructors that are not mapped to a vectorised type in the vectorisation map
-- (possibly because the defining module was not compiled with vectorisation) may be used in scalar
-- code encapsulated in vectorised code. If a such a type constructor 'T' is a member of the
-- 'Scalar' class (and hence also of 'PData' and 'PRepr'), it may also be used in vectorised code,
-- where 'T' represents itself, but the representation of 'T' still remains opaque in vectorised
-- code (i.e., it can only be used in scalar code).
--
-- An example is the treatment of 'Int'. 'Int's can be used in vectorised code and remain unchanged
-- by vectorisation. However, the representation of 'Int' by the 'I#' data constructor wrapping an
-- 'Int#' is not exposed in vectorised code. Instead, computations involving the representation need
-- to be confined to scalar code.
--
-- VECTORISE pragmas for type constructors cover four different flavours of vectorising data type
-- constructors:
--
-- (1) Data type constructor 'T' that together with its constructors 'Cn' may be used in vectorised
-- code, where 'T' and the 'Cn' are automatically vectorised in the same manner as data types
-- declared in a vectorised module. This includes the case where the vectoriser determines that
-- the original representation of 'T' may be used in vectorised code (as it does not embed any
-- parallel arrays.) This case is for type constructors that are *imported* from a non-
-- vectorised module, but that we want to use with full vectorisation support.
--
-- An example is the treatment of 'Ordering' and '[]'. The former remains unchanged by
-- vectorisation, whereas the latter is fully vectorised.
--
-- 'PData' and 'PRepr' instances are automatically generated by the vectoriser.
--
-- Type constructors declared with {-# VECTORISE type T #-} are treated in this manner.
--
-- (2) Data type constructor 'T' that may be used in vectorised code, where 'T' is represented by an
-- explicitly given 'Tv', but the representation of 'T' is opaque in vectorised code (i.e., the
-- constructors of 'T' may not occur in vectorised code).
--
-- An example is the treatment of '[::]'. The type '[::]' can be used in vectorised code and is
-- vectorised to 'PArray'. However, the representation of '[::]' is not exposed in vectorised
-- code. Instead, computations involving the representation need to be confined to scalar code.
--
-- 'PData' and 'PRepr' instances need to be explicitly supplied for 'T' (they are not generated
-- by the vectoriser).
--
-- Type constructors declared with {-# VECTORISE type T = Tv #-} are treated in this manner
-- manner. (The vectoriser never treats a type constructor automatically in this manner.)
--
-- (3) Data type constructor 'T' that does not contain any parallel arrays and has explicitly
-- provided 'PData' and 'PRepr' instances (and maybe also a 'Scalar' instance), which together
-- with the type's constructors 'Cn' may be used in vectorised code. The type 'T' and its
-- constructors 'Cn' are represented by themselves in vectorised code.
--
-- An example is 'Bool', which is represented by itself in vectorised code (as it cannot embed
-- any parallel arrays). However, we do not want any automatic generation of class and family
-- instances, which is why Case (1) does not apply.
--
-- 'PData' and 'PRepr' instances need to be explicitly supplied for 'T' (they are not generated
-- by the vectoriser).
--
-- Type constructors declared with {-# VECTORISE SCALAR type T #-} are treated in this manner.
--
-- (4) Data type constructor 'T' that does not contain any parallel arrays and that, in vectorised
-- code, is represented by an explicitly given 'Tv', but the representation of 'T' is opaque in
-- vectorised code and 'T' is regarded to be scalar — i.e., it may be used in encapsulated
-- scalar subcomputations.
--
-- An example is the treatment of '(->)'. Types '(->)' can be used in vectorised code and are
-- vectorised to '(:->)'. However, the representation of '(->)' is not exposed in vectorised
-- code. Instead, computations involving the representation need to be confined to scalar code
-- and may be part of encapsulated scalar computations.
--
-- 'PData' and 'PRepr' instances need to be explicitly supplied for 'T' (they are not generated
-- by the vectoriser).
--
-- Type constructors declared with {-# VECTORISE SCALAR type T = Tv #-} are treated in this
-- manner. (The vectoriser never treats a type constructor automatically in this manner.)
--
-- In addition, we have also got a single pragma form for type classes: {-# VECTORISE class C #-}.
-- It implies that the class type constructor may be used in vectorised code together with its data
-- constructor. We generally produce a vectorised version of the data type and data constructor.
-- We do not generate 'PData' and 'PRepr' instances for class type constructors. This pragma is the
-- default for all type classes declared in a vectorised module, but the pragma can also be used
-- explitly on imported classes.
-- Note [Vectorising classes]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- We vectorise classes essentially by just vectorising their desugared Core representation, but we
-- do generate a 'Class' structure along the way (see 'Vectorise.Type.TyConDecl.vectTyConDecl').
--
-- Here is an example illustrating the mapping — assume
--
-- class Num a where
-- (+) :: a -> a -> a
--
-- It desugars to
--
-- data Num a = D:Num { (+) :: a -> a -> a }
--
-- which we vectorise to
--
-- data V:Num a = D:V:Num { ($v+) :: PArray a :-> PArray a :-> PArray a }
--
-- while adding the following entries to the vectorisation map:
--
-- tycon : Num --> V:Num
-- datacon: D:Num --> D:V:Num
-- var : (+) --> ($v+)
-- |Vectorise type constructor including class type constructors.
--
vectTypeEnv :: [TyCon] -- Type constructors defined in this module
-> [CoreVect] -- All 'VECTORISE [SCALAR] type' declarations in this module
-> [CoreVect] -- All 'VECTORISE class' declarations in this module
-> VM ( [TyCon] -- old TyCons ++ new TyCons
, [FamInst] -- New type family instances.
, [(Var, CoreExpr)]) -- New top level bindings.
vectTypeEnv tycons vectTypeDecls vectClassDecls
= do { traceVt "** vectTypeEnv" $ ppr tycons
; let -- {-# VECTORISE type T -#} (ONLY the imported tycons)
impVectTyCons = ( [tycon | VectType False tycon Nothing <- vectTypeDecls]
++ [tycon | VectClass tycon <- vectClassDecls])
\\ tycons
-- {-# VECTORISE type T = Tv -#} (imported & local tycons with an /RHS/)
vectTyConsWithRHS = [ (tycon, rhs)
| VectType False tycon (Just rhs) <- vectTypeDecls]
-- {-# VECTORISE SCALAR type T = Tv -#} (imported & local tycons with an /RHS/)
scalarTyConsWithRHS = [ (tycon, rhs)
| VectType True tycon (Just rhs) <- vectTypeDecls]
-- {-# VECTORISE SCALAR type T -#} (imported & local /scalar/ tycons without an RHS)
scalarTyConsNoRHS = [tycon | VectType True tycon Nothing <- vectTypeDecls]
-- Check that is not a VECTORISE SCALAR tycon nor VECTORISE tycons with explicit rhs?
vectSpecialTyConNames = mkNameSet . map tyConName $
scalarTyConsNoRHS ++
map fst (vectTyConsWithRHS ++ scalarTyConsWithRHS)
notVectSpecialTyCon tc = not $ (tyConName tc) `elemNameSet` vectSpecialTyConNames
-- Build a map containing all vectorised type constructor. If the vectorised type
-- constructor differs from the original one, then it is mapped to 'True'; if they are
-- both the same, then it maps to 'False'.
; vectTyCons <- globalVectTyCons
; let vectTyConBase = mapUFM_Directly isDistinct vectTyCons -- 'True' iff tc /= V[[tc]]
isDistinct u tc = u /= getUnique tc
vectTyConFlavour = vectTyConBase
`plusNameEnv`
mkNameEnv [ (tyConName tycon, True)
| (tycon, _) <- vectTyConsWithRHS ++ scalarTyConsWithRHS]
`plusNameEnv`
mkNameEnv [ (tyConName tycon, False) -- original representation
| tycon <- scalarTyConsNoRHS]
-- Split the list of 'TyCons' into the ones (1) that we must vectorise and those (2)
-- that we could, but don't need to vectorise. Type constructors that are not data
-- type constructors or use non-Haskell98 features are being dropped. They may not
-- appear in vectorised code. (We also drop the local type constructors appearing in a
-- VECTORISE SCALAR pragma or a VECTORISE pragma with an explicit right-hand side, as
-- these are being handled separately. NB: Some type constructors may be marked SCALAR
-- /and/ have an explicit right-hand side.)
--
-- Furthermore, 'par_tcs' are those type constructors (converted or not) whose
-- definition, directly or indirectly, depends on parallel arrays. Finally, 'drop_tcs'
-- are all type constructors that cannot be vectorised.
; parallelTyCons <- (`extendNameSetList` map (tyConName . fst) vectTyConsWithRHS) <$>
globalParallelTyCons
; let maybeVectoriseTyCons = filter notVectSpecialTyCon tycons ++ impVectTyCons
(conv_tcs, keep_tcs, par_tcs, drop_tcs)
= classifyTyCons vectTyConFlavour parallelTyCons maybeVectoriseTyCons
; traceVt " known parallel : " $ ppr parallelTyCons
; traceVt " VECT SCALAR : " $ ppr (scalarTyConsNoRHS ++ map fst scalarTyConsWithRHS)
; traceVt " VECT [class] : " $ ppr impVectTyCons
; traceVt " VECT with rhs : " $ ppr (map fst (vectTyConsWithRHS ++ scalarTyConsWithRHS))
; traceVt " -- after classification (local and VECT [class] tycons) --" Outputable.empty
; traceVt " reuse : " $ ppr keep_tcs
; traceVt " convert : " $ ppr conv_tcs
-- warn the user about unvectorised type constructors
; let explanation = text "(They use unsupported language extensions"
$$ text "or depend on type constructors that are" <+>
text "not vectorised)"
drop_tcs_nosyn = filter (not . isTypeFamilyTyCon) .
filter (not . isTypeSynonymTyCon) $ drop_tcs
; unless (null drop_tcs_nosyn) $
emitVt "Warning: cannot vectorise these type constructors:" $
pprQuotedList drop_tcs_nosyn $$ explanation
; mapM_ addParallelTyConAndCons $ par_tcs ++ map fst vectTyConsWithRHS
; let mapping =
-- Type constructors that we found we don't need to vectorise and those
-- declared VECTORISE SCALAR /without/ an explicit right-hand side, use the same
-- representation in both unvectorised and vectorised code; they are not
-- abstract.
[(tycon, tycon, False) | tycon <- keep_tcs ++ scalarTyConsNoRHS]
-- We do the same for type constructors declared VECTORISE SCALAR /without/
-- an explicit right-hand side
++ [(tycon, vTycon, True) | (tycon, vTycon) <- vectTyConsWithRHS ++ scalarTyConsWithRHS]
; syn_tcs <- catMaybes <$> mapM defTyConDataCons mapping
-- Vectorise all the data type declarations that we can and must vectorise (enter the
-- type and data constructors into the vectorisation map on-the-fly.)
; new_tcs <- vectTyConDecls conv_tcs
; let dumpTc tc vTc = traceVt "---" (ppr tc <+> text "::" <+> ppr (dataConSig tc) $$
ppr vTc <+> text "::" <+> ppr (dataConSig vTc))
dataConSig tc | Just dc <- tyConSingleDataCon_maybe tc = dataConRepType dc
| otherwise = panic "dataConSig"
; zipWithM_ dumpTc (filter isClassTyCon conv_tcs) (filter isClassTyCon new_tcs)
-- We don't need new representation types for dictionary constructors. The constructors
-- are always fully applied, and we don't need to lift them to arrays as a dictionary
-- of a particular type always has the same value.
; let orig_tcs = filter (not . isClassTyCon) $ keep_tcs ++ conv_tcs
vect_tcs = filter (not . isClassTyCon) $ keep_tcs ++ new_tcs
-- Build 'PRepr' and 'PData' instance type constructors and family instances for all
-- type constructors with vectorised representations.
; reprs <- mapM tyConRepr vect_tcs
; repr_fis <- zipWith3M buildPReprTyCon orig_tcs vect_tcs reprs
; pdata_fis <- zipWith3M buildPDataTyCon orig_tcs vect_tcs reprs
; pdatas_fis <- zipWith3M buildPDatasTyCon orig_tcs vect_tcs reprs
; let fam_insts = repr_fis ++ pdata_fis ++ pdatas_fis
repr_axs = map famInstAxiom repr_fis
pdata_tcs = famInstsRepTyCons pdata_fis
pdatas_tcs = famInstsRepTyCons pdatas_fis
; updGEnv $ extendFamEnv fam_insts
-- Generate workers for the vectorised data constructors, dfuns for the 'PA' instances of
-- the vectorised type constructors, and associate the type constructors with their dfuns
-- in the global environment. We get back the dfun bindings (which we will subsequently
-- inject into the modules toplevel).
; (_, binds) <- fixV $ \ ~(dfuns, _) ->
do { defTyConPAs (zipLazy vect_tcs dfuns)
-- Query the 'PData' instance type constructors for type constructors that have a
-- VECTORISE SCALAR type pragma without an explicit right-hand side (this is Item
-- (3) of "Note [Pragmas to vectorise tycons]" above).
; pdata_scalar_tcs <- mapM pdataReprTyConExact scalarTyConsNoRHS
-- Build workers for all vectorised data constructors (except abstract ones)
; sequence_ $
zipWith3 vectDataConWorkers (orig_tcs ++ scalarTyConsNoRHS)
(vect_tcs ++ scalarTyConsNoRHS)
(pdata_tcs ++ pdata_scalar_tcs)
-- Build a 'PA' dictionary for all type constructors (except abstract ones & those
-- defined with an explicit right-hand side where the dictionary is user-supplied)
; dfuns <- sequence $
zipWith4 buildTyConPADict
vect_tcs
repr_axs
pdata_tcs
pdatas_tcs
; binds <- takeHoisted
; return (dfuns, binds)
}
-- Return the vectorised variants of type constructors as well as the generated instance
-- type constructors, family instances, and dfun bindings.
; return ( new_tcs ++ pdata_tcs ++ pdatas_tcs ++ syn_tcs
, fam_insts, binds)
}
where
addParallelTyConAndCons tycon
= do
{ addGlobalParallelTyCon tycon
; mapM_ addGlobalParallelVar [ id | dc <- tyConDataCons tycon
, AnId id <- dataConImplicitTyThings dc ]
-- Ignoring the promoted tycon; hope that's ok
}
-- Add a mapping from the original to vectorised type constructor to the vectorisation map.
-- Unless the type constructor is abstract, also mappings from the orignal's data constructors
-- to the vectorised type's data constructors.
--
-- We have three cases: (1) original and vectorised type constructor are the same, (2) the
-- name of the vectorised type constructor is canonical (as prescribed by 'mkVectTyConOcc'), or
-- (3) the name is not canonical. In the third case, we additionally introduce a type synonym
-- with the canonical name that is set equal to the non-canonical name (so that we find the
-- right type constructor when reading vectorisation information from interface files).
--
defTyConDataCons (origTyCon, vectTyCon, isAbstract)
= do
{ canonName <- mkLocalisedName mkVectTyConOcc origName
; if origName == vectName -- Case (1)
|| vectName == canonName -- Case (2)
then do
{ defTyCon origTyCon vectTyCon -- T --> vT
; defDataCons -- Ci --> vCi
; return Nothing
}
else do -- Case (3)
{ let synTyCon = mkSyn canonName (mkTyConTy vectTyCon) -- type S = vT
; defTyCon origTyCon synTyCon -- T --> S
; defDataCons -- Ci --> vCi
; return $ Just synTyCon
}
}
where
origName = tyConName origTyCon
vectName = tyConName vectTyCon
mkSyn canonName ty = mkSynonymTyCon canonName [] (typeKind ty) [] ty
defDataCons
| isAbstract = return ()
| otherwise
= do { MASSERT(length (tyConDataCons origTyCon) == length (tyConDataCons vectTyCon))
; zipWithM_ defDataCon (tyConDataCons origTyCon) (tyConDataCons vectTyCon)
}
-- Helpers --------------------------------------------------------------------
buildTyConPADict :: TyCon -> CoAxiom Unbranched -> TyCon -> TyCon -> VM Var
buildTyConPADict vect_tc prepr_ax pdata_tc pdatas_tc
= tyConRepr vect_tc >>= buildPADict vect_tc prepr_ax pdata_tc pdatas_tc
-- Produce a custom-made worker for the data constructors of a vectorised data type. This includes
-- all data constructors that may be used in vectorised code — i.e., all data constructors of data
-- types with 'VECTORISE [SCALAR] type' pragmas with an explicit right-hand side. Also adds a mapping
-- from the original to vectorised worker into the vectorisation map.
--
-- FIXME: It's not nice that we need create a special worker after the data constructors has
-- already been constructed. Also, I don't think the worker is properly added to the data
-- constructor. Seems messy.
vectDataConWorkers :: TyCon -> TyCon -> TyCon -> VM ()
vectDataConWorkers orig_tc vect_tc arr_tc
= do { traceVt "Building vectorised worker for datatype" (ppr orig_tc)
; bs <- sequence
. zipWith3 def_worker (tyConDataCons orig_tc) rep_tys
$ zipWith4 mk_data_con (tyConDataCons vect_tc)
rep_tys
(inits rep_tys)
(tail $ tails rep_tys)
; mapM_ (uncurry hoistBinding) bs
}
where
tyvars = tyConTyVars vect_tc
var_tys = mkTyVarTys tyvars
ty_args = map Type var_tys
res_ty = mkTyConApp vect_tc var_tys
cons = tyConDataCons vect_tc
arity = length cons
[arr_dc] = tyConDataCons arr_tc
rep_tys = map dataConRepArgTys $ tyConDataCons vect_tc
mk_data_con con tys pre post
= do dflags <- getDynFlags
liftM2 (,) (vect_data_con con)
(lift_data_con tys pre post (mkDataConTag dflags con))
sel_replicate len tag
| arity > 1 = do
rep <- builtin (selReplicate arity)
return [rep `mkApps` [len, tag]]
| otherwise = return []
vect_data_con con = return $ mkConApp con ty_args
lift_data_con tys pre_tys post_tys tag
= do
len <- builtin liftingContext
args <- mapM (newLocalVar (fsLit "xs"))
=<< mapM mkPDataType tys
sel <- sel_replicate (Var len) tag
pre <- mapM emptyPD (concat pre_tys)
post <- mapM emptyPD (concat post_tys)
return . mkLams (len : args)
. wrapFamInstBody arr_tc var_tys
. mkConApp arr_dc
$ ty_args ++ sel ++ pre ++ map Var args ++ post
def_worker data_con arg_tys mk_body
= do
arity <- polyArity tyvars
body <- closedV
. inBind orig_worker
. polyAbstract tyvars $ \args ->
liftM (mkLams (tyvars ++ args) . vectorised)
$ buildClosures tyvars [] [] arg_tys res_ty mk_body
raw_worker <- mkVectId orig_worker (exprType body)
let vect_worker = raw_worker `setIdUnfolding`
mkInlineUnfolding (Just arity) body
defGlobalVar orig_worker vect_worker
return (vect_worker, body)
where
orig_worker = dataConWorkId data_con
| snoyberg/ghc | compiler/vectorise/Vectorise/Type/Env.hs | bsd-3-clause | 22,685 | 0 | 19 | 6,860 | 2,674 | 1,440 | 1,234 | 211 | 2 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | Docker types.
module Stack.Types.Docker where
import Control.Applicative
import Control.Monad
import Control.Monad.Catch (MonadThrow)
import Data.Aeson.Extended
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Distribution.Text (simpleParse)
import Distribution.Version (anyVersion)
import GHC.Generics (Generic)
import Generics.Deriving.Monoid (mappenddefault, memptydefault)
import Path
import Stack.Types.Version
-- | Docker configuration.
data DockerOpts = DockerOpts
{dockerEnable :: !Bool
-- ^ Is using Docker enabled?
,dockerImage :: !String
-- ^ Exact Docker image tag or ID. Overrides docker-repo-*/tag.
,dockerRegistryLogin :: !Bool
-- ^ Does registry require login for pulls?
,dockerRegistryUsername :: !(Maybe String)
-- ^ Optional username for Docker registry.
,dockerRegistryPassword :: !(Maybe String)
-- ^ Optional password for Docker registry.
,dockerAutoPull :: !Bool
-- ^ Automatically pull new images.
,dockerDetach :: !Bool
-- ^ Whether to run a detached container
,dockerPersist :: !Bool
-- ^ Create a persistent container (don't remove it when finished). Implied by
-- `dockerDetach`.
,dockerContainerName :: !(Maybe String)
-- ^ Container name to use, only makes sense from command-line with `dockerPersist`
-- or `dockerDetach`.
,dockerRunArgs :: ![String]
-- ^ Arguments to pass directly to @docker run@.
,dockerMount :: ![Mount]
-- ^ Volumes to mount in the container.
,dockerEnv :: ![String]
-- ^ Environment variables to set in the container.
,dockerDatabasePath :: !(Path Abs File)
-- ^ Location of image usage database.
,dockerStackExe :: !(Maybe DockerStackExe)
-- ^ Location of container-compatible stack executable
,dockerSetUser :: !(Maybe Bool)
-- ^ Set in-container user to match host's
,dockerRequireDockerVersion :: !VersionRange
-- ^ Require a version of Docker within this range.
}
deriving (Show)
-- | An uninterpreted representation of docker options.
-- Configurations may be "cascaded" using mappend (left-biased).
data DockerOptsMonoid = DockerOptsMonoid
{dockerMonoidDefaultEnable :: !Any
-- ^ Should Docker be defaulted to enabled (does @docker:@ section exist in the config)?
,dockerMonoidEnable :: !(First Bool)
-- ^ Is using Docker enabled?
,dockerMonoidRepoOrImage :: !(First DockerMonoidRepoOrImage)
-- ^ Docker repository name (e.g. @fpco/stack-build@ or @fpco/stack-full:lts-2.8@)
,dockerMonoidRegistryLogin :: !(First Bool)
-- ^ Does registry require login for pulls?
,dockerMonoidRegistryUsername :: !(First String)
-- ^ Optional username for Docker registry.
,dockerMonoidRegistryPassword :: !(First String)
-- ^ Optional password for Docker registry.
,dockerMonoidAutoPull :: !(First Bool)
-- ^ Automatically pull new images.
,dockerMonoidDetach :: !(First Bool)
-- ^ Whether to run a detached container
,dockerMonoidPersist :: !(First Bool)
-- ^ Create a persistent container (don't remove it when finished). Implied by
-- `dockerDetach`.
,dockerMonoidContainerName :: !(First String)
-- ^ Container name to use, only makes sense from command-line with `dockerPersist`
-- or `dockerDetach`.
,dockerMonoidRunArgs :: ![String]
-- ^ Arguments to pass directly to @docker run@
,dockerMonoidMount :: ![Mount]
-- ^ Volumes to mount in the container
,dockerMonoidEnv :: ![String]
-- ^ Environment variables to set in the container
,dockerMonoidDatabasePath :: !(First String)
-- ^ Location of image usage database.
,dockerMonoidStackExe :: !(First String)
-- ^ Location of container-compatible stack executable
,dockerMonoidSetUser :: !(First Bool)
-- ^ Set in-container user to match host's
,dockerMonoidRequireDockerVersion :: !IntersectingVersionRange
-- ^ See: 'dockerRequireDockerVersion'
}
deriving (Show, Generic)
-- | Decode uninterpreted docker options from JSON/YAML.
instance FromJSON (WithJSONWarnings DockerOptsMonoid) where
parseJSON = withObjectWarnings "DockerOptsMonoid"
(\o -> do dockerMonoidDefaultEnable <- pure (Any True)
dockerMonoidEnable <- First <$> o ..:? dockerEnableArgName
dockerMonoidRepoOrImage <- First <$>
(((Just . DockerMonoidImage) <$> o ..: dockerImageArgName) <|>
((Just . DockerMonoidRepo) <$> o ..: dockerRepoArgName) <|>
pure Nothing)
dockerMonoidRegistryLogin <- First <$> o ..:? dockerRegistryLoginArgName
dockerMonoidRegistryUsername <- First <$> o ..:? dockerRegistryUsernameArgName
dockerMonoidRegistryPassword <- First <$> o ..:? dockerRegistryPasswordArgName
dockerMonoidAutoPull <- First <$> o ..:? dockerAutoPullArgName
dockerMonoidDetach <- First <$> o ..:? dockerDetachArgName
dockerMonoidPersist <- First <$> o ..:? dockerPersistArgName
dockerMonoidContainerName <- First <$> o ..:? dockerContainerNameArgName
dockerMonoidRunArgs <- o ..:? dockerRunArgsArgName ..!= []
dockerMonoidMount <- o ..:? dockerMountArgName ..!= []
dockerMonoidEnv <- o ..:? dockerEnvArgName ..!= []
dockerMonoidDatabasePath <- First <$> o ..:? dockerDatabasePathArgName
dockerMonoidStackExe <- First <$> o ..:? dockerStackExeArgName
dockerMonoidSetUser <- First <$> o ..:? dockerSetUserArgName
dockerMonoidRequireDockerVersion
<- IntersectingVersionRange <$> unVersionRangeJSON <$>
o ..:? dockerRequireDockerVersionArgName
..!= VersionRangeJSON anyVersion
return DockerOptsMonoid{..})
-- | Left-biased combine Docker options
instance Monoid DockerOptsMonoid where
mempty = memptydefault
mappend = mappenddefault
-- | Where to get the `stack` executable to run in Docker containers
data DockerStackExe
= DockerStackExeDownload -- ^ Download from official bindist
| DockerStackExeHost -- ^ Host's `stack` (linux-x86_64 only)
| DockerStackExeImage -- ^ Docker image's `stack` (versions must match)
| DockerStackExePath (Path Abs File) -- ^ Executable at given path
deriving (Show)
-- | Parse 'DockerStackExe'.
parseDockerStackExe :: (MonadThrow m) => String -> m DockerStackExe
parseDockerStackExe t
| t == dockerStackExeDownloadVal = return DockerStackExeDownload
| t == dockerStackExeHostVal = return DockerStackExeHost
| t == dockerStackExeImageVal = return DockerStackExeImage
| otherwise = liftM DockerStackExePath (parseAbsFile t)
-- | Docker volume mount.
data Mount = Mount String String
-- | For optparse-applicative.
instance Read Mount where
readsPrec _ s =
case break (== ':') s of
(a,':':b) -> [(Mount a b,"")]
(a,[]) -> [(Mount a a,"")]
_ -> fail "Invalid value for Docker mount (expect '/host/path:/container/path')"
-- | Show instance.
instance Show Mount where
show (Mount a b) = if a == b
then a
else concat [a,":",b]
-- | For YAML.
instance FromJSON Mount where
parseJSON v = fmap read (parseJSON v)
-- | Options for Docker repository or image.
data DockerMonoidRepoOrImage
= DockerMonoidRepo String
| DockerMonoidImage String
deriving (Show)
-- | Newtype for non-orphan FromJSON instance.
newtype VersionRangeJSON = VersionRangeJSON { unVersionRangeJSON :: VersionRange }
-- | Parse VersionRange.
instance FromJSON VersionRangeJSON where
parseJSON = withText "VersionRange"
(\s -> maybe (fail ("Invalid cabal-style VersionRange: " ++ T.unpack s))
(return . VersionRangeJSON)
(Distribution.Text.simpleParse (T.unpack s)))
-- | Docker enable argument name.
dockerEnableArgName :: Text
dockerEnableArgName = "enable"
-- | Docker repo arg argument name.
dockerRepoArgName :: Text
dockerRepoArgName = "repo"
-- | Docker image argument name.
dockerImageArgName :: Text
dockerImageArgName = "image"
-- | Docker registry login argument name.
dockerRegistryLoginArgName :: Text
dockerRegistryLoginArgName = "registry-login"
-- | Docker registry username argument name.
dockerRegistryUsernameArgName :: Text
dockerRegistryUsernameArgName = "registry-username"
-- | Docker registry password argument name.
dockerRegistryPasswordArgName :: Text
dockerRegistryPasswordArgName = "registry-password"
-- | Docker auto-pull argument name.
dockerAutoPullArgName :: Text
dockerAutoPullArgName = "auto-pull"
-- | Docker detach argument name.
dockerDetachArgName :: Text
dockerDetachArgName = "detach"
-- | Docker run args argument name.
dockerRunArgsArgName :: Text
dockerRunArgsArgName = "run-args"
-- | Docker mount argument name.
dockerMountArgName :: Text
dockerMountArgName = "mount"
-- | Docker environment variable argument name.
dockerEnvArgName :: Text
dockerEnvArgName = "env"
-- | Docker container name argument name.
dockerContainerNameArgName :: Text
dockerContainerNameArgName = "container-name"
-- | Docker persist argument name.
dockerPersistArgName :: Text
dockerPersistArgName = "persist"
-- | Docker database path argument name.
dockerDatabasePathArgName :: Text
dockerDatabasePathArgName = "database-path"
-- | Docker database path argument name.
dockerStackExeArgName :: Text
dockerStackExeArgName = "stack-exe"
-- | Value for @--docker-stack-exe=download@
dockerStackExeDownloadVal :: String
dockerStackExeDownloadVal = "download"
-- | Value for @--docker-stack-exe=host@
dockerStackExeHostVal :: String
dockerStackExeHostVal = "host"
-- | Value for @--docker-stack-exe=image@
dockerStackExeImageVal :: String
dockerStackExeImageVal = "image"
-- | Docker @set-user@ argument name
dockerSetUserArgName :: Text
dockerSetUserArgName = "set-user"
-- | Docker @require-version@ argument name
dockerRequireDockerVersionArgName :: Text
dockerRequireDockerVersionArgName = "require-docker-version"
-- | Argument name used to pass docker entrypoint data (only used internally)
dockerEntrypointArgName :: String
dockerEntrypointArgName = "internal-docker-entrypoint"
| phadej/stack | src/Stack/Types/Docker.hs | bsd-3-clause | 10,618 | 0 | 20 | 2,276 | 1,596 | 900 | 696 | 227 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Name.Name(
Module(),
Name,
Class,
NameType(..),
ToName(..),
fromName,
ffiExportName,
getIdent,
getModule,
isConstructor,
isTypeNamespace,
isValNamespace,
isOpLike,
mapName,
mapName',
nameParts,
nameType,
parseName,
qualifyName,
setModule,
quoteName,
fromQuotedName,
toModule,
FieldName,
ClassName,
combineName,
toUnqualified,
removeUniquifier,
-- new interface
unMkName,
mkName,
mkComplexName,
emptyNameParts,
mkNameType,
NameParts(..),
nameTyLevel_u,
nameTyLevel_s,
typeLevel,
kindLevel,
termLevel,
originalUnqualifiedName,
deconstructName
) where
import C.FFI
import Data.Char
import Doc.DocLike
import Doc.PPrint
import GenUtil
import Name.Internals
import Name.Prim
import StringTable.Atom
import Ty.Level
import Util.Std
isTypeNamespace TypeConstructor = True
isTypeNamespace ClassName = True
isTypeNamespace TypeVal = True
isTypeNamespace _ = False
isValNamespace DataConstructor = True
isValNamespace Val = True
isValNamespace _ = False
-----------------
-- name definiton
-----------------
-- should only be used for printing, the parser should know when things are in
-- operator position or not.
isOpLike n = x `elem` "!#$%&*+./<=>?@\\^-~:|" where
(_,_,(x:_)) = nameParts n
createName :: NameType -> Module -> String -> Name
createName _ (Module "") i = error $ "createName: empty module " ++ i
createName _ m "" = error $ "createName: empty ident " ++ show m
createName t m i = forgeName t (Just m) i
createUName :: NameType -> String -> Name
createUName _ "" = error $ "createUName: empty ident"
createUName t i = forgeName t Nothing i
class ToName a where
toName :: NameType -> a -> Name
fromName' :: Name -> a
fromName :: ToName a => Name -> (NameType, a)
fromName n = (nameType n,fromName' n)
instance ToName (String,String) where
toName nt (m,i) = createName nt (Module $ toAtom m) i
fromName' n = case fromName' n of
(Just (Module m),i) -> (show m,i)
(Nothing,i) -> ("",i)
instance ToName (Module,String) where
toName nt (m,i) = createName nt m i
fromName' n = case fromName' n of
(Just m,i) -> (m,i)
(Nothing,i) -> (Module "",i)
instance ToName (Maybe Module,String) where
toName nt (Just m,i) = createName nt m i
toName nt (Nothing,i) = createUName nt i
fromName' n = case nameParts n of
(_,a,b) -> (a,b)
instance ToName Name where
toName nt i = case nameToBits i of
(a,_) -> bitsToName a nt
fromName' n = n
instance ToName String where
toName nt i = createUName nt i
fromName' n = case fromName' n of
(Just (Module m),i) -> show m ++ "." ++ i
(Nothing,i) -> i
getModule :: Monad m => Name -> m Module
getModule n = case nameParts n of
(_,Just m,_) -> return m
_ -> fail "Name is unqualified."
getIdent :: Name -> String
getIdent n = case nameParts n of
(_,_,s) -> s
toUnqualified :: Name -> Name
toUnqualified n = case nameParts n of
(_,Nothing,_) -> n
(t,Just _,i) -> toName t (Nothing :: Maybe Module,i)
qualifyName :: Module -> Name -> Name
qualifyName m n = case nameParts n of
(t,Nothing,n) -> toName t (Just m, n)
_ -> n
setModule :: Module -> Name -> Name
setModule m n = toName nt (m,i) where
(nt,_,i) = nameParts n
parseName :: NameType -> String -> Name
parseName t name = toName t (intercalate "." ms, intercalate "." (ns ++ [last sn])) where
sn = (split (== '.') name)
(ms,ns) = span validMod (init sn)
validMod (c:cs) = isUpper c && all (\c -> isAlphaNum c || c `elem` "_'") cs
validMod _ = False
nameType :: Name -> NameType
nameType name = snd $ nameToBits name
instance Show Name where
showsPrec _ n = f n where
f (fromQuotedName -> Just n) = showChar '`' . f n
f (nameType -> UnknownType) = showChar '¿' . (g $ nameParts n)
f n = g $ nameParts n
g (_,Just a,b) = shows a . showChar '.' . showString b
g (_,Nothing,b) = showString b
instance DocLike d => PPrint d Name where
pprint n = text (show n)
mapName :: (Module -> Module,String -> String) -> Name -> Name
mapName (f,g) n = case nameParts n of
(nt,Nothing,i) -> toName nt (g i)
(nt,Just m,i) -> toName nt (Just (f m :: Module),g i)
mapName' :: (Maybe Module -> Maybe Module) -> (String -> String) -> Name -> Name
mapName' f g n = case nameParts n of
(nt,m,i) -> toName nt (f m,g i)
ffiExportName :: FfiExport -> Name
ffiExportName (FfiExport cn _ cc _ _) = toName Val (Module "FE@", show cc ++ "." ++ cn)
type Class = Name
----------
-- Modules
----------
toModule :: String -> Module
toModule s = Module $ toAtom s
--------------
--prefered api
--------------
mkName :: TyLevel -> Bool -> Maybe Module -> String -> Name
mkName l b mm s = toName (mkNameType l b) (mm,s)
-- the left name effectively becomes the module.
combineName :: Name -> Name -> Name
combineName (nameToBits -> (a1,nt1)) (nameToBits -> (a2,nt2)) = bitsToName ((toAtom $ "{" ++ encodeNameType nt1:show a1 ++ "}") `mappend` a2) nt2
data NameParts = NameParts {
nameLevel :: TyLevel,
nameQuoted :: Bool,
nameConstructor :: Bool,
nameModule :: Maybe Module,
nameOuter :: [Name],
nameUniquifier :: Maybe Int,
nameIdent :: String
} deriving(Show)
emptyNameParts = NameParts {
nameLevel = termLevel,
nameQuoted = False,
nameConstructor = False,
nameModule = Nothing,
nameOuter = [],
nameUniquifier = Nothing,
nameIdent = "(empty)"
}
mkComplexName :: NameParts -> Name
mkComplexName NameParts { .. } = qn $ on nameOuter $ toName (mkNameType nameLevel nameConstructor) (nameModule,ident) where
ident = maybe id (\c s -> show c ++ "_" ++ s) nameUniquifier nameIdent
qn = if nameQuoted then quoteName else id
on xs n = case xs of
(x:xs) -> combineName x (on xs n)
[] -> n
unMkName :: Name -> NameParts
unMkName nm@(nameToBits -> (a1,nt1)) = NameParts { .. } where
(nameOuter,name) = h (show a1) where
h xs@('{':_) = g xs []
h _ = ([],nm)
g ('{':nt:rs) zs = f (0::Int) rs (decodeNameType nt) [] where
f 0 ('}':xs) nt rs = g xs (bitsToName (toAtom $ reverse rs) nt:zs)
f n ('{':xs) nt rs = f (n + 1) xs nt ('{':rs)
f n ('}':xs) nt rs = f (n - 1) xs nt ('}':rs)
f n (x:xs) nt rs = f n xs nt (x:rs)
f n _ _ rs = error $ "unMkName: invalid outer " ++ show a1
g rs zs = (reverse zs,bitsToName (toAtom rs) nt1)
(nameQuoted,nameModule,_,uqn,nameUniquifier) = deconstructName name
(_,_,nameIdent) = nameParts uqn
nameConstructor = isConstructor nm
nameLevel = tyLevelOf nm
-- internal
mkNameType :: TyLevel -> Bool -> NameType
mkNameType l b = (f l b) where
f l b | l == termLevel = if b then DataConstructor else Val
| l == typeLevel = if b then TypeConstructor else TypeVal
| l == kindLevel && b = SortName
f l b = error ("mkName: invalid " ++ show (l,b))
unRenameString :: String -> (Maybe Int,String)
unRenameString s = case span isDigit s of
(ns@(_:_),'_':rs) -> (Just (read ns),rs)
(_,_) -> (Nothing,s)
-- deconstruct name into all its possible parts
-- does not work on quoted names.
deconstructName :: Name -> (Bool,Maybe Module,Maybe UnqualifiedName,UnqualifiedName,Maybe Int)
deconstructName name | Just name <- fromQuotedName name = case deconstructName name of
(_,a,b,c,d) -> (True,a,b,c,d)
deconstructName name = f nt where
(nt,mod,id) = nameParts name
(mi,id') = unRenameString id
f _ = (False,mod,Nothing,toName nt id',mi)
originalUnqualifiedName :: Name -> Name
originalUnqualifiedName n = case unMkName n of
NameParts { .. } -> toName (nameType n) nameIdent
----------------
-- Parameterized
----------------
instance HasTyLevel Name where
getTyLevel n = f (nameType n) where
f DataConstructor = Just termLevel
f Val = Just termLevel
f RawType = Just typeLevel
f TypeConstructor = Just typeLevel
f TypeVal = Just typeLevel
f SortName
| n == s_HashHash = Just $ succ kindLevel
| n == s_StarStar = Just $ succ kindLevel
| otherwise = Just kindLevel
f QuotedName = getTyLevel $ fromJust (fromQuotedName n)
f _ = Nothing
isConstructor :: Name -> Bool
isConstructor n = f (nameType n) where
f TypeConstructor = True
f DataConstructor = True
f SortName = True
f QuotedName = isConstructor $ fromJust (fromQuotedName n)
f _ = False
nameTyLevel_s tl n = nameTyLevel_u (const tl) n
nameTyLevel_u f (fromQuotedName -> Just qn) = quoteName $ nameTyLevel_u f qn
nameTyLevel_u f n = case getTyLevel n of
Nothing -> n
Just cl | cl == cl' -> n
| otherwise -> toName (mkNameType cl' (isConstructor n)) n
where cl' = f cl
removeUniquifier name = mkComplexName (unMkName name) { nameUniquifier = Nothing }
| hvr/jhc | src/Name/Name.hs | mit | 9,173 | 0 | 17 | 2,373 | 3,610 | 1,908 | 1,702 | -1 | -1 |
import System.Environment
import System.IO
import Text.ParserCombinators.Parsec
import Control.Monad
import Control.Applicative hiding ((<|>), many)
import Data.List
import qualified Data.Text as DT (replace)
import qualified Text.Regex as RE (mkRegex,subRegex)
{--
formhame(Open usp Tukubai)
designed by Nobuaki Tounaka
written by Ryuichi Ueda
The MIT License
Copyright (C) 2013-2014 Universal Shell Programming Laboratory
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--}
showUsage :: IO ()
showUsage = do System.IO.hPutStr stderr ("Usage : formhame <html_template> <data>\n" ++
"Sat Sep 20 16:45:33 JST 2014\n" ++
"Open usp Tukubai (LINUX+FREEBSD), Haskell ver.\n")
data Opts = NormalOpts TemplateFile DataFile | Error String deriving Show
type KeyValue = (String,String)
type TemplateFile = String
type DataFile = String
main :: IO ()
main = do args <- getArgs
case args of
["-h"] -> showUsage
["--help"] -> showUsage
[('-':'i':istr),('-':'d':dstr),f1,f2] -> main' istr dstr f1 f2
[('-':'i':istr),('-':'d':dstr),f1] -> main' istr dstr f1 "-"
[('-':'d':dstr),('-':'i':istr),f1,f2] -> main' istr dstr f1 f2
[('-':'d':dstr),('-':'i':istr),f1] -> main' istr dstr f1 "-"
[('-':'i':istr),f1,f2] -> main' istr "" f1 f2
[('-':'i':istr),f1] -> main' istr "" f1 "-"
[('-':'d':dstr),f1,f2] -> main' "" dstr f1 f2
[('-':'d':dstr),f1] -> main' "" dstr f1 "-"
[f1,f2] -> main' "" "" f1 f2
[f1] -> main' "" "" f1 "-"
main' :: String-> String -> String -> String -> IO ()
main' istr dstr tempfile datafile = do tempcs <- readF tempfile
datacs <- readF datafile
formhame ( readData istr dstr (lines datacs) ) (lines tempcs)
readF :: String -> IO String
readF "-" = getContents
readF f = readFile f
readData :: String -> String -> [String] -> [KeyValue]
readData istr dstr lns = map ( (fd dstr) . (fi istr) . f . words) lns
where f (a:b:c) = (a,b)
f (a:[]) = (a,"")
fi istr (a,b) = if istr == b then (a,"") else (a,b)
fd dstr (a,b) = (a,sub dstr b)
sub :: String -> String -> String
sub "" str = str
sub dstr str
| length dstr > length str = str
| ('\\':dstr) `isPrefixOf` str = dstr ++ (sub dstr $ drop (1 + length dstr) str )
| dstr `isPrefixOf` str = " " ++ (sub dstr $ drop (length dstr) str )
| otherwise = (take 1 str ) ++ sub dstr (drop 1 str)
formhame :: [KeyValue] -> [String] -> IO ()
formhame _ [] = return ()
formhame kvs (ln:lns)
| pickedkvs == [] = putStrLn ln >> formhame kvs lns
| otherwise = replaceValue tp pickedkvs (fst x) >> formhame kvs (snd x)
where pickedkvs = pickKvs kvs ln
x = cutTargetHtml tp (ln:lns)
tp = checkType ln
replaceValue :: String -> [KeyValue] -> [String] -> IO ()
replaceValue "text" (kv:[]) (ln:[]) = replaceValueText kv ln
replaceValue "radio" (kv:[]) (ln:[]) = replaceValueRadio kv ln
replaceValue "checkbox" kvs (ln:[]) = replaceValueChkbox kvs ln
replaceValue "textarea" (kv:[]) lns = replaceTextArea kv (unwords lns)
replaceValue "select" (kv:[]) lns = replaceSelect kv lns
replaceValue _ _ lns = putStr $ unlines lns
{-- RADIO --}
replaceValueRadio :: KeyValue -> String -> IO ()
replaceValueRadio (k,v) ln = putStrLn newln
where bareln = RE.subRegex ckd ln ""
ckd = RE.mkRegex "(checked=\"checked\"|checked) *"
newln = checkRadio v bareln
checkRadio :: String -> String -> String
checkRadio val ln = if vstr `isInfixOf` ln then newln else ln
where vstr = "value=\"" ++ val ++ "\""
re = RE.mkRegex " */>$"
newln = RE.subRegex re ln " checked=\"checked\" />"
{-- CHECKBOX --}
replaceValueChkbox :: [KeyValue] -> String -> IO ()
replaceValueChkbox kvs ln = putStrLn newln
where bareln = RE.subRegex ckd ln ""
ckd = RE.mkRegex "(checked=\"checked\"|checked) *"
newln = checkChkbox kvs bareln
checkChkbox :: [KeyValue] -> String -> String
checkChkbox [] ln = ln
checkChkbox ((k,v):kvs) ln = if f v ln then rep ln else checkChkbox kvs ln
where f val ln = ("value=\"" ++ val ++ "\"") `isInfixOf` ln
rep str = RE.subRegex ckd str " checked=\"checked\" />"
ckd = RE.mkRegex " */>"
{-- TEXT --}
replaceValueText :: KeyValue -> String -> IO ()
replaceValueText (k,v) ln = putStrLn newln
where re = RE.mkRegex "value=\"[^\"]*\""
str = "value=\"" ++ v ++ "\""
newln = if isValue ln then RE.subRegex re ln str else insertValue ln str
{-- SELECT --}
replaceSelect :: KeyValue -> [String] -> IO ()
replaceSelect (k,v) lns = putStr $ unlines ans
where barelns = map (\ln -> RE.subRegex re ln "") lns
re = RE.mkRegex " *(selected=\"selected\"|selected) *"
target = "value=\"" ++ v ++ "\""
ans = [ if target `isInfixOf` ln then RE.subRegex re2 ln sel else ln | ln <- barelns ]
re2 = RE.mkRegex "<option"
sel = "<option selected=\"selected\""
getSelectBlock :: [String] -> ([String],[String]) -> ([String],[String])
getSelectBlock [] (a,[]) = (a,[])
getSelectBlock (ln:lns) (a,[])
| "</select>" `isInfixOf` ln = (a ++ [ln],lns)
| otherwise = getSelectBlock lns (a ++ [ln],[])
{-- TEXTAREA --}
replaceTextArea :: KeyValue -> String -> IO ()
replaceTextArea (k,v) ln = putStr $ unlines ans
where lns = lines $ RE.subRegex re ln ">\n<"
re = RE.mkRegex ">.*<"
re2 = RE.mkRegex "\\\\n"
vn = RE.subRegex re2 v "\n"
ans = (head lns) : vn : (drop 1 lns)
getTextBoxBlock :: [String] -> ([String],[String]) -> ([String],[String])
getTextBoxBlock [] (a,[]) = (a,[])
getTextBoxBlock (ln:lns) (a,[])
| "</textarea>" `isInfixOf` ln = (a ++ [ln],lns)
| otherwise = getTextBoxBlock lns (a ++ [ln],[])
{-- utilities --}
isValue :: String -> Bool
isValue ln = "value=\"" `isInfixOf` ln
insertValue :: String -> String -> String
insertValue str vstr = unwords $ a ++ [vstr,b]
where ws = words str
a = init ws
b = last ws
checkType :: String -> String
checkType ln
| "type=\"text\"" `isInfixOf` ln = "text"
| "type=\"radio\"" `isInfixOf` ln = "radio"
| "type=\"checkbox\"" `isInfixOf` ln = "checkbox"
| "<textarea " `isInfixOf` ln = "textarea"
| "<select " `isInfixOf` ln = "select"
| otherwise = "unknown"
cutTargetHtml :: String -> [String] -> ([String],[String])
cutTargetHtml tp [] = ([],[])
cutTargetHtml tp (ln:[]) = ([ln],[])
cutTargetHtml tp lns
| tp == "textarea" = getTextBoxBlock lns ([],[])
| tp == "select" = getSelectBlock lns ([],[])
| otherwise = ([head lns], drop 1 lns)
pickKvs :: [KeyValue] -> String -> [KeyValue]
pickKvs [] _ = []
pickKvs kvs ln = filter (\x -> f x ln) kvs
where f (k,v) ln = isInfixOf ("name=\"" ++ k ++ "\"") ln
{--
setOpts :: [String] -> Opts
setOpts as = case parse args "" ((unwords as) ++ " ") of
Right opt -> opt
Left err -> Error ( show err )
args = do f1 <- try(filename) <|> return "-"
char ' '
f2 <- try(filename) <|> return "-"
return $ NormalOpts f1 f2
filename = many1 ( try(letter) <|> try(digit) <|> symbol )
symbol = oneOf "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
--}
| h8gi/Open-usp-Tukubai | COMMANDS.HS/formhame.hs | mit | 8,567 | 41 | 13 | 2,237 | 2,874 | 1,519 | 1,355 | 143 | 12 |
<?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="fil-PH">
<title>Requester</title>
<maps>
<homeID>requester</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/requester/src/main/javahelp/help_fil_PH/helpset_fil_PH.hs | apache-2.0 | 961 | 82 | 52 | 155 | 387 | 205 | 182 | -1 | -1 |
-- #2409
module ShouldCompile where
f :: Int -> Int
f _ | () `seq` False = undefined
| otherwise = error "XXX"
g :: Int -> Int
g _ | () `seq` False = undefined
| otherwise = error "XXX"
| sdiehl/ghc | testsuite/tests/deSugar/should_compile/T2409.hs | bsd-3-clause | 203 | 0 | 9 | 58 | 91 | 46 | 45 | 7 | 1 |
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
module Distribution.Server.Users.UserIdSet (
UserIdSet(..),
empty,
insert,
delete,
member,
size,
toList,
fromList,
unions,
) where
import Distribution.Server.Users.Types
import Distribution.Server.Framework.MemSize
import qualified Data.IntSet as IntSet
import Data.Monoid (Monoid)
import Data.SafeCopy (SafeCopy(..), contain)
import qualified Data.Serialize as Serialize
import Data.Typeable (Typeable)
import Control.DeepSeq
import Control.Applicative ((<$>))
import Data.Aeson (ToJSON)
-- | A simple set of 'UserId's. Used to implement user groups, but can be used
-- anywhere a set of users identified by 'UserId' is needed.
--
newtype UserIdSet = UserIdSet IntSet.IntSet
deriving (Eq, Monoid, Typeable, Show, NFData, MemSize, ToJSON)
empty :: UserIdSet
empty = UserIdSet IntSet.empty
insert :: UserId -> UserIdSet -> UserIdSet
insert (UserId uid) (UserIdSet uidset) = UserIdSet (IntSet.insert uid uidset)
delete :: UserId -> UserIdSet -> UserIdSet
delete (UserId uid) (UserIdSet uidset) = UserIdSet (IntSet.delete uid uidset)
member :: UserId -> UserIdSet -> Bool
member (UserId uid) (UserIdSet uidset) = IntSet.member uid uidset
size :: UserIdSet -> Int
size (UserIdSet uidset) = IntSet.size uidset
toList :: UserIdSet -> [UserId]
toList (UserIdSet uidset) = map UserId (IntSet.toList uidset)
fromList :: [UserId] -> UserIdSet
fromList ids = UserIdSet $ IntSet.fromList (map (\(UserId uid) -> uid) ids)
unions :: [UserIdSet] -> UserIdSet
unions uidsets = UserIdSet (IntSet.unions [ uidset | UserIdSet uidset <- uidsets ])
instance SafeCopy UserIdSet where
putCopy (UserIdSet x) = contain $ Serialize.put x
getCopy = contain $ UserIdSet <$> Serialize.get
| ocharles/hackage-server | Distribution/Server/Users/UserIdSet.hs | bsd-3-clause | 1,782 | 0 | 12 | 285 | 543 | 301 | 242 | 42 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.MessageEvent (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.MessageEvent
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.MessageEvent
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/MessageEvent.hs | mit | 349 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Anonymous.Tor.ProtocolSpec where
import Control.Concurrent (ThreadId, forkIO,
killThread, threadDelay)
import Control.Concurrent.MVar
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.List (intersect)
import qualified Network.Simple.TCP as NS (accept, connect,
listen, send)
import qualified Network.Socket as NS (Socket)
import qualified Network.Anonymous.Tor.Protocol as P
import qualified Network.Anonymous.Tor.Protocol.Types as PT
import qualified Network.Socks5.Types as SocksT
import qualified Data.Base32String.Default as B32
import qualified Data.ByteString.Char8 as BS8
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Test.Hspec
mockServer :: ( MonadIO m
, MonadMask m)
=> String
-> (NS.Socket -> IO a)
-> m ThreadId
mockServer port callback = do
tid <- liftIO $ forkIO $
NS.listen "*" port (\(lsock, _) -> NS.accept lsock (\(sock, _) -> do
_ <- callback sock
threadDelay 1000000
return ()))
liftIO $ threadDelay 500000
return tid
whichPort :: IO Integer
whichPort = do
let ports = [9051, 9151]
availability <- mapM P.isAvailable ports
return . fst . head . filter ((== P.Available) . snd) $ zip ports availability
connect :: (NS.Socket -> IO a) -> IO a
connect callback = do
port <- whichPort
NS.connect "127.0.0.1" (show port) (\(sock, _) -> callback sock)
spec :: Spec
spec = do
describe "when detecting a Tor control port" $ do
it "should detect a port" $ do
port <- whichPort
port `shouldSatisfy` (> 1024)
describe "when detecting protocol info" $ do
it "should allow cookie or null authentication" $ do
info <- connect P.protocolInfo
(PT.authMethods info) `shouldSatisfy`
(not . null . intersect [PT.Cookie, PT.Null])
describe "when authenticating with Tor" $ do
it "should succeed" $ do
_ <- connect P.authenticate
True `shouldBe` True
describe "when detecting SOCKS port" $ do
it "should return a valid port" $ do
port <- connect $ \sock -> do
P.authenticate sock
P.socksPort sock
port `shouldSatisfy` (> 1024)
describe "when connecting through a SOCKS port" $ do
it "should be able to connect to google" $
let clientSock done _ =
putMVar done True
constructSocksDestination =
SocksT.SocksAddress (SocksT.SocksAddrDomainName (BS8.pack "www.google.com")) 80
in do
done <- newEmptyMVar
_ <- connect $ \controlSock -> do
P.authenticate controlSock
P.connect' controlSock constructSocksDestination (clientSock done)
takeMVar done `shouldReturn` True
describe "when mapping an onion address" $ do
it "should succeed in creating a mapping" $
let serverSock sock = do
putStrLn "got client connecting to hidden service!"
NS.send sock "HELLO\n"
clientSock _ =
putStrLn "Got a connection with hidden service!"
destinationAddress onion =
TE.encodeUtf8 $ T.concat [B32.toText onion, T.pack ".ONION"]
constructSocksDestination onion =
SocksT.SocksAddress (SocksT.SocksAddrDomainName (destinationAddress onion)) 80
in do
thread <- liftIO $ mockServer "8080" serverSock
_ <- connect $ \controlSock -> do
P.authenticate controlSock
addr <- P.mapOnion controlSock 80 8080 False Nothing
putStrLn ("got onion address: " ++ show addr)
putStrLn ("waiting 1 minute..")
threadDelay 60000000
putStrLn ("waited 1 minute, connecting..")
P.connect' controlSock (constructSocksDestination addr) clientSock
killThread thread
| solatis/haskell-network-anonymous-tor | test/Network/Anonymous/Tor/ProtocolSpec.hs | mit | 4,338 | 0 | 23 | 1,484 | 1,079 | 546 | 533 | 96 | 1 |
module PrettyJSON
(
renderJValue
) where
import Numeric (showHex)
import Data.Char (ord)
import Data.Bits (shiftR, (.&.))
import SimpleJSON (JValue(..))
import Prettify (Doc, (<>), char, double, fsep, hcat, punctuate, text, compact)
-- , pretty
--import Prettify (Doc, (<>), char, double, fsep, hcat, punctuate, text, compact, pretty)
renderJValue :: JValue -> Doc
renderJValue (JBool True) = text "true"
renderJValue (JBool False) = text "false"
renderJValue JNull = text "null"
renderJValue (JNumber num) = double num
renderJValue (JString str) = string str
renderJValue (JArray ary) = series '[' ']' renderJValue ary
renderJValue (JObject obj) = series '{' '}' field obj
-- where field (name, val) = string name
-- <> text ": "
-- <> renderJValue val
field (name, val) = string name
<> text ": "
<> renderJValue val
enclose :: Char -> Char -> Doc -> Doc
enclose left right x = char left <> x <> char right
hexEscape :: Char -> Doc
hexEscape c | d < 0x10000 = smallHex d
| otherwise = astral (d - 0x10000)
where d = ord c
smallHex :: Int -> Doc
smallHex x = text "\\u"
<> text (replicate (4 - length h) '0')
<> text h
where h = showHex x ""
astral :: Int -> Doc
astral n = smallHex (a + 0xd800) <> smallHex (b + 0xdc00)
where a = (n `shiftR` 10) .&. 0x3ff
b = n .&. 0x3ff
string :: String -> Doc
string = enclose '"' '"' . hcat . map oneChar
oneChar :: Char -> Doc
oneChar c = case lookup c simpleEscapes of
Just r -> text r
Nothing | mustEscape c -> hexEscape c
| otherwise -> char c
where mustEscape c = c < ' ' || c == '\x7f' || c > '\xff'
simpleEscapes :: [(Char, String)]
simpleEscapes = zipWith ch "\b\n\f\r\t\\\"/" "bnfrt\\\"/"
where ch a b = (a, ['\\',b])
series :: Char -> Char -> (a -> Doc) -> [a] -> Doc
series open close item = enclose open close
. fsep . punctuate (char ',') . map item
| NickAger/LearningHaskell | haskellForMacMiscPlayground/realworldhaskellch04.hsproj/PrettyJSON.hs | mit | 2,120 | 0 | 12 | 657 | 744 | 385 | 359 | 48 | 2 |
module NameResolution.Ast where
import Parser.Ast
import qualified Data.Map as M
data Resolved = Local
{ name :: String
}
| Global
{ name :: String
}
| ReplacementLocal
{ member :: Bool
, name :: String
}
| Self
deriving (Eq, Ord, Show)
data ResolvedSource = ResolvedSource
{ types :: M.Map String (TypeDefT Resolved)
, callables :: M.Map String (CallableDefT Resolved)
, cImports :: [RequestT Type Resolved]
, cExports :: [RequestT Type Resolved]
}
| elegios/datalang | src/NameResolution/Ast.hs | mit | 631 | 0 | 11 | 255 | 155 | 91 | 64 | 17 | 0 |
{-|
Module : Test.Make.Instances.Common
Description : Tests the Common instances for Make
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : [email protected]
Stability : experimental
Portability : Unknown
Contains the test hierarchy for the Make Common modules
-}
module Test.Make.Instances.Common (
tests, -- :: TestTree
) where
import qualified Test.Make.Instances.Common.Clause as Clause
import qualified Test.Make.Instances.Common.Clauses as Clauses
import qualified Test.Make.Instances.Common.Literal as Literal
import TestUtils
name :: String
name = "Common"
tests :: TestTree
tests =
testGroup name [
Literal.tests,
Clause.tests ,
Clauses.tests
]
| aburnett88/HSat | tests-src/Test/Make/Instances/Common.hs | mit | 702 | 0 | 7 | 120 | 92 | 64 | 28 | 14 | 1 |
import Control.Monad (guard)
data Response a
= Error String
| Ok a
deriving (Show, Eq)
squareRoot x =
if x < 0 then Error "negative" else Ok (sqrt x)
main = do
guard $ squareRoot 9 == Ok 3
guard $ squareRoot 100.0 == Ok 10.0
guard $ squareRoot (-4) == Error "negative"
| rtoal/ple | haskell/response.hs | mit | 301 | 1 | 11 | 85 | 134 | 64 | 70 | 11 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Data.Matrix.Hermitian.Dense
(DenseHMatrix(..)
,fullEigensystem)
where
import Data.Matrix
import Data.Matrix.Dense
import LAPACK
import LAPACK.Utils
import Data.Complex
import Data.Complex.Utils
import Data.Maybe (fromMaybe)
import Operator
import qualified Data.List as LST
import Control.Monad (forM_)
import Control.Monad.ST (runST)
import System.IO.Unsafe (unsafePerformIO)
import Foreign.C.Types (CDouble)
import qualified Data.Vector.Generic as GV
import qualified Data.Vector.Generic.Mutable as GVM
import qualified Data.Vector.Storable as SV
import qualified Data.Vector.Storable.Mutable as SVM
import qualified Data.Vector.Unboxed as UV
-- | Datatype for a dense hermitian matrix, with data stored in column-major order.
data DenseHMatrix s a
= DenseHMatrix
{ dhmOrder :: Int
, dhmFull :: Bool
, dhmData :: s a }
instance (Conjugable a, GV.Vector v a) => Matrix DenseHMatrix v a where
rows = dhmOrder
cols = rows
row m r = GV.generate (rows m) (ij m r)
col m@(DenseHMatrix mo f d) c =
if f
then GV.unsafeSlice (c * mo) mo d
else GV.generate mo (flip (ij m) c)
ij (DenseHMatrix mo True d) r c = d GV.! ((c * mo) + r)
ij (DenseHMatrix mo False d) r c
| r <= c = d GV.! ((c * mo) + r)
| otherwise = cconj $ d GV.! ((r * mo) + c)
transpose m@(DenseHMatrix _ _ d) = m { dhmData = GV.map cconj d }
generate mo _ f =
DenseHMatrix { dhmOrder = mo, dhmData = d, dhmFull = False }
where d = runST $ do
mv <- GVM.new (mo * mo)
forM_ [0..(mo - 1)] $ \c ->
forM_ [0..c] $ \r ->
GVM.write mv ((c * mo) + r) (f r c)
GV.unsafeFreeze mv
generateM mo _ f = do
d <- GV.generateM (mo * mo) (f' . flip quotRem mo)
return DenseHMatrix
{ dhmOrder = mo, dhmData = d, dhmFull = False }
where fill = f 0 0
f' (c,r) | c <= r = f r c
| otherwise = fill
fromList l = DenseHMatrix
{ dhmOrder = length $ head l
, dhmData = GV.fromList . LST.concat . LST.transpose $ l
, dhmFull = True }
instance (Functor s) => Functor (DenseHMatrix s) where
fmap f m@(DenseHMatrix _ _ d) = m { dhmData = fmap f d }
instance (Conjugable a, GV.Vector v a) => MatrixRing DenseHMatrix v a DenseHMatrix v a where
type MSumMatrix DenseHMatrix v a DenseHMatrix v a = DenseHMatrix
type MSumStore DenseHMatrix v a DenseHMatrix v a = v
type MSumElement DenseHMatrix v a DenseHMatrix v a = a
mp m@(DenseHMatrix _ f d) (DenseHMatrix _ f' d')
= m { dhmFull = f && f'
, dhmData = GV.zipWith (+) d d'
}
-- | Wrapper to "raw" Haskell function 'hszheevr' for the eigensystem of a Hermitian matrix.
fullEigensystem :: (FComplexable a CDouble
, GV.Vector v a
, GV.Vector v (FComplex CDouble)
, GV.Vector v' Double
, GV.Vector v' CDouble
, GV.Vector v'' (FComplex CDouble)
, GV.Vector v'' (Complex Double)) =>
DenseHMatrix v a -- ^ input matrix
-> Bool -- ^ calculate eigenvectors
-> RANGE -- ^ eigenvalue calculation range type
-> Double -- ^ lower bound of eigenvalue interval
-> Double -- ^ upper bound of eigenvalue interval
-> Int -- ^ lower eigenvalue index
-> Int -- ^ upper eigenvalue index
-> (v' Double, Maybe (v'' (Complex Double)))
fullEigensystem (DenseHMatrix mo _ d) vecs rng vl vu il iu =
unsafePerformIO $ do
mdat <- SV.unsafeThaw . GV.convert . GV.map toFComplex $ d
SVM.unsafeWith mdat $ \pmat ->
hszheevr jz rng uploUpper mo pmat mo vl vu (il + 1) (iu + 1) globalFAbstol >>= freezeHermitianES
where jz = if vecs
then jzEigvalsEigvecs
else jzEigvals
instance (FComplexable a CDouble
,GV.Vector v a
,GV.Vector v (FComplex CDouble)) =>
EndoOperator (DenseHMatrix v a) where
type Eigenvalue (DenseHMatrix v a) = Double
type EigenvalueStorage (DenseHMatrix v a) = UV.Vector
type EigenvectorStorage (DenseHMatrix v a) = DenseMatrix UV.Vector (Complex Double)
eigvals m (Just (lo,hi)) = GV.unsafeTake (hi - lo + 1) . fst $
(fullEigensystem m False rngEigNums 0 0 lo hi
:: (UV.Vector Double, Maybe (UV.Vector (Complex Double))))
eigvals m Nothing = fst
(fullEigensystem m False rngAll 0 0 0 0
:: (UV.Vector Double, Maybe (UV.Vector (Complex Double))))
eigvecs m (Just (lo,hi)) = fromColMajorVector rs cs .
maybe GV.empty (GV.unsafeTake (rs * cs)) $
snd (fullEigensystem m True rngEigNums 0 0 lo hi
:: (UV.Vector Double, Maybe (UV.Vector (Complex Double))))
where rs = dhmOrder m
cs = hi - lo + 1
eigvecs m Nothing = fromColMajorVector (dhmOrder m) (dhmOrder m) .
fromMaybe GV.empty . snd $
(fullEigensystem m True rngAll 0 0 0 0
:: (UV.Vector Double, Maybe (UV.Vector (Complex Double))))
adjoint = id
| lensky/hs-matrix | lib/Data/Matrix/Hermitian/Dense.hs | mit | 5,483 | 0 | 19 | 1,729 | 1,836 | 982 | 854 | 119 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE TypeApplications #-}
module SolverSpec where
import Control.Monad
import Data.Int
import Math.NumberTheory.Primes
import Solver
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Data.Either
smallPrimes :: [Integer]
smallPrimes = takeWhile (< 10000) $ fmap unPrime primes
spec :: Spec
spec = do
describe "extEuclidean" $ do
specify "example" $
extEuclidean @Integer 1234 4147 `shouldBe` (1, (-1314, 391))
prop "props" $ do
x <- choose (1, 0xFFFFFF)
y <- choose (1, 0xFFFFFF)
let (t, (u, v)) = extEuclidean @Integer x y
gcdResult = gcd x y
lbl = if gcdResult == 1 then "coprimes" else "not coprimes"
pure $
label lbl $
t === gcd x y
.&&. (gcd x y =/= 1
.||. u * x + v * y === 1)
describe "multInv" $ do
prop "props" $ do
m <- choose (1, 0xFFFFFF)
n <- choose (1, 0xFFFFFF)
let r = multInv @Integer m n
pure $
either
(label "no inv" . (=== n))
(\n' ->
label "has inv" $
n' >= 0 .&&. n' < m .&&. (n' * n) `mod` m === 1)
r
describe "solveMatOne" $ do
{-
TODO: coverage
- small modulo (2~12)
- intentionally underdetermined
-}
specify "example" $
solveMatOne @Int
17
[ [3, 4, 7, 2]
, [4, 11, 2, 8]
, [16, 7, 3, 3]
]
`shouldBe` Right [4, 15, 7]
prop "correctness (primes)" $ do
sz <- choose @Int (3, 20)
let rndIntVal = choose @Int64 (-0xFF_FFFF, 0xFF_FFFF)
mPre <- elements smallPrimes
let m = fromInteger mPre
mat <- replicateM sz $ replicateM (sz + 1) rndIntVal
let result = solveMatOne m mat
lbl = case result of
Right _ -> "right"
Left v ->
"left: " <> case v of
NoMultInv _ -> "no mult inv"
Underdetermined -> "underdet"
Todo _ -> "TODO"
Gaussian _ -> "Gaussian"
pure $
label lbl $
case result of
Right xs ->
counterexample (show (m, mat)) $
conjoin $ do
eqn <- mat
let lhs = init eqn
rhs = last eqn
pure $
length xs === length lhs
.&&. counterexample (show ((lhs, xs), rhs)) (
sum (zipWith (*) lhs xs) `mod` m === (rhs `mod` m))
Left _ -> property True
{-
prop "correctness (small modulo)" $ do
let maxM = 12
rndIntVal = choose @Int (-sq, sq)
where
sq = maxM * maxM
m <- choose @Int (2, maxM)
sz <- choose @Int (2, 8)
mat <- do
matLhs <- replicateM sz $ replicateM sz rndIntVal
assns <- replicateM sz rndIntVal
let matRhs :: [Int]
matRhs = fmap (\lhs -> sum (zipWith(*) assns lhs) `mod` m) matLhs
pure $ zipWith (\lhs rhs -> lhs <> [rhs]) matLhs matRhs
let result = solveMatOne m mat
-- TODO
pure $ counterexample (show result) $ property $ isRight result -}
describe "shuffler" $ do
specify "example" $ do
let (f, g) = shuffler 2
f "ABCD" `shouldBe` "CABD"
g "CABD" `shouldBe` "ABCD"
prop "correctness" $ \(xs :: String) ->
conjoin $ do
(i,e) <- zip [0..] xs
let (f,g) = shuffler i
ys = f xs
pure $ xs === g ys .&&. head ys === e
| Javran/misc | gaussian-elim/test/SolverSpec.hs | mit | 3,619 | 0 | 27 | 1,395 | 1,050 | 531 | 519 | -1 | -1 |
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
module Unison.Test.UnisonSources where
import Control.Exception (throwIO)
import Control.Lens ( view )
import Control.Lens.Tuple ( _5 )
import Control.Monad (void)
import Control.Monad.IO.Class (liftIO)
import qualified Data.Map as Map
import Data.Sequence (Seq)
import Data.Text (unpack)
import Data.Text.IO (readFile)
import EasyTest
import System.FilePath (joinPath, splitPath, replaceExtension)
import System.FilePath.Find (always, extension, find, (==?))
import System.Directory ( doesFileExist )
import qualified Unison.ABT as ABT
import qualified Unison.Builtin as Builtin
import Unison.Codebase.Runtime ( Runtime, evaluateWatches )
import Unison.Codebase.Serialization ( getFromBytes, putBytes )
import qualified Unison.Codebase.Serialization.V1 as V1
import Unison.DataDeclaration (EffectDeclaration, DataDeclaration)
import Unison.Parser as Parser
import qualified Unison.Parsers as Parsers
import qualified Unison.PrettyPrintEnv as PPE
import qualified Unison.PrintError as PrintError
import Unison.Reference ( Reference )
import Unison.Result (pattern Result, Result)
import qualified Unison.Result as Result
import qualified Unison.Runtime.Interface as RTI
import Unison.Symbol (Symbol)
import qualified Unison.Term as Term
import Unison.Term ( Term )
import Unison.Test.Common (parseAndSynthesizeAsFile, parsingEnv)
import Unison.Type ( Type )
import qualified Unison.UnisonFile as UF
import Unison.Util.Monoid (intercalateMap)
import Unison.Util.Pretty (toPlain)
import qualified Unison.Var as Var
import qualified Unison.Test.Common as Common
import qualified Unison.Names3
type Note = Result.Note Symbol Parser.Ann
type TFile = UF.TypecheckedUnisonFile Symbol Ann
type SynthResult =
Result (Seq Note)
(Either Unison.Names3.Names0 TFile)
type EitherResult = Either String TFile
ppEnv :: PPE.PrettyPrintEnv
ppEnv = PPE.fromNames Common.hqLength Builtin.names
expectRight' :: Either String a -> Test a
expectRight' (Left e) = crash e
expectRight' (Right a) = ok >> pure a
good :: EitherResult -> Test TFile
good = expectRight'
bad :: EitherResult -> Test TFile
bad r = EasyTest.expectLeft r >> done
test :: Test ()
test = do
rt <- io RTI.startRuntime
scope "unison-src"
. tests
$ [ go rt shouldPassNow good
, go rt shouldFailNow bad
, go rt shouldPassLater (pending . bad)
, go rt shouldFailLater (pending . good)
]
shouldPassPath, shouldFailPath :: String
shouldPassPath = "unison-src/tests"
shouldFailPath = "unison-src/errors"
shouldPassNow :: IO [FilePath]
shouldPassNow = find always (extension ==? ".u") shouldPassPath
shouldFailNow :: IO [FilePath]
shouldFailNow = find always (extension ==? ".u") shouldFailPath
shouldPassLater :: IO [FilePath]
shouldPassLater = find always (extension ==? ".uu") shouldPassPath
shouldFailLater :: IO [FilePath]
shouldFailLater = find always (extension ==? ".uu") shouldFailPath
go :: Runtime Symbol -> IO [FilePath] -> (EitherResult -> Test TFile) -> Test ()
go rt files how = do
files' <- liftIO files
tests (makePassingTest rt how <$> files')
showNotes :: Foldable f => String -> PrintError.Env -> f Note -> String
showNotes source env =
intercalateMap "\n\n" $ PrintError.renderNoteAsANSI 60 env source
decodeResult
:: String -> SynthResult -> EitherResult-- String (UF.TypecheckedUnisonFile Symbol Ann)
decodeResult source (Result notes Nothing) =
Left $ showNotes source ppEnv notes
decodeResult source (Result notes (Just (Left errNames))) =
Left $ showNotes
source
(PPE.fromNames Common.hqLength
(Unison.Names3.shadowing errNames Builtin.names))
notes
decodeResult _source (Result _notes (Just (Right uf))) =
Right uf
makePassingTest
:: Runtime Symbol -> (EitherResult -> Test TFile) -> FilePath -> Test ()
makePassingTest rt how filepath = scope (shortName filepath) $ do
uf <- typecheckingTest how filepath
resultTest rt uf filepath *> serializationTest uf
shortName :: FilePath -> FilePath
shortName = joinPath . drop 1 . splitPath
typecheckingTest :: (EitherResult -> Test TFile) -> FilePath -> Test TFile
typecheckingTest how filepath = scope "typecheck" $ do
source <- io $ unpack <$> Data.Text.IO.readFile filepath
how . decodeResult source $ parseAndSynthesizeAsFile [] (shortName filepath) source
resultTest
:: Runtime Symbol -> TFile -> FilePath -> Test ()
resultTest rt uf filepath = do
let valueFile = replaceExtension filepath "ur"
rFileExists <- io $ doesFileExist valueFile
if rFileExists
then scope "result" $ do
values <- io $ unpack <$> Data.Text.IO.readFile valueFile
let untypedFile = UF.discardTypes uf
let term = Parsers.parseTerm values parsingEnv
let report e = throwIO (userError $ toPlain 10000 e)
(bindings, watches) <- io $ either report pure =<<
evaluateWatches Builtin.codeLookup
mempty
(const $ pure Nothing)
rt
untypedFile
case term of
Right tm -> do
-- compare the the watch expression from the .u with the expr in .ur
let [watchResult] = view _5 <$> Map.elems watches
tm' = Term.letRec' False bindings watchResult
-- note . show $ tm'
-- note . show $ Term.amap (const ()) tm
expectEqual tm' (Term.amap (const ()) tm)
Left e -> crash $ show e
else pure ()
serializationTest :: TFile -> Test ()
serializationTest uf = scope "serialization" . tests . concat $
[ map testDataDeclaration (Map.toList $ UF.dataDeclarations' uf)
, map testEffectDeclaration (Map.toList $ UF.effectDeclarations' uf)
, map testTerm (Map.toList $ UF.hashTerms uf)
]
where
putUnit :: Monad m => () -> m ()
putUnit () = pure ()
getUnit :: Monad m => m ()
getUnit = pure ()
testDataDeclaration :: (Symbol, (Reference, DataDeclaration Symbol Ann)) -> Test ()
testDataDeclaration (name, (_, decl)) = scope (Var.nameStr name) $
let decl' :: DataDeclaration Symbol ()
decl' = void decl
bytes = putBytes (V1.putDataDeclaration V1.putSymbol putUnit) decl'
decl'' = getFromBytes (V1.getDataDeclaration V1.getSymbol getUnit) bytes
in expectEqual decl'' (Just decl')
testEffectDeclaration :: (Symbol, (Reference, EffectDeclaration Symbol Ann)) -> Test ()
testEffectDeclaration (name, (_, decl)) = scope (Var.nameStr name) $
let decl' :: EffectDeclaration Symbol ()
decl' = void decl
bytes = putBytes (V1.putEffectDeclaration V1.putSymbol putUnit) decl'
decl'' = getFromBytes (V1.getEffectDeclaration V1.getSymbol getUnit) bytes
in expectEqual decl'' (Just decl')
testTerm :: (Symbol, (Reference, Term Symbol Ann, Type Symbol Ann)) -> Test ()
testTerm (name, (_, tm, tp)) = scope (Var.nameStr name) $
let tm' :: Term Symbol ()
tm' = Term.amap (const ()) tm
tp' :: Type Symbol ()
tp' = ABT.amap (const ()) tp
tmBytes = putBytes (V1.putTerm V1.putSymbol putUnit) tm'
tpBytes = putBytes (V1.putType V1.putSymbol putUnit) tp'
tm'' = getFromBytes (V1.getTerm V1.getSymbol getUnit) tmBytes
tp'' = getFromBytes (V1.getType V1.getSymbol getUnit) tpBytes
in tests
[ scope "type" $ expectEqual tp'' (Just tp')
, scope "term" $ expectEqual tm'' (Just tm')
]
| unisonweb/platform | parser-typechecker/tests/Unison/Test/UnisonSources.hs | mit | 7,971 | 0 | 21 | 2,055 | 2,366 | 1,240 | 1,126 | 166 | 3 |
{-# LANGUAGE OverloadedStrings #-}
import System.Authinfo
main = getPassword "gmail.com" "ablabla" >>= print
| robgssp/authinfo-hs | Test.hs | mit | 110 | 0 | 6 | 14 | 21 | 11 | 10 | 3 | 1 |
module Main where
import Data.List
import System.Environment
import System.Random
import qualified Data.Set as S
import qualified ACME.Yes.PreCure5 as Yes
import ACME.Yes.PreCure5.Class (allPrecures)
import qualified ACME.Yes.PreCure5.Random as R
import qualified ACME.Yes.PreCure5.GoGo as GoGo
main :: IO ()
main = do
arg <- intercalate " " `fmap` getArgs
g <- getStdGen
putStr $ possibblyInfiniteMetamorphoses g arg
possibblyInfiniteMetamorphoses :: (RandomGen g) => g -> String -> String
possibblyInfiniteMetamorphoses g = unlines . repeat . possiblyMetamorphose g
possiblyMetamorphose :: (RandomGen g) => g -> String -> String
possiblyMetamorphose g s
| GoGo.isPreCure5GoGo s = metamorphoseGoGo
| Yes.isPreCure5 s = metamorphose
| otherwise = generateLine s
where
(metamorphoseGoGo, _) = R.chooseMetamorphoseFrom (allPrecures :: S.Set GoGo.PreCure5GoGo) g
(metamorphose , _) = R.chooseMetamorphoseFrom (allPrecures :: S.Set Yes.PreCure5 ) g
generateLine :: String -> String
generateLine "" = "y"
generateLine s = s
| igrep/yes-precure5-command | main.hs | mit | 1,055 | 0 | 10 | 171 | 319 | 174 | 145 | 26 | 1 |
module Environment (
Environment,
nullEnv,
setVar,
getVar,
defineVar,
bindVars,
) where
import IError
import Control.Monad
import Control.Monad.Error
import Data.IORef
import System.IO
type Environment a = IORef [(String, IORef a)]
nullEnv :: IO (Environment a)
nullEnv = newIORef []
-- Check if a variable has been bound
isBound :: (Environment a) -> String -> IO Bool
isBound envRef var = readIORef envRef >>=
return . maybe False (const True) . lookup var
-- Get the value of a variable
getVar :: (Environment a) -> String -> IOThrowsError a a
getVar envRef var = do
env <- liftIO $ readIORef envRef
maybe
(throwError $ UnboundVar "Getting an unbound variable" var)
(liftIO . readIORef)
(lookup var env)
-- Set the value of a variable
setVar :: (Environment a) -> String -> a -> IOThrowsError a a
setVar envRef var val = do
env <- liftIO $ readIORef envRef
maybe
(throwError $ UnboundVar "Setting an unbound variable" var)
(liftIO . (flip writeIORef val))
(lookup var env)
return val
-- Define a new variable
defineVar :: (Environment a) -> String -> a -> IOThrowsError a a
defineVar envRef var val = do
alreadyDefined <- liftIO $ isBound envRef var
if alreadyDefined
then setVar envRef var val >> return val
else liftIO $ do
valRef <- newIORef val
env <- readIORef envRef
writeIORef envRef ((var, valRef) : env)
return val
-- Bind multiple variables
bindVars :: (Environment a) -> [(String, a)] -> IO (Environment a)
bindVars envRef vars = readIORef envRef >>= extendEnv vars >>= newIORef
where
extendEnv vars env = liftM (++ env) (mapM addBinding vars)
addBinding (var, val) = do
ref <- newIORef val
return (var, ref)
| mhrheaume/hskme | Environment.hs | gpl-2.0 | 1,686 | 30 | 14 | 336 | 639 | 323 | 316 | 49 | 2 |
{- This module was generated from data in the Kate syntax
highlighting file monobasic.xml, version 1.01, by Davide Bettio ([email protected]) -}
module Text.Highlighting.Kate.Syntax.Monobasic
(highlight, parseExpression, syntaxName, syntaxExtensions)
where
import Text.Highlighting.Kate.Types
import Text.Highlighting.Kate.Common
import Text.ParserCombinators.Parsec hiding (State)
import Control.Monad.State
import Data.Char (isSpace)
import qualified Data.Set as Set
-- | Full name of language.
syntaxName :: String
syntaxName = "MonoBasic"
-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "*.vb"
-- | Highlight source code using this syntax definition.
highlight :: String -> [SourceLine]
highlight input = evalState (mapM parseSourceLine $ lines input) startingState
parseSourceLine :: String -> State SyntaxState SourceLine
parseSourceLine = mkParseSourceLine (parseExpression Nothing)
-- | Parse an expression using appropriate local context.
parseExpression :: Maybe (String,String)
-> KateParser Token
parseExpression mbcontext = do
(lang,cont) <- maybe currentContext return mbcontext
result <- parseRules (lang,cont)
optional $ do eof
updateState $ \st -> st{ synStPrevChar = '\n' }
pEndLine
return result
startingState = SyntaxState {synStContexts = [("MonoBasic","Normal")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = False, synStCaptures = []}
pEndLine = do
updateState $ \st -> st{ synStPrevNonspace = False }
context <- currentContext
contexts <- synStContexts `fmap` getState
st <- getState
if length contexts >= 2
then case context of
_ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False }
("MonoBasic","Normal") -> return ()
("MonoBasic","String") -> (popContext) >> pEndLine
("MonoBasic","Comment") -> (popContext) >> pEndLine
_ -> return ()
else return ()
withAttribute attr txt = do
when (null txt) $ fail "Parser matched no text"
updateState $ \st -> st { synStPrevChar = last txt
, synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) }
return (attr, txt)
list_keywords = Set.fromList $ words $ "option explicit strict imports inherits as new dim redim private friend public const readonly writeonly default shared shadows protected overloads overrides notoverridable notinheritable mustinherit mustoverride mybase myclass me delegate catch finaly when throw to step then else true false nothing call byval byref optional paramarray return declare withevents event raiseevent addhandler and or not xor andalso orelse goto on error resume"
list_types = Set.fromList $ words $ "boolean char string integer long double object exception date datetime int16 int32 int64 paramarray timespan byte decimal intptr single guid"
regex_'5cb'28Namespace'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Namespace)([\\s]|$)"
regex_End'2eNamespace'2e'2a'24 = compileRegex True "End.Namespace.*$"
regex_'5cb'28Module'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Module)([\\s]|$)"
regex_End'2eModule'2e'2a'24 = compileRegex True "End.Module.*$"
regex_'5cb'28Class'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Class)([\\s]|$)"
regex_End'2eClass'2e'2a'24 = compileRegex True "End.Class.*$"
regex_'5cb'28Interface'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Interface)([\\s]|$)"
regex_End'2eInterface'2e'2a'24 = compileRegex True "End.Interface.*$"
regex_'5cb'28Structure'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Structure)([\\s]|$)"
regex_End'2eStructure'2e'2a'24 = compileRegex True "End.Structure.*$"
regex_'5cb'28Enum'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Enum)([\\s]|$)"
regex_End'2eEnum'2e'2a'24 = compileRegex True "End.Enum.*$"
regex_'5cb'28Property'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Property)([\\s]|$)"
regex_End'2eProperty'2e'2a'24 = compileRegex True "End.Property.*$"
regex_'5cb'28Get'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Get)([\\s]|$)"
regex_End'2eGet'2e'2a'24 = compileRegex True "End.Get.*$"
regex_'5cb'28Set'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Set)([\\s]|$)"
regex_End'2eSet'2e'2a'24 = compileRegex True "End.Set.*$"
regex_'5cb'28Sub'29'28'5b'2e'5cs'5d'7c'24'29 = compileRegex True "\\b(Sub)([.\\s]|$)"
regex_End'2eSub'2e'2a'24 = compileRegex True "End.Sub.*$"
regex_Exit'2eSub'2e'2a'24 = compileRegex True "Exit.Sub.*$"
regex_'5cb'28Function'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Function)([\\s]|$)"
regex_End'2eFunction'2e'2a'24 = compileRegex True "End.Function.*$"
regex_Exit'2eFunction'2e'2a'24 = compileRegex True "Exit.Function.*$"
regex_'5cb'28Try'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Try)([\\s]|$)"
regex_End'2eTry'2e'2a'24 = compileRegex True "End.Try.*$"
regex_'5cb'28If'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(If)([\\s]|$)"
regex_End'2eIf'2e'2a'24 = compileRegex True "End.If.*$"
regex_Select'2eCase'2e'2a'24 = compileRegex True "Select.Case.*$"
regex_End'2eSelect'2e'2a'24 = compileRegex True "End.Select.*$"
regex_'5cb'28For'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(For)([\\s]|$)"
regex_'5cb'28Next'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Next)([\\s]|$)"
regex_'5cb'28Do'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Do)([\\s]|$)"
regex_'5cb'28Loop'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(Loop)([\\s]|$)"
regex_'5cb'28While'29'28'5b'5cs'5d'7c'24'29 = compileRegex True "\\b(While)([\\s]|$)"
regex_End'2eWhile'2e'2a'24 = compileRegex True "End.While.*$"
regex_Exit'2eWhile'2e'2a'24 = compileRegex True "Exit.While.*$"
regex_'23Region'2e'2a'24 = compileRegex True "#Region.*$"
regex_'23End'2eRegion'2e'2a'24 = compileRegex True "#End.Region.*$"
regex_'23If'2e'2a'24 = compileRegex True "#If.*$"
regex_'23End'2eIf'2e'2a'24 = compileRegex True "#End.If.*$"
parseRules ("MonoBasic","Normal") =
(((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_keywords >>= withAttribute KeywordTok))
<|>
((pKeyword " \n\t.():!+,-<=>%&*/;?[]^{|}~\\" list_types >>= withAttribute DataTypeTok))
<|>
((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("MonoBasic","String"))
<|>
((pDetectChar False '\'' >>= withAttribute CommentTok) >>~ pushContext ("MonoBasic","Comment"))
<|>
((pRegExpr regex_'5cb'28Namespace'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eNamespace'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Module'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eModule'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Class'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eClass'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Interface'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eInterface'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Structure'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eStructure'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Enum'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eEnum'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Property'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eProperty'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Get'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eGet'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Set'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eSet'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Sub'29'28'5b'2e'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eSub'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_Exit'2eSub'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Function'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eFunction'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_Exit'2eFunction'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Try'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eTry'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28If'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eIf'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_Select'2eCase'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eSelect'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28For'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Next'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Do'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28Loop'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'5cb'28While'29'28'5b'5cs'5d'7c'24'29 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_End'2eWhile'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_Exit'2eWhile'2e'2a'24 >>= withAttribute KeywordTok))
<|>
((pRegExpr regex_'23Region'2e'2a'24 >>= withAttribute OtherTok))
<|>
((pRegExpr regex_'23End'2eRegion'2e'2a'24 >>= withAttribute OtherTok))
<|>
((pRegExpr regex_'23If'2e'2a'24 >>= withAttribute OtherTok))
<|>
((pRegExpr regex_'23End'2eIf'2e'2a'24 >>= withAttribute OtherTok))
<|>
(currentContext >>= \x -> guard (x == ("MonoBasic","Normal")) >> pDefault >>= withAttribute NormalTok))
parseRules ("MonoBasic","String") =
(((pLineContinue >>= withAttribute StringTok) >>~ (popContext))
<|>
((pHlCStringChar >>= withAttribute NormalTok))
<|>
((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext))
<|>
(currentContext >>= \x -> guard (x == ("MonoBasic","String")) >> pDefault >>= withAttribute StringTok))
parseRules ("MonoBasic","Comment") =
(currentContext >>= \x -> guard (x == ("MonoBasic","Comment")) >> pDefault >>= withAttribute CommentTok)
parseRules x = parseRules ("MonoBasic","Normal") <|> fail ("Unknown context" ++ show x)
| ambiata/highlighting-kate | Text/Highlighting/Kate/Syntax/Monobasic.hs | gpl-2.0 | 10,683 | 0 | 54 | 1,405 | 2,242 | 1,163 | 1,079 | 190 | 6 |
-- Sample code to demonstrate how to emulate X86 code
import Unicorn
import Unicorn.Hook
import qualified Unicorn.CPU.X86 as X86
import Control.Monad.Trans.Class (lift)
import qualified Data.ByteString as BS
import Data.Word
import qualified Numeric as N (showHex)
import System.Environment
-- Code to be emulated
--
-- inc ecx; dec edx
x86Code32 :: BS.ByteString
x86Code32 = BS.pack [0x41, 0x4a]
-- jmp 4; nop; nop; nop; nop; nop; nop
x86Code32Jump :: BS.ByteString
x86Code32Jump = BS.pack [0xeb, 0x02, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90]
-- inc ecx; dec edx; jmp self-loop
x86Code32Loop :: BS.ByteString
x86Code32Loop = BS.pack [0x41, 0x4a, 0xeb, 0xfe]
-- mov [0xaaaaaaaa], ecx; inc ecx; dec edx
x86Code32MemWrite :: BS.ByteString
x86Code32MemWrite = BS.pack [0x89, 0x0d, 0xaa, 0xaa, 0xaa, 0xaa, 0x41, 0x4a]
-- mov ecx, [0xaaaaaaaa]; inc ecx; dec edx
x86Code32MemRead :: BS.ByteString
x86Code32MemRead = BS.pack [0x8b, 0x0d, 0xaa, 0xaa, 0xaa, 0xaa, 0x41, 0x4a]
-- jmp ouside; inc ecx; dec edx
x86Code32JmpInvalid :: BS.ByteString
x86Code32JmpInvalid = BS.pack [0xe9, 0xe9, 0xee, 0xee, 0xee, 0x41, 0x4a]
-- inc ecx; in al, 0x3f; dec edx; out 0x46, al; inc ebx
x86Code32InOut :: BS.ByteString
x86Code32InOut = BS.pack [0x41, 0xe4, 0x3f, 0x4a, 0xe6, 0x46, 0x43]
x86Code64 :: BS.ByteString
x86Code64 = BS.pack [0x41, 0xbc, 0x3b, 0xb0, 0x28, 0x2a, 0x49, 0x0f, 0xc9,
0x90, 0x4d, 0x0f, 0xad, 0xcf, 0x49, 0x87, 0xfd, 0x90,
0x48, 0x81, 0xd2, 0x8a, 0xce, 0x77, 0x35, 0x48, 0xf7,
0xd9, 0x4d, 0x29, 0xf4, 0x49, 0x81, 0xc9, 0xf6, 0x8a,
0xc6, 0x53, 0x4d, 0x87, 0xed, 0x48, 0x0f, 0xad, 0xd2,
0x49, 0xf7, 0xd4, 0x48, 0xf7, 0xe1, 0x4d, 0x19, 0xc5,
0x4d, 0x89, 0xc5, 0x48, 0xf7, 0xd6, 0x41, 0xb8, 0x4f,
0x8d, 0x6b, 0x59, 0x4d, 0x87, 0xd0, 0x68, 0x6a, 0x1e,
0x09, 0x3c, 0x59]
-- add byte ptr [bx + si], al
x86Code16 :: BS.ByteString
x86Code16 = BS.pack [0x00, 0x00]
-- SYSCALL
x86Code64Syscall :: BS.ByteString
x86Code64Syscall = BS.pack [0x0f, 0x05]
-- Memory address where emulation starts
address :: Word64
address = 0x1000000
-- Pretty-print integral as hex
showHex :: (Integral a, Show a) => a -> String
showHex i =
N.showHex (fromIntegral i :: Word64) ""
-- Pretty-print byte string as hex
showHexBS :: BS.ByteString -> String
showHexBS =
concatMap (flip N.showHex "") . reverse . BS.unpack
-- Write a string (with a newline character) to standard output in the emulator
emuPutStrLn :: String -> Emulator ()
emuPutStrLn =
lift . putStrLn
-- Calculate code length
codeLength :: Num a => BS.ByteString -> a
codeLength =
fromIntegral . BS.length
-- Callback for tracing basic blocks
hookBlock :: BlockHook ()
hookBlock _ addr size _ =
putStrLn $ ">>> Tracing basic block at 0x" ++ showHex addr ++
", block size = 0x" ++ (maybe "0" showHex size)
-- Callback for tracing instruction
hookCode :: CodeHook ()
hookCode uc addr size _ = do
runEmulator $ do
emuPutStrLn $ ">>> Tracing instruction at 0x" ++ showHex addr ++
", instruction size = 0x" ++ (maybe "0" showHex size)
eflags <- regRead uc X86.Eflags
emuPutStrLn $ ">>> --- EFLAGS is 0x" ++ showHex eflags
return ()
-- Callback for tracing instruction
hookCode64 :: CodeHook ()
hookCode64 uc addr size _ = do
runEmulator $ do
rip <- regRead uc X86.Rip
emuPutStrLn $ ">>> Tracing instruction at 0x" ++ showHex addr ++
", instruction size = 0x" ++ (maybe "0" showHex size)
emuPutStrLn $ ">>> RIP is 0x" ++ showHex rip
return ()
-- Callback for tracing memory access (READ or WRITE)
hookMemInvalid :: MemoryEventHook ()
hookMemInvalid uc MemWriteUnmapped addr size (Just value) _ = do
runEmulator $ do
emuPutStrLn $ ">>> Missing memory is being WRITE at 0x" ++
showHex addr ++ ", data size = " ++ show size ++
", data value = 0x" ++ showHex value
memMap uc 0xaaaa0000 (2 * 1024 * 1024) [ProtAll]
return True
hookMemInvalid _ _ _ _ _ _ =
return False
hookMem64 :: MemoryHook ()
hookMem64 _ MemRead addr size _ _ =
putStrLn $ ">>> Memory is being READ at 0x" ++ showHex addr ++
", data size = " ++ show size
hookMem64 _ MemWrite addr size (Just value) _ =
putStrLn $ ">>> Memory is being WRITE at 0x" ++ showHex addr ++
", data size = " ++ show size ++ ", data value = 0x" ++
showHex value
-- Callback for IN instruction (X86)
-- This returns the data read from the port
hookIn :: InHook ()
hookIn uc port size _ = do
result <- runEmulator $ do
eip <- regRead uc X86.Eip
emuPutStrLn $ "--- reading from port 0x" ++ showHex port ++
", size: " ++ show size ++ ", address: 0x" ++ showHex eip
case size of
-- Read 1 byte to AL
1 -> return 0xf1
-- Read 2 byte to AX
2 -> return 0xf2
-- Read 4 byte to EAX
4 -> return 0xf4
-- Should never reach this
_ -> return 0
case result of
Right r -> return r
Left _ -> return 0
-- Callback for OUT instruction (X86)
hookOut :: OutHook ()
hookOut uc port size value _ = do
runEmulator $ do
eip <- regRead uc X86.Eip
emuPutStrLn $ "--- writing to port 0x" ++ showHex port ++ ", size: " ++
show size ++ ", value: 0x" ++ showHex value ++
", address: 0x" ++ showHex eip
-- Confirm that value is indeed the value of AL/AX/EAX
case size of
1 -> do
tmp <- regRead uc X86.Al
emuPutStrLn $ "--- register value = 0x" ++ showHex tmp
2 -> do
tmp <- regRead uc X86.Ax
emuPutStrLn $ "--- register value = 0x" ++ showHex tmp
4 -> do
tmp <- regRead uc X86.Eax
emuPutStrLn $ "--- register value = 0x" ++ showHex tmp
-- Should never reach this
_ -> return ()
return ()
-- Callback for SYSCALL instruction (X86)
hookSyscall :: SyscallHook ()
hookSyscall uc _ = do
runEmulator $ do
rax <- regRead uc X86.Rax
if rax == 0x100 then
regWrite uc X86.Rax 0x200
else
emuPutStrLn $ "ERROR: was not expecting rax=0x" ++ showHex rax ++
" in syscall"
return ()
testI386 :: IO ()
testI386 = do
putStrLn "Emulate i386 code"
result <- runEmulator $ do
-- Initialize emulator in X86-32bit mode
uc <- open ArchX86 [Mode32]
-- Map 2MB memory for this emulation
memMap uc address (2 * 1024 * 1024) [ProtAll]
-- Write machine code to be emulated to memory
memWrite uc address x86Code32
-- Initialize machine registers
regWrite uc X86.Ecx 0x1234
regWrite uc X86.Edx 0x7890
-- Tracing all basic blocks with customized callback
blockHookAdd uc hookBlock () 1 0
-- Tracing all instruction by having @begin > @end
codeHookAdd uc hookCode () 1 0
-- Emulate machine code in infinite time
let codeLen = codeLength x86Code32
start uc address (address + codeLen) Nothing Nothing
-- Now print out some registers
emuPutStrLn ">>> Emulation done. Below is the CPU context"
ecx <- regRead uc X86.Ecx
edx <- regRead uc X86.Edx
emuPutStrLn $ ">>> ECX = 0x" ++ showHex ecx
emuPutStrLn $ ">>> EDX = 0x" ++ showHex edx
-- Read from memory
tmp <- memRead uc address 4
emuPutStrLn $ ">>> Read 4 bytes from [0x" ++ showHex address ++
"] = 0x" ++ showHexBS tmp
case result of
Right _ -> return ()
Left err -> putStrLn $ "Failed with error " ++ show err ++ ": " ++
strerror err
testI386Jump :: IO ()
testI386Jump = do
putStrLn "==================================="
putStrLn "Emulate i386 code with jump"
result <- runEmulator $ do
-- Initialize emulator in X86-32bit mode
uc <- open ArchX86 [Mode32]
-- Map 2MB memory for this emulation
memMap uc address (2 * 1024 * 1024) [ProtAll]
-- Write machine code to be emulated to memory
memWrite uc address x86Code32Jump
-- Tracing 1 basic block with customized callback
blockHookAdd uc hookBlock () address address
-- Tracing 1 instruction at address
codeHookAdd uc hookCode () address address
-- Emulate machine code ininfinite time
let codeLen = codeLength x86Code32Jump
start uc address (address + codeLen) Nothing Nothing
emuPutStrLn ">>> Emulation done. Below is the CPU context"
case result of
Right _ -> return ()
Left err -> putStrLn $ "Failed with error " ++ show err ++ ": " ++
strerror err
-- Emulate code that loop forever
testI386Loop :: IO ()
testI386Loop = do
putStrLn "==================================="
putStrLn "Emulate i386 code that loop forever"
result <- runEmulator $ do
-- Initialize emulator in X86-32bit mode
uc <- open ArchX86 [Mode32]
-- Map 2MB memory for this emulation
memMap uc address (2 * 1024 * 1024) [ProtAll]
-- Write machine code to be emulated in memory
memWrite uc address x86Code32Loop
-- Initialize machine registers
regWrite uc X86.Ecx 0x1234
regWrite uc X86.Edx 0x7890
-- Emulate machine code in 2 seconds, so we can quit even if the code
-- loops
let codeLen = codeLength x86Code32Loop
start uc address (address + codeLen) (Just $ 2 * 1000000) Nothing
-- Now print out some registers
emuPutStrLn ">>> Emulation done. Below is the CPU context"
ecx <- regRead uc X86.Ecx
edx <- regRead uc X86.Edx
emuPutStrLn $ ">>> ECX = 0x" ++ showHex ecx
emuPutStrLn $ ">>> EDX = 0x" ++ showHex edx
case result of
Right _ -> return ()
Left err -> putStrLn $ "Failed with error " ++ show err ++ ": " ++
strerror err
-- Emulate code that read invalid memory
testI386InvalidMemRead :: IO ()
testI386InvalidMemRead = do
putStrLn "==================================="
putStrLn "Emulate i386 code that read from invalid memory"
result <- runEmulator $ do
-- Initialize emulator in X86-32bit mode
uc <- open ArchX86 [Mode32]
-- Map 2MB memory for this emulation
memMap uc address (2 * 1024 * 1024) [ProtAll]
-- Write machine code to be emulated to memory
memWrite uc address x86Code32MemRead
-- Initialize machine registers
regWrite uc X86.Ecx 0x1234
regWrite uc X86.Edx 0x7890
-- Tracing all basic block with customized callback
blockHookAdd uc hookBlock () 1 0
-- Tracing all instructions by having @beegin > @end
codeHookAdd uc hookCode () 1 0
-- Emulate machine code in infinite time
let codeLen = codeLength x86Code32MemRead
start uc address (address + codeLen) Nothing Nothing
-- Now print out some registers
emuPutStrLn ">>> Emulation done. Below is the CPU context"
ecx <- regRead uc X86.Ecx
edx <- regRead uc X86.Edx
emuPutStrLn $ ">>> ECX = 0x" ++ showHex ecx
emuPutStrLn $ ">>> EDX = 0x" ++ showHex edx
case result of
Right _ -> return ()
Left err -> putStrLn $ "Failed with error " ++ show err ++ ": " ++
strerror err
-- Emulate code that write invalid memory
testI386InvalidMemWrite :: IO ()
testI386InvalidMemWrite = do
putStrLn "==================================="
putStrLn "Emulate i386 code that write to invalid memory"
result <- runEmulator $ do
-- Initialize emulator in X86-32bit mode
uc <- open ArchX86 [Mode32]
-- Map 2MB memory for this emulation
memMap uc address (2 * 1024 * 1024) [ProtAll]
-- Write machine code to be emulated to memory
memWrite uc address x86Code32MemWrite
-- Initialize machine registers
regWrite uc X86.Ecx 0x1234
regWrite uc X86.Edx 0x7890
-- Tracing all basic blocks with customized callback
blockHookAdd uc hookBlock () 1 0
-- Tracing all instruction by having @begin > @end
codeHookAdd uc hookCode () 1 0
-- Intercept invalid memory events
memoryEventHookAdd uc HookMemReadUnmapped hookMemInvalid () 1 0
memoryEventHookAdd uc HookMemWriteUnmapped hookMemInvalid () 1 0
-- Emulate machine code in infinite time
let codeLen = codeLength x86Code32MemWrite
start uc address (address + codeLen) Nothing Nothing
-- Now print out some registers
emuPutStrLn ">>> Emulation done. Below is the CPU context"
ecx <- regRead uc X86.Ecx
edx <- regRead uc X86.Edx
emuPutStrLn $ ">>> ECX = 0x" ++ showHex ecx
emuPutStrLn $ ">>> EDX = 0x" ++ showHex edx
-- Read from memory
tmp <- memRead uc 0xaaaaaaaa 4
emuPutStrLn $ ">>> Read 4 bytes from [0x" ++ showHex 0xaaaaaaaa ++
"] = 0x" ++ showHexBS tmp
tmp <- memRead uc 0xffffffaa 4
emuPutStrLn $ ">>> Read 4 bytes from [0x" ++ showHex 0xffffffaa ++
"] = 0x" ++ showHexBS tmp
case result of
Right _ -> return ()
Left err -> putStrLn $ "Failed with error " ++ show err ++ ": " ++
strerror err
-- Emulate code that jump to invalid memory
testI386JumpInvalid :: IO ()
testI386JumpInvalid = do
putStrLn "==================================="
putStrLn "Emulate i386 code that jumps to invalid memory"
result <- runEmulator $ do
-- Initialize emulator in X86-32bit mode
uc <- open ArchX86 [Mode32]
-- Map 2MB memory for this emulation
memMap uc address (2 * 1024 * 1024) [ProtAll]
-- Write machine code to be emulated to memory
memWrite uc address x86Code32JmpInvalid
-- Initialize machine registers
regWrite uc X86.Ecx 0x1234
regWrite uc X86.Edx 0x7890
-- Tracing all basic blocks with customized callback
blockHookAdd uc hookBlock () 1 0
-- Tracing all instructions by having @begin > @end
codeHookAdd uc hookCode () 1 0
-- Emulate machine code in infinite time
let codeLen = codeLength x86Code32JmpInvalid
start uc address (address + codeLen) Nothing Nothing
-- Now print out some registers
emuPutStrLn ">>> Emulation done. Below is the CPU context"
ecx <- regRead uc X86.Ecx
edx <- regRead uc X86.Edx
emuPutStrLn $ ">>> ECX = 0x" ++ showHex ecx
emuPutStrLn $ ">>> EDX = 0x" ++ showHex edx
case result of
Right _ -> return ()
Left err -> putStrLn $ "Failed with error " ++ show err ++ ": " ++
strerror err
testI386InOut :: IO ()
testI386InOut = do
putStrLn "==================================="
putStrLn "Emulate i386 code with IN/OUT instructions"
result <- runEmulator $ do
-- Initialize emulator in X86-32bit mode
uc <- open ArchX86 [Mode32]
-- Map 2MB memory for this emulation
memMap uc address (2 * 1024 * 1024) [ProtAll]
-- Write machine code to be emulated to memory
memWrite uc address x86Code32InOut
-- Initialize machine registers
regWrite uc X86.Eax 0x1234
regWrite uc X86.Ecx 0x6789
-- Tracing all basic blocks with customized callback
blockHookAdd uc hookBlock () 1 0
-- Tracing all instructions
codeHookAdd uc hookCode () 1 0
-- uc IN instruction
inHookAdd uc hookIn () 1 0
-- uc OUT instruction
outHookAdd uc hookOut () 1 0
-- Emulate machine code in infinite time
let codeLen = codeLength x86Code32InOut
start uc address (address + codeLen) Nothing Nothing
-- Now print out some registers
emuPutStrLn ">>> Emulation done. Below is the CPU context"
eax <- regRead uc X86.Eax
ecx <- regRead uc X86.Ecx
emuPutStrLn $ ">>> EAX = 0x" ++ showHex eax
emuPutStrLn $ ">>> ECX = 0x" ++ showHex ecx
case result of
Right _ -> return ()
Left err -> putStrLn $ "Failed with error " ++ show err ++ ": " ++
strerror err
testX8664 :: IO ()
testX8664 = do
putStrLn "Emulate x86_64 code"
result <- runEmulator $ do
-- Initialize emualator in X86-64bit mode
uc <- open ArchX86 [Mode64]
-- Map 2MB memory for this emulation
memMap uc address (2 * 1024 * 1024) [ProtAll]
-- Write machine code to be emulated to memory
memWrite uc address x86Code64
-- Initialize machine registers
regWrite uc X86.Rsp (fromIntegral address + 0x200000)
regWrite uc X86.Rax 0x71f3029efd49d41d
regWrite uc X86.Rbx 0xd87b45277f133ddb
regWrite uc X86.Rcx 0xab40d1ffd8afc461
regWrite uc X86.Rdx 0x919317b4a733f01
regWrite uc X86.Rsi 0x4c24e753a17ea358
regWrite uc X86.Rdi 0xe509a57d2571ce96
regWrite uc X86.R8 0xea5b108cc2b9ab1f
regWrite uc X86.R9 0x19ec097c8eb618c1
regWrite uc X86.R10 0xec45774f00c5f682
regWrite uc X86.R11 0xe17e9dbec8c074aa
regWrite uc X86.R12 0x80f86a8dc0f6d457
regWrite uc X86.R13 0x48288ca5671c5492
regWrite uc X86.R14 0x595f72f6e4017f6e
regWrite uc X86.R15 0x1efd97aea331cccc
-- Tracing all basic blocks with customized callback
blockHookAdd uc hookBlock () 1 0
-- Tracing all instructions in the range [address, address+20]
codeHookAdd uc hookCode64 () address (address + 20)
-- Tracing all memory WRITE access (with @begin > @end)
memoryHookAdd uc HookMemWrite hookMem64 () 1 0
-- Tracing all memory READ access (with @begin > @end)
memoryHookAdd uc HookMemRead hookMem64 () 1 0
-- Emulate machine code in infinite time (last param = Nothing), or
-- when finishing all the code
let codeLen = codeLength x86Code64
start uc address (address + codeLen) Nothing Nothing
-- Now print out some registers
emuPutStrLn ">>> Emulation done. Below is the CPU context"
rax <- regRead uc X86.Rax
rbx <- regRead uc X86.Rbx
rcx <- regRead uc X86.Rcx
rdx <- regRead uc X86.Rdx
rsi <- regRead uc X86.Rsi
rdi <- regRead uc X86.Rdi
r8 <- regRead uc X86.R8
r9 <- regRead uc X86.R9
r10 <- regRead uc X86.R10
r11 <- regRead uc X86.R11
r12 <- regRead uc X86.R12
r13 <- regRead uc X86.R13
r14 <- regRead uc X86.R14
r15 <- regRead uc X86.R15
emuPutStrLn $ ">>> RAX = 0x" ++ showHex rax
emuPutStrLn $ ">>> RBX = 0x" ++ showHex rbx
emuPutStrLn $ ">>> RCX = 0x" ++ showHex rcx
emuPutStrLn $ ">>> RDX = 0x" ++ showHex rdx
emuPutStrLn $ ">>> RSI = 0x" ++ showHex rsi
emuPutStrLn $ ">>> RDI = 0x" ++ showHex rdi
emuPutStrLn $ ">>> R8 = 0x" ++ showHex r8
emuPutStrLn $ ">>> R9 = 0x" ++ showHex r9
emuPutStrLn $ ">>> R10 = 0x" ++ showHex r10
emuPutStrLn $ ">>> R11 = 0x" ++ showHex r11
emuPutStrLn $ ">>> R12 = 0x" ++ showHex r12
emuPutStrLn $ ">>> R13 = 0x" ++ showHex r13
emuPutStrLn $ ">>> R14 = 0x" ++ showHex r14
emuPutStrLn $ ">>> R15 = 0x" ++ showHex r15
case result of
Right _ -> return ()
Left err -> putStrLn $ "Failed with error " ++ show err ++ ": " ++
strerror err
testX8664Syscall :: IO ()
testX8664Syscall = do
putStrLn "==================================="
putStrLn "Emulate x86_64 code with 'syscall' instruction"
result <- runEmulator $ do
-- Initialize emulator in X86-64bit mode
uc <- open ArchX86 [Mode64]
-- Map 2MB memory for this emulation
memMap uc address (2 * 1024 * 1024) [ProtAll]
-- Write machine code to be emulated to memory
memWrite uc address x86Code64Syscall
-- Hook interrupts for syscall
syscallHookAdd uc hookSyscall () 1 0
-- Initialize machine registers
regWrite uc X86.Rax 0x100
-- Emulate machine code in infinite time (last param = Nothing), or
-- when finishing all code
let codeLen = codeLength x86Code64Syscall
start uc address (address + codeLen) Nothing Nothing
-- Now print out some registers
emuPutStrLn ">>> Emulation done. Below is the CPU context"
rax <- regRead uc X86.Rax
emuPutStrLn $ ">>> RAX = 0x" ++ showHex rax
case result of
Right _ -> return ()
Left err -> putStrLn $ "Failed with error " ++ show err ++ ": " ++
strerror err
testX8616 :: IO ()
testX8616 = do
putStrLn "Emulate x86 16-bit code"
result <- runEmulator $ do
-- Initialize emulator in X86-16bit mode
uc <- open ArchX86 [Mode16]
-- Map 8KB memory for this emulation
memMap uc 0 (8 * 1024) [ProtAll]
-- Write machine code to be emulated in memory
memWrite uc 0 x86Code16
-- Initialize machine registers
regWrite uc X86.Eax 7
regWrite uc X86.Ebx 5
regWrite uc X86.Esi 6
-- Emulate machine code in infinite time (last param = Nothing), or
-- when finishing all the code
let codeLen = codeLength x86Code16
start uc 0 codeLen Nothing Nothing
-- Now print out some registers
emuPutStrLn ">>> Emulation done. Below is the CPU context"
-- Read from memory
tmp <- memRead uc 11 1
emuPutStrLn $ ">>> Read 1 bytes from [0x" ++ showHex 11 ++
"] = 0x" ++ showHexBS tmp
case result of
Right _ -> return ()
Left err -> putStrLn $ "Failed with error " ++ show err ++ ": " ++
strerror err
main :: IO ()
main = do
progName <- getProgName
args <- getArgs
case args of
["-32"] -> do
testI386
testI386InOut
testI386Jump
testI386Loop
testI386InvalidMemRead
testI386InvalidMemWrite
testI386JumpInvalid
["-64"] -> do
testX8664
testX8664Syscall
["-16"] -> testX8616
-- Test memleak
["-0"] -> testI386
_ -> putStrLn $ "Syntax: " ++ progName ++ " <-16|-32|-64>"
| petmac/unicorn | bindings/haskell/samples/SampleX86.hs | gpl-2.0 | 23,004 | 0 | 17 | 7,281 | 5,369 | 2,580 | 2,789 | 414 | 5 |
{-# LANGUAGE OverloadedStrings #-}
module InnerEar.Widgets.ScoreGraphs where
import Reflex
import Reflex.Dom
import Data.Map
import Control.Monad
import qualified Data.Text as T
import Data.Monoid((<>))
import Data.Maybe (fromJust)
import InnerEar.Types.Frequency
import InnerEar.Widgets.Utility
import InnerEar.Widgets.Lines
import InnerEar.Types.Score
import InnerEar.Types.GScore
import InnerEar.Widgets.Labels
import InnerEar.Widgets.Bars
import InnerEar.Widgets.Circles
--a list of frequencies (a list for the x axis)
xPoints :: [Double]
xPoints = [0, 1 .. 10000] -- :: [Frequency]
--a list to generate points in the y axis
linearGraphYPoints :: [Double]
linearGraphYPoints = fmap (\x -> x) xPoints
--a list to generate points in the y axis
steepGraphYpoints :: [Double]
steepGraphYpoints = fmap (\x -> (x*x)) xPoints
gradualGrapYpoints :: [Double]
gradualGrapYpoints = fmap (\x -> sqrt x) xPoints
flatGraphYpoints :: [Double]
flatGraphYpoints = fmap (\x -> 100) xPoints
--a graph generator for spectral shapes
graphGen :: MonadWidget t m => [Double] -> [Double] -> m ()
graphGen xPoints yPoints= do
let xAndYPoints = zip xPoints yPoints
shapeLine (constDyn "polyline") xAndYPoints
return ()
--an oval graph generator
graphGenOval :: MonadWidget t m => Dynamic t (Maybe GScore) -> m ()
graphGenOval score = elClass "div" "graphGenOval" $ do
gamifiedGraphLabel "ovalGraphLabel" score
ovalScoreBar score
return ()
--a cirular graph generator
graphGenCircular :: MonadWidget t m => Dynamic t (Maybe GScore) -> m ()
graphGenCircular score = elClass "div" "graphGenCircular" $ do
gamifiedGraphLabel "circularGrapLabel" score
percentageCircleGraph score
return ()
| luisnavarrodelangel/InnerEar | src/InnerEar/Widgets/ScoreGraphs.hs | gpl-3.0 | 1,725 | 0 | 10 | 282 | 472 | 256 | 216 | 42 | 1 |
{-# LANGUAGE DeriveDataTypeable, TemplateHaskell #-}
module BinLists where
import Prelude hiding ((+), (*), (++), (&&),(||),not)
import HipSpec
import Control.Applicative
data Bin = One | ZeroAnd Bin | OneAnd Bin deriving (Show, Eq, Ord, Typeable)
data Nat = Z | S Nat deriving (Show,Eq,Ord,Typeable)
instance Names Bin where names _ = ["a","b","c"]
instance Names Nat where names _ = ["x","y","z"]
{-
toNat :: Bin -> Nat
toNat = toNatFrom (S Z)
toNatFrom :: Nat -> Bin -> Nat
toNatFrom k One = k
toNatFrom k (ZeroAnd xs) = toNatFrom (k + k) xs
toNatFrom k (OneAnd xs) = k + toNatFrom (k + k) xs
-}
toNat :: Bin -> Nat
toNat One = S Z
toNat (ZeroAnd xs) = toNat xs + toNat xs
toNat (OneAnd xs) = S (toNat xs + toNat xs)
infixl 6 +
infixl 7 *
(+) :: Nat -> Nat -> Nat
Z + m = m
S n + m = S (n + m)
(*) :: Nat -> Nat -> Nat
Z * _ = Z
S n * m = m + (n * m)
s :: Bin -> Bin
s One = ZeroAnd One
s (ZeroAnd xs) = OneAnd xs
s (OneAnd xs) = ZeroAnd (s xs)
plus :: Bin -> Bin -> Bin
plus One xs = s xs
plus xs@ZeroAnd{} One = s xs
plus xs@OneAnd{} One = s xs
plus (ZeroAnd xs) (ZeroAnd ys) = ZeroAnd (plus xs ys)
plus (ZeroAnd xs) (OneAnd ys) = OneAnd (plus xs ys)
plus (OneAnd xs) (ZeroAnd ys) = OneAnd (plus xs ys)
plus (OneAnd xs) (OneAnd ys) = ZeroAnd (s (plus xs ys))
prop_s :: Bin -> Prop Nat
prop_s n = toNat (s n) =:= S (toNat n)
prop_plus :: Bin -> Bin -> Prop Nat
prop_plus x y = toNat (x `plus` y) =:= toNat x + toNat y
{-
main :: IO ()
main = hipSpec $(fileName)
[ vars ["x", "y", "z"] (error "Nat type" :: Nat)
, vars ["a", "b", "c"] (error "Bin type" :: Bin)
, fun1 "toNat" toNat
, fun0 "One" One
, fun1 "ZeroAnd" ZeroAnd
, fun1 "OneAnd" OneAnd
, fun1 "s" s
, fun2 "plus" plus
, fun0 "Z" Z
, fun1 "S" S
, fun2 "+" (+)
]
-}
instance Arbitrary Bin where
arbitrary = sized arbBin
where
arbBin sz = frequency
[ (1, return One)
, (sz, ZeroAnd <$> arbBin (sz `div` 2))
, (sz, OneAnd <$> arbBin (sz `div` 2))
]
instance Enum Nat where
toEnum 0 = Z
toEnum n = S (toEnum (pred n))
fromEnum Z = 0
fromEnum (S n) = succ (fromEnum n)
instance Arbitrary Nat where
arbitrary = sized $ \sz -> do
x <- choose (0,round (sqrt (toEnum sz :: Double)))
return (toEnum x)
| danr/hipspec | examples/BinLists.hs | gpl-3.0 | 2,297 | 2 | 17 | 602 | 938 | 488 | 450 | 52 | 1 |
--
-- Epanet.hs: EPANET Toolkit module in Haskell
--
-- Author:
-- Steffen Macke ([email protected])
--
-- Copyright (C) 2013 Steffen Macke (http://epanet.de)
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, version 3 of the License
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http:--www.gnu.org/licenses/>.
--
{-# LANGUAGE ForeignFunctionInterface #-}
module Epanet where
import Foreign (alloca, Int64, peek)
import Foreign.C
import Foreign.Ptr (Ptr, nullPtr)
import System.IO.Unsafe (unsafePerformIO)
-- Required only for setPattern
-- import qualified Data.Vector.Storable as DVS
en_ELEVATION :: Int
en_ELEVATION = 0 -- Node parameters
en_BASEDEMAND :: Int
en_BASEDEMAND = 1
en_PATTERN :: Int
en_PATTERN = 2
en_EMITTER :: Int
en_EMITTER = 3
en_INITQUAL :: Int
en_INITQUAL = 4
en_SOURCEQUAL :: Int
en_SOURCEQUAL = 5
en_SOURCEPAT :: Int
en_SOURCEPAT = 6
en_SOURCETYPE :: Int
en_SOURCETYPE = 7
en_TANKLEVEL :: Int
en_TANKLEVEL = 8
en_DEMAND :: Int
en_DEMAND = 9
en_HEAD :: Int
en_HEAD = 10
en_PRESSURE :: Int
en_PRESSURE = 11
en_QUALITY :: Int
en_QUALITY = 12
en_SOURCEMASS :: Int
en_SOURCEMASS = 13
en_INITVOLUME :: Int
en_INITVOLUME = 14
en_MIXMODEL :: Int
en_MIXMODEL = 15
en_MIXZONEVOL :: Int
en_MIXZONEVOL = 16
en_TANKDIAM :: Int
en_TANKDIAM = 17
en_MINVOLUME :: Int
en_MINVOLUME = 18
en_VOLCURVE :: Int
en_VOLCURVE = 19
en_MINLEVEL :: Int
en_MINLEVEL = 20
en_MAXLEVEL :: Int
en_MAXLEVEL = 21
en_MIXFRACTION :: Int
en_MIXFRACTION = 22
en_TANK_KBULK :: Int
en_TANK_KBULK = 23
en_DIAMETER :: Int
en_DIAMETER = 0 -- Link parameters
en_LENGTH :: Int
en_LENGTH = 1
en_ROUGHNESS :: Int
en_ROUGHNESS = 2
en_MINORLOSS :: Int
en_MINORLOSS = 3
en_INITSTATUS :: Int
en_INITSTATUS = 4
en_INITSETTING :: Int
en_INITSETTING = 5
en_KBULK :: Int
en_KBULK = 6
en_KWALL :: Int
en_KWALL = 7
en_FLOW :: Int
en_FLOW = 8
en_VELOCITY :: Int
en_VELOCITY = 9
en_HEADLOSS :: Int
en_HEADLOSS = 10
en_STATUS :: Int
en_STATUS = 11
en_SETTING :: Int
en_SETTING = 12
en_ENERGY :: Int
en_ENERGY = 13
en_DURATION :: Int
en_DURATION = 0 -- Time parameters
en_HYDSTEP :: Int
en_HYDSTEP = 1
en_QUALSTEP :: Int
en_QUALSTEP = 2
en_PATTERNSTEP :: Int
en_PATTERNSTEP = 3
en_PATTERNSTART :: Int
en_PATTERNSTART= 4
en_REPORTSTEP :: Int
en_REPORTSTEP = 5
en_REPORTSTART :: Int
en_REPORTSTART = 6
en_RULESTEP :: Int
en_RULESTEP = 7
en_STATISTIC :: Int
en_STATISTIC = 8
en_PERIODS :: Int
en_PERIODS = 9
en_NODECOUNT :: Int
en_NODECOUNT = 0 -- Component counts
en_TANKCOUNT :: Int
en_TANKCOUNT = 1
en_LINKCOUNT :: Int
en_LINKCOUNT = 2
en_PATCOUNT :: Int
en_PATCOUNT = 3
en_CURVECOUNT :: Int
en_CURVECOUNT = 4
en_CONTROLCOUNT :: Int
en_CONTROLCOUNT= 5
en_JUNCTION :: Int
en_JUNCTION = 0 -- Node types
en_RESERVOIR :: Int
en_RESERVOIR = 1
en_TANK :: Int
en_TANK = 2
en_CVPIPE :: Int
en_CVPIPE = 0 -- Link types.
en_PIPE :: Int
en_PIPE = 1 -- See LinkType in TYPES.H
en_PUMP :: Int
en_PUMP = 2
en_PRV :: Int
en_PRV = 3
en_PSV :: Int
en_PSV = 4
en_PBV :: Int
en_PBV = 5
en_FCV :: Int
en_FCV = 6
en_TCV :: Int
en_TCV = 7
en_GPV :: Int
en_GPV = 8
en_NONE :: Int
en_NONE = 0 -- Quality analysis types.
en_CHEM :: Int
en_CHEM = 1 -- See QualType in TYPES.H
en_AGE :: Int
en_AGE = 2
en_TRACE :: Int
en_TRACE = 3
en_CONCEN :: Int
en_CONCEN = 0 -- Source quality types.
en_MASS :: Int
en_MASS = 1 -- See SourceType in TYPES.H.
en_SETPOINT :: Int
en_SETPOINT = 2
en_FLOWPACED :: Int
en_FLOWPACED = 3
en_CFS :: Int
en_CFS = 0 -- Flow units types.
en_GPM :: Int
en_GPM = 1 -- See FlowUnitsType
en_MGD :: Int
en_MGD = 2 -- in TYPES.H.
en_IMGD :: Int
en_IMGD = 3
en_AFD :: Int
en_AFD = 4
en_LPS :: Int
en_LPS = 5
en_LPM :: Int
en_LPM = 6
en_MLD :: Int
en_MLD = 7
en_CMH :: Int
en_CMH = 8
en_CMD :: Int
en_CMD = 9
en_TRIALS :: Int
en_TRIALS = 0 -- Misc. options
en_ACCURACY :: Int
en_ACCURACY = 1
en_TOLERANCE :: Int
en_TOLERANCE = 2
en_EMITEXPON :: Int
en_EMITEXPON = 3
en_DEMANDMULT :: Int
en_DEMANDMULT = 4
en_LOWLEVEL :: Int
en_LOWLEVEL = 0 -- Control types.
en_HILEVEL :: Int
en_HILEVEL = 1 -- See ControlType
en_TIMER :: Int
en_TIMER = 2 -- in TYPES.H.
en_TIMEOFDAY :: Int
en_TIMEOFDAY = 3
en_AVERAGE :: Int
en_AVERAGE = 1 -- Time statistic types.
en_MINIMUM :: Int
en_MINIMUM = 2 -- See TstatType in TYPES.H
en_MAXIMUM :: Int
en_MAXIMUM = 3
en_RANGE :: Int
en_RANGE = 4
en_MIX1 :: Int
en_MIX1 = 0 -- Tank mixing models
en_MIX2 :: Int
en_MIX2 = 1
en_FIFO :: Int
en_FIFO = 2
en_LIFO :: Int
en_LIFO = 3
en_NOSAVE :: Int
en_NOSAVE = 0 -- Save-results-to-file flag
en_SAVE :: Int
en_SAVE = 1
en_INITFLOW :: Int
en_INITFLOW =10 -- Re-initialize flows flag
foreign import ccall unsafe "toolkit.h ENepanet" c_ENepanet :: CString -> CString -> CString -> Ptr CInt -> CInt
epanet :: String -> String -> String -> Int
epanet f1 f2 f3 = unsafePerformIO $
withCString f1 $ \cf1 ->
withCString f2 $ \cf2 ->
withCString f3 $ \cf3 ->
return $ fromIntegral $ c_ENepanet cf1 cf2 cf3 nullPtr
foreign import ccall unsafe "toolkit.h ENopen" c_ENopen :: CString -> CString -> CString -> CInt
open :: String -> String -> String -> Int
open f1 f2 f3 = unsafePerformIO $
withCString f1 $ \cf1 ->
withCString f2 $ \cf2 ->
withCString f3 $ \cf3 ->
return $ fromIntegral $ c_ENopen cf1 cf2 cf3
foreign import ccall unsafe "toolkit.h ENsaveinpfile" c_ENsaveinpfile :: CString -> CInt
saveInpFile :: String -> Int
saveInpFile f1 = unsafePerformIO $
withCString f1 $ \cf1 ->
return $ fromIntegral $ c_ENsaveinpfile cf1
foreign import ccall unsafe "toolkit.h ENclose" c_ENclose :: CInt
close :: Int
close = unsafePerformIO $
return $ fromIntegral $ c_ENclose
foreign import ccall unsafe "toolkit.h ENsolveH" c_ENsolveH :: CInt
solveH :: Int
solveH = unsafePerformIO $
return $ fromIntegral $ c_ENsolveH
foreign import ccall unsafe "toolkit.h ENsaveH" c_ENsaveH :: CInt
saveH :: Int
saveH = unsafePerformIO $
return $ fromIntegral $ c_ENsaveH
foreign import ccall unsafe "toolkit.h ENopenH" c_ENopenH :: CInt
openH :: Int
openH = unsafePerformIO $
return $ fromIntegral $ c_ENopenH
foreign import ccall unsafe "toolkit.h ENinitH" c_ENinitH :: CInt -> CInt
initH :: Int -> Int
initH flag = unsafePerformIO $
return $ fromIntegral $ c_ENinitH (fromIntegral flag)
foreign import ccall unsafe "toolkit.h ENrunH" c_ENrunH :: Ptr CLong -> CInt
runH :: Either Int Int
runH = unsafePerformIO $
alloca $ \tptr -> do
let errcode = c_ENrunH tptr
if 0 == errcode
then do
t <- peek tptr
return $ Right (fromIntegral t)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENnextH" c_ENnextH :: Ptr CLong -> CInt
nextH :: Either Int Int
nextH = unsafePerformIO $
alloca $ \tptr -> do
let errcode = c_ENnextH tptr
if 0 == errcode
then do
t <- peek tptr
return $ Right (fromIntegral t)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENcloseH" c_ENcloseH :: CInt
closeH :: Int
closeH = unsafePerformIO $
return $ fromIntegral $ c_ENcloseH
foreign import ccall unsafe "toolkit.h ENsavehydfile" c_ENsavehydfile :: CString -> CInt
saveHydFile :: String -> Int
saveHydFile f = unsafePerformIO $
withCString f $ \cf ->
return $ fromIntegral $ c_ENsavehydfile cf
foreign import ccall unsafe "toolkit.h ENusehydfile" c_ENusehydfile :: CString -> CInt
useHydFile :: String -> Int
useHydFile f = unsafePerformIO $
withCString f $ \cf ->
return $ fromIntegral $ c_ENusehydfile cf
foreign import ccall unsafe "toolkit.h ENsolveQ" c_ENsolveQ :: CInt
solveQ :: Int
solveQ = unsafePerformIO $
return $ fromIntegral $ c_ENsolveQ
foreign import ccall unsafe "toolkit.h ENopenQ" c_ENopenQ :: CInt
openQ :: Int
openQ = unsafePerformIO $
return $ fromIntegral $ c_ENopenQ
foreign import ccall unsafe "toolkit.h ENinitQ" c_ENinitQ :: CInt -> CInt
initQ :: Int -> Int
initQ flag = unsafePerformIO $
return $ fromIntegral $ c_ENinitQ (fromIntegral flag)
foreign import ccall unsafe "toolkit.h ENrunQ" c_ENrunQ :: Ptr CLong -> CInt
runQ :: Either Int Int
runQ = unsafePerformIO $
alloca $ \tptr -> do
let errcode = c_ENrunQ tptr
if 0 == errcode
then do
t <- peek tptr
return $ Right (fromIntegral t)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENnextQ" c_ENnextQ :: Ptr CLong -> CInt
nextQ :: Either Int Int
nextQ = unsafePerformIO $
alloca $ \tptr -> do
let errcode = c_ENnextQ tptr
if 0 == errcode
then do
t <- peek tptr
return $ Right (fromIntegral t)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENstepQ" c_ENstepQ :: Ptr CLong -> CInt
stepQ :: Either Int Int
stepQ = unsafePerformIO $
alloca $ \tptr -> do
let errcode = c_ENstepQ tptr
if 0 == errcode
then do
t <- peek tptr
return $ Right (fromIntegral t)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENcloseQ" c_ENcloseQ :: CInt
closeQ :: Int
closeQ = unsafePerformIO $
return $ fromIntegral $ c_ENcloseQ
foreign import ccall unsafe "toolkit.h ENwriteline" c_ENwriteline :: CString -> CInt
writeLine :: String -> Int
writeLine l = unsafePerformIO $
withCString l $ \cl ->
return $ fromIntegral $ c_ENwriteline cl
foreign import ccall unsafe "toolkit.h ENreport" c_ENreport :: CInt
report :: Int
report = unsafePerformIO $
return $ fromIntegral $ c_ENreport
foreign import ccall unsafe "toolkit.h ENresetreport" c_ENresetreport :: CInt
resetReport :: Int
resetReport = unsafePerformIO $
return $ fromIntegral $ c_ENresetreport
foreign import ccall unsafe "toolkit.h ENsetreport" c_ENsetreport :: CString -> CInt
setReport :: String -> Int
setReport f = unsafePerformIO $
withCString f $ \cf ->
return $ fromIntegral $ c_ENsetreport cf
foreign import ccall unsafe "toolkit.h ENgetcontrol" c_ENgetcontrol :: CInt -> Ptr CInt -> Ptr CInt -> Ptr CFloat -> Ptr CInt -> Ptr CFloat -> CInt
getControl :: Int -> Either Int (Int, Int, Float, Int, Float)
getControl cindex = unsafePerformIO $
alloca $ \ctypeptr -> do
alloca $ \lindexptr -> do
alloca $ \settingptr -> do
alloca $ \nindexptr -> do
alloca $ \levelptr -> do
let errcode = c_ENgetcontrol (fromIntegral cindex) ctypeptr lindexptr settingptr nindexptr levelptr
if 0 == errcode
then do
ctype <- peek ctypeptr
lindex <- peek lindexptr
setting <- peek settingptr
nindex <- peek nindexptr
level <- peek levelptr
return $ Right (fromIntegral ctype, fromIntegral lindex, realToFrac setting, fromIntegral nindex, realToFrac level)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetcount" c_ENgetcount :: CInt -> Ptr CInt -> CInt
getCount :: Int -> Either Int Int
getCount code = unsafePerformIO $
alloca $ \countptr -> do
let errcode = c_ENgetcount (fromIntegral code) countptr
if 0 == errcode
then do
count <- peek countptr
return $ Right (fromIntegral count)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetoption" c_ENgetoption :: CInt -> Ptr CFloat -> CInt
getOption :: Int -> Either Int Float
getOption code = unsafePerformIO $
alloca $ \valueptr -> do
let errcode = c_ENgetoption (fromIntegral code) valueptr
if 0 == errcode
then do
value <- peek valueptr
return $ Right (realToFrac value)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgettimeparam" c_ENgettimeparam :: CInt -> Ptr CLong -> CInt
getTimeParam :: Int -> Either Int Int64
getTimeParam code = unsafePerformIO $
alloca $ \valueptr -> do
let errcode = c_ENgettimeparam (fromIntegral code) valueptr
if 0 == errcode
then do
value <- peek valueptr
return $ Right (fromIntegral value)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetflowunits" c_ENgetflowunits :: Ptr CInt -> CInt
getFlowUnits :: Either Int Int
getFlowUnits = unsafePerformIO $
alloca $ \codeptr -> do
let errcode = c_ENgetflowunits codeptr
if 0 == errcode
then do
code <- peek codeptr
return $ Right (fromIntegral code)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetpatternindex" c_ENgetpatternindex :: CString -> Ptr CInt -> CInt
getPatternIndex :: String -> Either Int Int
getPatternIndex id = unsafePerformIO $
withCString id $ \cid ->
alloca $ \indexptr -> do
let errcode = c_ENgetpatternindex cid indexptr
if 0 == errcode
then do
index <- peek indexptr
return $ Right (fromIntegral index)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetpatternid" c_ENgetpatternid :: CInt -> CString -> CInt
getPatternId :: Int -> Either Int String
getPatternId index = unsafePerformIO $
alloca $ \idptr -> do
let errcode = c_ENgetpatternid (fromIntegral index) idptr
if 0 == errcode
then do
id <- peekCString idptr
return $ Right id
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetpatternlen" c_ENgetpatternlen :: CInt -> Ptr CInt -> CInt
getPatternLen :: Int -> Either Int Int
getPatternLen index = unsafePerformIO $
alloca $ \lenptr -> do
let errcode = c_ENgetpatternlen (fromIntegral index) lenptr
if 0 == errcode
then do
len <- peek lenptr
return $ Right (fromIntegral len)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetpatternvalue" c_ENgetpatternvalue :: CInt -> CInt -> Ptr CFloat -> CInt
getPatternValue :: Int -> Int -> Either Int Float
getPatternValue index period = unsafePerformIO $
alloca $ \valueptr -> do
let errcode = c_ENgetpatternvalue (fromIntegral index) (fromIntegral period) valueptr
if 0 == errcode
then do
value <- peek valueptr
return $ Right (realToFrac value)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetqualtype" c_ENgetqualtype :: Ptr CInt -> Ptr CInt -> CInt
getQualType :: Either Int (Int, Int)
getQualType = unsafePerformIO $
alloca $ \qualcodeptr -> do
alloca $ \tracenodeptr -> do
let errcode = c_ENgetqualtype qualcodeptr tracenodeptr
if 0 == errcode
then do
qualcode <- peek qualcodeptr
tracenode <- peek tracenodeptr
return $ Right (fromIntegral qualcode, fromIntegral tracenode)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgeterror" c_ENgeterror :: CInt -> CString -> CInt -> CInt
getError :: Int -> Int -> Either Int String
getError code n = unsafePerformIO $
withCString (replicate n ' ') $ \cerrmsg -> do
let errcode = c_ENgeterror (fromIntegral code) cerrmsg (fromIntegral n)
if 0 == errcode
then do
errmsg <- peekCString cerrmsg
return $ Right errmsg
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetnodeindex" c_ENgetnodeindex :: CString -> Ptr CInt -> CInt
getNodeIndex :: String -> Either Int Int
getNodeIndex id = unsafePerformIO $
withCString id $ \cid ->
alloca $ \indexptr -> do
let errcode = c_ENgetnodeindex cid indexptr
if 0 == errcode
then do
index <- peek indexptr
return $ Right (fromIntegral index)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetnodeid" c_ENgetnodeid :: CInt -> CString -> CInt
getNodeId :: Int -> Either Int String
getNodeId index = unsafePerformIO $
alloca $ \idptr -> do
let errcode = c_ENgetnodeid (fromIntegral index) idptr
if 0 == errcode
then do
id <- peekCString idptr
return $ Right id
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetnodetype" c_ENgetnodetype :: CInt -> Ptr CInt -> CInt
getNodeType :: Int -> Either Int Int
getNodeType index = unsafePerformIO $
alloca $ \typeptr -> do
let errcode = c_ENgetnodetype (fromIntegral index) typeptr
if 0 == errcode
then do
t <- peek typeptr
return $ Right (fromIntegral t)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetnodevalue" c_ENgetnodevalue :: CInt -> CInt -> Ptr CFloat -> CInt
getNodeValue :: Int -> Int -> Either Int Float
getNodeValue index code = unsafePerformIO $
alloca $ \valueptr -> do
let errcode = c_ENgetnodevalue (fromIntegral index) (fromIntegral code) valueptr
if 0 == errcode
then do
value <- peek valueptr
return $ Right (realToFrac value)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetlinkindex" c_ENgetlinkindex :: CString -> Ptr CInt -> CInt
getLinkIndex :: String -> Either Int Int
getLinkIndex id = unsafePerformIO $
withCString id $ \cid ->
alloca $ \indexptr -> do
let errcode = c_ENgetlinkindex cid indexptr
if 0 == errcode
then do
index <- peek indexptr
return $ Right (fromIntegral index)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetlinkid" c_ENgetlinkid :: CInt -> CString -> CInt
getLinkId :: Int -> Either Int String
getLinkId index = unsafePerformIO $
alloca $ \idptr -> do
let errcode = c_ENgetlinkid (fromIntegral index) idptr
if 0 == errcode
then do
id <- peekCString idptr
return $ Right id
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetlinktype" c_ENgetlinktype :: CInt -> Ptr CInt -> CInt
getLinkType :: Int -> Either Int Int
getLinkType index = unsafePerformIO $
alloca $ \typeptr -> do
let errcode = c_ENgetlinktype (fromIntegral index) typeptr
if 0 == errcode
then do
t <- peek typeptr
return $ Right (fromIntegral t)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetlinknodes" c_ENgetlinknodes :: CInt -> Ptr CInt -> Ptr CInt -> CInt
getLinkNodes :: Int -> Either Int (Int, Int)
getLinkNodes index = unsafePerformIO $
alloca $ \node1ptr -> do
alloca $ \node2ptr -> do
let errcode = c_ENgetlinknodes (fromIntegral index) node1ptr node2ptr
if 0 == errcode
then do
node1 <- peek node1ptr
node2 <- peek node2ptr
return $ Right (fromIntegral node1, fromIntegral node2)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetlinkvalue" c_ENgetlinkvalue :: CInt -> CInt -> Ptr CFloat -> CInt
getLinkValue :: Int -> Int -> Either Int Float
getLinkValue index code = unsafePerformIO $
alloca $ \valueptr -> do
let errcode = c_ENgetlinkvalue (fromIntegral index) (fromIntegral code) valueptr
if 0 == errcode
then do
value <- peek valueptr
return $ Right (realToFrac value)
else do
return $ Left (fromIntegral errcode)
foreign import ccall unsafe "toolkit.h ENgetversion" c_ENgetversion :: Ptr CInt -> CInt
getVersion :: Int
getVersion = unsafePerformIO $
alloca $ \vptr -> do
if 0 == (c_ENgetversion vptr)
then do
v <- peek vptr
return $ fromIntegral v
else do
return $ fromIntegral 0
foreign import ccall unsafe "toolkit.h ENsetcontrol" c_ENsetcontrol :: CInt -> CInt -> CInt -> CFloat -> CInt -> CFloat -> CInt
setControl :: Int -> Int -> Int -> Float -> Int -> Float -> Int
setControl cindex ctype lindex setting nindex level = unsafePerformIO $
return $ fromIntegral $ c_ENsetcontrol (fromIntegral cindex) (fromIntegral ctype) (fromIntegral lindex) (realToFrac setting) (fromIntegral nindex) (realToFrac level)
foreign import ccall unsafe "toolkit.h ENsetnodevalue" c_ENsetnodevalue :: CInt -> CInt -> CFloat -> CInt
setNodeValue :: Int -> Int -> Float -> Int
setNodeValue index code v = unsafePerformIO $
return $ fromIntegral $ c_ENsetnodevalue (fromIntegral index) (fromIntegral code) (realToFrac v)
foreign import ccall unsafe "toolkit.h ENsetlinkvalue" c_ENsetlinkvalue :: CInt -> CInt -> CFloat -> CInt
setLinkValue :: Int -> Int -> Float -> Int
setLinkValue index code v = unsafePerformIO $
return $ fromIntegral $ c_ENsetlinkvalue (fromIntegral index) (fromIntegral code) (realToFrac v)
foreign import ccall unsafe "toolkit.h ENaddpattern" c_ENaddpattern :: CString -> CInt
addPattern :: String -> Int
addPattern p = unsafePerformIO $
withCString p $ \cp -> do
return $ fromIntegral $ c_ENaddpattern cp
-- Use setPatternValue instead
-- foreign import ccall unsafe "toolkit.h ENsetpattern" c_ENsetpattern :: CInt -> Ptr CFloat -> CInt -> CInt
-- setPattern :: Int -> DVS.Vector CFloat -> Int
-- setPattern index f = unsafePerformIO $
-- DVS.unsafeWith f $ \fptr (return (fromIntegral (c_ENsetpattern (fromIntegral index) fptr (fromIntegral (DVS.length f))))
foreign import ccall unsafe "toolkit.h ENsetpatternvalue" c_ENsetpatternvalue :: CInt -> CInt -> CFloat -> CInt
setPatternValue :: Int -> Int -> Float -> Int
setPatternValue index period value = unsafePerformIO $
return $ fromIntegral $ c_ENsetpatternvalue (fromIntegral index) (fromIntegral period) (realToFrac value)
foreign import ccall unsafe "toolkit.h ENsettimeparam" c_ENsettimeparam :: CInt -> CLong -> CInt
setTimeParam :: Int -> Int -> Int
setTimeParam code value = unsafePerformIO $
return $ fromIntegral $ c_ENsettimeparam (fromIntegral code) (fromIntegral value)
foreign import ccall unsafe "toolkit.h ENsetoption" c_ENsetoption :: CInt -> CFloat -> CInt
setOption :: Int -> Float -> Int
setOption code v = unsafePerformIO $
return $ fromIntegral $ c_ENsetoption (fromIntegral code) (realToFrac v)
foreign import ccall unsafe "toolkit.h ENsetstatusreport" c_ENsetstatusreport :: CInt -> CInt
setStatusReport :: Int -> Int
setStatusReport code = unsafePerformIO $
return $ fromIntegral $ c_ENsetstatusreport (fromIntegral code)
foreign import ccall unsafe "toolkit.h ENsetqualtype" c_ENsetqualtype :: CInt -> CString -> CString -> CString -> CInt
setQualType :: Int -> String -> String -> String -> Int
setQualType qualcode chemname chemunits tracenode = unsafePerformIO $
withCString chemname $ \cchemname -> do
withCString chemunits $ \cchemunits -> do
withCString tracenode $ \ctracenode -> do
return $ fromIntegral $ c_ENsetqualtype (fromIntegral qualcode) cchemname cchemunits ctracenode
| sdteffen/epanet-haskell | Epanet.hs | gpl-3.0 | 23,325 | 0 | 32 | 5,127 | 6,679 | 3,448 | 3,231 | 641 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module BTFO where
import qualified Data.Text as T
import Data.Text (Text)
import qualified Database as DB
import Web.Telegram.API.Bot hiding (from)
import Data.Maybe
countBTFO :: Text -> Message -> IO ()
countBTFO txt Message{..} =
case entities of
Nothing -> return ()
Just es -> do
let ments = catMaybes . map (fmap user_id . me_user) $ es
DB.runDB $ DB.addBTFO ments txt
DB.runDB $ DB.addBTFOName (collectBTFOText txt) txt
data Persons = Persons
{ mentions :: [Text]
, accomulator :: Maybe Text
} deriving Show
collectBTFOText :: Text -> [Text]
collectBTFOText txt = mentions . addLast . T.foldl' findPersons (Persons [] Nothing) $ txt
where
findPersons :: Persons -> Char -> Persons
findPersons (Persons xs (Just acc)) ' ' = Persons ((T.reverse acc) : xs) Nothing
findPersons (Persons xs (Just acc)) c = Persons xs (Just $ T.cons c acc)
findPersons (Persons xs Nothing) '@' = Persons xs (Just "")
findPersons (Persons xs Nothing) _ = Persons xs Nothing
addLast :: Persons -> Persons
addLast (Persons xs (Just p)) = Persons ((T.reverse p) : xs) Nothing
addLast (Persons xs Nothing) = Persons xs Nothing
| fgaray/telegram-bot | src/BTFO.hs | gpl-3.0 | 1,337 | 0 | 18 | 354 | 479 | 248 | 231 | 30 | 5 |
{-
emacs2nix - Generate Nix expressions for Emacs packages
Copyright (C) 2016 Thomas Tuegel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Distribution.Nix.Package.Melpa ( Package(..), Recipe(..), expression ) where
import Data.Fix
import Data.Text ( Text )
import qualified Data.Text as T
import Data.Version ( Version, showVersion )
import Nix.Expr
import Distribution.Nix.Builtin
import Distribution.Nix.Fetch ( Fetch, fetchExpr, importFetcher )
import Distribution.Nix.Name
data Package
= Package
{ pname :: !Name
, version :: !Version
, fetch :: !Fetch
, deps :: ![Name]
, recipe :: !Recipe
}
data Recipe
= Recipe { ename :: !Text
, commit :: !Text
, sha256 :: !Text
}
expression :: Package -> NExpr
expression (Package {..}) = (mkSym "callPackage") @@ drv @@ emptySet where
drv = mkFunction args body
emptySet = mkNonRecSet []
requires = map fromName deps
args = (flip mkParamset False . map optionalBuiltins)
("lib" : "melpaBuild" : "fetchurl" : importFetcher fetch : requires)
body = ((@@) (mkSym "melpaBuild") . mkNonRecSet)
[ "pname" `bindTo` mkStr (fromName pname)
, "ename" `bindTo` mkStr ename
, "version" `bindTo` mkStr (T.pack $ showVersion version)
, "src" `bindTo` fetchExpr fetch
, "recipe" `bindTo` fetchRecipe
, "packageRequires" `bindTo` mkList (map mkSym requires)
, "meta" `bindTo` meta
]
where
Recipe { ename, commit } = recipe
meta = mkNonRecSet
[ "homepage" `bindTo` mkStr homepage
, "license" `bindTo` license
]
where
homepage = T.append "https://melpa.org/#/" ename
license =
Fix (NSelect (mkSym "lib")
[StaticKey "licenses", StaticKey "free"] Nothing)
fetchRecipe = ((@@) (mkSym "fetchurl") . mkNonRecSet)
[ "url" `bindTo` mkStr
(T.concat
[ "https://raw.githubusercontent.com/milkypostman/melpa/"
, commit
, "/recipes/"
, ename
])
, "sha256" `bindTo` mkStr (sha256 recipe)
, "name" `bindTo` mkStr "recipe"
]
| ttuegel/emacs2nix | src/Distribution/Nix/Package/Melpa.hs | gpl-3.0 | 3,081 | 0 | 15 | 882 | 611 | 348 | 263 | 73 | 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.Blogger.Posts.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a post by blog id and post id.
--
-- /See:/ <https://developers.google.com/blogger/docs/3.0/getting_started Blogger API v3 Reference> for @blogger.posts.delete@.
module Network.Google.Resource.Blogger.Posts.Delete
(
-- * REST Resource
PostsDeleteResource
-- * Creating a Request
, postsDelete
, PostsDelete
-- * Request Lenses
, pdXgafv
, pdUploadProtocol
, pdAccessToken
, pdUploadType
, pdBlogId
, pdPostId
, pdCallback
) where
import Network.Google.Blogger.Types
import Network.Google.Prelude
-- | A resource alias for @blogger.posts.delete@ method which the
-- 'PostsDelete' request conforms to.
type PostsDeleteResource =
"v3" :>
"blogs" :>
Capture "blogId" Text :>
"posts" :>
Capture "postId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes a post by blog id and post id.
--
-- /See:/ 'postsDelete' smart constructor.
data PostsDelete =
PostsDelete'
{ _pdXgafv :: !(Maybe Xgafv)
, _pdUploadProtocol :: !(Maybe Text)
, _pdAccessToken :: !(Maybe Text)
, _pdUploadType :: !(Maybe Text)
, _pdBlogId :: !Text
, _pdPostId :: !Text
, _pdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PostsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pdXgafv'
--
-- * 'pdUploadProtocol'
--
-- * 'pdAccessToken'
--
-- * 'pdUploadType'
--
-- * 'pdBlogId'
--
-- * 'pdPostId'
--
-- * 'pdCallback'
postsDelete
:: Text -- ^ 'pdBlogId'
-> Text -- ^ 'pdPostId'
-> PostsDelete
postsDelete pPdBlogId_ pPdPostId_ =
PostsDelete'
{ _pdXgafv = Nothing
, _pdUploadProtocol = Nothing
, _pdAccessToken = Nothing
, _pdUploadType = Nothing
, _pdBlogId = pPdBlogId_
, _pdPostId = pPdPostId_
, _pdCallback = Nothing
}
-- | V1 error format.
pdXgafv :: Lens' PostsDelete (Maybe Xgafv)
pdXgafv = lens _pdXgafv (\ s a -> s{_pdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pdUploadProtocol :: Lens' PostsDelete (Maybe Text)
pdUploadProtocol
= lens _pdUploadProtocol
(\ s a -> s{_pdUploadProtocol = a})
-- | OAuth access token.
pdAccessToken :: Lens' PostsDelete (Maybe Text)
pdAccessToken
= lens _pdAccessToken
(\ s a -> s{_pdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pdUploadType :: Lens' PostsDelete (Maybe Text)
pdUploadType
= lens _pdUploadType (\ s a -> s{_pdUploadType = a})
pdBlogId :: Lens' PostsDelete Text
pdBlogId = lens _pdBlogId (\ s a -> s{_pdBlogId = a})
pdPostId :: Lens' PostsDelete Text
pdPostId = lens _pdPostId (\ s a -> s{_pdPostId = a})
-- | JSONP
pdCallback :: Lens' PostsDelete (Maybe Text)
pdCallback
= lens _pdCallback (\ s a -> s{_pdCallback = a})
instance GoogleRequest PostsDelete where
type Rs PostsDelete = ()
type Scopes PostsDelete =
'["https://www.googleapis.com/auth/blogger"]
requestClient PostsDelete'{..}
= go _pdBlogId _pdPostId _pdXgafv _pdUploadProtocol
_pdAccessToken
_pdUploadType
_pdCallback
(Just AltJSON)
bloggerService
where go
= buildClient (Proxy :: Proxy PostsDeleteResource)
mempty
| brendanhay/gogol | gogol-blogger/gen/Network/Google/Resource/Blogger/Posts/Delete.hs | mpl-2.0 | 4,483 | 0 | 18 | 1,125 | 779 | 452 | 327 | 109 | 1 |
{-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-}
module NicovideoTranslator.Main (main) where
import Data.Char (toLower)
import System.IO (stderr, stdout)
import System.IO.Error (catchIOError)
import Data.Data (Data)
import qualified Data.LanguageCodes as L
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Text.Format (Format, format)
import Data.Text.Format.Params (Params)
import Data.Text.Format.Types (Only(Only))
import Data.Text.IO (hPutStrLn)
import qualified Data.Text.Lazy as LT
import Data.Typeable (Typeable)
import Network.DNS.Resolver (defaultResolvConf, makeResolvSeed, withResolver)
import Network.DNS.Lookup (lookupA)
import Network.Wai.Handler.Warp (Port, run)
import System.Console.CmdArgs ( argPos
, cmdArgs
, def
, details
, explicit
, help
, name
, program
, summary
, typ
, (&=)
)
import System.Locale.SetLocale (Category(LC_CTYPE), setLocale)
import NicovideoTranslator.Proxy ( ProxyConfiguration ( ProxyConfiguration
, apiKey
, language
, upstreamHost
)
, app
)
data Translator = Translator { port :: Port
, language' :: String
, apiKey' :: String
} deriving (Show, Data, Typeable)
formatIoError :: Params ps => Format -> ps -> IO a
formatIoError fmt ps = ioError $ userError $ LT.unpack $ format fmt ps
readLanguageCode :: [Char] -> IO L.ISO639_1
readLanguageCode (x:y:[]) =
case L.fromChars (toLower x) (toLower y) of
Just lang -> return lang
_ -> formatIoError "{} is wrong language code" (Only (x:y:[]))
readLanguageCode lang = formatIoError "{} is wrong language code" (Only lang)
currentLanguage :: IO L.ISO639_1
currentLanguage = do
currentLocale <- setLocale LC_CTYPE Nothing
case currentLocale of
Just s -> readLanguageCode s
Nothing -> formatIoError "locale is not set" ()
defaultUpstreamHost :: T.Text
defaultUpstreamHost = "nmsg.nicovideo.jp"
translateCmdArgs :: String -> Translator
translateCmdArgs lang =
Translator { language' = lang &= explicit
&= name "language"
&= name "lang"
&= name "l"
&= typ "LANG"
&= help "Target language to translate to [en]"
, port = 80 &= typ "PORT"
&= help "Port number to listen [80]"
, apiKey' = def &= argPos 0 &= typ "API_KEY"
}
&= program "nicovideo-translator"
&= summary "Nico Nico Douga (ニコニコ動画) Comment Translator"
&= details
["It takes a Google Translate API key as its first argument."]
main :: IO ()
main = do
currentLang <- catchIOError currentLanguage (\_ -> return L.EN)
opts <- cmdArgs $ translateCmdArgs $ L.language currentLang
lang <- readLanguageCode $ language' opts
let portNum = port opts
hPutStrLn stdout $ LT.toStrict $
format "Running on http://0.0.0.0:{}/ (Press ^C to quit)" (Only portNum)
rs <- makeResolvSeed defaultResolvConf
resolution <- withResolver rs $
\resolver -> lookupA resolver (encodeUtf8 defaultUpstreamHost)
case resolution of
Right (resolvedHost:_) ->
let upstreamHost' = T.pack $ show resolvedHost
in do
hPutStrLn stdout $ T.concat ["Upstream: "
, defaultUpstreamHost
, " (", upstreamHost', ")"
]
let conf = ProxyConfiguration { language = lang
, upstreamHost = upstreamHost'
, apiKey = T.pack $ apiKey' opts
}
run portNum $ app conf
_ -> hPutStrLn stderr $ T.concat [ "error: failed to resolve "
, defaultUpstreamHost
]
| dahlia/nicovideo-translator | lib/NicovideoTranslator/Main.hs | agpl-3.0 | 4,714 | 0 | 20 | 1,975 | 998 | 538 | 460 | 94 | 2 |
import Debug.Trace
import Euler
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.List
candidates = map (+(-1)) primes
filter357 n =
let d = divisors n
ds = map (\m -> m + (n `div` m)) d
in all isPrime ds
prob357 = sum $ takeWhile (<10^8) $ filter filter357 candidates
main = print prob357
| jdavidberger/project-euler | prob357.hs | lgpl-3.0 | 340 | 0 | 14 | 73 | 151 | 83 | 68 | 13 | 1 |
{-# LANGUAGE RecordWildCards #-}
module Forces
( forces
)
where
import Control.Concurrent
import Linear.Affine
import RigidBody.Physics hiding (forces)
import qualified RigidBody.Physics as Physics
import qualified Types
update :: Types.Input -> Types.State -> Types.State
update i s = Types.State
{ particles = np
}
where
np = either (const $ Types.particles s) (map stateParticle . particles) next
next = bigStep (Forces [0.1]) 0.01 world
world = World
{ particles = map (mkParticle $ Types.particles s) (Types.particles s)
}
mkParticle :: [Types.Particle] -> Types.Particle -> Particle Float
mkParticle particles Types.Particle{..} = Particle
{ mass = 1
, pos = P pos
, vel = vel
, Physics.forces = []
}
stateParticle :: Particle Float -> Types.Particle
stateParticle Particle{..} = Types.Particle
{ Types.pos = pos .-. 0
, Types.vel = vel
}
forces :: MVar Types.Input -> MVar Types.State -> IO ()
forces input state = do
i <- readMVar input
modifyMVar_ state (pure . update i)
| mbernat/sdl | main/Forces.hs | unlicense | 1,074 | 0 | 13 | 247 | 369 | 198 | 171 | 29 | 1 |
{-
Created : 2013 Oct 29 (Tue) 18:57:36 by carr.
Last Modified : 2014 Mar 06 (Thu) 13:46:19 by Harold Carr.
-}
module FP07GameDef where
data Game = Game { terrain :: Pos -> Bool
, startPos :: Pos
, goal :: Pos
}
data Pos = Pos { x :: Int, y :: Int } deriving (Eq, Read, Show)
{-# ANN dyp "HLint: ignore Redundant bracket" #-}
dxp, dyp :: Pos -> Int -> Pos
dxp p d = Pos (x p + d) (y p)
dyp p d = Pos (x p) ((y p) + d)
data Move = MLeft | MRight | MUp | MDown deriving (Eq, Read, Show)
data Block = Block { b1 :: Pos, b2 :: Pos } deriving (Eq, Read, Show)
{- TODO the effect of:
newBlock b1 b2 =
if (x b1) > (x b2) || (y b1) > (y b2)
then error "Invalid block position: b1=" ++ (show b1) ++ ", b2=" + (show b2)
else Block b1 b2
-}
dxb, dyb :: Block -> Int -> Int -> Block
dxb b d1 d2 = Block (dxp (b1 b) d1) (dxp (b2 b) d2)
dyb b d1 d2 = Block (dyp (b1 b) d1) (dyp (b2 b) d2)
move :: (Block -> t1 -> t2 -> t) -> t1 -> t2 -> t1 -> t2 -> t1 -> t2 -> Block -> t
move dxyb s1 s2 e1 e2 o1 o2 b
| isStanding b = dxyb b s1 s2
| x (b1 b) == x (b2 b) = dxyb b e1 e2
| otherwise = dxyb b o1 o2
left, right, up, down :: Block -> Block
left = move dyb (-2) (-1) (-1) (-2) (-1) (-1)
right = move dyb 1 2 2 1 1 1
up = move dxb (-2) (-1) (-1) (-1) (-1) (-2)
down = move dxb 1 2 1 1 2 1
neighbors :: Block -> [(Block, Move)]
neighbors b = [(left b, MLeft), (right b, MRight), (up b, MUp), (down b, MDown)]
legalNeighbors :: Game -> Block -> [(Block, Move)]
legalNeighbors game b = Prelude.filter (\(n,_) -> isLegal game n) (neighbors b)
isStanding :: Block -> Bool
isStanding b = b1 b == b2 b
isLegal :: Game -> Block -> Bool
isLegal game b = terrain game (b1 b) && terrain game (b2 b)
-- End of file.
| haroldcarr/learn-haskell-coq-ml-etc | haskell/course/2013-11-coursera-fp-odersky-but-in-haskell/FP07GameDef.hs | unlicense | 1,858 | 0 | 12 | 568 | 844 | 452 | 392 | 32 | 1 |
-- Copyright 2017 Ondrej Sykora
--
-- 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.
-- | Contains definitions of the data types for the state of the game, the game
-- update monad, and basic functions for working inside this monad.
module HBodies.Game.State where
import Control.Applicative ((<*>), (<$>))
import qualified Control.Monad.State as MonadState
import qualified Data.Map.Strict as Map
import qualified HBodies.Asteroid.State as AsteroidState
import qualified HBodies.Bullet.State as BulletState
import qualified HBodies.Geometry as Geometry
import HBodies.Geometry ((+.))
import qualified HBodies.Inputs as Inputs
import qualified HBodies.Particle.State as ParticleState
import qualified HBodies.Player.State as PlayerState
import qualified HBodies.Time as Time
import qualified System.Random as Random
-- | The list of asteroids indexed by their IDs.
type IndexedAsteroids = Map.Map AsteroidState.Id AsteroidState.State
-- | The state of the game.
data State = GameState
{ -- | The list of asteroids in the game.
getAsteroids :: !IndexedAsteroids
-- | The list of bullets in the game.
, getBullets :: ![BulletState.State]
-- | The time when the last bullet was fired.
, getLastBulletTime :: !Time.Time
-- | The ID of the next asteroid created in the game.
, getStateNextAsteroidId :: !AsteroidState.Id
-- | The time of the last update (of in-game time).
, getLastUpdate :: !Time.Time
-- | The state of the particles in the game.
, getParticles :: [ParticleState.State]
-- | The player object.
, getPlayer :: PlayerState.State
-- | The random number generator used by the game.
, getRandomGenerator :: Random.StdGen
}
-- | Collection of updates to the game state between two frames. This is used
-- as the state in the updaet
data UpdateData = UpdateData
{ -- | The state of the game before the update.
getCurrentState :: !State
-- | The amount of in-game time that passed since the last frame.
, getDuration :: !Time.Duration
-- | The state of the inputs during the update.
, getInputState :: !Inputs.State
-- | The accumulated damage to the player.
, getPlayerDamage :: !Double
-- | The impulses of force applied to the player in this frame.
, getPlayerImpulse :: Geometry.Direction
-- | The asteroid the player collided with in this frame. Contains None
-- if there was no collision; contains the last asteroid if the player
-- collided with more than one in the same frame.
, getAsteroidCollision :: Maybe AsteroidState.State
-- | The damage inflicted to the asteroids during this frame.
, getAsteroidDamage :: Map.Map AsteroidState.Id Double
-- | The impulses applied to asteroids, e.g. from bullet hits or
-- collisions with players.
, getAsteroidImpulses :: Map.Map AsteroidState.Id Geometry.Direction
-- | The states of the asteroids in the following frame.
, getUpdatedAsteroids :: !IndexedAsteroids
-- | The states of the bullets in the following frame. Note that the list
-- is reversed before it is used in the State structure of the next frame
-- to make the order of the bullets in the list stable.
, getUpdatedBullets :: ![BulletState.State]
-- | Whether a bullet was fired this round.
, getBulletFired :: Bool
-- | The ID of the next asteroid created in the game.
, getUpdateNextAsteroidId :: !AsteroidState.Id
-- | The updated player data.
, getUpdatedPlayer :: !PlayerState.State
-- | The state of the particles in the following frame. Note that the
-- list is reversed before it is used in the State structure of the next
-- frame to make the order of the particles in the list stable.
, getUpdatedParticles :: ![ParticleState.State]
-- | The random generator used during the update. This generator is used
-- (and changed) by the functions HBodies.Game.State.random and
-- HBodies.Game.State.randomR.
, getUpdateRandomGenerator :: Random.StdGen
}
-- | The monad, in which all state updates are executed.
type Update = MonadState.State UpdateData
addNewBullet :: BulletState.State -> Update ()
addNewBullet bullet = MonadState.modify'$ \d ->
d { getUpdatedBullets = bullet:getUpdatedBullets d
, getBulletFired = True }
-- | Records damage inflicted to the given asteroid in this frame.
addAsteroidDamage :: AsteroidState.Id
-- ^ The ID of the asteroid receiving the damage.
-> Double
-- ^ The damage added to the asteroid.
-> Update ()
addAsteroidDamage asteroid_id damage = MonadState.modify'$ \d ->
let damages = getAsteroidDamage d
new_damage = damage + Map.findWithDefault 0.0 asteroid_id damages
new_damages = Map.insert asteroid_id new_damage damages
in d { getAsteroidDamage = new_damages }
-- | Records an impuls of force to the given asteroid in this frame.
addAsteroidImpulse :: AsteroidState.Id
-- ^ The ID of the asteroid receiving the impulse.
-> Geometry.Direction
-- ^ The magnitude of the impulse.
-> Update ()
addAsteroidImpulse asteroid_id impulse = MonadState.modify'$ \d ->
let impulses = getAsteroidImpulses d
old_impulse = Map.findWithDefault Geometry.zeroDirection
asteroid_id
impulses
new_impulse = impulse +. old_impulse
new_impulses = Map.insert asteroid_id new_impulse impulses
in d { getAsteroidImpulses = new_impulses }
-- | Adds player damage in the current frame.
addPlayerDamage :: Double
-- ^ The damage added to the player.
-> Update ()
addPlayerDamage damage = MonadState.modify'$ \d ->
d { getPlayerDamage = damage + getPlayerDamage d }
-- | Adds an updated asteroid to the state updates.
addUpdatedAsteroid :: AsteroidState.State
-- ^ The updated asteroid object.
-> Update ()
addUpdatedAsteroid asteroid = MonadState.modify'$ \d ->
let asteroids = getUpdatedAsteroids d
asteroid_id = AsteroidState.getId asteroid
in d { getUpdatedAsteroids = Map.insert asteroid_id asteroid asteroids }
-- | Adds an updated bullet to state updates.
addUpdatedBullet :: BulletState.State
-- ^ The updated bullet object.
-> Update ()
addUpdatedBullet bullet = MonadState.modify'$ \d ->
d { getUpdatedBullets = bullet:getUpdatedBullets d }
-- | Adds an updated particle to the state updates.
addUpdatedParticle :: ParticleState.State
-- ^ The updated particle object.
-> Update ()
addUpdatedParticle particle = MonadState.modify'$ \d ->
d { getUpdatedParticles = particle:getUpdatedParticles d }
-- | Returns the list of asteroids from the previous frame.
asteroids :: Update IndexedAsteroids
asteroids = MonadState.gets$ getAsteroids . getCurrentState
-- | Returns the asteroid with the given ID, or Nothing if no such asteroid was
-- found.
asteroidById :: AsteroidState.Id -> Update (Maybe AsteroidState.State)
asteroidById asteroid_id = Map.lookup asteroid_id <$> asteroids
-- | Returns the asteroid that collided with the player, or Nothing if there was
-- no collision or the collision was not detected yet.
asteroidCollision :: Update (Maybe AsteroidState.State)
asteroidCollision = MonadState.gets$ getAsteroidCollision
-- | Returns the damage inflicted to the given asteroid in the current frame.
-- Returns 0.0 if there was no damage to the asteroid or there is no such
-- asteroid.
asteroidDamageById :: AsteroidState.Id -> Update Double
asteroidDamageById asteroid_id =
MonadState.gets$ Map.findWithDefault 0.0 asteroid_id . getAsteroidDamage
-- | Returns the sum of all impulses of force applied to the asteroid with the
-- given ID in the current frame.
asteroidImpulseById :: AsteroidState.Id -> Update Geometry.Direction
asteroidImpulseById asteroid_id =
MonadState.gets$ findImpulseOrDefault . getAsteroidImpulses
where
findImpulseOrDefault = Map.findWithDefault Geometry.zeroDirection
asteroid_id
-- | Returns true if the player fired a bullet in this frame.
bulletFired :: Update Bool
bulletFired = MonadState.gets$ getBulletFired
-- | Returns the "previous" state in the update monad.
currentState :: Update State
currentState = MonadState.gets$ getCurrentState
-- | Returns the in-game time passed since the last frame.
duration :: Update Time.Duration
duration = MonadState.gets$ getDuration
-- | Returns the state of the inputs in the update.
inputs :: Update Inputs.State
inputs = MonadState.gets$ getInputState
-- | Returns the timestamp of the current frame.
currentFrameTime :: Update Time.Time
currentFrameTime = Time.add <$> lastFrameTime <*> duration
-- | Returns the time when the last bullet was fired.
lastBulletTime :: Update Time.Time
lastBulletTime = MonadState.gets$ getLastBulletTime . getCurrentState
-- | Returns the timestamp of the last frame.
lastFrameTime :: Update Time.Time
lastFrameTime = MonadState.gets$ getLastUpdate . getCurrentState
-- | Returns a new asteroid ID.
newAsteroidId :: Update AsteroidState.Id
newAsteroidId = MonadState.state$ \d ->
let id = getUpdateNextAsteroidId d
in (id, d { getUpdateNextAsteroidId = AsteroidState.nextId id })
-- | Returns the state of the player in the previous frame.
player :: Update PlayerState.State
player = MonadState.gets$ getPlayer . getCurrentState
-- | Returns the playr damage accumulated so far in the current frame.
playerDamage :: Update Double
playerDamage = MonadState.gets$ getPlayerDamage
-- | Generates a random value using the random generator in the monad.
random :: Random.Random a => Update a
random = MonadState.state$ \d ->
let generator = getUpdateRandomGenerator d
(v, generator') = Random.random generator
in (v, d { getUpdateRandomGenerator = generator' })
-- | Generates a random value from the given range using the random
-- generator in the monad.
randomR :: Random.Random a => (a, a) -> Update a
randomR range = MonadState.state$ \d ->
let generator = getUpdateRandomGenerator d
(v, generator') = Random.randomR range generator
in (v, d { getUpdateRandomGenerator = generator' })
-- | Sets the asteroid the player collided with.
setAsteroidCollision :: AsteroidState.State
-- ^ The asteroid the player collided with.
-> Update ()
setAsteroidCollision asteroid = MonadState.modify'$ \d ->
d { getAsteroidCollision = Just asteroid }
-- | Returns the updated data of the asteroid with the given ID. Returns Nothing
-- if no such asteroid exists or if the asteroid was not updated yet.
updatedAsteroidById :: AsteroidState.Id -> Update (Maybe AsteroidState.State)
updatedAsteroidById asteroid_id =
Map.lookup asteroid_id <$> MonadState.gets getUpdatedAsteroids
-- | Modifies the player state in the update.
updatePlayer :: PlayerState.State
-- ^ The new state of the player.
-> Update ()
updatePlayer player = MonadState.modify'$ \d -> d { getUpdatedPlayer = player }
-- | Runs a game update action. Collects the updates produced by the action into
-- an empty UpdateData structure.
runUpdate :: Time.Duration
-- ^ The amount of in-game time that passed since the last frame.
-> Inputs.State
-- ^ The state of the inputs during the update.
-> State
-- ^ The previous state of the game.
-> Update a
-- ^ The update action.
-> UpdateData
-- ^ The updates produced by the action.
runUpdate duration inputs old_state code = MonadState.execState code empty
where
empty = UpdateData
{ getCurrentState = old_state
, getDuration = duration
, getInputState = inputs
, getPlayerDamage = 0.0
, getPlayerImpulse = Geometry.zeroDirection
, getAsteroidCollision = Nothing
, getAsteroidDamage = Map.empty
, getAsteroidImpulses = Map.empty
, getUpdatedAsteroids = Map.empty
, getUpdateNextAsteroidId = getStateNextAsteroidId old_state
, getUpdatedBullets = []
, getBulletFired = False
, getUpdatedParticles = []
, getUpdatedPlayer = getPlayer old_state
, getUpdateRandomGenerator = getRandomGenerator old_state }
| ondrasej/heavenly-bodies | src/HBodies/Game/State.hs | apache-2.0 | 13,059 | 0 | 13 | 2,953 | 1,877 | 1,070 | 807 | 187 | 1 |
module Game where
import Cards
import Player
data Game = Game { topCard :: Card
, players :: [Player]
, stack :: Deck
, ntake :: Int
, nskip :: Bool
} deriving (Show)
data Move = Play Card | Draw | Pass deriving (Eq, Show)
-- | Returns whether whether card2 can be played on top of card1
isValidMove :: Game -> Card -> Bool
isValidMove game card = if ntake game == 0 then isValidCard (topCard game) card
else case card of
(Card _ Take2) -> not (isPick4 . topCard $ game)
_ -> False
where
isPick4 (Picked _) = True
isPick4 _ = False
-- | Takes a Hand and returns a list of every card that could be played
validMoves :: Game -> Hand -> [Card]
validMoves = filter . isValidMove
| Kingdread/Huno | src/Game.hs | bsd-2-clause | 952 | 0 | 12 | 412 | 223 | 125 | 98 | 19 | 4 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Controller
( withBioSpace
, withDevelApp
) where
import BioSpace
import Settings
import Yesod.Helpers.Static
import Yesod.Auth
import Yesod.Auth.HashDB(migrateUsers)
import Database.Persist.GenericSql
import Data.ByteString (ByteString)
import Data.Dynamic (Dynamic, toDyn)
-- Import all relevant handler modules here.
import Handler.Root
import Handler.Dashboard
import Handler.Profile
import Handler.Project
import Handler.Wiki
import Handler.Event
-- This line actually creates our YesodSite instance. It is the second half
-- of the call to mkYesodData which occurs in BioSpace.hs. Please see
-- the comments there for more details.
mkYesodDispatch "BioSpace" resourcesBioSpace
-- Some default handlers that ship with the Yesod site template. You will
-- very rarely need to modify this.
getFaviconR :: Handler ()
getFaviconR = sendFile "image/x-icon" "config/favicon.ico"
getRobotsR :: Handler RepPlain
getRobotsR = return $ RepPlain $ toContent ("User-agent: *" :: ByteString)
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
withBioSpace :: (Application -> IO a) -> IO a
withBioSpace f = Settings.withConnectionPool $ \p -> do
runConnectionPool (runMigration migrateAll >> runMigration migrateUsers) p
let h = BioSpace s p
toWaiApp h >>= f
where
s = static Settings.staticdir
withDevelApp :: Dynamic
withDevelApp = toDyn (withBioSpace :: (Application -> IO ()) -> IO ())
| chetant/bioSpace | Controller.hs | bsd-2-clause | 1,767 | 0 | 12 | 271 | 309 | 172 | 137 | 34 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Command.Export.Perform
( ExportOptions
, options
, perform
) where
import Data.Monoid
import Options.Applicative
import System.Exit
import Text.Comma
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified System.FilePath as F
import Load
import Story
import Util
-- | Options of the "export-csv" command.
data ExportOptions = ExportOptions
{ exportNoHeader :: Bool
, exportTimestamp :: Bool
, exportFile :: FilePath }
deriving (Show)
-- | Switch to trigger exclusion of a CSV header.
optionNoHeader :: Parser Bool -- ^ parser
optionNoHeader = switch
$ long "n"
<> long "no-header"
<> help "Header-less output table"
-- | Switch to trigger timestamps instead of formatted dates.
optionTimestamp :: Parser Bool -- ^ parser
optionTimestamp = switch
$ short 't'
<> long "timestamp"
<> help "Display time values as timestamps"
-- | Data file to export into CSV.
optionFile :: Parser FilePath -- ^ parser
optionFile = argument str (metavar "FILE")
-- | Command-line user interface.
options :: Parser ExportOptions -- ^ parser
options = ExportOptions <$> optionNoHeader <*> optionTimestamp <*> optionFile
-- | Create a CSV-formatted table of a story.
table :: ExportOptions -- ^ command-line options
-> Story -- ^ story
-> T.Text -- ^ CSV table
table opts story = uncomma $ bool rows (headers:rows) (exportNoHeader opts)
where
headers = ["time", "value"]
rows = map conv story
conv (time, val) = [showTime (exportTimestamp opts) time, textShow val]
-- | Pretty-print the content of a story file.
perform :: ExportOptions -- ^ options
-> IO () -- ^ command action
perform opts = storyLoad file >>= \case
Left msg -> errorPrint msg >> exitFailure
Right story -> T.writeFile newName (table opts story) >> exitSuccess
where
file = exportFile opts
newName = F.replaceExtension file "csv"
| lovasko/swim | src/Command/Export/Perform.hs | bsd-2-clause | 2,035 | 0 | 12 | 453 | 444 | 247 | 197 | 49 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-|
Module : $Header$
Copyright : (c) 2015 Deakin Software and Technology Innovation Lab
License : BSD3
Maintainer : Rhys Adams <[email protected]>
Stability : unstable
Portability : portable
The server entry point.
-}
module Main where
import Aegle.API (
API, Host, Group, zkNode
, Status, positive, negative
, Service, ServiceMap (..), ServiceStatuses (..)
, ResourceInfo, resisum, unknownRI, cpu, ram, disk, used, total )
import qualified Aegle.API as A
import qualified Network.Protocol.Riemann as R
import Control.Applicative ((<|>))
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (Concurrently (..), runConcurrently)
import Control.Concurrent.STM (
STM, atomically
, TBQueue, newTBQueue, readTBQueue, writeTBQueue
, TVar, newTVar, readTVar, writeTVar, modifyTVar' )
import Control.Exception (throwIO)
import Control.Monad (forever, when)
import Control.Monad.Except (throwError, runExceptT)
import Control.Monad.Logger (MonadLoggerIO, logDebugN, runStdoutLoggingT)
import Control.Monad.Trans (lift, liftIO)
import qualified Data.Aeson as Aeson
import Data.Aeson.TH (deriveFromJSON, defaultOptions, fieldLabelModifier)
import Data.Bool (bool)
import qualified Data.ByteString.Lazy as BL
import Data.Char (toLower)
import Data.Composition ((.:))
import Data.Either (isRight)
import Data.Foldable (foldlM, foldl')
import qualified Data.HashSet as HS
import qualified Data.HashMap.Strict as HM
import Data.Int (Int64)
import Data.Maybe (fromMaybe)
import Data.Metrology ((|+|), zero)
import Data.Metrology.Computing (Byte (Byte), Core (Core), Data, Parallelism)
import Data.Metrology.Suspicious ((%>), (#>))
import Data.Monoid ((<>))
import Data.Proxy (Proxy (Proxy))
import Data.Scientific.Suspicious (Sustific, fromFloatDigits, sustific, toBoundedRealFloat)
import Data.String (fromString)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock.POSIX (getPOSIXTime)
import Data.Word (Word16)
import qualified Database.Zookeeper.ManagedEvents as ZK
import qualified Database.Zookeeper.Election as ZK
import Lens.Micro.Platform (ASetter', Lens', (&), (^.), (.~), at, lens, makeLenses)
import qualified ListT
import Network.HTTP.Types (methodGet)
import Network.Simple.TCP (HostPreference (..))
import qualified Network.Wai.Handler.Warp as Warp
import Network.Wai.Middleware.Cors (CorsResourcePolicy (..), cors)
import Servant ((:<|>) (..))
import qualified Servant.Server as Server
import qualified STMContainers.Map as M
import System.Environment (getArgs)
data HostInfo = HostInfo { rd :: TVar ResourceData
, groups :: HS.HashSet Group
, services :: HM.HashMap Service (TVar Status) }
data ResourceData = ResourceData { __rdRi :: ResourceInfo
, _rdDiskReserved :: Maybe Sustific
, _rdDiskFree :: Maybe Sustific
, _rdCpuPcts :: HM.HashMap RiemannService Parallelism }
rdRi :: ResourceData -> ResourceInfo
rdRi = __rdRi
data HostConfig = HostConfig { configGroups :: HS.HashSet Group
, configServices :: [Service] }
data State = State (HM.HashMap Host HostInfo) (M.Map (Host, RiemannService) Int64)
newtype HostPref = HP { unHP :: HostPreference }
deriving (Eq, Show)
data Config = Config { apiHost :: HostPref
, apiPort :: Word16
, riemannHost :: HostPref
, riemannPort :: Word16
, zookeeperHosts :: ZK.ZKURI
, resourceLimits :: ResourceLimits
, monUnits :: [Text] }
data ResourceLimits = ResourceLimits { maxCpuPct :: Double
, minRamMb :: Double
, minDiskMb :: Double }
data Expired = Expired deriving (Show, Eq)
type RiemannService = Text
data Ev = Ev Host RiemannService Int64 (Either Expired Double)
deriving (Show, Eq)
$(makeLenses ''ResourceData)
-- | RESTful 'API' server.
server :: (MonadLoggerIO m) => HostPreference -> Word16 -> State -> m ()
server host port (State state _) = do
logDebugN $ "Starting API on " <> T.pack (show host ++ ":" ++ show port)
liftIO . Warp.runSettings settings . myCors $ Server.serve (Proxy :: Proxy API) impl
where
myCors = cors . const $ Just
CorsResourcePolicy { corsOrigins = Nothing
, corsMethods = [methodGet]
, corsRequestHeaders = ["content-type"]
, corsExposedHeaders = Nothing
, corsMaxAge = Nothing
, corsVaryOrigin = False
, corsRequireOrigin = False
, corsIgnoreFailures = False }
settings = Warp.setHost (fromString $ prefToStr host) $
Warp.setPort (fromIntegral port)
Warp.defaultSettings
impl = hosts :<|> allResources :<|> totalResources
:<|> allServices :<|> hostResources :<|> hostServices
:<|> allData
hosts [] = pure $ HM.keys state
hosts gs = pure . HM.keys $ grpMems gs
allResources [] [] = run $ traverse (fmap rdRi . readTVar . rd) state
allResources hs gs = run . traverse (fmap rdRi . readTVar . rd) $ grpHs hs gs
totalResources [] [] = run $ sumResources state
totalResources hs gs = run . sumResources $ grpHs hs gs
allServices ss = run . fmap (ServiceStatuses . invert) $ traverse filterHost state
where
invert :: HM.HashMap Host [(Service, Status)] -> HM.HashMap Service [(Host, Status)]
invert = HM.foldlWithKey' (\a h -> foldl' (\a' (s, st) -> HM.insertWith (++) s [(h, st)] a') a) HM.empty
filterHost :: HostInfo -> STM [(Service, Status)]
filterHost info = traverse (traverse readTVar) . filter svcPred . HM.toList $ services info
svcPred :: (Service, a) -> Bool
svcPred | [] <- ss = const True
| otherwise = (`elem` ss) . fst
hostResources h = runForHost h $ fmap rdRi . readTVar . rd
hostServices h = runForHost h $ fmap ServiceMap . traverse (traverse readTVar) . HM.toList . services
allData = A.All <$> allServices [] <*> allResources [] [] <*> pure allGroups
grpMems :: [Group] -> HM.HashMap Host HostInfo
grpMems [] = HM.empty
grpMems gs = HM.filter (\hi -> any (`HS.member` groups hi) gs) state
grpHs :: [Host] -> [Group] -> HM.HashMap Host HostInfo
grpHs hs gs = HM.filterWithKey (\h hi -> h `elem` hs || any (`HS.member` groups hi) gs) state
run = lift . atomically
sumResources = foldlM (\a -> fmap (resisum a . rdRi) . readTVar . rd) unknownRI
runForHost h f = maybe (throwError Server.err404) (run . f) $ HM.lookup h state
allGroups = HM.foldlWithKey' go HM.empty state
where
go :: HM.HashMap Group (HS.HashSet Host) -> Host -> HostInfo -> HM.HashMap Group (HS.HashSet Host)
go acc hst = HS.foldl' (\m g -> HM.insertWith HS.union g (HS.singleton hst) m) acc . groups
-- | Consume Riemann events and update the 'State'.
consumer :: TBQueue Ev -> ResourceLimits -> [Text] -> State -> IO a
consumer q ResourceLimits{..} otherUnits (State state exps) = forever $ handle =<< atomically (readTBQueue q)
where
handle :: Ev -> IO ()
handle e@(Ev hst srv time det) = atomically $ maybeSetExpiry =<< handle' e
where
maybeSetExpiry = (`when` setExpiry) . (&& isRight det)
setExpiry = M.insert (time + timeout) (hst, srv) exps
timeout = 20
handle' :: Ev -> STM Bool
handle' (Ev hst srv _ det)
| "cpu-" `T.isInfixOf` srv && "/percent-active" `T.isSuffixOf` srv =
cpuUpdate
| srv == "memavailable/bytes-memory-total" =
setRI (total . ram . bytes . dbl)
| srv == "memavailable/bytes-memory-unavailable" =
setRI (used . ram . bytes . dbl)
| srv == "df-root/df_complex-free" = do
_ <- diskUpdate rdDiskFree
setServiceVar "disk" $ predStatus (> minDiskMb * 1e6)
| srv == "df-root/df_complex-reserved" =
diskUpdate rdDiskReserved
| srv == "df-root/df_complex-used" =
diskUpdate (_rdRi . used . disk . bytes)
| srv == "memavailable/bytes-memory-available" =
setServiceVar "ram" $ predStatus (> minRamMb * 1e6)
| srv == "systemd-mesos-master.service/gauge-active" =
setDistServiceVar "mesos-master" Process defProcPred
| srv == "mesos-master/gauge-master_elected" =
setDistServiceVar "mesos-master" Accessibility (bool Follower Leader . (== 1))
| srv == "systemd-mesos-slave.service/gauge-active" =
setDistServiceVar "mesos-slave" Process defProcPred
| srv == "mesos-slave/gauge-slave_registered" =
setDistServiceVar "mesos-slave" Accessibility (bool Offline Unknown . (== 1))
| srv == "systemd-eclogues.service/gauge-active" =
setDistServiceVar "eclogues" Process defProcPred
| srv == "eclogues/gauge-scheduler_accessible" =
setDistServiceVar "eclogues" Accessibility (bool Offline Unknown . (== 1))
| srv == "systemd-aurora-scheduler.service/gauge-active" =
setDistServiceVar "aurora-scheduler" Process defProcPred
| srv == "aurora-scheduler-default/gauge-scheduler_lifecycle_ACTIVE" && det == Right 1.0 =
-- TODO: check if /aurora/scheduler ZK node is active
setDistServiceVar "aurora-scheduler" Accessibility (const Leader)
| srv == "aurora-scheduler-default/gauge-scheduler_lifecycle_STORAGE_PREPARED" && det == Right 1.0 =
setDistServiceVar "aurora-scheduler" Accessibility (const Follower)
| srv == "systemd-zookeeper.service/gauge-active" =
setDistServiceVar "zookeeper" Process defProcPred
| srv == "zookeeper/gauge-zk_is_leader" =
setDistServiceVar "zookeeper" Accessibility (bool Follower Leader . (== 1))
| Just grp <- HM.lookup srv otherUnitSrvs =
setServiceVar grp $ predStatus (== 1)
| otherwise = pure False
where
setRI :: ASetter' ResourceInfo (Maybe Double) -> STM Bool
setRI l = True <$ modifyRD (\r -> r { __rdRi = expireL l det (rdRi r) })
diskUpdate :: Lens' ResourceData (Maybe Sustific) -> STM Bool
diskUpdate l = True <$ modifyRD (recalc . expireL l (fromFloatDigits <$> det))
where
recalc :: ResourceData -> ResourceData
recalc r@(ResourceData ri (Just a) (Just b) _) | Just c <- ri ^. used . disk =
let ttl = (a + b + (c #> Byte)) %> Byte
in r & _rdRi . total . disk .~ Just ttl
recalc r = r & _rdRi . total . disk .~ Nothing
cpuUpdate = (True <$) . withHostInfo $ \hi -> do
r <- readTVar $ rd hi
let r' = r & recalc . expireL (rdCpuPcts . at srv . cores . dbl) ((/ 100) <$> det)
writeTVar (rd hi) r'
mapM_ (`writeTVar` service' r') $ services hi ^. at "cpu"
where
recalc r = r & _rdRi . total . cpu . cores .~ whenAny (sustific (fromIntegral size) 0)
& _rdRi . used . cpu .~ whenAny (HM.foldl' (|+|) zero (r ^. rdCpuPcts))
where
size = HM.size $ r ^. rdCpuPcts
whenAny | size == 0 = const Nothing
| otherwise = Just
service' r | Just u <- r ^. _rdRi . used . cpu . cores . dbl
, Just t <- r ^. _rdRi . total . cpu . cores . dbl
= bool negative positive ((u / t * 100) < maxCpuPct) Nothing
| otherwise = missing
modifyServiceVar typ f = withServiceTVar typ (`modifyTVar'` f)
setServiceVar typ f = True <$ withServiceTVar typ (`writeTVar` f)
setDistServiceVar typ dtyp f = True <$ modifyServiceVar typ (calcDistService dtyp f det)
defProcPred = bool Offline Unknown . (== 1)
modifyRD f = withHostInfo $ (`modifyTVar'` f) . rd
withServiceTVar typ f = withHostInfo $ mapM_ f . HM.lookup typ . services
withHostInfo = (`mapM_` HM.lookup hst state)
predStatus f | det == Left Expired = missing
| Right v <- det, f v = positive Nothing
| otherwise = negative Nothing
expireL l = either (const $ l .~ Nothing) ((l .~) . Just)
-- It'd be nice if these lenses could be lifted into (Maybe a), but
-- that's incompatible with the lens laws.
bytes :: Lens' (Maybe Data) (Maybe Sustific)
bytes = lens (fmap (#> Byte)) (const (fmap (%> Byte)))
cores :: Lens' (Maybe Parallelism) (Maybe Sustific)
cores = lens (fmap (#> Core)) (const (fmap (%> Core)))
dbl :: Lens' (Maybe Sustific) (Maybe Double)
dbl = lens (fmap (either id id . toBoundedRealFloat)) (const (fmap fromFloatDigits))
otherUnitSrvs = HM.fromList $ (\pn -> ("systemd-" <> pn <> "/gauge-active", fromMaybe pn $ T.stripSuffix ".service" pn)) <$> otherUnits
data DistServiceDat = Accessibility | Process deriving (Eq)
data Leadership = Leader | Follower | Unknown | Offline deriving (Eq)
calcDistService :: DistServiceDat -> (Double -> Leadership) -> Either Expired Double -> Status -> Status
calcDistService typ prd dat st = case () of
_ | process && accessible -> positive . Just $ "running and accessible" <> lshipSuf
| process -> negative . Just $ "running but cannot access leader" <> lshipSuf
| Left Expired <- dat -> missing
| otherwise -> negative Nothing
where
accessible
| typ == Accessibility = lship /= Offline
| otherwise = isInfixOfSd "accessible"
process
| typ == Process = lship /= Offline
| otherwise = isInfixOfSd "running"
lship = case either (const Offline) prd dat of
Offline -> Offline
Unknown
| isInfixOfSd "(leader)" -> Leader
| isInfixOfSd "(follower)" -> Follower
| otherwise -> Unknown
other -> other
lshipSuf = case lship of
Leader -> " (leader)"
Follower -> " (follower)"
_ -> ""
isInfixOfSd s = maybe False (s `T.isInfixOf`) $ st ^. A.detail
expirer :: TBQueue Ev -> State -> IO ()
expirer q (State _ exps) = forever $ do
threadDelay 1000000 -- 1 second
time <- floor <$> getPOSIXTime
atomically . ListT.traverse_ (go time) $ M.stream exps
where
go :: Int64 -> ((Host, RiemannService), Int64) -> STM ()
go time ((hst, srv), e) = when (e < time) $ do
M.delete (hst, srv) exps
writeTBQueue q . Ev hst srv time $ Left Expired
-- | Enqueue all useful events.
enqueue :: TBQueue Ev -> [R.Event] -> IO ()
enqueue q = atomically .: mapM_ $ mapM_ (writeTBQueue q) . ev
where
ev :: R.Event -> Maybe Ev
ev event
| R.expired event = meta <*> pure (Left Expired)
| otherwise = meta <*> (Right <$> event ^. R.metric)
where
meta = Ev <$> event ^. R.host <*> event ^. R.service <*> event ^. R.time
main :: IO ()
main = do
(configPath, hostsPath) <- getArgs >>= \case
[p0, p1] -> pure (p0, p1)
_ -> error "Usage: aegle-api CONFIG-FILE HOSTS-FILE"
(Config (HP h) p (HP rh) rp zkuri lim oProcs) <- readConfig configPath
hostConf <- readConfig hostsPath
let host = case h of
Host s -> s
_ -> error "apiHost must be set to a hostname"
(st, q) <- atomically $ (,) <$> (State <$> traverse confToInfo hostConf <*> M.new)
<*> newTBQueue 8000
whenLeader zkuri zkNode host p . runConcurrently $
Concurrently (runStdoutLoggingT $ R.server rh rp (enqueue q))
<|> Concurrently (consumer q lim oProcs st)
<|> Concurrently (expirer q st)
<|> Concurrently (runStdoutLoggingT $ server h p st)
instance Aeson.FromJSON HostPref where
parseJSON (Aeson.String s) = pure . HP . fromString $ T.unpack s
parseJSON _ = fail "HostPref must be String"
prefToStr :: HostPreference -> String
prefToStr HostAny = "*"
prefToStr HostIPv4 = "*4"
prefToStr HostIPv6 = "*6"
prefToStr (Host s) = s
confToInfo :: HostConfig -> STM HostInfo
confToInfo (HostConfig grps svcs) =
HostInfo <$> newTVar (ResourceData unknownRI Nothing Nothing HM.empty) <*> pure grps <*> stats
where
stats = HM.fromList <$> traverse (\g -> (g,) <$> newTVar missing) svcs
missing :: Status
missing = negative $ Just "missing"
readConfig :: (Aeson.FromJSON a) => String -> IO a
readConfig = fmap (either error id . Aeson.eitherDecode') . BL.readFile
whenLeader :: ZK.ZKURI -> ZK.ZNode -> String -> Word16 -> IO a -> IO a
whenLeader zkuri node host port act = ZK.withZookeeper zkuri go
where
advertisement = BL.toStrict $ Aeson.encode (host, port)
go zk = runExceptT (ZK.whenLeader zk node advertisement act) >>= \case
Right a -> pure a
Left ZK.LeadershipLost -> go zk
Left ZK.ZookeeperInvariantViolated -> go zk
Left (ZK.ActionException e) -> throwIO e
Left (ZK.LZKError e) ->
error $ "Zookeeper coordination error: " ++ show e
$(deriveFromJSON defaultOptions ''ResourceLimits)
$(deriveFromJSON defaultOptions ''Config)
$(deriveFromJSON defaultOptions{ fieldLabelModifier = fmap toLower . drop 6 } ''HostConfig)
| dstil/aegle | aegle-impl/app/Main.hs | bsd-3-clause | 17,928 | 0 | 22 | 4,981 | 5,637 | 2,961 | 2,676 | -1 | -1 |
module MB.Gen.Base
( buildPage
)
where
import MB.Types
import MB.Templates
buildPage :: Blog -> String -> Maybe String -> Template -> String
buildPage blog content extraTitle tmpl =
let attrs = [ ("content", content)
] ++ maybe [] (\t -> [("extraTitle", t)]) extraTitle
in fillTemplate blog tmpl attrs
| jtdaugherty/mathblog | src/MB/Gen/Base.hs | bsd-3-clause | 336 | 0 | 14 | 82 | 117 | 64 | 53 | 9 | 1 |
module Main where
main = putStrLn "cool" | tolysz/ssh-proxy | Main.hs | bsd-3-clause | 41 | 0 | 5 | 7 | 12 | 7 | 5 | 2 | 1 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
module Common.MonadRef (
MonadRef (..)
) where
import Control.Monad.ST (ST)
import Control.Monad (void)
import Data.IORef (IORef, newIORef, readIORef, writeIORef, modifyIORef, modifyIORef')
import Data.STRef (STRef, newSTRef, readSTRef, writeSTRef, modifySTRef, modifySTRef')
import Prelude hiding (read)
class Monad m => MonadRef r m | m -> r where
{-# MINIMAL new, read, write, (modify_ | modify), (modify_' | modify') #-}
new :: a -> m (r a)
read :: r a -> m a
write :: r a -> a -> m ()
modify_, modify_' :: r a -> (a -> a) -> m ()
modify_ r f = void $ modify r f
modify_' r f = void $ modify' r f
modify, modify' :: r a -> (a -> a) -> m a
modify r f = modify_ r f >> read r
modify' r f = modify_' r f >> read r
instance MonadRef IORef IO where
new = newIORef
read = readIORef
write = writeIORef
modify_ = modifyIORef
modify_' = modifyIORef'
instance MonadRef (STRef s) (ST s) where
new = newSTRef
read = readSTRef
write = writeSTRef
modify_ = modifySTRef
modify_' = modifySTRef'
| foreverbell/project-euler-solutions | lib/Common/MonadRef.hs | bsd-3-clause | 1,099 | 0 | 10 | 242 | 397 | 216 | 181 | 31 | 0 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
module Duckling.Dimensions.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import qualified Duckling.AmountOfMoney.Tests as AmountOfMoney
import qualified Duckling.Distance.Tests as Distance
import qualified Duckling.Duration.Tests as Duration
import qualified Duckling.Email.Tests as Email
import qualified Duckling.Numeral.Tests as Numeral
import qualified Duckling.Ordinal.Tests as Ordinal
import qualified Duckling.PhoneNumber.Tests as PhoneNumber
import qualified Duckling.Quantity.Tests as Quantity
import qualified Duckling.Temperature.Tests as Temperature
import qualified Duckling.Time.Tests as Time
import qualified Duckling.Volume.Tests as Volume
import qualified Duckling.Url.Tests as Url
tests :: TestTree
tests = testGroup "Dimensions Tests"
[ AmountOfMoney.tests
, Distance.tests
, Duration.tests
, Email.tests
, Numeral.tests
, Ordinal.tests
, PhoneNumber.tests
, Quantity.tests
, Temperature.tests
, Time.tests
, Volume.tests
, Url.tests
]
| rfranek/duckling | tests/Duckling/Dimensions/Tests.hs | bsd-3-clause | 1,319 | 0 | 7 | 193 | 214 | 150 | 64 | 31 | 1 |
-- (c) The University of Glasgow 2006
-- (c) The GRASP/AQUA Project, Glasgow University, 1998
--
-- Type - public interface
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Main functions for manipulating types and type-related things
module Type (
-- Note some of this is just re-exports from TyCon..
-- * Main data types representing Types
-- $type_classification
-- $representation_types
TyThing(..), Type, VisibilityFlag(..), KindOrType, PredType, ThetaType,
Var, TyVar, isTyVar, TyCoVar, TyBinder,
-- ** Constructing and deconstructing types
mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, repGetTyVar_maybe,
getCastedTyVar_maybe, tyVarKind,
mkAppTy, mkAppTys, splitAppTy, splitAppTys, repSplitAppTys,
splitAppTy_maybe, repSplitAppTy_maybe, tcRepSplitAppTy_maybe,
mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
splitFunTys, splitFunTysN,
funResultTy, funArgTy,
mkTyConApp, mkTyConTy,
tyConAppTyCon_maybe, tyConAppTyConPicky_maybe,
tyConAppArgs_maybe, tyConAppTyCon, tyConAppArgs,
splitTyConApp_maybe, splitTyConApp, tyConAppArgN, nextRole,
splitListTyConApp_maybe,
repSplitTyConApp_maybe,
mkForAllTy, mkForAllTys, mkInvForAllTys, mkSpecForAllTys,
mkVisForAllTys,
mkNamedForAllTy,
splitForAllTy_maybe, splitForAllTys, splitForAllTy,
splitPiTy_maybe, splitPiTys, splitPiTy,
splitNamedPiTys,
mkPiType, mkPiTypes, mkTyBindersPreferAnon,
piResultTy, piResultTys,
applyTysX, dropForAlls,
mkNumLitTy, isNumLitTy,
mkStrLitTy, isStrLitTy,
mkCastTy, mkCoercionTy, splitCastTy_maybe,
userTypeError_maybe, pprUserTypeErrorTy,
coAxNthLHS,
stripCoercionTy, splitCoercionType_maybe,
splitPiTysInvisible, filterOutInvisibleTypes,
filterOutInvisibleTyVars, partitionInvisibles,
synTyConResKind,
-- Analyzing types
TyCoMapper(..), mapType, mapCoercion,
-- (Newtypes)
newTyConInstRhs,
-- Pred types
mkFamilyTyConApp,
isDictLikeTy,
mkPrimEqPred, mkReprPrimEqPred, mkPrimEqPredRole,
equalityTyCon,
mkHeteroPrimEqPred, mkHeteroReprPrimEqPred,
mkClassPred,
isClassPred, isEqPred, isNomEqPred,
isIPPred, isIPPred_maybe, isIPTyCon, isIPClass,
isCTupleClass,
-- Deconstructing predicate types
PredTree(..), EqRel(..), eqRelRole, classifyPredType,
getClassPredTys, getClassPredTys_maybe,
getEqPredTys, getEqPredTys_maybe, getEqPredRole,
predTypeEqRel,
-- ** Binders
sameVis,
mkNamedBinder, mkAnonBinder, isNamedBinder, isAnonBinder,
isIdLikeBinder, binderVisibility, binderVar_maybe,
binderVar, binderRelevantType_maybe, caseBinder,
partitionBinders, partitionBindersIntoBinders,
binderType, isVisibleBinder, isInvisibleBinder,
-- ** Common type constructors
funTyCon,
-- ** Predicates on types
allDistinctTyVars,
isTyVarTy, isFunTy, isDictTy, isPredTy, isVoidTy, isCoercionTy,
isCoercionTy_maybe, isCoercionType, isForAllTy,
isPiTy,
-- (Lifting and boxity)
isUnliftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
isPrimitiveType, isStrictType,
isRuntimeRepTy, isRuntimeRepVar, isRuntimeRepKindedTy,
dropRuntimeRepArgs,
getRuntimeRep, getRuntimeRepFromKind,
-- * Main data types representing Kinds
Kind,
-- ** Finding the kind of a type
typeKind,
-- ** Common Kind
liftedTypeKind,
-- * Type free variables
tyCoVarsOfType, tyCoVarsOfTypes, tyCoVarsOfTypeAcc,
tyCoVarsOfTypeDSet,
coVarsOfType,
coVarsOfTypes, closeOverKinds,
splitDepVarsOfType, splitDepVarsOfTypes,
splitVisVarsOfType, splitVisVarsOfTypes,
expandTypeSynonyms,
typeSize,
-- * Well-scoped lists of variables
varSetElemsWellScoped, toposortTyVars, tyCoVarsOfTypeWellScoped,
tyCoVarsOfTypesWellScoped,
-- * Type comparison
eqType, eqTypeX, eqTypes, cmpType, cmpTypes, cmpTypeX, cmpTypesX, cmpTc,
eqVarBndrs,
-- * Forcing evaluation of types
seqType, seqTypes,
-- * Other views onto Types
coreView, coreViewOneStarKind,
UnaryType, RepType(..), flattenRepType, repType,
tyConsOfType,
-- * Type representation for the code generator
typePrimRep, typeRepArity, kindPrimRep, tyConPrimRep,
-- * Main type substitution data types
TvSubstEnv, -- Representation widely visible
TCvSubst(..), -- Representation visible to a few friends
-- ** Manipulating type substitutions
emptyTvSubstEnv, emptyTCvSubst, mkEmptyTCvSubst,
mkTCvSubst, zipTvSubst, mkTvSubstPrs,
notElemTCvSubst,
getTvSubstEnv, setTvSubstEnv,
zapTCvSubst, getTCvInScope,
extendTCvInScope, extendTCvInScopeList, extendTCvInScopeSet,
extendTCvSubst, extendCvSubst,
extendTvSubst, extendTvSubstList, extendTvSubstAndInScope,
isInScope, composeTCvSubstEnv, composeTCvSubst, zipTyEnv, zipCoEnv,
isEmptyTCvSubst, unionTCvSubst,
-- ** Performing substitution on types and kinds
substTy, substTys, substTyWith, substTysWith, substTheta,
substTyAddInScope,
substTyUnchecked, substTysUnchecked, substThetaUnchecked,
substTyWithBindersUnchecked, substTyWithUnchecked,
substCoUnchecked, substCoWithUnchecked,
substTyVarBndr, substTyVar, substTyVars,
cloneTyVarBndr, cloneTyVarBndrs, lookupTyVar,
-- * Pretty-printing
pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing,
pprTvBndr, pprTvBndrs, pprForAll, pprForAllImplicit, pprUserForAll,
pprSigmaType,
pprTheta, pprThetaArrowTy, pprClassPred,
pprKind, pprParendKind, pprSourceTyCon,
TyPrec(..), maybeParen,
pprTyVar, pprTcAppTy, pprPrefixApp, pprArrowChain,
-- * Tidying type related things up for printing
tidyType, tidyTypes,
tidyOpenType, tidyOpenTypes,
tidyOpenKind,
tidyTyCoVarBndr, tidyTyCoVarBndrs, tidyFreeTyCoVars,
tidyOpenTyCoVar, tidyOpenTyCoVars,
tidyTyVarOcc,
tidyTopType,
tidyKind
) where
#include "HsVersions.h"
-- We import the representation and primitive functions from TyCoRep.
-- Many things are reexported, but not the representation!
import Kind
import TyCoRep
-- friends:
import Var
import VarEnv
import VarSet
import NameEnv
import Class
import TyCon
import TysPrim
import {-# SOURCE #-} TysWiredIn ( listTyCon, typeNatKind
, typeSymbolKind, liftedTypeKind )
import PrelNames
import CoAxiom
import {-# SOURCE #-} Coercion
-- others
import BasicTypes ( Arity, RepArity )
import Util
import Outputable
import FastString
import Pair
import ListSetOps
import Digraph
import Maybes ( orElse )
import Data.Maybe ( isJust, mapMaybe )
import Control.Monad ( guard )
import Control.Arrow ( first, second )
-- $type_classification
-- #type_classification#
--
-- Types are one of:
--
-- [Unboxed] Iff its representation is other than a pointer
-- Unboxed types are also unlifted.
--
-- [Lifted] Iff it has bottom as an element.
-- Closures always have lifted types: i.e. any
-- let-bound identifier in Core must have a lifted
-- type. Operationally, a lifted object is one that
-- can be entered.
-- Only lifted types may be unified with a type variable.
--
-- [Algebraic] Iff it is a type with one or more constructors, whether
-- declared with @data@ or @newtype@.
-- An algebraic type is one that can be deconstructed
-- with a case expression. This is /not/ the same as
-- lifted types, because we also include unboxed
-- tuples in this classification.
--
-- [Data] Iff it is a type declared with @data@, or a boxed tuple.
--
-- [Primitive] Iff it is a built-in type that can't be expressed in Haskell.
--
-- Currently, all primitive types are unlifted, but that's not necessarily
-- the case: for example, @Int@ could be primitive.
--
-- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
-- but unlifted (such as @ByteArray#@). The only primitive types that we
-- classify as algebraic are the unboxed tuples.
--
-- Some examples of type classifications that may make this a bit clearer are:
--
-- @
-- Type primitive boxed lifted algebraic
-- -----------------------------------------------------------------------------
-- Int# Yes No No No
-- ByteArray# Yes Yes No No
-- (\# a, b \#) Yes No No Yes
-- ( a, b ) No Yes Yes Yes
-- [a] No Yes Yes Yes
-- @
-- $representation_types
-- A /source type/ is a type that is a separate type as far as the type checker is
-- concerned, but which has a more low-level representation as far as Core-to-Core
-- passes and the rest of the back end is concerned.
--
-- You don't normally have to worry about this, as the utility functions in
-- this module will automatically convert a source into a representation type
-- if they are spotted, to the best of it's abilities. If you don't want this
-- to happen, use the equivalent functions from the "TcType" module.
{-
************************************************************************
* *
Type representation
* *
************************************************************************
-}
{-# INLINE coreView #-}
coreView :: Type -> Maybe Type
-- ^ This function Strips off the /top layer only/ of a type synonym
-- application (if any) its underlying representation type.
-- Returns Nothing if there is nothing to look through.
--
-- By being non-recursive and inlined, this case analysis gets efficiently
-- joined onto the case analysis that the caller is already doing
coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys
= Just (mkAppTys (substTy (mkTvSubstPrs tenv) rhs) tys')
-- The free vars of 'rhs' should all be bound by 'tenv', so it's
-- ok to use 'substTy' here.
-- See also Note [The substitution invariant] in TyCoRep.
-- Its important to use mkAppTys, rather than (foldl AppTy),
-- because the function part might well return a
-- partially-applied type constructor; indeed, usually will!
coreView _ = Nothing
-- | Like 'coreView', but it also "expands" @Constraint@ to become
-- @TYPE PtrRepLifted@.
{-# INLINE coreViewOneStarKind #-}
coreViewOneStarKind :: Type -> Maybe Type
coreViewOneStarKind ty
| Just ty' <- coreView ty = Just ty'
| TyConApp tc [] <- ty
, isStarKindSynonymTyCon tc = Just liftedTypeKind
| otherwise = Nothing
-----------------------------------------------
expandTypeSynonyms :: Type -> Type
-- ^ Expand out all type synonyms. Actually, it'd suffice to expand out
-- just the ones that discard type variables (e.g. type Funny a = Int)
-- But we don't know which those are currently, so we just expand all.
--
-- 'expandTypeSynonyms' only expands out type synonyms mentioned in the type,
-- not in the kinds of any TyCon or TyVar mentioned in the type.
expandTypeSynonyms ty
= go (mkEmptyTCvSubst in_scope) ty
where
in_scope = mkInScopeSet (tyCoVarsOfType ty)
go subst (TyConApp tc tys)
| Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc expanded_tys
= let subst' = mkTvSubst in_scope (mkVarEnv tenv)
-- Make a fresh substitution; rhs has nothing to
-- do with anything that has happened so far
-- NB: if you make changes here, be sure to build an
-- /idempotent/ substitution, even in the nested case
-- type T a b = a -> b
-- type S x y = T y x
-- (Trac #11665)
in mkAppTys (go subst' rhs) tys'
| otherwise
= TyConApp tc expanded_tys
where
expanded_tys = (map (go subst) tys)
go _ (LitTy l) = LitTy l
go subst (TyVarTy tv) = substTyVar subst tv
go subst (AppTy t1 t2) = mkAppTy (go subst t1) (go subst t2)
go subst (ForAllTy (Anon arg) res)
= mkFunTy (go subst arg) (go subst res)
go subst (ForAllTy (Named tv vis) t)
= let (subst', tv') = substTyVarBndrCallback go subst tv in
ForAllTy (Named tv' vis) (go subst' t)
go subst (CastTy ty co) = mkCastTy (go subst ty) (go_co subst co)
go subst (CoercionTy co) = mkCoercionTy (go_co subst co)
go_co subst (Refl r ty)
= mkReflCo r (go subst ty)
-- NB: coercions are always expanded upon creation
go_co subst (TyConAppCo r tc args)
= mkTyConAppCo r tc (map (go_co subst) args)
go_co subst (AppCo co arg)
= mkAppCo (go_co subst co) (go_co subst arg)
go_co subst (ForAllCo tv kind_co co)
= let (subst', tv', kind_co') = go_cobndr subst tv kind_co in
mkForAllCo tv' kind_co' (go_co subst' co)
go_co subst (CoVarCo cv)
= substCoVar subst cv
go_co subst (AxiomInstCo ax ind args)
= mkAxiomInstCo ax ind (map (go_co subst) args)
go_co subst (UnivCo p r t1 t2)
= mkUnivCo (go_prov subst p) r (go subst t1) (go subst t2)
go_co subst (SymCo co)
= mkSymCo (go_co subst co)
go_co subst (TransCo co1 co2)
= mkTransCo (go_co subst co1) (go_co subst co2)
go_co subst (NthCo n co)
= mkNthCo n (go_co subst co)
go_co subst (LRCo lr co)
= mkLRCo lr (go_co subst co)
go_co subst (InstCo co arg)
= mkInstCo (go_co subst co) (go_co subst arg)
go_co subst (CoherenceCo co1 co2)
= mkCoherenceCo (go_co subst co1) (go_co subst co2)
go_co subst (KindCo co)
= mkKindCo (go_co subst co)
go_co subst (SubCo co)
= mkSubCo (go_co subst co)
go_co subst (AxiomRuleCo ax cs) = AxiomRuleCo ax (map (go_co subst) cs)
go_prov _ UnsafeCoerceProv = UnsafeCoerceProv
go_prov subst (PhantomProv co) = PhantomProv (go_co subst co)
go_prov subst (ProofIrrelProv co) = ProofIrrelProv (go_co subst co)
go_prov _ p@(PluginProv _) = p
go_prov _ (HoleProv h) = pprPanic "expandTypeSynonyms hit a hole" (ppr h)
-- the "False" and "const" are to accommodate the type of
-- substForAllCoBndrCallback, which is general enough to
-- handle coercion optimization (which sometimes swaps the
-- order of a coercion)
go_cobndr subst = substForAllCoBndrCallback False (go_co subst) subst
{-
************************************************************************
* *
Analyzing types
* *
************************************************************************
These functions do a map-like operation over types, performing some operation
on all variables and binding sites. Primarily used for zonking.
Note [Efficiency for mapCoercion ForAllCo case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As noted in Note [Forall coercions] in TyCoRep, a ForAllCo is a bit redundant.
It stores a TyVar and a Coercion, where the kind of the TyVar always matches
the left-hand kind of the coercion. This is convenient lots of the time, but
not when mapping a function over a coercion.
The problem is that tcm_tybinder will affect the TyVar's kind and
mapCoercion will affect the Coercion, and we hope that the results will be
the same. Even if they are the same (which should generally happen with
correct algorithms), then there is an efficiency issue. In particular,
this problem seems to make what should be a linear algorithm into a potentially
exponential one. But it's only going to be bad in the case where there's
lots of foralls in the kinds of other foralls. Like this:
forall a : (forall b : (forall c : ...). ...). ...
This construction seems unlikely. So we'll do the inefficient, easy way
for now.
Note [Specialising mappers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
These INLINABLE pragmas are indispensable. mapType/mapCoercion are used
to implement zonking, and it's vital that they get specialised to the TcM
monad. This specialisation happens automatically (that is, without a
SPECIALISE pragma) as long as the definitions are INLINABLE. For example,
this one change made a 20% allocation difference in perf/compiler/T5030.
-}
-- | This describes how a "map" operation over a type/coercion should behave
data TyCoMapper env m
= TyCoMapper
{ tcm_smart :: Bool -- ^ Should the new type be created with smart
-- constructors?
, tcm_tyvar :: env -> TyVar -> m Type
, tcm_covar :: env -> CoVar -> m Coercion
, tcm_hole :: env -> CoercionHole -> Role
-> Type -> Type -> m Coercion
-- ^ What to do with coercion holes. See Note [Coercion holes] in
-- TyCoRep.
, tcm_tybinder :: env -> TyVar -> VisibilityFlag -> m (env, TyVar)
-- ^ The returned env is used in the extended scope
}
{-# INLINABLE mapType #-} -- See Note [Specialising mappers]
mapType :: Monad m => TyCoMapper env m -> env -> Type -> m Type
mapType mapper@(TyCoMapper { tcm_smart = smart, tcm_tyvar = tyvar
, tcm_tybinder = tybinder })
env ty
= go ty
where
go (TyVarTy tv) = tyvar env tv
go (AppTy t1 t2) = mkappty <$> go t1 <*> go t2
go (TyConApp tc tys) = mktyconapp tc <$> mapM go tys
go (ForAllTy (Anon arg) res) = mkfunty <$> go arg <*> go res
go (ForAllTy (Named tv vis) inner)
= do { (env', tv') <- tybinder env tv vis
; inner' <- mapType mapper env' inner
; return $ ForAllTy (Named tv' vis) inner' }
go ty@(LitTy {}) = return ty
go (CastTy ty co) = mkcastty <$> go ty <*> mapCoercion mapper env co
go (CoercionTy co) = CoercionTy <$> mapCoercion mapper env co
(mktyconapp, mkappty, mkcastty, mkfunty)
| smart = (mkTyConApp, mkAppTy, mkCastTy, mkFunTy)
| otherwise = (TyConApp, AppTy, CastTy, ForAllTy . Anon)
{-# INLINABLE mapCoercion #-} -- See Note [Specialising mappers]
mapCoercion :: Monad m
=> TyCoMapper env m -> env -> Coercion -> m Coercion
mapCoercion mapper@(TyCoMapper { tcm_smart = smart, tcm_covar = covar
, tcm_hole = cohole, tcm_tybinder = tybinder })
env co
= go co
where
go (Refl r ty) = Refl r <$> mapType mapper env ty
go (TyConAppCo r tc args)
= mktyconappco r tc <$> mapM go args
go (AppCo c1 c2) = mkappco <$> go c1 <*> go c2
go (ForAllCo tv kind_co co)
= do { kind_co' <- go kind_co
; (env', tv') <- tybinder env tv Invisible
; co' <- mapCoercion mapper env' co
; return $ mkforallco tv' kind_co' co' }
-- See Note [Efficiency for mapCoercion ForAllCo case]
go (CoVarCo cv) = covar env cv
go (AxiomInstCo ax i args)
= mkaxiominstco ax i <$> mapM go args
go (UnivCo (HoleProv hole) r t1 t2)
= cohole env hole r t1 t2
go (UnivCo p r t1 t2)
= mkunivco <$> go_prov p <*> pure r
<*> mapType mapper env t1 <*> mapType mapper env t2
go (SymCo co) = mksymco <$> go co
go (TransCo c1 c2) = mktransco <$> go c1 <*> go c2
go (AxiomRuleCo r cos) = AxiomRuleCo r <$> mapM go cos
go (NthCo i co) = mknthco i <$> go co
go (LRCo lr co) = mklrco lr <$> go co
go (InstCo co arg) = mkinstco <$> go co <*> go arg
go (CoherenceCo c1 c2) = mkcoherenceco <$> go c1 <*> go c2
go (KindCo co) = mkkindco <$> go co
go (SubCo co) = mksubco <$> go co
go_prov UnsafeCoerceProv = return UnsafeCoerceProv
go_prov (PhantomProv co) = PhantomProv <$> go co
go_prov (ProofIrrelProv co) = ProofIrrelProv <$> go co
go_prov p@(PluginProv _) = return p
go_prov (HoleProv _) = panic "mapCoercion"
( mktyconappco, mkappco, mkaxiominstco, mkunivco
, mksymco, mktransco, mknthco, mklrco, mkinstco, mkcoherenceco
, mkkindco, mksubco, mkforallco)
| smart
= ( mkTyConAppCo, mkAppCo, mkAxiomInstCo, mkUnivCo
, mkSymCo, mkTransCo, mkNthCo, mkLRCo, mkInstCo, mkCoherenceCo
, mkKindCo, mkSubCo, mkForAllCo )
| otherwise
= ( TyConAppCo, AppCo, AxiomInstCo, UnivCo
, SymCo, TransCo, NthCo, LRCo, InstCo, CoherenceCo
, KindCo, SubCo, ForAllCo )
{-
************************************************************************
* *
\subsection{Constructor-specific functions}
* *
************************************************************************
---------------------------------------------------------------------
TyVarTy
~~~~~~~
-}
-- | Attempts to obtain the type variable underlying a 'Type', and panics with the
-- given message if this is not a type variable type. See also 'getTyVar_maybe'
getTyVar :: String -> Type -> TyVar
getTyVar msg ty = case getTyVar_maybe ty of
Just tv -> tv
Nothing -> panic ("getTyVar: " ++ msg)
isTyVarTy :: Type -> Bool
isTyVarTy ty = isJust (getTyVar_maybe ty)
-- | Attempts to obtain the type variable underlying a 'Type'
getTyVar_maybe :: Type -> Maybe TyVar
getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
| otherwise = repGetTyVar_maybe ty
-- | If the type is a tyvar, possibly under a cast, returns it, along
-- with the coercion. Thus, the co is :: kind tv ~R kind type
getCastedTyVar_maybe :: Type -> Maybe (TyVar, Coercion)
getCastedTyVar_maybe ty | Just ty' <- coreView ty = getCastedTyVar_maybe ty'
getCastedTyVar_maybe (CastTy (TyVarTy tv) co) = Just (tv, co)
getCastedTyVar_maybe (TyVarTy tv)
= Just (tv, mkReflCo Nominal (tyVarKind tv))
getCastedTyVar_maybe _ = Nothing
-- | Attempts to obtain the type variable underlying a 'Type', without
-- any expansion
repGetTyVar_maybe :: Type -> Maybe TyVar
repGetTyVar_maybe (TyVarTy tv) = Just tv
repGetTyVar_maybe _ = Nothing
allDistinctTyVars :: [KindOrType] -> Bool
allDistinctTyVars tkvs = go emptyVarSet tkvs
where
go _ [] = True
go so_far (ty : tys)
= case getTyVar_maybe ty of
Nothing -> False
Just tv | tv `elemVarSet` so_far -> False
| otherwise -> go (so_far `extendVarSet` tv) tys
{-
---------------------------------------------------------------------
AppTy
~~~~~
We need to be pretty careful with AppTy to make sure we obey the
invariant that a TyConApp is always visibly so. mkAppTy maintains the
invariant: use it.
Note [Decomposing fat arrow c=>t]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Can we unify (a b) with (Eq a => ty)? If we do so, we end up with
a partial application like ((=>) Eq a) which doesn't make sense in
source Haskell. In constrast, we *can* unify (a b) with (t1 -> t2).
Here's an example (Trac #9858) of how you might do it:
i :: (Typeable a, Typeable b) => Proxy (a b) -> TypeRep
i p = typeRep p
j = i (Proxy :: Proxy (Eq Int => Int))
The type (Proxy (Eq Int => Int)) is only accepted with -XImpredicativeTypes,
but suppose we want that. But then in the call to 'i', we end
up decomposing (Eq Int => Int), and we definitely don't want that.
This really only applies to the type checker; in Core, '=>' and '->'
are the same, as are 'Constraint' and '*'. But for now I've put
the test in repSplitAppTy_maybe, which applies throughout, because
the other calls to splitAppTy are in Unify, which is also used by
the type checker (e.g. when matching type-function equations).
-}
-- | Applies a type to another, as in e.g. @k a@
mkAppTy :: Type -> Type -> Type
mkAppTy (TyConApp tc tys) ty2 = mkTyConApp tc (tys ++ [ty2])
mkAppTy ty1 ty2 = AppTy ty1 ty2
-- Note that the TyConApp could be an
-- under-saturated type synonym. GHC allows that; e.g.
-- type Foo k = k a -> k a
-- type Id x = x
-- foo :: Foo Id -> Foo Id
--
-- Here Id is partially applied in the type sig for Foo,
-- but once the type synonyms are expanded all is well
mkAppTys :: Type -> [Type] -> Type
mkAppTys ty1 [] = ty1
mkAppTys (TyConApp tc tys1) tys2 = mkTyConApp tc (tys1 ++ tys2)
mkAppTys ty1 tys2 = foldl AppTy ty1 tys2
-------------
splitAppTy_maybe :: Type -> Maybe (Type, Type)
-- ^ Attempt to take a type application apart, whether it is a
-- function, type constructor, or plain type application. Note
-- that type family applications are NEVER unsaturated by this!
splitAppTy_maybe ty | Just ty' <- coreView ty
= splitAppTy_maybe ty'
splitAppTy_maybe ty = repSplitAppTy_maybe ty
-------------
repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
-- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
-- any Core view stuff is already done
repSplitAppTy_maybe (ForAllTy (Anon ty1) ty2)
= Just (TyConApp funTyCon [ty1], ty2)
repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
repSplitAppTy_maybe (TyConApp tc tys)
| mightBeUnsaturatedTyCon tc || tys `lengthExceeds` tyConArity tc
, Just (tys', ty') <- snocView tys
= Just (TyConApp tc tys', ty') -- Never create unsaturated type family apps!
repSplitAppTy_maybe _other = Nothing
-- this one doesn't braek apart (c => t).
-- See Note [Decomposing fat arrow c=>t]
-- Defined here to avoid module loops between Unify and TcType.
tcRepSplitAppTy_maybe :: Type -> Maybe (Type,Type)
-- ^ Does the AppTy split as in 'tcSplitAppTy_maybe', but assumes that
-- any coreView stuff is already done. Refuses to look through (c => t)
tcRepSplitAppTy_maybe (ForAllTy (Anon ty1) ty2)
| isConstraintKind (typeKind ty1) = Nothing -- See Note [Decomposing fat arrow c=>t]
| otherwise = Just (TyConApp funTyCon [ty1], ty2)
tcRepSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
tcRepSplitAppTy_maybe (TyConApp tc tys)
| mightBeUnsaturatedTyCon tc || tys `lengthExceeds` tyConArity tc
, Just (tys', ty') <- snocView tys
= Just (TyConApp tc tys', ty') -- Never create unsaturated type family apps!
tcRepSplitAppTy_maybe _other = Nothing
-------------
splitAppTy :: Type -> (Type, Type)
-- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
-- and panics if this is not possible
splitAppTy ty = case splitAppTy_maybe ty of
Just pr -> pr
Nothing -> panic "splitAppTy"
-------------
splitAppTys :: Type -> (Type, [Type])
-- ^ Recursively splits a type as far as is possible, leaving a residual
-- type being applied to and the type arguments applied to it. Never fails,
-- even if that means returning an empty list of type applications.
splitAppTys ty = split ty ty []
where
split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
split _ (AppTy ty arg) args = split ty ty (arg:args)
split _ (TyConApp tc tc_args) args
= let -- keep type families saturated
n | mightBeUnsaturatedTyCon tc = 0
| otherwise = tyConArity tc
(tc_args1, tc_args2) = splitAt n tc_args
in
(TyConApp tc tc_args1, tc_args2 ++ args)
split _ (ForAllTy (Anon ty1) ty2) args = ASSERT( null args )
(TyConApp funTyCon [], [ty1,ty2])
split orig_ty _ args = (orig_ty, args)
-- | Like 'splitAppTys', but doesn't look through type synonyms
repSplitAppTys :: Type -> (Type, [Type])
repSplitAppTys ty = split ty []
where
split (AppTy ty arg) args = split ty (arg:args)
split (TyConApp tc tc_args) args
= let n | mightBeUnsaturatedTyCon tc = 0
| otherwise = tyConArity tc
(tc_args1, tc_args2) = splitAt n tc_args
in
(TyConApp tc tc_args1, tc_args2 ++ args)
split (ForAllTy (Anon ty1) ty2) args = ASSERT( null args )
(TyConApp funTyCon [], [ty1, ty2])
split ty args = (ty, args)
{-
LitTy
~~~~~
-}
mkNumLitTy :: Integer -> Type
mkNumLitTy n = LitTy (NumTyLit n)
-- | Is this a numeric literal. We also look through type synonyms.
isNumLitTy :: Type -> Maybe Integer
isNumLitTy ty | Just ty1 <- coreView ty = isNumLitTy ty1
isNumLitTy (LitTy (NumTyLit n)) = Just n
isNumLitTy _ = Nothing
mkStrLitTy :: FastString -> Type
mkStrLitTy s = LitTy (StrTyLit s)
-- | Is this a symbol literal. We also look through type synonyms.
isStrLitTy :: Type -> Maybe FastString
isStrLitTy ty | Just ty1 <- coreView ty = isStrLitTy ty1
isStrLitTy (LitTy (StrTyLit s)) = Just s
isStrLitTy _ = Nothing
-- | Is this type a custom user error?
-- If so, give us the kind and the error message.
userTypeError_maybe :: Type -> Maybe Type
userTypeError_maybe t
= do { (tc, _kind : msg : _) <- splitTyConApp_maybe t
-- There may be more than 2 arguments, if the type error is
-- used as a type constructor (e.g. at kind `Type -> Type`).
; guard (tyConName tc == errorMessageTypeErrorFamName)
; return msg }
-- | Render a type corresponding to a user type error into a SDoc.
pprUserTypeErrorTy :: Type -> SDoc
pprUserTypeErrorTy ty =
case splitTyConApp_maybe ty of
-- Text "Something"
Just (tc,[txt])
| tyConName tc == typeErrorTextDataConName
, Just str <- isStrLitTy txt -> ftext str
-- ShowType t
Just (tc,[_k,t])
| tyConName tc == typeErrorShowTypeDataConName -> ppr t
-- t1 :<>: t2
Just (tc,[t1,t2])
| tyConName tc == typeErrorAppendDataConName ->
pprUserTypeErrorTy t1 <> pprUserTypeErrorTy t2
-- t1 :$$: t2
Just (tc,[t1,t2])
| tyConName tc == typeErrorVAppendDataConName ->
pprUserTypeErrorTy t1 $$ pprUserTypeErrorTy t2
-- An uneavaluated type function
_ -> ppr ty
{-
---------------------------------------------------------------------
FunTy
~~~~~
Function types are represented with (ForAllTy (Anon ...) ...)
-}
isFunTy :: Type -> Bool
isFunTy ty = isJust (splitFunTy_maybe ty)
splitFunTy :: Type -> (Type, Type)
-- ^ Attempts to extract the argument and result types from a type, and
-- panics if that is not possible. See also 'splitFunTy_maybe'
splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
splitFunTy (ForAllTy (Anon arg) res) = (arg, res)
splitFunTy other = pprPanic "splitFunTy" (ppr other)
splitFunTy_maybe :: Type -> Maybe (Type, Type)
-- ^ Attempts to extract the argument and result types from a type
splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
splitFunTy_maybe (ForAllTy (Anon arg) res) = Just (arg, res)
splitFunTy_maybe _ = Nothing
splitFunTys :: Type -> ([Type], Type)
splitFunTys ty = split [] ty ty
where
split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
split args _ (ForAllTy (Anon arg) res) = split (arg:args) res res
split args orig_ty _ = (reverse args, orig_ty)
splitFunTysN :: Int -> Type -> ([Type], Type)
-- ^ Split off exactly the given number argument types, and panics if that is not possible
splitFunTysN 0 ty = ([], ty)
splitFunTysN n ty = ASSERT2( isFunTy ty, int n <+> ppr ty )
case splitFunTy ty of { (arg, res) ->
case splitFunTysN (n-1) res of { (args, res) ->
(arg:args, res) }}
funResultTy :: Type -> Type
-- ^ Extract the function result type and panic if that is not possible
funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
funResultTy (ForAllTy (Anon {}) res) = res
funResultTy ty = pprPanic "funResultTy" (ppr ty)
funArgTy :: Type -> Type
-- ^ Extract the function argument type and panic if that is not possible
funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
funArgTy (ForAllTy (Anon arg) _res) = arg
funArgTy ty = pprPanic "funArgTy" (ppr ty)
piResultTy :: Type -> Type -> Type
-- ^ Just like 'piResultTys' but for a single argument
-- Try not to iterate 'piResultTy', because it's inefficient to substitute
-- one variable at a time; instead use 'piResultTys"
piResultTy ty arg
| Just ty' <- coreView ty = piResultTy ty' arg
| ForAllTy bndr res <- ty
= case bndr of
Anon {} -> res
Named tv _ -> substTy (extendTvSubst empty_subst tv arg) res
where
empty_subst = mkEmptyTCvSubst $ mkInScopeSet $
tyCoVarsOfTypes [arg,res]
| otherwise
= panic "piResultTys"
-- | (piResultTys f_ty [ty1, .., tyn]) gives the type of (f ty1 .. tyn)
-- where f :: f_ty
-- 'piResultTys' is interesting because:
-- 1. 'f_ty' may have more for-alls than there are args
-- 2. Less obviously, it may have fewer for-alls
-- For case 2. think of:
-- piResultTys (forall a.a) [forall b.b, Int]
-- This really can happen, but only (I think) in situations involving
-- undefined. For example:
-- undefined :: forall a. a
-- Term: undefined @(forall b. b->b) @Int
-- This term should have type (Int -> Int), but notice that
-- there are more type args than foralls in 'undefined's type.
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
-- This is a heavily used function (e.g. from typeKind),
-- so we pay attention to efficiency, especially in the special case
-- where there are no for-alls so we are just dropping arrows from
-- a function type/kind.
piResultTys :: Type -> [Type] -> Type
piResultTys ty [] = ty
piResultTys ty orig_args@(arg:args)
| Just ty' <- coreView ty
= piResultTys ty' orig_args
| ForAllTy bndr res <- ty
= case bndr of
Anon {} -> piResultTys res args
Named tv _ -> go (extendVarEnv emptyTvSubstEnv tv arg) res args
| otherwise
= panic "piResultTys"
where
go :: TvSubstEnv -> Type -> [Type] -> Type
go tv_env ty [] = substTy (mkTvSubst in_scope tv_env) ty
where
in_scope = mkInScopeSet (tyCoVarsOfTypes (ty:orig_args))
go tv_env ty all_args@(arg:args)
| Just ty' <- coreView ty
= go tv_env ty' all_args
| ForAllTy bndr res <- ty
= case bndr of
Anon _ -> go tv_env res args
Named tv _ -> go (extendVarEnv tv_env tv arg) res args
| TyVarTy tv <- ty
, Just ty' <- lookupVarEnv tv_env tv
-- Deals with piResultTys (forall a. a) [forall b.b, Int]
= piResultTys ty' all_args
| otherwise
= panic "piResultTys"
{-
---------------------------------------------------------------------
TyConApp
~~~~~~~~
-}
-- | A key function: builds a 'TyConApp' or 'FunTy' as appropriate to
-- its arguments. Applies its arguments to the constructor from left to right.
mkTyConApp :: TyCon -> [Type] -> Type
mkTyConApp tycon tys
| isFunTyCon tycon, [ty1,ty2] <- tys
= ForAllTy (Anon ty1) ty2
| otherwise
= TyConApp tycon tys
-- splitTyConApp "looks through" synonyms, because they don't
-- mean a distinct type, but all other type-constructor applications
-- including functions are returned as Just ..
-- | Retrieve the tycon heading this type, if there is one. Does /not/
-- look through synonyms.
tyConAppTyConPicky_maybe :: Type -> Maybe TyCon
tyConAppTyConPicky_maybe (TyConApp tc _) = Just tc
tyConAppTyConPicky_maybe (ForAllTy (Anon _) _) = Just funTyCon
tyConAppTyConPicky_maybe _ = Nothing
-- | The same as @fst . splitTyConApp@
tyConAppTyCon_maybe :: Type -> Maybe TyCon
tyConAppTyCon_maybe ty | Just ty' <- coreView ty = tyConAppTyCon_maybe ty'
tyConAppTyCon_maybe (TyConApp tc _) = Just tc
tyConAppTyCon_maybe (ForAllTy (Anon _) _) = Just funTyCon
tyConAppTyCon_maybe _ = Nothing
tyConAppTyCon :: Type -> TyCon
tyConAppTyCon ty = tyConAppTyCon_maybe ty `orElse` pprPanic "tyConAppTyCon" (ppr ty)
-- | The same as @snd . splitTyConApp@
tyConAppArgs_maybe :: Type -> Maybe [Type]
tyConAppArgs_maybe ty | Just ty' <- coreView ty = tyConAppArgs_maybe ty'
tyConAppArgs_maybe (TyConApp _ tys) = Just tys
tyConAppArgs_maybe (ForAllTy (Anon arg) res) = Just [arg,res]
tyConAppArgs_maybe _ = Nothing
tyConAppArgs :: Type -> [Type]
tyConAppArgs ty = tyConAppArgs_maybe ty `orElse` pprPanic "tyConAppArgs" (ppr ty)
tyConAppArgN :: Int -> Type -> Type
-- Executing Nth
tyConAppArgN n ty
= case tyConAppArgs_maybe ty of
Just tys -> ASSERT2( n < length tys, ppr n <+> ppr tys ) tys `getNth` n
Nothing -> pprPanic "tyConAppArgN" (ppr n <+> ppr ty)
-- | Attempts to tease a type apart into a type constructor and the application
-- of a number of arguments to that constructor. Panics if that is not possible.
-- See also 'splitTyConApp_maybe'
splitTyConApp :: Type -> (TyCon, [Type])
splitTyConApp ty = case splitTyConApp_maybe ty of
Just stuff -> stuff
Nothing -> pprPanic "splitTyConApp" (ppr ty)
-- | Attempts to tease a type apart into a type constructor and the application
-- of a number of arguments to that constructor
splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
splitTyConApp_maybe ty = repSplitTyConApp_maybe ty
-- | Like 'splitTyConApp_maybe', but doesn't look through synonyms. This
-- assumes the synonyms have already been dealt with.
repSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
repSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
repSplitTyConApp_maybe (ForAllTy (Anon arg) res) = Just (funTyCon, [arg,res])
repSplitTyConApp_maybe _ = Nothing
-- | Attempts to tease a list type apart and gives the type of the elements if
-- successful (looks through type synonyms)
splitListTyConApp_maybe :: Type -> Maybe Type
splitListTyConApp_maybe ty = case splitTyConApp_maybe ty of
Just (tc,[e]) | tc == listTyCon -> Just e
_other -> Nothing
-- | What is the role assigned to the next parameter of this type? Usually,
-- this will be 'Nominal', but if the type is a 'TyConApp', we may be able to
-- do better. The type does *not* have to be well-kinded when applied for this
-- to work!
nextRole :: Type -> Role
nextRole ty
| Just (tc, tys) <- splitTyConApp_maybe ty
, let num_tys = length tys
, num_tys < tyConArity tc
= tyConRoles tc `getNth` num_tys
| otherwise
= Nominal
newTyConInstRhs :: TyCon -> [Type] -> Type
-- ^ Unwrap one 'layer' of newtype on a type constructor and its
-- arguments, using an eta-reduced version of the @newtype@ if possible.
-- This requires tys to have at least @newTyConInstArity tycon@ elements.
newTyConInstRhs tycon tys
= ASSERT2( tvs `leLength` tys, ppr tycon $$ ppr tys $$ ppr tvs )
applyTysX tvs rhs tys
where
(tvs, rhs) = newTyConEtadRhs tycon
{-
---------------------------------------------------------------------
CastTy
~~~~~~
A casted type has its *kind* casted into something new.
Note [Weird typing rule for ForAllTy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is the (truncated) typing rule for the dependent ForAllTy:
inner : kind
------------------------------------
ForAllTy (Named tv vis) inner : kind
Note that neither the inner type nor for ForAllTy itself have to have
kind *! But, it means that we should push any kind casts through the
ForAllTy. The only trouble is avoiding capture.
-}
splitCastTy_maybe :: Type -> Maybe (Type, Coercion)
splitCastTy_maybe ty | Just ty' <- coreView ty = splitCastTy_maybe ty'
splitCastTy_maybe (CastTy ty co) = Just (ty, co)
splitCastTy_maybe _ = Nothing
-- | Make a 'CastTy'. The Coercion must be nominal. This function looks
-- at the entire structure of the type and coercion in an attempt to
-- maintain representation invariance (that is, any two types that are `eqType`
-- look the same). Be very wary of calling this in a loop.
mkCastTy :: Type -> Coercion -> Type
-- Running example:
-- T :: forall k1. k1 -> forall k2. k2 -> Bool -> Maybe k1 -> *
-- co :: * ~R X (maybe X is a newtype around *)
-- ty = T Nat 3 Symbol "foo" True (Just 2)
--
-- We wish to "push" the cast down as far as possible. See also
-- Note [Pushing down casts] in TyCoRep. Here is where we end
-- up:
--
-- (T Nat 3 Symbol |> <Symbol> -> <Bool> -> <Maybe Nat> -> co)
-- "foo" True (Just 2)
--
mkCastTy ty co | isReflexiveCo co = ty
-- NB: Do the slow check here. This is important to keep the splitXXX
-- functions working properly. Otherwise, we may end up with something
-- like (((->) |> something_reflexive_but_not_obviously_so) biz baz)
-- fails under splitFunTy_maybe. This happened with the cheaper check
-- in test dependent/should_compile/dynamic-paper.
mkCastTy (CastTy ty co1) co2 = mkCastTy ty (co1 `mkTransCo` co2)
-- See Note [Weird typing rule for ForAllTy]
mkCastTy (ForAllTy (Named tv vis) inner_ty) co
= -- have to make sure that pushing the co in doesn't capture the bound var
let fvs = tyCoVarsOfCo co
empty_subst = mkEmptyTCvSubst (mkInScopeSet fvs)
(subst, tv') = substTyVarBndr empty_subst tv
in
ForAllTy (Named tv' vis) (substTy subst inner_ty `mkCastTy` co)
mkCastTy ty co = -- NB: don't check if the coercion "from" type matches here;
-- there may be unzonked variables about
let result = split_apps [] ty co in
ASSERT2( CastTy ty co `eqType` result
, ppr ty <+> dcolon <+> ppr (typeKind ty) $$
ppr co <+> dcolon <+> ppr (coercionKind co) $$
ppr result <+> dcolon <+> ppr (typeKind result) )
result
where
-- split_apps breaks apart any type applications, so we can see how far down
-- to push the cast
split_apps args (AppTy t1 t2) co
= split_apps (t2:args) t1 co
split_apps args (TyConApp tc tc_args) co
| mightBeUnsaturatedTyCon tc
= affix_co (tyConBinders tc) (mkTyConTy tc) (tc_args `chkAppend` args) co
| otherwise -- not decomposable... but it may still be oversaturated
= let (non_decomp_args, decomp_args) = splitAt (tyConArity tc) tc_args
saturated_tc = mkTyConApp tc non_decomp_args
in
affix_co (fst $ splitPiTys $ typeKind saturated_tc)
saturated_tc (decomp_args `chkAppend` args) co
split_apps args (ForAllTy (Anon arg) res) co
= affix_co (tyConBinders funTyCon) (mkTyConTy funTyCon)
(arg : res : args) co
split_apps args ty co
= affix_co (fst $ splitPiTys $ typeKind ty)
ty args co
-- having broken everything apart, this figures out the point at which there
-- are no more dependent quantifications, and puts the cast there
affix_co _ ty [] co = no_double_casts ty co
affix_co bndrs ty args co
-- if kind contains any dependent quantifications, we can't push.
-- apply arguments until it doesn't
= let (no_dep_bndrs, some_dep_bndrs) = spanEnd isAnonBinder bndrs
(some_dep_args, rest_args) = splitAtList some_dep_bndrs args
dep_subst = zipTyBinderSubst some_dep_bndrs some_dep_args
used_no_dep_bndrs = takeList rest_args no_dep_bndrs
rest_arg_tys = substTys dep_subst (map binderType used_no_dep_bndrs)
co' = mkFunCos Nominal
(map (mkReflCo Nominal) rest_arg_tys)
co
in
((ty `mkAppTys` some_dep_args) `no_double_casts` co') `mkAppTys` rest_args
no_double_casts (CastTy ty co1) co2 = CastTy ty (co1 `mkTransCo` co2)
no_double_casts ty co = CastTy ty co
{-
--------------------------------------------------------------------
CoercionTy
~~~~~~~~~~
CoercionTy allows us to inject coercions into types. A CoercionTy
should appear only in the right-hand side of an application.
-}
mkCoercionTy :: Coercion -> Type
mkCoercionTy = CoercionTy
isCoercionTy :: Type -> Bool
isCoercionTy (CoercionTy _) = True
isCoercionTy _ = False
isCoercionTy_maybe :: Type -> Maybe Coercion
isCoercionTy_maybe (CoercionTy co) = Just co
isCoercionTy_maybe _ = Nothing
stripCoercionTy :: Type -> Coercion
stripCoercionTy (CoercionTy co) = co
stripCoercionTy ty = pprPanic "stripCoercionTy" (ppr ty)
{-
---------------------------------------------------------------------
SynTy
~~~~~
Notes on type synonyms
~~~~~~~~~~~~~~~~~~~~~~
The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
to return type synonyms wherever possible. Thus
type Foo a = a -> a
we want
splitFunTys (a -> Foo a) = ([a], Foo a)
not ([a], a -> a)
The reason is that we then get better (shorter) type signatures in
interfaces. Notably this plays a role in tcTySigs in TcBinds.hs.
Representation types
~~~~~~~~~~~~~~~~~~~~
Note [Nullary unboxed tuple]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We represent the nullary unboxed tuple as the unary (but void) type
Void#. The reason for this is that the ReprArity is never
less than the Arity (as it would otherwise be for a function type like
(# #) -> Int).
As a result, ReprArity is always strictly positive if Arity is. This
is important because it allows us to distinguish at runtime between a
thunk and a function takes a nullary unboxed tuple as an argument!
-}
type UnaryType = Type
data RepType = UbxTupleRep [UnaryType] -- INVARIANT: never an empty list (see Note [Nullary unboxed tuple])
| UnaryRep UnaryType
instance Outputable RepType where
ppr (UbxTupleRep tys) = text "UbxTupleRep" <+> ppr tys
ppr (UnaryRep ty) = text "UnaryRep" <+> ppr ty
flattenRepType :: RepType -> [UnaryType]
flattenRepType (UbxTupleRep tys) = tys
flattenRepType (UnaryRep ty) = [ty]
-- | Looks through:
--
-- 1. For-alls
-- 2. Synonyms
-- 3. Predicates
-- 4. All newtypes, including recursive ones, but not newtype families
-- 5. Casts
--
-- It's useful in the back end of the compiler.
repType :: Type -> RepType
repType ty
= go initRecTc ty
where
go :: RecTcChecker -> Type -> RepType
go rec_nts ty -- Expand predicates and synonyms
| Just ty' <- coreView ty
= go rec_nts ty'
go rec_nts (ForAllTy (Named {}) ty2) -- Drop type foralls
= go rec_nts ty2
go rec_nts (TyConApp tc tys) -- Expand newtypes
| isNewTyCon tc
, tys `lengthAtLeast` tyConArity tc
, Just rec_nts' <- checkRecTc rec_nts tc -- See Note [Expanding newtypes] in TyCon
= go rec_nts' (newTyConInstRhs tc tys)
| isUnboxedTupleTyCon tc
= if null tys
then UnaryRep voidPrimTy -- See Note [Nullary unboxed tuple]
else UbxTupleRep (concatMap (flattenRepType . go rec_nts) non_rr_tys)
where
-- See Note [Unboxed tuple RuntimeRep vars] in TyCon
non_rr_tys = dropRuntimeRepArgs tys
go rec_nts (CastTy ty _)
= go rec_nts ty
go _ ty@(CoercionTy _)
= pprPanic "repType" (ppr ty)
go _ ty = UnaryRep ty
-- ToDo: this could be moved to the code generator, using splitTyConApp instead
-- of inspecting the type directly.
-- | Discovers the primitive representation of a more abstract 'UnaryType'
typePrimRep :: UnaryType -> PrimRep
typePrimRep ty = kindPrimRep (typeKind ty)
-- | Find the primitive representation of a 'TyCon'. Defined here to
-- avoid module loops. Call this only on unlifted tycons.
tyConPrimRep :: TyCon -> PrimRep
tyConPrimRep tc = kindPrimRep res_kind
where
res_kind = tyConResKind tc
-- | Take a kind (of shape @TYPE rr@) and produce the 'PrimRep' of values
-- of types of this kind.
kindPrimRep :: Kind -> PrimRep
kindPrimRep ki | Just ki' <- coreViewOneStarKind ki = kindPrimRep ki'
kindPrimRep (TyConApp typ [runtime_rep])
= ASSERT( typ `hasKey` tYPETyConKey )
go runtime_rep
where
go rr | Just rr' <- coreView rr = go rr'
go (TyConApp rr_dc args)
| RuntimeRep fun <- tyConRuntimeRepInfo rr_dc
= fun args
go rr = pprPanic "kindPrimRep.go" (ppr rr)
kindPrimRep ki = WARN( True
, text "kindPrimRep defaulting to PtrRep on" <+> ppr ki )
PtrRep -- this can happen legitimately for, e.g., Any
typeRepArity :: Arity -> Type -> RepArity
typeRepArity 0 _ = 0
typeRepArity n ty = case repType ty of
UnaryRep (ForAllTy bndr ty) -> length (flattenRepType (repType (binderType bndr))) + typeRepArity (n - 1) ty
_ -> pprPanic "typeRepArity: arity greater than type can handle" (ppr (n, ty, repType ty))
isVoidTy :: Type -> Bool
-- True if the type has zero width
isVoidTy ty = case repType ty of
UnaryRep (TyConApp tc _) -> isUnliftedTyCon tc &&
isVoidRep (tyConPrimRep tc)
_ -> False
{-
Note [AppTy rep]
~~~~~~~~~~~~~~~~
Types of the form 'f a' must be of kind *, not #, so we are guaranteed
that they are represented by pointers. The reason is that f must have
kind (kk -> kk) and kk cannot be unlifted; see Note [The kind invariant]
in TyCoRep.
---------------------------------------------------------------------
ForAllTy
~~~~~~~~
-}
mkForAllTy :: TyBinder -> Type -> Type
mkForAllTy = ForAllTy
-- | Make a dependent forall.
mkNamedForAllTy :: TyVar -> VisibilityFlag -> Type -> Type
mkNamedForAllTy tv vis = ASSERT( isTyVar tv )
ForAllTy (Named tv vis)
-- | Like mkForAllTys, but assumes all variables are dependent and invisible,
-- a common case
mkInvForAllTys :: [TyVar] -> Type -> Type
mkInvForAllTys tvs = ASSERT( all isTyVar tvs )
mkForAllTys (map (flip Named Invisible) tvs)
-- | Like mkForAllTys, but assumes all variables are dependent and specified,
-- a common case
mkSpecForAllTys :: [TyVar] -> Type -> Type
mkSpecForAllTys tvs = ASSERT( all isTyVar tvs )
mkForAllTys (map (flip Named Specified) tvs)
-- | Like mkForAllTys, but assumes all variables are dependent and visible
mkVisForAllTys :: [TyVar] -> Type -> Type
mkVisForAllTys tvs = ASSERT( all isTyVar tvs )
mkForAllTys (map (flip Named Visible) tvs)
mkPiType :: Var -> Type -> Type
-- ^ Makes a @(->)@ type or an implicit forall type, depending
-- on whether it is given a type variable or a term variable.
-- This is used, for example, when producing the type of a lambda.
-- Always uses Invisible binders.
mkPiTypes :: [Var] -> Type -> Type
-- ^ 'mkPiType' for multiple type or value arguments
mkPiType v ty
| isTyVar v = mkForAllTy (Named v Invisible) ty
| otherwise = mkForAllTy (Anon (varType v)) ty
mkPiTypes vs ty = foldr mkPiType ty vs
-- | Given a list of type-level vars and a result type, makes TyBinders, preferring
-- anonymous binders if the variable is, in fact, not dependent.
-- All binders are /visible/.
mkTyBindersPreferAnon :: [TyVar] -> Type -> [TyBinder]
mkTyBindersPreferAnon vars inner_ty = fst $ go vars inner_ty
where
go :: [TyVar] -> Type -> ([TyBinder], VarSet) -- also returns the free vars
go [] ty = ([], tyCoVarsOfType ty)
go (v:vs) ty | v `elemVarSet` fvs
= ( Named v Visible : binders
, fvs `delVarSet` v `unionVarSet` kind_vars )
| otherwise
= ( Anon (tyVarKind v) : binders
, fvs `unionVarSet` kind_vars )
where
(binders, fvs) = go vs ty
kind_vars = tyCoVarsOfType $ tyVarKind v
-- | Take a ForAllTy apart, returning the list of tyvars and the result type.
-- This always succeeds, even if it returns only an empty list. Note that the
-- result type returned may have free variables that were bound by a forall.
splitForAllTys :: Type -> ([TyVar], Type)
splitForAllTys ty = split ty ty []
where
split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
split _ (ForAllTy (Named tv _) ty) tvs = split ty ty (tv:tvs)
split orig_ty _ tvs = (reverse tvs, orig_ty)
-- | Split off all TyBinders to a type, splitting both proper foralls
-- and functions
splitPiTys :: Type -> ([TyBinder], Type)
splitPiTys ty = split ty ty []
where
split orig_ty ty bs | Just ty' <- coreView ty = split orig_ty ty' bs
split _ (ForAllTy b res) bs = split res res (b:bs)
split orig_ty _ bs = (reverse bs, orig_ty)
-- | Like 'splitPiTys' but split off only /named/ binders.
splitNamedPiTys :: Type -> ([TyBinder], Type)
splitNamedPiTys ty = split ty ty []
where
split orig_ty ty bs | Just ty' <- coreView ty = split orig_ty ty' bs
split _ (ForAllTy b@(Named {}) res) bs = split res res (b:bs)
split orig_ty _ bs = (reverse bs, orig_ty)
-- | Checks whether this is a proper forall (with a named binder)
isForAllTy :: Type -> Bool
isForAllTy (ForAllTy (Named {}) _) = True
isForAllTy _ = False
-- | Is this a function or forall?
isPiTy :: Type -> Bool
isPiTy (ForAllTy {}) = True
isPiTy _ = False
-- | Take a forall type apart, or panics if that is not possible.
splitForAllTy :: Type -> (TyVar, Type)
splitForAllTy ty
| Just answer <- splitForAllTy_maybe ty = answer
| otherwise = pprPanic "splitForAllTy" (ppr ty)
-- | Attempts to take a forall type apart, but only if it's a proper forall,
-- with a named binder
splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
splitForAllTy_maybe ty = splitFAT_m ty
where
splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
splitFAT_m (ForAllTy (Named tv _) ty) = Just (tv, ty)
splitFAT_m _ = Nothing
-- | Attempts to take a forall type apart; works with proper foralls and
-- functions
splitPiTy_maybe :: Type -> Maybe (TyBinder, Type)
splitPiTy_maybe ty = go ty
where
go ty | Just ty' <- coreView ty = go ty'
go (ForAllTy bndr ty) = Just (bndr, ty)
go _ = Nothing
-- | Takes a forall type apart, or panics
splitPiTy :: Type -> (TyBinder, Type)
splitPiTy ty
| Just answer <- splitPiTy_maybe ty = answer
| otherwise = pprPanic "splitPiTy" (ppr ty)
-- | Drops all non-anonymous ForAllTys
dropForAlls :: Type -> Type
dropForAlls ty | Just ty' <- coreView ty = dropForAlls ty'
| otherwise = go ty
where
go (ForAllTy (Named {}) res) = go res
go res = res
-- | Given a tycon and its arguments, filters out any invisible arguments
filterOutInvisibleTypes :: TyCon -> [Type] -> [Type]
filterOutInvisibleTypes tc tys = snd $ partitionInvisibles tc id tys
-- | Like 'filterOutInvisibles', but works on 'TyVar's
filterOutInvisibleTyVars :: TyCon -> [TyVar] -> [TyVar]
filterOutInvisibleTyVars tc tvs = snd $ partitionInvisibles tc mkTyVarTy tvs
-- | Given a tycon and a list of things (which correspond to arguments),
-- partitions the things into the invisible ones and the visible ones.
-- The callback function is necessary for this scenario:
--
-- > T :: forall k. k -> k
-- > partitionInvisibles T [forall m. m -> m -> m, S, R, Q]
--
-- After substituting, we get
--
-- > T (forall m. m -> m -> m) :: (forall m. m -> m -> m) -> forall n. n -> n -> n
--
-- Thus, the first argument is invisible, @S@ is visible, @R@ is invisible again,
-- and @Q@ is visible.
--
-- If you're absolutely sure that your tycon's kind doesn't end in a variable,
-- it's OK if the callback function panics, as that's the only time it's
-- consulted.
partitionInvisibles :: TyCon -> (a -> Type) -> [a] -> ([a], [a])
partitionInvisibles tc get_ty = go emptyTCvSubst (tyConKind tc)
where
go _ _ [] = ([], [])
go subst (ForAllTy bndr res_ki) (x:xs)
| isVisibleBinder bndr = second (x :) (go subst' res_ki xs)
| otherwise = first (x :) (go subst' res_ki xs)
where
subst' = extendTvSubstBinder subst bndr (get_ty x)
go subst (TyVarTy tv) xs
| Just ki <- lookupTyVar subst tv = go subst ki xs
go _ _ xs = ([], xs) -- something is ill-kinded. But this can happen
-- when printing errors. Assume everything is visible.
-- like splitPiTys, but returns only *invisible* binders, including constraints
splitPiTysInvisible :: Type -> ([TyBinder], Type)
splitPiTysInvisible ty = split ty ty []
where
split orig_ty ty bndrs
| Just ty' <- coreView ty = split orig_ty ty' bndrs
split _ (ForAllTy bndr ty) bndrs
| isInvisibleBinder bndr
= split ty ty (bndr:bndrs)
split orig_ty _ bndrs
= (reverse bndrs, orig_ty)
applyTysX :: [TyVar] -> Type -> [Type] -> Type
-- applyTyxX beta-reduces (/\tvs. body_ty) arg_tys
-- Assumes that (/\tvs. body_ty) is closed
applyTysX tvs body_ty arg_tys
= ASSERT2( length arg_tys >= n_tvs, pp_stuff )
ASSERT2( tyCoVarsOfType body_ty `subVarSet` mkVarSet tvs, pp_stuff )
mkAppTys (substTyWith tvs (take n_tvs arg_tys) body_ty)
(drop n_tvs arg_tys)
where
pp_stuff = vcat [ppr tvs, ppr body_ty, ppr arg_tys]
n_tvs = length tvs
{-
%************************************************************************
%* *
TyBinders
%* *
%************************************************************************
-}
-- | Make a named binder
mkNamedBinder :: VisibilityFlag -> Var -> TyBinder
mkNamedBinder vis var = Named var vis
-- | Make an anonymous binder
mkAnonBinder :: Type -> TyBinder
mkAnonBinder = Anon
-- | Does this binder bind a variable that is /not/ erased? Returns
-- 'True' for anonymous binders.
isIdLikeBinder :: TyBinder -> Bool
isIdLikeBinder (Named {}) = False
isIdLikeBinder (Anon {}) = True
-- | Does this type, when used to the left of an arrow, require
-- a visible argument? This checks to see if the kind of the type
-- is constraint.
isVisibleType :: Type -> Bool
isVisibleType = not . isPredTy
binderVisibility :: TyBinder -> VisibilityFlag
binderVisibility (Named _ vis) = vis
binderVisibility (Anon ty)
| isVisibleType ty = Visible
| otherwise = Invisible
-- | Extract a bound variable in a binder, if any
binderVar_maybe :: TyBinder -> Maybe Var
binderVar_maybe (Named v _) = Just v
binderVar_maybe (Anon {}) = Nothing
-- | Extract a bound variable in a binder, or panics
binderVar :: String -- ^ printed if there is a panic
-> TyBinder -> Var
binderVar _ (Named v _) = v
binderVar e (Anon t) = pprPanic ("binderVar (" ++ e ++ ")") (ppr t)
-- | Extract a relevant type, if there is one.
binderRelevantType_maybe :: TyBinder -> Maybe Type
binderRelevantType_maybe (Named {}) = Nothing
binderRelevantType_maybe (Anon ty) = Just ty
-- | Like 'maybe', but for binders.
caseBinder :: TyBinder -- ^ binder to scrutinize
-> (TyVar -> a) -- ^ named case
-> (Type -> a) -- ^ anonymous case
-> a
caseBinder (Named v _) f _ = f v
caseBinder (Anon t) _ d = d t
-- | Break apart a list of binders into tyvars and anonymous types.
partitionBinders :: [TyBinder] -> ([TyVar], [Type])
partitionBinders = partitionWith named_or_anon
where
named_or_anon bndr = caseBinder bndr Left Right
-- | Break apart a list of binders into a list of named binders and
-- a list of anonymous types.
partitionBindersIntoBinders :: [TyBinder] -> ([TyBinder], [Type])
partitionBindersIntoBinders = partitionWith named_or_anon
where
named_or_anon bndr = caseBinder bndr (\_ -> Left bndr) Right
{-
%************************************************************************
%* *
Pred
* *
************************************************************************
Predicates on PredType
Note [isPredTy complications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You would think that we could define
isPredTy ty = isConstraintKind (typeKind ty)
But there are a number of complications:
* isPredTy is used when printing types, which can happen in debug
printing during type checking of not-fully-zonked types. So it's
not cool to say isConstraintKind (typeKind ty) because, absent
zonking, the type might be ill-kinded, and typeKind crashes. Hence the
rather tiresome story here
* isPredTy must return "True" to *unlifted* coercions, such as (t1 ~# t2)
and (t1 ~R# t2), which are not of kind Constraint! Currently they are
of kind #.
* If we do form the type '(C a => C [a]) => blah', then we'd like to
print it as such. But that means that isPredTy must return True for
(C a => C [a]). Admittedly that type is illegal in Haskell, but we
want to print it nicely in error messages.
-}
-- | Is the type suitable to classify a given/wanted in the typechecker?
isPredTy :: Type -> Bool
-- See Note [isPredTy complications]
isPredTy ty = go ty []
where
go :: Type -> [KindOrType] -> Bool
go (AppTy ty1 ty2) args = go ty1 (ty2 : args)
go (TyVarTy tv) args = go_k (tyVarKind tv) args
go (TyConApp tc tys) args = ASSERT( null args ) -- TyConApp invariant
go_tc tc tys
go (ForAllTy (Anon arg) res) []
| isPredTy arg = isPredTy res -- (Eq a => C a)
| otherwise = False -- (Int -> Bool)
go (ForAllTy (Named {}) ty) [] = go ty []
go _ _ = False
go_tc :: TyCon -> [KindOrType] -> Bool
go_tc tc args
| tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey
= length args == 4 -- ~# and ~R# sadly have result kind #
-- not Contraint; but we still want
-- isPredTy to reply True.
| otherwise = go_k (tyConKind tc) args
go_k :: Kind -> [KindOrType] -> Bool
-- True <=> ('k' applied to 'kts') = Constraint
go_k k args = isConstraintKind (piResultTys k args)
isClassPred, isEqPred, isNomEqPred, isIPPred :: PredType -> Bool
isClassPred ty = case tyConAppTyCon_maybe ty of
Just tyCon | isClassTyCon tyCon -> True
_ -> False
isEqPred ty = case tyConAppTyCon_maybe ty of
Just tyCon -> tyCon `hasKey` eqPrimTyConKey
|| tyCon `hasKey` eqReprPrimTyConKey
_ -> False
isNomEqPred ty = case tyConAppTyCon_maybe ty of
Just tyCon -> tyCon `hasKey` eqPrimTyConKey
_ -> False
isIPPred ty = case tyConAppTyCon_maybe ty of
Just tc -> isIPTyCon tc
_ -> False
isIPTyCon :: TyCon -> Bool
isIPTyCon tc = tc `hasKey` ipClassKey
-- Class and its corresponding TyCon have the same Unique
isIPClass :: Class -> Bool
isIPClass cls = cls `hasKey` ipClassKey
isCTupleClass :: Class -> Bool
isCTupleClass cls = isTupleTyCon (classTyCon cls)
isIPPred_maybe :: Type -> Maybe (FastString, Type)
isIPPred_maybe ty =
do (tc,[t1,t2]) <- splitTyConApp_maybe ty
guard (isIPTyCon tc)
x <- isStrLitTy t1
return (x,t2)
{-
Make PredTypes
--------------------- Equality types ---------------------------------
-}
-- | Makes a lifted equality predicate at the given role
mkPrimEqPredRole :: Role -> Type -> Type -> PredType
mkPrimEqPredRole Nominal = mkPrimEqPred
mkPrimEqPredRole Representational = mkReprPrimEqPred
mkPrimEqPredRole Phantom = panic "mkPrimEqPredRole phantom"
-- | Creates a primitive type equality predicate.
-- Invariant: the types are not Coercions
mkPrimEqPred :: Type -> Type -> Type
mkPrimEqPred ty1 ty2
= TyConApp eqPrimTyCon [k1, k2, ty1, ty2]
where
k1 = typeKind ty1
k2 = typeKind ty2
-- | Creates a primite type equality predicate with explicit kinds
mkHeteroPrimEqPred :: Kind -> Kind -> Type -> Type -> Type
mkHeteroPrimEqPred k1 k2 ty1 ty2 = TyConApp eqPrimTyCon [k1, k2, ty1, ty2]
-- | Creates a primitive representational type equality predicate
-- with explicit kinds
mkHeteroReprPrimEqPred :: Kind -> Kind -> Type -> Type -> Type
mkHeteroReprPrimEqPred k1 k2 ty1 ty2
= TyConApp eqReprPrimTyCon [k1, k2, ty1, ty2]
-- | Try to split up a coercion type into the types that it coerces
splitCoercionType_maybe :: Type -> Maybe (Type, Type)
splitCoercionType_maybe ty
= do { (tc, [_, _, ty1, ty2]) <- splitTyConApp_maybe ty
; guard $ tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey
; return (ty1, ty2) }
mkReprPrimEqPred :: Type -> Type -> Type
mkReprPrimEqPred ty1 ty2
= TyConApp eqReprPrimTyCon [k1, k2, ty1, ty2]
where
k1 = typeKind ty1
k2 = typeKind ty2
equalityTyCon :: Role -> TyCon
equalityTyCon Nominal = eqPrimTyCon
equalityTyCon Representational = eqReprPrimTyCon
equalityTyCon Phantom = eqPhantPrimTyCon
-- --------------------- Dictionary types ---------------------------------
mkClassPred :: Class -> [Type] -> PredType
mkClassPred clas tys = TyConApp (classTyCon clas) tys
isDictTy :: Type -> Bool
isDictTy = isClassPred
isDictLikeTy :: Type -> Bool
-- Note [Dictionary-like types]
isDictLikeTy ty | Just ty' <- coreView ty = isDictLikeTy ty'
isDictLikeTy ty = case splitTyConApp_maybe ty of
Just (tc, tys) | isClassTyCon tc -> True
| isTupleTyCon tc -> all isDictLikeTy tys
_other -> False
{-
Note [Dictionary-like types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Being "dictionary-like" means either a dictionary type or a tuple thereof.
In GHC 6.10 we build implication constraints which construct such tuples,
and if we land up with a binding
t :: (C [a], Eq [a])
t = blah
then we want to treat t as cheap under "-fdicts-cheap" for example.
(Implication constraints are normally inlined, but sadly not if the
occurrence is itself inside an INLINE function! Until we revise the
handling of implication constraints, that is.) This turned out to
be important in getting good arities in DPH code. Example:
class C a
class D a where { foo :: a -> a }
instance C a => D (Maybe a) where { foo x = x }
bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b)
{-# INLINE bar #-}
bar x y = (foo (Just x), foo (Just y))
Then 'bar' should jolly well have arity 4 (two dicts, two args), but
we ended up with something like
bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ...
in \x,y. <blah>)
This is all a bit ad-hoc; eg it relies on knowing that implication
constraints build tuples.
Decomposing PredType
-}
-- | A choice of equality relation. This is separate from the type 'Role'
-- because 'Phantom' does not define a (non-trivial) equality relation.
data EqRel = NomEq | ReprEq
deriving (Eq, Ord)
instance Outputable EqRel where
ppr NomEq = text "nominal equality"
ppr ReprEq = text "representational equality"
eqRelRole :: EqRel -> Role
eqRelRole NomEq = Nominal
eqRelRole ReprEq = Representational
data PredTree = ClassPred Class [Type]
| EqPred EqRel Type Type
| IrredPred PredType
classifyPredType :: PredType -> PredTree
classifyPredType ev_ty = case splitTyConApp_maybe ev_ty of
Just (tc, [_, _, ty1, ty2])
| tc `hasKey` eqReprPrimTyConKey -> EqPred ReprEq ty1 ty2
| tc `hasKey` eqPrimTyConKey -> EqPred NomEq ty1 ty2
Just (tc, tys)
| Just clas <- tyConClass_maybe tc -> ClassPred clas tys
_ -> IrredPred ev_ty
getClassPredTys :: PredType -> (Class, [Type])
getClassPredTys ty = case getClassPredTys_maybe ty of
Just (clas, tys) -> (clas, tys)
Nothing -> pprPanic "getClassPredTys" (ppr ty)
getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
getClassPredTys_maybe ty = case splitTyConApp_maybe ty of
Just (tc, tys) | Just clas <- tyConClass_maybe tc -> Just (clas, tys)
_ -> Nothing
getEqPredTys :: PredType -> (Type, Type)
getEqPredTys ty
= case splitTyConApp_maybe ty of
Just (tc, [_, _, ty1, ty2])
| tc `hasKey` eqPrimTyConKey
|| tc `hasKey` eqReprPrimTyConKey
-> (ty1, ty2)
_ -> pprPanic "getEqPredTys" (ppr ty)
getEqPredTys_maybe :: PredType -> Maybe (Role, Type, Type)
getEqPredTys_maybe ty
= case splitTyConApp_maybe ty of
Just (tc, [_, _, ty1, ty2])
| tc `hasKey` eqPrimTyConKey -> Just (Nominal, ty1, ty2)
| tc `hasKey` eqReprPrimTyConKey -> Just (Representational, ty1, ty2)
_ -> Nothing
getEqPredRole :: PredType -> Role
getEqPredRole ty = eqRelRole (predTypeEqRel ty)
-- | Get the equality relation relevant for a pred type.
predTypeEqRel :: PredType -> EqRel
predTypeEqRel ty
| Just (tc, _) <- splitTyConApp_maybe ty
, tc `hasKey` eqReprPrimTyConKey
= ReprEq
| otherwise
= NomEq
{-
%************************************************************************
%* *
Size
* *
************************************************************************
-}
-- NB: This function does not respect `eqType`, in that two types that
-- are `eqType` may return different sizes. This is OK, because this
-- function is used only in reporting, not decision-making.
typeSize :: Type -> Int
typeSize (LitTy {}) = 1
typeSize (TyVarTy {}) = 1
typeSize (AppTy t1 t2) = typeSize t1 + typeSize t2
typeSize (ForAllTy b t) = typeSize (binderType b) + typeSize t
typeSize (TyConApp _ ts) = 1 + sum (map typeSize ts)
typeSize (CastTy ty co) = typeSize ty + coercionSize co
typeSize (CoercionTy co) = coercionSize co
{-
%************************************************************************
%* *
Well-scoped tyvars
* *
************************************************************************
-}
-- | Do a topological sort on a list of tyvars. This is a deterministic
-- sorting operation (that is, doesn't depend on Uniques).
toposortTyVars :: [TyVar] -> [TyVar]
toposortTyVars tvs = reverse $
[ tv | (tv, _, _) <- topologicalSortG $
graphFromEdgedVertices nodes ]
where
var_ids :: VarEnv Int
var_ids = mkVarEnv (zip tvs [1..])
nodes = [ ( tv
, lookupVarEnv_NF var_ids tv
, mapMaybe (lookupVarEnv var_ids)
(tyCoVarsOfTypeList (tyVarKind tv)) )
| tv <- tvs ]
-- | Extract a well-scoped list of variables from a set of variables.
varSetElemsWellScoped :: VarSet -> [Var]
varSetElemsWellScoped = toposortTyVars . varSetElems
-- | Get the free vars of a type in scoped order
tyCoVarsOfTypeWellScoped :: Type -> [TyVar]
tyCoVarsOfTypeWellScoped = toposortTyVars . tyCoVarsOfTypeList
-- | Get the free vars of types in scoped order
tyCoVarsOfTypesWellScoped :: [Type] -> [TyVar]
tyCoVarsOfTypesWellScoped = toposortTyVars . tyCoVarsOfTypesList
{-
************************************************************************
* *
\subsection{Type families}
* *
************************************************************************
-}
mkFamilyTyConApp :: TyCon -> [Type] -> Type
-- ^ Given a family instance TyCon and its arg types, return the
-- corresponding family type. E.g:
--
-- > data family T a
-- > data instance T (Maybe b) = MkT b
--
-- Where the instance tycon is :RTL, so:
--
-- > mkFamilyTyConApp :RTL Int = T (Maybe Int)
mkFamilyTyConApp tc tys
| Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
, let tvs = tyConTyVars tc
fam_subst = ASSERT2( length tvs == length tys, ppr tc <+> ppr tys )
zipTvSubst tvs tys
= mkTyConApp fam_tc (substTys fam_subst fam_tys)
| otherwise
= mkTyConApp tc tys
-- | Get the type on the LHS of a coercion induced by a type/data
-- family instance.
coAxNthLHS :: CoAxiom br -> Int -> Type
coAxNthLHS ax ind =
mkTyConApp (coAxiomTyCon ax) (coAxBranchLHS (coAxiomNthBranch ax ind))
-- | Pretty prints a 'TyCon', using the family instance in case of a
-- representation tycon. For example:
--
-- > data T [a] = ...
--
-- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
pprSourceTyCon :: TyCon -> SDoc
pprSourceTyCon tycon
| Just (fam_tc, tys) <- tyConFamInst_maybe tycon
= ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
| otherwise
= ppr tycon
{-
************************************************************************
* *
\subsection{Liftedness}
* *
************************************************************************
-}
-- | See "Type#type_classification" for what an unlifted type is
isUnliftedType :: Type -> Bool
-- isUnliftedType returns True for forall'd unlifted types:
-- x :: forall a. Int#
-- I found bindings like these were getting floated to the top level.
-- They are pretty bogus types, mind you. It would be better never to
-- construct them
isUnliftedType ty | Just ty' <- coreView ty = isUnliftedType ty'
isUnliftedType (ForAllTy (Named {}) ty) = isUnliftedType ty
isUnliftedType (TyConApp tc _) = isUnliftedTyCon tc
isUnliftedType _ = False
-- | Extract the RuntimeRep classifier of a type. Panics if this is not possible.
getRuntimeRep :: String -- ^ Printed in case of an error
-> Type -> Type
getRuntimeRep err ty = getRuntimeRepFromKind err (typeKind ty)
-- | Extract the RuntimeRep classifier of a type from its kind.
-- For example, getRuntimeRepFromKind * = PtrRepLifted;
-- getRuntimeRepFromKind # = PtrRepUnlifted.
-- Panics if this is not possible.
getRuntimeRepFromKind :: String -- ^ Printed in case of an error
-> Type -> Type
getRuntimeRepFromKind err = go
where
go k | Just k' <- coreViewOneStarKind k = go k'
go k
| Just (tc, [arg]) <- splitTyConApp_maybe k
, tc `hasKey` tYPETyConKey
= arg
go k = pprPanic "getRuntimeRep" (text err $$
ppr k <+> dcolon <+> ppr (typeKind k))
isUnboxedTupleType :: Type -> Bool
isUnboxedTupleType ty = case tyConAppTyCon_maybe ty of
Just tc -> isUnboxedTupleTyCon tc
_ -> False
-- | See "Type#type_classification" for what an algebraic type is.
-- Should only be applied to /types/, as opposed to e.g. partially
-- saturated type constructors
isAlgType :: Type -> Bool
isAlgType ty
= case splitTyConApp_maybe ty of
Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
isAlgTyCon tc
_other -> False
-- | See "Type#type_classification" for what an algebraic type is.
-- Should only be applied to /types/, as opposed to e.g. partially
-- saturated type constructors. Closed type constructors are those
-- with a fixed right hand side, as opposed to e.g. associated types
isClosedAlgType :: Type -> Bool
isClosedAlgType ty
= case splitTyConApp_maybe ty of
Just (tc, ty_args) | isAlgTyCon tc && not (isFamilyTyCon tc)
-> ASSERT2( ty_args `lengthIs` tyConArity tc, ppr ty ) True
_other -> False
-- | Computes whether an argument (or let right hand side) should
-- be computed strictly or lazily, based only on its type.
-- Currently, it's just 'isUnliftedType'.
isStrictType :: Type -> Bool
isStrictType = isUnliftedType
isPrimitiveType :: Type -> Bool
-- ^ Returns true of types that are opaque to Haskell.
isPrimitiveType ty = case splitTyConApp_maybe ty of
Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
isPrimTyCon tc
_ -> False
{-
************************************************************************
* *
\subsection{Sequencing on types}
* *
************************************************************************
-}
seqType :: Type -> ()
seqType (LitTy n) = n `seq` ()
seqType (TyVarTy tv) = tv `seq` ()
seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
seqType (TyConApp tc tys) = tc `seq` seqTypes tys
seqType (ForAllTy bndr ty) = seqType (binderType bndr) `seq` seqType ty
seqType (CastTy ty co) = seqType ty `seq` seqCo co
seqType (CoercionTy co) = seqCo co
seqTypes :: [Type] -> ()
seqTypes [] = ()
seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
{-
************************************************************************
* *
Comparison for types
(We don't use instances so that we know where it happens)
* *
************************************************************************
Note [Equality on AppTys]
~~~~~~~~~~~~~~~~~~~~~~~~~
In our cast-ignoring equality, we want to say that the following two
are equal:
(Maybe |> co) (Int |> co') ~? Maybe Int
But the left is an AppTy while the right is a TyConApp. The solution is
to use repSplitAppTy_maybe to break up the TyConApp into its pieces and
then continue. Easy to do, but also easy to forget to do.
-}
eqType :: Type -> Type -> Bool
-- ^ Type equality on source types. Does not look through @newtypes@ or
-- 'PredType's, but it does look through type synonyms.
-- This first checks that the kinds of the types are equal and then
-- checks whether the types are equal, ignoring casts and coercions.
-- (The kind check is a recursive call, but since all kinds have type
-- @Type@, there is no need to check the types of kinds.)
-- See also Note [Non-trivial definitional equality] in TyCoRep.
eqType t1 t2 = isEqual $ cmpType t1 t2
-- | Compare types with respect to a (presumably) non-empty 'RnEnv2'.
eqTypeX :: RnEnv2 -> Type -> Type -> Bool
eqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
-- | Type equality on lists of types, looking through type synonyms
-- but not newtypes.
eqTypes :: [Type] -> [Type] -> Bool
eqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
eqVarBndrs :: RnEnv2 -> [Var] -> [Var] -> Maybe RnEnv2
-- Check that the var lists are the same length
-- and have matching kinds; if so, extend the RnEnv2
-- Returns Nothing if they don't match
eqVarBndrs env [] []
= Just env
eqVarBndrs env (tv1:tvs1) (tv2:tvs2)
| eqTypeX env (tyVarKind tv1) (tyVarKind tv2)
= eqVarBndrs (rnBndr2 env tv1 tv2) tvs1 tvs2
eqVarBndrs _ _ _= Nothing
-- Now here comes the real worker
cmpType :: Type -> Type -> Ordering
cmpType t1 t2
-- we know k1 and k2 have the same kind, because they both have kind *.
= cmpTypeX rn_env t1 t2
where
rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfTypes [t1, t2]))
cmpTypes :: [Type] -> [Type] -> Ordering
cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
where
rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfTypes (ts1 ++ ts2)))
-- | An ordering relation between two 'Type's (known below as @t1 :: k1@
-- and @t2 :: k2@)
data TypeOrdering = TLT -- ^ @t1 < t2@
| TEQ -- ^ @t1 ~ t2@ and there are no casts in either,
-- therefore we can conclude @k1 ~ k2@
| TEQX -- ^ @t1 ~ t2@ yet one of the types contains a cast so
-- they may differ in kind.
| TGT -- ^ @t1 > t2@
deriving (Eq, Ord, Enum, Bounded)
cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
-- See Note [Non-trivial definitional equality] in TyCoRep
cmpTypeX env orig_t1 orig_t2 =
case go env orig_t1 orig_t2 of
-- If there are casts then we also need to do a comparison of the kinds of
-- the types being compared
TEQX -> toOrdering $ go env k1 k2
ty_ordering -> toOrdering ty_ordering
where
k1 = typeKind orig_t1
k2 = typeKind orig_t2
toOrdering :: TypeOrdering -> Ordering
toOrdering TLT = LT
toOrdering TEQ = EQ
toOrdering TEQX = EQ
toOrdering TGT = GT
liftOrdering :: Ordering -> TypeOrdering
liftOrdering LT = TLT
liftOrdering EQ = TEQ
liftOrdering GT = TGT
thenCmpTy :: TypeOrdering -> TypeOrdering -> TypeOrdering
thenCmpTy TEQ rel = rel
thenCmpTy TEQX rel = hasCast rel
thenCmpTy rel _ = rel
hasCast :: TypeOrdering -> TypeOrdering
hasCast TEQ = TEQX
hasCast rel = rel
-- Returns both the resulting ordering relation between the two types
-- and whether either contains a cast.
go :: RnEnv2 -> Type -> Type -> TypeOrdering
go env t1 t2
| Just t1' <- coreViewOneStarKind t1 = go env t1' t2
| Just t2' <- coreViewOneStarKind t2 = go env t1 t2'
go env (TyVarTy tv1) (TyVarTy tv2)
= liftOrdering $ rnOccL env tv1 `compare` rnOccR env tv2
go env (ForAllTy (Named tv1 _) t1) (ForAllTy (Named tv2 _) t2)
= go env (tyVarKind tv1) (tyVarKind tv2)
`thenCmpTy` go (rnBndr2 env tv1 tv2) t1 t2
-- See Note [Equality on AppTys]
go env (AppTy s1 t1) ty2
| Just (s2, t2) <- repSplitAppTy_maybe ty2
= go env s1 s2 `thenCmpTy` go env t1 t2
go env ty1 (AppTy s2 t2)
| Just (s1, t1) <- repSplitAppTy_maybe ty1
= go env s1 s2 `thenCmpTy` go env t1 t2
go env (ForAllTy (Anon s1) t1) (ForAllTy (Anon s2) t2)
= go env s1 s2 `thenCmpTy` go env t1 t2
go env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
= liftOrdering (tc1 `cmpTc` tc2) `thenCmpTy` gos env tys1 tys2
go _ (LitTy l1) (LitTy l2) = liftOrdering (compare l1 l2)
go env (CastTy t1 _) t2 = hasCast $ go env t1 t2
go env t1 (CastTy t2 _) = hasCast $ go env t1 t2
go _ (CoercionTy {}) (CoercionTy {}) = TEQ
-- Deal with the rest: TyVarTy < CoercionTy < AppTy < LitTy < TyConApp < ForAllTy
go _ ty1 ty2
= liftOrdering $ (get_rank ty1) `compare` (get_rank ty2)
where get_rank :: Type -> Int
get_rank (CastTy {})
= pprPanic "cmpTypeX.get_rank" (ppr [ty1,ty2])
get_rank (TyVarTy {}) = 0
get_rank (CoercionTy {}) = 1
get_rank (AppTy {}) = 3
get_rank (LitTy {}) = 4
get_rank (TyConApp {}) = 5
get_rank (ForAllTy (Anon {}) _) = 6
get_rank (ForAllTy (Named {}) _) = 7
gos :: RnEnv2 -> [Type] -> [Type] -> TypeOrdering
gos _ [] [] = TEQ
gos _ [] _ = TLT
gos _ _ [] = TGT
gos env (ty1:tys1) (ty2:tys2) = go env ty1 ty2 `thenCmpTy` gos env tys1 tys2
-------------
cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
cmpTypesX _ [] [] = EQ
cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2
`thenCmp` cmpTypesX env tys1 tys2
cmpTypesX _ [] _ = LT
cmpTypesX _ _ [] = GT
-------------
-- | Compare two 'TyCon's. NB: This should /never/ see the "star synonyms",
-- as recognized by Kind.isStarKindSynonymTyCon. See Note
-- [Kind Constraint and kind *] in Kind.
cmpTc :: TyCon -> TyCon -> Ordering
cmpTc tc1 tc2
= ASSERT( not (isStarKindSynonymTyCon tc1) && not (isStarKindSynonymTyCon tc2) )
u1 `compare` u2
where
u1 = tyConUnique tc1
u2 = tyConUnique tc2
{-
************************************************************************
* *
The kind of a type
* *
************************************************************************
-}
typeKind :: Type -> Kind
typeKind (TyConApp tc tys) = piResultTys (tyConKind tc) tys
typeKind (AppTy fun arg) = piResultTy (typeKind fun) arg
typeKind (LitTy l) = typeLiteralKind l
typeKind (ForAllTy (Anon _) _) = liftedTypeKind
typeKind (ForAllTy _ ty) = typeKind ty
typeKind (TyVarTy tyvar) = tyVarKind tyvar
typeKind (CastTy _ty co) = pSnd $ coercionKind co
typeKind (CoercionTy co) = coercionType co
typeLiteralKind :: TyLit -> Kind
typeLiteralKind l =
case l of
NumTyLit _ -> typeNatKind
StrTyLit _ -> typeSymbolKind
-- | Print a tyvar with its kind
pprTyVar :: TyVar -> SDoc
pprTyVar tv = ppr tv <+> dcolon <+> ppr (tyVarKind tv)
{-
%************************************************************************
%* *
Miscellaneous functions
%* *
%************************************************************************
-}
-- | All type constructors occurring in the type; looking through type
-- synonyms, but not newtypes.
-- When it finds a Class, it returns the class TyCon.
tyConsOfType :: Type -> NameEnv TyCon
tyConsOfType ty
= go ty
where
go :: Type -> NameEnv TyCon -- The NameEnv does duplicate elim
go ty | Just ty' <- coreView ty = go ty'
go (TyVarTy {}) = emptyNameEnv
go (LitTy {}) = emptyNameEnv
go (TyConApp tc tys) = go_tc tc `plusNameEnv` go_s tys
go (AppTy a b) = go a `plusNameEnv` go b
go (ForAllTy (Anon a) b) = go a `plusNameEnv` go b `plusNameEnv` go_tc funTyCon
go (ForAllTy (Named tv _) ty) = go ty `plusNameEnv` go (tyVarKind tv)
go (CastTy ty co) = go ty `plusNameEnv` go_co co
go (CoercionTy co) = go_co co
go_co (Refl _ ty) = go ty
go_co (TyConAppCo _ tc args) = go_tc tc `plusNameEnv` go_cos args
go_co (AppCo co arg) = go_co co `plusNameEnv` go_co arg
go_co (ForAllCo _ kind_co co) = go_co kind_co `plusNameEnv` go_co co
go_co (CoVarCo {}) = emptyNameEnv
go_co (AxiomInstCo ax _ args) = go_ax ax `plusNameEnv` go_cos args
go_co (UnivCo p _ t1 t2) = go_prov p `plusNameEnv` go t1 `plusNameEnv` go t2
go_co (SymCo co) = go_co co
go_co (TransCo co1 co2) = go_co co1 `plusNameEnv` go_co co2
go_co (NthCo _ co) = go_co co
go_co (LRCo _ co) = go_co co
go_co (InstCo co arg) = go_co co `plusNameEnv` go_co arg
go_co (CoherenceCo co1 co2) = go_co co1 `plusNameEnv` go_co co2
go_co (KindCo co) = go_co co
go_co (SubCo co) = go_co co
go_co (AxiomRuleCo _ cs) = go_cos cs
go_prov UnsafeCoerceProv = emptyNameEnv
go_prov (PhantomProv co) = go_co co
go_prov (ProofIrrelProv co) = go_co co
go_prov (PluginProv _) = emptyNameEnv
go_prov (HoleProv _) = emptyNameEnv
-- this last case can happen from the tyConsOfType used from
-- checkTauTvUpdate
go_s tys = foldr (plusNameEnv . go) emptyNameEnv tys
go_cos cos = foldr (plusNameEnv . go_co) emptyNameEnv cos
go_tc tc = unitNameEnv (tyConName tc) tc
go_ax ax = go_tc $ coAxiomTyCon ax
-- | Find the result 'Kind' of a type synonym,
-- after applying it to its 'arity' number of type variables
-- Actually this function works fine on data types too,
-- but they'd always return '*', so we never need to ask
synTyConResKind :: TyCon -> Kind
synTyConResKind tycon = piResultTys (tyConKind tycon) (mkTyVarTys (tyConTyVars tycon))
-- | Retrieve the free variables in this type, splitting them based
-- on whether the variable was used in a dependent context. It's possible
-- for a variable to be reported twice, if it's used both dependently
-- and non-dependently. (This isn't the most precise analysis, because
-- it's used in the typechecking knot. It might list some dependent
-- variables as also non-dependent.)
splitDepVarsOfType :: Type -> Pair TyCoVarSet
splitDepVarsOfType = go
where
go (TyVarTy tv) = Pair (tyCoVarsOfType $ tyVarKind tv)
(unitVarSet tv)
go (AppTy t1 t2) = go t1 `mappend` go t2
go (TyConApp _ tys) = foldMap go tys
go (ForAllTy (Anon arg) res) = go arg `mappend` go res
go (ForAllTy (Named tv _) ty)
= let Pair kvs tvs = go ty in
Pair (kvs `delVarSet` tv `unionVarSet` tyCoVarsOfType (tyVarKind tv))
(tvs `delVarSet` tv)
go (LitTy {}) = mempty
go (CastTy ty co) = go ty `mappend` Pair (tyCoVarsOfCo co)
emptyVarSet
go (CoercionTy co) = go_co co
go_co co = let Pair ty1 ty2 = coercionKind co in
go ty1 `mappend` go ty2 -- NB: the Pairs separate along different
-- dimensions here. Be careful!
-- | Like 'splitDepVarsOfType', but over a list of types
splitDepVarsOfTypes :: [Type] -> Pair TyCoVarSet
splitDepVarsOfTypes = foldMap splitDepVarsOfType
-- | Retrieve the free variables in this type, splitting them based
-- on whether they are used visibly or invisibly. Invisible ones come
-- first.
splitVisVarsOfType :: Type -> Pair TyCoVarSet
splitVisVarsOfType orig_ty = Pair invis_vars vis_vars
where
Pair invis_vars1 vis_vars = go orig_ty
invis_vars = invis_vars1 `minusVarSet` vis_vars
go (TyVarTy tv) = Pair (tyCoVarsOfType $ tyVarKind tv) (unitVarSet tv)
go (AppTy t1 t2) = go t1 `mappend` go t2
go (TyConApp tc tys) = go_tc tc tys
go (ForAllTy (Anon t1) t2) = go t1 `mappend` go t2
go (ForAllTy (Named tv _) ty)
= ((`delVarSet` tv) <$> go ty) `mappend`
(invisible (tyCoVarsOfType $ tyVarKind tv))
go (LitTy {}) = mempty
go (CastTy ty co) = go ty `mappend` invisible (tyCoVarsOfCo co)
go (CoercionTy co) = invisible $ tyCoVarsOfCo co
invisible vs = Pair vs emptyVarSet
go_tc tc tys = let (invis, vis) = partitionInvisibles tc id tys in
invisible (tyCoVarsOfTypes invis) `mappend` foldMap go vis
splitVisVarsOfTypes :: [Type] -> Pair TyCoVarSet
splitVisVarsOfTypes = foldMap splitVisVarsOfType
| mcschroeder/ghc | compiler/types/Type.hs | bsd-3-clause | 92,564 | 0 | 18 | 25,578 | 19,374 | 10,108 | 9,266 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Data.IHO.S57.DSPM where
import Control.Lens
import Data.Text (Text)
import Data.Data (Data)
import Data.Typeable (Typeable)
import Data.Tree
import Data.IHO.S57.Types
data CoordinateUnits =
LatitudeLongitude |
EastingNorthing |
UnitsOfMap
deriving (Show, Eq, Data, Typeable)
instance Enum CoordinateUnits where
toEnum 1 = LatitudeLongitude
toEnum 2 = EastingNorthing
toEnum 3 = UnitsOfMap
toEnum t = error $ "toEnum: " ++ show t ++ " is not a CoordinateUnits"
fromEnum LatitudeLongitude = 1
fromEnum EastingNorthing = 2
fromEnum UnitsOfMap = 3
instance FromS57Value CoordinateUnits where
fromS57Value (S57CharData "LL") = LatitudeLongitude
fromS57Value (S57CharData "EN") = EastingNorthing
fromS57Value (S57CharData "UM") = UnitsOfMap
fromS57Value (S57Int i) = toEnum i
fromS57Value v = error $ "fromS57Value CoordinateUnits undefined for " ++
show v
data DSPM =
DSPM { _dspmHorizontalDatum :: ! Int
, _dspmVerticalDatum :: ! Int
, _dspmSoundingDatum :: ! Int
, _dspmCompilationScale :: !Int
, _dspmUnitsOfDepth :: ! Int
, _dspmUnitsOfHeight :: ! Int
, _dspmUnitsOfPosAccuracy :: ! Int
, _dspmCoordinateUnits :: ! CoordinateUnits
, _dspmCoordinateMulFactor :: ! Int
, _dspmSoundingMulFactor :: ! Int
, _dspmComment :: ! Text
} deriving (Show, Eq, Data, Typeable)
makeLenses ''DSPM
instance FromS57FileRecord DSPM where
fromS57FileDataRecord r
| ((structureFieldName . rootLabel $ r) /= "DSPM") =
error $ "not an DSPM record: " ++ show r
| otherwise =
DSPM { _dspmHorizontalDatum = lookupField r "HDAT"
, _dspmVerticalDatum = lookupField r "VDAT"
, _dspmSoundingDatum = lookupField r "SDAT"
, _dspmCompilationScale = lookupField r "CSCL"
, _dspmUnitsOfDepth = lookupField r "DUNI"
, _dspmUnitsOfHeight = lookupField r "HUNI"
, _dspmUnitsOfPosAccuracy = lookupField r "PUNI"
, _dspmCoordinateUnits = lookupField r "COUN"
, _dspmCoordinateMulFactor = lookupField r "COMF"
, _dspmSoundingMulFactor = lookupField r "SOMF"
, _dspmComment = lookupField r "COMT"
}
| alios/iho-s57 | library/Data/IHO/S57/DSPM.hs | bsd-3-clause | 2,384 | 20 | 13 | 603 | 561 | 305 | 256 | 82 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Control.Applicative (optional, (<|>))
import Control.Exception (SomeException, throwIO)
import Data.Text (Text)
import Data.Version (showVersion)
import Dhall.JSONToDhall
import Dhall.Pretty (CharacterSet (..))
import Options.Applicative (Parser, ParserInfo)
import qualified Control.Exception
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy.Char8 as ByteString
import qualified Dhall.Core
import qualified Dhall.Util
import qualified GHC.IO.Encoding
import qualified Options.Applicative as Options
import qualified Paths_dhall_json as Meta
import qualified System.Exit
import qualified System.IO as IO
-- ---------------
-- Command options
-- ---------------
-- | Command info and description
parserInfo :: ParserInfo Options
parserInfo = Options.info
( Options.helper <*> parseOptions)
( Options.fullDesc
<> Options.progDesc "Convert a JSON expression to a Dhall expression, given the expected Dhall type"
)
-- | All the command arguments and options
data Options
= Default
{ schema :: Maybe Text
, conversion :: Conversion
, file :: Maybe FilePath
, output :: Maybe FilePath
, ascii :: Bool
, plain :: Bool
}
| Type
{ file :: Maybe FilePath
, output :: Maybe FilePath
, ascii :: Bool
, plain :: Bool
}
| Version
deriving Show
-- | Parser for all the command arguments and options
parseOptions :: Parser Options
parseOptions =
typeCommand
<|> ( Default
<$> optional parseSchema
<*> parseConversion
<*> optional parseFile
<*> optional parseOutput
<*> parseASCII
<*> parsePlain
)
<|> parseVersion
where
typeCommand =
Options.hsubparser
(Options.command "type" info <> Options.metavar "type")
where
info =
Options.info parser (Options.progDesc "Output the inferred Dhall type from a JSON value")
parser =
Type
<$> optional parseFile
<*> optional parseOutput
<*> parseASCII
<*> parsePlain
parseSchema =
Options.strArgument
( Options.metavar "SCHEMA"
<> Options.help "Dhall type (schema). You can omit the schema to let the executable infer the schema from the JSON value."
)
parseVersion =
Options.flag'
Version
( Options.long "version"
<> Options.short 'V'
<> Options.help "Display version"
)
parseFile =
Options.strOption
( Options.long "file"
<> Options.help "Read JSON from a file instead of standard input"
<> Options.metavar "FILE"
<> Options.action "file"
)
parseOutput =
Options.strOption
( Options.long "output"
<> Options.help "Write Dhall expression to a file instead of standard output"
<> Options.metavar "FILE"
<> Options.action "file"
)
parseASCII =
Options.switch
( Options.long "ascii"
<> Options.help "Format code using only ASCII syntax"
)
parsePlain =
Options.switch
( Options.long "plain"
<> Options.help "Disable syntax highlighting"
)
-- ----------
-- Main
-- ----------
main :: IO ()
main = do
GHC.IO.Encoding.setLocaleEncoding GHC.IO.Encoding.utf8
options <- Options.execParser parserInfo
let toCharacterSet ascii = case ascii of
True -> ASCII
False -> Unicode
let toValue file = do
bytes <- case file of
Nothing -> ByteString.getContents
Just path -> ByteString.readFile path
case Aeson.eitherDecode bytes of
Left err -> throwIO (userError err)
Right v -> pure v
let toSchema schema value = do
finalSchema <- case schema of
Just text -> resolveSchemaExpr text
Nothing -> return (schemaToDhallType (inferSchema value))
typeCheckSchemaExpr id finalSchema
case options of
Version ->
putStrLn (showVersion Meta.version)
Default{..} -> do
let characterSet = toCharacterSet ascii
handle $ do
value <- toValue file
finalSchema <- toSchema schema value
expression <- Dhall.Core.throws (dhallFromJSON conversion finalSchema value)
Dhall.Util.renderExpression characterSet plain output expression
Type{..} -> do
let characterSet = toCharacterSet ascii
handle $ do
value <- toValue file
finalSchema <- toSchema Nothing value
Dhall.Util.renderExpression characterSet plain output finalSchema
handle :: IO a -> IO a
handle = Control.Exception.handle handler
where
handler :: SomeException -> IO a
handler e = do
IO.hPutStrLn IO.stderr ""
IO.hPrint IO.stderr e
System.Exit.exitFailure
| Gabriel439/Haskell-Dhall-Library | dhall-json/json-to-dhall/Main.hs | bsd-3-clause | 5,546 | 0 | 20 | 1,898 | 1,136 | 584 | 552 | 137 | 7 |
module Codex.Lib.Compression (
Compression (..),
compress,
compressFile,
decompress,
decompressFile
) where
class Compression a where
compress :: a -> Either String a
compressFile :: String -> IO (Either String a)
decompress :: a -> Either String a
decompressFile :: String -> IO (Either String a)
| adarqui/Codex | src/Codex/Lib/Compression.hs | bsd-3-clause | 309 | 0 | 10 | 56 | 105 | 57 | 48 | 11 | 0 |
module TaglessFinal.Deep where
import TaglessFinal.Syntax
import TaglessFinal.Term
import Text.Printf ( printf )
import Control.Monad.State
import TaglessFinal.VarState
import qualified Syntax
newtype Deep a = Deep { unDeep :: State VarState (Either (Syntax.Tx) (Syntax.G Syntax.X)) }
fromLeft :: Either a b -> a
fromLeft (Left a) = a
fromRight :: Either a b -> b
fromRight (Right b) = b
instance Goal Deep where
term x = Deep $ return $ Left (toSyntax x)
unify x y = Deep $ do
x <- unDeep x
y <- unDeep y
return $ Right $ (Syntax.===) (fromLeft x) (fromLeft y)
conj x y = Deep $ do
x <- unDeep x
y <- unDeep y
return $ Right $ (Syntax.&&&) (fromRight x) (fromRight y)
disj x y = Deep $ do
x <- unDeep x
y <- unDeep y
return $ Right $ (Syntax.|||) (fromRight x) (fromRight y)
fresh f = Deep $ do
v <- nextFreshVar
let x = toFreshVar v
body <- unDeep $ f x
return $ Right $ Syntax.Fresh x (fromRight body)
lam f = Deep $ do
v <- nextVar
let x = toVar v
body <- unDeep $ f (Deep $ return (Left $ toSyntax $ Var x))
return body
fixP name f = Deep $ do
body <- unDeep $ f (Deep $ return (Left $ toSyntax $ Var name))
return body
app f arg = Deep $ do
application <- unDeep f
arg <- unDeep arg
return $ application
view :: Deep a -> Syntax.G Syntax.X
view goal = fromRight $ evalState (unDeep goal) (VarState 0 0) | kajigor/uKanren_transformations | src/TaglessFinal/Deep.hs | bsd-3-clause | 1,423 | 0 | 17 | 375 | 663 | 321 | 342 | 45 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Promotion.Prelude
-- Copyright : (C) 2014 Jan Stolarek
-- License : BSD-style (see LICENSE)
-- Maintainer : Jan Stolarek ([email protected])
-- Stability : experimental
-- Portability : non-portable
--
-- Mimics the Haskell Prelude, but with promoted types.
--
----------------------------------------------------------------------------
{-# LANGUAGE ExplicitNamespaces #-}
module Data.Promotion.Prelude (
-- * Standard types, classes and related functions
-- ** Basic data types
If, Not, (:&&), (:||), Otherwise,
maybe_, Maybe_, either_, Either_,
Symbol,
Fst, Snd, Curry, Uncurry,
-- * Error reporting
Error, ErrorSym0,
-- * Promoted equality
module Data.Promotion.Prelude.Eq,
-- * Promoted comparisons
module Data.Promotion.Prelude.Ord,
-- * Promoted enumerations
-- | As a matter of convenience, the promoted Prelude does /not/ export
-- promoted @succ@ and @pred@, due to likely conflicts with
-- unary numbers. Please import 'Data.Promotion.Prelude.Enum' directly if
-- you want these.
module Data.Promotion.Prelude.Enum,
-- * Promoted numbers
module Data.Promotion.Prelude.Num,
-- ** Miscellaneous functions
Id, Const, (:.), type ($), type ($!), Flip, AsTypeOf, Until, Seq,
-- * List operations
Map, (:++), Filter,
Head, Last, Tail, Init, Null, Length, (:!!),
Reverse,
-- ** Reducing lists (folds)
Foldl, Foldl1, Foldr, Foldr1,
-- *** Special folds
And, Or, any_, Any_, All,
Sum, Product,
Concat, ConcatMap,
Maximum, Minimum,
-- ** Building lists
-- *** Scans
Scanl, Scanl1, Scanr, Scanr1,
-- *** Infinite lists
Replicate,
-- ** Sublists
Take, Drop, SplitAt,
TakeWhile, DropWhile, Span, Break,
-- ** Searching lists
Elem, NotElem, Lookup,
-- ** Zipping and unzipping lists
Zip, Zip3, ZipWith, ZipWith3, Unzip, Unzip3,
-- * Defunctionalization symbols
FalseSym0, TrueSym0,
NotSym0, NotSym1, (:&&$), (:&&$$), (:&&$$$), (:||$), (:||$$), (:||$$$),
OtherwiseSym0,
NothingSym0, JustSym0, JustSym1,
Maybe_Sym0, Maybe_Sym1, Maybe_Sym2, Maybe_Sym3,
LeftSym0, LeftSym1, RightSym0, RightSym1,
Either_Sym0, Either_Sym1, Either_Sym2, Either_Sym3,
Tuple0Sym0,
Tuple2Sym0, Tuple2Sym1, Tuple2Sym2,
Tuple3Sym0, Tuple3Sym1, Tuple3Sym2, Tuple3Sym3,
Tuple4Sym0, Tuple4Sym1, Tuple4Sym2, Tuple4Sym3, Tuple4Sym4,
Tuple5Sym0, Tuple5Sym1, Tuple5Sym2, Tuple5Sym3, Tuple5Sym4, Tuple5Sym5,
Tuple6Sym0, Tuple6Sym1, Tuple6Sym2, Tuple6Sym3, Tuple6Sym4, Tuple6Sym5, Tuple6Sym6,
Tuple7Sym0, Tuple7Sym1, Tuple7Sym2, Tuple7Sym3, Tuple7Sym4, Tuple7Sym5, Tuple7Sym6, Tuple7Sym7,
FstSym0, FstSym1, SndSym0, SndSym1,
CurrySym0, CurrySym1, CurrySym2, CurrySym3,
UncurrySym0, UncurrySym1, UncurrySym2,
(:^$), (:^$$),
IdSym0, IdSym1, ConstSym0, ConstSym1, ConstSym2,
(:.$), (:.$$), (:.$$$),
type ($$), type ($$$), type ($$$$),
type ($!$), type ($!$$), type ($!$$$),
FlipSym0, FlipSym1, FlipSym2,
AsTypeOfSym0, AsTypeOfSym1, AsTypeOfSym2, SeqSym0, SeqSym1, SeqSym2,
(:$), (:$$), (:$$$), NilSym0,
MapSym0, MapSym1, MapSym2, ReverseSym0, ReverseSym1,
(:++$$), (:++$), HeadSym0, HeadSym1, LastSym0, LastSym1,
TailSym0, TailSym1, InitSym0, InitSym1, NullSym0, NullSym1,
FoldlSym0, FoldlSym1, FoldlSym2, FoldlSym3,
Foldl1Sym0, Foldl1Sym1, Foldl1Sym2,
FoldrSym0, FoldrSym1, FoldrSym2, FoldrSym3,
Foldr1Sym0, Foldr1Sym1, Foldr1Sym2,
ConcatSym0, ConcatSym1,
ConcatMapSym0, ConcatMapSym1, ConcatMapSym2,
MaximumBySym0, MaximumBySym1, MaximumBySym2,
MinimumBySym0, MinimumBySym1, MinimumBySym2,
AndSym0, AndSym1, OrSym0, OrSym1,
Any_Sym0, Any_Sym1, Any_Sym2,
AllSym0, AllSym1, AllSym2,
ScanlSym0, ScanlSym1, ScanlSym2, ScanlSym3,
Scanl1Sym0, Scanl1Sym1, Scanl1Sym2,
ScanrSym0, ScanrSym1, ScanrSym2, ScanrSym3,
Scanr1Sym0, Scanr1Sym1, Scanr1Sym2,
ElemSym0, ElemSym1, ElemSym2,
NotElemSym0, NotElemSym1, NotElemSym2,
ZipSym0, ZipSym1, ZipSym2,
Zip3Sym0, Zip3Sym1, Zip3Sym2, Zip3Sym3,
ZipWithSym0, ZipWithSym1, ZipWithSym2, ZipWithSym3,
ZipWith3Sym0, ZipWith3Sym1, ZipWith3Sym2, ZipWith3Sym3,
UnzipSym0, UnzipSym1,
UntilSym0, UntilSym1, UntilSym2, UntilSym3,
LengthSym0, LengthSym1,
SumSym0, SumSym1,
ProductSym0, ProductSym1,
ReplicateSym0, ReplicateSym1, ReplicateSym2,
TakeSym0, TakeSym1, TakeSym2,
DropSym0, DropSym1, DropSym2,
SplitAtSym0, SplitAtSym1, SplitAtSym2,
TakeWhileSym0, TakeWhileSym1, TakeWhileSym2,
DropWhileSym0, DropWhileSym1, DropWhileSym2,
SpanSym0, SpanSym1, SpanSym2,
BreakSym0, BreakSym1, BreakSym2,
LookupSym0, LookupSym1, LookupSym2,
FilterSym0, FilterSym1, FilterSym2,
(:!!$), (:!!$$), (:!!$$$),
) where
import Data.Promotion.Prelude.Base
import Data.Promotion.Prelude.Bool
import Data.Promotion.Prelude.Either
import Data.Promotion.Prelude.List
import Data.Promotion.Prelude.Maybe
import Data.Promotion.Prelude.Tuple
import Data.Promotion.Prelude.Eq
import Data.Promotion.Prelude.Ord
import Data.Promotion.Prelude.Enum
hiding (Succ, Pred, SuccSym0, SuccSym1, PredSym0, PredSym1)
import Data.Promotion.Prelude.Num
import Data.Singletons.TypeLits
| int-index/singletons | src/Data/Promotion/Prelude.hs | bsd-3-clause | 5,200 | 0 | 5 | 789 | 1,166 | 814 | 352 | 103 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Types
( St(..)
, UIMode(..)
, AppEvent(..)
, uiMode, backend, store, config
, availableMigrations, installedMigrations
, migrationList, editMigrationName, editMigrationDeps
, initialState, editingMigration, status, statusChan
)
where
import Control.Lens
import Control.Concurrent (Chan)
import Data.Monoid
import Graphics.Vty (Event)
import Moo.Core
import Database.Schema.Migrations.Migration (Migration)
import qualified Database.Schema.Migrations.Backend as B
import qualified Database.Schema.Migrations.Store as S
import Brick.Types
import Brick.Widgets.Core
import Brick.Widgets.List
import Brick.Widgets.Edit
data UIMode = MigrationListing | EditMigration
data AppEvent =
VtyEvent Event
| ClearStatus String
data St =
St { _uiMode :: UIMode
, _backend :: B.Backend
, _store :: S.MigrationStore
, _config :: Configuration
, _status :: Maybe String
, _statusChan :: Chan AppEvent
-- Data from the most recent read of the store and backend
, _availableMigrations :: [String]
, _installedMigrations :: [String]
-- mode: MigrationListing
, _migrationList :: List String
-- mode: EditMigration
, _editMigrationName :: Editor
, _editMigrationDeps :: List (Bool, String)
, _editingMigration :: Maybe Migration
}
makeLenses ''St
initialState :: Configuration -> B.Backend -> S.MigrationStore -> Chan AppEvent -> St
initialState cfg theBackend theStore ch =
St { _uiMode = MigrationListing
, _backend = theBackend
, _store = theStore
, _availableMigrations = []
, _installedMigrations = []
, _migrationList = list (Name "migrationList") mempty 1
, _config = cfg
, _editMigrationName = editor (Name "editMigrationName") (str . unlines) (Just 1) ""
, _editMigrationDeps = list (Name "editMigrationDeps") mempty 1
, _editingMigration = Nothing
, _status = Nothing
, _statusChan = ch
}
| jtdaugherty/dbmigrations-client | src/Types.hs | bsd-3-clause | 2,050 | 0 | 10 | 473 | 478 | 292 | 186 | 53 | 1 |
import Control.Concurrent (threadDelay, forkIO)
import Control.Monad (forever)
{-
main :: IO ()
main = do
forkIO $ forever $ do
threadDelay 1000000
putStrLn "chatter program"
getLine
return ()
-}
main :: IO () | wavewave/chatter | src/test.hs | bsd-3-clause | 230 | 0 | 6 | 53 | 35 | 20 | 15 | 3 | 0 |
module Wham.Translator(translate, annotate) where
import Wham.AST
import Wham.ControlPoint
import Wham.AMDefinitions hiding ((+))
addCP :: Statement -> ControlPoint -> (ControlPoint, StatementCP)
addCP (Skip) cp = (cp + 1, SkipCP cp)
addCP (Assign x a) cp = (cp + 1, AssignCP x a cp)
addCP (Compound s1 s2) cp = (cp2, CompoundCP stm1 stm2)
where
(cp1, stm1) = addCP s1 cp
(cp2, stm2) = addCP s2 cp1
addCP (If b s1 s2) cp = (cp2, IfCP b stm1 stm2 cp)
where
(cp1, stm1) = addCP s1 $ cp + 1
(cp2, stm2) = addCP s2 cp1
addCP (While b s) cp = (cp1 + 1, WhileCP b stm (cp + 1) cp)
where
(cp1, stm) = addCP s $ cp + 2
addCP (TryCatch s1 s2) cp = (cp2, TryCatchCP stm1 stm2 cp)
where
(cp1, stm1) = addCP s1 $ cp + 1
(cp2, stm2) = addCP s2 cp1
annotate :: Statement -> StatementCP
annotate s = stm
where (_, stm) = addCP s 0
translate :: Statement -> [AMExpression]
translate s = (ANALYZE (-2)):code ++ [ANALYZE (-1)]
where (_, stm) = addCP s 0
code = translateStatement stm
translateArithmetic :: ArithmeticExp -> ControlPoint -> [AMExpression]
translateArithmetic (Number n) cp = [(PUSH n cp)]
translateArithmetic (Variable x) cp = [(FETCH x cp)]
translateArithmetic (Add a1 a2) cp = (translateArithmetic a2 cp) ++
(translateArithmetic a1 cp) ++
[ADD cp]
translateArithmetic (Sub a1 a2) cp = (translateArithmetic a2 cp) ++
(translateArithmetic a1 cp) ++
[SUB cp]
translateArithmetic (Mul a1 a2) cp = (translateArithmetic a2 cp) ++
(translateArithmetic a1 cp) ++
[MULT cp]
translateArithmetic (Div a1 a2) cp = (translateArithmetic a2 cp) ++
(translateArithmetic a1 cp) ++
[DIV cp]
translateBoolean :: BooleanExp -> ControlPoint -> [AMExpression]
translateBoolean (Boolean True) cp = [TRUE cp]
translateBoolean (Boolean False) cp = [FALSE cp]
translateBoolean (Not b) cp = (translateBoolean b cp) ++ [NEG cp]
translateBoolean (Equal a1 a2) cp = (translateArithmetic a2 cp) ++
(translateArithmetic a1 cp) ++
[EQUAL cp]
translateBoolean (LessOrEqual a1 a2) cp = (translateArithmetic a2 cp) ++
(translateArithmetic a1 cp) ++
[LE cp]
translateBoolean (And b1 b2) cp = (translateBoolean b2 cp) ++
(translateBoolean b1 cp) ++
[AND cp]
translateStatement :: StatementCP -> [AMExpression]
translateStatement (SkipCP cp) = [NOOP cp]
translateStatement (AssignCP x a cp) = (translateArithmetic a cp) ++
[(STORE x cp)]
translateStatement (CompoundCP s1 s2) = (translateStatement s1) ++
(translateStatement s2)
translateStatement (IfCP b s1 s2 cp) = (translateBoolean b cp) ++
[BRANCH (translateStatement s1)
(translateStatement s2) cp]
translateStatement (WhileCP b s cp cp2) = (ANALYZE cp2):
[LOOP (translateBoolean b cp)
(translateStatement s) cp]
translateStatement (TryCatchCP s1 s2 cp) = [TRY (translateStatement s1)
(translateStatement s2) cp]
| helino/wham | src/Wham/Translator.hs | bsd-3-clause | 3,659 | 0 | 10 | 1,362 | 1,267 | 656 | 611 | 67 | 1 |
module Main where
import Test.DocTest
main :: IO ()
main = doctest
[ "-XOverloadedStrings"
, "Network/HTTP/QueryString/Internal.hs"
]
| worksap-ate/http-querystring | test/Doctest.hs | bsd-3-clause | 148 | 0 | 6 | 31 | 33 | 19 | 14 | 6 | 1 |
{-# LANGUAGE RankNTypes, NamedFieldPuns, RecordWildCards, RecursiveDo,
BangPatterns, OverloadedStrings, TemplateHaskell, FlexibleContexts #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Distribution.Server.Features.Users (
initUserFeature,
UserFeature(..),
UserResource(..),
GroupResource(..),
) where
import Distribution.Server.Framework
import Distribution.Server.Framework.BackupDump
import Distribution.Server.Framework.Templating
import qualified Distribution.Server.Framework.Auth as Auth
import Distribution.Server.Users.Types
import Distribution.Server.Users.State
import Distribution.Server.Users.Backup
import qualified Distribution.Server.Users.Users as Users
import qualified Distribution.Server.Users.Group as Group
import Distribution.Server.Users.Group
(UserGroup(..), GroupDescription(..), UserIdSet, nullDescription)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Maybe (fromMaybe)
import Data.Function (fix)
import Control.Applicative (optional)
import Data.Aeson (toJSON)
import Data.Aeson.TH
import qualified Data.Text as T
import Distribution.Text (display, simpleParse)
-- | A feature to allow manipulation of the database of users.
--
-- TODO: clean up mismatched and duplicate functionality (some noted below).
data UserFeature = UserFeature {
-- | The users `HackageFeature`.
userFeatureInterface :: HackageFeature,
-- | User resources.
userResource :: UserResource,
-- | Notification that a user has been added. Currently unused.
userAdded :: Hook () (), --TODO: delete, other status changes?
-- | The admin user group, including its description, members, and
-- modification thereof.
adminGroup :: UserGroup,
groupChangedHook :: Hook (GroupDescription, Bool, UserId, UserId, String) (),
-- Authorisation
-- | Require any of a set of privileges.
guardAuthorised_ :: [PrivilegeCondition] -> ServerPartE (),
-- | Require any of a set of privileges, giving the id of the current user.
guardAuthorised :: [PrivilegeCondition] -> ServerPartE UserId,
-- | Require being logged in, giving the id of the current user.
guardAuthenticated :: ServerPartE UserId,
-- | A hook to override the default authentication error in particular
-- circumstances.
authFailHook :: Hook Auth.AuthError (Maybe ErrorResponse),
-- | Retrieves the entire user base.
queryGetUserDb :: forall m. MonadIO m => m Users.Users,
-- | Creates a Hackage 2 user credential.
newUserAuth :: UserName -> PasswdPlain -> UserAuth,
-- | Adds a user with a fresh name.
updateAddUser :: forall m. MonadIO m => UserName -> UserAuth -> m (Either Users.ErrUserNameClash UserId),
-- | Sets the account-enabled status of an existing user to True or False.
updateSetUserEnabledStatus :: forall m. MonadIO m => UserId -> Bool
-> m (Maybe (Either Users.ErrNoSuchUserId Users.ErrDeletedUser)),
-- | Sets the credentials of an existing user.
updateSetUserAuth :: forall m. MonadIO m => UserId -> UserAuth
-> m (Maybe (Either Users.ErrNoSuchUserId Users.ErrDeletedUser)),
-- | Adds a user to a group based on a "user" path component.
--
-- Use the UserGroup or GroupResource directly instead, as this is a hack.
groupAddUser :: UserGroup -> DynamicPath -> ServerPartE (),
-- | Likewise, deletes a user, will go away soon.
groupDeleteUser :: UserGroup -> DynamicPath -> ServerPartE (),
-- | Get a username from a path.
userNameInPath :: forall m. MonadPlus m => DynamicPath -> m UserName,
-- | Lookup a `UserId` from a name, if the name exists.
lookupUserName :: UserName -> ServerPartE UserId,
-- | Lookup full `UserInfo` from a name, if the name exists.
lookupUserNameFull :: UserName -> ServerPartE (UserId, UserInfo),
-- | Lookup full `UserInfo` from an id, if the id exists.
lookupUserInfo :: UserId -> ServerPartE UserInfo,
-- | An action to change a password directly, using "password" and
-- "repeat-password" form fields. Only admins and the user themselves
-- can do this. This is messy, as it was one of the first things writen
-- for the users feature.
--
-- TODO: update and make more usable.
changePassword :: UserName -> ServerPartE (),
-- | Determine if the first user can change the second user's password,
-- replicating auth functionality. Avoid using.
canChangePassword :: forall m. MonadIO m => UserId -> UserId -> m Bool,
-- | Action to create a new user with the given credentials. This takes the
-- desired name, a password, and a repeated password, validating all.
newUserWithAuth :: String -> PasswdPlain -> PasswdPlain -> ServerPartE UserName,
-- | Action for an admin to create a user with "username", "password", and
-- "repeat-password" username fields.
adminAddUser :: ServerPartE Response,
-- Create a group resource for the given resource path.
groupResourceAt :: String -> UserGroup -> IO (UserGroup, GroupResource),
-- | Create a parameretrized group resource for the given resource path.
-- The parameter `a` can here be called a group key, and there is
-- potentially a set of initial values.
--
-- This takes functions to create a user group on the fly for the given
-- key, go from a key to a DynamicPath (for URI generation), as well as
-- go from a DynamicPath to a key with some possibility of failure. This
-- should check key membership, as well.
--
-- When these parameretrized `UserGroup`s need to be modified, the returned
-- `a -> UserGroup` function should be used, as it wraps the given
-- `a -> UserGroup` function to keep user-to-group mappings up-to-date.
groupResourcesAt :: forall a. String -> (a -> UserGroup)
-> (a -> DynamicPath)
-> (DynamicPath -> ServerPartE a)
-> [a]
-> IO (a -> UserGroup, GroupResource),
-- | Look up whether the current user has (add, remove) capabilities for
-- the given group, erroring out if neither are present.
lookupGroupEditAuth :: UserGroup -> ServerPartE (Bool, Bool),
-- | For a given user, return all of the URIs for groups they are in.
getGroupIndex :: forall m. (Functor m, MonadIO m) => UserId -> m [String],
-- | For a given URI, get a GroupDescription for it, if one can be found.
getIndexDesc :: forall m. MonadIO m => String -> m GroupDescription
}
instance IsHackageFeature UserFeature where
getFeatureInterface = userFeatureInterface
data UserResource = UserResource {
-- | The list of all users.
userList :: Resource,
-- | The main page for a given user.
userPage :: Resource,
-- | A user's password.
passwordResource :: Resource,
-- | A user's enabled status.
enabledResource :: Resource,
-- | The admin group.
adminResource :: GroupResource,
-- | Manage a user
manageUserResource :: Resource,
-- | URI for `userList` given a format.
userListUri :: String -> String,
-- | URI for `userPage` given a format and name.
userPageUri :: String -> UserName -> String,
-- | URI for `passwordResource` given a format and name.
userPasswordUri :: String -> UserName -> String,
-- | URI for `enabledResource` given a format and name.
userEnabledUri :: String -> UserName -> String,
-- | URI for `adminResource` given a format.
adminPageUri :: String -> String,
-- | URI for `manageUserResource` give a format and name
manageUserUri :: String -> UserName -> String
}
instance FromReqURI UserName where
fromReqURI = simpleParse
data GroupResource = GroupResource {
-- | A group, potentially parametetrized over some collection.
groupResource :: Resource,
-- | A user's presence in a group.
groupUserResource :: Resource,
-- | A `UserGroup` for a group, with a `DynamicPath` for any parameterization.
getGroup :: DynamicPath -> ServerPartE UserGroup
}
-- This is a mapping of UserId -> group URI and group URI -> description.
-- Like many reverse mappings, it is probably rather volatile. Still, it is
-- a secondary concern, as user groups should be defined by each feature
-- and not globally, to be perfectly modular.
data GroupIndex = GroupIndex {
usersToGroupUri :: !(IntMap (Set String)),
groupUrisToDesc :: !(Map String GroupDescription)
}
emptyGroupIndex :: GroupIndex
emptyGroupIndex = GroupIndex IntMap.empty Map.empty
instance MemSize GroupIndex where
memSize (GroupIndex a b) = memSize2 a b
-- TODO: add renaming
initUserFeature :: ServerEnv -> IO (IO UserFeature)
initUserFeature ServerEnv{serverStateDir, serverTemplatesDir, serverTemplatesMode} = do
-- Canonical state
usersState <- usersStateComponent serverStateDir
adminsState <- adminsStateComponent serverStateDir
-- Ephemeral state
groupIndex <- newMemStateWHNF emptyGroupIndex
-- Extension hooks
userAdded <- newHook
authFailHook <- newHook
groupChangedHook <- newHook
-- Load templates
templates <-
loadTemplates serverTemplatesMode
[serverTemplatesDir, serverTemplatesDir </> "Users"]
[ "manage.html", "token-created.html", "token-revoked.html"
]
return $ do
-- Slightly tricky: we have an almost recursive knot between the group
-- resource management functions, and creating the admin group
-- resource that is part of the user feature.
--
-- Instead of trying to pull it apart, we just use a 'do rec'
--
rec let (feature@UserFeature{groupResourceAt}, adminGroupDesc)
= userFeature templates
usersState
adminsState
groupIndex
userAdded authFailHook groupChangedHook
adminG adminR
(adminG, adminR) <- groupResourceAt "/users/admins/" adminGroupDesc
return feature
usersStateComponent :: FilePath -> IO (StateComponent AcidState Users.Users)
usersStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "Users") initialUsers
return StateComponent {
stateDesc = "List of users"
, stateHandle = st
, getState = query st GetUserDb
, putState = update st . ReplaceUserDb
, backupState = usersBackup
, restoreState = usersRestore
, resetState = usersStateComponent
}
adminsStateComponent :: FilePath -> IO (StateComponent AcidState HackageAdmins)
adminsStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "HackageAdmins") initialHackageAdmins
return StateComponent {
stateDesc = "Admins"
, stateHandle = st
, getState = query st GetHackageAdmins
, putState = update st . ReplaceHackageAdmins . adminList
, backupState = \_ (HackageAdmins admins) -> [csvToBackup ["admins.csv"] (groupToCSV admins)]
, restoreState = HackageAdmins <$> groupBackup ["admins.csv"]
, resetState = adminsStateComponent
}
userFeature :: Templates
-> StateComponent AcidState Users.Users
-> StateComponent AcidState HackageAdmins
-> MemState GroupIndex
-> Hook () ()
-> Hook Auth.AuthError (Maybe ErrorResponse)
-> Hook (GroupDescription, Bool, UserId, UserId, String) ()
-> UserGroup
-> GroupResource
-> (UserFeature, UserGroup)
userFeature templates usersState adminsState
groupIndex userAdded authFailHook groupChangedHook
adminGroup adminResource
= (UserFeature {..}, adminGroupDesc)
where
userFeatureInterface = (emptyHackageFeature "users") {
featureDesc = "Manipulate the user database."
, featureResources =
map ($ userResource)
[ userList
, userPage
, passwordResource
, enabledResource
, manageUserResource
]
++ [
groupResource adminResource
, groupUserResource adminResource
]
, featureState = [
abstractAcidStateComponent usersState
, abstractAcidStateComponent adminsState
]
, featureCaches = [
CacheComponent {
cacheDesc = "user group index",
getCacheMemSize = memSize <$> readMemState groupIndex
}
]
}
userResource = fix $ \r -> UserResource {
userList = (resourceAt "/users/.:format") {
resourceDesc = [ (GET, "list of users") ]
, resourceGet = [ ("json", serveUsersGet) ]
}
, userPage = (resourceAt "/user/:username.:format") {
resourceDesc = [ (GET, "user id info")
, (PUT, "create user")
, (DELETE, "delete user")
]
, resourceGet = [ ("json", serveUserGet) ]
, resourcePut = [ ("", serveUserPut) ]
, resourceDelete = [ ("", serveUserDelete) ]
}
, manageUserResource =
(resourceAt "/user/:username/manage.:format")
{ resourceDesc =
[ (GET, "user management page")
]
, resourceGet = [ ("", serveUserManagementGet) ]
, resourcePost = [ ("", serveUserManagementPost) ]
}
, passwordResource = resourceAt "/user/:username/password.:format"
--TODO: PUT
, enabledResource = (resourceAt "/user/:username/enabled.:format") {
resourceDesc = [ (GET, "return if the user is enabled")
, (PUT, "set if the user is enabled")
]
, resourceGet = [("json", serveUserEnabledGet)]
, resourcePut = [("json", serveUserEnabledPut)]
}
, adminResource = adminResource
, userListUri = \format ->
renderResource (userList r) [format]
, userPageUri = \format uname ->
renderResource (userPage r) [display uname, format]
, userPasswordUri = \format uname ->
renderResource (passwordResource r) [display uname, format]
, userEnabledUri = \format uname ->
renderResource (enabledResource r) [display uname, format]
, adminPageUri = \format ->
renderResource (groupResource adminResource) [format]
, manageUserUri = \format uname ->
renderResource (manageUserResource r) [display uname, format]
}
-- Queries and updates
--
queryGetUserDb :: MonadIO m => m Users.Users
queryGetUserDb = queryState usersState GetUserDb
updateAddUser :: MonadIO m => UserName -> UserAuth -> m (Either Users.ErrUserNameClash UserId)
updateAddUser uname auth = updateState usersState (AddUserEnabled uname auth)
updateSetUserEnabledStatus :: MonadIO m => UserId -> Bool
-> m (Maybe (Either Users.ErrNoSuchUserId Users.ErrDeletedUser))
updateSetUserEnabledStatus uid isenabled = updateState usersState (SetUserEnabledStatus uid isenabled)
updateSetUserAuth :: MonadIO m => UserId -> UserAuth
-> m (Maybe (Either Users.ErrNoSuchUserId Users.ErrDeletedUser))
updateSetUserAuth uid auth = updateState usersState (SetUserAuth uid auth)
--
-- Authorisation: authentication checks and privilege checks
--
-- High level, all in one check that the client is authenticated as a
-- particular user and has an appropriate privilege, but then ignore the
-- identity of the user.
guardAuthorised_ :: [PrivilegeCondition] -> ServerPartE ()
guardAuthorised_ = void . guardAuthorised
-- As above but also return the identity of the client
guardAuthorised :: [PrivilegeCondition] -> ServerPartE UserId
guardAuthorised privconds = do
users <- queryGetUserDb
uid <- guardAuthenticatedWithErrHook users
Auth.guardPriviledged users uid privconds
return uid
-- Simply check if the user is authenticated as some user, without any
-- check that they have any particular priveledges. Only useful as a
-- building block.
guardAuthenticated :: ServerPartE UserId
guardAuthenticated = do
users <- queryGetUserDb
guardAuthenticatedWithErrHook users
-- As above but using the given userdb snapshot
guardAuthenticatedWithErrHook :: Users.Users -> ServerPartE UserId
guardAuthenticatedWithErrHook users = do
(uid,_) <- Auth.checkAuthenticated realm users
>>= either handleAuthError return
return uid
where
realm = Auth.hackageRealm --TODO: should be configurable
handleAuthError :: Auth.AuthError -> ServerPartE a
handleAuthError err = do
defaultResponse <- Auth.authErrorResponse realm err
overrideResponse <- msum <$> runHook authFailHook err
throwError (fromMaybe defaultResponse overrideResponse)
-- | Resources representing the collection of known users.
--
-- Features:
--
-- * listing the collection of users
-- * adding and deleting users
-- * enabling and disabling accounts
-- * changing user's name and password
--
serveUsersGet :: DynamicPath -> ServerPartE Response
serveUsersGet _ = do
userlist <- Users.enumerateActiveUsers <$> queryGetUserDb
let users = [ UserNameIdResource {
ui_username = userName uinfo,
ui_userid = uid
}
| (uid, uinfo) <- userlist ]
return . toResponse $ toJSON users
serveUserGet :: DynamicPath -> ServerPartE Response
serveUserGet dpath = do
(uid, uinfo) <- lookupUserNameFull =<< userNameInPath dpath
groups <- getGroupIndex uid
return . toResponse $
toJSON UserInfoResource {
ui1_username = userName uinfo,
ui1_userid = uid,
ui1_groups = map T.pack groups
}
serveUserPut :: DynamicPath -> ServerPartE Response
serveUserPut dpath = do
guardAuthorised_ [InGroup adminGroup]
username <- userNameInPath dpath
muid <- updateState usersState $ AddUserDisabled username
case muid of
Left Users.ErrUserNameClash ->
errBadRequest "Username already exists"
[MText "Cannot create a new user account with that username because already exists"]
Right uid -> return . toResponse $
toJSON UserNameIdResource {
ui_username = username,
ui_userid = uid
}
serveUserDelete :: DynamicPath -> ServerPartE Response
serveUserDelete dpath = do
guardAuthorised_ [InGroup adminGroup]
uid <- lookupUserName =<< userNameInPath dpath
merr <- updateState usersState $ DeleteUser uid
case merr of
Nothing -> noContent $ toResponse ()
--TODO: need to be able to delete user by name to fix this race condition
Just Users.ErrNoSuchUserId -> errInternalError [MText "uid does not exist"]
serveUserEnabledGet :: DynamicPath -> ServerPartE Response
serveUserEnabledGet dpath = do
guardAuthorised_ [InGroup adminGroup]
(_uid, uinfo) <- lookupUserNameFull =<< userNameInPath dpath
let enabled = case userStatus uinfo of
AccountEnabled _ -> True
_ -> False
return . toResponse $ toJSON EnabledResource { ui_enabled = enabled }
serveUserEnabledPut :: DynamicPath -> ServerPartE Response
serveUserEnabledPut dpath = do
guardAuthorised_ [InGroup adminGroup]
uid <- lookupUserName =<< userNameInPath dpath
EnabledResource enabled <- expectAesonContent
merr <- updateState usersState (SetUserEnabledStatus uid enabled)
case merr of
Nothing -> noContent $ toResponse ()
Just (Left Users.ErrNoSuchUserId) ->
errInternalError [MText "uid does not exist"]
Just (Right Users.ErrDeletedUser) ->
errBadRequest "User deleted"
[MText "Cannot disable account, it has already been deleted"]
serveUserManagementGet :: DynamicPath -> ServerPartE Response
serveUserManagementGet dpath = do
(uid, uinfo) <- lookupUserNameFull =<< userNameInPath dpath
guardAuthorised_ [IsUserId uid, InGroup adminGroup]
template <- getTemplate templates "manage.html"
ok $ toResponse $
template
[ "username" $= userName uinfo
, "tokens" $=
[ templateDict
[ templateVal "hash" authtok
, templateVal "description" desc
]
| (authtok, desc) <- Map.toList (userTokens uinfo) ]
]
serveUserManagementPost :: DynamicPath -> ServerPartE Response
serveUserManagementPost dpath = do
(uid, uinfo) <- lookupUserNameFull =<< userNameInPath dpath
guardAuthorised_ [IsUserId uid, InGroup adminGroup]
action <- look "action"
case action of
"new-auth-token" -> do
desc <- T.pack <$> look "description"
template <- getTemplate templates "token-created.html"
origTok <- liftIO generateOriginalToken
let storeTok = convertToken origTok
res <- updateState usersState (AddAuthToken uid storeTok desc)
case res of
Nothing ->
ok $ toResponse $
template
[ "username" $= userName uinfo
, "token" $= viewOriginalToken origTok
]
Just Users.ErrNoSuchUserId ->
errInternalError [MText "uid does not exist"]
"revoke-auth-token" -> do
mauthToken <- parseAuthToken . T.pack <$> look "auth-token"
template <- getTemplate templates "token-revoked.html"
case mauthToken of
Left err -> errBadRequest "Bad auth token"
[MText "The auth token provided is malformed: "
,MText err]
Right authToken -> do
res <- updateState usersState (RevokeAuthToken uid authToken)
case res of
Nothing ->
ok $ toResponse $
template [ "username" $= userName uinfo ]
Just (Left Users.ErrNoSuchUserId) ->
errInternalError [MText "uid does not exist"]
Just (Right Users.ErrTokenNotOwned) ->
errBadRequest "Invalid auth token"
[MText "Cannot revoke this token, no such token."]
_ -> errBadRequest "Invalid form action" []
--
-- Exported utils for looking up user names in URLs\/paths
--
userNameInPath :: forall m. MonadPlus m => DynamicPath -> m UserName
userNameInPath dpath = maybe mzero return (simpleParse =<< lookup "username" dpath)
lookupUserName :: UserName -> ServerPartE UserId
lookupUserName = fmap fst . lookupUserNameFull
lookupUserNameFull :: UserName -> ServerPartE (UserId, UserInfo)
lookupUserNameFull uname = do
users <- queryState usersState GetUserDb
case Users.lookupUserName uname users of
Just u -> return u
Nothing -> userLost "Could not find user: not presently registered"
where userLost = errNotFound "User not found" . return . MText
--FIXME: 404 is only the right error for operating on User resources
-- not when users are being looked up for other reasons, like setting
-- ownership of packages. In that case needs errBadRequest
lookupUserInfo :: UserId -> ServerPartE UserInfo
lookupUserInfo uid = do
users <- queryState usersState GetUserDb
case Users.lookupUserId uid users of
Just uinfo -> return uinfo
Nothing -> errInternalError [MText "user id does not exist"]
adminAddUser :: ServerPartE Response
adminAddUser = do
-- with this line commented out, self-registration is allowed
guardAuthorised_ [InGroup adminGroup]
reqData <- getDataFn lookUserNamePasswords
case reqData of
(Left errs) -> errBadRequest "Error registering user"
((MText "Username, password, or repeated password invalid.") : map MText errs)
(Right (ustr, pwd1, pwd2)) -> do
uname <- newUserWithAuth ustr (PasswdPlain pwd1) (PasswdPlain pwd2)
seeOther ("/user/" ++ display uname) (toResponse ())
where lookUserNamePasswords = do
(,,) <$> look "username"
<*> look "password"
<*> look "repeat-password"
newUserWithAuth :: String -> PasswdPlain -> PasswdPlain -> ServerPartE UserName
newUserWithAuth _ pwd1 pwd2 | pwd1 /= pwd2 = errBadRequest "Error registering user" [MText "Entered passwords do not match"]
newUserWithAuth userNameStr password _ =
case simpleParse userNameStr of
Nothing -> errBadRequest "Error registering user" [MText "Not a valid user name!"]
Just uname -> do
let auth = newUserAuth uname password
muid <- updateState usersState $ AddUserEnabled uname auth
case muid of
Left Users.ErrUserNameClash -> errForbidden "Error registering user" [MText "A user account with that user name already exists."]
Right _ -> return uname
-- Arguments: the auth'd user id, the user path id (derived from the :username)
canChangePassword :: MonadIO m => UserId -> UserId -> m Bool
canChangePassword uid userPathId = do
admins <- queryState adminsState GetAdminList
return $ uid == userPathId || (uid `Group.member` admins)
--FIXME: this thing is a total mess!
-- Do admins need to change user's passwords? Why not just reset passwords & (de)activate accounts.
changePassword :: UserName -> ServerPartE ()
changePassword username = do
uid <- lookupUserName username
guardAuthorised [IsUserId uid, InGroup adminGroup]
passwd1 <- look "password" --TODO: fail rather than mzero if missing
passwd2 <- look "repeat-password"
when (passwd1 /= passwd2) $
forbidChange "Copies of new password do not match or is an invalid password (ex: blank)"
let passwd = PasswdPlain passwd1
auth = newUserAuth username passwd
res <- updateState usersState (SetUserAuth uid auth)
case res of
Nothing -> return ()
Just (Left Users.ErrNoSuchUserId) -> errInternalError [MText "user id lookup failure"]
Just (Right Users.ErrDeletedUser) -> forbidChange "Cannot set passwords for deleted users"
where
forbidChange = errForbidden "Error changing password" . return . MText
newUserAuth :: UserName -> PasswdPlain -> UserAuth
newUserAuth name pwd = UserAuth (Auth.newPasswdHash Auth.hackageRealm name pwd)
------ User group management
adminGroupDesc :: UserGroup
adminGroupDesc = UserGroup {
groupDesc = nullDescription { groupTitle = "Hackage admins" },
queryUserGroup = queryState adminsState GetAdminList,
addUserToGroup = updateState adminsState . AddHackageAdmin,
removeUserFromGroup = updateState adminsState . RemoveHackageAdmin,
groupsAllowedToAdd = [adminGroupDesc],
groupsAllowedToDelete = [adminGroupDesc]
}
groupAddUser :: UserGroup -> DynamicPath -> ServerPartE ()
groupAddUser group _ = do
actorUid <- guardAuthorised (map InGroup (groupsAllowedToAdd group))
users <- queryState usersState GetUserDb
muser <- optional $ look "user"
reason <- optional $ look "reason"
case muser of
Nothing -> addError "Bad request (could not find 'user' argument)"
Just ustr -> case simpleParse ustr >>= \uname -> Users.lookupUserName uname users of
Nothing -> addError $ "No user with name " ++ show ustr ++ " found"
Just (uid,_) -> do
liftIO $ addUserToGroup group uid
runHook_ groupChangedHook (groupDesc group, True,actorUid,uid,fromMaybe "" reason)
where addError = errBadRequest "Failed to add user" . return . MText
groupDeleteUser :: UserGroup -> DynamicPath -> ServerPartE ()
groupDeleteUser group dpath = do
actorUid <- guardAuthorised (map InGroup (groupsAllowedToDelete group))
uid <- lookupUserName =<< userNameInPath dpath
reason <- localRq (\req -> req {rqMethod = POST}) . optional $ look "reason"
liftIO $ removeUserFromGroup group uid
runHook_ groupChangedHook (groupDesc group, False,actorUid,uid,fromMaybe "" reason)
lookupGroupEditAuth :: UserGroup -> ServerPartE (Bool, Bool)
lookupGroupEditAuth group = do
addList <- liftIO . Group.queryUserGroups $ groupsAllowedToAdd group
removeList <- liftIO . Group.queryUserGroups $ groupsAllowedToDelete group
uid <- guardAuthenticated
let (canAdd, canDelete) = (uid `Group.member` addList, uid `Group.member` removeList)
if not (canAdd || canDelete)
then errForbidden "Forbidden" [MText "Can't edit permissions for user group"]
else return (canAdd, canDelete)
------------ Encapsulation of resources related to editing a user group.
-- | Registers a user group for external display. It takes the index group
-- mapping (groupIndex from UserFeature), the base uri of the group, and a
-- UserGroup object with all the necessary hooks. The base uri shouldn't
-- contain any dynamic or varying components. It returns the GroupResource
-- object, and also an adapted UserGroup that updates the cache. You should
-- use this in order to keep the index updated.
groupResourceAt :: String -> UserGroup -> IO (UserGroup, GroupResource)
groupResourceAt uri group = do
let mainr = resourceAt uri
descr = groupDesc group
groupUri = renderResource mainr []
group' = group
{ addUserToGroup = \uid -> do
addGroupIndex uid groupUri descr
addUserToGroup group uid
, removeUserFromGroup = \uid -> do
removeGroupIndex uid groupUri
removeUserFromGroup group uid
}
ulist <- queryUserGroup group
initGroupIndex ulist groupUri descr
let groupr = GroupResource {
groupResource = (extendResourcePath "/.:format" mainr) {
resourceDesc = [ (GET, "Description of the group and a list of its members (defined in 'users' feature)") ]
, resourceGet = [ ("json", serveUserGroupGet groupr) ]
}
, groupUserResource = (extendResourcePath "/user/:username.:format" mainr) {
resourceDesc = [ (PUT, "Add a user to the group (defined in 'users' feature)")
, (DELETE, "Remove a user from the group (defined in 'users' feature)")
]
, resourcePut = [ ("", serveUserGroupUserPut groupr) ]
, resourceDelete = [ ("", serveUserGroupUserDelete groupr) ]
}
, getGroup = \_ -> return group'
}
return (group', groupr)
-- | Registers a collection of user groups for external display. These groups
-- are usually backing a separate collection. Like groupResourceAt, it takes the
-- index group mapping and a base uri The base uri can contain varying path
-- components, so there should be a group-generating function that, given a
-- DynamicPath, yields the proper UserGroup. The final argument is the initial
-- list of DynamicPaths to build the initial group index. Like groupResourceAt,
-- this function returns an adaptor function that keeps the index updated.
groupResourcesAt :: String
-> (a -> UserGroup)
-> (a -> DynamicPath)
-> (DynamicPath -> ServerPartE a)
-> [a]
-> IO (a -> UserGroup, GroupResource)
groupResourcesAt uri mkGroup mkPath getGroupData initialGroupData = do
let mainr = resourceAt uri
sequence_
[ do let group = mkGroup x
dpath = mkPath x
ulist <- queryUserGroup group
initGroupIndex ulist (renderResource' mainr dpath) (groupDesc group)
| x <- initialGroupData ]
let mkGroup' x =
let group = mkGroup x
dpath = mkPath x
in group {
addUserToGroup = \uid -> do
addGroupIndex uid (renderResource' mainr dpath) (groupDesc group)
addUserToGroup group uid
, removeUserFromGroup = \uid -> do
removeGroupIndex uid (renderResource' mainr dpath)
removeUserFromGroup group uid
}
groupr = GroupResource {
groupResource = (extendResourcePath "/.:format" mainr) {
resourceDesc = [ (GET, "Description of the group and a list of the members (defined in 'users' feature)") ]
, resourceGet = [ ("json", serveUserGroupGet groupr) ]
}
, groupUserResource = (extendResourcePath "/user/:username.:format" mainr) {
resourceDesc = [ (PUT, "Add a user to the group (defined in 'users' feature)")
, (DELETE, "Delete a user from the group (defined in 'users' feature)")
]
, resourcePut = [ ("", serveUserGroupUserPut groupr) ]
, resourceDelete = [ ("", serveUserGroupUserDelete groupr) ]
}
, getGroup = \dpath -> mkGroup' <$> getGroupData dpath
}
return (mkGroup', groupr)
serveUserGroupGet groupr dpath = do
group <- getGroup groupr dpath
userDb <- queryGetUserDb
userlist <- liftIO $ queryUserGroup group
return . toResponse $ toJSON
UserGroupResource {
ui_title = T.pack $ groupTitle (groupDesc group),
ui_description = T.pack $ groupPrologue (groupDesc group),
ui_members = [ UserNameIdResource {
ui_username = Users.userIdToName userDb uid,
ui_userid = uid
}
| uid <- Group.toList userlist ]
}
--TODO: add serveUserGroupUserPost for the sake of the html frontend
-- and then remove groupAddUser & groupDeleteUser
serveUserGroupUserPut groupr dpath = do
group <- getGroup groupr dpath
actorUid <- guardAuthorised (map InGroup (groupsAllowedToAdd group))
uid <- lookupUserName =<< userNameInPath dpath
reason <- optional $ look "reason"
liftIO $ addUserToGroup group uid
runHook_ groupChangedHook (groupDesc group, True,actorUid,uid,fromMaybe "" reason)
goToList groupr dpath
serveUserGroupUserDelete groupr dpath = do
group <- getGroup groupr dpath
actorUid <- guardAuthorised (map InGroup (groupsAllowedToDelete group))
uid <- lookupUserName =<< userNameInPath dpath
reason <- optional $ look "reason"
liftIO $ removeUserFromGroup group uid
runHook_ groupChangedHook (groupDesc group, False,actorUid,uid,fromMaybe "" reason)
goToList groupr dpath
goToList group dpath = seeOther (renderResource' (groupResource group) dpath)
(toResponse ())
---------------------------------------------------------------
addGroupIndex :: MonadIO m => UserId -> String -> GroupDescription -> m ()
addGroupIndex (UserId uid) uri desc =
modifyMemState groupIndex $
adjustGroupIndex
(IntMap.insertWith Set.union uid (Set.singleton uri))
(Map.insert uri desc)
removeGroupIndex :: MonadIO m => UserId -> String -> m ()
removeGroupIndex (UserId uid) uri =
modifyMemState groupIndex $
adjustGroupIndex
(IntMap.update (keepSet . Set.delete uri) uid)
id
where
keepSet m = if Set.null m then Nothing else Just m
initGroupIndex :: MonadIO m => UserIdSet -> String -> GroupDescription -> m ()
initGroupIndex ulist uri desc =
modifyMemState groupIndex $
adjustGroupIndex
(IntMap.unionWith Set.union (IntMap.fromList . map mkEntry $ Group.toList ulist))
(Map.insert uri desc)
where
mkEntry (UserId uid) = (uid, Set.singleton uri)
getGroupIndex :: (Functor m, MonadIO m) => UserId -> m [String]
getGroupIndex (UserId uid) =
liftM (maybe [] Set.toList . IntMap.lookup uid . usersToGroupUri) $ readMemState groupIndex
getIndexDesc :: MonadIO m => String -> m GroupDescription
getIndexDesc uri =
liftM (Map.findWithDefault nullDescription uri . groupUrisToDesc) $ readMemState groupIndex
-- partitioning index modifications, a cheap combinator
adjustGroupIndex :: (IntMap (Set String) -> IntMap (Set String))
-> (Map String GroupDescription -> Map String GroupDescription)
-> GroupIndex -> GroupIndex
adjustGroupIndex f g (GroupIndex a b) = GroupIndex (f a) (g b)
{------------------------------------------------------------------------------
Some types for JSON resources
------------------------------------------------------------------------------}
data UserNameIdResource = UserNameIdResource { ui_username :: UserName,
ui_userid :: UserId }
data UserInfoResource = UserInfoResource { ui1_username :: UserName,
ui1_userid :: UserId,
ui1_groups :: [T.Text] }
data EnabledResource = EnabledResource { ui_enabled :: Bool }
data UserGroupResource = UserGroupResource { ui_title :: T.Text,
ui_description :: T.Text,
ui_members :: [UserNameIdResource] }
deriveJSON (compatAesonOptionsDropPrefix "ui_") ''UserNameIdResource
deriveJSON (compatAesonOptionsDropPrefix "ui1_") ''UserInfoResource
deriveJSON (compatAesonOptionsDropPrefix "ui_") ''EnabledResource
deriveJSON (compatAesonOptionsDropPrefix "ui_") ''UserGroupResource
| agrafix/hackage-server | Distribution/Server/Features/Users.hs | bsd-3-clause | 39,376 | 28 | 27 | 11,548 | 7,561 | 3,960 | 3,601 | 592 | 24 |
module BrowseSpec where
import Control.Applicative
import Test.Hspec
import Browse
import Expectation
import Types
spec :: Spec
spec = do
describe "browseModule" $ do
it "lists up symbols in the module" $ do
syms <- lines <$> browseModule defaultOptions "Data.Map"
syms `shouldContain` "differenceWithKey"
describe "browseModule -d" $ do
it "lists up symbols with type info in the module" $ do
syms <- lines <$> browseModule defaultOptions { detailed = True } "Data.Either"
syms `shouldContain` "either :: (a -> c) -> (b -> c) -> Either a b -> c"
it "lists up data constructors with type info in the module" $ do
syms <- lines <$> browseModule defaultOptions { detailed = True} "Data.Either"
syms `shouldContain` "Left :: a -> Either a b"
| eagletmt/ghc-mod | test/BrowseSpec.hs | bsd-3-clause | 847 | 0 | 17 | 229 | 174 | 87 | 87 | 19 | 1 |
{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-}
module Main where
import Web.Scotty as S
import Control.Monad.IO.Class
import Control.Monad.Reader
import Data.Monoid
import TimeEdit
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import Text.Blaze.Html5 as H hiding (main)
import Text.Blaze.Html5.Attributes as A hiding (id)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Data.Time.Format
import Network.HTTP.Client.Conduit
default (T.Text)
main :: IO ()
main = do
manager <- newManager
scotty 8080 $ do
get "/" $ do
maybeQuery <- processParams <$> S.params
case maybeQuery of
Nothing -> frontPage manager ""
Just roomQuery -> do
table <- queryTable manager roomQuery
blaze . template $ searchBox roomQuery <> table
notFound $
frontPage manager ""
processParams :: [Param] -> Maybe Text
processParams (("room", query):_) = case query of
"" -> Nothing
q -> Just q
processParams _ = Nothing
frontPageQueries :: [Text]
frontPageQueries = ["mvf", "mvl", "fl", "ha", "hb", "hc"]
frontPage :: Manager -> Text -> ActionM ()
frontPage manager query = do
tables <- mapM (queryTable manager) frontPageQueries
blaze . template . mconcat $ searchBox query : tables
queryTable :: Manager -> Text -> ActionM Html
queryTable manager query = do
resultEither <- liftIO $ runReaderT (roomStatusSearch query) manager
return . toHtml . htmlResults $ resultEither
htmlResults :: Either Text [Room] -> Html
htmlResults = either (p . toHtml) roomStatusTable
searchBox :: Text -> Html
searchBox query
= H.div $
H.form ! A.method "get" $
input ! A.name "room"
! A.type_ "text"
! A.placeholder "room name"
! A.autofocus ""
! A.value (lazyTextValue query)
template :: Html -> Html
template pageBody
= docTypeHtml $ do
H.head $ do
H.meta ! A.charset "utf-8"
H.style css
H.body pageBody
css :: Html
css =
"body { font-size: 30px; font-family: Helvetica, sans-serif; }\
\table { display: inline-block; vertical-align: top; margin: 0.5em; }\
\form { text-align: center; }\
\input { font-size: 50px; }\
\.green { color: green; }\
\.red { color: red; }"
green :: Html -> Html
green = H.span ! A.class_ "green"
red :: Html -> Html
red = H.span ! A.class_ "red"
roomStatusTable :: [Room] -> Html
roomStatusTable = table . mapM_ htmlFromRoom
htmlFromRoom :: Room -> Html
htmlFromRoom (Room name status)
= tr $ do
td $ toHtml name
td $ htmlFromRoomStatus status
htmlFromRoomStatus :: RoomStatus -> Html
htmlFromRoomStatus status = case status of
Occupied -> red "Occupied"
Free -> green "Free today"
(FreeUntil time)
-> green . toHtml $ "Free until " ++ format time
where
format = formatTime defaultTimeLocale "%H:%M"
blaze = S.html . renderHtml
| pnutus/slask | app/Main.hs | bsd-3-clause | 2,877 | 0 | 20 | 634 | 870 | 450 | 420 | 83 | 3 |
module Llvm.Hir.Data (module Llvm.Hir.Data.Module
,module Llvm.Hir.Data.Type
,module Llvm.Hir.Data.Inst
,module Llvm.Hir.Data.Commentor
,module Llvm.Hir.Data
) where
import Llvm.Hir.Data.Module
import Llvm.Hir.Data.Type
import Llvm.Hir.Data.Inst hiding (LocalId)
import Llvm.Hir.Data.Commentor
import Llvm.Hir.Target
{-
SpecializedModule dlm g a
^ ^ ^
| | +- specialized Cnode, it can be customized by a client
| +---- specialized GlobalId, it can be customized by a client
+------- an instance of DataLayoutMetrics to specify
target datalayout and triple
For a consumer that does not demand specializing Cnode and GlobalId,
then SpecializedModule dlm () () is a typical instance, and dlm
is a target datalayout and target triple instance.
Sorry for such a long type instance with multiple type instantiations, but I
haven't found a better way to hide them for the default instance.
-}
data SpecializedModule g a = SpecializedModule Target (Module g a) | mlite/hLLVM | src/Llvm/Hir/Data.hs | bsd-3-clause | 1,199 | 0 | 8 | 380 | 110 | 76 | 34 | 11 | 0 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Halytics.Tutorial where
import Control.Lens
import Halytics.Monitor
import Halytics.Metric
import Halytics.Metric.Statistics
{-$
First, some extensions:
>>> :set -XDataKinds
== The basics
The most important type in Halytics is a 'Monitor'. It stores the values you
give it and, when you ask for it, gives you a result. To get a 'Monitor' you
usually call 'generate', which will take care of setting up everything for you.
>>> :t generate
generate :: (Default t, Collect t) => Monitor t
Let's leave the constraint aside for now. What you need to do is simply tell
'generate' what /type/ of 'Monitor' you want and it will build one for you.
Let's start with a simple type, 'Max', that can be found in 'Halytics.Metric'
('Max' works within the constraint @(Default t, Collect t)@):
>>> let firstMonitor = generate :: Monitor Max
There are two functions important to the use of a 'Monitor':
* 'notify': notify a 'Monitor' that a new value is available for collection.
* 'result': computes a type of result using the values collected.
Let's have a look at 'notify' first:
>>> :t notify
notify :: Collect t => Monitor t -> Double -> Monitor t
As expected, 'notify' takes a 'Monitor', a new value, and returns a 'Monitor'
of the same type. The internal state of the 'Monitor' was updated to account
for the new value. In the case of @firstMonitor@, @t = Max@. Let's add some
values to our monitor:
>>> let firstMonitor' = (`notify` 3) . (`notify` 1) $ firstMonitor
Here we successively notified the monitor of the values @1@ and @3@. Now, let's
use 'result', mentioned above:
>>> result firstMonitor' :: Maybe Double
Just 3.0
Well, that's good. As expected, the maximum of @1@ and @3@ is... @3@. What
about adding a value?
>>> result $ notify firstMonitor' 42 :: Maybe Double
Just 42.0
Now let's have a quick look at the signature of 'result':
>>> :t result
result :: Resultable t r => Monitor t -> r
'Resultable' is a type class defining a relation between a type of metric (@t@)
and a type of result it can produce (@r@). When we called 'result' above we
used the instance
> instance Resultable Max (Maybe Double) where ...
We could also have used:
>>> result firstMonitor' :: String
"Max: 3.0"
which makes it convenient to print out results. Finally, using our initial
monitor (which doesn't hold any value) we understand why 'result' uses 'Maybe'
'Double' instead of just 'Double' for 'Max':
>>> result firstMonitor :: String
"No maximum found"
The maximum is not defined when there are no values.
== Bundling metrics together
Often you will want to record several metrics over the same set of data. A
'Monitor' doesn't limit you to a single 'Metric'. For instance, Alice wants to
record the minimum, the maximum, and the list of all values that have been
collected.
>>> type AliceMetrics = (Min, Max, All)
>>> let alice = generate :: Monitor AliceMetrics
We know 'Max', and we can infer what 'Min' does. 'All' is different in the
sense that it will keep track of /all/ the values that have been collected so
far. Now we will need to access the metrics. For this, some lenses are
provided:
>>> alice^._1&result :: String
"No minimum found"
>>> alice^._3&result :: String
"Collected: (none)"
Let's see what we're accessing here:
>>> :t alice^._1
alice^._1 :: Monitor Min
>>> :t alice^._2
alice^._2 :: Monitor Max
>>> :t alice^._3
alice^._3 :: Monitor All
Great! Using instances of lens' 'Field1', 'Field2', ... we can jump inside a
'Monitor' @(a, b, ...)@ and use each individual 'Monitor' @a, b, c...@. Still,
you will only need to notify one monitor:
>>> let alice' = (`notify` 9) . (`notify` 3) $ alice
>>> alice'^._1&result :: String
"Min: 3.0"
>>> alice'^._3&result :: String
"Collected: 3.0, 9.0"
Enters Bob, who wants to record the median, @95th@ and @99th@ percentiles:
>>> type BobMetrics = (Median, Percentile 95, Percentile 99)
>>> let bob = generate :: Monitor BobMetrics
'Median' and 'Percentile' are defined in 'Halytics.Metric.Statistics'.
'Percentile' allows you to define the percentile you want to read at compile
time:
>>> :kind Percentile
Percentile :: GHC.TypeLits.Nat -> *
(The median is simply defined as @type Median = Percentile 50@)
Now comes Bob and Alice's boss, who wants to use all those metrics together:
>>> type CompanyMetrics = (AliceMetrics, BobMetrics)
>>> let company = generate :: Monitor CompanyMetrics
>>> let company' = notifyMany company [1, 3.43, -5, 103.0]
And we can still use the individual metrics by combining the lenses:
>>> company'^._1._3&result :: String
"Collected: 1.0, 3.43, -5.0, 103.0"
== Combinators
TODO
== The type classes
TODO
-}
| nmattia/halytics | src/Halytics/Tutorial.hs | bsd-3-clause | 4,711 | 0 | 4 | 848 | 29 | 19 | 10 | 6 | 0 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | See "Control.Monad.Trans.Except".
module Control.Monad.Trans.Ether.Except
(
-- * The Except monad
Except
, except
, runExcept
-- * The ExceptT monad transformer
, ExceptT
, exceptT
, runExceptT
-- * Exception operations
, throw
, catch
) where
import Data.Functor.Identity (Identity(..))
import Control.Applicative
import Control.Monad (MonadPlus)
import Control.Monad.Fix (MonadFix)
import Control.Monad.Trans.Class (MonadTrans, lift)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Morph (MFunctor, MMonad)
import Control.Ether.Tagged (Taggable(..), Tagged(..))
import GHC.Generics (Generic)
import qualified Control.Newtype as NT
import qualified Control.Monad.Base as MB
import qualified Control.Monad.Trans.Control as MC
import qualified Control.Monad.Trans.Except as Trans
import qualified Control.Monad.Trans.Lift.StT as Lift
import qualified Control.Monad.Trans.Lift.Local as Lift
import qualified Control.Monad.Trans.Lift.Catch as Lift
import qualified Control.Monad.Trans.Lift.Listen as Lift
import qualified Control.Monad.Trans.Lift.Pass as Lift
import qualified Control.Monad.Trans.Lift.CallCC as Lift
import qualified Control.Monad.Cont.Class as Class
import qualified Control.Monad.Reader.Class as Class
import qualified Control.Monad.State.Class as Class
import qualified Control.Monad.Writer.Class as Class
import qualified Control.Monad.Error.Class as Class
-- | The parameterizable exception monad.
--
-- Computations are either exceptions or normal values.
--
-- The 'return' function returns a normal value, while '>>=' exits on
-- the first exception.
type Except tag e = ExceptT tag e Identity
-- | Runs an 'Except' and returns either an exception or a normal value.
runExcept :: proxy tag -> Except tag e a -> Either e a
runExcept t = Trans.runExcept . untagged t
-- | The exception monad transformer.
--
-- The 'return' function returns a normal value, while '>>=' exits on
-- the first exception.
newtype ExceptT tag e m a = ExceptT (Trans.ExceptT e m a)
deriving ( Generic
, Functor, Applicative, Alternative, Monad, MonadPlus
, MonadFix, MonadTrans, MonadIO, MFunctor, MMonad )
instance NT.Newtype (ExceptT tag e m a)
instance MB.MonadBase b m => MB.MonadBase b (ExceptT tag e m) where
liftBase = MB.liftBaseDefault
instance MC.MonadTransControl (ExceptT tag e) where
type StT (ExceptT tag e) a = MC.StT (Trans.ExceptT e) a
liftWith = MC.defaultLiftWith NT.pack NT.unpack
restoreT = MC.defaultRestoreT NT.pack
instance MC.MonadBaseControl b m => MC.MonadBaseControl b (ExceptT tag e m) where
type StM (ExceptT tag e m) a = MC.ComposeSt (ExceptT tag e) m a
liftBaseWith = MC.defaultLiftBaseWith
restoreM = MC.defaultRestoreM
type instance Lift.StT (ExceptT tag e) a = MC.StT (ExceptT tag e) a
instance Lift.LiftLocal (ExceptT tag e) where
liftLocal = Lift.defaultLiftLocal NT.pack NT.unpack
instance Lift.LiftCatch (ExceptT tag e) where
liftCatch = Lift.defaultLiftCatch NT.pack NT.unpack
instance Lift.LiftListen (ExceptT tag e) where
liftListen = Lift.defaultLiftListen NT.pack NT.unpack
instance Lift.LiftPass (ExceptT tag e) where
liftPass = Lift.defaultLiftPass NT.pack NT.unpack
instance Lift.LiftCallCC (ExceptT tag e) where
liftCallCC = Lift.defaultLiftCallCC NT.pack NT.unpack
liftCallCC' = Lift.defaultLiftCallCC NT.pack NT.unpack
instance Taggable (ExceptT tag e m) where
type Tag (ExceptT tag e m) = 'Just tag
type Inner (ExceptT tag e m) = 'Just m
instance Tagged (ExceptT tag e m) tag where
type Untagged (ExceptT tag e m) = Trans.ExceptT e m
-- | Constructor for computations in the exception monad transformer.
exceptT :: proxy tag -> m (Either e a) -> ExceptT tag e m a
exceptT t = tagged t . Trans.ExceptT
-- | Constructor for computations in the exception monad
-- (the inverse of 'runExcept').
except :: Monad m => proxy tag -> Either e a -> ExceptT tag e m a
except t = exceptT t . return
-- | Runs an 'ExceptT' and returns either an exception or a normal value.
runExceptT :: proxy tag -> ExceptT tag e m a -> m (Either e a)
runExceptT t = Trans.runExceptT . untagged t
-- | Is used within a monadic computation to begin exception processing.
throw :: Monad m => proxy tag -> e -> ExceptT tag e m a
throw t = tagged t . Trans.throwE
-- | A handler function to handle previous exceptions and return to normal execution.
catch :: Monad m => proxy tag -> ExceptT tag e m a -> (e -> ExceptT tag e m a) -> ExceptT tag e m a
catch t m h = tagged t $ Trans.catchE (untagged t m) (untagged t . h)
instance Class.MonadCont m => Class.MonadCont (ExceptT tag e m) where
callCC = Lift.liftCallCC Class.callCC
instance Class.MonadReader r m => Class.MonadReader r (ExceptT tag e m) where
ask = lift Class.ask
local = Lift.liftLocal Class.ask Class.local
reader = lift . Class.reader
instance Class.MonadState s m => Class.MonadState s (ExceptT tag e m) where
get = lift Class.get
put = lift . Class.put
state = lift . Class.state
instance Class.MonadWriter w m => Class.MonadWriter w (ExceptT tag e m) where
writer = lift . Class.writer
tell = lift . Class.tell
listen = Lift.liftListen Class.listen
pass = Lift.liftPass Class.pass
instance Class.MonadError e' m => Class.MonadError e' (ExceptT tag e m) where
throwError = lift . Class.throwError
catchError = Lift.liftCatch Class.catchError
| bitemyapp/ether | src/Control/Monad/Trans/Ether/Except.hs | bsd-3-clause | 5,742 | 0 | 11 | 1,060 | 1,645 | 902 | 743 | 104 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE ExistentialQuantification #-}
module Language.LSP.Types.Cancellation where
import Data.Aeson.TH
import Language.LSP.Types.LspId
import Language.LSP.Types.Utils
data CancelParams = forall m.
CancelParams
{ -- | The request id to cancel.
_id :: LspId m
}
deriving instance Read CancelParams
deriving instance Show CancelParams
instance Eq CancelParams where
(CancelParams a) == CancelParams b =
case (a,b) of
(IdInt x, IdInt y) -> x == y
(IdString x, IdString y) -> x == y
_ -> False
deriveJSON lspOptions ''CancelParams
| alanz/haskell-lsp | lsp-types/src/Language/LSP/Types/Cancellation.hs | mit | 773 | 0 | 10 | 178 | 172 | 96 | 76 | 22 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
module DTypes.Internal.TH.Helpers
( destructure
, appEs
, apAppEs
, liftAppEs
, nameFromTyVarBndr
, conAppsT
) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative (Applicative (..), (<$>))
#endif
import Language.Haskell.TH
-- | Generates `case $val of { $pat -> $exp }`
destructure :: ExpQ -> PatQ -> ExpQ -> ExpQ
destructure val pat expr = caseE val [match pat (normalB expr) []]
-- | Generates `f arg1 ... argn`
appEs :: ExpQ -> [ExpQ] -> ExpQ
appEs = foldl appE
-- | Generates `f <*> arg1 <*> ... <*> argn`
apAppEs :: ExpQ -> [ExpQ] -> ExpQ
apAppEs = foldl (\g y -> [e| $g <*> $y |])
-- | Generates `f <$> arg1 <*> ... <*> argn`
liftAppEs :: ExpQ -> [ExpQ] -> ExpQ
liftAppEs x args =
case args of
[] -> [e| pure $x |]
firstArg:nextArgs -> apAppEs [e| $x <$> $firstArg |] nextArgs
-- | Extract the name from a TyVarBndr.
nameFromTyVarBndr :: TyVarBndr -> Name
nameFromTyVarBndr bndr =
case bndr of
PlainTV name -> name
KindedTV name _kind -> name
-- | Apply arguments to a type constructor.
conAppsT :: Name -> [Type] -> Type
conAppsT conName = foldl AppT (ConT conName)
| timjb/frecords | src/DTypes/Internal/TH/Helpers.hs | mit | 1,180 | 0 | 9 | 244 | 314 | 181 | 133 | 29 | 2 |
module Main where
import Genes;
import Util;
import Debug.Trace;
fit::Fitness
fit chr = sum $ map fromIntegral chr
fitGenerator::Double->(Double->Double)->Double->Fitness
fitGenerator num f target = (\chromosome ->
let x = binToDouble num chromosome
delta = target - f x :: Double
in 1.0 / delta ** 2.0)
fit' = fitGenerator 3 (\x -> x * sin x) 3
opts::EvOptions
opts= EvOptions{populationSize = 42,
individLength = 10,
maxGeneration = 1000,
fitness = fit',
targetFitness = 10^10,
mutationChance = 0.3,
elitePart = 0.1}
main::IO()
main = do
(n,result, bestInd) <- initEvol opts
print $ "Generation: " ++ show n
print $ "Best Individual: " ++ show bestInd
print $ "Individual val: " ++ show (binToDouble 3 bestInd)
print $ "Error equals: " ++ show (1.0 / (fit' bestInd))
print $ "Whole population:" ++ show result | Teaspot-Studio/bmstu-binary-genetics | src/Main.hs | mit | 957 | 0 | 12 | 277 | 333 | 177 | 156 | 28 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.EFS.Types.Sum
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.EFS.Types.Sum where
import Network.AWS.Prelude
data LifeCycleState
= Available
| Creating
| Deleted
| Deleting
deriving (Eq,Ord,Read,Show,Enum,Data,Typeable,Generic)
instance FromText LifeCycleState where
parser = takeLowerText >>= \case
"available" -> pure Available
"creating" -> pure Creating
"deleted" -> pure Deleted
"deleting" -> pure Deleting
e -> fromTextError $ "Failure parsing LifeCycleState from value: '" <> e
<> "'. Accepted values: available, creating, deleted, deleting"
instance ToText LifeCycleState where
toText = \case
Available -> "available"
Creating -> "creating"
Deleted -> "deleted"
Deleting -> "deleting"
instance Hashable LifeCycleState
instance ToByteString LifeCycleState
instance ToQuery LifeCycleState
instance ToHeader LifeCycleState
instance FromJSON LifeCycleState where
parseJSON = parseJSONText "LifeCycleState"
| fmapfmapfmap/amazonka | amazonka-efs/gen/Network/AWS/EFS/Types/Sum.hs | mpl-2.0 | 1,549 | 0 | 12 | 344 | 236 | 128 | 108 | 33 | 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.MachineLearning.DeleteDataSource
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Assigns the DELETED status to a 'DataSource', rendering it unusable.
--
-- After using the 'DeleteDataSource' operation, you can use the 'GetDataSource'
-- operation to verify that the status of the 'DataSource' changed to DELETED.
--
-- Caution The results of the 'DeleteDataSource' operation are irreversible.
--
--
-- <http://http://docs.aws.amazon.com/machine-learning/latest/APIReference/API_DeleteDataSource.html>
module Network.AWS.MachineLearning.DeleteDataSource
(
-- * Request
DeleteDataSource
-- ** Request constructor
, deleteDataSource
-- ** Request lenses
, ddsDataSourceId
-- * Response
, DeleteDataSourceResponse
-- ** Response constructor
, deleteDataSourceResponse
-- ** Response lenses
, ddsrDataSourceId
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.MachineLearning.Types
import qualified GHC.Exts
newtype DeleteDataSource = DeleteDataSource
{ _ddsDataSourceId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteDataSource' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ddsDataSourceId' @::@ 'Text'
--
deleteDataSource :: Text -- ^ 'ddsDataSourceId'
-> DeleteDataSource
deleteDataSource p1 = DeleteDataSource
{ _ddsDataSourceId = p1
}
-- | A user-supplied ID that uniquely identifies the 'DataSource'.
ddsDataSourceId :: Lens' DeleteDataSource Text
ddsDataSourceId = lens _ddsDataSourceId (\s a -> s { _ddsDataSourceId = a })
newtype DeleteDataSourceResponse = DeleteDataSourceResponse
{ _ddsrDataSourceId :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'DeleteDataSourceResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ddsrDataSourceId' @::@ 'Maybe' 'Text'
--
deleteDataSourceResponse :: DeleteDataSourceResponse
deleteDataSourceResponse = DeleteDataSourceResponse
{ _ddsrDataSourceId = Nothing
}
-- | A user-supplied ID that uniquely identifies the 'DataSource'. This value should
-- be identical to the value of the 'DataSourceID' in the request.
ddsrDataSourceId :: Lens' DeleteDataSourceResponse (Maybe Text)
ddsrDataSourceId = lens _ddsrDataSourceId (\s a -> s { _ddsrDataSourceId = a })
instance ToPath DeleteDataSource where
toPath = const "/"
instance ToQuery DeleteDataSource where
toQuery = const mempty
instance ToHeaders DeleteDataSource
instance ToJSON DeleteDataSource where
toJSON DeleteDataSource{..} = object
[ "DataSourceId" .= _ddsDataSourceId
]
instance AWSRequest DeleteDataSource where
type Sv DeleteDataSource = MachineLearning
type Rs DeleteDataSource = DeleteDataSourceResponse
request = post "DeleteDataSource"
response = jsonResponse
instance FromJSON DeleteDataSourceResponse where
parseJSON = withObject "DeleteDataSourceResponse" $ \o -> DeleteDataSourceResponse
<$> o .:? "DataSourceId"
| romanb/amazonka | amazonka-ml/gen/Network/AWS/MachineLearning/DeleteDataSource.hs | mpl-2.0 | 4,056 | 0 | 9 | 809 | 464 | 284 | 180 | 56 | 1 |
{-# LANGUAGE TemplateHaskell, TupleSections, MultiParamTypeClasses #-}
{-|
This module contains the Template Haskell routines used to generate indexed
set structures and their associated query types.
-}
module Language.K3.Utils.IndexedSet.TemplateHaskell
( QueryDescriptor(..)
, createIndexedSet
) where
import Control.Applicative
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
import Language.K3.Utils.IndexedSet.Class as ISC
import Language.K3.Utils.IndexedSet.Common
import Language.K3.Utils.TemplateHaskell.Utils
-- |A data type used to describe a query on an indexed structure. The query has
-- the following components: a name (used in the names of the query constructor
-- as well as the structure's index), the types of the query input and the
-- query response, and an analysis function accepting an element and returning
-- a list of tuples of those inputs and outputs. This analysis function
-- indicates which entries are added to the indices as a result of the element.
data QueryDescriptor
= QueryDescriptor
{ queryName :: String
, queryInputType :: Q Type
, queryOutputType :: Q Type
, queryAnalyzer :: Q Exp
}
{- |Generates an indexed data structure from the appropriate program fragments.
This routine accepts an element data type and a list of @QueryDescriptor@.
It defines types for the data structure and query types using the specified
names; it also creates an instance of @IndexedSet@ for these types.
-}
createIndexedSet :: String
-- ^The name of the indexed structure type to
-- generate.
-> String
-- ^The name of the query type to generate.
-> Q Type
-- ^The type of element stored in the structure.
-> [QueryDescriptor]
-- ^The descriptions of the queries to generate.
-> Q [Dec]
-- ^The declarations which generate the
-- aforementioned.
createIndexedSet idxStrName queryTypName elTyp descs = do
isD <- indexedStructureDeclaration
qtD <- queryTypeDefinition
inD <- instanceDefinition
return $ [isD,qtD,inD]
where
indexedStructureDeclaration :: Q Dec
indexedStructureDeclaration = do
indices <- mapM mkIndexDefinition descs
allField <- (allFieldName idxStrName, NotStrict,) <$>
[t| Set $(elTyp) |]
return $ DataD [] (mkName idxStrName) []
[ RecC (mkName idxStrName) $ allField:indices ] []
where
mkIndexDefinition :: QueryDescriptor -> Q VarStrictType
mkIndexDefinition desc =
(indexName desc, NotStrict,) <$>
[t| MultiMap $(queryInputType desc) $(queryOutputType desc) |]
queryTypeDefinition :: Q Dec
queryTypeDefinition = do
v <- newName "result"
cons <- mapM (mkQueryConstructor v) descs
return $ DataD [] (mkName queryTypName) [PlainTV v] cons []
where
mkQueryConstructor :: Name -> QueryDescriptor -> Q Con
mkQueryConstructor varName desc = do
inType <- queryInputType desc
outType <- queryOutputType desc
return $ ForallC [] [EqualP (VarT varName) outType] $
NormalC (queryConName desc) [(NotStrict, inType)]
instanceDefinition :: Q Dec
instanceDefinition =
instanceD (pure [])
(foldl appT (conT $ ''IndexedSet)
[ conT $ mkName idxStrName
, elTyp
, conT $ mkName queryTypName
])
[ emptyDefinition
, insertDefinition
, unionDefinition
, queryDefinition
, toSetDefinition
]
where
mkIdxStrP :: Name -> [Name] -> Q Pat
mkIdxStrP allName idxNames =
conP (mkName idxStrName) $ map varP $ allName:idxNames
emptyDefinition :: Q Dec
emptyDefinition =
let emptyExpr =
foldl appE (appE (conE $ mkName idxStrName) [|Set.empty|]) $
map (const [|Map.empty|]) descs
in valD (varP 'ISC.empty) (normalB emptyExpr) []
insertDefinition :: Q Dec
insertDefinition = do
indexNames <- mapM snd $ zip descs $ mkPrefixNames "idx"
allFieldNm <- newName "f"
elName <- newName "e"
let elP = varP elName
let idxStrP = mkIdxStrP allFieldNm indexNames
let expr =
foldl appE (appE (conE $ mkName idxStrName)
[|Set.insert $(varE elName)
$(varE allFieldNm)|]) $
map (uncurry $ mkFieldExpr elName) $ zip indexNames descs
funD 'ISC.insert $ [ clause [elP, idxStrP] (normalB expr) []]
where
mkFieldExpr elNm fNm desc =
[| let entries = $(queryAnalyzer desc) $(varE elNm) in
let newMap = concatMultiMap $
map (mapToMultiMap . uncurry Map.singleton)
entries in
appendMultiMap $(varE fNm) newMap
|]
unionDefinition :: Q Dec
unionDefinition = do
indexNames1 <- mapM snd $ zip descs $ mkPrefixNames "i1"
indexNames2 <- mapM snd $ zip descs $ mkPrefixNames "i2"
allName1 <- newName "a1"
allName2 <- newName "a2"
let arg1P = mkIdxStrP allName1 indexNames1
let arg2P = mkIdxStrP allName2 indexNames2
let expr =
foldl appE (appE (conE $ mkName idxStrName)
[|Set.union $(varE allName1) $(varE allName2)|]) $
map (\(n1,n2) ->
[|appendMultiMap $(varE n1) $(varE n2)|]) $
zip indexNames1 indexNames2
funD 'ISC.union [clause [arg1P, arg2P] (normalB expr) []]
queryDefinition :: Q Dec
queryDefinition = do
qName <- newName "q"
indexNames <- mapM snd $ zip descs $ mkPrefixNames "i"
allName <- newName "_a"
let idxStrP = mkIdxStrP allName indexNames
let expr = caseE (varE qName) $
map (mkMatchForQuery qName) $ zip indexNames descs
funD 'ISC.query [clause [idxStrP, varP qName] (normalB expr) []]
where
mkMatchForQuery qName (idxName, desc) = do
argName <- newName "arg"
match (conP (queryConName desc) [varP argName])
(normalB $
[|multiMapLookup $(varE argName) $(varE $ idxName)|]
) []
toSetDefinition :: Q Dec
toSetDefinition = do
allName <- newName "a"
let wilds = map (const wildP) descs
let idxStrP = conP (mkName $ idxStrName) ((varP allName):wilds)
funD 'ISC.toSet [clause [idxStrP] (normalB $ varE allName) []]
-- |Determines the name of the field in the record of the indexed structure
-- which contains a set of all values in the structure.
allFieldName :: String -> Name
allFieldName idxStrName = mkName $ "elementsOf" ++ idxStrName
-- |Determines the name of an index given its descriptor and the name of the
-- type in which it appears.
indexName :: QueryDescriptor -> Name
indexName desc = mkName $ "index" ++ queryName desc
-- |Determines the name of the query constructor for a given index.
queryConName :: QueryDescriptor -> Name
queryConName desc = mkName $ "Query" ++ queryName desc
| DaMSL/K3 | src/Language/K3/Utils/IndexedSet/TemplateHaskell.hs | apache-2.0 | 7,671 | 8 | 27 | 2,491 | 1,614 | 827 | 787 | 133 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.