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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
module RefacIntroPattern(introPattern, introCase, foldPattern) where
import TypeCheck
import PrettyPrint
import PosSyntax
import AbstractIO
import Data.Maybe
import TypedIds
import UniqueNames hiding (srcLoc)
import PNT
import TiPNT
import Data.List
import RefacUtils hiding (getParams)
import PFE0 (findFile, allFiles, allModules)
import MUtils (( # ))
import RefacLocUtils
-- import System
import System.IO
import Relations
import Ents
import Data.Set (toList)
import Data.List
-- | An argument list for a function which of course is a list of paterns.
type FunctionPats = [HsPatP]
-- | A list of declarations used to represent a where or let clause.
type WhereDecls = [HsDeclP]
data PatFun = Mat | Patt | Er deriving (Eq, Show)
{- This module contains 3 refactorings for HaRe:
introPattern : introduce a exhaustive pattern match for a
selected pattern variable.
introCase : introduce a case analysis over a selected
pattern variable. Introduces an exhaustive
set of patterns for the type.
foldPattern : allows one to fold a sub expression against a
particular pattern variable
-}
{- Introduces pattern matching over a pattern variable.
Introduces an exhaustive set of patterns for a type
in a case analysis on the lhs of an equation.
Copyright : (c) Christopher Brown 2008
Maintainer : cmb21@kent.ac.uk
Stability : provisional
Portability : portable
-}
introPattern args
= do let fileName = ghead "filename" args
--fileName'= moduleName fileName
--modName = Module fileName'
row = read (args!!1)::Int
col = read (args!!2)::Int
modName <-fileNameToModName fileName
let modName1 = convertModName modName
(inscps, exps, mod, tokList)<-parseSourceFile fileName
-- (inscps3, exps3, mod3, tokList3)<-parsePrelude
let pnt = locToPNT fileName (row, col) mod
if not (checkInPat pnt mod)
then do
-- it's quite possible we are dealing with a sub-pattern
-- let's check that case.
if not (checkInSubPat pnt mod)
then error "Please select a pattern variable on the LHS of an equation!"
else do
AbstractIO.putStrLn "introSubPattern"
((_,m), (newToks, newMod))<-applyRefac (doIntroPatterns' fileName inscps pnt (modNameToStr modName))
(Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles False [((fileName,m), (newToks,newMod))]
AbstractIO.putStrLn "Completed.\n"
else do
AbstractIO.putStrLn "introPattern"
((_,m), (newToks, newMod))<-applyRefac (doIntroPatterns pnt)
(Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles False [((fileName,m), (newToks,newMod))]
AbstractIO.putStrLn "Completed.\n"
convertModName (PlainModule s) = s
convertModName m@(MainModule f) = modNameToStr m
doIntroPatterns pnt (_,_,t)
= do mod <- introPats pnt t
return mod
doIntroPatterns' fileName inscps pnt modName (_,_,t)
= do mod <- introPats' fileName inscps pnt modName t
return mod
introPats pnt t
= applyTP (full_tdTP (idTP `adhocTP` inDec)) t
where
inDec (dec@(Dec (HsFunBind s matches))::HsDeclP)
| findPNT pnt matches && inMatch pnt matches
= do
-- we need to find the type of the variable in question,
-- and also the implementation of the type. If the type
-- is defined outside of the project, we must error!
let match@(HsMatch loc name pats rhs ds) = getMatch pnt matches
typeSig = getTypeSig (pNTtoPN name) t
(typeOfPat, position) = findPatAndType 0 pnt (flatternType typeSig) pats
constrsOfData = findTypeAndConstrs 0 pnt (flatternType typeSig) pats
-- check that argument position is a variable in all defining
-- equations...
if checkVariableEquation matches position
then do
let newMatches = concatMap (createMatches dec (declToName dec) name pats (position+1) constrsOfData) matches
update dec (Dec (HsFunBind s (newMatches++matches))) dec
else do
return dec
inDec x = return x
typToPNT (Typ (HsTyCon x)) = x
typToPNT x = error "Please select a variable with a type constructor!"
checkVariableEquation [] _ = True
checkVariableEquation ((HsMatch _ _ pats _ _):ms) position
| checkPats (pats !! position) = checkVariableEquation ms position
| otherwise = error "Pattern argument must be a variable in all defining equations!"
checkPats (Pat (HsPIrrPat p)) = checkPats p
checkPats (Pat (HsPParen p)) = checkPats p
checkPats (Pat (HsPId (HsVar x))) = True
checkPats _ = False
createMatches (Dec (HsFunBind loc environment)) funName name pats position constrs match
= let (before, after) = break (==match) environment
newMatches = createMatches2 position (length pats) match constrs
in newMatches
where
createMatches2 _ _ _ [] = []
createMatches2 position arity m@(HsMatch _ _ pats rhs ds) ((ConInfo (PN n _) a _):cs)
= let newPats = replace position pats (createPat pnt n a (pats !! (position-1)) (map pNtoName (hsPNs pats ++ hsPNs ds)))
in (HsMatch loc0 name newPats rhs ds) : createMatches2 position arity m cs
where
myReplicate 0 _ _ = []
myReplicate arity names index
= let newName = mkNewName "a" names index
in (nameToPat newName) : (myReplicate (arity-1) (names ++ [newName]) (index+1))
-- ==========================================================================
-- end of introPattern
-- ==========================================================================
-- ==========================================================================
-- introduce sub pattern
-- ==========================================================================
introPats' fileName inscps pnt modName t
= applyTP (full_tdTP (idTP `adhocTP` inDec)) t
where
inDec (dec@(Dec (HsFunBind s matches))::HsDeclP)
| findPNT pnt matches && inMatch pnt matches
= do
-- we need to find the type of the variable in question,
-- and also the implementation of the type. If the type
-- is defined outside of the project, we must error!
let match@(HsMatch loc name pats rhs ds) = getMatch pnt matches
typeSig = getTypeSig (pNTtoPN name) t
(typeOfPat, position) = findPatAndType 0 pnt (flatternType typeSig) pats
-- we need to check to make sure there are no polymorphic. If they are we
-- can simply replace them with the () type. This seems to be the Haskell
-- equivalent of Null.
newTypeSig <- replacePolymorphicType typeSig
let closureEquation = createClosure ((render.ppi) newTypeSig) (pNTtoName pnt) (pats !! position) position
-- res <- liftIO $ ghcTypeCheckPattern closureEquation "closure___" ses
typeOfPat2 <- getSigAsString fileName closureEquation (force $ ghcTypeCheckPattern closureEquation "closure___" modName fileName)
-- this is necessary to force the evaluation of the GHC compiler,
-- since it's wrapped up in a naughty unsafePerformIO...
lift $ AbstractIO.putStrLn $ (typeOfPat2 \\ typeOfPat2)
let typeOfPat2' = last $ typeAnnot' typeOfPat2
let typeOfPat2Cleaned = cleanPatType typeOfPat2'
constrsOfData = extractConstructors typeOfPat2Cleaned (toList inscps)
let newMatches = createMatches dec (declToName dec) name pats position constrsOfData match
(beforeM, afterM) = break (==match) matches
update dec (Dec (HsFunBind s (beforeM ++ newMatches ++ afterM))) dec
inDec x = return x
replacePolymorphicType typeSig
= applyTP (full_tdTP (idTP `adhocTP` rename)) typeSig
where
rename (Typ (HsTyVar n)) = return (Typ (HsTyVar (nameToPNT "Int")))
rename x = return x
force a = if a==a then a else a
extractConstructors typeName [] = []
extractConstructors typeName ((_,Ent _ (HsCon (SN n _)) (Type (TypeInfo _ cs _))):xs)
| n == typeName && cs == [] = error $ "Cannot instantiate new patterns for the selected pattern. It may be of a polymorphic type, or a Haskell defined type such as Int."
| n == typeName = cs
| otherwise = extractConstructors typeName xs
extractConstructors typeName (x:xs) = extractConstructors typeName xs
cleanPatType [] = []
cleanPatType (' ':xs) = cleanPatType xs
cleanPatType ('[':xs) = "[]"
cleanPatType ('(':xs)
= "(" ++ ( filter (==',') xs) ++ ")"
cleanPatType xs = let (x, s') = break (== ' ') xs
in x
getSigAsString ses closureEquation res
= do
let types = lines2 res
let types1 = cleanTypes (tail types)
let (context, l) = getContext (head types)
let types2 = l : types1
let types3 = map (filter (/= '\n')) types2
let types4 = fold (tail types3)
return (context ++ " => " ++ (head types3) ++ " -> " ++ types4)
where
fold [] = []
fold [x] = x
fold (x:xs) = x ++ (" -> " ++ fold xs)
createClosure :: String -> String -> HsPatP -> Int -> String
createClosure typeSig p pat pos
= "(\\(" ++ ((render.ppi) pat) ++ "::" ++ ((typeAnnot typeSig)!!pos) ++ ") -> " ++ p ++")"
-- = "closure___ " ++ "(" ++ ((render.ppi) pat) ++ "::" ++ ((typeAnnot typeSig)!!pos) ++ ") = " ++ p
where
typeAnnot :: String -> [String]
typeAnnot "" = []
typeAnnot s = let (_, s') = break (== ':') s
in case s' of
{ [] -> [];
(_:s'') -> typeAnnot' (tail s'') }
typeAnnot' :: String -> [String]
typeAnnot' "" = []
typeAnnot' s = let (l, s') = break (== '-') s
in l : case s' of
{[] -> [];
(_:s'') -> typeAnnot' (tail s'')}
getModuleName [] modName = ""
getModuleName (t:ts) modName
| stripFilePath t == modName = t
| otherwise = getModuleName ts modName
where
stripFilePath t
= let (f,_) = break (=='/') (reverse t);
(f',_) = break ( =='.') (reverse f) in f'
createMatches (Dec (HsFunBind loc environment)) funName name pats position constrs match
= let (before, after) = break (==match) environment
newMatches = createMatches2 position (length pats) match constrs
in newMatches
where
createMatches2 _ _ _ [] = []
createMatches2 position arity m@(HsMatch _ _ pats rhs ds) ((ConInfo (SN n _) a _):cs)
= -- only update the pattern we are interested in...
let newPats = replace (position+1) pats (createSubPat pnt n a (pats !! position) (map pNtoName (hsPNs pats ++ hsPNs ds)))
in (HsMatch loc0 name newPats rhs ds) : createMatches2 position arity m cs
-- let newPats = replace position pats (createPat pnt n a (pats !! position) (map pNtoName (hsPNs pats ++ hsPNs ds)))
-- in (HsMatch loc0 name newPats rhs ds) : createMatches2 position arity m cs
where
myReplicate 0 _ _ = []
myReplicate arity names index
= let newName = mkNewName "a" names index
in (nameToPat newName) : (myReplicate (arity-1) (names ++ [newName]) (index+1))
createSubPat :: PNT -> String -> Int -> HsPatP -> [String] -> HsPatP
createSubPat pnt x i (Pat (HsPParen p)) environ = (Pat (HsPParen (createSubPat pnt x i p environ)))
createSubPat pnt x i (Pat (HsPApp n p)) environ
= let myTail [] = []
myTail [x] = []
myTail (x:xs) = xs
(before, a) = break (findPNT pnt) p
in case a of
[] -> createSubPat'' pnt x i environ
after -> (Pat (HsPApp n (before ++ [createSubPat pnt x i (ghead "createSubPat" after) environ] ++ (myTail after))))
createSubPat pnt x i (Pat (HsPTuple s p)) environ
= let myTail [] = []
myTail [x] = []
myTail (x:xs) = xs
(before, a) = break (findPNT pnt) p
in case a of
[] -> createSubPat'' pnt x i environ -- create the sub pattern and get out of here!
after -> (Pat (HsPTuple s (before ++ [createSubPat pnt x i (ghead "createSubPat" after) environ] ++ (myTail after))))
createSubPat pnt x i (Pat (HsPIrrPat p)) environ
= (Pat (HsPIrrPat (createSubPat pnt x i p environ)))
createSubPat pnt x i (Pat (HsPInfixApp p1 i2 p2)) environ
| findPNT pnt p1 = (Pat (HsPInfixApp (createSubPat pnt x i p1 environ) i2 p2))
| findPNT pnt p2 = (Pat (HsPInfixApp p1 i2 (createSubPat pnt x i p2 environ)))
createSubPat pnt x i (Pat (HsPAsPat n p)) environ
= (Pat (HsPAsPat n (createSubPat pnt x i p environ)))
createSubPat pnt x i _ environ = createSubPat' pnt x i environ
createSubPat' pnt i 0 environ = Pat (HsPAsPat pnt (Pat (HsPId (HsCon (nameToPNT i)))))
createSubPat' pnt x@(':':xs) ts environ
= Pat (HsPAsPat pnt (Pat (HsPInfixApp (ghead "createPat" pat1) (nameToPNT x)
(last pat1))))
where
pat1 = reverse $ createId environ ts
createSubPat' pnt x@('(':xs) ts environ
= Pat (HsPAsPat pnt (Pat ( HsPTuple loc0 (reverse (createId environ ts)))))
createSubPat' pnt i ts environ = Pat (HsPAsPat pnt (Pat (HsPApp (nameToPNT i) (reverse (createId environ ts)))))
createSubPat'' pnt i 0 environ = (Pat (HsPId (HsCon (nameToPNT i))))
createSubPat'' pnt x@(':':xs) ts environ
= (Pat (HsPInfixApp (ghead "createPat" pat1) (nameToPNT x)
(last pat1)))
where
pat1 = reverse $ createId environ ts
createSubPat'' pnt x@('(':xs) ts environ
= (Pat ( HsPTuple loc0 (reverse (createId environ ts))))
createSubPat'' pnt i ts environ = (Pat (HsPApp (nameToPNT i) (reverse (createId environ ts))))
findType index _ _ [] = error "No type associated with pattern variable!"
findType index pnt types (p:ps)
| findPNT pnt p = extractTypeName (types !! index)
| otherwise = findType (index+1) pnt types ps
extractTypeName (Typ (HsTyCon (PNT pn (Type (TypeInfo _ cs _)) _ ))) = pn
extractTypeName (Typ (HsTyVar (PNT pn _ _))) = pn
extractTypeName x = error "Please select a variable with a type constructor!"
extractTypeImplem [] typeName = error (typeName ++ " cannot be found in this project!")
extractTypeImplem (d:ds) typeName
| declToName d == typeName = d
| otherwise = extractTypeImplem ds typeName
constrsToModule (PNT (PN _ (G (PlainModule m) _ _)) _ _) = m
constrsToModule (PNT p@(PN _ (G (MainModule m) _ _)) _ _) = "Main"
constrsToModule x = error "Error in constrsToModule!"
findPatAndType index _ _ [] = error "No type associated with pattern variable!"
findPatAndType index pnt types (p:ps)
| findPNT' pnt [p] = (typToPNT (types !! index), index)
| otherwise = findPatAndType (index+1) pnt types ps
findConstrAndType pnt pat typeOfPat
= (positionOfPat, typ)
where
positionOfPat = flatternPat pnt pat
typ = extractType positionOfPat constr typeOfPat
constr = findConstr pnt pat
extractType pos constr d@(Dec (HsDataDecl _ _ _ cs _))
= extractCons cs
where
extractCons [] = error "This is not a valid parameter of the binding constructor!"
extractCons ((HsConDecl _ _ _ n types) : more)
| ghead "extractCons" (pNTtoName constr) == '(' &&
pNTtoName n == pNTtoName constr = removeBang (types !! pos)
| n == constr = removeBang (types !! pos)
| otherwise = extractCons more
where
removeBang (HsBangedType t) = t
removeBang (HsUnBangedType t) = t
findPosition index pnt [] = 0
findPosition index pnt (p:ps)
| findPNT pnt p = index
| otherwise = findPosition (index+1) pnt ps
flatternPat pnt (Pat (HsPAsPat i p)) = flatternPat pnt p
flatternPat pnt (Pat (HsPApp i p))
| findPNT pnt p = findPosition 0 pnt p
flatternPat pnt (Pat (HsPTuple _ p))
| findPNT pnt p = findPosition 0 pnt p
flatternPat pnt (Pat (HsPInfixApp p1 i p2)) = findPosition 0 pnt [p1] + findPosition 1 pnt [p2]
flatternPat pnt (Pat (HsPParen p)) = flatternPat pnt p
-- flatternPat pnt (Pat (HsPId i)) = 1
flatternPat pnt p = error "Selected pattern is not a sub-pattern in flatternPat"
findConstr pnt (Pat (HsPAsPat i p))
= findConstr pnt p
findConstr pnt (Pat (HsPApp i p))
| findPNT' pnt p = i
findConstr pnt (Pat (HsPTuple _ p))
| findPNT' pnt p = nameToPNT "(,)" -- this needs checking for arbitrary sized tuples
findConstr pnt (Pat (HsPInfixApp p1 i p2))
| findPNT pnt p1 || findPNT pnt p2 = i
findConstr pnt (p@(Pat (HsPParen p1)))
= findConstr pnt p1
findConstr pnt (p@(Pat (HsPId (HsCon i))))
| findPNT pnt p = i
findConstr pnt p = error "pattern is not bound to a constructor entity!"
findPNT' pnt [] = False
findPNT' pnt ((Pat (HsPAsPat i p)):ps)
| findPNT pnt i = True
| findPNT' pnt [p] = True
| otherwise = findPNT' pnt ps
findPNT' pnt ((Pat (HsPApp i ps)):pss)
| findPNT' pnt ps = True
| otherwise = findPNT' pnt ps
findPNT' pnt ((Pat (HsPTuple i ps)):pss)
| findPNT' pnt ps = True
| otherwise = findPNT' pnt ps
findPNT' pnt (Pat (HsPInfixApp p1 i p2):ps)
| findPNT pnt p1 || findPNT pnt p2 = True
| otherwise = findPNT' pnt ps
findPNT' pnt (p@(Pat (HsPParen p1)):ps)
| findPNT' pnt [p1] = True
| otherwise = findPNT' pnt ps
findPNT' pnt (p@(Pat (HsPId x)):ps)
| findPNT pnt p = True
| otherwise = findPNT' pnt ps
findPNT' pnt (p:ps) = findPNT' pnt ps
typToPNT (Typ (HsTyCon x)) = x
typToPNT x = error "Please select a variable with a type constructor!"
checkVariableEquation [] _ = True
checkVariableEquation ((HsMatch _ _ pats _ _):ms) position
| checkPats (pats !! position) = checkVariableEquation ms position
| otherwise = error "Pattern argument must be a variable in all defining equations!"
checkPats (Pat (HsPIrrPat p)) = checkPats p
checkPats (Pat (HsPParen p)) = checkPats p
checkPats (Pat (HsPId (HsVar x))) = True
checkPats _ = False
-- ==========================================================================
-- end of introSubPattern
-- ==========================================================================
introCase args
= do let fileName = ghead "filename" args
--fileName'= moduleName fileName
--modName = Module fileName'
row = read (args!!1)::Int
col = read (args!!2)::Int
modName <-fileNameToModName fileName
let modName1 = convertModName modName
(inscps, exps, mod, tokList)<-parseSourceFile fileName
let pnt = locToPNT fileName (row, col) mod
if not (checkInPat pnt mod)
then do
if not (checkInSubPat pnt mod)
then error "Please select a pattern variable on the LHS of an equation!"
else do
AbstractIO.putStrLn "introCaseSubPattern"
((_,m), (newToks, newMod))<-applyRefac (doIntroCasePatterns' fileName inscps pnt (modNameToStr modName))
(Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles False [((fileName,m), (newToks,newMod))]
AbstractIO.putStrLn "Completed.\n"
else do
AbstractIO.putStrLn "introCasePattern"
((_,m), (newToks, newMod))<-applyRefac (doIntroCasePatterns pnt)
(Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles False [((fileName,m), (newToks,newMod))]
AbstractIO.putStrLn "Completed.\n"
doIntroCasePatterns pnt (_,_,t)
= do mod <- introPatsCase pnt t
return mod
doIntroCasePatterns' fileName inscps pnt modName (_,_,t)
= do mod <- introPatsCase' fileName inscps pnt modName t
return mod
introPatsCase' fileName inscps pnt modName t
= applyTP (full_tdTP (idTP `adhocTP` inDec)) t
where
inDec (dec@(Dec (HsFunBind s matches))::HsDeclP)
| findPNT pnt matches && inMatch pnt matches
= do
-- we need to find the type of the variable in question,
-- and also the implementation of the type. If the type
-- is defined outside of the project, we must error!
let match@(HsMatch loc name pats rhs ds) = getMatch pnt matches
typeSig = getTypeSig (pNTtoPN name) t
(typeOfPat, position) = findPatAndType 0 pnt (flatternType typeSig) pats
-- we need to check to make sure there are no polymorphic. If they are we
-- can simply replace them with the () type. This seems to be the Haskell
-- equivalent of Null.
newTypeSig <- replacePolymorphicType typeSig
let closureEquation = createClosure ((render.ppi) newTypeSig) (pNTtoName pnt) (pats !! position) position
-- error $ "RefacIntroPattern.introPatsCase': ghcTypeCheckPattern params" ++ (show (closureEquation,"closure___",modName,fileName))-- ++AZ++
-- res <- liftIO $ ghcTypeCheckPattern closureEquation "closure___" ses
typeOfPat2 <- getSigAsString fileName closureEquation (force $ ghcTypeCheckPattern closureEquation "closure___" modName fileName)
-- this is necessary to force the evaluation of the GHC compiler,
-- since it's wrapped up in a naughty unsafePerformIO...
lift $ AbstractIO.putStrLn $ (typeOfPat2 \\ typeOfPat2)
let typeOfPat2' = last $ typeAnnot' typeOfPat2
let typeOfPat2Cleaned = cleanPatType typeOfPat2'
constrsOfData = extractConstructors typeOfPat2Cleaned (toList inscps)
let newMatches = createMatches dec (declToName dec) pnt name pats position constrsOfData match
(beforeM, afterM) = break (==match) matches
update dec (Dec (HsFunBind s (beforeM ++ newMatches ++ afterM))) dec
inDec x = return x
createMatches (Dec (HsFunBind loc environment)) funName pnt name pats position constrs match
= let (before, after) = break (==match) environment
newMatches = createMatches2 position (length pats) match constrs
in newMatches
where
createMatches2 _ _ _ [] = []
createMatches2 position arity m@(HsMatch _ _ pats rhs ds) constrs@(c:cs)
= [HsMatch loc0 name pats newCase ds]
where
newPats [] = []
newPats ((ConInfo (SN n _) a _):cs) = createPat pnt n a (pats !! position)
(map pNtoName (hsPNs pats ++ hsPNs ds))
: newPats cs
newCase = HsBody (Exp (HsCase (nameToExp (pNTtoName pnt)) (newAlts (newPats constrs))))
newAlts [] = []
newAlts (p:ps) = (HsAlt loc0 p rhs []) : newAlts ps
myReplicate 0 _ _ = []
myReplicate arity names index
= let newName = mkNewName "a" names index
in (nameToPat newName) : (myReplicate (arity-1) (names ++ [newName]) (index+1))
replacePolymorphicType typeSig
= applyTP (full_tdTP (idTP `adhocTP` rename)) typeSig
where
rename (Typ (HsTyVar n)) = return (Typ (HsTyVar (nameToPNT "Int")))
rename x = return x
force a = if a==a then a else a
extractConstructors typeName [] = []
extractConstructors typeName ((_,Ent _ (HsCon (SN n _)) (Type (TypeInfo _ cs _))):xs)
| n == typeName && cs == [] = error $ "Cannot instantiate new patterns for the selected pattern. It may be of a polymorphic type, or a Haskell defined type such as Int."
| n == typeName = cs
| otherwise = extractConstructors typeName xs
extractConstructors typeName (x:xs) = extractConstructors typeName xs
cleanPatType [] = []
cleanPatType (' ':xs) = cleanPatType xs
cleanPatType ('[':xs) = "[]"
cleanPatType ('(':xs)
= "(" ++ ( filter (==',') xs) ++ ")"
cleanPatType xs = let (x, s') = break (== ' ') xs
in x
getSigAsString ses closureEquation res
= do
let types = lines2 res
let types1 = cleanTypes (tail types)
let (context, l) = getContext (head types)
let types2 = l : types1
let types3 = map (filter (/= '\n')) types2
let types4 = fold (tail types3)
return (context ++ " => " ++ (head types3) ++ " -> " ++ types4)
where
fold [] = []
fold [x] = x
fold (x:xs) = x ++ (" -> " ++ fold xs)
createClosure :: String -> String -> HsPatP -> Int -> String
createClosure typeSig p pat pos
= "(\\(" ++ ((render.ppi) pat) ++ "::" ++ ((typeAnnot typeSig)!!pos) ++ ") -> " ++ p ++")"
-- = "closure___ " ++ "(" ++ ((render.ppi) pat) ++ "::" ++ ((typeAnnot typeSig)!!pos) ++ ") = " ++ p
where
typeAnnot :: String -> [String]
typeAnnot "" = []
typeAnnot s = let (_, s') = break (== ':') s
in case s' of
{ [] -> [];
(_:s'') -> typeAnnot' (tail s'') }
typeAnnot' :: String -> [String]
typeAnnot' "" = []
typeAnnot' s = let (l, s') = break (== '-') s
in l : case s' of
{[] -> [];
(_:s'') -> typeAnnot' (tail s'')}
introPatsCase pnt t
= applyTP (full_tdTP (idTP `adhocTP` inDec)) t
where
inDec (dec@(Dec (HsFunBind s matches))::HsDeclP)
| findPNT pnt matches && inMatch pnt matches
= do
-- we need to find the type of the variable in question,
-- and also the implementation of the type. If the type
-- is defined outside of the project, we must error!
let match@(HsMatch loc name pats rhs ds) = getMatch pnt matches
typeSig = getTypeSig (pNTtoPN name) t
(typeOfPat, position) = findPatAndType 0 pnt (flatternType typeSig) pats
constrsOfData = findTypeAndConstrs 0 pnt (flatternType typeSig) pats
-- check that argument position is a variable in all defining
-- equations...
if checkVariableEquation matches position
then do
let newMatches = concatMap (createMatches dec (declToName dec) name pats (position+1) constrsOfData) matches
update dec (Dec (HsFunBind s (newMatches++matches))) dec
else do
return dec
inDec x = return x
typToPNT (Typ (HsTyCon x)) = x
typToPNT x = error "Please select a variable with a type constructor1!"
checkVariableEquation [] _ = True
checkVariableEquation ((HsMatch _ _ pats _ _):ms) position
| checkPats (pats !! position) = checkVariableEquation ms position
| otherwise = error "Pattern argument must be a variable in all defining equations!"
checkPats (Pat (HsPIrrPat p)) = checkPats p
checkPats (Pat (HsPParen p)) = checkPats p
checkPats (Pat (HsPId (HsVar x))) = True
checkPats _ = False
createMatches (Dec (HsFunBind loc environment)) funName name pats position constrs match
= let (before, after) = break (==match) environment
newMatches = createMatches2 position (length pats) match constrs
in newMatches
where
createMatches2 _ _ _ [] = []
createMatches2 position arity m@(HsMatch _ _ pats rhs ds) constrs@(c:cs)
= [HsMatch loc0 name pats newCase ds]
where
newPats [] = []
newPats ((ConInfo (PN n _) a _):cs) = createPat pnt n a (pats !! (position-1))
(map pNtoName (hsPNs pats ++ hsPNs ds))
: newPats cs
newCase = HsBody (Exp (HsCase (nameToExp (pNtoName (patToPN (pats !! (position-1))))) (newAlts (newPats constrs) )))
newAlts [] = []
newAlts (p:ps) = (HsAlt loc0 p rhs []) : newAlts ps
myReplicate 0 _ _ = []
myReplicate arity names index
= let newName = mkNewName "a" names index
in (nameToPat newName) : (myReplicate (arity-1) (names ++ [newName]) (index+1))
-- ==========================================================================
-- end of introCase
-- ==========================================================================
foldPattern args
= do let fileName = ghead "filename" args
--fileName'= moduleName fileName
--modName = Module fileName'
patName = (args!!1)
beginRow = read (args!!2)::Int
beginCol = read (args!!3)::Int
endRow = read (args!!4)::Int
endCol = read (args!!5)::Int
modName <-fileNameToModName fileName
(inscps, exps, mod, tokList)<-parseSourceFile fileName
let (ty, pnt, pats, subExp, wh)
= findDefNameAndExp tokList
(beginRow, beginCol)
(endRow, endCol)
mod
let exp = locToExp (beginRow, beginCol)
(endRow, endCol)
tokList
mod
((_,m), (newToks, newMod))<-applyRefac (doFoldPattern patName pnt exp)
(Just (inscps, exps, mod, tokList)) fileName
writeRefactoredFiles False [((fileName,m), (newToks,newMod))]
AbstractIO.putStrLn "Completed.\n"
doFoldPattern patName pnt exp (_,_,t)
= do
mod <- foldPatterns patName pnt exp t
return mod
foldPatterns patName pnt exp t
= applyTP (stop_tdTP (failTP `adhocTP` inMod
`adhocTP` inMatch)) t
where
inMod (mod@(HsModule loc name exps imps ds):: HsModuleP)
| pnt `elem` (map declToPNT ds)
= do
ds' <- doFoldModule ds
return (HsModule loc name exps imps ds')
where
doFoldModule t
= applyTP (stop_tdTP (failTP `adhocTP` inMatch2)) t
where
inMatch2 (match@(HsMatch loc name pats rhs ds)::HsMatchP)
| useLoc pnt == useLoc name
= do
-- let's check that the pattern name
-- occurs as a variable pattern in pats
if checkPattern patName pats == False
then error "The pattern entered does not occur with the pattern list or is not a pattern variable!"
else do
-- let's replace the highlighted expression with the pattern name
newExp <- replaceExp rhs patName exp
return (HsMatch loc name pats newExp ds)
inMatch2 x = mzero
inMod x = mzero
inMatch (match@(HsMatch loc name pats rhs ds)::HsMatchP)
| useLoc pnt == useLoc name
=do
-- let's check that the pattern name
-- occurs as a variable pattern in pats
if checkPattern patName pats == False
then error "The pattern entered does not occur with the pattern list or is not a pattern variable!"
else do
-- let's replace the highlighted expression with the pattern name
newExp <- replaceExp rhs patName exp
return (HsMatch loc name pats newExp ds)
inMatch x = mzero
replaceExp t patName e
= applyTP (stop_tdTP (failTP `adhocTP` subExp)) t
where
subExp exp@((Exp _)::HsExpP)
| sameOccurrence exp e == True
= update exp (nameToExp patName) exp
| otherwise = mzero
checkPattern :: String -> [HsPatP] -> Bool
checkPattern patName
= (fromMaybe False).applyTU (once_tdTU (failTU `adhocTU` inVar))
where
inVar (Pat (HsPId (HsVar n)))
| pNTtoName n == patName = Just True
inVar (Pat (HsPAsPat n p))
| pNTtoName n == patName = Just True
inVar x = Nothing
-- ==========================================================================
-- end of foldPattern
-- ==========================================================================
-- utility functions
{-|
Takes the position of the highlighted code and returns
the function name, the list of arguments, the expression that has been
highlighted by the user, and any where\/let clauses associated with the
function.
-}
findDefNameAndExp :: Term t => [PosToken] -- ^ The token stream for the
-- file to be
-- refactored.
-> (Int, Int) -- ^ The beginning position of the highlighting.
-> (Int, Int) -- ^ The end position of the highlighting.
-> t -- ^ The abstract syntax tree.
-> (PatFun, PNT, FunctionPats, HsExpP, WhereDecls) -- ^ A tuple of,
-- (the function name, the list of arguments,
-- the expression highlighted, any where\/let clauses
-- associated with the function).
findDefNameAndExp toks beginPos endPos t
= fromMaybe (Er, defaultPNT, [], defaultExp, [])
(applyTU (once_buTU (failTU `adhocTU` inMatch `adhocTU` inPat)) t)
where
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 pnt pats rhs@(HsBody e) ds)::HsMatchP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Mat, pnt, pats, locToExp beginPos endPos toks rhs, ds)
inMatch (match@(HsMatch loc1 pnt pats rhs@(HsGuard e) ds)::HsMatchP)
| locToExp beginPos endPos toks rhs /= defaultExp
= Just (Mat, pnt, pats, rmGuard rhs, ds)
inMatch _ = Nothing
--The selected sub-expression is in the rhs of a pattern-binding
inPat (pat@(Dec (HsPatBind loc1 ps rhs ds))::HsDeclP)
| locToExp beginPos endPos toks rhs /= defaultExp
= error "Cannot fold against a variable within a pattern binding!"
inPat _ = Nothing
rmGuard ((HsGuard gs)::RhsP)
= let (_,e1,e2)=glast "guardToIfThenElse" gs
in if ((pNtoName.expToPN) e1)=="otherwise"
then (foldl mkIfThenElse e2 (tail(reverse gs)))
else (foldl mkIfThenElse defaultElse (reverse gs))
mkIfThenElse e (_,e1, e2)=(Exp (HsIf e1 e2 e))
defaultElse=(Exp (HsApp (Exp (HsId (HsVar (PNT (PN (UnQual "error") (G (PlainModule "Prelude") "error"
(N (Just loc0)))) Value (N (Just loc0)))))) (Exp (HsLit loc0 (HsString "UnMatched Pattern")))))
checkInPat :: Term t => PNT -> t -> Bool
checkInPat pnt t
= checkInMatch pnt t
where
checkInMatch pnt t
= fromMaybe (False)
(applyTU (once_tdTU (failTU `adhocTU` inMatch)) t)
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 _ pats rhs ds)::HsMatchP)
| findPNT' pnt pats
= Just True
where findPNT' pnt [] = False
findPNT' pnt (p@(Pat (HsPIrrPat p1)):ps)
| findPNT pnt p1 = True
| otherwise = findPNT' pnt ps
findPNT' pnt (p@(Pat (HsPParen p1)):ps)
| findPNT' pnt [p1] = True
| otherwise = findPNT' pnt ps
findPNT' pnt (p@(Pat (HsPId x)):ps)
| findPNT pnt p = True
| otherwise = findPNT' pnt ps
findPNT' pnt (p:ps) = findPNT' pnt ps
inMatch _ = Nothing
checkInSubPat :: Term t => PNT -> t -> Bool
checkInSubPat pnt t
= checkInPat pnt t
where
checkInPat pnt t
= fromMaybe (False)
(applyTU (once_tdTU (failTU `adhocTU` inMatch)) t)
--The selected sub-expression is in the rhs of a match
inMatch (match@(HsMatch loc1 _ pats rhs ds)::HsMatchP)
| findPNT' pnt pats
= Just True
where findPNT' pnt [] = False
findPNT' pnt ((Pat (HsPAsPat i p)):ps)
| findPNT pnt i = True
| findPNT' pnt [p] = True
| otherwise = findPNT' pnt ps
findPNT' pnt ((Pat (HsPApp i ps)):pss)
| findPNT' pnt ps = True
| otherwise = findPNT' pnt ps
findPNT' pnt ((Pat (HsPTuple _ ps)):pss)
| findPNT' pnt ps = True
| otherwise = findPNT' pnt ps
findPNT' pnt (Pat (HsPInfixApp p1 i p2):ps)
| findPNT pnt p1 || findPNT pnt p2 = True
| otherwise = findPNT' pnt ps
findPNT' pnt (p@(Pat (HsPParen p1)):ps)
| findPNT' pnt [p1] = True
| otherwise = findPNT' pnt ps
findPNT' pnt (p@(Pat (HsPId x)):ps)
| findPNT pnt p = True
| otherwise = findPNT' pnt ps
findPNT' pnt (p:ps) = findPNT' pnt ps
inMatch _ = Nothing
createPat :: PNT -> String -> Int -> HsPatP -> [String] -> HsPatP
createPat pnt x i (Pat (HsPIrrPat p)) environ
= (Pat (HsPIrrPat (createPat' pnt x i environ)))
createPat pnt x i _ environ = createPat' pnt x i environ
createPat' pnt i 0 environ = Pat (HsPAsPat pnt (Pat (HsPId (HsCon (nameToPNT i)))))
createPat' pnt x@(':':xs) ts environ
= Pat (HsPAsPat pnt (Pat (HsPInfixApp (ghead "createPat" pat1) (nameToPNT x)
(last pat1))))
where
pat1 = reverse $ createId environ ts
createPat' pnt x@('(':xs) ts environ
= Pat (HsPAsPat pnt (Pat ( HsPTuple loc0 (reverse (createId environ ts)))))
createPat' pnt i ts environ = Pat (HsPAsPat pnt (Pat (HsPApp (nameToPNT i) (reverse (createId environ ts)))))
createId _ 0 = []
createId names a
= let newName = mkNewName "b" names a
in (nameToPat newName) : (createId (names ++ [newName]) (a-1))
replace :: Int -> [a] -> a -> [a]
replace pos [] e = []
replace pos list e
= (init (take pos list)) ++ [e] ++ (drop pos list)
inMatch _ [] = False
inMatch pnt (match@(HsMatch loc name pats rhs ds):ms)
| findPNT pnt pats = True
| otherwise = inMatch pnt ms
getMatch _ [] = error "Please select a pattern variable on the LHS of an equation!"
getMatch pnt (match@(HsMatch loc name pats rhs ds):ms)
| findPNT pnt pats = match
| otherwise = getMatch pnt ms
getTypeSig name t
= fromMaybe (error "Please define a type signature for the definition!")
(applyTU (once_tdTU (failTU `adhocTU` inDec)) t)
where
inDec (d@(Dec (HsTypeSig _ _ _ _))::HsDeclP)
| definesTypeSig name d = Just d
inDec _ = Nothing
findTypeAndConstrs index _ _ [] = error "No type associated with pattern variable!"
findTypeAndConstrs index pnt types (p:ps)
| findPNT pnt p = extractConstrs (types !! index)
| otherwise = findTypeAndConstrs (index+1) pnt types ps
findPatAndType index _ _ [] = error "No type associated with pattern variable!"
findPatAndType index pnt types (p:ps)
| findPNT pnt p = (typToPNT (types !! index), index)
| otherwise = findPatAndType (index+1) pnt types ps
-- flatternType :: HsDeclP -> [HsTypeP]
flatternType (Dec (HsTypeSig _ _ _ t))
= flatternT t
flatternT (Typ (HsTyApp t1 t2)) = flatternT t1
flatternT (Typ (HsTyFun t1 t2)) = flatternT t1 ++ flatternT t2
flatternT (Typ (HsTyForall _ _ t)) = flatternT t
flatternT t = [t]
flatternAllType (Dec (HsTypeSig _ _ _ t))
= flatternAllT t
flatternAllT (Typ (HsTyApp t1 t2))
= flatternAllT t1 ++ flatternAllT t2
-- | pNTtoName (typToPNT t1) == "[]" = flatternAllT t1
-- | otherwise = flatternAllT t1 ++ flatternAllT t2
flatternAllT (Typ (HsTyFun t1 t2)) = flatternAllT t1 ++ flatternAllT t2
flatternAllT (Typ (HsTyForall _ _ t)) = flatternAllT t
flatternAllT t = [t]
extractConstrs t@(Typ (HsTyCon (PNT pn (Type (TypeInfo _ [] _)) _ )))
= error "There are no constructors defined for the type of this pattern!"
extractConstrs (Typ (HsTyCon (PNT pn (Type (TypeInfo _ cs _)) _ ))) = cs
extractConstrs x = error "Please select a variable with a type constructor!"
extractConstrs' t@(Typ (HsTyCon (PNT pn (Type (TypeInfo _ [] _)) _ ))) _ _ _ _
= error "There are no constructors defined for the type of this pattern!"
extractConstrs' (Typ (HsTyCon (PNT pn (Type (TypeInfo _ cs _)) _ ))) _ _ _ _ = cs
extractConstrs' (Typ (HsTyVar (PNT pn (Type (TypeInfo _ cs _)) _ ))) types ty pos constrName
= -- if it's a variable, then it must be exposed on the
-- LHS of the type
-- what about existential types?
let posOfVar = findPosOfVar constrName ty
instanceOfVarType = findPosOfInstance posOfVar (declToPNT ty) types
in extractConstrs instanceOfVarType
findPosOfInstance _ _ [] = error "pattern is a variable which is not instantiated within the type signature!"
findPosOfInstance offset pn (t@(Typ (HsTyCon pnt)):ts)
| rmLocs pn == rmLocs pnt = ts !! (offset-1)
| otherwise = findPosOfInstance offset pn ts
findPosOfVar (Typ (HsTyVar pnt)) (Dec (HsDataDecl _ _ t _ _))
= extractPos 0 (flatternAllT t)
where
extractPos i [] = i
extractPos i ((Typ (HsTyCon pnt2)):ts)
= extractPos (i+1) ts
extractPos i ((Typ (HsTyVar pnt2)):ts)
| rmLocs pnt2 == rmLocs pnt = i
| otherwise = extractPos (i+1) ts
| kmate/HaRe | old/refactorer/RefacIntroPattern.hs | bsd-3-clause | 46,058 | 0 | 26 | 16,651 | 13,613 | 6,846 | 6,767 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Command.VCS.Common
-- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL Nothing
--
-- Maintainer : maintainer@leksah.org
-- Stability : provisional
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module IDE.Command.VCS.Common (
setMenuForPackage
--getter
,getVCSConf'
) where
import IDE.Core.Types
import IDE.Core.State
import IDE.Utils.GUIUtils
import qualified IDE.Utils.GUIUtils as GUIUtils
import qualified IDE.Workspaces.Writer as Writer
import qualified IDE.Command.VCS.Types as Types
import qualified IDE.Command.VCS.GIT as GIT
import qualified IDE.Command.VCS.SVN as SVN
import qualified IDE.Command.VCS.Mercurial as Mercurial
import qualified VCSWrapper.Common as VCS
import qualified VCSGui.Common as VCSGUI
import qualified Graphics.UI.Gtk as Gtk
import Control.Monad.Reader
import Control.Monad.Trans(liftIO)
import qualified Control.Exception as Exc
import Data.Maybe
import qualified Data.Map as Map
import Data.Text (Text)
import qualified Data.Text as T (pack)
setMenuForPackage :: Gtk.Menu -> FilePath -> Maybe VCSConf -> IDEAction
setMenuForPackage vcsMenu cabalFp mbVCSConf = do
ideR <- ask
-- create or get packageItem and set it to ide to be able to get it later again
(oldMenuItems,pw) <- readIDE vcsData
packageItem <-
case Map.lookup cabalFp oldMenuItems of
Nothing -> liftIO . Gtk.menuItemNewWithLabel $ T.pack cabalFp
Just menuItem -> return menuItem
let newMenuItems = Map.insert cabalFp packageItem oldMenuItems
modifyIDE_ (\ide -> ide {vcsData = (newMenuItems,pw)})
packageMenu <- liftIO Gtk.menuNew
-- build and set set-up repo action
setupActionItem <- liftIO $ Gtk.menuItemNewWithMnemonic (__"_Setup Repo")
liftIO $ setupActionItem `Gtk.on` Gtk.menuItemActivate $
reflectIDE (
runSetupRepoActionWithContext cabalFp
) ideR
liftIO $ Gtk.menuShellAppend packageMenu setupActionItem
-- build and set other actions
let packageMenuOperations = case mbVCSConf of
Nothing -> []
Just (vcsType,_,_) -> mkVCSActions vcsType
liftIO $ addActions cabalFp packageMenu ideR packageMenuOperations
-- set menus
liftIO $ Gtk.menuItemRemoveSubmenu packageItem
liftIO $ Gtk.menuItemSetSubmenu packageItem packageMenu
liftIO $ Gtk.menuShellAppend vcsMenu packageItem
liftIO $ Gtk.widgetShowAll vcsMenu
return ()
where
addActions cabalFp packageMenu ideR
= mapM_
(\ (name, action) ->
do actionItem <- Gtk.menuItemNewWithMnemonic name
actionItem `Gtk.on` Gtk.menuItemActivate $
reflectIDE (runActionWithContext action cabalFp) ideR
Gtk.menuShellAppend packageMenu actionItem)
mkVCSActions :: VCS.VCSType -> [(Text, Types.VCSAction ())]
mkVCSActions VCS.SVN = SVN.mkSVNActions
mkVCSActions VCS.GIT = GIT.mkGITActions
mkVCSActions VCS.Mercurial = Mercurial.mkMercurialActions
{- |
Retrieves VCS configuration for given package from current workspace and runs given
VCS action using it. VCS Configuration must be set before.
-}
runActionWithContext :: Types.VCSAction () -- ^ computation to execute, i.e. showCommit
-> FilePath -- ^ filepath to package
-> IDEAction
runActionWithContext vcsAction packageFp = do
config <- getVCSConf'' packageFp
runVcs config packageFp vcsAction
where
runVcs :: VCSConf -> FilePath -> Types.VCSAction t -> IDEM t
runVcs config cabalFp (Types.VCSAction a) = runReaderT a (config,cabalFp)
{- |
Shows a GUI to set up a VCS. If a vcs-config is set for given package it will be used.
-}
runSetupRepoActionWithContext :: FilePath
-> IDEAction
runSetupRepoActionWithContext packageFp = do
eConfigErr <- getVCSConf packageFp
case eConfigErr of
Left error -> liftIO $ GUIUtils.showErrorDialog error
Right mbConfig -> do
ide <- ask
liftIO $ VCSGUI.showSetupConfigGUI mbConfig (callback ide packageFp)
where
callback :: IDERef -> FilePath -> Maybe (VCS.VCSType, VCS.Config, Maybe VCSGUI.MergeTool) -> IO()
callback ideRef packageFp mbConfig =
-- set config in workspace
runReaderT (workspaceSetVCSConfig packageFp mbConfig) ideRef
--
-- Basic setters and getters
--
workspaceSetVCSConfig :: FilePath -> Maybe VCSConf -> IDEAction
workspaceSetVCSConfig pathToPackage mbVCSConf = do
vcsItem <- GUIUtils.getVCS
mbVcsMenu <- liftIO $ Gtk.menuItemGetSubmenu vcsItem
let vcsMenu = Gtk.castToMenu $ fromJust mbVcsMenu
setMenuForPackage vcsMenu pathToPackage mbVCSConf
modifyIDE_ (\ide -> do
let oldWs = fromJust (workspace ide)
let oldMap = packageVcsConf oldWs
let newMap = case mbVCSConf of
Nothing -> Map.delete pathToPackage oldMap
Just vcsConf -> Map.insert pathToPackage vcsConf oldMap
let newWs = (fromJust (workspace ide)) { packageVcsConf = newMap }
ide {workspace = Just newWs })
newWs <- readIDE workspace
Writer.writeWorkspace $ fromJust newWs
-- | vcs conf for given package in current workspace.
getVCSConf :: FilePath -> IDEM (Either Text (Maybe VCSConf))
getVCSConf pathToPackage = do
mbWorkspace <- readIDE workspace
case mbWorkspace of
Nothing -> return $ Left "No open workspace. Open Workspace first."
Just workspace -> getVCSConf' workspace pathToPackage
-- | vcs conf for given package in given workspace.
getVCSConf' :: Workspace -> FilePath -> IDEM (Either Text (Maybe VCSConf))
getVCSConf' workspace pathToPackage = do
let mbConfig = Map.lookup pathToPackage $ packageVcsConf workspace
case mbConfig of
--Left $ "Could not find version-control-system configuration for package "++pathToPackage
Nothing -> return $ Right Nothing
Just conf -> return $ Right $ Just conf
-- | vcs conf for given package in current workspace. Workspae and VCS conf must be set before.
getVCSConf'' :: FilePath -> IDEM VCSConf
getVCSConf'' pathToPackage = do
(Just workspace) <- readIDE workspace
return $ fromJust $ Map.lookup pathToPackage $ packageVcsConf workspace
| 573/leksah | src/IDE/Command/VCS/Common.hs | gpl-2.0 | 7,260 | 0 | 19 | 2,193 | 1,445 | 744 | 701 | 112 | 5 |
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Array.ST.Safe
-- Copyright : (c) The University of Glasgow 2011
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (uses Data.Array.MArray)
--
-- Mutable boxed and unboxed arrays in the 'Control.Monad.ST.ST' monad.
--
-- Safe API only of "Data.Array.ST".
--
-- /Since: 0.4.0.0/
-----------------------------------------------------------------------------
module Data.Array.ST.Safe (
-- * Boxed arrays
STArray, -- instance of: Eq, MArray
runSTArray,
-- * Unboxed arrays
STUArray, -- instance of: Eq, MArray
runSTUArray,
-- * Overloaded mutable array interface
module Data.Array.MArray.Safe,
) where
import Data.Array.ST
import Data.Array.MArray.Safe
| jtojnar/haste-compiler | libraries/ghc-7.10/array/Data/Array/ST/Safe.hs | bsd-3-clause | 961 | 0 | 5 | 178 | 66 | 53 | 13 | 9 | 0 |
module Foo () where
import Language.Haskell.Liquid.Prelude (choose)
prop = if x < 0 then bar x else x
where x = choose 0
{-@ bar :: Nat -> Nat @-}
bar :: Int -> Int
bar x = x
{-@ bar :: a -> {v:Int | v = 9} @-}
bar :: a -> Int
bar _ = 8
| mightymoose/liquidhaskell | tests/neg/LocalSpec.hs | bsd-3-clause | 263 | 0 | 7 | 85 | 85 | 49 | 36 | 8 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Hooks.SetWMName
-- Copyright : Β© 2007 Ivan Tarasov <Ivan.Tarasov@gmail.com>
-- License : BSD
--
-- Maintainer : Ivan.Tarasov@gmail.com
-- Stability : experimental
-- Portability : unportable
--
-- Sets the WM name to a given string, so that it could be detected using
-- _NET_SUPPORTING_WM_CHECK protocol.
--
-- May be useful for making Java GUI programs work, just set WM name to "LG3D"
-- and use Java 1.6u1 (1.6.0_01-ea-b03 works for me) or later.
--
-- To your @~\/.xmonad\/xmonad.hs@ file, add the following line:
--
-- > import XMonad.Hooks.SetWMName
--
-- Then edit your @startupHook@:
--
-- > startupHook = setWMName "LG3D"
--
-- For details on the problems with running Java GUI programs in non-reparenting
-- WMs, see <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6429775> and
-- related bugs.
--
-- Setting WM name to "compiz" does not solve the problem, because of yet
-- another bug in AWT code (related to insets). For LG3D insets are explicitly
-- set to 0, while for other WMs the insets are \"guessed\" and the algorithm
-- fails miserably by guessing absolutely bogus values.
--
-- For detailed instructions on editing your hooks, see
-- "XMonad.Doc.Extending#4".
-----------------------------------------------------------------------------
module XMonad.Hooks.SetWMName (
setWMName) where
import Control.Monad (join)
import Data.Char (ord)
import Data.List (nub)
import Data.Maybe (fromJust, listToMaybe, maybeToList)
import Foreign.C.Types (CChar)
import Foreign.Marshal.Alloc (alloca)
import XMonad
-- | sets WM name
setWMName :: String -> X ()
setWMName name = do
atom_NET_SUPPORTING_WM_CHECK <- netSupportingWMCheckAtom
atom_NET_WM_NAME <- getAtom "_NET_WM_NAME"
atom_NET_SUPPORTED_ATOM <- getAtom "_NET_SUPPORTED"
atom_UTF8_STRING <- getAtom "UTF8_STRING"
root <- asks theRoot
supportWindow <- getSupportWindow
dpy <- asks display
io $ do
-- _NET_SUPPORTING_WM_CHECK atom of root and support windows refers to the support window
mapM_ (\w -> changeProperty32 dpy w atom_NET_SUPPORTING_WM_CHECK wINDOW 0 [fromIntegral supportWindow]) [root, supportWindow]
-- set WM_NAME in supportWindow (now only accepts latin1 names to eliminate dependency on utf8 encoder)
changeProperty8 dpy supportWindow atom_NET_WM_NAME atom_UTF8_STRING 0 (latin1StringToCCharList name)
-- declare which _NET protocols are supported (append to the list if it exists)
supportedList <- fmap (join . maybeToList) $ getWindowProperty32 dpy atom_NET_SUPPORTED_ATOM root
changeProperty32 dpy root atom_NET_SUPPORTED_ATOM aTOM 0 (nub $ fromIntegral atom_NET_SUPPORTING_WM_CHECK : fromIntegral atom_NET_WM_NAME : supportedList)
where
netSupportingWMCheckAtom :: X Atom
netSupportingWMCheckAtom = getAtom "_NET_SUPPORTING_WM_CHECK"
latin1StringToCCharList :: String -> [CChar]
latin1StringToCCharList str = map (fromIntegral . ord) str
getSupportWindow :: X Window
getSupportWindow = withDisplay $ \dpy -> do
atom_NET_SUPPORTING_WM_CHECK <- netSupportingWMCheckAtom
root <- asks theRoot
supportWindow <- fmap (join . fmap listToMaybe) $ io $ getWindowProperty32 dpy atom_NET_SUPPORTING_WM_CHECK root
validateWindow (fmap fromIntegral supportWindow)
validateWindow :: Maybe Window -> X Window
validateWindow w = do
valid <- maybe (return False) isValidWindow w
if valid then
return $ fromJust w
else
createSupportWindow
-- is there a better way to check the validity of the window?
isValidWindow :: Window -> X Bool
isValidWindow w = withDisplay $ \dpy -> io $ alloca $ \p -> do
status <- xGetWindowAttributes dpy w p
return (status /= 0)
-- this code was translated from C (see OpenBox WM, screen.c)
createSupportWindow :: X Window
createSupportWindow = withDisplay $ \dpy -> do
root <- asks theRoot
let visual = defaultVisual dpy (defaultScreen dpy) -- should be CopyFromParent (=0), but the constructor is hidden in X11.XLib
window <- io $ allocaSetWindowAttributes $ \winAttrs -> do
set_override_redirect winAttrs True -- WM cannot decorate/move/close this window
set_event_mask winAttrs propertyChangeMask -- not sure if this is needed
let bogusX = -100
bogusY = -100
in
createWindow dpy root bogusX bogusY 1 1 0 0 inputOutput visual (cWEventMask .|. cWOverrideRedirect) winAttrs
io $ mapWindow dpy window -- not sure if this is needed
io $ lowerWindow dpy window -- not sure if this is needed
return window
| pjones/xmonad-test | vendor/xmonad-contrib/XMonad/Hooks/SetWMName.hs | bsd-2-clause | 4,831 | 0 | 20 | 1,027 | 792 | 410 | 382 | 56 | 2 |
{-# LANGUAGE TypeInType #-}
module T11648b where
import Data.Proxy
data X (a :: Proxy k)
| ezyang/ghc | testsuite/tests/polykinds/T11648b.hs | bsd-3-clause | 92 | 0 | 6 | 18 | 23 | 15 | 8 | -1 | -1 |
module A (f, y) where
import B.C (T(..))
f (T x) = x
y = T 42
| siddhanathan/ghc | testsuite/tests/rename/prog006/A.hs | bsd-3-clause | 67 | 0 | 7 | 22 | 48 | 28 | 20 | 4 | 1 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DefaultSignatures #-}
module GFunctor (
-- * Generic Functor class
GFunctor(..)
) where
import GHC.Generics
--------------------------------------------------------------------------------
-- Generic fmap
--------------------------------------------------------------------------------
class GFunctor' f where
gmap' :: (a -> b) -> f a -> f b
instance GFunctor' U1 where
gmap' _ U1 = U1
instance GFunctor' Par1 where
gmap' f (Par1 a) = Par1 (f a)
instance GFunctor' (K1 i c) where
gmap' _ (K1 a) = K1 a
instance (GFunctor f) => GFunctor' (Rec1 f) where
gmap' f (Rec1 a) = Rec1 (gmap f a)
instance (GFunctor' f) => GFunctor' (M1 i c f) where
gmap' f (M1 a) = M1 (gmap' f a)
instance (GFunctor' f, GFunctor' g) => GFunctor' (f :+: g) where
gmap' f (L1 a) = L1 (gmap' f a)
gmap' f (R1 a) = R1 (gmap' f a)
instance (GFunctor' f, GFunctor' g) => GFunctor' (f :*: g) where
gmap' f (a :*: b) = gmap' f a :*: gmap' f b
instance (GFunctor f, GFunctor' g) => GFunctor' (f :.: g) where
gmap' f (Comp1 x) = Comp1 (gmap (gmap' f) x)
class GFunctor f where
gmap :: (a -> b) -> f a -> f b
default gmap :: (Generic1 f, GFunctor' (Rep1 f))
=> (a -> b) -> f a -> f b
gmap f = to1 . gmap' f . from1
-- Base types instances
instance GFunctor Maybe
instance GFunctor []
instance GFunctor ((,) a)
| urbanslug/ghc | testsuite/tests/generics/GFunctor/GFunctor.hs | bsd-3-clause | 1,449 | 0 | 11 | 342 | 594 | 302 | 292 | 33 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
module Hpack.UtilSpec (main, spec) where
import Data.Aeson
import Data.Aeson.QQ
import Data.Aeson.Types
import Helper
import System.Directory
import Hpack.Config
import Hpack.Util
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "sort" $ do
it "sorts lexicographically" $ do
sort ["foo", "Foo"] `shouldBe` ["Foo", "foo" :: String]
describe "parseMain" $ do
it "accepts source file" $ do
parseMain "Main.hs" `shouldBe` ("Main.hs", [])
it "accepts literate source file" $ do
parseMain "Main.lhs" `shouldBe` ("Main.lhs", [])
it "accepts module" $ do
parseMain "Foo" `shouldBe` ("Foo.hs", ["-main-is Foo"])
it "accepts hierarchical module" $ do
parseMain "Foo.Bar.Baz" `shouldBe` ("Foo/Bar/Baz.hs", ["-main-is Foo.Bar.Baz"])
it "accepts qualified identifier" $ do
parseMain "Foo.bar" `shouldBe` ("Foo.hs", ["-main-is Foo.bar"])
describe "toModule" $ do
it "maps paths to module names" $ do
toModule ["Foo", "Bar", "Baz.hs"] `shouldBe` Just "Foo.Bar.Baz"
it "rejects invalid module names" $ do
toModule ["resources", "hello.hs"] `shouldBe` Nothing
describe "getFilesRecursive" $ do
it "gets all files from given directory and all its subdirectories" $ do
inTempDirectoryNamed "test" $ do
touch "foo/bar"
touch "foo/baz"
touch "foo/foobar/baz"
actual <- getFilesRecursive "foo"
actual `shouldMatchList` [
["bar"]
, ["baz"]
, ["foobar", "baz"]
]
describe "List" $ do
let invalid = [aesonQQ|{
name: "hpack",
gi: "sol/hpack",
ref: "master"
}|]
parseError :: Either String (List Dependency)
parseError = Left "neither key \"git\" nor key \"github\" present"
context "when parsing single values" $ do
it "returns the value in a singleton list" $ do
fromJSON (toJSON $ Number 23) `shouldBe` Success (List [23 :: Int])
it "returns error messages from element parsing" $ do
parseEither parseJSON invalid `shouldBe` parseError
context "when parsing a list of values" $ do
it "returns the list" $ do
fromJSON (toJSON [Number 23, Number 42]) `shouldBe` Success (List [23, 42 :: Int])
it "propagates parse error messages of invalid elements" $ do
parseEither parseJSON (toJSON [String "foo", invalid]) `shouldBe` parseError
describe "tryReadFile" $ do
it "reads file" $ do
inTempDirectory $ do
writeFile "foo" "bar"
tryReadFile "foo" `shouldReturn` Just "bar"
it "returns Nothing if file does not exist" $ do
inTempDirectory $ do
tryReadFile "foo" `shouldReturn` Nothing
describe "extractFieldOrderHint" $ do
it "extracts field order hints" $ do
let input = unlines [
"name: cabalize"
, "version: 0.0.0"
, "license:"
, "license-file: "
, "build-type: Simple"
, "cabal-version: >= 1.10"
]
extractFieldOrderHint input `shouldBe` [
"name"
, "version"
, "license"
, "license-file"
, "build-type"
, "cabal-version"
]
describe "sniffAlignment" $ do
it "sniffs field alignment from given cabal file" $ do
let input = unlines [
"name: cabalize"
, "version: 0.0.0"
, "license: MIT"
, "license-file: LICENSE"
, "build-type: Simple"
, "cabal-version: >= 1.10"
]
sniffAlignment input `shouldBe` Just 16
it "ignores fields without a value on the same line" $ do
let input = unlines [
"name: cabalize"
, "version: 0.0.0"
, "description: "
, " foo"
, " bar"
]
sniffAlignment input `shouldBe` Just 16
describe "splitField" $ do
it "splits fields" $ do
splitField "foo: bar" `shouldBe` Just ("foo", " bar")
it "accepts fields names with dashes" $ do
splitField "foo-bar: baz" `shouldBe` Just ("foo-bar", " baz")
it "rejects fields names with spaces" $ do
splitField "foo bar: baz" `shouldBe` Nothing
it "rejects invalid fields" $ do
splitField "foo bar" `shouldBe` Nothing
describe "expandGlobs" $ around_ inTempDirectory $ do
it "accepts simple files" $ do
touch "foo.js"
expandGlobs ["foo.js"] `shouldReturn` ([], ["foo.js"])
it "removes duplicates" $ do
touch "foo.js"
expandGlobs ["foo.js", "*.js"] `shouldReturn` ([], ["foo.js"])
it "rejects directories" $ do
touch "foo"
createDirectory "bar"
expandGlobs ["*"] `shouldReturn` ([], ["foo"])
it "rejects character ranges" $ do
touch "foo1"
touch "foo2"
touch "foo[1,2]"
expandGlobs ["foo[1,2]"] `shouldReturn` ([], ["foo[1,2]"])
context "when expanding *" $ do
it "expands by extension" $ do
let files = [
"files/foo.js"
, "files/bar.js"
, "files/baz.js"]
mapM_ touch files
touch "files/foo.hs"
expandGlobs ["files/*.js"] `shouldReturn` ([], sort files)
it "rejects dot-files" $ do
touch "foo/bar"
touch "foo/.baz"
expandGlobs ["foo/*"] `shouldReturn` ([], ["foo/bar"])
it "accepts dot-files when explicitly asked to" $ do
touch "foo/bar"
touch "foo/.baz"
expandGlobs ["foo/.*"] `shouldReturn` ([], ["foo/.baz"])
it "matches at most one directory component" $ do
touch "foo/bar/baz.js"
touch "foo/bar.js"
expandGlobs ["*/*.js"] `shouldReturn` ([], ["foo/bar.js"])
context "when expanding **" $ do
it "matches arbitrary many directory components" $ do
let file = "foo/bar/baz.js"
touch file
expandGlobs ["**/*.js"] `shouldReturn` ([], [file])
context "when a pattern does not match anything" $ do
it "warns" $ do
expandGlobs ["foo"] `shouldReturn`
(["Specified pattern \"foo\" for extra-source-files does not match any files"], [])
context "when a pattern only matches a directory" $ do
it "warns" $ do
createDirectory "foo"
expandGlobs ["foo"] `shouldReturn`
(["Specified pattern \"foo\" for extra-source-files does not match any files"], [])
| phunehehe/hpack | test/Hpack/UtilSpec.hs | mit | 6,657 | 0 | 21 | 2,081 | 1,663 | 815 | 848 | 160 | 1 |
{-# LANGUAGE
ScopedTypeVariables,
TupleSections,
OverloadedStrings
#-}
{-
The compactor does link-time optimization. It is much simpler
than the Optimizer, no fancy dataflow analysis here.
Optimizations:
- rewrite all variables starting with h$$ to shorter names,
these are internal names
- write all function metadata compactly
-}
module Gen2.Compactor where
import DynFlags
import Util
import Panic
import Control.Applicative
import Control.Lens hiding ((#))
import Control.Monad.State.Strict
import Prelude
import Data.Array
import qualified Data.Binary.Get as DB
import qualified Data.Binary.Put as DB
import qualified Data.Bits as Bits
import Data.Bits (shiftL, shiftR)
import qualified Data.ByteString.Lazy as BL
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Builder as BB
import Data.Char (chr)
import Data.Function (on)
import qualified Data.Graph as G
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import qualified Data.Map.Strict as M
import Data.Map (Map)
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import qualified Data.Set as S
import Data.Set (Set)
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Encoding as TE
import Compiler.JMacro
import Compiler.JMacro.Combinators
import Compiler.Settings
import Gen2.Base
import Gen2.ClosureInfo
import Gen2.Utils (buildingProf, buildingDebug)
import Gen2.Printer (pretty)
import qualified Gen2.Utils as U
import Text.PrettyPrint.Leijen.Text (renderPretty, displayT)
import qualified Crypto.Hash.SHA256 as SHA256
-- import qualified Debug.Trace
type LinkedUnit = (JStat, [ClosureInfo], [StaticInfo])
-- | collect global objects (data / CAFs). rename them and add them to the table
collectGlobals :: [StaticInfo]
-> State CompactorState ()
collectGlobals = mapM_ (\(StaticInfo i _ _) -> renameObj i)
debugShowStat :: (JStat, [ClosureInfo], [StaticInfo]) -> String
debugShowStat (_s, cis, sis) =
"closures:\n" ++
unlines (map show cis) ++
"\nstatics:" ++
unlines (map show sis) ++
"\n\n"
{- create a single string initializer for all StaticUnboxedString references
in the code, and rewrite all references to point to it
if incremental linking is used, each increment gets its own packed string
blob. if a string value already exists in an earlier blob it is not added
again
-}
packStrings :: HasDebugCallStack
=> GhcjsSettings
-> DynFlags
-> CompactorState
-> [LinkedUnit]
-> (CompactorState, [LinkedUnit])
packStrings _settings _dflags cstate code =
let allStatics :: [StaticInfo]
allStatics = concatMap (\(_,_,x) -> x) code
origStringTable :: StringTable
origStringTable = cstate ^. stringTable
allStrings :: Set ByteString
allStrings = S.fromList $
filter (not . isExisting)
(mapMaybe (staticString . siVal) allStatics)
where
isExisting bs = isJust (HM.lookup bs $ stOffsets origStringTable)
staticString :: StaticVal -> Maybe ByteString
staticString (StaticUnboxed (StaticUnboxedString bs)) = Just bs
staticString (StaticUnboxed (StaticUnboxedStringOffset bs)) = Just bs
staticString _ = Nothing
allStringsList :: [ByteString]
allStringsList = S.toList allStrings
-- we may see two kinds of null characters
-- - string separator, packed as \0
-- - within a string, packed as \cz\0
-- we transform the strings to
transformPackedLiteral :: Text -> Text
transformPackedLiteral = T.concatMap f
where
f :: Char -> Text
f '\0' = "\^Z\0"
f '\^Z' = "\^Z\^Z"
f x = T.singleton x
allStringsPacked :: Text
allStringsPacked = T.intercalate "\0" $
map (\str -> maybe (packBase64 str)
transformPackedLiteral
(U.decodeModifiedUTF8 str))
allStringsList
packBase64 :: ByteString -> Text
packBase64 bs
| BS.null bs = mempty
| otherwise =
let (h,t) = BS.splitAt 128 bs
esc = T.singleton '\^Z' <>
T.singleton (chr . fromIntegral $ BS.length h + 0x1f)
b64 = esc <> fromJust (U.decodeModifiedUTF8 (B64.encode h))
in maybe b64 transformPackedLiteral (U.decodeModifiedUTF8 h) <>
packBase64 t
allStringsWithOffset :: [(ByteString, Int)]
allStringsWithOffset = snd $
mapAccumL (\o b -> let o' = o + fromIntegral (BS.length b) + 1
in o' `seq` (o', (b, o)))
0
allStringsList
-- the offset of each of the strings in the big blob
offsetIndex :: HashMap ByteString Int
offsetIndex = HM.fromList allStringsWithOffset
stringSymbol :: Ident
stringSymbol = head $ cstate ^. identSupply
stringSymbolT :: Text
stringSymbolT = let (TxtI t) = stringSymbol in t
stringSymbolIdx :: Int
stringSymbolIdx = snd (bounds $ stTableIdents origStringTable) + 1
-- append the new string symbol
newTableIdents :: Array Int Text
newTableIdents =
listArray (0, stringSymbolIdx)
(elems (stTableIdents origStringTable) ++ [stringSymbolT])
newOffsetsMap :: HashMap ByteString (Int, Int)
newOffsetsMap = HM.union (stOffsets origStringTable)
(fmap (stringSymbolIdx,) offsetIndex)
newIdentsMap :: HashMap Text (Either Int Int)
newIdentsMap =
let f (StaticInfo s (StaticUnboxed (StaticUnboxedString bs)) _)
= Just (s, Left . fst $ newOffsetsMap HM.! bs)
f (StaticInfo s (StaticUnboxed (StaticUnboxedStringOffset bs)) _)
= Just (s, Right . snd $ newOffsetsMap HM.! bs)
f _ = Nothing
in HM.union (stIdents origStringTable)
(HM.fromList $ mapMaybe f allStatics)
newStringTable :: StringTable
newStringTable = StringTable newTableIdents newOffsetsMap newIdentsMap
newOffsetsInverted :: HashMap (Int, Int) ByteString
newOffsetsInverted = HM.fromList .
map (\(x,y) -> (y,x)) .
HM.toList $
newOffsetsMap
replaceSymbol :: Text -> Maybe JVal
replaceSymbol t =
let f (Left i) = JVar (TxtI $ newTableIdents ! i)
f (Right o) = JInt (fromIntegral o)
in fmap f (HM.lookup t newIdentsMap)
cstate0 :: CompactorState
cstate0 = cstate & identSupply %~ tail
& stringTable .~ newStringTable
initStr :: JStat
initStr =
DeclStat stringSymbol <>
AssignStat (ValExpr $ JVar stringSymbol)
(ApplExpr (ApplExpr (ValExpr $ JVar (TxtI "h$pstr"))
[ValExpr (JStr allStringsPacked)])
[])
rewriteValsE :: JExpr -> JExpr
rewriteValsE (ApplExpr e xs)
| Just t <- appMatchStringLit e xs = ValExpr (JStr t)
rewriteValsE (ValExpr v) = ValExpr (rewriteVals v)
rewriteValsE e = e & exprsE %~ rewriteValsE
rewriteVals :: JVal -> JVal
rewriteVals (JVar (TxtI t))
| Just v <- replaceSymbol t = v
rewriteVals (JList es) = JList (map rewriteValsE es)
rewriteVals (JHash m) = JHash (fmap rewriteValsE m)
rewriteVals (JFunc args body) = JFunc args (body & exprsS %~ rewriteValsE)
rewriteVals v = v
rewriteStat :: JStat -> JStat
rewriteStat st = st & exprsS %~ rewriteValsE
appMatchStringLit :: JExpr -> [JExpr] -> Maybe Text
appMatchStringLit (ValExpr (JVar (TxtI "h$decodeUtf8z")))
[ValExpr (JVar (TxtI x)), ValExpr (JVar (TxtI y))]
| Just (Left i) <- HM.lookup x newIdentsMap
, Just (Right j) <- HM.lookup y newIdentsMap
, Just bs <- HM.lookup (i,j) newOffsetsInverted =
U.decodeModifiedUTF8 bs
appMatchStringLit _ _ = Nothing
rewriteStatic :: StaticInfo -> Maybe StaticInfo
rewriteStatic (StaticInfo _i
(StaticUnboxed StaticUnboxedString{})
_cc) =
Nothing
rewriteStatic (StaticInfo _i
(StaticUnboxed StaticUnboxedStringOffset {})
_cc) =
Nothing
rewriteStatic si = Just (si & staticInfoArgs %~ rewriteStaticArg)
rewriteStaticArg :: StaticArg -> StaticArg
rewriteStaticArg a@(StaticObjArg t) =
case HM.lookup t newIdentsMap of
Just (Right v) -> StaticLitArg (IntLit $ fromIntegral v)
Just (Left idx) -> StaticObjArg (newTableIdents ! idx)
_ -> a
rewriteStaticArg (StaticConArg v es)
= StaticConArg v (map rewriteStaticArg es)
rewriteStaticArg x = x
initStatic :: LinkedUnit
initStatic =
let (TxtI ss) = stringSymbol
in (initStr, [], [StaticInfo ss (StaticThunk Nothing) Nothing])
rewriteBlock :: LinkedUnit -> LinkedUnit
rewriteBlock (stat, ci, si)
= (rewriteStat stat, ci, mapMaybe rewriteStatic si)
in (cstate0, initStatic : map rewriteBlock code)
renameInternals :: HasDebugCallStack
=> GhcjsSettings
-> DynFlags
-> CompactorState
-> [Text]
-> [LinkedUnit]
-> (CompactorState, [JStat], JStat)
renameInternals settings dflags cs0 rtsDeps stats0a = (cs, stats, meta)
where
(stbs, stats0) = (if gsDedupe settings
then dedupeBodies rtsDeps . dedupe rtsDeps
else (mempty,)) stats0a
((stats, meta), cs) = runState renamed cs0
renamed :: State CompactorState ([JStat], JStat)
renamed
| buildingDebug dflags || buildingProf dflags = do
cs <- get
let renamedStats = map (\(s,_,_) -> s & identsS %~ lookupRenamed cs)
stats0
statics = map (renameStaticInfo cs) $
concatMap (\(_,_,x) -> x) stats0
infos = map (renameClosureInfo cs) $
concatMap (\(_,x,_) -> x) stats0
-- render metadata as individual statements
meta = mconcat (map staticDeclStat statics) <>
(stbs & identsS %~ lookupRenamed cs) <>
mconcat (map (staticInitStat $ buildingProf dflags) statics) <>
mconcat (map (closureInfoStat True) infos)
return (renamedStats, meta)
| otherwise = do
-- collect all global objects and entries, add them to the renaming table
mapM_ (\(_, cis, sis) -> do
mapM_ (renameEntry . TxtI . ciVar) cis
mapM_ (renameObj . siVar) sis
mapM_ collectLabels sis) stats0
-- sort our entries, store the results
-- propagate all renamings throughtout the code
cs <- get
let -- Safari on iOS 10 (64 bit only?) crashes on very long arrays
safariCrashWorkaround :: [Ident] -> JExpr
safariCrashWorkaround xs =
case chunksOf 10000 xs of
(y:ys) | not (null ys)
-> ApplExpr (SelExpr (toJExpr y) (TxtI "concat"))
(map toJExpr ys)
_ -> toJExpr xs
let renamedStats = map (\(s,_,_) -> s & identsS %~ lookupRenamed cs)
stats0
sortedInfo = concatMap (\(_,xs,_) -> map (renameClosureInfo cs)
xs)
stats0
entryArr = safariCrashWorkaround $
map (TxtI . fst) .
sortBy (compare `on` snd) .
HM.toList $
cs ^. entries
lblArr = map (TxtI . fst) .
sortBy (compare `on` snd) .
HM.toList $
cs ^. labels
ss = concatMap (\(_,_,xs) -> map (renameStaticInfo cs) xs)
stats0
infoBlock = encodeStr (concatMap (encodeInfo cs) sortedInfo)
staticBlock = encodeStr (concatMap (encodeStatic cs) ss)
stbs' = stbs & identsS %~ lookupRenamed cs
staticDecls = mconcat (map staticDeclStat ss) <> stbs'
meta = staticDecls #
appS "h$scheduleInit" [ entryArr
, var "h$staticDelayed"
, e lblArr
, e infoBlock
, e staticBlock
]
-- error "scheduleInit"
{-
[j| h$scheduleInit( `entryArr`
, h$staticDelayed
, `lblArr`
, `infoBlock`
, `staticBlock`);
h$staticDelayed = [];
|] -}
return (renamedStats, meta)
-- | rename a heap object, which means adding it to the
-- static init table in addition to the renamer
renameObj :: Text
-> State CompactorState Text
renameObj xs = do
(TxtI xs') <- renameVar (TxtI xs)
addItem statics statics numStatics numStatics parentStatics xs'
return xs'
renameEntry :: Ident
-> State CompactorState Ident
renameEntry i = do
i'@(TxtI i'') <- renameVar i
addItem entries entries numEntries numEntries parentEntries i''
return i'
addItem :: HasDebugCallStack
=> Getting (HashMap Text Int) CompactorState (HashMap Text Int)
-> Setting (->)
CompactorState
CompactorState
(HashMap Text Int)
(HashMap Text Int)
-> Getting Int CompactorState Int
-> ASetter' CompactorState Int
-> Getting (HashMap Text Int) CompactorState (HashMap Text Int)
-> Text
-> State CompactorState ()
addItem items items' numItems numItems' parentItems i = do
s <- use items
case HM.lookup i s of
Just _ -> return ()
Nothing -> do
sp <- use parentItems
case HM.lookup i sp of
Just _ -> return ()
Nothing -> do
ni <- use numItems
items' %= HM.insert i ni
numItems' += 1
collectLabels :: StaticInfo -> State CompactorState ()
collectLabels si = mapM_ (addItem labels labels numLabels numLabels parentLabels)
(labelsV . siVal $ si)
where
labelsV (StaticData _ args) = concatMap labelsA args
labelsV (StaticList args _) = concatMap labelsA args
labelsV _ = []
labelsA (StaticLitArg l) = labelsL l
labelsA _ = []
labelsL (LabelLit _ lbl) = [lbl]
labelsL _ = []
lookupRenamed :: CompactorState -> Ident -> Ident
lookupRenamed cs i@(TxtI t) =
case HM.lookup t (cs ^. nameMap) of
Nothing -> i
Just i' -> i'
renameVar :: Ident -- ^ text identifier to rename
-> State CompactorState Ident -- ^ the updated renamer state and the new ident
renameVar i@(TxtI t)
| "h$$" `T.isPrefixOf` t = do
m <- use nameMap
case HM.lookup t m of
Just r -> return r
Nothing -> do
y <- newIdent
nameMap %= HM.insert t y
return y
| otherwise = return i
newIdent :: State CompactorState Ident
newIdent = do
yys <- use identSupply
case yys of
(y:ys) -> do
identSupply .= ys
return y
_ -> error "newIdent: empty list"
-- | rename a compactor info entry according to the compactor state (no new renamings are added)
renameClosureInfo :: CompactorState
-> ClosureInfo
-> ClosureInfo
renameClosureInfo cs (ClosureInfo v rs n l t s) =
(ClosureInfo (renameV v) rs n l t (f s))
where
renameV t = maybe t (\(TxtI t') -> t') (HM.lookup t m)
m = cs ^. nameMap
f (CIStaticRefs rs) = CIStaticRefs (map renameV rs)
-- | rename a static info entry according to the compactor state (no new renamings are added)
renameStaticInfo :: CompactorState
-> StaticInfo
-> StaticInfo
renameStaticInfo cs si = si & staticIdents %~ renameIdent
where
renameIdent t = maybe t (\(TxtI t') -> t') (HM.lookup t $ cs ^. nameMap)
staticIdents :: Traversal' StaticInfo Text
staticIdents f (StaticInfo i v cc) =
StaticInfo <$> f i <*> staticIdentsV f v <*> pure cc
staticIdentsV :: Traversal' StaticVal Text
staticIdentsV f (StaticFun i args) =
StaticFun <$> f i <*> traverse (staticIdentsA f) args
staticIdentsV f (StaticThunk (Just (i, args))) =
StaticThunk . Just <$> liftA2 (,) (f i) (traverse (staticIdentsA f) args)
staticIdentsV f (StaticData con args) =
StaticData <$> f con <*> traverse (staticIdentsA f) args
staticIdentsV f (StaticList xs t) =
StaticList <$> traverse (staticIdentsA f) xs <*> traverse f t
staticIdentsV _ x =
pure x
staticIdentsA :: Traversal' StaticArg Text
staticIdentsA f (StaticObjArg t) = StaticObjArg <$> f t
staticIdentsA _ x = pure x
{-
simple encoding of naturals using only printable low char points,
rely on gzip to compress repeating sequences,
most significant bits first
1 byte: ascii code 32-123 (0-89), \ and " unused
2 byte: 124 a b (90-8189)
3 byte: 125 a b c (8190-737189)
-}
encodeStr :: HasDebugCallStack => [Int] -> String
encodeStr = concatMap encodeChr
where
c :: HasDebugCallStack => Int -> Char
c i | i > 90 || i < 0 = error ("encodeStr: c " ++ show i)
| i >= 59 = chr (34+i)
| i >= 2 = chr (33+i)
| otherwise = chr (32+i)
encodeChr :: HasDebugCallStack => Int -> String
encodeChr i
| i < 0 = panic "encodeStr: negative"
| i <= 89 = [c i]
| i <= 8189 = let (c1, c2) = (i - 90) `divMod` 90 in [chr 124, c c1, c c2]
| i <= 737189 = let (c2a, c3) = (i - 8190) `divMod` 90
(c1, c2) = c2a `divMod` 90
in [chr 125, c c1, c c2, c c3]
| otherwise = panic "encodeStr: overflow"
entryIdx :: HasDebugCallStack
=> String
-> CompactorState
-> Text
-> Int
entryIdx msg cs i = fromMaybe lookupParent (HM.lookup i' (cs ^. entries))
where
(TxtI i') = lookupRenamed cs (TxtI i)
lookupParent = maybe err
(+ cs ^. numEntries)
(HM.lookup i' (cs ^. parentEntries))
err = panic (msg ++ ": invalid entry: " ++ T.unpack i')
objectIdx :: HasDebugCallStack
=> String
-> CompactorState
-> Text
-> Int
objectIdx msg cs i = fromMaybe lookupParent (HM.lookup i' (cs ^. statics))
where
(TxtI i') = lookupRenamed cs (TxtI i)
lookupParent = maybe err
(+ cs ^. numStatics)
(HM.lookup i' (cs ^. parentStatics))
err = panic (msg ++ ": invalid static: " ++ T.unpack i')
labelIdx :: HasDebugCallStack
=> String
-> CompactorState
-> Text
-> Int
labelIdx msg cs l = fromMaybe lookupParent (HM.lookup l (cs ^. labels))
where
lookupParent = maybe err
(+ cs ^. numLabels)
(HM.lookup l (cs ^. parentLabels))
err = panic (msg ++ ": invalid label: " ++ T.unpack l)
encodeInfo :: HasDebugCallStack
=> CompactorState
-> ClosureInfo -- ^ information to encode
-> [Int]
encodeInfo cs (ClosureInfo _var regs name layout typ static)
| CIThunk <- typ = [0] ++ ls
| (CIFun _arity regs0) <- typ, regs0 /= argSize regs
= panic ("encodeInfo: inconsistent register metadata for " ++ T.unpack name)
| (CIFun arity _regs0) <- typ = [1, arity, encodeRegs regs] ++ ls
| (CICon tag) <- typ = [2, tag] ++ ls
| CIStackFrame <- typ = [3, encodeRegs regs] ++ ls
-- (CIPap ar) <- typ = [4, ar] ++ ls -- these should only appear during runtime
| otherwise = panic $
"encodeInfo, unexpected closure type: " ++ show typ
where
ls = encodeLayout layout ++ encodeSrt static
encodeLayout CILayoutVariable = [0]
encodeLayout (CILayoutUnknown s) = [s+1]
encodeLayout (CILayoutFixed s _vs) = [s+1]
encodeSrt (CIStaticRefs rs) = length rs : map (objectIdx "encodeInfo" cs) rs
encodeRegs CIRegsUnknown = 0
encodeRegs (CIRegs skip regTypes) = let nregs = sum (map varSize regTypes)
in encodeRegsTag skip nregs
encodeRegsTag skip nregs
| skip < 0 || skip > 1 = panic "encodeRegsTag: unexpected skip"
| otherwise = 1 + (nregs `shiftL` 1) + skip
argSize (CIRegs skip regTypes) = sum (map varSize regTypes) - 1 + skip
argSize _ = 0
encodeStatic :: HasDebugCallStack
=> CompactorState
-> StaticInfo
-> [Int]
encodeStatic cs si =
U.trace' ("encodeStatic: " ++ show si)
(encodeStatic0 cs si)
encodeStatic0 :: HasDebugCallStack
=> CompactorState
-> StaticInfo
-> [Int]
encodeStatic0 cs (StaticInfo _to sv _)
| StaticFun f args <- sv =
[1, entry f, length args] ++ concatMap encodeArg args
| StaticThunk (Just (t, args)) <- sv =
[2, entry t, length args] ++ concatMap encodeArg args
| StaticThunk Nothing <- sv =
[0]
| StaticUnboxed (StaticUnboxedBool b) <- sv =
[3 + fromEnum b]
| StaticUnboxed (StaticUnboxedInt _i) <- sv =
[5] -- ++ encodeInt i
| StaticUnboxed (StaticUnboxedDouble _d) <- sv =
[6] -- ++ encodeDouble d
| (StaticUnboxed _) <- sv = [] -- unboxed strings have their own table
-- | StaticString t <- sv = [7, T.length t] ++ map encodeChar (T.unpack t)
-- | StaticBin bs <- sv = [8, BS.length bs] ++ map fromIntegral (BS.unpack bs)
| StaticList [] Nothing <- sv =
[8]
| StaticList args t <- sv =
[9, length args] ++
maybe [0] (\t' -> [1, obj t']) t ++
concatMap encodeArg (reverse args)
| StaticData con args <- sv =
(if length args <= 6
then [11+length args]
else [10,length args]) ++
[entry con] ++
concatMap encodeArg args
where
obj = objectIdx "encodeStatic" cs
entry = entryIdx "encodeStatic" cs
lbl = labelIdx "encodeStatic" cs
-- | an argument is either a reference to a heap object or a primitive value
encodeArg (StaticLitArg (BoolLit b)) =
[0 + fromEnum b]
encodeArg (StaticLitArg (IntLit 0)) =
[2]
encodeArg (StaticLitArg (IntLit 1)) =
[3]
encodeArg (StaticLitArg (IntLit i)) =
[4] ++ encodeInt i
encodeArg (StaticLitArg NullLit) =
[5]
encodeArg (StaticLitArg (DoubleLit d)) =
[6] ++ encodeDouble d
encodeArg (StaticLitArg (StringLit s)) =
[7] ++ encodeString s
encodeArg (StaticLitArg (BinLit b)) =
[8] ++ encodeBinary b
encodeArg (StaticLitArg (LabelLit b l)) =
[9, fromEnum b, lbl l]
encodeArg (StaticConArg con args) =
[10, entry con, length args] ++ concatMap encodeArg args
encodeArg (StaticObjArg t) =
[11 + obj t]
-- encodeArg x = panic ("encodeArg: unexpected: " ++ show x)
-- encodeChar = ord -- fixme make characters more readable
encodeString :: Text -> [Int]
encodeString xs = encodeBinary (TE.encodeUtf8 xs)
-- ByteString is prefixed with length, then blocks of 4 numbers encoding 3 bytes
encodeBinary :: BS.ByteString -> [Int]
encodeBinary bs = BS.length bs : go bs
where
go b | BS.null b = []
| l == 1 = let b0 = b `BS.index` 0
in map fromIntegral [ b0 `shiftR` 2, (b0 Bits..&. 3) `shiftL` 4 ]
| l == 2 = let b0 = b `BS.index` 0
b1 = b `BS.index` 1
in map fromIntegral [ b0 `shiftR` 2
, ((b0 Bits..&. 3) `shiftL` 4) Bits..|. (b1 `shiftR` 4)
, (b1 Bits..&. 15) `shiftL` 2
]
| otherwise = let b0 = b `BS.index` 0
b1 = b `BS.index` 1
b2 = b `BS.index` 2
in map fromIntegral [ b0 `shiftR` 2
, ((b0 Bits..&. 3) `shiftL` 4) Bits..|. (b1 `shiftR` 4)
, ((b1 Bits..&. 15) `shiftL` 2) Bits..|. (b2 `shiftR` 6)
, b2 Bits..&. 63
] ++ go (BS.drop 3 b)
where l = BS.length b
encodeInt :: Integer -> [Int]
encodeInt i
| i >= -10 && i < encodeMax - 11 = [fromIntegral i + 12]
| i > 2^(31::Int)-1 || i < -2^(31::Int)
= panic "encodeInt: integer outside 32 bit range"
| otherwise = let i' :: Int32 = fromIntegral i
in [ 0
, fromIntegral ((i' `shiftR` 16) Bits..&. 0xffff)
, fromIntegral (i' Bits..&. 0xffff)
]
-- encode a possibly 53 bit int
encodeSignificand :: Integer -> [Int]
encodeSignificand i
| i >= -10 && i < encodeMax - 11 = [fromIntegral i + 12]
| i > 2^(53::Int) || i < -2^(53::Int)
= panic ("encodeInt: integer outside 53 bit range: " ++ show i)
| otherwise = let i' = abs i
in [if i < 0 then 0 else 1] ++
map (\r -> fromIntegral ((i' `shiftR` r) Bits..&. 0xffff))
[48,32,16,0]
encodeDouble :: SaneDouble -> [Int]
encodeDouble (SaneDouble d)
| isNegativeZero d = [0]
| d == 0 = [1]
| isInfinite d && d > 0 = [2]
| isInfinite d = [3]
| isNaN d = [4]
| abs exponent <= 30
= [6 + fromIntegral exponent + 30] ++ encodeSignificand significand
| otherwise
= [5] ++ encodeInt (fromIntegral exponent) ++ encodeSignificand significand
where
(significand, exponent) = decodeFloat d
encodeMax :: Integer
encodeMax = 737189
{- |
The Base data structure contains the information we need
to do incremental linking against a base bundle.
base file format:
GHCJSBASE
[renamer state]
[linkedPackages]
[packages]
[modules]
[symbols]
-}
renderBase :: Base -- ^ base metadata
-> BL.ByteString -- ^ rendered result
renderBase = DB.runPut . putBase
loadBase :: FilePath -> IO Base
loadBase file = DB.runGet (getBase file) <$> BL.readFile file
----------------------------
{-# INLINE identsS #-}
identsS :: Traversal' JStat Ident
identsS f (DeclStat i) = DeclStat <$> f i
identsS f (ReturnStat e) = ReturnStat <$> identsE f e
identsS f (IfStat e s1 s2) = IfStat <$> identsE f e <*> identsS f s1 <*> identsS f s2
identsS f (WhileStat b e s) = WhileStat b <$> identsE f e <*> identsS f s
identsS f (ForInStat b i e s) = ForInStat b <$> f i <*> identsE f e <*> identsS f s
identsS f (SwitchStat e xs s) = SwitchStat <$> identsE f e <*> (traverse . traverseCase) f xs <*> identsS f s
where traverseCase g (e,s) = (,) <$> identsE g e <*> identsS g s
identsS f (TryStat s1 i s2 s3) = TryStat <$> identsS f s1 <*> f i <*> identsS f s2 <*> identsS f s3
identsS f (BlockStat xs) = BlockStat <$> (traverse . identsS) f xs
identsS f (ApplStat e es) = ApplStat <$> identsE f e <*> (traverse . identsE) f es
identsS f (UOpStat op e) = UOpStat op <$> identsE f e
identsS f (AssignStat e1 e2) = AssignStat <$> identsE f e1 <*> identsE f e2
identsS _ UnsatBlock{} = error "identsS: UnsatBlock"
identsS f (LabelStat l s) = LabelStat l <$> identsS f s
identsS _ b@BreakStat{} = pure b
identsS _ c@ContinueStat{} = pure c
{-# INLINE identsE #-}
identsE :: Traversal' JExpr Ident
identsE f (ValExpr v) = ValExpr <$> identsV f v
identsE f (SelExpr e i) = SelExpr <$> identsE f e <*> pure i -- do not rename properties
identsE f (IdxExpr e1 e2) = IdxExpr <$> identsE f e1 <*> identsE f e2
identsE f (InfixExpr s e1 e2) = InfixExpr s <$> identsE f e1 <*> identsE f e2
identsE f (UOpExpr o e) = UOpExpr o <$> identsE f e
identsE f (IfExpr e1 e2 e3) = IfExpr <$> identsE f e1 <*> identsE f e2 <*> identsE f e3
identsE f (ApplExpr e es) = ApplExpr <$> identsE f e <*> (traverse . identsE) f es
identsE _ UnsatExpr{} = error "identsE: UnsatExpr"
{-# INLINE identsV #-}
identsV :: Traversal' JVal Ident
identsV f (JVar i) = JVar <$> f i
identsV f (JList xs) = JList <$> (traverse . identsE) f xs
identsV _ d@JDouble{} = pure d
identsV _ i@JInt{} = pure i
identsV _ s@JStr{} = pure s
identsV _ r@JRegEx{} = pure r
identsV f (JHash m) = JHash <$> (traverse . identsE) f m
identsV f (JFunc args s) = JFunc <$> traverse f args <*> identsS f s
identsV _ UnsatVal{} = error "identsV: UnsatVal"
----------------------------
{-# INLINE valsS #-}
valsS :: Traversal' JStat JVal
valsS _ d@(DeclStat _i) = pure d -- DeclStat <$> f i
valsS f (ReturnStat e) = ReturnStat <$> valsE f e
valsS f (IfStat e s1 s2) = IfStat <$> valsE f e <*> valsS f s1 <*> valsS f s2
valsS f (WhileStat b e s) = WhileStat b <$> valsE f e <*> valsS f s
valsS f (ForInStat b i e s) = ForInStat b <$> pure i <*> valsE f e <*> valsS f s
valsS f (SwitchStat e xs s) = SwitchStat <$> valsE f e <*> (traverse . traverseCase) f xs <*> valsS f s
where traverseCase g (e,s) = (,) <$> valsE g e <*> valsS g s
valsS f (TryStat s1 i s2 s3) = TryStat <$> valsS f s1 <*> pure i <*> valsS f s2 <*> valsS f s3
valsS f (BlockStat xs) = BlockStat <$> (traverse . valsS) f xs
valsS f (ApplStat e es) = ApplStat <$> valsE f e <*> (traverse . valsE) f es
valsS f (UOpStat op e) = UOpStat op <$> valsE f e
valsS f (AssignStat e1 e2) = AssignStat <$> valsE f e1 <*> valsE f e2
valsS _ UnsatBlock{} = panic "valsS: UnsatBlock"
valsS f (LabelStat l s) = LabelStat l <$> valsS f s
valsS _ b@BreakStat{} = pure b
valsS _ c@ContinueStat{} = pure c
{-# INLINE valsE #-}
valsE :: Traversal' JExpr JVal
valsE f (ValExpr v) = ValExpr <$> f v
valsE f (SelExpr e i) = SelExpr <$> valsE f e <*> pure i
valsE f (IdxExpr e1 e2) = IdxExpr <$> valsE f e1 <*> valsE f e2
valsE f (InfixExpr s e1 e2) = InfixExpr s <$> valsE f e1 <*> valsE f e2
valsE f (UOpExpr o e) = UOpExpr o <$> valsE f e
valsE f (IfExpr e1 e2 e3) = IfExpr <$> valsE f e1 <*> valsE f e2 <*> valsE f e3
valsE f (ApplExpr e es) = ApplExpr <$> valsE f e <*> (traverse . valsE) f es
valsE _ UnsatExpr{} = panic "valsE: UnsatExpr"
{-# INLINE exprsS #-}
exprsS :: Traversal' JStat JExpr
exprsS _ d@(DeclStat _i) = pure d -- DeclStat <$> f i
exprsS f (ReturnStat e) = ReturnStat <$> f e
exprsS f (IfStat e s1 s2) = IfStat <$> f e <*> exprsS f s1 <*> exprsS f s2
exprsS f (WhileStat b e s) = WhileStat b <$> f e <*> exprsS f s
exprsS f (ForInStat b i e s) = ForInStat b <$> pure i <*> f e <*> exprsS f s
exprsS f (SwitchStat e xs s) = SwitchStat <$> f e <*> (traverse . traverseCase) f xs <*> exprsS f s
where traverseCase g (e,s) = (,) <$> g e <*> exprsS g s
exprsS f (TryStat s1 i s2 s3) = TryStat <$> exprsS f s1 <*> pure i <*> exprsS f s2 <*> exprsS f s3
exprsS f (BlockStat xs) = BlockStat <$> (traverse . exprsS) f xs
exprsS f (ApplStat e es) = ApplStat <$> f e <*> traverse f es
exprsS f (UOpStat op e) = UOpStat op <$> f e
exprsS f (AssignStat e1 e2) = AssignStat <$> f e1 <*> f e2
exprsS _ UnsatBlock{} = panic "exprsS: UnsatBlock"
exprsS f (LabelStat l s) = LabelStat l <$> exprsS f s
exprsS _ b@BreakStat{} = pure b
exprsS _ c@ContinueStat{} = pure c
-- doesn't traverse through values
{-# INLINE exprsE #-}
exprsE :: Traversal' JExpr JExpr
exprsE _ ve@(ValExpr _) = pure ve
exprsE f (SelExpr e i) = SelExpr <$> f e <*> pure i
exprsE f (IdxExpr e1 e2) = IdxExpr <$> f e1 <*> f e2
exprsE f (InfixExpr s e1 e2) = InfixExpr s <$> f e1 <*> f e2
exprsE f (UOpExpr o e) = UOpExpr o <$> f e
exprsE f (IfExpr e1 e2 e3) = IfExpr <$> f e1 <*> f e2 <*> f e3
exprsE f (ApplExpr e es) = ApplExpr <$> f e <*> traverse f es
exprsE _ UnsatExpr{} = panic "exprsE: UnsatExpr"
staticInfoArgs :: Traversal' StaticInfo StaticArg
staticInfoArgs f (StaticInfo si sv sa) =
StaticInfo <$> pure si <*> staticValArgs f sv <*> pure sa
staticValArgs :: Traversal' StaticVal StaticArg
staticValArgs f (StaticFun fn as)
= StaticFun fn <$> traverse f as
staticValArgs f (StaticThunk (Just (t, as)))
= StaticThunk . Just . (t,) <$> traverse f as
staticValArgs f (StaticData c as) = StaticData c <$> traverse f as
staticValArgs f (StaticList as mt) = StaticList <$> traverse f as <*> pure mt
staticValArgs _ x = pure x
compact :: GhcjsSettings
-> DynFlags
-> CompactorState
-> [Text]
-> [LinkedUnit]
-> (CompactorState, [JStat], JStat)
compact settings dflags cs0 rtsDeps0 input0
-- | dumpHashes' input
=
let rtsDeps1 = rtsDeps0 ++
map (<> "_e") rtsDeps0 ++
map (<> "_con_e") rtsDeps0
(cs1, input1) = packStrings settings dflags cs0 input0
in renameInternals settings dflags cs1 rtsDeps1 input1
-- renameInternals settings dflags cs1 rtsDeps' input
-- hash compactification
dedupeBodies :: [Text]
-> [(JStat, [ClosureInfo], [StaticInfo])]
-> (JStat, [(JStat, [ClosureInfo], [StaticInfo])])
dedupeBodies rtsDeps input = (renderBuildFunctions bfN bfCB, input')
where
(bfN, bfCB, input') = rewriteBodies globals hdefsR hdefs input
hdefs = M.fromListWith (\(s,ks1) (_,ks2) -> (s, ks1++ks2))
(map (\(k, s, bs) -> (bs, (s, [k]))) hdefs0)
hdefsR = M.fromList $ map (\(k, _, bs) -> (k, bs)) hdefs0
hdefs0 :: [(Text, Int, BS.ByteString)]
hdefs0 = concatMap (\(b,_,_) ->
(map (\(k,h) ->
let (s,fh, _deps) = finalizeHash' h
in (k, s, fh))
. hashDefinitions globals) b
)
input
globals = foldl' (flip S.delete) (findAllGlobals input) rtsDeps
renderBuildFunctions :: [BuildFunction] -> [BuildFunction] -> JStat
renderBuildFunctions normalBfs cycleBreakerBfs =
cycleBr1 <> mconcat (map renderBuildFunction normalBfs) <> cycleBr2
where
renderCbr f = mconcat (zipWith f cycleBreakerBfs [1..])
cbName :: Int -> Text
cbName = T.pack . ("h$$$cb"++) . show
cycleBr1 = renderCbr $ \bf n ->
let args = map (TxtI . T.pack . ('a':) . show) [1..bfArgs bf]
body = ReturnStat $ ApplExpr (ValExpr (JVar (TxtI $ cbName n)))
(map (ValExpr . JVar) args)
in DeclStat (TxtI (bfName bf)) <>
AssignStat (ValExpr (JVar (TxtI (bfName bf))))
(ValExpr (JFunc args body))
cycleBr2 = renderCbr $ \bf n -> renderBuildFunction (bf { bfName = cbName n })
data BuildFunction = BuildFunction
{ bfName :: !Text
, bfBuilder :: !Ident
, bfDeps :: [Text]
, bfArgs :: !Int
} deriving (Eq, Ord, Show)
{-
Stack frame initialization order is important when code is reused:
all dependencies have to be ready when the closure is built.
This function sorts the initializers and returns an additional list
of cycle breakers, which are built in a two-step fashion
-}
sortBuildFunctions :: [BuildFunction] -> ([BuildFunction], [BuildFunction])
sortBuildFunctions bfs = (map snd normBFs, map snd cbBFs)
where
(normBFs, cbBFs) = partition (not.fst) . concatMap fromSCC $ sccs bfs
bfm :: Map Text BuildFunction
bfm = M.fromList (map (\x -> (bfName x, x)) bfs)
fromSCC :: G.SCC Text -> [(Bool, BuildFunction)]
fromSCC (G.AcyclicSCC x) = [(False, bfm M.! x)]
fromSCC (G.CyclicSCC xs) = breakCycles xs
sccs :: [BuildFunction] -> [G.SCC Text]
sccs b = G.stronglyConnComp $
map (\bf -> let n = bfName bf in (n, n, bfDeps bf)) b
{-
finding the maximum acyclic subgraph is the Minimum Feedback Arc Set problem,
which is NP-complete. We use an approximation here.
-}
breakCycles :: [Text] -> [(Bool, BuildFunction)]
breakCycles nodes =
(True, bfm M.! selected)
: concatMap fromSCC (sccs $ (map (bfm M.!) $ filter (/=selected) nodes))
where
outDeg, inDeg :: Map Text Int
outDeg = M.fromList $ map (\n -> (n, length (bfDeps (bfm M.! n)))) nodes
inDeg = M.fromListWith (+) (map (,1) . concatMap (bfDeps . (bfm M.!)) $ nodes)
-- ELS heuristic (Eades et. al.)
selected :: Text
selected = maximumBy (compare `on` (\x -> outDeg M.! x - inDeg M.! x)) nodes
rewriteBodies :: Set Text
-> Map Text BS.ByteString
-> Map BS.ByteString (Int, [Text])
-> [LinkedUnit]
-> ([BuildFunction], [BuildFunction], [LinkedUnit])
rewriteBodies globals idx1 idx2 input = (bfsNormal, bfsCycleBreaker, input')
where
(bfs1, input') = unzip (map rewriteBlock input)
(bfsNormal, bfsCycleBreaker) = sortBuildFunctions (concat bfs1)
-- this index only contains the entries we actually want to dedupe
idx2' :: Map BS.ByteString (Int, [Text])
idx2' = M.filter (\(s, xs) -> dedupeBody (length xs) s) idx2
rewriteBlock :: (JStat, [ClosureInfo], [StaticInfo])
-> ([BuildFunction], LinkedUnit)
rewriteBlock (st, cis, sis) =
let (bfs, st') = rewriteFunctions st
-- remove the declarations for things that we just deduped
st'' = removeDecls (S.fromList $ map bfName bfs) st'
in (bfs, (st'', cis, sis))
removeDecls :: Set Text -> JStat -> JStat
removeDecls t (BlockStat ss) = BlockStat (map (removeDecls t) ss)
removeDecls t (DeclStat (TxtI i))
| i `S.member` t = mempty
removeDecls _ s = s
rewriteFunctions :: JStat -> ([BuildFunction], JStat)
rewriteFunctions (BlockStat ss) =
let (bfs, ss') = unzip (map rewriteFunctions ss)
in (concat bfs, BlockStat ss')
rewriteFunctions (AssignStat (ValExpr (JVar (TxtI i)))
(ValExpr (JFunc args st)))
| Just h <- M.lookup i idx1
, Just (_s, his) <- M.lookup h idx2' =
let (bf, st') = rewriteFunction i h his args st in ([bf], st')
rewriteFunctions x = ([], x)
rewriteFunction :: Text
-> BS.ByteString
-> [Text]
-> [Ident]
-> JStat
-> (BuildFunction, JStat)
rewriteFunction i h his args body
| i == iFirst = (bf, createFunction i idx g args body)
| otherwise = (bf, mempty)
where
bf :: BuildFunction
bf = BuildFunction i (buildFunId idx) g (length args)
g :: [Text]
g = findGlobals globals body
iFirst = head his
Just idx = M.lookupIndex h idx2'
createFunction :: Text
-> Int
-> [Text]
-> [Ident]
-> JStat
-> JStat
createFunction _i idx g args body =
DeclStat bi <>
AssignStat (ValExpr (JVar bi))
(ValExpr (JFunc bargs bbody))
where
ng = length g
bi = buildFunId idx
bargs :: [Ident]
bargs = map (TxtI . T.pack . ("h$$$g"++) . show) [1..ng]
bgm :: Map Text Ident
bgm = M.fromList (zip g bargs)
bbody :: JStat
bbody = ReturnStat (ValExpr $ JFunc args ibody)
ibody :: JStat
ibody = body & identsS %~ \ti@(TxtI i) -> fromMaybe ti (M.lookup i bgm)
renderBuildFunction :: BuildFunction -> JStat
renderBuildFunction (BuildFunction i bfid deps _nargs) =
DeclStat (TxtI i) <>
AssignStat (ValExpr (JVar (TxtI i)))
(ApplExpr (ValExpr (JVar bfid)) (map (ValExpr . JVar . TxtI) deps))
dedupeBody :: Int -> Int -> Bool
dedupeBody n size
| n < 2 = False
| size * n > 200 = True
| n > 6 = True
| otherwise = False
buildFunId :: Int -> Ident
buildFunId i = TxtI (T.pack $ "h$$$f" ++ show i)
-- result is ordered, does not contain duplicates
findGlobals :: Set Text -> JStat -> [Text]
findGlobals globals stat = nub'
(filter isGlobal . map (\(TxtI i) -> i) $ stat ^.. identsS)
where
locals = S.fromList (findLocals stat)
isGlobal i = i `S.member` globals && i `S.notMember` locals
findLocals :: JStat -> [Text]
findLocals (BlockStat ss) = concatMap findLocals ss
findLocals (DeclStat (TxtI i)) = [i]
findLocals _ = []
nub' :: Ord a => [a] -> [a]
nub' = go S.empty
where
go _ [] = []
go s (x:xs)
| x `S.member` s = go s xs
| otherwise = x : go (S.insert x s) xs
data HashIdx = HashIdx (Map Text Hash) (Map Hash Text)
dedupe :: [Text]
-> [(JStat, [ClosureInfo], [StaticInfo])]
-> [(JStat, [ClosureInfo], [StaticInfo])]
dedupe rtsDeps input
-- | dumpHashIdx idx
=
map (\(st,cis,sis) -> dedupeBlock idx st cis sis) input
where
idx = HashIdx hashes hr
hashes0 = buildHashes rtsDeps input
hashes = foldl' (flip M.delete) hashes0 rtsDeps
hr = fmap pickShortest
(M.fromListWith (++) $
map (\(i, h) -> (h, [i])) (M.toList hashes))
pickShortest :: [Text] -> Text
pickShortest = minimumBy (compare `on` T.length)
dedupeBlock :: HashIdx
-> JStat
-> [ClosureInfo]
-> [StaticInfo]
-> LinkedUnit
dedupeBlock hi st ci si =
( dedupeStat hi st
, mapMaybe (dedupeClosureInfo hi) ci
, mapMaybe (dedupeStaticInfo hi) si
)
dedupeStat :: HashIdx -> JStat -> JStat
dedupeStat hi st = go st
where
go (BlockStat ss) = BlockStat (map go ss)
go s@(DeclStat (TxtI i))
| not (isCanon hi i) = mempty
| otherwise = s
go (AssignStat v@(ValExpr (JVar (TxtI i))) e)
| not (isCanon hi i) = mempty
| otherwise = AssignStat v (e & identsE %~ toCanonI hi)
-- rewrite identifiers in e
go s = s & identsS %~ toCanonI hi
dedupeClosureInfo :: HashIdx -> ClosureInfo -> Maybe ClosureInfo
dedupeClosureInfo hi (ClosureInfo i rs n l ty st)
| isCanon hi i = Just (ClosureInfo i rs n l ty (dedupeCIStatic hi st))
dedupeClosureInfo _ _ = Nothing
dedupeStaticInfo :: HashIdx -> StaticInfo -> Maybe StaticInfo
dedupeStaticInfo hi (StaticInfo i val ccs)
| isCanon hi i = Just (StaticInfo i (dedupeStaticVal hi val) ccs)
dedupeStaticInfo _ _ = Nothing
dedupeCIStatic :: HashIdx -> CIStatic -> CIStatic
dedupeCIStatic hi (CIStaticRefs refs) = CIStaticRefs (nub $ map (toCanon hi) refs)
dedupeStaticVal :: HashIdx -> StaticVal -> StaticVal
dedupeStaticVal hi (StaticFun t args) =
StaticFun (toCanon hi t) (map (dedupeStaticArg hi) args)
dedupeStaticVal hi (StaticThunk (Just (o, args))) =
StaticThunk (Just (toCanon hi o, map (dedupeStaticArg hi) args))
dedupeStaticVal hi (StaticData dcon args) =
StaticData (toCanon hi dcon) (map (dedupeStaticArg hi) args)
dedupeStaticVal hi (StaticList args lt) =
StaticList (map (dedupeStaticArg hi) args) (fmap (toCanon hi) lt)
dedupeStaticVal _ v = v -- unboxed value or thunk with alt init, no rewrite needed
dedupeStaticArg :: HashIdx -> StaticArg -> StaticArg
dedupeStaticArg hi (StaticObjArg o)
= StaticObjArg (toCanon hi o)
dedupeStaticArg hi (StaticConArg c args)
= StaticConArg (toCanon hi c)
(map (dedupeStaticArg hi) args)
dedupeStaticArg _hi a@StaticLitArg{} = a
isCanon :: HashIdx -> Text -> Bool
isCanon (HashIdx a b) t
| Nothing <- la = True
| Just h <- la
, Just t' <- M.lookup h b = t == t'
| otherwise = False
where la = M.lookup t a
toCanon :: HashIdx -> Text -> Text
toCanon (HashIdx a b) t
| Just h <- M.lookup t a
, Just t' <- M.lookup h b = t'
| otherwise = t
toCanonI :: HashIdx -> Ident -> Ident
toCanonI hi (TxtI x) = TxtI (toCanon hi x)
type Hash = (BS.ByteString, [Text])
data HashBuilder = HashBuilder !BB.Builder ![Text]
instance Monoid HashBuilder where
mempty = HashBuilder mempty mempty
instance Semigroup HashBuilder where
(<>) (HashBuilder b1 l1) (HashBuilder b2 l2) =
HashBuilder (b1 <> b2) (l1 <> l2)
{-
dumpHashIdx :: HashIdx -> Bool
dumpHashIdx hi@(HashIdx ma mb) =
let ks = M.keys ma
difCanon i = let i' = toCanon hi i
in if i == i' then Nothing else Just i'
writeHashIdx = do
putStrLn "writing hash idx"
T.writeFile "hashidx.txt"
(T.unlines . sort $ mapMaybe (\i -> fmap ((i <> " -> ") <>) (difCanon i)) ks)
putStrLn "writing full hash idx"
T.writeFile "hashIdxFull.txt"
(T.unlines . sort $ M.keys ma)
in unsafePerformIO writeHashIdx `seq` True
-}
-- debug thing
{-
dumpHashes' :: [(JStat, [ClosureInfo], [StaticInfo])] -> Bool
dumpHashes' input =
let hashes = buildHashes input
writeHashes = do
putStrLn "writing hashes"
BL.writeFile "hashes.json" (Aeson.encode $ dumpHashes hashes)
in unsafePerformIO writeHashes `seq` True
-}
buildHashes :: [Text] -> [LinkedUnit] -> Map Text Hash
buildHashes rtsDeps xss
-- - | dumpHashes0 hashes0
= fixHashes (fmap finalizeHash hashes0)
where
globals = foldl' (flip S.delete) (findAllGlobals xss) rtsDeps
hashes0 = (M.unions (map buildHashesBlock xss))
buildHashesBlock (st, cis, sis) =
let hdefs = hashDefinitions globals st
hcis = map hashClosureInfo cis
hsis = map hashStaticInfo (filter (not . ignoreStatic) sis)
in M.fromList (combineHashes hdefs hcis ++ hsis)
findAllGlobals :: [LinkedUnit] -> Set Text
findAllGlobals xss = S.fromList $ concatMap f xss
where
f (_, cis, sis) =
map (\(ClosureInfo i _ _ _ _ _) -> i) cis ++
map (\(StaticInfo i _ _) -> i) sis
fixHashes :: Map Text Hash -> Map Text Hash
fixHashes hashes = fmap (\(bs,h) -> (bs, map replaceHash h)) hashes
where
replaceHash h = fromMaybe h (M.lookup h finalHashes)
hashText bs = "h$$$" <> TE.decodeUtf8 (B16.encode bs)
sccs :: [[Text]]
sccs = map fromSCC $
G.stronglyConnComp (map (\(k, (_bs, deps)) -> (k, k, deps)) (M.toList hashes))
ks = M.keys hashes
invDeps = M.fromListWith (++) (concatMap mkInvDeps $ M.toList hashes)
mkInvDeps (k, (_, ds)) = map (,[k]) ds
finalHashes = fmap hashText (fixHashesIter 500 invDeps ks ks sccs hashes mempty)
fromSCC :: G.SCC a -> [a]
fromSCC (G.AcyclicSCC x) = [x]
fromSCC (G.CyclicSCC xs) = xs
fixHashesIter :: Int
-> Map Text [Text]
-> [Text]
-> [Text]
-> [[Text]]
-> Map Text Hash
-> Map Text BS.ByteString
-> Map Text BS.ByteString
fixHashesIter n invDeps allKeys checkKeys sccs hashes finalHashes
-- - | unsafePerformIO (putStrLn ("fixHashesIter: " ++ show n)) `seq` False = undefined
| n < 0 = finalHashes
| not (null newHashes) = fixHashesIter (n-1) invDeps allKeys checkKeys' sccs hashes
(M.union finalHashes $ M.fromList newHashes)
-- - | unsafePerformIO (putStrLn ("fixHashesIter killing cycles:\n" ++ show rootSCCs)) `seq` False = undefined
| not (null rootSCCs) = fixHashesIter n {- -1 -} invDeps allKeys allKeys sccs hashes
(M.union finalHashes (M.fromList $ concatMap hashRootSCC rootSCCs))
| otherwise = finalHashes
where
checkKeys' | length newHashes > (M.size hashes `div` 10) = allKeys
| otherwise = S.toList . S.fromList $ concatMap newHashDeps newHashes
newHashDeps (k, _) = fromMaybe [] (M.lookup k invDeps)
mkNewHash k | M.notMember k finalHashes
, Just (hb, htxt) <- M.lookup k hashes
, Just bs <- mapM (`M.lookup` finalHashes) htxt =
Just (k, makeFinalHash hb bs)
| otherwise = Nothing
newHashes :: [(Text, BS.ByteString)]
newHashes = mapMaybe mkNewHash checkKeys
rootSCCs :: [[Text]]
rootSCCs = filter isRootSCC sccs
isRootSCC :: [Text] -> Bool
isRootSCC scc = not (all (`M.member` finalHashes) scc) && all check scc
where
check n = let Just (_bs, out) = M.lookup n hashes
in all checkEdge out
checkEdge e = e `S.member` s || e `M.member` finalHashes
s = S.fromList scc
hashRootSCC :: [Text] -> [(Text,BS.ByteString)]
hashRootSCC scc
| any (`M.member` finalHashes) scc = Panic.panic "Gen2.Compactor.hashRootSCC: has finalized nodes"
| otherwise = map makeHash toHash
where
makeHash k = let Just (bs,deps) = M.lookup k hashes
luds = map lookupDep deps
in (k, makeFinalHash bs luds)
lookupDep :: Text -> BS.ByteString
lookupDep d
| Just b <- M.lookup d finalHashes = b
| Just i <- M.lookup d toHashIdx
= grpHash <> (TE.encodeUtf8 . T.pack . show $ i)
| otherwise
= Panic.panic $ "Gen2.Compactor.hashRootSCC: unknown key: " ++
T.unpack d
toHashIdx :: M.Map Text Integer
toHashIdx = M.fromList $ zip toHash [1..]
grpHash :: BS.ByteString
grpHash = BL.toStrict
. BB.toLazyByteString
$ mconcat (map (mkGrpHash . (hashes M.!)) toHash)
mkGrpHash (h, deps) =
let deps' = mapMaybe (`M.lookup` finalHashes) deps
in BB.byteString h <>
BB.int64LE (fromIntegral $ length deps') <>
mconcat (map BB.byteString deps')
toHash :: [Text]
toHash = sortBy (compare `on` (fst . (hashes M.!))) scc
makeFinalHash :: BS.ByteString -> [BS.ByteString] -> BS.ByteString
makeFinalHash b bs = SHA256.hash (mconcat (b:bs))
-- do not deduplicate thunks
ignoreStatic :: StaticInfo -> Bool
ignoreStatic (StaticInfo _ StaticThunk {} _) = True
ignoreStatic _ = False
-- combine hashes from x and y, leaving only those which have an entry in both
combineHashes :: [(Text, HashBuilder)]
-> [(Text, HashBuilder)]
-> [(Text, HashBuilder)]
combineHashes x y = M.toList $ M.intersectionWith (<>)
(M.fromList x)
(M.fromList y)
{-
dumpHashes0 :: Map Text HashBuilder -> Bool
dumpHashes0 hashes = unsafePerformIO writeHashes `seq` True
where
hashLine (n, HashBuilder bb txt) =
n <> " ->\n " <>
escapeBS (BB.toLazyByteString bb) <> "\n [" <> T.intercalate " " txt <> "]\n"
escapeBS :: BL.ByteString -> T.Text
escapeBS = T.pack . concatMap escapeCH . BL.unpack
escapeCH c | c < 32 || c > 127 = '\\' : show c
| c == 92 = "\\\\"
| otherwise = [chr (fromIntegral c)]
writeHashes = do
putStrLn "writing hashes0"
T.writeFile "hashes0.dump" (T.unlines $ map hashLine (M.toList hashes))
dumpHashes :: Map Text Hash -> Value
dumpHashes idx = toJSON iidx
where
iidx :: Map Text [(Text, [Text])]
iidx = M.fromListWith (++) $
map (\(t, (b, deps)) -> (TE.decodeUtf8 (B16.encode b), [(t,deps)])) (M.toList idx)
-}
ht :: Int8 -> HashBuilder
ht x = HashBuilder (BB.int8 x) []
hi :: Int -> HashBuilder
hi x = HashBuilder (BB.int64LE $ fromIntegral x) []
hi' :: (Show a, Integral a) => a -> HashBuilder
hi' x | x' > toInteger (maxBound :: Int64) || x' < toInteger (minBound :: Int64) =
Panic.panic $ "Gen2.Compactor.hi': integer out of range: " ++ show x
| otherwise = HashBuilder (BB.int64LE $ fromInteger x') []
where
x' = toInteger x
hd :: Double -> HashBuilder
hd d = HashBuilder (BB.doubleLE d) []
htxt :: Text -> HashBuilder
htxt x = HashBuilder (BB.int64LE (fromIntegral $ BS.length bs) <> BB.byteString bs) []
where
bs = TE.encodeUtf8 x
hobj :: Text -> HashBuilder
hobj x = HashBuilder (BB.int8 127) [x]
hb :: BS.ByteString -> HashBuilder
hb x = HashBuilder (BB.int64LE (fromIntegral $ BS.length x) <> BB.byteString x) []
hashDefinitions :: Set Text -> JStat -> [(Text, HashBuilder)]
hashDefinitions globals st =
let defs = findDefinitions st
in map (uncurry (hashSingleDefinition globals)) defs
findDefinitions :: JStat -> [(Ident, JExpr)]
findDefinitions (BlockStat ss) = concatMap findDefinitions ss
findDefinitions (AssignStat (ValExpr (JVar i)) e) = [(i,e)]
findDefinitions _ = []
hashSingleDefinition :: Set Text -> Ident -> JExpr -> (Text, HashBuilder)
hashSingleDefinition globals (TxtI i) expr = (i, ht 0 <> render st <> mconcat (map hobj globalRefs))
where
globalRefs = nub $ filter (`S.member` globals) (map (\(TxtI i) -> i) (expr ^.. identsE))
globalMap = M.fromList $ zip globalRefs (map (T.pack . ("h$$$global_"++) . show) [(1::Int)..])
expr' = expr & identsE %~ (\i@(TxtI t) -> maybe i TxtI (M.lookup t globalMap))
st = AssignStat (ValExpr (JVar (TxtI "dummy"))) expr'
render = htxt . TL.toStrict . displayT . renderPretty 0.8 150 . pretty
hashClosureInfo :: ClosureInfo -> (Text, HashBuilder)
hashClosureInfo (ClosureInfo civ cir _cin cil cit cis) =
(civ, ht 1 <> hashCIRegs cir <> hashCILayout cil <> hashCIType cit <> hashCIStatic cis)
hashStaticInfo :: StaticInfo -> (Text, HashBuilder)
hashStaticInfo (StaticInfo sivr sivl _sicc) =
(sivr, ht 2 <> hashStaticVal sivl)
hashCIType :: CIType -> HashBuilder
hashCIType (CIFun a r) = ht 1 <> hi a <> hi r
hashCIType CIThunk = ht 2
hashCIType (CICon c) = ht 3 <> hi c
hashCIType CIPap = ht 4
hashCIType CIBlackhole = ht 5
hashCIType CIStackFrame = ht 6
hashCIRegs :: CIRegs -> HashBuilder
hashCIRegs CIRegsUnknown = ht 1
hashCIRegs (CIRegs sk tys) = ht 2 <> hi sk <> hashList hashVT tys
hashCILayout :: CILayout -> HashBuilder
hashCILayout CILayoutVariable = ht 1
hashCILayout (CILayoutUnknown size) = ht 2 <> hi size
hashCILayout (CILayoutFixed n l) = ht 3 <> hi n <> hashList hashVT l
hashCIStatic :: CIStatic -> HashBuilder
hashCIStatic CIStaticRefs{} = mempty -- hashList hobj xs -- we get these from the code
hashList :: (a -> HashBuilder) -> [a] -> HashBuilder
hashList f xs = hi (length xs) <> mconcat (map f xs)
hashVT :: VarType -> HashBuilder
hashVT = hi . fromEnum
hashStaticVal :: StaticVal -> HashBuilder
hashStaticVal (StaticFun t args) = ht 1 <> hobj t <> hashList hashStaticArg args
hashStaticVal (StaticThunk mtn) = ht 2 <> hashMaybe htobj mtn
where
htobj (o, args) = hobj o <> hashList hashStaticArg args
hashStaticVal (StaticUnboxed su) = ht 3 <> hashStaticUnboxed su
hashStaticVal (StaticData dcon args) = ht 4 <> hobj dcon <> hashList hashStaticArg args
hashStaticVal (StaticList args lt) = ht 5 <> hashList hashStaticArg args <> hashMaybe hobj lt
hashMaybe :: (a -> HashBuilder) -> Maybe a -> HashBuilder
hashMaybe _ Nothing = ht 1
hashMaybe f (Just x) = ht 2 <> f x
hashStaticUnboxed :: StaticUnboxed -> HashBuilder
hashStaticUnboxed (StaticUnboxedBool b) = ht 1 <> hi (fromEnum b)
hashStaticUnboxed (StaticUnboxedInt iv) = ht 2 <> hi' iv
hashStaticUnboxed (StaticUnboxedDouble sd) = ht 3 <> hashSaneDouble sd
hashStaticUnboxed (StaticUnboxedString str) = ht 4 <> hb str
hashStaticUnboxed (StaticUnboxedStringOffset str) = ht 5 <> hb str
hashStaticArg :: StaticArg -> HashBuilder
hashStaticArg (StaticObjArg t) = ht 1 <> hobj t
hashStaticArg (StaticLitArg sl) = ht 2 <> hashStaticLit sl
hashStaticArg (StaticConArg cn args) = ht 3 <> hobj cn <> hashList hashStaticArg args
hashStaticLit :: StaticLit -> HashBuilder
hashStaticLit (BoolLit b) = ht 1 <> hi (fromEnum b)
hashStaticLit (IntLit iv) = ht 2 <> hi (fromIntegral iv)
hashStaticLit NullLit = ht 3
hashStaticLit (DoubleLit d) = ht 4 <> hashSaneDouble d
hashStaticLit (StringLit tt) = ht 5 <> htxt tt
hashStaticLit (BinLit bs) = ht 6 <> hb bs
hashStaticLit (LabelLit bb ln) = ht 7 <> hi (fromEnum bb) <> htxt ln
hashSaneDouble :: SaneDouble -> HashBuilder
hashSaneDouble (SaneDouble sd) = hd sd
finalizeHash :: HashBuilder -> Hash
finalizeHash (HashBuilder hb tt) =
let h = SHA256.hash (BL.toStrict $ BB.toLazyByteString hb)
in h `seq` (h, tt)
finalizeHash' :: HashBuilder -> (Int, BS.ByteString, [Text])
finalizeHash' (HashBuilder hb tt) =
let b = BL.toStrict (BB.toLazyByteString hb)
bl = BS.length b
h = SHA256.hash b
in h `seq` bl `seq` (bl, h, tt)
| ghcjs/ghcjs | src/Gen2/Compactor.hs | mit | 57,974 | 0 | 22 | 18,073 | 19,235 | 9,806 | 9,429 | -1 | -1 |
import Control.Monad.State
import System.Random
type GeneratorState = State StdGen
data Tree a =
Node a [Tree a]
deriving (Show)
vertexNumWithEqualValAndDegree :: Tree Int -> Int
vertexNumWithEqualValAndDegree tree =
let
func (Node a [])
| a == 0 = 1
| otherwise = 0
func (Node a childs)
| a == (length childs) = 1 + child_num
| otherwise = child_num
where
child_num = foldl (+) 0 $ map func childs
in
func tree
generateList :: Int -> Int -> Int -> Int -> GeneratorState [Int]
generateList lborder hborder lenLborder lenHborder = do
gen <- get
let
(listLen, newGen) = runState (randomInt lenLborder lenHborder) gen
generateList' :: Int -> GeneratorState [Int]
generateList' len = do
cgen <- get
case len of
0 -> return []
_ -> do
let
(x, newGen') = runState (randomInt lborder hborder) cgen
(xs, newGen'') = runState (generateList' $ len - 1) newGen'
put newGen''
return (x:xs)
(list, resGen) = runState (generateList' listLen) newGen
put resGen
return list
mapS :: (a -> GeneratorState b) -> [a] -> GeneratorState [b]
mapS f [] = do
return []
mapS f (x:xs) = do
gen <- get
let
(lhead, newGen) = runState (f x) gen
(ltail, newGen') = runState (mapS f xs) newGen
put newGen'
return $ lhead:ltail
generateTree :: Int -> Int -> Int -> Int -> Int -> GeneratorState (Tree Int)
generateTree lborder hborder childNumLborder childNumHborder heigth = do
gen <- get
let
(headVal, newGen) = runState (randomInt lborder hborder) gen
generateTree' :: Int -> Int -> GeneratorState (Tree Int)
generateTree' vertexVal heigth = do
cgen <- get
case heigth of
0 -> return (Node vertexVal [])
_ -> do
let
(list, newGen') = runState (generateList lborder hborder childNumLborder childNumHborder) cgen
(childTrees, newGen'') = runState (mapS (\c -> generateTree' c $ heigth - 1) list) newGen'
put newGen''
return (Node vertexVal childTrees)
(tree, resGen) = runState (generateTree' headVal heigth) newGen
put resGen
return tree
randomInt :: Int -> Int -> GeneratorState Int
randomInt lborder hborder = do
gen <- get
let (num, newGenerator) = randomR (lborder, hborder) gen
put newGenerator
return num
main = do
let
testTrees =
[
(Node 2 [(Node 1 [(Node 0 [])]), (Node 4 [])]),
(Node 3 [(Node 2 [(Node 0 []), (Node 1 [])]), (Node 2 [(Node 4 []), (Node 2 [(Node 1 []), (Node 0 [])])])]),
(evalState (generateTree 0 5 0 10 2) $ mkStdGen 0)
]
mapM_
(\tree -> do
let
res = "tree:\n" ++ (show tree) ++ "\n" ++ "vertex number: " ++
(show $ vertexNumWithEqualValAndDegree tree) ++ "\n"
putStrLn res
)
testTrees | agsh/hs3-lab | Baladurin Constantine (var 11)/lab3.hs | mit | 2,697 | 27 | 27 | 639 | 1,226 | 604 | 622 | 85 | 2 |
module Graphics.Urho3D.UI.Internal.CheckBox(
CheckBox
, checkBoxCntx
, sharedCheckBoxPtrCntx
, SharedCheckBox
) where
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Context as C
import qualified Language.C.Types as C
import Graphics.Urho3D.Container.Ptr
import qualified Data.Map as Map
data CheckBox
checkBoxCntx :: C.Context
checkBoxCntx = mempty {
C.ctxTypesTable = Map.fromList [
(C.TypeName "CheckBox", [t| CheckBox |])
]
}
sharedPtrImpl "CheckBox" | Teaspot-Studio/Urho3D-Haskell | src/Graphics/Urho3D/UI/Internal/CheckBox.hs | mit | 516 | 0 | 11 | 89 | 120 | 80 | 40 | -1 | -1 |
module Unison.PrettyTerminal where
import Unison.Util.Less (less)
import qualified Unison.Util.Pretty as P
import qualified Unison.Util.ColorText as CT
import qualified System.Console.Terminal.Size as Terminal
import Data.List (dropWhileEnd)
import Data.Char (isSpace)
stripSurroundingBlanks :: String -> String
stripSurroundingBlanks s = unlines (dropWhile isBlank . dropWhileEnd isBlank $ lines s) where
isBlank line = all isSpace line
-- like putPrettyLn' but prints a blank line before and after.
putPrettyLn :: P.Pretty CT.ColorText -> IO ()
putPrettyLn p | p == mempty = pure ()
putPrettyLn p = do
width <- getAvailableWidth
less . P.toANSI width $ P.border 2 p
putPrettyLnUnpaged :: P.Pretty CT.ColorText -> IO ()
putPrettyLnUnpaged p | p == mempty = pure ()
putPrettyLnUnpaged p = do
width <- getAvailableWidth
putStrLn . P.toANSI width $ P.border 2 p
putPrettyLn' :: P.Pretty CT.ColorText -> IO ()
putPrettyLn' p | p == mempty = pure ()
putPrettyLn' p = do
width <- getAvailableWidth
less $ P.toANSI width p
clearCurrentLine :: IO ()
clearCurrentLine = do
width <- getAvailableWidth
putStr "\r"
putStr $ replicate (P.widthToInt width) ' '
putStr "\r"
putPretty' :: P.Pretty CT.ColorText -> IO ()
putPretty' p = do
width <- getAvailableWidth
putStr $ P.toANSI width p
getAvailableWidth :: IO P.Width
getAvailableWidth =
maybe 80 (\s -> 100 `min` P.Width (Terminal.width s)) <$> Terminal.size
putPrettyNonempty :: P.Pretty P.ColorText -> IO ()
putPrettyNonempty msg = do
if msg == mempty then pure () else putPrettyLn msg
| unisonweb/platform | parser-typechecker/src/Unison/PrettyTerminal.hs | mit | 1,611 | 0 | 13 | 312 | 567 | 279 | 288 | 41 | 2 |
{-# LANGUAGE MultiWayIf #-}
module Data.Bitsplit.Calc
(deleteSplit, upsertSplit, deduct) where
import Data.Bitsplit.Types
import Data.Ratio
import Data.Natural
import Data.List (partition, genericLength)
import Data.Set (fromList, member)
import Debug.Trace
traceMessage :: (Show a) => String -> a -> a
traceMessage message item =
trace (message ++ ":\n" ++ show item) item
mkSplit' :: [(Address, Ratio Natural)] -> Maybe Split
mkSplit' split =
case mkSplit split of
(Left _) -> Nothing
(Right value) -> Just value
zero :: Num a => b -> a
zero _ = 0
subtractPos :: (Num a, Ord a) => a -> a -> ([a],a) -> ([a],a)
subtractPos toSub num (soFar, remaining) =
if | num == 0 -> (soFar, remaining)
| toSub > num -> (0:soFar, remaining + toSub - num)
| otherwise -> ((num - toSub):soFar, remaining)
-- no fear of number not between 0 and 1!
deduct :: (Show a, Integral a) => Ratio a -> [Ratio a] -> [Ratio a]
deduct amount [] = []
deduct 0 numbers = numbers
deduct 1 numbers = fmap zero numbers
deduct amount [number] = [number - amount]
deduct amount numbers =
let total = genericLength $ filter (> 0) numbers
toSub = amount / total
(result, remaining) = foldr (subtractPos toSub) ([],0) numbers
in if remaining == 0 then result
else deduct remaining result
deleteSplit :: Address -> Split -> Maybe Split
deleteSplit address split =
mkSplit' $ unsafeDeleteSplit address (unpackSplit split)
unsafeDeleteSplit :: Address -> [(Address, Ratio Natural)] -> [(Address, Ratio Natural)]
unsafeDeleteSplit address split =
let (match, rest) = partition ((== address) . fst) split
in if length match == 0 then split
else let [(_, amount)] = match
(addresses, amounts) = unzip rest
toAdd = amount / (genericLength amounts)
in zip addresses (fmap (+ toAdd) amounts)
upsertSplit :: Address -> Ratio Natural -> Split -> Maybe Split
upsertSplit addr amount split =
let unpacked = unpackSplit split
withoutAddr = unsafeDeleteSplit addr unpacked
amount = min amount 1
(addresses, amounts) = unzip withoutAddr
newSplits = zip (addr : addresses) (amount : deduct amount amounts)
in mkSplit' newSplits
| micmarsh/bitsplit-hs | src/Data/Bitsplit/Calc.hs | mit | 2,409 | 0 | 14 | 676 | 868 | 459 | 409 | 54 | 3 |
{-# LANGUAGE OverloadedStrings, RecordWildCards, ScopedTypeVariables #-}
module Expression where
import Text.Parsec hiding (many, (<|>))
import Control.Applicative
import Text.Parsec hiding (many, (<|>))
import Data.Functor.Identity (Identity)
import Data.Text (Text)
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
runParse :: ExprParser a -> String -> a
runParse parser inp =
case Text.Parsec.parse parser "" inp of
Left x -> error $ "parser failed: " ++ show x
Right xs -> xs
-- expression parsers
-- Fields are accessed with $NUM where NUM is an integer, starting at 1,
-- like awk.
data Expr = FieldNum Int -- access to DSV fields
| And Expr Expr
| Or Expr Expr
| Compare String Expr Expr
| StringChoice (M.Map String Expr) -- usually for css class selection
| LiteralExpr Literal -- used in the context of comparison
deriving (Eq, Show)
data Literal = LitString String | LitNumber Double
deriving (Eq, Show)
data TextChunk = PassThrough String | Interpolation String
deriving (Show, Eq)
data ComparableValue = ComparableNumber Double
| ComparableString Text
deriving (Ord, Eq, Show)
type ExprParser = ParsecT String () Identity
expr = do
stringChoice <|> (do
expr1 <- exprTerm
try (do symbol "&&"; expr2 <- expr; return $ And expr1 expr2)
<|> try (do symbol "||"; expr2 <- expr; return $ Or expr1 expr2)
<|> try (do op <- comparisonOp; expr2 <- expr; return $ Compare op expr1 expr2)
<|> return expr1)
stringChoice = do
char '{' >> spaces
pairs :: [(String, Expr)] <-
sepBy1 ((,) <$> varName <*> (char ':' >> spaces >> expr <* spaces))
(char ',' >> spaces)
spaces >> char '}' >> spaces
return $ StringChoice $ M.fromList pairs
symbol :: String -> ExprParser String
symbol s = spaces *> string s <* spaces
comparisonOp = choice $ map (try . symbol) [">=", "<=", "!=", "/=", "<>", ">", "<", "=="]
exprTerm :: ExprParser Expr
exprTerm = (char '(' *> expr <* char ')') <|> fieldNum <|> literalExpr
fieldNum :: ExprParser Expr
fieldNum = (FieldNum . read) <$> (char '$' *> many1 digit)
varName = many1 (alphaNum <|> char '$' <|> char '_')
literalExpr = LiteralExpr <$> (litNumber <|> litString)
-- https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/parsing-floats-with-parsec
------------------------------------------------------------------------
(<++>) a b = (++) <$> a <*> b
(<:>) a b = (:) <$> a <*> b
number = many1 digit
plus = char '+' *> number
minus = char '-' <:> number
integer = plus <|> minus <|> number
float = fmap rd $ integer <++> decimal <++> exponent
where rd = read :: String -> Double
decimal = option "" $ char '.' <:> number
exponent = option "" $ oneOf "eE" <:> integer
------------------------------------------------------------------------
litNumber :: ExprParser Literal
litNumber = LitNumber <$> float
-- dumb simple implementation that does not deal with escaping
litString :: ExprParser Literal
litString = LitString <$> ((char '"' *> many (noneOf "\"") <* char '"') <|> (char '\'' *> many (noneOf "'") <* char '\''))
------------------------------------------------------------------------
-- free text interpolation
{-
interpolateValues :: ArrowXml a => Value -> a XmlTree XmlTree
interpolateValues context =
((changeText (interpolateText context)) `when` isText)
>>>
(processAttrl (changeAttrValue (interpolateText context)) `when` isElem)
interpolateText context = mconcat . map (evalText context) . parseText
-}
parseText :: String -> [TextChunk]
parseText = runParse (many textChunk)
textChunk :: ExprParser TextChunk
textChunk = interpolationChunk <|> passThroughChunk
interpolationChunk = do
try (string "{{")
spaces
xs <- manyTill anyChar (lookAhead $ try (string "}}"))
spaces
string "}}"
return $ Interpolation xs
passThroughChunk = PassThrough <$> passThrough
passThrough = do
-- a lead single { char. This is guaranteed not to be part of {{
t <- optionMaybe (string "{")
xs <- many1 (noneOf "{")
x <- (eof *> pure "{{") <|> lookAhead (try (string "{{") <|> string "{")
res <- case x of
"{{" -> return []
"{" -> ('{':) <$> passThrough
return $ (fromMaybe "" t) ++ xs ++ res
| danchoi/dsvt | Expression.hs | mit | 4,427 | 0 | 19 | 997 | 1,279 | 664 | 615 | 86 | 2 |
{-# LANGUAGE RankNTypes, FlexibleContexts #-}
{-# LANGUAGE TupleSections #-}
module Turnip.Eval.Util where
import Turnip.Eval.Types
import Control.Lens
import qualified Data.Map as Map (lookup, empty, lookupMax, split, findMin, notMember, null)
import Data.Map
import Control.Monad.Except (throwError)
getFunctionData :: FunctionRef -> LuaM FunctionData
getFunctionData ref = LuaMT $ do
fns <- use functions
case Map.lookup ref fns of
Just fdata -> return fdata
Nothing -> error "Function ref dead" -- should never really happen
getTableData :: TableRef -> LuaM TableData
getTableData ref = LuaMT $ do
ts <- use tables
case Map.lookup ref ts of
Just tdata -> return tdata
Nothing -> error "Function ref dead" -- should never really happen
uniqueFunctionRef :: LuaM FunctionRef
uniqueFunctionRef = LuaMT $ do
lastId += 1
FunctionRef <$> use lastId
uniqueTableRef :: LuaM TableRef
uniqueTableRef = LuaMT $ do
lastId += 1
TableRef <$> use lastId
coerceToBool :: [Value] -> Bool
coerceToBool (Boolean x:_) = x
coerceToBool (Nil:_) = False
coerceToBool (Number n:_) = not $ isNaN n
coerceToBool (_h:_) = True
coerceToBool _ = False
-- This function fills in the Nil for the missing Value
extractVal :: Maybe Value -> Value
extractVal Nothing = Nil
extractVal (Just v) = v
-- This was needed to shield Eval from seeing into the LuaM insides
getGlobalTableRef :: LuaM TableRef
getGlobalTableRef = LuaMT $ use gRef
setGlobal :: Value -> Value -> LuaM ()
setGlobal k v = LuaMT $ do
gTabRef <- use gRef
tables . at gTabRef . traversed . mapData . at k .= Just v
createNativeFunction :: FunctionData -> LuaM FunctionRef
createNativeFunction fdata = do
newRef <- uniqueFunctionRef
LuaMT $ functions . at newRef .= Just fdata
return newRef
addNativeFunction :: String -> FunctionData -> LuaM FunctionRef
addNativeFunction name fdata = do
newRef <- createNativeFunction fdata
setGlobal (Str name) (Function newRef)
return newRef
addNativeModule :: String -> [(String, FunctionData)] -> LuaM ()
addNativeModule modName funs = do
tr <- makeNewTable
funs' <- mapM (\(n, fd) -> createNativeFunction fd >>= \f -> return (Str n, Function f)) funs
mapM_ (setTableField tr) funs'
setGlobal (Str modName) (Table tr)
makeNewTableWith :: TableMapData -> LuaM TableRef
makeNewTableWith initial = do
newRef <- uniqueTableRef
LuaMT $ do
tables . at newRef .= Just (TableData initial Nothing)
return newRef
makeNewTable :: LuaM TableRef
makeNewTable = makeNewTableWith Map.empty
-- this is very similar to makeNewTable, just operates on functions
makeNewLambda :: FunctionData -> LuaM FunctionRef
makeNewLambda f = do
newRef <- uniqueFunctionRef
LuaMT $ do
functions . at newRef .= Just f
return newRef
setTableField :: TableRef -> (Value, Value) -> LuaM ()
setTableField _ (Nil, _) = throwErrorStr "Table index is nil"
setTableField tr (k,v) = LuaMT $ tables . at tr . traversed . mapData %= insert k v
rawGetTableField :: TableRef -> Value -> LuaM (Maybe Value)
rawGetTableField tr k = (^. mapData . at k) <$> getTableData tr
getTableField :: TableRef -> Value -> LuaM Value
getTableField tr k = maybe Nil id <$> rawGetTableField tr k
getFirstTableField :: TableRef -> LuaM (Value, Value)
getFirstTableField tr = do
md <- (^. mapData) <$> getTableData tr
if Map.null md
then return (Nil, Nil)
else return (Map.findMin md)
-- This is a Maybe Value because Nil is a legitimate result, while
-- Nothing means that the passed key doesn't exist and errors out;
-- this mirrors the behavior of the original next.
getNextTableField :: TableRef -> Value -> LuaM (Maybe (Value, Value))
getNextTableField tr k = do
md <- (^. mapData) <$> getTableData tr
if Map.notMember k md then
return Nothing
else
let (_, right) = Map.split k md in
return . Just $ if Map.null right
then (Nil, Nil)
else Map.findMin right
getTableLength :: TableRef -> LuaM Value
getTableLength tr = do
(TableData td _) <- getTableData tr
case Map.lookupMax td of
Just (Number x, _) -> return $ Number x
_ -> return $ Number 0
throwErrorStr :: String -> LuaM a
throwErrorStr = throwError . Str
-- |This function is currently not doing anything over regular throwError.
-- In the future, however, it should be used to report critical vm errors (such as totality problems etc.)
vmErrorStr :: String -> LuaM a
vmErrorStr = throwErrorStr
| bananu7/Turnip | src/Turnip/Eval/Util.hs | mit | 4,562 | 0 | 15 | 984 | 1,408 | 697 | 711 | -1 | -1 |
module Day13 where
import Data.List
type Feelings = [(String, String, Int)]
parse :: String -> Feelings
parse = map (go . words . init) . lines
where go :: [String] -> (String, String, Int)
go [name, _, "lose", num, _, _, _, _, _, _, to] = (name, to, (- readInt num))
go [name, _, "gain", num, _, _, _, _, _, _, to] = (name, to, readInt num )
go x@_ = error $ "no parse: " ++ concat x
readInt :: String -> Int
readInt = read
getHappiness :: String -> String -> Feelings -> Int
getHappiness x y feels =
case find (\(a,b,_) -> x == a && y == b) feels of
Just (a,b,i) -> i
Nothing -> error $ "no parse: " ++ x ++ '|':y
happiness :: Feelings -> [String] -> Int
happiness feels (x:xs) = doubleHappiness x (last xs) feels + go feels (x:xs)
where go :: Feelings -> [String] -> Int
go feels [y] = 0
go feels (x:y:xs) = doubleHappiness x y feels + go feels (y:xs)
doubleHappiness n1 n2 feels = feel1 + feel2
where feel1 = getHappiness n1 n2 feels
feel2 = getHappiness n2 n1 feels
part1 :: IO ()
part1 = do
txt <- readFile "lib/day13-input.txt"
let feels = parse txt
(p,_,_) = unzip3 feels
people = nub p
positions = permutations people
rating = maximum . map (happiness feels) $ positions
print rating
createMyself :: [String] -> [(String, String, Int)]
createMyself [] = []
createMyself (x:xs) = ("Me", x, 0):(x,"Me", 0) : createMyself xs
part2 :: IO ()
part2 = do
txt <- readFile "lib/day13-input.txt"
let feels = parse txt
(p,_,_) = unzip3 feels
people = nub p
feels' = createMyself people ++ feels
people' = "Me":people
positions = permutations people'
rating = maximum . map (happiness feels') $ positions
print rating | cirquit/Personal-Repository | Haskell/Playground/AdventOfCode/advent-coding/src/Day13.hs | mit | 1,893 | 1 | 15 | 583 | 813 | 439 | 374 | 47 | 3 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.Headers
(append, delete, get, get_, getUnsafe, getUnchecked, has, has_,
set, Headers(..), gTypeHeaders)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Headers.append Mozilla Headers.append documentation>
append ::
(MonadDOM m, ToJSString name, ToJSString value) =>
Headers -> name -> value -> m ()
append self name value
= liftDOM
(void (self ^. jsf "append" [toJSVal name, toJSVal value]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Headers.delete Mozilla Headers.delete documentation>
delete :: (MonadDOM m, ToJSString name) => Headers -> name -> m ()
delete self name
= liftDOM (void (self ^. jsf "delete" [toJSVal name]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Headers.get Mozilla Headers.get documentation>
get ::
(MonadDOM m, ToJSString name, FromJSString result) =>
Headers -> name -> m (Maybe result)
get self name
= liftDOM
((self ^. jsf "get" [toJSVal name]) >>= fromMaybeJSString)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Headers.get Mozilla Headers.get documentation>
get_ :: (MonadDOM m, ToJSString name) => Headers -> name -> m ()
get_ self name = liftDOM (void (self ^. jsf "get" [toJSVal name]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Headers.get Mozilla Headers.get documentation>
getUnsafe ::
(MonadDOM m, ToJSString name, HasCallStack, FromJSString result) =>
Headers -> name -> m result
getUnsafe self name
= liftDOM
(((self ^. jsf "get" [toJSVal name]) >>= fromMaybeJSString) >>=
maybe (Prelude.error "Nothing to return") return)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Headers.get Mozilla Headers.get documentation>
getUnchecked ::
(MonadDOM m, ToJSString name, FromJSString result) =>
Headers -> name -> m result
getUnchecked self name
= liftDOM
((self ^. jsf "get" [toJSVal name]) >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Headers.has Mozilla Headers.has documentation>
has :: (MonadDOM m, ToJSString name) => Headers -> name -> m Bool
has self name
= liftDOM ((self ^. jsf "has" [toJSVal name]) >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Headers.has Mozilla Headers.has documentation>
has_ :: (MonadDOM m, ToJSString name) => Headers -> name -> m ()
has_ self name = liftDOM (void (self ^. jsf "has" [toJSVal name]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Headers.set Mozilla Headers.set documentation>
set ::
(MonadDOM m, ToJSString name, ToJSString value) =>
Headers -> name -> value -> m ()
set self name value
= liftDOM (void (self ^. jsf "set" [toJSVal name, toJSVal value]))
| ghcjs/jsaddle-dom | src/JSDOM/Generated/Headers.hs | mit | 3,683 | 0 | 14 | 595 | 1,038 | 580 | 458 | -1 | -1 |
{-|
Module : Database.Orville.PostgreSQL.Internal.QueryKey
Copyright : Flipstone Technology Partners 2016-2018
License : MIT
-}
{-# LANGUAGE CPP #-}
module Database.Orville.PostgreSQL.Internal.QueryKey where
import Database.Orville.PostgreSQL.Internal.MappendCompat ((<>))
import Data.Time.LocalTime
import Database.HDBC
data QueryKey
= QKValue OrdSqlValue
| QKField String
| QKTable String
| QKOp String
QueryKey
| QKList [QueryKey]
| QKEmpty
deriving (Eq, Ord)
#if MIN_VERSION_base(4,11,0)
instance Semigroup QueryKey where
(<>) = appendQueryKeys
#endif
instance Monoid QueryKey where
mempty = QKEmpty
mappend = appendQueryKeys
mconcat = QKList
appendQueryKeys :: QueryKey -> QueryKey -> QueryKey
appendQueryKeys a b = QKList [a, b]
class QueryKeyable a where
queryKey :: a -> QueryKey
instance QueryKeyable QueryKey where
queryKey = id
instance QueryKeyable a => QueryKeyable [a] where
queryKey = foldMap queryKey
instance QueryKeyable a => QueryKeyable (Maybe a) where
queryKey = foldMap queryKey
instance QueryKeyable SqlValue where
queryKey = QKValue . OrdSqlValue
qkOp :: (QueryKeyable a) => String -> a -> QueryKey
qkOp op a = QKOp op $ queryKey a
qkOp2 :: (QueryKeyable a, QueryKeyable b) => String -> a -> b -> QueryKey
qkOp2 op a b = QKOp op $ QKList [queryKey a, queryKey b]
newtype OrdSqlValue =
OrdSqlValue SqlValue
instance Ord OrdSqlValue where
compare (OrdSqlValue s) (OrdSqlValue s') = compareSqlValue s s'
instance Eq OrdSqlValue where
a == b = compare a b == EQ
compareSqlValue :: SqlValue -> SqlValue -> Ordering
compareSqlValue (SqlString v) (SqlString v') = compare v v'
compareSqlValue (SqlString _) _ = LT
compareSqlValue _ (SqlString _) = GT
compareSqlValue (SqlByteString v) (SqlByteString v') = compare v v'
compareSqlValue (SqlByteString _) _ = LT
compareSqlValue _ (SqlByteString _) = GT
compareSqlValue (SqlWord32 v) (SqlWord32 v') = compare v v'
compareSqlValue (SqlWord32 _) _ = LT
compareSqlValue _ (SqlWord32 _) = GT
compareSqlValue (SqlWord64 v) (SqlWord64 v') = compare v v'
compareSqlValue (SqlWord64 _) _ = LT
compareSqlValue _ (SqlWord64 _) = GT
compareSqlValue (SqlInt32 v) (SqlInt32 v') = compare v v'
compareSqlValue (SqlInt32 _) _ = LT
compareSqlValue _ (SqlInt32 _) = GT
compareSqlValue (SqlInt64 v) (SqlInt64 v') = compare v v'
compareSqlValue (SqlInt64 _) _ = LT
compareSqlValue _ (SqlInt64 _) = GT
compareSqlValue (SqlInteger v) (SqlInteger v') = compare v v'
compareSqlValue (SqlInteger _) _ = LT
compareSqlValue _ (SqlInteger _) = GT
compareSqlValue (SqlChar v) (SqlChar v') = compare v v'
compareSqlValue (SqlChar _) _ = LT
compareSqlValue _ (SqlChar _) = GT
compareSqlValue (SqlBool v) (SqlBool v') = compare v v'
compareSqlValue (SqlBool _) _ = LT
compareSqlValue _ (SqlBool _) = GT
compareSqlValue (SqlDouble v) (SqlDouble v') = compare v v'
compareSqlValue (SqlDouble _) _ = LT
compareSqlValue _ (SqlDouble _) = GT
compareSqlValue (SqlRational v) (SqlRational v') = compare v v'
compareSqlValue (SqlRational _) _ = LT
compareSqlValue _ (SqlRational _) = GT
compareSqlValue (SqlLocalDate v) (SqlLocalDate v') = compare v v'
compareSqlValue (SqlLocalDate _) _ = LT
compareSqlValue _ (SqlLocalDate _) = GT
compareSqlValue (SqlLocalTimeOfDay v) (SqlLocalTimeOfDay v') = compare v v'
compareSqlValue (SqlLocalTimeOfDay _) _ = LT
compareSqlValue _ (SqlLocalTimeOfDay _) = GT
compareSqlValue (SqlZonedLocalTimeOfDay v z) (SqlZonedLocalTimeOfDay v' z') =
compare v v' <> compare z z'
compareSqlValue (SqlZonedLocalTimeOfDay _ _) _ = LT
compareSqlValue _ (SqlZonedLocalTimeOfDay _ _) = GT
compareSqlValue (SqlLocalTime v) (SqlLocalTime v') = compare v v'
compareSqlValue (SqlLocalTime _) _ = LT
compareSqlValue _ (SqlLocalTime _) = GT
compareSqlValue (SqlZonedTime (ZonedTime v z)) (SqlZonedTime (ZonedTime v' z')) =
compare v v' <> compare z z'
compareSqlValue (SqlZonedTime _) _ = LT
compareSqlValue _ (SqlZonedTime _) = GT
compareSqlValue (SqlUTCTime v) (SqlUTCTime v') = compare v v'
compareSqlValue (SqlUTCTime _) _ = LT
compareSqlValue _ (SqlUTCTime _) = GT
compareSqlValue (SqlDiffTime v) (SqlDiffTime v') = compare v v'
compareSqlValue (SqlDiffTime _) _ = LT
compareSqlValue _ (SqlDiffTime _) = GT
compareSqlValue (SqlPOSIXTime v) (SqlPOSIXTime v') = compare v v'
compareSqlValue (SqlPOSIXTime _) _ = LT
compareSqlValue _ (SqlPOSIXTime _) = GT
compareSqlValue (SqlEpochTime v) (SqlEpochTime v') = compare v v'
compareSqlValue (SqlEpochTime _) _ = LT
compareSqlValue _ (SqlEpochTime _) = GT
compareSqlValue (SqlTimeDiff v) (SqlTimeDiff v') = compare v v'
compareSqlValue (SqlTimeDiff _) _ = LT
compareSqlValue _ (SqlTimeDiff _) = GT
compareSqlValue SqlNull SqlNull = EQ
| flipstone/orville | orville-postgresql/src/Database/Orville/PostgreSQL/Internal/QueryKey.hs | mit | 4,695 | 0 | 9 | 754 | 1,743 | 878 | 865 | 107 | 1 |
-- |
-- Module : Elrond.Client
-- Description :
-- Copyright : (c) Jonatan H Sundqvist, 2015
-- License : MIT
-- Maintainer : Jonatan H Sundqvist
-- Stability : experimental|stable
-- Portability : POSIX (not sure)
--
-- Created December 22 2015
-- TODO | -
-- -
-- SPEC | -
-- -
--------------------------------------------------------------------------------------------------------------------------------------------
-- GHC Pragmas
--------------------------------------------------------------------------------------------------------------------------------------------
-- {-# LANGUAGE OverloadedStrings #-}
-- {-# LANGUAGE ViewPatterns #-}
--------------------------------------------------------------------------------------------------------------------------------------------
-- API
--------------------------------------------------------------------------------------------------------------------------------------------
module Elrond.Client where
--------------------------------------------------------------------------------------------------------------------------------------------
-- We'll need these
--------------------------------------------------------------------------------------------------------------------------------------------
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Char8 as C
import Text.Printf
import Control.Monad
import Control.Concurrent
import Network.HTTP.Client
import Network.HTTP.Types.Status (statusCode)
import Elrond.Core.Types
--------------------------------------------------------------------------------------------------------------------------------------------
-- Functions
--------------------------------------------------------------------------------------------------------------------------------------------
-- |
start :: IO ()
start = do
manager <- newManager defaultManagerSettings
request <- parseUrl "http://192.168.1.88:8000/flic.html"
forM [(1::Int)..5] $ \n -> do
printf "\n\n---- %s %d %s\n\n" "Request" n (replicate 60 '-')
response <- httpLbs request manager
printf "The status code was '%s'.\n" (show . statusCode $ responseStatus response)
printf "The response body was '%s'.\n" (C.unpack $ responseBody response)
threadDelay $ round (2.5 * 10^6)
return ()
| SwiftsNamesake/Elrond | src/Elrond/Client.hs | mit | 2,363 | 0 | 15 | 262 | 257 | 149 | 108 | 20 | 1 |
{-|
Module : CatNPlus.App
Description : Application entrypoint for catnplus
Copyright : (C) Richard Cook, 2017
Licence : MIT
Maintainer : rcook@rcook.org
Stability : experimental
Portability : portable
-}
module CatNPlus.App (runApp) where
import CatNPlus.KeyPress
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Either
import qualified System.Console.ANSI as ANSI
import qualified System.Console.Terminal.Size as TS
import System.Directory
import System.IO
import Text.Printf
withSGR :: [ANSI.SGR] -> IO a -> IO a
withSGR sgrs = bracket_
(ANSI.setSGR sgrs)
(ANSI.setSGR [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.White])
withSGRCond :: Bool -> [ANSI.SGR] -> IO a -> IO a
withSGRCond True sgrs action = withSGR sgrs action
withSGRCond False _ action = action
getPageLength :: IO Int
getPageLength = do
mbWindow <- TS.size
case mbWindow of
Nothing -> return 20
Just (TS.Window h _) -> return $ h - 2
runApp :: [FilePath] -> IO ()
runApp paths = do
pageLength <- getPageLength
isTerminal <- hIsTerminalDevice stdout
void $ runEitherT $ forM_ paths $ \p -> do
content <- liftIO $ do
path <- canonicalizePath p
withSGRCond isTerminal [ANSI.SetColor ANSI.Foreground ANSI.Dull ANSI.Green] $
putStrLn path
readFile path
runEitherT $ forM_ (zip [1..] (lines content)) $ \(n, line) -> do
liftIO $ do
withSGRCond isTerminal [ANSI.SetColor ANSI.Foreground ANSI.Vivid ANSI.Yellow] $
putStr (printf "%6d" n)
putStrLn $ " " ++ line
when (isTerminal && n `mod` pageLength == 0) $ do
shouldContinue <- liftIO $ do
c <- waitForKeyPressOneOf ['Q', 'q', ' ']
return $ c /= 'Q' && c/= 'q'
when (not shouldContinue) $ lift $ left ()
| rcook/catnplus | src/CatNPlus/App.hs | mit | 2,076 | 0 | 25 | 622 | 602 | 305 | 297 | 45 | 2 |
module Data.CTG1371.Encoder ( encodeCTG
, CTGData(..)
, CTGStatus(..)
, SignalQuality(..)
, FetalMovement(..)
, HR(..)
, HR1(..)
, HR2(..)
, MHR(..)
, TOCO(..)
, HRMode(..)
, MHRMode (..)
, TOCOMode(..)
) where
import Data.CTG1371.Internal.Types
import Data.CTG1371.Internal.Encoder.Encoders
import qualified Data.ByteString.Lazy as BL
import qualified Data.Binary.Put as P
-- | Provides mechanism for encoding an instance of CTGData into a ByteString
encodeCTG :: CTGData -> BL.ByteString
encodeCTG ctgData = P.runPut (buildCTGByteString ctgData)
| danplubell/CTG1371 | library/Data/CTG1371/Encoder.hs | mit | 918 | 0 | 7 | 439 | 160 | 109 | 51 | 19 | 1 |
module Class2 where
data String
data Bool = True | False
class Show a where
show :: a -> String
instance Show Bool
false x = show False
falseFn x = show (x False)
show' x = show x
| Lemmih/haskell-tc | tests/Class2.hs | mit | 188 | 0 | 7 | 47 | 81 | 41 | 40 | -1 | -1 |
module Kind
where
import Data.Maybe (isNothing, fromJust)
import Types
import Utils
maxNumChildren :: Kind a -> Int
maxNumChildren (ArrayFold _ _ c) = length c
maxNumChildren (Bind _ _ _ _) = 2
maxNumChildren (Const _) = 0
maxNumChildren (Freeze _ _ _) = 1
maxNumChildren Invalid = 0
maxNumChildren Uninitialized = 0
maxNumChildren (Variable _ _ _) = 0
maxNumChildren (Map _ _) = 1
maxNumChildren (Map2 _ _ _) = 2
maxNumChildren (Map3 _ _ _ _) = 3
maxNumChildren (Map4 _ _ _ _ _) = 4
-- | 'slowGetChild' fetch the child at the given index.
slowGetChild :: (Eq a) => Kind a -> Index -> Maybe PackedNode
slowGetChild k index = if index < maxNumChildren k
then Just $ (iteriChildren k (\_ n -> n)) !! index
else Nothing
-- | 'iteriChildren' iterate all the child node
iteriChildren :: (Eq a) => Kind a -> (Index -> PackedNode -> b) -> [b]
iteriChildren (ArrayFold _ _ children) g = map (\(i, c) -> g i (pack c)) (zip [0..] children)
iteriChildren (Freeze _ child _) g = [ g 0 (pack child) ]
iteriChildren (Map _ b) g = [ g 0 (pack b) ]
iteriChildren (Map2 _ b c) g = [ g 0 (pack b), g 1 (pack c) ]
iteriChildren (Map3 _ b c d) g = [ g 0 (pack b), g 1 (pack c), g 2 (pack d) ]
iteriChildren (Map4 _ b c d e) g = [ g 0 (pack b), g 1 (pack c), g 2 (pack d)
, g 3 (pack e) ]
iteriChildren (Bind _ lhs rhs _) g = let l = g 0 (pack lhs)
in if (isNothing rhs)
then [l]
else l:[g 1 (pack $ fromJust rhs)]
iteriChildren _ _ = []
freeze_child_index :: Index
freeze_child_index = 0
isFreeze :: Kind a -> Bool
isFreeze (Freeze _ _ _) = True
isFreeze _ = False
| JenniferWang/incremental-haskell | src/Kind.hs | mit | 1,930 | 0 | 13 | 708 | 800 | 410 | 390 | 38 | 2 |
power2 :: Num a => [a] -> [a]
power2 [] = []
power2 (x:xs) = (x^2):power2 xs
-- let geopro n = last $ take n (iterate (*2) 1)
apply :: (a -> a) -> Int -> a -> a
apply f 0 x = x
apply f n x = apply f (n - 1) (f x)
geopro n = \n -> apply (*2) (n-1) 1
insert :: Ord a => a -> [a] -> [a]
insert x [] = [x]
insert x (y:ys) | x < y = x:y:ys
| otherwise = y:insert x ys
isort :: Ord a => [a] -> [a]
isort xs = foldr insert [] xs
skip :: Eq a => a -> [a] -> [a]
skip x [] = [x]
skip x (y:ys) | x == y = (y:ys)
| otherwise = x:y:ys
compress :: Eq a => [a] -> [a]
compress = foldr skip []
snoc :: Int -> [Int] -> [Int]
snoc x = foldr (:) [x] | dalonng/hellos | haskell.hello/higherOrderFunction.hs | gpl-2.0 | 661 | 2 | 8 | 195 | 462 | 240 | 222 | 21 | 1 |
{-# OPTIONS_HADDOCK ignore-exports #-}
-- |This module provides methods to build a cyclic half-edge data structure
-- from an already parsed obj mesh file. As such, it depends on details
-- of the parsed data.
--
-- In particular, 'indirectHeFaces', 'indirectHeVerts' and 'indirectToDirect'
-- assume specific structure of some input lists. Check their respective
-- documentation.
--
-- As the data structure has a lot of cross-references and the knots are
-- not really known at compile-time, we have to use helper data structures
-- such as lists and maps under the hood and tie the knots through
-- index lookups.
--
-- For an explanation of the abstract concept of the half-edge data structure,
-- check <http://www.flipcode.com/archives/The_Half-Edge_Data_Structure.shtml>
module Graphics.HalfEdge (
HeVert(..)
, HeFace(..)
, HeEdge(..)
, buildHeEdge
, buildHeEdgeFromStr
) where
import Algebra.Vector
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as B
import qualified Data.IntMap.Lazy as Map
import Data.Maybe
import Parser.Meshparser
import Safe
-- |The vertex data structure for the half-edge.
data HeVert a = HeVert {
vcoord :: a -- the coordinates of the vertex
, emedge :: HeEdge a -- one of the half-edges emanating from the vertex
} | NoVert
-- |The face data structure for the half-edge.
data HeFace a = HeFace {
bordedge :: HeEdge a -- one of the half-edges bordering the face
} | NoFace
-- |The actual half-edge data structure.
data HeEdge a = HeEdge {
startvert :: HeVert a -- start-vertex of the half-edge
, oppedge :: HeEdge a -- oppositely oriented adjacent half-edge
, edgeface :: HeFace a -- face the half-edge borders
, nextedge :: HeEdge a -- next half-edge around the face
} | NoEdge
-- This is a helper data structure of half-edge edges
-- for tying the knots in 'indirectToDirect'.
data IndirectHeEdge = IndirectHeEdge {
edgeindex :: Int -- edge index
, svindex :: Int -- index of start-vertice
, nvindex :: Int -- index of next-vertice
, indexf :: Int -- index of face
, offsetedge :: Int -- offset to get the next edge
} deriving (Show)
-- This is a helper data structure of half-edge vertices
-- for tying the knots in 'indirectToDirect'.
data IndirectHeVert = IndirectHeVert {
emedgeindex :: Int -- emanating edge index (starts at 1)
, edgelist :: [Int] -- index of edge that points to this vertice
} deriving (Show)
-- This is a helper data structure of half-edge faces
-- for tying the knots in 'indirectToDirect'.
data IndirectHeFace =
IndirectHeFace (Int, [Int]) -- (faceIndex, [verticeindex])
deriving (Show)
-- |Construct the indirect data structure for half-edge faces.
-- This function assumes that the input faces are parsed exactly like so:
--
-- @
-- f 1 3 4 5
-- f 4 6 1 3
-- @
--
-- becomes
--
-- > [[1,3,4,5],[4,6,1,3]]
indirectHeFaces :: [[Int]] -- ^ list of faces with their respective
-- list of vertice-indices
-> [IndirectHeFace]
indirectHeFaces = fmap IndirectHeFace . zip [0..]
-- |Construct the indirect data structure for half-edge edges.
indirectHeEdges :: [IndirectHeFace] -> [IndirectHeEdge]
indirectHeEdges = concat . fmap indirectHeEdge
where
indirectHeEdge :: IndirectHeFace -> [IndirectHeEdge]
indirectHeEdge (IndirectHeFace (_, [])) = []
indirectHeEdge p@(IndirectHeFace (_, pv@(v:_))) = go p 0
where
go (IndirectHeFace (_, [])) _
= []
-- connect last to first element
go (IndirectHeFace (fi, [vlast])) ei
= [IndirectHeEdge ei vlast v fi (negate $ length pv - 1)]
-- regular non-last element
go (IndirectHeFace (fi, vfirst:vnext:vrest)) ei
= (:) (IndirectHeEdge ei vfirst vnext fi 1)
(go (IndirectHeFace (fi, vnext:vrest)) (ei + 1))
-- |Construct the indirect data structure for half-edge vertices.
-- It is assumed that the list of points is indexed in order of their
-- appearance in the obj mesh file.
indirectHeVerts :: [IndirectHeEdge] -- ^ list of indirect edges
-> Map.IntMap IndirectHeVert -- ^ output map, starts at index 1
indirectHeVerts hes' = go hes' Map.empty 0
where
go [] map' _ = map'
go (IndirectHeEdge _ _ nv _ offset:hes) map' i
= go hes
(Map.alter updateMap nv map')
(i + 1)
where
updateMap (Just (IndirectHeVert _ xs))
= Just (IndirectHeVert (i + offset) (i:xs))
updateMap Nothing
= Just (IndirectHeVert (i + offset) [i])
-- |Tie the knots!
-- It is assumed that the list of points is indexed in order of their
-- appearance in the obj mesh file.
--
-- pseudo-code:
--
-- @
-- indirectToDirect :: [a] -- parsed vertices, e.g. 2d points (Double, Double)
-- -> [IndirectHeEdge]
-- -> [IndirectHeFace]
-- -> [IndirectHeVert]
-- -> HeEdge a
-- indirectToDirect points edges faces vertices
-- = thisEdge (head edges)
-- where
-- thisEdge edge
-- = HeEdge (thisVert (vertices !! svindex edge) $ svindex edge)
-- (thisOppEdge (svindex edge) $ indexf edge)
-- (thisFace $ faces !! indexf edge)
-- (thisEdge $ edges !! (edgeindex edge + offsetedge edge))
-- thisFace face = HeFace $ thisEdge (edges !! (head . snd $ face))
-- thisVert vertice coordindex
-- = HeVert (points !! (coordindex - 1))
-- (thisEdge $ points !! (emedgeindex vertice - 1))
-- thisOppEdge startverticeindex faceindex
-- = case headMay
-- . filter ((/=) faceindex . indexf)
-- . fmap (edges !!)
-- . edgelist -- getter
-- $ vertices !! startverticeindex
-- of Just x -> thisEdge x
-- Nothing -> NoEdge
-- @
indirectToDirect :: [a] -- ^ list of points
-> [IndirectHeEdge]
-> [IndirectHeFace]
-> Map.IntMap IndirectHeVert -- ^ assumed to start at index 1
-> HeEdge a
indirectToDirect pts pe@(e:_) fs vertmap
= thisEdge e
where
thisEdge (IndirectHeEdge ei sv _ fi off)
= case (fs `atMay` fi, pe `atMay` (ei + off), Map.lookup sv vertmap) of
(Just face,
Just edge,
Just vert) -> HeEdge (thisVert vert sv)
(getOppEdge sv fi)
(thisFace face)
(thisEdge edge)
_ -> NoEdge
thisFace (IndirectHeFace (_, vi:_))
= case pe `atMay` vi of
Just edge -> HeFace (thisEdge edge)
Nothing -> NoFace
thisFace (IndirectHeFace _) = NoFace
thisVert (IndirectHeVert eedg _) coordi
= case (pts `atMay` (coordi - 1), pe `atMay` (eedg - 1)) of
(Just vert, Just edge) -> HeVert vert $ thisEdge edge
_ -> NoVert
getOppEdge sv fi
= case join
$ headMay
. filter ((/=) fi . indexf)
. catMaybes
. fmap (pe `atMay`)
. edgelist
<$> Map.lookup sv vertmap
of Just x -> thisEdge x
Nothing -> NoEdge
indirectToDirect _ _ _ _ = NoEdge
-- |Build the half-edge data structure from a list of points
-- and from a list of faces.
-- The points are assumed to have been parsed in order of their appearance
-- in the .obj mesh file, so that the indices match.
-- The faces are assumed to have been parsed in order of their appearance
-- in the .obj mesh file as follows:
--
-- @
-- f 1 3 4 5
-- f 4 6 1 3
-- @
--
-- becomes
--
-- > [[1,3,4,5],[4,6,1,3]]
buildHeEdge :: [a] -> [[Int]] -> Maybe (HeEdge a)
buildHeEdge [] _ = Nothing
buildHeEdge _ [] = Nothing
buildHeEdge pts fs
= let faces' = indirectHeFaces fs
edges' = indirectHeEdges faces'
verts' = indirectHeVerts edges'
in Just $ indirectToDirect pts edges' faces' verts'
-- |Build the HeEdge data structure from the .obj mesh file contents.
buildHeEdgeFromStr :: B.ByteString -- ^ contents of an .obj mesh file
-> HeEdge PT
buildHeEdgeFromStr bmesh =
let pts = meshVertices bmesh
faces' = indirectHeFaces . meshFaces $ bmesh
edges = indirectHeEdges faces'
verts = indirectHeVerts edges
in indirectToDirect pts edges faces' verts
| hasufell/CGA | Graphics/HalfEdge.hs | gpl-2.0 | 8,486 | 0 | 16 | 2,399 | 1,519 | 873 | 646 | 121 | 6 |
module Cryptography.ComputationalProblems.Games.Abstract.Macro where
import Types
import Macro.MetaMacro
import Functions.Application.Macro
import Logic.PropositionalLogic.Macro
-- * Games
-- ** Winning condition
wins_ :: Note
wins_ = omega
wins :: Note -> Note -> Note
wins = fn2 wins_
-- ** Deterministic games
gme_ :: Note
gme_ = "g"
plr_ :: Note
plr_ = "w"
-- ** Probabillistic games
gmev_ :: Note
gmev_ = "G"
plrv_ :: Note
plrv_ = "W"
-- * Multigames
winsub_ :: Note -> Note
winsub_ = (wins_ !:)
winsub :: Note -> Note -> Note -> Note
winsub i = fn2 $ winsub_ i
orgame :: Note -> Note
orgame = (^: ("" β¨ ""))
andgame :: Note -> Note
andgame = (^: ("" β§ ""))
| NorfairKing/the-notes | src/Cryptography/ComputationalProblems/Games/Abstract/Macro.hs | gpl-2.0 | 722 | 0 | 7 | 172 | 205 | 123 | 82 | 25 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Intelligence (DB, createDatabase, generateLine) where
import Control.Applicative ((<$>))
import Control.Monad ((=<<), mapM)
import Control.Monad.Random (Rand, RandomGen, evalRandIO, getRandomR)
import Data.Maybe (maybe)
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import qualified Data.Vector as V
import Data.Text (Text)
import Data.Vector (Vector)
import System.Random (RandomGen, StdGen, randomR, randomRs)
-- | Algorithm gratefully borrowed from
-- https://golang.org/doc/codewalk/markov/
-- And:
-- https://blog.codinghorror.com/markov-and-you/
-- | Maps prefixes to the a list of the next word.
-- Also contains the length of the prefix.
data DB = DB
{ database :: M.Map (Vector Text) (Vector Text)
, prefixLength :: Int
}
-- | The order of the Markov chain, or length of the prefix, in number of words.
-- Returns a list of prefixes and their suffixes.
toMarkovPairs :: Int -> Text -> [(Vector Text, Text)]
toMarkovPairs i s = zipWith combine prefixes (tail prefixes)
where
words = V.fromList $ filter (not . T.null) $ T.splitOn " " s
count = V.length words
prefixes = map (\start -> V.slice start i words) [0..count-i]
combine a b = (a, V.last b)
-- | Create a database of Markov wisdom from a prefix length and a list of texts.
createDatabase :: Int -> [Text] -> DB
createDatabase prefixLen texts = DB { database = M.fromListWith (V.++)
$ map (fmap V.singleton)
$ concatMap (toMarkovPairs prefixLen) texts,
prefixLength = prefixLen
}
-- | Get a random suffix from a list of suffixes.
getRandomSuffix :: RandomGen g => Vector Text -> Rand g Text
getRandomSuffix ts = (ts V.!) <$> getRandomR (0, (V.length ts)-1)
-- | Create the first phrase of a message.
firstPhrase :: RandomGen g => DB -> Rand g (Vector Text)
firstPhrase db = do
let ddb = database db
(prefix, ss) <- (`M.elemAt` ddb) <$> getRandomR (0, (M.size ddb)-1)
(prefix `V.snoc`) <$> (getRandomSuffix ss)
-- | Generate a randomly selected suffix for a prefix, and append it to the suffix.
nextPhrase :: RandomGen g => Vector Text -> DB -> Rand g (Maybe (Vector Text))
nextPhrase prefix db = do
let len = prefixLength db
let p' = V.slice ((V.length prefix) - len) len prefix
case M.lookup p' $ database db of
Nothing -> return Nothing
Just ss -> Just <$> (V.snoc prefix) <$> getRandomSuffix ss
-- | Use the Markov-chain to generate a line consisting of up to maxLength number of chains.
-- It might be shorter if there is no good path in the database.
generateLine :: RandomGen g => Int -> DB -> Rand g Text
generateLine length db = V.foldl1 (\t1 t2 -> t1 `T.append` (' ' `T.cons` t2))
<$> (firstPhrase db >>= (generateLine' length db))
where
generateLine' :: RandomGen g => Int -> DB -> Vector Text -> Rand g (Vector Text)
generateLine' 0 _ ts = return ts
generateLine' maxLength db ts = maybe (return ts) (generateLine' (maxLength - 1) db) =<< (nextPhrase ts db)
| Rembane/mrShoe | src/Intelligence.hs | gpl-3.0 | 3,188 | 0 | 15 | 769 | 945 | 508 | 437 | 46 | 2 |
-- Author: Viacheslav Lotsmanov
-- License: GPLv3 https://raw.githubusercontent.com/unclechu/xlib-keys-hack/master/LICENSE
{-# LANGUAGE ScopedTypeVariables, RankNTypes, BangPatterns #-}
{-# LANGUAGE DeriveGeneric, DeriveAnyClass, TemplateHaskell #-}
module Options
( Options (..)
, HasOptions (..)
, ErgonomicMode (..)
, extractOptions
, usageInfo
, noise
, subsDisplay
) where
import "base" GHC.Generics (Generic)
import "base" Data.Maybe (fromJust)
import "data-default" Data.Default (Default, def)
import "base" Data.Word (Word8)
import qualified "text" Data.Text as T (pack, unpack, replace)
import "qm-interpolated-string" Text.InterpolatedString.QM (qm, qms, qmb)
import "time" Data.Time.Clock.POSIX (POSIXTime)
import "base" Control.Arrow ((&&&))
import "base" Control.Applicative ((<|>))
import "lens" Control.Lens (Lens', (.~), (%~), (^.), set)
import "deepseq" Control.DeepSeq (NFData)
import "base" System.IO (Handle)
import qualified "base" System.Console.GetOpt as GetOpt
-- local imports
import Utils.Instances ()
import Utils.Sugar ((.>), (&), (?))
import Utils.Lens (makeApoClassy)
-- ^ Indicates whether Ergonomic (ErgoDox) Mode feature is enabled
data ErgonomicMode
= NoErgonomicMode
| ErgonomicMode
| ErgoDoxErgonomicMode
deriving (Eq, Show, Generic, NFData)
data Options
= Options
{ showHelp :: Bool
, verboseMode :: Bool
, realCapsLock :: Bool
, additionalControls :: Bool
, escapeIsAdditionalControl :: Bool
, shiftNumericKeys :: Bool
, shiftHJKLKeys :: Bool
, rightControlAsRightSuper :: Bool
, alternativeModeWithAltMod :: Bool
, toggleAlternativeModeByAlts :: Bool
, turnOffFourthRow :: Bool
, ergonomicMode :: ErgonomicMode
, superDoublePress :: Bool
, leftSuperDoublePressCmd :: Maybe String
, rightSuperDoublePressCmd :: Maybe String
, rightSuperAsSpace :: Bool
, f24asVerticalBar :: Bool
, resetByRealEscape :: Bool
, resetByEscapeOnCapsLock :: Bool
, resetByWindowFocusEvent :: Bool
, defaultKeyboardLayout :: Word8
, debouncerTiming :: Maybe POSIXTime
, disableXInputDeviceName :: [String]
, disableXInputDeviceId :: [Word]
, handleDevicePath :: [FilePath]
, xmobarIndicators :: Bool
, xmobarIndicatorsObjPath :: String
, xmobarIndicatorsBusName :: String
, xmobarIndicatorsIface :: String
, xmobarIndicatorsFlushObjPath :: String
, xmobarIndicatorsFlushIface :: String
, externalControl :: Bool
, externalControlObjPath :: String
, externalControlBusName :: String
, externalControlIface :: String
, handleDeviceFd :: [Handle]
, availableDevices :: [FilePath]
, availableXInputDevices :: [Word]
} deriving (Show, Eq, Generic, NFData)
instance Default Options where
def
= Options
-- From arguments
{ showHelp = False
, verboseMode = False
, realCapsLock = False
, additionalControls = True
, escapeIsAdditionalControl = False
, shiftNumericKeys = False
, shiftHJKLKeys = False
, rightControlAsRightSuper = False
, alternativeModeWithAltMod = False
, toggleAlternativeModeByAlts = False
, turnOffFourthRow = False
, ergonomicMode = NoErgonomicMode
, superDoublePress = True
, leftSuperDoublePressCmd = Nothing
, rightSuperDoublePressCmd = Nothing
, rightSuperAsSpace = False
, f24asVerticalBar = False
, resetByRealEscape = False
, resetByEscapeOnCapsLock = True
, resetByWindowFocusEvent = True
, defaultKeyboardLayout = 1
, debouncerTiming = Nothing
, disableXInputDeviceName = []
, disableXInputDeviceId = []
, handleDevicePath = []
, xmobarIndicators = False
, xmobarIndicatorsObjPath = "/"
, xmobarIndicatorsBusName = "com.github.unclechu.xmonadrc.%DISPLAY%"
, xmobarIndicatorsIface = "com.github.unclechu.xmonadrc"
, xmobarIndicatorsFlushObjPath = "/com/github/unclechu/xmonadrc/%DISPLAY%"
, xmobarIndicatorsFlushIface = "com.github.unclechu.xmonadrc"
, externalControl = False
, externalControlObjPath = "/"
, externalControlBusName = [qm| com.github.unclechu.
xlib_keys_hack.%DISPLAY% |]
, externalControlIface = "com.github.unclechu.xlib_keys_hack"
-- Will be extracted from `handleDevicePath`
-- and will be reduced with only available
-- devices (that connected to pc).
, handleDeviceFd = []
-- Same as `handleDevicePath` but contains only
-- available devies (that exist in file system).
-- Will be extracted at initialization step
-- (as `handleDeviceFd`).
, availableDevices = []
-- Will be extracted from `disableXInputDeviceName`
-- and from `disableXInputDeviceId` and filtered
-- with only available devices.
, availableXInputDevices = []
}
makeApoClassy ''Options
options :: [GetOpt.OptDescr (Options -> Options)]
options =
[ GetOpt.Option ['h'] ["help"]
(GetOpt.NoArg $ showHelp' .~ True)
"Show this usage info"
, GetOpt.Option ['v'] ["verbose"]
(GetOpt.NoArg $ verboseMode' .~ True)
[qmb| Start in verbose-mode
Default is: {verboseMode def ? "On" $ "Off"}
|]
-- Features options
, GetOpt.Option [ ] ["real-capslock"]
(GetOpt.NoArg $ set realCapsLock' True
. set resetByEscapeOnCapsLock' False)
[qmb| Use real Caps Lock instead of remapping it to Escape
Default is: {realCapsLock def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] [noAdditionalControlsOptName]
(GetOpt.NoArg $ additionalControls' .~ False)
[qmb| Disable additional controls behavior for Caps Lock and Enter keys
(could be comfortable for playing some video games)
Default is: {additionalControls def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] ["escape-is-additional-control"]
(GetOpt.NoArg $ escapeIsAdditionalControl' .~ True)
[qmb| Make Escape work as additional control
(I have Plank EZ layout which has Escape mapped on the key where \
Caps Lock usually is, with this option I can use it as \
additional control)
{makesNoSense noAdditionalControlsOptName}
Default is: {escapeIsAdditionalControl def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] ["shift-numeric-keys"]
(GetOpt.NoArg $ shiftNumericKeys' .~ True)
[qmb| Shift numeric keys in numbers row one key righter, \
and move 'minus' key to the left side at '1' key position.
Could be more consistent for 10-fingers typing.
Default is: {shiftNumericKeys def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] [shiftHjklOptName]
(GetOpt.NoArg $ shiftHJKLKeys' .~ True)
[qmb| Shift 'HJKL' keys one column right \
('semicolon' key would be moved on original 'H' key position).
To place arrows keys (alternative mode, vim, tmux selection, etc.) \
under four fingers to provide more convenient experience.
Default is: {shiftHJKLKeys def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] ["right-control-as-super"]
(GetOpt.NoArg $ rightControlAsRightSuper' .~ True)
[qmb| Remap Right Control as Right Super key.
Some keyboards doesn't have neither Right Super nor Menu key \
at the right side, since you can have Control key pressing \
Enter by "additional controls" feature, this could be a solution.
Default is: {rightControlAsRightSuper def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] [holdAltForAlternativeModeOptName]
(GetOpt.NoArg $ alternativeModeWithAltMod' .~ True)
[qmb| When hold Alt key (left or right, doesn't matter) \
alternative mode is turned on (real Alt keys aren't triggered).
To trigger real Alt key you press Alt+Space, in this case \
alternative mode is turned off and real Alt is triggered \
from that moment.
To turn alternative mode on Alt key supposed to be pressed first \
before any other key or modifier.
Do not use with --{toggleAlternativeModeByAltsOptName} to be able \
to press combo like Alt-2 by just both Alts pressed plus "w" \
key. Otherwise you'll just have turn alternative mode on \
permanently (by pressing both Alts or by double pressing Super \
key if such feature is enabled) \
and then press Alt-w to trigger actual Alt-2.
Default is: {alternativeModeWithAltMod def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] [toggleAlternativeModeByAltsOptName]
(GetOpt.NoArg $ toggleAlternativeModeByAlts' .~ True)
[qmb| Enable toggling alternative mode \
by pressing Alt keys (Left and Right) both at the same time.
Default is: {toggleAlternativeModeByAlts def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] [turnOffFourthRowOptName]
(GetOpt.NoArg $ turnOffFourthRow' .~ True)
[qmb| Turns off fourth keys row completely.
This helps to change your reflexes when \
--{holdAltForAlternativeModeOptName} feature is turned on.
{makesNoSense ergonomicModeOptName}
Default is: {turnOffFourthRow def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] [ergonomicModeOptName]
(GetOpt.NoArg $ (turnOffFourthRow' .~ True)
. (ergonomicMode' .~ ErgonomicMode))
[qmb| Turns on kinda hardcore ergonomic mode \
(an attempt to make the experience of using a traditional \
keyboard to be more convenient, or I would say less painful).
WARNING! It may force you to change a lot of your reflexes!
I urgently recommend to use this option with \
--{holdAltForAlternativeModeOptName} option!
Also --{shiftHjklOptName} would probably get you even more \
feeling of consistency.
This mode implies --{turnOffFourthRowOptName} option.
The main idea of this mode is that a finger moves vertically only \
one row up/down, and horizontally the index/pinky finger moves \
only one column left/right.
Of course to achive this some keys wouldn't be available, to \
solve this issue some keys will be remapped and some moved to \
alternative mode (and those keys which don't satisfy the rules \
will be turned off completely):
\ Remappings:
\ * Apostrophe ( ' " ) key will become Enter key \
(which also will work as additional Ctrl key \
if related option is enabled);
\ * Open Bracket ( [ \{ ) key will become Apostrophe key \
(which was Minus ( - _ ) key in alternative mode).
\ Rest keys are moved to alternative mode (to first level):
\ * "A" key will become Minus ( - _ ) key;
\ * "S" key will become Equal ( = + ) key;
\ * "D" key will become Open Bracket ( [ \{ ) key;
\ * "F" key will become Close Bracket ( ] } ) key;
\ * "G" key will become Backslash ( \\ | ) key;
\ * Open Bracket key will become Delete key \
(Apostrophe ( ' " ) key will be remapped to Enter key, so \
it can't be Delete key anymore because Enter key should be \
available in all modes).
\ Also in second level of alternative mode some FN keys will be \
rearranged:
\ * Open Bracket key will become F11 key;
\ * Tab key will become F12 key (it could be F1 and all next in \
ascending order in this row but you loose consistency with \
regular number keys from first alternative mode level in \
this case).
Real keys which will be disabled (along with fourth row):
\ * Close Bracket ( ] } ) key;
\ * Backslash ( \\ | ) key;
\ * Enter key.
Default is: {ergonomicMode def /= ErgonomicMode ? "On" $ "Off"}
|]
, GetOpt.Option [ ] [ergonomicErgoDoxModeOptName]
(GetOpt.NoArg $ (turnOffFourthRow' .~ False)
. (ergonomicMode' .~ ErgoDoxErgonomicMode))
[qms| It's an ErgoDox-oriented version of --{ergonomicModeOptName} which
doesn't turn off numbers row (to keep them for "shifted punctuation"
keys defined on ErgoDox firmware level).\
\n\
Remaps provided by this option are tied to my own ErgoDox EZ
layout.\
\n\
Remappings (mostly based on --{ergonomicModeOptName} option,
here are only the different ones):\
\n\
\ * Backslash ( \\ ) key will become Apostrophe ( ' " ) key
(on the keyboard layout I have Backslash coming right after P
key and at the position of Apostrophe key I have Enter key,
so this making Apostrophe key being reachable like with the
--{ergonomicModeOptName} option, on the same physical
position whilst Backslash is being reachable via alternative
mode);\
\n\
\ * In the alternative mode Delete (first level) and F11
(second level) keys are reachable by Backslash key
(instead of Open Bracket key becuase on my ErgoDox EZ layout
Backslash key goes right after P key instead of
Open Bracket key on a regular archaically designed keyboard).\
\n\
Default is: \
{ergonomicMode def == ErgoDoxErgonomicMode ? "On" $ "Off"}
|]
, GetOpt.Option [ ] [disableSuperDoublePressOptName]
(GetOpt.NoArg $ superDoublePress' .~ False)
[qmb| Disable handling of double Super key press.
Default is: {superDoublePress def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] ["super-double-press-cmd"]
(GetOpt.ReqArg
(\(Just -> x) -> set leftSuperDoublePressCmd' x
. set rightSuperDoublePressCmd' x)
"COMMAND")
[qmb| When Super key is pressed twice in short interval \
alternative mode will be toggled or \
specified shell command will be spawned.
{makesNoSense disableSuperDoublePressOptName}
|]
, GetOpt.Option [ ] ["left-super-double-press-cmd"]
(GetOpt.ReqArg (Just .> set leftSuperDoublePressCmd') "COMMAND")
[qmb| Double Left Super key press will spawn specified shell command \
instead of toggling alternative mode.
{makesNoSense disableSuperDoublePressOptName}
|]
, GetOpt.Option [ ] ["right-super-double-press-cmd"]
(GetOpt.ReqArg (Just .> set rightSuperDoublePressCmd') "COMMAND")
[qmb| Double Right Super key press will spawn specified shell command \
instead of toggling alternative mode.
{makesNoSense disableSuperDoublePressOptName}
|]
, GetOpt.Option [ ] ["right-super-as-space"]
(GetOpt.NoArg (rightSuperAsSpace' .~ True))
[qms| It makes sense to turn this on when I use my ErgoDox EZ layout and
play videogames. I got 3 bottom keys for thumb mapped as
Super, Alt and Control.
Super keys are used by a window manager which in my case blocks some
other events (in a game) when it's pressed, e.g. when I hold it
mouse for some reason doesn't work.\n\
Remapping Super key to something else could solve the problem
(like remapping it to the Spacebar by turning this option on).\n\
Default is: {rightSuperAsSpace def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] ["f24-as-vertical-bar"]
(GetOpt.NoArg (f24asVerticalBar' .~ True))
[qms| This option makes F24 key (which isn't presented on most of the
keyboards, at least I've never seen such a keyboard, only up to F19
on Apple's keyboard) being interpreted as two keys pressed in
sequence: Shift + Backslash.\
\n\
This has to do with my own ErgoDox EZ layout where there is another
layout layer which has a lot of "shifted punctuation" keys including
vertical bar (which means it is an automated combo of both Shfit and
Backslash keys) but at the same time I have Backslash key remapped
to Apostrophe key (see --{ergonomicErgoDoxModeOptName} option). So
it would trigger Shift + Apostrophe which would give you a double
quote. This option is an experimental attempt to solve it, by
remapping that "shifted punctuation" vertical bar key to F24 on the
keyboard firmware level and trigger that vertical bar by this tool
instead.\
\n\
Default is: {f24asVerticalBar def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] ["reset-by-real-escape"]
(GetOpt.NoArg $ resetByRealEscape' .~ True)
[qmb| Enable resetting Caps Lock mode, Alternative mode \
and keyboard layout by real Escape key.
Default is: {resetByRealEscape def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] ["disable-reset-by-escape-on-capslock"]
(GetOpt.NoArg $ resetByEscapeOnCapsLock' .~ False)
[qmb| Disable resetting Caps Lock mode, Alternative mode \
and keyboard layout by Escape that triggered by Caps Lock key
(only when it's remapped, no need to use this option \
if you already use --real-capslock)
Default is: {resetByEscapeOnCapsLock def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] ["disable-reset-by-window-focus-event"]
(GetOpt.NoArg $ resetByWindowFocusEvent' .~ False)
[qmb| Disable resetting Caps Lock mode, Alternative mode \
and keyboard layout by switching between windows.
WARNING! If you don't disable this feature you should ensure \
that you have directory that contains \
'xlib-keys-hack-watch-for-window-focus-events' \
executable in your 'PATH' environment variable!
Default is: {resetByWindowFocusEvent def ? "On" $ "Off"}
|]
, let validate x
| x < 1 = error "Default keyboard layout must be greater than zero"
| otherwise = x
setter = set defaultKeyboardLayout'
in GetOpt.Option [ ] ["default-keyboard-layout"]
(GetOpt.ReqArg (read .> validate .> pred .> setter) "NUMBER")
[qms| Kayboard layout number (starting with 1) to reset keyboard
layout to when pressing Escape or doing whatever action that
resets stuff (keyboard layout, alternative mode, etc.)
|]
, let defaultValue = 0.03 :: POSIXTime
convertFn x = fromRational $ toRational (read x :: Word8) / 1000
setter x = set debouncerTiming' $ fmap convertFn x <|> Just defaultValue
defaultIs Nothing = "Off"
defaultIs (Just x) = [qm| On ({ floor $ x * 1000 :: Word8 }ms) |]
in GetOpt.Option [ ] ["software-debouncer"]
(GetOpt.OptArg setter "MILLISECONDS")
[qmb| Enable software debouncer feature.
Debouncing is usually done on hardware or firmware level of a \
keyboard but timing could be not configurable. \
Some keyboards may have issues with doubling or just \
shrapnelling some keys (triggering a key pressing more than \
once per one physical press) especially after long use time. \
By using this feature you could use your keyboard longer, \
give it a second life.
How this feature works: when you press/release a key only \
first event is handled and then it waits for specified or \
default timing ignoring any other events of that key in that \
gap and only after that it handles next state of that key.
If this feature is turned on but timing is not specified then \
default timing would be: \
{ floor $ defaultValue * 1000 :: Word8 }ms.
Default is: {defaultIs $ debouncerTiming def}
|]
-- Devices handling and disabling xinput devices options
, GetOpt.Option [ ] ["disable-xinput-device-name"]
(GetOpt.OptArg
(\x -> disableXInputDeviceName' %~ (<> [fromJust x]))
"NAME")
"Name of device to disable using 'xinput' tool"
, GetOpt.Option [ ] ["disable-xinput-device-id"]
(GetOpt.OptArg
(\x -> disableXInputDeviceId' %~ (<> [fromJust x & read]))
"ID")
"Id of device to disable using 'xinput' tool"
, GetOpt.Option [ ] ["device-fd-path"]
(GetOpt.OptArg
(\x -> handleDevicePath' %~ (<> [fromJust x]))
"FDPATH")
"Path to device file descriptor to get events from"
-- "xmobar indicators" options
, GetOpt.Option [ ] [xmobarIndicatorsOptName]
(GetOpt.NoArg $ xmobarIndicators' .~ True)
[qmb| Enable notifying xmobar indicators process about indicators \
(num lock, caps lock and alternative mode) \
state changes by DBus.
See also https://github.com/unclechu/xmonadrc
See also https://github.com/unclechu/unclechu-i3-status \
(this one isn't about xmobar but uses same IPC interface)
Default is: {xmobarIndicators def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] ["xmobar-indicators-dbus-path"]
(GetOpt.ReqArg (set xmobarIndicatorsObjPath') "PATH")
[qmb| DBus object path for xmobar indicators.
{explainDef xmobarIndicatorsObjPath'}
{makesSense xmobarIndicatorsOptName}
|]
, GetOpt.Option [ ] ["xmobar-indicators-dbus-bus"]
(GetOpt.ReqArg (set xmobarIndicatorsBusName') "BUS")
[qmb| DBus bus name for xmobar indicators.
{explainDef xmobarIndicatorsBusName'}
{makesSense xmobarIndicatorsOptName}
Use --xmobar-indicators-dbus-bus=any to broadcast for everyone.
|]
, GetOpt.Option [ ] ["xmobar-indicators-dbus-interface"]
(GetOpt.ReqArg (set xmobarIndicatorsIface') "INTERFACE")
[qmb| DBus interface for xmobar indicators.
{explainDef xmobarIndicatorsIface'}
{makesSense xmobarIndicatorsOptName}
|]
, GetOpt.Option [ ] ["xmobar-indicators-dbus-flush-path"]
(GetOpt.ReqArg (set xmobarIndicatorsFlushObjPath') "PATH")
[qmb| DBus object path for 'flush' request from xmobar indicators process.
{explainDef xmobarIndicatorsFlushObjPath'}
{makesSense xmobarIndicatorsOptName}
|]
, GetOpt.Option [ ] ["xmobar-indicators-dbus-flush-interface"]
(GetOpt.ReqArg (set xmobarIndicatorsFlushIface') "INTERFACE")
[qmb| DBus interface for 'flush' request from xmobar indicators process.
{explainDef xmobarIndicatorsFlushIface'}
{makesSense xmobarIndicatorsOptName}
|]
-- "External control" options
, GetOpt.Option [ ] [externalControlOptName]
(GetOpt.NoArg $ externalControl' .~ True)
[qmb| Enabling handling of external control IPC-commands through DBus.
Default is: {externalControl def ? "On" $ "Off"}
|]
, GetOpt.Option [ ] ["external-control-dbus-path"]
(GetOpt.ReqArg (set externalControlObjPath') "PATH")
[qmb| DBus object path of external control IPC.
{explainDef externalControlObjPath'}
{makesSense externalControlOptName}
|]
, GetOpt.Option [ ] ["external-control-dbus-bus"]
(GetOpt.ReqArg (set externalControlBusName') "BUS")
[qmb| DBus bus name of external control IPC.
{explainDef externalControlBusName'}
{makesSense externalControlOptName}
|]
, GetOpt.Option [ ] ["external-control-dbus-interface"]
(GetOpt.ReqArg (set externalControlIface') "INTERFACE")
[qmb| DBus interface of external control IPC.
{explainDef externalControlIface'}
{makesSense externalControlOptName}
|]
]
where explainDef :: Lens' Options String -> String
explainDef ((def ^.) -> id &&& (not . _hasDpy) -> (d, isPlain))
| isPlain = [qmb| Default is: '{d}'
{_hint}
'%DISPLAY%' will be replaced with {_viewOf}
{_forExample d}
|]
| otherwise = [qmb| Default is: '{d}' where '%DISPLAY%' is {_viewOf}
{_forExample d}
{_hint}
|]
makesSense :: String -> String
makesSense x = [qm| This option makes sense only with --{x} option. |]
makesNoSense :: String -> String
makesNoSense x = [qm| This option makes no sense with --{x} option. |]
holdAltForAlternativeModeOptName :: String
holdAltForAlternativeModeOptName = "hold-alt-for-alternative-mode"
toggleAlternativeModeByAltsOptName :: String
toggleAlternativeModeByAltsOptName = "toggle-alternative-mode-by-alts"
disableSuperDoublePressOptName :: String
disableSuperDoublePressOptName = "disable-super-double-press"
xmobarIndicatorsOptName, externalControlOptName :: String
xmobarIndicatorsOptName = "xmobar-indicators"
externalControlOptName = "external-control"
turnOffFourthRowOptName :: String
turnOffFourthRowOptName = "turn-off-fourth-row"
ergonomicModeOptName :: String
ergonomicModeOptName = "ergonomic-mode"
ergonomicErgoDoxModeOptName :: String
ergonomicErgoDoxModeOptName = "ergonomic-ergodox-mode"
shiftHjklOptName :: String
shiftHjklOptName = "shift-hjkl"
noAdditionalControlsOptName :: String
noAdditionalControlsOptName = "no-additional-controls"
_forExample :: String -> String
_forExample ((\x -> _hasDpy x ? x $ "foo.%DISPLAY%.bar") -> d) =
[qms| For example if we have '$DISPLAY' as '{_demoDpy}'
'{d}' will be replaced to '{_s d}'. |]
_viewOf :: String
_viewOf = [qms| view of '$DISPLAY' environment variable where
':' and '.' symbols are replaced to underscore '_'. |]
_hint :: String
_hint = [qms| You can use '%DISPLAY%' in your own value of this
option (it will be automatically replaced). |]
_s = subsDisplay _demoDpy ; _s :: String -> String
_hasDpy x = x /= _s x ; _hasDpy :: String -> Bool
_demoDpy = ":0.0" ; _demoDpy :: String
type ErrorMessage = String
extractOptions :: [String] -> Either ErrorMessage Options
extractOptions = GetOpt.getOpt GetOpt.Permute options .> \case
(o, n, []) ->
Right $ foldl (flip id) def o & handleDevicePath' %~ (<> n)
(_, _, errs) ->
Left $ case concat errs of
(reverse -> '\n':xs) -> reverse xs
x -> x
usageInfo :: String
usageInfo = '\n' : GetOpt.usageInfo header options where
header = "Usage: xlib-keys-hack [OPTION...] DEVICES-FD-PATHS..."
noise :: Options -> String -> IO ()
noise (verboseMode -> True) msg = putStrLn msg
noise _ _ = pure ()
subsDisplay :: String -> String -> String
subsDisplay dpy =
T.pack .> T.replace (T.pack "%DISPLAY%") (T.pack $ map f dpy) .> T.unpack
where f ':' = '_'; f '.' = '_'; f x = x
| unclechu/xlib-keys-hack | src/Options.hs | gpl-3.0 | 28,704 | 0 | 15 | 8,971 | 3,184 | 1,875 | 1,309 | -1 | -1 |
module Main where
import Elocmd
import Elovalo
import Effects
import Interface.JsonRpc
-- This is a test only
main = do
elo <- initElocmd "/dev/ttyUSB0"
sendFrame elo $ singleIntensity elo 0.5
runJsonRpc 8080 elo
| elovalo/helovalo | src/Main.hs | gpl-3.0 | 222 | 0 | 8 | 42 | 57 | 29 | 28 | 9 | 1 |
{-# LANGUAGE BangPatterns #-}
-- Copyright : (c) Nikolay Orlyuk 2012
-- License : GNU GPLv3 (see COPYING)
module FRP.Yampa.GLUT.InternalUI where
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT.Callbacks
data UI = GlutDisplay
| GlutReshape !Size
| GlutMotion !Position
| GlutPassiveMotion !Position
| GlutKeyboardMouse !Key !KeyState !Modifiers !Position
| GlutCrossing !Crossing
deriving (Eq, Show)
| ony/yampa-glut | FRP/Yampa/GLUT/InternalUI.hs | gpl-3.0 | 465 | 0 | 7 | 107 | 81 | 46 | 35 | 27 | 0 |
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE UnicodeSyntax #-}
{-# LANGUAGE ViewPatterns #-}
module C.Deep where
import CLL
import Data.Monoid
import Data.List
import Data.Function
import C.Common
-- | Declare a variable of the appropriate type
cDecl :: (String, Type) -> C
cDecl (n,t) = cDecl' t (Just n)
-- | Declare a variable of the dual type
coDecl :: (String, Type) -> C
coDecl (n,t) = cDecl' (dual t) (Just n)
-- | Structure fields
cStruct :: [(String,Type)] -> C
cStruct fields = mconcat [cDecl (f,t) <> ";\n" | (f,t) <- fields]
-- | Unique name for a type
cTypeName :: Type -> String
cTypeName (t :* u) = "p" <> cTypeName t <> "_" <> cTypeName u
cTypeName (t :+ u) = "s" <> cTypeName t <> "_" <> cTypeName u
cTypeName (I) = "i"
cTypeName (Var x) = "v" <> x
cTypeName (Perp t) = "n" <> cTypeName t
cName :: Maybe String β C
cName (Just x) = dcl x
cName Nothing = ""
-- Function signature
cSig :: String -> C -> Type -> Maybe String -> C
cSig n env t arg = "void " <> lit n <> "(" <> cDecl' t arg <> "," <> env <> ")"
cDecl' :: Type -> Maybe String -> C
cDecl' t0 n = case t0 of
(t :* u) -> cStructDef (cTypeName t0) (cStruct [("fst",t),("snd",u)]) <+> cName n
(t :+ u) -> cStructDef (cTypeName t0)
("char tag;\n" <>
"union " <> braces
(cStruct [("left",t),("right",u)]) <+> "val") <+> cName n
I -> cStructDef (cTypeName t0) (cStruct []) <+> cName n
(Var x) -> lit x <> " " <> cName n
(Perp t) -> cStructDef (cTypeName t0)
(cSig "(*code)" "char*" t Nothing <> ";\n" <>
"char env[0];") <> "*" <+> cName n
-- | Compile a focused, polarised logic to C.
compileC :: LL (String, Type) (String, Type) β C
compileC t0 = case t0 of
Plus z x t y u ->
"if (" <> var z <> "tag) {\n" <>
stmt (cDecl x <> " = " <> var z <> ".val.left") <>
compileC t <>
"} else {" <>
stmt (cDecl y <> " = " <> var z <> ".val.right") <>
compileC u <>
"};"
Tensor z x y t' ->
cDecl x <> " = " <> var z <> ".fst;\n" <>
cDecl y <> " = " <> var z <> ".snd;\n" <>
compileC t'
One _ t' -> stmt "NOP()" <> compileC t'
Zero x -> stmt ("ABORT(" <> var x <> ")")
Ax x y -> stmt (coDecl x <> "=" <> var y)
Down z x'@(x,_) t' ->
stmt (coDecl x') <>
cocompileC t' (lit (quoteVar x)) <>
stmt (var z <> "->code" <> parens (commas [lit (quoteVar x),var z <> "->env"]))
Bang z x t' ->
stmt (cDecl x <> " = " <> cCall "BOX_CONTENTS" [var z]) <>
stmt (cCall "BOX_DEREF" [var z]) <>
compileC t'
Contract z x y t' ->
stmt (cDecl x <> " = " <> var z) <>
stmt (cDecl y <> " = " <> var z) <>
stmt (cCall "BOX_REF_COUNT" [var z] <> "++") <>
compileC t'
Derelict z t' ->
stmt (cCall "BOX_DEREF" [var z]) <>
compileC t'
-- | Compiling negatives, by construction of the eliminated variable.
cocompileC :: LL (String, Type) (String, Type) -> C β C
cocompileC t0 target = case t0 of
Ax _x y -> stmt (target <> "=" <> var y)
With pol _z _x t ->
stmt (target <> ".tag = " <> (if pol then "1" else "0")) <>
cocompileC t (target <> ".val." <> (if pol then "left" else "right"))
Par _z _x t' _y u' ->
cocompileC t' (target <> ".fst") <>
cocompileC u' (target <> ".snd")
Bot _z -> mempty
Up _z _x@(xn,t) t' ->
def (cSig xfun (envStruct <> "* env") t (Just xn) <>
braces (mconcat [stmt (cDecl v <> "= env->" <> var v) | v <- env'] <> -- load env in local vars
stmt (cCall "free" ["CLOSURE_OF(env)"]) <> -- free env
t'c )) <>
stmt (target <> " = " <> cCall "malloc" ["4 /* fixme */+" <> cCall "sizeof" [envStruct]]) <>
stmt (envStruct <> " *" <> cXenv <> " = " <> target <> "-> env") <>
mconcat [stmt $ cXenv <> "->" <> v <> " = " <> v | v <- map var env'] <> -- fill each env field
stmt (target <> "->code = " <> lit xfun) -- fixme: add a cast
where xenv = (xn ++ "_env")
xfun = quoteVar $ fresh xn "fun"
t'c@(Code _ env _ _ _) = compileC t'
env' = nubBy ((==) `on` fst) (env \\\ [xn])
envStruct = cStructDef (cEnvName env') (cStruct env')
cXenv = lit (quoteVar xenv)
Quest _ _ t' ->
stmt (target <> " = BOX_ALLOCATE()") <>
cocompileC t' ("*" <> target)
cEnvName :: [(String,Type)] -> String
cEnvName env = "e" <> mconcat ["f_" <> f <> "_" <> cTypeName t | (f,t) <- env]
compile :: ([(String, Type)], LL String String) β String
compile (ctx,input) = cCode $
"#include \"cd.h\"\n" <>
mconcat (cleanStructs (cStructs cctx <> cStructs t'c)) <>
lit (mconcat (cDefs t'c)) <>
("void main_function(" <> cctx <> ") " <> braces t'c)
where t'c = compileC t'
t' = (normalize ctx input)
cctx = commas [cDecl x | x <- ctx]
main :: IO ()
main = writeFile "simp.c" $ compile simpl
-- >>> main
| jyp/inox | C/Deep.hs | gpl-3.0 | 5,323 | 0 | 25 | 1,433 | 2,141 | 1,088 | 1,053 | 125 | 9 |
-- Hplayground Ajax control is de-inverted. This means that ajax request follows the
-- normal flow. there is no need to se hup a response handler for each request
-- ajax is just a monadic statement in the Widget monad.
--
-- This example make use of the web service por compilation of tryplayground and
-- show the result
--
-- The service in the server is "compileServ" at
-- https://github.com/agocorona/tryhplay/blob/master/Main.hs
--
import Haste.HPlay.View
main= runBody $ do
r <- ajax POST "/compile" [("name","test"),("text","main=print \"hello\"")]
wprint (r :: Maybe String) | agocorona/tryhplay | examples/ajax.hs | gpl-3.0 | 597 | 0 | 11 | 101 | 73 | 44 | 29 | 4 | 1 |
module Fault
( FaultLevel(Error, Warning)
, Fault(Fault)
, MaybeAst
) where
import Syntax as S
data FaultLevel = Error | Warning deriving (Eq, Show, Ord)
data Fault = Fault { faultLevel :: FaultLevel
, faultReason :: String
, faultContext :: String
} deriving (Eq, Show)
-- Either errors or AST and warnings
type MaybeAst a = Either [Fault] ([S.Expression a], [Fault])
| mbelicki/valdemar | src/Fault.hs | gpl-3.0 | 445 | 0 | 9 | 137 | 126 | 79 | 47 | 15 | 0 |
{-# LANGUAGE OverloadedStrings, GADTs, ScopedTypeVariables #-}
{-|
Description: Generate a new SVG file from the database graph representation.
This module is responsible for taking the database representation of a graph
and creating a new SVG file.
This functionality is used both to create SVG for the Graph component,
as well as generating images on the fly for Facebook posting.
-}
module Svg.Generator where
import Svg.Builder
import Database.Tables
import Database.DataType
import Control.Monad.IO.Class (liftIO)
import Database.Persist.Sqlite
import Data.List hiding (map, filter)
import Data.Int
import MakeElements
import Data.Maybe (fromMaybe)
import qualified Data.Text as T
import Text.Blaze.Svg11 ((!))
import qualified Text.Blaze.Svg11 as S
import qualified Text.Blaze.Svg11.Attributes as A
import Text.Blaze.Svg.Renderer.String (renderSvg)
import Text.Blaze.Internal (stringValue)
import Text.Blaze (toMarkup)
import Css.Constants
import qualified Data.Map.Strict as M
import Data.Monoid (mempty)
import Config (dbStr)
-- | This is the main function that retrieves a stored graph
-- from the database and creates a new SVG file for it.
buildSVG :: Int64 -- ^ The ID of the graph that is being built.
-> M.Map String String -- ^ A map of courses that holds the course
-- ID as a key, and the data-active
-- attribute as the course's value.
-- The data-active attribute is used in the
-- interactive graph to indicate which
-- courses the user has selected.
-> String -- ^ The filename that this graph will be
-- written to.
-> Bool -- ^ Whether to include inline styles.
-> IO ()
buildSVG gId courseMap filename styled =
runSqlite dbStr $ do
sqlRects :: [Entity Shape] <- selectList
[ShapeType_ <-. [Node, Hybrid],
ShapeGId ==. gId] []
sqlTexts :: [Entity Text] <- selectList [TextGId ==. gId] []
sqlPaths :: [Entity Path] <- selectList [PathGId ==. gId] []
sqlEllipses :: [Entity Shape] <- selectList
[ShapeType_ ==. BoolNode,
ShapeGId ==. gId] []
let courseStyleMap = M.map convertSelectionToStyle courseMap
texts = map entityVal sqlTexts
-- TODO: Ideally, we would do these "build" steps *before*
-- inserting these values into the database.
rects = zipWith (buildRect texts)
(map entityVal sqlRects)
(map keyAsInt sqlRects)
ellipses = zipWith (buildEllipses texts)
(map entityVal sqlEllipses)
(map keyAsInt sqlEllipses)
paths = zipWith (buildPath rects ellipses)
(map entityVal sqlPaths)
(map keyAsInt sqlPaths)
regions = filter pathIsRegion paths
edges = filter (not . pathIsRegion) paths
regionTexts = filter (not .
intersectsWithShape (rects ++ ellipses))
texts
stringSVG = renderSvg $ makeSVGDoc courseStyleMap
rects
ellipses
edges
regions
regionTexts
styled
liftIO $ writeFile filename stringSVG
where
keyAsInt :: PersistEntity a => Entity a -> Int64
keyAsInt = (\(PersistInt64 x) -> x) . head . keyToValues . entityKey
convertSelectionToStyle :: String -> String
convertSelectionToStyle courseStatus =
if isSelected courseStatus
then "stroke-width:4;"
else "opacity:0.5;stroke-dasharray:8,5;"
isSelected courseStatus =
isPrefixOf "active" courseStatus ||
isPrefixOf "overridden" courseStatus
-- * SVG Creation
-- | This function does the heavy lifting to actually create
-- a new SVG value given the graph components.
makeSVGDoc :: M.Map String String
-> [Shape] -- ^ A list of the Nodes that will be included
-- in the graph. This includes both Hybrids and
-- course nodes.
-> [Shape] -- ^ A list of the Ellipses that will be included
-- in the graph.
-> [Path] -- ^ A list of the Edges that will be included
-- in the graph.
-> [Path] -- ^ A list of the Regions that will be included
-- in the graph.
-> [Text] -- ^ A list of the 'Text' elements that will be included
-- in the graph.
-> Bool -- ^ Whether to include inline styles in the graph.
-> S.Svg -- ^ The completed SVG document.
makeSVGDoc courseMap rects ellipses edges regions regionTexts styled =
S.docTypeSvg ! A.width "1195"
! A.height "650"
! S.customAttribute "xmlns:svg" "http://www.w3.org/2000/svg"
! S.customAttribute "xmlns:dc" "http://purl.org/dc/elements/1.1/"
! S.customAttribute "xmlns:cc" "http://creativecommons.org/ns#"
! S.customAttribute "xmlns:rdf"
"http://www.w3.org/1999/02/22-rdf-syntax-ns#"
! A.version "1.1" $ do
makeSVGDefs
S.g ! A.id_ "regions" $
concatSVG $ map (regionToSVG styled)
regions
S.g ! A.id_ "nodes"
! A.style "stroke:#000000;" $
concatSVG $ map (rectToSVG styled courseMap)
rects
S.g ! A.id_ "bools" $
concatSVG $ map (ellipseToSVG styled)
ellipses
S.g ! A.id_ "edges"
! A.style "stroke:#000000" $
concatSVG $ map (edgeToSVG styled)
edges
S.g ! A.id_ "region-labels" $
concatSVG $ map (textToSVG styled Region 0)
regionTexts
-- | Builds the SVG defs. Currently, we only use a single one, for the arrowheads.
makeSVGDefs :: S.Svg
makeSVGDefs =
S.defs $
S.marker ! A.id_ "arrow"
! A.viewbox "0 0 10 10"
! A.refx "4"
! A.refy "5"
! A.markerunits "strokeWidth"
! A.orient "auto"
! A.markerwidth "7"
! A.markerheight "7" $
S.polyline ! A.points "0,1 10,5 0,9"
! A.fill "black"
-- | Converts a node to SVG.
rectToSVG :: Bool -> M.Map String String -> Shape -> S.Svg
rectToSVG styled courseMap rect
| shapeFill rect == "none" = S.rect
| otherwise =
let style = case shapeType_ rect of
Node -> fromMaybe "" $ M.lookup (shapeId_ rect)
courseMap
_ -> ""
class_ = case shapeType_ rect of
Node -> "node"
Hybrid -> "hybrid"
in S.g ! A.id_ (stringValue $ toId $ shapeId_ rect)
! A.class_ (stringValue class_)
! S.customAttribute "data-group" (stringValue
(getArea (shapeId_ rect)))
! S.customAttribute "text-rendering" "geometricPrecision"
! S.customAttribute "shape-rendering" "geometricPrecision"
-- TODO: Remove the reliance on the colours here
! (if styled || class_ /= "hybrid"
then
A.style (stringValue style)
else
mempty)
$
do S.rect ! A.rx "4"
! A.ry "4"
! A.x (stringValue . show . fst $ shapePos rect)
! A.y (stringValue . show . snd $ shapePos rect)
! A.width (stringValue . show $ shapeWidth rect)
! A.height (stringValue . show $ shapeHeight rect)
! A.style (stringValue $ "fill:" ++ shapeFill rect ++ ";")
concatSVG $ map
(textToSVG
styled
(shapeType_ rect)
(fst (shapePos rect) + (shapeWidth rect / 2)))
(shapeText rect)
-- | Converts an ellipse to SVG.
ellipseToSVG :: Bool -> Shape -> S.Svg
ellipseToSVG styled ellipse =
S.g ! A.id_ (stringValue (shapeId_ ellipse))
! A.class_ "bool" $ do
S.ellipse ! A.cx (stringValue . show . fst $ shapePos ellipse)
! A.cy (stringValue . show . snd $ shapePos ellipse)
! A.rx (stringValue . show $ shapeWidth ellipse / 2)
! A.ry (stringValue . show $ shapeHeight ellipse / 2)
! if styled
then
A.style "stroke:#000000;fill:none;"
else mempty
concatSVG $ map
(textToSVG styled BoolNode (fst $ shapePos ellipse))
(shapeText ellipse)
-- | Converts a text value to SVG.
textToSVG :: Bool -> ShapeType -> Double -> Text -> S.Svg
textToSVG styled type_ xPos' text =
S.text_ ! A.x (stringValue $ show $
if type_ == Region
then xPos
else xPos')
! A.y (stringValue $ show yPos)
! A.style (stringValue $ align ++ fontStyle ++ fill)
$ toMarkup $ textText text
where
(xPos, yPos) = textPos text
alignVal = case type_ of
Region -> textAlign text
_ -> "middle"
align = "text-anchor:" ++ alignVal ++ ";"
fill = case textFill text of
"" -> ""
colour -> "fill:" ++ colour ++ ";"
getTextStyle Hybrid = hybridTextStyle
getTextStyle BoolNode = ellipseTextStyle
getTextStyle Region = regionTextStyle
getTextStyle _ = ""
-- TODO: Possibly move this closer to the CSS
hybridTextStyle = "font-size:7.5pt;fill:white;"
ellipseTextStyle = "font-size:7.5pt;"
regionTextStyle = "font-size:9pt;"
fontStyle = if styled
then
getTextStyle type_ ++
"font-family:sans-serif;stroke:none;"
else
""
-- | Converts a path to SVG.
edgeToSVG :: Bool -> Path -> S.Svg
edgeToSVG styled path =
S.path ! A.id_ (stringValue $ "path" ++ pathId_ path)
! A.class_ "path"
! A.d (stringValue $ 'M' : buildPathString (pathPoints path))
! A.markerEnd "url(#arrow)"
! S.customAttribute "source-node" (stringValue $ toId
$ pathSource path)
! S.customAttribute "target-node" (stringValue $ toId
$ pathTarget path)
! if styled
then
A.style (stringValue $ "fill:" ++
pathFill path ++
";fill-opacity:1;")
else
mempty
-- | Converts a region to SVG.
regionToSVG :: Bool -> Path -> S.Svg
regionToSVG styled path =
S.path ! A.id_ (stringValue $ "region" ++ pathId_ path)
! A.class_ "region"
! A.d (stringValue $ 'M' : buildPathString (pathPoints path))
! A.style (stringValue $ "fill:" ++ pathFill path ++ ";" ++
if styled
then
";opacity:0.7;fill-opacity:0.58;"
else "")
-- ** Hard-coded map definitions (should be removed, eventually)
-- | Gets a tuple from areaMap where id_ is in the list of courses for that
-- tuple.
getTuple :: String -- ^ The course's ID.
-> Maybe (T.Text, String)
getTuple id_
| M.null tuples = Nothing
| otherwise = Just $ snd $ M.elemAt 0 tuples
where tuples = M.filterWithKey (\k _ -> id_ `elem` k) areaMap
-- | Gets an area from areaMap where id_ is in the list of courses for the
-- corresponding tuple.
getArea :: String -> String
getArea id_ = maybe "" snd $ getTuple id_
-- | A list of tuples that contain disciplines (areas), fill values, and courses
-- that are in the areas.
-- TODO: Remove colour dependencies, and probably the whole map.
areaMap :: M.Map [String] (T.Text, String)
areaMap = M.fromList
[
(["csc165", "csc236", "csc240", "csc263", "csc265",
"csc310", "csc373", "csc438", "csc448",
"csc463"], (theoryDark, "theory")),
(["csc207", "csc301", "csc302", "csc410", "csc465",
"csc324"], (seDark, "se")),
(["csc209", "csc258", "csc358", "csc369", "csc372",
"csc458", "csc469", "csc488", "ece385", "ece489",
"csc309", "csc343", "csc443"],
(systemsDark, "systems")),
(["csc200", "csc300", "csc318", "csc404", "csc428",
"csc454"], (hciDark, "hci")),
(["csc320", "csc418", "csc420"], (graphicsDark, "graphics")),
(["csc336", "csc436", "csc446", "csc456", "csc466"],
(numDark, "num")),
(["csc321", "csc384", "csc401", "csc411", "csc412",
"csc485", "csc486"], (aiDark, "ai")),
(["csc104", "csc120", "csc108", "csc148"], (introDark, "intro")),
(["calc1", "lin1", "sta1", "sta2"], (mathDark, "math"))]
-- ** Other helpers
-- | Strip disallowed characters from string for DOM id
toId :: String -> String
toId = filter (\c -> not $ elem c ",()/<>%")
| cchens/courseography | hs/Svg/Generator.hs | gpl-3.0 | 14,743 | 0 | 20 | 6,108 | 2,999 | 1,581 | 1,418 | 250 | 8 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.WebmasterTools.Types.Sum
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.WebmasterTools.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
| brendanhay/gogol | gogol-webmaster-tools/gen/Network/Google/WebmasterTools/Types/Sum.hs | mpl-2.0 | 617 | 0 | 5 | 101 | 35 | 29 | 6 | 8 | 0 |
{-# 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.DialogFlow.Projects.Locations.Agents.Environments.Sessions.EntityTypes.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes the specified session entity type.
--
-- /See:/ <https://cloud.google.com/dialogflow/ Dialogflow API Reference> for @dialogflow.projects.locations.agents.environments.sessions.entityTypes.delete@.
module Network.Google.Resource.DialogFlow.Projects.Locations.Agents.Environments.Sessions.EntityTypes.Delete
(
-- * REST Resource
ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDeleteResource
-- * Creating a Request
, projectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete
, ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete
-- * Request Lenses
, plaesetdXgafv
, plaesetdUploadProtocol
, plaesetdAccessToken
, plaesetdUploadType
, plaesetdName
, plaesetdCallback
) where
import Network.Google.DialogFlow.Types
import Network.Google.Prelude
-- | A resource alias for @dialogflow.projects.locations.agents.environments.sessions.entityTypes.delete@ method which the
-- 'ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete' request conforms to.
type ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDeleteResource
=
"v3" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Delete '[JSON] GoogleProtobufEmpty
-- | Deletes the specified session entity type.
--
-- /See:/ 'projectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete' smart constructor.
data ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete =
ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete'
{ _plaesetdXgafv :: !(Maybe Xgafv)
, _plaesetdUploadProtocol :: !(Maybe Text)
, _plaesetdAccessToken :: !(Maybe Text)
, _plaesetdUploadType :: !(Maybe Text)
, _plaesetdName :: !Text
, _plaesetdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plaesetdXgafv'
--
-- * 'plaesetdUploadProtocol'
--
-- * 'plaesetdAccessToken'
--
-- * 'plaesetdUploadType'
--
-- * 'plaesetdName'
--
-- * 'plaesetdCallback'
projectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete
:: Text -- ^ 'plaesetdName'
-> ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete
projectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete pPlaesetdName_ =
ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete'
{ _plaesetdXgafv = Nothing
, _plaesetdUploadProtocol = Nothing
, _plaesetdAccessToken = Nothing
, _plaesetdUploadType = Nothing
, _plaesetdName = pPlaesetdName_
, _plaesetdCallback = Nothing
}
-- | V1 error format.
plaesetdXgafv :: Lens' ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete (Maybe Xgafv)
plaesetdXgafv
= lens _plaesetdXgafv
(\ s a -> s{_plaesetdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plaesetdUploadProtocol :: Lens' ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete (Maybe Text)
plaesetdUploadProtocol
= lens _plaesetdUploadProtocol
(\ s a -> s{_plaesetdUploadProtocol = a})
-- | OAuth access token.
plaesetdAccessToken :: Lens' ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete (Maybe Text)
plaesetdAccessToken
= lens _plaesetdAccessToken
(\ s a -> s{_plaesetdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plaesetdUploadType :: Lens' ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete (Maybe Text)
plaesetdUploadType
= lens _plaesetdUploadType
(\ s a -> s{_plaesetdUploadType = a})
-- | Required. The name of the session entity type to delete. Format:
-- \`projects\/\/locations\/\/agents\/\/sessions\/\/entityTypes\/\` or
-- \`projects\/\/locations\/\/agents\/\/environments\/\/sessions\/\/entityTypes\/\`.
-- If \`Environment ID\` is not specified, we assume default \'draft\'
-- environment.
plaesetdName :: Lens' ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete Text
plaesetdName
= lens _plaesetdName (\ s a -> s{_plaesetdName = a})
-- | JSONP
plaesetdCallback :: Lens' ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete (Maybe Text)
plaesetdCallback
= lens _plaesetdCallback
(\ s a -> s{_plaesetdCallback = a})
instance GoogleRequest
ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete
where
type Rs
ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete
= GoogleProtobufEmpty
type Scopes
ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete
=
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/dialogflow"]
requestClient
ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDelete'{..}
= go _plaesetdName _plaesetdXgafv
_plaesetdUploadProtocol
_plaesetdAccessToken
_plaesetdUploadType
_plaesetdCallback
(Just AltJSON)
dialogFlowService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsAgentsEnvironmentsSessionsEntityTypesDeleteResource)
mempty
| brendanhay/gogol | gogol-dialogflow/gen/Network/Google/Resource/DialogFlow/Projects/Locations/Agents/Environments/Sessions/EntityTypes/Delete.hs | mpl-2.0 | 6,485 | 0 | 15 | 1,256 | 706 | 416 | 290 | 114 | 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.DialogFlow.Projects.Locations.Agents.Environments.Experiments.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns the list of all experiments in the specified Environment.
--
-- /See:/ <https://cloud.google.com/dialogflow/ Dialogflow API Reference> for @dialogflow.projects.locations.agents.environments.experiments.list@.
module Network.Google.Resource.DialogFlow.Projects.Locations.Agents.Environments.Experiments.List
(
-- * REST Resource
ProjectsLocationsAgentsEnvironmentsExperimentsListResource
-- * Creating a Request
, projectsLocationsAgentsEnvironmentsExperimentsList
, ProjectsLocationsAgentsEnvironmentsExperimentsList
-- * Request Lenses
, plaeelParent
, plaeelXgafv
, plaeelUploadProtocol
, plaeelAccessToken
, plaeelUploadType
, plaeelPageToken
, plaeelPageSize
, plaeelCallback
) where
import Network.Google.DialogFlow.Types
import Network.Google.Prelude
-- | A resource alias for @dialogflow.projects.locations.agents.environments.experiments.list@ method which the
-- 'ProjectsLocationsAgentsEnvironmentsExperimentsList' request conforms to.
type ProjectsLocationsAgentsEnvironmentsExperimentsListResource
=
"v3" :>
Capture "parent" Text :>
"experiments" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON]
GoogleCloudDialogflowCxV3ListExperimentsResponse
-- | Returns the list of all experiments in the specified Environment.
--
-- /See:/ 'projectsLocationsAgentsEnvironmentsExperimentsList' smart constructor.
data ProjectsLocationsAgentsEnvironmentsExperimentsList =
ProjectsLocationsAgentsEnvironmentsExperimentsList'
{ _plaeelParent :: !Text
, _plaeelXgafv :: !(Maybe Xgafv)
, _plaeelUploadProtocol :: !(Maybe Text)
, _plaeelAccessToken :: !(Maybe Text)
, _plaeelUploadType :: !(Maybe Text)
, _plaeelPageToken :: !(Maybe Text)
, _plaeelPageSize :: !(Maybe (Textual Int32))
, _plaeelCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsAgentsEnvironmentsExperimentsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plaeelParent'
--
-- * 'plaeelXgafv'
--
-- * 'plaeelUploadProtocol'
--
-- * 'plaeelAccessToken'
--
-- * 'plaeelUploadType'
--
-- * 'plaeelPageToken'
--
-- * 'plaeelPageSize'
--
-- * 'plaeelCallback'
projectsLocationsAgentsEnvironmentsExperimentsList
:: Text -- ^ 'plaeelParent'
-> ProjectsLocationsAgentsEnvironmentsExperimentsList
projectsLocationsAgentsEnvironmentsExperimentsList pPlaeelParent_ =
ProjectsLocationsAgentsEnvironmentsExperimentsList'
{ _plaeelParent = pPlaeelParent_
, _plaeelXgafv = Nothing
, _plaeelUploadProtocol = Nothing
, _plaeelAccessToken = Nothing
, _plaeelUploadType = Nothing
, _plaeelPageToken = Nothing
, _plaeelPageSize = Nothing
, _plaeelCallback = Nothing
}
-- | Required. The Environment to list all environments for. Format:
-- \`projects\/\/locations\/\/agents\/\/environments\/\`.
plaeelParent :: Lens' ProjectsLocationsAgentsEnvironmentsExperimentsList Text
plaeelParent
= lens _plaeelParent (\ s a -> s{_plaeelParent = a})
-- | V1 error format.
plaeelXgafv :: Lens' ProjectsLocationsAgentsEnvironmentsExperimentsList (Maybe Xgafv)
plaeelXgafv
= lens _plaeelXgafv (\ s a -> s{_plaeelXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plaeelUploadProtocol :: Lens' ProjectsLocationsAgentsEnvironmentsExperimentsList (Maybe Text)
plaeelUploadProtocol
= lens _plaeelUploadProtocol
(\ s a -> s{_plaeelUploadProtocol = a})
-- | OAuth access token.
plaeelAccessToken :: Lens' ProjectsLocationsAgentsEnvironmentsExperimentsList (Maybe Text)
plaeelAccessToken
= lens _plaeelAccessToken
(\ s a -> s{_plaeelAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plaeelUploadType :: Lens' ProjectsLocationsAgentsEnvironmentsExperimentsList (Maybe Text)
plaeelUploadType
= lens _plaeelUploadType
(\ s a -> s{_plaeelUploadType = a})
-- | The next_page_token value returned from a previous list request.
plaeelPageToken :: Lens' ProjectsLocationsAgentsEnvironmentsExperimentsList (Maybe Text)
plaeelPageToken
= lens _plaeelPageToken
(\ s a -> s{_plaeelPageToken = a})
-- | The maximum number of items to return in a single page. By default 20
-- and at most 100.
plaeelPageSize :: Lens' ProjectsLocationsAgentsEnvironmentsExperimentsList (Maybe Int32)
plaeelPageSize
= lens _plaeelPageSize
(\ s a -> s{_plaeelPageSize = a})
. mapping _Coerce
-- | JSONP
plaeelCallback :: Lens' ProjectsLocationsAgentsEnvironmentsExperimentsList (Maybe Text)
plaeelCallback
= lens _plaeelCallback
(\ s a -> s{_plaeelCallback = a})
instance GoogleRequest
ProjectsLocationsAgentsEnvironmentsExperimentsList
where
type Rs
ProjectsLocationsAgentsEnvironmentsExperimentsList
= GoogleCloudDialogflowCxV3ListExperimentsResponse
type Scopes
ProjectsLocationsAgentsEnvironmentsExperimentsList
=
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/dialogflow"]
requestClient
ProjectsLocationsAgentsEnvironmentsExperimentsList'{..}
= go _plaeelParent _plaeelXgafv _plaeelUploadProtocol
_plaeelAccessToken
_plaeelUploadType
_plaeelPageToken
_plaeelPageSize
_plaeelCallback
(Just AltJSON)
dialogFlowService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsAgentsEnvironmentsExperimentsListResource)
mempty
| brendanhay/gogol | gogol-dialogflow/gen/Network/Google/Resource/DialogFlow/Projects/Locations/Agents/Environments/Experiments/List.hs | mpl-2.0 | 7,043 | 0 | 18 | 1,519 | 886 | 514 | 372 | 137 | 1 |
module Kernel.Conversion where
import Kernel.Universe
import Kernel.Term
import Kernel.Env
import Kernel.KernelMonad
import Kernel.Reduce
import Control.Applicative
universeLe :: UnivExpr -> UnivExpr -> Kernel Bool
universeLe = go 0
where
go n UnivExpr0 UnivExpr0 | n >= 0 = return True
go n (UnivExprVar v1) (UnivExprVar v2) | n >= 0 && v1 == v2 = return True
go n (UnivExprMax u v) w =
(&&) <$> go n u w <*> go n v w
go n (UnivExprLift u i) v = go (n - i) u v
go n u (UnivExprLift v i) = go (n + i) u v
go n u (UnivExprVar v) = do ub <- getUniverseBindings
case lookup v ub of
Nothing -> fatalError $ "not declared universe: " ++ v
Just w -> go n u w
go n u (UnivExprMax v w) =
(||) <$> go n u v <*> go n u w
go _ _ _ = return False
universeEq :: UnivExpr -> UnivExpr -> Kernel Bool
universeEq u1 u2 = (&&) <$> universeLe u1 u2 <*> universeLe u2 u1
-- e |- t1 <: t2
convertible :: LocalEnv -> Term -> Term -> Kernel Bool
convertible e t1 t2 = do t1' <- reduceFull e t1
t2' <- reduceFull e t2
go False t1' t2'
where
go True (TmUniv u1) (TmUniv u2) = u1 `universeEq` u2
go False (TmUniv u1) (TmUniv u2) = u1 `universeLe` u2
go _ (TmVar v1) (TmVar v2) = return $ v1 == v2
go _ (TmConst v1) (TmConst v2) = return $ v1 == v2
go eq (TmProd _ ty1 body1) (TmProd _ ty2 body2) =
ands [go True ty1 ty2, go eq body1 body2]
go eq (TmAbs _ ty1 body1) (TmAbs _ ty2 body2) =
ands [go True ty1 ty2, go eq body1 body2]
go eq (TmApp f1 a1) (TmApp f2 a2) =
ands [go eq f1 f2, go True a1 a2]
go _ (TmEq a1 x1 y1) (TmEq a2 x2 y2) =
ands [go True a1 a2, go True x1 x2, go True y1 y2]
go _ (TmRefl a1 x1) (TmRefl a2 x2) =
ands [go True a1 a2, go True x1 x2]
go _ (TmEqInd ct1 c1 x1 y1 p1) (TmEqInd ct2 c2 x2 y2 p2) =
ands [go True ct1 ct2, go True c1 c2, go True x1 x2, go True y1 y2, go True p1 p2]
go _ _ _ = return False
ands = fmap and . sequence
| kik/ToyPr | src/Kernel/Conversion.hs | apache-2.0 | 2,118 | 0 | 13 | 696 | 1,006 | 497 | 509 | 46 | 11 |
-- |
-- Module : Criterion.Main
-- Copyright : (c) 2009-2014 Bryan O'Sullivan
--
-- License : BSD-style
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : GHC
--
-- Wrappers for compiling and running benchmarks quickly and easily.
-- See 'defaultMain' below for an example.
module Criterion.Main
(
-- * How to write benchmarks
-- $bench
-- ** Benchmarking IO actions
-- $io
-- ** Benchmarking pure code
-- $pure
-- ** Fully evaluating a result
-- $rnf
-- * Types
Benchmarkable
, Benchmark
-- * Creating a benchmark suite
, env
, bench
, bgroup
-- ** Running a benchmark
, nf
, whnf
, nfIO
, whnfIO
-- * Turning a suite of benchmarks into a program
, defaultMain
, defaultMainWith
, defaultConfig
-- * Other useful code
, makeMatcher
) where
import Control.Monad (unless)
import Control.Monad.Trans (liftIO)
import Criterion.IO.Printf (printError, writeCsv)
import Criterion.Internal (runAndAnalyse, runNotAnalyse, addPrefix)
import Criterion.Main.Options (MatchType(..), Mode(..), defaultConfig, describe,
versionInfo)
import Criterion.Measurement (initializeTime)
import Criterion.Monad (withConfig)
import Criterion.Types
import Data.Char (toLower)
import Data.List (isInfixOf, isPrefixOf, sort, stripPrefix)
import Data.Maybe (fromMaybe)
import Options.Applicative (execParser)
import System.Environment (getProgName)
import System.Exit (ExitCode(..), exitWith)
import System.FilePath.Glob
-- | An entry point that can be used as a @main@ function.
--
-- > import Criterion.Main
-- >
-- > fib :: Int -> Int
-- > fib 0 = 0
-- > fib 1 = 1
-- > fib n = fib (n-1) + fib (n-2)
-- >
-- > main = defaultMain [
-- > bgroup "fib" [ bench "10" $ whnf fib 10
-- > , bench "35" $ whnf fib 35
-- > , bench "37" $ whnf fib 37
-- > ]
-- > ]
defaultMain :: [Benchmark] -> IO ()
defaultMain = defaultMainWith defaultConfig
-- | Create a function that can tell if a name given on the command
-- line matches a benchmark.
makeMatcher :: MatchType
-> [String]
-- ^ Command line arguments.
-> Either String (String -> Bool)
makeMatcher matchKind args =
case matchKind of
Prefix -> Right $ \b -> null args || any (`isPrefixOf` b) args
Glob ->
let compOptions = compDefault { errorRecovery = False }
in case mapM (tryCompileWith compOptions) args of
Left errMsg -> Left . fromMaybe errMsg . stripPrefix "compile :: " $
errMsg
Right ps -> Right $ \b -> null ps || any (`match` b) ps
Pattern -> Right $ \b -> null args || any (`isInfixOf` b) args
IPattern -> Right $ \b -> null args || any (`isInfixOf` map toLower b) (map (map toLower) args)
selectBenches :: MatchType -> [String] -> Benchmark -> IO (String -> Bool)
selectBenches matchType benches bsgroup = do
let go pfx (Environment _ b) = go pfx (b undefined)
go pfx (BenchGroup pfx' bms) = concatMap (go (addPrefix pfx pfx')) bms
go pfx (Benchmark desc _) = [addPrefix pfx desc]
toRun <- either parseError return . makeMatcher matchType $ benches
unless (null benches || any toRun (go "" bsgroup)) $
parseError "none of the specified names matches a benchmark"
return toRun
-- | An entry point that can be used as a @main@ function, with
-- configurable defaults.
--
-- Example:
--
-- > import Criterion.Main.Options
-- > import Criterion.Main
-- >
-- > myConfig = defaultConfig {
-- > -- Do not GC between runs.
-- > forceGC = False
-- > }
-- >
-- > main = defaultMainWith myConfig [
-- > bench "fib 30" $ whnf fib 30
-- > ]
--
-- If you save the above example as @\"Fib.hs\"@, you should be able
-- to compile it as follows:
--
-- > ghc -O --make Fib
--
-- Run @\"Fib --help\"@ on the command line to get a list of command
-- line options.
defaultMainWith :: Config
-> [Benchmark]
-> IO ()
defaultMainWith defCfg bs = do
wat <- execParser (describe defCfg)
let bsgroup = BenchGroup "" bs
case wat of
List -> mapM_ putStrLn . sort . concatMap benchNames $ bs
Version -> putStrLn versionInfo
OnlyRun iters matchType benches -> do
shouldRun <- selectBenches matchType benches bsgroup
withConfig defaultConfig $
runNotAnalyse iters shouldRun bsgroup
Run cfg matchType benches -> do
shouldRun <- selectBenches matchType benches bsgroup
withConfig cfg $ do
writeCsv ("Name","Mean","MeanLB","MeanUB","Stddev","StddevLB",
"StddevUB")
liftIO initializeTime
runAndAnalyse shouldRun bsgroup
-- | Display an error message from a command line parsing failure, and
-- exit.
parseError :: String -> IO a
parseError msg = do
_ <- printError "Error: %s\n" msg
_ <- printError "Run \"%s --help\" for usage information\n" =<< getProgName
exitWith (ExitFailure 64)
-- $bench
--
-- The 'Benchmarkable' type is a container for code that can be
-- benchmarked. The value inside must run a benchmark the given
-- number of times. We are most interested in benchmarking two
-- things:
--
-- * 'IO' actions. Any 'IO' action can be benchmarked directly.
--
-- * Pure functions. GHC optimises aggressively when compiling with
-- @-O@, so it is easy to write innocent-looking benchmark code that
-- doesn't measure the performance of a pure function at all. We
-- work around this by benchmarking both a function and its final
-- argument together.
-- $io
--
-- Any 'IO' action can be benchmarked easily if its type resembles
-- this:
--
-- @
-- 'IO' a
-- @
-- $pure
--
-- Because GHC optimises aggressively when compiling with @-O@, it is
-- potentially easy to write innocent-looking benchmark code that will
-- only be evaluated once, for which all but the first iteration of
-- the timing loop will be timing the cost of doing nothing.
--
-- To work around this, we provide two functions for benchmarking pure
-- code.
--
-- The first will cause results to be fully evaluated to normal form
-- (NF):
--
-- @
-- 'nf' :: 'NFData' b => (a -> b) -> a -> 'Benchmarkable'
-- @
--
-- The second will cause results to be evaluated to weak head normal
-- form (the Haskell default):
--
-- @
-- 'whnf' :: (a -> b) -> a -> 'Benchmarkable'
-- @
--
-- As both of these types suggest, when you want to benchmark a
-- function, you must supply two values:
--
-- * The first element is the function, saturated with all but its
-- last argument.
--
-- * The second element is the last argument to the function.
--
-- Here is an example that makes the use of these functions clearer.
-- Suppose we want to benchmark the following function:
--
-- @
-- firstN :: Int -> [Int]
-- firstN k = take k [(0::Int)..]
-- @
--
-- So in the easy case, we construct a benchmark as follows:
--
-- @
-- 'nf' firstN 1000
-- @
-- $rnf
--
-- The 'whnf' harness for evaluating a pure function only evaluates
-- the result to weak head normal form (WHNF). If you need the result
-- evaluated all the way to normal form, use the 'nf' function to
-- force its complete evaluation.
--
-- Using the @firstN@ example from earlier, to naive eyes it might
-- /appear/ that the following code ought to benchmark the production
-- of the first 1000 list elements:
--
-- @
-- 'whnf' firstN 1000
-- @
--
-- Since we are using 'whnf', in this case the result will only be
-- forced until it reaches WHNF, so what this would /actually/
-- benchmark is merely how long it takes to produce the first list
-- element!
| osa1/criterion | Criterion/Main.hs | bsd-2-clause | 7,712 | 0 | 17 | 1,863 | 1,162 | 678 | 484 | 81 | 5 |
{-# OPTIONS_GHC -Wall #-}
module Primitives
( primitiveEnv )
where
import Control.Exception.Base
import qualified Data.HashMap.Lazy as Map
import SExpr
-- Error thrown when the number of arguments to a functions is wrong.
airityError :: IO SExpr
airityError = (return . Err) "Wrong airity!"
-- Type error.
expectingError :: String -> IO SExpr
expectingError s = return . Err $ "Function expecting " ++ s ++ "!"
-- Int -> Int -> Int function wrapped into a primitive function.
intintPrim :: (Int -> Int -> Int) -> [SExpr] -> IO SExpr
intintPrim fun args
| length args < 2 = airityError
| all isInt args = return . Int $ foldl1 fun (map unpackInt args)
| otherwise = expectingError "integers"
-- Int division.
divPrim :: [SExpr] -> IO SExpr
divPrim args
| all isInt args &&
notElem (Int 0) args = return . Int $ foldl1 div (map unpackInt args)
| all isInt args = (return . Err) "Division by zero!"
| otherwise = expectingError "integers"
-- Equal and not equal function wrapper.
eqneqPrim :: (SExpr -> SExpr -> Bool) -> [SExpr] -> IO SExpr
eqneqPrim fun [exp1, exp2] = return . Bool $ fun exp1 exp2
eqneqPrim _ _ = airityError
-- Wrapper for functions that compare ints.
intComparisonPrim :: (Int -> Int -> Bool) -> [SExpr] -> IO SExpr
intComparisonPrim fun [Int i1, Int i2] = return . Bool $ fun i1 i2
intComparisonPrim _ [_, _] = expectingError "two integers"
intComparisonPrim _ _ = airityError
-- List head.
headPrim :: [SExpr] -> IO SExpr
headPrim [List []] = expectingError "non-empty list"
headPrim [List l] = return (head l)
headPrim [_] = expectingError "list"
headPrim _ = airityError
-- List tail.
tailPrim :: [SExpr] -> IO SExpr
tailPrim [List []] = expectingError "non-empty list"
tailPrim [List l] = return . List $ tail l
tailPrim [_] = expectingError "list"
tailPrim _ = airityError
-- Cons for lists.
consPrim :: [SExpr] -> IO SExpr
consPrim [val, List l] = return . List $ val : l
consPrim [_, _] = expectingError "value and list"
consPrim _ = airityError
-- Concat/paste strings or lists.
concatPrim :: [SExpr] -> IO SExpr
concatPrim args
| length args < 2 = airityError
| all isString args = return . String $ foldl1 (++) $ map unpackString args
| all isList args = return . List $ foldl1 (++) $ map unpackList args
| otherwise = expectingError "strings or lists"
stringPrim :: [SExpr] -> IO SExpr
stringPrim = return . String . unwords . map show
-- Throw an error.
errorPrim :: [SExpr] -> IO SExpr
errorPrim [String message] = (return . Err) message
errorPrim [_] = expectingError "string"
errorPrim _ = airityError
-- Print to stdout.
printPrim :: [SExpr] -> IO SExpr
printPrim args = putStrLn (concatMap show args) >> return Nil
-- Read string from stdin. TODO
readPrim :: [SExpr] -> IO SExpr
readPrim [] = fmap String getLine
readPrim _ = airityError
-- Read a file.
slurpPrim :: [SExpr] -> IO SExpr
slurpPrim [String filename] = catch (fmap String (readFile filename))
(openFileHandler filename)
slurpPrim [_] = expectingError "string"
slurpPrim _ = airityError
-- Error handler for slurpPrim.
openFileHandler :: String -> IOError -> IO SExpr
openFileHandler name _ = return . Err $ "File \"" ++ name ++ "\" not found!"
-- Environment containing primitive functions.
primitiveEnv :: Scope
primitiveEnv = Map.fromList [ ("+", Primitive $ intintPrim (+))
, ("-", Primitive $ intintPrim (-))
, ("*", Primitive $ intintPrim (*))
, ("div", Primitive divPrim)
, ("rem", Primitive $ intintPrim rem)
, ("=", Primitive $ eqneqPrim (==))
, ("not=", Primitive $ eqneqPrim (/=))
, (">", Primitive $ intComparisonPrim (>))
, (">=", Primitive $ intComparisonPrim (>=))
, ("<", Primitive $ intComparisonPrim (<))
, ("<=", Primitive $ intComparisonPrim (<=))
, ("head", Primitive headPrim)
, ("tail", Primitive tailPrim)
, ("cons", Primitive consPrim)
, ("concat", Primitive concatPrim)
, ("string", Primitive stringPrim)
, ("error", Primitive errorPrim)
, ("print", Primitive printPrim)
, ("read", Primitive readPrim)
, ("slurp", Primitive slurpPrim)
]
| mtsch/basic-lisp | src/Primitives.hs | bsd-2-clause | 4,865 | 0 | 11 | 1,564 | 1,427 | 750 | 677 | 87 | 1 |
module ZHelpers where
import System.ZMQ
import System.Random
import Numeric (showHex)
import Control.Monad (foldM)
import Control.Applicative ((<*>))
import Data.ByteString.Char8 (pack, unpack, ByteString, cons, empty)
import Data.Char (ord)
import Text.Printf (printf)
import qualified Data.ByteString as B
-- Not Tail Recursive
recvMultipart :: Socket a -> IO [String]
recvMultipart sock = do
recv <- fmap unpack $ receive sock []
mre <- moreToReceive sock
if mre
then do
remainder <- recvMultipart sock
return $ recv : remainder
else return [recv]
sendMultipart :: [String] -> Socket a -> IO ()
sendMultipart [] sock = return ()
sendMultipart [x] sock = send sock (pack x) []
sendMultipart (x:xs) sock = send sock (pack x) [SndMore] >> sendMultipart xs sock
dumpMsg :: [B.ByteString] -> IO ()
dumpMsg msg_parts = do
putStrLn "----------------------------------------"
mapM_ (\i -> putStr (printf "[%03d] " (B.length i)) >> func (unpack i)) msg_parts where
func :: String -> IO ()
func item | all (\c -> (ord c >= 32) && (ord c <= 128)) item = putStrLn item
| otherwise = putStrLn $ prettyPrint $ pack item
dumpSock :: Socket a -> IO ()
dumpSock sock = fmap reverse (recvMultipart sock) >>= dumpMsg . map pack
-- In General Since We use Randomness, You should Pass in
-- an StdGen, but for simplicity we just use newStdGen
setId :: Socket a -> IO ()
setId sock = do
gen <- newStdGen
let (val1, gen') = randomR (0 :: Int, 65536) gen
let (val2, gen'') = randomR (0 :: Int, 65536) gen'
let string_id = show val1 ++ show val2
setOption sock (Identity string_id)
zpipe :: Context -> (Socket Pair -> Socket Pair -> IO a) -> IO a
zpipe ctx func = withSocket ctx Pair $ \sock_a -> do
setOption sock_a (Linger 0)
setOption sock_a (HighWM 1)
withSocket ctx Pair $ \sock_b -> do
setOption sock_b (Linger 0)
setOption sock_b (HighWM 1)
bytes <- genKBytes 8
let iface = "inproc://" ++ prettyPrint bytes
bind sock_a iface
connect sock_b iface
func sock_a sock_b
-- In General Since We use Randomness, You should Pass in
-- an StdGen, but for simplicity we just use newStdGen
genKBytes :: Int -> IO B.ByteString
genKBytes k = do
gen <- newStdGen
bs <- foldM (\(g, s) _i -> let (val, g') = random g in return (g', cons val s)) (gen, empty) [1..k]
return $ snd bs
prettyPrint :: B.ByteString -> String
prettyPrint = concatMap (`showHex` "") . B.unpack | krattai/noo-ebs | docs/zeroMQ-guide2/examples/Haskell/zhelpers.hs | bsd-2-clause | 2,546 | 0 | 17 | 611 | 978 | 487 | 491 | 58 | 2 |
{-# LANGUAGE PatternGuards #-}
module Idris.CaseSplit(splitOnLine, replaceSplits,
getClause, getProofClause,
mkWith,
nameMissing,
getUniq, nameRoot) where
-- splitting a variable in a pattern clause
import Idris.AbsSyntax
import Idris.ElabDecls
import Idris.ElabTerm
import Idris.Delaborate
import Idris.Parser
import Idris.Error
import Idris.Output
import Idris.Core.TT
import Idris.Core.Typecheck
import Idris.Core.Evaluate
import Data.Maybe
import Data.Char
import Data.List (isPrefixOf, isSuffixOf)
import Control.Monad
import Control.Monad.State.Strict
import Text.Parser.Combinators
import Text.Parser.Char(anyChar)
import Text.Trifecta(Result(..), parseString)
import Text.Trifecta.Delta
import qualified Data.ByteString.UTF8 as UTF8
import Debug.Trace
{-
Given a pattern clause and a variable 'n', elaborate the clause and find the
type of 'n'.
Make new pattern clauses by replacing 'n' with all the possibly constructors
applied to '_', and replacing all other variables with '_' in order to
resolve other dependencies.
Finally, merge the generated patterns with the original, by matching.
Always take the "more specific" argument when there is a discrepancy, i.e.
names over '_', patterns over names, etc.
-}
-- Given a variable to split, and a term application, return a list of
-- variable updates
split :: Name -> PTerm -> Idris [[(Name, PTerm)]]
split n t'
= do ist <- getIState
-- Make sure all the names in the term are accessible
mapM_ (\n -> setAccessibility n Public) (allNamesIn t')
(tm, ty, pats) <- elabValBind toplevel True True (addImplPat ist t')
-- ASSUMPTION: tm is in normal form after elabValBind, so we don't
-- need to do anything special to find out what family each argument
-- is in
logLvl 4 ("Elaborated:\n" ++ show tm ++ " : " ++ show ty ++ "\n" ++ show pats)
-- iputStrLn (show (delab ist tm) ++ " : " ++ show (delab ist ty))
-- iputStrLn (show pats)
let t = mergeUserImpl (addImplPat ist t') (delab ist tm)
let ctxt = tt_ctxt ist
case lookup n pats of
Nothing -> fail $ show n ++ " is not a pattern variable"
Just ty ->
do let splits = findPats ist ty
iLOG ("New patterns " ++ showSep ", "
(map showTmImpls splits))
let newPats_in = zipWith (replaceVar ctxt n) splits (repeat t)
logLvl 4 ("Working from " ++ show t)
logLvl 4 ("Trying " ++ showSep "\n"
(map (showTmImpls) newPats_in))
newPats <- mapM elabNewPat newPats_in
logLvl 3 ("Original:\n" ++ show t)
logLvl 3 ("Split:\n" ++
(showSep "\n" (map show (mapMaybe id newPats))))
logLvl 3 "----"
let newPats' = mergeAllPats ist n t (mapMaybe id newPats)
iLOG ("Name updates " ++ showSep "\n"
(map (\ (p, u) -> show u ++ " " ++ show p) newPats'))
return (map snd newPats')
data MergeState = MS { namemap :: [(Name, Name)],
invented :: [(Name, Name)],
explicit :: [Name],
updates :: [(Name, PTerm)] }
addUpdate n tm = do ms <- get
put (ms { updates = ((n, stripNS tm) : updates ms) } )
inventName ist ty n =
do ms <- get
let supp = case ty of
Nothing -> []
Just t -> getNameHints ist t
let nsupp = case n of
MN i n | not (tnull n) && thead n == '_'
-> mkSupply (supp ++ varlist)
MN i n -> mkSupply (UN n : supp ++ varlist)
UN n | thead n == '_'
-> mkSupply (supp ++ varlist)
x -> mkSupply (x : supp)
let badnames = map snd (namemap ms) ++ map snd (invented ms) ++
explicit ms
case lookup n (invented ms) of
Just n' -> return n'
Nothing ->
do let n' = uniqueNameFrom nsupp badnames
put (ms { invented = (n, n') : invented ms })
return n'
mkSupply ns = mkSupply' ns (map nextName ns)
where mkSupply' xs ns' = xs ++ mkSupply ns'
varlist = map (sUN . (:[])) "xyzwstuv" -- EB's personal preference :)
stripNS tm = mapPT dens tm where
dens (PRef fc n) = PRef fc (nsroot n)
dens t = t
mergeAllPats :: IState -> Name -> PTerm -> [PTerm] -> [(PTerm, [(Name, PTerm)])]
mergeAllPats ist cv t [] = []
mergeAllPats ist cv t (p : ps)
= let (p', MS _ _ _ u) = runState (mergePat ist t p Nothing)
(MS [] [] (filter (/=cv) (patvars t)) [])
ps' = mergeAllPats ist cv t ps in
((p', u) : ps')
where patvars (PRef _ n) = [n]
patvars (PApp _ _ as) = concatMap (patvars . getTm) as
patvars (PPatvar _ n) = [n]
patvars _ = []
mergePat :: IState -> PTerm -> PTerm -> Maybe Name -> State MergeState PTerm
-- If any names are unified, make sure they stay unified. Always prefer
-- user provided name (first pattern)
mergePat ist (PPatvar fc n) new t
= mergePat ist (PRef fc n) new t
mergePat ist old (PPatvar fc n) t
= mergePat ist old (PRef fc n) t
mergePat ist orig@(PRef fc n) new@(PRef _ n') t
| isDConName n' (tt_ctxt ist) = do addUpdate n new
return new
| otherwise
= do ms <- get
case lookup n' (namemap ms) of
Just x -> do addUpdate n (PRef fc x)
return (PRef fc x)
Nothing -> do put (ms { namemap = ((n', n) : namemap ms) })
return (PRef fc n)
mergePat ist (PApp _ _ args) (PApp fc f args') t
= do newArgs <- zipWithM mergeArg args (zip args' (argTys ist f))
return (PApp fc f newArgs)
where mergeArg x (y, t)
= do tm' <- mergePat ist (getTm x) (getTm y) t
case x of
(PImp _ _ _ _ _) ->
return (y { machine_inf = machine_inf x,
getTm = tm' })
_ -> return (y { getTm = tm' })
mergePat ist (PRef fc n) tm ty = do tm <- tidy ist tm ty
addUpdate n tm
return tm
mergePat ist x y t = return y
mergeUserImpl :: PTerm -> PTerm -> PTerm
mergeUserImpl x y = x
argTys :: IState -> PTerm -> [Maybe Name]
argTys ist (PRef fc n)
= case lookupTy n (tt_ctxt ist) of
[ty] -> map (tyName . snd) (getArgTys ty) ++ repeat Nothing
_ -> repeat Nothing
where tyName (Bind _ (Pi _) _) = Just (sUN "->")
tyName t | (P _ n _, _) <- unApply t = Just n
| otherwise = Nothing
argTys _ _ = repeat Nothing
tidy :: IState -> PTerm -> Maybe Name -> State MergeState PTerm
tidy ist orig@(PRef fc n) ty
= do ms <- get
case lookup n (namemap ms) of
Just x -> return (PRef fc x)
Nothing -> case n of
(UN _) -> return orig
_ -> do n' <- inventName ist ty n
return (PRef fc n')
tidy ist (PApp fc f args) ty
= do args' <- zipWithM tidyArg args (argTys ist f)
return (PApp fc f args')
where tidyArg x ty' = do tm' <- tidy ist (getTm x) ty'
return (x { getTm = tm' })
tidy ist tm ty = return tm
-- mapPT tidyVar tm
-- where tidyVar (PRef _ _) = Placeholder
-- tidyVar t = t
elabNewPat :: PTerm -> Idris (Maybe PTerm)
elabNewPat t = idrisCatch (do (tm, ty) <- elabVal toplevel True t
i <- getIState
return (Just (delab i tm)))
(\e -> do i <- getIState
logLvl 5 $ "Not a valid split:\n" ++ pshow i e
return Nothing)
findPats :: IState -> Type -> [PTerm]
findPats ist t | (P _ n _, _) <- unApply t
= case lookupCtxt n (idris_datatypes ist) of
[ti] -> map genPat (con_names ti)
_ -> [Placeholder]
where genPat n = case lookupCtxt n (idris_implicits ist) of
[args] -> PApp emptyFC (PRef emptyFC n)
(map toPlaceholder args)
_ -> error $ "Can't happen (genPat) " ++ show n
toPlaceholder tm = tm { getTm = Placeholder }
findPats ist t = [Placeholder]
replaceVar :: Context -> Name -> PTerm -> PTerm -> PTerm
replaceVar ctxt n t (PApp fc f pats) = PApp fc f (map substArg pats)
where subst :: PTerm -> PTerm
subst orig@(PPatvar _ v) | v == n = t
| otherwise = Placeholder
subst orig@(PRef _ v) | v == n = t
| isDConName v ctxt = orig
subst (PRef _ _) = Placeholder
subst (PApp fc (PRef _ t) pats)
| isTConName t ctxt = Placeholder -- infer types
subst (PApp fc f pats) = PApp fc f (map substArg pats)
subst (PEq fc l r) = Placeholder -- PEq fc (subst l) (subst r)
subst x = x
substArg arg = arg { getTm = subst (getTm arg) }
replaceVar ctxt n t pat = pat
splitOnLine :: Int -- ^ line number
-> Name -- ^ variable
-> FilePath -- ^ name of file
-> Idris [[(Name, PTerm)]]
splitOnLine l n fn = do
-- let (before, later) = splitAt (l-1) (lines inp)
-- i <- getIState
cl <- getInternalApp fn l
logLvl 3 ("Working with " ++ showTmImpls cl)
tms <- split n cl
-- iputStrLn (showSep "\n" (map show tms))
return tms -- "" -- not yet done...
replaceSplits :: String -> [[(Name, PTerm)]] -> Idris [String]
replaceSplits l ups = updateRHSs 1 (map (rep (expandBraces l)) ups)
where
rep str [] = str ++ "\n"
rep str ((n, tm) : ups) = rep (updatePat False (show n) (nshow tm) str) ups
updateRHSs i [] = return []
updateRHSs i (x : xs) = do (x', i') <- updateRHS i x
xs' <- updateRHSs i' xs
return (x' : xs')
updateRHS i ('?':'=':xs) = do (xs', i') <- updateRHS i xs
return ("?=" ++ xs', i')
updateRHS i ('?':xs) = do let (nm, rest) = span (not . isSpace) xs
(nm', i') <- getUniq nm i
return ('?':nm' ++ rest, i')
updateRHS i (x : xs) = do (xs', i') <- updateRHS i xs
return (x : xs', i')
updateRHS i [] = return ("", i)
-- TMP HACK: If there are Nats, we don't want to show as numerals since
-- this isn't supported in a pattern, so special case here
nshow (PRef _ (UN z)) | z == txt "Z" = "Z"
nshow (PApp _ (PRef _ (UN s)) [x]) | s == txt "S" =
"S " ++ addBrackets (nshow (getTm x))
nshow t = show t
-- if there's any {n} replace with {n=n}
expandBraces ('{' : xs)
= let (brace, (_:rest)) = span (/= '}') xs in
if (not ('=' `elem` brace))
then ('{' : brace ++ " = " ++ brace ++ "}") ++
expandBraces rest
else ('{' : brace ++ "}") ++ expandBraces rest
expandBraces (x : xs) = x : expandBraces xs
expandBraces [] = []
updatePat start n tm [] = []
updatePat start n tm ('{':rest) =
let (space, rest') = span isSpace rest in
'{' : space ++ updatePat False n tm rest'
updatePat True n tm xs@(c:rest) | length xs > length n
= let (before, after@(next:_)) = splitAt (length n) xs in
if (before == n && not (isAlphaNum next))
then addBrackets tm ++ updatePat False n tm after
else c : updatePat (not (isAlphaNum c)) n tm rest
updatePat start n tm (c:rest) = c : updatePat (not (isAlpha c)) n tm rest
addBrackets tm | ' ' `elem` tm
, not (isPrefixOf "(" tm)
, not (isSuffixOf ")" tm) = "(" ++ tm ++ ")"
| otherwise = tm
getUniq nm i
= do ist <- getIState
let n = nameRoot [] nm ++ "_" ++ show i
case lookupTy (sUN n) (tt_ctxt ist) of
[] -> return (n, i+1)
_ -> getUniq nm (i+1)
nameRoot acc nm | all isDigit nm = showSep "_" acc
nameRoot acc nm =
case span (/='_') nm of
(before, ('_' : after)) -> nameRoot (acc ++ [before]) after
_ -> showSep "_" (acc ++ [nm])
getClause :: Int -- ^ line number that the type is declared on
-> Name -- ^ Function name
-> FilePath -- ^ Source file name
-> Idris String
getClause l fn fp = do ty <- getInternalApp fp l
ist <- get
let ap = mkApp ist ty []
return (show fn ++ " " ++ ap ++
"= ?" ++ show fn ++ "_rhs")
where mkApp i (PPi (Exp _ _ False) (MN _ _) ty sc) used
= let n = getNameFrom i used ty in
show n ++ " " ++ mkApp i sc (n : used)
mkApp i (PPi (Exp _ _ False) (UN n) ty sc) used
| thead n == '_'
= let n = getNameFrom i used ty in
show n ++ " " ++ mkApp i sc (n : used)
mkApp i (PPi (Exp _ _ False) n _ sc) used
= show n ++ " " ++ mkApp i sc (n : used)
mkApp i (PPi _ _ _ sc) used = mkApp i sc used
mkApp i _ _ = ""
getNameFrom i used (PPi _ _ _ _)
= uniqueNameFrom (mkSupply [sUN "f", sUN "g"]) used
getNameFrom i used (PApp fc f as) = getNameFrom i used f
getNameFrom i used (PEq _ _ _) = uniqueNameFrom [sUN "prf"] used
getNameFrom i used (PRef fc f)
= case getNameHints i f of
[] -> uniqueName (sUN "x") used
ns -> uniqueNameFrom (mkSupply ns) used
getNameFrom i used _ = uniqueName (sUN "x") used
getProofClause :: Int -- ^ line number that the type is declared
-> Name -- ^ Function name
-> FilePath -- ^ Source file name
-> Idris String
getProofClause l fn fp
= do ty <- getInternalApp fp l
return (mkApp ty ++ " = ?" ++ show fn ++ "_rhs")
where mkApp (PPi _ _ _ sc) = mkApp sc
mkApp rt = "(" ++ show rt ++ ") <== " ++ show fn
-- Purely syntactic - turn a pattern match clause into a with and a new
-- match clause
mkWith :: String -> Name -> String
mkWith str n = let str' = replaceRHS str "with (_)"
in str' ++ "\n" ++ newpat str
where replaceRHS [] str = str
replaceRHS ('?':'=': rest) str = str
replaceRHS ('=': rest) str
| not ('=' `elem` rest) = str
replaceRHS (x : rest) str = x : replaceRHS rest str
newpat ('>':patstr) = '>':newpat patstr
newpat patstr =
" " ++
replaceRHS patstr "| with_pat = ?" ++ show n ++ "_rhs"
-- Replace _ with names in missing clauses
nameMissing :: [PTerm] -> Idris [PTerm]
nameMissing ps = do ist <- get
newPats <- mapM nm ps
let newPats' = mergeAllPats ist (sUN "_") (base (head ps))
newPats
return (map fst newPats')
where
base (PApp fc f args) = PApp fc f (map (fmap (const (PRef fc (sUN "_")))) args)
base t = t
nm ptm = do mptm <- elabNewPat ptm
case mptm of
Nothing -> return ptm
Just ptm' -> return ptm'
| DanielWaterworth/Idris-dev | src/Idris/CaseSplit.hs | bsd-3-clause | 16,001 | 0 | 22 | 6,171 | 5,659 | 2,807 | 2,852 | 309 | 15 |
-- | A thread-safe DNS library for both clients and servers written
-- in pure Haskell.
-- The Network.DNS module re-exports all other exposed modules for
-- convenience.
-- Applications will most likely use the high-level interface, while
-- library/daemon authors may need to use the lower-level one.
-- EDNS and TCP fallback are supported.
--
-- Examples:
--
-- >>> rs <- makeResolvSeed defaultResolvConf
-- >>> withResolver rs $ \resolver -> lookupA resolver "192.0.2.1.nip.io"
-- Right [192.0.2.1]
module Network.DNS (
-- * High level
module Network.DNS.Lookup
-- | This module contains simple functions to
-- perform various DNS lookups. If you simply want to resolve a
-- hostname ('lookupA'), or find a domain's MX record
-- ('lookupMX'), this is the easiest way to do it.
, module Network.DNS.Resolver
-- | Resolver related data types.
, module Network.DNS.Types
-- | All of the types that the other modules use.
, module Network.DNS.Utils
-- | This module contains utility functions used
-- for processing DNS data.
-- * Middle level
, module Network.DNS.LookupRaw
-- | This provides the 'lookup', 'lookupAuth', 'lookupRaw' and
-- 'lookupRawCtl' functions for any resource records.
-- * Low level
, module Network.DNS.Encode
-- | Encoding a query or response.
, module Network.DNS.Decode
-- | Decoding a qurey or response.
, module Network.DNS.IO
-- | Sending and receiving.
) where
import Network.DNS.Decode
import Network.DNS.Encode
import Network.DNS.IO
import Network.DNS.Lookup
import Network.DNS.LookupRaw
import Network.DNS.Resolver
import Network.DNS.Types
import Network.DNS.Utils
| kazu-yamamoto/dns | Network/DNS.hs | bsd-3-clause | 1,688 | 0 | 5 | 326 | 141 | 106 | 35 | 17 | 0 |
{-# LANGUAGE DataKinds, NoPolyKinds #-}
module T11334 where
import Data.Functor.Compose
import Data.Proxy
p = Proxy :: Proxy 'Compose
| mcschroeder/ghc | testsuite/tests/dependent/should_fail/T11334.hs | bsd-3-clause | 137 | 0 | 6 | 21 | 29 | 18 | 11 | 5 | 1 |
module Y2017.Day02 (answer1, answer2) where
import Data.List (sort)
import qualified Control.Foldl as F
answer1, answer2 :: IO ()
answer1 = print $ sum $ map diff input
answer2 = print $ sum $ map ((\(a, b) -> b `div` a) . findDivisors) input
diff :: [Int] -> Int
diff xs =
let f = (,) <$> F.maximum <*> F.minimum
in case F.fold f xs of
(Just max, Just min) -> max - min
_ -> error "impossible"
-- assume the list is sorted in increasing order
findDivisors :: [Int] -> (Int, Int)
findDivisors = go Nothing
where
go _ [] = error "no divisors?"
go (Just x) xs =
let evenlyDivided = filter (\a -> a `rem` x == 0) xs
in if null evenlyDivided then go Nothing xs else (x, head evenlyDivided)
go Nothing (x:xs) = go (Just x) xs
test, test2 :: [[Int]]
test = [[5,1,9,5], [7,5,3], [2,4,6,8]]
test2 = map sort [[5,9,2,8], [9,4,7,3], [3,8,6,5]]
input :: [[Int]]
input = map sort
[ [3458, 3471, 163, 1299, 170, 4200, 2425, 167, 3636, 4001, 4162, 115, 2859, 130, 4075, 4269]
, [2777, 2712, 120, 2569, 2530, 3035, 1818, 32, 491, 872, 113, 92, 2526, 477, 138, 1360]
, [2316, 35, 168, 174, 1404, 1437, 2631, 1863, 1127, 640, 1745, 171, 2391, 2587, 214, 193]
, [197, 2013, 551, 1661, 121, 206, 203, 174, 2289, 843, 732, 2117, 360, 1193, 999, 2088]
, [3925, 3389, 218, 1134, 220, 171, 1972, 348, 3919, 3706, 494, 3577, 3320, 239, 120, 2508]
, [239, 947, 1029, 2024, 733, 242, 217, 1781, 2904, 2156, 1500, 3100, 497, 2498, 3312, 211]
, [188, 3806, 3901, 261, 235, 3733, 3747, 3721, 267, 3794, 3814, 3995, 3004, 915, 4062, 3400]
, [918, 63, 2854, 2799, 178, 176, 1037, 487, 206, 157, 2212, 2539, 2816, 2501, 927, 3147]
, [186, 194, 307, 672, 208, 351, 243, 180, 619, 749, 590, 745, 671, 707, 334, 224]
, [1854, 3180, 1345, 3421, 478, 214, 198, 194, 4942, 5564, 2469, 242, 5248, 5786, 5260, 4127]
, [3780, 2880, 236, 330, 3227, 1252, 3540, 218, 213, 458, 201, 408, 3240, 249, 1968, 2066]
, [1188, 696, 241, 57, 151, 609, 199, 765, 1078, 976, 1194, 177, 238, 658, 860, 1228]
, [903, 612, 188, 766, 196, 900, 62, 869, 892, 123, 226, 57, 940, 168, 165, 103]
, [710, 3784, 83, 2087, 2582, 3941, 97, 1412, 2859, 117, 3880, 411, 102, 3691, 4366, 4104]
, [3178, 219, 253, 1297, 3661, 1552, 8248, 678, 245, 7042, 260, 581, 7350, 431, 8281, 8117]
, [837, 80, 95, 281, 652, 822, 1028, 1295, 101, 1140, 88, 452, 85, 444, 649, 1247]
]
| geekingfrog/advent-of-code | src/Y2017/Day02.hs | bsd-3-clause | 2,462 | 0 | 15 | 597 | 1,294 | 815 | 479 | 40 | 4 |
{-#LANGUAGE ViewPatterns, NamedFieldPuns#-}
module Distribution.HBrew.DepGraph
( Graph, isUserPkg
, Node, packageInfo, cabalFile
, flatten
, lookupNodesFuzzy
, ancestor
, makeConfigGraph, makeProcedure
) where
import System.FilePath
import Data.Map (Map)
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import Data.Array
import Data.Maybe
import Data.List
import Distribution.Package hiding (depends)
import Distribution.Version
import Distribution.InstalledPackageInfo
import Distribution.HBrew.Utils
data Graph = Graph { nodes :: Map Node Int
, edges :: Array (Int,Int) Bool
, dict :: Map InstalledPackageId PackageId
, revDict :: Map PackageId [InstalledPackageId]
}
deriving Show
flatten :: Graph -> [Node]
flatten Graph{nodes} = M.keys nodes
updateDict :: Graph -> Graph
updateDict gr@Graph{nodes} =
let (dict, revDict) =
M.foldlWithKey (\(d, r) n _ -> let iid = installedPackageId $ packageInfo n
pid = sourcePackageId $ packageInfo n
in (M.insert iid pid d, M.insertWith (++) pid [iid] r)
) (M.empty, M.empty) nodes
in gr{dict = dict, revDict = revDict}
hasEdgeIdx :: Graph -> Int -> Int -> Bool
hasEdgeIdx Graph{edges} a b = edges ! (a,b)
data Node = UserPkg { packageInfo :: InstalledPackageInfo
, cabalFile :: FilePath
}
| GlobalPkg { packageInfo :: InstalledPackageInfo
, cabalFile :: FilePath
}
deriving Show
isUserPkg :: Node -> Bool
isUserPkg UserPkg{} = True
isUserPkg _ = False
isGlobalPkg :: Node -> Bool
isGlobalPkg GlobalPkg{} = True
isGlobalPkg _ = False
instance Eq Node where
a == b = installedPackageId (packageInfo a) == installedPackageId (packageInfo b)
instance Ord Node where
(packageInfo -> a) `compare` (packageInfo -> b) =
case sourcePackageId a `compare` sourcePackageId b
of EQ -> installedPackageId a `compare` installedPackageId b
o -> o
makeConfigGraph :: [FilePath] -> [FilePath] -> IO Graph
makeConfigGraph uConfs gConfs = do
hInfo <- mapM (\f -> readConfFileIO f >>= \info -> return $ UserPkg info f) $
filter ((== ".conf") . takeExtension) uConfs
gInfo <- mapM (\f -> readConfFileIO f >>= \info -> return $ GlobalPkg info f) gConfs
let info = gInfo ++ hInfo
nodes = M.fromList $ zip info [0..]
revNodes = IM.fromList $ zip [0..] info
rel = map (\i -> let inf = packageInfo i
in (installedPackageId inf, sourcePackageId inf)
) info
dict = M.fromList rel
revDict = M.fromListWith (++) $ map (\(i,p) -> (p, [i])) rel
size = M.size nodes - 1
edges = [((x,y), has) | x <- [0 .. size], y <- [0 .. size]
, let has = case IM.lookup x revNodes of
Nothing -> False
Just nx -> let iids = depends $ packageInfo nx
nds = map (\i -> lookupNode' i dict nodes) iids
ys = mapMaybe (\i -> case i of
Just ny -> M.lookup ny nodes
Nothing -> Nothing
) nds
in y `elem` ys
]
return $ Graph nodes (array ((0,0), (size,size)) edges) dict revDict
type Procedure = (Graph, [PackageId])
makeProcedure :: Graph -> [PackageId] -> Procedure
makeProcedure _all pids =
let nodes = nub $ concatMap (`lookupNodesByPid` _all) pids
rej = rejectConflicts pids . rejectConflictsWithToInstalls pids $ descendant _all nodes
ins = filter (`notMemberPid` rej) pids
in (dropGlobal rej, ins)
rejectConflictsWithToInstalls :: [PackageId] -> Graph -> Graph
rejectConflictsWithToInstalls _ins _gr@Graph{nodes = _nodes} =
let torej = ancestorIdx _gr. IS.fromList. M.elems $ M.filterWithKey
(\k _ -> let spid = (sourcePackageId. packageInfo) k
in foldl' (\b i -> ( packageName spid == packageName i &&
packageVersion spid /= packageVersion i) || b
) False _ins
) _nodes
in updateDict $ _gr{ nodes = M.filter (`IS.notMember` torej) _nodes }
rejectConflicts :: [PackageId] -> Graph -> Graph
rejectConflicts _ins _gr = updateDict $ _gr{nodes = foldl' sub (nodes _gr) $ conflicts _gr}
where sub nds c =
let hold = IS.fromList. M.elems $
case M.filterWithKey (\k _ -> (sourcePackageId. packageInfo) k `elem` _ins) c of
m | M.null m -> M.filterWithKey (\k _ -> isGlobalPkg k) c
| otherwise -> m
all_ = IS.fromList $ M.elems c
torej = ancestorIdx _gr $ all_ `IS.difference` hold
in M.filter (`IS.notMember` torej) nds
conflicts :: Graph -> [Map Node Int]
conflicts Graph{nodes} = sub nodes
where sub m = case M.minViewWithKey m of
Nothing -> []
Just ((n,i), mp) ->
let name = packageName. sourcePackageId . packageInfo
(c, o) = M.partitionWithKey (\k _ -> name n == name k) mp
in if M.null c then sub o else M.insert n i c : sub o
ancestorIdx :: Graph -> IntSet -> IntSet
ancestorIdx = dfsIdx parentIdx
ancestor :: Graph -> [Node] -> Graph
ancestor = (updateDict.) . dfs parentIdx
descendant :: Graph -> [Node] -> Graph
descendant = (updateDict.) . dfs childrenIdx
childrenIdx, parentIdx :: Graph -> Int -> IntSet
childrenIdx gr@Graph{nodes} i = IS.filter (hasEdgeIdx gr i) . IS.fromList $ M.elems nodes
parentIdx gr@Graph{nodes} i = IS.filter (flip (hasEdgeIdx gr) i) . IS.fromList $ M.elems nodes
dfs :: (Graph -> Int -> IntSet) -> Graph -> [Node] -> Graph
dfs fun gr@Graph{nodes} nds =
let idx = IS.fromList . catMaybes $ map (`M.lookup` nodes) nds
set = dfsIdx fun gr idx
in gr{nodes = M.filter (`IS.member` set) nodes}
dfsIdx :: (Graph -> Int -> IntSet) -> Graph -> IntSet -> IntSet
dfsIdx fun gr _is = _is `IS.union` go IS.empty _is
where go done is
| IS.null is = IS.empty
| otherwise = let neighbor = IS.foldl (\a k -> fun gr k `IS.union` a) IS.empty is
next = IS.filter (`IS.notMember` done) neighbor
nextdone = done `IS.union` neighbor
in neighbor `IS.union` go nextdone next
lookupNodesFuzzy :: PackageId -> Graph -> [Node]
lookupNodesFuzzy pid gr =
if packageVersion pid == Version [] []
then lookupNodesByPName (packageName pid) gr
else lookupNodesByPid pid gr
lookupNodesByPName :: PackageName -> Graph -> [Node]
lookupNodesByPName pname Graph{revDict, dict, nodes} = do
iids <- M.elems $ M.filterWithKey (curry $ (== pname). packageName .fst) revDict
mapMaybe (\iid -> lookupNode' iid dict nodes) iids
lookupNodesByPid :: PackageId -> Graph -> [Node]
lookupNodesByPid pid Graph{revDict, dict, nodes} = do
iids <- maybeToList $ M.lookup pid revDict
mapMaybe (\iid -> lookupNode' iid dict nodes) iids
lookupNode' :: InstalledPackageId -> Map InstalledPackageId PackageId -> Map Node b -> Maybe Node
lookupNode' iid dict nodes = do pid <- M.lookup iid dict
idx <- M.lookupIndex (UserPkg emptyInstalledPackageInfo {
installedPackageId = iid,
sourcePackageId = pid
} "") nodes
return . fst $ M.elemAt idx nodes
notMemberPid :: PackageId -> Graph -> Bool
notMemberPid pid Graph{revDict} = pid `M.notMember` revDict
dropGlobal :: Graph -> Graph
dropGlobal gr@Graph{nodes} =
updateDict $ gr{nodes = M.filterWithKey (\k _ -> isUserPkg k) nodes}
| philopon/hbrew | src/Distribution/HBrew/DepGraph.hs | bsd-3-clause | 8,408 | 1 | 29 | 2,855 | 2,803 | 1,482 | 1,321 | 162 | 3 |
-----------------------------------------------------------------------------
-- TIMonad: Type inference monad
--
-- Part of `Typing Haskell in Haskell', version of November 23, 2000
-- Copyright (c) Mark P Jones and the Oregon Graduate Institute
-- of Science and Technology, 1999-2000
--
-- This program is distributed as Free Software under the terms
-- in the file "License" that is included in the distribution
-- of this software, copies of which may be obtained from:
-- http://www.cse.ogi.edu/~mpj/thih/
--
-----------------------------------------------------------------------------
module TIMonad where
import Id
import Kind
import Type
import Subst
import Unify
import Pred
import Scheme
newtype TI a = TI (Subst -> Int -> (Subst, Int, a))
instance Monad TI where
return x = TI (\s n -> (s,n,x))
TI f >>= g = TI (\s n -> case f s n of
(s',m,x) -> let TI gx = g x
in gx s' m)
runTI :: TI a -> a
runTI (TI f) = x where (s,n,x) = f nullSubst 0
getSubst :: TI Subst
getSubst = TI (\s n -> (s,n,s))
unify :: Type -> Type -> TI ()
unify t1 t2 = do s <- getSubst
u <- mgu (apply s t1) (apply s t2)
extSubst u
trim :: [Tyvar] -> TI ()
trim vs = TI (\s n ->
let s' = [ (v,t) | (v,t) <-s, v `elem` vs ]
force = length (tv (map snd s'))
in force `seq` (s', n, ()))
extSubst :: Subst -> TI ()
extSubst s' = TI (\s n -> (s'@@s, n, ()))
newTVar :: Kind -> TI Type
newTVar k = TI (\s n -> let v = Tyvar (enumId n) k
in (s, n+1, TVar v))
freshInst :: Scheme -> TI (Qual Type)
freshInst (Forall ks qt) = do ts <- mapM newTVar ks
return (inst ts qt)
class Instantiate t where
inst :: [Type] -> t -> t
instance Instantiate Type where
inst ts (TAp l r) = TAp (inst ts l) (inst ts r)
inst ts (TGen n) = ts !! n
inst ts t = t
instance Instantiate a => Instantiate [a] where
inst ts = map (inst ts)
instance Instantiate t => Instantiate (Qual t) where
inst ts (ps :=> t) = inst ts ps :=> inst ts t
instance Instantiate Pred where
inst ts (IsIn c t) = IsIn c (inst ts t)
-----------------------------------------------------------------------------
| elben/typing-haskell-in-haskell | TIMonad.hs | bsd-3-clause | 2,433 | 0 | 16 | 784 | 862 | 452 | 410 | 47 | 1 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, StandaloneDeriving, OverloadedStrings #-}
module Main where
import QueryArrow.QueryPlan
import QueryArrow.DB.DB
import QueryArrow.DB.ResultStream
import QueryArrow.Syntax.Term
import QueryArrow.Parser
import QueryArrow.SQL.SQL
import qualified QueryArrow.Mapping as ICAT
import qualified QueryArrow.BuiltIn as BuiltIn
import qualified QueryArrow.SQL.ICAT as SQL.ICAT
import QueryArrow.Cypher.Mapping
import QueryArrow.Cypher.Cypher
import qualified QueryArrow.Cypher.Cypher as Cypher
import QueryArrow.DB.GenericDatabase
import QueryArrow.Utils
import Test.QuickCheck
import Control.Applicative ((<$>), (<*>))
import Control.Monad (replicateM)
import Text.Parsec (runParser)
import Data.Functor.Identity (runIdentity, Identity)
import Data.Map.Strict ((!), Map, empty, insert, fromList, singleton, toList)
import Control.Monad.Trans.State.Strict (StateT, evalState, runState, evalStateT, runStateT)
import Debug.Trace (trace)
import Test.Hspec
import Data.Monoid
import Data.Convertible
import Control.Monad.Trans.Except
import qualified Data.Text as T
import Control.Monad.IO.Class
import System.IO.Unsafe
import Data.Namespace.Namespace
import Data.Namespace.Path
import Data.Maybe
import Algebra.Lattice
import QueryArrow.Syntax.Serialize
import QueryArrow.Serialize
import qualified Data.Set as Set
standardPreds = (++) <$> (loadPreds "../QueryArrow-gen/gen/ICATGen.yaml") <*> pure BuiltIn.standardBuiltInPreds
standardMappings = (SQL.ICAT.loadMappings "../QueryArrow-gen/gen/SQL/ICATGen.yaml")
sqlStandardTrans ns = SQL.ICAT.sqlStandardTrans ns <$> standardPreds <*> standardMappings <*> pure (Just "nextid")
standardPredMap = ICAT.standardPredMap <$> standardPreds
parseStandardQuery :: String -> IO Formula
parseStandardQuery query2 = do
mappings <- standardPredMap
return (case runParser progp () "" query2 of
Left err -> let errmsg = "cannot parse " ++ query2 ++ show err in trace errmsg error ""
Right [Execute qu2] -> qu2)
qParseStandardQuery :: String -> String -> IO Formula
qParseStandardQuery ns query2 = do
preds <- ICAT.qStandardPredsMap ns <$> standardPreds
return (case runParser progp () "" query2 of
Left err -> let errmsg = "cannot parse " ++ query2 ++ show err in trace errmsg error ""
Right [Execute qu2] -> qu2)
translateQuery2 :: SQLTrans -> Set.Set Var -> Formula -> SQLQuery
translateQuery2 trans vars qu = translateQuery1 trans vars qu Set.empty
translateQuery1 :: SQLTrans -> Set.Set Var -> Formula -> Set.Set Var -> SQLQuery
translateQuery1 trans vars qu env =
let (SQLTrans builtin predtablemap _ ptm) = trans
env2 = foldl (\map2 key@(Var w) -> insert key (SQLParamExpr w) map2) empty env in
fst (runNew (runStateT (translateQueryToSQL (Set.toAscList vars) qu) (TransState {builtin = builtin, predtablemap = predtablemap, repmap = env2, tablemap = empty, nextid=Just (SQL.ICAT.nextidPred ["cat"] "nextid"), ptm = ptm})))
translateCypherQuery2 :: CypherTrans -> Set.Set Var -> Formula -> CypherQuery
translateCypherQuery2 trans vars qu = translateCypherQuery1 trans vars qu Set.empty
translateCypherQuery1 :: CypherTrans -> Set.Set Var -> Formula -> Set.Set Var -> CypherQuery
translateCypherQuery1 trans vars qu env =
let (CypherTrans builtin predtablemap ptm) = trans
env2 = foldl (\map2 key@(Var w) -> insert key (SQLParamExpr w) map2) empty env in
fst (runNew (runStateT (translateQueryToCypher qu) (builtin, predtablemap, mempty, Set.toAscList vars, Set.toAscList env, ptm)))
testTranslateSQLInsert :: String -> String -> String -> IO ()
testTranslateSQLInsert ns qus sqls = do
qu <- qParseStandardQuery "cat" qus
sql <- translateQuery2 <$> (sqlStandardTrans "cat") <*> pure Set.empty <*> pure qu
serialize ((\(_,x,_) -> x)sql) `shouldBe` sqls
main :: IO ()
main = hspec $ do
it "test translate cypher query 0" $ do
qu <- qParseStandardQuery "cat" "cat.DATA_NAME(x, y, z) return x y"
cyphertrans <- cypherTrans "cat" <$> standardPreds <*> standardMappings
let cypher = translateCypherQuery2 cyphertrans (Set.fromList [Var "x", Var "y"]) qu
serialize cypher `shouldBe` "MATCH (var:DataObject)-[var1:resc_id]->(var0) WITH var.data_id AS x,var0.resc_id AS y RETURN x,y"
it "test translate cypher query 1" $ do
qu <- qParseStandardQuery "cat" "cat.DATA_NAME(x, y, z) return x y z"
cyphertrans <- cypherTrans "cat" <$> standardPreds <*> standardMappings
let cypher = translateCypherQuery2 cyphertrans (Set.fromList [Var "x", Var "y", Var "z"]) qu
serialize cypher `shouldBe` "MATCH (var:DataObject)-[var1:resc_id]->(var0) WITH var.data_id AS x,var0.resc_id AS y,var.data_name AS z RETURN x,y,z"
it "test translate cypher query 2" $ do
qu <- qParseStandardQuery "cat" "cat.DATA_NAME(x, y, z) return z"
cyphertrans <- cypherTrans "cat" <$> standardPreds <*> standardMappings
let cypher = translateCypherQuery1 cyphertrans (Set.fromList [Var "z"]) qu (Set.fromList [Var "x", Var "y"])
serialize cypher `shouldBe` "WITH {x} AS x,{y} AS y MATCH (var:DataObject)-[var1:resc_id]->(var0) WHERE (var0.resc_id = y AND var.data_id = x) WITH var.data_name AS z RETURN z"
it "test translate cypher query 3" $ do
qu <- qParseStandardQuery "cat" "cat.COLL_NAME(x, y) return x y"
cyphertrans <- cypherTrans "cat" <$> standardPreds <*> standardMappings
let cypher = translateCypherQuery2 cyphertrans (Set.fromList [Var "x", Var "y"]) qu
serialize cypher `shouldBe` "MATCH (var:Collection) WITH var.coll_id AS x,var.coll_name AS y RETURN x,y"
it "test translate cypher query 4" $ do
qu <- qParseStandardQuery "cat" "cat.COLL_NAME(x, y) return y"
cyphertrans <- cypherTrans "cat" <$> standardPreds <*> standardMappings
let cypher = translateCypherQuery1 cyphertrans (Set.fromList [Var "y"]) qu (Set.fromList [Var "x"])
serialize cypher `shouldBe` "WITH {x} AS x MATCH (var:Collection) WHERE var.coll_id = x WITH var.coll_name AS y RETURN y"
it "test translate cypher query 5" $ do
qu <- qParseStandardQuery "cat" "cat.DATA_OBJ(x, y) return x y"
cyphertrans <- cypherTrans "cat" <$> standardPreds <*> standardMappings
let cypher = translateCypherQuery1 cyphertrans (Set.fromList []) qu (Set.fromList [Var "x", Var "y"])
serialize cypher `shouldBe` "WITH {x} AS x,{y} AS y MATCH (var0:DataObject)-[var1:resc_id]->(var) WHERE (var0.data_id = x AND var.resc_id = y) WITH 1 AS dummy RETURN 1"
it "test translate cypher query 6" $ do
qu <- qParseStandardQuery "cat" "cat.DATA_OBJ(x, y) return y"
cyphertrans <- cypherTrans "cat" <$> standardPreds <*> standardMappings
let cypher = translateCypherQuery1 cyphertrans (Set.fromList [Var "y"]) qu (Set.fromList [Var "x"])
serialize cypher `shouldBe` "WITH {x} AS x MATCH (var0:DataObject)-[var1:resc_id]->(var) WHERE var0.data_id = x WITH var.resc_id AS y RETURN y"
it "test translate cypher query 7" $ do
qu <- qParseStandardQuery "cat" "cat.DATA_OBJ(x, y) return x y"
cyphertrans <- cypherTrans "cat" <$> standardPreds <*> standardMappings
let cypher = translateCypherQuery1 cyphertrans (Set.fromList [Var "x", Var "y"]) qu (Set.fromList [])
serialize cypher `shouldBe` "MATCH (var0:DataObject)-[var1:resc_id]->(var) WITH var0.data_id AS x,var.resc_id AS y RETURN x,y"
it "test translate cypher insert 0" $ do
qu <- qParseStandardQuery "cat" "insert cat.DATA_NAME(x, y, z)"
cyphertrans <- cypherTrans "cat" <$> standardPreds <*> standardMappings
let cypher = translateCypherQuery1 cyphertrans (Set.fromList []) qu (Set.fromList [Var "x", Var "y",Var "z"])
serialize cypher `shouldBe` "WITH {x} AS x,{y} AS y,{z} AS z MATCH (var:DataObject)-[var1:resc_id]->(var0) WHERE (var0.resc_id = y AND var.data_id = x) SET var.data_name = z WITH 1 AS dummy RETURN 1"
it "test translate cypher insert 1" $ do
qu <- qParseStandardQuery "cat" "insert cat.DATA_OBJ(1, 2) cat.DATA_NAME(1, 2, \"foo\") cat.DATA_SIZE(1, 2, 1000)"
cyphertrans <- cypherTrans "cat" <$> standardPreds <*> standardMappings
let cypher = translateCypherQuery1 cyphertrans (Set.fromList []) qu (Set.fromList [Var "x", Var "y",Var "z"])
serialize cypher `shouldBe` "WITH {x} AS x,{y} AS y,{z} AS z MATCH (var{resc_id:2}) CREATE (var0:DataObject{data_id:1}),(var0)-[var1:resc_id]->(var) WITH 1 AS dummy MATCH (var2:DataObject{data_id:1})-[var4:resc_id]->(var3{resc_id:2}) SET var2.data_name = 'foo' WITH 1 AS dummy0 MATCH (var5:DataObject{data_id:1})-[var7:resc_id]->(var6{resc_id:2}) SET var5.data_size = 1000 WITH 1 AS dummy1 RETURN 1"
{- it "test translate cypher insert 2" $ do
let qu = parseStandardInsert "COLL_NAME(a,c) insert DATA_OBJ(1) DATA_NAME(1, c) DATA_SIZE(1, 1000)"
let sql = translateInsert (cypherTrans "") qu
show (snd sql) `shouldBe` "MATCH (var:Collection) CREATE (var2:DataObject{object_id:1,data_name:var.coll_name,data_size:1000})"
it "test translate cypher insert 3" $ do
let qu = parseStandardInsert "COLL_NAME(2,c) insert DATA_OBJ(1) DATA_NAME(1, c) DATA_SIZE(1, 1000)"
let sql = translateInsert (cypherTrans "") qu
show (snd sql) `shouldBe` "MATCH (var:Collection{object_id:2}) CREATE (var2:DataObject{object_id:1,data_name:var.coll_name,data_size:1000})"
it "test translate cypher insert 4" $ do
let qu = parseStandardInsert "insert ~DATA_NAME(1, c)"
let sql = translateInsert (cypherTrans "") qu
show (snd sql) `shouldBe` "MATCH (var:DataObject{object_id:1}) SET var.data_name = NULL"
it "test translate cypher insert 5" $ do
let qu = parseStandardInsert "insert ~DATA_NAME(1, c) DATA_NAME(1, \"foo\")"
let sql = translateInsert (cypherTrans "") qu
show (snd sql) `shouldBe` "MATCH (var:DataObject{object_id:1}) SET var.data_name = 'foo'"
it "test translate cypher insert 6" $ do
let qu = parseStandardInsert "insert ~DATA_NAME(x, c) DATA_NAME(x, \"foo\")"
let sql = translateInsert (cypherTrans "") qu
show (snd sql) `shouldBe` "MATCH (var:DataObject) SET var.data_name = 'foo'"
{- it "test translate cypher insert 7 E" $ do
let qu = parseStandardInsert "insert ~DATA_NAME(x, \"foo1\") DATA_NAME(x, \"foo\")"
val <- validate verifier2 qu
val `shouldNotBe` Nothing
-- let sql = translateInsert (cypherTrans "") qu
-- show sql `shouldBe` "MATCH (var:DataObject) SET var.data_name = 'foo'" -}
it "test translate cypher insert 7.1" $ do
let qu = parseStandardInsert "insert ~DATA_NAME(x, \"foo1\")"
let sql = translateInsert (cypherTrans "") qu
show (snd sql) `shouldBe` "MATCH (var:DataObject{data_name:'foo1'}) SET var.data_name = NULL"
{- it "test translate cypher insert 7.2 E" $ do
let qu = parseStandardInsert "insert ~DATA_NAME(x, \"foo1\") DATA_SIZE(x, 1000)"
val <- validate verifier2 qu
val `shouldNotBe` Nothing
-- let sql = translateInsert cypherTrans qu
-- show sql `shouldBe` "MATCH (var:DataObject) SET var.data_size = 1000 WITH (var:DataObject{data_name:'foo1'}) SET var.data_name = NULL" -}
it "test translate cypher insert 8" $ do
let qu = parseStandardInsert "DATA_NAME(x, \"bar\") insert DATA_NAME(x, \"foo\")"
let sql = translateInsert (cypherTrans "") qu
show (snd sql) `shouldBe` "MATCH (var:DataObject{data_name:'bar'}) SET var.data_name = 'foo'"
it "test translate cypher insert 9" $ do
let qu = parseStandardInsert "insert ~DATA_OBJ(1)"
let sql = translateInsert (cypherTrans "") qu
show (snd sql) `shouldBe` "MATCH (var:DataObject{object_id:1}) DELETE var"
it "test tranlate cypher insert 10" $ do
let qu = parseStandardInsert "insert ~DATA_OBJ(x)"
let sql = translateInsert (cypherTrans "") qu
show (snd sql) `shouldBe` "MATCH (var:DataObject) DELETE var"
-}
| xu-hao/QueryArrow | QueryArrow-db-cypher/test/Test.hs | bsd-3-clause | 12,674 | 0 | 18 | 2,843 | 2,185 | 1,105 | 1,080 | 125 | 2 |
{-# LANGUAGE RecordWildCards #-}
module Legal (legalPlayer) where
import GGP.Player
import GGP.Utils
import Language.GDL
firstMove :: State -> GGP () ()
firstMove st = do
Match {..} <- get
let moves = legal matchDB st matchRole
liftIO $ putStrLn $ "LEGAL: " ++ show (head moves)
setBest $ head moves
liftIO $ putStrLn $ "LEGAL DONE"
legalPlayer :: Player ()
legalPlayer = def { handlePlay = basicPlay firstMove }
| ian-ross/ggp | players/Legal.hs | bsd-3-clause | 426 | 0 | 10 | 82 | 151 | 76 | 75 | 14 | 1 |
{-# LANGUAGE TypeSynonymInstances
, FlexibleInstances
, ScopedTypeVariables
, RankNTypes
#-}
module Spire.Surface.PrettyPrinter (prettyPrint , prettyPrintError) where
import Spire.Canonical.Embedder
import Spire.Canonical.Types
import Spire.Expression.Embedder
import Spire.Expression.Types
import Spire.Surface.Types
import Control.Applicative ((<$>))
import Control.Monad.Reader
import qualified Text.PrettyPrint.Leijen as PP
import Text.PrettyPrint.Leijen (Doc)
import Unbound.LocallyNameless hiding ( Spine )
import Unbound.LocallyNameless.Fresh
----------------------------------------------------------------------
prettyPrint :: Display t => t -> String
prettyPrint t = render $ runFreshM $ runReaderT (display t) emptyDisplayR
where
-- To adjust the printing parameters:
render x = PP.displayS (PP.renderPretty ribbon columns x) ""
columns = 80
ribbon = 1.0
-- The raw data is printed in color to make it easier to ignore :P
prettyPrintError :: (Show t , Display t) => t -> String
prettyPrintError a = prettyPrint a ++ "\x1b[35m(" ++ show a ++ ")\x1b[0m"
----------------------------------------------------------------------
-- Lift standard pretty printing ops to a monad.
sepM , fsepM , hsepM , vcatM , listM , alignSepM , groupNestSepM ::
(Functor m , Monad m) => [m Doc] -> m Doc
sepM xs = PP.sep <$> sequence xs
fsepM xs = PP.fillSep <$> sequence xs
hsepM xs = PP.hsep <$> sequence xs
vsepM xs = PP.vsep <$> sequence xs
vcatM xs = PP.vcat <$> sequence xs
listM xs = PP.list <$> sequence xs
alignSepM = alignM . sepM
groupNestSepM = groupM . nestM 2 . sepM
nestM , indentM :: Functor m => Int -> m Doc -> m Doc
nestM n = fmap $ PP.nest n
indentM n = fmap $ PP.indent n
parensM , groupM , alignM :: Functor m => m Doc -> m Doc
parensM = fmap PP.parens
groupM = fmap PP.group
alignM = fmap PP.align
infixr 5 </> , <$$> , <$+$>
infixr 6 <> , <+>
(<>) , (<+>) , (</>) , (<$$>) , (<$+$>) ::
Monad m => m Doc -> m Doc -> m Doc
(<>) = liftM2 (PP.<>)
(<+>) = liftM2 (PP.<+>)
(</>) = liftM2 (PP.</>)
(<$$>) = liftM2 (PP.<$$>)
(<$+$>) = liftM2 (PP.<$>)
dt :: String -> DisplayM Doc
dt = return . PP.text
----------------------------------------------------------------------
binding :: (Precedence t', Precedence t, Display t) =>
t' -> Nom -> t -> DisplayM Doc
binding outside nm tp | isWildcard nm = wrapNonAssoc outside tp
binding _ nm tp = parensM . hsepM $ [pushName nm (d nm) , dt ":" , d tp]
----------------------------------------------------------------------
-- Short hands.
d :: Display t => t -> DisplayM Doc
d = display
w , ww :: (Precedence o , Precedence i, Display i) =>
o -> i -> DisplayM Doc
w = wrap -- Mnemonic: (w)rapped display
ww = wrapNonAssoc -- Mnemonic: (w)rapped (w)rapped display
-- (i.e. more wrapped :P)
----------------------------------------------------------------------
-- Syntactic-category agnostic printers.
--
-- The idea was to write all the pretty printers using these
-- ... except now all but one printer is defined by embedding.
-- Constructors with no arguments have printers with no arguments.
dNil = dt "[]"
dRefl = dt "refl"
dHere = dt "here"
dWildCard = dt wildcard
dQuotes :: String -> DisplayM Doc
dQuotes = return . PP.dquotes . PP.text
-- Constructors with arguments pass *themselves* and their args to
-- their printers.
dCons o x y = ww o x <+> dt "::" <+> w o y
dPair o x y = ww o x <+> dt "," <+> w o y
dEq o x y = ww o x <+> dt "==" <+> w o y
dLam o bnd_b = do
(nm , b) <- unbind bnd_b
fsepM [ dt "\\" <+> pushName nm (d nm) <+> dt "->" , pushName nm (w o b) ]
dLamArg o bnd_b = parensM (dLam o bnd_b)
dPi o _A bnd_B = do
(nm , _B) <- unbind bnd_B
fsepM [ binding o nm _A <+> dt "->" , pushName nm (w o _B) ]
dSg o _A bnd_B = do
(nm , _B) <- unbind bnd_B
binding o nm _A <+> dt "*" <+> pushName nm (d _B)
dIf o c t f = groupNestSepM
[ dt "if" <+> w o c
, dt "then" <+> w o t
, dt "else" <+> w o f
]
dThere o t = dt "there" <+> ww o t
dEnd o i = dt "End" <+> ww o i
dTag o _E = dt "Tag" <+> ww o _E
dInit o xs = dt "init" <+> ww o xs
dApp o f a = alignM $ w o f </> ww o a
dAnn _ a _A = parensM . alignSepM $ [ d a , dt ":" <+> d _A ]
dRec o i _D =
dt "Rec" <+> groupNestSepM
[ ww o i , ww o _D ]
dArg o _A _B =
dt "Arg" <+> groupNestSepM
[ ww o _A , dLamArg o _B ]
----------------------------------------------------------------------
instance Display Syntax where
display s = case s of
SRefl -> dRefl
SHere -> dHere
SThere t -> dThere s t
SEnd i -> dEnd s i
SPair a b -> dPair s a b
SLam b -> dLam s b
SRec i _D -> dRec s i _D
SInit xs -> dInit s xs
SPi _A _B -> dPi s _A _B
SSg _A _B -> dSg s _A _B
SArg _A _B -> dArg s _A _B
SEq a b -> dEq s a b
SVar nm -> d nm
SQuotes s -> dQuotes s
SWildCard -> dWildCard
SIf c t f -> dIf s c t f
SApp f a -> dApp s f a
SAnn a _A -> dAnn s a _A
instance Display Stmt where
display (SDef nm a _A) =
(groupM . nestM 2) (d nm <+> dt ":" <$+$> d _A) <$$>
(groupM . nestM 2) (d nm <+> dt "=" <$+$> d a)
display (SData _N _P _I css) = let
params = map (\(l , _A) -> parensM $ dt l <+> dt ":" <+> d _A ) _P
indices = PP.hcat . PP.punctuate (PP.text " => ") <$> mapM maybeParens (_I ++ [(wildcard , sType)])
constrs = vsepM $ map (\ (nm , cs) -> dt nm <+> dt ":" <+> displayConstrs _N (map fst _P) cs) css
in
dt "data" <+> hsepM (dt _N : params) <+> dt ":" <+> indices <+> dt "where"
<$$> indentM 2 constrs <$$>
dt "end"
where
maybeParens = \(l , _A) -> if l == wildcard then d _A else parensM (dt l <+> dt ":" <+> d _A)
displayConstrs :: String -> [String] -> [Constr] -> DisplayM Doc
displayConstrs _N _P cs = PP.hcat . PP.punctuate (PP.text " => ") <$> mapM (displayConstr _N _P) cs
displayConstr :: String -> [String] -> Constr -> DisplayM Doc
displayConstr _N _P (Fix _I) = hsepM $ (dt _N : map dt _P) ++ map d _I
displayConstr _N _P (Arg nm _A) = maybeParens (nm , _A)
instance Display SProg where
display defs = PP.vcat . PP.punctuate PP.line <$> mapM d defs
instance Display Nom where
-- It's incorrect to use 'name2String' here, since it allows
-- shadowing, but using 'show' is really ugly, since it prints many
-- unnecessary freshenings.
--
-- The approach we take is to only freshen a name 'x' if there is
-- another name 'y' in scope for the binding sight of 'x' s.t. 'x'
-- and 'y' have the same string part (a 'Name' is essentially a
-- '(String , Int)' pair, with the int used for freshening).
--
-- For example, the function
--
-- \ x . \ x . x
--
-- will print as
--
-- \ x . \ x$<n> . x$<n> .
--
-- A much fancier printer could detect that this example need not be
-- freshened, but we're taking a simple approach here.
display nm = do
nms <- asks names
-- Here 'nms'' is the names in scope for the binding of 'nm'.
-- The 'nms' is a stack of bindings, so all the bindings after
-- 'nm' correspond to bindings in scope for 'nm's binding.
--
-- Metavars are always freshened.
let nms' = drop 1 . dropWhile (/= nm) $ nms
suffix = if name2String nm `elem` map name2String nms'
|| isMV nm
then "$" ++ show (name2Integer nm)
else ""
dt $ name2String nm ++ suffix
----------------------------------------------------------------------
instance Display CProg where
display = d . runFreshM . mapM embedCDef
instance Display VProg where
display = d . runFreshM . mapM (embedCDef <=< embedVDef)
instance Display Check where
display = d . runFreshM . embedC
instance Display Infer where
display = d . runFreshM . embedI
----------------------------------------------------------------------
instance Display Value where
display = d . runFreshM . (embedC <=< embedV)
instance Display (Nom , Spine) where
display (nm , fs) = d . runFreshM $ (embedI =<< embedN nm fs)
instance Display Tel where
display = listM . map (uncurry $ dAnn undefined) . tel2List
----------------------------------------------------------------------
instance Precedence Syntax where
level s = case s of
SPair _ _ -> pairLevel
SEq _ _ -> eqLevel
SLam _ -> lamLevel
SPi _ _ -> piLevel
SSg _ _ -> sgLevel
SIf _ _ _ -> ifLevel
SApp _ _ -> appLevel
SAnn _ _ -> annLevel
SThere _ -> initialLevel
SEnd _ -> initialLevel
SRec _ _ -> initialLevel
SInit _ -> initialLevel
SArg _ _ -> initialLevel
SRefl -> atomicLevel
SHere -> atomicLevel
SWildCard -> atomicLevel
SVar _ -> atomicLevel
SQuotes _ -> atomicLevel
assoc s = case s of
SPi _ _ -> piAssoc
SSg _ _ -> sgAssoc
SApp _ _ -> appAssoc
SPair _ _ -> pairAssoc
SEq _ _ -> AssocNone
SInit _ -> AssocNone
SRec _ _ -> AssocNone
SArg _ _ -> AssocNone
SLam _ -> AssocNone
SIf _ _ _ -> AssocNone
SThere _ -> AssocNone
SEnd _ -> AssocNone
SAnn _ _ -> AssocNone
SRefl -> AssocNone
SHere -> AssocNone
SWildCard -> AssocNone
SVar _ -> AssocNone
SQuotes _ -> AssocNone
----------------------------------------------------------------------
instance Precedence Nom where
level _ = atomicLevel
assoc _ = AssocNone
----------------------------------------------------------------------
-- The 'Reader' data of the 'DisplayM'. E.g., the "flags" Tim
-- mentioned would go in here.
data DisplayR = DisplayR { names :: [Nom] }
emptyDisplayR :: DisplayR
emptyDisplayR = DisplayR { names = [] }
pushName :: Nom -> DisplayM a -> DisplayM a
pushName nm = local (\d -> d { names = nm : names d })
type DisplayM = ReaderT DisplayR FreshM
-- Convert 't' to 'Doc', using 'DisplayR'.
class Display t where
display :: t -> DisplayM Doc
-- Same as 'Text.Parsec.Expr.Assoc', except with 'Eq' :P
data Assoc = AssocLeft | AssocRight | AssocNone deriving Eq
-- The precedence level is the tightness of binding: larger levels
-- mean tighter binding.
class Precedence t where
level :: t -> Float
assoc :: t -> Assoc
-- Precedence levels and infix op associativities.
--
-- Compare with table in used in Spire.Surface.Parsing.
atomicLevel = -1
initialLevel = 0
annLevel = atomicLevel
appLevel = initialLevel
appAssoc = AssocLeft
consLevel = 2
consAssoc = AssocRight
pairLevel = 3
pairAssoc = AssocRight
sgLevel = 4
sgAssoc = AssocRight
piLevel = 5
piAssoc = AssocRight
ifLevel = 6
lamLevel = 7
eqLevel = 8
defsLevel = 9
defLevel = 10
-- For non-infix operators, use 'wrap' to wrap optionally recursive
-- displays as needed.
--
-- For infix operators, use 'wrap' to optionally wrap recursive
-- displays in positions consistent with association, and use
-- 'wrapNonAssoc' to optionally wrap recursive displays in positions
-- inconsistent with association.
--
-- For example, for a left associative application 'App', the
-- 'display' case could be written:
--
-- display s@(App f x) =
-- sepM [ wrap s f (display f) , wrapNonAssoc s x (display x) ]
wrap , wrapNonAssoc :: (Display t2, Precedence t1 , Precedence t2) =>
t1 -> t2 -> DisplayM Doc
wrap outside inside =
if level outside < level inside ||
level outside == level inside && assoc outside /= assoc inside
then parensM . display $ inside
else display inside
wrapNonAssoc outside inside =
if level outside <= level inside
then parensM . display $ inside
else display inside
---------------------------------------------------------------------- | spire/spire | src/Spire/Surface/PrettyPrinter.hs | bsd-3-clause | 12,316 | 0 | 17 | 3,448 | 3,622 | 1,853 | 1,769 | 241 | 2 |
-----------------------------------------------------------------------------
--
-- Module : Main
-- Copyright : 2012 (c) Mahmut Bulut
-- License : AllRightsReserved
--
-- Maintainer : Mahmut Bulut
-- Stability : unstable
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module Main (
main
) where
import AI.Planning.Swarm.SandData
main = print (AgentObjCoor [(1, 8080, "Suleyman", (1234.354, 453.5234))]) <- (AgentObj [(1, 30, "Ahmet")]) --err | vertexclique/sandlib | src/Test.hs | bsd-3-clause | 527 | 1 | 10 | 83 | 87 | 59 | 28 | -1 | -1 |
module Safe.Length where
import Data.Proxy (Proxy(..))
safeLength :: (Foldable f) => Proxy (f a) -> f a -> Int
safeLength _ f = length f
list :: Proxy [a]
list = Proxy
| stepcut/safe-length | src/Safe/Length.hs | bsd-3-clause | 171 | 0 | 9 | 35 | 83 | 45 | 38 | 6 | 1 |
{-# LANGUAGE RecursiveDo #-}
-- This financial model is described in
-- Vensim 5 Modeling Guide, Chapter Financial Modeling and Risk.
--
-- It illustrates how you can use the Monte-Carlo simulation and
-- define external parameters for the system of recursive diffential
-- equations to provide the Sensitivity Analysis.
--
-- To enable the parallel simulation, you should compile it
-- with option -threaded and then pass in other options +RTS -N2 -RTS
-- to the executable if you have a dual core processor without
-- hyper-threading. Also you can increase the number
-- of parallel threads via option -N if you have a more modern
-- processor.
module Model
(-- * Simulation Model
model,
-- * Variable Names
netIncomeName,
netCashFlowName,
npvIncomeName,
npvCashFlowName,
-- * External Parameters
Parameters(..),
defaultParams,
randomParams) where
import Control.Monad
import Simulation.Aivika
import Simulation.Aivika.SystemDynamics
import Simulation.Aivika.Experiment
import Simulation.Aivika.Experiment.Chart
-- | The model parameters.
data Parameters =
Parameters { paramsTaxDepreciationTime :: Parameter Double,
paramsTaxRate :: Parameter Double,
paramsAveragePayableDelay :: Parameter Double,
paramsBillingProcessingTime :: Parameter Double,
paramsBuildingTime :: Parameter Double,
paramsDebtFinancingFraction :: Parameter Double,
paramsDebtRetirementTime :: Parameter Double,
paramsDiscountRate :: Parameter Double,
paramsFractionalLossRate :: Parameter Double,
paramsInterestRate :: Parameter Double,
paramsPrice :: Parameter Double,
paramsProductionCapacity :: Parameter Double,
paramsRequiredInvestment :: Parameter Double,
paramsVariableProductionCost :: Parameter Double }
-- | The default model parameters.
defaultParams :: Parameters
defaultParams =
Parameters { paramsTaxDepreciationTime = 10,
paramsTaxRate = 0.4,
paramsAveragePayableDelay = 0.09,
paramsBillingProcessingTime = 0.04,
paramsBuildingTime = 1,
paramsDebtFinancingFraction = 0.6,
paramsDebtRetirementTime = 3,
paramsDiscountRate = 0.12,
paramsFractionalLossRate = 0.06,
paramsInterestRate = 0.12,
paramsPrice = 1,
paramsProductionCapacity = 2400,
paramsRequiredInvestment = 2000,
paramsVariableProductionCost = 0.6 }
-- | Random parameters for the Monte-Carlo simulation.
randomParams :: IO Parameters
randomParams =
do averagePayableDelay <- memoParameter $ randomUniform 0.07 0.11
billingProcessingTime <- memoParameter $ randomUniform 0.03 0.05
buildingTime <- memoParameter $ randomUniform 0.8 1.2
fractionalLossRate <- memoParameter $ randomUniform 0.05 0.08
interestRate <- memoParameter $ randomUniform 0.09 0.15
price <- memoParameter $ randomUniform 0.9 1.2
productionCapacity <- memoParameter $ randomUniform 2200 2600
requiredInvestment <- memoParameter $ randomUniform 1800 2200
variableProductionCost <- memoParameter $ randomUniform 0.5 0.7
return defaultParams { paramsAveragePayableDelay = averagePayableDelay,
paramsBillingProcessingTime = billingProcessingTime,
paramsBuildingTime = buildingTime,
paramsFractionalLossRate = fractionalLossRate,
paramsInterestRate = interestRate,
paramsPrice = price,
paramsProductionCapacity = productionCapacity,
paramsRequiredInvestment = requiredInvestment,
paramsVariableProductionCost = variableProductionCost }
-- | This is the model itself that returns experimental data.
model :: Parameters -> Simulation Results
model params =
mdo let getParameter f = liftParameter $ f params
-- the equations below are given in an arbitrary order!
bookValue <- integ (newInvestment - taxDepreciation) 0
let taxDepreciation = bookValue / taxDepreciationTime
taxableIncome = grossIncome - directCosts - losses
- interestPayments - taxDepreciation
production = availableCapacity
availableCapacity = ifDynamics (time .>=. buildingTime)
productionCapacity 0
taxDepreciationTime = getParameter paramsTaxDepreciationTime
taxRate = getParameter paramsTaxRate
accountsReceivable <- integ (billings - cashReceipts - losses)
(billings / (1 / averagePayableDelay
+ fractionalLossRate))
let averagePayableDelay = getParameter paramsAveragePayableDelay
awaitingBilling <- integ (price * production - billings)
(price * production * billingProcessingTime)
let billingProcessingTime = getParameter paramsBillingProcessingTime
billings = awaitingBilling / billingProcessingTime
borrowing = newInvestment * debtFinancingFraction
buildingTime = getParameter paramsBuildingTime
cashReceipts = accountsReceivable / averagePayableDelay
debt <- integ (borrowing - principalRepayment) 0
let debtFinancingFraction = getParameter paramsDebtFinancingFraction
debtRetirementTime = getParameter paramsDebtRetirementTime
directCosts = production * variableProductionCost
discountRate = getParameter paramsDiscountRate
fractionalLossRate = getParameter paramsFractionalLossRate
grossIncome = billings
interestPayments = debt * interestRate
interestRate = getParameter paramsInterestRate
losses = accountsReceivable * fractionalLossRate
netCashFlow = cashReceipts + borrowing - newInvestment
- directCosts - interestPayments
- principalRepayment - taxes
netIncome = taxableIncome - taxes
newInvestment = ifDynamics (time .>=. buildingTime)
0 (requiredInvestment / buildingTime)
npvCashFlow <- npv netCashFlow discountRate 0 1
npvIncome <- npv netIncome discountRate 0 1
let price = getParameter paramsPrice
principalRepayment = debt / debtRetirementTime
productionCapacity = getParameter paramsProductionCapacity
requiredInvestment = getParameter paramsRequiredInvestment
taxes = taxableIncome * taxRate
variableProductionCost = getParameter paramsVariableProductionCost
return $
results
[resultSource netIncomeName "Net income" netIncome,
resultSource netCashFlowName "Net cash flow" netCashFlow,
resultSource npvIncomeName "NPV income" npvIncome,
resultSource npvCashFlowName "NPV cash flow" npvCashFlow]
-- the names of the variables we are interested in
netIncomeName = "netIncome"
netCashFlowName = "netCashFlow"
npvIncomeName = "npvIncome"
npvCashFlowName = "npvCashFlow"
| dsorokin/aivika-experiment-chart | examples/Financial/Model.hs | bsd-3-clause | 7,623 | 0 | 15 | 2,328 | 1,117 | 603 | 514 | 124 | 1 |
-- Copyright 2012 Wu Xingbo
-- head {{{
{-# LANGUAGE ScopedTypeVariables, DeriveDataTypeable #-}
-- }}}
-- module export {{{
module Eval.Node (
SockNode,
SockHandler,
directSockNode,
startSockNode,
stopSockNode,
sendRequest,
sendRequestSafe,
sendRequestMaybe,
putBSL,
getBSL,
putObject,
getObject,) where
-- }}}
-- import {{{
import Prelude (($), (.), (/), (-), (+), (>),
String, Int, fromIntegral, id, Float, fst,)
import Control.Applicative ((<$>))
import Control.Monad (Monad(..), void)
import Control.Concurrent (forkIO, yield, myThreadId, ThreadId,)
import Control.Exception (SomeException, Exception, IOException,
handle, bracket, catch, throwTo, catches,
Handler(..))
import qualified Data.ByteString.Lazy as BSL
import Data.Binary (Binary, encode, decode,)
import Data.Bool (Bool(..))
import Data.Maybe (Maybe(..), maybe,)
import Data.Typeable (Typeable(..),)
import Network (HostName, PortNumber(..), PortID(..), Socket(..), connectTo,
withSocketsDo, accept, listenOn, sClose,)
import Network.Socket(getNameInfo, SockAddr(..),)
import System.Log.Logger (errorM, debugM, infoM, warningM, noticeM, )
import System.CPUTime (getCPUTime,)
import System.IO (IO (..), hGetLine, hFlush, hPutStrLn, Handle, hClose,
hSetBuffering, BufferMode(..), putStrLn,)
import System.Posix.Signals (installHandler, sigPIPE)
import qualified System.Posix.Signals as Sig
import Data.List ((++), words, head)
import Text.Read (Read(..), read)
import Text.Show (Show(..))
import Text.Printf (printf)
-- }}}
-- Logger {{{
moduleName :: String
moduleName = "Eval.Node"
-- }}}
-- NodeDownException {{{
-- used for close node
data NodeDownEx = NodeDownEx ThreadId
deriving (Typeable, Show)
instance Exception NodeDownEx where
-- }}}
-- SockNode {{{
data SockNode
= SockNode {
snThreadId :: !ThreadId,
snHostName :: !HostName,
snPortNumber :: !PortNumber
} deriving (Show)
type SockHandler a = Handle -> IO a
directSockNode :: SockHandler () -> PortNumber -> IO ()
directSockNode reqHandler port = do
mbss <- getSocket port
case mbss of
Just ss -> do
hostname <- getHostName
servThread reqHandler ss
_ -> return ()
startSockNode :: SockHandler () -> PortNumber -> IO (Maybe SockNode)
startSockNode reqHandler port = do
mbss <- getSocket port
case mbss of
Just ss -> do
hostname <- getHostName
tid <- forkIO $ servThread reqHandler ss
return (Just $ SockNode tid hostname port)
_ -> return Nothing
servThread :: SockHandler () -> Socket -> IO ()
servThread f ss = servWith f ss `catches` exHandlers
where
exHandlers :: [Handler ()]
exHandlers = [Handler $ closeHandler ss, Handler defaultHandler]
defaultHandler :: SomeException -> IO ()
defaultHandler e = do
putStrLn $ "ERROR - socket closed with exception: " ++ show e
sClose ss
closeHandler :: Socket -> NodeDownEx -> IO ()
closeHandler so (NodeDownEx tid) = do
sClose ss
putStrLn $ "socket normally closed by thread " ++ show tid
stopSockNode :: SockNode -> IO ()
stopSockNode ss = do
me <- myThreadId
throwTo (snThreadId ss) (NodeDownEx me)
yield
getHostName :: IO HostName
getHostName = do
mbhost <- fst <$> getNameInfo [] True False (SockAddrUnix "localhost")
return $ maybe "localhost" id mbhost
getSocket :: PortNumber -> IO (Maybe Socket)
getSocket port = catch (Just <$> listenOn (PortNumber port)) exHandler
where
exHandler (e :: SomeException) = do
putStrLn $ "listenOn failed. " ++ show e
return Nothing
servWith :: SockHandler () -> Socket -> IO ()
servWith f socket = do
(hdl, _, _) <- accept socket
void $ forkIO $ servRequest f hdl
servWith f socket
servRequest :: SockHandler () -> Handle -> IO ()
servRequest f conn = bracket (return conn) hClose serv
where
exHandler (e :: SomeException) = do
errorM moduleName $ "servRequest: " ++ show e
serv hdl = do
hSetBuffering hdl $ BlockBuffering Nothing -- use buffer
handle exHandler $ f hdl
-- }}}
-- client {{{
sendRequest :: SockHandler a -> HostName -> PortNumber -> IO a
sendRequest f n p =
withSocketsDo $ do
_ <- installHandler sigPIPE Sig.Ignore Nothing
bracket (connectTo n (PortNumber p)) (hClose) (send)
where
send hdl = do
hSetBuffering hdl $ BlockBuffering Nothing
f hdl
sendRequestSafe :: SockHandler a -> a -> HostName -> PortNumber -> IO a
sendRequestSafe f d n p = catch (sendRequest f n p) exHandler
where
exHandler (e :: SomeException) = do
debugM moduleName $ "sendRequestSafe" ++ show e
return d
sendRequestMaybe :: SockHandler a -> HostName -> PortNumber -> IO (Maybe a)
sendRequestMaybe f n p = catch (Just <$> sendRequest f n p) exHandler
where
exHandler (e :: IOException) = do
debugM moduleName $ "sendRequestMaybe: " ++ show e
return Nothing
-- }}}
-- put/get ByteString {{{
-- | Puts a bytestring to a handle. But to make the reading easier, we write
-- the length of the data as a message-header to the handle, too.
putBSL :: BSL.ByteString -> Handle -> IO ()
putBSL msg hdl = do
handle exHandler $ do
hPutStrLn hdl $ (show $ BSL.length msg) ++ " "
BSL.hPut hdl msg
hFlush hdl
where
exHandler (e :: SomeException) = errorM moduleName $ "putMessage: " ++ show msg
-- | Reads data from a stream. We define, that the first line of the message
-- is the message header which tells us how much bytes we have to read.
getBSL :: Handle -> IO (BSL.ByteString)
getBSL hdl = do
line <- hGetLine hdl
bs <- BSL.hGet hdl (read $ line :: Int)
return bs
-- }}}
-- put/get Object on System.IO.Handle {{{
putObject :: Binary a => a -> Handle -> IO ()
putObject obj h = putBSL (encode obj) h
getObject :: Binary a => Handle -> IO a
getObject h = decode <$> getBSL h
-- }}}
-- vim:fdm=marker
| wuxb45/eval | Eval/low/Node.hs | bsd-3-clause | 5,927 | 0 | 15 | 1,291 | 1,923 | 1,021 | 902 | 147 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
module AUTOSAR.Shared.Velocity
( VelocityCtrl(..)
, velocityCtrl
) where
import AUTOSAR.ARSim
import Control.Monad
-- * Velocity estimation
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- | The velocity estimation algorithm requires wheel speeds and (filtered)
-- accelerometer inputs. It is assumed that the first two wheel inputs belong to
-- the non-driving wheels (if any).
data VelocityCtrl = VelocityCtrl
{ wheels :: [DataElem Unqueued Double Required]
-- ^ Wheel velocities
, accel :: DataElem Unqueued Double Required
-- ^ Accelerometer
, velocity :: DataElem Unqueued Double Provided
-- ^ Velocity approximation
}
-- | Performs vehicle velocity estimation based on vehicle longtitudal
-- acceleration and wheel speeds. Requires a longtitudal accelerometer to be
-- mounted on the vehicle. Moreover, it is assumed that the data from this
-- accelerometer has been filtered.
--
-- The algorithm used assumes that the first two wheel velocity inputs come from
-- the non-driving wheels of the vehicle, and that a longtitudal accelerometer
-- is mounted on the unit. The slip calculation algorithm is borrowed from
-- Active Braking Control Systems: Design for Vehicles by Savaresi and Tanelli,
-- chapter 5.
velocityCtrl :: Time
-- ^ Sample time
-> Task
-- ^ Task assignment
-> AUTOSAR VelocityCtrl
velocityCtrl deltaT task = atomic $
do wheels <- replicateM 4 requiredPort
accel <- requiredPort
velocity <- providedPort
mapM_ (`comSpec` InitValue 0.0) wheels
comSpec accel (InitValue 0.0)
comSpec velocity (InitValue 0.0)
let memory = 200
-- Keep acceleration memory for backwards integration phase.
accMem <- interRunnableVariable (replicate memory 0.0)
avgMem <- interRunnableVariable (replicate memory 0.0)
veloMem <- interRunnableVariable 0.0
state <- interRunnableVariable S0
runnableT [task] (MinInterval 0) [TimingEvent deltaT] $
do velos <- mapM (fmap fromOk . rteRead) wheels
Ok acc <- rteRead accel
Ok s0 <- rteIrvRead state
Ok v0 <- rteIrvRead veloMem
Ok as <- rteIrvRead accMem
Ok avs <- rteIrvRead avgMem
-- Velocity estimation
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Assume that accelerometer input is filtered. This could be
-- done here, provided that we implement a FIR filter (for instance
-- moving average).
--
-- For low speeds or states with very little acceleration,
-- approximate the vehicle speed as the average of the wheel
-- speeds. For high acceleration, use the average of the non-
-- driving wheels. For hard braking, use the back integration
-- algorithm with the on-board accelerometer.
let vAvg = sum velos / fromIntegral (length velos)
nonDr = take 2 velos
vNd = sum nonDr / fromIntegral (length nonDr)
-- Get next state
s1 = stateTrans vAvg acc s0
-- Compute vehicle velocity estimate.
-- If the state transition was from S0 to S1, we've gone from
-- soft to hard deceleration and should perform backwards
-- integration for @memory@ steps. If the state transition was
-- from S1 to SM2, we ignore it since we're reaching a full stop
-- doing hard braking.
v1 = case s1 of
SM2 | s0 /= S1 -> vAvg
| otherwise -> v0 + acc * deltaT
SM1 -> vNd
S0 -> vAvg
S1 | s0 == S1 -> v0 + acc * deltaT
| otherwise -> v0' + acc * deltaT
where
v0' = foldl (\v a -> v + a * deltaT)
(last avs)
(reverse as)
-- Write memo-variables
rteIrvWrite accMem (acc:init as)
rteIrvWrite veloMem v1
rteIrvWrite avgMem (vAvg:init avs)
rteIrvWrite state s1
-- Write velocity estimate
rteWrite velocity v1
return $ sealBy VelocityCtrl wheels accel velocity
fromOk (Ok v) = v
-- * Vehicle state machine
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- To generate a good estimate of wheel slip when all wheels are locked (or
-- nearing lock-up at the same speed), velocity estimation is done by
-- integrating the vehicle acceleration. To simplify this, the vehicle is kept
-- in one of four states, where
--
-- SM2 -> Vehicle is moving at low speed
-- SM1 -> Vehicle is accelerating
-- S0 -> Vehicle is moving at constant speed or braking very lightly
-- S1 -> Vehicle is braking hard
--
-- Velocity estimations will differ depending on the state which the vehicle
-- is in.
data CState = SM2 | SM1 | S0 | S1
deriving (Data, Eq, Typeable)
-- Vehicle state machine transitions.
stateTrans :: Double -- Average velocity
-> Double -- Longtitudal acceleration
-> CState -- Input state
-> CState
stateTrans v a state =
case state of
SM2 | v <= vMin + hv -> SM2
| a >= delta -> SM1
| a >= -beta -> S0
| otherwise -> S1
SM1 | v <= vMin -> SM2
| a >= delta -> SM1
| a >= -beta -> S0
| otherwise -> S1
S0 | v <= vMin -> SM2
| a >= delta -> SM1
| a >= -beta -> S0
| otherwise -> S1
S1 | v <= vMin -> SM2
| a >= delta -> SM1
| a >= -beta + ha -> S0
| otherwise -> S1
where
vMin = 0.01 -- Low velocity threshold (m/s)
hv = 0.2 -- Velocity hysteresis (m/s)
ha = 0.1 -- Acceleration hysteresis (m/s^2)
beta = 0.8 -- Deceleration threshold (m/s^2)
delta = 0.1 -- Acceleration threshold (m/s^2)
| josefs/autosar | ARSim/arsim-examples/AUTOSAR/Shared/Velocity.hs | bsd-3-clause | 6,303 | 0 | 23 | 2,138 | 1,035 | 526 | 509 | 82 | 4 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
{-# LANGUAGE EmptyDataDecls, ScopedTypeVariables, KindSignatures #-}
{-# LANGUAGE UndecidableInstances, ExistentialQuantification #-}
-- | Haskell with only one typeclass
--
-- <http://okmij.org/ftp/Haskell/Haskell1/Class2.hs>
--
-- <http://okmij.org/ftp/Haskell/types.html#Haskell1>
--
-- How to make ad hoc overloading less ad hoc while defining no
-- type classes.
-- Haskell1' -- the extension of Haskell1 with functional dependencies,
-- and bounded-polymorphic higher-rank types
module Data.Class2 where
import Data.Class1
-- ----------------------------------------------------------------------
-- | Some functional dependencies: implementing Monad Error
-- As it turns out, some functional dependencies are expressible already
-- in Haskell1. The example is MonadError, which in Haskell' has the form
-- class Error a where
-- strMsg :: String -> a
-- class Monad m => MonadError e m | m -> e where
-- throwError :: e -> m a
-- catchError :: m a -> (e -> m a) -> m a
-- In Haskell1, the above code becomes
data ERROR a
strMsg :: forall a. C (ERROR a) (String->a) => String -> a
strMsg = ac (__::ERROR a)
instance C (ERROR String) (String->String) where
ac _ = id
data ThrowError (m :: * -> *) a
-- The C (RET m a) t1 and C (BIND m a b) t2 constraints are not
-- called for, but we specified them anyway. That is, we require that
-- `m' be an instance of a Monad. This extra constraints are Haskell1
-- analogue of Haskell's `class constraints'
throwError :: forall e m a b t1 t2.
(C (ThrowError m a) (e -> m a),
C (RET m a) t1,
C (BIND m a b) t2) =>
e -> m a
throwError = ac (__::ThrowError m a)
data CatchError (m :: * -> *) a
catchError :: forall e m a. C (CatchError m a) (m a -> (e -> m a) -> m a) =>
m a -> (e -> m a) -> m a
catchError = ac (__::CatchError m a)
-- define one particular Error Monad, Either e
instance C (ThrowError (Either e) a) (e -> Either e a) where
ac _ = Left
instance C (CatchError (Either e) a)
(Either e a -> (e -> Either e a) -> Either e a) where
ac _ (Left x) f = f x
ac _ x _ = x
-- so we can write a test
te1 x = runEither $ catchError ac (\e -> ret e)
where
ac = (if x then throwError "er" else ret (2::Int)) `bind`
(\x -> ret (x *$ x)) `bind` (ret.shw)
runEither :: Either a b -> Either a b
runEither = id
te1r = (te1 True, te1 False)
-- (Right "er",Right "4")
-- ----------------------------------------------------------------------
-- Functional dependencies
-- The first example has no functional dependencies. In Haskell:
-- class FC1 a b c where fc1 :: a -> b -> c
-- instance FC1 Bool Char Int
-- In Haskell1:
data FC1 a b c
instance C (FC1 Bool Char Int) (Bool->Char->Int) where
ac _ x y = 1
fc1 :: forall a b c. C (FC1 a b c) (a->b->c) => a->b->c
fc1 = ac (__::FC1 a b c)
-- The definition tfc1 below is rejected because of the unresolved
-- overloading on the return type of fc1. If we specify the return
-- type explicitly, the definition is accepted.
-- To eliminate such explicit type annotations, functional dependencies
-- are introduced.
-- tfc1 = fc1 True 'a'
tfc12 = (fc1 True 'a') :: Int -- OK
-- 1
-- If our function fc is such that the type of its two arguments determines
-- the result type, we can write, in Haskell
-- class FC2 a b c | a b -> c where fc2 :: a -> b -> c
-- instance FC2 Bool Char Int
-- In Haskell1'
data FC2 a b c
instance TypeCast c Int => C (FC2 Bool Char c) (Bool->Char->Int) where
ac _ x y = 1
fc2 :: forall a b c. C (FC2 a b c) (a->b->c) => a->b->c
fc2 = ac (__::FC2 a b c)
-- Now, tfc2 is accepted without the additional annotations.
-- The argument types still have to be explicitly specified:
-- The definition tfc21 is rejected because of the unresolved overloading
-- over the second argument
tfc2 = fc2 True 'a' -- This is now OK with no type annotations
-- tfc21 = fc2 True undefined -- here, the second arg type is needed
-- If fc is overloaded over the type of the first argument only, we
-- can write
-- class FC3 a b c | a -> b c where fc3 :: a -> b -> c
-- instance FC3 Bool Char Int
-- Or, in Haskell1:
data FC3 a b c
instance TypeCast (FC3 Bool b c) (FC3 Bool Char Int)
=> C (FC3 Bool b c) (Bool->Char->Int) where
ac _ x y = 1
fc3 :: forall a b c. C (FC3 a b c) (a->b->c) => a->b->c
fc3 = ac (__::FC3 a b c)
-- In this case, no more type annotations are needed. Both
-- of the following definitions are accepted as they are.
tfc3 = fc3 True 'a'
tfc31 = fc3 True undefined
-- We do not distinguish between a b -> c and a->b, a->c
-- The argument has been made for the distinction (Stuckey, Sulzmann:
-- A theory of overloading)
-- Hereby we make an argument for not having this distinction. We offer
-- a different model: when an instance is selected, its dependent
-- argument are improved (`typecast'). If an instance is not selected,
-- no type improvement is applied.
-- Associated Datatypes
-- The implementation of arrays, whose concrete representation depends on the
-- data type of their elements. This is the first example from
-- the paper Manuel M. T. Chakravarty, Gabriele Keller, Simon Peyton Jones
-- and Simon Marlow, `Associated Types with Class', POPL2005.
-- For simplicity, we limit ourselves to two methods: fromList
-- (which creates an array) and index. Again for simplicity, our
-- arrays are one-dimensional and indexed from 0.
-- As in the paper, the overloading is over the element type only.
-- Although for the function indexA, it would make more sense to overload
-- over the array type (and so the type of the result, that is, of the
-- extracted element, will be inferred).
data FromList e
fromList :: forall e array. C (FromList e) (Int -> [e] -> array) =>
Int -> [e] -> array
fromList = ac (__::FromList e)
data Index e
indexA :: forall e array. C (Index e) (array -> Int -> e) =>
(array -> Int -> e)
indexA = ac (__::Index e)
instance C (FromList Bool) (Int -> [Bool] -> (Int,Integer)) where
ac _ dim lst = (dim,foldr (\e a -> 2*a + fromIntegral (fromEnum e)) 0
(take dim lst))
instance C (FromList Char) (Int -> [Char] -> String) where
ac _ dim lst = take dim lst
-- Represent the array of pairs as a pair of arrays (example from the paper)
instance (C (FromList a) (Int -> [a] -> ara),
C (FromList b) (Int -> [b] -> arb))
=> C (FromList (a,b)) (Int -> [(a,b)] -> (ara,arb)) where
ac _ dim lst = (fromList dim (map fst lst),
fromList dim (map snd lst))
instance C (Index Bool) ((Int,Integer) -> Int -> Bool) where
ac _ (dim,num) i = if i >= dim then error "range check"
else (num `div` (2^i)) `mod` 2 == 1
instance C (Index Char) (String -> Int -> Char) where
ac _ s i = s !! i
instance (C (Index a) (ara -> Int -> a),
C (Index b) (arb -> Int -> b))
=> C (Index (a,b)) ((ara,arb) -> Int -> (a,b)) where
ac _ (ara,arb) i = (indexA ara i, indexA arb i)
-- The `asTypeOf` annotation below could be avoided if we overloaded
-- indexA differently, as mentioned above. We preferred to literally follow
-- the paper though...
testar lst = let arr = fromList (length lst) lst
in [(indexA arr 0) `asTypeOf` (head lst),
indexA arr (pred (length lst))]
testarr = (testar [True,True,False], testar "abc",
testar [('x',True),('y',True),('z',False)])
-- ([True,False],"ac",[('x',True),('z',False)])
-- ----------------------------------------------------------------------
-- Haskell98 classes (method bundles) and bounded existentials
-- But what if we really need classes, as bundles of methods?
-- The compelling application is higher-ranked types: bounded existentials.
-- Let's define the Num bundle and numeric functions that are truly
-- NUM-overloaded
data NUM a = NUM{nm_add,nm_mul :: a->a->a,
nm_fromInteger :: Integer->a,
nm_show :: a->String}
data CLS a
instance (C (Add a) (a->a->a), C (Mul a) (a->a->a),
C (FromInteger a) (Integer->a),
C (SHOW a) (a->String))
=> C (CLS (NUM a)) (NUM a) where
ac _ = NUM (+$) (*$) frmInteger shw
-- We re-visit the overloaded addition, multiplication, show and
-- fromInteger functions, defining them now in terms of the just
-- introduced `class' NUM.
-- We should point out the uniformity of the declarations below, ripe
-- for syntactic sugar. For example, one may introduce NUM a => ...
-- to mean C (CLS (NUM a)) (NUM a) => ...
infixl 6 +$$
infixl 7 *$$
(+$$) :: forall a. C (CLS (NUM a)) (NUM a) => a -> a -> a
(+$$) x y = nm_add (ac (__:: CLS (NUM a))) x y
(*$$) :: forall a. C (CLS (NUM a)) (NUM a) => a -> a -> a
(*$$) x y = nm_mul (ac (__:: CLS (NUM a))) x y
nshw :: forall a. C (CLS (NUM a)) (NUM a) => a -> String
nshw x = nm_show (ac (__:: CLS (NUM a))) x
nfromI :: forall a. C (CLS (NUM a)) (NUM a) => Integer -> a
nfromI x = nm_fromInteger (ac (__:: CLS (NUM a))) x
-- We are in a position to define a bounded existential, whose quantified
-- type variable 'a' is restricted to members of NUM. The latter lets us
-- use the overloaded numerical functions after opening the existential
-- envelope.
data PACK = forall a. C (CLS (NUM a)) (NUM a) => PACK a
t1d = let x = PACK (Dual (1.0::Float) 2) in
case x of PACK y -> nshw (y *$$ y +$$ y +$$ (nfromI 2))
--"(|4.0,6.0|)"
-- This typeclass assumed pre-defined; it is not user-extensible.
-- It is best viewed as a ``built-in constraint''
class TypeCast a b | a -> b, b->a where typeCast :: a -> b
class TypeCast' t a b | t a -> b, t b -> a where typeCast' :: t->a->b
class TypeCast'' t a b | t a -> b, t b -> a where typeCast'' :: t->a->b
instance TypeCast' () a b => TypeCast a b where typeCast x = typeCast' () x
instance TypeCast'' t a b => TypeCast' t a b where typeCast' = typeCast''
instance TypeCast'' () a a where typeCast'' _ x = x
| suhailshergill/liboleg | Data/Class2.hs | bsd-3-clause | 9,903 | 38 | 14 | 2,129 | 2,860 | 1,580 | 1,280 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Lucid.Foundation.Buttons.SplitButtons where
import Lucid.Base
import Lucid.Html5
import qualified Data.Text as T
import Data.Monoid
split_ :: T.Text
split_ = " split "
| athanclark/lucid-foundation | src/Lucid/Foundation/Buttons/SplitButtons.hs | bsd-3-clause | 214 | 0 | 5 | 30 | 44 | 29 | 15 | 8 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ImplicitParams #-}
{-# OPTIONS_GHC -Wno-orphans #-}
module Verifier.SAW.Heapster.TypedCrucible where
import Data.Maybe
import qualified Data.Text as Text
import Data.List hiding (sort)
import Data.Functor.Constant
import Data.Functor.Product
import Data.Type.Equality
import Data.Kind
import Data.Reflection
import qualified Data.BitVector.Sized as BV
import GHC.TypeLits
import What4.ProgramLoc
import What4.FunctionName
import What4.Interface (StringLiteral(..))
import Control.Lens hiding ((:>), Index, ix)
import Control.Monad.State.Strict hiding (ap)
import Control.Monad.Reader hiding (ap)
import Prettyprinter as PP
import qualified Data.Type.RList as RL
import Data.Binding.Hobbits
import Data.Binding.Hobbits.MonadBind
import Data.Binding.Hobbits.NameSet (NameSet, SomeName(..), SomeRAssign(..),
namesListToNames, namesToNamesList,
nameSetIsSubsetOf)
import qualified Data.Binding.Hobbits.NameSet as NameSet
import Data.Binding.Hobbits.NameMap (NameMap)
import qualified Data.Binding.Hobbits.NameMap as NameMap
import Data.Parameterized.Context hiding ((:>), empty, take, view, last, drop)
import qualified Data.Parameterized.Context as Ctx
import Data.Parameterized.TraversableF
import Data.Parameterized.TraversableFC
import Lang.Crucible.FunctionHandle
import Lang.Crucible.Types
import Lang.Crucible.LLVM.Bytes
import Lang.Crucible.LLVM.Extension
import Lang.Crucible.LLVM.MemModel
import Lang.Crucible.CFG.Expr
import Lang.Crucible.CFG.Core
import Lang.Crucible.Analysis.Fixpoint.Components
import Lang.Crucible.LLVM.DataLayout
import Lang.Crucible.LLVM.Errors.UndefinedBehavior as UB
import Verifier.SAW.Heapster.CruUtil
import Verifier.SAW.Heapster.GenMonad
import Verifier.SAW.Heapster.Implication
import Verifier.SAW.Heapster.NamePropagation
import Verifier.SAW.Heapster.Permissions
import Verifier.SAW.Heapster.Widening
import GHC.Stack (HasCallStack)
----------------------------------------------------------------------
-- * Handling Crucible Extensions
----------------------------------------------------------------------
-- | A Crucible extension that satisfies 'NuMatching'
type NuMatchingExtC ext =
(NuMatchingAny1 (ExprExtension ext RegWithVal)
-- (NuMatchingAny1 (ExprExtension ext TypedReg)
-- , NuMatchingAny1 (StmtExtension ext TypedReg))
)
-- | GADT telling us that @ext@ is a syntax extension we can handle
data ExtRepr ext where
ExtRepr_Unit :: ExtRepr ()
ExtRepr_LLVM :: ExtRepr LLVM
instance KnownRepr ExtRepr () where
knownRepr = ExtRepr_Unit
instance KnownRepr ExtRepr LLVM where
knownRepr = ExtRepr_LLVM
-- | The constraints for a Crucible syntax extension that supports permission
-- checking
type PermCheckExtC ext =
(NuMatchingExtC ext, IsSyntaxExtension ext, KnownRepr ExtRepr ext)
-- | Extension-specific state
data PermCheckExtState ext where
-- | No extension-specific state for the empty extension
PermCheckExtState_Unit :: PermCheckExtState ()
-- | The extension-specific state for LLVM is the current frame pointer, if it
-- exists
PermCheckExtState_LLVM ::
Maybe SomeFrameReg ->
PermCheckExtState LLVM
-- | Create a default empty extension-specific state object
emptyPermCheckExtState :: ExtRepr ext -> PermCheckExtState ext
emptyPermCheckExtState ExtRepr_Unit = PermCheckExtState_Unit
emptyPermCheckExtState ExtRepr_LLVM = PermCheckExtState_LLVM Nothing
-- | Get all the names contained in a 'PermCheckExtState'
permCheckExtStateNames :: PermCheckExtState ext -> Some (RAssign ExprVar)
permCheckExtStateNames (PermCheckExtState_LLVM (Just (SomeFrameReg _ treg))) =
Some (MNil :>: typedRegVar treg)
permCheckExtStateNames (PermCheckExtState_LLVM Nothing) = Some MNil
permCheckExtStateNames (PermCheckExtState_Unit) = Some MNil
data SomeFrameReg where
SomeFrameReg ::
NatRepr w ->
TypedReg (LLVMFrameType w) ->
SomeFrameReg
----------------------------------------------------------------------
-- * Typed Jump Targets and Function Handles
----------------------------------------------------------------------
-- | During type-checking, we convert Crucible registers to variables
newtype TypedReg tp = TypedReg { typedRegVar :: ExprVar tp }
instance PermPretty (TypedReg tp) where
permPrettyM = permPrettyM . typedRegVar
-- | A sequence of typed registers
data TypedRegs ctx where
TypedRegsNil :: TypedRegs RNil
TypedRegsCons :: !(TypedRegs ctx) -> !(TypedReg a) -> TypedRegs (ctx :> a)
-- | Extract out a sequence of variables from a 'TypedRegs'
typedRegsToVars :: TypedRegs ctx -> RAssign Name ctx
typedRegsToVars TypedRegsNil = MNil
typedRegsToVars (TypedRegsCons regs (TypedReg x)) = typedRegsToVars regs :>: x
-- | Convert a sequence of variables to a 'TypedRegs'
varsToTypedRegs :: RAssign Name ctx -> TypedRegs ctx
varsToTypedRegs MNil = TypedRegsNil
varsToTypedRegs (xs :>: x) = TypedRegsCons (varsToTypedRegs xs) (TypedReg x)
-- | Turn a sequence of typed registers into a variable substitution
typedRegsToVarSubst :: TypedRegs ctx -> PermVarSubst ctx
typedRegsToVarSubst = permVarSubstOfNames . typedRegsToVars
-- | A typed register along with its value if that is known statically
data RegWithVal a
= RegWithVal (TypedReg a) (PermExpr a)
| RegNoVal (TypedReg a)
-- | Get the 'TypedReg' from a 'RegWithVal'
regWithValReg :: RegWithVal a -> TypedReg a
regWithValReg (RegWithVal r _) = r
regWithValReg (RegNoVal r) = r
-- | Get the expression for a 'RegWithVal', even if it is only the variable for
-- its register value when it has no statically-known value
regWithValExpr :: RegWithVal a -> PermExpr a
regWithValExpr (RegWithVal _ e) = e
regWithValExpr (RegNoVal (TypedReg x)) = PExpr_Var x
-- | A type-checked Crucible expression is a Crucible 'Expr' that uses
-- 'TypedReg's for variables. As part of type-checking, these typed registers
-- (which are the inputs to the expression) as well as the final output value of
-- the expression are annotated with equality permissions @eq(e)@ if their
-- values can be statically represented as permission expressions @e@.
data TypedExpr ext tp =
TypedExpr !(App ext RegWithVal tp) !(Maybe (PermExpr tp))
-- | A "typed" function handle is a normal function handle along with contexts
-- of ghost input and output variables
data TypedFnHandle ghosts args gouts ret where
TypedFnHandle :: !(CruCtx ghosts) -> !(CruCtx gouts) ->
!(FnHandle cargs ret) ->
TypedFnHandle ghosts (CtxToRList cargs) gouts ret
-- | Extract out the context of ghost arguments from a 'TypedFnHandle'
typedFnHandleGhosts :: TypedFnHandle ghosts args gouts ret -> CruCtx ghosts
typedFnHandleGhosts (TypedFnHandle ghosts _ _) = ghosts
-- | Extract out the context of output ghost arguments from a 'TypedFnHandle'
typedFnHandleGouts :: TypedFnHandle ghosts args gouts ret -> CruCtx gouts
typedFnHandleGouts (TypedFnHandle _ gouts _) = gouts
-- | Extract out the context of regular arguments from a 'TypedFnHandle'
typedFnHandleArgs :: TypedFnHandle ghosts args gouts ret -> CruCtx args
typedFnHandleArgs (TypedFnHandle _ _ h) = mkCruCtx $ handleArgTypes h
-- | Extract out the context of all arguments of a 'TypedFnHandle', including
-- the lifetime argument
typedFnHandleAllArgs :: TypedFnHandle ghosts args gouts ret ->
CruCtx (ghosts :++: args)
typedFnHandleAllArgs h =
appendCruCtx (typedFnHandleGhosts h) (typedFnHandleArgs h)
-- | Extract out the return type of a 'TypedFnHandle'
typedFnHandleRetType :: TypedFnHandle ghosts args gouts ret -> TypeRepr ret
typedFnHandleRetType (TypedFnHandle _ _ h) = handleReturnType h
-- | Extract out all the return types of a 'TypedFnHandle'
typedFnHandleRetTypes :: TypedFnHandle ghosts args gouts ret ->
CruCtx (gouts :> ret)
typedFnHandleRetTypes (TypedFnHandle _ gouts h) =
CruCtxCons gouts $ handleReturnType h
-- | As in standard Crucible, blocks are identified by membership proofs that
-- their input arguments are in the @blocks@ list. We also track an 'Int' that
-- gives the 'indexVal' of the original Crucible block ID, so that typed block
-- IDs can be printed the same way as standard Crucible block IDs. The issue
-- here is that 'Member' proofs count from the right of an 'RList', while
-- Crucible uses membership proofs that count from the left, and so the sizes
-- are not the same.
data TypedBlockID (ctx :: RList (RList CrucibleType)) args =
TypedBlockID { typedBlockIDMember :: Member ctx args, typedBlockIDIx :: Int }
deriving Eq
instance TestEquality (TypedBlockID ctx) where
testEquality (TypedBlockID memb1 _) (TypedBlockID memb2 _) =
testEquality memb1 memb2
instance Show (TypedBlockID ctx args) where
show tblkID = "%" ++ show (typedBlockIDIx tblkID)
-- | Convert a Crucible 'Index' to a 'TypedBlockID'
indexToTypedBlockID :: Size ctx -> Index ctx args ->
TypedBlockID (CtxCtxToRList ctx) (CtxToRList args)
indexToTypedBlockID sz ix =
TypedBlockID (indexCtxToMember sz ix) (Ctx.indexVal ix)
-- | All of our blocks have multiple entry points, for different inferred types,
-- so a "typed" 'BlockID' is a normal Crucible 'BlockID' (which is just an index
-- into the @blocks@ context of contexts) plus an 'Int' specifying which entry
-- point to that block
data TypedEntryID (blocks :: RList (RList CrucibleType)) (args :: RList CrucibleType) =
TypedEntryID { entryBlockID :: TypedBlockID blocks args, entryIndex :: Int }
deriving Eq
-- | Get the 'Member' proof of the 'TypedBlockID' of a 'TypedEntryID'
entryBlockMember :: TypedEntryID blocks args -> Member blocks args
entryBlockMember = typedBlockIDMember . entryBlockID
-- | Compute the indices corresponding to the 'BlockID' and 'entryIndex' of a
-- 'TypedEntryID', for printing purposes
entryIDIndices :: TypedEntryID blocks args -> (Int, Int)
entryIDIndices (TypedEntryID tblkID ix) = (typedBlockIDIx tblkID, ix)
instance Show (TypedEntryID blocks args) where
show (TypedEntryID {..}) = show entryBlockID ++ "(" ++ show entryIndex ++ ")"
instance TestEquality (TypedEntryID blocks) where
testEquality (TypedEntryID memb1 i1) (TypedEntryID memb2 i2)
| i1 == i2 = testEquality memb1 memb2
testEquality _ _ = Nothing
-- | Each call site, that jumps or branches to another block, is identified by
-- the entrypoint it occurs in and the entrypoint it calls, and is associated
-- with the free variables at that call site, each of which could have
-- permissions being passed by the call. Call sites also have an integer index
-- to handle the case when one entrypoint calls another multiple times, which
-- can happen if a disjunctive permission is eliminated in the former.
data TypedCallSiteID blocks args vars =
forall args_src.
TypedCallSiteID { callSiteSrc :: TypedEntryID blocks args_src,
callSiteIx :: Int,
callSiteDest :: TypedEntryID blocks args,
callSiteVars :: CruCtx vars }
-- | Get the 'TypedBlockID' of the callee of a call site
callSiteDestBlock :: TypedCallSiteID blocks args vars ->
TypedBlockID blocks args
callSiteDestBlock = entryBlockID . callSiteDest
instance TestEquality (TypedCallSiteID blocks args) where
testEquality (TypedCallSiteID
src1 ix1 dest1 vars1) (TypedCallSiteID src2 ix2 dest2 vars2)
| Just Refl <- testEquality src1 src2
, ix1 == ix2, dest1 == dest2 = testEquality vars1 vars2
testEquality _ _ = Nothing
instance Show (TypedCallSiteID blocks args vars) where
show (TypedCallSiteID {..}) =
"<siteID: src = " ++ show callSiteSrc ++
", ix = " ++ show callSiteIx ++
", dest = " ++ show callSiteDest ++
", vars =" ++ renderDoc (permPretty emptyPPInfo callSiteVars) ++ ">"
-- | Test if the caller of a 'TypedCallSiteID' equals a given entrypoint
callSiteIDCallerEq :: TypedEntryID blocks args_src ->
TypedCallSiteID blocks args vars -> Bool
callSiteIDCallerEq entryID (TypedCallSiteID {..}) =
isJust $ testEquality entryID callSiteSrc
-- | A typed target for jump and branch statements, where the argument registers
-- (including top-level function arguments and free variables) are given with
-- their permissions as a 'DistPerms'
data TypedJumpTarget blocks tops ps where
TypedJumpTarget ::
!(TypedCallSiteID blocks args vars) ->
!(Proxy tops) -> !(CruCtx args) ->
!(DistPerms ((tops :++: args) :++: vars)) ->
TypedJumpTarget blocks tops ((tops :++: args) :++: vars)
$(mkNuMatching [t| forall tp. TypedReg tp |])
$(mkNuMatching [t| forall tp. RegWithVal tp |])
$(mkNuMatching [t| forall ctx. TypedRegs ctx |])
instance NuMatchingAny1 TypedReg where
nuMatchingAny1Proof = nuMatchingProof
instance NuMatchingAny1 RegWithVal where
nuMatchingAny1Proof = nuMatchingProof
$(mkNuMatching [t| forall ext tp. NuMatchingExtC ext => TypedExpr ext tp |])
$(mkNuMatching [t| forall ghosts args gouts ret.
TypedFnHandle ghosts args gouts ret |])
$(mkNuMatching [t| forall blocks args. TypedBlockID blocks args |])
$(mkNuMatching [t| forall blocks args. TypedEntryID blocks args |])
$(mkNuMatching [t| forall blocks args ghosts. TypedCallSiteID blocks args ghosts |])
$(mkNuMatching [t| forall blocks tops ps_in. TypedJumpTarget blocks tops ps_in |])
instance NuMatchingAny1 (TypedJumpTarget blocks tops) where
nuMatchingAny1Proof = nuMatchingProof
instance NuMatchingAny1 (TypedBlockID blocks) where
nuMatchingAny1Proof = nuMatchingProof
instance NuMatchingAny1 (TypedEntryID blocks) where
nuMatchingAny1Proof = nuMatchingProof
instance Closable (TypedBlockID blocks args) where
toClosed (TypedBlockID memb ix) =
$(mkClosed [| TypedBlockID |])
`clApply` toClosed memb `clApply` toClosed ix
instance Liftable (TypedBlockID blocks args) where
mbLift = unClosed . mbLift . fmap toClosed
instance Closable (TypedEntryID blocks args) where
toClosed (TypedEntryID entryBlockID entryIndex) =
$(mkClosed [| TypedEntryID |])
`clApply` toClosed entryBlockID `clApply` toClosed entryIndex
instance Liftable (TypedEntryID blocks args) where
mbLift = unClosed . mbLift . fmap toClosed
instance Closable (TypedCallSiteID blocks args vars) where
toClosed (TypedCallSiteID src ix dest vars) =
$(mkClosed [| TypedCallSiteID |])
`clApply` toClosed src `clApply` toClosed ix
`clApply` toClosed dest `clApply` toClosed vars
instance Liftable (TypedCallSiteID blocks args vars) where
mbLift = unClosed . mbLift . fmap toClosed
----------------------------------------------------------------------
-- * Typed Crucible Statements
----------------------------------------------------------------------
-- | Typed Crucible statements with the given Crucible syntax extension and the
-- given set of return values
data TypedStmt ext (stmt_rets :: RList CrucibleType) ps_in ps_out where
-- | Assign a pure Crucible expressions to a register, where pure here means
-- that its translation to SAW will be pure (i.e., no LLVM pointer operations)
TypedSetReg :: !(TypeRepr tp) -> !(TypedExpr ext tp) ->
TypedStmt ext (RNil :> tp) RNil (RNil :> tp)
-- | Assign a pure permissions expression to a register
TypedSetRegPermExpr :: !(TypeRepr tp) -> !(PermExpr tp) ->
TypedStmt ext (RNil :> tp) RNil (RNil :> tp)
-- | A function call to the function in register @f@, which must have function
-- permission @(ghosts). ps_in -o ps_out@, passing the supplied registers for
-- the @ghosts@ and @args@, where the former must be equal to the supplied
-- expressions @gexprs@. A call has permissions
--
-- > [gexprs/ghosts]ps_in, ghosts1:eq(gexprs1), ..., ghostsn:eq(gexprsn),
-- > f:((ghosts). ps_in -o ps_out)
-- > -o
-- > [gexprs/ghosts]ps_out
TypedCall :: args ~ CtxToRList cargs =>
!(TypedReg (FunctionHandleType cargs ret)) ->
!(FunPerm ghosts args gouts ret) ->
!(TypedRegs ghosts) -> !(PermExprs ghosts) -> !(TypedRegs args) ->
TypedStmt ext (gouts :> ret)
((ghosts :++: args) :++: ghosts :> FunctionHandleType cargs ret)
((ghosts :++: args) :++: gouts :> ret)
-- | Assert a boolean condition, printing the given string on failure
TypedAssert :: !(TypedReg BoolType) -> !(TypedReg (StringType Unicode)) ->
TypedStmt ext RNil RNil RNil
-- | LLVM-specific statement
TypedLLVMStmt :: !(TypedLLVMStmt ret ps_in ps_out) ->
TypedStmt LLVM (RNil :> ret) ps_in ps_out
data TypedLLVMStmt ret ps_in ps_out where
-- | Assign an LLVM word (i.e., a pointer with block 0) to a register
--
-- Type: @. -o ret:eq(word(x))@
ConstructLLVMWord :: (1 <= w2, KnownNat w2) =>
!(TypedReg (BVType w2)) ->
TypedLLVMStmt (LLVMPointerType w2)
RNil
(RNil :> LLVMPointerType w2)
-- | Assert that an LLVM pointer is a word, and return 0. This is the typed
-- version of 'LLVM_PointerBlock' when we know the input is a word, i.e., has
-- a pointer block value of 0.
--
-- Type: @x:eq(word(y)) -o ret:eq(0)@
AssertLLVMWord :: (1 <= w2, KnownNat w2) =>
!(TypedReg (LLVMPointerType w2)) ->
!(PermExpr (BVType w2)) ->
TypedLLVMStmt NatType
(RNil :> LLVMPointerType w2)
(RNil :> NatType)
-- | Assert that an LLVM pointer is a pointer
--
-- Type: @x:is_llvmptr -o .@
AssertLLVMPtr :: (1 <= w2, KnownNat w2) =>
!(TypedReg (LLVMPointerType w2)) ->
TypedLLVMStmt UnitType (RNil :> LLVMPointerType w2) RNil
-- | Destruct an LLVM word into its bitvector value, which should equal the
-- given expression
--
-- Type: @x:eq(word(e)) -o ret:eq(e)@
DestructLLVMWord :: (1 <= w2, KnownNat w2) =>
!(TypedReg (LLVMPointerType w2)) ->
!(PermExpr (BVType w2)) ->
TypedLLVMStmt (BVType w2)
(RNil :> LLVMPointerType w2)
(RNil :> BVType w2)
-- | Add an offset to an LLVM value
--
-- Type: @. -o ret:eq(x &+ off)@
OffsetLLVMValue :: (1 <= w2, KnownNat w2) =>
!(TypedReg (LLVMPointerType w2)) ->
!(PermExpr (BVType w2)) ->
TypedLLVMStmt (LLVMPointerType w2)
RNil
(RNil :> LLVMPointerType w2)
-- | Load a machine value from the address pointed to by the given pointer
-- using the supplied field permission. Some set of permissions @ps@ can be on
-- the stack below the field permission, and these are preserved. The lifetime
-- of the field permission must also be proved to be current; the permissions
-- for this are on the top of the stack and are also preserved.
--
-- Type:
-- > ps, x:ptr((rw,0) |-> p), cur_ps
-- > -o ps, x:ptr((rw,0) |-> eq(ret)), ret:p, cur_ps
TypedLLVMLoad ::
(HasPtrWidth w, 1 <= sz, KnownNat sz) =>
!(TypedReg (LLVMPointerType w)) ->
!(LLVMFieldPerm w sz) ->
!(DistPerms ps) ->
!(LifetimeCurrentPerms ps_l) ->
TypedLLVMStmt (LLVMPointerType sz)
(ps :> LLVMPointerType w :++: ps_l)
(ps :> LLVMPointerType w :> LLVMPointerType sz :++: ps_l)
-- | Store a machine value to the address pointed to by the given pointer
-- using the supplied field permission, which also specifies the offset from
-- the pointer where the store occurs. Some set of permissions @ps@ can be on
-- the stack below the field permission, and these are preserved. The lifetime
-- of the field permission must also be proved to be current; the permissions
-- for this are on the top of the stack and are also preserved.
--
-- Type:
-- > ps, x:ptr((rw,0) |-> p), cur_ps
-- > -o ps, x:ptr((rw,0) |-> eq(e)), cur_ps
TypedLLVMStore ::
(HasPtrWidth w, 1 <= sz, KnownNat sz) =>
!(TypedReg (LLVMPointerType w)) ->
!(LLVMFieldPerm w sz) ->
!(PermExpr (LLVMPointerType sz)) ->
!(DistPerms ps) ->
!(LifetimeCurrentPerms ps_l) ->
TypedLLVMStmt UnitType
(ps :> LLVMPointerType w :++: ps_l)
(ps :> LLVMPointerType w :++: ps_l)
-- | Allocate an object of the given size on the given LLVM frame, described
-- as a memory block with empty shape:
--
-- Type:
-- > fp:frame(ps) -o fp:frame(ps,(ret,i)),
-- > ret:memblock(W,0,sz,emptysh)
--
-- where @sz@ is the number of bytes allocated
TypedLLVMAlloca ::
HasPtrWidth w =>
!(TypedReg (LLVMFrameType w)) ->
!(LLVMFramePerm w) ->
!Integer ->
TypedLLVMStmt (LLVMPointerType w)
(RNil :> LLVMFrameType w)
(RNil :> LLVMFrameType w :> LLVMPointerType w)
-- | Create a new LLVM frame
--
-- Type: @. -o ret:frame()@
TypedLLVMCreateFrame ::
HasPtrWidth w =>
TypedLLVMStmt (LLVMFrameType w) RNil (RNil :> LLVMFrameType w)
-- | Delete an LLVM frame and deallocate all memory objects allocated in it,
-- assuming that the current distinguished permissions @ps@ correspond to the
-- write permissions to all those objects allocated on the frame
--
-- Type: @ps, fp:frame(ps) -o .@
TypedLLVMDeleteFrame ::
HasPtrWidth w =>
!(TypedReg (LLVMFrameType w)) ->
!(LLVMFramePerm w) -> !(DistPerms ps) ->
TypedLLVMStmt UnitType (ps :> LLVMFrameType w) RNil
-- | Typed version of 'LLVM_LoadHandle', that loads the function handle
-- referred to by a function pointer, assuming we know it has one:
--
-- Type: @x:llvm_funptr(p) -o ret:p@
TypedLLVMLoadHandle ::
HasPtrWidth w =>
!(TypedReg (LLVMPointerType w)) ->
!(TypeRepr (FunctionHandleType cargs ret)) ->
!(ValuePerm (FunctionHandleType cargs ret)) ->
TypedLLVMStmt (FunctionHandleType cargs ret)
(RNil :> LLVMPointerType w)
(RNil :> FunctionHandleType cargs ret)
-- | Typed version of 'LLVM_ResolveGlobal', that resolves a 'GlobalSymbol' to
-- an LLVM value, assuming it has the given permission in the environment:
--
-- Type: @. -o ret:p@
TypedLLVMResolveGlobal ::
HasPtrWidth w =>
!GlobalSymbol ->
!(ValuePerm (LLVMPointerType w)) ->
TypedLLVMStmt (LLVMPointerType w) RNil (RNil :> LLVMPointerType w)
-- | An if-then-else statement over LLVM values
TypedLLVMIte ::
1 <= w =>
!(NatRepr w) ->
!(TypedReg BoolType) ->
!(TypedReg (LLVMPointerType w)) ->
!(TypedReg (LLVMPointerType w)) ->
TypedLLVMStmt (LLVMPointerType w) RNil (RNil :> LLVMPointerType w)
-- | Return the input permissions for a 'TypedStmt'
typedStmtIn :: TypedStmt ext stmt_rets ps_in ps_out -> DistPerms ps_in
typedStmtIn (TypedSetReg _ _) = DistPermsNil
typedStmtIn (TypedSetRegPermExpr _ _) = DistPermsNil
typedStmtIn (TypedCall (TypedReg f) fun_perm ghosts gexprs args) =
DistPermsCons
(funPermDistIns fun_perm (typedRegsToVars ghosts) gexprs (typedRegsToVars args))
f (ValPerm_Conj1 $ Perm_Fun fun_perm)
typedStmtIn (TypedAssert _ _) = DistPermsNil
typedStmtIn (TypedLLVMStmt llvmStmt) = typedLLVMStmtIn llvmStmt
-- | Return the input permissions for a 'TypedLLVMStmt'
typedLLVMStmtIn :: TypedLLVMStmt ret ps_in ps_out -> DistPerms ps_in
typedLLVMStmtIn (ConstructLLVMWord _) = DistPermsNil
typedLLVMStmtIn (AssertLLVMWord (TypedReg x) e) =
distPerms1 x (ValPerm_Eq $ PExpr_LLVMWord e)
typedLLVMStmtIn (AssertLLVMPtr (TypedReg x)) =
distPerms1 x (ValPerm_Conj1 Perm_IsLLVMPtr)
typedLLVMStmtIn (DestructLLVMWord (TypedReg x) e) =
distPerms1 x (ValPerm_Eq $ PExpr_LLVMWord e)
typedLLVMStmtIn (OffsetLLVMValue _ _) =
DistPermsNil
typedLLVMStmtIn (TypedLLVMLoad (TypedReg x) fp ps ps_l) =
withKnownNat ?ptrWidth $
permAssert
(lifetimeCurrentPermsLifetime ps_l == llvmFieldLifetime fp)
"typedLLVMStmtIn: TypedLLVMLoad: mismatch for field lifetime" $
permAssert (bvEq (llvmFieldOffset fp) (bvInt 0))
"typedLLVMStmtIn: TypedLLVMLoad: mismatch for field offset" $
appendDistPerms
(DistPermsCons ps x (ValPerm_Conj1 $ Perm_LLVMField fp))
(lifetimeCurrentPermsPerms ps_l)
typedLLVMStmtIn (TypedLLVMStore (TypedReg x) fp _ ps cur_ps) =
withKnownNat ?ptrWidth $
permAssert (llvmFieldRW fp == PExpr_Write &&
bvEq (llvmFieldOffset fp) (bvInt 0) &&
llvmFieldLifetime fp == lifetimeCurrentPermsLifetime cur_ps)
"typedLLVMStmtIn: TypedLLVMStore: mismatch for field permission" $
appendDistPerms
(DistPermsCons ps x (ValPerm_Conj1 $ Perm_LLVMField fp))
(lifetimeCurrentPermsPerms cur_ps)
typedLLVMStmtIn (TypedLLVMAlloca (TypedReg f) fperms _) =
withKnownNat ?ptrWidth $
distPerms1 f (ValPerm_Conj [Perm_LLVMFrame fperms])
typedLLVMStmtIn TypedLLVMCreateFrame = DistPermsNil
typedLLVMStmtIn (TypedLLVMDeleteFrame (TypedReg f) fperms perms) =
withKnownNat ?ptrWidth $
case llvmFrameDeletionPerms fperms of
Some perms'
| Just Refl <- testEquality perms perms' ->
DistPermsCons perms f (ValPerm_Conj1 $ Perm_LLVMFrame fperms)
_ -> error "typedLLVMStmtIn: incorrect perms in rule"
typedLLVMStmtIn (TypedLLVMLoadHandle (TypedReg f) tp p) =
withKnownNat ?ptrWidth $
distPerms1 f (ValPerm_Conj1 $ Perm_LLVMFunPtr tp p)
typedLLVMStmtIn (TypedLLVMResolveGlobal _ _) =
DistPermsNil
typedLLVMStmtIn (TypedLLVMIte _ _ _ _) = DistPermsNil
-- | Return the output permissions for a 'TypedStmt'
typedStmtOut :: TypedStmt ext stmt_rets ps_in ps_out ->
RAssign Name stmt_rets -> DistPerms ps_out
typedStmtOut (TypedSetReg _ (TypedExpr _ (Just e))) (_ :>: ret) =
distPerms1 ret (ValPerm_Eq e)
typedStmtOut (TypedSetReg _ (TypedExpr _ Nothing)) (_ :>: ret) =
distPerms1 ret ValPerm_True
typedStmtOut (TypedSetRegPermExpr _ e) (_ :>: ret) =
distPerms1 ret (ValPerm_Eq e)
typedStmtOut (TypedCall _ fun_perm ghosts gexprs args) rets =
funPermDistOuts fun_perm (typedRegsToVars ghosts) gexprs
(typedRegsToVars args) rets
typedStmtOut (TypedAssert _ _) _ = DistPermsNil
typedStmtOut (TypedLLVMStmt llvmStmt) (_ :>: ret) =
typedLLVMStmtOut llvmStmt ret
-- | Return the output permissions for a 'TypedStmt'
typedLLVMStmtOut :: TypedLLVMStmt ret ps_in ps_out -> Name ret ->
DistPerms ps_out
typedLLVMStmtOut (ConstructLLVMWord (TypedReg x)) ret =
distPerms1 ret (ValPerm_Eq $ PExpr_LLVMWord $ PExpr_Var x)
typedLLVMStmtOut (AssertLLVMWord (TypedReg _) _) ret =
distPerms1 ret (ValPerm_Eq $ PExpr_Nat 0)
typedLLVMStmtOut (AssertLLVMPtr _) _ = DistPermsNil
typedLLVMStmtOut (DestructLLVMWord (TypedReg _) e) ret =
distPerms1 ret (ValPerm_Eq e)
typedLLVMStmtOut (OffsetLLVMValue (TypedReg x) off) ret =
distPerms1 ret (ValPerm_Eq $ PExpr_LLVMOffset x off)
typedLLVMStmtOut (TypedLLVMLoad (TypedReg x) fp ps ps_l) ret =
withKnownNat ?ptrWidth $
if lifetimeCurrentPermsLifetime ps_l == llvmFieldLifetime fp then
appendDistPerms
(DistPermsCons
(DistPermsCons ps
x (ValPerm_Conj1 $ Perm_LLVMField $
fp { llvmFieldContents = ValPerm_Eq (PExpr_Var ret) }))
ret (llvmFieldContents fp))
(lifetimeCurrentPermsPerms ps_l)
else
error "typedLLVMStmtOut: TypedLLVMLoad: mismatch for field lifetime"
typedLLVMStmtOut (TypedLLVMStore (TypedReg x) fp e ps cur_ps) _ =
withKnownNat ?ptrWidth $
permAssert (llvmFieldRW fp == PExpr_Write &&
bvEq (llvmFieldOffset fp) (bvInt 0) &&
llvmFieldLifetime fp == lifetimeCurrentPermsLifetime cur_ps)
"typedLLVMStmtOut: TypedLLVMStore: mismatch for field permission" $
appendDistPerms
(DistPermsCons ps x (ValPerm_Conj1 $ Perm_LLVMField $
fp { llvmFieldContents = ValPerm_Eq e }))
(lifetimeCurrentPermsPerms cur_ps)
typedLLVMStmtOut (TypedLLVMAlloca
(TypedReg f) (fperms :: LLVMFramePerm w) len) ret =
withKnownNat ?ptrWidth $
distPerms2 f (ValPerm_Conj [Perm_LLVMFrame ((PExpr_Var ret, len):fperms)])
ret (llvmEmptyBlockPermOfSize Proxy len)
typedLLVMStmtOut TypedLLVMCreateFrame ret =
withKnownNat ?ptrWidth $
distPerms1 ret $ ValPerm_Conj [Perm_LLVMFrame []]
typedLLVMStmtOut (TypedLLVMDeleteFrame _ _ _) _ = DistPermsNil
typedLLVMStmtOut (TypedLLVMLoadHandle _ _ p) ret = distPerms1 ret p
typedLLVMStmtOut (TypedLLVMResolveGlobal _ p) ret =
distPerms1 ret p
typedLLVMStmtOut (TypedLLVMIte _ _ (TypedReg x1) (TypedReg x2)) ret =
distPerms1 ret (ValPerm_Or (ValPerm_Eq $ PExpr_Var x1)
(ValPerm_Eq $ PExpr_Var x2))
-- | Check that the permission stack of the given permission set matches the
-- input permissions of the given statement, and replace them with the output
-- permissions of the statement
applyTypedStmt :: TypedStmt ext stmt_rets ps_in ps_out ->
RAssign Name stmt_rets -> PermSet ps_in -> PermSet ps_out
applyTypedStmt stmt stmt_rets =
modifyDistPerms $ \perms ->
if perms == typedStmtIn stmt then
typedStmtOut stmt stmt_rets
else
error "applyTypedStmt: unexpected input permissions!"
----------------------------------------------------------------------
-- * Typed Sequences of Crucible Statements
----------------------------------------------------------------------
-- | A permission implication annotated a top-level error message to be printed
-- on failure
data AnnotPermImpl r ps = AnnotPermImpl !String !(PermImpl r ps)
-- | Typed return argument
data TypedRet tops rets ps =
TypedRet
!(ps :~: tops :++: rets) !(CruCtx rets) !(RAssign ExprVar rets)
!(Mb rets (DistPerms ps))
-- | Typed Crucible block termination statements
data TypedTermStmt blocks tops rets ps_in where
-- | Jump to the given jump target
TypedJump :: !(AnnotPermImpl (TypedJumpTarget blocks tops) ps_in) ->
TypedTermStmt blocks tops rets ps_in
-- | Branch on condition: if true, jump to the first jump target, and
-- otherwise jump to the second jump target
TypedBr :: !(TypedReg BoolType) ->
!(AnnotPermImpl (TypedJumpTarget blocks tops) ps_in) ->
!(AnnotPermImpl (TypedJumpTarget blocks tops) ps_in) ->
TypedTermStmt blocks tops rets ps_in
-- | Return from function, providing the return value and also proof that the
-- current permissions imply the required return permissions
TypedReturn :: !(AnnotPermImpl (TypedRet tops rets) ps_in) ->
TypedTermStmt blocks tops rets ps_in
-- | Block ends with an error
TypedErrorStmt :: !(Maybe String) -> !(TypedReg (StringType Unicode)) ->
TypedTermStmt blocks tops rets ps_in
-- | A typed sequence of Crucible statements
data TypedStmtSeq ext blocks tops rets ps_in where
-- | A permission implication step, which modifies the current permission
-- set. This can include pattern-matches and/or assertion failures.
TypedImplStmt :: !(AnnotPermImpl (TypedStmtSeq ext blocks tops rets) ps_in) ->
TypedStmtSeq ext blocks tops rets ps_in
-- | Typed version of 'ConsStmt', which binds new variables for the return
-- value(s) of each statement
TypedConsStmt :: !ProgramLoc ->
!(TypedStmt ext stmt_rets ps_in ps_next) ->
!(RAssign Proxy stmt_rets) ->
!(Mb stmt_rets (TypedStmtSeq ext blocks tops rets ps_next)) ->
TypedStmtSeq ext blocks tops rets ps_in
-- | Typed version of 'TermStmt', which terminates the current block
TypedTermStmt :: !ProgramLoc ->
!(TypedTermStmt blocks tops rets ps_in) ->
TypedStmtSeq ext blocks tops rets ps_in
$(mkNuMatching [t| forall r ps. NuMatchingAny1 r => AnnotPermImpl r ps |])
$(mkNuMatching [t| forall tp ps_out ps_in.
TypedLLVMStmt tp ps_out ps_in |])
$(mkNuMatching [t| forall ext stmt_rets ps_in ps_out. NuMatchingExtC ext =>
TypedStmt ext stmt_rets ps_in ps_out |])
$(mkNuMatching [t| forall tops rets ps. TypedRet tops rets ps |])
instance NuMatchingAny1 (TypedRet tops rets) where
nuMatchingAny1Proof = nuMatchingProof
$(mkNuMatching [t| forall blocks tops rets ps_in.
TypedTermStmt blocks tops rets ps_in |])
$(mkNuMatching [t| forall ext blocks tops rets ps_in.
NuMatchingExtC ext => TypedStmtSeq ext blocks tops rets ps_in |])
instance NuMatchingExtC ext =>
NuMatchingAny1 (TypedStmtSeq ext blocks tops rets) where
nuMatchingAny1Proof = nuMatchingProof
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (TypedReg tp) m where
genSubst s (mbMatch -> [nuMP| TypedReg x |]) = TypedReg <$> genSubst s x
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (RegWithVal tp) m where
genSubst s mb_x = case mbMatch mb_x of
[nuMP| RegWithVal r e |] ->
RegWithVal <$> genSubst s r <*> genSubst s e
[nuMP| RegNoVal r |] -> RegNoVal <$> genSubst s r
instance SubstVar PermVarSubst m =>
Substable1 PermVarSubst RegWithVal m where
genSubst1 = genSubst
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (TypedRegs tp) m where
genSubst s mb_x = case mbMatch mb_x of
[nuMP| TypedRegsNil |] -> return TypedRegsNil
[nuMP| TypedRegsCons rs r |] ->
TypedRegsCons <$> genSubst s rs <*> genSubst s r
instance (NuMatchingAny1 r, SubstVar PermVarSubst m,
Substable1 PermVarSubst r m) =>
Substable PermVarSubst (AnnotPermImpl r ps) m where
genSubst s (mbMatch -> [nuMP| AnnotPermImpl err impl |]) =
AnnotPermImpl (mbLift err) <$> genSubst s impl
instance (PermCheckExtC ext, NuMatchingAny1 f,
SubstVar PermVarSubst m, Substable1 PermVarSubst f m,
Substable PermVarSubst (f BoolType) m) =>
Substable PermVarSubst (App ext f a) m where
genSubst s mb_expr = case mbMatch mb_expr of
[nuMP| ExtensionApp _ |] ->
error "genSubst: unexpected ExtensionApp"
[nuMP| BaseIsEq tp e1 e2 |] ->
BaseIsEq (mbLift tp) <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| EmptyApp |] -> return EmptyApp
[nuMP| BoolLit b |] -> return $ BoolLit $ mbLift b
[nuMP| Not e |] ->
Not <$> genSubst1 s e
[nuMP| And e1 e2 |] ->
And <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| Or e1 e2 |] ->
Or <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BoolXor e1 e2 |] ->
BoolXor <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| NatLit n |] ->
return $ NatLit $ mbLift n
[nuMP| NatLt e1 e2 |] ->
NatLt <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| NatLe e1 e2 |] ->
NatLe <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| NatEq e1 e2 |] ->
NatEq <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| NatAdd e1 e2 |] ->
NatAdd <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| NatSub e1 e2 |] ->
NatSub <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| NatMul e1 e2 |] ->
NatMul <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| NatDiv e1 e2 |] ->
NatDiv <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| NatMod e1 e2 |] ->
NatMod <$> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| HandleLit h |] ->
return $ HandleLit $ mbLift h
[nuMP| BVUndef w |] ->
BVUndef <$> genSubst s w
[nuMP| BVLit w i |] ->
BVLit <$> genSubst s w <*> return (mbLift i)
[nuMP| BVConcat w1 w2 e1 e2 |] ->
BVConcat <$> genSubst s w1 <*> genSubst s w2 <*>
genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVTrunc w1 w2 e |] ->
BVTrunc <$> genSubst s w1 <*> genSubst s w2 <*> genSubst1 s e
[nuMP| BVZext w1 w2 e |] ->
BVZext <$> genSubst s w1 <*> genSubst s w2 <*> genSubst1 s e
[nuMP| BVSext w1 w2 e |] ->
BVSext <$> genSubst s w1 <*> genSubst s w2 <*> genSubst1 s e
[nuMP| BVNot w e |] ->
BVNot <$> genSubst s w <*> genSubst1 s e
[nuMP| BVAnd w e1 e2 |] ->
BVAnd <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVOr w e1 e2 |] ->
BVOr <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVXor w e1 e2 |] ->
BVXor <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVNeg w e |] ->
BVNeg <$> genSubst s w <*> genSubst1 s e
[nuMP| BVAdd w e1 e2 |] ->
BVAdd <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVSub w e1 e2 |] ->
BVSub <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVMul w e1 e2 |] ->
BVMul <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVUdiv w e1 e2 |] ->
BVUdiv <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVSdiv w e1 e2 |] ->
BVSdiv <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVUrem w e1 e2 |] ->
BVUrem <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVSrem w e1 e2 |] ->
BVSrem <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVUle w e1 e2 |] ->
BVUle <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVUlt w e1 e2 |] ->
BVUlt <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVSle w e1 e2 |] ->
BVSle <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVSlt w e1 e2 |] ->
BVSlt <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVCarry w e1 e2 |] ->
BVCarry <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVSCarry w e1 e2 |] ->
BVSCarry <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVSBorrow w e1 e2 |] ->
BVSBorrow <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVShl w e1 e2 |] ->
BVShl <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVLshr w e1 e2 |] ->
BVLshr <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BVAshr w e1 e2 |] ->
BVAshr <$> genSubst s w <*> genSubst1 s e1 <*> genSubst1 s e2
[nuMP| BoolToBV w e |] ->
BoolToBV <$> genSubst s w <*> genSubst1 s e
[nuMP| BVNonzero w e |] ->
BVNonzero <$> genSubst s w <*> genSubst1 s e
[nuMP| StringLit str_lit |] ->
return $ StringLit $ mbLift str_lit
[nuMP| MkStruct tps flds |] ->
MkStruct (mbLift tps) <$> genSubst s flds
[nuMP| GetStruct str ix tp |] ->
GetStruct <$> genSubst1 s str <*> return (mbLift ix) <*> return (mbLift tp)
[nuMP| SetStruct tps str ix x |] ->
SetStruct (mbLift tps) <$> genSubst1 s str <*> return (mbLift ix)
<*> genSubst1 s x
_ ->
error ("genSubst: unhandled Crucible expression construct: "
++ mbLift (fmap (show . ppApp (const (pretty "_"))) mb_expr))
instance (PermCheckExtC ext, SubstVar PermVarSubst m) =>
Substable PermVarSubst (TypedExpr ext tp) m where
genSubst s (mbMatch -> [nuMP| TypedExpr app maybe_val |]) =
TypedExpr <$> genSubst s app <*> genSubst s maybe_val
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (TypedLLVMStmt tp ps_out ps_in) m where
genSubst s mb_x = case mbMatch mb_x of
[nuMP| ConstructLLVMWord r |] -> ConstructLLVMWord <$> genSubst s r
[nuMP| AssertLLVMWord r e |] ->
AssertLLVMWord <$> genSubst s r <*> genSubst s e
[nuMP| AssertLLVMPtr r |] ->
AssertLLVMPtr <$> genSubst s r
[nuMP| DestructLLVMWord r e |] ->
DestructLLVMWord <$> genSubst s r <*> genSubst s e
[nuMP| OffsetLLVMValue r off |] ->
OffsetLLVMValue <$> genSubst s r <*> genSubst s off
[nuMP| TypedLLVMLoad r fp ps ps_l |] ->
TypedLLVMLoad <$> genSubst s r <*> genSubst s fp <*> genSubst s ps <*>
genSubst s ps_l
[nuMP| TypedLLVMStore r fp e ps cur_ps |] ->
TypedLLVMStore <$> genSubst s r <*> genSubst s fp <*> genSubst s e <*>
genSubst s ps <*> genSubst s cur_ps
[nuMP| TypedLLVMAlloca r fperms i |] ->
TypedLLVMAlloca <$> genSubst s r <*> genSubst s fperms <*>
return (mbLift i)
[nuMP| TypedLLVMCreateFrame |] -> return TypedLLVMCreateFrame
[nuMP| TypedLLVMDeleteFrame r fperms perms |] ->
TypedLLVMDeleteFrame <$> genSubst s r <*> genSubst s fperms <*>
genSubst s perms
[nuMP| TypedLLVMLoadHandle r tp p |] ->
TypedLLVMLoadHandle <$> genSubst s r <*> return (mbLift tp) <*> genSubst s p
[nuMP| TypedLLVMResolveGlobal gsym p |] ->
TypedLLVMResolveGlobal (mbLift gsym) <$> genSubst s p
[nuMP| TypedLLVMIte w r1 r2 r3 |] ->
TypedLLVMIte (mbLift w) <$> genSubst s r1 <*> genSubst s r2 <*> genSubst s r3
instance (PermCheckExtC ext, SubstVar PermVarSubst m) =>
Substable PermVarSubst (TypedStmt ext rets ps_in ps_out) m where
genSubst s mb_x = case mbMatch mb_x of
[nuMP| TypedSetReg tp expr |] ->
TypedSetReg (mbLift tp) <$> genSubst s expr
[nuMP| TypedSetRegPermExpr tp expr |] ->
TypedSetRegPermExpr (mbLift tp) <$> genSubst s expr
[nuMP| TypedCall f fun_perm ghosts gexprs args |] ->
TypedCall <$> genSubst s f <*> genSubst s fun_perm <*>
genSubst s ghosts <*> genSubst s gexprs <*> genSubst s args
[nuMP| TypedAssert r1 r2 |] ->
TypedAssert <$> genSubst s r1 <*> genSubst s r2
[nuMP| TypedLLVMStmt llvmStmt |] ->
TypedLLVMStmt <$> genSubst s llvmStmt
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (TypedRet tops rets ps) m where
genSubst s (mbMatch -> [nuMP| TypedRet e rets ret_vars mb_perms |]) =
give (cruCtxProxies $ mbLift rets)
(TypedRet (mbLift e) (mbLift rets) <$> genSubst s ret_vars
<*> genSubst s mb_perms)
instance SubstVar PermVarSubst m =>
Substable1 PermVarSubst (TypedRet tops rets) m where
genSubst1 = genSubst
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (TypedJumpTarget blocks tops ps) m where
genSubst s (mbMatch -> [nuMP| TypedJumpTarget siteID prx ctx perms |]) =
TypedJumpTarget (mbLift siteID) (mbLift prx) (mbLift ctx) <$>
genSubst s perms
instance SubstVar PermVarSubst m =>
Substable1 PermVarSubst (TypedJumpTarget blocks tops) m where
genSubst1 = genSubst
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (TypedTermStmt blocks tops rets ps_in) m where
genSubst s mb_x = case mbMatch mb_x of
[nuMP| TypedJump impl_tgt |] -> TypedJump <$> genSubst s impl_tgt
[nuMP| TypedBr reg impl_tgt1 impl_tgt2 |] ->
TypedBr <$> genSubst s reg <*> genSubst s impl_tgt1 <*>
genSubst s impl_tgt2
[nuMP| TypedReturn impl_ret |] ->
TypedReturn <$> genSubst s impl_ret
[nuMP| TypedErrorStmt str r |] ->
TypedErrorStmt (mbLift str) <$> genSubst s r
instance (PermCheckExtC ext, SubstVar PermVarSubst m) =>
Substable PermVarSubst (TypedStmtSeq ext blocks tops rets ps_in) m where
genSubst s mb_x = case mbMatch mb_x of
[nuMP| TypedImplStmt impl_seq |] ->
TypedImplStmt <$> genSubst s impl_seq
[nuMP| TypedConsStmt loc stmt pxys mb_seq |] ->
TypedConsStmt (mbLift loc) <$> genSubst s stmt <*> pure (mbLift pxys)
<*> give (mbLift pxys) (genSubst s mb_seq)
[nuMP| TypedTermStmt loc term_stmt |] ->
TypedTermStmt (mbLift loc) <$> genSubst s term_stmt
instance (PermCheckExtC ext, SubstVar PermVarSubst m) =>
Substable1 PermVarSubst (TypedStmtSeq ext blocks tops rets) m where
genSubst1 = genSubst
----------------------------------------------------------------------
-- * Typed Control-Flow Graphs
----------------------------------------------------------------------
-- FIXME: remove in-degree stuff
-- | This type characterizes the number and sort of jumps to a 'TypedEntry'
data TypedEntryInDegree
-- | There are no jumps to the entrypoint
= EntryInDegree_None
-- | There is one jump to the entrypoint
| EntryInDegree_One
-- | There is more than one jump to the entrypoint
| EntryInDegree_Many
-- | The entrypoint is the head of a loop, so has more than one jump to it,
-- one of which is a back edge
| EntryInDegree_Loop
-- | "Add" two in-degrees
addInDegrees :: TypedEntryInDegree -> TypedEntryInDegree -> TypedEntryInDegree
addInDegrees EntryInDegree_Loop _ = EntryInDegree_Loop
addInDegrees _ EntryInDegree_Loop = EntryInDegree_Loop
addInDegrees EntryInDegree_None in_deg = in_deg
addInDegrees in_deg EntryInDegree_None = in_deg
addInDegrees _ _ =
-- The last case is adding 1 or many + 1 or many = many
EntryInDegree_Many
-- | Add one to an in-degree
incrInDegree :: TypedEntryInDegree -> TypedEntryInDegree
incrInDegree = addInDegrees EntryInDegree_One
-- | Test if an in-degree is at least many
inDegreeIsMulti :: TypedEntryInDegree -> Bool
inDegreeIsMulti EntryInDegree_None = False
inDegreeIsMulti EntryInDegree_One = False
inDegreeIsMulti EntryInDegree_Many = True
inDegreeIsMulti EntryInDegree_Loop = True
-- | Type-level data-kind to indicate a phase of Heapster, which could be
-- type-checking or translation
data HeapsterPhase = TCPhase | TransPhase
type TCPhase = 'TCPhase
type TransPhase = 'TransPhase
-- | A piece of data of type @a@ needed in the translation phase but that could
-- still be being computed in the type-checking phase
type family TransData phase a where
TransData TCPhase a = Maybe a
TransData TransPhase a = a
-- | The body of an implication in a call site, which ensures that the
-- permissions are as expected and gives expressions for the ghost variables. It
-- also includes a 'TypedEntryID' for the callee, to make translation easier.
data CallSiteImplRet blocks tops args ghosts ps_out =
CallSiteImplRet (TypedEntryID blocks args) (CruCtx ghosts)
((tops :++: args) :++: ghosts :~: ps_out)
(RAssign ExprVar (tops :++: args)) (RAssign ExprVar ghosts)
$(mkNuMatching [t| forall blocks tops args ghosts ps_out.
CallSiteImplRet blocks tops args ghosts ps_out |])
instance NuMatchingAny1 (CallSiteImplRet blocks tops args ghosts) where
nuMatchingAny1Proof = nuMatchingProof
instance SubstVar PermVarSubst m =>
Substable PermVarSubst (CallSiteImplRet
blocks tops args ghosts ps) m where
genSubst s (mbMatch -> [nuMP| CallSiteImplRet entryID ghosts Refl tavars gvars |]) =
CallSiteImplRet (mbLift entryID) (mbLift ghosts) Refl <$>
genSubst s tavars <*> genSubst s gvars
instance SubstVar PermVarSubst m =>
Substable1 PermVarSubst (CallSiteImplRet
blocks tops args ghosts) m where
genSubst1 = genSubst
-- | An implication used in a call site, which binds the input variables in an
-- implication of the output variables
newtype CallSiteImpl blocks ps_in tops args ghosts =
CallSiteImpl (Mb ps_in (AnnotPermImpl
(CallSiteImplRet blocks tops args ghosts) ps_in))
-- | The identity implication
idCallSiteImpl :: TypedEntryID blocks args ->
CruCtx tops -> CruCtx args -> CruCtx vars ->
CallSiteImpl blocks ((tops :++: args) :++: vars) tops args vars
idCallSiteImpl entryID tops args vars =
let tops_args_prxs = cruCtxProxies (appendCruCtx tops args)
vars_prxs = cruCtxProxies vars in
CallSiteImpl $ mbCombine vars_prxs $ nuMulti tops_args_prxs $ \tops_args_ns ->
nuMulti vars_prxs $ \vars_ns ->
AnnotPermImpl "" $ PermImpl_Done $
CallSiteImplRet entryID vars Refl tops_args_ns vars_ns
-- | A jump / branch to a particular entrypoint
data TypedCallSite phase blocks tops args ghosts vars =
TypedCallSite
{
-- | The ID of this call site
typedCallSiteID :: TypedCallSiteID blocks args vars,
-- | The permissions held at the call site
typedCallSitePerms :: MbValuePerms ((tops :++: args) :++: vars),
-- | An implication from the call site perms to the input perms of the
-- entrypoint we are jumping to
typedCallSiteImpl :: TransData phase (CallSiteImpl
blocks
((tops :++: args) :++: vars)
tops args ghosts)
}
-- | Transition a 'TypedEntry' from type-checking to translation phase if its
-- implication has been proved
completeTypedCallSite ::
TypedCallSite TCPhase blocks tops args ghosts vars ->
Maybe (TypedCallSite TransPhase blocks tops args ghosts vars)
completeTypedCallSite call_site
| Just impl <- typedCallSiteImpl call_site
= Just $ call_site { typedCallSiteImpl = impl }
completeTypedCallSite _ = Nothing
-- | Build a 'TypedCallSite' with no implication
emptyTypedCallSite :: TypedCallSiteID blocks args vars ->
MbValuePerms ((tops :++: args) :++: vars) ->
TypedCallSite TCPhase blocks tops args ghosts vars
emptyTypedCallSite siteID perms = TypedCallSite siteID perms Nothing
-- | Build a 'TypedCallSite' that uses the identity implication, meaning its
-- @vars@ will equal the @ghosts@ of its entrypoint
idTypedCallSite :: TypedCallSiteID blocks args vars ->
CruCtx tops -> CruCtx args ->
MbValuePerms ((tops :++: args) :++: vars) ->
TypedCallSite TCPhase blocks tops args vars vars
idTypedCallSite siteID tops args perms =
TypedCallSite siteID perms $ Just $
idCallSiteImpl (callSiteDest siteID) tops args (callSiteVars siteID)
-- | Test if the implication of a call site fails or is not present
typedCallSiteImplFails :: TypedCallSite TCPhase blocks tops args ghosts vars ->
Bool
typedCallSiteImplFails (TypedCallSite { typedCallSiteImpl =
Just (CallSiteImpl mb_annot_impl) }) =
mbLift $ fmap (\(AnnotPermImpl _ impl) -> permImplFails impl) mb_annot_impl
typedCallSiteImplFails _ = True
-- | Extract the caller permissions of a call site as an 'ArgVarPerms'
typedCallSiteArgVarPerms :: TypedCallSite phase blocks tops args ghsots vars ->
ArgVarPerms (tops :++: args) vars
typedCallSiteArgVarPerms (TypedCallSite {..}) =
ArgVarPerms (callSiteVars typedCallSiteID) typedCallSitePerms
-- | A single, typed entrypoint to a Crucible block. Note that our blocks
-- implicitly take extra "ghost" arguments, that are needed to express the input
-- and output permissions. The first of these ghost arguments are the top-level
-- inputs to the entire function.
data TypedEntry phase ext blocks tops rets args ghosts =
TypedEntry
{
-- | The identifier for this particular entrypoing
typedEntryID :: !(TypedEntryID blocks args),
-- | The top-level arguments to the entire function
typedEntryTops :: !(CruCtx tops),
-- | The real arguments to this block
typedEntryArgs :: !(CruCtx args),
-- | The return values (including ghosts) from the entire function
typedEntryRets :: !(CruCtx rets),
-- | The call sites that jump to this particular entrypoint
typedEntryCallers :: ![Some (TypedCallSite phase blocks tops args ghosts)],
-- | The ghost variables for this entrypoint
typedEntryGhosts :: !(CruCtx ghosts),
-- | The input permissions for this entrypoint
typedEntryPermsIn :: !(MbValuePerms ((tops :++: args) :++: ghosts)),
-- | The output permissions for the function (cached locally)
typedEntryPermsOut :: !(MbValuePerms (tops :++: rets)),
-- | The type-checked body of the entrypoint
typedEntryBody :: !(TransData phase
(Mb ((tops :++: args) :++: ghosts)
(TypedStmtSeq ext blocks tops rets
((tops :++: args) :++: ghosts))))
}
-- | Test if an entrypoint has in-degree greater than 1
typedEntryHasMultiInDegree :: TypedEntry phase ext blocks tops rets args ghosts ->
Bool
typedEntryHasMultiInDegree entry = length (typedEntryCallers entry) > 1
-- | Get the types of all the inputs of an entrypoint
typedEntryAllArgs :: TypedEntry phase ext blocks tops rets args ghosts ->
CruCtx ((tops :++: args) :++: ghosts)
typedEntryAllArgs (TypedEntry {..}) =
appendCruCtx (appendCruCtx typedEntryTops typedEntryArgs) typedEntryGhosts
-- | Transition a 'TypedEntry' from type-checking to translation phase if its
-- body is present and all call site implications have been proved
completeTypedEntry ::
TypedEntry TCPhase ext blocks tops rets args ghosts ->
Maybe (TypedEntry TransPhase ext blocks tops rets args ghosts)
completeTypedEntry (TypedEntry { .. })
| Just body <- typedEntryBody
, Just callers <- mapM (traverseF completeTypedCallSite) typedEntryCallers
= Just $ TypedEntry { typedEntryBody = body, typedEntryCallers = callers, .. }
completeTypedEntry _ = Nothing
-- | Build an entrypoint from a call site, using that call site's permissions as
-- the entyrpoint input permissions
singleCallSiteEntry :: TypedCallSiteID blocks args vars ->
CruCtx tops -> CruCtx args -> CruCtx rets ->
MbValuePerms ((tops :++: args) :++: vars) ->
MbValuePerms (tops :++: rets) ->
TypedEntry TCPhase ext blocks tops rets args vars
singleCallSiteEntry siteID tops args rets perms_in perms_out =
TypedEntry
{
typedEntryID = callSiteDest siteID, typedEntryTops = tops,
typedEntryArgs = args, typedEntryRets = rets,
typedEntryCallers = [Some $ idTypedCallSite siteID tops args perms_in],
typedEntryGhosts = callSiteVars siteID,
typedEntryPermsIn = perms_in, typedEntryPermsOut = perms_out,
typedEntryBody = Nothing
}
-- | Test if an entrypoint contains a call site with the given caller
typedEntryHasCaller :: TypedEntryID blocks args_src ->
TypedEntry phase ext blocks tops rets args ghosts ->
Bool
typedEntryHasCaller callerID (typedEntryCallers -> callers) =
any (\(Some site) ->
callSiteIDCallerEq callerID $ typedCallSiteID site) callers
-- | Return the 'TypedCallSite' structure in an entrypoint for a particular call
-- site id, if it exists. Unlike 'typedEntryHasCaller', this requires the site
-- id to have the same variables.
typedEntryCallerSite ::
TypedCallSiteID blocks args vars ->
TypedEntry phase ext blocks tops rets args ghosts ->
Maybe (TypedCallSite phase blocks tops args ghosts vars)
typedEntryCallerSite siteID (typedEntryCallers -> callers) =
listToMaybe $ flip mapMaybe callers $ \(Some site) ->
case testEquality (typedCallSiteID site) siteID of
Just Refl -> Just site
Nothing -> Nothing
-- | A typed Crucible block is either a join block, meaning that all jumps to it
-- get joined into the same entrypoint, or is a multi-entry block, meaning that
-- each jump to it gets type-checked separately with a different entrypoint
data TypedBlockSort = JoinSort | MultiEntrySort
-- | A typed Crucible block is a list of typed entrypoints to that block
data TypedBlock phase ext (blocks :: RList (RList CrucibleType)) tops rets args =
forall gouts ret cargs. (CtxToRList cargs ~ args, rets ~ (gouts :> ret)) =>
TypedBlock
{
-- | An identifier for this block
typedBlockID :: TypedBlockID blocks args,
-- | The original Crucible block
typedBlockBlock :: Block ext (RListToCtxCtx blocks) ret cargs,
-- | What sort of block is this
typedBlockSort :: TypedBlockSort,
-- | Whether widening is allowed for entrypoints in this block; widening
-- disallowed for user-supplied permissions
typedBlockCanWiden :: Bool,
-- | The entrypoints into this block
_typedBlockEntries :: [Some (TypedEntry phase ext blocks tops rets args)],
-- | Debug name information for the current block
_typedBlockNames :: [Maybe String]
}
-- NOTE: this doesn't work because of the rets ~ (gouts :> ret) constraint
-- makeLenses ''TypedBlock
-- | The lens for '_typedBlockEntries'
typedBlockEntries :: Lens' (TypedBlock phase ext blocks tops rets args)
[Some (TypedEntry phase ext blocks tops rets args)]
typedBlockEntries =
lens _typedBlockEntries (\tblk entries ->
tblk { _typedBlockEntries = entries })
-- | The lens for '_typedBlockNames'
typedBlockNames :: Lens' (TypedBlock phase ext blocks tops rets args)
[Maybe String]
typedBlockNames =
lens _typedBlockNames (\tblk ns -> tblk { _typedBlockNames = ns })
-- | The input argument types of a block
blockArgs :: TypedBlock phase ext blocks tops rets args -> CruCtx args
blockArgs (TypedBlock {..}) = mkCruCtx $ blockInputs typedBlockBlock
-- | Get the 'Int' index of the location of entrypoint in the
-- 'typedBlockEntries' of a block, if it exists
blockEntryMaybeIx :: TypedEntryID blocks args ->
TypedBlock phase ext blocks tops rets args ->
Maybe Int
blockEntryMaybeIx entryID blk =
findIndex (\(Some entry) -> entryID == typedEntryID entry)
(blk ^. typedBlockEntries)
-- | Get the 'Int' index of the location of entrypoint in the
-- 'typedBlockEntries' of a block, or raise an error if it does not exist
blockEntryIx :: TypedEntryID blocks args ->
TypedBlock phase ext blocks tops rets args ->
Int
blockEntryIx entryID blk =
maybe (error "blockEntryIx: no such entrypoint!") id $
blockEntryMaybeIx entryID blk
-- | Test if an entrypoint ID has a corresponding entrypoint in a block
entryIDInBlock :: TypedEntryID blocks args ->
TypedBlock phase ext blocks tops rets args -> Bool
entryIDInBlock entryID blk = isJust $ blockEntryMaybeIx entryID blk
-- | The 'Lens' for finding a 'TypedEntry' by id in a 'TypedBlock'
entryByID :: TypedEntryID blocks args ->
Lens' (TypedBlock phase ext blocks tops ret args)
(Some (TypedEntry phase ext blocks tops ret args))
entryByID entryID =
lens
(\blk -> view typedBlockEntries blk !! blockEntryIx entryID blk)
(\blk e ->
over typedBlockEntries (replaceNth (blockEntryIx entryID blk) e) blk)
-- | Build an empty 'TypedBlock'
emptyBlockOfSort ::
[Maybe String] ->
Assignment CtxRepr cblocks ->
TypedBlockSort ->
Block ext cblocks ret cargs ->
TypedBlock TCPhase ext (CtxCtxToRList cblocks) tops (gouts :> ret) (CtxToRList
cargs)
emptyBlockOfSort names cblocks sort blk
| Refl <- reprReprToCruCtxCtxEq cblocks
= TypedBlock (indexToTypedBlockID (size cblocks) $
blockIDIndex $ blockID blk) blk sort True [] names
-- | Build a block with a user-supplied input permission
emptyBlockForPerms ::
[Maybe String] ->
Assignment CtxRepr cblocks ->
Block ext cblocks ret cargs -> CruCtx tops ->
TypeRepr ret -> CruCtx ghosts -> CruCtx gouts ->
MbValuePerms ((tops :++: CtxToRList cargs) :++: ghosts) ->
MbValuePerms (tops :++: gouts :> ret) ->
TypedBlock TCPhase ext (CtxCtxToRList
cblocks) tops (gouts :> ret) (CtxToRList cargs)
emptyBlockForPerms names cblocks blk tops ret ghosts gouts perms_in perms_out
| Refl <- reprReprToCruCtxCtxEq cblocks
, blockID <- indexToTypedBlockID (size cblocks) $ blockIDIndex $ blockID blk
, args <- mkCruCtx (blockInputs blk) =
TypedBlock blockID blk JoinSort False
[Some TypedEntry {
typedEntryID = TypedEntryID blockID 0, typedEntryTops = tops,
typedEntryArgs = args, typedEntryRets = CruCtxCons gouts ret,
typedEntryCallers = [], typedEntryGhosts = ghosts,
typedEntryPermsIn = perms_in, typedEntryPermsOut = perms_out,
typedEntryBody = Nothing }]
names
-- | Transition a 'TypedBlock' from type-checking to translation phase, by
-- making sure that all of data needed for the translation phase is present
completeTypedBlock :: TypedBlock TCPhase ext blocks tops rets args ->
Maybe (TypedBlock TransPhase ext blocks tops rets args)
completeTypedBlock (TypedBlock { .. })
| Just entries <- mapM (traverseF completeTypedEntry) _typedBlockEntries
= Just $ TypedBlock { _typedBlockEntries = entries, .. }
completeTypedBlock _ = Nothing
-- | Add a new entrypoint to a block, making sure that its entry ID does not
-- already exist in the block
addEntryToBlock :: TypedEntry phase ext blocks tops rets args ghosts ->
TypedBlock phase ext blocks tops rets args ->
TypedBlock phase ext blocks tops rets args
addEntryToBlock entry blk
| entryIDInBlock (typedEntryID entry) blk =
error "addEntryToBlock: entry with the same ID already in block!"
addEntryToBlock entry blk = over typedBlockEntries (++ [Some entry]) blk
-- | Return a 'Int' not in a list
freshInt :: [Int] -> Int
freshInt [] = 0
freshInt xs = 1 + maximum xs
-- | Build a new 'TypedCallSiteID' for a new call to a block from a given
-- entrypoint. If the block has 'JoinSort', this will call the one and only
-- entrypoint for that block, and otherwise, for a 'MultiEntrySort' block, it
-- will create a new entrypoint id.
newCallSiteID :: TypedEntryID blocks args_src -> CruCtx vars ->
TypedBlock phase ext blocks tops rets args ->
TypedCallSiteID blocks args vars
-- If blk has JoinSort but has no entrypoints yet, we will create one. It cannot
-- have any other callers, either, so we use caller index 0.
newCallSiteID callerID vars blk@(typedBlockSort -> JoinSort)
| [] <- blk ^. typedBlockEntries =
let entryID = TypedEntryID (typedBlockID blk) 0
call_ix = 0 in
TypedCallSiteID callerID call_ix entryID vars
-- If blk has JoinSort and does have an entrypoint already, choose a caller
-- index that is greater than any already being used
newCallSiteID callerID vars blk@(typedBlockSort -> JoinSort)
| Some entry:_ <- blk ^. typedBlockEntries =
let entryID = TypedEntryID (typedBlockID blk) 0
call_ix = freshInt (map
(\(Some site) -> callSiteIx (typedCallSiteID site))
(typedEntryCallers entry)) in
TypedCallSiteID callerID call_ix entryID vars
-- If blk has MultiEntrySort, make a new entrypoint
newCallSiteID callerID vars blk@(typedBlockSort -> MultiEntrySort) =
let entry_ix = freshInt (map
(\(Some entry) -> entryIndex (typedEntryID entry))
(blk ^. typedBlockEntries))
entryID = TypedEntryID (typedBlockID blk) entry_ix
call_ix = 0 in
TypedCallSiteID callerID call_ix entryID vars
-- Should never happen...
newCallSiteID _ _ _ = error "newCallSiteID: impossible case!"
-- | Add a call site to an entrypoint. It is an error if the entrypoint already
-- has a call site with the given call site id.
entryAddCallSite :: TypedCallSiteID blocks args vars ->
MbValuePerms ((tops :++: args) :++: vars) ->
TypedEntry TCPhase ext blocks tops rets args ghosts ->
TypedEntry TCPhase ext blocks tops rets args ghosts
entryAddCallSite siteID _ entry
| any (\(Some site) ->
isJust $ testEquality (typedCallSiteID site) siteID)
(typedEntryCallers entry)
= error "entryAddCallSite: call site already exists!"
entryAddCallSite siteID perms_in entry =
entry { typedEntryCallers =
typedEntryCallers entry ++ [Some $
emptyTypedCallSite siteID perms_in] }
-- | Add a call site to a block for a particular caller to have the supplied
-- permissions over the supplied variables, adding a new entrypoint if that of
-- the given call site ID does not yet exist. It is an error if the block
-- already has a call site with the given call site id.
blockAddCallSite :: TypedCallSiteID blocks args vars ->
CruCtx tops -> CruCtx rets ->
MbValuePerms ((tops :++: args) :++: vars) ->
MbValuePerms (tops :++: rets) ->
TypedBlock TCPhase ext blocks tops rets args ->
TypedBlock TCPhase ext blocks tops rets args
-- If the entrypoint for the site ID exists, update it with entrySetCallSite
blockAddCallSite siteID _ _ perms_in _ blk
| Just _ <- blockEntryMaybeIx (callSiteDest siteID) blk =
over
(entryByID $ callSiteDest siteID)
(\(Some entry) -> Some $ entryAddCallSite siteID perms_in entry)
blk
-- Otherwise, make a new entrypoint
blockAddCallSite siteID tops rets perms_in perms_out blk =
addEntryToBlock (singleCallSiteEntry
siteID tops (blockArgs blk) rets perms_in perms_out) blk
-- | A map assigning a 'TypedBlock' to each 'BlockID'
type TypedBlockMap phase ext blocks tops rets =
RAssign (TypedBlock phase ext blocks tops rets) blocks
instance Show (TypedEntry phase ext blocks tops rets args ghosts) where
show (TypedEntry { .. }) =
"<entry " ++ show typedEntryID ++ ">"
instance Show (TypedBlock phase ext blocks tops rets args) where
show = concatMap (\(Some entry) -> show entry) . (^. typedBlockEntries)
instance Show (TypedBlockMap phase ext blocks tops rets) where
show blkMap = show $ RL.mapToList show blkMap
-- | Transition a 'TypedBlockMap' from type-checking to translation phase, by
-- making sure that all of data needed for the translation phase is present
completeTypedBlockMap :: TypedBlockMap TCPhase ext blocks tops rets ->
Maybe (TypedBlockMap TransPhase ext blocks tops rets)
completeTypedBlockMap = traverseRAssign completeTypedBlock
-- | The 'Lens' for finding a 'TypedBlock' by id in a 'TypedBlockMap'
blockByID :: TypedBlockID blocks args ->
Lens'
(TypedBlockMap phase ext blocks tops rets)
(TypedBlock phase ext blocks tops rets args)
blockByID blkID =
let memb = typedBlockIDMember blkID in
lens (RL.get memb) (flip $ RL.set memb)
-- | Look up a 'TypedEntry' by its 'TypedEntryID'
lookupEntry :: TypedEntryID blocks args ->
TypedBlockMap phase ext blocks tops rets ->
Some (TypedEntry phase ext blocks tops rets args)
lookupEntry entryID =
view (blockByID (entryBlockID entryID) . entryByID entryID)
-- | Find all call sites called by an entrypoint
entryCallees :: TypedEntryID blocks args ->
TypedBlockMap phase ext blocks tops rets ->
[Some (TypedEntryID blocks)]
entryCallees entryID =
concat . RL.mapToList
(\blk ->
flip mapMaybe (blk ^. typedBlockEntries) $ \(Some entry) ->
if typedEntryHasCaller entryID entry
then Just (Some $ typedEntryID entry)
else Nothing)
-- | Delete any call sites whose source is a given entrypoint. For any call
-- sites to entrypoints in multi-entry blocks, delete those entrypoints as well,
-- etc.
deleteEntryCallees :: TypedEntryID blocks args ->
TypedBlockMap phase ext blocks tops rets ->
TypedBlockMap phase ext blocks tops rets
deleteEntryCallees topEntryID = execState (deleteCallees topEntryID) where
-- Delete call sites of a caller from all of its callees
deleteCallees :: TypedEntryID blocks args' ->
State (TypedBlockMap phase ext blocks tops rets) ()
deleteCallees callerID =
get >>= \blkMap ->
mapM_ (\(Some calleeID) ->
deleteCall callerID calleeID) (entryCallees callerID blkMap)
-- Delete call sites of a caller to a particular callee
deleteCall :: TypedEntryID blocks args1 -> TypedEntryID blocks args2 ->
State (TypedBlockMap phase ext blocks tops rets) ()
deleteCall callerID calleeID =
(typedBlockSort <$> use (blockByID $ entryBlockID calleeID)) >>= \case
JoinSort ->
-- The target has JoinSort, so we want to keep the callee entrypoint. Thus
-- we just delete all call sites whose caller equals callerID.
modifying (blockByID (entryBlockID calleeID)
. entryByID calleeID) $ \(Some callee) ->
let callers' =
flip filter (typedEntryCallers callee) $ \(Some site) ->
not $ callSiteIDCallerEq callerID $ typedCallSiteID site in
Some $ callee { typedEntryCallers = callers' }
MultiEntrySort ->
-- The target has MultiEntrySort, so callerID is the only caller to this
-- entrypoint, and thus we recursively delete the entrypoint
modifying (blockByID (entryBlockID calleeID) . typedBlockEntries)
(filter (\(Some entry) -> typedEntryID entry /= calleeID))
>>
deleteCallees calleeID
-- | Build the input permissions for the initial block of a CFG, where the
-- top-level variables (which in this case are the ghosts plus the normal
-- arguments of the function permission) get the function input permissions and
-- the normal arguments get equality permissions to their respective top-level
-- variables.
funPermToBlockInputs :: FunPerm ghosts args gouts ret ->
MbValuePerms ((ghosts :++: args) :++: args)
funPermToBlockInputs fun_perm =
let args_prxs = cruCtxProxies $ funPermArgs fun_perm in
extMbMulti args_prxs $
flip nuMultiWithElim1 (funPermIns fun_perm) $ \ghosts_args_ns perms_in ->
let (_, args_ns) =
RL.split (funPermGhosts fun_perm) args_prxs ghosts_args_ns in
appendValuePerms perms_in (eqValuePerms args_ns)
-- | Build an initial 'TypedBlockMap' from a 'BlockMap'. Determine the sort, and
-- possibly entrypoint permissions, for each block by using hints in the
-- supplied 'PermEnv' along with a list of 'Bool' flags indicating which blocks
-- are at the head of a loop (or other strongly-connected component)
initTypedBlockMap ::
KnownRepr ExtRepr ext =>
PermEnv ->
FunPerm ghosts (CtxToRList init) gouts ret ->
CFG ext cblocks init ret ->
Assignment (Constant Bool) cblocks ->
TypedBlockMap TCPhase ext (CtxCtxToRList cblocks)
(ghosts :++: CtxToRList init) (gouts :> ret)
initTypedBlockMap env fun_perm cfg sccs =
let block_map = cfgBlockMap cfg
cblocks = fmapFC blockInputs block_map
namess = computeCfgNames knownRepr (size sccs) cfg
gouts = funPermGouts fun_perm
ret = funPermRet fun_perm
tops = funPermTops fun_perm
top_perms_in = funPermToBlockInputs fun_perm
perms_out = funPermOuts fun_perm in
assignToRListRList
(\(Pair blk (Pair (Constant is_scc) (Constant names))) ->
let blkID = blockID blk
hints = lookupBlockHints env (cfgHandle cfg) cblocks blkID in
case hints of
_ | Just Refl <- testEquality (cfgEntryBlockID cfg) blkID ->
emptyBlockForPerms names cblocks blk tops ret
CruCtxNil gouts top_perms_in perms_out
(find isBlockEntryHint ->
Just (BlockEntryHintSort tops' ghosts perms_in))
| Just Refl <- testEquality tops tops' ->
emptyBlockForPerms names cblocks blk tops ret
ghosts gouts perms_in perms_out
_ | is_scc || any isJoinPointHint hints ->
emptyBlockOfSort names cblocks JoinSort blk
_ -> emptyBlockOfSort names cblocks MultiEntrySort blk) $
Ctx.zipWith Pair block_map (Ctx.zipWith Pair sccs namess)
computeCfgNames ::
ExtRepr ext ->
Size cblocks ->
CFG ext cblocks init ret ->
Ctx.Assignment (Constant [Maybe String]) cblocks
computeCfgNames ExtRepr_LLVM _ cfg = computeNames cfg
computeCfgNames ExtRepr_Unit s _ = Ctx.replicate s (Constant [])
-- | A typed Crucible CFG
data TypedCFG
(ext :: Type)
(blocks :: RList (RList CrucibleType))
(ghosts :: RList CrucibleType)
(inits :: RList CrucibleType)
(gouts :: RList CrucibleType)
(ret :: CrucibleType)
= TypedCFG { tpcfgHandle :: !(TypedFnHandle ghosts inits gouts ret)
, tpcfgFunPerm :: !(FunPerm ghosts inits gouts ret)
, tpcfgBlockMap :: !(TypedBlockMap TransPhase ext blocks
(ghosts :++: inits) (gouts :> ret))
, tpcfgEntryID :: !(TypedEntryID blocks inits)
}
-- | Get the input permissions for a 'CFG'
tpcfgInputPerms :: TypedCFG ext blocks ghosts inits gouts ret ->
MbValuePerms (ghosts :++: inits)
tpcfgInputPerms = funPermIns . tpcfgFunPerm
-- | Get the output permissions for a 'CFG'
tpcfgOutputPerms :: TypedCFG ext blocks ghosts inits gouts ret ->
MbValuePerms ((ghosts :++: inits) :++: gouts :> ret)
tpcfgOutputPerms = funPermOuts . tpcfgFunPerm
----------------------------------------------------------------------
-- * Monad(s) for Permission Checking
----------------------------------------------------------------------
-- | A translation of a Crucible context to 'TypedReg's that exist in the local
-- Hobbits context
type CtxTrans ctx = Assignment TypedReg ctx
-- | Build a Crucible context translation from a set of variables
mkCtxTrans :: Assignment f ctx -> RAssign Name (CtxToRList ctx) -> CtxTrans ctx
mkCtxTrans (viewAssign -> AssignEmpty) _ = Ctx.empty
mkCtxTrans (viewAssign -> AssignExtend ctx' _) (ns :>: n) =
extend (mkCtxTrans ctx' ns) (TypedReg n)
-- | Add a variable to the current Crucible context translation
addCtxName :: CtxTrans ctx -> ExprVar tp -> CtxTrans (ctx ::> tp)
addCtxName ctx x = extend ctx (TypedReg x)
-- | The translation of a Crucible block id
newtype BlockIDTrans blocks args =
BlockIDTrans { unBlockIDTrans :: TypedBlockID blocks (CtxToRList args) }
-- | Build a map from Crucible block IDs to 'Member' proofs
buildBlockIDMap :: Size cblocks ->
Assignment (BlockIDTrans (CtxCtxToRList cblocks)) cblocks
buildBlockIDMap sz =
Ctx.generate sz $ \ix -> BlockIDTrans (indexToTypedBlockID sz ix)
data SomePtrWidth where SomePtrWidth :: HasPtrWidth w => SomePtrWidth
-- | Top-level state, maintained outside of permission-checking single blocks
data TopPermCheckState ext cblocks blocks tops rets =
TopPermCheckState
{
-- | The top-level inputs of the function being type-checked
stTopCtx :: !(CruCtx tops),
-- | The return types including ghosts of the function being type-checked
stRetTypes :: !(CruCtx rets),
-- | The return permission of the function being type-checked
stRetPerms :: !(MbValuePerms (tops :++: rets)),
-- | A mapping from 'BlockID's to 'TypedBlockID's
stBlockTrans :: !(Assignment (BlockIDTrans blocks) cblocks),
-- | The current set of type-checked blocks
_stBlockMap :: !(TypedBlockMap TCPhase ext blocks tops rets),
-- | The permissions environment
stPermEnv :: !PermEnv,
-- | The un-translated input types of all of the Crucible blocks
--
-- FIXME: this is only needed to look up hints, to prove that the @blocks@
-- type argument of the hints are equal to that of the function being
-- type-checked; if we translated @blocks@ to @'CtxCtxToRList' blocks@ when
-- creating the hints, this field would go away
stBlockTypes :: !(Assignment CtxRepr cblocks),
-- | Equality constraint between @cblocks@ and @blocks@
stCBlocksEq :: RListToCtxCtx blocks :~: cblocks,
-- | The endianness of the current architecture
stEndianness :: !EndianForm,
stArchWidth :: SomePtrWidth,
-- | The debugging level
stDebugLevel :: DebugLevel
}
makeLenses ''TopPermCheckState
-- | Build an empty 'TopPermCheckState' from a Crucible 'BlockMap'
emptyTopPermCheckState ::
HasPtrWidth w =>
KnownRepr ExtRepr ext =>
PermEnv ->
FunPerm ghosts (CtxToRList init) gouts ret ->
EndianForm ->
DebugLevel ->
CFG ext cblocks init ret ->
Assignment (Constant Bool) cblocks ->
TopPermCheckState ext cblocks
(CtxCtxToRList cblocks)
(ghosts :++: CtxToRList init) (gouts :> ret)
emptyTopPermCheckState env fun_perm endianness dlevel cfg sccs =
let blkMap = cfgBlockMap cfg in
TopPermCheckState
{ stTopCtx = funPermTops fun_perm
, stRetTypes = funPermRets fun_perm
, stRetPerms = funPermOuts fun_perm
, stBlockTrans = buildBlockIDMap (Ctx.size blkMap)
, _stBlockMap = initTypedBlockMap env fun_perm cfg sccs
, stPermEnv = env
, stBlockTypes = fmapFC blockInputs blkMap
, stCBlocksEq = reprReprToCruCtxCtxEq (fmapFC blockInputs blkMap)
, stEndianness = endianness
, stArchWidth = SomePtrWidth
, stDebugLevel = dlevel
}
-- | Look up a Crucible block id in a top-level perm-checking state
stLookupBlockID :: BlockID cblocks args ->
TopPermCheckState ext cblocks blocks tops rets ->
TypedBlockID blocks (CtxToRList args)
stLookupBlockID (BlockID ix) st =
unBlockIDTrans $ stBlockTrans st Ctx.! ix
-- | The top-level monad for permission-checking CFGs
type TopPermCheckM ext cblocks blocks tops rets =
State (TopPermCheckState ext cblocks blocks tops rets)
{-
-- | A datakind for the type-level parameters needed to define blocks, including
-- the @ext@, @blocks@, @ret@ and @args@ arguments
data BlkParams =
BlkParams Type (RList (RList CrucibleType)) CrucibleType (RList CrucibleType)
type family BlkExt (args :: BlkParams) :: Type where
BlkExt ('BlkParams ext _ _ _) = ext
type family BlkBlocks (args :: BlkParams) :: (RList (RList CrucibleType)) where
BlkBlocks ('BlkParams _ blocks _ _) = blocks
type family BlkRet (args :: BlkParams) :: CrucibleType where
BlkRet ('BlkParams _ _ ret _) = ret
type family BlkArgs (args :: BlkParams) :: RList CrucibleType where
BlkArgs ('BlkParams _ _ _ args) = args
-}
-- | A change to a 'TypedBlockMap'
data TypedBlockMapDelta blocks tops rets where
-- | Add a call site to a block for a particular caller to have the supplied
-- permissions over the supplied variables
TypedBlockMapAddCallSite :: TypedCallSiteID blocks args vars ->
MbValuePerms ((tops :++: args) :++: vars) ->
TypedBlockMapDelta blocks tops rets
-- | Apply a 'TypedBlockMapDelta' to a 'TypedBlockMap'
applyTypedBlockMapDelta :: TypedBlockMapDelta blocks tops rets ->
TopPermCheckState ext cblocks blocks tops rets ->
TopPermCheckState ext cblocks blocks tops rets
applyTypedBlockMapDelta (TypedBlockMapAddCallSite siteID perms_in) top_st =
over (stBlockMap . member (entryBlockMember $ callSiteDest siteID))
(blockAddCallSite siteID (stTopCtx top_st) (stRetTypes top_st)
perms_in (stRetPerms top_st))
top_st
-- | Apply a list of 'TypedBlockMapDelta's to a 'TopPermCheckState'
applyDeltasToTopState :: [TypedBlockMapDelta blocks tops rets] ->
TopPermCheckState ext cblocks blocks tops rets ->
TopPermCheckState ext cblocks blocks tops rets
applyDeltasToTopState deltas top_st =
foldl (flip applyTypedBlockMapDelta) top_st deltas
-- | The state that can be modified by "inner" computations = a list of changes
-- / "deltas" to the current 'TypedBlockMap'
data InnerPermCheckState blocks tops rets =
InnerPermCheckState
{
innerStateDeltas :: [TypedBlockMapDelta blocks tops rets]
}
-- | Build an empty, closed 'InnerPermCheckState'
clEmptyInnerPermCheckState :: Closed (InnerPermCheckState blocks tops rets)
clEmptyInnerPermCheckState = $(mkClosed [| InnerPermCheckState [] |])
-- | The "inner" monad that runs inside 'PermCheckM' continuations. It can see
-- but not modify the top-level state, but it can add 'TypedBlockMapDelta's to
-- be applied later to the top-level state.
type InnerPermCheckM ext cblocks blocks tops rets =
ReaderT (TopPermCheckState ext cblocks blocks tops rets)
(State (Closed (InnerPermCheckState blocks tops rets)))
-- | The local state maintained while type-checking is the current permission
-- set and the permissions required on return from the entire function.
data PermCheckState ext blocks tops rets ps =
PermCheckState
{
stCurPerms :: !(PermSet ps),
stExtState :: !(PermCheckExtState ext),
stTopVars :: !(RAssign Name tops),
stCurEntry :: !(Some (TypedEntryID blocks)),
stVarTypes :: !(NameMap TypeRepr),
stUnitVar :: !(Maybe (ExprVar UnitType)),
-- ^ An optional global unit variable that all other unit variables will be
-- equal to
stPPInfo :: !PPInfo,
stErrPrefix :: !(Maybe (Doc ())),
stDebug :: ![Maybe String]
}
-- | Build a default, empty 'PermCheckState'
emptyPermCheckState ::
KnownRepr ExtRepr ext =>
PermSet ps ->
RAssign ExprVar tops ->
TypedEntryID blocks args ->
[Maybe String] ->
PermCheckState ext blocks tops rets ps
emptyPermCheckState perms tops entryID names =
PermCheckState { stCurPerms = perms,
stExtState = emptyPermCheckExtState knownRepr,
stTopVars = tops,
stCurEntry = Some entryID,
stVarTypes = NameMap.empty,
stUnitVar = Nothing,
stPPInfo = emptyPPInfo,
stErrPrefix = Nothing,
stDebug = names }
-- | Like the 'set' method of a lens, but allows the @ps@ argument to change
setSTCurPerms :: PermSet ps2 -> PermCheckState ext blocks tops rets ps1 ->
PermCheckState ext blocks tops rets ps2
setSTCurPerms perms (PermCheckState {..}) =
PermCheckState { stCurPerms = perms, .. }
modifySTCurPerms :: (PermSet ps1 -> PermSet ps2) ->
PermCheckState ext blocks tops rets ps1 ->
PermCheckState ext blocks tops rets ps2
modifySTCurPerms f_perms st = setSTCurPerms (f_perms $ stCurPerms st) st
nextDebugName :: PermCheckM ext cblocks blocks tops rets a ps a ps (Maybe String)
nextDebugName =
do st <- get
put st { stDebug = drop 1 (stDebug st)}
pure (foldr (\x _ -> x) Nothing (stDebug st))
-- | The generalized monad for permission-checking
type PermCheckM ext cblocks blocks tops rets r1 ps1 r2 ps2 =
GenStateContT
(PermCheckState ext blocks tops rets ps1) r1
(PermCheckState ext blocks tops rets ps2) r2
(InnerPermCheckM ext cblocks blocks tops rets)
-- | The generalized monad for permission-checking statements
type StmtPermCheckM ext cblocks blocks tops rets ps1 ps2 =
PermCheckM ext cblocks blocks tops rets
(TypedStmtSeq ext blocks tops rets ps1) ps1
(TypedStmtSeq ext blocks tops rets ps2) ps2
-- | Lift an 'InnerPermCheckM' computation to a 'PermCheckM' computation
liftPermCheckM :: InnerPermCheckM ext cblocks blocks tops rets a ->
PermCheckM ext cblocks blocks tops rets r ps r ps a
liftPermCheckM = lift
-- | Lift an 'InnerPermCheckM' to a 'TopPermCheckM'
liftInnerToTopM :: InnerPermCheckM ext cblocks blocks tops rets a ->
TopPermCheckM ext cblocks blocks tops rets a
liftInnerToTopM m =
do st <- get
let (a, cl_inner_st) =
runState (runReaderT m st) clEmptyInnerPermCheckState
let deltas = innerStateDeltas $ unClosed cl_inner_st
modify (applyDeltasToTopState deltas)
return a
-- | Get the current top-level state modulo the modifications to the current
-- block info map
top_get :: PermCheckM ext cblocks blocks tops rets r ps r ps
(TopPermCheckState ext cblocks blocks tops rets)
top_get = gcaptureCC $ \k ->
do top_st <- ask
deltas <- innerStateDeltas <$> unClosed <$> get
k $ applyDeltasToTopState deltas top_st
-- | Set the extension-specific state
setInputExtState :: ExtRepr ext -> CruCtx as -> RAssign Name as ->
PermCheckM ext cblocks blocks tops rets r ps r ps ()
setInputExtState ExtRepr_Unit _ _ = pure ()
setInputExtState ExtRepr_LLVM tps ns
| [SomeExprVarFrame rep n] <- findLLVMFrameVars tps ns
= setFramePtr rep (TypedReg n)
setInputExtState ExtRepr_LLVM _ _ =
-- FIXME: make sure there are not more than one frame var and/or a frame var
-- of the wrong type
pure ()
-- | Run a 'PermCheckM' computation for a particular entrypoint with a given set
-- of top-level arguments, local arguments, ghost variables, and permissions on
-- all three, and return a result inside a binding for these variables
--
-- Note that calls to @runPermCheckM@ should be accompanied by calls to
-- @handleUnitVars@ or @stmtHandleUnitVars@ to ensure that all unit-typed
-- variables are unified during type-checking. These functions are not currently
-- combined because @handleUnitVars@ embeds an @ImplM@ computation and someties
-- it is more convenient to combine multiple @ImplM@ computations into one.
runPermCheckM ::
KnownRepr ExtRepr ext =>
[Maybe String] ->
TypedEntryID blocks some_args ->
CruCtx args -> CruCtx ghosts -> MbValuePerms ((tops :++: args) :++: ghosts) ->
(RAssign ExprVar tops -> RAssign ExprVar args -> RAssign ExprVar ghosts ->
DistPerms ((tops :++: args) :++: ghosts) ->
PermCheckM ext cblocks blocks tops rets
() ps_out
r ((tops :++: args) :++: ghosts)
()) ->
TopPermCheckM ext cblocks blocks tops rets (Mb ((tops :++: args) :++: ghosts) r)
runPermCheckM names entryID args ghosts mb_perms_in m =
get >>= \(TopPermCheckState {..}) ->
let args_prxs = cruCtxProxies args
ghosts_prxs = cruCtxProxies ghosts in
liftInnerToTopM $ strongMbM $
flip nuMultiWithElim1 (mbValuePermsToDistPerms mb_perms_in) $ \ns perms_in ->
let (tops_args, ghosts_ns) = RL.split Proxy ghosts_prxs ns
(tops_ns, args_ns) = RL.split Proxy args_prxs tops_args
(arg_names, local_names) = initialNames args names
st = emptyPermCheckState (distPermSet perms_in) tops_ns entryID local_names in
let go x = runGenStateContT x st (\_ () -> pure ()) in
go $
setVarTypes (Just "top") (noNames' stTopCtx) tops_ns stTopCtx >>>
setVarTypes (Just "local") arg_names args_ns args >>>
setVarTypes (Just "ghost") (noNames' ghosts) ghosts_ns ghosts >>>
setInputExtState knownRepr ghosts ghosts_ns >>>
m tops_ns args_ns ghosts_ns perms_in
rassignLen :: RAssign f x -> Int
rassignLen = go 0
where
go :: Int -> RAssign f x -> Int
go acc MNil = acc
go acc (xs :>: _) = (go $! (acc+1)) xs
initialNames ::
CruCtx tps ->
[Maybe String] ->
(RAssign (Constant (Maybe String)) tps, [Maybe String])
initialNames CruCtxNil xs = (MNil, xs)
initialNames (CruCtxCons ts _) xs =
case initialNames ts xs of
(ys, z:zs) -> (ys :>: Constant z, zs)
(ys, [] ) -> (ys :>: Constant Nothing, [])
-- | Compute an empty debug name assignment from a known context
noNames ::
KnownRepr CruCtx tps =>
RAssign (Constant (Maybe String)) tps
noNames = noNames' knownRepr
-- | Compute an empty debug name assignment from a given context
noNames' ::
CruCtx tps ->
RAssign (Constant (Maybe String)) tps
noNames' CruCtxNil = MNil
noNames' (CruCtxCons xs _) = noNames' xs :>: Constant Nothing
-- | Call 'debugNames'' with a known type list.
dbgNames ::
KnownRepr CruCtx tps =>
PermCheckM ext cblocks blocks tops rets a ps a ps
(RAssign (Constant (Maybe String)) tps)
dbgNames = dbgNames' knownRepr
-- | Pop as many local variable names from the debug information
-- as needed to populate the given type list.
dbgNames' ::
CruCtx tps ->
PermCheckM ext cblocks blocks tops rets a ps a ps
(RAssign (Constant (Maybe String)) tps)
dbgNames' CruCtxNil = pure MNil
dbgNames' (CruCtxCons ts _) =
do ns <- dbgNames' ts
n <- nextDebugName
pure (ns :>: Constant n)
-- | Emit a 'TypedBlockMapDelta', which must be 'Closed', in an
-- 'InnerPermCheckM' computation
innerEmitDelta :: Closed (TypedBlockMapDelta blocks tops rets) ->
InnerPermCheckM ext cblocks blocks tops rets ()
innerEmitDelta cl_delta =
modify (clApply
($(mkClosed [| \delta st ->
st { innerStateDeltas =
innerStateDeltas st ++ [delta] } |])
`clApply` cl_delta))
-- | Create a call from the current entrypoint to the specified block, passing
-- the supplied permissions, which must be closed, on local variables
callBlockWithPerms :: TypedEntryID blocks args_src ->
TypedBlockID blocks args -> CruCtx vars ->
Closed (MbValuePerms ((tops :++: args) :++: vars)) ->
InnerPermCheckM ext cblocks blocks tops rets
(TypedCallSiteID blocks args vars)
callBlockWithPerms srcEntryID destID vars cl_perms_in =
do blk <- view (stBlockMap . member (typedBlockIDMember destID)) <$> ask
let siteID = newCallSiteID srcEntryID vars blk
innerEmitDelta ($(mkClosed [| TypedBlockMapAddCallSite |])
`clApply` toClosed siteID `clApply` cl_perms_in)
return siteID
-- | Look up the current primary permission associated with a variable
getVarPerm :: ExprVar a ->
PermCheckM ext cblocks blocks tops rets r ps r ps (ValuePerm a)
getVarPerm x = gets (view (varPerm x) . stCurPerms)
-- | Set the current primary permission associated with a variable
setVarPerm :: ExprVar a -> ValuePerm a ->
PermCheckM ext cblocks blocks tops rets r ps r ps ()
setVarPerm x p = modify (modifySTCurPerms (set (varPerm x) p))
-- | Look up the current primary permission associated with a register
getRegPerm :: TypedReg a ->
PermCheckM ext cblocks blocks tops rets r ps r ps (ValuePerm a)
getRegPerm (TypedReg x) = getVarPerm x
-- | Eliminate any disjunctions, existentials, or recursive permissions for a
-- register and then return the resulting "simple" permission, leaving it on the
-- top of the stack
getPushSimpleRegPerm :: PermCheckExtC ext => TypedReg a ->
StmtPermCheckM ext cblocks blocks tops rets
(ps :> a) ps (ValuePerm a)
getPushSimpleRegPerm r =
getRegPerm r >>>= \p_init ->
pcmEmbedImplM TypedImplStmt emptyCruCtx
(implPushM (typedRegVar r) p_init >>>
elimOrsExistsNamesM (typedRegVar r)) >>>= \(_, p_ret) ->
pure p_ret
-- | Eliminate any disjunctions, existentials, or recursive permissions for a
-- register and then return the resulting "simple" permission
getSimpleRegPerm :: PermCheckExtC ext => TypedReg a ->
StmtPermCheckM ext cblocks blocks tops rets ps ps
(ValuePerm a)
getSimpleRegPerm r =
snd <$> pcmEmbedImplM TypedImplStmt emptyCruCtx (getSimpleVarPerm $
typedRegVar r)
-- | A version of 'getEqualsExpr' for 'TypedReg's
getRegEqualsExpr ::
PermCheckExtC ext => TypedReg a ->
StmtPermCheckM ext cblocks blocks tops rets ps ps (PermExpr a)
getRegEqualsExpr r =
snd <$> pcmEmbedImplM TypedImplStmt emptyCruCtx (getEqualsExpr $
PExpr_Var $ typedRegVar r)
-- | Eliminate any disjunctions, existentials, recursive permissions, or
-- equality permissions for an LLVM register until we either get a conjunctive
-- permission for it or we get that it is equal to a bitvector word. In either
-- case, leave the resulting permission on the top of the stack and return its
-- contents as the return value.
getAtomicOrWordLLVMPerms ::
(1 <= w, KnownNat w, PermCheckExtC ext) => TypedReg (LLVMPointerType w) ->
StmtPermCheckM ext cblocks blocks tops rets
(ps :> LLVMPointerType w)
ps
(Either (PermExpr (BVType w)) [AtomicPerm (LLVMPointerType w)])
getAtomicOrWordLLVMPerms r =
let x = typedRegVar r in
getPushSimpleRegPerm r >>>= \p ->
case p of
ValPerm_Conj ps ->
pure $ Right ps
ValPerm_Eq (PExpr_Var y) ->
pcmEmbedImplM TypedImplStmt emptyCruCtx
(introEqCopyM x (PExpr_Var y) >>> recombinePerm x p) >>>
getAtomicOrWordLLVMPerms (TypedReg y) >>>= \eith ->
case eith of
Left e ->
pcmEmbedImplM TypedImplStmt emptyCruCtx
(introCastM x y $ ValPerm_Eq $ PExpr_LLVMWord e) >>>
pure (Left e)
Right ps ->
pcmEmbedImplM TypedImplStmt emptyCruCtx (introCastM x y $
ValPerm_Conj ps) >>>
pure (Right ps)
ValPerm_Eq e@(PExpr_LLVMOffset y off) ->
pcmEmbedImplM TypedImplStmt emptyCruCtx
(introEqCopyM x e >>> recombinePerm x p) >>>
getAtomicOrWordLLVMPerms (TypedReg y) >>>= \eith ->
case eith of
Left e' ->
pcmEmbedImplM TypedImplStmt emptyCruCtx (offsetLLVMWordM
y e' off x) >>>
pure (Left $ bvAdd e' off)
Right ps ->
pcmEmbedImplM TypedImplStmt emptyCruCtx (castLLVMPtrM
y (ValPerm_Conj ps) off x) >>>
pure (Right $ mapMaybe (offsetLLVMAtomicPerm $ bvNegate off) ps)
ValPerm_Eq e@(PExpr_LLVMWord e_word) ->
pcmEmbedImplM TypedImplStmt emptyCruCtx (introEqCopyM x e >>>
recombinePerm x p) >>>
pure (Left e_word)
_ ->
stmtFailM (\i ->
sep [pretty "getAtomicOrWordLLVMPerms:",
pretty "Needed atomic permissions for" <+> permPretty i r,
pretty "but found" <+>
permPretty i p])
-- | Like 'getAtomicOrWordLLVMPerms', but fail if an equality permission to a
-- bitvector word is found
getAtomicLLVMPerms :: (1 <= w, KnownNat w, PermCheckExtC ext) =>
TypedReg (LLVMPointerType w) ->
StmtPermCheckM ext cblocks blocks tops rets
(ps :> LLVMPointerType w)
ps
[AtomicPerm (LLVMPointerType w)]
getAtomicLLVMPerms r =
getAtomicOrWordLLVMPerms r >>>= \eith ->
case eith of
Right ps -> pure ps
Left e ->
stmtFailM (\i ->
sep [pretty "getAtomicLLVMPerms:",
pretty "Needed atomic permissions for" <+> permPretty i r,
pretty "but found" <+>
permPretty i (ValPerm_Eq $ PExpr_LLVMWord e)])
data SomeExprVarFrame where
SomeExprVarFrame ::
NatRepr w ->
ExprVar (LLVMFrameType w) ->
SomeExprVarFrame
-- | Find all the variables of LLVM frame pointer type in a sequence
-- FIXME: move to Permissions.hs
findLLVMFrameVars ::
CruCtx as -> RAssign Name as ->
[SomeExprVarFrame]
findLLVMFrameVars CruCtxNil _ = []
findLLVMFrameVars (CruCtxCons tps (LLVMFrameRepr w')) (ns :>: n) =
SomeExprVarFrame w' n : findLLVMFrameVars tps ns
findLLVMFrameVars (CruCtxCons tps _) (ns :>: _) = findLLVMFrameVars tps ns
-- | Get the current frame pointer on LLVM architectures
getFramePtr ::
NatRepr w ->
PermCheckM LLVM cblocks blocks tops rets r ps r ps
(Maybe (TypedReg (LLVMFrameType w)))
getFramePtr w =
gets stExtState >>= \case
PermCheckExtState_LLVM (Just (SomeFrameReg rep fp))
| Just Refl <- testEquality rep w -> pure (Just fp)
_ -> pure Nothing
-- | Set the current frame pointer on LLVM architectures
setFramePtr ::
NatRepr w ->
TypedReg (LLVMFrameType w) ->
PermCheckM LLVM cblocks blocks tops rets r ps r ps ()
setFramePtr rep fp =
modify (\st -> st { stExtState = PermCheckExtState_LLVM (Just (SomeFrameReg rep fp)) })
-- | Look up the type of a free variable, or raise an error if it is unknown
getVarType :: ExprVar a ->
PermCheckM ext cblocks blocks tops rets r ps r ps (TypeRepr a)
getVarType x =
gets (NameMap.lookup x . stVarTypes) >>= \case
Just tp -> pure tp
Nothing ->
stmtTraceM (\i -> pretty "getVarType: could not find type for variable:"
<+> permPretty i x) >>>
error "getVarType"
-- | Look up the types of multiple free variables
getVarTypes :: RAssign Name tps ->
PermCheckM ext cblocks blocks tops rets r ps r ps (CruCtx tps)
getVarTypes MNil = pure CruCtxNil
getVarTypes (xs :>: x) = CruCtxCons <$> getVarTypes xs <*> getVarType x
-- | Output a string representing a variable given optional information such as
-- a base name and a C name
dbgStringPP ::
Maybe String -> -- ^ The base name of the variable (e.g., "top", "arg", etc.)
Maybe String -> -- ^ The C name of the variable, if applicable
TypeRepr a -> -- ^ The type of the variable
String
dbgStringPP _ (Just d) _ = "C[" ++ d ++ "]"
dbgStringPP (Just str) _ tp = str ++ "_" ++ typeBaseName tp
dbgStringPP Nothing Nothing tp = typeBaseName tp
-- | After all variables have been added to the context, unify all unit-typed
-- variables by lifting through the ImplM monad
stmtHandleUnitVars :: forall (tps :: RList CrucibleType)
ext cblocks blocks tops ret ps.
PermCheckExtC ext =>
RAssign Name tps ->
StmtPermCheckM ext cblocks blocks tops ret ps ps ()
stmtHandleUnitVars ns =
stmtEmbedImplM $ handleUnitVars ns
-- | Remember the type of a free variable, and ensure that it has a permission
setVarType ::
Maybe String -> -- ^ The base name of the variable (e.g., "top", "arg", etc.)
Maybe String -> -- ^ The C name of the variable, if applicable
ExprVar a -> -- ^ The Hobbits variable itself
TypeRepr a -> -- ^ The type of the variable
PermCheckM ext cblocks blocks tops rets r ps r ps ()
setVarType maybe_str dbg x tp =
(modify $ \st ->
st { stCurPerms = initVarPerm x (stCurPerms st),
stVarTypes = NameMap.insert x tp (stVarTypes st),
stPPInfo = ppInfoAddExprName (dbgStringPP maybe_str dbg tp)
x
(stPPInfo st)
})
-- | Remember the types of a sequence of free variables
setVarTypes ::
Maybe String -> -- ^ The bsae name of the variable (e.g., "top", "arg", etc.)
RAssign (Constant (Maybe String)) tps ->
RAssign Name tps ->
CruCtx tps ->
PermCheckM ext cblocks blocks tops rets r ps r ps ()
setVarTypes _ MNil MNil CruCtxNil = pure ()
setVarTypes str (ds :>: Constant d) (ns :>: n) (CruCtxCons ts t) =
do setVarTypes str ds ns ts
setVarType str d n t
-- | Get the current 'PPInfo'
permGetPPInfo :: PermCheckM ext cblocks blocks tops rets r ps r ps PPInfo
permGetPPInfo = gets stPPInfo
-- | Get the current prefix string to give context to error messages
getErrorPrefix :: PermCheckM ext cblocks blocks tops rets r ps r ps (Doc ())
getErrorPrefix = gets (fromMaybe emptyDoc . stErrPrefix)
-- | Emit debugging output at the given 'DebugLevel'
stmtDebugM :: DebugLevel -> (PPInfo -> Doc ()) ->
PermCheckM ext cblocks blocks tops ret r ps r ps String
stmtDebugM reqlvl f =
do dlevel <- stDebugLevel <$> top_get
doc <- f <$> permGetPPInfo
let str = renderDoc doc
debugTrace reqlvl dlevel str (return str)
-- | Emit debugging output at 'traceDebugLevel'
stmtTraceM :: (PPInfo -> Doc ()) ->
PermCheckM ext cblocks blocks tops ret r ps r ps String
stmtTraceM = stmtDebugM traceDebugLevel
-- | Emit debugging output at 'verboseDebugLevel'
stmtVerbTraceM :: (PPInfo -> Doc ()) ->
PermCheckM ext cblocks blocks tops ret r ps r ps String
stmtVerbTraceM = stmtDebugM verboseDebugLevel
-- | Failure in the statement permission-checking monad
stmtFailM :: (PPInfo -> Doc ()) -> PermCheckM ext cblocks blocks tops rets r1 ps1
(TypedStmtSeq ext blocks tops rets ps2) ps2 a
stmtFailM msg =
getErrorPrefix >>>= \err_prefix ->
stmtTraceM (\i -> err_prefix <> line <>
pretty "Type-checking failure:" <> softline <> msg i) >>>= \str ->
gabortM (return $ TypedImplStmt $ AnnotPermImpl str $
PermImpl_Step (Impl1_Fail "") MbPermImpls_Nil)
-- | FIXME HERE: Make 'ImplM' quantify over any underlying monad, so that we do
-- not have to use 'traversePermImpl' after we run an 'ImplM'
data WithImplState vars a ps ps' =
WithImplState a (ImplState vars ps) (ps' :~: ps)
-- | Run a 'PermCheckM' computation in a locally-scoped way, where all effects
-- are restricted to the local computation. This is essentially a form of the
-- @reset@ operation of delimited continuations.
--
-- FIXME: this is not used, but is still here in case we need it later...
localPermCheckM ::
PermCheckM ext cblocks blocks tops rets r_out ps_out r_in ps_in r_out ->
PermCheckM ext cblocks blocks tops rets r' ps_in r' ps_in r_in
localPermCheckM m =
get >>= \st ->
liftPermCheckM (runGenStateContT m st (\_ -> pure))
-- | Call 'runImplM' in the 'PermCheckM' monad
pcmRunImplM ::
HasCallStack =>
NuMatchingAny1 r =>
CruCtx vars -> Doc () -> (a -> r ps_out) ->
ImplM vars (InnerPermCheckState blocks tops rets) r ps_out ps_in a ->
PermCheckM ext cblocks blocks tops rets r' ps_in r' ps_in
(AnnotPermImpl r ps_in)
pcmRunImplM vars fail_doc retF impl_m =
getErrorPrefix >>>= \err_prefix ->
(stPermEnv <$> top_get) >>>= \env ->
gets stCurPerms >>>= \perms_in ->
gets stPPInfo >>>= \ppInfo ->
gets stVarTypes >>>= \varTypes ->
gets stUnitVar >>>= \unitVar ->
(stEndianness <$> top_get) >>>= \endianness ->
(stDebugLevel <$> top_get) >>>= \dlevel ->
liftPermCheckM $ lift $
fmap (AnnotPermImpl (renderDoc (err_prefix <> line <> fail_doc))) $
runImplM vars perms_in env ppInfo "" dlevel varTypes unitVar endianness impl_m
(return . retF . fst)
-- | Call 'runImplImplM' in the 'PermCheckM' monad
pcmRunImplImplM ::
HasCallStack =>
NuMatchingAny1 r =>
CruCtx vars -> Doc () ->
ImplM vars (InnerPermCheckState blocks tops rets) r ps_out ps_in (PermImpl
r ps_out) ->
PermCheckM ext cblocks blocks tops rets r' ps_in r' ps_in
(AnnotPermImpl r ps_in)
pcmRunImplImplM vars fail_doc impl_m =
getErrorPrefix >>>= \err_prefix ->
(stPermEnv <$> top_get) >>>= \env ->
gets stCurPerms >>>= \perms_in ->
gets stPPInfo >>>= \ppInfo ->
gets stVarTypes >>>= \varTypes ->
gets stUnitVar >>>= \unitVar ->
(stEndianness <$> top_get) >>>= \endianness ->
(stDebugLevel <$> top_get) >>>= \dlevel ->
liftPermCheckM $ lift $
fmap (AnnotPermImpl (renderDoc (err_prefix <> line <> fail_doc))) $
runImplImplM vars perms_in env ppInfo "" dlevel varTypes unitVar endianness impl_m
-- | Embed an implication computation inside a permission-checking computation,
-- also supplying an overall error message for failures
pcmEmbedImplWithErrM ::
HasCallStack =>
NuMatchingAny1 r =>
(forall ps. AnnotPermImpl r ps -> r ps) -> CruCtx vars -> Doc () ->
ImplM vars (InnerPermCheckState blocks tops rets) r ps_out ps_in a ->
PermCheckM ext cblocks blocks tops rets (r ps_out) ps_out (r ps_in) ps_in
(PermSubst vars, a)
pcmEmbedImplWithErrM f_impl vars fail_doc m =
getErrorPrefix >>>= \err_prefix ->
gmapRet ((f_impl . AnnotPermImpl (renderDoc
(err_prefix <> line <> fail_doc))) <$>) >>>
(stPermEnv <$> top_get) >>>= \env ->
gets stCurPerms >>>= \perms_in ->
gets stPPInfo >>>= \ppInfo ->
gets stVarTypes >>>= \varTypes ->
gets stUnitVar >>>= \unitVar ->
(stEndianness <$> top_get) >>>= \endianness ->
(stDebugLevel <$> top_get) >>>= \dlevel ->
addReader
(gcaptureCC
(runImplM vars perms_in env ppInfo "" dlevel varTypes unitVar endianness m))
>>>= \(a, implSt) ->
gmodify ((\st -> st { stPPInfo = implSt ^. implStatePPInfo,
stVarTypes = implSt ^. implStateNameTypes,
stUnitVar = implSt ^. implStateUnitVar })
. setSTCurPerms (implSt ^. implStatePerms)) >>>
pure (completePSubst vars (implSt ^. implStatePSubst), a)
-- | Embed an implication computation inside a permission-checking computation
pcmEmbedImplM ::
HasCallStack =>
NuMatchingAny1 r =>
(forall ps. AnnotPermImpl r ps -> r ps) -> CruCtx vars ->
ImplM vars (InnerPermCheckState blocks tops rets) r ps_out ps_in a ->
PermCheckM ext cblocks blocks tops rets (r ps_out) ps_out (r ps_in) ps_in
(PermSubst vars, a)
pcmEmbedImplM f_impl vars m = pcmEmbedImplWithErrM f_impl vars mempty m
-- | Special case of 'pcmEmbedImplM' for a statement type-checking context where
-- @vars@ is empty
stmtEmbedImplM ::
HasCallStack =>
NuMatchingExtC ext =>
ImplM RNil (InnerPermCheckState
blocks tops rets) (TypedStmtSeq ext blocks tops rets) ps_out ps_in a ->
StmtPermCheckM ext cblocks blocks tops rets ps_out ps_in a
stmtEmbedImplM m = snd <$> pcmEmbedImplM TypedImplStmt emptyCruCtx m
-- | Recombine any outstanding distinguished permissions back into the main
-- permission set, in the context of type-checking statements
stmtRecombinePerms ::
HasCallStack =>
PermCheckExtC ext =>
StmtPermCheckM ext cblocks blocks tops rets RNil ps_in ()
stmtRecombinePerms =
get >>>= \(!st) ->
let dist_perms = view distPerms (stCurPerms st) in
pcmEmbedImplM TypedImplStmt emptyCruCtx (recombinePerms dist_perms) >>>
pure ()
-- | Helper function to pretty print "Could not prove ps" for permissions @ps@
ppProofError :: PermPretty a => PPInfo -> a -> Doc ()
ppProofError ppInfo mb_ps =
nest 2 $ sep [pretty "Could not prove", PP.group (permPretty ppInfo mb_ps)]
-- | Prove a sequence of permissions over some existential variables and append
-- them to the top of the stack
stmtProvePermsAppend :: PermCheckExtC ext =>
CruCtx vars -> ExDistPerms vars ps ->
StmtPermCheckM ext cblocks blocks tops rets
(ps_in :++: ps) ps_in (PermSubst vars)
stmtProvePermsAppend vars ps =
permGetPPInfo >>>= \ppInfo ->
let err = ppProofError ppInfo ps in
fst <$> pcmEmbedImplWithErrM TypedImplStmt vars err (proveVarsImplAppend ps)
-- | Prove a sequence of permissions over some existential variables in the
-- context of the empty permission stack
stmtProvePerms :: PermCheckExtC ext =>
CruCtx vars -> ExDistPerms vars ps ->
StmtPermCheckM ext cblocks blocks tops rets
ps RNil (PermSubst vars)
stmtProvePerms vars ps =
permGetPPInfo >>>= \ppInfo ->
let err = ppProofError ppInfo ps in
fst <$> pcmEmbedImplWithErrM TypedImplStmt vars err (proveVarsImpl ps)
-- | Prove a sequence of permissions over some existential variables in the
-- context of the empty permission stack, but first generate fresh lifetimes for
-- any existential lifetime variables
stmtProvePermsFreshLs :: PermCheckExtC ext =>
CruCtx vars -> ExDistPerms vars ps ->
StmtPermCheckM ext cblocks blocks tops rets
ps RNil (PermSubst vars)
stmtProvePermsFreshLs vars ps =
permGetPPInfo >>>= \ppInfo ->
let err = ppProofError ppInfo ps in
fst <$> pcmEmbedImplWithErrM TypedImplStmt vars err
(instantiateLifetimeVars ps >>> proveVarsImpl ps)
-- | Prove a single permission in the context of type-checking statements
stmtProvePerm :: (PermCheckExtC ext, KnownRepr CruCtx vars) =>
TypedReg a -> Mb vars (ValuePerm a) ->
StmtPermCheckM ext cblocks blocks tops rets
(ps :> a) ps (PermSubst vars)
stmtProvePerm (TypedReg x) mb_p =
permGetPPInfo >>>= \ppInfo ->
let err = ppProofError ppInfo (fmap (distPerms1 x) mb_p) in
fst <$> pcmEmbedImplWithErrM TypedImplStmt knownRepr err
(proveVarImpl x mb_p)
-- | Try to prove that a register equals a constant integer (of the given input
-- type) using equality permissions in the context
resolveConstant :: TypedReg tp ->
StmtPermCheckM ext cblocks blocks tops rets ps ps
(Maybe Integer)
resolveConstant = helper . PExpr_Var . typedRegVar where
helper :: PermExpr a ->
StmtPermCheckM ext cblocks blocks tops rets ps ps
(Maybe Integer)
helper (PExpr_Var x) =
getVarPerm x >>= \case
ValPerm_Eq e -> helper e
_ -> pure Nothing
helper (PExpr_Nat i) = pure (Just $ toInteger i)
helper (PExpr_BV factors (BV.BV off)) =
foldM (\maybe_res (BVFactor (BV.BV i) x) ->
helper (PExpr_Var x) >>= \maybe_x_val ->
case (maybe_res, maybe_x_val) of
(Just res, Just x_val) ->
return (Just (res + x_val * i))
_ -> return Nothing)
(Just off) factors
helper (PExpr_LLVMWord e) = helper e
helper (PExpr_LLVMOffset x e) =
do maybe_x_val <- helper (PExpr_Var x)
maybe_e_val <- helper e
case (maybe_x_val, maybe_e_val) of
(Just x_val, Just e_val) -> return (Just (x_val + e_val))
_ -> return Nothing
helper _ = return Nothing
-- | Convert a register of one type to one of another type, if possible
convertRegType :: PermCheckExtC ext => ExtRepr ext -> ProgramLoc ->
TypedReg tp1 -> TypeRepr tp1 -> TypeRepr tp2 ->
StmtPermCheckM ext cblocks blocks tops rets RNil RNil
(TypedReg tp2)
convertRegType _ _ reg tp1 tp2
| Just Refl <- testEquality tp1 tp2 = pure reg
convertRegType _ loc reg (BVRepr w1) tp2@(BVRepr w2)
| Left LeqProof <- decideLeq (knownNat :: NatRepr 1) w2
, NatCaseGT LeqProof <- testNatCases w1 w2 =
withKnownNat w2 $
emitStmt knownRepr noNames loc
(TypedSetReg tp2 $
TypedExpr (BVTrunc w2 w1 $ RegNoVal reg)
Nothing) >>>= \(MNil :>: x) ->
stmtRecombinePerms >>>
pure (TypedReg x)
convertRegType _ loc reg (BVRepr w1) tp2@(BVRepr w2)
| Left LeqProof <- decideLeq (knownNat :: NatRepr 1) w1
, Left LeqProof <- decideLeq (knownNat :: NatRepr 1) w2
, NatCaseLT LeqProof <- testNatCases w1 w2 =
-- FIXME: should this use endianness?
-- (stEndianness <$> top_get) >>>= \endianness ->
withKnownNat w2 $
emitStmt knownRepr noNames loc
(TypedSetReg tp2 $
TypedExpr (BVSext w2 w1 $ RegNoVal reg)
Nothing) >>>= \(MNil :>: x) ->
stmtRecombinePerms >>>
pure (TypedReg x)
convertRegType ExtRepr_LLVM loc reg (LLVMPointerRepr w1) (BVRepr w2)
| Just Refl <- testEquality w1 w2 =
withKnownNat w1 $
stmtProvePerm reg (llvmExEqWord w1) >>>= \sbst ->
let e = substLookup sbst Member_Base in
emitLLVMStmt knownRepr Nothing loc (DestructLLVMWord reg e) >>>= \x ->
stmtRecombinePerms >>>
pure (TypedReg x)
convertRegType ext loc reg (LLVMPointerRepr w1) (BVRepr w2) =
convertRegType ext loc reg (LLVMPointerRepr w1) (BVRepr w1) >>>= \reg' ->
convertRegType ext loc reg' (BVRepr w1) (BVRepr w2)
convertRegType ExtRepr_LLVM loc reg (BVRepr w2) (LLVMPointerRepr w1)
| Just Refl <- testEquality w1 w2 =
withKnownNat w1 $
emitLLVMStmt knownRepr Nothing loc (ConstructLLVMWord reg) >>>= \x ->
stmtRecombinePerms >>> pure (TypedReg x)
convertRegType ext loc reg (BVRepr w1) (LLVMPointerRepr w2) =
convertRegType ext loc reg (BVRepr w1) (BVRepr w2) >>>= \reg' ->
convertRegType ext loc reg' (BVRepr w2) (LLVMPointerRepr w2)
convertRegType ext loc reg (LLVMPointerRepr w1) (LLVMPointerRepr w2) =
convertRegType ext loc reg (LLVMPointerRepr w1) (BVRepr w1) >>>= \reg1 ->
convertRegType ext loc reg1 (BVRepr w1) (BVRepr w2) >>>= \reg2 ->
convertRegType ext loc reg2 (BVRepr w2) (LLVMPointerRepr w2)
convertRegType _ _ x tp1 tp2 =
stmtFailM (\i -> pretty "Could not cast" <+> permPretty i x
<+> pretty "from" <+> pretty (show tp1)
<+> pretty "to" <+> pretty (show tp2))
-- | Extract the bitvector of size @sz@ at offset @off@ from a larger bitvector
-- @bv@, using the current endianness to determine how this extraction works
extractBVBytes :: (1 <= w, KnownNat w) =>
ProgramLoc -> NatRepr sz -> Bytes -> TypedReg (BVType w) ->
StmtPermCheckM LLVM cblocks blocks tops rets RNil RNil
(TypedReg (BVType sz))
extractBVBytes loc sz off_bytes (reg :: TypedReg (BVType w)) =
let w :: NatRepr w = knownNat in
(stEndianness <$> top_get) >>= \endianness ->
withKnownNat sz $
case (endianness, decideLeq (knownNat @1) sz) of
-- For little endian, we can just call BVSelect
(LittleEndian, Left sz_pf)
| Just (Some off) <- someNat (bytesToBits off_bytes)
, Left off_sz_w_pf <- decideLeq (addNat off sz) w ->
withLeqProof sz_pf $ withLeqProof off_sz_w_pf $
emitStmt knownRepr noNames loc
(TypedSetReg (BVRepr sz) $
TypedExpr (BVSelect off sz w $ RegNoVal reg)
Nothing) >>>= \(MNil :>: x) ->
stmtRecombinePerms >>>
pure (TypedReg x)
-- For big endian, we call BVSelect with idx = w - off - sz
(BigEndian, Left sz_pf)
| Just (Some idx) <- someNat (intValue w
- toInteger (bytesToBits off_bytes)
- intValue sz)
, Left idx_sz_w_pf <- decideLeq (addNat idx sz) w ->
withLeqProof sz_pf $ withLeqProof idx_sz_w_pf $
emitStmt knownRepr noNames loc
(TypedSetReg (BVRepr sz) $
TypedExpr (BVSelect idx sz w $ RegNoVal reg)
Nothing) >>>= \(MNil :>: x) ->
stmtRecombinePerms >>>
pure (TypedReg x)
_ -> error "extractBVBytes: negative offset!"
-- | Emit a statement in the current statement sequence, where the supplied
-- function says how that statement modifies the current permissions, given the
-- freshly-bound names for the return values. Return those freshly-bound names
-- for the return values.
emitStmt ::
PermCheckExtC ext =>
CruCtx stmt_rets ->
RAssign (Constant (Maybe String)) stmt_rets ->
ProgramLoc ->
TypedStmt ext stmt_rets ps_in ps_out ->
StmtPermCheckM ext cblocks blocks tops rets ps_out ps_in
(RAssign Name stmt_rets)
emitStmt tps names loc stmt =
gopenBinding
((TypedConsStmt loc stmt (cruCtxProxies tps) <$>) . strongMbM)
(mbPure (cruCtxProxies tps) ()) >>>= \(ns, ()) ->
setVarTypes Nothing names ns tps >>>
gmodify (modifySTCurPerms (applyTypedStmt stmt ns)) >>>
gets (view distPerms . stCurPerms) >>>= \perms_out ->
stmtVerbTraceM (\i ->
pretty "Created new variables: "
<+> permPretty i ns <> line <>
pretty "Statement output permissions: " <+>
permPretty i perms_out) >>>
-- Note: must come after both setVarTypes and gmodify
stmtHandleUnitVars ns >>>
pure ns
-- | Call emitStmt with a 'TypedLLVMStmt'
emitLLVMStmt ::
TypeRepr tp ->
Maybe String ->
ProgramLoc ->
TypedLLVMStmt tp ps_in ps_out ->
StmtPermCheckM LLVM cblocks blocks tops rets ps_out ps_in (Name tp)
emitLLVMStmt tp name loc stmt =
RL.head <$> emitStmt (singletonCruCtx tp) (RL.singleton (Constant name)) loc (TypedLLVMStmt stmt)
-- | A program location for code which was generated by the type-checker
checkerProgramLoc :: ProgramLoc
checkerProgramLoc =
mkProgramLoc (functionNameFromText (Text.pack "None"))
(OtherPos (Text.pack "(Generated by permission type-checker)"))
----------------------------------------------------------------------
-- * Permission Checking and Pretty-Printing for Registers
----------------------------------------------------------------------
-- | Type-check a Crucible register by looking it up in the translated context
tcReg :: CtxTrans ctx -> Reg ctx tp -> TypedReg tp
tcReg ctx (Reg ix) = ctx ! ix
-- | Type-check a Crucible register and also look up its value, if known
tcRegWithVal :: PermCheckExtC ext => CtxTrans ctx -> Reg ctx tp ->
StmtPermCheckM ext cblocks blocks tops rets ps ps
(RegWithVal tp)
tcRegWithVal ctx r_untyped =
let r = tcReg ctx r_untyped in
getRegEqualsExpr r >>= \case
PExpr_Var x | x == typedRegVar r -> pure $ RegNoVal r
e -> pure $ RegWithVal r e
-- | Type-check a sequence of Crucible registers
tcRegs :: CtxTrans ctx -> Assignment (Reg ctx) tps -> TypedRegs (CtxToRList tps)
tcRegs _ctx (viewAssign -> AssignEmpty) = TypedRegsNil
tcRegs ctx (viewAssign -> AssignExtend regs reg) =
TypedRegsCons (tcRegs ctx regs) (tcReg ctx reg)
-- | Pretty-print the permissions that are "relevant" to a register, which
-- includes its permissions and all those relevant to any register it is equal
-- to, possibly plus some offset
ppRelevantPerms :: TypedReg tp ->
PermCheckM ext cblocks blocks tops rets r ps r ps (Doc ())
ppRelevantPerms r =
getRegPerm r >>>= \p ->
permGetPPInfo >>>= \ppInfo ->
let pp_r = permPretty ppInfo r <> colon <> permPretty ppInfo p in
case p of
ValPerm_Eq (PExpr_Var x) ->
((pp_r <> comma) <+>) <$> ppRelevantPerms (TypedReg x)
ValPerm_Eq (PExpr_LLVMOffset x _) ->
((pp_r <> comma) <+>) <$> ppRelevantPerms (TypedReg x)
ValPerm_Eq (PExpr_LLVMWord (PExpr_Var x)) ->
((pp_r <> comma) <+>) <$> ppRelevantPerms (TypedReg x)
_ -> pure pp_r
-- | Pretty-print a Crucible 'Reg' and what 'TypedReg' it is equal to, along
-- with the relevant permissions for that 'TypedReg'
ppCruRegAndPerms :: CtxTrans ctx -> Reg ctx a ->
PermCheckM ext cblocks blocks tops rets r ps r ps (Doc ())
ppCruRegAndPerms ctx r =
permGetPPInfo >>>= \ppInfo ->
ppRelevantPerms (tcReg ctx r) >>>= \doc ->
pure (PP.group (pretty r <+> pretty '=' <+> permPretty ppInfo (tcReg ctx r)
<> comma <+> doc))
-- | Get the permissions on the variables in the input set, the variables in
-- their permissions, the variables in those permissions etc., as in
-- 'varPermsTransFreeVars'
getRelevantPerms :: [SomeName CrucibleType] ->
PermCheckM ext cblocks blocks tops rets r ps r ps
(Some DistPerms)
getRelevantPerms (namesListToNames -> SomeRAssign ns) =
gets stCurPerms >>>= \perms ->
case varPermsTransFreeVars ns perms of
Some all_ns -> pure (Some $ varPermsMulti (RL.append ns all_ns) perms)
-- | Pretty-print a list of Crucible registers and the variables they translate
-- to, and then pretty-print the permissions on those variables and all
-- variables they contain, as well as the top-level input variables and the
-- extension-specific variables
ppCruRegsAndTopsPerms ::
[Maybe String] ->
CtxTrans ctx ->
[Some (Reg ctx)] ->
PermCheckM ext cblocks blocks tops rets r ps r ps (Doc (), Doc ())
ppCruRegsAndTopsPerms names ctx regs =
permGetPPInfo >>>= \ppInfo ->
gets stTopVars >>>= \tops ->
gets (permCheckExtStateNames . stExtState) >>>= \(Some ext_ns) ->
let vars_pp =
fillSep $ punctuate comma $
map (\(Some r) ->
let name = listToMaybe (drop (indexVal (regIndex r)) names) in
pretty r <+> pretty '=' <+>
permPretty ppInfo (tcReg ctx r) <>
foldMap (\n -> pretty " @" <+> pretty n) name)
(nub regs)
vars =
namesToNamesList tops ++ namesToNamesList ext_ns ++
map (\(Some r) -> SomeName $ typedRegVar $ tcReg ctx r) regs in
getRelevantPerms vars >>>= \some_perms ->
case some_perms of
Some perms -> pure (vars_pp, permPretty ppInfo perms)
-- | Set the current prefix string to give context to error messages
setErrorPrefix ::
[Maybe String] ->
ProgramLoc ->
Doc () ->
CtxTrans ctx ->
[Some (Reg ctx)] ->
PermCheckM ext cblocks blocks tops rets r ps r ps ()
setErrorPrefix names loc stmt_pp ctx regs =
ppCruRegsAndTopsPerms names ctx regs >>>= \(regs_pp, perms_pp) ->
let prefix =
PP.sep
[PP.group (pretty "At" <+> ppShortFileName (plSourceLoc loc)
<+> parens stmt_pp),
PP.group (pretty "Regs:" <+> regs_pp),
PP.group (pretty "Input perms:" <+> perms_pp)] in
gmodify $ \st -> st { stErrPrefix = Just prefix }
----------------------------------------------------------------------
-- * Permission Checking for Expressions and Statements
----------------------------------------------------------------------
-- | Get a dynamic representation of an architecture's width
archWidth :: KnownNat (ArchWidth arch) => f arch -> NatRepr (ArchWidth arch)
archWidth _ = knownNat
-- | Type-check a Crucibe block id into a 'TypedBlockID'
tcBlockID :: BlockID cblocks args ->
StmtPermCheckM ext cblocks blocks tops rets ps ps
(TypedBlockID blocks (CtxToRList args))
tcBlockID blkID = stLookupBlockID blkID <$> top_get
-- | Type-check a Crucible expression to test if it has a statically known
-- 'PermExpr' value that we can use as an @eq(e)@ permission on the output of
-- the expression
tcExpr ::
forall ext tp cblocks blocks tops rets ps.
(PermCheckExtC ext, KnownRepr ExtRepr ext) =>
App ext RegWithVal tp ->
StmtPermCheckM ext cblocks blocks tops rets ps ps (Maybe (PermExpr tp))
tcExpr (ExtensionApp _e_ext :: App ext RegWithVal tp)
| ExtRepr_LLVM <- knownRepr :: ExtRepr ext
= error "tcExpr: unexpected LLVM expression"
-- Equality expressions --
-- For equalities, we can definitely return True if the values of the two
-- expressions being compared are equal, but we can only return False if we know
-- for sure that the two values are unequal. If, e.g., one is a variable with
-- unknown value, it could equal anything, so we know nothing about the result
-- of the equality test.
tcExpr (BoolEq (RegWithVal _ (PExpr_Bool b1))
(RegWithVal _ (PExpr_Bool b2))) =
pure $ Just $ PExpr_Bool (b1 == b2)
tcExpr (BoolEq rwv1 rwv2)
| regWithValExpr rwv1 == regWithValExpr rwv2 =
pure $ Just $ PExpr_Bool True
tcExpr (NatEq (RegWithVal _ (PExpr_Nat i1))
(RegWithVal _ (PExpr_Nat i2))) =
pure $ Just $ PExpr_Bool (i1 == i2)
tcExpr (NatEq rwv1 rwv2)
| regWithValExpr rwv1 == regWithValExpr rwv2 =
pure $ Just $ PExpr_Bool True
tcExpr (BVEq _ (RegWithVal _ bv1) (RegWithVal _ bv2))
| bvEq bv1 bv2 = pure $ Just $ PExpr_Bool True
tcExpr (BVEq _ (RegWithVal _ bv1) (RegWithVal _ bv2))
| not (bvCouldEqual bv1 bv2) = pure $ Just $ PExpr_Bool False
tcExpr (BVEq _ rwv1 rwv2)
| regWithValExpr rwv1 == regWithValExpr rwv2 =
pure $ Just $ PExpr_Bool True
tcExpr (BaseIsEq _ rwv1 rwv2)
| regWithValExpr rwv1 == regWithValExpr rwv2 =
pure $ Just $ PExpr_Bool True
-- Boolean expressions --
tcExpr (BoolLit b) = pure $ Just $ PExpr_Bool b
tcExpr (Not (RegWithVal _ (PExpr_Bool b))) =
pure $ Just $ PExpr_Bool $ not b
tcExpr (And (RegWithVal _ (PExpr_Bool False)) _) =
pure $ Just $ PExpr_Bool False
tcExpr (And _ (RegWithVal _ (PExpr_Bool False))) =
pure $ Just $ PExpr_Bool False
tcExpr (And (RegWithVal _ (PExpr_Bool True)) rwv) =
pure $ Just $ regWithValExpr rwv
tcExpr (And rwv (RegWithVal _ (PExpr_Bool True))) =
pure $ Just $ regWithValExpr rwv
tcExpr (Or (RegWithVal _ (PExpr_Bool True)) _) =
pure $ Just $ PExpr_Bool True
tcExpr (Or _ (RegWithVal _ (PExpr_Bool True))) =
pure $ Just $ PExpr_Bool True
tcExpr (Or (RegWithVal _ (PExpr_Bool False)) rwv) =
pure $ Just $ regWithValExpr rwv
tcExpr (Or rwv (RegWithVal _ (PExpr_Bool False))) =
pure $ Just $ regWithValExpr rwv
tcExpr (BoolXor (RegWithVal _ (PExpr_Bool False)) rwv) =
pure $ Just $ regWithValExpr rwv
tcExpr (BoolXor rwv (RegWithVal _ (PExpr_Bool False))) =
pure $ Just $ regWithValExpr rwv
tcExpr (BoolXor (RegWithVal _ (PExpr_Bool True))
(RegWithVal _ (PExpr_Bool True))) =
pure $ Just $ PExpr_Bool False
-- Nat expressions --
tcExpr (NatLit i) = pure $ Just $ PExpr_Nat i
-- Bitvector expressions --
tcExpr (BVUndef _w) =
-- "Undefined" bitvectors are translated to 0 as a stand-in but we don't
-- return any equality permissions about them
pure Nothing
tcExpr (BVLit w (BV.BV i)) = withKnownNat w $ pure $ Just $ bvInt i
tcExpr (BVTrunc w2 _ (RegWithVal _ (bvMatchConst -> Just bv))) =
withKnownNat w2 $ pure $ Just $ bvBV $ BV.trunc w2 bv
tcExpr (BVZext w2 _ (RegWithVal _ (bvMatchConst -> Just bv))) =
withKnownNat w2 $ pure $ Just $ bvBV $ BV.zext w2 bv
tcExpr (BVSext w2 w (RegWithVal _ (bvMatchConst -> Just bv))) =
withKnownNat w2 $ pure $ Just $ bvBV $ BV.sext w w2 bv
tcExpr (BVNot w (RegWithVal _ (bvMatchConst -> Just bv))) =
withKnownNat w $ pure $ Just $ bvBV $ BV.complement w bv
tcExpr (BVAnd w (RegWithVal _ (bvMatchConst ->
Just bv1)) (RegWithVal _
(bvMatchConst -> Just bv2))) =
withKnownNat w $ pure $ Just $ bvBV $ BV.and bv1 bv2
tcExpr (BVOr w (RegWithVal _ (bvMatchConst ->
Just bv1)) (RegWithVal _
(bvMatchConst -> Just bv2))) =
withKnownNat w $ pure $ Just $ bvBV $ BV.or bv1 bv2
tcExpr (BVXor w (RegWithVal _ (bvMatchConst ->
Just bv1)) (RegWithVal _
(bvMatchConst -> Just bv2))) =
withKnownNat w $ pure $ Just $ bvBV $ BV.xor bv1 bv2
tcExpr (BVAdd w (RegWithVal _ e1) (RegWithVal _ e2)) =
withKnownNat w $ pure $ Just $ bvAdd e1 e2
tcExpr (BVMul w (RegWithVal _ (bvMatchConstInt -> Just i)) (RegWithVal _ e)) =
withKnownNat w $ pure $ Just $ bvMult i e
tcExpr (BVMul w (RegWithVal _ e) (RegWithVal _ (bvMatchConstInt -> Just i))) =
withKnownNat w $ pure $ Just $ bvMult i e
tcExpr (BoolToBV w (RegWithVal _ (PExpr_Bool True))) =
withKnownNat w $ pure $ Just $ bvInt 1
tcExpr (BoolToBV w (RegWithVal _ (PExpr_Bool False))) =
withKnownNat w $ pure $ Just $ bvInt 0
tcExpr (BVUlt _ (RegWithVal _ e1) (RegWithVal _ e2))
| bvLt e1 e2 = pure $ Just $ PExpr_Bool True
tcExpr (BVUlt _ (RegWithVal _ e1) (RegWithVal _ e2))
| not (bvCouldBeLt e1 e2) = pure $ Just $ PExpr_Bool False
tcExpr (BVUle _ (RegWithVal _ e1) (RegWithVal _ e2))
| bvLt e2 e1 = pure $ Just $ PExpr_Bool False
tcExpr (BVUle _ (RegWithVal _ e1) (RegWithVal _ e2))
| not (bvCouldBeLt e2 e1) = pure $ Just $ PExpr_Bool True
tcExpr (BVSlt w (RegWithVal _ e1) (RegWithVal _ e2))
| withKnownNat w $ bvSLt e1 e2
= pure $ Just $ PExpr_Bool True
tcExpr (BVSlt w (RegWithVal _ e1) (RegWithVal _ e2))
| withKnownNat w $ not (bvCouldBeSLt e1 e2)
= pure $ Just $ PExpr_Bool False
tcExpr (BVSle w (RegWithVal _ e1) (RegWithVal _ e2))
| withKnownNat w $ bvSLt e2 e1
= pure $ Just $ PExpr_Bool False
tcExpr (BVSle w (RegWithVal _ e1) (RegWithVal _ e2))
| withKnownNat w $ not (bvCouldBeSLt e2 e1)
= pure $ Just $ PExpr_Bool True
tcExpr (BVNonzero w (RegWithVal _ bv))
| bvEq bv (withKnownNat w $ bvInt 0) = pure $ Just $ PExpr_Bool False
tcExpr (BVNonzero _ (RegWithVal _ bv))
| not (bvZeroable bv) = pure $ Just $ PExpr_Bool True
-- String expressions --
tcExpr (StringLit (UnicodeLiteral text)) =
pure $ Just $ PExpr_String $ Text.unpack text
-- Struct expressions --
-- For a struct built from registers r1, ..., rn, return struct(r1,...,rn)
tcExpr (MkStruct _ vars) =
pure $ Just $ PExpr_Struct $ namesToExprs $
RL.map (typedRegVar . regWithValReg) $ assignToRList vars
-- For GetStruct x ix, if x has a value it will have been eta-expanded to a
-- struct expression, so simply get out the required field of that struct
tcExpr (GetStruct (RegWithVal r (PExpr_Struct es)) ix _) =
getVarType (typedRegVar r) >>= \(StructRepr tps) ->
let memb = indexToMember (Ctx.size tps) ix in
pure $ Just $ RL.get memb (exprsToRAssign es)
-- For SetStruct x ix y, if x has a value it will have been eta-expanded to a
-- struct expression, so simply replace required field of that struct with y
tcExpr (SetStruct tps (RegWithVal _ (PExpr_Struct es)) ix r') =
let memb = indexToMember (Ctx.size tps) ix in
pure $ Just $ PExpr_Struct $ rassignToExprs $
RL.set memb (PExpr_Var $ typedRegVar $ regWithValReg r') $
exprsToRAssign es
-- Misc expressions --
tcExpr _ = pure Nothing
-- | Test if a sequence of arguments could potentially satisfy some function
-- input permissions. This is an overapproximation, meaning that we might return
-- 'True' even if the arguments do not satisfy the permissions.
couldSatisfyPermsM :: PermCheckExtC ext => CruCtx args -> TypedRegs args ->
Mb ghosts (ValuePerms args) ->
StmtPermCheckM ext cblocks blocks tops rets ps ps Bool
couldSatisfyPermsM CruCtxNil _ _ = pure True
couldSatisfyPermsM (CruCtxCons tps (BVRepr _)) (TypedRegsCons args arg)
(mbMatch -> [nuMP| ValPerms_Cons ps (ValPerm_Eq mb_e) |]) =
do b <- couldSatisfyPermsM tps args ps
arg_val <- getRegEqualsExpr arg
pure (b && mbLift (fmap (bvCouldEqual arg_val) mb_e))
couldSatisfyPermsM (CruCtxCons tps _) (TypedRegsCons args arg)
(mbMatch -> [nuMP| ValPerms_Cons ps
(ValPerm_Eq (PExpr_LLVMWord mb_e)) |]) =
do b <- couldSatisfyPermsM tps args ps
getRegEqualsExpr arg >>= \case
PExpr_LLVMWord e ->
pure (b && mbLift (fmap (bvCouldEqual e) mb_e))
_ -> pure False
couldSatisfyPermsM (CruCtxCons tps _) (TypedRegsCons args _)
(mbMatch -> [nuMP| ValPerms_Cons ps _ |]) =
couldSatisfyPermsM tps args ps
-- | Typecheck a statement and emit it in the current statement sequence,
-- starting and ending with an empty stack of distinguished permissions
tcEmitStmt ::
(PermCheckExtC ext, KnownRepr ExtRepr ext) =>
CtxTrans ctx ->
ProgramLoc ->
Stmt ext ctx ctx' ->
StmtPermCheckM ext cblocks blocks tops rets RNil RNil (CtxTrans ctx')
tcEmitStmt ctx loc stmt =
do _ <- stmtTraceM (const (pretty "Type-checking statement:" <+>
ppStmt (size ctx) stmt))
!_ <- permGetPPInfo
!pps <- mapM (\(Some r) -> ppCruRegAndPerms ctx r) (stmtInputRegs stmt)
!_ <- stmtTraceM (\_-> pretty "Input perms:" <> softline <>
ppCommaSep pps)
!ctx' <- tcEmitStmt' ctx loc stmt
!pps' <- mapM (\(Some r) -> ppCruRegAndPerms ctx' r)
(stmtOutputRegs (Ctx.size ctx') stmt)
_ <- stmtTraceM (const (pretty "Output perms:" <> softline <>
ppCommaSep pps'))
pure ctx'
tcEmitStmt' ::
forall ext ctx ctx' cblocks blocks tops rets.
(PermCheckExtC ext, KnownRepr ExtRepr ext) =>
CtxTrans ctx ->
ProgramLoc ->
Stmt ext ctx ctx' ->
StmtPermCheckM ext cblocks blocks tops rets RNil RNil
(CtxTrans ctx')
tcEmitStmt' ctx loc (SetReg _ (App (ExtensionApp e_ext
:: App ext (Reg ctx) tp)))
| ExtRepr_LLVM <- knownRepr :: ExtRepr ext
= tcEmitLLVMSetExpr ctx loc e_ext
tcEmitStmt' ctx loc (SetReg tp (App e)) =
traverseFC (tcRegWithVal ctx) e >>= \e_with_vals ->
tcExpr e_with_vals >>= \maybe_val ->
let typed_e = TypedExpr e_with_vals maybe_val in
let stmt_rets = (singletonCruCtx tp) in
dbgNames' stmt_rets >>= \names ->
emitStmt stmt_rets names loc (TypedSetReg tp typed_e) >>>= \(_ :>: x) ->
stmtRecombinePerms >>>
pure (addCtxName ctx x)
tcEmitStmt' ctx loc (ExtendAssign stmt_ext :: Stmt ext ctx ctx')
| ExtRepr_LLVM <- knownRepr :: ExtRepr ext
= tcEmitLLVMStmt Proxy ctx loc stmt_ext
tcEmitStmt' ctx loc (CallHandle _ret freg_untyped _args_ctx args_untyped) =
let freg = tcReg ctx freg_untyped
args = tcRegs ctx args_untyped
{- args_subst = typedRegsToVarSubst args -} in
{- getVarTypes (typedRegsToVars args) >>>= \argTypes -> -}
getSimpleRegPerm freg >>>= \p_freg ->
(case p_freg of
ValPerm_Conj ps ->
forM ps $ \p -> case p of
Perm_Fun fun_perm ->
-- FIXME: rewrite couldSatisfyPermsM to fit ghosts having permissions
{- couldSatisfyPermsM argTypes args (fmap (varSubst args_subst) $
funPermIns fun_perm) >>>= \could -> -}
let could = True in
pure (if could then Just (SomeFunPerm fun_perm) else Nothing)
_ -> pure Nothing
_ -> pure []) >>>= \maybe_fun_perms ->
(stmtEmbedImplM $ foldr1WithDefault (implCatchM "tcEmitStmt (fun perm)" $
typedRegVar freg)
(implFailMsgM "Could not find function permission")
(mapMaybe (fmap pure) maybe_fun_perms)) >>>= \some_fun_perm ->
case some_fun_perm of
SomeFunPerm fun_perm ->
let ghosts = funPermGhosts fun_perm
args_ns = typedRegsToVars args
rets = funPermRets fun_perm in
(stmtProvePermsFreshLs ghosts (funPermExDistIns
fun_perm args_ns)) >>>= \gsubst ->
let gexprs = exprsOfSubst gsubst in
gets (RL.split ghosts args_ns . distPermsVars . view distPerms . stCurPerms)
>>>= \(ghosts_ns,_) ->
stmtProvePermsAppend CruCtxNil (emptyMb $
eqDistPerms ghosts_ns gexprs) >>>= \_ ->
stmtProvePerm freg (emptyMb $ ValPerm_Conj1 $ Perm_Fun fun_perm) >>>= \_ ->
dbgNames' rets >>>= \names ->
emitStmt rets names loc (TypedCall freg fun_perm
(varsToTypedRegs ghosts_ns) gexprs args)
>>>= \(_ :>: ret') ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret')
tcEmitStmt' ctx loc (Assert reg msg) =
let treg = tcReg ctx reg in
getRegEqualsExpr treg >>= \case
PExpr_Bool True -> pure ctx
PExpr_Bool False -> stmtFailM (\_ -> pretty "Failed assertion")
_ -> ctx <$ emitStmt CruCtxNil MNil loc (TypedAssert (tcReg ctx reg) (tcReg ctx msg))
tcEmitStmt' _ _ _ = error "tcEmitStmt: unsupported statement"
-- | Translate a Crucible assignment of an LLVM expression
tcEmitLLVMSetExpr ::
CtxTrans ctx ->
ProgramLoc ->
LLVMExtensionExpr (Reg ctx) tp ->
StmtPermCheckM LLVM cblocks blocks tops rets RNil RNil
(CtxTrans (ctx ::> tp))
-- Type-check a pointer-building expression, which is only valid when the block
-- = 0, i.e., when building a word
tcEmitLLVMSetExpr ctx loc (LLVM_PointerExpr w blk_reg off_reg) =
let toff_reg = tcReg ctx off_reg
tblk_reg = tcReg ctx blk_reg in
resolveConstant tblk_reg >>= \case
Just 0 ->
nextDebugName >>>= \name ->
withKnownNat w $
emitLLVMStmt knownRepr name loc (ConstructLLVMWord toff_reg) >>>= \x ->
stmtRecombinePerms >>>
pure (addCtxName ctx x)
_ -> stmtFailM (\i -> pretty "LLVM_PointerExpr: Non-zero pointer block: "
<> permPretty i tblk_reg)
-- Type-check the LLVM value destructor that gets the block value, by either
-- proving a permission eq(llvmword e) and returning block 0 or proving
-- permission is_llvmptr and returning the constant value 1.
--
-- NOTE: our SAW translation does not include any computational content for
-- pointer blocks and offsets, so we cannot represent the actual runtime value
-- of the pointer block of a pointer. We can only know if it is zero or not by
-- using permissions, and we map all non-zero values to 1. This implicitly
-- assumes that the behavior of the program we are verifying is not altered in a
-- meaningful way by mapping the return value of 'LLVM_PointerBlock' to 1 when
-- it is applied to pointers, which is the case for all programs currently
-- generated by Crucible from LLVM.
tcEmitLLVMSetExpr ctx loc (LLVM_PointerBlock w ptr_reg) =
let tptr_reg = tcReg ctx ptr_reg in
withKnownNat w $
getAtomicOrWordLLVMPerms tptr_reg >>>= \case
Left e ->
nextDebugName >>>= \name ->
emitLLVMStmt knownRepr name loc (AssertLLVMWord tptr_reg e) >>>= \ret ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
Right _ ->
stmtRecombinePerms >>>
stmtProvePerm tptr_reg (emptyMb $ ValPerm_Conj1 Perm_IsLLVMPtr) >>>
emitLLVMStmt knownRepr Nothing loc (AssertLLVMPtr tptr_reg) >>>
dbgNames >>>= \names ->
emitStmt
knownRepr names loc
(TypedSetReg knownRepr $
TypedExpr (NatLit 1)
(Just $ PExpr_Nat 1)) >>>= \(_ :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- Type-check the LLVM value destructor that gets the offset value, by either
-- proving a permission eq(llvmword e) and returning e or proving
-- permission is_llvmptr and returning the constant bitvector value 0.
--
-- NOTE: Just as with 'LLVM_PointerBlock', because our SAW translation does not
-- include any computational content for pointer blocks and offsets, we cannot
-- represent the actual runtime value of the offset of a pointer. We thus return
-- 0 as a dummy value. This implicitly assumes that the behavior of the program
-- we are verifying is not altered in a meaningful way by mapping the return
-- value of 'LLVM_PointerOffset' to 0 when it is applied to pointers, which is
-- the case for all programs currently generated by Crucible from LLVM.
tcEmitLLVMSetExpr ctx loc (LLVM_PointerOffset w ptr_reg) =
let tptr_reg = tcReg ctx ptr_reg in
withKnownNat w $
getAtomicOrWordLLVMPerms tptr_reg >>>= \eith ->
case eith of
Left e ->
nextDebugName >>>= \name ->
emitLLVMStmt knownRepr name loc (DestructLLVMWord
tptr_reg e) >>>= \ret ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
Right _ ->
stmtRecombinePerms >>>
stmtProvePerm tptr_reg (emptyMb $ ValPerm_Conj1 Perm_IsLLVMPtr) >>>
emitLLVMStmt knownRepr Nothing loc (AssertLLVMPtr tptr_reg) >>>
dbgNames >>>= \names ->
emitStmt knownRepr names loc
(TypedSetReg knownRepr $
TypedExpr (BVLit w $ BV.mkBV w 0)
(Just $ bvInt 0)) >>>= \(MNil :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- An if-then-else at pointer type is just preserved, though we propogate
-- equality information when possible
tcEmitLLVMSetExpr ctx loc (LLVM_PointerIte w cond_reg then_reg else_reg) =
withKnownNat w $
let tcond_reg = tcReg ctx cond_reg
tthen_reg = tcReg ctx then_reg
telse_reg = tcReg ctx else_reg in
getRegEqualsExpr tcond_reg >>= \case
PExpr_Bool True ->
dbgNames >>= \names ->
emitStmt knownRepr names loc
(TypedSetRegPermExpr knownRepr $
PExpr_Var $ typedRegVar tthen_reg) >>>= \(MNil :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
PExpr_Bool False ->
dbgNames >>>= \names ->
emitStmt knownRepr names loc
(TypedSetRegPermExpr knownRepr $
PExpr_Var $ typedRegVar telse_reg) >>>= \(MNil :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
_ ->
nextDebugName >>>= \name ->
emitLLVMStmt knownRepr name loc (TypedLLVMIte w
tcond_reg tthen_reg telse_reg) >>>= \ret ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- For LLVM side conditions, treat each side condition as an assert
tcEmitLLVMSetExpr ctx loc (LLVM_SideConditions _ tp conds reg) =
let treg = tcReg ctx reg in
foldr
(\(LLVMSideCondition cond_reg ub) rest_m ->
let tcond_reg = tcReg ctx cond_reg
err_str = renderDoc (pretty "Undefined behavior: " <> softline <> UB.explain ub) in
getRegEqualsExpr tcond_reg >>= \case
PExpr_Bool True ->
rest_m
PExpr_Bool False -> stmtFailM (\_ -> pretty err_str)
_ ->
emitStmt knownRepr noNames loc
(TypedSetRegPermExpr knownRepr $
PExpr_String err_str) >>>= \(MNil :>: str_var) ->
stmtRecombinePerms >>>
emitStmt CruCtxNil MNil loc
(TypedAssert tcond_reg $
TypedReg str_var) >>>= \MNil ->
stmtRecombinePerms >>>
rest_m)
(let rets = singletonCruCtx tp in
dbgNames' rets >>>= \names ->
emitStmt rets names loc
(TypedSetRegPermExpr tp $ PExpr_Var $
typedRegVar treg) >>>= \(MNil :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret))
conds
tcEmitLLVMSetExpr _ctx _loc X86Expr{} =
stmtFailM (\_ -> pretty "X86Expr not supported")
-- FIXME HERE: move withLifetimeCurrentPerms somewhere better...
-- | Perform a statement type-checking conversation inside a context where the
-- supplied lifetime has been proved to be current using the supplied
-- 'LifetimeCurrentPerms'
withLifetimeCurrentPerms ::
PermCheckExtC ext => PermExpr LifetimeType ->
(forall ps_l. LifetimeCurrentPerms ps_l ->
StmtPermCheckM ext cblocks blocks tops rets (ps_out :++: ps_l)
(ps_in :++: ps_l) a) ->
StmtPermCheckM ext cblocks blocks tops rets ps_out ps_in a
withLifetimeCurrentPerms l m =
-- Get the proof steps needed to prove that the lifetime l is current
stmtEmbedImplM (getLifetimeCurrentPerms l) >>>= \(Some cur_perms) ->
-- Prove that the required permissions
stmtEmbedImplM (proveLifetimeCurrent cur_perms) >>>
-- Perform the computation
m cur_perms >>>= \a ->
-- Recombine the proof that the lifetime is current
stmtEmbedImplM (recombineLifetimeCurrentPerms cur_perms) >>>
-- Finally, return the result
pure a
-- | Emit a 'TypedLLVMLoad' instruction, assuming the given LLVM field
-- permission is on the top of the stack. Prove the required lifetime
-- permissions as part of this process, and pop the resulting lifetime
-- permission off the stack before returning. Return the resulting return
-- register.
emitTypedLLVMLoad ::
forall w sz arch cblocks blocks tops rets ps.
(HasPtrWidth w, 1 <= sz, KnownNat sz) =>
Proxy arch -> ProgramLoc ->
TypedReg (LLVMPointerType w) -> LLVMFieldPerm w sz -> DistPerms ps ->
StmtPermCheckM LLVM cblocks blocks tops rets
(ps :> LLVMPointerType w :> LLVMPointerType sz)
(ps :> LLVMPointerType w)
(Name (LLVMPointerType sz))
emitTypedLLVMLoad _ loc treg fp ps =
withLifetimeCurrentPerms (llvmFieldLifetime fp) $ \cur_perms ->
emitLLVMStmt knownRepr Nothing loc (TypedLLVMLoad treg fp ps cur_perms)
-- | Emit a 'TypedLLVMStore' instruction, assuming the given LLVM field
-- permission is on the top of the stack. Prove the required lifetime
-- permissions as part of this process, and pop the resulting lifetime
-- permission off the stack before returning. Return the resulting return
-- register of unit type.
emitTypedLLVMStore ::
(HasPtrWidth w, 1 <= sz, KnownNat sz) =>
Proxy arch ->
Maybe String ->
ProgramLoc ->
TypedReg (LLVMPointerType w) ->
LLVMFieldPerm w sz ->
PermExpr (LLVMPointerType sz) ->
DistPerms ps ->
StmtPermCheckM LLVM cblocks blocks tops rets
(ps :> LLVMPointerType w)
(ps :> LLVMPointerType w)
(Name UnitType)
emitTypedLLVMStore _ name loc treg_ptr fp e ps =
withLifetimeCurrentPerms (llvmFieldLifetime fp) $ \cur_perms ->
emitLLVMStmt knownRepr name loc (TypedLLVMStore treg_ptr fp e ps cur_perms)
open :: HasPtrWidth wptr => f (LLVMPointerType wptr) -> NatRepr wptr
open _ = ?ptrWidth
-- | Typecheck a statement and emit it in the current statement sequence,
-- starting and ending with an empty stack of distinguished permissions
tcEmitLLVMStmt ::
forall arch ctx tp cblocks blocks tops rets.
Proxy arch ->
CtxTrans ctx ->
ProgramLoc ->
LLVMStmt (Reg ctx) tp ->
StmtPermCheckM LLVM cblocks blocks tops rets RNil RNil
(CtxTrans (ctx ::> tp))
-- Type-check a load of an LLVM pointer by requiring a ptr permission and using
-- TypedLLVMLoad, rounding up the size of the load to a whole number of bytes
tcEmitLLVMStmt arch ctx loc (LLVM_Load _ ptr tp storage _)
| sz_bits <- bytesToBits $ storageTypeSize storage
, sz_rnd_bits <- 8 * ceil_div sz_bits 8
, Just (Some (sz_rnd :: NatRepr sz_rnd)) <- someNat sz_rnd_bits
, Left LeqProof <- decideLeq (knownNat @1) sz_rnd
= withKnownNat ?ptrWidth $ withKnownNat sz_rnd $
let tptr = tcReg ctx ptr in
-- Prove [l]ptr((sz_rnd,0,rw) |-> eq(y)) for some l, rw, and y
stmtProvePerm tptr (llvmPtr0EqExPerm sz_rnd) >>>= \impl_res ->
let fp = subst impl_res (llvmPtr0EqEx sz_rnd) in
-- Emit a TypedLLVMLoad instruction
emitTypedLLVMLoad arch loc tptr fp DistPermsNil >>>= \z ->
-- Recombine the resulting permissions onto the stack
stmtRecombinePerms >>>
-- Convert the return value to the requested type and return it
(convertRegType knownRepr loc (TypedReg z) knownRepr tp >>>= \ret ->
pure (addCtxName ctx $ typedRegVar ret))
-- FIXME: add a case for stores of smaller-than-byte-sized values
-- Type-check a store of an LLVM pointer
tcEmitLLVMStmt arch ctx loc (LLVM_Store _ ptr tp storage _ val)
| Just (Some sz) <- someNat $ bytesToBits $ storageTypeSize storage
, Left LeqProof <- decideLeq (knownNat @1) sz =
withKnownNat ?ptrWidth $
withKnownNat sz $
let tptr = tcReg ctx ptr
tval = tcReg ctx val in
convertRegType knownRepr loc tval tp (LLVMPointerRepr sz) >>>= \tval' ->
stmtProvePerm tptr (llvmWriteTrueExLPerm sz $ bvInt 0) >>>= \sbst ->
let l = substLookup sbst Member_Base in
let fp = llvmFieldWriteTrueL sz (bvInt 0) l in
nextDebugName >>>= \name ->
emitTypedLLVMStore arch name loc tptr fp
(PExpr_Var $ typedRegVar tval') DistPermsNil >>>= \z ->
stmtRecombinePerms >>>
pure (addCtxName ctx z)
-- Type-check a clear instruction by getting the list of field permissions
-- returned by 'llvmFieldsOfSize' and storing word 0 to each of them
tcEmitLLVMStmt arch ctx loc (LLVM_MemClear _ (ptr :: Reg ctx (LLVMPointerType wptr)) bytes) =
withKnownNat ?ptrWidth $
let tptr = tcReg ctx ptr
flds = llvmFieldsOfSize @wptr knownNat (bytesToInteger bytes) in
-- For each field perm, prove it and write 0 to it
(forM_ @_ @_ @_ @() flds $ \case
Perm_LLVMField fp ->
stmtProvePerm tptr (emptyMb $ ValPerm_Conj1 $ Perm_LLVMField fp) >>>
emitTypedLLVMStore arch Nothing loc tptr fp (PExpr_LLVMWord (bvInt 0)) DistPermsNil >>>
stmtRecombinePerms >>>
pure ()
_ -> error "Unexpected return value from llvmFieldsOfSize") >>>
-- Return a fresh unit variable
dbgNames >>= \names ->
emitStmt knownRepr names loc
(TypedSetReg knownRepr $
TypedExpr EmptyApp
(Just PExpr_Unit)) >>>= \(MNil :>: z) ->
stmtRecombinePerms >>>
pure (addCtxName ctx z)
{-
-- Type-check a non-empty mem-clear instruction by writing a 0 to the last word
-- and then recursively clearing all but the last word
-- FIXME: add support for using non-word-size ptr perms with MemClear
tcEmitLLVMStmt arch ctx loc (LLVM_MemClear mem ptr bytes) =
let tptr = tcReg ctx ptr
bytes' = bytes - bitsToBytes (intValue (archWidth arch))
off = bytesToInteger bytes' in
stmtProvePerm tptr (llvmWriteTrueExLPerm
(archWidth arch) (bvInt off)) >>>= \sbst ->
let l = substLookup sbst Member_Base in
let fp = llvmFieldWriteTrueL (archWidth arch) (bvInt off) l in
emitTypedLLVMStore arch loc tptr fp (PExpr_LLVMWord $
bvInt 0) DistPermsNil >>>
stmtRecombinePerms >>>
tcEmitLLVMStmt arch ctx loc (LLVM_MemClear mem ptr bytes')
-}
-- Type-check an alloca instruction
tcEmitLLVMStmt _arch ctx loc (LLVM_Alloca w _ sz_reg _ _) =
withKnownNat w $
let sz_treg = tcReg ctx sz_reg in
getFramePtr w >>>= \maybe_fp ->
maybe (pure ValPerm_True) getRegPerm maybe_fp >>>= \fp_perm ->
resolveConstant sz_treg >>>= \maybe_sz ->
case (maybe_fp, fp_perm, maybe_sz) of
(Just fp, ValPerm_Conj [Perm_LLVMFrame fperms], Just sz) ->
stmtProvePerm fp (emptyMb fp_perm) >>>= \_ ->
nextDebugName >>>= \name ->
emitLLVMStmt knownRepr name loc
(TypedLLVMAlloca fp fperms sz) >>>= \y ->
stmtRecombinePerms >>>
pure (addCtxName ctx y)
(_, _, Nothing) ->
stmtFailM (\i -> pretty "LLVM_Alloca: non-constant size for"
<+> permPretty i sz_treg)
(Just fp, p, _) ->
stmtFailM (\i -> pretty "LLVM_Alloca: expected LLVM frame perm for "
<+> permPretty i fp <> pretty ", found perm"
<+> permPretty i p)
(Nothing, _, _) ->
stmtFailM (const $ pretty "LLVM_Alloca: no frame pointer set")
-- Type-check a push frame instruction
tcEmitLLVMStmt _arch ctx loc (LLVM_PushFrame _ _) =
fmap stArchWidth top_get >>>= \SomePtrWidth ->
withKnownNat ?ptrWidth $
emitLLVMStmt knownRepr Nothing loc TypedLLVMCreateFrame >>>= \fp ->
setFramePtr ?ptrWidth (TypedReg fp) >>>
stmtRecombinePerms >>>
dbgNames >>>= \names ->
emitStmt knownRepr names loc
(TypedSetReg knownRepr
(TypedExpr EmptyApp Nothing)) >>>= \(MNil :>: y) ->
stmtRecombinePerms >>>
pure (addCtxName ctx y)
-- Type-check a pop frame instruction
tcEmitLLVMStmt _arch ctx loc (LLVM_PopFrame _) =
fmap stArchWidth top_get >>>= \SomePtrWidth ->
getFramePtr ?ptrWidth >>>= \maybe_fp ->
maybe (pure ValPerm_True) getRegPerm maybe_fp >>>= \fp_perm ->
case (maybe_fp, fp_perm) of
(Just fp, ValPerm_Conj [Perm_LLVMFrame fperms])
| Some del_perms <- llvmFrameDeletionPerms fperms ->
stmtProvePerms knownRepr (distPermsToExDistPerms del_perms) >>>= \_ ->
stmtProvePerm fp (emptyMb fp_perm) >>>= \_ ->
nextDebugName >>>= \name ->
emitLLVMStmt knownRepr name loc
(TypedLLVMDeleteFrame fp fperms del_perms) >>>= \y ->
modify (\st -> st { stExtState = PermCheckExtState_LLVM Nothing }) >>>
pure (addCtxName ctx y)
_ -> stmtFailM (const $ pretty "LLVM_PopFrame: no frame perms")
-- Type-check a pointer offset instruction by emitting OffsetLLVMValue
tcEmitLLVMStmt _arch ctx loc (LLVM_PtrAddOffset _w _ ptr off) =
let tptr = tcReg ctx ptr
toff = tcReg ctx off in
getRegEqualsExpr toff >>>= \off_expr ->
nextDebugName >>>= \name ->
withKnownNat ?ptrWidth $
emitLLVMStmt knownRepr name loc (OffsetLLVMValue tptr off_expr) >>>= \ret ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- Type-check a LoadHandle instruction by looking for a function pointer perm
tcEmitLLVMStmt _arch ctx loc (LLVM_LoadHandle _ _ ptr args ret) =
let tptr = tcReg ctx ptr
x = typedRegVar tptr in
withKnownNat ?ptrWidth $
getAtomicLLVMPerms tptr >>>= \ps ->
case findIndex (\p -> case p of
Perm_LLVMFunPtr _ _ -> True
_ -> False) ps of
Just i
| Perm_LLVMFunPtr tp p <- ps!!i
, Just Refl <- testEquality tp (FunctionHandleRepr args ret) ->
stmtEmbedImplM (implCopyConjM x ps i >>>
recombinePerm x (ValPerm_Conj ps)) >>>
nextDebugName >>>= \name ->
emitLLVMStmt (FunctionHandleRepr args ret) name loc
(TypedLLVMLoadHandle tptr tp p) >>>= \ret' ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret')
_ -> stmtFailM (const $ pretty "LLVM_PopFrame: no function pointer perms")
-- Type-check a ResolveGlobal instruction by looking up the global symbol
tcEmitLLVMStmt _arch ctx loc (LLVM_ResolveGlobal w _ gsym) =
(stPermEnv <$> top_get) >>>= \env ->
case lookupGlobalSymbol env gsym w of
Just (p, _) ->
nextDebugName >>>= \name ->
withKnownNat ?ptrWidth $
emitLLVMStmt knownRepr name loc (TypedLLVMResolveGlobal gsym p) >>>= \ret ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
Nothing ->
stmtFailM (const $ pretty ("LLVM_ResolveGlobal: no perms for global "
++ globalSymbolName gsym))
{-
tcEmitLLVMStmt _arch ctx loc (LLVM_PtrLe _ r1 r2) =
let x1 = tcReg ctx r1
x2 = tcReg ctx r2 in
getRegEqualsExpr x1 >>>= \e1 ->
getRegEqualsExpr x2 >>>= \e2 ->
case (e1, e2) of
-- If both variables equal words, then compare the words
--
-- FIXME: if we have bvEq e1' e2' or not (bvCouldEqual e1' e2') then we
-- should return a known Boolean value in place of the Nothing
(PExpr_LLVMWord e1', PExpr_LLVMWord e2') ->
emitStmt knownRepr loc (TypedSetRegPermExpr
knownRepr e1') >>>= \(_ :>: n1) ->
stmtRecombinePerms >>>
emitStmt knownRepr loc (TypedSetRegPermExpr
knownRepr e2') >>>= \(_ :>: n2) ->
stmtRecombinePerms >>>
emitStmt knownRepr loc (TypedSetReg knownRepr $
TypedExpr (BVUle knownRepr
(RegWithVal (TypedReg n1) e1')
(RegWithVal (TypedReg n1) e2'))
Nothing) >>>= \(_ :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- If both variables equal x+off for the same x, compare the offsets
--
-- FIXME: test off1 == off2 like above
(asLLVMOffset -> Just (x1', off1), asLLVMOffset -> Just (x2', off2))
| x1' == x2' ->
emitStmt knownRepr loc (TypedSetRegPermExpr
knownRepr off1) >>>= \(_ :>: n1) ->
stmtRecombinePerms >>>
emitStmt knownRepr loc (TypedSetRegPermExpr
knownRepr off2) >>>= \(_ :>: n2) ->
stmtRecombinePerms >>>
emitStmt knownRepr loc (TypedSetReg knownRepr $
TypedExpr (BVUle knownRepr
(RegWithVal (TypedReg n1) off1)
(RegWithVal (TypedReg n1) off2))
Nothing) >>>= \(_ :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- If one variable is a word and the other is not known to be a word, then
-- that other has to be a pointer, in which case the comparison will
-- definitely fail. Otherwise we cannot compare them and we fail.
(PExpr_LLVMWord e, asLLVMOffset -> Just (x', _)) ->
let r' = TypedReg x' in
stmtProvePerm r' (emptyMb $ ValPerm_Conj1 Perm_IsLLVMPtr) >>>
emitLLVMStmt knownRepr loc (AssertLLVMPtr r') >>>
emitStmt knownRepr loc (TypedSetReg knownRepr $
TypedExpr (BoolLit False)
Nothing) >>>= \(_ :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- Symmetrical version of the above case
(asLLVMOffset -> Just (x', _), PExpr_LLVMWord e) ->
let r' = TypedReg x' in
stmtProvePerm r' (emptyMb $ ValPerm_Conj1 Perm_IsLLVMPtr) >>>
emitLLVMStmt knownRepr loc (AssertLLVMPtr r') >>>
emitStmt knownRepr loc (TypedSetReg knownRepr $
TypedExpr (BoolLit False)
Nothing) >>>= \(_ :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- If we don't know any relationship between the two registers, then we
-- fail, because there is no way to compare pointers in the translation
_ ->
stmtFailM (\i ->
sep [pretty "Could not compare LLVM pointer values",
permPretty i x1, pretty "and", permPretty i x2])
-}
tcEmitLLVMStmt _arch ctx loc (LLVM_PtrEq _ (r1 :: Reg ctx (LLVMPointerType wptr)) r2) =
let x1 = tcReg ctx r1
x2 = tcReg ctx r2 in
withKnownNat (?ptrWidth :: NatRepr wptr) $
getRegEqualsExpr x1 >>>= \e1 ->
getRegEqualsExpr x2 >>>= \e2 ->
case (e1, e2) of
-- If both variables equal words, then compare the words
--
-- FIXME: if we have bvEq e1' e2' or not (bvCouldEqual e1' e2') then we
-- should return a known Boolean value in place of the Nothing
(PExpr_LLVMWord e1', PExpr_LLVMWord e2') ->
emitStmt knownRepr noNames loc (TypedSetRegPermExpr
knownRepr e1') >>>= \(MNil :>: n1) ->
stmtRecombinePerms >>>
emitStmt knownRepr noNames loc (TypedSetRegPermExpr
knownRepr e2') >>>= \(MNil :>: n2) ->
stmtRecombinePerms >>>
dbgNames >>>= \names ->
emitStmt knownRepr names loc
(TypedSetReg knownRepr $
TypedExpr (BaseIsEq knownRepr
(RegWithVal (TypedReg n1) e1')
(RegWithVal (TypedReg n2) e2'))
Nothing) >>>= \(MNil :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- If both variables equal x+off for the same x, compare the offsets
--
-- FIXME: test off1 == off2 like above
(asLLVMOffset -> Just (x1', off1), asLLVMOffset -> Just (x2', off2))
| x1' == x2' ->
emitStmt knownRepr noNames loc (TypedSetRegPermExpr
knownRepr off1) >>>= \(MNil :>: n1) ->
stmtRecombinePerms >>>
emitStmt knownRepr noNames loc (TypedSetRegPermExpr
knownRepr off2) >>>= \(MNil :>: n2) ->
stmtRecombinePerms >>>
dbgNames >>>= \names ->
emitStmt knownRepr names loc
(TypedSetReg knownRepr $
TypedExpr (BaseIsEq knownRepr
(RegWithVal (TypedReg n1) off1)
(RegWithVal (TypedReg n2) off2))
Nothing) >>>= \(MNil :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- If one variable is a word and the other is not known to be a word, then
-- that other has to be a pointer, in which case the comparison will
-- definitely fail. Otherwise we cannot compare them and we fail.
(PExpr_LLVMWord _e, asLLVMOffset -> Just (x', _)) ->
let r' = TypedReg x' in
stmtProvePerm r' (emptyMb $ ValPerm_Conj1 Perm_IsLLVMPtr) >>>
emitLLVMStmt knownRepr Nothing loc (AssertLLVMPtr r') >>>
dbgNames >>= \names ->
emitStmt knownRepr names loc
(TypedSetReg knownRepr $
TypedExpr (BoolLit False)
Nothing) >>>= \(MNil :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- Symmetrical version of the above case
(asLLVMOffset -> Just (x', _), PExpr_LLVMWord _e) ->
let r' = TypedReg x' in
stmtProvePerm r' (emptyMb $ ValPerm_Conj1 Perm_IsLLVMPtr) >>>
emitLLVMStmt knownRepr Nothing loc (AssertLLVMPtr r') >>>
dbgNames >>= \names ->
emitStmt knownRepr names loc
(TypedSetReg knownRepr $
TypedExpr (BoolLit False)
Nothing) >>>= \(MNil :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
-- If we don't know any relationship between the two registers, then we
-- fail, because there is no way to compare pointers in the translation
_ ->
stmtFailM (\i ->
sep [pretty "Could not compare LLVM pointer values",
permPretty i x1, pretty "and", permPretty i x2])
tcEmitLLVMStmt _arch ctx loc LLVM_Debug{} =
-- let tptr = tcReg ctx ptr in
dbgNames >>= \names ->
emitStmt knownRepr names loc
(TypedSetReg knownRepr (TypedExpr EmptyApp Nothing)) >>>= \(MNil :>: ret) ->
stmtRecombinePerms >>>
pure (addCtxName ctx ret)
tcEmitLLVMStmt _arch _ctx _loc stmt =
error ("tcEmitLLVMStmt: unimplemented statement - " ++ show (ppApp (\_ -> mempty) stmt))
-- FIXME HERE: need to handle PtrEq, PtrLe, and PtrSubtract
----------------------------------------------------------------------
-- * Permission Checking for Jump Targets and Termination Statements
----------------------------------------------------------------------
-- | Cast the primary permission for @x@ using any equality permissions on
-- variables *not* in the supplied list of determined variables. The idea here
-- is that we are trying to simplify out and remove un-determined variables.
castUnDetVarsForVar :: NuMatchingAny1 r => NameSet CrucibleType -> ExprVar a ->
ImplM vars s r RNil RNil ()
castUnDetVarsForVar det_vars x =
(view varPermMap <$> getPerms) >>>= \var_perm_map ->
getPerm x >>>= \p ->
let nondet_perms =
NameMap.fromList $
filter (\(NameMap.NameAndElem y _) -> not $ NameSet.member y det_vars) $
NameMap.assocs var_perm_map in
let eqp = someEqProofFromSubst nondet_perms p in
implPushM x p >>>
implCastPermM Proxy x eqp >>>
implPopM x (someEqProofRHS eqp)
-- | Simplify and drop permissions @p@ on variable @x@ so they only depend on
-- the determined variables given in the supplied list
simplify1PermForDetVars :: NuMatchingAny1 r =>
NameSet CrucibleType -> Name a -> ValuePerm a ->
ImplM vars s r RNil RNil ()
-- If the permissions contain an array permission with undetermined borrows,
-- return those undetermined borrows if possible
--
-- FIXME: we should only return borrows if we can; currently, if there are
-- borrows we can't return, we fail here, and should instead just drop the array
-- permission and keep going. To do this, we have to make a way to try to prove
-- a permission, either by changing the ImplM monad or by adding a notion of
-- local implication proofs where failure is scoped inside a proof
simplify1PermForDetVars det_vars x (ValPerm_Conj ps)
| Just i <-
findIndex
(\case
Perm_LLVMArray ap ->
any (\b -> not (nameSetIsSubsetOf
(freeVars b) det_vars)) (llvmArrayBorrows ap)
_ -> False) ps
, Perm_LLVMArray ap <- ps!!i
, det_borrows <- filter (\b -> nameSetIsSubsetOf
(freeVars b) det_vars) (llvmArrayBorrows ap)
, ret_p <- ValPerm_Conj1 $ Perm_LLVMArray $ ap { llvmArrayBorrows =
det_borrows } =
mbVarsM ret_p >>>= \mb_ret_p ->
proveVarImpl x mb_ret_p >>>
(getTopDistPerm x >>>= recombinePerm x) >>>
getPerm x >>>= \new_p ->
simplify1PermForDetVars det_vars x new_p
-- For permission l:lowned[ls](ps_in -o ps_out) where l or some free variable in
-- ps_in or ps_out is not determined, end l
simplify1PermForDetVars det_vars l (ValPerm_LOwned _ ps_in ps_out)
| vars <- NameSet.insert l $ freeVars (ps_in,ps_out)
, not $ NameSet.nameSetIsSubsetOf vars det_vars
= implEndLifetimeRecM l
-- For lowned permission l:lowned[ls](ps_in -o ps_out), end any lifetimes in ls
-- that are not determined and remove them from the lowned permission for ls
simplify1PermForDetVars det_vars l (ValPerm_LOwned ls _ _)
| l':_ <- flip mapMaybe ls (asVar >=> \l' ->
if NameSet.member l' det_vars then Nothing
else return l') =
implEndLifetimeRecM l' >>>
getPerm l >>>= \p' -> simplify1PermForDetVars det_vars l p'
-- If none of the above cases match but p has only determined free variables,
-- just leave p as is
simplify1PermForDetVars det_vars _ p
| nameSetIsSubsetOf (freeVars p) det_vars = pure ()
-- If p is an equality permission to a word with undetermined variables,
-- existentially quantify over the word
simplify1PermForDetVars _ x p@(ValPerm_Eq (PExpr_LLVMWord e)) =
let mb_p = nu $ \z -> ValPerm_Eq $ PExpr_LLVMWord $ PExpr_Var z in
implPushM x p >>> introExistsM x e mb_p >>>
implPopM x (ValPerm_Exists mb_p)
-- Otherwise, drop p, because it is not determined
simplify1PermForDetVars _det_vars x p =
implPushM x p >>> implDropM x p
-- | Simplify and drop permissions so they only depend on the determined
-- variables given in the supplied list
simplifyPermsForDetVars :: NuMatchingAny1 r => [SomeName CrucibleType] ->
ImplM vars s r RNil RNil ()
simplifyPermsForDetVars det_vars_list =
let det_vars = NameSet.fromList det_vars_list in
(permSetVars <$> getPerms) >>>= \vars ->
mapM_ (\(SomeName x) ->
castUnDetVarsForVar det_vars x >>>
getPerm x >>>= simplify1PermForDetVars det_vars x) vars
-- | If @x@ has permission @eq(llvmword e)@ where @e@ is not a needed variable
-- (in the supplied set), replace that perm with an existential permission
-- @x:exists z.eq(llvmword z)@. Similarly, if @x@ has permission @eq(e)@ where
-- @e@ is a literal, replace that permission with just @true@. Also do this
-- inside pointer permissions, by recursively destructing any pointer
-- permissions @ptr((rw,off) |-> p)@ to the permission @ptr((rw,off) |-> eq(y))@
-- for fresh variable @y@ and generalizing unneeded word equalities for @y@.
generalizeUnneededEqPerms1 ::
NuMatchingAny1 r => NameSet CrucibleType -> Name a -> ValuePerm a ->
ImplM vars s r ps ps ()
-- For x:eq(y) for needed variable y, do nothing
generalizeUnneededEqPerms1 needed_vars _ (ValPerm_Eq (PExpr_Var y))
| NameSet.member y needed_vars = pure ()
generalizeUnneededEqPerms1 needed_vars _ (ValPerm_Eq e@(PExpr_BV _ _))
| PExpr_Var y <- normalizeBVExpr e
, NameSet.member y needed_vars = pure ()
-- Similarly, for x:eq(llvmword y) for needed variable y, do nothing
generalizeUnneededEqPerms1 needed_vars _ (ValPerm_Eq (PExpr_LLVMWord e))
| PExpr_Var y <- normalizeBVExpr e
, NameSet.member y needed_vars = pure ()
generalizeUnneededEqPerms1 _needed_vars x p@(ValPerm_Eq (PExpr_LLVMWord e)) =
let mb_eq = nu $ \z -> ValPerm_Eq $ PExpr_LLVMWord $ PExpr_Var z in
implPushM x p >>>
introExistsM x e mb_eq >>>
implPopM x (ValPerm_Exists mb_eq)
-- Similarly, for x:eq(y &+ off) for needed variable y, do nothing
generalizeUnneededEqPerms1 needed_vars _ (ValPerm_Eq (PExpr_LLVMOffset y _))
| NameSet.member y needed_vars = pure ()
-- For x:eq(e) where e is a literal, just drop the eq(e) permission
generalizeUnneededEqPerms1 _needed_vars x p@(ValPerm_Eq PExpr_Unit) =
implPushM x p >>> implDropM x p
generalizeUnneededEqPerms1 _needed_vars x p@(ValPerm_Eq (PExpr_Nat _)) =
implPushM x p >>> implDropM x p
generalizeUnneededEqPerms1 _needed_vars x p@(ValPerm_Eq (PExpr_Bool _)) =
implPushM x p >>> implDropM x p
-- If x:p1 * ... * pn, generalize the contents of field permissions in the pis
generalizeUnneededEqPerms1 needed_vars x p@(ValPerm_Conj ps)
| Just i <- findIndex isLLVMFieldPerm ps
, Perm_LLVMField fp <- ps!!i
, y_p <- llvmFieldContents fp
, ps' <- deleteNth i ps
, (case y_p of
ValPerm_Eq (PExpr_Var _) -> False
_ -> True) =
implPushM x p >>> implExtractConjM x ps i >>>
implPopM x (ValPerm_Conj ps') >>>
implElimLLVMFieldContentsM x fp >>>= \y ->
let fp' = fp { llvmFieldContents = ValPerm_Eq (PExpr_Var y) } in
implPushM x (ValPerm_Conj ps') >>>
implInsertConjM x (Perm_LLVMField fp') ps' i >>>
implPopM x (ValPerm_Conj (take i ps' ++ Perm_LLVMField fp' : drop i ps')) >>>
generalizeUnneededEqPerms1 needed_vars y y_p
generalizeUnneededEqPerms1 _ _ _ = pure ()
-- | Find all permissions of the form @x:eq(llvmword e)@ other than those where
-- @e@ is a needed variable, and replace them with @x:exists z.eq(llvmword z)@
generalizeUnneededEqPerms :: NuMatchingAny1 r => ImplM vars s r ps ps ()
generalizeUnneededEqPerms =
do Some var_perms <- permSetAllVarPerms <$> getPerms
let needed_vars = neededVars var_perms
foldDistPerms
(\m x p -> m >> generalizeUnneededEqPerms1 needed_vars x p)
(pure ())
var_perms
-- | Type-check a Crucible jump target
tcJumpTarget :: PermCheckExtC ext => CtxTrans ctx -> JumpTarget cblocks ctx ->
StmtPermCheckM ext cblocks blocks tops rets RNil RNil
(AnnotPermImpl (TypedJumpTarget blocks tops) RNil)
tcJumpTarget ctx (JumpTarget blkID args_tps args) =
top_get >>= \top_st ->
get >>= \st ->
gets (permCheckExtStateNames . stExtState) >>= \(Some ext_ns) ->
tcBlockID blkID >>>= \tpBlkID ->
-- Step 0: run all of the following steps inside a local ImplM computation,
-- which we run in order to get out an AnnotPermImpl. This ensures that any
-- simplifications or other changes to permissions that are performed by this
-- computation are kept inside this local scope, which in turn is necessary so
-- that when we type-check a condition branch instruction (Br), the
-- simplifications of each branch do not affect each other.
pcmRunImplImplM CruCtxNil mempty $
-- NOTE: the args all must be distinct variables (this is required by
-- implPushOrReflMultiM below and also the translation of jump targets)
implFreshenNames (typedRegsToVars $ tcRegs ctx args) >>>= \args_ns ->
let tops_ns = stTopVars st
tops_args_ns = RL.append tops_ns args_ns
tops_args_ext_ns = RL.append tops_args_ns ext_ns in
-- Step 1: Compute the variables whose values are determined by the
-- permissions on the top and normal arguments as the starting point for
-- figuring out our ghost variables. The determined variables are the only
-- variables that could possibly be inferred by a caller, and they are the
-- only variables that could actually be accessed by the block we are calling,
-- so we should not be really giving up any permissions we need.
let orig_cur_perms = stCurPerms st
det_vars =
namesToNamesList tops_args_ext_ns ++
determinedVars orig_cur_perms tops_args_ext_ns in
-- Step 2: Simplify and drop permissions so they do not depend on undetermined
-- variables
simplifyPermsForDetVars det_vars >>>
-- Step 3: if gen_perms_hint is set, generalize any permissions of the form
-- eq(llvmword e) to exists z.eq(llvmword z) as long as they do not determine
-- a variable that we need, i.e., as long as they are not of the form
-- eq(llvmword x) for a variable x that we need
-- (if gen_perms_hint then generalizeUnneededEqPerms else pure ()) >>>
-- Step 4: Compute the ghost variables for the target block as those variables
-- whose values are determined by the permissions on the top and normal
-- arguments after our above simplifications, adding in the extension-specific
-- variables as well
getPerms >>>= \cur_perms ->
case namesListToNames $ determinedVars cur_perms tops_args_ext_ns of
SomeRAssign ghosts_ns' ->
localImplM $
let ghosts_ns = RL.append ext_ns ghosts_ns'
tops_perms = varPermsMulti tops_ns cur_perms
tops_set = NameSet.fromList $ namesToNamesList tops_ns
ghosts_perms = varPermsMulti ghosts_ns cur_perms
args_perms =
buildDistPerms (\n -> if NameSet.member n tops_set
then ValPerm_Eq (PExpr_Var n)
else cur_perms ^. varPerm n) args_ns
perms_in = appendDistPerms (appendDistPerms
tops_perms args_perms) ghosts_perms in
implTraceM (\i ->
pretty ("tcJumpTarget " ++ show blkID) <>
{- (if gen_perms_hint then pretty "(gen)" else emptyDoc) <> -}
line <>
(case permSetAllVarPerms orig_cur_perms of
Some all_perms ->
pretty "Current perms:" <+>
align (permPretty i all_perms))
<> line <>
pretty "Determined vars:"<+>
align (list (map (permPretty i) det_vars)) <> line <>
pretty "Input perms:" <+>
hang 2 (permPretty i perms_in)) >>>
-- Step 5: abstract all the variables out of the input permissions. Note
-- that abstractVars uses the left-most occurrence of any variable that
-- occurs multiple times in the variable list and we want our eq perms for
-- our args to map to our tops, not our args, so this order works for what
-- we want
(case abstractVars
(RL.append (RL.append tops_ns args_ns) ghosts_ns)
(distPermsToValuePerms perms_in) of
Just ps -> pure ps
Nothing
| SomeRAssign orig_det_vars <- namesListToNames det_vars
, orig_perms <- varPermsMulti orig_det_vars orig_cur_perms ->
implTraceM
(\i ->
pretty ("tcJumpTarget: unexpected free variable in perms_in:\n"
++ renderDoc (permPretty i perms_in)
++ "\norig_perms:\n"
++ renderDoc (permPretty i orig_perms))) >>>= \str ->
error str) >>>= \cl_mb_perms_in ->
-- Step 6: insert a new block entrypoint that has all the permissions
-- we constructed above as input permissions
implGetVarTypes ghosts_ns >>>= \ghosts_tps ->
(case stCurEntry st of
Some curEntryID ->
lift $ flip runReaderT top_st $
callBlockWithPerms curEntryID tpBlkID
ghosts_tps cl_mb_perms_in) >>>= \siteID ->
implTraceM (\_ ->
pretty ("tcJumpTarget " ++ show blkID ++ " siteID =" ++
show siteID)) >>>
-- Step 7: return a TypedJumpTarget inside a PermImpl that proves all the
-- required input permissions from the current permission set by copying
-- the existing permissions into the current distinguished perms, except
-- for the eq permissions for real arguments, which are proved by
-- reflexivity.
implWithoutTracingM (implPushOrReflMultiM perms_in) >>>
pure (PermImpl_Done $
TypedJumpTarget siteID Proxy (mkCruCtx args_tps) perms_in)
-- | Type-check a termination statement
tcTermStmt :: PermCheckExtC ext => CtxTrans ctx ->
TermStmt cblocks ret ctx ->
StmtPermCheckM ext cblocks blocks tops (gouts :> ret) RNil RNil
(TypedTermStmt blocks tops (gouts :> ret) RNil)
tcTermStmt ctx (Jump tgt) =
TypedJump <$> tcJumpTarget ctx tgt
tcTermStmt ctx (Br reg tgt1 tgt2) =
-- FIXME: Instead of mapping Br to TypedJump when the jump target is known,
-- make a version of TypedBr that still stores the JumpTargets of never-taken
-- branches in order to allow translating back to untyped Crucible
let treg = tcReg ctx reg in
getRegEqualsExpr treg >>>= \treg_expr ->
case treg_expr of
PExpr_Bool True ->
stmtTraceM (const $ pretty "tcTermStmt: br reg known to be true!") >>
(TypedJump <$> tcJumpTarget ctx tgt1)
PExpr_Bool False ->
stmtTraceM (const $ pretty "tcTermStmt: br reg known to be false!") >>
(TypedJump <$> tcJumpTarget ctx tgt2)
_ ->
stmtTraceM (const $ pretty
"tcTermStmt: br reg unknown, checking both branches...") >>
(TypedBr treg <$> tcJumpTarget ctx tgt1 <*> tcJumpTarget ctx tgt2)
tcTermStmt ctx (Return reg) =
let ret_n = typedRegVar $ tcReg ctx reg in
get >>>= \st ->
top_get >>>= \top_st ->
let tops = stTopVars st
rets = stRetTypes top_st
CruCtxCons gouts _ = rets
mb_ret_perms =
give (cruCtxProxies rets) $
varSubst (permVarSubstOfNames tops) $
mbSeparate (cruCtxProxies rets) $
mbValuePermsToDistPerms (stRetPerms top_st)
mb_req_perms =
fmap (varSubst (singletonVarSubst ret_n)) $
mbSeparate (MNil :>: Proxy) mb_ret_perms
err = ppProofError (stPPInfo st) mb_req_perms in
mapM (\(SomeName x) -> ppRelevantPerms $ TypedReg x) (NameSet.toList $
freeVars mb_req_perms)
>>>= \pps_before ->
stmtTraceM (\i ->
pretty "Type-checking return statement" <> line <>
pretty "Current perms:" <> softline <>
ppCommaSep pps_before <> line <>
pretty "Required perms:" <> softline <>
permPretty i mb_req_perms) >>>
TypedReturn <$>
pcmRunImplM gouts err
(\gouts_ns -> TypedRet Refl rets (gouts_ns :>: ret_n) mb_ret_perms)
(proveVarsImplVarEVars mb_req_perms)
tcTermStmt ctx (ErrorStmt reg) =
let treg = tcReg ctx reg in
getRegPerm treg >>>= \treg_p ->
let maybe_str = case treg_p of
ValPerm_Eq (PExpr_String str) -> Just str
_ -> Nothing in
pure $ TypedErrorStmt maybe_str treg
tcTermStmt _ tstmt =
error ("tcTermStmt: unhandled termination statement: "
++ show (pretty tstmt))
----------------------------------------------------------------------
-- * Permission Checking for Blocks and Sequences of Statements
----------------------------------------------------------------------
-- | Translate and emit a Crucible statement sequence, starting and ending with
-- an empty stack of distinguished permissions
tcEmitStmtSeq ::
(PermCheckExtC ext, KnownRepr ExtRepr ext) =>
[Maybe String] ->
CtxTrans ctx ->
StmtSeq ext cblocks ret ctx ->
PermCheckM ext cblocks blocks tops (gouts :> ret)
() RNil
(TypedStmtSeq ext blocks tops (gouts :> ret) RNil) RNil
()
tcEmitStmtSeq names ctx (ConsStmt loc stmt stmts) =
setErrorPrefix names loc (ppStmt (Ctx.size ctx) stmt) ctx (stmtInputRegs stmt) >>>
tcEmitStmt ctx loc stmt >>>= \ctx' -> tcEmitStmtSeq names ctx' stmts
tcEmitStmtSeq names ctx (TermStmt loc tstmt) =
setErrorPrefix names loc (pretty tstmt) ctx (termStmtRegs tstmt) >>>
tcTermStmt ctx tstmt >>>= \typed_tstmt ->
gmapRet (>> return (TypedTermStmt loc typed_tstmt))
-- | Type-check the body of a Crucible block as the body of an entrypoint
tcBlockEntryBody ::
(PermCheckExtC ext, KnownRepr ExtRepr ext) =>
[Maybe String] ->
Block ext cblocks ret args ->
TypedEntry TCPhase ext blocks tops (gouts :> ret) (CtxToRList args) ghosts ->
TopPermCheckM ext cblocks blocks tops (gouts :> ret)
(Mb ((tops :++: CtxToRList args) :++: ghosts)
(TypedStmtSeq ext blocks tops (gouts :> ret)
((tops :++: CtxToRList args) :++: ghosts)))
tcBlockEntryBody names blk entry@(TypedEntry {..}) =
runPermCheckM names typedEntryID typedEntryArgs typedEntryGhosts typedEntryPermsIn $
\tops_ns args_ns ghosts_ns perms ->
let ctx = mkCtxTrans (blockInputs blk) args_ns
ns = RL.append (RL.append tops_ns args_ns) ghosts_ns in
stmtTraceM (\i ->
pretty "Type-checking block" <+> pretty (blockID blk) <>
comma <+> pretty "entrypoint" <+> pretty (entryIndex typedEntryID)
<> line <>
pretty "Input types:"
<> align (permPretty i $
RL.map2 VarAndType ns $ cruCtxToTypes $
typedEntryAllArgs entry)
<> line <>
pretty "Input perms:"
<> align (permPretty i perms)) >>>
-- handle unit variables
stmtHandleUnitVars ns >>>
stmtRecombinePerms >>>
tcEmitStmtSeq names ctx (blk ^. blockStmts)
-- | Prove that the permissions held at a call site from the given source
-- entrypoint imply the supplied input permissions of the current entrypoint
proveCallSiteImpl ::
KnownRepr ExtRepr ext => TypedEntryID blocks some_args ->
TypedEntryID blocks args -> CruCtx args -> CruCtx ghosts -> CruCtx vars ->
MbValuePerms ((tops :++: args) :++: vars) ->
MbValuePerms ((tops :++: args) :++: ghosts) ->
TopPermCheckM ext cblocks blocks tops rets (CallSiteImpl
blocks
((tops :++: args) :++: vars)
tops args ghosts)
proveCallSiteImpl srcID destID args ghosts vars mb_perms_in mb_perms_out =
fmap CallSiteImpl $ runPermCheckM [] srcID args vars mb_perms_in $
\tops_ns args_ns _ perms_in ->
let ns = RL.append tops_ns args_ns
perms_out =
give (cruCtxProxies ghosts) $
varSubst (permVarSubstOfNames $ ns) $
mbSeparate (cruCtxProxies ghosts) $
mbValuePermsToDistPerms mb_perms_out in
stmtTraceM (\i ->
pretty ("proveCallSiteImpl, src = " ++ show srcID ++
", dest = " ++ show destID) <> line <>
indent 2 (permPretty i perms_in) <> line <>
pretty "-o" <> line <>
indent 2 (permPretty i perms_out)) >>>
permGetPPInfo >>>= \ppInfo ->
-- FIXME HERE NOW: add the input perms and call site to our error message
let err = ppProofError ppInfo perms_out in
pcmRunImplM ghosts err
(CallSiteImplRet destID ghosts Refl ns)
(handleUnitVars ns >>>
recombinePerms perms_in >>>
proveVarsImplVarEVars perms_out
) >>>= \impl ->
gmapRet (>> return impl)
-- | Set the entrypoint ghost variables of a call site, erasing its implication
callSiteSetGhosts :: CruCtx ghosts' ->
TypedCallSite TCPhase blocks tops args ghosts vars ->
TypedCallSite TCPhase blocks tops args ghosts' vars
callSiteSetGhosts _ (TypedCallSite {..}) =
TypedCallSite typedCallSiteID typedCallSitePerms Nothing
-- | Visit a call site, proving its implication of the entrypoint input
-- permissions if that implication does not already exist
visitCallSite ::
(PermCheckExtC ext, KnownRepr ExtRepr ext) =>
TypedEntry TCPhase ext blocks tops rets args ghosts ->
TypedCallSite TCPhase blocks tops args ghosts vars ->
TopPermCheckM ext cblocks blocks tops rets
(TypedCallSite TCPhase blocks tops args ghosts vars)
visitCallSite _ site@(TypedCallSite { typedCallSiteImpl = Just _ }) =
return site
visitCallSite (TypedEntry {..}) site@(TypedCallSite {..})
| TypedCallSiteID { callSiteSrc = srcID,
callSiteVars = vars } <- typedCallSiteID =
fmap (\impl -> site { typedCallSiteImpl = Just impl }) $
proveCallSiteImpl srcID typedEntryID
typedEntryArgs typedEntryGhosts vars
typedCallSitePerms typedEntryPermsIn
-- | Widen the permissions held by all callers of an entrypoint to compute new,
-- weaker input permissions that can hopefully be satisfied by them
widenEntry :: PermCheckExtC ext => DebugLevel -> PermEnv ->
TypedEntry TCPhase ext blocks tops rets args ghosts ->
Some (TypedEntry TCPhase ext blocks tops rets args)
widenEntry dlevel env (TypedEntry {..}) =
debugTraceTraceLvl dlevel ("Widening entrypoint: " ++ show typedEntryID) $
case foldl1' (widen dlevel env typedEntryTops typedEntryArgs) $
map (fmapF typedCallSiteArgVarPerms) typedEntryCallers of
Some (ArgVarPerms ghosts perms_in) ->
let callers =
map (fmapF (callSiteSetGhosts ghosts)) typedEntryCallers in
Some $
TypedEntry { typedEntryCallers = callers, typedEntryGhosts = ghosts,
typedEntryPermsIn = perms_in, typedEntryBody = Nothing, .. }
-- | Visit an entrypoint, by first proving the required implications at each
-- call site, meaning that the permissions held at the call site imply the input
-- permissions of the entrypoint, and then type-checking the body of the block
-- with those input permissions, if it has not been type-checked already.
--
-- If any of the call site implications fail, and the input "can widen" flag is
-- 'True', recompute the entrypoint input permissions using widening.
visitEntry ::
(PermCheckExtC ext, CtxToRList cargs ~ args, KnownRepr ExtRepr ext) =>
[Maybe String] ->
Bool -> Block ext cblocks ret cargs ->
TypedEntry TCPhase ext blocks tops (gouts :> ret) args ghosts ->
TopPermCheckM ext cblocks blocks tops (gouts :> ret)
(Some (TypedEntry TCPhase ext blocks tops (gouts :> ret) args))
-- If the entry is already complete, do nothing
visitEntry _ _ _ entry
| isJust $ completeTypedEntry entry =
(stDebugLevel <$> get) >>= \dlevel ->
debugTraceTraceLvl dlevel ("visitEntry " ++ show (typedEntryID entry)
++ ": no change") $
return $ Some entry
-- Otherwise, visit the call sites, widen if needed, and type-check the body
visitEntry names can_widen blk entry =
(stDebugLevel <$> get) >>= \dlevel ->
(stPermEnv <$> get) >>= \env ->
debugTracePretty traceDebugLevel dlevel
(vsep [pretty ("visitEntry " ++ show (typedEntryID entry)
++ " with input perms:"),
permPretty emptyPPInfo (typedEntryPermsIn entry)])
(return ()) >>= \() ->
mapM (traverseF $
visitCallSite entry) (typedEntryCallers entry) >>= \callers ->
debugTraceTraceLvl dlevel ("can_widen: " ++ show can_widen ++ ", any_fails: "
++ show (any (anyF typedCallSiteImplFails) callers)) $
if can_widen && any (anyF typedCallSiteImplFails) callers then
case widenEntry dlevel env entry of
Some entry' ->
-- If we widen then we are throwing away the old body, so all of its
-- callees are no longer needed and can be deleted
modifying stBlockMap (deleteEntryCallees $ typedEntryID entry) >>
visitEntry names False blk entry'
else
if isJust (typedEntryBody entry) then
-- If the body was complete when we started and we are not widening, there
-- is no reason to re-type-check the body, so just update the callers
return $ Some $ entry { typedEntryCallers = callers }
else
do body <- maybe (tcBlockEntryBody names blk entry) return (typedEntryBody entry)
return $ Some $ entry { typedEntryCallers = callers,
typedEntryBody = Just body }
-- | Visit a block by visiting all its entrypoints
visitBlock ::
(PermCheckExtC ext, KnownRepr ExtRepr ext) =>
Bool -> {- ^ Whether widening can be applied in type-checking this block -}
TypedBlock TCPhase ext blocks tops rets args ->
TopPermCheckM ext cblocks blocks tops rets
(TypedBlock TCPhase ext blocks tops rets args)
visitBlock can_widen blk@(TypedBlock {..}) =
(stCBlocksEq <$> get) >>= \Refl ->
flip (set typedBlockEntries) blk <$>
mapM (\(Some entry) ->
visitEntry _typedBlockNames (can_widen && typedBlockCanWiden)
typedBlockBlock entry)
_typedBlockEntries
-- | Flatten a list of topological ordering components to a list of nodes in
-- topological order paired with a flag denoting which nodes were loop heads
wtoCompsToListWithSCCs :: [WTOComponent n] -> [(n, Bool)]
wtoCompsToListWithSCCs =
concatMap (\case
Vertex n -> [(n,False)]
SCC comps -> [(wtoHead comps,True)] ++ wtoCompsToListWithSCCs (wtoComps comps))
-- | Build a topologically sorted list of 'BlockID's for a 'CFG', along with a
-- flag for each 'BlockID' indicating whether it is the head of a loop
cfgOrderWithSCCs :: CFG ext blocks init ret ->
([Some (BlockID blocks)], Assignment (Constant Bool) blocks)
cfgOrderWithSCCs cfg =
let nodes_sccs = wtoCompsToListWithSCCs $ cfgWeakTopologicalOrdering cfg in
(map fst nodes_sccs,
foldr (\(Some blkID, is_scc) ->
set (ixF $ blockIDIndex blkID) $ Constant is_scc)
(fmapFC (const $ Constant False) $ cfgBlockMap cfg)
nodes_sccs)
-- | The maximum number of iterations through the CFG while we allow widening
-- when type-checking before we give up and force everything to be done
maxWideningIters :: Int
maxWideningIters = 5
-- | Type-check a Crucible CFG
tcCFG ::
forall w ext cblocks ghosts inits gouts ret.
(PermCheckExtC ext, KnownRepr ExtRepr ext, 1 <= w, 16 <= w) =>
NatRepr w ->
PermEnv -> EndianForm -> DebugLevel ->
FunPerm ghosts (CtxToRList inits) gouts ret ->
CFG ext cblocks inits ret ->
TypedCFG ext (CtxCtxToRList cblocks) ghosts (CtxToRList inits) gouts ret
tcCFG w env endianness dlevel fun_perm cfg =
let h = cfgHandle cfg
ghosts = funPermGhosts fun_perm
gouts = funPermGouts fun_perm
(nodes, sccs) = cfgOrderWithSCCs cfg
init_st =
let ?ptrWidth = w in
emptyTopPermCheckState env fun_perm endianness dlevel cfg sccs
tp_nodes = map (\(Some blkID) ->
Some $ stLookupBlockID blkID init_st) nodes in
let tp_blk_map =
flip evalState init_st $ main_loop maxWideningIters tp_nodes in
TypedCFG { tpcfgHandle = TypedFnHandle ghosts gouts h
, tpcfgFunPerm = fun_perm
, tpcfgBlockMap = tp_blk_map
, tpcfgEntryID =
TypedEntryID (stLookupBlockID (cfgEntryBlockID cfg) init_st) 0 }
where
main_loop :: Int ->
[Some (TypedBlockID blocks :: RList CrucibleType -> Type)] ->
TopPermCheckM ext cblocks blocks tops rets
(TypedBlockMap TransPhase ext blocks tops rets)
main_loop rem_iters _
-- We may have to iterate through the CFG twice with widening turned off
-- to finally get everything to quiesce, once to ensure all block bodies
-- have type-checked and once again to ensure any back edged produced in
-- that last iteration have completed
| rem_iters < -2 = error "tcCFG: failed to complete on last iteration"
main_loop rem_iters nodes =
get >>= \st ->
case completeTypedBlockMap $ view stBlockMap st of
Just blkMapOut -> return blkMapOut
Nothing ->
forM_ nodes (\(Some tpBlkID) ->
let memb = typedBlockIDMember tpBlkID in
use (stBlockMap . member memb) >>=
(visitBlock (rem_iters > 0) >=>
assign (stBlockMap . member memb))) >>
main_loop (rem_iters - 1) nodes
| GaloisInc/saw-script | heapster-saw/src/Verifier/SAW/Heapster/TypedCrucible.hs | bsd-3-clause | 188,001 | 156 | 46 | 45,020 | 44,621 | 22,647 | 21,974 | -1 | -1 |
module Main( main ) where
import System.Environment( getArgs )
import Language.Elm.TH
import Language.Haskell.TH
main = do
(infile:_) <- getArgs
result <- runQ $ do
let options = Options True [] [] "Main"
LitE (StringL str) <- translateToElm options infile
return str
putStrLn result | JoeyEremondi/haskelm | src/Haskelm.hs | bsd-3-clause | 307 | 0 | 15 | 66 | 116 | 58 | 58 | 11 | 1 |
{-# LANGUAGE OverloadedStrings, TypeFamilies, PackageImports #-}
import Control.Applicative
import Control.Monad
import Control.Concurrent
import "crypto-random" Crypto.Random
import TestClient
import Data.HandleLike
import Control.Concurrent.STM
import qualified Data.ByteString as BS
import System.IO
import CommandLine
import System.Environment
import qualified Data.X509 as X509
import qualified Data.X509.CertificateStore as X509
import TestServer
cipherSuites :: [CipherSuite]
cipherSuites = [
CipherSuite ECDHE_ECDSA AES_128_CBC_SHA256,
CipherSuite ECDHE_ECDSA AES_128_CBC_SHA,
CipherSuite ECDHE_RSA AES_128_CBC_SHA256,
CipherSuite ECDHE_RSA AES_128_CBC_SHA,
CipherSuite DHE_RSA AES_128_CBC_SHA256,
CipherSuite DHE_RSA AES_128_CBC_SHA,
CipherSuite RSA AES_128_CBC_SHA256,
CipherSuite RSA AES_128_CBC_SHA
]
len :: Int
len = length cipherSuites - 1
main :: IO ()
main = do
forM_ (map (`drop` cipherSuites) [len, len - 1 .. 0]) runRsa
forM_ (map (`drop` cipherSuites) [len, len - 1 .. 0]) ecdsa
runRsa :: [CipherSuite] -> IO ()
runRsa cs = do
(cw, sw) <- getPair
_ <- forkIO $ srv sw cs
(rsk, rcc, crtS) <- readFiles
g <- cprgCreate <$> createEntropyPool :: IO SystemRNG
client g cw [(rsk, rcc)] crtS
ecdsa :: [CipherSuite] -> IO ()
ecdsa cs = do
(cw, sw) <- getPair
_ <- forkIO $ srv sw cs
(rsk, rcc, crtS) <- readFilesEcdsa
g <- cprgCreate <$> createEntropyPool :: IO SystemRNG
client g cw [(rsk, rcc)] crtS
srv :: ChanHandle -> [CipherSuite] -> IO ()
srv sw cs = do
g <- cprgCreate <$> createEntropyPool :: IO SystemRNG
(_prt, _cs, rsa, ec, mcs, _td) <- readOptions =<< getArgs
server g sw cs rsa ec mcs
readFiles :: IO (CertSecretKey, X509.CertificateChain, X509.CertificateStore)
readFiles = (,,)
<$> readPathKey "certs/yoshikuni.sample_key"
<*> readPathCertificateChain "certs/yoshikuni.sample_crt"
<*> readPathCertificateStore ["certs/cacert.pem"]
readFilesEcdsa :: IO
(CertSecretKey, X509.CertificateChain, X509.CertificateStore)
readFilesEcdsa = (,,)
<$> readPathKey "certs/client_ecdsa.sample_key"
<*> readPathCertificateChain "certs/client_ecdsa.sample_crt"
<*> readPathCertificateStore ["certs/cacert.pem"]
data ChanHandle = ChanHandle (TChan BS.ByteString) (TChan BS.ByteString)
instance HandleLike ChanHandle where
type HandleMonad ChanHandle = IO
hlPut (ChanHandle _ w) = atomically . writeTChan w
hlGet h@(ChanHandle r _) n = do
(b, l, bs) <- atomically $ do
bs <- readTChan r
let l = BS.length bs
if l < n
then return (True, l, bs)
else do let (x, y) = BS.splitAt n bs
unGetTChan r y
return (False, l, x)
if b then (bs `BS.append`) <$> hlGet h (n - l)
else return bs
hlDebug _ dl
| dl >= "high" = BS.putStr
| otherwise = const $ return ()
hlClose _ = return ()
instance ValidateHandle ChanHandle where
validate _ = validate (undefined :: Handle)
getPair :: IO (ChanHandle, ChanHandle)
getPair = do
c1 <- newTChanIO
c2 <- newTChanIO
return (ChanHandle c1 c2, ChanHandle c2 c1)
| YoshikuniJujo/peyotls | peyotls/test/testClient.hs | bsd-3-clause | 2,992 | 43 | 20 | 503 | 1,103 | 577 | 526 | 87 | 1 |
-- |Functions for fetching player/character data from the lodestone
module Data.Krile.Sharlayan.User (Character(..), findChar, expandCharacter)
where
import Text.HTML.TagSoup
import Network.Protocol.HTTP.Parser
import Control.Monad.TakeWhileM
import Data.Time.Clock
import Data.List.Split
import Data.Maybe ( fromMaybe )
-- |Data type for stroing details on a character
data Character = Character {
uid :: Int -- ^ The Lodestone character id
,name :: String -- ^ The character name
,world :: String -- ^ The world the character is on
,face :: String -- ^ The URL of the character's mugshot
,profile :: String -- ^ Character profile URL
,time :: UTCTime -- ^ The time this character's data was last updated
,fc :: Maybe Integer -- ^ Free Company's lodestone id (if available)
} deriving (Show)
-- |The root of the URL to be used for player searches
lsSearchRoot :: String
lsSearchRoot = "http://eu.finalfantasyxiv.com/lodestone/character/more/"
-- |The lodestone hostname
lsHost :: String
lsHost = "http://eu.finalfantasyxiv.com"
-- |Searches for a character on Lodestone given a full name and World
findChar :: String -> String -> IO [Character]
findChar n w = fmap concat $ takeWhileM (not . null) $ map parseLodestoneResults $ genQueryURL n w
-- |Takes a player name and world, and returns a list of search URLs
genQueryURL :: String -> String -> [String]
genQueryURL n w = map (((++) lsSearchRoot) . genQueryString n w) [1..]
-- |Takes a player name and a world, and returns the query string to search the first page only of lodestone results
genQueryString :: String -> String -> Int -> String
genQueryString name world page
= "?order=&q=" ++ escapeName name
++ "&worldname=" ++ world
++ "&classjob=&race_tribe=&page="
++ (show page)
where
escapeName name = map escapeChar name
escapeChar ' ' = '+'
escapeChar x = id x
-- |Searches on the lodestone at a given URL and returns a list of results
parseLodestoneResults :: String -> IO [Character]
parseLodestoneResults url
= do
tags <- parseTags <$> mobOpenURL url
let entries = partitions startOfEntry tags
mapM toCharRecord entries
where
startOfEntry e = (||) (e ~== TagOpen "div" [("class", "entry")])
(e ~== TagOpen "div" [("class", "entry last_message")])
toCharRecord :: [Tag String] -> IO Character
toCharRecord t = do
curTime <- getCurrentTime
return Character { uid = getUid t
, name = getName t
, world = getWorld t
, face = getFace t
, profile = getCharProfile t
, fc = Nothing
, time = curTime }
getWorld :: [Tag String] -> String
getWorld = innerText . (take 2) . head . sections (~== TagOpen "p" [("class", "entry__world")])
getName :: [Tag String] -> String
getName = innerText . (take 2) . head . sections (~== TagOpen "p" [("class", "entry__name")])
getFace :: [Tag String] -> String
getFace = (fromAttrib "src") . head
. (filter (~== TagOpen "img" []))
. (dropWhile (~/= TagOpen "div" [("class", "entry__chara__face")]))
getCharProfile :: [Tag String] -> String
getCharProfile = head
. (map (((++) lsHost) . fromAttrib "href"))
. filter (~== TagOpen "a" [("class", "entry__chara__link")])
getUid :: [Tag String] -> Int
getUid = read . head . (splitOn "/") . (!! 1) . (splitOn "character/") . getCharProfile
-- |Updates a character data object with information parsed from their profile page
expandCharacter :: Character -> IO (Character)
expandCharacter char
= do
let profileURL = profile char
(pic, fcid) <- parseProfilePage profileURL
time <- getCurrentTime
return Character { uid = uid char
, name = name char
, world = world char
, face = face char
, profile = profile char
, fc = Just fcid
, time = time }
-- |Parses a lodestone character profile page at a given URL and returns an image link and FC identifier
parseProfilePage :: String -> IO (String, Integer)
parseProfilePage url
= do
tags <- parseTags <$> mobOpenURL url
return (pictureLoc tags, fcId tags)
where
pictureLoc :: [Tag String] -> String
pictureLoc = (fromAttrib "href") . head . tail . head . sections (~== TagOpen "div" [("class", "character__detail__image")])
fcPage :: [Tag String] -> String
fcPage = (fromAttrib "href") . head . filter (~== TagOpen "a" [("class", "entry__freecompany")])
fcId :: [Tag String] -> Integer
fcId = read . head . (splitOn "/") . (!! 1) . (splitOn "freecompany/") . fcPage
| callummance/libsharlayan | src/Data/Krile/Sharlayan/User.hs | bsd-3-clause | 5,024 | 0 | 14 | 1,463 | 1,272 | 691 | 581 | 89 | 2 |
module Main where
import Control.Monad.IO.Class
import Servant.Client
import Servant.API
import Data.Proxy
import Options.Applicative
import Control.Applicative
import Data.Monoid
import Data.Maybe
import Network.HTTP.Client (newManager, defaultManagerSettings, Manager)
import API
url = BaseUrl Http "localhost" 8000 ""
listUsers :<|> queryUser = client userAPI
queries uid gid = case (uid, gid) of
(Nothing, Nothing) -> listUsers
_ -> queryUser uid gid
clientApp uid gid = do
mgr <- newManager defaultManagerSettings
runClientM (queries uid gid) (ClientEnv mgr url)
data Cmdline = Cmdline {
uid :: Maybe Int
, gid :: Maybe Int
} deriving Show
cmdlineOpts = Cmdline
<$> (optional $ option auto $ long "userid" <> short 'u' <> metavar "USERID" <> help "user id")
<*> (optional $ option auto $ long "groupid" <> short 'g' <> metavar "GROUPID" <> help "group id")
opts = info (cmdlineOpts <**> helper)
( fullDesc
<> progDesc "query rest api by optional userid or groupid"
<> header "hask-rest1-client" )
main :: IO ()
main = execParser opts >>= \(Cmdline uid gid) -> clientApp uid gid >>= either print (mapM_ print)
| cl04/rest1 | hask-rest1/app/Client.hs | bsd-3-clause | 1,213 | 0 | 13 | 270 | 388 | 200 | 188 | 32 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module BCalib.Event
( module X
, Event(..)
, runNumber, eventNumber, mu
, leptons, jets, met
, eventHs
, lepFlavorChannels
, lepChargeChannels
, nJetChannels
, overlapRemoval
, withWeights
) where
import qualified Control.Foldl as F
import Data.Bifunctor
import qualified Data.Map.Strict as M
import GHC.Float (float2Double)
import GHC.Generics (Generic)
import BCalib.Imports
import BCalib.Jet as X
import BCalib.Lepton as X
import BCalib.Systematics
data Event =
Event
{ _runNumber :: Int
, _eventNumber :: Int
, _mu :: Double
, _leptons :: (Lepton, Lepton)
, _jets :: [Jet]
, _met :: PtEtaPhiE
} deriving (Generic, Show)
jerSyst' :: PrimMonad m => Event -> VariationT "jerSyst" (Prob m) Event
jerSyst' = (jets.traverse) jerSyst
-- TH doesn't work with c compilation (e.g. ttree)
runNumber :: Lens' Event Int
runNumber = lens _runNumber $ \e x -> e { _runNumber = x }
eventNumber :: Lens' Event Int
eventNumber = lens _eventNumber $ \e x -> e { _eventNumber = x }
mu :: Lens' Event Double
mu = lens _mu $ \e x -> e { _mu = x }
leptons :: Lens' Event (Lepton, Lepton)
leptons = lens _leptons $ \e x -> e { _leptons = x }
jets :: Lens' Event [Jet]
jets = lens _jets $ \e x -> e { _jets = x }
met :: Lens' Event PtEtaPhiE
met = lens _met $ \e x -> e { _met = x }
overlapRemoval :: Event -> Event
overlapRemoval evt = over jets (filter filt) evt
where
leps = view leptons evt
filt = not . any (< 0.2) . traverse lvDREta leps
jetsHs :: Fill Event
jetsHs = (M.unions <$> sequenceA [ allHs, jet0Hs, jet1Hs ]) <$$= jets
where
allHs =
(nH 10 `mappend` F.handles (to distribute . folded) jetHs)
<&> (M.mapKeysMonotonic ("/jets" <>) . over (traverse.xlabel) ("jet " <>))
jet0Hs =
F.handles (to distribute . ix 0) jetHs
<&> (M.mapKeysMonotonic ("/jet0" <>) . over (traverse.xlabel) ("leading jet " <>))
jet1Hs =
F.handles (to distribute . ix 1) jetHs
<&> (M.mapKeysMonotonic ("/jet1" <>) . over (traverse.xlabel) ("subleading jet " <>))
distribute (fs, x) = (,) <$> fs <*> pure x
lepsHs :: Fill Event
lepsHs =
F.handles (to (first $ view leptons) . to distributeT . both) lepHs
<&> (M.mapKeysMonotonic ("/leps" <>) . over (traverse.xlabel) ("lepton " <>))
where
distributeT ((e, f), x) = ((e, x), (f, x))
muH :: Fill Event
muH =
hist1DDef (binD 0 50 50) "$ <\\mu> $" (dsigdXpbY "<\\mu>" "1") "/mu"
<$$= mu
eventHs :: Fill Event
eventHs = mconcat [ lepsHs, jetsHs, muH ]
readMET :: MonadIO m => String -> String -> TR m PtEtaPhiE
readMET m p = do
et <- float2Double <$> readBranch m
phi <- float2Double <$> readBranch p
return $ PtEtaPhiE et 0 phi et
-- weights :: MonadIO m => TR m (M.Map T.Text Double)
-- weights = M.singleton "nominal" . float2Double . product
-- <$> sequence
-- [ readBranch "eventWeight"
-- -- TODO
-- -- TODO
-- -- some of these are NaNs.
-- -- , readBranch "leptonSF"
-- -- , readBranch "trigSF"
-- ]
instance FromTTree Event where
fromTTree = do
isData <- (== (0 :: CInt)) <$> readBranch "sampleID"
Event
<$> fmap ci2i (readBranch "runNumber")
<*> fmap ci2i (readBranch "eventNumber")
<*> fmap (convMu isData . float2Double) (readBranch "mu")
<*> readLeptons
<*> readJets isData
<*> readMET "MET" "METphi"
where
ci2i :: CInt -> Int
ci2i = fromEnum
convMu False = id
convMu True = (/1.09)
leptonFlavors :: (LFlavor, LFlavor) -> Event -> Bool
leptonFlavors flvs e = flvs == (view leptons e & over both (view lepFlavor))
leptonCharges :: (LCharge, LCharge) -> Event -> Bool
leptonCharges chgs e = chgs == (view leptons e & over both (view lepCharge))
lepChargeChannels :: Fill Event -> Fill Event
lepChargeChannels =
channels
[ ("/os", (||) <$> leptonCharges (Plus, Minus) <*> leptonCharges (Minus, Plus))
-- , ("/ss", (||) <$> leptonCharges (Plus, Plus) <*> leptonCharges (Minus, Minus))
-- , ("/allLepCharge", const True)
]
lepFlavorChannels :: Fill Event -> Fill Event
lepFlavorChannels =
channels
[ ("/elmu", (||) <$> leptonFlavors (Electron, Muon) <*> leptonFlavors (Muon, Electron))
-- , ("/mumu", leptonFlavors (Muon, Muon))
-- , ("/elel", leptonFlavors (Electron, Electron))
-- , ("/allLepFlav", const True)
]
nJetChannels :: Fill Event -> Fill Event
nJetChannels =
channels
[ ("/2jet", (== 2) . views jets length)
-- , ("/3jet", (== 3) . views jets length)
-- , ("/4pjet", (>= 4) . views jets length)
-- , ("/2pjet", (>= 2) . views jets length)
]
withWeights :: Fill a -> F.Fold (a, SystMap Double) (SystMap YodaFolder)
withWeights (F.Fold comb start done) = F.Fold comb' start' done'
where
start' = M.empty
-- comb' :: M.Map T.Text x -> (a, M.Map T.Text Double) -> M.Map T.Text x
comb' mh (x, mw) = foldl (\h (k, xw) -> M.alter (f xw) k h) mh (M.toList $ (x,) <$> mw)
f xw Nothing = Just $ comb start xw
f xw (Just h) = Just $ comb h xw
done' = fmap done
| cspollard/bcalib | src/BCalib/Event.hs | bsd-3-clause | 5,334 | 0 | 16 | 1,370 | 1,696 | 926 | 770 | 116 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Data.OpenSRS.Types.Domain where
import Data.Map
import Data.OpenSRS.Types.Common
import Data.Time
--------------------------------------------------------------------------------
-- | Domain Record
data Domain = Domain {
domainName :: DomainName,
domainAutoRenew :: Bool,
domainContactSet :: Map String Contact,
domainUpdateDate :: Maybe UTCTime,
domainSponsoringRsp :: Bool,
domainCreateDate :: Maybe UTCTime,
domainAffiliateID :: Maybe String,
domainLetExpire :: Bool,
domainExpireDate :: Maybe UTCTime,
domainNameservers :: [Nameserver]
} deriving (Show, Eq)
-- | Domain Contacts
data Contact = Contact {
contactFirstName :: Maybe String,
contactLastName :: Maybe String,
contactOrgName :: Maybe String,
contactEmail :: Maybe String,
contactPhone :: Maybe String,
contactFax :: Maybe String,
contactAddress1 :: Maybe String,
contactAddress2 :: Maybe String,
contactAddress3 :: Maybe String,
contactCity :: Maybe String,
contactState :: Maybe String,
contactPostalCode :: Maybe String,
contactCountry :: Maybe String
} deriving (Show, Eq)
-- | Domain Nameservers
data Nameserver = Nameserver {
nsName :: Maybe String,
nsSortorder :: Maybe String,
nsIPAddr :: Maybe String
} deriving (Show, Eq)
type TLDData = Map String (Map String String)
| anchor/haskell-opensrs | lib/Data/OpenSRS/Types/Domain.hs | bsd-3-clause | 1,478 | 0 | 9 | 355 | 333 | 193 | 140 | 38 | 0 |
-- | Conversion to raster forms.
--
-- TODO: the reverse.
module Propane.Raster
( rasterize
, rastimate
) where
import qualified Data.Sequence as S
import qualified Data.Colour as C
import qualified Data.Colour.SRGB as C
import qualified Data.Array.Repa as R
import Data.Array.Repa ( Z(..), (:.)(..) )
import Propane.Types
import Propane.Transform ( spaced )
type W8888 = (Word8, Word8, Word8, Word8)
-- | Convert the @'Image'@ region [-1, 1] x [-1, 1] to a @'Raster'@ with
-- the specified number of pixels.
rasterize :: Size -> Image Colour -> Raster
rasterize (Size w h) im = Raster . chans $ R.fromFunction dim f where
f = quant . im . point
dw = fromIntegral w - 1
dh = fromIntegral h - 1
dim = Z :. w :. h
point :: R.DIM2 -> R2
point (Z :. y :. x) = (adj dw x, adj dh y) where
adj d n = (2 * fromIntegral n / d) - 1
quant :: Colour -> W8888
quant c = (r, g, b, a) where
C.RGB r g b = C.toSRGB24 (c `C.over` C.black)
a = round (C.alphaChannel c * 255.0)
chans :: R.Array R.DIM2 W8888 -> R.Array R.DIM3 Word8
chans arr = R.traverse arr (:. 4) chan where
chan a (Z :. y :. x :. c) = ix c (a (Z :. y :. x))
ix 0 (r,_,_,_) = r
ix 1 (_,g,_,_) = g
ix 2 (_,_,b,_) = b
ix 3 (_,_,_,a) = a
ix _ _ = error "Propane.Quantize: internal error (bad ix)"
-- | Convert the animation, for times in [0,1), to a @'Rastimation'@ with
-- the specified numbers of frames and pixels.
rastimate :: Count -> Size -> Animation Colour -> Rastimation
rastimate n sz ani = Rastimation (S.fromList frames) where
frames = map (rasterize sz . ani) (spaced n 0 1)
| kmcallister/propane | Propane/Raster.hs | bsd-3-clause | 1,681 | 0 | 14 | 451 | 646 | 359 | 287 | 35 | 5 |
{-
This is the entry point to actually building the modules in a package. It
doesn't actually do much itself, most of the work is delegated to
compiler-specific actions. It does do some non-compiler specific bits like
running pre-processors.
-}
module Distribution.Simple.Build (
build,
initialBuildSteps,
writeAutogenFiles,
) where
import qualified Distribution.Simple.GHC as GHC
import qualified Distribution.Simple.Build.Macros as Build.Macros
import qualified Distribution.Simple.Build.PathsModule as Build.PathsModule
import Distribution.Package
( Package(..), PackageName(..), PackageIdentifier(..)
, Dependency(..), thisPackageVersion )
import Distribution.Simple.Compiler
( CompilerFlavor(..), compilerFlavor, PackageDB(..) )
import Distribution.PackageDescription
( PackageDescription(..), BuildInfo(..), Library(..), Executable(..)
, App(..), TestSuite(..), TestSuiteInterface(..), Benchmark(..)
, BenchmarkInterface(..) )
import qualified Distribution.InstalledPackageInfo as IPI
import qualified Distribution.ModuleName as ModuleName
import Distribution.Simple.Setup
( BuildFlags(..), fromFlag )
import Distribution.Simple.PreProcess
( preprocessComponent, PPSuffixHandler )
import Distribution.Simple.LocalBuildInfo
( LocalBuildInfo(compiler, buildDir, withPackageDB, withPrograms)
, Component(..), ComponentLocalBuildInfo(..), withComponentsLBI
, inplacePackageId )
import Distribution.Simple.Program.Types
import Distribution.Simple.Program.Db
import Distribution.Simple.BuildPaths
( autogenModulesDir, autogenModuleName, cppHeaderName, exeExtension )
import Distribution.Simple.Register
( registerPackage, inplaceInstalledPackageInfo )
import Distribution.Simple.Test ( stubFilePath, stubName )
import Distribution.Simple.Utils
( createDirectoryIfMissingVerbose, rewriteFile
, die, info, setupMessage )
import Distribution.Verbosity
( Verbosity )
import Distribution.Text
( display )
import Data.Maybe
( maybeToList )
import Data.List
( intersect )
import Control.Monad
( unless )
import System.FilePath
( (</>), (<.>) )
import System.Directory
( getCurrentDirectory )
-- -----------------------------------------------------------------------------
-- |Build the libraries, executables, and apps in this package.
build :: PackageDescription -- ^ Mostly information from the .cabal file
-> LocalBuildInfo -- ^ Configuration information
-> BuildFlags -- ^ Flags that the user passed to build
-> [ PPSuffixHandler ] -- ^ preprocessors to run before compiling
-> IO ()
build pkg_descr lbi flags suffixes = do
let distPref = fromFlag (buildDistPref flags)
verbosity = fromFlag (buildVerbosity flags)
initialBuildSteps distPref pkg_descr lbi verbosity
setupMessage verbosity "Building" (packageId pkg_descr)
internalPackageDB <- createInternalPackageDB distPref
let pre c lbi' = preprocessComponent pkg_descr c lbi' False verbosity suffixes
withComponentsLBI pkg_descr lbi $ \comp clbi ->
case comp of
CLib lib -> do
let bi = libBuildInfo lib
progs' = addInternalBuildTools pkg_descr lbi bi (withPrograms lbi)
lbi' = lbi { withPrograms = progs' }
pre comp lbi'
info verbosity "Building library..."
buildLib verbosity pkg_descr lbi' lib clbi
-- Register the library in-place, so exes can depend
-- on internally defined libraries.
pwd <- getCurrentDirectory
let installedPkgInfo =
(inplaceInstalledPackageInfo pwd distPref pkg_descr lib lbi clbi) {
-- The inplace registration uses the "-inplace" suffix,
-- not an ABI hash.
IPI.installedPackageId = inplacePackageId (packageId installedPkgInfo)
}
registerPackage verbosity
installedPkgInfo pkg_descr lbi True -- True meaning inplace
(withPackageDB lbi ++ [internalPackageDB])
CExe exe -> do
let bi = buildInfo exe
progs' = addInternalBuildTools pkg_descr lbi bi (withPrograms lbi)
lbi' = lbi {
withPrograms = progs',
withPackageDB = withPackageDB lbi ++ [internalPackageDB]
}
pre comp lbi'
info verbosity $ "Building executable " ++ exeName exe ++ "..."
buildExe verbosity pkg_descr lbi' exe clbi
CApp app -> do
let bi = appBuildInfo app
progs' = addInternalBuildTools pkg_descr lbi bi (withPrograms lbi)
lbi' = lbi {
withPrograms = progs',
withPackageDB = withPackageDB lbi ++ [internalPackageDB]
}
pre comp lbi'
info verbosity $ "Building app " ++ appName app ++ "..."
buildApp verbosity pkg_descr lbi' app clbi
CTest test -> do
case testInterface test of
TestSuiteExeV10 _ f -> do
let bi = testBuildInfo test
exe = Executable
{ exeName = testName test
, modulePath = f
, buildInfo = bi
}
progs' = addInternalBuildTools pkg_descr lbi bi (withPrograms lbi)
lbi' = lbi {
withPrograms = progs',
withPackageDB = withPackageDB lbi ++ [internalPackageDB]
}
pre comp lbi'
info verbosity $ "Building test suite " ++ testName test ++ "..."
buildExe verbosity pkg_descr lbi' exe clbi
TestSuiteLibV09 _ m -> do
pwd <- getCurrentDirectory
let bi = testBuildInfo test
lib = Library
{ exposedModules = [ m ]
, libExposed = True
, libBuildInfo = bi
}
pkg = pkg_descr
{ package = (package pkg_descr)
{ pkgName = PackageName $ testName test
}
, buildDepends = targetBuildDepends $ testBuildInfo test
, executables = []
, testSuites = []
, library = Just lib
}
ipi = (inplaceInstalledPackageInfo
pwd distPref pkg lib lbi clbi)
{ IPI.installedPackageId = inplacePackageId $ packageId ipi
}
testDir = buildDir lbi' </> stubName test
</> stubName test ++ "-tmp"
testLibDep = thisPackageVersion $ package pkg
exe = Executable
{ exeName = stubName test
, modulePath = stubFilePath test
, buildInfo = (testBuildInfo test)
{ hsSourceDirs = [ testDir ]
, targetBuildDepends = testLibDep
: (targetBuildDepends $ testBuildInfo test)
}
}
-- | The stub executable needs a new 'ComponentLocalBuildInfo'
-- that exposes the relevant test suite library.
exeClbi = clbi
{ componentPackageDeps =
(IPI.installedPackageId ipi, packageId ipi)
: (filter (\(_, x) -> let PackageName name = pkgName x in name == "Cabal" || name == "base")
$ componentPackageDeps clbi)
}
progs' = addInternalBuildTools pkg_descr lbi bi (withPrograms lbi)
lbi' = lbi {
withPrograms = progs',
withPackageDB = withPackageDB lbi ++ [internalPackageDB]
}
pre comp lbi'
info verbosity $ "Building test suite " ++ testName test ++ "..."
buildLib verbosity pkg lbi' lib clbi
registerPackage verbosity ipi pkg lbi' True $ withPackageDB lbi'
buildExe verbosity pkg_descr lbi' exe exeClbi
TestSuiteUnsupported tt -> die $ "No support for building test suite "
++ "type " ++ display tt
CBench bm -> do
case benchmarkInterface bm of
BenchmarkExeV10 _ f -> do
let bi = benchmarkBuildInfo bm
exe = Executable
{ exeName = benchmarkName bm
, modulePath = f
, buildInfo = bi
}
progs' = addInternalBuildTools pkg_descr lbi bi (withPrograms lbi)
lbi' = lbi {
withPrograms = progs',
withPackageDB = withPackageDB lbi ++ [internalPackageDB]
}
pre comp lbi'
info verbosity $ "Building benchmark " ++ benchmarkName bm ++ "..."
buildExe verbosity pkg_descr lbi' exe clbi
BenchmarkUnsupported tt -> die $ "No support for building benchmark "
++ "type " ++ display tt
-- | Initialize a new package db file for libraries defined
-- internally to the package.
createInternalPackageDB :: FilePath -> IO PackageDB
createInternalPackageDB distPref = do
let dbFile = distPref </> "package.conf.inplace"
packageDB = SpecificPackageDB dbFile
writeFile dbFile "[]"
return packageDB
addInternalBuildTools :: PackageDescription -> LocalBuildInfo -> BuildInfo
-> ProgramDb -> ProgramDb
addInternalBuildTools pkg lbi bi progs =
foldr updateProgram progs internalBuildTools
where
internalBuildTools =
[ simpleConfiguredProgram toolName (FoundOnSystem toolLocation)
| toolName <- toolNames
, let toolLocation = buildDir lbi </> toolName </> toolName <.> exeExtension ]
toolNames = intersect buildToolNames internalExeNames
internalExeNames = map exeName (executables pkg)
buildToolNames = map buildToolName (buildTools bi)
where
buildToolName (Dependency (PackageName name) _ ) = name
-- TODO: build separate libs in separate dirs so that we can build
-- multiple libs, e.g. for 'LibTest' library-style testsuites
buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Library -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity pkg_descr lbi lib clbi =
case compilerFlavor (compiler lbi) of
GHC -> GHC.buildLib verbosity pkg_descr lbi lib clbi
_ -> die "Building is not supported with this compiler."
buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo
-> Executable -> ComponentLocalBuildInfo -> IO ()
buildExe verbosity pkg_descr lbi exe clbi =
case compilerFlavor (compiler lbi) of
GHC -> GHC.buildExe verbosity pkg_descr lbi exe clbi
_ -> die "Building is not supported with this compiler."
buildApp :: Verbosity -> PackageDescription -> LocalBuildInfo
-> App -> ComponentLocalBuildInfo -> IO ()
buildApp verbosity pkg_descr lbi app clbi =
case compilerFlavor (compiler lbi) of
GHC -> GHC.buildApp verbosity pkg_descr lbi app clbi
_ -> die "Building is not supported with this compiler."
initialBuildSteps :: FilePath -- ^"dist" prefix
-> PackageDescription -- ^mostly information from the .faction file
-> LocalBuildInfo -- ^Configuration information
-> Verbosity -- ^The verbosity to use
-> IO ()
initialBuildSteps _distPref pkg_descr lbi verbosity = do
-- check that there's something to build
let buildInfos =
map libBuildInfo (maybeToList (library pkg_descr)) ++
map buildInfo (executables pkg_descr) ++
map appBuildInfo (apps pkg_descr)
unless (any buildable buildInfos) $ do
let name = display (packageId pkg_descr)
die ("Package " ++ name ++ " can't be built on this system.")
createDirectoryIfMissingVerbose verbosity True (buildDir lbi)
writeAutogenFiles verbosity pkg_descr lbi
-- | Generate and write out the Paths_<pkg>.hs and faction_macros.h files
--
writeAutogenFiles :: Verbosity
-> PackageDescription
-> LocalBuildInfo
-> IO ()
writeAutogenFiles verbosity pkg lbi = do
createDirectoryIfMissingVerbose verbosity True (autogenModulesDir lbi)
let pathsModulePath = autogenModulesDir lbi
</> ModuleName.toFilePath (autogenModuleName pkg) <.> "hs"
rewriteFile pathsModulePath (Build.PathsModule.generate pkg lbi)
let cppHeaderPath = autogenModulesDir lbi </> cppHeaderName
rewriteFile cppHeaderPath (Build.Macros.generate pkg lbi)
| IreneKnapp/Faction | libfaction/Distribution/Simple/Build.hs | bsd-3-clause | 13,354 | 0 | 34 | 4,589 | 2,663 | 1,396 | 1,267 | 233 | 8 |
-----------------------------------------------------------------------------
--
-- Module : Transient.Move
-- Copyright :
-- License : MIT
--
-- Maintainer : agocorona@gmail.com
-- Stability :
-- Portability :
--
-- | @transient-universe@ extends the seamless composability of concurrent
-- multi-threaded programs provided by
-- <https://github.com/transient-haskell/transient transient>
-- to a multi-node cloud. Distributed concurrent programs are created and
-- composed seamlessly and effortlessly as if they were written for a single
-- node. @transient-universe@ has diverse applications from simple distributed
-- applications to massively parallel and distributed map-reduce problems. If
-- you are considering Apache Spark or Cloud Haskell then transient might be a
-- simpler yet better solution for you.
--
-- Transient makes it easy to write composable, distributed event driven
-- reactive UI applications with client side and server side code composed
-- freely in the same application. For example,
-- <https://hackage.haskell.org/package/axiom Axiom> is a transient based
-- unified client and server side web application framework that provides a
-- better programming model and composability compared to frameworks like
-- ReactJS.
--
-- = Overview
--
-- The 'Cloud' monad adds the following facilities to complement the 'TransIO'
-- monad:
--
-- * Create a distributed compute cluster of nodes
-- * Move computations across nodes at any point during computation
-- * Run computations on multiple nodes in parallel
--
-- = Further Reading
--
-- * <https://github.com/transient-haskell/transient/wiki/Transient-tutorial Tutorial>
-- * <https://github.com/transient-haskell/transient-examples Examples>
-- * <https://www.fpcomplete.com/user/agocorona/moving-haskell-processes-between-nodes-transient-effects-iv Blog post>
--
-----------------------------------------------------------------------------
{-# LANGUAGE CPP #-}
module Transient.Move(
-- * Running the Monad
Cloud(..),runCloud, runCloudIO, runCloudIO',
-- * Node & Cluster Management
-- $cluster
Node(..),
-- ** Creating nodes
Service(), createNodeServ, createNode, createWebNode,
-- ** Joining the cluster
Transient.Move.Internals.connect, connect', listen,
-- Low level APIs
addNodes, addThisNodeToRemote, shuffleNodes,
--Connection(..), ConnectionData(..), defConnection,
-- ** Querying nodes
getMyNode, getWebServerNode, getNodes, nodeList, isBrowserInstance,
-- * Running Local Computations
local, onAll, lazy, localFix, fixRemote, loggedc, lliftIO, localIO,
-- * Moving Computations
wormhole, teleport, copyData, fixClosure,
-- * Running at a Remote Node
beamTo, forkTo, callTo, runAt, atRemote, setSynchronous, syncStream,
-- * Running at Multiple Nodes
clustered, mclustered, callNodes,
-- * Messaging
putMailbox, putMailbox',getMailbox,getMailbox',cleanMailbox,cleanMailbox',
-- * Thread Control
single, unique,
#ifndef ghcjs_HOST_OS
-- * Buffering Control
setBuffSize, getBuffSize,
#endif
#ifndef ghcjs_HOST_OS
-- * REST API
api, HTTPMethod(..), PostParams,
#endif
) where
import Transient.Move.Internals
-- $cluster
--
-- To join the cluster a node 'connect's to a well known node already part of
-- the cluster.
--
-- @
-- import Transient.Move (runCloudIO, lliftIO, createNode, connect, getNodes, onAll)
--
-- main = runCloudIO $ do
-- this <- lliftIO (createNode "192.168.1.2" 8000)
-- master <- lliftIO (createNode "192.168.1.1" 8000)
-- connect this master
-- onAll getNodes >>= lliftIO . putStrLn . show
-- @
--
| agocorona/transient-universe | src/Transient/Move.hs | mit | 3,677 | 0 | 5 | 614 | 279 | 214 | 65 | 20 | 0 |
{-
Type name: qualified names for register types
Part of Mackerel: a strawman device definition DSL for Barrelfish
Copyright (c) 2011, ETH Zurich.
All rights reserved.
This file is distributed under the terms in the attached LICENSE file.
If you do not find this file, copies can be found by writing to:
ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
-}
module TypeName where
import MackerelParser
{--------------------------------------------------------------------
--------------------------------------------------------------------}
-- Fully-qualified name of a type
data Name = Name String String
deriving (Show, Eq)
fromParts :: String -> String -> Name
fromParts dev typename = Name dev typename
fromRef :: AST -> String -> Name
fromRef (TypeRef tname (Just dname)) _ = Name dname tname
fromRef (TypeRef tname Nothing) dname = Name dname tname
toString :: Name -> String
toString (Name d t) = d ++ "." ++ t
devName :: Name -> String
devName (Name d _) = d
typeName :: Name -> String
typeName (Name _ t) = t
is_builtin_type :: Name -> Bool
is_builtin_type (Name _ "uint8") = True
is_builtin_type (Name _ "uint16") = True
is_builtin_type (Name _ "uint32") = True
is_builtin_type (Name _ "uint64") = True
is_builtin_type _ = False
null :: Name
null = Name "" "" | kishoredbn/barrelfish | tools/mackerel/TypeName.hs | mit | 1,389 | 0 | 9 | 293 | 304 | 158 | 146 | 23 | 1 |
module SendTrap
( sendTrap
, pendingFin
) where
import SNMPTrapType
import Control.Concurrent
import Network.Socket
import Network.Socket.ByteString
import qualified Data.ByteString as B
sendTrap :: MVar Int -> Int -> Int -> SockAddr -> (SNMPTrap, B.ByteString) -> IO ()
sendTrap fin sent intval server (trap, msg) = do
withSocketsDo $ do
sock <- socket AF_INET Datagram defaultProtocol
bind sock (SockAddrInet aNY_PORT iNADDR_ANY)
sendAllTo sock msg server
close sock
readMVar fin >>= \f -> case f < 0 of
True -> do
threadDelay intval
sendTrap fin (sent+1) intval server (trap, msg)
False -> do
putStrLn $ show sent ++ " traps were successfully sent by [" ++ takeSection trap ++ "]."
modifyMVar_ fin $ \n -> return (n+1)
pendingFin :: MVar Int -> Int -> IO ()
pendingFin fin threads = readMVar fin >>= \f -> case f < threads of
True -> do
threadDelay 10000
pendingFin fin threads
False -> return ()
| IMOKURI/bulk-snmptrap-tool | src/SendTrap.hs | mit | 970 | 0 | 18 | 220 | 355 | 175 | 180 | 28 | 2 |
module End.Global.Object where
import End.Collection
import End.Collection.Header
import End.Constant.Settings
import End.Function.Object
import Graphics.UI.SDL
import End.Area.Tile
fpsToInt :: (Integral a, Num b) => a -> b
fpsToInt f = fromIntegral (1000 `div` f)
nextFrame :: Object o SpriteStatus => AAction -> o -> o
nextFrame sa o
| lfrmG > fpsToInt (sa^.fps) =
if frmG > sa^.maxFrames - 2
then o & frmS .~ 0 & lfrmS .~ 0
else o & frmS +~ 1 & lfrmS .~ 0
| otherwise = o
where frmG = o^.spriteStatus.frame
frmS = spriteStatus.frame
lfrmG = o^.spriteStatus.lastFrame
lfrmS = spriteStatus.lastFrame
manageFrames :: Object o SpriteStatus => o -> GameState o
manageFrames o = do
t <- use newTick
Just sa <- getSpriteAction o
return $ manageFrames' t sa o
manageFrames' :: Object o SpriteStatus => Word32 -> AAction -> o -> o
manageFrames' t sa o = nextFrame sa $ o&spriteStatus.lastFrame +~ t
objectFunction :: (Object a SpriteStatus) => Word32 -> a -> a
objectFunction b a = (a^.function) b a
fI :: Integral a => a -> Float
fI = fromIntegral
intersects :: AAction -> [Rect] -> Bool
intersects _ [] = False
intersects sp (Rect bx by bw bh:xs)
| t py + ph > by
&& t py < by + bh
&& t px + pw > bx
&& t px < bx + bw = True
| otherwise = intersects sp xs
where t = truncate
(px,py,pw,ph) = (sp^.box.x, sp^.box.y, sp^.box.w, sp^.box.h)
moveUp :: Integral a => Float -> Getting a s a -> s -> a -> Float
moveUp x' f sp sc
| x' < 0 = 0
| x' + fI (sp^.f) > fI sc = fI $ sc - sp^.f
| otherwise = x'
manageMove :: Object o SpriteStatus => o -> GameState Pos
manageMove o = do
t <- use newTick
Just sp <- getSpriteAction o
c <- view colls >>= return . filterNearbyTiles o sp
return $ move sp t c o
moveFPS :: Float -> Float -> Word32 -> Float
moveFPS a b f = a + b * (fromIntegral f / 1000)
move :: Object o SpriteStatus => AAction -> Word32 -> [Rect] -> o -> Pos
move sp t c o = do
let xx = moveFPS (o^.pos.x) (o^.vel.x) t
yy = moveFPS (o^.pos.y) (o^.vel.y) t
Pos (if intersects (sp&box.x +~ xx & box.y +~ o^.pos.y) c then o^.pos.x
else (moveUp xx w sp (tileBit*mapWidth)))
(if intersects (sp&box.y +~ yy & box.x +~ o^.pos.x) c then o^.pos.y
else (moveUp yy h sp (tileBit*mapHeight)))
getWalk :: Vel -> ActionTag
getWalk v | v^.x == 0 && v^.y == 0 = Stand
| otherwise = Walk
getDir :: Direction -> Vel -> Direction
getDir d v | v^.y < 0 = DUp
| v^.y > 0 = DDown
| v^.x > 0 = DRight
| v^.x < 0 = DLeft
| otherwise = d
manageCamera :: Player -> GameState Camera
manageCamera p = do
t <- use newTick
return $ moveCamera t p
moveCamera :: Word32 -> Player -> Camera
moveCamera deltaTicks p =
Camera (calcCam cxD px screenWidth mapWidthPx)
(calcCam cyD py screenHeight mapHeightPx)
where (Pos px py) = p^.pos
(Camera cx cy) = p^.camera
(Vel vx vy) = p^.vel
delta = (fI deltaTicks) / 1000.0
cxD = cx + (vx * delta)
cyD = cy + (vy * delta)
calcCam fc fp s mapPx
| fc < 0 = 0
| fp < fI halfScreen = 0
| fp > fI (mapPx - halfScreen) = fI $ mapPx - s
| otherwise = fp - fI halfScreen
where halfScreen = (s `div` 2)
| kwrooijen/sdl-game | End/Global/Object.hs | gpl-3.0 | 3,398 | 0 | 19 | 1,005 | 1,572 | 787 | 785 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module CC.ShellCheck.Types where
import CC.Types
import Control.Applicative
import Data.Aeson
import qualified Data.Map.Strict as DM
import qualified Data.Text as T
--------------------------------------------------------------------------------
-- | Remediation points and associated textual content.
data Mapping = Mapping Int Content deriving Show
instance FromJSON Mapping where
parseJSON (Object x) = do
points <- x .: "remediation_points"
content <- x .: "content"
return $! Mapping points content
parseJSON _ = empty
--------------------------------------------------------------------------------
-- | Represents mappings between check names, content and remediation points.
type Env = DM.Map T.Text Mapping
| filib/codeclimate-shellcheck | src/CC/ShellCheck/Types.hs | gpl-3.0 | 814 | 0 | 9 | 149 | 137 | 78 | 59 | 15 | 0 |
-- Copyright 2017 Google Inc.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
module Lib
( someFunc
) where
someFunc :: IO ()
someFunc = putStrLn "someFunc"
| robinp/haskell-indexer | wrappers/stack-docker/test-package/src/Lib.hs | apache-2.0 | 677 | 0 | 6 | 123 | 40 | 28 | 12 | 4 | 1 |
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell, OverloadedStrings, TypeSynonymInstances, GADTs, FlexibleInstances, MultiParamTypeClasses #-}
module Model where
import Yesod.Persist
import Database.Persist.Base (DeleteCascade (..))
import Yesod.Content (HasReps (..), toContent)
import Data.Text (Text, pack)
import Data.Time (UTCTime)
import Text.Hamlet (Html)
import Yesod.Form (Textarea)
import Yesod.Core (SinglePiece (..), MultiPiece (..))
import Data.ByteString (ByteString)
import Data.ByteString.Base64 (decodeLenient)
data TopicFormat = TFMarkdown | TFHtml | TFText | TFDitaConcept | TFDitaTopic
deriving (Read, Eq, Show)
derivePersistField "TopicFormat"
newtype MapNodeSlug = MapNodeSlug { unMapNodeSlug :: Text }
deriving (Read, Eq, Show, PersistField, SinglePiece, Ord)
type MapNodeSlugs = [MapNodeSlug]
instance MultiPiece MapNodeSlugs where
toMultiPiece = map unMapNodeSlug
fromMultiPiece = fmap (map MapNodeSlug) . fromMultiPiece
newtype BlogSlugT = BlogSlugT Text
deriving (Read, Eq, Show, PersistField, SinglePiece, Ord)
newtype UserHandleT = UserHandleT { unUserHandle :: Text }
deriving (Read, Eq, Show, PersistField, SinglePiece, Ord)
newtype Month = Month Int
deriving (Read, Eq, Show, PersistField, Ord)
instance SinglePiece Month where
toSinglePiece (Month i)
| i < 10 && i >= 0 = pack $ '0' : show i
| otherwise = toSinglePiece i
fromSinglePiece t = do
i <- fromSinglePiece t
if i >= 1 && i <= 12
then Just $ Month i
else Nothing
formats :: [(Text, TopicFormat)]
formats =
[ ("Markdown", TFMarkdown)
, ("HTML", TFHtml)
, ("Plain text", TFText)
, ("DITA Concept", TFDitaConcept)
, ("DITA Topic", TFDitaTopic)
]
-- You can define all of your database entities in the entities file.
-- You can find more information on persistent and how to declare entities
-- at:
-- http://www.yesodweb.com/book/persistent/
share [mkPersist sqlSettings, mkMigrate "migrateAll", mkDeleteCascade] $(persistFile "config/models")
instance HasReps StaticContent where
chooseRep (StaticContent mt content) _ = return (mt, toContent $ decodeLenient content)
| snoyberg/yesodwiki | Model.hs | bsd-2-clause | 2,220 | 0 | 11 | 399 | 607 | 341 | 266 | 46 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.InstallDirs
-- Copyright : Isaac Jones 2003-2004
-- License : BSD3
--
-- Maintainer : cabal-devel@haskell.org
-- 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 Data.List (isPrefixOf)
import Data.Maybe (fromMaybe)
import GHC.Generics (Generic)
import System.Directory (getAppUserDataDirectory)
import System.FilePath ((</>), isPathSeparator, pathSeparator)
import System.FilePath (dropDrive)
import Distribution.Package
( PackageIdentifier, packageName, packageVersion, ComponentId )
import Distribution.System
( OS(..), buildOS, Platform(..) )
import Distribution.Compiler
( AbiTag(..), abiTagString, CompilerInfo(..), CompilerFlavor(..) )
import Distribution.Text
( display )
#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, Generic)
instance Binary dir => Binary (InstallDirs dir)
instance Functor InstallDirs where
fmap f dirs = InstallDirs {
prefix = f (prefix dirs),
bindir = f (bindir dirs),
libdir = f (libdir dirs),
libsubdir = f (libsubdir dirs),
dynlibdir = f (dynlibdir dirs),
libexecdir = f (libexecdir dirs),
includedir = f (includedir dirs),
datadir = f (datadir dirs),
datasubdir = f (datasubdir dirs),
docdir = f (docdir dirs),
mandir = f (mandir dirs),
htmldir = f (htmldir dirs),
haddockdir = f (haddockdir dirs),
sysconfdir = f (sysconfdir dirs)
}
instance (Semigroup dir, Monoid dir) => Monoid (InstallDirs dir) where
mempty = InstallDirs {
prefix = mempty,
bindir = mempty,
libdir = mempty,
libsubdir = mempty,
dynlibdir = mempty,
libexecdir = mempty,
includedir = mempty,
datadir = mempty,
datasubdir = mempty,
docdir = mempty,
mandir = mempty,
htmldir = mempty,
haddockdir = mempty,
sysconfdir = mempty
}
mappend = (Semi.<>)
instance Semigroup dir => Semigroup (InstallDirs dir) where
(<>) = combineInstallDirs (<>)
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",
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
-> ComponentId
-> 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
-> ComponentId
-> 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
| 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
-> ComponentId
-> CompilerInfo
-> Platform
-> PathTemplateEnv
initialPathTemplateEnv pkgId libname compiler platform =
packageTemplateEnv pkgId libname
++ compilerTemplateEnv compiler
++ platformTemplateEnv platform
++ abiTemplateEnv compiler platform
packageTemplateEnv :: PackageIdentifier -> ComponentId -> 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)
,(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 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)
,("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
| randen/cabal | Cabal/Distribution/Simple/InstallDirs.hs | bsd-3-clause | 23,729 | 2 | 16 | 6,590 | 4,602 | 2,583 | 2,019 | 395 | 10 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Ros.Sensor_msgs.JoyFeedback where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import qualified Data.Word as Word
import Foreign.Storable (Storable(..))
import qualified Ros.Internal.Util.StorableMonad as SM
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data JoyFeedback = JoyFeedback { __type :: Word.Word8
, _id :: Word.Word8
, _intensity :: P.Float
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''JoyFeedback)
instance RosBinary JoyFeedback where
put obj' = put (__type obj') *> put (_id obj') *> put (_intensity obj')
get = JoyFeedback <$> get <*> get <*> get
instance Storable JoyFeedback where
sizeOf _ = sizeOf (P.undefined::Word.Word8) +
sizeOf (P.undefined::Word.Word8) +
sizeOf (P.undefined::P.Float)
alignment _ = 8
peek = SM.runStorable (JoyFeedback <$> SM.peek <*> SM.peek <*> SM.peek)
poke ptr' obj' = SM.runStorable store' ptr'
where store' = SM.poke (__type obj') *> SM.poke (_id obj') *> SM.poke (_intensity obj')
instance MsgInfo JoyFeedback where
sourceMD5 _ = "f4dcd73460360d98f36e55ee7f2e46f1"
msgTypeName _ = "sensor_msgs/JoyFeedback"
instance D.Default JoyFeedback
type_led :: Word.Word8
type_led = 0
type_rumble :: Word.Word8
type_rumble = 1
type_buzzer :: Word.Word8
type_buzzer = 2
| acowley/roshask | msgs/Sensor_msgs/Ros/Sensor_msgs/JoyFeedback.hs | bsd-3-clause | 1,762 | 1 | 12 | 354 | 518 | 294 | 224 | 44 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
module Stack.Options.Completion
( ghcOptsCompleter
, targetCompleter
, flagCompleter
, projectExeCompleter
) where
import Data.Char (isSpace)
import Data.List (isPrefixOf)
import Data.List.Extra (nubOrd)
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Set as Set
import qualified Data.Text as T
import qualified Distribution.PackageDescription as C
import qualified Distribution.Types.UnqualComponentName as C
import Options.Applicative
import Options.Applicative.Builder.Extra
import Stack.Config (getLocalPackages)
import Stack.Options.GlobalParser (globalOptsFromMonoid)
import Stack.Runners (loadConfigWithOpts)
import Stack.Prelude hiding (lift)
import Stack.Setup
import Stack.Types.Config
import Stack.Types.FlagName
import Stack.Types.Package
import Stack.Types.PackageName
import System.Process (readProcess)
import Language.Haskell.TH.Syntax (runIO, lift)
ghcOptsCompleter :: Completer
ghcOptsCompleter = mkCompleter $ \inputRaw -> return $
let input = unescapeBashArg inputRaw
(curArgReversed, otherArgsReversed) = break isSpace (reverse input)
curArg = reverse curArgReversed
otherArgs = reverse otherArgsReversed
in if null curArg then [] else
map (otherArgs ++) $
filter (curArg `isPrefixOf`)
-- Technically, we should be consulting the user's current ghc,
-- but that would require loading up a BuildConfig.
$(runIO (readProcess "ghc" ["--show-options"] "") >>= lift . lines)
-- TODO: Ideally this would pay attention to --stack-yaml, may require
-- changes to optparse-applicative.
buildConfigCompleter
:: (String -> RIO EnvConfig [String])
-> Completer
buildConfigCompleter inner = mkCompleter $ \inputRaw -> do
let input = unescapeBashArg inputRaw
case input of
-- If it looks like a flag, skip this more costly completion.
('-': _) -> return []
_ -> do
let go = (globalOptsFromMonoid False mempty)
{ globalLogLevel = LevelOther "silent" }
loadConfigWithOpts go $ \lc -> do
bconfig <- liftIO $ lcLoadBuildConfig lc (globalCompiler go)
envConfig <- runRIO bconfig (setupEnv Nothing)
runRIO envConfig (inner input)
targetCompleter :: Completer
targetCompleter = buildConfigCompleter $ \input -> do
lpvs <- fmap lpProject getLocalPackages
return $
filter (input `isPrefixOf`) $
concatMap allComponentNames (Map.toList lpvs)
where
allComponentNames (name, lpv) =
map (T.unpack . renderPkgComponent . (name,)) (Set.toList (lpvComponents lpv))
flagCompleter :: Completer
flagCompleter = buildConfigCompleter $ \input -> do
lpvs <- fmap lpProject getLocalPackages
bconfig <- view buildConfigL
let wildcardFlags
= nubOrd
$ concatMap (\(name, lpv) ->
map (\fl -> "*:" ++ flagString name fl) (C.genPackageFlags (lpvGPD lpv)))
$ Map.toList lpvs
normalFlags
= concatMap (\(name, lpv) ->
map (\fl -> packageNameString name ++ ":" ++ flagString name fl)
(C.genPackageFlags (lpvGPD lpv)))
$ Map.toList lpvs
flagString name fl =
let flname = C.unFlagName $ C.flagName fl
in (if flagEnabled name fl then "-" else "") ++ flname
flagEnabled name fl =
fromMaybe (C.flagDefault fl) $
Map.lookup (fromCabalFlagName (C.flagName fl)) $
Map.findWithDefault Map.empty name (bcFlags bconfig)
return $ filter (input `isPrefixOf`) $
case input of
('*' : ':' : _) -> wildcardFlags
('*' : _) -> wildcardFlags
_ -> normalFlags
projectExeCompleter :: Completer
projectExeCompleter = buildConfigCompleter $ \input -> do
lpvs <- fmap lpProject getLocalPackages
return $
filter (input `isPrefixOf`) $
nubOrd $
concatMap (\(_, lpv) -> map (C.unUnqualComponentName . fst) (C.condExecutables (lpvGPD lpv))) $
Map.toList lpvs
| MichielDerhaeg/stack | src/Stack/Options/Completion.hs | bsd-3-clause | 4,421 | 2 | 23 | 1,230 | 1,131 | 608 | 523 | 97 | 4 |
module Tandoori.Typing.Substitute where
-- module Tandoori.Ty.Substitute (Substitution, substCTy, addSubst, emptySubst, substTy) where
import Tandoori.Typing
import Control.Monad
import Control.Monad.RWS
import qualified Data.Map as Map
import qualified Data.Set as Set
newtype Subst = S (Map.Map Tv Ty)
emptySubst :: Subst
emptySubst = S Map.empty
getSubst :: Tv -> Subst -> Maybe Ty
getSubst Ξ± (S m) = Map.lookup Ξ± m
addSubst :: Tv -> Ty -> Subst -> Subst
addSubst Ξ± Ο (S m) = S $ Map.insert Ξ± Ο m
substTyM Ο@(TyVar Ξ±) = do tell $ Set.singleton Ξ±
lookup <- asks $ getSubst Ξ±
case lookup of
Nothing -> return Ο
Just Ο' -> substTyM Ο'
substTyM (TyFun Ο1 Ο2) = liftM2 TyFun (substTyM Ο1) (substTyM Ο2)
substTyM (TyApp Ο1 Ο2) = liftM2 TyApp (substTyM Ο1) (substTyM Ο2)
substTyM Ο@(TyCon _) = return Ο
substTyM Ο@(TyTuple _) = return Ο
substTy :: Subst -> Ty -> Ty
substTy s Ο = fst $ evalRWS (substTyM Ο) s ()
| bitemyapp/tandoori | src/Tandoori/Typing/Substitute.hs | bsd-3-clause | 1,079 | 0 | 10 | 302 | 383 | 196 | 187 | 24 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
module Bead.View.Headers.AcceptLanguage (
setLanguageFromAcceptLanguage
#ifdef TEST
, acceptLanguageTests
#endif
) where
import qualified Data.ByteString.Char8 as BS
import Data.List (nub, intersect)
import Data.Maybe
import Data.String.Utils
import Prelude hiding (id)
import Bead.Domain.Entities (Language(..))
import Bead.Domain.Types (readMaybe)
import Bead.View.BeadContext
import Bead.View.Content hiding (BlazeTemplate, template)
import Bead.View.Session (setLanguageInSession)
#ifdef TEST
import Test.Tasty.TestSet
#endif
setLanguageFromAcceptLanguage :: BeadHandler' b ()
setLanguageFromAcceptLanguage = do
acceptLanguages <- getHeaders "Accept-Language" <$> getRequest
case acceptLanguages of
Nothing -> return ()
Just ls -> do
let languages = nub . map acceptLanguageToLanguage
. concat
$ map (parseAcceptLanguageLine . BS.unpack) ls
dictionaryLanguages <- map fst <$> dcGetDictionaryInfos
let selectedLang = languages `intersect` dictionaryLanguages
case selectedLang of
[] -> return ()
(l:_) -> setLanguageInSession l
-- The possible accept langauge value in the Accept-Language headers
data AcceptLanguage
= AL_Simple String
| AL_Quality String Double
deriving (Eq, Show)
-- Eg:
-- AL_Simple "en-US" represents "en-US"
-- AL_quality "en" 0.5 represents "en;q=0.5"
acceptLanguage
simple
quality
al = case al of
AL_Simple s -> simple s
AL_Quality s q -> quality s q
parseAcceptLangValue :: String -> Maybe AcceptLanguage
parseAcceptLangValue s = case split ";" s of
[lang] -> Just $ AL_Simple lang
[lang, 'q':'=':q] -> AL_Quality lang <$> readMaybe q
_ -> Nothing
parseAcceptLanguageLine :: String -> [AcceptLanguage]
parseAcceptLanguageLine = catMaybes . map (parseAcceptLangValue . strip) . split ","
-- Convert an accept language to language dropping the localization
-- and the quality informations
acceptLanguageToLanguage = acceptLanguage
(Language . dropLocalization)
(\lang _q -> Language $ dropLocalization lang)
where
dropLocalization = takeWhile (/='-')
#ifdef TEST
acceptLanguageTests = group "accpetLanguage" $ do
group "parse" $ do
eqPartitions parseAcceptLangValue
[ Partition "accept language parse empty string" "" Nothing "Empty string is parsed"
, Partition "simple accept language" "en-US" (Just $ AL_Simple "en-US") "Simple language parameter is not parsed correctly"
, Partition "simple accept language" "en;q=0.5" (Just $ AL_Quality "en" 0.5) "Simple language parameter is not parsed correctly"
, Partition "noise for accept langauge" "qns;sdjfkj" Nothing "Noise is parsed"
]
assertEquals
"accept language line"
[AL_Simple "en-US", AL_Quality "en" 0.5]
(parseAcceptLanguageLine "en-US , en;q=0.5")
"Parse line missed some of the arguments"
group "accept language to language" $ eqPartitions acceptLanguageToLanguage
[ Partition "Simple with localization" (AL_Simple "en-US") (Language "en") "Drop localization has failed"
, Partition "Quality with localization" (AL_Quality "en-US" 0.5) (Language "en") "Drop localization has failed"
]
#endif
| andorp/bead | src/Bead/View/Headers/AcceptLanguage.hs | bsd-3-clause | 3,407 | 0 | 19 | 759 | 732 | 386 | 346 | 49 | 3 |
module MediaWiki.API.Query.WatchList.Import where
import MediaWiki.API.Types
import MediaWiki.API.Utils
import MediaWiki.API.Query.WatchList
import Text.XML.Light.Types
import Control.Monad
import Data.Maybe
stringXml :: String -> Either (String,[{-Error msg-}String]) WatchListResponse
stringXml s = parseDoc xml s
xml :: Element -> Maybe WatchListResponse
xml e = do
guard (elName e == nsName "api")
let es1 = children e
p <- pNode "query" es1
let es = children p
wl <- pNode "watchlist" es >>= xmlWatchList
let cont = pNode "query-continue" es1 >>= xmlContinue "watchlist" "wlstart"
return emptyWatchListResponse{wlWatch=wl,wlContinue=cont}
xmlWatchList :: Element -> Maybe WatchList
xmlWatchList e = do
guard (elName e == nsName "watchlist")
let ns = fromMaybe "0" $ pAttr "ns" e
let tit = fromMaybe "" $ pAttr "title" e
let pid = pAttr "pageid" e
let rid = pAttr "revid" e
let usr = pAttr "user" e
let isa = isJust (pAttr "anon" e)
let isn = isJust (pAttr "new" e)
let ism = isJust (pAttr "minor" e)
let isp = isJust (pAttr "patrolled" e)
let ts = pAttr "timestamp" e
let len = pAttr "newlen" e >>= readMb
let leno = pAttr "oldlen" e >>= readMb
let co = pAttr "comment" e
let pg = emptyPageTitle{pgNS=ns,pgTitle=tit,pgMbId=pid}
return emptyWatchList
{ wlPage = pg
, wlRevId = rid
, wlUser = usr
, wlIsAnon = isa
, wlIsNew = isn
, wlIsMinor = ism
, wlIsPatrolled = isp
, wlTimestamp = ts
, wlLength = len
, wlOldLength = leno
, wlComment = co
}
| HyperGainZ/neobot | mediawiki/MediaWiki/API/Query/WatchList/Import.hs | bsd-3-clause | 1,616 | 0 | 12 | 405 | 586 | 294 | 292 | 47 | 1 |
module WhereIn1 where
--A definition can be lifted from a where or let into the surronding binding group.
--Lifting a definition widens the scope of the definition.
--In this example, lift 'sq' in 'sumSquares'
--This example aims to test add parameters to 'sq'.
sumSquares x y = (sq pow) x + (sq pow) y
where
pow=2
sq pow 0 = 0
sq pow z = z^pow
anotherFun 0 y = sq y
where sq x = x^2
| SAdams601/HaRe | old/testing/liftOneLevel/WhereIn1_TokOut.hs | bsd-3-clause | 433 | 0 | 8 | 126 | 98 | 51 | 47 | 7 | 1 |
{-# OPTIONS -cpp #-}
module Map (
Map,
empty, singleton,
lookup, findWithDefault,
insert,
union, unionWith,
map,
fromList, toList
) where
import Prelude hiding (lookup, map)
#if __GLASGOW_HASKELL__ >= 603 || !__GLASGOW_HASKELL__
import Data.Map
#else
import Data.FiniteMap
type Map k a = FiniteMap k a
empty :: Map k a
empty = emptyFM
singleton :: k -> a -> Map k a
singleton = unitFM
lookup :: Ord k => k -> Map k a -> Maybe a
lookup = flip lookupFM
findWithDefault :: Ord k => a -> k -> Map k a -> a
findWithDefault a k m = lookupWithDefaultFM m a k
insert :: Ord k => k -> a -> Map k a -> Map k a
insert k a m = addToFM m k a
insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a
insertWith c k a m = addToFM_C (flip c) m k a
union :: Ord k => Map k a -> Map k a -> Map k a
union = flip plusFM
unionWith :: Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
unionWith c l r = plusFM_C (flip c) r l
map :: (a -> b) -> Map k a -> Map k b
map f = mapFM (\_ -> f)
fromList :: Ord k => [(k,a)] -> Map k a
fromList = listToFM
toList :: Map k a -> [(k, a)]
toList = fmToList
#endif
| k0001/gtk2hs | tools/c2hs/base/general/Map.hs | gpl-3.0 | 1,135 | 0 | 5 | 297 | 60 | 41 | 19 | 11 | 0 |
module LiftToToplevel.A2 where
import LiftToToplevel.C2
main = sumSquares [1..4] + anotherFun [1..4]
| kmate/HaRe | test/testdata/LiftToToplevel/A2.hs | bsd-3-clause | 108 | 0 | 7 | 19 | 36 | 20 | 16 | 3 | 1 |
{-# LANGUAGE CPP #-}
#define MODULE_NAME Windows
#define IS_WINDOWS True
#include "Internal.hs"
| juhp/stack | test/integration/tests/mutable-deps/files/filepath-1.4.2.1/System/FilePath/Windows.hs | bsd-3-clause | 105 | 0 | 2 | 21 | 6 | 5 | 1 | 1 | 0 |
module Imp where
{-@ inline implies @-}
implies p q = (not p) || q
| mightymoose/liquidhaskell | tests/pos/implies.hs | bsd-3-clause | 69 | 0 | 7 | 17 | 25 | 14 | 11 | 2 | 1 |
-- If care is not taken when aborting a fixed-point iteration, wrong absentness
-- information escapes
-- Needs to be a product type
data Stream = S Int Stream
bar :: Int -> Stream -> Int
bar n s = foo n s
where
foo :: Int -> Stream -> Int
foo 0 (S n s) = 0
foo i (S n s) = n + foo (i-1) s
{-# NOINLINE bar #-}
baz :: Int -> Stream -> Int
baz 0 not_absent = 0
baz 1 not_absent = baz 2 not_absent
baz x not_absent = bar 1000 arg
where
arg = S 1 $ S 1 $ S 1 $ S 1 $ S 1 $ S 1 $ S 1 $ S 1 $ S 1 $ S 1 $ not_absent
bamf x = baz x (S x (error "This is good!"))
{-# NOINLINE bamf #-}
main :: IO ()
main = bamf 10 `seq` return ()
| ezyang/ghc | testsuite/tests/stranal/should_run/T12368.hs | bsd-3-clause | 649 | 0 | 17 | 185 | 298 | 147 | 151 | 16 | 2 |
-- /tmp/panic.hs
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableSuperClasses #-}
{-# OPTIONS_GHC -fdefer-type-errors #-}
module T11254 where
class (Frac (Frac a) ~ Frac a, Fractional (Frac a), ID (Frac a)) => ID a where
type Frac a
embed :: a -> Frac a
instance ID Rational where
type Frac Rational = Int
embed :: Rational -> Rational
embed = undefined
| ezyang/ghc | testsuite/tests/typecheck/should_compile/T11254.hs | bsd-3-clause | 548 | 0 | 10 | 127 | 115 | 64 | 51 | 15 | 0 |
-- Generate.hs
module Graphter.Generate where
import Graphter.Representation
import Data.List
--
-- Generate complete graph
--
completeGraph :: Type -> Int -> Graph
completeGraph graphType vertexCount = Graph graphType vertices
[uncurry Edge edge 0 | edge <-
if (==) graphType Directed
then edges
else removeDuplicates edges]
where
vertices = [Vertex (show name) 0 | name <- [1..vertexCount]]
edges = [(from, to) | from <- vertices, to <- vertices, (/=) from to]
tupleEq (x, y) (u, v) = ((==) x u && (==) y v) || ((==) x v && (==) y u)
removeDuplicates = nubBy tupleEq
--
-- Generate complete bipartite graph
--
completeBipartiteGraph :: Type -> Int -> Int -> Graph
completeBipartiteGraph _ 0 _ = error "Partite set cannot contains 0 vertices."
completeBipartiteGraph _ _ 0 = error "Partite set cannot contains 0 vertices."
completeBipartiteGraph kind x y = Graph kind ((++) verticesSet1 verticesSet2) edges
where
verticesSet1 = [Vertex (show name) 0 | name <- [1..x]]
verticesSet2 = [Vertex (show name) 0 | name <- [((+) x 1)..((+) y x)]]
edges = if (==) kind Directed
then (++) [Edge from to 0
| from <- verticesSet1, to <- verticesSet2]
[Edge from to 0 | from <- verticesSet2, to <- verticesSet1]
else [Edge from to 0 | from <- verticesSet1, to <- verticesSet2]
| martinstarman/graphter | src/Graphter/Generate.hs | mit | 1,434 | 0 | 12 | 382 | 507 | 275 | 232 | 24 | 2 |
module Cmm.CmmMachOp where
import Cmm.CmmType
data MachOp
= MO_Add Width
| MO_Sub Width
| MO_Eq Width
| MO_NE Width
| MO_Mul Width
-- Signed comparisons
| MO_S_Ge Width
| MO_S_Le Width
| MO_S_Gt Width
| MO_S_Lt Width
-- Unsigned comparisons
| MO_U_Ge Width
| MO_U_Le Width
| MO_U_Gt Width
| MO_U_Lt Width
-- Bitwise Ops
| MO_And Width
| MO_Or Width
| MO_Xor Width
| MO_Not Width
| MO_Shl Width
| MO_U_Shr Width -- unsigned shift right
| MO_S_Shr Width -- signed shift right
deriving (Eq,Show)
data CallishMachOp
= MO_F64_Pwr
| MO_F64_Sin
| MO_F64_Cos
| MO_F64_Tan
| MO_F64_Sinh
| MO_F64_Cosh
| MO_F64_Tanh
| MO_F64_Asin
| MO_F64_Acos
| MO_F64_Atan
| MO_F64_Log
| MO_F64_Exp
| MO_F64_Fabs
| MO_F64_Sqrt
| MO_F32_Pwr
| MO_F32_Sin
| MO_F32_Cos
| MO_F32_Tan
| MO_F32_Sinh
| MO_F32_Cosh
| MO_F32_Tanh
| MO_F32_Asin
| MO_F32_Acos
| MO_F32_Atan
| MO_F32_Log
| MO_F32_Exp
| MO_F32_Fabs
| MO_F32_Sqrt
| MO_UF_Conv Width
| MO_S_QuotRem Width
| MO_U_QuotRem Width
| MO_U_QuotRem2 Width
| MO_Add2 Width
| MO_SubWordC Width
| MO_AddIntC Width
| MO_SubIntC Width
| MO_U_Mul2 Width
| MO_WriteBarrier
| MO_Touch -- Keep variables live (when using interior pointers)
-- Prefetch
| MO_Prefetch_Data Int -- Prefetch hint. May change program performance but not
-- program behavior.
-- the Int can be 0-3. Needs to be known at compile time
-- to interact with code generation correctly.
-- TODO: add support for prefetch WRITES,
-- currently only exposes prefetch reads, which
-- would the majority of use cases in ghc anyways
-- These three MachOps are parameterised by the known alignment
-- of the destination and source (for memcpy/memmove) pointers.
-- This information may be used for optimisation in backends.
| MO_Memcpy Int
| MO_Memset Int
| MO_Memmove Int
| MO_PopCnt Width
| MO_Clz Width
| MO_Ctz Width
| MO_BSwap Width
-- Atomic read-modify-write.
| MO_AtomicRMW Width AtomicMachOp
| MO_AtomicRead Width
| MO_AtomicWrite Width
| MO_Cmpxchg Width
deriving (Eq, Show)
data AtomicMachOp
= AMO_Add
| AMO_Sub
| AMO_And
| AMO_OR
| AMO_Xor
deriving (Eq,Show)
| C-Elegans/linear | Cmm/CmmMachOp.hs | mit | 2,590 | 0 | 6 | 873 | 386 | 243 | 143 | 84 | 0 |
-- Esolang Interpreters #1 - Introduction to Esolangs and My First Interpreter (MiniStringFuck)
-- https://www.codewars.com/kata/586dd26a69b6fd46dd0000c0
module MiniStringFuck where
import Data.Char (chr)
myFirstInterpreter :: String -> String
myFirstInterpreter = reverse . snd . foldl (\(m, o) c -> if c == '.' then (m, chr m : o) else ((`mod` 256) . succ $ m, o)) (0, "") . filter (`elem` ".+")
| gafiatulin/codewars | src/6 kyu/MiniStringFuck.hs | mit | 401 | 0 | 14 | 64 | 123 | 74 | 49 | 4 | 2 |
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys | v0lkan/learning-haskell | higher-order.hs | mit | 199 | 0 | 8 | 54 | 151 | 78 | 73 | 6 | 1 |
-- | Translation from Agda internal terms to the target logic.
{-# LANGUAGE CPP #-}
{-# LANGUAGE UnicodeSyntax #-}
module Apia.Translation.Terms
( agdaTermToFormula
, agdaTermToTerm
) where
------------------------------------------------------------------------------
import Apia.Prelude
import Agda.Syntax.Abstract.Name ( Name(nameConcrete) , QName(QName) )
import Agda.Syntax.Common
( Arg(Arg, argInfo, unArg)
, ArgInfo(ArgInfo, argInfoHiding)
, Dom(Dom, unDom)
, Hiding(Hidden, NotHidden)
, Nat
)
import qualified Agda.Syntax.Concrete.Name as C
( Name(Name, NoName)
, NamePart(Id, Hole)
)
import Agda.Syntax.Internal as I
( Abs(Abs, NoAbs)
, allApplyElims
, Args
, ConHead(ConHead)
, Elim
, Elim'(Apply, IApply, Proj)
, Elims
, Level(Max)
, PlusLevel(ClosedLevel)
, Sort(Type)
, Term(Con, Def, Lam, Pi, Sort, Var)
, Type'(El)
)
import Agda.Syntax.Position ( noRange )
import Agda.Utils.Impossible ( Impossible(Impossible), throwImpossible )
import Agda.Utils.Monad ( ifM )
import Apia.FOL.Constants
( lTrue
, lFalse
, lNot
, lAnd
, lOr
, lCond
, lBicond1
, lBicond2
, lExists
, lForAll
, lEquals
)
import Apia.FOL.Primitives ( appF, appP )
import Apia.FOL.Types as L
( LFormula( And
, Bicond
, Cond
, Eq
, Exists
, FALSE
, ForAll
, Not
, Or
, Predicate
, TRUE
)
, LTerm(Fun, Var)
)
import Apia.Monad.Base
( askTOpt
, getTVars
, newTVar
, popTVar
, pushTNewVar
, T
, tErr
, TErr ( IncompatibleCLOptions
, NoImplementedOption
, UniversalQuantificationError
)
)
import Apia.Monad.Reports ( reportDLn, reportSLn )
import Apia.Options
( Options ( optFnConstant
, optNoInternalEquality
, optNoPredicateConstants
, optSchematicFunctions
, optSchematicPropositionalFunctions
, optSchematicPropositionalSymbols
)
)
import {-# source #-} Apia.Translation.Types
( agdaDomTypeToFormula
, agdaTypeToFormula
)
-- import Apia.Utils.AgdaAPI.IgnoreSharing ( IgnoreSharing(ignoreSharing) )
import Apia.Utils.AgdaAPI.Interface ( qNameToUniqueString )
import Apia.Utils.PrettyPrint ( (<>), Pretty(pretty) )
#include "undefined.h"
------------------------------------------------------------------------------
agdaArgTermToFormula β· Arg Term β T LFormula
agdaArgTermToFormula Arg {argInfo = info, unArg = t} =
case info of
ArgInfo { argInfoHiding = NotHidden } β agdaTermToFormula t
_ β __IMPOSSIBLE__
agdaArgTermToTerm β· Arg Term β T LTerm
agdaArgTermToTerm Arg {argInfo = info, unArg = t} =
case info of
ArgInfo { argInfoHiding = Hidden } β agdaTermToTerm t
ArgInfo { argInfoHiding = NotHidden } β agdaTermToTerm t
_ β __IMPOSSIBLE__
binConst β· (LFormula β LFormula β LFormula) β
Arg Term β
Arg Term β
T LFormula
binConst op arg1 arg2 =
liftM2 op (agdaArgTermToFormula arg1) (agdaArgTermToFormula arg2)
elimToTerm β· Elim β T LTerm
elimToTerm (Apply arg) = agdaArgTermToTerm arg
elimToTerm (Proj _ _) = __IMPOSSIBLE__
elimToTerm IApply{} = __IMPOSSIBLE__
-- Translation of predicates.
predicate β· QName β Elims β T LFormula
predicate qName elims = do
pName β qNameToUniqueString qName
lTerms β mapM elimToTerm elims
case length elims of
0 β __IMPOSSIBLE__
_ β ifM (askTOpt optNoPredicateConstants)
-- Direct translation.
(return $ Predicate pName lTerms)
-- Translation using Koen's suggestion.
(return $ appP (Fun pName []) lTerms)
propositionalFunctionScheme β· [String] β Nat β Elims β T LFormula
propositionalFunctionScheme vars n elims = do
let var β· String
var = vars !! n
case length elims of
0 β __IMPOSSIBLE__
_ β fmap (appP (L.Var var)) (mapM elimToTerm elims)
-- | Translate an Agda internal 'Term' to a target logic formula.
agdaTermToFormula β· Term β T LFormula
agdaTermToFormula term'@(Def qName@(QName _ name) elims) = do
reportSLn "t2f" 10 $ "agdaTermToFormula Def:\n" ++ show term'
let cName β· C.Name
cName = nameConcrete name
case cName of
C.NoName{} β __IMPOSSIBLE__
C.Name _ [] β __IMPOSSIBLE__
C.Name{} β
case allApplyElims elims of
Nothing β __IMPOSSIBLE__
Just [] | isCNameLogicConst lTrue β return TRUE
| isCNameLogicConst lFalse β return FALSE
| otherwise β
-- In this guard we translate 0-ary predicates, i.e.
-- propositional functions, for example, AΒ :Β Set.
flip Predicate [] <$> qNameToUniqueString qName
Just [a]
| isCNameHoleRight lNot β fmap Not (agdaArgTermToFormula a)
| isCNameLogicConst lExists ||
isCNameLogicConst lForAll β do
fm β agdaArgTermToFormula a
freshVar β newTVar
return $ if isCNameLogicConst lExists
then Exists freshVar $ const fm
else ForAll freshVar $ const fm
| otherwise β predicate qName elims
Just [a1, a2]
| isCNameTwoHoles lAnd β binConst And a1 a2
| isCNameTwoHoles lOr β binConst Or a1 a2
| isCNameTwoHoles lCond β binConst Cond a1 a2
| isCNameTwoHoles lBicond1
|| isCNameTwoHoles lBicond2 β binConst Bicond a1 a2
| isCNameTwoHoles lEquals β do
reportSLn "t2f" 20 "Processing equals"
ifM (askTOpt optNoInternalEquality)
-- Not using the ATPs internal equality.
(predicate qName elims)
-- Using the ATPs internal equality.
(liftM2 Eq (agdaArgTermToTerm a1) (agdaArgTermToTerm a2))
| otherwise β predicate qName elims
_ β predicate qName elims
where
isCNameLogicConst β· String β Bool
isCNameLogicConst lConst =
-- The equality on the data type @C.Name@ is defined to
-- ignore ranges, so we use @noRange@.
cName == C.Name noRange [C.Id lConst]
isCNameHoleRight β· String β Bool
isCNameHoleRight lConst =
-- The operators are represented by a list with @Hole@'s.
-- See the documentation for @C.Name@.
cName == C.Name noRange [C.Id lConst, C.Hole]
isCNameTwoHoles β· String β Bool
isCNameTwoHoles lConst =
-- The operators are represented by a list with @Hole@'s. See
-- the documentation for @C.Name@.
cName == C.Name noRange [C.Hole, C.Id lConst, C.Hole]
agdaTermToFormula term'@(Lam _ (Abs _ termLam)) = do
reportSLn "t2f" 10 $ "agdaTermToFormula Lam:\n" ++ show term'
_ β pushTNewVar
f β agdaTermToFormula termLam
popTVar
return f
agdaTermToFormula (Pi domTy (Abs x absTy)) = do
reportSLn "t2f" 10 $
"agdaTermToFormula Pi _ (Abs _ _):\n"
++ "domTy: " ++ show domTy ++ "\n"
++ "absTy: " ++ show (Abs x absTy)
freshVar β pushTNewVar
reportSLn "t2f" 20 $
"Starting processing in local environment with fresh variable "
++ show freshVar ++ " and type:\n" ++ show absTy
f β agdaTypeToFormula absTy
popTVar
reportSLn "t2f" 20 $
"Finalized processing in local environment with fresh variable "
++ show freshVar ++ " and type:\n" ++ show absTy
reportDLn "t2f" 20 $ pretty "The formula f is: " <> pretty f
case unDom domTy of
-- The bounded variable is quantified on a @Set@,
--
-- e.g. the bounded variable is @d : D@ where @D : Set@,
--
-- so we can create a fresh variable and quantify on it without
-- any problem.
--
-- N.B. the pattern matching on @(Def _ [])@.
El (Type (Max [])) (Def _ []) β do
reportSLn "t2f" 20 $
"Adding universal quantification on variable " ++ show freshVar
return $ ForAll freshVar $ const f
-- The bounded variable is quantified on a proof. Due to we have
-- drop the quantification on proofs terms, this case is
-- impossible.
El (Type (Max [])) (Def _ _) β __IMPOSSIBLE__
-- Non-FOL translation: First-order logic universal quantified
-- functions term.
--
-- The bounded variable is quantified on a function of a @Set@
-- to a @Set@,
--
-- e.g. the bounded variable is @f : D β D@, where @D : Set@.
--
-- In this case we handle the bounded variable/function as a FOL
-- variable in @agdaTermToTerm (Var n args)@, which is processed
-- first due to lazyness. We quantified on this variable.
El (Type (Max []))
(Pi (Dom _ _ (El (Type (Max [])) (Def _ [])))
(NoAbs _ (El (Type (Max [])) (Def _ [])))) β do
reportSLn "t2f" 20
"Removing a quantification on a function of a Set to a Set"
return $ ForAll freshVar $ const f
-- N.B. The next case is just a generalization to various
-- arguments of the previous case.
-- Non-FOL translation: First-order logic universal quantified
-- functions term.
--
-- The bounded variable is quantified on a function of a @Set@
-- to a @Set@,
--
-- e.g. the bounded variable is @f : D β D β D@, where
-- @DΒ :Β Set@.
--
-- In this case we handle the bounded variable/function as a FOL
-- variable in @agdaTermToTerm (Var n args)@, which is processed
-- first due to lazyness. We quantified on this variable.
El (Type (Max []))
(Pi (Dom _ _ (El (Type (Max [])) (Def _ [])))
(NoAbs _ (El (Type (Max [])) (Pi _ (NoAbs _ _))))) β do
reportSLn "t2f" 20
"Removing a quantification on a function of a Set to a Set"
-- 31 May 2012. We don't have an example of this case.
--
-- return $ ForAll freshVar (\_ β f)
__IMPOSSIBLE__
El (Type (Max [])) someTerm β do
reportSLn "t2f" 20 $ "The term someterm is: " ++ show someTerm
__IMPOSSIBLE__
-- Non-FOL translation: First-order logic universal quantified
-- propositional functions.
--
-- The bounded variable is quantified on a @Setβ@,
--
-- e.g. the bounded variable is @A : D β D β Set@.
--
-- In this case we return a forall bind on the fresh variable. We
-- use this case for translate logic schemata such as
--
-- β¨-commβ : {Aβ Bβ : D β D β Set}{x y : D} β
-- Aβ x y β¨ Bβ x y β Aβ x y β¨ Bβ x y.
El (Type (Max [ClosedLevel 1])) (Pi _ (NoAbs _ _)) β do
reportSLn "t2f" 20 $ "The type domTy is: " ++ show domTy
return $ ForAll freshVar $ const f
-- Non-FOL translation: First-order logic universal quantified
-- propositional symbols.
--
-- The bounded variable is quantified on a @Setβ@,
--
-- e.g. the bounded variable is @A : Set@,
--
-- so we just return the consequent. We use this case for
-- translating logical schemata such
--
-- @β¨-comm : {A B : Set} β A β¨ B β B β¨ A@.
--
-- In this case we handle the bounded variable/function in
-- @agdaTermToFormula (Var n args)@, which is processed first due to
-- lazyness.
El (Type (Max [ClosedLevel 1])) (Sort _) β do
reportSLn "t2f" 20 $ "The type domTy is: " ++ show domTy
let p β· String
p = "--schematic-propositional-symbols"
ifM (askTOpt optSchematicPropositionalSymbols)
(return f)
(tErr $ UniversalQuantificationError p)
someType β do
reportSLn "t2f" 20 $ "The type domTy is: " ++ show someType
__IMPOSSIBLE__
agdaTermToFormula (Pi domTy (NoAbs x absTy)) = do
reportSLn "t2f" 10 $
"agdaTermToFormula Pi _ (NoAbs _ _):\n"
++ "domTy: " ++ show domTy ++ "\n"
++ "absTy: " ++ show (NoAbs x absTy)
f2 β agdaTypeToFormula absTy
if x /= "_"
then
case unDom domTy of
-- The variable @x@ is an universal quantified variable not
-- used, thefefore we generate a quantified first-order
-- logic formula.
El (Type (Max [])) (Def _ []) β do
freshVar β newTVar
return $ ForAll freshVar $ const f2
-- The variable @x@ is a proof term, therefore we erase the
-- quantification on it.
El (Type (Max [])) (Def _ _) β do
f1 β agdaDomTypeToFormula domTy
return $ Cond f1 f2
-- The variable in @domTy@ has type @Setβ@
-- (e.g. AΒ :Β DΒ βΒ Set) and it isn't used, so we omit it.
El (Type (Max [ClosedLevel 1])) (Pi _ (NoAbs _ _)) β return f2
someType β do
reportSLn "t2f" 20 $ "The type domTy is: " ++ show someType
__IMPOSSIBLE__
else do
f1 β agdaDomTypeToFormula domTy
return $ Cond f1 f2
agdaTermToFormula term'@(I.Var n elims) = do
reportSLn "t2f" 10 $ "agdaTermToFormula Var: " ++ show term'
when (n < 0) (__IMPOSSIBLE__)
vars β getTVars
-- We also test for equality because the first argument of @I.Var@
-- doesn't start in one but in zero.
when (length vars == n) (__IMPOSSIBLE__)
when (length vars < n) (__IMPOSSIBLE__)
case elims of
-- N.B. In this case we *don't* use Koen's approach.
[] β return $ Predicate (vars !! n) []
-- Non-FOL translation: First-order logic universal quantified
-- propositional functions.
-- If we have a bounded variable quantified on a function of a
-- @Set@ to a @Setβ@, for example, the variable/function @A@ in
--
-- @(A : D β Set) β (x : D) β A x β A x@
--
-- we are quantifying on this variable/function
--
-- (see @agdaTermToFormula (Pi domTy (Abs _ absTy))@),
--
-- therefore we need to apply this variable/function to the
-- others variables.
_ β do
let p β· String
p = "--schematic-propositional-functions"
ifM (askTOpt optSchematicPropositionalFunctions)
(ifM (askTOpt optNoPredicateConstants)
(tErr $ IncompatibleCLOptions
"--schematic-propositional-functions"
"--no-predicate-constants"
)
(propositionalFunctionScheme vars n elims)
)
(tErr $ UniversalQuantificationError p)
agdaTermToFormula term' = do
reportSLn "t2f" 20 $ "term: " ++ show term'
__IMPOSSIBLE__
-- Translate the function @foo x1 ... xn@.
appArgsF β· String β Args β T LTerm
appArgsF fn args = do
lTerms β mapM agdaArgTermToTerm args
ifM (askTOpt optFnConstant)
-- Translation using a hard-coded binary function symbol.
(return $ foldl' appF (Fun fn []) lTerms)
-- Direct translation.
(return $ Fun fn lTerms)
-- | Translate an Agda internal 'Term' to a target logic term.
agdaTermToTerm β· Term β T LTerm
agdaTermToTerm term'@(Con (ConHead (QName _ name) _ _) _ elims) = do
reportSLn "t2t" 10 $ "agdaTermToTerm Con:\n" ++ show term'
let cName β· C.Name
cName = nameConcrete name
case cName of
C.NoName{} β __IMPOSSIBLE__
C.Name _ [] β __IMPOSSIBLE__
-- The term @Con@ doesn't have holes. It should be translated as
-- a first-order logic function.
C.Name _ [C.Id str] β
case allApplyElims elims of
Nothing β __IMPOSSIBLE__
Just [] β return $ Fun str []
Just args β appArgsF str args
-- The term @Con@ has holes. It is translated as a first-order
-- logic function.
C.Name _ _ β __IMPOSSIBLE__
-- 2012-04-22: We do not have an example of it.
-- C.Name _ parts β
-- case args of
-- [] β __IMPOSSIBLE__
-- _ β appArgsFn (concatName parts) args
agdaTermToTerm term'@(Def qName@(QName _ name) elims) = do
reportSLn "t2t" 10 $ "agdaTermToTerm Def:\n" ++ show term'
let cName β· C.Name
cName = nameConcrete name
case cName of
C.NoName{} β __IMPOSSIBLE__
C.Name _ [] β __IMPOSSIBLE__
-- The term @Def@ doesn't have holes. It is translated as a
-- first-order logic function.
C.Name _ [C.Id _] β
case allApplyElims elims of
Nothing β __IMPOSSIBLE__
Just [] β flip Fun [] <$> qNameToUniqueString qName
Just args β qNameToUniqueString qName >>= flip appArgsF args
-- The term @Def@ has holes. It is translated as a first-order
-- logic function.
C.Name _ _ β
case allApplyElims elims of
Nothing β __IMPOSSIBLE__
Just [] β __IMPOSSIBLE__
Just args β qNameToUniqueString qName >>= flip appArgsF args
agdaTermToTerm term'@(Lam ArgInfo{argInfoHiding = NotHidden} (Abs _ termLam)) = do
reportSLn "t2f" 10 $ "agdaTermToTerm Lam:\n" ++ show term'
_ β pushTNewVar
f β agdaTermToTerm termLam
popTVar
return f
agdaTermToTerm term'@(I.Var n args) = do
reportSLn "t2t" 10 $ "agdaTermToTerm Var:\n" ++ show term'
when (n < 0) (__IMPOSSIBLE__)
vars β getTVars
-- We also test for equality because the first argument of @I.Var@
-- doesn't start in one but in zero.
when (length vars == n) (__IMPOSSIBLE__)
when (length vars < n) (__IMPOSSIBLE__)
case args of
[] β return $ L.Var (vars !! n)
-- Non-FOL translation: First-order logic universal quantified
-- functions term.
-- If we have a bounded variable quantified on a function of a
-- Set to a Set, for example, the variable/function @f@ in
--
-- @(f : D β D) β (a : D) β (lam f) β a β‘ f a@
--
-- we are quantifying on this variable/function
--
-- (see @agdaTermToFormula (Pi domTy (Abs _ absTy))@),
--
-- therefore we need to apply this variable/function to the
-- others variables. See an example in
-- Test.Succeed.AgdaInternalTerms.Var2.agda
_varArgs β do
let p β· String
p = "--schematic-functions"
ifM (askTOpt optSchematicFunctions)
-- TODO (24 March 2013). Implementation.
(tErr $ NoImplementedOption "--schematic-functions")
-- (do lTerms β mapM agdaArgTermToTerm varArgs
-- ifM (askTOpt optAppF)
-- (return $ foldl' app (Var (vars !! n)) lTerms)
-- (return $ Fun (vars !! n) lTerms))
(tErr $ UniversalQuantificationError p)
agdaTermToTerm _ = __IMPOSSIBLE__
------------------------------------------------------------------------------
-- Note [Non-dependent functions]
-- 27 June 2012. After the patch
--
-- Wed Sep 21 04:50:43 COT 2011 ulfn@chalmers.se
-- * got rid of the Fun constructor in internal syntax (using Pi _ (NoAbs _ _) instead)
--
-- Agda is using (Pi _ (NoAbs _ _)) for the non-dependent
-- functions. In a later patch, Agda changed somes (Pi _ (Abs _ _))
-- to (Pi _ (NoAbs _ _)). The solution below works for *all* our cases.
| asr/apia | src/Apia/Translation/Terms.hs | mit | 19,060 | 0 | 21 | 5,338 | 4,044 | 2,101 | 1,943 | 321 | 20 |
module Language.Haskell.TypeCheck.Pretty
( Pretty(..)
, parensIf
, module Text.PrettyPrint.ANSI.Leijen
) where
import Text.PrettyPrint.ANSI.Leijen hiding (Pretty(..))
class Pretty a where
prettyPrec :: Int -> a -> Doc
prettyPrec _ = pretty
pretty :: a -> Doc
pretty = prettyPrec 0
{-# MINIMAL prettyPrec | pretty #-}
instance Pretty a => Pretty [a] where
prettyPrec _ = list . map pretty
parensIf :: Bool -> Doc -> Doc
parensIf True = parens
parensIf False = id
| Lemmih/haskell-tc | src/Language/Haskell/TypeCheck/Pretty.hs | mit | 486 | 0 | 8 | 98 | 155 | 88 | 67 | 16 | 1 |
module Y2020.M10.D14.Solution where
{--
I really hate wikidata sometimes.
The query:
# Continents/Countries
SELECT ?continent ?continentLabel ?country ?countryLabel
# ?region ?regionLabel # ?particularRegion ?particularRegionLabel
WHERE
{
?continent wdt:P31 wd:Q5107.
?country wdt:P31 wd:Q6256.
# ?region wdt:P31 wd:Q82794.
# ?region wdt:p642 ?continent.
# ?particularRegion wdt:p361 ?region.
?country wdt:P361 ?continent.
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
says there are only two countries in Europe: Norway and Italy.
It also says there are only seventeen countries that are in continents in the
entire World. If you're not one of these seventeen countries, then, as Cee Lo
Green sings: "[Forget] you."
You see that some RDF triples are commented out. Removing the comment marker
reduces the result set to 0 countries and continents, even though manual
search shows otherwise.
[Forget] you, wikidata.
But, there is a wiki page that lists countries by continent. So I did a hand-
scrape of that page.
Today's Haskell problem, let's convert that scrape to Haskell data.
--}
import Y2020.M10.D12.Solution -- for Country-type
import Data.List (isPrefixOf, stripPrefix)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Text (Text)
import qualified Data.Text as T
workingDir :: FilePath
workingDir = "Y2020/M10/D14/"
cbc :: FilePath
cbc = "countries.txt"
type Continent = Text
type ContinentMap = Map Continent [Country]
countriesByContinent :: FilePath -> IO ContinentMap
countriesByContinent countriesFile =
readFile countriesFile >>=
return . flip process Map.empty
. dropWhile (not . isPrefixOf "Continent") . lines
{--
>>> countriesByContinent (workingDir ++ cbc)
...
>>> let contis = it
--}
{--
A note about formatting:
deal with it.
That is all.
--}
process :: [String] -> ContinentMap -> ContinentMap
process [] ans = ans
process lines@(l:ines) acc =
let (row, rest) = processContinent lines
in process rest (maybe acc (flip (uncurry Map.insert) acc) row)
processContinent :: [String] -> (Maybe (Continent, [Country]), [String])
processContinent (conti:countrsAnd) =
maybe (Nothing, []) (pc countrsAnd . T.pack) (stripPrefix "Continent: " conti)
pc :: [String] -> Continent -> (Maybe (Continent, [Country]), [String])
pc resti counti =
let (countries, rest) = processCountries resti []
in (Just (counti, countries), rest)
processCountries :: [String] -> [Country] -> ([Country], [String])
processCountries [] ans = (ans, [])
processCountries (l:ines) acc | l == "" = (acc, ines)
| otherwise = processCountries ines (q:acc)
where m = tail l
(n, o) = break (== '-') m
q = T.pack ((if o == "" then id else init) n)
{--
>>> countriesByContinent (workingDir ++ cbc)
fromList [("Africa",["Zimbabwe","Zambia",...], ...]
>>> let m = it
>>> Map.size m
7
>>> Map.map length m
fromList [("Africa",55),("Antarctica",0),("Asia",48),("Europe",49),
("North America",45),("Oceania",23),("South America",15)]
--}
| geophf/1HaskellADay | exercises/HAD/Y2020/M10/D14/Solution.hs | mit | 3,117 | 0 | 14 | 567 | 605 | 336 | 269 | 37 | 2 |
module Fao.Bot where
import Data.List (sortBy, intercalate)
import Data.Maybe (fromJust)
import Control.Monad.State (get)
import System.Log.FastLogger
import Control.Monad.IO.Class (liftIO)
import Fao.Pathfinding
import Fao.Goal
import Fao.Types
import Fao.Utils
bot :: Bot
bot = Bot { initialize = return ()
, nextMove = findBestGoal
}
where
findBestGoal = do
(BotState state _) <- get
goals <- getGoals
scores <- mapM goalScore goals
dist <- mapM goalDistance goals
let ourHero = vindiniumHero state
goalStats = zip3 goals scores dist
goalValue (_, v1, d1) (_, v2, d2) = case compare v1 v2 of
EQ -> compare d1 d2
LT -> GT
GT -> LT
bestGoals = take 50 $ sortBy goalValue goalStats
bestAvailableGoal <- findM reachableGoal bestGoals
liftIO $ pushLogStr globalLogger $
toLogStr ("Turn number: " ++ show ((gameTurn . vindiniumGame) state) ++ "\n" ++
"Our hero: health = " ++ show (heroLife ourHero) ++ "\n" ++
"Best goals: " ++ intercalate ", " (map showGoal bestGoals) ++ "\n" ++
"Best available goal: " ++ maybe "" showGoal bestAvailableGoal ++ "\n"
)
case bestAvailableGoal of
Nothing -> return Stay
(Just (Goal action pos, s, _)) -> do
hbm <- ourHeroBoardMap action
return $ if s > 0
then walk ourHero (fromJust $ hbm pos)
else Stay
| ksaveljev/vindinium-bot | Fao/Bot.hs | mit | 1,644 | 0 | 27 | 610 | 468 | 240 | 228 | 38 | 5 |
{-# LANGUAGE TupleSections #-}
module Board where
import Data.List
import Data.Maybe
import Data.Function
import Data.Monoid
import Control.Arrow
import Control.Monad
import qualified Data.Map.Strict as Map
import Data.Easy (monoidToMaybe)
import qualified Stone
type Position = (Char, Char) -- (X, Y)
type Board = Map.Map Position Stone.Cell
-- | succ / id / pred
type Direction = (Char -> Char, Char -> Char)
-- | If the cell is Nothing or the position is out of range, return Nothing
lookup' :: Position -> Board -> Maybe Stone.Stone
lookup' = (join.) . Map.lookup
render :: Board -> String
render =
unlines .
map (concatMap $ Stone.render . snd) . -- Show stones
transpose . -- Group by the digit of the position
groupBy ((==) `on` (fst . fst)) . -- Group by the alphabet of the position
Map.toAscList -- Sort by the position
renderWithRuler :: Board -> String
renderWithRuler = unlines . (:) (" " ++ intersperse ' ' xRange) . zipWith ((++) . (:" ")) yRange . lines . render
xRange = ['a'..'h']
yRange = ['1'..'8']
initial :: Board
initial = Map.fromListWith const $ [((x, y), Nothing) | x <- xRange, y <- yRange] ++ map (second Just)
[ (('d', '4'), Stone.White)
, (('d', '5'), Stone.Black)
, (('e', '4'), Stone.Black)
, (('e', '5'), Stone.White)
]
-- | Is it out of range?
validate :: Position -> Bool
validate = flip Map.member initial
-- | If there are no stones that can take, return Nothing or Just [].
canTakeStones :: Position -> Stone.Stone -> Board -> Direction -> Maybe [Position]
canTakeStones position turn board direction
| stone == Just turn = Just []
| stone == Just (Stone.turnOver turn) = (pos:) <$> canTakeStones pos turn board direction
| otherwise = Nothing
where
pos = uncurry (***) direction position -- A position that moved to the direction.
stone = lookup' pos board
-- | Search 8 directions.
canTakeStonesAll :: Position -> Stone.Stone -> Board -> [Position]
canTakeStonesAll position turn board =
concat $
mapMaybe (canTakeStones position turn board)
(join (liftM2 (,)) [succ, id, pred] :: [Direction]) -- 9 directions. (id, id) does nothing.
-- | If impossible to put the stone, return Nothing.
put :: Position -> Stone.Stone -> Board -> Maybe Board
put position turn board =
(<>board) . Map.fromList . map (, Just turn) . (position:) <$> do
-- ^ right-biased
guard $ isNothing $ lookup' position board -- If a stone already exists in the position, return Nothing
monoidToMaybe $ canTakeStonesAll position turn board -- If the player can't take any stones, return Nothing
count :: Board -> String
count =
unwords .
map (uncurry (++) <<< Stone.render . head &&& (' ':) . show . length) .
group . -- Group by stone
sort .
map snd .
Map.toList
| wh11e7rue/heversi | src/Board.hs | mit | 2,767 | 0 | 17 | 552 | 861 | 480 | 381 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
------------------------------------------------------------------------------
-- |
-- Module : Mahjong.Hand
-- Copyright : (C) 2014 Samuli Thomasson
-- License : MIT (see the file LICENSE)
-- Maintainer : Samuli Thomasson <samuli.thomasson@paivola.fi>
-- Stability : experimental
-- Portability : non-portable
--
-- This module provides the representation type for a mahjong hand
-- (@Hand@), and functions that operate on a hand.
--
-- hand { _handPicks = map maskPickedTile (_handPicks hand)
-- , _handConcealed = Nothing
-- , _handFuriten = Nothing
-- , _handCanTsumo = Nothing
-- , _handFlags = Just $ runIdentity $ _handFlags hand }
-- where
-- maskPickedTile (PickedTile _ wanpai) = PickedTile Nothing wanpai
------------------------------------------------------------------------------
module Mahjong.Hand
( module Mahjong.Hand
-- * Hand sub-modules
, module Mahjong.Hand.Algo
, module Mahjong.Hand.Mentsu
, module Mahjong.Hand.Value
, module Mahjong.Hand.Yaku
-- * Types and lenses
, Hand(..), PlayerHand(..), Discard(..), RiichiState(..), DrawState(..)
, PickedTile(..), FuritenState(..), HandFlag(..), Agari(..)
-- ** lenses
, handCalled
, handDiscards
, handRiichi
, handIppatsu
, handAgari
, handState
, handPicks
, handConcealed
, handFuriten
, handCanTsumo
, handFlags
, dcTile, dcRiichi, dcTo
) where
------------------------------------------------------------------------------
import qualified Data.List as L
------------------------------------------------------------------------------
import Import
import Mahjong.Tiles
import Mahjong.Kyoku.Internal
------------------------------------------------------------------------------
import Mahjong.Hand.Algo
import Mahjong.Hand.Mentsu
import Mahjong.Hand.Value
import Mahjong.Hand.Yaku
import Mahjong.Hand.Internal
------------------------------------------------------------------------------
-- * Functions
-- | Automatically execute a discard necessary to advance the game (in case
-- of inactive players).
handAutoDiscard :: CanError m => Hand -> m Discard
handAutoDiscard hand
| p : _ <- _handPicks hand = return $ Discard (pickedTile p) Nothing False
| otherwise = return $ Discard (hand ^?! handConcealed._last) Nothing False
valueHand :: Kaze -> Hand -> Kyoku -> ValuedHand
valueHand player h deal = ValuedHand called concealed (getValue vi)
where
vi = ValueInfo deal player h
(called, concealed) = case h^.handAgari of
Nothing -> (h^.handCalled, h^.handConcealed)
Just (AgariTsumo tsumo _) -> (h^.handCalled, h^.handConcealed ++ [tsumo])
Just (AgariCall call) -> (h^.handCalled ++ [fromShout call], h^.handConcealed)
handInNagashi :: Hand -> Bool
handInNagashi h = all id [ h^.handCalled == []
, null $ h^..handDiscards.traversed.filtered (isJust . _dcTo)
, null $ h^..handDiscards.traversed.filtered (isSuited . _dcTile) ]
-- ** Riichi
-- | Tiles the hand can discard for a riichi.
--
-- >>> handCanRiichiWith $ initHand ["M1","M1","M2","M2","M3","M3","S5","S6","S7","P6","P7","S9","S9", "W"]
-- ["W "]
--
-- >>> handCanRiichiWith $ initHand ["M1","M1","M2","M2","M3","M3","S5","S6","S7","P6","P7","S9","S9"] & handPicks .~ [PickedTile "W" False]
-- ["W "]
handCanRiichiWith :: Hand -> [Tile]
handCanRiichiWith h
| h^.handRiichi /= NoRiichi = []
| otherwise = mapMaybe f $ handAllConcealed h
where f t = guard (canRiichiWith t h) $> t
canRiichiWith :: Tile -> Hand -> Bool
canRiichiWith t h = null (h^.handCalled) && tenpai (L.delete t tiles)
where tiles = handAllConcealed h
-- ** Furiten
furiten :: Hand -> Bool
furiten h = any (`elem` (h^..handDiscards.each.dcTile)) . concatMap getAgari
. filter tenpai $ getGroupings h
-- * Player actions
toHand :: CanError m => Tile -> Hand -> m Hand
toHand t h = do
unless (h^.handState == DrawFromWall) $ throwError $ "Hand state was " <> tshow (h^.handState) <> ", but expected " <> tshow DrawFromWall
return $ updateAfterPick (PickedTile t False) h
toHandWanpai :: CanError m => Tile -> Hand -> m Hand
toHandWanpai t h = do
unless (h^.handState == DrawFromWanpai) $ throwError $ "Hand state was " <> tshow (h^.handState) <> ", but expected " <> tshow DrawFromWanpai
return $ updateAfterPick (PickedTile t True) h
-- | Discard a tile; fails if
--
-- 1. tile not in the hand
-- 2. riichi restriction
-- 3. need to draw first
discard :: CanError m => Discard -> Hand -> m Hand
discard d@Discard{..} hand
| _dcRiichi, hand^.handRiichi /= NoRiichi = throwError "Already in riichi"
| _dcRiichi, not (canRiichiWith _dcTile hand) = throwError "Cannot riichi: not tenpai"
| hand^.handState /= DrawNone = throwError "You need to draw first"
| hand^.handRiichi /= NoRiichi, p : _ <- hand^.handPicks, pickedTile p /= _dcTile
= throwError "Cannot change wait in riichi"
| otherwise = updateAfterDiscard d <$> tileFromHand _dcTile hand
-- | The tiles of the shout (including shoutTo-tiles) must NOT be present
-- in the hand when this function is called.
rons :: CanError m => Shout -> Hand -> m Hand
rons shout hand
| hand^.handFuriten/= NotFuriten = throwError "You are furiten"
| not $ complete $ setAgariCall shout hand = throwError $ "Cannot win with an incomplete hand: " ++ tshow (shout, hand)
| otherwise = return $ setAgariCall shout hand
-- | Ankan on the given tile if possible.
--
-- Remember to flip dora when this succeeds.
ankanOn :: CanError m => Tile -> Hand -> m Hand
ankanOn tile hand
| sameConcealed >= 4 = return hand'
| sameConcealed == 3, tile `elem` map pickedTile (hand^.handPicks)
= return $ handPicks %~ L.deleteBy (on (==~) pickedTile) (PickedTile tile False) $ hand'
| otherwise = throwError "Not enough same tiles"
where
sameConcealed = hand^.handConcealed^..folded.filtered (==~ tile) & length
hand' = hand & handConcealed%~ L.foldl1' (.) (replicate 4 (L.delete tile)) -- @delete@, not @filter@: allows for hypotethical situation of more than 4 of the same tile
& handCalled %~ (:) (kantsu tile)
& handState .~ DrawFromWanpai
-- | Shouminkan with the tile if possible.
--
-- Remember to flip dora when this succeeds.
shouminkanOn :: CanError m => Tile -> Hand -> m Hand
shouminkanOn tile hand = do
hand' <- tile `tileFromHand` hand
let isShoum m = mentsuKind m == Koutsu && headEx (mentsuTiles m) ==~ tile
case hand' ^? handCalled.each.filtered isShoum of
Nothing -> throwError "Shouminkan not possible: no such open koutsu"
Just _ -> return $ handCalled.each.filtered isShoum %~ promoteToKantsu
$ handState .~ DrawFromWanpai
$ hand'
-- ** State changes from actions
updateAfterDiscard :: Discard -> Hand -> Hand
updateAfterDiscard d@Discard{..} hand = updateFlags
. updateFuriten -- If the discard brought us to furiten state set a flag -- XXX: should be a flag
. setRiichi -- If we riichi with the discard, set a flag -- XXX: should be a flag
. set handIppatsu (if' _dcRiichi True False) -- Ippatsu-flag is set here XXX: should be a flag
. set (handCanTsumo) False -- tsumo impossible at least after discard
. over handDiscards (|> d) -- Discard to discard pool
$ movePicks hand -- handPicks -> handConcealed
where
setRiichi
| _dcRiichi, null (hand^.handDiscards) = handRiichi .~ DoubleRiichi
| _dcRiichi = handRiichi .~ Riichi
| otherwise = id
updateFlags = unsetHandFlag HandFirsRoundUninterrupted
movePicks = over (handConcealed) (++ map pickedTile (_handPicks hand)) . set handPicks []
updateFuriten h = h & handFuriten.~ if' (furiten h) Furiten NotFuriten
-- | Update hand state after picked tile
updateAfterPick :: PickedTile -> Hand -> Hand
updateAfterPick pick h = if' (complete h') (handCanTsumo .~ True) id h'
where
h' = handPicks %~ (++ [pick]) $ handState .~ DrawNone $ h
-- * Calling
-- | Meld the mentsu to the hand. on win sets the agari info
--
-- * if the hand wins, call handWin to set agari tile.
-- * move the melded mentsu to called.
-- * if the shout was kan, meld it and set state to DrawFromWanpai.
meldTo :: CanError m => Shout -> Hand -> m Hand
meldTo shout hand
| not correctConcealedTilesInHand = throwError $ "meldTo: Tiles not available (concealed: " ++ tshow concealedTiles ++ ", needed: " ++ tshow tilesFromHand ++ ")"
| shoutKind shout `elem` [Ron, Chankan] = rons shout (removeFromConcealed hand)
| shoutKind shout == Kan = return $ (handState .~ DrawFromWanpai) (moveFromConcealed hand)
| otherwise = return $ moveFromConcealed hand
where
tilesFromHand = shoutTo shout
concealedTiles = hand^.handConcealed
correctConcealedTilesInHand = length concealedTiles == length (concealedTiles L.\\ tilesFromHand) + length tilesFromHand
moveFromConcealed = setHandFlag HandOpen . over handCalled (|> fromShout shout) . removeFromConcealed
removeFromConcealed = over (handConcealed) removeTiles
removeTiles ih = let (aka, notaka) = partition isAka ih in (aka ++ notaka) L.\\ tilesFromHand -- XXX: this is needed because Eq on Tile is warped
shoutFromHand :: CanError m => Kaze -> Shout -> Hand -> m Hand
shoutFromHand sk shout hand
| shoutKind shout == Chankan = return hand
| Just Discard{..} <- hand ^? handDiscards._last = return $ handDiscards._last.dcTo .~ Just sk $ hand
| otherwise = throwError "shoutFromHand: There were no discards on the hand."
-- | All mentsu that could be melded with hand given some tile.
shoutsOn :: Kaze -- ^ Shout from (player in turn)
-> Tile -- ^ Tile to shout
-> Kaze -- ^ Shouter
-> Hand -- ^ shouter's
-> [Shout]
shoutsOn np t p hand
| np == p = [] -- You're not shouting the thing you just discarded from yourself, right?
| Just x <- kokushiAgari (hand^.handConcealed)
, either (==~ t) (elem t) x = [Shout Ron np t []] -- Ron kokushi
| otherwise = concatMap toShout $ possibleShouts t
where
canChi = succCirc np == p
ih = sort (_handConcealed hand) -- NOTE: sort
akaIh = filter isAka ih
toShout (mk, st) = do
-- Tiles to shout with must be in our hand. *Uses semantic Eq*
guard $ st `isSubListOf` ih
-- Set aka information to the shoutTo tiles, for as many as
-- possible.
let goAka akas (x:xs) | x `elem` akas = setAka x : goAka (L.delete x akas) xs
| otherwise = x : goAka akas xs
goAka _ [] = []
tiles = goAka akaIh st
s <- case mk of
Jantou -> [Ron]
Kantsu -> [Kan]
Koutsu -> [Pon, Ron]
Shuntsu -> [Chi, Ron]
-- require Chi is from previous player
when (s == Chi) $ guard canChi
-- if riichi, only winning shouts. NOTE: chankan is handled after
-- the shoutsOn function.
when (hand^.handRiichi /= NoRiichi) $ guard (s == Ron)
when (s == Ron) $ guard $ complete
-- XXX: This looks fragile...
(toMentsu mk t tiles : (hand^.handCalled), hand^.handConcealed L.\\ tiles)
return $ Shout s np t tiles
-- * Utility
setAgariTsumo :: Hand -> Hand
setAgariTsumo hand = case hand^?handPicks._last of
Just (PickedTile t wanpai) -> hand & handPicks %~ initEx & handAgari .~ Just (AgariTsumo t wanpai)
Nothing -> error "Can't tsumo with no picked tile"
setAgariCall :: Shout -> Hand -> Hand
setAgariCall shout = handAgari .~ Just (AgariCall shout)
-- XXX: Could cache the result in the Hand data
handGetAgari :: Hand -> [Tile]
handGetAgari = L.nub . concatMap getAgari . tenpaiGroupings
-- | Take the tile from hand if possible.
tileFromHand :: CanError m => Tile -> Hand -> m Hand
tileFromHand tile hand
| pick : _ <- filter ((==@ tile).pickedTile) (hand^.handPicks) = return $ handPicks %~ L.deleteBy ((==@) `on` pickedTile) pick $ hand
| (xs, _ : ys) <- break (==@ tile) (hand^.handConcealed) = return $ handConcealed .~ (xs ++ ys) $ hand
| otherwise = throwError "Tile not in hand"
-- |
-- >>> [1..5] `isSubListOf` [1..9]
-- True
--
-- >>> [1,1,1] `isSubListOf` [1,2,1,1]
-- True
--
-- >>> [1,1] `isSubListOf` [1, 2, 3]
-- False
isSubListOf :: Eq a => [a] -> [a] -> Bool
isSubListOf xs ys = length ys - length (ys L.\\ xs) == length xs
| SimSaladin/hajong | hajong-server/src/Mahjong/Hand.hs | mit | 13,545 | 0 | 17 | 3,805 | 3,244 | 1,682 | 1,562 | -1 | -1 |
module Bonawitz_3_16a
where
import Blaze
import Tree
-- Actual data with means generated from N(0.5,1.2)
-- > c(rnorm(5,-0.36),rnorm(3,1.52),rnorm(7,1.13))
-- [1] 0.47292825 0.75540756 -1.88129332 -2.27875185 -0.42945479
-- [6] 1.27713236 1.52884804 1.11515755 0.85932051 0.68070500
-- [11] 2.10720307 -0.03267406 1.95447534 2.21044549 1.63612941
-- Root state
sr :: State
sr = collectStates dummyState $ (scs `tagNode` "scs") : sgps
-- Global parameters for group means
sgps :: [State]
sgps = mkDoubleParams ["mu","sigma"] [1.0, 1.0]
-- Collection state to hold components
scs :: State
scs = collectStates dummyCState [c1,c2,c3]
where c1 = mkComp 1 [0.47,1.28,2.11,0.75,1.53]
c2 = mkComp 2 [(-0.03),(-1.88),1.11,1.95,(-2.28)]
c3 = mkComp 3 [0.85,2.21,(-0.43),0.68,1.63]
-- Each component has its own mu (which is adjusted by the Kernel) and
-- sigma (which is held fixed)
mkComp :: Int -> [Double] -> State
mkComp i xs = collectStates dummyState [mu,sigma,csx] `tagNode` ct
where ct = "c" ++ show i
csx = collectStates dummyCState $
zipWith (flip tagNode) (((ct ++) . show) `fmap` [1..]) $
map mkDoubleData xs
[mu,sigma] = mkDoubleParams ["mu","sigma"] [0.0,1.0]
-- Likelihood depends on the likelihood of the component parameters
-- and the likelihood of the data in each component given its parameters.
dr :: Density
dr = mkACDensity (productDensity [dparam,dcomp]) ["scs"] [["mu"],["sigma"]]
where dparam = mkDensity [] [["mu"]] [["dso","mu"],["dso","sigma"]] normal
dcomp = mkACDensity ddatum [""] [["mu"],["sigma"]]
ddatum = mkDensity [] [[]] [["dso","mu"],["dso","sigma"]] normal
-- Kernel does uniform reassignment, perturbs the global parameters,
-- and perturbs each component mean
buildMachine :: Entropy -> Machine
buildMachine e = Machine sr dr kroot e
where kroot = mkCCKernel $
kreassign : kgmu : kgsigma : map perturb ["c1","c2","c3"]
kreassign = mkRDSLKernel ["scs"]
kgmu = mkGPKernel 0.05 ["mu"]
kgsigma = mkGPKernel 0.01 ["sigma"]
perturb t = mkGPKernel 0.1 ["scs",t,"mu"]
main :: IO ()
main = run buildMachine 10 [ trace paramLocs, dump paramLocs ]
where paramLocs = [ ([],"mu")
, ([],"sigma") ] | othercriteria/blaze | Bonawitz_3_16a.hs | mit | 2,384 | 0 | 14 | 573 | 686 | 398 | 288 | 36 | 1 |
-- Tying the loop
-- ref: | Airtnp/Freshman_Simple_Haskell_Lib | Idioms/Tying-the-loop.hs | mit | 26 | 0 | 2 | 6 | 4 | 3 | 1 | 1 | 0 |
module BlocVoting.Instructions.ModRes where
import qualified Data.ByteString as BS
import qualified BlocVoting.Nulldata as ND
import BlocVoting.Bitcoin.Address
import BlocVoting.Bitcoin.Base58
import BlocVoting.Binary (get4ByteInt, get1ByteInt)
data OpModRes = OpModRes {
mrCategories :: Int
, mrEndTimestamp :: Int
, mrResolution :: BS.ByteString
, mrUrl :: BS.ByteString
, mrND :: ND.Nulldata
}
deriving (Show, Eq)
_isValidNulldata :: ND.Nulldata -> Bool
_isValidNulldata nd@(ND.Nulldata msg sender _ _)
| BS.length msg > 40 = False
| otherwise = True
fromNulldata :: ND.Nulldata -> Maybe OpModRes
fromNulldata nd@(ND.Nulldata msg senderAddress _ _) = if _isValidNulldata nd then Just $ OpModRes cats endT resolution url nd else Nothing
where cats = get1ByteInt $ BS.drop 1 msg
endT = get4ByteInt (BS.drop 2 msg) 0
resL = get1ByteInt $ BS.drop 6 msg
resolution = BS.take resL $ BS.drop 7 msg
lastChunk = BS.drop (resL + 7) msg
urlL = get1ByteInt lastChunk
url = BS.take urlL $ BS.drop 1 lastChunk
| XertroV/blocvoting | src/BlocVoting/Instructions/ModRes.hs | mit | 1,076 | 0 | 10 | 224 | 352 | 190 | 162 | 26 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.